xref: /llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.cpp (revision cf67633e66de0853ed061dd38960623209aa9dba)
1 //===- llvm-objcopy.cpp ---------------------------------------------------===//
2 //
3 //                      The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm-objcopy.h"
11 
12 #include "Object.h"
13 #include "llvm/ADT/BitmaskEnum.h"
14 #include "llvm/ADT/Optional.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/BinaryFormat/ELF.h"
20 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ArchiveWriter.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/Arg.h"
27 #include "llvm/Option/ArgList.h"
28 #include "llvm/Option/Option.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Error.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ErrorOr.h"
35 #include "llvm/Support/FileOutputBuffer.h"
36 #include "llvm/Support/InitLLVM.h"
37 #include "llvm/Support/Memory.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/WithColor.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstdlib>
45 #include <functional>
46 #include <iterator>
47 #include <memory>
48 #include <string>
49 #include <system_error>
50 #include <utility>
51 
52 using namespace llvm;
53 using namespace llvm::objcopy;
54 using namespace object;
55 using namespace ELF;
56 
57 namespace {
58 
59 enum ObjcopyID {
60   OBJCOPY_INVALID = 0, // This is not an option ID.
61 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
62                HELPTEXT, METAVAR, VALUES)                                      \
63   OBJCOPY_##ID,
64 #include "ObjcopyOpts.inc"
65 #undef OPTION
66 };
67 
68 #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
69 #include "ObjcopyOpts.inc"
70 #undef PREFIX
71 
72 static const opt::OptTable::Info ObjcopyInfoTable[] = {
73 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
74                HELPTEXT, METAVAR, VALUES)                                      \
75   {OBJCOPY_##PREFIX,                                                           \
76    NAME,                                                                       \
77    HELPTEXT,                                                                   \
78    METAVAR,                                                                    \
79    OBJCOPY_##ID,                                                               \
80    opt::Option::KIND##Class,                                                   \
81    PARAM,                                                                      \
82    FLAGS,                                                                      \
83    OBJCOPY_##GROUP,                                                            \
84    OBJCOPY_##ALIAS,                                                            \
85    ALIASARGS,                                                                  \
86    VALUES},
87 #include "ObjcopyOpts.inc"
88 #undef OPTION
89 };
90 
91 class ObjcopyOptTable : public opt::OptTable {
92 public:
93   ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
94 };
95 
96 enum StripID {
97   STRIP_INVALID = 0, // This is not an option ID.
98 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
99                HELPTEXT, METAVAR, VALUES)                                      \
100   STRIP_##ID,
101 #include "StripOpts.inc"
102 #undef OPTION
103 };
104 
105 #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
106 #include "StripOpts.inc"
107 #undef PREFIX
108 
109 static const opt::OptTable::Info StripInfoTable[] = {
110 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
111                HELPTEXT, METAVAR, VALUES)                                      \
112   {STRIP_##PREFIX, NAME,       HELPTEXT,                                       \
113    METAVAR,        STRIP_##ID, opt::Option::KIND##Class,                       \
114    PARAM,          FLAGS,      STRIP_##GROUP,                                  \
115    STRIP_##ALIAS,  ALIASARGS,  VALUES},
116 #include "StripOpts.inc"
117 #undef OPTION
118 };
119 
120 class StripOptTable : public opt::OptTable {
121 public:
122   StripOptTable() : OptTable(StripInfoTable, true) {}
123 };
124 
125 struct SectionRename {
126   StringRef OriginalName;
127   StringRef NewName;
128   Optional<uint64_t> NewFlags;
129 };
130 
131 struct CopyConfig {
132   // Main input/output options
133   StringRef InputFilename;
134   StringRef InputFormat;
135   StringRef OutputFilename;
136   StringRef OutputFormat;
137 
138   // Only applicable for --input-format=Binary
139   MachineInfo BinaryArch;
140 
141   // Advanced options
142   StringRef AddGnuDebugLink;
143   StringRef SplitDWO;
144   StringRef SymbolsPrefix;
145 
146   // Repeated options
147   std::vector<StringRef> AddSection;
148   std::vector<StringRef> DumpSection;
149   std::vector<StringRef> Keep;
150   std::vector<StringRef> OnlyKeep;
151   std::vector<StringRef> SymbolsToGlobalize;
152   std::vector<StringRef> SymbolsToKeep;
153   std::vector<StringRef> SymbolsToLocalize;
154   std::vector<StringRef> SymbolsToRemove;
155   std::vector<StringRef> SymbolsToWeaken;
156   std::vector<StringRef> ToRemove;
157 
158   // Map options
159   StringMap<SectionRename> SectionsToRename;
160   StringMap<StringRef> SymbolsToRename;
161 
162   // Boolean options
163   bool DiscardAll = false;
164   bool ExtractDWO = false;
165   bool KeepFileSymbols = false;
166   bool LocalizeHidden = false;
167   bool OnlyKeepDebug = false;
168   bool PreserveDates = false;
169   bool StripAll = false;
170   bool StripAllGNU = false;
171   bool StripDWO = false;
172   bool StripDebug = false;
173   bool StripNonAlloc = false;
174   bool StripSections = false;
175   bool StripUnneeded = false;
176   bool Weaken = false;
177 };
178 
179 using SectionPred = std::function<bool(const SectionBase &Sec)>;
180 
181 enum SectionFlag {
182   SecNone = 0,
183   SecAlloc = 1 << 0,
184   SecLoad = 1 << 1,
185   SecNoload = 1 << 2,
186   SecReadonly = 1 << 3,
187   SecDebug = 1 << 4,
188   SecCode = 1 << 5,
189   SecData = 1 << 6,
190   SecRom = 1 << 7,
191   SecMerge = 1 << 8,
192   SecStrings = 1 << 9,
193   SecContents = 1 << 10,
194   SecShare = 1 << 11,
195   LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ SecShare)
196 };
197 
198 } // namespace
199 
200 namespace llvm {
201 namespace objcopy {
202 
203 // The name this program was invoked as.
204 StringRef ToolName;
205 
206 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
207   WithColor::error(errs(), ToolName) << Message << ".\n";
208   errs().flush();
209   exit(1);
210 }
211 
212 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
213   assert(EC);
214   WithColor::error(errs(), ToolName)
215       << "'" << File << "': " << EC.message() << ".\n";
216   exit(1);
217 }
218 
219 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
220   assert(E);
221   std::string Buf;
222   raw_string_ostream OS(Buf);
223   logAllUnhandledErrors(std::move(E), OS, "");
224   OS.flush();
225   WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
226   exit(1);
227 }
228 
229 } // end namespace objcopy
230 } // end namespace llvm
231 
232 static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
233   return llvm::StringSwitch<SectionFlag>(SectionName)
234       .Case("alloc", SectionFlag::SecAlloc)
235       .Case("load", SectionFlag::SecLoad)
236       .Case("noload", SectionFlag::SecNoload)
237       .Case("readonly", SectionFlag::SecReadonly)
238       .Case("debug", SectionFlag::SecDebug)
239       .Case("code", SectionFlag::SecCode)
240       .Case("data", SectionFlag::SecData)
241       .Case("rom", SectionFlag::SecRom)
242       .Case("merge", SectionFlag::SecMerge)
243       .Case("strings", SectionFlag::SecStrings)
244       .Case("contents", SectionFlag::SecContents)
245       .Case("share", SectionFlag::SecShare)
246       .Default(SectionFlag::SecNone);
247 }
248 
249 static SectionRename parseRenameSectionValue(StringRef FlagValue) {
250   if (!FlagValue.contains('='))
251     error("Bad format for --rename-section: missing '='");
252 
253   // Initial split: ".foo" = ".bar,f1,f2,..."
254   auto Old2New = FlagValue.split('=');
255   SectionRename SR;
256   SR.OriginalName = Old2New.first;
257 
258   // Flags split: ".bar" "f1" "f2" ...
259   SmallVector<StringRef, 6> NameAndFlags;
260   Old2New.second.split(NameAndFlags, ',');
261   SR.NewName = NameAndFlags[0];
262 
263   if (NameAndFlags.size() > 1) {
264     SectionFlag Flags = SectionFlag::SecNone;
265     for (size_t I = 1, Size = NameAndFlags.size(); I < Size; ++I) {
266       SectionFlag Flag = parseSectionRenameFlag(NameAndFlags[I]);
267       if (Flag == SectionFlag::SecNone)
268         error("Unrecognized section flag '" + NameAndFlags[I] +
269               "'. Flags supported for GNU compatibility: alloc, load, noload, "
270               "readonly, debug, code, data, rom, share, contents, merge, "
271               "strings.");
272       Flags |= Flag;
273     }
274 
275     SR.NewFlags = 0;
276     if (Flags & SectionFlag::SecAlloc)
277       *SR.NewFlags |= ELF::SHF_ALLOC;
278     if (!(Flags & SectionFlag::SecReadonly))
279       *SR.NewFlags |= ELF::SHF_WRITE;
280     if (Flags & SectionFlag::SecCode)
281       *SR.NewFlags |= ELF::SHF_EXECINSTR;
282     if (Flags & SectionFlag::SecMerge)
283       *SR.NewFlags |= ELF::SHF_MERGE;
284     if (Flags & SectionFlag::SecStrings)
285       *SR.NewFlags |= ELF::SHF_STRINGS;
286   }
287 
288   return SR;
289 }
290 
291 static bool isDebugSection(const SectionBase &Sec) {
292   return Sec.Name.startswith(".debug") || Sec.Name.startswith(".zdebug") ||
293          Sec.Name == ".gdb_index";
294 }
295 
296 static bool isDWOSection(const SectionBase &Sec) {
297   return Sec.Name.endswith(".dwo");
298 }
299 
300 static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
301   // We can't remove the section header string table.
302   if (&Sec == Obj.SectionNames)
303     return false;
304   // Short of keeping the string table we want to keep everything that is a DWO
305   // section and remove everything else.
306   return !isDWOSection(Sec);
307 }
308 
309 static const StringMap<MachineInfo> ArchMap{
310     // Name, {EMachine, 64bit, LittleEndian}
311     {"aarch64", {EM_AARCH64, true, true}},
312     {"arm", {EM_ARM, false, true}},
313     {"i386", {EM_386, false, true}},
314     {"i386:x86-64", {EM_X86_64, true, true}},
315     {"powerpc:common64", {EM_PPC64, true, true}},
316     {"sparc", {EM_SPARC, false, true}},
317     {"x86-64", {EM_X86_64, true, true}},
318 };
319 
320 static const MachineInfo &getMachineInfo(StringRef Arch) {
321   auto Iter = ArchMap.find(Arch);
322   if (Iter == std::end(ArchMap))
323     error("Invalid architecture: '" + Arch + "'");
324   return Iter->getValue();
325 }
326 
327 static ElfType getOutputElfType(const Binary &Bin) {
328   // Infer output ELF type from the input ELF object
329   if (isa<ELFObjectFile<ELF32LE>>(Bin))
330     return ELFT_ELF32LE;
331   if (isa<ELFObjectFile<ELF64LE>>(Bin))
332     return ELFT_ELF64LE;
333   if (isa<ELFObjectFile<ELF32BE>>(Bin))
334     return ELFT_ELF32BE;
335   if (isa<ELFObjectFile<ELF64BE>>(Bin))
336     return ELFT_ELF64BE;
337   llvm_unreachable("Invalid ELFType");
338 }
339 
340 static ElfType getOutputElfType(const MachineInfo &MI) {
341   // Infer output ELF type from the binary arch specified
342   if (MI.Is64Bit)
343     return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
344   else
345     return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
346 }
347 
348 static std::unique_ptr<Writer> createWriter(const CopyConfig &Config,
349                                             Object &Obj, Buffer &Buf,
350                                             ElfType OutputElfType) {
351   if (Config.OutputFormat == "binary") {
352     return llvm::make_unique<BinaryWriter>(Obj, Buf);
353   }
354   // Depending on the initial ELFT and OutputFormat we need a different Writer.
355   switch (OutputElfType) {
356   case ELFT_ELF32LE:
357     return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
358                                                  !Config.StripSections);
359   case ELFT_ELF64LE:
360     return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
361                                                  !Config.StripSections);
362   case ELFT_ELF32BE:
363     return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
364                                                  !Config.StripSections);
365   case ELFT_ELF64BE:
366     return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
367                                                  !Config.StripSections);
368   }
369   llvm_unreachable("Invalid output format");
370 }
371 
372 static void splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
373                            StringRef File, ElfType OutputElfType) {
374   auto DWOFile = Reader.create();
375   DWOFile->removeSections(
376       [&](const SectionBase &Sec) { return onlyKeepDWOPred(*DWOFile, Sec); });
377   FileBuffer FB(File);
378   auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
379   Writer->finalize();
380   Writer->write();
381 }
382 
383 static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
384                                Object &Obj) {
385   for (auto &Sec : Obj.sections()) {
386     if (Sec.Name == SecName) {
387       if (Sec.OriginalData.size() == 0)
388         return make_error<StringError>("Can't dump section \"" + SecName +
389                                            "\": it has no contents",
390                                        object_error::parse_failed);
391       Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
392           FileOutputBuffer::create(Filename, Sec.OriginalData.size());
393       if (!BufferOrErr)
394         return BufferOrErr.takeError();
395       std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
396       std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
397                 Buf->getBufferStart());
398       if (Error E = Buf->commit())
399         return E;
400       return Error::success();
401     }
402   }
403   return make_error<StringError>("Section not found",
404                                  object_error::parse_failed);
405 }
406 
407 // This function handles the high level operations of GNU objcopy including
408 // handling command line options. It's important to outline certain properties
409 // we expect to hold of the command line operations. Any operation that "keeps"
410 // should keep regardless of a remove. Additionally any removal should respect
411 // any previous removals. Lastly whether or not something is removed shouldn't
412 // depend a) on the order the options occur in or b) on some opaque priority
413 // system. The only priority is that keeps/copies overrule removes.
414 static void handleArgs(const CopyConfig &Config, Object &Obj,
415                        const Reader &Reader, ElfType OutputElfType) {
416 
417   if (!Config.SplitDWO.empty()) {
418     splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
419   }
420 
421   // TODO: update or remove symbols only if there is an option that affects
422   // them.
423   if (Obj.SymbolTable) {
424     Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
425       if ((Config.LocalizeHidden &&
426            (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
427           (!Config.SymbolsToLocalize.empty() &&
428            is_contained(Config.SymbolsToLocalize, Sym.Name)))
429         Sym.Binding = STB_LOCAL;
430 
431       if (!Config.SymbolsToGlobalize.empty() &&
432           is_contained(Config.SymbolsToGlobalize, Sym.Name))
433         Sym.Binding = STB_GLOBAL;
434 
435       if (!Config.SymbolsToWeaken.empty() &&
436           is_contained(Config.SymbolsToWeaken, Sym.Name) &&
437           Sym.Binding == STB_GLOBAL)
438         Sym.Binding = STB_WEAK;
439 
440       if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
441           Sym.getShndx() != SHN_UNDEF)
442         Sym.Binding = STB_WEAK;
443 
444       const auto I = Config.SymbolsToRename.find(Sym.Name);
445       if (I != Config.SymbolsToRename.end())
446         Sym.Name = I->getValue();
447 
448       if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
449         Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
450     });
451 
452     // The purpose of this loop is to mark symbols referenced by sections
453     // (like GroupSection or RelocationSection). This way, we know which
454     // symbols are still 'needed' and wich are not.
455     if (Config.StripUnneeded) {
456       for (auto &Section : Obj.sections())
457         Section.markSymbols();
458     }
459 
460     Obj.removeSymbols([&](const Symbol &Sym) {
461       if ((!Config.SymbolsToKeep.empty() &&
462            is_contained(Config.SymbolsToKeep, Sym.Name)) ||
463           (Config.KeepFileSymbols && Sym.Type == STT_FILE))
464         return false;
465 
466       if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
467           Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
468           Sym.Type != STT_SECTION)
469         return true;
470 
471       if (Config.StripAll || Config.StripAllGNU)
472         return true;
473 
474       if (!Config.SymbolsToRemove.empty() &&
475           is_contained(Config.SymbolsToRemove, Sym.Name)) {
476         return true;
477       }
478 
479       if (Config.StripUnneeded && !Sym.Referenced &&
480           (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
481           Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
482         return true;
483 
484       return false;
485     });
486   }
487 
488   SectionPred RemovePred = [](const SectionBase &) { return false; };
489 
490   // Removes:
491   if (!Config.ToRemove.empty()) {
492     RemovePred = [&Config](const SectionBase &Sec) {
493       return find(Config.ToRemove, Sec.Name) != Config.ToRemove.end();
494     };
495   }
496 
497   if (Config.StripDWO || !Config.SplitDWO.empty())
498     RemovePred = [RemovePred](const SectionBase &Sec) {
499       return isDWOSection(Sec) || RemovePred(Sec);
500     };
501 
502   if (Config.ExtractDWO)
503     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
504       return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
505     };
506 
507   if (Config.StripAllGNU)
508     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
509       if (RemovePred(Sec))
510         return true;
511       if ((Sec.Flags & SHF_ALLOC) != 0)
512         return false;
513       if (&Sec == Obj.SectionNames)
514         return false;
515       switch (Sec.Type) {
516       case SHT_SYMTAB:
517       case SHT_REL:
518       case SHT_RELA:
519       case SHT_STRTAB:
520         return true;
521       }
522       return isDebugSection(Sec);
523     };
524 
525   if (Config.StripSections) {
526     RemovePred = [RemovePred](const SectionBase &Sec) {
527       return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
528     };
529   }
530 
531   if (Config.StripDebug) {
532     RemovePred = [RemovePred](const SectionBase &Sec) {
533       return RemovePred(Sec) || isDebugSection(Sec);
534     };
535   }
536 
537   if (Config.StripNonAlloc)
538     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
539       if (RemovePred(Sec))
540         return true;
541       if (&Sec == Obj.SectionNames)
542         return false;
543       return (Sec.Flags & SHF_ALLOC) == 0;
544     };
545 
546   if (Config.StripAll)
547     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
548       if (RemovePred(Sec))
549         return true;
550       if (&Sec == Obj.SectionNames)
551         return false;
552       if (Sec.Name.startswith(".gnu.warning"))
553         return false;
554       return (Sec.Flags & SHF_ALLOC) == 0;
555     };
556 
557   // Explicit copies:
558   if (!Config.OnlyKeep.empty()) {
559     RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
560       // Explicitly keep these sections regardless of previous removes.
561       if (find(Config.OnlyKeep, Sec.Name) != Config.OnlyKeep.end())
562         return false;
563 
564       // Allow all implicit removes.
565       if (RemovePred(Sec))
566         return true;
567 
568       // Keep special sections.
569       if (Obj.SectionNames == &Sec)
570         return false;
571       if (Obj.SymbolTable == &Sec ||
572           (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
573         return false;
574 
575       // Remove everything else.
576       return true;
577     };
578   }
579 
580   if (!Config.Keep.empty()) {
581     RemovePred = [Config, RemovePred](const SectionBase &Sec) {
582       // Explicitly keep these sections regardless of previous removes.
583       if (find(Config.Keep, Sec.Name) != Config.Keep.end())
584         return false;
585       // Otherwise defer to RemovePred.
586       return RemovePred(Sec);
587     };
588   }
589 
590   // This has to be the last predicate assignment.
591   // If the option --keep-symbol has been specified
592   // and at least one of those symbols is present
593   // (equivalently, the updated symbol table is not empty)
594   // the symbol table and the string table should not be removed.
595   if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
596       Obj.SymbolTable && !Obj.SymbolTable->empty()) {
597     RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
598       if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
599         return false;
600       return RemovePred(Sec);
601     };
602   }
603 
604   Obj.removeSections(RemovePred);
605 
606   if (!Config.SectionsToRename.empty()) {
607     for (auto &Sec : Obj.sections()) {
608       const auto Iter = Config.SectionsToRename.find(Sec.Name);
609       if (Iter != Config.SectionsToRename.end()) {
610         const SectionRename &SR = Iter->second;
611         Sec.Name = SR.NewName;
612         if (SR.NewFlags.hasValue()) {
613           // Preserve some flags which should not be dropped when setting flags.
614           // Also, preserve anything OS/processor dependant.
615           const uint64_t PreserveMask = ELF::SHF_COMPRESSED | ELF::SHF_EXCLUDE |
616                                         ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
617                                         ELF::SHF_MASKOS | ELF::SHF_MASKPROC |
618                                         ELF::SHF_TLS | ELF::SHF_INFO_LINK;
619           Sec.Flags = (Sec.Flags & PreserveMask) |
620                       (SR.NewFlags.getValue() & ~PreserveMask);
621         }
622       }
623     }
624   }
625 
626   if (!Config.AddSection.empty()) {
627     for (const auto &Flag : Config.AddSection) {
628       auto SecPair = Flag.split("=");
629       auto SecName = SecPair.first;
630       auto File = SecPair.second;
631       auto BufOrErr = MemoryBuffer::getFile(File);
632       if (!BufOrErr)
633         reportError(File, BufOrErr.getError());
634       auto Buf = std::move(*BufOrErr);
635       auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
636       auto BufSize = Buf->getBufferSize();
637       Obj.addSection<OwnedDataSection>(SecName,
638                                        ArrayRef<uint8_t>(BufPtr, BufSize));
639     }
640   }
641 
642   if (!Config.DumpSection.empty()) {
643     for (const auto &Flag : Config.DumpSection) {
644       std::pair<StringRef, StringRef> SecPair = Flag.split("=");
645       StringRef SecName = SecPair.first;
646       StringRef File = SecPair.second;
647       if (Error E = dumpSectionToFile(SecName, File, Obj))
648         reportError(Config.InputFilename, std::move(E));
649     }
650   }
651 
652   if (!Config.AddGnuDebugLink.empty())
653     Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
654 }
655 
656 static void executeElfObjcopyOnBinary(const CopyConfig &Config, Reader &Reader,
657                                       Buffer &Out, ElfType OutputElfType) {
658   std::unique_ptr<Object> Obj = Reader.create();
659 
660   handleArgs(Config, *Obj, Reader, OutputElfType);
661 
662   std::unique_ptr<Writer> Writer =
663       createWriter(Config, *Obj, Out, OutputElfType);
664   Writer->finalize();
665   Writer->write();
666 }
667 
668 // For regular archives this function simply calls llvm::writeArchive,
669 // For thin archives it writes the archive file itself as well as its members.
670 static Error deepWriteArchive(StringRef ArcName,
671                               ArrayRef<NewArchiveMember> NewMembers,
672                               bool WriteSymtab, object::Archive::Kind Kind,
673                               bool Deterministic, bool Thin) {
674   Error E =
675       writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
676   if (!Thin || E)
677     return E;
678   for (const NewArchiveMember &Member : NewMembers) {
679     // Internally, FileBuffer will use the buffer created by
680     // FileOutputBuffer::create, for regular files (that is the case for
681     // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
682     // OnDiskBuffer uses a temporary file and then renames it. So in reality
683     // there is no inefficiency / duplicated in-memory buffers in this case. For
684     // now in-memory buffers can not be completely avoided since
685     // NewArchiveMember still requires them even though writeArchive does not
686     // write them on disk.
687     FileBuffer FB(Member.MemberName);
688     FB.allocate(Member.Buf->getBufferSize());
689     std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
690               FB.getBufferStart());
691     if (auto E = FB.commit())
692       return E;
693   }
694   return Error::success();
695 }
696 
697 static void executeElfObjcopyOnArchive(const CopyConfig &Config,
698                                        const Archive &Ar) {
699   std::vector<NewArchiveMember> NewArchiveMembers;
700   Error Err = Error::success();
701   for (const Archive::Child &Child : Ar.children(Err)) {
702     Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
703     if (!ChildOrErr)
704       reportError(Ar.getFileName(), ChildOrErr.takeError());
705     Binary *Bin = ChildOrErr->get();
706 
707     Expected<StringRef> ChildNameOrErr = Child.getName();
708     if (!ChildNameOrErr)
709       reportError(Ar.getFileName(), ChildNameOrErr.takeError());
710 
711     MemBuffer MB(ChildNameOrErr.get());
712     ELFReader Reader(Bin);
713     executeElfObjcopyOnBinary(Config, Reader, MB, getOutputElfType(*Bin));
714 
715     Expected<NewArchiveMember> Member =
716         NewArchiveMember::getOldMember(Child, true);
717     if (!Member)
718       reportError(Ar.getFileName(), Member.takeError());
719     Member->Buf = MB.releaseMemoryBuffer();
720     Member->MemberName = Member->Buf->getBufferIdentifier();
721     NewArchiveMembers.push_back(std::move(*Member));
722   }
723 
724   if (Err)
725     reportError(Config.InputFilename, std::move(Err));
726   if (Error E =
727           deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
728                            Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin()))
729     reportError(Config.OutputFilename, std::move(E));
730 }
731 
732 static void restoreDateOnFile(StringRef Filename,
733                               const sys::fs::file_status &Stat) {
734   int FD;
735 
736   if (auto EC = sys::fs::openFileForWrite(Filename, FD))
737     reportError(Filename, EC);
738 
739   if (auto EC = sys::fs::setLastAccessAndModificationTime(
740           FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
741     reportError(Filename, EC);
742 
743   if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
744     reportError(Filename, EC);
745 }
746 
747 static void executeElfObjcopy(const CopyConfig &Config) {
748   sys::fs::file_status Stat;
749   if (Config.PreserveDates)
750     if (auto EC = sys::fs::status(Config.InputFilename, Stat))
751       reportError(Config.InputFilename, EC);
752 
753   if (Config.InputFormat == "binary") {
754     auto BufOrErr = MemoryBuffer::getFile(Config.InputFilename);
755     if (!BufOrErr)
756       reportError(Config.InputFilename, BufOrErr.getError());
757 
758     FileBuffer FB(Config.OutputFilename);
759     BinaryReader Reader(Config.BinaryArch, BufOrErr->get());
760     executeElfObjcopyOnBinary(Config, Reader, FB,
761                               getOutputElfType(Config.BinaryArch));
762   } else {
763     Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
764         createBinary(Config.InputFilename);
765     if (!BinaryOrErr)
766       reportError(Config.InputFilename, BinaryOrErr.takeError());
767 
768     if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) {
769       executeElfObjcopyOnArchive(Config, *Ar);
770     } else {
771       FileBuffer FB(Config.OutputFilename);
772       Binary *Bin = BinaryOrErr.get().getBinary();
773       ELFReader Reader(Bin);
774       executeElfObjcopyOnBinary(Config, Reader, FB, getOutputElfType(*Bin));
775     }
776   }
777 
778   if (Config.PreserveDates) {
779     restoreDateOnFile(Config.OutputFilename, Stat);
780     if (!Config.SplitDWO.empty())
781       restoreDateOnFile(Config.SplitDWO, Stat);
782   }
783 }
784 
785 // ParseObjcopyOptions returns the config and sets the input arguments. If a
786 // help flag is set then ParseObjcopyOptions will print the help messege and
787 // exit.
788 static CopyConfig parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
789   ObjcopyOptTable T;
790   unsigned MissingArgumentIndex, MissingArgumentCount;
791   llvm::opt::InputArgList InputArgs =
792       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
793 
794   if (InputArgs.size() == 0) {
795     T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
796     exit(1);
797   }
798 
799   if (InputArgs.hasArg(OBJCOPY_help)) {
800     T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
801     exit(0);
802   }
803 
804   SmallVector<const char *, 2> Positional;
805 
806   for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
807     error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
808 
809   for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
810     Positional.push_back(Arg->getValue());
811 
812   if (Positional.empty())
813     error("No input file specified");
814 
815   if (Positional.size() > 2)
816     error("Too many positional arguments");
817 
818   CopyConfig Config;
819   Config.InputFilename = Positional[0];
820   Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
821   Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
822   Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
823   if (Config.InputFormat == "binary") {
824     auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
825     if (BinaryArch.empty())
826       error("Specified binary input without specifiying an architecture");
827     Config.BinaryArch = getMachineInfo(BinaryArch);
828   }
829 
830   Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
831   Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
832   Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
833 
834   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
835     if (!StringRef(Arg->getValue()).contains('='))
836       error("Bad format for --redefine-sym");
837     auto Old2New = StringRef(Arg->getValue()).split('=');
838     if (!Config.SymbolsToRename.insert(Old2New).second)
839       error("Multiple redefinition of symbol " + Old2New.first);
840   }
841 
842   for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
843     SectionRename SR = parseRenameSectionValue(StringRef(Arg->getValue()));
844     if (!Config.SectionsToRename.try_emplace(SR.OriginalName, SR).second)
845       error("Multiple renames of section " + SR.OriginalName);
846   }
847 
848   for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
849     Config.ToRemove.push_back(Arg->getValue());
850   for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
851     Config.Keep.push_back(Arg->getValue());
852   for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
853     Config.OnlyKeep.push_back(Arg->getValue());
854   for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
855     Config.AddSection.push_back(Arg->getValue());
856   for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
857     Config.DumpSection.push_back(Arg->getValue());
858   Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
859   Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
860   Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
861   Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
862   Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
863   Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
864   Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
865   Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
866   Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
867   Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
868   Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
869   Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
870   Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
871   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
872     Config.SymbolsToLocalize.push_back(Arg->getValue());
873   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
874     Config.SymbolsToGlobalize.push_back(Arg->getValue());
875   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
876     Config.SymbolsToWeaken.push_back(Arg->getValue());
877   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
878     Config.SymbolsToRemove.push_back(Arg->getValue());
879   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
880     Config.SymbolsToKeep.push_back(Arg->getValue());
881 
882   Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
883 
884   return Config;
885 }
886 
887 // ParseStripOptions returns the config and sets the input arguments. If a
888 // help flag is set then ParseStripOptions will print the help messege and
889 // exit.
890 static CopyConfig parseStripOptions(ArrayRef<const char *> ArgsArr) {
891   StripOptTable T;
892   unsigned MissingArgumentIndex, MissingArgumentCount;
893   llvm::opt::InputArgList InputArgs =
894       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
895 
896   if (InputArgs.size() == 0) {
897     T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
898     exit(1);
899   }
900 
901   if (InputArgs.hasArg(STRIP_help)) {
902     T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
903     exit(0);
904   }
905 
906   SmallVector<const char *, 2> Positional;
907   for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
908     error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
909   for (auto Arg : InputArgs.filtered(STRIP_INPUT))
910     Positional.push_back(Arg->getValue());
911 
912   if (Positional.empty())
913     error("No input file specified");
914 
915   if (Positional.size() > 2)
916     error("Support for multiple input files is not implemented yet");
917 
918   CopyConfig Config;
919   Config.InputFilename = Positional[0];
920   Config.OutputFilename =
921       InputArgs.getLastArgValue(STRIP_output, Positional[0]);
922 
923   Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
924 
925   Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all);
926   Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
927   Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
928 
929   if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll)
930     Config.StripAll = true;
931 
932   for (auto Arg : InputArgs.filtered(STRIP_remove_section))
933     Config.ToRemove.push_back(Arg->getValue());
934 
935   for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
936     Config.SymbolsToKeep.push_back(Arg->getValue());
937 
938   Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
939 
940   return Config;
941 }
942 
943 int main(int argc, char **argv) {
944   InitLLVM X(argc, argv);
945   ToolName = argv[0];
946   CopyConfig Config;
947   if (sys::path::stem(ToolName).endswith_lower("strip"))
948     Config = parseStripOptions(makeArrayRef(argv + 1, argc));
949   else
950     Config = parseObjcopyOptions(makeArrayRef(argv + 1, argc));
951   executeElfObjcopy(Config);
952 }
953