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 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 std::optional<DebugCompressionType> CType;
225 for (auto &[Matcher, T] : Config.compressSections)
226 if (Matcher.matches(Sec.Name))
227 CType = T;
228 // Handle --compress-debug-sections and --decompress-debug-sections, which
229 // apply to non-ALLOC debug sections.
230 if (!(Sec.Flags & SHF_ALLOC) && StringRef(Sec.Name).starts_with(".debug")) {
231 if (Config.CompressionType != DebugCompressionType::None)
232 CType = Config.CompressionType;
233 else if (Config.DecompressDebugSections)
235 }
236 if (!CType)
237 continue;
238
239 if (Sec.ParentSegment)
240 return createStringError(
242 "section '" + Sec.Name +
243 "' within a segment cannot be (de)compressed");
244
245 if (auto *CS = dyn_cast<CompressedSection>(&Sec)) {
246 if (*CType == DebugCompressionType::None)
247 ToReplace.emplace_back(
248 &Sec, [=] { return &addSection<DecompressedSection>(*CS); });
249 } else if (*CType != DebugCompressionType::None) {
250 ToReplace.emplace_back(&Sec, [=, S = &Sec] {
251 return &addSection<CompressedSection>(
252 CompressedSection(*S, *CType, Is64Bits));
253 });
254 }
255 }
256
258 for (auto [S, Func] : ToReplace)
259 FromTo[S] = Func();
260 return replaceSections(FromTo);
261}
262
263static bool isAArch64MappingSymbol(const Symbol &Sym) {
264 if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
266 return false;
268 if (!Name.consume_front("$x") && !Name.consume_front("$d"))
269 return false;
270 return Name.empty() || Name.starts_with(".");
271}
272
273static bool isArmMappingSymbol(const Symbol &Sym) {
274 if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
276 return false;
278 if (!Name.consume_front("$a") && !Name.consume_front("$d") &&
279 !Name.consume_front("$t"))
280 return false;
281 return Name.empty() || Name.starts_with(".");
282}
283
284// Check if the symbol should be preserved because it is required by ABI.
285static bool isRequiredByABISymbol(const Object &Obj, const Symbol &Sym) {
286 switch (Obj.Machine) {
287 case EM_AARCH64:
288 // Mapping symbols should be preserved for a relocatable object file.
290 case EM_ARM:
291 // Mapping symbols should be preserved for a relocatable object file.
292 return Obj.isRelocatable() && isArmMappingSymbol(Sym);
293 default:
294 return false;
295 }
296}
297
298static bool isUnneededSymbol(const Symbol &Sym) {
299 return !Sym.Referenced &&
300 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
302}
303
305 const ELFConfig &ELFConfig, Object &Obj) {
306 // TODO: update or remove symbols only if there is an option that affects
307 // them.
308 if (!Obj.SymbolTable)
309 return Error::success();
310
312 if (Config.SymbolsToSkip.matches(Sym.Name))
313 return;
314
315 // Common and undefined symbols don't make sense as local symbols, and can
316 // even cause crashes if we localize those, so skip them.
317 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
320 Config.SymbolsToLocalize.matches(Sym.Name)))
322
323 for (auto &[Matcher, Visibility] : ELFConfig.SymbolsToSetVisibility)
324 if (Matcher.matches(Sym.Name))
325 Sym.Visibility = Visibility;
326
327 // Note: these two globalize flags have very similar names but different
328 // meanings:
329 //
330 // --globalize-symbol: promote a symbol to global
331 // --keep-global-symbol: all symbols except for these should be made local
332 //
333 // If --globalize-symbol is specified for a given symbol, it will be
334 // global in the output file even if it is not included via
335 // --keep-global-symbol. Because of that, make sure to check
336 // --globalize-symbol second.
337 if (!Config.SymbolsToKeepGlobal.empty() &&
338 !Config.SymbolsToKeepGlobal.matches(Sym.Name) &&
341
342 if (Config.SymbolsToGlobalize.matches(Sym.Name) &&
345
346 // SymbolsToWeaken applies to both STB_GLOBAL and STB_GNU_UNIQUE.
347 if (Config.SymbolsToWeaken.matches(Sym.Name) && Sym.Binding != STB_LOCAL)
349
350 if (Config.Weaken && Sym.Binding != STB_LOCAL &&
353
354 const auto I = Config.SymbolsToRename.find(Sym.Name);
355 if (I != Config.SymbolsToRename.end())
356 Sym.Name = std::string(I->getValue());
357
358 if (!Config.SymbolsPrefixRemove.empty() && Sym.Type != STT_SECTION)
359 if (Sym.Name.compare(0, Config.SymbolsPrefixRemove.size(),
360 Config.SymbolsPrefixRemove) == 0)
361 Sym.Name = Sym.Name.substr(Config.SymbolsPrefixRemove.size());
362
363 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
364 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
365 });
366
367 // The purpose of this loop is to mark symbols referenced by sections
368 // (like GroupSection or RelocationSection). This way, we know which
369 // symbols are still 'needed' and which are not.
370 if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty() ||
371 !Config.OnlySection.empty()) {
372 for (SectionBase &Sec : Obj.sections())
373 Sec.markSymbols();
374 }
375
376 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
377 if (Config.SymbolsToKeep.matches(Sym.Name) ||
379 return false;
380
381 if (Config.SymbolsToRemove.matches(Sym.Name))
382 return true;
383
384 if (Config.StripAll || Config.StripAllGNU)
385 return true;
386
387 if (isRequiredByABISymbol(Obj, Sym))
388 return false;
389
390 if (Config.StripDebug && Sym.Type == STT_FILE)
391 return true;
392
393 if ((Config.DiscardMode == DiscardType::All ||
394 (Config.DiscardMode == DiscardType::Locals &&
395 StringRef(Sym.Name).starts_with(".L"))) &&
398 return true;
399
400 if ((Config.StripUnneeded ||
401 Config.UnneededSymbolsToRemove.matches(Sym.Name)) &&
403 return true;
404
405 // We want to remove undefined symbols if all references have been stripped.
406 if (!Config.OnlySection.empty() && !Sym.Referenced &&
408 return true;
409
410 return false;
411 };
412
413 return Obj.removeSymbols(RemoveSymbolsPred);
414}
415
417 const ELFConfig &ELFConfig, Object &Obj) {
418 SectionPred RemovePred = [](const SectionBase &) { return false; };
419
420 // Removes:
421 if (!Config.ToRemove.empty()) {
422 RemovePred = [&Config](const SectionBase &Sec) {
423 return Config.ToRemove.matches(Sec.Name);
424 };
425 }
426
427 if (Config.StripDWO)
428 RemovePred = [RemovePred](const SectionBase &Sec) {
429 return isDWOSection(Sec) || RemovePred(Sec);
430 };
431
432 if (Config.ExtractDWO)
433 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
434 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
435 };
436
437 if (Config.StripAllGNU)
438 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
439 if (RemovePred(Sec))
440 return true;
441 if ((Sec.Flags & SHF_ALLOC) != 0)
442 return false;
443 if (&Sec == Obj.SectionNames)
444 return false;
445 switch (Sec.Type) {
446 case SHT_SYMTAB:
447 case SHT_REL:
448 case SHT_RELA:
449 case SHT_STRTAB:
450 return true;
451 }
452 return isDebugSection(Sec);
453 };
454
455 if (Config.StripSections) {
456 RemovePred = [RemovePred](const SectionBase &Sec) {
457 return RemovePred(Sec) || Sec.ParentSegment == nullptr;
458 };
459 }
460
461 if (Config.StripDebug || Config.StripUnneeded) {
462 RemovePred = [RemovePred](const SectionBase &Sec) {
463 return RemovePred(Sec) || isDebugSection(Sec);
464 };
465 }
466
467 if (Config.StripNonAlloc)
468 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
469 if (RemovePred(Sec))
470 return true;
471 if (&Sec == Obj.SectionNames)
472 return false;
473 return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
474 };
475
476 if (Config.StripAll)
477 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
478 if (RemovePred(Sec))
479 return true;
480 if (&Sec == Obj.SectionNames)
481 return false;
482 if (StringRef(Sec.Name).starts_with(".gnu.warning"))
483 return false;
484 if (StringRef(Sec.Name).starts_with(".gnu_debuglink"))
485 return false;
486 // We keep the .ARM.attribute section to maintain compatibility
487 // with Debian derived distributions. This is a bug in their
488 // patchset as documented here:
489 // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=943798
490 if (Sec.Type == SHT_ARM_ATTRIBUTES)
491 return false;
492 if (Sec.ParentSegment != nullptr)
493 return false;
494 return (Sec.Flags & SHF_ALLOC) == 0;
495 };
496
497 if (Config.ExtractPartition || Config.ExtractMainPartition) {
498 RemovePred = [RemovePred](const SectionBase &Sec) {
499 if (RemovePred(Sec))
500 return true;
501 if (Sec.Type == SHT_LLVM_PART_EHDR || Sec.Type == SHT_LLVM_PART_PHDR)
502 return true;
503 return (Sec.Flags & SHF_ALLOC) != 0 && !Sec.ParentSegment;
504 };
505 }
506
507 // Explicit copies:
508 if (!Config.OnlySection.empty()) {
509 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
510 // Explicitly keep these sections regardless of previous removes.
511 if (Config.OnlySection.matches(Sec.Name))
512 return false;
513
514 // Allow all implicit removes.
515 if (RemovePred(Sec))
516 return true;
517
518 // Keep special sections.
519 if (Obj.SectionNames == &Sec)
520 return false;
521 if (Obj.SymbolTable == &Sec ||
522 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
523 return false;
524
525 // Remove everything else.
526 return true;
527 };
528 }
529
530 if (!Config.KeepSection.empty()) {
531 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
532 // Explicitly keep these sections regardless of previous removes.
533 if (Config.KeepSection.matches(Sec.Name))
534 return false;
535 // Otherwise defer to RemovePred.
536 return RemovePred(Sec);
537 };
538 }
539
540 // This has to be the last predicate assignment.
541 // If the option --keep-symbol has been specified
542 // and at least one of those symbols is present
543 // (equivalently, the updated symbol table is not empty)
544 // the symbol table and the string table should not be removed.
545 if ((!Config.SymbolsToKeep.empty() || ELFConfig.KeepFileSymbols) &&
546 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
547 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
548 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
549 return false;
550 return RemovePred(Sec);
551 };
552 }
553
554 if (Error E = Obj.removeSections(ELFConfig.AllowBrokenLinks, RemovePred))
555 return E;
556
558 return E;
559
560 return Error::success();
561}
562
563// Add symbol to the Object symbol table with the specified properties.
564static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo,
565 uint8_t DefaultVisibility) {
566 SectionBase *Sec = Obj.findSection(SymInfo.SectionName);
567 uint64_t Value = Sec ? Sec->Addr + SymInfo.Value : SymInfo.Value;
568
569 uint8_t Bind = ELF::STB_GLOBAL;
570 uint8_t Type = ELF::STT_NOTYPE;
571 uint8_t Visibility = DefaultVisibility;
572
573 for (SymbolFlag FlagValue : SymInfo.Flags)
574 switch (FlagValue) {
576 Bind = ELF::STB_GLOBAL;
577 break;
579 Bind = ELF::STB_LOCAL;
580 break;
581 case SymbolFlag::Weak:
582 Bind = ELF::STB_WEAK;
583 break;
585 Visibility = ELF::STV_DEFAULT;
586 break;
588 Visibility = ELF::STV_HIDDEN;
589 break;
591 Visibility = ELF::STV_PROTECTED;
592 break;
593 case SymbolFlag::File:
595 break;
598 break;
601 break;
604 break;
607 break;
608 default: /* Other flag values are ignored for ELF. */
609 break;
610 };
611
613 SymInfo.SymbolName, Bind, Type, Sec, Value, Visibility,
615}
616
617static Error
620 ArrayRef<uint8_t> Data(reinterpret_cast<const uint8_t *>(
621 NewSection.SectionData->getBufferStart()),
622 NewSection.SectionData->getBufferSize());
623 return F(NewSection.SectionName, Data);
624}
625
626// This function handles the high level operations of GNU objcopy including
627// handling command line options. It's important to outline certain properties
628// we expect to hold of the command line operations. Any operation that "keeps"
629// should keep regardless of a remove. Additionally any removal should respect
630// any previous removals. Lastly whether or not something is removed shouldn't
631// depend a) on the order the options occur in or b) on some opaque priority
632// system. The only priority is that keeps/copies overrule removes.
634 Object &Obj) {
635 if (Config.OutputArch) {
636 Obj.Machine = Config.OutputArch->EMachine;
637 Obj.OSABI = Config.OutputArch->OSABI;
638 }
639
640 if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
641 return Obj.removeSections(
643 [&Obj](const SectionBase &Sec) { return onlyKeepDWOPred(Obj, Sec); });
644 }
645
646 // Dump sections before add/remove for compatibility with GNU objcopy.
647 for (StringRef Flag : Config.DumpSection) {
649 StringRef FileName;
650 std::tie(SectionName, FileName) = Flag.split('=');
651 if (Error E = dumpSectionToFile(SectionName, FileName, Obj))
652 return E;
653 }
654
655 // It is important to remove the sections first. For example, we want to
656 // remove the relocation sections before removing the symbols. That allows
657 // us to avoid reporting the inappropriate errors about removing symbols
658 // named in relocations.
660 return E;
661
663 return E;
664
665 if (!Config.SetSectionAlignment.empty()) {
666 for (SectionBase &Sec : Obj.sections()) {
667 auto I = Config.SetSectionAlignment.find(Sec.Name);
668 if (I != Config.SetSectionAlignment.end())
669 Sec.Align = I->second;
670 }
671 }
672
673 if (Config.OnlyKeepDebug)
674 for (auto &Sec : Obj.sections())
675 if (Sec.Flags & SHF_ALLOC && Sec.Type != SHT_NOTE)
676 Sec.Type = SHT_NOBITS;
677
678 for (const NewSectionInfo &AddedSection : Config.AddSection) {
679 auto AddSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
680 OwnedDataSection &NewSection =
682 if (Name.starts_with(".note") && Name != ".note.GNU-stack")
683 NewSection.Type = SHT_NOTE;
684 return Error::success();
685 };
686 if (Error E = handleUserSection(AddedSection, AddSection))
687 return E;
688 }
689
690 for (const NewSectionInfo &NewSection : Config.UpdateSection) {
691 auto UpdateSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
692 return Obj.updateSection(Name, Data);
693 };
694 if (Error E = handleUserSection(NewSection, UpdateSection))
695 return E;
696 }
697
698 if (!Config.AddGnuDebugLink.empty())
699 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink,
700 Config.GnuDebugLinkCRC32);
701
702 // If the symbol table was previously removed, we need to create a new one
703 // before adding new symbols.
704 if (!Obj.SymbolTable && !Config.SymbolsToAdd.empty())
705 if (Error E = Obj.addNewSymbolTable())
706 return E;
707
708 for (const NewSymbolInfo &SI : Config.SymbolsToAdd)
710
711 // --set-section-{flags,type} work with sections added by --add-section.
712 if (!Config.SetSectionFlags.empty() || !Config.SetSectionType.empty()) {
713 for (auto &Sec : Obj.sections()) {
714 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
715 if (Iter != Config.SetSectionFlags.end()) {
716 const SectionFlagsUpdate &SFU = Iter->second;
717 if (Error E = setSectionFlagsAndType(Sec, SFU.NewFlags, Obj.Machine))
718 return E;
719 }
720 auto It2 = Config.SetSectionType.find(Sec.Name);
721 if (It2 != Config.SetSectionType.end())
722 setSectionType(Sec, It2->second);
723 }
724 }
725
726 if (!Config.SectionsToRename.empty()) {
727 std::vector<RelocationSectionBase *> RelocSections;
728 DenseSet<SectionBase *> RenamedSections;
729 for (SectionBase &Sec : Obj.sections()) {
730 auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec);
731 const auto Iter = Config.SectionsToRename.find(Sec.Name);
732 if (Iter != Config.SectionsToRename.end()) {
733 const SectionRename &SR = Iter->second;
734 Sec.Name = std::string(SR.NewName);
735 if (SR.NewFlags) {
736 if (Error E = setSectionFlagsAndType(Sec, *SR.NewFlags, Obj.Machine))
737 return E;
738 }
739 RenamedSections.insert(&Sec);
740 } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
741 // Postpone processing relocation sections which are not specified in
742 // their explicit '--rename-section' commands until after their target
743 // sections are renamed.
744 // Dynamic relocation sections (i.e. ones with SHF_ALLOC) should be
745 // renamed only explicitly. Otherwise, renaming, for example, '.got.plt'
746 // would affect '.rela.plt', which is not desirable.
747 RelocSections.push_back(RelocSec);
748 }
749
750 // Rename relocation sections according to their target sections.
751 for (RelocationSectionBase *RelocSec : RelocSections) {
752 auto Iter = RenamedSections.find(RelocSec->getSection());
753 if (Iter != RenamedSections.end())
754 RelocSec->Name = (RelocSec->getNamePrefix() + (*Iter)->Name).str();
755 }
756 }
757
758 // Add a prefix to allocated sections and their relocation sections. This
759 // should be done after renaming the section by Config.SectionToRename to
760 // imitate the GNU objcopy behavior.
761 if (!Config.AllocSectionsPrefix.empty()) {
762 DenseSet<SectionBase *> PrefixedSections;
763 for (SectionBase &Sec : Obj.sections()) {
764 if (Sec.Flags & SHF_ALLOC) {
765 Sec.Name = (Config.AllocSectionsPrefix + Sec.Name).str();
766 PrefixedSections.insert(&Sec);
767 } else if (auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec)) {
768 // Rename relocation sections associated to the allocated sections.
769 // For example, if we rename .text to .prefix.text, we also rename
770 // .rel.text to .rel.prefix.text.
771 //
772 // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
773 // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
774 // .rela.prefix.plt since GNU objcopy does so.
775 const SectionBase *TargetSec = RelocSec->getSection();
776 if (TargetSec && (TargetSec->Flags & SHF_ALLOC)) {
777 // If the relocation section comes *after* the target section, we
778 // don't add Config.AllocSectionsPrefix because we've already added
779 // the prefix to TargetSec->Name. Otherwise, if the relocation
780 // section comes *before* the target section, we add the prefix.
781 if (PrefixedSections.count(TargetSec))
782 Sec.Name = (RelocSec->getNamePrefix() + TargetSec->Name).str();
783 else
784 Sec.Name = (RelocSec->getNamePrefix() + Config.AllocSectionsPrefix +
785 TargetSec->Name)
786 .str();
787 }
788 }
789 }
790 }
791
793 Obj.Entry = ELFConfig.EntryExpr(Obj.Entry);
794 return Error::success();
795}
796
798 raw_ostream &Out, ElfType OutputElfType) {
799 std::unique_ptr<Writer> Writer =
800 createWriter(Config, Obj, Out, OutputElfType);
801 if (Error E = Writer->finalize())
802 return E;
803 return Writer->write();
804}
805
807 const ELFConfig &ELFConfig,
808 MemoryBuffer &In, raw_ostream &Out) {
809 IHexReader Reader(&In);
811 if (!Obj)
812 return Obj.takeError();
813
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,
823 MemoryBuffer &In,
824 raw_ostream &Out) {
827 if (!Obj)
828 return Obj.takeError();
829
830 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
831 // (-B<arch>).
832 const ElfType OutputElfType =
833 getOutputElfType(Config.OutputArch.value_or(MachineInfo()));
834 if (Error E = handleArgs(Config, ELFConfig, **Obj))
835 return E;
836 return writeOutput(Config, **Obj, Out, OutputElfType);
837}
838
840 const ELFConfig &ELFConfig,
842 raw_ostream &Out) {
843 ELFReader Reader(&In, Config.ExtractPartition);
845 Reader.create(!Config.SymbolsToAdd.empty());
846 if (!Obj)
847 return Obj.takeError();
848 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
849 const ElfType OutputElfType = Config.OutputArch
850 ? getOutputElfType(*Config.OutputArch)
851 : getOutputElfType(In);
852
853 if (Error E = handleArgs(Config, ELFConfig, **Obj))
854 return createFileError(Config.InputFilename, std::move(E));
855
856 if (Error E = writeOutput(Config, **Obj, Out, OutputElfType))
857 return createFileError(Config.InputFilename, std::move(E));
858
859 return Error::success();
860}
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:416
static bool isArmMappingSymbol(const Symbol &Sym)
Definition: ELFObjcopy.cpp:273
static Error handleUserSection(const NewSectionInfo &NewSection, function_ref< Error(StringRef, ArrayRef< uint8_t >)> F)
Definition: ELFObjcopy.cpp:618
static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo, uint8_t DefaultVisibility)
Definition: ELFObjcopy.cpp:564
static Error updateAndRemoveSymbols(const CommonConfig &Config, const ELFConfig &ELFConfig, Object &Obj)
Definition: ELFObjcopy.cpp:304
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:285
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:797
static bool isUnneededSymbol(const Symbol &Sym)
Definition: ELFObjcopy.cpp:298
static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig, Object &Obj)
Definition: ELFObjcopy.cpp:633
static bool isAArch64MappingSymbol(const Symbol &Sym)
Definition: ELFObjcopy.cpp:263
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:223
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:258
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition: StringRef.h:270
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:2238
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:2214
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:699
void updateSymbols(function_ref< void(Symbol &)> Callable)
Definition: ELFObject.cpp:741
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:1165
@ SHF_STRINGS
Definition: ELF.h:1168
@ SHF_INFO_LINK
Definition: ELF.h:1171
@ SHF_EXCLUDE
Definition: ELF.h:1193
@ SHF_ALLOC
Definition: ELF.h:1159
@ SHF_MASKPROC
Definition: ELF.h:1203
@ SHF_LINK_ORDER
Definition: ELF.h:1174
@ SHF_GROUP
Definition: ELF.h:1181
@ SHF_COMPRESSED
Definition: ELF.h:1187
@ SHF_MASKOS
Definition: ELF.h:1197
@ SHF_X86_64_LARGE
Definition: ELF.h:1222
@ SHF_WRITE
Definition: ELF.h:1156
@ SHF_TLS
Definition: ELF.h:1184
@ SHF_EXECINSTR
Definition: ELF.h:1162
@ EM_X86_64
Definition: ELF.h:178
@ EM_AARCH64
Definition: ELF.h:280
@ EM_ARM
Definition: ELF.h:156
@ STV_INTERNAL
Definition: ELF.h:1343
@ STV_HIDDEN
Definition: ELF.h:1344
@ STV_PROTECTED
Definition: ELF.h:1345
@ STV_DEFAULT
Definition: ELF.h:1342
@ SHN_ABS
Definition: ELF.h:1056
@ SHN_UNDEF
Definition: ELF.h:1050
@ SHT_STRTAB
Definition: ELF.h:1067
@ SHT_PROGBITS
Definition: ELF.h:1065
@ SHT_REL
Definition: ELF.h:1073
@ SHT_ARM_ATTRIBUTES
Definition: ELF.h:1121
@ SHT_NOBITS
Definition: ELF.h:1072
@ SHT_SYMTAB
Definition: ELF.h:1066
@ SHT_LLVM_PART_EHDR
Definition: ELF.h:1096
@ SHT_RELA
Definition: ELF.h:1068
@ SHT_LLVM_PART_PHDR
Definition: ELF.h:1097
@ SHT_NOTE
Definition: ELF.h:1071
@ STB_GLOBAL
Definition: ELF.h:1313
@ STB_LOCAL
Definition: ELF.h:1312
@ STB_WEAK
Definition: ELF.h:1314
@ STT_FUNC
Definition: ELF.h:1326
@ STT_NOTYPE
Definition: ELF.h:1324
@ STT_SECTION
Definition: ELF.h:1327
@ STT_FILE
Definition: ELF.h:1328
@ STT_GNU_IFUNC
Definition: ELF.h:1331
@ STT_OBJECT
Definition: ELF.h:1325
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:806
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:839
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:821
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:669