OSDN Git Service

f379f1aadd1b59a9e1897ab3b591856d736334c0
[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 };
310
311 static Expected<MachineInfo> getOutputFormatMachineInfo(StringRef Format) {
312   StringRef OriginalFormat = Format;
313   bool IsFreeBSD = Format.consume_back("-freebsd");
314   auto Iter = OutputFormatMap.find(Format);
315   if (Iter == std::end(OutputFormatMap))
316     return createStringError(errc::invalid_argument,
317                              "invalid output format: '%s'",
318                              OriginalFormat.str().c_str());
319   MachineInfo MI = Iter->getValue();
320   if (IsFreeBSD)
321     MI.OSABI = ELF::ELFOSABI_FREEBSD;
322   return {MI};
323 }
324
325 static Error addSymbolsFromFile(std::vector<NameOrRegex> &Symbols,
326                                 BumpPtrAllocator &Alloc, StringRef Filename,
327                                 bool UseRegex) {
328   StringSaver Saver(Alloc);
329   SmallVector<StringRef, 16> Lines;
330   auto BufOrErr = MemoryBuffer::getFile(Filename);
331   if (!BufOrErr)
332     return createFileError(Filename, BufOrErr.getError());
333
334   BufOrErr.get()->getBuffer().split(Lines, '\n');
335   for (StringRef Line : Lines) {
336     // Ignore everything after '#', trim whitespace, and only add the symbol if
337     // it's not empty.
338     auto TrimmedLine = Line.split('#').first.trim();
339     if (!TrimmedLine.empty())
340       Symbols.emplace_back(Saver.save(TrimmedLine), UseRegex);
341   }
342
343   return Error::success();
344 }
345
346 NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
347   if (!IsRegex) {
348     Name = Pattern;
349     return;
350   }
351
352   SmallVector<char, 32> Data;
353   R = std::make_shared<Regex>(
354       ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
355 }
356
357 static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
358                                         BumpPtrAllocator &Alloc,
359                                         StringRef Filename) {
360   StringSaver Saver(Alloc);
361   SmallVector<StringRef, 16> Lines;
362   auto BufOrErr = MemoryBuffer::getFile(Filename);
363   if (!BufOrErr)
364     return createFileError(Filename, BufOrErr.getError());
365
366   BufOrErr.get()->getBuffer().split(Lines, '\n');
367   size_t NumLines = Lines.size();
368   for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
369     StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
370     if (TrimmedLine.empty())
371       continue;
372
373     std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
374     StringRef NewName = Pair.second.trim();
375     if (NewName.empty())
376       return createStringError(errc::invalid_argument,
377                                "%s:%zu: missing new symbol name",
378                                Filename.str().c_str(), LineNo + 1);
379     SymbolsToRename.insert({Pair.first, NewName});
380   }
381   return Error::success();
382 }
383
384 template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
385   T Result;
386   if (Val.getAsInteger(0, Result))
387     return errc::invalid_argument;
388   return Result;
389 }
390
391 // ParseObjcopyOptions returns the config and sets the input arguments. If a
392 // help flag is set then ParseObjcopyOptions will print the help messege and
393 // exit.
394 Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
395   DriverConfig DC;
396   ObjcopyOptTable T;
397   unsigned MissingArgumentIndex, MissingArgumentCount;
398   llvm::opt::InputArgList InputArgs =
399       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
400
401   if (InputArgs.size() == 0) {
402     T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
403     exit(1);
404   }
405
406   if (InputArgs.hasArg(OBJCOPY_help)) {
407     T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
408     exit(0);
409   }
410
411   if (InputArgs.hasArg(OBJCOPY_version)) {
412     outs() << "llvm-objcopy, compatible with GNU objcopy\n";
413     cl::PrintVersionMessage();
414     exit(0);
415   }
416
417   SmallVector<const char *, 2> Positional;
418
419   for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
420     return createStringError(errc::invalid_argument, "unknown argument '%s'",
421                              Arg->getAsString(InputArgs).c_str());
422
423   for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
424     Positional.push_back(Arg->getValue());
425
426   if (Positional.empty())
427     return createStringError(errc::invalid_argument, "no input file specified");
428
429   if (Positional.size() > 2)
430     return createStringError(errc::invalid_argument,
431                              "too many positional arguments");
432
433   CopyConfig Config;
434   Config.InputFilename = Positional[0];
435   Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
436   if (InputArgs.hasArg(OBJCOPY_target) &&
437       (InputArgs.hasArg(OBJCOPY_input_target) ||
438        InputArgs.hasArg(OBJCOPY_output_target)))
439     return createStringError(
440         errc::invalid_argument,
441         "--target cannot be used with --input-target or --output-target");
442
443   bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
444   if (InputArgs.hasArg(OBJCOPY_target)) {
445     Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
446     Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
447   } else {
448     Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
449     Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
450   }
451   if (Config.InputFormat == "binary") {
452     auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
453     if (BinaryArch.empty())
454       return createStringError(
455           errc::invalid_argument,
456           "specified binary input without specifiying an architecture");
457     Expected<const MachineInfo &> MI = getMachineInfo(BinaryArch);
458     if (!MI)
459       return MI.takeError();
460     Config.BinaryArch = *MI;
461   }
462   if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary" &&
463       Config.OutputFormat != "ihex") {
464     Expected<MachineInfo> MI = getOutputFormatMachineInfo(Config.OutputFormat);
465     if (!MI)
466       return MI.takeError();
467     Config.OutputArch = *MI;
468   }
469
470   if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
471                                       OBJCOPY_compress_debug_sections_eq)) {
472     Config.CompressionType = DebugCompressionType::Z;
473
474     if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
475       Config.CompressionType =
476           StringSwitch<DebugCompressionType>(
477               InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
478               .Case("zlib-gnu", DebugCompressionType::GNU)
479               .Case("zlib", DebugCompressionType::Z)
480               .Default(DebugCompressionType::None);
481       if (Config.CompressionType == DebugCompressionType::None)
482         return createStringError(
483             errc::invalid_argument,
484             "invalid or unsupported --compress-debug-sections format: %s",
485             InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
486                 .str()
487                 .c_str());
488     }
489     if (!zlib::isAvailable())
490       return createStringError(
491           errc::invalid_argument,
492           "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
493   }
494
495   Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
496   // The gnu_debuglink's target is expected to not change or else its CRC would
497   // become invalidated and get rejected. We can avoid recalculating the
498   // checksum for every target file inside an archive by precomputing the CRC
499   // here. This prevents a significant amount of I/O.
500   if (!Config.AddGnuDebugLink.empty()) {
501     auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
502     if (!DebugOrErr)
503       return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
504     auto Debug = std::move(*DebugOrErr);
505     JamCRC CRC;
506     CRC.update(
507         ArrayRef<char>(Debug->getBuffer().data(), Debug->getBuffer().size()));
508     // The CRC32 value needs to be complemented because the JamCRC doesn't
509     // finalize the CRC32 value.
510     Config.GnuDebugLinkCRC32 = ~CRC.getCRC();
511   }
512   Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
513   if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
514     Config.BuildIdLinkInput =
515         InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
516   if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
517     Config.BuildIdLinkOutput =
518         InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
519   Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
520   Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
521   Config.AllocSectionsPrefix =
522       InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
523   if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
524     Config.ExtractPartition = Arg->getValue();
525
526   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
527     if (!StringRef(Arg->getValue()).contains('='))
528       return createStringError(errc::invalid_argument,
529                                "bad format for --redefine-sym");
530     auto Old2New = StringRef(Arg->getValue()).split('=');
531     if (!Config.SymbolsToRename.insert(Old2New).second)
532       return createStringError(errc::invalid_argument,
533                                "multiple redefinition of symbol '%s'",
534                                Old2New.first.str().c_str());
535   }
536
537   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
538     if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
539                                              Arg->getValue()))
540       return std::move(E);
541
542   for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
543     Expected<SectionRename> SR =
544         parseRenameSectionValue(StringRef(Arg->getValue()));
545     if (!SR)
546       return SR.takeError();
547     if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
548       return createStringError(errc::invalid_argument,
549                                "multiple renames of section '%s'",
550                                SR->OriginalName.str().c_str());
551   }
552   for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
553     Expected<SectionFlagsUpdate> SFU =
554         parseSetSectionFlagValue(Arg->getValue());
555     if (!SFU)
556       return SFU.takeError();
557     if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
558       return createStringError(
559           errc::invalid_argument,
560           "--set-section-flags set multiple times for section '%s'",
561           SFU->Name.str().c_str());
562   }
563   // Prohibit combinations of --set-section-flags when the section name is used
564   // by --rename-section, either as a source or a destination.
565   for (const auto &E : Config.SectionsToRename) {
566     const SectionRename &SR = E.second;
567     if (Config.SetSectionFlags.count(SR.OriginalName))
568       return createStringError(
569           errc::invalid_argument,
570           "--set-section-flags=%s conflicts with --rename-section=%s=%s",
571           SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
572           SR.NewName.str().c_str());
573     if (Config.SetSectionFlags.count(SR.NewName))
574       return createStringError(
575           errc::invalid_argument,
576           "--set-section-flags=%s conflicts with --rename-section=%s=%s",
577           SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
578           SR.NewName.str().c_str());
579   }
580
581   for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
582     Config.ToRemove.emplace_back(Arg->getValue(), UseRegex);
583   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
584     Config.KeepSection.emplace_back(Arg->getValue(), UseRegex);
585   for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
586     Config.OnlySection.emplace_back(Arg->getValue(), UseRegex);
587   for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
588     Config.AddSection.push_back(Arg->getValue());
589   for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
590     Config.DumpSection.push_back(Arg->getValue());
591   Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
592   Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
593   Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
594   Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
595   Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
596   Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
597   Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
598   Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
599   Config.ExtractMainPartition =
600       InputArgs.hasArg(OBJCOPY_extract_main_partition);
601   Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
602   Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
603   if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
604     Config.DiscardMode =
605         InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
606             ? DiscardType::All
607             : DiscardType::Locals;
608   Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
609   Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
610   Config.DecompressDebugSections =
611       InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
612   if (Config.DiscardMode == DiscardType::All)
613     Config.StripDebug = true;
614   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
615     Config.SymbolsToLocalize.emplace_back(Arg->getValue(), UseRegex);
616   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
617     if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
618                                      Arg->getValue(), UseRegex))
619       return std::move(E);
620   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
621     Config.SymbolsToKeepGlobal.emplace_back(Arg->getValue(), UseRegex);
622   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
623     if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
624                                      Arg->getValue(), UseRegex))
625       return std::move(E);
626   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
627     Config.SymbolsToGlobalize.emplace_back(Arg->getValue(), UseRegex);
628   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
629     if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
630                                      Arg->getValue(), UseRegex))
631       return std::move(E);
632   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
633     Config.SymbolsToWeaken.emplace_back(Arg->getValue(), UseRegex);
634   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
635     if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
636                                      Arg->getValue(), UseRegex))
637       return std::move(E);
638   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
639     Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
640   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
641     if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
642                                      Arg->getValue(), UseRegex))
643       return std::move(E);
644   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
645     Config.UnneededSymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
646   for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
647     if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
648                                      Arg->getValue(), UseRegex))
649       return std::move(E);
650   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
651     Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegex);
652   for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
653     if (Error E = addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc,
654                                      Arg->getValue(), UseRegex))
655       return std::move(E);
656   for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
657     Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(Arg->getValue());
658     if (!NSI)
659       return NSI.takeError();
660     Config.SymbolsToAdd.push_back(*NSI);
661   }
662
663   Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
664
665   Config.DeterministicArchives = InputArgs.hasFlag(
666       OBJCOPY_enable_deterministic_archives,
667       OBJCOPY_disable_deterministic_archives, /*default=*/true);
668
669   Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
670
671   if (Config.PreserveDates &&
672       (Config.OutputFilename == "-" || Config.InputFilename == "-"))
673     return createStringError(errc::invalid_argument,
674                              "--preserve-dates requires a file");
675
676   for (auto Arg : InputArgs)
677     if (Arg->getOption().matches(OBJCOPY_set_start)) {
678       auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
679       if (!EAddr)
680         return createStringError(
681             EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
682
683       Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
684     } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
685       auto EIncr = getAsInteger<int64_t>(Arg->getValue());
686       if (!EIncr)
687         return createStringError(EIncr.getError(),
688                                  "bad entry point increment: '%s'",
689                                  Arg->getValue());
690       auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
691                                    : [](uint64_t A) { return A; };
692       Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
693         return Expr(EAddr) + *EIncr;
694       };
695     }
696
697   if (Config.DecompressDebugSections &&
698       Config.CompressionType != DebugCompressionType::None) {
699     return createStringError(
700         errc::invalid_argument,
701         "cannot specify both --compress-debug-sections and "
702         "--decompress-debug-sections");
703   }
704
705   if (Config.DecompressDebugSections && !zlib::isAvailable())
706     return createStringError(
707         errc::invalid_argument,
708         "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
709
710   if (Config.ExtractPartition && Config.ExtractMainPartition)
711     return createStringError(errc::invalid_argument,
712                              "cannot specify --extract-partition together with "
713                              "--extract-main-partition");
714
715   DC.CopyConfigs.push_back(std::move(Config));
716   return std::move(DC);
717 }
718
719 // ParseStripOptions returns the config and sets the input arguments. If a
720 // help flag is set then ParseStripOptions will print the help messege and
721 // exit.
722 Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
723   StripOptTable T;
724   unsigned MissingArgumentIndex, MissingArgumentCount;
725   llvm::opt::InputArgList InputArgs =
726       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
727
728   if (InputArgs.size() == 0) {
729     T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
730     exit(1);
731   }
732
733   if (InputArgs.hasArg(STRIP_help)) {
734     T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
735     exit(0);
736   }
737
738   if (InputArgs.hasArg(STRIP_version)) {
739     outs() << "llvm-strip, compatible with GNU strip\n";
740     cl::PrintVersionMessage();
741     exit(0);
742   }
743
744   SmallVector<StringRef, 2> Positional;
745   for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
746     return createStringError(errc::invalid_argument, "unknown argument '%s'",
747                              Arg->getAsString(InputArgs).c_str());
748   for (auto Arg : InputArgs.filtered(STRIP_INPUT))
749     Positional.push_back(Arg->getValue());
750
751   if (Positional.empty())
752     return createStringError(errc::invalid_argument, "no input file specified");
753
754   if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
755     return createStringError(
756         errc::invalid_argument,
757         "multiple input files cannot be used in combination with -o");
758
759   CopyConfig Config;
760   bool UseRegexp = InputArgs.hasArg(STRIP_regex);
761   Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
762   Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
763
764   if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
765     Config.DiscardMode =
766         InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
767             ? DiscardType::All
768             : DiscardType::Locals;
769   Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
770   if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
771     Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
772   Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
773   Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
774   Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
775
776   for (auto Arg : InputArgs.filtered(STRIP_keep_section))
777     Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
778
779   for (auto Arg : InputArgs.filtered(STRIP_remove_section))
780     Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
781
782   for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
783     Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
784
785   for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
786     Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
787
788   if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
789       !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
790       !Config.StripAllGNU && Config.SymbolsToRemove.empty())
791     Config.StripAll = true;
792
793   if (Config.DiscardMode == DiscardType::All)
794     Config.StripDebug = true;
795
796   Config.DeterministicArchives =
797       InputArgs.hasFlag(STRIP_enable_deterministic_archives,
798                         STRIP_disable_deterministic_archives, /*default=*/true);
799
800   Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
801
802   DriverConfig DC;
803   if (Positional.size() == 1) {
804     Config.InputFilename = Positional[0];
805     Config.OutputFilename =
806         InputArgs.getLastArgValue(STRIP_output, Positional[0]);
807     DC.CopyConfigs.push_back(std::move(Config));
808   } else {
809     for (StringRef Filename : Positional) {
810       Config.InputFilename = Filename;
811       Config.OutputFilename = Filename;
812       DC.CopyConfigs.push_back(Config);
813     }
814   }
815
816   if (Config.PreserveDates && (is_contained(Positional, "-") ||
817                                InputArgs.getLastArgValue(STRIP_output) == "-"))
818     return createStringError(errc::invalid_argument,
819                              "--preserve-dates requires a file");
820
821   return std::move(DC);
822 }
823
824 } // namespace objcopy
825 } // namespace llvm