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/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     // SymbolsToWeaken applies to both STB_GLOBAL and STB_GNU_UNIQUE.
306     if (Config.SymbolsToWeaken.matches(Sym.Name) && Sym.Binding != STB_LOCAL)
307       Sym.Binding = STB_WEAK;
308 
309     if (Config.Weaken && Sym.Binding != STB_LOCAL &&
310         Sym.getShndx() != SHN_UNDEF)
311       Sym.Binding = STB_WEAK;
312 
313     const auto I = Config.SymbolsToRename.find(Sym.Name);
314     if (I != Config.SymbolsToRename.end())
315       Sym.Name = std::string(I->getValue());
316 
317     if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
318       Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
319   });
320 
321   // The purpose of this loop is to mark symbols referenced by sections
322   // (like GroupSection or RelocationSection). This way, we know which
323   // symbols are still 'needed' and which are not.
324   if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty() ||
325       !Config.OnlySection.empty()) {
326     for (SectionBase &Sec : Obj.sections())
327       Sec.markSymbols();
328   }
329 
330   auto RemoveSymbolsPred = [&](const Symbol &Sym) {
331     if (Config.SymbolsToKeep.matches(Sym.Name) ||
332         (ELFConfig.KeepFileSymbols && Sym.Type == STT_FILE))
333       return false;
334 
335     if (Config.SymbolsToRemove.matches(Sym.Name))
336       return true;
337 
338     if (Config.StripAll || Config.StripAllGNU)
339       return true;
340 
341     if (isRequiredByABISymbol(Obj, Sym))
342       return false;
343 
344     if (Config.StripDebug && Sym.Type == STT_FILE)
345       return true;
346 
347     if ((Config.DiscardMode == DiscardType::All ||
348          (Config.DiscardMode == DiscardType::Locals &&
349           StringRef(Sym.Name).startswith(".L"))) &&
350         Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
351         Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
352       return true;
353 
354     if ((Config.StripUnneeded ||
355          Config.UnneededSymbolsToRemove.matches(Sym.Name)) &&
356         (!Obj.isRelocatable() || isUnneededSymbol(Sym)))
357       return true;
358 
359     // We want to remove undefined symbols if all references have been stripped.
360     if (!Config.OnlySection.empty() && !Sym.Referenced &&
361         Sym.getShndx() == SHN_UNDEF)
362       return true;
363 
364     return false;
365   };
366 
367   return Obj.removeSymbols(RemoveSymbolsPred);
368 }
369 
370 static Error replaceAndRemoveSections(const CommonConfig &Config,
371                                       const ELFConfig &ELFConfig, Object &Obj) {
372   SectionPred RemovePred = [](const SectionBase &) { return false; };
373 
374   // Removes:
375   if (!Config.ToRemove.empty()) {
376     RemovePred = [&Config](const SectionBase &Sec) {
377       return Config.ToRemove.matches(Sec.Name);
378     };
379   }
380 
381   if (Config.StripDWO)
382     RemovePred = [RemovePred](const SectionBase &Sec) {
383       return isDWOSection(Sec) || RemovePred(Sec);
384     };
385 
386   if (Config.ExtractDWO)
387     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
388       return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
389     };
390 
391   if (Config.StripAllGNU)
392     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
393       if (RemovePred(Sec))
394         return true;
395       if ((Sec.Flags & SHF_ALLOC) != 0)
396         return false;
397       if (&Sec == Obj.SectionNames)
398         return false;
399       switch (Sec.Type) {
400       case SHT_SYMTAB:
401       case SHT_REL:
402       case SHT_RELA:
403       case SHT_STRTAB:
404         return true;
405       }
406       return isDebugSection(Sec);
407     };
408 
409   if (Config.StripSections) {
410     RemovePred = [RemovePred](const SectionBase &Sec) {
411       return RemovePred(Sec) || Sec.ParentSegment == nullptr;
412     };
413   }
414 
415   if (Config.StripDebug || Config.StripUnneeded) {
416     RemovePred = [RemovePred](const SectionBase &Sec) {
417       return RemovePred(Sec) || isDebugSection(Sec);
418     };
419   }
420 
421   if (Config.StripNonAlloc)
422     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
423       if (RemovePred(Sec))
424         return true;
425       if (&Sec == Obj.SectionNames)
426         return false;
427       return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
428     };
429 
430   if (Config.StripAll)
431     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
432       if (RemovePred(Sec))
433         return true;
434       if (&Sec == Obj.SectionNames)
435         return false;
436       if (StringRef(Sec.Name).startswith(".gnu.warning"))
437         return false;
438       // We keep the .ARM.attribute section to maintain compatibility
439       // with Debian derived distributions. This is a bug in their
440       // patchset as documented here:
441       // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=943798
442       if (Sec.Type == SHT_ARM_ATTRIBUTES)
443         return false;
444       if (Sec.ParentSegment != nullptr)
445         return false;
446       return (Sec.Flags & SHF_ALLOC) == 0;
447     };
448 
449   if (Config.ExtractPartition || Config.ExtractMainPartition) {
450     RemovePred = [RemovePred](const SectionBase &Sec) {
451       if (RemovePred(Sec))
452         return true;
453       if (Sec.Type == SHT_LLVM_PART_EHDR || Sec.Type == SHT_LLVM_PART_PHDR)
454         return true;
455       return (Sec.Flags & SHF_ALLOC) != 0 && !Sec.ParentSegment;
456     };
457   }
458 
459   // Explicit copies:
460   if (!Config.OnlySection.empty()) {
461     RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
462       // Explicitly keep these sections regardless of previous removes.
463       if (Config.OnlySection.matches(Sec.Name))
464         return false;
465 
466       // Allow all implicit removes.
467       if (RemovePred(Sec))
468         return true;
469 
470       // Keep special sections.
471       if (Obj.SectionNames == &Sec)
472         return false;
473       if (Obj.SymbolTable == &Sec ||
474           (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
475         return false;
476 
477       // Remove everything else.
478       return true;
479     };
480   }
481 
482   if (!Config.KeepSection.empty()) {
483     RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
484       // Explicitly keep these sections regardless of previous removes.
485       if (Config.KeepSection.matches(Sec.Name))
486         return false;
487       // Otherwise defer to RemovePred.
488       return RemovePred(Sec);
489     };
490   }
491 
492   // This has to be the last predicate assignment.
493   // If the option --keep-symbol has been specified
494   // and at least one of those symbols is present
495   // (equivalently, the updated symbol table is not empty)
496   // the symbol table and the string table should not be removed.
497   if ((!Config.SymbolsToKeep.empty() || ELFConfig.KeepFileSymbols) &&
498       Obj.SymbolTable && !Obj.SymbolTable->empty()) {
499     RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
500       if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
501         return false;
502       return RemovePred(Sec);
503     };
504   }
505 
506   if (Error E = Obj.removeSections(ELFConfig.AllowBrokenLinks, RemovePred))
507     return E;
508 
509   if (Config.CompressionType != DebugCompressionType::None) {
510     if (Error Err = replaceDebugSections(
511             Obj, isCompressable,
512             [&Config, &Obj](const SectionBase *S) -> Expected<SectionBase *> {
513               return &Obj.addSection<CompressedSection>(
514                   CompressedSection(*S, Config.CompressionType));
515             }))
516       return Err;
517   } else if (Config.DecompressDebugSections) {
518     if (Error Err = replaceDebugSections(
519             Obj,
520             [](const SectionBase &S) { return isa<CompressedSection>(&S); },
521             [&Obj](const SectionBase *S) {
522               const CompressedSection *CS = cast<CompressedSection>(S);
523               return &Obj.addSection<DecompressedSection>(*CS);
524             }))
525       return Err;
526   }
527 
528   return Error::success();
529 }
530 
531 // Add symbol to the Object symbol table with the specified properties.
532 static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo,
533                       uint8_t DefaultVisibility) {
534   SectionBase *Sec = Obj.findSection(SymInfo.SectionName);
535   uint64_t Value = Sec ? Sec->Addr + SymInfo.Value : SymInfo.Value;
536 
537   uint8_t Bind = ELF::STB_GLOBAL;
538   uint8_t Type = ELF::STT_NOTYPE;
539   uint8_t Visibility = DefaultVisibility;
540 
541   for (SymbolFlag FlagValue : SymInfo.Flags)
542     switch (FlagValue) {
543     case SymbolFlag::Global:
544       Bind = ELF::STB_GLOBAL;
545       break;
546     case SymbolFlag::Local:
547       Bind = ELF::STB_LOCAL;
548       break;
549     case SymbolFlag::Weak:
550       Bind = ELF::STB_WEAK;
551       break;
552     case SymbolFlag::Default:
553       Visibility = ELF::STV_DEFAULT;
554       break;
555     case SymbolFlag::Hidden:
556       Visibility = ELF::STV_HIDDEN;
557       break;
558     case SymbolFlag::Protected:
559       Visibility = ELF::STV_PROTECTED;
560       break;
561     case SymbolFlag::File:
562       Type = ELF::STT_FILE;
563       break;
564     case SymbolFlag::Section:
565       Type = ELF::STT_SECTION;
566       break;
567     case SymbolFlag::Object:
568       Type = ELF::STT_OBJECT;
569       break;
570     case SymbolFlag::Function:
571       Type = ELF::STT_FUNC;
572       break;
573     case SymbolFlag::IndirectFunction:
574       Type = ELF::STT_GNU_IFUNC;
575       break;
576     default: /* Other flag values are ignored for ELF. */
577       break;
578     };
579 
580   Obj.SymbolTable->addSymbol(
581       SymInfo.SymbolName, Bind, Type, Sec, Value, Visibility,
582       Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
583 }
584 
585 static Error
586 handleUserSection(const NewSectionInfo &NewSection,
587                   function_ref<Error(StringRef, ArrayRef<uint8_t>)> F) {
588   ArrayRef<uint8_t> Data(reinterpret_cast<const uint8_t *>(
589                              NewSection.SectionData->getBufferStart()),
590                          NewSection.SectionData->getBufferSize());
591   return F(NewSection.SectionName, Data);
592 }
593 
594 // This function handles the high level operations of GNU objcopy including
595 // handling command line options. It's important to outline certain properties
596 // we expect to hold of the command line operations. Any operation that "keeps"
597 // should keep regardless of a remove. Additionally any removal should respect
598 // any previous removals. Lastly whether or not something is removed shouldn't
599 // depend a) on the order the options occur in or b) on some opaque priority
600 // system. The only priority is that keeps/copies overrule removes.
601 static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig,
602                         Object &Obj) {
603   if (Config.OutputArch) {
604     Obj.Machine = Config.OutputArch.getValue().EMachine;
605     Obj.OSABI = Config.OutputArch.getValue().OSABI;
606   }
607 
608   if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
609     return Obj.removeSections(
610         ELFConfig.AllowBrokenLinks,
611         [&Obj](const SectionBase &Sec) { return onlyKeepDWOPred(Obj, Sec); });
612   }
613 
614   // Dump sections before add/remove for compatibility with GNU objcopy.
615   for (StringRef Flag : Config.DumpSection) {
616     StringRef SectionName;
617     StringRef FileName;
618     std::tie(SectionName, FileName) = Flag.split('=');
619     if (Error E = dumpSectionToFile(SectionName, FileName, Obj))
620       return E;
621   }
622 
623   // It is important to remove the sections first. For example, we want to
624   // remove the relocation sections before removing the symbols. That allows
625   // us to avoid reporting the inappropriate errors about removing symbols
626   // named in relocations.
627   if (Error E = replaceAndRemoveSections(Config, ELFConfig, Obj))
628     return E;
629 
630   if (Error E = updateAndRemoveSymbols(Config, ELFConfig, Obj))
631     return E;
632 
633   if (!Config.SectionsToRename.empty()) {
634     std::vector<RelocationSectionBase *> RelocSections;
635     DenseSet<SectionBase *> RenamedSections;
636     for (SectionBase &Sec : Obj.sections()) {
637       auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec);
638       const auto Iter = Config.SectionsToRename.find(Sec.Name);
639       if (Iter != Config.SectionsToRename.end()) {
640         const SectionRename &SR = Iter->second;
641         Sec.Name = std::string(SR.NewName);
642         if (SR.NewFlags.hasValue())
643           setSectionFlagsAndType(Sec, SR.NewFlags.getValue());
644         RenamedSections.insert(&Sec);
645       } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
646         // Postpone processing relocation sections which are not specified in
647         // their explicit '--rename-section' commands until after their target
648         // sections are renamed.
649         // Dynamic relocation sections (i.e. ones with SHF_ALLOC) should be
650         // renamed only explicitly. Otherwise, renaming, for example, '.got.plt'
651         // would affect '.rela.plt', which is not desirable.
652         RelocSections.push_back(RelocSec);
653     }
654 
655     // Rename relocation sections according to their target sections.
656     for (RelocationSectionBase *RelocSec : RelocSections) {
657       auto Iter = RenamedSections.find(RelocSec->getSection());
658       if (Iter != RenamedSections.end())
659         RelocSec->Name = (RelocSec->getNamePrefix() + (*Iter)->Name).str();
660     }
661   }
662 
663   // Add a prefix to allocated sections and their relocation sections. This
664   // should be done after renaming the section by Config.SectionToRename to
665   // imitate the GNU objcopy behavior.
666   if (!Config.AllocSectionsPrefix.empty()) {
667     DenseSet<SectionBase *> PrefixedSections;
668     for (SectionBase &Sec : Obj.sections()) {
669       if (Sec.Flags & SHF_ALLOC) {
670         Sec.Name = (Config.AllocSectionsPrefix + Sec.Name).str();
671         PrefixedSections.insert(&Sec);
672       } else if (auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec)) {
673         // Rename relocation sections associated to the allocated sections.
674         // For example, if we rename .text to .prefix.text, we also rename
675         // .rel.text to .rel.prefix.text.
676         //
677         // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
678         // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
679         // .rela.prefix.plt since GNU objcopy does so.
680         const SectionBase *TargetSec = RelocSec->getSection();
681         if (TargetSec && (TargetSec->Flags & SHF_ALLOC)) {
682           // If the relocation section comes *after* the target section, we
683           // don't add Config.AllocSectionsPrefix because we've already added
684           // the prefix to TargetSec->Name. Otherwise, if the relocation
685           // section comes *before* the target section, we add the prefix.
686           if (PrefixedSections.count(TargetSec))
687             Sec.Name = (RelocSec->getNamePrefix() + TargetSec->Name).str();
688           else
689             Sec.Name = (RelocSec->getNamePrefix() + Config.AllocSectionsPrefix +
690                         TargetSec->Name)
691                            .str();
692         }
693       }
694     }
695   }
696 
697   if (!Config.SetSectionAlignment.empty()) {
698     for (SectionBase &Sec : Obj.sections()) {
699       auto I = Config.SetSectionAlignment.find(Sec.Name);
700       if (I != Config.SetSectionAlignment.end())
701         Sec.Align = I->second;
702     }
703   }
704 
705   if (Config.OnlyKeepDebug)
706     for (auto &Sec : Obj.sections())
707       if (Sec.Flags & SHF_ALLOC && Sec.Type != SHT_NOTE)
708         Sec.Type = SHT_NOBITS;
709 
710   for (const NewSectionInfo &AddedSection : Config.AddSection) {
711     auto AddSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
712       OwnedDataSection &NewSection =
713           Obj.addSection<OwnedDataSection>(Name, Data);
714       if (Name.startswith(".note") && Name != ".note.GNU-stack")
715         NewSection.Type = SHT_NOTE;
716       return Error::success();
717     };
718     if (Error E = handleUserSection(AddedSection, AddSection))
719       return E;
720   }
721 
722   for (const NewSectionInfo &NewSection : Config.UpdateSection) {
723     auto UpdateSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
724       return Obj.updateSection(Name, Data);
725     };
726     if (Error E = handleUserSection(NewSection, UpdateSection))
727       return E;
728   }
729 
730   if (!Config.AddGnuDebugLink.empty())
731     Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink,
732                                         Config.GnuDebugLinkCRC32);
733 
734   // If the symbol table was previously removed, we need to create a new one
735   // before adding new symbols.
736   if (!Obj.SymbolTable && !Config.SymbolsToAdd.empty())
737     if (Error E = Obj.addNewSymbolTable())
738       return E;
739 
740   for (const NewSymbolInfo &SI : Config.SymbolsToAdd)
741     addSymbol(Obj, SI, ELFConfig.NewSymbolVisibility);
742 
743   // --set-section-flags works with sections added by --add-section.
744   if (!Config.SetSectionFlags.empty()) {
745     for (auto &Sec : Obj.sections()) {
746       const auto Iter = Config.SetSectionFlags.find(Sec.Name);
747       if (Iter != Config.SetSectionFlags.end()) {
748         const SectionFlagsUpdate &SFU = Iter->second;
749         setSectionFlagsAndType(Sec, SFU.NewFlags);
750       }
751     }
752   }
753 
754   if (ELFConfig.EntryExpr)
755     Obj.Entry = ELFConfig.EntryExpr(Obj.Entry);
756   return Error::success();
757 }
758 
759 static Error writeOutput(const CommonConfig &Config, Object &Obj,
760                          raw_ostream &Out, ElfType OutputElfType) {
761   std::unique_ptr<Writer> Writer =
762       createWriter(Config, Obj, Out, OutputElfType);
763   if (Error E = Writer->finalize())
764     return E;
765   return Writer->write();
766 }
767 
768 Error objcopy::elf::executeObjcopyOnIHex(const CommonConfig &Config,
769                                          const ELFConfig &ELFConfig,
770                                          MemoryBuffer &In, raw_ostream &Out) {
771   IHexReader Reader(&In);
772   Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
773   if (!Obj)
774     return Obj.takeError();
775 
776   const ElfType OutputElfType =
777       getOutputElfType(Config.OutputArch.getValueOr(MachineInfo()));
778   if (Error E = handleArgs(Config, ELFConfig, **Obj))
779     return E;
780   return writeOutput(Config, **Obj, Out, OutputElfType);
781 }
782 
783 Error objcopy::elf::executeObjcopyOnRawBinary(const CommonConfig &Config,
784                                               const ELFConfig &ELFConfig,
785                                               MemoryBuffer &In,
786                                               raw_ostream &Out) {
787   BinaryReader Reader(&In, ELFConfig.NewSymbolVisibility);
788   Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
789   if (!Obj)
790     return Obj.takeError();
791 
792   // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
793   // (-B<arch>).
794   const ElfType OutputElfType =
795       getOutputElfType(Config.OutputArch.getValueOr(MachineInfo()));
796   if (Error E = handleArgs(Config, ELFConfig, **Obj))
797     return E;
798   return writeOutput(Config, **Obj, Out, OutputElfType);
799 }
800 
801 Error objcopy::elf::executeObjcopyOnBinary(const CommonConfig &Config,
802                                            const ELFConfig &ELFConfig,
803                                            object::ELFObjectFileBase &In,
804                                            raw_ostream &Out) {
805   ELFReader Reader(&In, Config.ExtractPartition);
806   Expected<std::unique_ptr<Object>> Obj =
807       Reader.create(!Config.SymbolsToAdd.empty());
808   if (!Obj)
809     return Obj.takeError();
810   // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
811   const ElfType OutputElfType =
812       Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
813                         : getOutputElfType(In);
814 
815   if (Error E = handleArgs(Config, ELFConfig, **Obj))
816     return createFileError(Config.InputFilename, std::move(E));
817 
818   if (Error E = writeOutput(Config, **Obj, Out, OutputElfType))
819     return createFileError(Config.InputFilename, std::move(E));
820 
821   return Error::success();
822 }
823