xref: /llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.cpp (revision fdfe2a9236db507dc85bbf561138b72f1ced6850)
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 #include "Object.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/BinaryFormat/ELF.h"
16 #include "llvm/Object/Archive.h"
17 #include "llvm/Object/ArchiveWriter.h"
18 #include "llvm/Object/Binary.h"
19 #include "llvm/Object/ELFObjectFile.h"
20 #include "llvm/Object/ELFTypes.h"
21 #include "llvm/Object/Error.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/Option.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Error.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/ErrorOr.h"
31 #include "llvm/Support/FileOutputBuffer.h"
32 #include "llvm/Support/InitLLVM.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <cstdlib>
38 #include <functional>
39 #include <iterator>
40 #include <memory>
41 #include <string>
42 #include <system_error>
43 #include <utility>
44 
45 using namespace llvm;
46 using namespace llvm::objcopy;
47 using namespace object;
48 using namespace ELF;
49 
50 namespace {
51 
52 enum ObjcopyID {
53   OBJCOPY_INVALID = 0, // This is not an option ID.
54 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
55                HELPTEXT, METAVAR, VALUES)                                      \
56   OBJCOPY_##ID,
57 #include "ObjcopyOpts.inc"
58 #undef OPTION
59 };
60 
61 #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
62 #include "ObjcopyOpts.inc"
63 #undef PREFIX
64 
65 static const opt::OptTable::Info ObjcopyInfoTable[] = {
66 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
67                HELPTEXT, METAVAR, VALUES)                                      \
68   {OBJCOPY_##PREFIX,                                                           \
69    NAME,                                                                       \
70    HELPTEXT,                                                                   \
71    METAVAR,                                                                    \
72    OBJCOPY_##ID,                                                               \
73    opt::Option::KIND##Class,                                                   \
74    PARAM,                                                                      \
75    FLAGS,                                                                      \
76    OBJCOPY_##GROUP,                                                            \
77    OBJCOPY_##ALIAS,                                                            \
78    ALIASARGS,                                                                  \
79    VALUES},
80 #include "ObjcopyOpts.inc"
81 #undef OPTION
82 };
83 
84 class ObjcopyOptTable : public opt::OptTable {
85 public:
86   ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
87 };
88 
89 enum StripID {
90   STRIP_INVALID = 0, // This is not an option ID.
91 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
92                HELPTEXT, METAVAR, VALUES)                                      \
93   STRIP_##ID,
94 #include "StripOpts.inc"
95 #undef OPTION
96 };
97 
98 #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
99 #include "StripOpts.inc"
100 #undef PREFIX
101 
102 static const opt::OptTable::Info StripInfoTable[] = {
103 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
104                HELPTEXT, METAVAR, VALUES)                                      \
105   {STRIP_##PREFIX, NAME,       HELPTEXT,                                       \
106    METAVAR,        STRIP_##ID, opt::Option::KIND##Class,                       \
107    PARAM,          FLAGS,      STRIP_##GROUP,                                  \
108    STRIP_##ALIAS,  ALIASARGS,  VALUES},
109 #include "StripOpts.inc"
110 #undef OPTION
111 };
112 
113 class StripOptTable : public opt::OptTable {
114 public:
115   StripOptTable() : OptTable(StripInfoTable, true) {}
116 };
117 
118 struct CopyConfig {
119   StringRef OutputFilename;
120   StringRef InputFilename;
121   StringRef OutputFormat;
122   StringRef InputFormat;
123   StringRef BinaryArch;
124 
125   StringRef SplitDWO;
126   StringRef AddGnuDebugLink;
127   std::vector<StringRef> ToRemove;
128   std::vector<StringRef> Keep;
129   std::vector<StringRef> OnlyKeep;
130   std::vector<StringRef> AddSection;
131   std::vector<StringRef> SymbolsToLocalize;
132   std::vector<StringRef> SymbolsToGlobalize;
133   std::vector<StringRef> SymbolsToWeaken;
134   std::vector<StringRef> SymbolsToRemove;
135   std::vector<StringRef> SymbolsToKeep;
136   StringMap<StringRef> SectionsToRename;
137   StringMap<StringRef> SymbolsToRename;
138   bool StripAll = false;
139   bool StripAllGNU = false;
140   bool StripDebug = false;
141   bool StripSections = false;
142   bool StripNonAlloc = false;
143   bool StripDWO = false;
144   bool StripUnneeded = false;
145   bool ExtractDWO = false;
146   bool LocalizeHidden = false;
147   bool Weaken = false;
148   bool DiscardAll = false;
149   bool OnlyKeepDebug = false;
150   bool KeepFileSymbols = false;
151 };
152 
153 using SectionPred = std::function<bool(const SectionBase &Sec)>;
154 
155 } // namespace
156 
157 namespace llvm {
158 namespace objcopy {
159 
160 // The name this program was invoked as.
161 StringRef ToolName;
162 
163 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
164   errs() << ToolName << ": " << Message << ".\n";
165   errs().flush();
166   exit(1);
167 }
168 
169 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
170   assert(EC);
171   errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
172   exit(1);
173 }
174 
175 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
176   assert(E);
177   std::string Buf;
178   raw_string_ostream OS(Buf);
179   logAllUnhandledErrors(std::move(E), OS, "");
180   OS.flush();
181   errs() << ToolName << ": '" << File << "': " << Buf;
182   exit(1);
183 }
184 
185 } // end namespace objcopy
186 } // end namespace llvm
187 
188 static bool IsDebugSection(const SectionBase &Sec) {
189   return Sec.Name.startswith(".debug") || Sec.Name.startswith(".zdebug");
190 }
191 
192 static bool IsDWOSection(const SectionBase &Sec) {
193   return Sec.Name.endswith(".dwo");
194 }
195 
196 static bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
197   // We can't remove the section header string table.
198   if (&Sec == Obj.SectionNames)
199     return false;
200   // Short of keeping the string table we want to keep everything that is a DWO
201   // section and remove everything else.
202   return !IsDWOSection(Sec);
203 }
204 
205 static std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config,
206                                             Object &Obj, Buffer &Buf,
207                                             ElfType OutputElfType) {
208   if (Config.OutputFormat == "binary") {
209     return llvm::make_unique<BinaryWriter>(Obj, Buf);
210   }
211   // Depending on the initial ELFT and OutputFormat we need a different Writer.
212   switch (OutputElfType) {
213   case ELFT_ELF32LE:
214     return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
215                                                  !Config.StripSections);
216   case ELFT_ELF64LE:
217     return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
218                                                  !Config.StripSections);
219   case ELFT_ELF32BE:
220     return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
221                                                  !Config.StripSections);
222   case ELFT_ELF64BE:
223     return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
224                                                  !Config.StripSections);
225   }
226   llvm_unreachable("Invalid output format");
227 }
228 
229 static void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
230                            StringRef File, ElfType OutputElfType) {
231   auto DWOFile = Reader.create();
232   DWOFile->removeSections(
233       [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
234   FileBuffer FB(File);
235   auto Writer = CreateWriter(Config, *DWOFile, FB, OutputElfType);
236   Writer->finalize();
237   Writer->write();
238 }
239 
240 // This function handles the high level operations of GNU objcopy including
241 // handling command line options. It's important to outline certain properties
242 // we expect to hold of the command line operations. Any operation that "keeps"
243 // should keep regardless of a remove. Additionally any removal should respect
244 // any previous removals. Lastly whether or not something is removed shouldn't
245 // depend a) on the order the options occur in or b) on some opaque priority
246 // system. The only priority is that keeps/copies overrule removes.
247 static void HandleArgs(const CopyConfig &Config, Object &Obj,
248                        const Reader &Reader, ElfType OutputElfType) {
249 
250   if (!Config.SplitDWO.empty()) {
251     SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
252   }
253 
254   // TODO: update or remove symbols only if there is an option that affects
255   // them.
256   if (Obj.SymbolTable) {
257     Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
258       if ((Config.LocalizeHidden &&
259            (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
260           (!Config.SymbolsToLocalize.empty() &&
261            is_contained(Config.SymbolsToLocalize, Sym.Name)))
262         Sym.Binding = STB_LOCAL;
263 
264       if (!Config.SymbolsToGlobalize.empty() &&
265           is_contained(Config.SymbolsToGlobalize, Sym.Name))
266         Sym.Binding = STB_GLOBAL;
267 
268       if (!Config.SymbolsToWeaken.empty() &&
269           is_contained(Config.SymbolsToWeaken, Sym.Name) &&
270           Sym.Binding == STB_GLOBAL)
271         Sym.Binding = STB_WEAK;
272 
273       if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
274           Sym.getShndx() != SHN_UNDEF)
275         Sym.Binding = STB_WEAK;
276 
277       const auto I = Config.SymbolsToRename.find(Sym.Name);
278       if (I != Config.SymbolsToRename.end())
279         Sym.Name = I->getValue();
280     });
281 
282     // The purpose of this loop is to mark symbols referenced by sections
283     // (like GroupSection or RelocationSection). This way, we know which
284     // symbols are still 'needed' and wich are not.
285     if (Config.StripUnneeded) {
286       for (auto &Section : Obj.sections())
287         Section.markSymbols();
288     }
289 
290     Obj.removeSymbols([&](const Symbol &Sym) {
291       if ((!Config.SymbolsToKeep.empty() &&
292            is_contained(Config.SymbolsToKeep, Sym.Name)) ||
293           (Config.KeepFileSymbols && Sym.Type == STT_FILE))
294         return false;
295 
296       if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
297           Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
298           Sym.Type != STT_SECTION)
299         return true;
300 
301       if (Config.StripAll || Config.StripAllGNU)
302         return true;
303 
304       if (!Config.SymbolsToRemove.empty() &&
305           is_contained(Config.SymbolsToRemove, Sym.Name)) {
306         return true;
307       }
308 
309       if (Config.StripUnneeded && !Sym.Referenced &&
310           (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
311           Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
312         return true;
313 
314       return false;
315     });
316   }
317 
318   SectionPred RemovePred = [](const SectionBase &) { return false; };
319 
320   // Removes:
321   if (!Config.ToRemove.empty()) {
322     RemovePred = [&Config](const SectionBase &Sec) {
323       return find(Config.ToRemove, Sec.Name) != Config.ToRemove.end();
324     };
325   }
326 
327   if (Config.StripDWO || !Config.SplitDWO.empty())
328     RemovePred = [RemovePred](const SectionBase &Sec) {
329       return IsDWOSection(Sec) || RemovePred(Sec);
330     };
331 
332   if (Config.ExtractDWO)
333     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
334       return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
335     };
336 
337   if (Config.StripAllGNU)
338     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
339       if (RemovePred(Sec))
340         return true;
341       if ((Sec.Flags & SHF_ALLOC) != 0)
342         return false;
343       if (&Sec == Obj.SectionNames)
344         return false;
345       switch (Sec.Type) {
346       case SHT_SYMTAB:
347       case SHT_REL:
348       case SHT_RELA:
349       case SHT_STRTAB:
350         return true;
351       }
352       return IsDebugSection(Sec);
353     };
354 
355   if (Config.StripSections) {
356     RemovePred = [RemovePred](const SectionBase &Sec) {
357       return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
358     };
359   }
360 
361   if (Config.StripDebug) {
362     RemovePred = [RemovePred](const SectionBase &Sec) {
363       return RemovePred(Sec) || IsDebugSection(Sec);
364     };
365   }
366 
367   if (Config.StripNonAlloc)
368     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
369       if (RemovePred(Sec))
370         return true;
371       if (&Sec == Obj.SectionNames)
372         return false;
373       return (Sec.Flags & SHF_ALLOC) == 0;
374     };
375 
376   if (Config.StripAll)
377     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
378       if (RemovePred(Sec))
379         return true;
380       if (&Sec == Obj.SectionNames)
381         return false;
382       if (Sec.Name.startswith(".gnu.warning"))
383         return false;
384       return (Sec.Flags & SHF_ALLOC) == 0;
385     };
386 
387   // Explicit copies:
388   if (!Config.OnlyKeep.empty()) {
389     RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
390       // Explicitly keep these sections regardless of previous removes.
391       if (find(Config.OnlyKeep, Sec.Name) != Config.OnlyKeep.end())
392         return false;
393 
394       // Allow all implicit removes.
395       if (RemovePred(Sec))
396         return true;
397 
398       // Keep special sections.
399       if (Obj.SectionNames == &Sec)
400         return false;
401       if (Obj.SymbolTable == &Sec ||
402           (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
403         return false;
404 
405       // Remove everything else.
406       return true;
407     };
408   }
409 
410   if (!Config.Keep.empty()) {
411     RemovePred = [Config, RemovePred](const SectionBase &Sec) {
412       // Explicitly keep these sections regardless of previous removes.
413       if (find(Config.Keep, Sec.Name) != Config.Keep.end())
414         return false;
415       // Otherwise defer to RemovePred.
416       return RemovePred(Sec);
417     };
418   }
419 
420   // This has to be the last predicate assignment.
421   // If the option --keep-symbol has been specified
422   // and at least one of those symbols is present
423   // (equivalently, the updated symbol table is not empty)
424   // the symbol table and the string table should not be removed.
425   if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
426       Obj.SymbolTable && !Obj.SymbolTable->empty()) {
427     RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
428       if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
429         return false;
430       return RemovePred(Sec);
431     };
432   }
433 
434   Obj.removeSections(RemovePred);
435 
436   if (!Config.SectionsToRename.empty()) {
437     for (auto &Sec : Obj.sections()) {
438       const auto Iter = Config.SectionsToRename.find(Sec.Name);
439       if (Iter != Config.SectionsToRename.end())
440         Sec.Name = Iter->second;
441     }
442   }
443 
444   if (!Config.AddSection.empty()) {
445     for (const auto &Flag : Config.AddSection) {
446       auto SecPair = Flag.split("=");
447       auto SecName = SecPair.first;
448       auto File = SecPair.second;
449       auto BufOrErr = MemoryBuffer::getFile(File);
450       if (!BufOrErr)
451         reportError(File, BufOrErr.getError());
452       auto Buf = std::move(*BufOrErr);
453       auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
454       auto BufSize = Buf->getBufferSize();
455       Obj.addSection<OwnedDataSection>(SecName,
456                                        ArrayRef<uint8_t>(BufPtr, BufSize));
457     }
458   }
459 
460   if (!Config.AddGnuDebugLink.empty())
461     Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
462 }
463 
464 static void ExecuteElfObjcopyOnBinary(const CopyConfig &Config, Binary &Binary,
465                                       Buffer &Out) {
466   ELFReader Reader(&Binary);
467   std::unique_ptr<Object> Obj = Reader.create();
468 
469   HandleArgs(Config, *Obj, Reader, Reader.getElfType());
470 
471   std::unique_ptr<Writer> Writer =
472       CreateWriter(Config, *Obj, Out, Reader.getElfType());
473   Writer->finalize();
474   Writer->write();
475 }
476 
477 // For regular archives this function simply calls llvm::writeArchive,
478 // For thin archives it writes the archive file itself as well as its members.
479 static Error deepWriteArchive(StringRef ArcName,
480                               ArrayRef<NewArchiveMember> NewMembers,
481                               bool WriteSymtab, object::Archive::Kind Kind,
482                               bool Deterministic, bool Thin) {
483   Error E =
484       writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
485   if (!Thin || E)
486     return E;
487   for (const NewArchiveMember &Member : NewMembers) {
488     // Internally, FileBuffer will use the buffer created by
489     // FileOutputBuffer::create, for regular files (that is the case for
490     // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
491     // OnDiskBuffer uses a temporary file and then renames it. So in reality
492     // there is no inefficiency / duplicated in-memory buffers in this case. For
493     // now in-memory buffers can not be completely avoided since
494     // NewArchiveMember still requires them even though writeArchive does not
495     // write them on disk.
496     FileBuffer FB(Member.MemberName);
497     FB.allocate(Member.Buf->getBufferSize());
498     std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
499               FB.getBufferStart());
500     if (auto E = FB.commit())
501       return E;
502   }
503   return Error::success();
504 }
505 
506 static void ExecuteElfObjcopyOnArchive(const CopyConfig &Config, const Archive &Ar) {
507   std::vector<NewArchiveMember> NewArchiveMembers;
508   Error Err = Error::success();
509   for (const Archive::Child &Child : Ar.children(Err)) {
510     Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
511     if (!ChildOrErr)
512       reportError(Ar.getFileName(), ChildOrErr.takeError());
513     Expected<StringRef> ChildNameOrErr = Child.getName();
514     if (!ChildNameOrErr)
515       reportError(Ar.getFileName(), ChildNameOrErr.takeError());
516 
517     MemBuffer MB(ChildNameOrErr.get());
518     ExecuteElfObjcopyOnBinary(Config, **ChildOrErr, MB);
519 
520     Expected<NewArchiveMember> Member =
521         NewArchiveMember::getOldMember(Child, true);
522     if (!Member)
523       reportError(Ar.getFileName(), Member.takeError());
524     Member->Buf = MB.releaseMemoryBuffer();
525     Member->MemberName = Member->Buf->getBufferIdentifier();
526     NewArchiveMembers.push_back(std::move(*Member));
527   }
528 
529   if (Err)
530     reportError(Config.InputFilename, std::move(Err));
531   if (Error E =
532           deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
533                            Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin()))
534     reportError(Config.OutputFilename, std::move(E));
535 }
536 
537 static void ExecuteElfObjcopy(const CopyConfig &Config) {
538   Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
539       createBinary(Config.InputFilename);
540   if (!BinaryOrErr)
541     reportError(Config.InputFilename, BinaryOrErr.takeError());
542 
543   if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary()))
544     return ExecuteElfObjcopyOnArchive(Config, *Ar);
545 
546   FileBuffer FB(Config.OutputFilename);
547   ExecuteElfObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB);
548 }
549 
550 // ParseObjcopyOptions returns the config and sets the input arguments. If a
551 // help flag is set then ParseObjcopyOptions will print the help messege and
552 // exit.
553 static CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
554   ObjcopyOptTable T;
555   unsigned MissingArgumentIndex, MissingArgumentCount;
556   llvm::opt::InputArgList InputArgs =
557       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
558 
559   if (InputArgs.size() == 0) {
560     T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
561     exit(1);
562   }
563 
564   if (InputArgs.hasArg(OBJCOPY_help)) {
565     T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
566     exit(0);
567   }
568 
569   SmallVector<const char *, 2> Positional;
570 
571   for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
572     error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
573 
574   for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
575     Positional.push_back(Arg->getValue());
576 
577   if (Positional.empty())
578     error("No input file specified");
579 
580   if (Positional.size() > 2)
581     error("Too many positional arguments");
582 
583   CopyConfig Config;
584   Config.InputFilename = Positional[0];
585   Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
586   Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
587   Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
588   Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
589 
590   Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
591   Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
592 
593   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
594     if (!StringRef(Arg->getValue()).contains('='))
595       error("Bad format for --redefine-sym");
596     auto Old2New = StringRef(Arg->getValue()).split('=');
597     if (!Config.SymbolsToRename.insert(Old2New).second)
598       error("Multiple redefinition of symbol " + Old2New.first);
599   }
600 
601   for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
602     if (!StringRef(Arg->getValue()).contains('='))
603       error("Bad format for --rename-section");
604     auto Old2New = StringRef(Arg->getValue()).split('=');
605     if (!Config.SectionsToRename.insert(Old2New).second)
606       error("Already have a section rename for " + Old2New.first);
607   }
608 
609   for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
610     Config.ToRemove.push_back(Arg->getValue());
611   for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
612     Config.Keep.push_back(Arg->getValue());
613   for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
614     Config.OnlyKeep.push_back(Arg->getValue());
615   for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
616     Config.AddSection.push_back(Arg->getValue());
617   Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
618   Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
619   Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
620   Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
621   Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
622   Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
623   Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
624   Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
625   Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
626   Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
627   Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
628   Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
629   Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
630   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
631     Config.SymbolsToLocalize.push_back(Arg->getValue());
632   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
633     Config.SymbolsToGlobalize.push_back(Arg->getValue());
634   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
635     Config.SymbolsToWeaken.push_back(Arg->getValue());
636   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
637     Config.SymbolsToRemove.push_back(Arg->getValue());
638   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
639     Config.SymbolsToKeep.push_back(Arg->getValue());
640 
641   return Config;
642 }
643 
644 // ParseStripOptions returns the config and sets the input arguments. If a
645 // help flag is set then ParseStripOptions will print the help messege and
646 // exit.
647 static CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
648   StripOptTable T;
649   unsigned MissingArgumentIndex, MissingArgumentCount;
650   llvm::opt::InputArgList InputArgs =
651       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
652 
653   if (InputArgs.size() == 0) {
654     T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
655     exit(1);
656   }
657 
658   if (InputArgs.hasArg(STRIP_help)) {
659     T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
660     exit(0);
661   }
662 
663   SmallVector<const char *, 2> Positional;
664   for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
665     error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
666   for (auto Arg : InputArgs.filtered(STRIP_INPUT))
667     Positional.push_back(Arg->getValue());
668 
669   if (Positional.empty())
670     error("No input file specified");
671 
672   if (Positional.size() > 2)
673     error("Support for multiple input files is not implemented yet");
674 
675   CopyConfig Config;
676   Config.InputFilename = Positional[0];
677   Config.OutputFilename =
678       InputArgs.getLastArgValue(STRIP_output, Positional[0]);
679 
680   Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
681 
682   Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all);
683   Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
684   Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
685 
686   if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll)
687     Config.StripAll = true;
688 
689   for (auto Arg : InputArgs.filtered(STRIP_remove_section))
690     Config.ToRemove.push_back(Arg->getValue());
691 
692   for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
693     Config.SymbolsToKeep.push_back(Arg->getValue());
694 
695   return Config;
696 }
697 
698 int main(int argc, char **argv) {
699   InitLLVM X(argc, argv);
700   ToolName = argv[0];
701   CopyConfig Config;
702   if (sys::path::stem(ToolName).endswith_lower("strip"))
703     Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
704   else
705     Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
706   ExecuteElfObjcopy(Config);
707 }
708