OSDN Git Service

[llvm-objcopy] Add elf32-sparc and elf32-sparcel target
[android-x86/external-llvm.git] / tools / llvm-objcopy / CopyConfig.cpp
1 //===- CopyConfig.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 "CopyConfig.h"
10
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/Option/Arg.h"
15 #include "llvm/Option/ArgList.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Compression.h"
18 #include "llvm/Support/Errc.h"
19 #include "llvm/Support/JamCRC.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/StringSaver.h"
22 #include <memory>
23
24 namespace llvm {
25 namespace objcopy {
26
27 namespace {
28 enum ObjcopyID {
29   OBJCOPY_INVALID = 0, // This is not an option ID.
30 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
31                HELPTEXT, METAVAR, VALUES)                                      \
32   OBJCOPY_##ID,
33 #include "ObjcopyOpts.inc"
34 #undef OPTION
35 };
36
37 #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
38 #include "ObjcopyOpts.inc"
39 #undef PREFIX
40
41 static const opt::OptTable::Info ObjcopyInfoTable[] = {
42 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
43                HELPTEXT, METAVAR, VALUES)                                      \
44   {OBJCOPY_##PREFIX,                                                           \
45    NAME,                                                                       \
46    HELPTEXT,                                                                   \
47    METAVAR,                                                                    \
48    OBJCOPY_##ID,                                                               \
49    opt::Option::KIND##Class,                                                   \
50    PARAM,                                                                      \
51    FLAGS,                                                                      \
52    OBJCOPY_##GROUP,                                                            \
53    OBJCOPY_##ALIAS,                                                            \
54    ALIASARGS,                                                                  \
55    VALUES},
56 #include "ObjcopyOpts.inc"
57 #undef OPTION
58 };
59
60 class ObjcopyOptTable : public opt::OptTable {
61 public:
62   ObjcopyOptTable() : OptTable(ObjcopyInfoTable) {}
63 };
64
65 enum StripID {
66   STRIP_INVALID = 0, // This is not an option ID.
67 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
68                HELPTEXT, METAVAR, VALUES)                                      \
69   STRIP_##ID,
70 #include "StripOpts.inc"
71 #undef OPTION
72 };
73
74 #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
75 #include "StripOpts.inc"
76 #undef PREFIX
77
78 static const opt::OptTable::Info StripInfoTable[] = {
79 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
80                HELPTEXT, METAVAR, VALUES)                                      \
81   {STRIP_##PREFIX, NAME,       HELPTEXT,                                       \
82    METAVAR,        STRIP_##ID, opt::Option::KIND##Class,                       \
83    PARAM,          FLAGS,      STRIP_##GROUP,                                  \
84    STRIP_##ALIAS,  ALIASARGS,  VALUES},
85 #include "StripOpts.inc"
86 #undef OPTION
87 };
88
89 class StripOptTable : public opt::OptTable {
90 public:
91   StripOptTable() : OptTable(StripInfoTable) {}
92 };
93
94 } // namespace
95
96 static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
97   return llvm::StringSwitch<SectionFlag>(SectionName)
98       .CaseLower("alloc", SectionFlag::SecAlloc)
99       .CaseLower("load", SectionFlag::SecLoad)
100       .CaseLower("noload", SectionFlag::SecNoload)
101       .CaseLower("readonly", SectionFlag::SecReadonly)
102       .CaseLower("debug", SectionFlag::SecDebug)
103       .CaseLower("code", SectionFlag::SecCode)
104       .CaseLower("data", SectionFlag::SecData)
105       .CaseLower("rom", SectionFlag::SecRom)
106       .CaseLower("merge", SectionFlag::SecMerge)
107       .CaseLower("strings", SectionFlag::SecStrings)
108       .CaseLower("contents", SectionFlag::SecContents)
109       .CaseLower("share", SectionFlag::SecShare)
110       .Default(SectionFlag::SecNone);
111 }
112
113 static Expected<SectionFlag>
114 parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
115   SectionFlag ParsedFlags = SectionFlag::SecNone;
116   for (StringRef Flag : SectionFlags) {
117     SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
118     if (ParsedFlag == SectionFlag::SecNone)
119       return createStringError(
120           errc::invalid_argument,
121           "unrecognized section flag '%s'. Flags supported for GNU "
122           "compatibility: alloc, load, noload, readonly, debug, code, data, "
123           "rom, share, contents, merge, strings",
124           Flag.str().c_str());
125     ParsedFlags |= ParsedFlag;
126   }
127
128   return ParsedFlags;
129 }
130
131 static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
132   if (!FlagValue.contains('='))
133     return createStringError(errc::invalid_argument,
134                              "bad format for --rename-section: missing '='");
135
136   // Initial split: ".foo" = ".bar,f1,f2,..."
137   auto Old2New = FlagValue.split('=');
138   SectionRename SR;
139   SR.OriginalName = Old2New.first;
140
141   // Flags split: ".bar" "f1" "f2" ...
142   SmallVector<StringRef, 6> NameAndFlags;
143   Old2New.second.split(NameAndFlags, ',');
144   SR.NewName = NameAndFlags[0];
145
146   if (NameAndFlags.size() > 1) {
147     Expected<SectionFlag> ParsedFlagSet =
148         parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
149     if (!ParsedFlagSet)
150       return ParsedFlagSet.takeError();
151     SR.NewFlags = *ParsedFlagSet;
152   }
153
154   return SR;
155 }
156
157 static Expected<SectionFlagsUpdate>
158 parseSetSectionFlagValue(StringRef FlagValue) {
159   if (!StringRef(FlagValue).contains('='))
160     return createStringError(errc::invalid_argument,
161                              "bad format for --set-section-flags: missing '='");
162
163   // Initial split: ".foo" = "f1,f2,..."
164   auto Section2Flags = StringRef(FlagValue).split('=');
165   SectionFlagsUpdate SFU;
166   SFU.Name = Section2Flags.first;
167
168   // Flags split: "f1" "f2" ...
169   SmallVector<StringRef, 6> SectionFlags;
170   Section2Flags.second.split(SectionFlags, ',');
171   Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
172   if (!ParsedFlagSet)
173     return ParsedFlagSet.takeError();
174   SFU.NewFlags = *ParsedFlagSet;
175
176   return SFU;
177 }
178
179 static Expected<NewSymbolInfo> parseNewSymbolInfo(StringRef FlagValue) {
180   // Parse value given with --add-symbol option and create the
181   // new symbol if possible. The value format for --add-symbol is:
182   //
183   // <name>=[<section>:]<value>[,<flags>]
184   //
185   // where:
186   // <name> - symbol name, can be empty string
187   // <section> - optional section name. If not given ABS symbol is created
188   // <value> - symbol value, can be decimal or hexadecimal number prefixed
189   //           with 0x.
190   // <flags> - optional flags affecting symbol type, binding or visibility:
191   //           The following are currently supported:
192   //
193   //           global, local, weak, default, hidden, file, section, object,
194   //           indirect-function.
195   //
196   //           The following flags are ignored and provided for GNU
197   //           compatibility only:
198   //
199   //           warning, debug, constructor, indirect, synthetic,
200   //           unique-object, before=<symbol>.
201   NewSymbolInfo SI;
202   StringRef Value;
203   std::tie(SI.SymbolName, Value) = FlagValue.split('=');
204   if (Value.empty())
205     return createStringError(
206         errc::invalid_argument,
207         "bad format for --add-symbol, missing '=' after '%s'",
208         SI.SymbolName.str().c_str());
209
210   if (Value.contains(':')) {
211     std::tie(SI.SectionName, Value) = Value.split(':');
212     if (SI.SectionName.empty() || Value.empty())
213       return createStringError(
214           errc::invalid_argument,
215           "bad format for --add-symbol, missing section name or symbol value");
216   }
217
218   SmallVector<StringRef, 6> Flags;
219   Value.split(Flags, ',');
220   if (Flags[0].getAsInteger(0, SI.Value))
221     return createStringError(errc::invalid_argument, "bad symbol value: '%s'",
222                              Flags[0].str().c_str());
223
224   using Functor = std::function<void(void)>;
225   SmallVector<StringRef, 6> UnsupportedFlags;
226   for (size_t I = 1, NumFlags = Flags.size(); I < NumFlags; ++I)
227     static_cast<Functor>(
228         StringSwitch<Functor>(Flags[I])
229             .CaseLower("global", [&SI] { SI.Bind = ELF::STB_GLOBAL; })
230             .CaseLower("local", [&SI] { SI.Bind = ELF::STB_LOCAL; })
231             .CaseLower("weak", [&SI] { SI.Bind = ELF::STB_WEAK; })
232             .CaseLower("default", [&SI] { SI.Visibility = ELF::STV_DEFAULT; })
233             .CaseLower("hidden", [&SI] { SI.Visibility = ELF::STV_HIDDEN; })
234             .CaseLower("file", [&SI] { SI.Type = ELF::STT_FILE; })
235             .CaseLower("section", [&SI] { SI.Type = ELF::STT_SECTION; })
236             .CaseLower("object", [&SI] { SI.Type = ELF::STT_OBJECT; })
237             .CaseLower("function", [&SI] { SI.Type = ELF::STT_FUNC; })
238             .CaseLower("indirect-function",
239                        [&SI] { SI.Type = ELF::STT_GNU_IFUNC; })
240             .CaseLower("debug", [] {})
241             .CaseLower("constructor", [] {})
242             .CaseLower("warning", [] {})
243             .CaseLower("indirect", [] {})
244             .CaseLower("synthetic", [] {})
245             .CaseLower("unique-object", [] {})
246             .StartsWithLower("before", [] {})
247             .Default([&] { UnsupportedFlags.push_back(Flags[I]); }))();
248   if (!UnsupportedFlags.empty())
249     return createStringError(errc::invalid_argument,
250                              "unsupported flag%s for --add-symbol: '%s'",
251                              UnsupportedFlags.size() > 1 ? "s" : "",
252                              join(UnsupportedFlags, "', '").c_str());
253   return SI;
254 }
255
256 static const StringMap<MachineInfo> ArchMap{
257     // Name, {EMachine, 64bit, LittleEndian}
258     {"aarch64", {ELF::EM_AARCH64, true, true}},
259     {"arm", {ELF::EM_ARM, false, true}},
260     {"i386", {ELF::EM_386, false, true}},
261     {"i386:x86-64", {ELF::EM_X86_64, true, true}},
262     {"mips", {ELF::EM_MIPS, false, false}},
263     {"powerpc:common64", {ELF::EM_PPC64, true, true}},
264     {"riscv:rv32", {ELF::EM_RISCV, false, true}},
265     {"riscv:rv64", {ELF::EM_RISCV, true, true}},
266     {"sparc", {ELF::EM_SPARC, false, false}},
267     {"sparcel", {ELF::EM_SPARC, false, true}},
268     {"x86-64", {ELF::EM_X86_64, true, true}},
269 };
270
271 static Expected<const MachineInfo &> getMachineInfo(StringRef Arch) {
272   auto Iter = ArchMap.find(Arch);
273   if (Iter == std::end(ArchMap))
274     return createStringError(errc::invalid_argument,
275                              "invalid architecture: '%s'", Arch.str().c_str());
276   return Iter->getValue();
277 }
278
279 // FIXME: consolidate with the bfd parsing used by lld.
280 static const StringMap<MachineInfo> OutputFormatMap{
281     // Name, {EMachine, 64bit, LittleEndian}
282     // x86
283     {"elf32-i386", {ELF::EM_386, false, true}},
284     {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
285     {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
286     // Intel MCU
287     {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
288     // ARM
289     {"elf32-littlearm", {ELF::EM_ARM, false, true}},
290     // ARM AArch64
291     {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
292     {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
293     // RISC-V
294     {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
295     {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
296     // PowerPC
297     {"elf32-powerpc", {ELF::EM_PPC, false, false}},
298     {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
299     {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
300     {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
301     // MIPS
302     {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
303     {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
304     {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
305     {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
306     {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
307     {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
308     {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
309     // SPARC
310     {"elf32-sparc", {ELF::EM_SPARC, false, false}},
311     {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
312 };
313
314 static Expected<MachineInfo> getOutputFormatMachineInfo(StringRef Format) {
315   StringRef OriginalFormat = Format;
316   bool IsFreeBSD = Format.consume_back("-freebsd");
317   auto Iter = OutputFormatMap.find(Format);
318   if (Iter == std::end(OutputFormatMap))
319     return createStringError(errc::invalid_argument,
320                              "invalid output format: '%s'",
321                              OriginalFormat.str().c_str());
322   MachineInfo MI = Iter->getValue();
323   if (IsFreeBSD)
324     MI.OSABI = ELF::ELFOSABI_FREEBSD;
325   return {MI};
326 }
327
328 static Error addSymbolsFromFile(std::vector<NameOrRegex> &Symbols,
329                                 BumpPtrAllocator &Alloc, StringRef Filename,
330                                 bool UseRegex) {
331   StringSaver Saver(Alloc);
332   SmallVector<StringRef, 16> Lines;
333   auto BufOrErr = MemoryBuffer::getFile(Filename);
334   if (!BufOrErr)
335     return createFileError(Filename, BufOrErr.getError());
336
337   BufOrErr.get()->getBuffer().split(Lines, '\n');
338   for (StringRef Line : Lines) {
339     // Ignore everything after '#', trim whitespace, and only add the symbol if
340     // it's not empty.
341     auto TrimmedLine = Line.split('#').first.trim();
342     if (!TrimmedLine.empty())
343       Symbols.emplace_back(Saver.save(TrimmedLine), UseRegex);
344   }
345
346   return Error::success();
347 }
348
349 NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
350   if (!IsRegex) {
351     Name = Pattern;
352     return;
353   }
354
355   SmallVector<char, 32> Data;
356   R = std::make_shared<Regex>(
357       ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
358 }
359
360 static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
361                                         BumpPtrAllocator &Alloc,
362                                         StringRef Filename) {
363   StringSaver Saver(Alloc);
364   SmallVector<StringRef, 16> Lines;
365   auto BufOrErr = MemoryBuffer::getFile(Filename);
366   if (!BufOrErr)
367     return createFileError(Filename, BufOrErr.getError());
368
369   BufOrErr.get()->getBuffer().split(Lines, '\n');
370   size_t NumLines = Lines.size();
371   for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
372     StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
373     if (TrimmedLine.empty())
374       continue;
375
376     std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
377     StringRef NewName = Pair.second.trim();
378     if (NewName.empty())
379       return createStringError(errc::invalid_argument,
380                                "%s:%zu: missing new symbol name",
381                                Filename.str().c_str(), LineNo + 1);
382     SymbolsToRename.insert({Pair.first, NewName});
383   }
384   return Error::success();
385 }
386
387 template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
388   T Result;
389   if (Val.getAsInteger(0, Result))
390     return errc::invalid_argument;
391   return Result;
392 }
393
394 // ParseObjcopyOptions returns the config and sets the input arguments. If a
395 // help flag is set then ParseObjcopyOptions will print the help messege and
396 // exit.
397 Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
398   DriverConfig DC;
399   ObjcopyOptTable T;
400   unsigned MissingArgumentIndex, MissingArgumentCount;
401   llvm::opt::InputArgList InputArgs =
402       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
403
404   if (InputArgs.size() == 0) {
405     T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
406     exit(1);
407   }
408
409   if (InputArgs.hasArg(OBJCOPY_help)) {
410     T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
411     exit(0);
412   }
413
414   if (InputArgs.hasArg(OBJCOPY_version)) {
415     outs() << "llvm-objcopy, compatible with GNU objcopy\n";
416     cl::PrintVersionMessage();
417     exit(0);
418   }
419
420   SmallVector<const char *, 2> Positional;
421
422   for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
423     return createStringError(errc::invalid_argument, "unknown argument '%s'",
424                              Arg->getAsString(InputArgs).c_str());
425
426   for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
427     Positional.push_back(Arg->getValue());
428
429   if (Positional.empty())
430     return createStringError(errc::invalid_argument, "no input file specified");
431
432   if (Positional.size() > 2)
433     return createStringError(errc::invalid_argument,
434                              "too many positional arguments");
435
436   CopyConfig Config;
437   Config.InputFilename = Positional[0];
438   Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
439   if (InputArgs.hasArg(OBJCOPY_target) &&
440       (InputArgs.hasArg(OBJCOPY_input_target) ||
441        InputArgs.hasArg(OBJCOPY_output_target)))
442     return createStringError(
443         errc::invalid_argument,
444         "--target cannot be used with --input-target or --output-target");
445
446   bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
447   if (InputArgs.hasArg(OBJCOPY_target)) {
448     Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
449     Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
450   } else {
451     Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
452     Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
453   }
454   if (Config.InputFormat == "binary") {
455     auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
456     if (BinaryArch.empty())
457       return createStringError(
458           errc::invalid_argument,
459           "specified binary input without specifiying an architecture");
460     Expected<const MachineInfo &> MI = getMachineInfo(BinaryArch);
461     if (!MI)
462       return MI.takeError();
463     Config.BinaryArch = *MI;
464   }
465   if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary" &&
466       Config.OutputFormat != "ihex") {
467     Expected<MachineInfo> MI = getOutputFormatMachineInfo(Config.OutputFormat);
468     if (!MI)
469       return MI.takeError();
470     Config.OutputArch = *MI;
471   }
472
473   if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
474                                       OBJCOPY_compress_debug_sections_eq)) {
475     Config.CompressionType = DebugCompressionType::Z;
476
477     if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
478       Config.CompressionType =
479           StringSwitch<DebugCompressionType>(
480               InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
481               .Case("zlib-gnu", DebugCompressionType::GNU)
482               .Case("zlib", DebugCompressionType::Z)
483               .Default(DebugCompressionType::None);
484       if (Config.CompressionType == DebugCompressionType::None)
485         return createStringError(
486             errc::invalid_argument,
487             "invalid or unsupported --compress-debug-sections format: %s",
488             InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
489                 .str()
490                 .c_str());
491     }
492     if (!zlib::isAvailable())
493       return createStringError(
494           errc::invalid_argument,
495           "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
496   }
497
498   Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
499   // The gnu_debuglink's target is expected to not change or else its CRC would
500   // become invalidated and get rejected. We can avoid recalculating the
501   // checksum for every target file inside an archive by precomputing the CRC
502   // here. This prevents a significant amount of I/O.
503   if (!Config.AddGnuDebugLink.empty()) {
504     auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
505     if (!DebugOrErr)
506       return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
507     auto Debug = std::move(*DebugOrErr);
508     JamCRC CRC;
509     CRC.update(
510         ArrayRef<char>(Debug->getBuffer().data(), Debug->getBuffer().size()));
511     // The CRC32 value needs to be complemented because the JamCRC doesn't
512     // finalize the CRC32 value.
513     Config.GnuDebugLinkCRC32 = ~CRC.getCRC();
514   }
515   Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
516   if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
517     Config.BuildIdLinkInput =
518         InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
519   if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
520     Config.BuildIdLinkOutput =
521         InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
522   Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
523   Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
524   Config.AllocSectionsPrefix =
525       InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
526   if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
527     Config.ExtractPartition = Arg->getValue();
528
529   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
530     if (!StringRef(Arg->getValue()).contains('='))
531       return createStringError(errc::invalid_argument,
532                                "bad format for --redefine-sym");
533     auto Old2New = StringRef(Arg->getValue()).split('=');
534     if (!Config.SymbolsToRename.insert(Old2New).second)
535       return createStringError(errc::invalid_argument,
536                                "multiple redefinition of symbol '%s'",
537                                Old2New.first.str().c_str());
538   }
539
540   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
541     if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
542                                              Arg->getValue()))
543       return std::move(E);
544
545   for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
546     Expected<SectionRename> SR =
547         parseRenameSectionValue(StringRef(Arg->getValue()));
548     if (!SR)
549       return SR.takeError();
550     if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
551       return createStringError(errc::invalid_argument,
552                                "multiple renames of section '%s'",
553                                SR->OriginalName.str().c_str());
554   }
555   for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
556     Expected<SectionFlagsUpdate> SFU =
557         parseSetSectionFlagValue(Arg->getValue());
558     if (!SFU)
559       return SFU.takeError();
560     if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
561       return createStringError(
562           errc::invalid_argument,
563           "--set-section-flags set multiple times for section '%s'",
564           SFU->Name.str().c_str());
565   }
566   // Prohibit combinations of --set-section-flags when the section name is used
567   // by --rename-section, either as a source or a destination.
568   for (const auto &E : Config.SectionsToRename) {
569     const SectionRename &SR = E.second;
570     if (Config.SetSectionFlags.count(SR.OriginalName))
571       return createStringError(
572           errc::invalid_argument,
573           "--set-section-flags=%s conflicts with --rename-section=%s=%s",
574           SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
575           SR.NewName.str().c_str());
576     if (Config.SetSectionFlags.count(SR.NewName))
577       return createStringError(
578           errc::invalid_argument,
579           "--set-section-flags=%s conflicts with --rename-section=%s=%s",
580           SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
581           SR.NewName.str().c_str());
582   }
583
584   for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
585     Config.ToRemove.emplace_back(Arg->getValue(), UseRegex);
586   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
587     Config.KeepSection.emplace_back(Arg->getValue(), UseRegex);
588   for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
589     Config.OnlySection.emplace_back(Arg->getValue(), UseRegex);
590   for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
591     Config.AddSection.push_back(Arg->getValue());
592   for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
593     Config.DumpSection.push_back(Arg->getValue());
594   Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
595   Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
596   Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
597   Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
598   Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
599   Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
600   Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
601   Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
602   Config.ExtractMainPartition =
603       InputArgs.hasArg(OBJCOPY_extract_main_partition);
604   Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
605   Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
606   if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
607     Config.DiscardMode =
608         InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
609             ? DiscardType::All
610             : DiscardType::Locals;
611   Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
612   Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
613   Config.DecompressDebugSections =
614       InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
615   if (Config.DiscardMode == DiscardType::All)
616     Config.StripDebug = true;
617   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
618     Config.SymbolsToLocalize.emplace_back(Arg->getValue(), UseRegex);
619   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
620     if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
621                                      Arg->getValue(), UseRegex))
622       return std::move(E);
623   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
624     Config.SymbolsToKeepGlobal.emplace_back(Arg->getValue(), UseRegex);
625   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
626     if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
627                                      Arg->getValue(), UseRegex))
628       return std::move(E);
629   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
630     Config.SymbolsToGlobalize.emplace_back(Arg->getValue(), UseRegex);
631   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
632     if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
633                                      Arg->getValue(), UseRegex))
634       return std::move(E);
635   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
636     Config.SymbolsToWeaken.emplace_back(Arg->getValue(), UseRegex);
637   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
638     if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
639                                      Arg->getValue(), UseRegex))
640       return std::move(E);
641   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
642     Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
643   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
644     if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
645                                      Arg->getValue(), UseRegex))
646       return std::move(E);
647   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
648     Config.UnneededSymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
649   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
650     if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
651                                      Arg->getValue(), UseRegex))
652       return std::move(E);
653   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
654     Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegex);
655   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
656     if (Error E = addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc,
657                                      Arg->getValue(), UseRegex))
658       return std::move(E);
659   for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
660     Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(Arg->getValue());
661     if (!NSI)
662       return NSI.takeError();
663     Config.SymbolsToAdd.push_back(*NSI);
664   }
665
666   Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
667
668   Config.DeterministicArchives = InputArgs.hasFlag(
669       OBJCOPY_enable_deterministic_archives,
670       OBJCOPY_disable_deterministic_archives, /*default=*/true);
671
672   Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
673
674   if (Config.PreserveDates &&
675       (Config.OutputFilename == "-" || Config.InputFilename == "-"))
676     return createStringError(errc::invalid_argument,
677                              "--preserve-dates requires a file");
678
679   for (auto Arg : InputArgs)
680     if (Arg->getOption().matches(OBJCOPY_set_start)) {
681       auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
682       if (!EAddr)
683         return createStringError(
684             EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
685
686       Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
687     } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
688       auto EIncr = getAsInteger<int64_t>(Arg->getValue());
689       if (!EIncr)
690         return createStringError(EIncr.getError(),
691                                  "bad entry point increment: '%s'",
692                                  Arg->getValue());
693       auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
694                                    : [](uint64_t A) { return A; };
695       Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
696         return Expr(EAddr) + *EIncr;
697       };
698     }
699
700   if (Config.DecompressDebugSections &&
701       Config.CompressionType != DebugCompressionType::None) {
702     return createStringError(
703         errc::invalid_argument,
704         "cannot specify both --compress-debug-sections and "
705         "--decompress-debug-sections");
706   }
707
708   if (Config.DecompressDebugSections && !zlib::isAvailable())
709     return createStringError(
710         errc::invalid_argument,
711         "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
712
713   if (Config.ExtractPartition && Config.ExtractMainPartition)
714     return createStringError(errc::invalid_argument,
715                              "cannot specify --extract-partition together with "
716                              "--extract-main-partition");
717
718   DC.CopyConfigs.push_back(std::move(Config));
719   return std::move(DC);
720 }
721
722 // ParseStripOptions returns the config and sets the input arguments. If a
723 // help flag is set then ParseStripOptions will print the help messege and
724 // exit.
725 Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
726   StripOptTable T;
727   unsigned MissingArgumentIndex, MissingArgumentCount;
728   llvm::opt::InputArgList InputArgs =
729       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
730
731   if (InputArgs.size() == 0) {
732     T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
733     exit(1);
734   }
735
736   if (InputArgs.hasArg(STRIP_help)) {
737     T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
738     exit(0);
739   }
740
741   if (InputArgs.hasArg(STRIP_version)) {
742     outs() << "llvm-strip, compatible with GNU strip\n";
743     cl::PrintVersionMessage();
744     exit(0);
745   }
746
747   SmallVector<StringRef, 2> Positional;
748   for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
749     return createStringError(errc::invalid_argument, "unknown argument '%s'",
750                              Arg->getAsString(InputArgs).c_str());
751   for (auto Arg : InputArgs.filtered(STRIP_INPUT))
752     Positional.push_back(Arg->getValue());
753
754   if (Positional.empty())
755     return createStringError(errc::invalid_argument, "no input file specified");
756
757   if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
758     return createStringError(
759         errc::invalid_argument,
760         "multiple input files cannot be used in combination with -o");
761
762   CopyConfig Config;
763   bool UseRegexp = InputArgs.hasArg(STRIP_regex);
764   Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
765   Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
766
767   if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
768     Config.DiscardMode =
769         InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
770             ? DiscardType::All
771             : DiscardType::Locals;
772   Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
773   if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
774     Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
775   Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
776   Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
777   Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
778
779   for (auto Arg : InputArgs.filtered(STRIP_keep_section))
780     Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
781
782   for (auto Arg : InputArgs.filtered(STRIP_remove_section))
783     Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
784
785   for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
786     Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
787
788   for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
789     Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
790
791   if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
792       !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
793       !Config.StripAllGNU && Config.SymbolsToRemove.empty())
794     Config.StripAll = true;
795
796   if (Config.DiscardMode == DiscardType::All)
797     Config.StripDebug = true;
798
799   Config.DeterministicArchives =
800       InputArgs.hasFlag(STRIP_enable_deterministic_archives,
801                         STRIP_disable_deterministic_archives, /*default=*/true);
802
803   Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
804
805   DriverConfig DC;
806   if (Positional.size() == 1) {
807     Config.InputFilename = Positional[0];
808     Config.OutputFilename =
809         InputArgs.getLastArgValue(STRIP_output, Positional[0]);
810     DC.CopyConfigs.push_back(std::move(Config));
811   } else {
812     for (StringRef Filename : Positional) {
813       Config.InputFilename = Filename;
814       Config.OutputFilename = Filename;
815       DC.CopyConfigs.push_back(Config);
816     }
817   }
818
819   if (Config.PreserveDates && (is_contained(Positional, "-") ||
820                                InputArgs.getLastArgValue(STRIP_output) == "-"))
821     return createStringError(errc::invalid_argument,
822                              "--preserve-dates requires a file");
823
824   return std::move(DC);
825 }
826
827 } // namespace objcopy
828 } // namespace llvm