1 //===- ObjcopyOptions.cpp -------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ObjcopyOptions.h"
10 #include "llvm/ADT/Optional.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/ADT/StringSet.h"
14 #include "llvm/BinaryFormat/COFF.h"
15 #include "llvm/ObjCopy/ConfigManager.h"
16 #include "llvm/Option/Arg.h"
17 #include "llvm/Option/ArgList.h"
18 #include "llvm/Support/CRC.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Compression.h"
21 #include "llvm/Support/Errc.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 
25 using namespace llvm;
26 using namespace llvm::objcopy;
27 
28 namespace {
29 enum ObjcopyID {
30   OBJCOPY_INVALID = 0, // This is not an option ID.
31 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
32                HELPTEXT, METAVAR, VALUES)                                      \
33   OBJCOPY_##ID,
34 #include "ObjcopyOpts.inc"
35 #undef OPTION
36 };
37 
38 #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
39 #include "ObjcopyOpts.inc"
40 #undef PREFIX
41 
42 const opt::OptTable::Info ObjcopyInfoTable[] = {
43 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
44                HELPTEXT, METAVAR, VALUES)                                      \
45   {OBJCOPY_##PREFIX,                                                           \
46    NAME,                                                                       \
47    HELPTEXT,                                                                   \
48    METAVAR,                                                                    \
49    OBJCOPY_##ID,                                                               \
50    opt::Option::KIND##Class,                                                   \
51    PARAM,                                                                      \
52    FLAGS,                                                                      \
53    OBJCOPY_##GROUP,                                                            \
54    OBJCOPY_##ALIAS,                                                            \
55    ALIASARGS,                                                                  \
56    VALUES},
57 #include "ObjcopyOpts.inc"
58 #undef OPTION
59 };
60 
61 class ObjcopyOptTable : public opt::OptTable {
62 public:
63   ObjcopyOptTable() : OptTable(ObjcopyInfoTable) {
64     setGroupedShortOptions(true);
65   }
66 };
67 
68 enum InstallNameToolID {
69   INSTALL_NAME_TOOL_INVALID = 0, // This is not an option ID.
70 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
71                HELPTEXT, METAVAR, VALUES)                                      \
72   INSTALL_NAME_TOOL_##ID,
73 #include "InstallNameToolOpts.inc"
74 #undef OPTION
75 };
76 
77 #define PREFIX(NAME, VALUE)                                                    \
78   const char *const INSTALL_NAME_TOOL_##NAME[] = VALUE;
79 #include "InstallNameToolOpts.inc"
80 #undef PREFIX
81 
82 const opt::OptTable::Info InstallNameToolInfoTable[] = {
83 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
84                HELPTEXT, METAVAR, VALUES)                                      \
85   {INSTALL_NAME_TOOL_##PREFIX,                                                 \
86    NAME,                                                                       \
87    HELPTEXT,                                                                   \
88    METAVAR,                                                                    \
89    INSTALL_NAME_TOOL_##ID,                                                     \
90    opt::Option::KIND##Class,                                                   \
91    PARAM,                                                                      \
92    FLAGS,                                                                      \
93    INSTALL_NAME_TOOL_##GROUP,                                                  \
94    INSTALL_NAME_TOOL_##ALIAS,                                                  \
95    ALIASARGS,                                                                  \
96    VALUES},
97 #include "InstallNameToolOpts.inc"
98 #undef OPTION
99 };
100 
101 class InstallNameToolOptTable : public opt::OptTable {
102 public:
103   InstallNameToolOptTable() : OptTable(InstallNameToolInfoTable) {}
104 };
105 
106 enum BitcodeStripID {
107   BITCODE_STRIP_INVALID = 0, // This is not an option ID.
108 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
109                HELPTEXT, METAVAR, VALUES)                                      \
110   BITCODE_STRIP_##ID,
111 #include "BitcodeStripOpts.inc"
112 #undef OPTION
113 };
114 
115 #define PREFIX(NAME, VALUE) const char *const BITCODE_STRIP_##NAME[] = VALUE;
116 #include "BitcodeStripOpts.inc"
117 #undef PREFIX
118 
119 const opt::OptTable::Info BitcodeStripInfoTable[] = {
120 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
121                HELPTEXT, METAVAR, VALUES)                                      \
122   {BITCODE_STRIP_##PREFIX,                                                     \
123    NAME,                                                                       \
124    HELPTEXT,                                                                   \
125    METAVAR,                                                                    \
126    BITCODE_STRIP_##ID,                                                         \
127    opt::Option::KIND##Class,                                                   \
128    PARAM,                                                                      \
129    FLAGS,                                                                      \
130    BITCODE_STRIP_##GROUP,                                                      \
131    BITCODE_STRIP_##ALIAS,                                                      \
132    ALIASARGS,                                                                  \
133    VALUES},
134 #include "BitcodeStripOpts.inc"
135 #undef OPTION
136 };
137 
138 class BitcodeStripOptTable : public opt::OptTable {
139 public:
140   BitcodeStripOptTable() : OptTable(BitcodeStripInfoTable) {}
141 };
142 
143 enum StripID {
144   STRIP_INVALID = 0, // This is not an option ID.
145 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
146                HELPTEXT, METAVAR, VALUES)                                      \
147   STRIP_##ID,
148 #include "StripOpts.inc"
149 #undef OPTION
150 };
151 
152 #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
153 #include "StripOpts.inc"
154 #undef PREFIX
155 
156 const opt::OptTable::Info StripInfoTable[] = {
157 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
158                HELPTEXT, METAVAR, VALUES)                                      \
159   {STRIP_##PREFIX, NAME,       HELPTEXT,                                       \
160    METAVAR,        STRIP_##ID, opt::Option::KIND##Class,                       \
161    PARAM,          FLAGS,      STRIP_##GROUP,                                  \
162    STRIP_##ALIAS,  ALIASARGS,  VALUES},
163 #include "StripOpts.inc"
164 #undef OPTION
165 };
166 
167 class StripOptTable : public opt::OptTable {
168 public:
169   StripOptTable() : OptTable(StripInfoTable) { setGroupedShortOptions(true); }
170 };
171 
172 } // namespace
173 
174 static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
175   return llvm::StringSwitch<SectionFlag>(SectionName)
176       .CaseLower("alloc", SectionFlag::SecAlloc)
177       .CaseLower("load", SectionFlag::SecLoad)
178       .CaseLower("noload", SectionFlag::SecNoload)
179       .CaseLower("readonly", SectionFlag::SecReadonly)
180       .CaseLower("debug", SectionFlag::SecDebug)
181       .CaseLower("code", SectionFlag::SecCode)
182       .CaseLower("data", SectionFlag::SecData)
183       .CaseLower("rom", SectionFlag::SecRom)
184       .CaseLower("merge", SectionFlag::SecMerge)
185       .CaseLower("strings", SectionFlag::SecStrings)
186       .CaseLower("contents", SectionFlag::SecContents)
187       .CaseLower("share", SectionFlag::SecShare)
188       .CaseLower("exclude", SectionFlag::SecExclude)
189       .Default(SectionFlag::SecNone);
190 }
191 
192 static Expected<SectionFlag>
193 parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
194   SectionFlag ParsedFlags = SectionFlag::SecNone;
195   for (StringRef Flag : SectionFlags) {
196     SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
197     if (ParsedFlag == SectionFlag::SecNone)
198       return createStringError(
199           errc::invalid_argument,
200           "unrecognized section flag '%s'. Flags supported for GNU "
201           "compatibility: alloc, load, noload, readonly, exclude, debug, "
202           "code, data, rom, share, contents, merge, strings",
203           Flag.str().c_str());
204     ParsedFlags |= ParsedFlag;
205   }
206 
207   return ParsedFlags;
208 }
209 
210 static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
211   if (!FlagValue.contains('='))
212     return createStringError(errc::invalid_argument,
213                              "bad format for --rename-section: missing '='");
214 
215   // Initial split: ".foo" = ".bar,f1,f2,..."
216   auto Old2New = FlagValue.split('=');
217   SectionRename SR;
218   SR.OriginalName = Old2New.first;
219 
220   // Flags split: ".bar" "f1" "f2" ...
221   SmallVector<StringRef, 6> NameAndFlags;
222   Old2New.second.split(NameAndFlags, ',');
223   SR.NewName = NameAndFlags[0];
224 
225   if (NameAndFlags.size() > 1) {
226     Expected<SectionFlag> ParsedFlagSet =
227         parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
228     if (!ParsedFlagSet)
229       return ParsedFlagSet.takeError();
230     SR.NewFlags = *ParsedFlagSet;
231   }
232 
233   return SR;
234 }
235 
236 static Expected<std::pair<StringRef, uint64_t>>
237 parseSetSectionAlignment(StringRef FlagValue) {
238   if (!FlagValue.contains('='))
239     return createStringError(
240         errc::invalid_argument,
241         "bad format for --set-section-alignment: missing '='");
242   auto Split = StringRef(FlagValue).split('=');
243   if (Split.first.empty())
244     return createStringError(
245         errc::invalid_argument,
246         "bad format for --set-section-alignment: missing section name");
247   uint64_t NewAlign;
248   if (Split.second.getAsInteger(0, NewAlign))
249     return createStringError(
250         errc::invalid_argument,
251         "invalid alignment for --set-section-alignment: '%s'",
252         Split.second.str().c_str());
253   return std::make_pair(Split.first, NewAlign);
254 }
255 
256 static Expected<SectionFlagsUpdate>
257 parseSetSectionFlagValue(StringRef FlagValue) {
258   if (!StringRef(FlagValue).contains('='))
259     return createStringError(errc::invalid_argument,
260                              "bad format for --set-section-flags: missing '='");
261 
262   // Initial split: ".foo" = "f1,f2,..."
263   auto Section2Flags = StringRef(FlagValue).split('=');
264   SectionFlagsUpdate SFU;
265   SFU.Name = Section2Flags.first;
266 
267   // Flags split: "f1" "f2" ...
268   SmallVector<StringRef, 6> SectionFlags;
269   Section2Flags.second.split(SectionFlags, ',');
270   Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
271   if (!ParsedFlagSet)
272     return ParsedFlagSet.takeError();
273   SFU.NewFlags = *ParsedFlagSet;
274 
275   return SFU;
276 }
277 
278 namespace {
279 struct TargetInfo {
280   FileFormat Format;
281   MachineInfo Machine;
282 };
283 } // namespace
284 
285 // FIXME: consolidate with the bfd parsing used by lld.
286 static const StringMap<MachineInfo> TargetMap{
287     // Name, {EMachine, 64bit, LittleEndian}
288     // x86
289     {"elf32-i386", {ELF::EM_386, false, true}},
290     {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
291     {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
292     // Intel MCU
293     {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
294     // ARM
295     {"elf32-littlearm", {ELF::EM_ARM, false, true}},
296     // ARM AArch64
297     {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
298     {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
299     // RISC-V
300     {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
301     {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
302     // PowerPC
303     {"elf32-powerpc", {ELF::EM_PPC, false, false}},
304     {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
305     {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
306     {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
307     // MIPS
308     {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
309     {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
310     {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
311     {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
312     {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
313     {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
314     {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
315     // SPARC
316     {"elf32-sparc", {ELF::EM_SPARC, false, false}},
317     {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
318     {"elf32-hexagon", {ELF::EM_HEXAGON, false, true}},
319 };
320 
321 static Expected<TargetInfo>
322 getOutputTargetInfoByTargetName(StringRef TargetName) {
323   StringRef OriginalTargetName = TargetName;
324   bool IsFreeBSD = TargetName.consume_back("-freebsd");
325   auto Iter = TargetMap.find(TargetName);
326   if (Iter == std::end(TargetMap))
327     return createStringError(errc::invalid_argument,
328                              "invalid output format: '%s'",
329                              OriginalTargetName.str().c_str());
330   MachineInfo MI = Iter->getValue();
331   if (IsFreeBSD)
332     MI.OSABI = ELF::ELFOSABI_FREEBSD;
333 
334   FileFormat Format;
335   if (TargetName.startswith("elf"))
336     Format = FileFormat::ELF;
337   else
338     // This should never happen because `TargetName` is valid (it certainly
339     // exists in the TargetMap).
340     llvm_unreachable("unknown target prefix");
341 
342   return {TargetInfo{Format, MI}};
343 }
344 
345 static Error addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
346                                 StringRef Filename, MatchStyle MS,
347                                 function_ref<Error(Error)> ErrorCallback) {
348   StringSaver Saver(Alloc);
349   SmallVector<StringRef, 16> Lines;
350   auto BufOrErr = MemoryBuffer::getFile(Filename);
351   if (!BufOrErr)
352     return createFileError(Filename, BufOrErr.getError());
353 
354   BufOrErr.get()->getBuffer().split(Lines, '\n');
355   for (StringRef Line : Lines) {
356     // Ignore everything after '#', trim whitespace, and only add the symbol if
357     // it's not empty.
358     auto TrimmedLine = Line.split('#').first.trim();
359     if (!TrimmedLine.empty())
360       if (Error E = Symbols.addMatcher(NameOrPattern::create(
361               Saver.save(TrimmedLine), MS, ErrorCallback)))
362         return E;
363   }
364 
365   return Error::success();
366 }
367 
368 Expected<NameOrPattern>
369 NameOrPattern::create(StringRef Pattern, MatchStyle MS,
370                       function_ref<Error(Error)> ErrorCallback) {
371   switch (MS) {
372   case MatchStyle::Literal:
373     return NameOrPattern(Pattern);
374   case MatchStyle::Wildcard: {
375     SmallVector<char, 32> Data;
376     bool IsPositiveMatch = true;
377     if (Pattern[0] == '!') {
378       IsPositiveMatch = false;
379       Pattern = Pattern.drop_front();
380     }
381     Expected<GlobPattern> GlobOrErr = GlobPattern::create(Pattern);
382 
383     // If we couldn't create it as a glob, report the error, but try again with
384     // a literal if the error reporting is non-fatal.
385     if (!GlobOrErr) {
386       if (Error E = ErrorCallback(GlobOrErr.takeError()))
387         return std::move(E);
388       return create(Pattern, MatchStyle::Literal, ErrorCallback);
389     }
390 
391     return NameOrPattern(std::make_shared<GlobPattern>(*GlobOrErr),
392                          IsPositiveMatch);
393   }
394   case MatchStyle::Regex: {
395     SmallVector<char, 32> Data;
396     return NameOrPattern(std::make_shared<Regex>(
397         ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data)));
398   }
399   }
400   llvm_unreachable("Unhandled llvm.objcopy.MatchStyle enum");
401 }
402 
403 static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
404                                         BumpPtrAllocator &Alloc,
405                                         StringRef Filename) {
406   StringSaver Saver(Alloc);
407   SmallVector<StringRef, 16> Lines;
408   auto BufOrErr = MemoryBuffer::getFile(Filename);
409   if (!BufOrErr)
410     return createFileError(Filename, BufOrErr.getError());
411 
412   BufOrErr.get()->getBuffer().split(Lines, '\n');
413   size_t NumLines = Lines.size();
414   for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
415     StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
416     if (TrimmedLine.empty())
417       continue;
418 
419     std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
420     StringRef NewName = Pair.second.trim();
421     if (NewName.empty())
422       return createStringError(errc::invalid_argument,
423                                "%s:%zu: missing new symbol name",
424                                Filename.str().c_str(), LineNo + 1);
425     SymbolsToRename.insert({Pair.first, NewName});
426   }
427   return Error::success();
428 }
429 
430 template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
431   T Result;
432   if (Val.getAsInteger(0, Result))
433     return errc::invalid_argument;
434   return Result;
435 }
436 
437 namespace {
438 
439 enum class ToolType { Objcopy, Strip, InstallNameTool, BitcodeStrip };
440 
441 } // anonymous namespace
442 
443 static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
444                       ToolType Tool) {
445   StringRef HelpText, ToolName;
446   switch (Tool) {
447   case ToolType::Objcopy:
448     ToolName = "llvm-objcopy";
449     HelpText = " [options] input [output]";
450     break;
451   case ToolType::Strip:
452     ToolName = "llvm-strip";
453     HelpText = " [options] inputs...";
454     break;
455   case ToolType::InstallNameTool:
456     ToolName = "llvm-install-name-tool";
457     HelpText = " [options] input";
458     break;
459   case ToolType::BitcodeStrip:
460     ToolName = "llvm-bitcode-strip";
461     HelpText = " [options] input";
462     break;
463   }
464   OptTable.printHelp(OS, (ToolName + HelpText).str().c_str(),
465                      (ToolName + " tool").str().c_str());
466   // TODO: Replace this with libOption call once it adds extrahelp support.
467   // The CommandLine library has a cl::extrahelp class to support this,
468   // but libOption does not have that yet.
469   OS << "\nPass @FILE as argument to read options from FILE.\n";
470 }
471 
472 static Expected<NewSymbolInfo> parseNewSymbolInfo(StringRef FlagValue) {
473   // Parse value given with --add-symbol option and create the
474   // new symbol if possible. The value format for --add-symbol is:
475   //
476   // <name>=[<section>:]<value>[,<flags>]
477   //
478   // where:
479   // <name> - symbol name, can be empty string
480   // <section> - optional section name. If not given ABS symbol is created
481   // <value> - symbol value, can be decimal or hexadecimal number prefixed
482   //           with 0x.
483   // <flags> - optional flags affecting symbol type, binding or visibility.
484   NewSymbolInfo SI;
485   StringRef Value;
486   std::tie(SI.SymbolName, Value) = FlagValue.split('=');
487   if (Value.empty())
488     return createStringError(
489         errc::invalid_argument,
490         "bad format for --add-symbol, missing '=' after '%s'",
491         SI.SymbolName.str().c_str());
492 
493   if (Value.contains(':')) {
494     std::tie(SI.SectionName, Value) = Value.split(':');
495     if (SI.SectionName.empty() || Value.empty())
496       return createStringError(
497           errc::invalid_argument,
498           "bad format for --add-symbol, missing section name or symbol value");
499   }
500 
501   SmallVector<StringRef, 6> Flags;
502   Value.split(Flags, ',');
503   if (Flags[0].getAsInteger(0, SI.Value))
504     return createStringError(errc::invalid_argument, "bad symbol value: '%s'",
505                              Flags[0].str().c_str());
506 
507   using Functor = std::function<void()>;
508   SmallVector<StringRef, 6> UnsupportedFlags;
509   for (size_t I = 1, NumFlags = Flags.size(); I < NumFlags; ++I)
510     static_cast<Functor>(
511         StringSwitch<Functor>(Flags[I])
512             .CaseLower("global",
513                        [&] { SI.Flags.push_back(SymbolFlag::Global); })
514             .CaseLower("local", [&] { SI.Flags.push_back(SymbolFlag::Local); })
515             .CaseLower("weak", [&] { SI.Flags.push_back(SymbolFlag::Weak); })
516             .CaseLower("default",
517                        [&] { SI.Flags.push_back(SymbolFlag::Default); })
518             .CaseLower("hidden",
519                        [&] { SI.Flags.push_back(SymbolFlag::Hidden); })
520             .CaseLower("protected",
521                        [&] { SI.Flags.push_back(SymbolFlag::Protected); })
522             .CaseLower("file", [&] { SI.Flags.push_back(SymbolFlag::File); })
523             .CaseLower("section",
524                        [&] { SI.Flags.push_back(SymbolFlag::Section); })
525             .CaseLower("object",
526                        [&] { SI.Flags.push_back(SymbolFlag::Object); })
527             .CaseLower("function",
528                        [&] { SI.Flags.push_back(SymbolFlag::Function); })
529             .CaseLower(
530                 "indirect-function",
531                 [&] { SI.Flags.push_back(SymbolFlag::IndirectFunction); })
532             .CaseLower("debug", [&] { SI.Flags.push_back(SymbolFlag::Debug); })
533             .CaseLower("constructor",
534                        [&] { SI.Flags.push_back(SymbolFlag::Constructor); })
535             .CaseLower("warning",
536                        [&] { SI.Flags.push_back(SymbolFlag::Warning); })
537             .CaseLower("indirect",
538                        [&] { SI.Flags.push_back(SymbolFlag::Indirect); })
539             .CaseLower("synthetic",
540                        [&] { SI.Flags.push_back(SymbolFlag::Synthetic); })
541             .CaseLower("unique-object",
542                        [&] { SI.Flags.push_back(SymbolFlag::UniqueObject); })
543             .StartsWithLower("before=",
544                              [&] {
545                                StringRef SymNamePart =
546                                    Flags[I].split('=').second;
547 
548                                if (!SymNamePart.empty())
549                                  SI.BeforeSyms.push_back(SymNamePart);
550                              })
551             .Default([&] { UnsupportedFlags.push_back(Flags[I]); }))();
552   if (!UnsupportedFlags.empty())
553     return createStringError(errc::invalid_argument,
554                              "unsupported flag%s for --add-symbol: '%s'",
555                              UnsupportedFlags.size() > 1 ? "s" : "",
556                              join(UnsupportedFlags, "', '").c_str());
557 
558   return SI;
559 }
560 
561 // Parse input option \p ArgValue and load section data. This function
562 // extracts section name and name of the file keeping section data from
563 // ArgValue, loads data from the file, and stores section name and data
564 // into the vector of new sections \p NewSections.
565 static Error loadNewSectionData(StringRef ArgValue, StringRef OptionName,
566                                 std::vector<NewSectionInfo> &NewSections) {
567   if (!ArgValue.contains('='))
568     return createStringError(errc::invalid_argument,
569                              "bad format for " + OptionName + ": missing '='");
570 
571   std::pair<StringRef, StringRef> SecPair = ArgValue.split("=");
572   if (SecPair.second.empty())
573     return createStringError(errc::invalid_argument, "bad format for " +
574                                                          OptionName +
575                                                          ": missing file name");
576 
577   ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
578       MemoryBuffer::getFile(SecPair.second);
579   if (!BufOrErr)
580     return createFileError(SecPair.second,
581                            errorCodeToError(BufOrErr.getError()));
582 
583   NewSections.push_back({SecPair.first, std::move(*BufOrErr)});
584   return Error::success();
585 }
586 
587 // ParseObjcopyOptions returns the config and sets the input arguments. If a
588 // help flag is set then ParseObjcopyOptions will print the help messege and
589 // exit.
590 Expected<DriverConfig>
591 objcopy::parseObjcopyOptions(ArrayRef<const char *> RawArgsArr,
592                              function_ref<Error(Error)> ErrorCallback) {
593   DriverConfig DC;
594   ObjcopyOptTable T;
595 
596   const char *const *DashDash =
597       std::find_if(RawArgsArr.begin(), RawArgsArr.end(),
598                    [](StringRef Str) { return Str == "--"; });
599   ArrayRef<const char *> ArgsArr = makeArrayRef(RawArgsArr.begin(), DashDash);
600   if (DashDash != RawArgsArr.end())
601     DashDash = std::next(DashDash);
602 
603   unsigned MissingArgumentIndex, MissingArgumentCount;
604   llvm::opt::InputArgList InputArgs =
605       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
606 
607   if (InputArgs.size() == 0 && DashDash == RawArgsArr.end()) {
608     printHelp(T, errs(), ToolType::Objcopy);
609     exit(1);
610   }
611 
612   if (InputArgs.hasArg(OBJCOPY_help)) {
613     printHelp(T, outs(), ToolType::Objcopy);
614     exit(0);
615   }
616 
617   if (InputArgs.hasArg(OBJCOPY_version)) {
618     outs() << "llvm-objcopy, compatible with GNU objcopy\n";
619     cl::PrintVersionMessage();
620     exit(0);
621   }
622 
623   SmallVector<const char *, 2> Positional;
624 
625   for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
626     return createStringError(errc::invalid_argument, "unknown argument '%s'",
627                              Arg->getAsString(InputArgs).c_str());
628 
629   for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
630     Positional.push_back(Arg->getValue());
631   std::copy(DashDash, RawArgsArr.end(), std::back_inserter(Positional));
632 
633   if (Positional.empty())
634     return createStringError(errc::invalid_argument, "no input file specified");
635 
636   if (Positional.size() > 2)
637     return createStringError(errc::invalid_argument,
638                              "too many positional arguments");
639 
640   ConfigManager ConfigMgr;
641   CommonConfig &Config = ConfigMgr.Common;
642   COFFConfig &COFFConfig = ConfigMgr.COFF;
643   ELFConfig &ELFConfig = ConfigMgr.ELF;
644   MachOConfig &MachOConfig = ConfigMgr.MachO;
645   Config.InputFilename = Positional[0];
646   Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
647   if (InputArgs.hasArg(OBJCOPY_target) &&
648       (InputArgs.hasArg(OBJCOPY_input_target) ||
649        InputArgs.hasArg(OBJCOPY_output_target)))
650     return createStringError(
651         errc::invalid_argument,
652         "--target cannot be used with --input-target or --output-target");
653 
654   if (InputArgs.hasArg(OBJCOPY_regex) && InputArgs.hasArg(OBJCOPY_wildcard))
655     return createStringError(errc::invalid_argument,
656                              "--regex and --wildcard are incompatible");
657 
658   MatchStyle SectionMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
659                                      ? MatchStyle::Regex
660                                      : MatchStyle::Wildcard;
661   MatchStyle SymbolMatchStyle
662       = InputArgs.hasArg(OBJCOPY_regex)    ? MatchStyle::Regex
663       : InputArgs.hasArg(OBJCOPY_wildcard) ? MatchStyle::Wildcard
664                                            : MatchStyle::Literal;
665   StringRef InputFormat, OutputFormat;
666   if (InputArgs.hasArg(OBJCOPY_target)) {
667     InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
668     OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
669   } else {
670     InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
671     OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
672   }
673 
674   // FIXME:  Currently, we ignore the target for non-binary/ihex formats
675   // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
676   // format by llvm::object::createBinary regardless of the option value.
677   Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
678                            .Case("binary", FileFormat::Binary)
679                            .Case("ihex", FileFormat::IHex)
680                            .Default(FileFormat::Unspecified);
681 
682   if (InputArgs.hasArg(OBJCOPY_new_symbol_visibility)) {
683     const uint8_t Invalid = 0xff;
684     StringRef VisibilityStr =
685         InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility);
686 
687     ELFConfig.NewSymbolVisibility = StringSwitch<uint8_t>(VisibilityStr)
688                                         .Case("default", ELF::STV_DEFAULT)
689                                         .Case("hidden", ELF::STV_HIDDEN)
690                                         .Case("internal", ELF::STV_INTERNAL)
691                                         .Case("protected", ELF::STV_PROTECTED)
692                                         .Default(Invalid);
693 
694     if (ELFConfig.NewSymbolVisibility == Invalid)
695       return createStringError(errc::invalid_argument,
696                                "'%s' is not a valid symbol visibility",
697                                VisibilityStr.str().c_str());
698   }
699 
700   for (const auto *Arg : InputArgs.filtered(OBJCOPY_subsystem)) {
701     StringRef Subsystem, Version;
702     std::tie(Subsystem, Version) = StringRef(Arg->getValue()).split(':');
703     COFFConfig.Subsystem =
704         StringSwitch<unsigned>(Subsystem.lower())
705             .Case("boot_application",
706                   COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
707             .Case("console", COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI)
708             .Case("efi_application", COFF::IMAGE_SUBSYSTEM_EFI_APPLICATION)
709             .Case("efi_boot_service_driver",
710                   COFF::IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
711             .Case("efi_rom", COFF::IMAGE_SUBSYSTEM_EFI_ROM)
712             .Case("efi_runtime_driver",
713                   COFF::IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
714             .Case("native", COFF::IMAGE_SUBSYSTEM_NATIVE)
715             .Case("posix", COFF::IMAGE_SUBSYSTEM_POSIX_CUI)
716             .Case("windows", COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI)
717             .Default(COFF::IMAGE_SUBSYSTEM_UNKNOWN);
718     if (*COFFConfig.Subsystem == COFF::IMAGE_SUBSYSTEM_UNKNOWN)
719       return createStringError(errc::invalid_argument,
720                                "'%s' is not a valid subsystem",
721                                Subsystem.str().c_str());
722     if (!Version.empty()) {
723       StringRef Major, Minor;
724       std::tie(Major, Minor) = Version.split('.');
725       unsigned Number;
726       if (Major.getAsInteger(10, Number))
727         return createStringError(errc::invalid_argument,
728                                  "'%s' is not a valid subsystem major version",
729                                  Major.str().c_str());
730       COFFConfig.MajorSubsystemVersion = Number;
731       Number = 0;
732       if (!Minor.empty() && Minor.getAsInteger(10, Number))
733         return createStringError(errc::invalid_argument,
734                                  "'%s' is not a valid subsystem minor version",
735                                  Minor.str().c_str());
736       COFFConfig.MinorSubsystemVersion = Number;
737     }
738   }
739 
740   Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
741                             .Case("binary", FileFormat::Binary)
742                             .Case("ihex", FileFormat::IHex)
743                             .Default(FileFormat::Unspecified);
744   if (Config.OutputFormat == FileFormat::Unspecified) {
745     if (OutputFormat.empty()) {
746       Config.OutputFormat = Config.InputFormat;
747     } else {
748       Expected<TargetInfo> Target =
749           getOutputTargetInfoByTargetName(OutputFormat);
750       if (!Target)
751         return Target.takeError();
752       Config.OutputFormat = Target->Format;
753       Config.OutputArch = Target->Machine;
754     }
755   }
756 
757   if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
758                                       OBJCOPY_compress_debug_sections_eq)) {
759     Config.CompressionType = DebugCompressionType::Z;
760 
761     if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
762       Config.CompressionType =
763           StringSwitch<DebugCompressionType>(
764               InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
765               .Case("zlib-gnu", DebugCompressionType::GNU)
766               .Case("zlib", DebugCompressionType::Z)
767               .Default(DebugCompressionType::None);
768       if (Config.CompressionType == DebugCompressionType::None)
769         return createStringError(
770             errc::invalid_argument,
771             "invalid or unsupported --compress-debug-sections format: %s",
772             InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
773                 .str()
774                 .c_str());
775     }
776     if (!zlib::isAvailable())
777       return createStringError(
778           errc::invalid_argument,
779           "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
780   }
781 
782   Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
783   // The gnu_debuglink's target is expected to not change or else its CRC would
784   // become invalidated and get rejected. We can avoid recalculating the
785   // checksum for every target file inside an archive by precomputing the CRC
786   // here. This prevents a significant amount of I/O.
787   if (!Config.AddGnuDebugLink.empty()) {
788     auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
789     if (!DebugOrErr)
790       return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
791     auto Debug = std::move(*DebugOrErr);
792     Config.GnuDebugLinkCRC32 =
793         llvm::crc32(arrayRefFromStringRef(Debug->getBuffer()));
794   }
795   Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
796   Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
797   Config.AllocSectionsPrefix =
798       InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
799   if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
800     Config.ExtractPartition = Arg->getValue();
801 
802   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
803     if (!StringRef(Arg->getValue()).contains('='))
804       return createStringError(errc::invalid_argument,
805                                "bad format for --redefine-sym");
806     auto Old2New = StringRef(Arg->getValue()).split('=');
807     if (!Config.SymbolsToRename.insert(Old2New).second)
808       return createStringError(errc::invalid_argument,
809                                "multiple redefinition of symbol '%s'",
810                                Old2New.first.str().c_str());
811   }
812 
813   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
814     if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
815                                              Arg->getValue()))
816       return std::move(E);
817 
818   for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
819     Expected<SectionRename> SR =
820         parseRenameSectionValue(StringRef(Arg->getValue()));
821     if (!SR)
822       return SR.takeError();
823     if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
824       return createStringError(errc::invalid_argument,
825                                "multiple renames of section '%s'",
826                                SR->OriginalName.str().c_str());
827   }
828   for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_alignment)) {
829     Expected<std::pair<StringRef, uint64_t>> NameAndAlign =
830         parseSetSectionAlignment(Arg->getValue());
831     if (!NameAndAlign)
832       return NameAndAlign.takeError();
833     Config.SetSectionAlignment[NameAndAlign->first] = NameAndAlign->second;
834   }
835   for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
836     Expected<SectionFlagsUpdate> SFU =
837         parseSetSectionFlagValue(Arg->getValue());
838     if (!SFU)
839       return SFU.takeError();
840     if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
841       return createStringError(
842           errc::invalid_argument,
843           "--set-section-flags set multiple times for section '%s'",
844           SFU->Name.str().c_str());
845   }
846   // Prohibit combinations of --set-section-flags when the section name is used
847   // by --rename-section, either as a source or a destination.
848   for (const auto &E : Config.SectionsToRename) {
849     const SectionRename &SR = E.second;
850     if (Config.SetSectionFlags.count(SR.OriginalName))
851       return createStringError(
852           errc::invalid_argument,
853           "--set-section-flags=%s conflicts with --rename-section=%s=%s",
854           SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
855           SR.NewName.str().c_str());
856     if (Config.SetSectionFlags.count(SR.NewName))
857       return createStringError(
858           errc::invalid_argument,
859           "--set-section-flags=%s conflicts with --rename-section=%s=%s",
860           SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
861           SR.NewName.str().c_str());
862   }
863 
864   for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
865     if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
866             Arg->getValue(), SectionMatchStyle, ErrorCallback)))
867       return std::move(E);
868   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
869     if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
870             Arg->getValue(), SectionMatchStyle, ErrorCallback)))
871       return std::move(E);
872   for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
873     if (Error E = Config.OnlySection.addMatcher(NameOrPattern::create(
874             Arg->getValue(), SectionMatchStyle, ErrorCallback)))
875       return std::move(E);
876   for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
877     if (Error Err = loadNewSectionData(Arg->getValue(), "--add-section",
878                                        Config.AddSection))
879       return std::move(Err);
880   }
881   for (auto Arg : InputArgs.filtered(OBJCOPY_update_section)) {
882     if (Error Err = loadNewSectionData(Arg->getValue(), "--update-section",
883                                        Config.UpdateSection))
884       return std::move(Err);
885   }
886   for (auto *Arg : InputArgs.filtered(OBJCOPY_dump_section)) {
887     StringRef Value(Arg->getValue());
888     if (Value.split('=').second.empty())
889       return createStringError(
890           errc::invalid_argument,
891           "bad format for --dump-section, expected section=file");
892     Config.DumpSection.push_back(Value);
893   }
894   Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
895   Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
896   Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
897   Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
898   Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
899   Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
900   Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
901   Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
902   Config.ExtractMainPartition =
903       InputArgs.hasArg(OBJCOPY_extract_main_partition);
904   ELFConfig.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
905   Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
906   if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
907     Config.DiscardMode =
908         InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
909             ? DiscardType::All
910             : DiscardType::Locals;
911   Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
912   ELFConfig.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
913   MachOConfig.KeepUndefined = InputArgs.hasArg(OBJCOPY_keep_undefined);
914   Config.DecompressDebugSections =
915       InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
916   if (Config.DiscardMode == DiscardType::All) {
917     Config.StripDebug = true;
918     ELFConfig.KeepFileSymbols = true;
919   }
920   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
921     if (Error E = Config.SymbolsToLocalize.addMatcher(NameOrPattern::create(
922             Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
923       return std::move(E);
924   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
925     if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
926                                      Arg->getValue(), SymbolMatchStyle,
927                                      ErrorCallback))
928       return std::move(E);
929   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
930     if (Error E = Config.SymbolsToKeepGlobal.addMatcher(NameOrPattern::create(
931             Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
932       return std::move(E);
933   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
934     if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
935                                      Arg->getValue(), SymbolMatchStyle,
936                                      ErrorCallback))
937       return std::move(E);
938   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
939     if (Error E = Config.SymbolsToGlobalize.addMatcher(NameOrPattern::create(
940             Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
941       return std::move(E);
942   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
943     if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
944                                      Arg->getValue(), SymbolMatchStyle,
945                                      ErrorCallback))
946       return std::move(E);
947   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
948     if (Error E = Config.SymbolsToWeaken.addMatcher(NameOrPattern::create(
949             Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
950       return std::move(E);
951   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
952     if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
953                                      Arg->getValue(), SymbolMatchStyle,
954                                      ErrorCallback))
955       return std::move(E);
956   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
957     if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
958             Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
959       return std::move(E);
960   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
961     if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
962                                      Arg->getValue(), SymbolMatchStyle,
963                                      ErrorCallback))
964       return std::move(E);
965   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
966     if (Error E =
967             Config.UnneededSymbolsToRemove.addMatcher(NameOrPattern::create(
968                 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
969       return std::move(E);
970   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
971     if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
972                                      Arg->getValue(), SymbolMatchStyle,
973                                      ErrorCallback))
974       return std::move(E);
975   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
976     if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
977             Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
978       return std::move(E);
979   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
980     if (Error E =
981             addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc, Arg->getValue(),
982                                SymbolMatchStyle, ErrorCallback))
983       return std::move(E);
984   for (auto *Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
985     Expected<NewSymbolInfo> SymInfo = parseNewSymbolInfo(Arg->getValue());
986     if (!SymInfo)
987       return SymInfo.takeError();
988 
989     Config.SymbolsToAdd.push_back(*SymInfo);
990   }
991 
992   ELFConfig.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
993 
994   Config.DeterministicArchives = InputArgs.hasFlag(
995       OBJCOPY_enable_deterministic_archives,
996       OBJCOPY_disable_deterministic_archives, /*default=*/true);
997 
998   Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
999 
1000   if (Config.PreserveDates &&
1001       (Config.OutputFilename == "-" || Config.InputFilename == "-"))
1002     return createStringError(errc::invalid_argument,
1003                              "--preserve-dates requires a file");
1004 
1005   for (auto Arg : InputArgs)
1006     if (Arg->getOption().matches(OBJCOPY_set_start)) {
1007       auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
1008       if (!EAddr)
1009         return createStringError(
1010             EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
1011 
1012       ELFConfig.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
1013     } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
1014       auto EIncr = getAsInteger<int64_t>(Arg->getValue());
1015       if (!EIncr)
1016         return createStringError(EIncr.getError(),
1017                                  "bad entry point increment: '%s'",
1018                                  Arg->getValue());
1019       auto Expr = ELFConfig.EntryExpr ? std::move(ELFConfig.EntryExpr)
1020                                       : [](uint64_t A) { return A; };
1021       ELFConfig.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
1022         return Expr(EAddr) + *EIncr;
1023       };
1024     }
1025 
1026   if (Config.DecompressDebugSections &&
1027       Config.CompressionType != DebugCompressionType::None) {
1028     return createStringError(
1029         errc::invalid_argument,
1030         "cannot specify both --compress-debug-sections and "
1031         "--decompress-debug-sections");
1032   }
1033 
1034   if (Config.DecompressDebugSections && !zlib::isAvailable())
1035     return createStringError(
1036         errc::invalid_argument,
1037         "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
1038 
1039   if (Config.ExtractPartition && Config.ExtractMainPartition)
1040     return createStringError(errc::invalid_argument,
1041                              "cannot specify --extract-partition together with "
1042                              "--extract-main-partition");
1043 
1044   DC.CopyConfigs.push_back(std::move(ConfigMgr));
1045   return std::move(DC);
1046 }
1047 
1048 // ParseInstallNameToolOptions returns the config and sets the input arguments.
1049 // If a help flag is set then ParseInstallNameToolOptions will print the help
1050 // messege and exit.
1051 Expected<DriverConfig>
1052 objcopy::parseInstallNameToolOptions(ArrayRef<const char *> ArgsArr) {
1053   DriverConfig DC;
1054   ConfigManager ConfigMgr;
1055   CommonConfig &Config = ConfigMgr.Common;
1056   MachOConfig &MachOConfig = ConfigMgr.MachO;
1057   InstallNameToolOptTable T;
1058   unsigned MissingArgumentIndex, MissingArgumentCount;
1059   llvm::opt::InputArgList InputArgs =
1060       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
1061 
1062   if (MissingArgumentCount)
1063     return createStringError(
1064         errc::invalid_argument,
1065         "missing argument to " +
1066             StringRef(InputArgs.getArgString(MissingArgumentIndex)) +
1067             " option");
1068 
1069   if (InputArgs.size() == 0) {
1070     printHelp(T, errs(), ToolType::InstallNameTool);
1071     exit(1);
1072   }
1073 
1074   if (InputArgs.hasArg(INSTALL_NAME_TOOL_help)) {
1075     printHelp(T, outs(), ToolType::InstallNameTool);
1076     exit(0);
1077   }
1078 
1079   if (InputArgs.hasArg(INSTALL_NAME_TOOL_version)) {
1080     outs() << "llvm-install-name-tool, compatible with cctools "
1081               "install_name_tool\n";
1082     cl::PrintVersionMessage();
1083     exit(0);
1084   }
1085 
1086   for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_add_rpath))
1087     MachOConfig.RPathToAdd.push_back(Arg->getValue());
1088 
1089   for (auto *Arg : InputArgs.filtered(INSTALL_NAME_TOOL_prepend_rpath))
1090     MachOConfig.RPathToPrepend.push_back(Arg->getValue());
1091 
1092   for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_delete_rpath)) {
1093     StringRef RPath = Arg->getValue();
1094 
1095     // Cannot add and delete the same rpath at the same time.
1096     if (is_contained(MachOConfig.RPathToAdd, RPath))
1097       return createStringError(
1098           errc::invalid_argument,
1099           "cannot specify both -add_rpath '%s' and -delete_rpath '%s'",
1100           RPath.str().c_str(), RPath.str().c_str());
1101     if (is_contained(MachOConfig.RPathToPrepend, RPath))
1102       return createStringError(
1103           errc::invalid_argument,
1104           "cannot specify both -prepend_rpath '%s' and -delete_rpath '%s'",
1105           RPath.str().c_str(), RPath.str().c_str());
1106 
1107     MachOConfig.RPathsToRemove.insert(RPath);
1108   }
1109 
1110   for (auto *Arg : InputArgs.filtered(INSTALL_NAME_TOOL_rpath)) {
1111     StringRef Old = Arg->getValue(0);
1112     StringRef New = Arg->getValue(1);
1113 
1114     auto Match = [=](StringRef RPath) { return RPath == Old || RPath == New; };
1115 
1116     // Cannot specify duplicate -rpath entries
1117     auto It1 = find_if(
1118         MachOConfig.RPathsToUpdate,
1119         [&Match](const DenseMap<StringRef, StringRef>::value_type &OldNew) {
1120           return Match(OldNew.getFirst()) || Match(OldNew.getSecond());
1121         });
1122     if (It1 != MachOConfig.RPathsToUpdate.end())
1123       return createStringError(errc::invalid_argument,
1124                                "cannot specify both -rpath '" +
1125                                    It1->getFirst() + "' '" + It1->getSecond() +
1126                                    "' and -rpath '" + Old + "' '" + New + "'");
1127 
1128     // Cannot specify the same rpath under both -delete_rpath and -rpath
1129     auto It2 = find_if(MachOConfig.RPathsToRemove, Match);
1130     if (It2 != MachOConfig.RPathsToRemove.end())
1131       return createStringError(errc::invalid_argument,
1132                                "cannot specify both -delete_rpath '" + *It2 +
1133                                    "' and -rpath '" + Old + "' '" + New + "'");
1134 
1135     // Cannot specify the same rpath under both -add_rpath and -rpath
1136     auto It3 = find_if(MachOConfig.RPathToAdd, Match);
1137     if (It3 != MachOConfig.RPathToAdd.end())
1138       return createStringError(errc::invalid_argument,
1139                                "cannot specify both -add_rpath '" + *It3 +
1140                                    "' and -rpath '" + Old + "' '" + New + "'");
1141 
1142     // Cannot specify the same rpath under both -prepend_rpath and -rpath.
1143     auto It4 = find_if(MachOConfig.RPathToPrepend, Match);
1144     if (It4 != MachOConfig.RPathToPrepend.end())
1145       return createStringError(errc::invalid_argument,
1146                                "cannot specify both -prepend_rpath '" + *It4 +
1147                                    "' and -rpath '" + Old + "' '" + New + "'");
1148 
1149     MachOConfig.RPathsToUpdate.insert({Old, New});
1150   }
1151 
1152   if (auto *Arg = InputArgs.getLastArg(INSTALL_NAME_TOOL_id)) {
1153     MachOConfig.SharedLibId = Arg->getValue();
1154     if (MachOConfig.SharedLibId->empty())
1155       return createStringError(errc::invalid_argument,
1156                                "cannot specify an empty id");
1157   }
1158 
1159   for (auto *Arg : InputArgs.filtered(INSTALL_NAME_TOOL_change))
1160     MachOConfig.InstallNamesToUpdate.insert(
1161         {Arg->getValue(0), Arg->getValue(1)});
1162 
1163   MachOConfig.RemoveAllRpaths =
1164       InputArgs.hasArg(INSTALL_NAME_TOOL_delete_all_rpaths);
1165 
1166   SmallVector<StringRef, 2> Positional;
1167   for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_UNKNOWN))
1168     return createStringError(errc::invalid_argument, "unknown argument '%s'",
1169                              Arg->getAsString(InputArgs).c_str());
1170   for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_INPUT))
1171     Positional.push_back(Arg->getValue());
1172   if (Positional.empty())
1173     return createStringError(errc::invalid_argument, "no input file specified");
1174   if (Positional.size() > 1)
1175     return createStringError(
1176         errc::invalid_argument,
1177         "llvm-install-name-tool expects a single input file");
1178   Config.InputFilename = Positional[0];
1179   Config.OutputFilename = Positional[0];
1180 
1181   DC.CopyConfigs.push_back(std::move(ConfigMgr));
1182   return std::move(DC);
1183 }
1184 
1185 Expected<DriverConfig>
1186 objcopy::parseBitcodeStripOptions(ArrayRef<const char *> ArgsArr) {
1187   DriverConfig DC;
1188   ConfigManager ConfigMgr;
1189   CommonConfig &Config = ConfigMgr.Common;
1190   BitcodeStripOptTable T;
1191   unsigned MissingArgumentIndex, MissingArgumentCount;
1192   opt::InputArgList InputArgs =
1193       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
1194 
1195   if (InputArgs.size() == 0) {
1196     printHelp(T, errs(), ToolType::BitcodeStrip);
1197     exit(1);
1198   }
1199 
1200   if (InputArgs.hasArg(BITCODE_STRIP_help)) {
1201     printHelp(T, outs(), ToolType::BitcodeStrip);
1202     exit(0);
1203   }
1204 
1205   if (InputArgs.hasArg(BITCODE_STRIP_version)) {
1206     outs() << "llvm-bitcode-strip, compatible with cctools "
1207               "bitcode_strip\n";
1208     cl::PrintVersionMessage();
1209     exit(0);
1210   }
1211 
1212   for (auto *Arg : InputArgs.filtered(BITCODE_STRIP_UNKNOWN))
1213     return createStringError(errc::invalid_argument, "unknown argument '%s'",
1214                              Arg->getAsString(InputArgs).c_str());
1215 
1216   SmallVector<StringRef, 2> Positional;
1217   for (auto *Arg : InputArgs.filtered(BITCODE_STRIP_INPUT))
1218     Positional.push_back(Arg->getValue());
1219   if (Positional.size() > 1)
1220     return createStringError(errc::invalid_argument,
1221                              "llvm-bitcode-strip expects a single input file");
1222   assert(!Positional.empty());
1223   Config.InputFilename = Positional[0];
1224   Config.OutputFilename = Positional[0];
1225 
1226   DC.CopyConfigs.push_back(std::move(ConfigMgr));
1227   return std::move(DC);
1228 }
1229 
1230 // ParseStripOptions returns the config and sets the input arguments. If a
1231 // help flag is set then ParseStripOptions will print the help messege and
1232 // exit.
1233 Expected<DriverConfig>
1234 objcopy::parseStripOptions(ArrayRef<const char *> RawArgsArr,
1235                            function_ref<Error(Error)> ErrorCallback) {
1236   const char *const *DashDash =
1237       std::find_if(RawArgsArr.begin(), RawArgsArr.end(),
1238                    [](StringRef Str) { return Str == "--"; });
1239   ArrayRef<const char *> ArgsArr = makeArrayRef(RawArgsArr.begin(), DashDash);
1240   if (DashDash != RawArgsArr.end())
1241     DashDash = std::next(DashDash);
1242 
1243   StripOptTable T;
1244   unsigned MissingArgumentIndex, MissingArgumentCount;
1245   llvm::opt::InputArgList InputArgs =
1246       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
1247 
1248   if (InputArgs.size() == 0 && DashDash == RawArgsArr.end()) {
1249     printHelp(T, errs(), ToolType::Strip);
1250     exit(1);
1251   }
1252 
1253   if (InputArgs.hasArg(STRIP_help)) {
1254     printHelp(T, outs(), ToolType::Strip);
1255     exit(0);
1256   }
1257 
1258   if (InputArgs.hasArg(STRIP_version)) {
1259     outs() << "llvm-strip, compatible with GNU strip\n";
1260     cl::PrintVersionMessage();
1261     exit(0);
1262   }
1263 
1264   SmallVector<StringRef, 2> Positional;
1265   for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
1266     return createStringError(errc::invalid_argument, "unknown argument '%s'",
1267                              Arg->getAsString(InputArgs).c_str());
1268   for (auto Arg : InputArgs.filtered(STRIP_INPUT))
1269     Positional.push_back(Arg->getValue());
1270   std::copy(DashDash, RawArgsArr.end(), std::back_inserter(Positional));
1271 
1272   if (Positional.empty())
1273     return createStringError(errc::invalid_argument, "no input file specified");
1274 
1275   if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
1276     return createStringError(
1277         errc::invalid_argument,
1278         "multiple input files cannot be used in combination with -o");
1279 
1280   ConfigManager ConfigMgr;
1281   CommonConfig &Config = ConfigMgr.Common;
1282   ELFConfig &ELFConfig = ConfigMgr.ELF;
1283   MachOConfig &MachOConfig = ConfigMgr.MachO;
1284 
1285   if (InputArgs.hasArg(STRIP_regex) && InputArgs.hasArg(STRIP_wildcard))
1286     return createStringError(errc::invalid_argument,
1287                              "--regex and --wildcard are incompatible");
1288   MatchStyle SectionMatchStyle =
1289       InputArgs.hasArg(STRIP_regex) ? MatchStyle::Regex : MatchStyle::Wildcard;
1290   MatchStyle SymbolMatchStyle
1291       = InputArgs.hasArg(STRIP_regex)    ? MatchStyle::Regex
1292       : InputArgs.hasArg(STRIP_wildcard) ? MatchStyle::Wildcard
1293                                          : MatchStyle::Literal;
1294   ELFConfig.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
1295   Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
1296 
1297   if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
1298     Config.DiscardMode =
1299         InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
1300             ? DiscardType::All
1301             : DiscardType::Locals;
1302   Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
1303   Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
1304   if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
1305     Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
1306   Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
1307   MachOConfig.StripSwiftSymbols = InputArgs.hasArg(STRIP_strip_swift_symbols);
1308   Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
1309   ELFConfig.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
1310   MachOConfig.KeepUndefined = InputArgs.hasArg(STRIP_keep_undefined);
1311 
1312   for (auto Arg : InputArgs.filtered(STRIP_keep_section))
1313     if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
1314             Arg->getValue(), SectionMatchStyle, ErrorCallback)))
1315       return std::move(E);
1316 
1317   for (auto Arg : InputArgs.filtered(STRIP_remove_section))
1318     if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
1319             Arg->getValue(), SectionMatchStyle, ErrorCallback)))
1320       return std::move(E);
1321 
1322   for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
1323     if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
1324             Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
1325       return std::move(E);
1326 
1327   for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
1328     if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
1329             Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
1330       return std::move(E);
1331 
1332   if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
1333       !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
1334       !Config.StripAllGNU && Config.SymbolsToRemove.empty())
1335     Config.StripAll = true;
1336 
1337   if (Config.DiscardMode == DiscardType::All) {
1338     Config.StripDebug = true;
1339     ELFConfig.KeepFileSymbols = true;
1340   }
1341 
1342   Config.DeterministicArchives =
1343       InputArgs.hasFlag(STRIP_enable_deterministic_archives,
1344                         STRIP_disable_deterministic_archives, /*default=*/true);
1345 
1346   Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
1347   Config.InputFormat = FileFormat::Unspecified;
1348   Config.OutputFormat = FileFormat::Unspecified;
1349 
1350   DriverConfig DC;
1351   if (Positional.size() == 1) {
1352     Config.InputFilename = Positional[0];
1353     Config.OutputFilename =
1354         InputArgs.getLastArgValue(STRIP_output, Positional[0]);
1355     DC.CopyConfigs.push_back(std::move(ConfigMgr));
1356   } else {
1357     StringMap<unsigned> InputFiles;
1358     for (StringRef Filename : Positional) {
1359       if (InputFiles[Filename]++ == 1) {
1360         if (Filename == "-")
1361           return createStringError(
1362               errc::invalid_argument,
1363               "cannot specify '-' as an input file more than once");
1364         if (Error E = ErrorCallback(createStringError(
1365                 errc::invalid_argument, "'%s' was already specified",
1366                 Filename.str().c_str())))
1367           return std::move(E);
1368       }
1369       Config.InputFilename = Filename;
1370       Config.OutputFilename = Filename;
1371       DC.CopyConfigs.push_back(ConfigMgr);
1372     }
1373   }
1374 
1375   if (Config.PreserveDates && (is_contained(Positional, "-") ||
1376                                InputArgs.getLastArgValue(STRIP_output) == "-"))
1377     return createStringError(errc::invalid_argument,
1378                              "--preserve-dates requires a file");
1379 
1380   return std::move(DC);
1381 }
1382