1 //===- CopyConfig.cpp -----------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "CopyConfig.h"
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"
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) \
33 #include "ObjcopyOpts.inc"
37 #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
38 #include "ObjcopyOpts.inc"
41 static const opt::OptTable::Info ObjcopyInfoTable[] = {
42 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
43 HELPTEXT, METAVAR, VALUES) \
49 opt::Option::KIND##Class, \
56 #include "ObjcopyOpts.inc"
60 class ObjcopyOptTable : public opt::OptTable {
62 ObjcopyOptTable() : OptTable(ObjcopyInfoTable) {}
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) \
70 #include "StripOpts.inc"
74 #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
75 #include "StripOpts.inc"
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"
89 class StripOptTable : public opt::OptTable {
91 StripOptTable() : OptTable(StripInfoTable) {}
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);
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",
125 ParsedFlags |= ParsedFlag;
131 static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
132 if (!FlagValue.contains('='))
133 return createStringError(errc::invalid_argument,
134 "bad format for --rename-section: missing '='");
136 // Initial split: ".foo" = ".bar,f1,f2,..."
137 auto Old2New = FlagValue.split('=');
139 SR.OriginalName = Old2New.first;
141 // Flags split: ".bar" "f1" "f2" ...
142 SmallVector<StringRef, 6> NameAndFlags;
143 Old2New.second.split(NameAndFlags, ',');
144 SR.NewName = NameAndFlags[0];
146 if (NameAndFlags.size() > 1) {
147 Expected<SectionFlag> ParsedFlagSet =
148 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
150 return ParsedFlagSet.takeError();
151 SR.NewFlags = *ParsedFlagSet;
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 '='");
163 // Initial split: ".foo" = "f1,f2,..."
164 auto Section2Flags = StringRef(FlagValue).split('=');
165 SectionFlagsUpdate SFU;
166 SFU.Name = Section2Flags.first;
168 // Flags split: "f1" "f2" ...
169 SmallVector<StringRef, 6> SectionFlags;
170 Section2Flags.second.split(SectionFlags, ',');
171 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
173 return ParsedFlagSet.takeError();
174 SFU.NewFlags = *ParsedFlagSet;
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:
183 // <name>=[<section>:]<value>[,<flags>]
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
190 // <flags> - optional flags affecting symbol type, binding or visibility:
191 // The following are currently supported:
193 // global, local, weak, default, hidden, file, section, object,
194 // indirect-function.
196 // The following flags are ignored and provided for GNU
197 // compatibility only:
199 // warning, debug, constructor, indirect, synthetic,
200 // unique-object, before=<symbol>.
203 std::tie(SI.SymbolName, Value) = FlagValue.split('=');
205 return createStringError(
206 errc::invalid_argument,
207 "bad format for --add-symbol, missing '=' after '%s'",
208 SI.SymbolName.str().c_str());
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");
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());
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());
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}},
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();
279 // FIXME: consolidate with the bfd parsing used by lld.
280 static const StringMap<MachineInfo> OutputFormatMap{
281 // Name, {EMachine, 64bit, LittleEndian}
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}},
287 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
289 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
291 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
292 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
294 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
295 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
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}},
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}},
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();
321 MI.OSABI = ELF::ELFOSABI_FREEBSD;
325 static Error addSymbolsFromFile(std::vector<NameOrRegex> &Symbols,
326 BumpPtrAllocator &Alloc, StringRef Filename,
328 StringSaver Saver(Alloc);
329 SmallVector<StringRef, 16> Lines;
330 auto BufOrErr = MemoryBuffer::getFile(Filename);
332 return createFileError(Filename, BufOrErr.getError());
334 BufOrErr.get()->getBuffer().split(Lines, '\n');
335 for (StringRef Line : Lines) {
336 // Ignore everything after '#', trim whitespace, and only add the symbol if
338 auto TrimmedLine = Line.split('#').first.trim();
339 if (!TrimmedLine.empty())
340 Symbols.emplace_back(Saver.save(TrimmedLine), UseRegex);
343 return Error::success();
346 NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
352 SmallVector<char, 32> Data;
353 R = std::make_shared<Regex>(
354 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
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);
364 return createFileError(Filename, BufOrErr.getError());
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())
373 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
374 StringRef NewName = Pair.second.trim();
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});
381 return Error::success();
384 template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
386 if (Val.getAsInteger(0, Result))
387 return errc::invalid_argument;
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
394 Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
397 unsigned MissingArgumentIndex, MissingArgumentCount;
398 llvm::opt::InputArgList InputArgs =
399 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
401 if (InputArgs.size() == 0) {
402 T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
406 if (InputArgs.hasArg(OBJCOPY_help)) {
407 T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
411 if (InputArgs.hasArg(OBJCOPY_version)) {
412 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
413 cl::PrintVersionMessage();
417 SmallVector<const char *, 2> Positional;
419 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
420 return createStringError(errc::invalid_argument, "unknown argument '%s'",
421 Arg->getAsString(InputArgs).c_str());
423 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
424 Positional.push_back(Arg->getValue());
426 if (Positional.empty())
427 return createStringError(errc::invalid_argument, "no input file specified");
429 if (Positional.size() > 2)
430 return createStringError(errc::invalid_argument,
431 "too many positional arguments");
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");
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);
448 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
449 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
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);
459 return MI.takeError();
460 Config.BinaryArch = *MI;
462 if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary" &&
463 Config.OutputFormat != "ihex") {
464 Expected<MachineInfo> MI = getOutputFormatMachineInfo(Config.OutputFormat);
466 return MI.takeError();
467 Config.OutputArch = *MI;
470 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
471 OBJCOPY_compress_debug_sections_eq)) {
472 Config.CompressionType = DebugCompressionType::Z;
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)
489 if (!zlib::isAvailable())
490 return createStringError(
491 errc::invalid_argument,
492 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
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);
503 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
504 auto Debug = std::move(*DebugOrErr);
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();
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();
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());
537 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
538 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
542 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
543 Expected<SectionRename> SR =
544 parseRenameSectionValue(StringRef(Arg->getValue()));
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());
552 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
553 Expected<SectionFlagsUpdate> SFU =
554 parseSetSectionFlagValue(Arg->getValue());
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());
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());
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))
605 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
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))
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))
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))
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))
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))
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))
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))
656 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
657 Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(Arg->getValue());
659 return NSI.takeError();
660 Config.SymbolsToAdd.push_back(*NSI);
663 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
665 Config.DeterministicArchives = InputArgs.hasFlag(
666 OBJCOPY_enable_deterministic_archives,
667 OBJCOPY_disable_deterministic_archives, /*default=*/true);
669 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
671 if (Config.PreserveDates &&
672 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
673 return createStringError(errc::invalid_argument,
674 "--preserve-dates requires a file");
676 for (auto Arg : InputArgs)
677 if (Arg->getOption().matches(OBJCOPY_set_start)) {
678 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
680 return createStringError(
681 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
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());
687 return createStringError(EIncr.getError(),
688 "bad entry point increment: '%s'",
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;
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");
705 if (Config.DecompressDebugSections && !zlib::isAvailable())
706 return createStringError(
707 errc::invalid_argument,
708 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
710 if (Config.ExtractPartition && Config.ExtractMainPartition)
711 return createStringError(errc::invalid_argument,
712 "cannot specify --extract-partition together with "
713 "--extract-main-partition");
715 DC.CopyConfigs.push_back(std::move(Config));
716 return std::move(DC);
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
722 Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
724 unsigned MissingArgumentIndex, MissingArgumentCount;
725 llvm::opt::InputArgList InputArgs =
726 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
728 if (InputArgs.size() == 0) {
729 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
733 if (InputArgs.hasArg(STRIP_help)) {
734 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
738 if (InputArgs.hasArg(STRIP_version)) {
739 outs() << "llvm-strip, compatible with GNU strip\n";
740 cl::PrintVersionMessage();
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());
751 if (Positional.empty())
752 return createStringError(errc::invalid_argument, "no input file specified");
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");
760 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
761 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
762 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
764 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
766 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
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);
776 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
777 Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
779 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
780 Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
782 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
783 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
785 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
786 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
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;
793 if (Config.DiscardMode == DiscardType::All)
794 Config.StripDebug = true;
796 Config.DeterministicArchives =
797 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
798 STRIP_disable_deterministic_archives, /*default=*/true);
800 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
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));
809 for (StringRef Filename : Positional) {
810 Config.InputFilename = Filename;
811 Config.OutputFilename = Filename;
812 DC.CopyConfigs.push_back(Config);
816 if (Config.PreserveDates && (is_contained(Positional, "-") ||
817 InputArgs.getLastArgValue(STRIP_output) == "-"))
818 return createStringError(errc::invalid_argument,
819 "--preserve-dates requires a file");
821 return std::move(DC);
824 } // namespace objcopy