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