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