LLVM 19.0.0git
ELFObjcopy.cpp
Go to the documentation of this file.
1//===- ELFObjcopy.cpp -----------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "ELFObject.h"
12#include "llvm/ADT/DenseSet.h"
13#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/ADT/Twine.h"
21#include "llvm/Object/Binary.h"
24#include "llvm/Object/Error.h"
25#include "llvm/Option/Option.h"
28#include "llvm/Support/Errc.h"
29#include "llvm/Support/Error.h"
33#include "llvm/Support/Memory.h"
34#include "llvm/Support/Path.h"
36#include <algorithm>
37#include <cassert>
38#include <cstdlib>
39#include <functional>
40#include <iterator>
41#include <memory>
42#include <string>
43#include <system_error>
44#include <utility>
45
46using namespace llvm;
47using namespace llvm::ELF;
48using namespace llvm::objcopy;
49using namespace llvm::objcopy::elf;
50using namespace llvm::object;
51
52using SectionPred = std::function<bool(const SectionBase &Sec)>;
53
54static bool isDebugSection(const SectionBase &Sec) {
55 return StringRef(Sec.Name).starts_with(".debug") || Sec.Name == ".gdb_index";
56}
57
58static bool isDWOSection(const SectionBase &Sec) {
59 return StringRef(Sec.Name).ends_with(".dwo");
60}
61
62static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
63 // We can't remove the section header string table.
64 if (&Sec == Obj.SectionNames)
65 return false;
66 // Short of keeping the string table we want to keep everything that is a DWO
67 // section and remove everything else.
68 return !isDWOSection(Sec);
69}
70
72 uint16_t EMachine) {
73 uint64_t NewFlags = 0;
74 if (AllFlags & SectionFlag::SecAlloc)
75 NewFlags |= ELF::SHF_ALLOC;
76 if (!(AllFlags & SectionFlag::SecReadonly))
77 NewFlags |= ELF::SHF_WRITE;
78 if (AllFlags & SectionFlag::SecCode)
79 NewFlags |= ELF::SHF_EXECINSTR;
80 if (AllFlags & SectionFlag::SecMerge)
81 NewFlags |= ELF::SHF_MERGE;
82 if (AllFlags & SectionFlag::SecStrings)
83 NewFlags |= ELF::SHF_STRINGS;
84 if (AllFlags & SectionFlag::SecExclude)
85 NewFlags |= ELF::SHF_EXCLUDE;
86 if (AllFlags & SectionFlag::SecLarge) {
87 if (EMachine != EM_X86_64)
88 return createStringError(errc::invalid_argument,
89 "section flag SHF_X86_64_LARGE can only be used "
90 "with x86_64 architecture");
91 NewFlags |= ELF::SHF_X86_64_LARGE;
92 }
93 return NewFlags;
94}
95
97 uint64_t NewFlags,
98 uint16_t EMachine) {
99 // Preserve some flags which should not be dropped when setting flags.
100 // Also, preserve anything OS/processor dependant.
101 const uint64_t PreserveMask =
106 ~(EMachine == EM_X86_64 ? (uint64_t)ELF::SHF_X86_64_LARGE : 0UL);
107 return (OldFlags & PreserveMask) | (NewFlags & ~PreserveMask);
108}
109
111 // If Sec's type is changed from SHT_NOBITS due to --set-section-flags,
112 // Offset may not be aligned. Align it to max(Align, 1).
113 if (Sec.Type == ELF::SHT_NOBITS && Type != ELF::SHT_NOBITS)
114 Sec.Offset = alignTo(Sec.Offset, std::max(Sec.Align, uint64_t(1)));
115 Sec.Type = Type;
116}
117
119 uint16_t EMachine) {
120 Expected<uint64_t> NewFlags = getNewShfFlags(Flags, EMachine);
121 if (!NewFlags)
122 return NewFlags.takeError();
123 Sec.Flags = getSectionFlagsPreserveMask(Sec.Flags, *NewFlags, EMachine);
124
125 // In GNU objcopy, certain flags promote SHT_NOBITS to SHT_PROGBITS. This rule
126 // may promote more non-ALLOC sections than GNU objcopy, but it is fine as
127 // non-ALLOC SHT_NOBITS sections do not make much sense.
128 if (Sec.Type == SHT_NOBITS &&
129 (!(Sec.Flags & ELF::SHF_ALLOC) ||
130 Flags & (SectionFlag::SecContents | SectionFlag::SecLoad)))
132
133 return Error::success();
134}
135
137 // Infer output ELF type from the input ELF object
139 return ELFT_ELF32LE;
141 return ELFT_ELF64LE;
143 return ELFT_ELF32BE;
145 return ELFT_ELF64BE;
146 llvm_unreachable("Invalid ELFType");
147}
148
150 // Infer output ELF type from the binary arch specified
151 if (MI.Is64Bit)
152 return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
153 else
154 return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
155}
156
157static std::unique_ptr<Writer> createELFWriter(const CommonConfig &Config,
158 Object &Obj, raw_ostream &Out,
159 ElfType OutputElfType) {
160 // Depending on the initial ELFT and OutputFormat we need a different Writer.
161 switch (OutputElfType) {
162 case ELFT_ELF32LE:
163 return std::make_unique<ELFWriter<ELF32LE>>(Obj, Out, !Config.StripSections,
164 Config.OnlyKeepDebug);
165 case ELFT_ELF64LE:
166 return std::make_unique<ELFWriter<ELF64LE>>(Obj, Out, !Config.StripSections,
167 Config.OnlyKeepDebug);
168 case ELFT_ELF32BE:
169 return std::make_unique<ELFWriter<ELF32BE>>(Obj, Out, !Config.StripSections,
170 Config.OnlyKeepDebug);
171 case ELFT_ELF64BE:
172 return std::make_unique<ELFWriter<ELF64BE>>(Obj, Out, !Config.StripSections,
173 Config.OnlyKeepDebug);
174 }
175 llvm_unreachable("Invalid output format");
176}
177
178static std::unique_ptr<Writer> createWriter(const CommonConfig &Config,
179 Object &Obj, raw_ostream &Out,
180 ElfType OutputElfType) {
181 switch (Config.OutputFormat) {
182 case FileFormat::Binary:
183 return std::make_unique<BinaryWriter>(Obj, Out, Config);
184 case FileFormat::IHex:
185 return std::make_unique<IHexWriter>(Obj, Out, Config.OutputFilename);
186 case FileFormat::SREC:
187 return std::make_unique<SRECWriter>(Obj, Out, Config.OutputFilename);
188 default:
189 return createELFWriter(Config, Obj, Out, OutputElfType);
190 }
191}
192
194 Object &Obj) {
195 for (auto &Sec : Obj.sections()) {
196 if (Sec.Name == SecName) {
197 if (Sec.Type == SHT_NOBITS)
198 return createStringError(object_error::parse_failed,
199 "cannot dump section '%s': it has no contents",
200 SecName.str().c_str());
202 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
203 if (!BufferOrErr)
204 return BufferOrErr.takeError();
205 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
206 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
207 Buf->getBufferStart());
208 if (Error E = Buf->commit())
209 return E;
210 return Error::success();
211 }
212 }
213 return createStringError(object_error::parse_failed, "section '%s' not found",
214 SecName.str().c_str());
215}
216
218 // Build a list of the debug sections we are going to replace.
219 // We can't call `AddSection` while iterating over sections,
220 // because it would mutate the sections array.
221 SmallVector<std::pair<SectionBase *, std::function<SectionBase *()>>, 0>
222 ToReplace;
223 for (SectionBase &Sec : sections()) {
224 if ((Sec.Flags & SHF_ALLOC) || !StringRef(Sec.Name).starts_with(".debug"))
225 continue;
226 if (auto *CS = dyn_cast<CompressedSection>(&Sec)) {
227 if (Config.DecompressDebugSections) {
228 ToReplace.emplace_back(
229 &Sec, [=] { return &addSection<DecompressedSection>(*CS); });
230 }
231 } else if (Config.CompressionType != DebugCompressionType::None) {
232 ToReplace.emplace_back(&Sec, [&, S = &Sec] {
233 return &addSection<CompressedSection>(
234 CompressedSection(*S, Config.CompressionType, Is64Bits));
235 });
236 }
237 }
238
240 for (auto [S, Func] : ToReplace)
241 FromTo[S] = Func();
242 return replaceSections(FromTo);
243}
244
245static bool isAArch64MappingSymbol(const Symbol &Sym) {
246 if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
248 return false;
250 if (!Name.consume_front("$x") && !Name.consume_front("$d"))
251 return false;
252 return Name.empty() || Name.starts_with(".");
253}
254
255static bool isArmMappingSymbol(const Symbol &Sym) {
256 if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
258 return false;
260 if (!Name.consume_front("$a") && !Name.consume_front("$d") &&
261 !Name.consume_front("$t"))
262 return false;
263 return Name.empty() || Name.starts_with(".");
264}
265
266// Check if the symbol should be preserved because it is required by ABI.
267static bool isRequiredByABISymbol(const Object &Obj, const Symbol &Sym) {
268 switch (Obj.Machine) {
269 case EM_AARCH64:
270 // Mapping symbols should be preserved for a relocatable object file.
272 case EM_ARM:
273 // Mapping symbols should be preserved for a relocatable object file.
274 return Obj.isRelocatable() && isArmMappingSymbol(Sym);
275 default:
276 return false;
277 }
278}
279
280static bool isUnneededSymbol(const Symbol &Sym) {
281 return !Sym.Referenced &&
282 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
284}
285
287 const ELFConfig &ELFConfig, Object &Obj) {
288 // TODO: update or remove symbols only if there is an option that affects
289 // them.
290 if (!Obj.SymbolTable)
291 return Error::success();
292
294 if (Config.SymbolsToSkip.matches(Sym.Name))
295 return;
296
297 // Common and undefined symbols don't make sense as local symbols, and can
298 // even cause crashes if we localize those, so skip them.
299 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
302 Config.SymbolsToLocalize.matches(Sym.Name)))
304
305 for (auto &[Matcher, Visibility] : ELFConfig.SymbolsToSetVisibility)
306 if (Matcher.matches(Sym.Name))
307 Sym.Visibility = Visibility;
308
309 // Note: these two globalize flags have very similar names but different
310 // meanings:
311 //
312 // --globalize-symbol: promote a symbol to global
313 // --keep-global-symbol: all symbols except for these should be made local
314 //
315 // If --globalize-symbol is specified for a given symbol, it will be
316 // global in the output file even if it is not included via
317 // --keep-global-symbol. Because of that, make sure to check
318 // --globalize-symbol second.
319 if (!Config.SymbolsToKeepGlobal.empty() &&
320 !Config.SymbolsToKeepGlobal.matches(Sym.Name) &&
323
324 if (Config.SymbolsToGlobalize.matches(Sym.Name) &&
327
328 // SymbolsToWeaken applies to both STB_GLOBAL and STB_GNU_UNIQUE.
329 if (Config.SymbolsToWeaken.matches(Sym.Name) && Sym.Binding != STB_LOCAL)
331
332 if (Config.Weaken && Sym.Binding != STB_LOCAL &&
335
336 const auto I = Config.SymbolsToRename.find(Sym.Name);
337 if (I != Config.SymbolsToRename.end())
338 Sym.Name = std::string(I->getValue());
339
340 if (!Config.SymbolsPrefixRemove.empty() && Sym.Type != STT_SECTION)
341 if (Sym.Name.compare(0, Config.SymbolsPrefixRemove.size(),
342 Config.SymbolsPrefixRemove) == 0)
343 Sym.Name = Sym.Name.substr(Config.SymbolsPrefixRemove.size());
344
345 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
346 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
347 });
348
349 // The purpose of this loop is to mark symbols referenced by sections
350 // (like GroupSection or RelocationSection). This way, we know which
351 // symbols are still 'needed' and which are not.
352 if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty() ||
353 !Config.OnlySection.empty()) {
354 for (SectionBase &Sec : Obj.sections())
355 Sec.markSymbols();
356 }
357
358 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
359 if (Config.SymbolsToKeep.matches(Sym.Name) ||
361 return false;
362
363 if (Config.SymbolsToRemove.matches(Sym.Name))
364 return true;
365
366 if (Config.StripAll || Config.StripAllGNU)
367 return true;
368
369 if (isRequiredByABISymbol(Obj, Sym))
370 return false;
371
372 if (Config.StripDebug && Sym.Type == STT_FILE)
373 return true;
374
375 if ((Config.DiscardMode == DiscardType::All ||
376 (Config.DiscardMode == DiscardType::Locals &&
377 StringRef(Sym.Name).starts_with(".L"))) &&
380 return true;
381
382 if ((Config.StripUnneeded ||
383 Config.UnneededSymbolsToRemove.matches(Sym.Name)) &&
385 return true;
386
387 // We want to remove undefined symbols if all references have been stripped.
388 if (!Config.OnlySection.empty() && !Sym.Referenced &&
390 return true;
391
392 return false;
393 };
394
395 return Obj.removeSymbols(RemoveSymbolsPred);
396}
397
399 const ELFConfig &ELFConfig, Object &Obj) {
400 SectionPred RemovePred = [](const SectionBase &) { return false; };
401
402 // Removes:
403 if (!Config.ToRemove.empty()) {
404 RemovePred = [&Config](const SectionBase &Sec) {
405 return Config.ToRemove.matches(Sec.Name);
406 };
407 }
408
409 if (Config.StripDWO)
410 RemovePred = [RemovePred](const SectionBase &Sec) {
411 return isDWOSection(Sec) || RemovePred(Sec);
412 };
413
414 if (Config.ExtractDWO)
415 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
416 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
417 };
418
419 if (Config.StripAllGNU)
420 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
421 if (RemovePred(Sec))
422 return true;
423 if ((Sec.Flags & SHF_ALLOC) != 0)
424 return false;
425 if (&Sec == Obj.SectionNames)
426 return false;
427 switch (Sec.Type) {
428 case SHT_SYMTAB:
429 case SHT_REL:
430 case SHT_RELA:
431 case SHT_STRTAB:
432 return true;
433 }
434 return isDebugSection(Sec);
435 };
436
437 if (Config.StripSections) {
438 RemovePred = [RemovePred](const SectionBase &Sec) {
439 return RemovePred(Sec) || Sec.ParentSegment == nullptr;
440 };
441 }
442
443 if (Config.StripDebug || Config.StripUnneeded) {
444 RemovePred = [RemovePred](const SectionBase &Sec) {
445 return RemovePred(Sec) || isDebugSection(Sec);
446 };
447 }
448
449 if (Config.StripNonAlloc)
450 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
451 if (RemovePred(Sec))
452 return true;
453 if (&Sec == Obj.SectionNames)
454 return false;
455 return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
456 };
457
458 if (Config.StripAll)
459 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
460 if (RemovePred(Sec))
461 return true;
462 if (&Sec == Obj.SectionNames)
463 return false;
464 if (StringRef(Sec.Name).starts_with(".gnu.warning"))
465 return false;
466 if (StringRef(Sec.Name).starts_with(".gnu_debuglink"))
467 return false;
468 // We keep the .ARM.attribute section to maintain compatibility
469 // with Debian derived distributions. This is a bug in their
470 // patchset as documented here:
471 // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=943798
472 if (Sec.Type == SHT_ARM_ATTRIBUTES)
473 return false;
474 if (Sec.ParentSegment != nullptr)
475 return false;
476 return (Sec.Flags & SHF_ALLOC) == 0;
477 };
478
479 if (Config.ExtractPartition || Config.ExtractMainPartition) {
480 RemovePred = [RemovePred](const SectionBase &Sec) {
481 if (RemovePred(Sec))
482 return true;
483 if (Sec.Type == SHT_LLVM_PART_EHDR || Sec.Type == SHT_LLVM_PART_PHDR)
484 return true;
485 return (Sec.Flags & SHF_ALLOC) != 0 && !Sec.ParentSegment;
486 };
487 }
488
489 // Explicit copies:
490 if (!Config.OnlySection.empty()) {
491 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
492 // Explicitly keep these sections regardless of previous removes.
493 if (Config.OnlySection.matches(Sec.Name))
494 return false;
495
496 // Allow all implicit removes.
497 if (RemovePred(Sec))
498 return true;
499
500 // Keep special sections.
501 if (Obj.SectionNames == &Sec)
502 return false;
503 if (Obj.SymbolTable == &Sec ||
504 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
505 return false;
506
507 // Remove everything else.
508 return true;
509 };
510 }
511
512 if (!Config.KeepSection.empty()) {
513 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
514 // Explicitly keep these sections regardless of previous removes.
515 if (Config.KeepSection.matches(Sec.Name))
516 return false;
517 // Otherwise defer to RemovePred.
518 return RemovePred(Sec);
519 };
520 }
521
522 // This has to be the last predicate assignment.
523 // If the option --keep-symbol has been specified
524 // and at least one of those symbols is present
525 // (equivalently, the updated symbol table is not empty)
526 // the symbol table and the string table should not be removed.
527 if ((!Config.SymbolsToKeep.empty() || ELFConfig.KeepFileSymbols) &&
528 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
529 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
530 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
531 return false;
532 return RemovePred(Sec);
533 };
534 }
535
536 if (Error E = Obj.removeSections(ELFConfig.AllowBrokenLinks, RemovePred))
537 return E;
538
540 return E;
541
542 return Error::success();
543}
544
545// Add symbol to the Object symbol table with the specified properties.
546static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo,
547 uint8_t DefaultVisibility) {
548 SectionBase *Sec = Obj.findSection(SymInfo.SectionName);
549 uint64_t Value = Sec ? Sec->Addr + SymInfo.Value : SymInfo.Value;
550
551 uint8_t Bind = ELF::STB_GLOBAL;
552 uint8_t Type = ELF::STT_NOTYPE;
553 uint8_t Visibility = DefaultVisibility;
554
555 for (SymbolFlag FlagValue : SymInfo.Flags)
556 switch (FlagValue) {
558 Bind = ELF::STB_GLOBAL;
559 break;
561 Bind = ELF::STB_LOCAL;
562 break;
563 case SymbolFlag::Weak:
564 Bind = ELF::STB_WEAK;
565 break;
567 Visibility = ELF::STV_DEFAULT;
568 break;
570 Visibility = ELF::STV_HIDDEN;
571 break;
573 Visibility = ELF::STV_PROTECTED;
574 break;
575 case SymbolFlag::File:
577 break;
580 break;
583 break;
586 break;
589 break;
590 default: /* Other flag values are ignored for ELF. */
591 break;
592 };
593
595 SymInfo.SymbolName, Bind, Type, Sec, Value, Visibility,
597}
598
599static Error
602 ArrayRef<uint8_t> Data(reinterpret_cast<const uint8_t *>(
603 NewSection.SectionData->getBufferStart()),
604 NewSection.SectionData->getBufferSize());
605 return F(NewSection.SectionName, Data);
606}
607
608// This function handles the high level operations of GNU objcopy including
609// handling command line options. It's important to outline certain properties
610// we expect to hold of the command line operations. Any operation that "keeps"
611// should keep regardless of a remove. Additionally any removal should respect
612// any previous removals. Lastly whether or not something is removed shouldn't
613// depend a) on the order the options occur in or b) on some opaque priority
614// system. The only priority is that keeps/copies overrule removes.
616 Object &Obj) {
617 if (Config.OutputArch) {
618 Obj.Machine = Config.OutputArch->EMachine;
619 Obj.OSABI = Config.OutputArch->OSABI;
620 }
621
622 if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
623 return Obj.removeSections(
625 [&Obj](const SectionBase &Sec) { return onlyKeepDWOPred(Obj, Sec); });
626 }
627
628 // Dump sections before add/remove for compatibility with GNU objcopy.
629 for (StringRef Flag : Config.DumpSection) {
631 StringRef FileName;
632 std::tie(SectionName, FileName) = Flag.split('=');
633 if (Error E = dumpSectionToFile(SectionName, FileName, Obj))
634 return E;
635 }
636
637 // It is important to remove the sections first. For example, we want to
638 // remove the relocation sections before removing the symbols. That allows
639 // us to avoid reporting the inappropriate errors about removing symbols
640 // named in relocations.
642 return E;
643
645 return E;
646
647 if (!Config.SetSectionAlignment.empty()) {
648 for (SectionBase &Sec : Obj.sections()) {
649 auto I = Config.SetSectionAlignment.find(Sec.Name);
650 if (I != Config.SetSectionAlignment.end())
651 Sec.Align = I->second;
652 }
653 }
654
655 if (Config.OnlyKeepDebug)
656 for (auto &Sec : Obj.sections())
657 if (Sec.Flags & SHF_ALLOC && Sec.Type != SHT_NOTE)
658 Sec.Type = SHT_NOBITS;
659
660 for (const NewSectionInfo &AddedSection : Config.AddSection) {
661 auto AddSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
662 OwnedDataSection &NewSection =
664 if (Name.starts_with(".note") && Name != ".note.GNU-stack")
665 NewSection.Type = SHT_NOTE;
666 return Error::success();
667 };
668 if (Error E = handleUserSection(AddedSection, AddSection))
669 return E;
670 }
671
672 for (const NewSectionInfo &NewSection : Config.UpdateSection) {
673 auto UpdateSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
674 return Obj.updateSection(Name, Data);
675 };
676 if (Error E = handleUserSection(NewSection, UpdateSection))
677 return E;
678 }
679
680 if (!Config.AddGnuDebugLink.empty())
681 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink,
682 Config.GnuDebugLinkCRC32);
683
684 // If the symbol table was previously removed, we need to create a new one
685 // before adding new symbols.
686 if (!Obj.SymbolTable && !Config.SymbolsToAdd.empty())
687 if (Error E = Obj.addNewSymbolTable())
688 return E;
689
690 for (const NewSymbolInfo &SI : Config.SymbolsToAdd)
692
693 // --set-section-{flags,type} work with sections added by --add-section.
694 if (!Config.SetSectionFlags.empty() || !Config.SetSectionType.empty()) {
695 for (auto &Sec : Obj.sections()) {
696 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
697 if (Iter != Config.SetSectionFlags.end()) {
698 const SectionFlagsUpdate &SFU = Iter->second;
699 if (Error E = setSectionFlagsAndType(Sec, SFU.NewFlags, Obj.Machine))
700 return E;
701 }
702 auto It2 = Config.SetSectionType.find(Sec.Name);
703 if (It2 != Config.SetSectionType.end())
704 setSectionType(Sec, It2->second);
705 }
706 }
707
708 if (!Config.SectionsToRename.empty()) {
709 std::vector<RelocationSectionBase *> RelocSections;
710 DenseSet<SectionBase *> RenamedSections;
711 for (SectionBase &Sec : Obj.sections()) {
712 auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec);
713 const auto Iter = Config.SectionsToRename.find(Sec.Name);
714 if (Iter != Config.SectionsToRename.end()) {
715 const SectionRename &SR = Iter->second;
716 Sec.Name = std::string(SR.NewName);
717 if (SR.NewFlags) {
718 if (Error E = setSectionFlagsAndType(Sec, *SR.NewFlags, Obj.Machine))
719 return E;
720 }
721 RenamedSections.insert(&Sec);
722 } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
723 // Postpone processing relocation sections which are not specified in
724 // their explicit '--rename-section' commands until after their target
725 // sections are renamed.
726 // Dynamic relocation sections (i.e. ones with SHF_ALLOC) should be
727 // renamed only explicitly. Otherwise, renaming, for example, '.got.plt'
728 // would affect '.rela.plt', which is not desirable.
729 RelocSections.push_back(RelocSec);
730 }
731
732 // Rename relocation sections according to their target sections.
733 for (RelocationSectionBase *RelocSec : RelocSections) {
734 auto Iter = RenamedSections.find(RelocSec->getSection());
735 if (Iter != RenamedSections.end())
736 RelocSec->Name = (RelocSec->getNamePrefix() + (*Iter)->Name).str();
737 }
738 }
739
740 // Add a prefix to allocated sections and their relocation sections. This
741 // should be done after renaming the section by Config.SectionToRename to
742 // imitate the GNU objcopy behavior.
743 if (!Config.AllocSectionsPrefix.empty()) {
744 DenseSet<SectionBase *> PrefixedSections;
745 for (SectionBase &Sec : Obj.sections()) {
746 if (Sec.Flags & SHF_ALLOC) {
747 Sec.Name = (Config.AllocSectionsPrefix + Sec.Name).str();
748 PrefixedSections.insert(&Sec);
749 } else if (auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec)) {
750 // Rename relocation sections associated to the allocated sections.
751 // For example, if we rename .text to .prefix.text, we also rename
752 // .rel.text to .rel.prefix.text.
753 //
754 // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
755 // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
756 // .rela.prefix.plt since GNU objcopy does so.
757 const SectionBase *TargetSec = RelocSec->getSection();
758 if (TargetSec && (TargetSec->Flags & SHF_ALLOC)) {
759 // If the relocation section comes *after* the target section, we
760 // don't add Config.AllocSectionsPrefix because we've already added
761 // the prefix to TargetSec->Name. Otherwise, if the relocation
762 // section comes *before* the target section, we add the prefix.
763 if (PrefixedSections.count(TargetSec))
764 Sec.Name = (RelocSec->getNamePrefix() + TargetSec->Name).str();
765 else
766 Sec.Name = (RelocSec->getNamePrefix() + Config.AllocSectionsPrefix +
767 TargetSec->Name)
768 .str();
769 }
770 }
771 }
772 }
773
775 Obj.Entry = ELFConfig.EntryExpr(Obj.Entry);
776 return Error::success();
777}
778
780 raw_ostream &Out, ElfType OutputElfType) {
781 std::unique_ptr<Writer> Writer =
782 createWriter(Config, Obj, Out, OutputElfType);
783 if (Error E = Writer->finalize())
784 return E;
785 return Writer->write();
786}
787
789 const ELFConfig &ELFConfig,
790 MemoryBuffer &In, raw_ostream &Out) {
791 IHexReader Reader(&In);
793 if (!Obj)
794 return Obj.takeError();
795
796 const ElfType OutputElfType =
797 getOutputElfType(Config.OutputArch.value_or(MachineInfo()));
798 if (Error E = handleArgs(Config, ELFConfig, **Obj))
799 return E;
800 return writeOutput(Config, **Obj, Out, OutputElfType);
801}
802
804 const ELFConfig &ELFConfig,
805 MemoryBuffer &In,
806 raw_ostream &Out) {
809 if (!Obj)
810 return Obj.takeError();
811
812 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
813 // (-B<arch>).
814 const ElfType OutputElfType =
815 getOutputElfType(Config.OutputArch.value_or(MachineInfo()));
816 if (Error E = handleArgs(Config, ELFConfig, **Obj))
817 return E;
818 return writeOutput(Config, **Obj, Out, OutputElfType);
819}
820
822 const ELFConfig &ELFConfig,
824 raw_ostream &Out) {
825 ELFReader Reader(&In, Config.ExtractPartition);
827 Reader.create(!Config.SymbolsToAdd.empty());
828 if (!Obj)
829 return Obj.takeError();
830 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
831 const ElfType OutputElfType = Config.OutputArch
832 ? getOutputElfType(*Config.OutputArch)
833 : getOutputElfType(In);
834
835 if (Error E = handleArgs(Config, ELFConfig, **Obj))
836 return createFileError(Config.InputFilename, std::move(E));
837
838 if (Error E = writeOutput(Config, **Obj, Out, OutputElfType))
839 return createFileError(Config.InputFilename, std::move(E));
840
841 return Error::success();
842}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
This file defines the DenseSet and SmallDenseSet classes.
std::string Name
static Error replaceAndRemoveSections(const CommonConfig &Config, const ELFConfig &ELFConfig, Object &Obj)
Definition: ELFObjcopy.cpp:398
static bool isArmMappingSymbol(const Symbol &Sym)
Definition: ELFObjcopy.cpp:255
static Error handleUserSection(const NewSectionInfo &NewSection, function_ref< Error(StringRef, ArrayRef< uint8_t >)> F)
Definition: ELFObjcopy.cpp:600
static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo, uint8_t DefaultVisibility)
Definition: ELFObjcopy.cpp:546
static Error updateAndRemoveSymbols(const CommonConfig &Config, const ELFConfig &ELFConfig, Object &Obj)
Definition: ELFObjcopy.cpp:286
std::function< bool(const SectionBase &Sec)> SectionPred
Definition: ELFObjcopy.cpp:52
static bool isDWOSection(const SectionBase &Sec)
Definition: ELFObjcopy.cpp:58
static bool isRequiredByABISymbol(const Object &Obj, const Symbol &Sym)
Definition: ELFObjcopy.cpp:267
static bool isDebugSection(const SectionBase &Sec)
Definition: ELFObjcopy.cpp:54
static Error dumpSectionToFile(StringRef SecName, StringRef Filename, Object &Obj)
Definition: ELFObjcopy.cpp:193
static Error writeOutput(const CommonConfig &Config, Object &Obj, raw_ostream &Out, ElfType OutputElfType)
Definition: ELFObjcopy.cpp:779
static bool isUnneededSymbol(const Symbol &Sym)
Definition: ELFObjcopy.cpp:280
static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig, Object &Obj)
Definition: ELFObjcopy.cpp:615
static bool isAArch64MappingSymbol(const Symbol &Sym)
Definition: ELFObjcopy.cpp:245
static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec)
Definition: ELFObjcopy.cpp:62
static void setSectionType(SectionBase &Sec, uint64_t Type)
Definition: ELFObjcopy.cpp:110
static Expected< uint64_t > getNewShfFlags(SectionFlag AllFlags, uint16_t EMachine)
Definition: ELFObjcopy.cpp:71
static Error setSectionFlagsAndType(SectionBase &Sec, SectionFlag Flags, uint16_t EMachine)
Definition: ELFObjcopy.cpp:118
static std::unique_ptr< Writer > createELFWriter(const CommonConfig &Config, Object &Obj, raw_ostream &Out, ElfType OutputElfType)
Definition: ELFObjcopy.cpp:157
static uint64_t getSectionFlagsPreserveMask(uint64_t OldFlags, uint64_t NewFlags, uint16_t EMachine)
Definition: ELFObjcopy.cpp:96
static std::unique_ptr< Writer > createWriter(const CommonConfig &Config, Object &Obj, raw_ostream &Out, ElfType OutputElfType)
Definition: ELFObjcopy.cpp:178
static ElfType getOutputElfType(const Binary &Bin)
Definition: ELFObjcopy.cpp:136
RelaxConfig Config
Definition: ELF_riscv.cpp:506
Symbol * Sym
Definition: ELF_riscv.cpp:479
Provides ErrorOr<T> smart pointer.
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
if(VerifyEach)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
static Expected< std::unique_ptr< FileOutputBuffer > > create(StringRef FilePath, size_t Size, unsigned Flags=0)
Factory method to create an OutputBuffer object which manages a read/write buffer of the specified si...
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:51
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:222
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:257
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition: StringRef.h:271
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
iterator find(const_arg_type_t< ValueT > V)
Definition: DenseSet.h:179
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:97
An efficient, type-erasing, non-owning reference to a callable.
SectionTableRef sections() const
Definition: ELFObject.h:1191
StringTableSection * SectionNames
Definition: ELFObject.h:1185
bool isRelocatable() const
Definition: ELFObject.h:1229
Error updateSection(StringRef Name, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:2127
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove)
Definition: ELFObject.cpp:2234
T & addSection(Ts &&...Args)
Definition: ELFObject.h:1216
Error removeSections(bool AllowBrokenLinks, std::function< bool(const SectionBase &)> ToRemove)
Definition: ELFObject.cpp:2158
SymbolTableSection * SymbolTable
Definition: ELFObject.h:1186
Error compressOrDecompressSections(const CommonConfig &Config)
Definition: ELFObjcopy.cpp:217
SectionBase * findSection(StringRef Name)
Definition: ELFObject.h:1202
Error replaceSections(const DenseMap< SectionBase *, SectionBase * > &FromTo)
Definition: ELFObject.cpp:2210
virtual Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const =0
const SectionBase * getStrTab() const
Definition: ELFObject.h:836
void addSymbol(Twine Name, uint8_t Bind, uint8_t Type, SectionBase *DefinedIn, uint64_t Value, uint8_t Visibility, uint16_t Shndx, uint64_t SymbolSize)
Definition: ELFObject.cpp:697
void updateSymbols(function_ref< void(Symbol &)> Callable)
Definition: ELFObject.cpp:739
virtual Error finalize()=0
virtual Error write()=0
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ELF.h:27
@ SHF_MERGE
Definition: ELF.h:1163
@ SHF_STRINGS
Definition: ELF.h:1166
@ SHF_INFO_LINK
Definition: ELF.h:1169
@ SHF_EXCLUDE
Definition: ELF.h:1191
@ SHF_ALLOC
Definition: ELF.h:1157
@ SHF_MASKPROC
Definition: ELF.h:1201
@ SHF_LINK_ORDER
Definition: ELF.h:1172
@ SHF_GROUP
Definition: ELF.h:1179
@ SHF_COMPRESSED
Definition: ELF.h:1185
@ SHF_MASKOS
Definition: ELF.h:1195
@ SHF_X86_64_LARGE
Definition: ELF.h:1220
@ SHF_WRITE
Definition: ELF.h:1154
@ SHF_TLS
Definition: ELF.h:1182
@ SHF_EXECINSTR
Definition: ELF.h:1160
@ EM_X86_64
Definition: ELF.h:178
@ EM_AARCH64
Definition: ELF.h:280
@ EM_ARM
Definition: ELF.h:156
@ STV_INTERNAL
Definition: ELF.h:1341
@ STV_HIDDEN
Definition: ELF.h:1342
@ STV_PROTECTED
Definition: ELF.h:1343
@ STV_DEFAULT
Definition: ELF.h:1340
@ SHN_ABS
Definition: ELF.h:1054
@ SHN_UNDEF
Definition: ELF.h:1048
@ SHT_STRTAB
Definition: ELF.h:1065
@ SHT_PROGBITS
Definition: ELF.h:1063
@ SHT_REL
Definition: ELF.h:1071
@ SHT_ARM_ATTRIBUTES
Definition: ELF.h:1119
@ SHT_NOBITS
Definition: ELF.h:1070
@ SHT_SYMTAB
Definition: ELF.h:1064
@ SHT_LLVM_PART_EHDR
Definition: ELF.h:1094
@ SHT_RELA
Definition: ELF.h:1066
@ SHT_LLVM_PART_PHDR
Definition: ELF.h:1095
@ SHT_NOTE
Definition: ELF.h:1069
@ STB_GLOBAL
Definition: ELF.h:1311
@ STB_LOCAL
Definition: ELF.h:1310
@ STB_WEAK
Definition: ELF.h:1312
@ STT_FUNC
Definition: ELF.h:1324
@ STT_NOTYPE
Definition: ELF.h:1322
@ STT_SECTION
Definition: ELF.h:1325
@ STT_FILE
Definition: ELF.h:1326
@ STT_GNU_IFUNC
Definition: ELF.h:1329
@ STT_OBJECT
Definition: ELF.h:1323
Error executeObjcopyOnIHex(const CommonConfig &Config, const ELFConfig &ELFConfig, MemoryBuffer &In, raw_ostream &Out)
Apply the transformations described by Config and ELFConfig to In, which must represent an IHex file,...
Definition: ELFObjcopy.cpp:788
Error executeObjcopyOnBinary(const CommonConfig &Config, const ELFConfig &ELFConfig, object::ELFObjectFileBase &In, raw_ostream &Out)
Apply the transformations described by Config and ELFConfig to In and writes the result into Out.
Definition: ELFObjcopy.cpp:821
Error executeObjcopyOnRawBinary(const CommonConfig &Config, const ELFConfig &ELFConfig, MemoryBuffer &In, raw_ostream &Out)
Apply the transformations described by Config and ELFConfig to In, which is treated as a raw binary i...
Definition: ELFObjcopy.cpp:803
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition: Error.h:1339
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1258
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition: Casting.h:548
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
SymInfo contains information about symbol: it's address and section index which is -1LL for absolute ...
std::vector< std::pair< NameMatcher, uint8_t > > SymbolsToSetVisibility
Definition: ELFConfig.h:22
std::function< uint64_t(uint64_t)> EntryExpr
Definition: ELFConfig.h:28
std::shared_ptr< MemoryBuffer > SectionData
Definition: CommonConfig.h:191
std::optional< SectionFlag > NewFlags
Definition: CommonConfig.h:72
uint16_t getShndx() const
Definition: ELFObject.cpp:667