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