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, true}},
267 {"x86-64", {ELF::EM_X86_64, true, true}},
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();
278 // FIXME: consolidate with the bfd parsing used by lld.
279 static const StringMap<MachineInfo> OutputFormatMap{
280 // Name, {EMachine, 64bit, LittleEndian}
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}},
286 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
288 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
290 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
291 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
293 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
294 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
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}},
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}},
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();
320 MI.OSABI = ELF::ELFOSABI_FREEBSD;
324 static Error addSymbolsFromFile(std::vector<NameOrRegex> &Symbols,
325 BumpPtrAllocator &Alloc, StringRef Filename,
327 StringSaver Saver(Alloc);
328 SmallVector<StringRef, 16> Lines;
329 auto BufOrErr = MemoryBuffer::getFile(Filename);
331 return createFileError(Filename, BufOrErr.getError());
333 BufOrErr.get()->getBuffer().split(Lines, '\n');
334 for (StringRef Line : Lines) {
335 // Ignore everything after '#', trim whitespace, and only add the symbol if
337 auto TrimmedLine = Line.split('#').first.trim();
338 if (!TrimmedLine.empty())
339 Symbols.emplace_back(Saver.save(TrimmedLine), UseRegex);
342 return Error::success();
345 NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
351 SmallVector<char, 32> Data;
352 R = std::make_shared<Regex>(
353 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
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);
363 return createFileError(Filename, BufOrErr.getError());
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())
372 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
373 StringRef NewName = Pair.second.trim();
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});
380 return Error::success();
383 template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
385 if (Val.getAsInteger(0, Result))
386 return errc::invalid_argument;
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
393 Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
396 unsigned MissingArgumentIndex, MissingArgumentCount;
397 llvm::opt::InputArgList InputArgs =
398 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
400 if (InputArgs.size() == 0) {
401 T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
405 if (InputArgs.hasArg(OBJCOPY_help)) {
406 T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
410 if (InputArgs.hasArg(OBJCOPY_version)) {
411 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
412 cl::PrintVersionMessage();
416 SmallVector<const char *, 2> Positional;
418 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
419 return createStringError(errc::invalid_argument, "unknown argument '%s'",
420 Arg->getAsString(InputArgs).c_str());
422 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
423 Positional.push_back(Arg->getValue());
425 if (Positional.empty())
426 return createStringError(errc::invalid_argument, "No input file specified");
428 if (Positional.size() > 2)
429 return createStringError(errc::invalid_argument,
430 "Too many positional arguments");
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");
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);
447 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
448 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
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);
458 return MI.takeError();
459 Config.BinaryArch = *MI;
461 if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary" &&
462 Config.OutputFormat != "ihex") {
463 Expected<MachineInfo> MI = getOutputFormatMachineInfo(Config.OutputFormat);
465 return MI.takeError();
466 Config.OutputArch = *MI;
469 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
470 OBJCOPY_compress_debug_sections_eq)) {
471 Config.CompressionType = DebugCompressionType::Z;
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)
488 if (!zlib::isAvailable())
489 return createStringError(
490 errc::invalid_argument,
491 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
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);
502 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
503 auto Debug = std::move(*DebugOrErr);
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();
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();
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());
536 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
537 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
541 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
542 Expected<SectionRename> SR =
543 parseRenameSectionValue(StringRef(Arg->getValue()));
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());
551 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
552 Expected<SectionFlagsUpdate> SFU =
553 parseSetSectionFlagValue(Arg->getValue());
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());
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());
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))
604 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
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))
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))
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))
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))
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))
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))
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))
655 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
656 Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(Arg->getValue());
658 return NSI.takeError();
659 Config.SymbolsToAdd.push_back(*NSI);
662 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
664 Config.DeterministicArchives = InputArgs.hasFlag(
665 OBJCOPY_enable_deterministic_archives,
666 OBJCOPY_disable_deterministic_archives, /*default=*/true);
668 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
670 for (auto Arg : InputArgs)
671 if (Arg->getOption().matches(OBJCOPY_set_start)) {
672 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
674 return createStringError(
675 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
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());
681 return createStringError(EIncr.getError(),
682 "bad entry point increment: '%s'",
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;
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");
699 if (Config.DecompressDebugSections && !zlib::isAvailable())
700 return createStringError(
701 errc::invalid_argument,
702 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
704 if (Config.ExtractPartition && Config.ExtractMainPartition)
705 return createStringError(errc::invalid_argument,
706 "cannot specify --extract-partition together with "
707 "--extract-main-partition");
709 DC.CopyConfigs.push_back(std::move(Config));
710 return std::move(DC);
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
716 Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
718 unsigned MissingArgumentIndex, MissingArgumentCount;
719 llvm::opt::InputArgList InputArgs =
720 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
722 if (InputArgs.size() == 0) {
723 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
727 if (InputArgs.hasArg(STRIP_help)) {
728 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
732 if (InputArgs.hasArg(STRIP_version)) {
733 outs() << "llvm-strip, compatible with GNU strip\n";
734 cl::PrintVersionMessage();
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());
745 if (Positional.empty())
746 return createStringError(errc::invalid_argument, "No input file specified");
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");
754 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
755 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
756 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
758 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
760 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
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);
770 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
771 Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
773 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
774 Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
776 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
777 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
779 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
780 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
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;
787 if (Config.DiscardMode == DiscardType::All)
788 Config.StripDebug = true;
790 Config.DeterministicArchives =
791 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
792 STRIP_disable_deterministic_archives, /*default=*/true);
794 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
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));
803 for (const char *Filename : Positional) {
804 Config.InputFilename = Filename;
805 Config.OutputFilename = Filename;
806 DC.CopyConfigs.push_back(Config);
810 return std::move(DC);
813 } // namespace objcopy