OSDN Git Service

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