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