LLVM 20.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
628 // An ELF note has the following structure:
629 // Name Size: 4 bytes (integer)
630 // Desc Size: 4 bytes (integer)
631 // Type : 4 bytes
632 // Name : variable size, padded to a 4 byte boundary
633 // Desc : variable size, padded to a 4 byte boundary
634
635 if (Data.empty())
636 return Error::success();
637
638 if (Data.size() < 12) {
639 std::string msg;
641 << Name << " data must be either empty or at least 12 bytes long";
643 }
644 if (Data.size() % 4 != 0) {
645 std::string msg;
647 << Name << " data size must be a multiple of 4 bytes";
649 }
650 ArrayRef<uint8_t> NameSize = Data.slice(0, 4);
651 ArrayRef<uint8_t> DescSize = Data.slice(4, 4);
652
653 uint32_t NameSizeValue = support::endian::read32(NameSize.data(), Endianness);
654 uint32_t DescSizeValue = support::endian::read32(DescSize.data(), Endianness);
655
656 uint64_t ExpectedDataSize =
657 /*NameSize=*/4 + /*DescSize=*/4 + /*Type=*/4 +
658 /*Name=*/alignTo(NameSizeValue, 4) +
659 /*Desc=*/alignTo(DescSizeValue, 4);
660 uint64_t ActualDataSize = Data.size();
661 if (ActualDataSize != ExpectedDataSize) {
662 std::string msg;
664 << Name
665 << " data size is incompatible with the content of "
666 "the name and description size fields:"
667 << " expecting " << ExpectedDataSize << ", found " << ActualDataSize;
669 }
670
671 return Error::success();
672}
673
674// This function handles the high level operations of GNU objcopy including
675// handling command line options. It's important to outline certain properties
676// we expect to hold of the command line operations. Any operation that "keeps"
677// should keep regardless of a remove. Additionally any removal should respect
678// any previous removals. Lastly whether or not something is removed shouldn't
679// depend a) on the order the options occur in or b) on some opaque priority
680// system. The only priority is that keeps/copies overrule removes.
682 ElfType OutputElfType, Object &Obj) {
683 if (Config.OutputArch) {
684 Obj.Machine = Config.OutputArch->EMachine;
685 Obj.OSABI = Config.OutputArch->OSABI;
686 }
687
688 if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
689 return Obj.removeSections(
691 [&Obj](const SectionBase &Sec) { return onlyKeepDWOPred(Obj, Sec); });
692 }
693
694 // Dump sections before add/remove for compatibility with GNU objcopy.
695 for (StringRef Flag : Config.DumpSection) {
697 StringRef FileName;
698 std::tie(SectionName, FileName) = Flag.split('=');
699 if (Error E = dumpSectionToFile(SectionName, FileName, Obj))
700 return E;
701 }
702
703 // It is important to remove the sections first. For example, we want to
704 // remove the relocation sections before removing the symbols. That allows
705 // us to avoid reporting the inappropriate errors about removing symbols
706 // named in relocations.
708 return E;
709
711 return E;
712
713 if (!Config.SetSectionAlignment.empty()) {
714 for (SectionBase &Sec : Obj.sections()) {
715 auto I = Config.SetSectionAlignment.find(Sec.Name);
716 if (I != Config.SetSectionAlignment.end())
717 Sec.Align = I->second;
718 }
719 }
720
721 if (Config.ChangeSectionLMAValAll != 0) {
722 for (Segment &Seg : Obj.segments()) {
723 if (Seg.FileSize > 0) {
724 if (Config.ChangeSectionLMAValAll > 0 &&
725 Seg.PAddr > std::numeric_limits<uint64_t>::max() -
726 Config.ChangeSectionLMAValAll) {
727 return createStringError(
729 "address 0x" + Twine::utohexstr(Seg.PAddr) +
730 " cannot be increased by 0x" +
731 Twine::utohexstr(Config.ChangeSectionLMAValAll) +
732 ". The result would overflow");
733 } else if (Config.ChangeSectionLMAValAll < 0 &&
734 Seg.PAddr < std::numeric_limits<uint64_t>::min() -
735 Config.ChangeSectionLMAValAll) {
736 return createStringError(
738 "address 0x" + Twine::utohexstr(Seg.PAddr) +
739 " cannot be decreased by 0x" +
740 Twine::utohexstr(std::abs(Config.ChangeSectionLMAValAll)) +
741 ". The result would underflow");
742 }
743 Seg.PAddr += Config.ChangeSectionLMAValAll;
744 }
745 }
746 }
747
748 if (!Config.ChangeSectionAddress.empty()) {
749 if (Obj.Type != ELF::ET_REL)
750 return createStringError(
751 object_error::invalid_file_type,
752 "cannot change section address in a non-relocatable file");
753
754 StringMap<AddressUpdate> SectionsToUpdateAddress;
755 for (const SectionPatternAddressUpdate &PatternUpdate :
756 make_range(Config.ChangeSectionAddress.rbegin(),
757 Config.ChangeSectionAddress.rend())) {
758 for (SectionBase &Sec : Obj.sections()) {
759 if (PatternUpdate.SectionPattern.matches(Sec.Name) &&
760 SectionsToUpdateAddress.try_emplace(Sec.Name, PatternUpdate.Update)
761 .second) {
762 if (PatternUpdate.Update.Kind == AdjustKind::Subtract &&
763 Sec.Addr < PatternUpdate.Update.Value) {
764 return createStringError(
766 "address 0x" + Twine::utohexstr(Sec.Addr) +
767 " cannot be decreased by 0x" +
768 Twine::utohexstr(PatternUpdate.Update.Value) +
769 ". The result would underflow");
770 }
771 if (PatternUpdate.Update.Kind == AdjustKind::Add &&
772 Sec.Addr > std::numeric_limits<uint64_t>::max() -
773 PatternUpdate.Update.Value) {
774 return createStringError(
776 "address 0x" + Twine::utohexstr(Sec.Addr) +
777 " cannot be increased by 0x" +
778 Twine::utohexstr(PatternUpdate.Update.Value) +
779 ". The result would overflow");
780 }
781
782 switch (PatternUpdate.Update.Kind) {
783 case (AdjustKind::Set):
784 Sec.Addr = PatternUpdate.Update.Value;
785 break;
787 Sec.Addr -= PatternUpdate.Update.Value;
788 break;
789 case (AdjustKind::Add):
790 Sec.Addr += PatternUpdate.Update.Value;
791 break;
792 }
793 }
794 }
795 }
796 }
797
798 if (Config.OnlyKeepDebug)
799 for (auto &Sec : Obj.sections())
800 if (Sec.Flags & SHF_ALLOC && Sec.Type != SHT_NOTE)
801 Sec.Type = SHT_NOBITS;
802
803 endianness E = OutputElfType == ELFT_ELF32LE || OutputElfType == ELFT_ELF64LE
806
807 for (const NewSectionInfo &AddedSection : Config.AddSection) {
808 auto AddSection = [&](StringRef Name, ArrayRef<uint8_t> Data) -> Error {
809 OwnedDataSection &NewSection =
811 if (Name.starts_with(".note") && Name != ".note.GNU-stack") {
812 NewSection.Type = SHT_NOTE;
814 return verifyNoteSection(Name, E, Data);
815 }
816 return Error::success();
817 };
818 if (Error E = handleUserSection(AddedSection, AddSection))
819 return E;
820 }
821
822 for (const NewSectionInfo &NewSection : Config.UpdateSection) {
823 auto UpdateSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
824 return Obj.updateSection(Name, Data);
825 };
826 if (Error E = handleUserSection(NewSection, UpdateSection))
827 return E;
828 }
829
830 if (!Config.AddGnuDebugLink.empty())
831 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink,
832 Config.GnuDebugLinkCRC32);
833
834 // If the symbol table was previously removed, we need to create a new one
835 // before adding new symbols.
836 if (!Obj.SymbolTable && !Config.SymbolsToAdd.empty())
837 if (Error E = Obj.addNewSymbolTable())
838 return E;
839
840 for (const NewSymbolInfo &SI : Config.SymbolsToAdd)
842
843 // --set-section-{flags,type} work with sections added by --add-section.
844 if (!Config.SetSectionFlags.empty() || !Config.SetSectionType.empty()) {
845 for (auto &Sec : Obj.sections()) {
846 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
847 if (Iter != Config.SetSectionFlags.end()) {
848 const SectionFlagsUpdate &SFU = Iter->second;
849 if (Error E = setSectionFlagsAndType(Sec, SFU.NewFlags, Obj.Machine))
850 return E;
851 }
852 auto It2 = Config.SetSectionType.find(Sec.Name);
853 if (It2 != Config.SetSectionType.end())
854 setSectionType(Sec, It2->second);
855 }
856 }
857
858 if (!Config.SectionsToRename.empty()) {
859 std::vector<RelocationSectionBase *> RelocSections;
860 DenseSet<SectionBase *> RenamedSections;
861 for (SectionBase &Sec : Obj.sections()) {
862 auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec);
863 const auto Iter = Config.SectionsToRename.find(Sec.Name);
864 if (Iter != Config.SectionsToRename.end()) {
865 const SectionRename &SR = Iter->second;
866 Sec.Name = std::string(SR.NewName);
867 if (SR.NewFlags) {
868 if (Error E = setSectionFlagsAndType(Sec, *SR.NewFlags, Obj.Machine))
869 return E;
870 }
871 RenamedSections.insert(&Sec);
872 } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
873 // Postpone processing relocation sections which are not specified in
874 // their explicit '--rename-section' commands until after their target
875 // sections are renamed.
876 // Dynamic relocation sections (i.e. ones with SHF_ALLOC) should be
877 // renamed only explicitly. Otherwise, renaming, for example, '.got.plt'
878 // would affect '.rela.plt', which is not desirable.
879 RelocSections.push_back(RelocSec);
880 }
881
882 // Rename relocation sections according to their target sections.
883 for (RelocationSectionBase *RelocSec : RelocSections) {
884 auto Iter = RenamedSections.find(RelocSec->getSection());
885 if (Iter != RenamedSections.end())
886 RelocSec->Name = (RelocSec->getNamePrefix() + (*Iter)->Name).str();
887 }
888 }
889
890 // Add a prefix to allocated sections and their relocation sections. This
891 // should be done after renaming the section by Config.SectionToRename to
892 // imitate the GNU objcopy behavior.
893 if (!Config.AllocSectionsPrefix.empty()) {
894 DenseSet<SectionBase *> PrefixedSections;
895 for (SectionBase &Sec : Obj.sections()) {
896 if (Sec.Flags & SHF_ALLOC) {
897 Sec.Name = (Config.AllocSectionsPrefix + Sec.Name).str();
898 PrefixedSections.insert(&Sec);
899 } else if (auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec)) {
900 // Rename relocation sections associated to the allocated sections.
901 // For example, if we rename .text to .prefix.text, we also rename
902 // .rel.text to .rel.prefix.text.
903 //
904 // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
905 // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
906 // .rela.prefix.plt since GNU objcopy does so.
907 const SectionBase *TargetSec = RelocSec->getSection();
908 if (TargetSec && (TargetSec->Flags & SHF_ALLOC)) {
909 // If the relocation section comes *after* the target section, we
910 // don't add Config.AllocSectionsPrefix because we've already added
911 // the prefix to TargetSec->Name. Otherwise, if the relocation
912 // section comes *before* the target section, we add the prefix.
913 if (PrefixedSections.count(TargetSec))
914 Sec.Name = (RelocSec->getNamePrefix() + TargetSec->Name).str();
915 else
916 Sec.Name = (RelocSec->getNamePrefix() + Config.AllocSectionsPrefix +
917 TargetSec->Name)
918 .str();
919 }
920 }
921 }
922 }
923
925 Obj.Entry = ELFConfig.EntryExpr(Obj.Entry);
926 return Error::success();
927}
928
930 raw_ostream &Out, ElfType OutputElfType) {
931 std::unique_ptr<Writer> Writer =
932 createWriter(Config, Obj, Out, OutputElfType);
933 if (Error E = Writer->finalize())
934 return E;
935 return Writer->write();
936}
937
939 const ELFConfig &ELFConfig,
940 MemoryBuffer &In, raw_ostream &Out) {
941 IHexReader Reader(&In);
943 if (!Obj)
944 return Obj.takeError();
945
946 const ElfType OutputElfType =
947 getOutputElfType(Config.OutputArch.value_or(MachineInfo()));
948 if (Error E = handleArgs(Config, ELFConfig, OutputElfType, **Obj))
949 return E;
950 return writeOutput(Config, **Obj, Out, OutputElfType);
951}
952
954 const ELFConfig &ELFConfig,
955 MemoryBuffer &In,
956 raw_ostream &Out) {
959 if (!Obj)
960 return Obj.takeError();
961
962 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
963 // (-B<arch>).
964 const ElfType OutputElfType =
965 getOutputElfType(Config.OutputArch.value_or(MachineInfo()));
966 if (Error E = handleArgs(Config, ELFConfig, OutputElfType, **Obj))
967 return E;
968 return writeOutput(Config, **Obj, Out, OutputElfType);
969}
970
972 const ELFConfig &ELFConfig,
974 raw_ostream &Out) {
975 ELFReader Reader(&In, Config.ExtractPartition);
977 Reader.create(!Config.SymbolsToAdd.empty());
978 if (!Obj)
979 return Obj.takeError();
980 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
981 const ElfType OutputElfType = Config.OutputArch
982 ? getOutputElfType(*Config.OutputArch)
983 : getOutputElfType(In);
984
985 if (Error E = handleArgs(Config, ELFConfig, OutputElfType, **Obj))
986 return createFileError(Config.InputFilename, std::move(E));
987
988 if (Error E = writeOutput(Config, **Obj, Out, OutputElfType))
989 return createFileError(Config.InputFilename, std::move(E));
990
991 return Error::success();
992}
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 handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig, ElfType OutputElfType, Object &Obj)
Definition: ELFObjcopy.cpp:681
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 Error verifyNoteSection(StringRef Name, endianness Endianness, ArrayRef< uint8_t > Data)
Definition: ELFObjcopy.cpp:626
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:929
static bool isUnneededSymbol(const Symbol &Sym)
Definition: ELFObjcopy.cpp:298
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(PassOpts->AAPipeline)
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
const T * data() const
Definition: ArrayRef.h:162
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:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
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
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition: StringMap.h:368
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:215
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:250
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition: StringRef.h:262
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:416
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:1199
StringTableSection * SectionNames
Definition: ELFObject.h:1193
bool isRelocatable() const
Definition: ELFObject.h:1237
Error updateSection(StringRef Name, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:2160
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove)
Definition: ELFObject.cpp:2276
T & addSection(Ts &&...Args)
Definition: ELFObject.h:1224
Error removeSections(bool AllowBrokenLinks, std::function< bool(const SectionBase &)> ToRemove)
Definition: ELFObject.cpp:2191
ConstRange< Segment > segments() const
Definition: ELFObject.h:1217
SymbolTableSection * SymbolTable
Definition: ELFObject.h:1194
Error compressOrDecompressSections(const CommonConfig &Config)
Definition: ELFObjcopy.cpp:217
SectionBase * findSection(StringRef Name)
Definition: ELFObject.h:1210
Error replaceSections(const DenseMap< SectionBase *, SectionBase * > &FromTo)
Definition: ELFObject.cpp:2252
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:717
void updateSymbols(function_ref< void(Symbol &)> Callable)
Definition: ELFObject.cpp:759
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
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ELF.h:28
@ STV_INTERNAL
Definition: ELF.h:1370
@ STV_HIDDEN
Definition: ELF.h:1371
@ STV_PROTECTED
Definition: ELF.h:1372
@ STV_DEFAULT
Definition: ELF.h:1369
@ EM_X86_64
Definition: ELF.h:179
@ EM_AARCH64
Definition: ELF.h:281
@ EM_ARM
Definition: ELF.h:157
@ ET_REL
Definition: ELF.h:117
@ SHT_STRTAB
Definition: ELF.h:1091
@ SHT_PROGBITS
Definition: ELF.h:1089
@ SHT_REL
Definition: ELF.h:1097
@ SHT_ARM_ATTRIBUTES
Definition: ELF.h:1148
@ SHT_NOBITS
Definition: ELF.h:1096
@ SHT_SYMTAB
Definition: ELF.h:1090
@ SHT_LLVM_PART_EHDR
Definition: ELF.h:1123
@ SHT_RELA
Definition: ELF.h:1092
@ SHT_LLVM_PART_PHDR
Definition: ELF.h:1124
@ SHT_NOTE
Definition: ELF.h:1095
@ STB_GLOBAL
Definition: ELF.h:1340
@ STB_LOCAL
Definition: ELF.h:1339
@ STB_WEAK
Definition: ELF.h:1341
@ SHN_ABS
Definition: ELF.h:1080
@ SHN_UNDEF
Definition: ELF.h:1074
@ SHF_MERGE
Definition: ELF.h:1192
@ SHF_STRINGS
Definition: ELF.h:1195
@ SHF_INFO_LINK
Definition: ELF.h:1198
@ SHF_EXCLUDE
Definition: ELF.h:1220
@ SHF_ALLOC
Definition: ELF.h:1186
@ SHF_MASKPROC
Definition: ELF.h:1230
@ SHF_LINK_ORDER
Definition: ELF.h:1201
@ SHF_GROUP
Definition: ELF.h:1208
@ SHF_COMPRESSED
Definition: ELF.h:1214
@ SHF_MASKOS
Definition: ELF.h:1224
@ SHF_X86_64_LARGE
Definition: ELF.h:1249
@ SHF_WRITE
Definition: ELF.h:1183
@ SHF_TLS
Definition: ELF.h:1211
@ SHF_EXECINSTR
Definition: ELF.h:1189
@ STT_FUNC
Definition: ELF.h:1353
@ STT_NOTYPE
Definition: ELF.h:1351
@ STT_SECTION
Definition: ELF.h:1354
@ STT_FILE
Definition: ELF.h:1355
@ STT_GNU_IFUNC
Definition: ELF.h:1358
@ STT_OBJECT
Definition: ELF.h:1352
constexpr size_t NameSize
Definition: XCOFF.h:29
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:938
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:971
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:953
uint32_t read32(const void *P, endianness E)
Definition: Endian.h:405
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:1380
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
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
endianness
Definition: bit.h:70
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:203
std::optional< SectionFlag > NewFlags
Definition: CommonConfig.h:72
uint16_t getShndx() const
Definition: ELFObject.cpp:687