]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-objcopy/llvm-objcopy.cpp
Merge libc++ trunk r338150 (just before the 7.0.0 branch point), and
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-objcopy / llvm-objcopy.cpp
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          Sec.Name == ".gdb_index";
191 }
192
193 static bool IsDWOSection(const SectionBase &Sec) {
194   return Sec.Name.endswith(".dwo");
195 }
196
197 static bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
198   // We can't remove the section header string table.
199   if (&Sec == Obj.SectionNames)
200     return false;
201   // Short of keeping the string table we want to keep everything that is a DWO
202   // section and remove everything else.
203   return !IsDWOSection(Sec);
204 }
205
206 static std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config,
207                                             Object &Obj, Buffer &Buf,
208                                             ElfType OutputElfType) {
209   if (Config.OutputFormat == "binary") {
210     return llvm::make_unique<BinaryWriter>(Obj, Buf);
211   }
212   // Depending on the initial ELFT and OutputFormat we need a different Writer.
213   switch (OutputElfType) {
214   case ELFT_ELF32LE:
215     return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
216                                                  !Config.StripSections);
217   case ELFT_ELF64LE:
218     return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
219                                                  !Config.StripSections);
220   case ELFT_ELF32BE:
221     return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
222                                                  !Config.StripSections);
223   case ELFT_ELF64BE:
224     return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
225                                                  !Config.StripSections);
226   }
227   llvm_unreachable("Invalid output format");
228 }
229
230 static void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
231                            StringRef File, ElfType OutputElfType) {
232   auto DWOFile = Reader.create();
233   DWOFile->removeSections(
234       [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
235   FileBuffer FB(File);
236   auto Writer = CreateWriter(Config, *DWOFile, FB, OutputElfType);
237   Writer->finalize();
238   Writer->write();
239 }
240
241 // This function handles the high level operations of GNU objcopy including
242 // handling command line options. It's important to outline certain properties
243 // we expect to hold of the command line operations. Any operation that "keeps"
244 // should keep regardless of a remove. Additionally any removal should respect
245 // any previous removals. Lastly whether or not something is removed shouldn't
246 // depend a) on the order the options occur in or b) on some opaque priority
247 // system. The only priority is that keeps/copies overrule removes.
248 static void HandleArgs(const CopyConfig &Config, Object &Obj,
249                        const Reader &Reader, ElfType OutputElfType) {
250
251   if (!Config.SplitDWO.empty()) {
252     SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
253   }
254
255   // TODO: update or remove symbols only if there is an option that affects
256   // them.
257   if (Obj.SymbolTable) {
258     Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
259       if ((Config.LocalizeHidden &&
260            (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
261           (!Config.SymbolsToLocalize.empty() &&
262            is_contained(Config.SymbolsToLocalize, Sym.Name)))
263         Sym.Binding = STB_LOCAL;
264
265       if (!Config.SymbolsToGlobalize.empty() &&
266           is_contained(Config.SymbolsToGlobalize, Sym.Name))
267         Sym.Binding = STB_GLOBAL;
268
269       if (!Config.SymbolsToWeaken.empty() &&
270           is_contained(Config.SymbolsToWeaken, Sym.Name) &&
271           Sym.Binding == STB_GLOBAL)
272         Sym.Binding = STB_WEAK;
273
274       if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
275           Sym.getShndx() != SHN_UNDEF)
276         Sym.Binding = STB_WEAK;
277
278       const auto I = Config.SymbolsToRename.find(Sym.Name);
279       if (I != Config.SymbolsToRename.end())
280         Sym.Name = I->getValue();
281     });
282
283     // The purpose of this loop is to mark symbols referenced by sections
284     // (like GroupSection or RelocationSection). This way, we know which
285     // symbols are still 'needed' and wich are not.
286     if (Config.StripUnneeded) {
287       for (auto &Section : Obj.sections())
288         Section.markSymbols();
289     }
290
291     Obj.removeSymbols([&](const Symbol &Sym) {
292       if ((!Config.SymbolsToKeep.empty() &&
293            is_contained(Config.SymbolsToKeep, Sym.Name)) ||
294           (Config.KeepFileSymbols && Sym.Type == STT_FILE))
295         return false;
296
297       if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
298           Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
299           Sym.Type != STT_SECTION)
300         return true;
301
302       if (Config.StripAll || Config.StripAllGNU)
303         return true;
304
305       if (!Config.SymbolsToRemove.empty() &&
306           is_contained(Config.SymbolsToRemove, Sym.Name)) {
307         return true;
308       }
309
310       if (Config.StripUnneeded && !Sym.Referenced &&
311           (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
312           Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
313         return true;
314
315       return false;
316     });
317   }
318
319   SectionPred RemovePred = [](const SectionBase &) { return false; };
320
321   // Removes:
322   if (!Config.ToRemove.empty()) {
323     RemovePred = [&Config](const SectionBase &Sec) {
324       return find(Config.ToRemove, Sec.Name) != Config.ToRemove.end();
325     };
326   }
327
328   if (Config.StripDWO || !Config.SplitDWO.empty())
329     RemovePred = [RemovePred](const SectionBase &Sec) {
330       return IsDWOSection(Sec) || RemovePred(Sec);
331     };
332
333   if (Config.ExtractDWO)
334     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
335       return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
336     };
337
338   if (Config.StripAllGNU)
339     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
340       if (RemovePred(Sec))
341         return true;
342       if ((Sec.Flags & SHF_ALLOC) != 0)
343         return false;
344       if (&Sec == Obj.SectionNames)
345         return false;
346       switch (Sec.Type) {
347       case SHT_SYMTAB:
348       case SHT_REL:
349       case SHT_RELA:
350       case SHT_STRTAB:
351         return true;
352       }
353       return IsDebugSection(Sec);
354     };
355
356   if (Config.StripSections) {
357     RemovePred = [RemovePred](const SectionBase &Sec) {
358       return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
359     };
360   }
361
362   if (Config.StripDebug) {
363     RemovePred = [RemovePred](const SectionBase &Sec) {
364       return RemovePred(Sec) || IsDebugSection(Sec);
365     };
366   }
367
368   if (Config.StripNonAlloc)
369     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
370       if (RemovePred(Sec))
371         return true;
372       if (&Sec == Obj.SectionNames)
373         return false;
374       return (Sec.Flags & SHF_ALLOC) == 0;
375     };
376
377   if (Config.StripAll)
378     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
379       if (RemovePred(Sec))
380         return true;
381       if (&Sec == Obj.SectionNames)
382         return false;
383       if (Sec.Name.startswith(".gnu.warning"))
384         return false;
385       return (Sec.Flags & SHF_ALLOC) == 0;
386     };
387
388   // Explicit copies:
389   if (!Config.OnlyKeep.empty()) {
390     RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
391       // Explicitly keep these sections regardless of previous removes.
392       if (find(Config.OnlyKeep, Sec.Name) != Config.OnlyKeep.end())
393         return false;
394
395       // Allow all implicit removes.
396       if (RemovePred(Sec))
397         return true;
398
399       // Keep special sections.
400       if (Obj.SectionNames == &Sec)
401         return false;
402       if (Obj.SymbolTable == &Sec ||
403           (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
404         return false;
405
406       // Remove everything else.
407       return true;
408     };
409   }
410
411   if (!Config.Keep.empty()) {
412     RemovePred = [Config, RemovePred](const SectionBase &Sec) {
413       // Explicitly keep these sections regardless of previous removes.
414       if (find(Config.Keep, Sec.Name) != Config.Keep.end())
415         return false;
416       // Otherwise defer to RemovePred.
417       return RemovePred(Sec);
418     };
419   }
420
421   // This has to be the last predicate assignment.
422   // If the option --keep-symbol has been specified
423   // and at least one of those symbols is present
424   // (equivalently, the updated symbol table is not empty)
425   // the symbol table and the string table should not be removed.
426   if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
427       Obj.SymbolTable && !Obj.SymbolTable->empty()) {
428     RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
429       if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
430         return false;
431       return RemovePred(Sec);
432     };
433   }
434
435   Obj.removeSections(RemovePred);
436
437   if (!Config.SectionsToRename.empty()) {
438     for (auto &Sec : Obj.sections()) {
439       const auto Iter = Config.SectionsToRename.find(Sec.Name);
440       if (Iter != Config.SectionsToRename.end())
441         Sec.Name = Iter->second;
442     }
443   }
444
445   if (!Config.AddSection.empty()) {
446     for (const auto &Flag : Config.AddSection) {
447       auto SecPair = Flag.split("=");
448       auto SecName = SecPair.first;
449       auto File = SecPair.second;
450       auto BufOrErr = MemoryBuffer::getFile(File);
451       if (!BufOrErr)
452         reportError(File, BufOrErr.getError());
453       auto Buf = std::move(*BufOrErr);
454       auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
455       auto BufSize = Buf->getBufferSize();
456       Obj.addSection<OwnedDataSection>(SecName,
457                                        ArrayRef<uint8_t>(BufPtr, BufSize));
458     }
459   }
460
461   if (!Config.AddGnuDebugLink.empty())
462     Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
463 }
464
465 static void ExecuteElfObjcopyOnBinary(const CopyConfig &Config, Binary &Binary,
466                                       Buffer &Out) {
467   ELFReader Reader(&Binary);
468   std::unique_ptr<Object> Obj = Reader.create();
469
470   HandleArgs(Config, *Obj, Reader, Reader.getElfType());
471
472   std::unique_ptr<Writer> Writer =
473       CreateWriter(Config, *Obj, Out, Reader.getElfType());
474   Writer->finalize();
475   Writer->write();
476 }
477
478 // For regular archives this function simply calls llvm::writeArchive,
479 // For thin archives it writes the archive file itself as well as its members.
480 static Error deepWriteArchive(StringRef ArcName,
481                               ArrayRef<NewArchiveMember> NewMembers,
482                               bool WriteSymtab, object::Archive::Kind Kind,
483                               bool Deterministic, bool Thin) {
484   Error E =
485       writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
486   if (!Thin || E)
487     return E;
488   for (const NewArchiveMember &Member : NewMembers) {
489     // Internally, FileBuffer will use the buffer created by
490     // FileOutputBuffer::create, for regular files (that is the case for
491     // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
492     // OnDiskBuffer uses a temporary file and then renames it. So in reality
493     // there is no inefficiency / duplicated in-memory buffers in this case. For
494     // now in-memory buffers can not be completely avoided since
495     // NewArchiveMember still requires them even though writeArchive does not
496     // write them on disk.
497     FileBuffer FB(Member.MemberName);
498     FB.allocate(Member.Buf->getBufferSize());
499     std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
500               FB.getBufferStart());
501     if (auto E = FB.commit())
502       return E;
503   }
504   return Error::success();
505 }
506
507 static void ExecuteElfObjcopyOnArchive(const CopyConfig &Config, const Archive &Ar) {
508   std::vector<NewArchiveMember> NewArchiveMembers;
509   Error Err = Error::success();
510   for (const Archive::Child &Child : Ar.children(Err)) {
511     Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
512     if (!ChildOrErr)
513       reportError(Ar.getFileName(), ChildOrErr.takeError());
514     Expected<StringRef> ChildNameOrErr = Child.getName();
515     if (!ChildNameOrErr)
516       reportError(Ar.getFileName(), ChildNameOrErr.takeError());
517
518     MemBuffer MB(ChildNameOrErr.get());
519     ExecuteElfObjcopyOnBinary(Config, **ChildOrErr, MB);
520
521     Expected<NewArchiveMember> Member =
522         NewArchiveMember::getOldMember(Child, true);
523     if (!Member)
524       reportError(Ar.getFileName(), Member.takeError());
525     Member->Buf = MB.releaseMemoryBuffer();
526     Member->MemberName = Member->Buf->getBufferIdentifier();
527     NewArchiveMembers.push_back(std::move(*Member));
528   }
529
530   if (Err)
531     reportError(Config.InputFilename, std::move(Err));
532   if (Error E =
533           deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
534                            Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin()))
535     reportError(Config.OutputFilename, std::move(E));
536 }
537
538 static void ExecuteElfObjcopy(const CopyConfig &Config) {
539   Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
540       createBinary(Config.InputFilename);
541   if (!BinaryOrErr)
542     reportError(Config.InputFilename, BinaryOrErr.takeError());
543
544   if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary()))
545     return ExecuteElfObjcopyOnArchive(Config, *Ar);
546
547   FileBuffer FB(Config.OutputFilename);
548   ExecuteElfObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB);
549 }
550
551 // ParseObjcopyOptions returns the config and sets the input arguments. If a
552 // help flag is set then ParseObjcopyOptions will print the help messege and
553 // exit.
554 static CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
555   ObjcopyOptTable T;
556   unsigned MissingArgumentIndex, MissingArgumentCount;
557   llvm::opt::InputArgList InputArgs =
558       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
559
560   if (InputArgs.size() == 0) {
561     T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
562     exit(1);
563   }
564
565   if (InputArgs.hasArg(OBJCOPY_help)) {
566     T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
567     exit(0);
568   }
569
570   SmallVector<const char *, 2> Positional;
571
572   for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
573     error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
574
575   for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
576     Positional.push_back(Arg->getValue());
577
578   if (Positional.empty())
579     error("No input file specified");
580
581   if (Positional.size() > 2)
582     error("Too many positional arguments");
583
584   CopyConfig Config;
585   Config.InputFilename = Positional[0];
586   Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
587   Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
588   Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
589   Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
590
591   Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
592   Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
593
594   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
595     if (!StringRef(Arg->getValue()).contains('='))
596       error("Bad format for --redefine-sym");
597     auto Old2New = StringRef(Arg->getValue()).split('=');
598     if (!Config.SymbolsToRename.insert(Old2New).second)
599       error("Multiple redefinition of symbol " + Old2New.first);
600   }
601
602   for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
603     if (!StringRef(Arg->getValue()).contains('='))
604       error("Bad format for --rename-section");
605     auto Old2New = StringRef(Arg->getValue()).split('=');
606     if (!Config.SectionsToRename.insert(Old2New).second)
607       error("Already have a section rename for " + Old2New.first);
608   }
609
610   for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
611     Config.ToRemove.push_back(Arg->getValue());
612   for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
613     Config.Keep.push_back(Arg->getValue());
614   for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
615     Config.OnlyKeep.push_back(Arg->getValue());
616   for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
617     Config.AddSection.push_back(Arg->getValue());
618   Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
619   Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
620   Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
621   Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
622   Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
623   Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
624   Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
625   Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
626   Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
627   Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
628   Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
629   Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
630   Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
631   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
632     Config.SymbolsToLocalize.push_back(Arg->getValue());
633   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
634     Config.SymbolsToGlobalize.push_back(Arg->getValue());
635   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
636     Config.SymbolsToWeaken.push_back(Arg->getValue());
637   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
638     Config.SymbolsToRemove.push_back(Arg->getValue());
639   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
640     Config.SymbolsToKeep.push_back(Arg->getValue());
641
642   return Config;
643 }
644
645 // ParseStripOptions returns the config and sets the input arguments. If a
646 // help flag is set then ParseStripOptions will print the help messege and
647 // exit.
648 static CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
649   StripOptTable T;
650   unsigned MissingArgumentIndex, MissingArgumentCount;
651   llvm::opt::InputArgList InputArgs =
652       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
653
654   if (InputArgs.size() == 0) {
655     T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
656     exit(1);
657   }
658
659   if (InputArgs.hasArg(STRIP_help)) {
660     T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
661     exit(0);
662   }
663
664   SmallVector<const char *, 2> Positional;
665   for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
666     error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
667   for (auto Arg : InputArgs.filtered(STRIP_INPUT))
668     Positional.push_back(Arg->getValue());
669
670   if (Positional.empty())
671     error("No input file specified");
672
673   if (Positional.size() > 2)
674     error("Support for multiple input files is not implemented yet");
675
676   CopyConfig Config;
677   Config.InputFilename = Positional[0];
678   Config.OutputFilename =
679       InputArgs.getLastArgValue(STRIP_output, Positional[0]);
680
681   Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
682
683   Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all);
684   Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
685   Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
686
687   if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll)
688     Config.StripAll = true;
689
690   for (auto Arg : InputArgs.filtered(STRIP_remove_section))
691     Config.ToRemove.push_back(Arg->getValue());
692
693   for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
694     Config.SymbolsToKeep.push_back(Arg->getValue());
695
696   return Config;
697 }
698
699 int main(int argc, char **argv) {
700   InitLLVM X(argc, argv);
701   ToolName = argv[0];
702   CopyConfig Config;
703   if (sys::path::stem(ToolName).endswith_lower("strip"))
704     Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
705   else
706     Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
707   ExecuteElfObjcopy(Config);
708 }