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 "Object.h"
11 #include "llvm/ADT/BitmaskEnum.h"
12 #include "llvm/ADT/DenseSet.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/BinaryFormat/ELF.h"
19 #include "llvm/MC/MCTargetOptions.h"
20 #include "llvm/ObjCopy/CommonConfig.h"
21 #include "llvm/ObjCopy/ELF/ELFConfig.h"
22 #include "llvm/Object/Binary.h"
23 #include "llvm/Object/ELFObjectFile.h"
24 #include "llvm/Object/ELFTypes.h"
25 #include "llvm/Object/Error.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Compression.h"
29 #include "llvm/Support/Errc.h"
30 #include "llvm/Support/Error.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ErrorOr.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Memory.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstdlib>
40 #include <functional>
41 #include <iterator>
42 #include <memory>
43 #include <string>
44 #include <system_error>
45 #include <utility>
46 
47 using namespace llvm;
48 using namespace llvm::ELF;
49 using namespace llvm::objcopy;
50 using namespace llvm::objcopy::elf;
51 using namespace llvm::object;
52 
53 using SectionPred = std::function<bool(const SectionBase &Sec)>;
54 
55 static bool isDebugSection(const SectionBase &Sec) {
56   return StringRef(Sec.Name).startswith(".debug") ||
57          StringRef(Sec.Name).startswith(".zdebug") || Sec.Name == ".gdb_index";
58 }
59 
60 static bool isDWOSection(const SectionBase &Sec) {
61   return StringRef(Sec.Name).endswith(".dwo");
62 }
63 
64 static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
65   // We can't remove the section header string table.
66   if (&Sec == Obj.SectionNames)
67     return false;
68   // Short of keeping the string table we want to keep everything that is a DWO
69   // section and remove everything else.
70   return !isDWOSection(Sec);
71 }
72 
73 static uint64_t getNewShfFlags(SectionFlag AllFlags) {
74   uint64_t NewFlags = 0;
75   if (AllFlags & SectionFlag::SecAlloc)
76     NewFlags |= ELF::SHF_ALLOC;
77   if (!(AllFlags & SectionFlag::SecReadonly))
78     NewFlags |= ELF::SHF_WRITE;
79   if (AllFlags & SectionFlag::SecCode)
80     NewFlags |= ELF::SHF_EXECINSTR;
81   if (AllFlags & SectionFlag::SecMerge)
82     NewFlags |= ELF::SHF_MERGE;
83   if (AllFlags & SectionFlag::SecStrings)
84     NewFlags |= ELF::SHF_STRINGS;
85   if (AllFlags & SectionFlag::SecExclude)
86     NewFlags |= ELF::SHF_EXCLUDE;
87   return NewFlags;
88 }
89 
90 static uint64_t getSectionFlagsPreserveMask(uint64_t OldFlags,
91                                             uint64_t NewFlags) {
92   // Preserve some flags which should not be dropped when setting flags.
93   // Also, preserve anything OS/processor dependant.
94   const uint64_t PreserveMask =
95       (ELF::SHF_COMPRESSED | ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
96        ELF::SHF_MASKOS | ELF::SHF_MASKPROC | ELF::SHF_TLS |
97        ELF::SHF_INFO_LINK) &
98       ~ELF::SHF_EXCLUDE;
99   return (OldFlags & PreserveMask) | (NewFlags & ~PreserveMask);
100 }
101 
102 static void setSectionFlagsAndType(SectionBase &Sec, SectionFlag Flags) {
103   Sec.Flags = getSectionFlagsPreserveMask(Sec.Flags, getNewShfFlags(Flags));
104 
105   // In GNU objcopy, certain flags promote SHT_NOBITS to SHT_PROGBITS. This rule
106   // may promote more non-ALLOC sections than GNU objcopy, but it is fine as
107   // non-ALLOC SHT_NOBITS sections do not make much sense.
108   if (Sec.Type == SHT_NOBITS &&
109       (!(Sec.Flags & ELF::SHF_ALLOC) ||
110        Flags & (SectionFlag::SecContents | SectionFlag::SecLoad)))
111     Sec.Type = SHT_PROGBITS;
112 }
113 
114 static ElfType getOutputElfType(const Binary &Bin) {
115   // Infer output ELF type from the input ELF object
116   if (isa<ELFObjectFile<ELF32LE>>(Bin))
117     return ELFT_ELF32LE;
118   if (isa<ELFObjectFile<ELF64LE>>(Bin))
119     return ELFT_ELF64LE;
120   if (isa<ELFObjectFile<ELF32BE>>(Bin))
121     return ELFT_ELF32BE;
122   if (isa<ELFObjectFile<ELF64BE>>(Bin))
123     return ELFT_ELF64BE;
124   llvm_unreachable("Invalid ELFType");
125 }
126 
127 static ElfType getOutputElfType(const MachineInfo &MI) {
128   // Infer output ELF type from the binary arch specified
129   if (MI.Is64Bit)
130     return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
131   else
132     return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
133 }
134 
135 static std::unique_ptr<Writer> createELFWriter(const CommonConfig &Config,
136                                                Object &Obj, raw_ostream &Out,
137                                                ElfType OutputElfType) {
138   // Depending on the initial ELFT and OutputFormat we need a different Writer.
139   switch (OutputElfType) {
140   case ELFT_ELF32LE:
141     return std::make_unique<ELFWriter<ELF32LE>>(Obj, Out, !Config.StripSections,
142                                                 Config.OnlyKeepDebug);
143   case ELFT_ELF64LE:
144     return std::make_unique<ELFWriter<ELF64LE>>(Obj, Out, !Config.StripSections,
145                                                 Config.OnlyKeepDebug);
146   case ELFT_ELF32BE:
147     return std::make_unique<ELFWriter<ELF32BE>>(Obj, Out, !Config.StripSections,
148                                                 Config.OnlyKeepDebug);
149   case ELFT_ELF64BE:
150     return std::make_unique<ELFWriter<ELF64BE>>(Obj, Out, !Config.StripSections,
151                                                 Config.OnlyKeepDebug);
152   }
153   llvm_unreachable("Invalid output format");
154 }
155 
156 static std::unique_ptr<Writer> createWriter(const CommonConfig &Config,
157                                             Object &Obj, raw_ostream &Out,
158                                             ElfType OutputElfType) {
159   switch (Config.OutputFormat) {
160   case FileFormat::Binary:
161     return std::make_unique<BinaryWriter>(Obj, Out);
162   case FileFormat::IHex:
163     return std::make_unique<IHexWriter>(Obj, Out);
164   default:
165     return createELFWriter(Config, Obj, Out, OutputElfType);
166   }
167 }
168 
169 template <class... Ts>
170 static Error makeStringError(std::error_code EC, const Twine &Msg,
171                              Ts &&...Args) {
172   std::string FullMsg = (EC.message() + ": " + Msg).str();
173   return createStringError(EC, FullMsg.c_str(), std::forward<Ts>(Args)...);
174 }
175 
176 static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
177                                Object &Obj) {
178   for (auto &Sec : Obj.sections()) {
179     if (Sec.Name == SecName) {
180       if (Sec.Type == SHT_NOBITS)
181         return createStringError(object_error::parse_failed,
182                                  "cannot dump section '%s': it has no contents",
183                                  SecName.str().c_str());
184       Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
185           FileOutputBuffer::create(Filename, Sec.OriginalData.size());
186       if (!BufferOrErr)
187         return BufferOrErr.takeError();
188       std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
189       std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
190                 Buf->getBufferStart());
191       if (Error E = Buf->commit())
192         return E;
193       return Error::success();
194     }
195   }
196   return createStringError(object_error::parse_failed, "section '%s' not found",
197                            SecName.str().c_str());
198 }
199 
200 static bool isCompressable(const SectionBase &Sec) {
201   return !(Sec.Flags & ELF::SHF_COMPRESSED) &&
202          StringRef(Sec.Name).startswith(".debug");
203 }
204 
205 static Error replaceDebugSections(
206     Object &Obj, function_ref<bool(const SectionBase &)> ShouldReplace,
207     function_ref<Expected<SectionBase *>(const SectionBase *)> AddSection) {
208   // Build a list of the debug sections we are going to replace.
209   // We can't call `AddSection` while iterating over sections,
210   // because it would mutate the sections array.
211   SmallVector<SectionBase *, 13> ToReplace;
212   for (auto &Sec : Obj.sections())
213     if (ShouldReplace(Sec))
214       ToReplace.push_back(&Sec);
215 
216   // Build a mapping from original section to a new one.
217   DenseMap<SectionBase *, SectionBase *> FromTo;
218   for (SectionBase *S : ToReplace) {
219     Expected<SectionBase *> NewSection = AddSection(S);
220     if (!NewSection)
221       return NewSection.takeError();
222 
223     FromTo[S] = *NewSection;
224   }
225 
226   return Obj.replaceSections(FromTo);
227 }
228 
229 static bool isAArch64MappingSymbol(const Symbol &Sym) {
230   if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
231       Sym.getShndx() == SHN_UNDEF)
232     return false;
233   StringRef Name = Sym.Name;
234   if (!Name.consume_front("$x") && !Name.consume_front("$d"))
235     return false;
236   return Name.empty() || Name.startswith(".");
237 }
238 
239 static bool isArmMappingSymbol(const Symbol &Sym) {
240   if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
241       Sym.getShndx() == SHN_UNDEF)
242     return false;
243   StringRef Name = Sym.Name;
244   if (!Name.consume_front("$a") && !Name.consume_front("$d") &&
245       !Name.consume_front("$t"))
246     return false;
247   return Name.empty() || Name.startswith(".");
248 }
249 
250 // Check if the symbol should be preserved because it is required by ABI.
251 static bool isRequiredByABISymbol(const Object &Obj, const Symbol &Sym) {
252   switch (Obj.Machine) {
253   case EM_AARCH64:
254     // Mapping symbols should be preserved for a relocatable object file.
255     return Obj.isRelocatable() && isAArch64MappingSymbol(Sym);
256   case EM_ARM:
257     // Mapping symbols should be preserved for a relocatable object file.
258     return Obj.isRelocatable() && isArmMappingSymbol(Sym);
259   default:
260     return false;
261   }
262 }
263 
264 static bool isUnneededSymbol(const Symbol &Sym) {
265   return !Sym.Referenced &&
266          (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
267          Sym.Type != STT_SECTION;
268 }
269 
270 static Error updateAndRemoveSymbols(const CommonConfig &Config,
271                                     const ELFConfig &ELFConfig, Object &Obj) {
272   // TODO: update or remove symbols only if there is an option that affects
273   // them.
274   if (!Obj.SymbolTable)
275     return Error::success();
276 
277   Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
278     // Common and undefined symbols don't make sense as local symbols, and can
279     // even cause crashes if we localize those, so skip them.
280     if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
281         ((ELFConfig.LocalizeHidden &&
282           (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
283          Config.SymbolsToLocalize.matches(Sym.Name)))
284       Sym.Binding = STB_LOCAL;
285 
286     // Note: these two globalize flags have very similar names but different
287     // meanings:
288     //
289     // --globalize-symbol: promote a symbol to global
290     // --keep-global-symbol: all symbols except for these should be made local
291     //
292     // If --globalize-symbol is specified for a given symbol, it will be
293     // global in the output file even if it is not included via
294     // --keep-global-symbol. Because of that, make sure to check
295     // --globalize-symbol second.
296     if (!Config.SymbolsToKeepGlobal.empty() &&
297         !Config.SymbolsToKeepGlobal.matches(Sym.Name) &&
298         Sym.getShndx() != SHN_UNDEF)
299       Sym.Binding = STB_LOCAL;
300 
301     if (Config.SymbolsToGlobalize.matches(Sym.Name) &&
302         Sym.getShndx() != SHN_UNDEF)
303       Sym.Binding = STB_GLOBAL;
304 
305     if (Config.SymbolsToWeaken.matches(Sym.Name) && Sym.Binding == STB_GLOBAL)
306       Sym.Binding = STB_WEAK;
307 
308     if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
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               Expected<CompressedSection> NewSection =
513                   CompressedSection::create(*S, Config.CompressionType);
514               if (!NewSection)
515                 return NewSection.takeError();
516 
517               return &Obj.addSection<CompressedSection>(std::move(*NewSection));
518             }))
519       return Err;
520   } else if (Config.DecompressDebugSections) {
521     if (Error Err = replaceDebugSections(
522             Obj,
523             [](const SectionBase &S) { return isa<CompressedSection>(&S); },
524             [&Obj](const SectionBase *S) {
525               const CompressedSection *CS = cast<CompressedSection>(S);
526               return &Obj.addSection<DecompressedSection>(*CS);
527             }))
528       return Err;
529   }
530 
531   return Error::success();
532 }
533 
534 // Add symbol to the Object symbol table with the specified properties.
535 static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo,
536                       uint8_t DefaultVisibility) {
537   SectionBase *Sec = Obj.findSection(SymInfo.SectionName);
538   uint64_t Value = Sec ? Sec->Addr + SymInfo.Value : SymInfo.Value;
539 
540   uint8_t Bind = ELF::STB_GLOBAL;
541   uint8_t Type = ELF::STT_NOTYPE;
542   uint8_t Visibility = DefaultVisibility;
543 
544   for (SymbolFlag FlagValue : SymInfo.Flags)
545     switch (FlagValue) {
546     case SymbolFlag::Global:
547       Bind = ELF::STB_GLOBAL;
548       break;
549     case SymbolFlag::Local:
550       Bind = ELF::STB_LOCAL;
551       break;
552     case SymbolFlag::Weak:
553       Bind = ELF::STB_WEAK;
554       break;
555     case SymbolFlag::Default:
556       Visibility = ELF::STV_DEFAULT;
557       break;
558     case SymbolFlag::Hidden:
559       Visibility = ELF::STV_HIDDEN;
560       break;
561     case SymbolFlag::Protected:
562       Visibility = ELF::STV_PROTECTED;
563       break;
564     case SymbolFlag::File:
565       Type = ELF::STT_FILE;
566       break;
567     case SymbolFlag::Section:
568       Type = ELF::STT_SECTION;
569       break;
570     case SymbolFlag::Object:
571       Type = ELF::STT_OBJECT;
572       break;
573     case SymbolFlag::Function:
574       Type = ELF::STT_FUNC;
575       break;
576     case SymbolFlag::IndirectFunction:
577       Type = ELF::STT_GNU_IFUNC;
578       break;
579     default: /* Other flag values are ignored for ELF. */
580       break;
581     };
582 
583   Obj.SymbolTable->addSymbol(
584       SymInfo.SymbolName, Bind, Type, Sec, Value, Visibility,
585       Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
586 }
587 
588 static Error
589 handleUserSection(StringRef Flag,
590                   function_ref<Error(StringRef, ArrayRef<uint8_t>)> F) {
591   std::pair<StringRef, StringRef> SecPair = Flag.split("=");
592   StringRef SecName = SecPair.first;
593   StringRef File = SecPair.second;
594   ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(File);
595   if (!BufOrErr)
596     return createFileError(File, errorCodeToError(BufOrErr.getError()));
597   std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
598   ArrayRef<uint8_t> Data(
599       reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
600       Buf->getBufferSize());
601   return F(SecName, Data);
602 }
603 
604 // This function handles the high level operations of GNU objcopy including
605 // handling command line options. It's important to outline certain properties
606 // we expect to hold of the command line operations. Any operation that "keeps"
607 // should keep regardless of a remove. Additionally any removal should respect
608 // any previous removals. Lastly whether or not something is removed shouldn't
609 // depend a) on the order the options occur in or b) on some opaque priority
610 // system. The only priority is that keeps/copies overrule removes.
611 static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig,
612                         Object &Obj) {
613   if (Config.OutputArch) {
614     Obj.Machine = Config.OutputArch.getValue().EMachine;
615     Obj.OSABI = Config.OutputArch.getValue().OSABI;
616   }
617 
618   if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
619     return Obj.removeSections(
620         ELFConfig.AllowBrokenLinks,
621         [&Obj](const SectionBase &Sec) { return onlyKeepDWOPred(Obj, Sec); });
622   }
623 
624   // Dump sections before add/remove for compatibility with GNU objcopy.
625   for (StringRef Flag : Config.DumpSection) {
626     StringRef SectionName;
627     StringRef FileName;
628     std::tie(SectionName, FileName) = Flag.split('=');
629     if (Error E = dumpSectionToFile(SectionName, FileName, Obj))
630       return E;
631   }
632 
633   // It is important to remove the sections first. For example, we want to
634   // remove the relocation sections before removing the symbols. That allows
635   // us to avoid reporting the inappropriate errors about removing symbols
636   // named in relocations.
637   if (Error E = replaceAndRemoveSections(Config, ELFConfig, Obj))
638     return E;
639 
640   if (Error E = updateAndRemoveSymbols(Config, ELFConfig, Obj))
641     return E;
642 
643   if (!Config.SectionsToRename.empty()) {
644     std::vector<RelocationSectionBase *> RelocSections;
645     DenseSet<SectionBase *> RenamedSections;
646     for (SectionBase &Sec : Obj.sections()) {
647       auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec);
648       const auto Iter = Config.SectionsToRename.find(Sec.Name);
649       if (Iter != Config.SectionsToRename.end()) {
650         const SectionRename &SR = Iter->second;
651         Sec.Name = std::string(SR.NewName);
652         if (SR.NewFlags.hasValue())
653           setSectionFlagsAndType(Sec, SR.NewFlags.getValue());
654         RenamedSections.insert(&Sec);
655       } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
656         // Postpone processing relocation sections which are not specified in
657         // their explicit '--rename-section' commands until after their target
658         // sections are renamed.
659         // Dynamic relocation sections (i.e. ones with SHF_ALLOC) should be
660         // renamed only explicitly. Otherwise, renaming, for example, '.got.plt'
661         // would affect '.rela.plt', which is not desirable.
662         RelocSections.push_back(RelocSec);
663     }
664 
665     // Rename relocation sections according to their target sections.
666     for (RelocationSectionBase *RelocSec : RelocSections) {
667       auto Iter = RenamedSections.find(RelocSec->getSection());
668       if (Iter != RenamedSections.end())
669         RelocSec->Name = (RelocSec->getNamePrefix() + (*Iter)->Name).str();
670     }
671   }
672 
673   // Add a prefix to allocated sections and their relocation sections. This
674   // should be done after renaming the section by Config.SectionToRename to
675   // imitate the GNU objcopy behavior.
676   if (!Config.AllocSectionsPrefix.empty()) {
677     DenseSet<SectionBase *> PrefixedSections;
678     for (SectionBase &Sec : Obj.sections()) {
679       if (Sec.Flags & SHF_ALLOC) {
680         Sec.Name = (Config.AllocSectionsPrefix + Sec.Name).str();
681         PrefixedSections.insert(&Sec);
682       } else if (auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec)) {
683         // Rename relocation sections associated to the allocated sections.
684         // For example, if we rename .text to .prefix.text, we also rename
685         // .rel.text to .rel.prefix.text.
686         //
687         // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
688         // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
689         // .rela.prefix.plt since GNU objcopy does so.
690         const SectionBase *TargetSec = RelocSec->getSection();
691         if (TargetSec && (TargetSec->Flags & SHF_ALLOC)) {
692           // If the relocation section comes *after* the target section, we
693           // don't add Config.AllocSectionsPrefix because we've already added
694           // the prefix to TargetSec->Name. Otherwise, if the relocation
695           // section comes *before* the target section, we add the prefix.
696           if (PrefixedSections.count(TargetSec))
697             Sec.Name = (RelocSec->getNamePrefix() + TargetSec->Name).str();
698           else
699             Sec.Name = (RelocSec->getNamePrefix() + Config.AllocSectionsPrefix +
700                         TargetSec->Name)
701                            .str();
702         }
703       }
704     }
705   }
706 
707   if (!Config.SetSectionAlignment.empty()) {
708     for (SectionBase &Sec : Obj.sections()) {
709       auto I = Config.SetSectionAlignment.find(Sec.Name);
710       if (I != Config.SetSectionAlignment.end())
711         Sec.Align = I->second;
712     }
713   }
714 
715   if (Config.OnlyKeepDebug)
716     for (auto &Sec : Obj.sections())
717       if (Sec.Flags & SHF_ALLOC && Sec.Type != SHT_NOTE)
718         Sec.Type = SHT_NOBITS;
719 
720   for (const auto &Flag : Config.AddSection) {
721     auto AddSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
722       OwnedDataSection &NewSection =
723           Obj.addSection<OwnedDataSection>(Name, Data);
724       if (Name.startswith(".note") && Name != ".note.GNU-stack")
725         NewSection.Type = SHT_NOTE;
726       return Error::success();
727     };
728     if (Error E = handleUserSection(Flag, AddSection))
729       return E;
730   }
731 
732   for (StringRef Flag : Config.UpdateSection) {
733     auto UpdateSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
734       return Obj.updateSection(Name, Data);
735     };
736     if (Error E = handleUserSection(Flag, UpdateSection))
737       return E;
738   }
739 
740   if (!Config.AddGnuDebugLink.empty())
741     Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink,
742                                         Config.GnuDebugLinkCRC32);
743 
744   // If the symbol table was previously removed, we need to create a new one
745   // before adding new symbols.
746   if (!Obj.SymbolTable && !Config.SymbolsToAdd.empty())
747     if (Error E = Obj.addNewSymbolTable())
748       return E;
749 
750   for (const NewSymbolInfo &SI : Config.SymbolsToAdd)
751     addSymbol(Obj, SI, ELFConfig.NewSymbolVisibility);
752 
753   // --set-section-flags works with sections added by --add-section.
754   if (!Config.SetSectionFlags.empty()) {
755     for (auto &Sec : Obj.sections()) {
756       const auto Iter = Config.SetSectionFlags.find(Sec.Name);
757       if (Iter != Config.SetSectionFlags.end()) {
758         const SectionFlagsUpdate &SFU = Iter->second;
759         setSectionFlagsAndType(Sec, SFU.NewFlags);
760       }
761     }
762   }
763 
764   if (ELFConfig.EntryExpr)
765     Obj.Entry = ELFConfig.EntryExpr(Obj.Entry);
766   return Error::success();
767 }
768 
769 static Error writeOutput(const CommonConfig &Config, Object &Obj,
770                          raw_ostream &Out, ElfType OutputElfType) {
771   std::unique_ptr<Writer> Writer =
772       createWriter(Config, Obj, Out, OutputElfType);
773   if (Error E = Writer->finalize())
774     return E;
775   return Writer->write();
776 }
777 
778 Error objcopy::elf::executeObjcopyOnIHex(const CommonConfig &Config,
779                                          const ELFConfig &ELFConfig,
780                                          MemoryBuffer &In, raw_ostream &Out) {
781   IHexReader Reader(&In);
782   Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
783   if (!Obj)
784     return Obj.takeError();
785 
786   const ElfType OutputElfType =
787       getOutputElfType(Config.OutputArch.getValueOr(MachineInfo()));
788   if (Error E = handleArgs(Config, ELFConfig, **Obj))
789     return E;
790   return writeOutput(Config, **Obj, Out, OutputElfType);
791 }
792 
793 Error objcopy::elf::executeObjcopyOnRawBinary(const CommonConfig &Config,
794                                               const ELFConfig &ELFConfig,
795                                               MemoryBuffer &In,
796                                               raw_ostream &Out) {
797   BinaryReader Reader(&In, ELFConfig.NewSymbolVisibility);
798   Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
799   if (!Obj)
800     return Obj.takeError();
801 
802   // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
803   // (-B<arch>).
804   const ElfType OutputElfType =
805       getOutputElfType(Config.OutputArch.getValueOr(MachineInfo()));
806   if (Error E = handleArgs(Config, ELFConfig, **Obj))
807     return E;
808   return writeOutput(Config, **Obj, Out, OutputElfType);
809 }
810 
811 Error objcopy::elf::executeObjcopyOnBinary(const CommonConfig &Config,
812                                            const ELFConfig &ELFConfig,
813                                            object::ELFObjectFileBase &In,
814                                            raw_ostream &Out) {
815   ELFReader Reader(&In, Config.ExtractPartition);
816   Expected<std::unique_ptr<Object>> Obj =
817       Reader.create(!Config.SymbolsToAdd.empty());
818   if (!Obj)
819     return Obj.takeError();
820   // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
821   const ElfType OutputElfType =
822       Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
823                         : getOutputElfType(In);
824 
825   if (Error E = handleArgs(Config, ELFConfig, **Obj))
826     return createFileError(Config.InputFilename, std::move(E));
827 
828   if (Error E = writeOutput(Config, **Obj, Out, OutputElfType))
829     return createFileError(Config.InputFilename, std::move(E));
830 
831   return Error::success();
832 }
833