xref: /freebsd/contrib/llvm-project/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp (revision 0ad011ececb978e22a9bff2acf76633b094f1ff6)
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 
9 #include "llvm/ObjCopy/ELF/ELFObjcopy.h"
10 #include "ELFObject.h"
11 #include "llvm/ADT/BitmaskEnum.h"
12 #include "llvm/ADT/DenseSet.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/MC/MCTargetOptions.h"
19 #include "llvm/ObjCopy/CommonConfig.h"
20 #include "llvm/ObjCopy/ELF/ELFConfig.h"
21 #include "llvm/Object/Binary.h"
22 #include "llvm/Object/ELFObjectFile.h"
23 #include "llvm/Object/ELFTypes.h"
24 #include "llvm/Object/Error.h"
25 #include "llvm/Option/Option.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Compression.h"
28 #include "llvm/Support/Errc.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ErrorOr.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Memory.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/raw_ostream.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 
46 using namespace llvm;
47 using namespace llvm::ELF;
48 using namespace llvm::objcopy;
49 using namespace llvm::objcopy::elf;
50 using namespace llvm::object;
51 
52 using SectionPred = std::function<bool(const SectionBase &Sec)>;
53 
54 static bool isDebugSection(const SectionBase &Sec) {
55   return StringRef(Sec.Name).startswith(".debug") || Sec.Name == ".gdb_index";
56 }
57 
58 static bool isDWOSection(const SectionBase &Sec) {
59   return StringRef(Sec.Name).endswith(".dwo");
60 }
61 
62 static 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 
71 static uint64_t getNewShfFlags(SectionFlag AllFlags) {
72   uint64_t NewFlags = 0;
73   if (AllFlags & SectionFlag::SecAlloc)
74     NewFlags |= ELF::SHF_ALLOC;
75   if (!(AllFlags & SectionFlag::SecReadonly))
76     NewFlags |= ELF::SHF_WRITE;
77   if (AllFlags & SectionFlag::SecCode)
78     NewFlags |= ELF::SHF_EXECINSTR;
79   if (AllFlags & SectionFlag::SecMerge)
80     NewFlags |= ELF::SHF_MERGE;
81   if (AllFlags & SectionFlag::SecStrings)
82     NewFlags |= ELF::SHF_STRINGS;
83   if (AllFlags & SectionFlag::SecExclude)
84     NewFlags |= ELF::SHF_EXCLUDE;
85   return NewFlags;
86 }
87 
88 static uint64_t getSectionFlagsPreserveMask(uint64_t OldFlags,
89                                             uint64_t NewFlags) {
90   // Preserve some flags which should not be dropped when setting flags.
91   // Also, preserve anything OS/processor dependant.
92   const uint64_t PreserveMask =
93       (ELF::SHF_COMPRESSED | ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
94        ELF::SHF_MASKOS | ELF::SHF_MASKPROC | ELF::SHF_TLS |
95        ELF::SHF_INFO_LINK) &
96       ~ELF::SHF_EXCLUDE;
97   return (OldFlags & PreserveMask) | (NewFlags & ~PreserveMask);
98 }
99 
100 static void setSectionType(SectionBase &Sec, uint64_t Type) {
101   // If Sec's type is changed from SHT_NOBITS due to --set-section-flags,
102   // Offset may not be aligned. Align it to max(Align, 1).
103   if (Sec.Type == ELF::SHT_NOBITS && Type != ELF::SHT_NOBITS)
104     Sec.Offset = alignTo(Sec.Offset, std::max(Sec.Align, uint64_t(1)));
105   Sec.Type = Type;
106 }
107 
108 static void setSectionFlagsAndType(SectionBase &Sec, SectionFlag Flags) {
109   Sec.Flags = getSectionFlagsPreserveMask(Sec.Flags, getNewShfFlags(Flags));
110 
111   // In GNU objcopy, certain flags promote SHT_NOBITS to SHT_PROGBITS. This rule
112   // may promote more non-ALLOC sections than GNU objcopy, but it is fine as
113   // non-ALLOC SHT_NOBITS sections do not make much sense.
114   if (Sec.Type == SHT_NOBITS &&
115       (!(Sec.Flags & ELF::SHF_ALLOC) ||
116        Flags & (SectionFlag::SecContents | SectionFlag::SecLoad)))
117     setSectionType(Sec, ELF::SHT_PROGBITS);
118 }
119 
120 static ElfType getOutputElfType(const Binary &Bin) {
121   // Infer output ELF type from the input ELF object
122   if (isa<ELFObjectFile<ELF32LE>>(Bin))
123     return ELFT_ELF32LE;
124   if (isa<ELFObjectFile<ELF64LE>>(Bin))
125     return ELFT_ELF64LE;
126   if (isa<ELFObjectFile<ELF32BE>>(Bin))
127     return ELFT_ELF32BE;
128   if (isa<ELFObjectFile<ELF64BE>>(Bin))
129     return ELFT_ELF64BE;
130   llvm_unreachable("Invalid ELFType");
131 }
132 
133 static ElfType getOutputElfType(const MachineInfo &MI) {
134   // Infer output ELF type from the binary arch specified
135   if (MI.Is64Bit)
136     return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
137   else
138     return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
139 }
140 
141 static std::unique_ptr<Writer> createELFWriter(const CommonConfig &Config,
142                                                Object &Obj, raw_ostream &Out,
143                                                ElfType OutputElfType) {
144   // Depending on the initial ELFT and OutputFormat we need a different Writer.
145   switch (OutputElfType) {
146   case ELFT_ELF32LE:
147     return std::make_unique<ELFWriter<ELF32LE>>(Obj, Out, !Config.StripSections,
148                                                 Config.OnlyKeepDebug);
149   case ELFT_ELF64LE:
150     return std::make_unique<ELFWriter<ELF64LE>>(Obj, Out, !Config.StripSections,
151                                                 Config.OnlyKeepDebug);
152   case ELFT_ELF32BE:
153     return std::make_unique<ELFWriter<ELF32BE>>(Obj, Out, !Config.StripSections,
154                                                 Config.OnlyKeepDebug);
155   case ELFT_ELF64BE:
156     return std::make_unique<ELFWriter<ELF64BE>>(Obj, Out, !Config.StripSections,
157                                                 Config.OnlyKeepDebug);
158   }
159   llvm_unreachable("Invalid output format");
160 }
161 
162 static std::unique_ptr<Writer> createWriter(const CommonConfig &Config,
163                                             Object &Obj, raw_ostream &Out,
164                                             ElfType OutputElfType) {
165   switch (Config.OutputFormat) {
166   case FileFormat::Binary:
167     return std::make_unique<BinaryWriter>(Obj, Out);
168   case FileFormat::IHex:
169     return std::make_unique<IHexWriter>(Obj, Out);
170   default:
171     return createELFWriter(Config, Obj, Out, OutputElfType);
172   }
173 }
174 
175 static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
176                                Object &Obj) {
177   for (auto &Sec : Obj.sections()) {
178     if (Sec.Name == SecName) {
179       if (Sec.Type == SHT_NOBITS)
180         return createStringError(object_error::parse_failed,
181                                  "cannot dump section '%s': it has no contents",
182                                  SecName.str().c_str());
183       Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
184           FileOutputBuffer::create(Filename, Sec.OriginalData.size());
185       if (!BufferOrErr)
186         return BufferOrErr.takeError();
187       std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
188       std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
189                 Buf->getBufferStart());
190       if (Error E = Buf->commit())
191         return E;
192       return Error::success();
193     }
194   }
195   return createStringError(object_error::parse_failed, "section '%s' not found",
196                            SecName.str().c_str());
197 }
198 
199 static bool isCompressable(const SectionBase &Sec) {
200   return !(Sec.Flags & ELF::SHF_COMPRESSED) &&
201          StringRef(Sec.Name).startswith(".debug");
202 }
203 
204 static Error replaceDebugSections(
205     Object &Obj, function_ref<bool(const SectionBase &)> ShouldReplace,
206     function_ref<Expected<SectionBase *>(const SectionBase *)> AddSection) {
207   // Build a list of the debug sections we are going to replace.
208   // We can't call `AddSection` while iterating over sections,
209   // because it would mutate the sections array.
210   SmallVector<SectionBase *, 13> ToReplace;
211   for (auto &Sec : Obj.sections())
212     if (ShouldReplace(Sec))
213       ToReplace.push_back(&Sec);
214 
215   // Build a mapping from original section to a new one.
216   DenseMap<SectionBase *, SectionBase *> FromTo;
217   for (SectionBase *S : ToReplace) {
218     Expected<SectionBase *> NewSection = AddSection(S);
219     if (!NewSection)
220       return NewSection.takeError();
221 
222     FromTo[S] = *NewSection;
223   }
224 
225   return Obj.replaceSections(FromTo);
226 }
227 
228 static bool isAArch64MappingSymbol(const Symbol &Sym) {
229   if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
230       Sym.getShndx() == SHN_UNDEF)
231     return false;
232   StringRef Name = Sym.Name;
233   if (!Name.consume_front("$x") && !Name.consume_front("$d"))
234     return false;
235   return Name.empty() || Name.startswith(".");
236 }
237 
238 static bool isArmMappingSymbol(const Symbol &Sym) {
239   if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
240       Sym.getShndx() == SHN_UNDEF)
241     return false;
242   StringRef Name = Sym.Name;
243   if (!Name.consume_front("$a") && !Name.consume_front("$d") &&
244       !Name.consume_front("$t"))
245     return false;
246   return Name.empty() || Name.startswith(".");
247 }
248 
249 // Check if the symbol should be preserved because it is required by ABI.
250 static bool isRequiredByABISymbol(const Object &Obj, const Symbol &Sym) {
251   switch (Obj.Machine) {
252   case EM_AARCH64:
253     // Mapping symbols should be preserved for a relocatable object file.
254     return Obj.isRelocatable() && isAArch64MappingSymbol(Sym);
255   case EM_ARM:
256     // Mapping symbols should be preserved for a relocatable object file.
257     return Obj.isRelocatable() && isArmMappingSymbol(Sym);
258   default:
259     return false;
260   }
261 }
262 
263 static bool isUnneededSymbol(const Symbol &Sym) {
264   return !Sym.Referenced &&
265          (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
266          Sym.Type != STT_SECTION;
267 }
268 
269 static Error updateAndRemoveSymbols(const CommonConfig &Config,
270                                     const ELFConfig &ELFConfig, Object &Obj) {
271   // TODO: update or remove symbols only if there is an option that affects
272   // them.
273   if (!Obj.SymbolTable)
274     return Error::success();
275 
276   Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
277     // Common and undefined symbols don't make sense as local symbols, and can
278     // even cause crashes if we localize those, so skip them.
279     if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
280         ((ELFConfig.LocalizeHidden &&
281           (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
282          Config.SymbolsToLocalize.matches(Sym.Name)))
283       Sym.Binding = STB_LOCAL;
284 
285     // Note: these two globalize flags have very similar names but different
286     // meanings:
287     //
288     // --globalize-symbol: promote a symbol to global
289     // --keep-global-symbol: all symbols except for these should be made local
290     //
291     // If --globalize-symbol is specified for a given symbol, it will be
292     // global in the output file even if it is not included via
293     // --keep-global-symbol. Because of that, make sure to check
294     // --globalize-symbol second.
295     if (!Config.SymbolsToKeepGlobal.empty() &&
296         !Config.SymbolsToKeepGlobal.matches(Sym.Name) &&
297         Sym.getShndx() != SHN_UNDEF)
298       Sym.Binding = STB_LOCAL;
299 
300     if (Config.SymbolsToGlobalize.matches(Sym.Name) &&
301         Sym.getShndx() != SHN_UNDEF)
302       Sym.Binding = STB_GLOBAL;
303 
304     // SymbolsToWeaken applies to both STB_GLOBAL and STB_GNU_UNIQUE.
305     if (Config.SymbolsToWeaken.matches(Sym.Name) && Sym.Binding != STB_LOCAL)
306       Sym.Binding = STB_WEAK;
307 
308     if (Config.Weaken && Sym.Binding != STB_LOCAL &&
309         Sym.getShndx() != SHN_UNDEF)
310       Sym.Binding = STB_WEAK;
311 
312     const auto I = Config.SymbolsToRename.find(Sym.Name);
313     if (I != Config.SymbolsToRename.end())
314       Sym.Name = std::string(I->getValue());
315 
316     if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
317       Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
318   });
319 
320   // The purpose of this loop is to mark symbols referenced by sections
321   // (like GroupSection or RelocationSection). This way, we know which
322   // symbols are still 'needed' and which are not.
323   if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty() ||
324       !Config.OnlySection.empty()) {
325     for (SectionBase &Sec : Obj.sections())
326       Sec.markSymbols();
327   }
328 
329   auto RemoveSymbolsPred = [&](const Symbol &Sym) {
330     if (Config.SymbolsToKeep.matches(Sym.Name) ||
331         (ELFConfig.KeepFileSymbols && Sym.Type == STT_FILE))
332       return false;
333 
334     if (Config.SymbolsToRemove.matches(Sym.Name))
335       return true;
336 
337     if (Config.StripAll || Config.StripAllGNU)
338       return true;
339 
340     if (isRequiredByABISymbol(Obj, Sym))
341       return false;
342 
343     if (Config.StripDebug && Sym.Type == STT_FILE)
344       return true;
345 
346     if ((Config.DiscardMode == DiscardType::All ||
347          (Config.DiscardMode == DiscardType::Locals &&
348           StringRef(Sym.Name).startswith(".L"))) &&
349         Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
350         Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
351       return true;
352 
353     if ((Config.StripUnneeded ||
354          Config.UnneededSymbolsToRemove.matches(Sym.Name)) &&
355         (!Obj.isRelocatable() || isUnneededSymbol(Sym)))
356       return true;
357 
358     // We want to remove undefined symbols if all references have been stripped.
359     if (!Config.OnlySection.empty() && !Sym.Referenced &&
360         Sym.getShndx() == SHN_UNDEF)
361       return true;
362 
363     return false;
364   };
365 
366   return Obj.removeSymbols(RemoveSymbolsPred);
367 }
368 
369 static Error replaceAndRemoveSections(const CommonConfig &Config,
370                                       const ELFConfig &ELFConfig, Object &Obj) {
371   SectionPred RemovePred = [](const SectionBase &) { return false; };
372 
373   // Removes:
374   if (!Config.ToRemove.empty()) {
375     RemovePred = [&Config](const SectionBase &Sec) {
376       return Config.ToRemove.matches(Sec.Name);
377     };
378   }
379 
380   if (Config.StripDWO)
381     RemovePred = [RemovePred](const SectionBase &Sec) {
382       return isDWOSection(Sec) || RemovePred(Sec);
383     };
384 
385   if (Config.ExtractDWO)
386     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
387       return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
388     };
389 
390   if (Config.StripAllGNU)
391     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
392       if (RemovePred(Sec))
393         return true;
394       if ((Sec.Flags & SHF_ALLOC) != 0)
395         return false;
396       if (&Sec == Obj.SectionNames)
397         return false;
398       switch (Sec.Type) {
399       case SHT_SYMTAB:
400       case SHT_REL:
401       case SHT_RELA:
402       case SHT_STRTAB:
403         return true;
404       }
405       return isDebugSection(Sec);
406     };
407 
408   if (Config.StripSections) {
409     RemovePred = [RemovePred](const SectionBase &Sec) {
410       return RemovePred(Sec) || Sec.ParentSegment == nullptr;
411     };
412   }
413 
414   if (Config.StripDebug || Config.StripUnneeded) {
415     RemovePred = [RemovePred](const SectionBase &Sec) {
416       return RemovePred(Sec) || isDebugSection(Sec);
417     };
418   }
419 
420   if (Config.StripNonAlloc)
421     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
422       if (RemovePred(Sec))
423         return true;
424       if (&Sec == Obj.SectionNames)
425         return false;
426       return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
427     };
428 
429   if (Config.StripAll)
430     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
431       if (RemovePred(Sec))
432         return true;
433       if (&Sec == Obj.SectionNames)
434         return false;
435       if (StringRef(Sec.Name).startswith(".gnu.warning"))
436         return false;
437       // We keep the .ARM.attribute section to maintain compatibility
438       // with Debian derived distributions. This is a bug in their
439       // patchset as documented here:
440       // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=943798
441       if (Sec.Type == SHT_ARM_ATTRIBUTES)
442         return false;
443       if (Sec.ParentSegment != nullptr)
444         return false;
445       return (Sec.Flags & SHF_ALLOC) == 0;
446     };
447 
448   if (Config.ExtractPartition || Config.ExtractMainPartition) {
449     RemovePred = [RemovePred](const SectionBase &Sec) {
450       if (RemovePred(Sec))
451         return true;
452       if (Sec.Type == SHT_LLVM_PART_EHDR || Sec.Type == SHT_LLVM_PART_PHDR)
453         return true;
454       return (Sec.Flags & SHF_ALLOC) != 0 && !Sec.ParentSegment;
455     };
456   }
457 
458   // Explicit copies:
459   if (!Config.OnlySection.empty()) {
460     RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
461       // Explicitly keep these sections regardless of previous removes.
462       if (Config.OnlySection.matches(Sec.Name))
463         return false;
464 
465       // Allow all implicit removes.
466       if (RemovePred(Sec))
467         return true;
468 
469       // Keep special sections.
470       if (Obj.SectionNames == &Sec)
471         return false;
472       if (Obj.SymbolTable == &Sec ||
473           (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
474         return false;
475 
476       // Remove everything else.
477       return true;
478     };
479   }
480 
481   if (!Config.KeepSection.empty()) {
482     RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
483       // Explicitly keep these sections regardless of previous removes.
484       if (Config.KeepSection.matches(Sec.Name))
485         return false;
486       // Otherwise defer to RemovePred.
487       return RemovePred(Sec);
488     };
489   }
490 
491   // This has to be the last predicate assignment.
492   // If the option --keep-symbol has been specified
493   // and at least one of those symbols is present
494   // (equivalently, the updated symbol table is not empty)
495   // the symbol table and the string table should not be removed.
496   if ((!Config.SymbolsToKeep.empty() || ELFConfig.KeepFileSymbols) &&
497       Obj.SymbolTable && !Obj.SymbolTable->empty()) {
498     RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
499       if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
500         return false;
501       return RemovePred(Sec);
502     };
503   }
504 
505   if (Error E = Obj.removeSections(ELFConfig.AllowBrokenLinks, RemovePred))
506     return E;
507 
508   if (Config.CompressionType != DebugCompressionType::None) {
509     if (Error Err = replaceDebugSections(
510             Obj, isCompressable,
511             [&Config, &Obj](const SectionBase *S) -> Expected<SectionBase *> {
512               return &Obj.addSection<CompressedSection>(
513                   CompressedSection(*S, Config.CompressionType, Obj.Is64Bits));
514             }))
515       return Err;
516   } else if (Config.DecompressDebugSections) {
517     if (Error Err = replaceDebugSections(
518             Obj,
519             [](const SectionBase &S) { return isa<CompressedSection>(&S); },
520             [&Obj](const SectionBase *S) {
521               const CompressedSection *CS = cast<CompressedSection>(S);
522               return &Obj.addSection<DecompressedSection>(*CS);
523             }))
524       return Err;
525   }
526 
527   return Error::success();
528 }
529 
530 // Add symbol to the Object symbol table with the specified properties.
531 static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo,
532                       uint8_t DefaultVisibility) {
533   SectionBase *Sec = Obj.findSection(SymInfo.SectionName);
534   uint64_t Value = Sec ? Sec->Addr + SymInfo.Value : SymInfo.Value;
535 
536   uint8_t Bind = ELF::STB_GLOBAL;
537   uint8_t Type = ELF::STT_NOTYPE;
538   uint8_t Visibility = DefaultVisibility;
539 
540   for (SymbolFlag FlagValue : SymInfo.Flags)
541     switch (FlagValue) {
542     case SymbolFlag::Global:
543       Bind = ELF::STB_GLOBAL;
544       break;
545     case SymbolFlag::Local:
546       Bind = ELF::STB_LOCAL;
547       break;
548     case SymbolFlag::Weak:
549       Bind = ELF::STB_WEAK;
550       break;
551     case SymbolFlag::Default:
552       Visibility = ELF::STV_DEFAULT;
553       break;
554     case SymbolFlag::Hidden:
555       Visibility = ELF::STV_HIDDEN;
556       break;
557     case SymbolFlag::Protected:
558       Visibility = ELF::STV_PROTECTED;
559       break;
560     case SymbolFlag::File:
561       Type = ELF::STT_FILE;
562       break;
563     case SymbolFlag::Section:
564       Type = ELF::STT_SECTION;
565       break;
566     case SymbolFlag::Object:
567       Type = ELF::STT_OBJECT;
568       break;
569     case SymbolFlag::Function:
570       Type = ELF::STT_FUNC;
571       break;
572     case SymbolFlag::IndirectFunction:
573       Type = ELF::STT_GNU_IFUNC;
574       break;
575     default: /* Other flag values are ignored for ELF. */
576       break;
577     };
578 
579   Obj.SymbolTable->addSymbol(
580       SymInfo.SymbolName, Bind, Type, Sec, Value, Visibility,
581       Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
582 }
583 
584 static Error
585 handleUserSection(const NewSectionInfo &NewSection,
586                   function_ref<Error(StringRef, ArrayRef<uint8_t>)> F) {
587   ArrayRef<uint8_t> Data(reinterpret_cast<const uint8_t *>(
588                              NewSection.SectionData->getBufferStart()),
589                          NewSection.SectionData->getBufferSize());
590   return F(NewSection.SectionName, Data);
591 }
592 
593 // This function handles the high level operations of GNU objcopy including
594 // handling command line options. It's important to outline certain properties
595 // we expect to hold of the command line operations. Any operation that "keeps"
596 // should keep regardless of a remove. Additionally any removal should respect
597 // any previous removals. Lastly whether or not something is removed shouldn't
598 // depend a) on the order the options occur in or b) on some opaque priority
599 // system. The only priority is that keeps/copies overrule removes.
600 static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig,
601                         Object &Obj) {
602   if (Config.OutputArch) {
603     Obj.Machine = Config.OutputArch->EMachine;
604     Obj.OSABI = Config.OutputArch->OSABI;
605   }
606 
607   if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
608     return Obj.removeSections(
609         ELFConfig.AllowBrokenLinks,
610         [&Obj](const SectionBase &Sec) { return onlyKeepDWOPred(Obj, Sec); });
611   }
612 
613   // Dump sections before add/remove for compatibility with GNU objcopy.
614   for (StringRef Flag : Config.DumpSection) {
615     StringRef SectionName;
616     StringRef FileName;
617     std::tie(SectionName, FileName) = Flag.split('=');
618     if (Error E = dumpSectionToFile(SectionName, FileName, Obj))
619       return E;
620   }
621 
622   // It is important to remove the sections first. For example, we want to
623   // remove the relocation sections before removing the symbols. That allows
624   // us to avoid reporting the inappropriate errors about removing symbols
625   // named in relocations.
626   if (Error E = replaceAndRemoveSections(Config, ELFConfig, Obj))
627     return E;
628 
629   if (Error E = updateAndRemoveSymbols(Config, ELFConfig, Obj))
630     return E;
631 
632   if (!Config.SetSectionAlignment.empty()) {
633     for (SectionBase &Sec : Obj.sections()) {
634       auto I = Config.SetSectionAlignment.find(Sec.Name);
635       if (I != Config.SetSectionAlignment.end())
636         Sec.Align = I->second;
637     }
638   }
639 
640   if (Config.OnlyKeepDebug)
641     for (auto &Sec : Obj.sections())
642       if (Sec.Flags & SHF_ALLOC && Sec.Type != SHT_NOTE)
643         Sec.Type = SHT_NOBITS;
644 
645   for (const NewSectionInfo &AddedSection : Config.AddSection) {
646     auto AddSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
647       OwnedDataSection &NewSection =
648           Obj.addSection<OwnedDataSection>(Name, Data);
649       if (Name.startswith(".note") && Name != ".note.GNU-stack")
650         NewSection.Type = SHT_NOTE;
651       return Error::success();
652     };
653     if (Error E = handleUserSection(AddedSection, AddSection))
654       return E;
655   }
656 
657   for (const NewSectionInfo &NewSection : Config.UpdateSection) {
658     auto UpdateSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
659       return Obj.updateSection(Name, Data);
660     };
661     if (Error E = handleUserSection(NewSection, UpdateSection))
662       return E;
663   }
664 
665   if (!Config.AddGnuDebugLink.empty())
666     Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink,
667                                         Config.GnuDebugLinkCRC32);
668 
669   // If the symbol table was previously removed, we need to create a new one
670   // before adding new symbols.
671   if (!Obj.SymbolTable && !Config.SymbolsToAdd.empty())
672     if (Error E = Obj.addNewSymbolTable())
673       return E;
674 
675   for (const NewSymbolInfo &SI : Config.SymbolsToAdd)
676     addSymbol(Obj, SI, ELFConfig.NewSymbolVisibility);
677 
678   // --set-section-{flags,type} work with sections added by --add-section.
679   if (!Config.SetSectionFlags.empty() || !Config.SetSectionType.empty()) {
680     for (auto &Sec : Obj.sections()) {
681       const auto Iter = Config.SetSectionFlags.find(Sec.Name);
682       if (Iter != Config.SetSectionFlags.end()) {
683         const SectionFlagsUpdate &SFU = Iter->second;
684         setSectionFlagsAndType(Sec, SFU.NewFlags);
685       }
686       auto It2 = Config.SetSectionType.find(Sec.Name);
687       if (It2 != Config.SetSectionType.end())
688         setSectionType(Sec, It2->second);
689     }
690   }
691 
692   if (!Config.SectionsToRename.empty()) {
693     std::vector<RelocationSectionBase *> RelocSections;
694     DenseSet<SectionBase *> RenamedSections;
695     for (SectionBase &Sec : Obj.sections()) {
696       auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec);
697       const auto Iter = Config.SectionsToRename.find(Sec.Name);
698       if (Iter != Config.SectionsToRename.end()) {
699         const SectionRename &SR = Iter->second;
700         Sec.Name = std::string(SR.NewName);
701         if (SR.NewFlags)
702           setSectionFlagsAndType(Sec, *SR.NewFlags);
703         RenamedSections.insert(&Sec);
704       } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
705         // Postpone processing relocation sections which are not specified in
706         // their explicit '--rename-section' commands until after their target
707         // sections are renamed.
708         // Dynamic relocation sections (i.e. ones with SHF_ALLOC) should be
709         // renamed only explicitly. Otherwise, renaming, for example, '.got.plt'
710         // would affect '.rela.plt', which is not desirable.
711         RelocSections.push_back(RelocSec);
712     }
713 
714     // Rename relocation sections according to their target sections.
715     for (RelocationSectionBase *RelocSec : RelocSections) {
716       auto Iter = RenamedSections.find(RelocSec->getSection());
717       if (Iter != RenamedSections.end())
718         RelocSec->Name = (RelocSec->getNamePrefix() + (*Iter)->Name).str();
719     }
720   }
721 
722   // Add a prefix to allocated sections and their relocation sections. This
723   // should be done after renaming the section by Config.SectionToRename to
724   // imitate the GNU objcopy behavior.
725   if (!Config.AllocSectionsPrefix.empty()) {
726     DenseSet<SectionBase *> PrefixedSections;
727     for (SectionBase &Sec : Obj.sections()) {
728       if (Sec.Flags & SHF_ALLOC) {
729         Sec.Name = (Config.AllocSectionsPrefix + Sec.Name).str();
730         PrefixedSections.insert(&Sec);
731       } else if (auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec)) {
732         // Rename relocation sections associated to the allocated sections.
733         // For example, if we rename .text to .prefix.text, we also rename
734         // .rel.text to .rel.prefix.text.
735         //
736         // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
737         // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
738         // .rela.prefix.plt since GNU objcopy does so.
739         const SectionBase *TargetSec = RelocSec->getSection();
740         if (TargetSec && (TargetSec->Flags & SHF_ALLOC)) {
741           // If the relocation section comes *after* the target section, we
742           // don't add Config.AllocSectionsPrefix because we've already added
743           // the prefix to TargetSec->Name. Otherwise, if the relocation
744           // section comes *before* the target section, we add the prefix.
745           if (PrefixedSections.count(TargetSec))
746             Sec.Name = (RelocSec->getNamePrefix() + TargetSec->Name).str();
747           else
748             Sec.Name = (RelocSec->getNamePrefix() + Config.AllocSectionsPrefix +
749                         TargetSec->Name)
750                            .str();
751         }
752       }
753     }
754   }
755 
756   if (ELFConfig.EntryExpr)
757     Obj.Entry = ELFConfig.EntryExpr(Obj.Entry);
758   return Error::success();
759 }
760 
761 static Error writeOutput(const CommonConfig &Config, Object &Obj,
762                          raw_ostream &Out, ElfType OutputElfType) {
763   std::unique_ptr<Writer> Writer =
764       createWriter(Config, Obj, Out, OutputElfType);
765   if (Error E = Writer->finalize())
766     return E;
767   return Writer->write();
768 }
769 
770 Error objcopy::elf::executeObjcopyOnIHex(const CommonConfig &Config,
771                                          const ELFConfig &ELFConfig,
772                                          MemoryBuffer &In, raw_ostream &Out) {
773   IHexReader Reader(&In);
774   Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
775   if (!Obj)
776     return Obj.takeError();
777 
778   const ElfType OutputElfType =
779       getOutputElfType(Config.OutputArch.value_or(MachineInfo()));
780   if (Error E = handleArgs(Config, ELFConfig, **Obj))
781     return E;
782   return writeOutput(Config, **Obj, Out, OutputElfType);
783 }
784 
785 Error objcopy::elf::executeObjcopyOnRawBinary(const CommonConfig &Config,
786                                               const ELFConfig &ELFConfig,
787                                               MemoryBuffer &In,
788                                               raw_ostream &Out) {
789   BinaryReader Reader(&In, ELFConfig.NewSymbolVisibility);
790   Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
791   if (!Obj)
792     return Obj.takeError();
793 
794   // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
795   // (-B<arch>).
796   const ElfType OutputElfType =
797       getOutputElfType(Config.OutputArch.value_or(MachineInfo()));
798   if (Error E = handleArgs(Config, ELFConfig, **Obj))
799     return E;
800   return writeOutput(Config, **Obj, Out, OutputElfType);
801 }
802 
803 Error objcopy::elf::executeObjcopyOnBinary(const CommonConfig &Config,
804                                            const ELFConfig &ELFConfig,
805                                            object::ELFObjectFileBase &In,
806                                            raw_ostream &Out) {
807   ELFReader Reader(&In, Config.ExtractPartition);
808   Expected<std::unique_ptr<Object>> Obj =
809       Reader.create(!Config.SymbolsToAdd.empty());
810   if (!Obj)
811     return Obj.takeError();
812   // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
813   const ElfType OutputElfType = Config.OutputArch
814                                     ? getOutputElfType(*Config.OutputArch)
815                                     : getOutputElfType(In);
816 
817   if (Error E = handleArgs(Config, ELFConfig, **Obj))
818     return createFileError(Config.InputFilename, std::move(E));
819 
820   if (Error E = writeOutput(Config, **Obj, Out, OutputElfType))
821     return createFileError(Config.InputFilename, std::move(E));
822 
823   return Error::success();
824 }
825