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