[MIParser] Set RegClassOrRegBank during instruction parsing
[llvm-complete.git] / tools / llvm-objcopy / CopyConfig.cpp
blobd707bec20c494782b6403eadde597eb39be48031
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 //===----------------------------------------------------------------------===//
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/ADT/StringSet.h"
15 #include "llvm/Option/Arg.h"
16 #include "llvm/Option/ArgList.h"
17 #include "llvm/Support/CRC.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Compression.h"
20 #include "llvm/Support/Errc.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/StringSaver.h"
23 #include <memory>
25 namespace llvm {
26 namespace objcopy {
28 namespace {
29 enum ObjcopyID {
30 OBJCOPY_INVALID = 0, // This is not an option ID.
31 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
32 HELPTEXT, METAVAR, VALUES) \
33 OBJCOPY_##ID,
34 #include "ObjcopyOpts.inc"
35 #undef OPTION
38 #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
39 #include "ObjcopyOpts.inc"
40 #undef PREFIX
42 static const opt::OptTable::Info ObjcopyInfoTable[] = {
43 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
44 HELPTEXT, METAVAR, VALUES) \
45 {OBJCOPY_##PREFIX, \
46 NAME, \
47 HELPTEXT, \
48 METAVAR, \
49 OBJCOPY_##ID, \
50 opt::Option::KIND##Class, \
51 PARAM, \
52 FLAGS, \
53 OBJCOPY_##GROUP, \
54 OBJCOPY_##ALIAS, \
55 ALIASARGS, \
56 VALUES},
57 #include "ObjcopyOpts.inc"
58 #undef OPTION
61 class ObjcopyOptTable : public opt::OptTable {
62 public:
63 ObjcopyOptTable() : OptTable(ObjcopyInfoTable) {}
66 enum StripID {
67 STRIP_INVALID = 0, // This is not an option ID.
68 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
69 HELPTEXT, METAVAR, VALUES) \
70 STRIP_##ID,
71 #include "StripOpts.inc"
72 #undef OPTION
75 #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
76 #include "StripOpts.inc"
77 #undef PREFIX
79 static const opt::OptTable::Info StripInfoTable[] = {
80 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
81 HELPTEXT, METAVAR, VALUES) \
82 {STRIP_##PREFIX, NAME, HELPTEXT, \
83 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
84 PARAM, FLAGS, STRIP_##GROUP, \
85 STRIP_##ALIAS, ALIASARGS, VALUES},
86 #include "StripOpts.inc"
87 #undef OPTION
90 class StripOptTable : public opt::OptTable {
91 public:
92 StripOptTable() : OptTable(StripInfoTable) {}
95 } // namespace
97 static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
98 return llvm::StringSwitch<SectionFlag>(SectionName)
99 .CaseLower("alloc", SectionFlag::SecAlloc)
100 .CaseLower("load", SectionFlag::SecLoad)
101 .CaseLower("noload", SectionFlag::SecNoload)
102 .CaseLower("readonly", SectionFlag::SecReadonly)
103 .CaseLower("debug", SectionFlag::SecDebug)
104 .CaseLower("code", SectionFlag::SecCode)
105 .CaseLower("data", SectionFlag::SecData)
106 .CaseLower("rom", SectionFlag::SecRom)
107 .CaseLower("merge", SectionFlag::SecMerge)
108 .CaseLower("strings", SectionFlag::SecStrings)
109 .CaseLower("contents", SectionFlag::SecContents)
110 .CaseLower("share", SectionFlag::SecShare)
111 .Default(SectionFlag::SecNone);
114 static Expected<SectionFlag>
115 parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
116 SectionFlag ParsedFlags = SectionFlag::SecNone;
117 for (StringRef Flag : SectionFlags) {
118 SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
119 if (ParsedFlag == SectionFlag::SecNone)
120 return createStringError(
121 errc::invalid_argument,
122 "unrecognized section flag '%s'. Flags supported for GNU "
123 "compatibility: alloc, load, noload, readonly, debug, code, data, "
124 "rom, share, contents, merge, strings",
125 Flag.str().c_str());
126 ParsedFlags |= ParsedFlag;
129 return ParsedFlags;
132 static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
133 if (!FlagValue.contains('='))
134 return createStringError(errc::invalid_argument,
135 "bad format for --rename-section: missing '='");
137 // Initial split: ".foo" = ".bar,f1,f2,..."
138 auto Old2New = FlagValue.split('=');
139 SectionRename SR;
140 SR.OriginalName = Old2New.first;
142 // Flags split: ".bar" "f1" "f2" ...
143 SmallVector<StringRef, 6> NameAndFlags;
144 Old2New.second.split(NameAndFlags, ',');
145 SR.NewName = NameAndFlags[0];
147 if (NameAndFlags.size() > 1) {
148 Expected<SectionFlag> ParsedFlagSet =
149 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
150 if (!ParsedFlagSet)
151 return ParsedFlagSet.takeError();
152 SR.NewFlags = *ParsedFlagSet;
155 return SR;
158 static Expected<std::pair<StringRef, uint64_t>>
159 parseSetSectionAlignment(StringRef FlagValue) {
160 if (!FlagValue.contains('='))
161 return createStringError(
162 errc::invalid_argument,
163 "bad format for --set-section-alignment: missing '='");
164 auto Split = StringRef(FlagValue).split('=');
165 if (Split.first.empty())
166 return createStringError(
167 errc::invalid_argument,
168 "bad format for --set-section-alignment: missing section name");
169 uint64_t NewAlign;
170 if (Split.second.getAsInteger(0, NewAlign))
171 return createStringError(errc::invalid_argument,
172 "invalid alignment for --set-section-alignment: '%s'",
173 Split.second.str().c_str());
174 return std::make_pair(Split.first, NewAlign);
177 static Expected<SectionFlagsUpdate>
178 parseSetSectionFlagValue(StringRef FlagValue) {
179 if (!StringRef(FlagValue).contains('='))
180 return createStringError(errc::invalid_argument,
181 "bad format for --set-section-flags: missing '='");
183 // Initial split: ".foo" = "f1,f2,..."
184 auto Section2Flags = StringRef(FlagValue).split('=');
185 SectionFlagsUpdate SFU;
186 SFU.Name = Section2Flags.first;
188 // Flags split: "f1" "f2" ...
189 SmallVector<StringRef, 6> SectionFlags;
190 Section2Flags.second.split(SectionFlags, ',');
191 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
192 if (!ParsedFlagSet)
193 return ParsedFlagSet.takeError();
194 SFU.NewFlags = *ParsedFlagSet;
196 return SFU;
199 struct TargetInfo {
200 FileFormat Format;
201 MachineInfo Machine;
204 // FIXME: consolidate with the bfd parsing used by lld.
205 static const StringMap<MachineInfo> TargetMap{
206 // Name, {EMachine, 64bit, LittleEndian}
207 // x86
208 {"elf32-i386", {ELF::EM_386, false, true}},
209 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
210 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
211 // Intel MCU
212 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
213 // ARM
214 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
215 // ARM AArch64
216 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
217 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
218 // RISC-V
219 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
220 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
221 // PowerPC
222 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
223 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
224 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
225 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
226 // MIPS
227 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
228 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
229 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
230 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
231 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
232 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
233 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
234 // SPARC
235 {"elf32-sparc", {ELF::EM_SPARC, false, false}},
236 {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
239 static Expected<TargetInfo>
240 getOutputTargetInfoByTargetName(StringRef TargetName) {
241 StringRef OriginalTargetName = TargetName;
242 bool IsFreeBSD = TargetName.consume_back("-freebsd");
243 auto Iter = TargetMap.find(TargetName);
244 if (Iter == std::end(TargetMap))
245 return createStringError(errc::invalid_argument,
246 "invalid output format: '%s'",
247 OriginalTargetName.str().c_str());
248 MachineInfo MI = Iter->getValue();
249 if (IsFreeBSD)
250 MI.OSABI = ELF::ELFOSABI_FREEBSD;
252 FileFormat Format;
253 if (TargetName.startswith("elf"))
254 Format = FileFormat::ELF;
255 else
256 // This should never happen because `TargetName` is valid (it certainly
257 // exists in the TargetMap).
258 llvm_unreachable("unknown target prefix");
260 return {TargetInfo{Format, MI}};
263 static Error
264 addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
265 StringRef Filename, MatchStyle MS,
266 llvm::function_ref<Error(Error)> ErrorCallback) {
267 StringSaver Saver(Alloc);
268 SmallVector<StringRef, 16> Lines;
269 auto BufOrErr = MemoryBuffer::getFile(Filename);
270 if (!BufOrErr)
271 return createFileError(Filename, BufOrErr.getError());
273 BufOrErr.get()->getBuffer().split(Lines, '\n');
274 for (StringRef Line : Lines) {
275 // Ignore everything after '#', trim whitespace, and only add the symbol if
276 // it's not empty.
277 auto TrimmedLine = Line.split('#').first.trim();
278 if (!TrimmedLine.empty())
279 if (Error E = Symbols.addMatcher(NameOrPattern::create(
280 Saver.save(TrimmedLine), MS, ErrorCallback)))
281 return E;
284 return Error::success();
287 Expected<NameOrPattern>
288 NameOrPattern::create(StringRef Pattern, MatchStyle MS,
289 llvm::function_ref<Error(Error)> ErrorCallback) {
290 switch (MS) {
291 case MatchStyle::Literal:
292 return NameOrPattern(Pattern);
293 case MatchStyle::Wildcard: {
294 SmallVector<char, 32> Data;
295 bool IsPositiveMatch = true;
296 if (Pattern[0] == '!') {
297 IsPositiveMatch = false;
298 Pattern = Pattern.drop_front();
300 Expected<GlobPattern> GlobOrErr = GlobPattern::create(Pattern);
302 // If we couldn't create it as a glob, report the error, but try again with
303 // a literal if the error reporting is non-fatal.
304 if (!GlobOrErr) {
305 if (Error E = ErrorCallback(GlobOrErr.takeError()))
306 return std::move(E);
307 return create(Pattern, MatchStyle::Literal, ErrorCallback);
310 return NameOrPattern(std::make_shared<GlobPattern>(*GlobOrErr),
311 IsPositiveMatch);
313 case MatchStyle::Regex: {
314 SmallVector<char, 32> Data;
315 return NameOrPattern(std::make_shared<Regex>(
316 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data)));
319 llvm_unreachable("Unhandled llvm.objcopy.MatchStyle enum");
322 static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
323 BumpPtrAllocator &Alloc,
324 StringRef Filename) {
325 StringSaver Saver(Alloc);
326 SmallVector<StringRef, 16> Lines;
327 auto BufOrErr = MemoryBuffer::getFile(Filename);
328 if (!BufOrErr)
329 return createFileError(Filename, BufOrErr.getError());
331 BufOrErr.get()->getBuffer().split(Lines, '\n');
332 size_t NumLines = Lines.size();
333 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
334 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
335 if (TrimmedLine.empty())
336 continue;
338 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
339 StringRef NewName = Pair.second.trim();
340 if (NewName.empty())
341 return createStringError(errc::invalid_argument,
342 "%s:%zu: missing new symbol name",
343 Filename.str().c_str(), LineNo + 1);
344 SymbolsToRename.insert({Pair.first, NewName});
346 return Error::success();
349 template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
350 T Result;
351 if (Val.getAsInteger(0, Result))
352 return errc::invalid_argument;
353 return Result;
356 static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
357 StringRef ToolName) {
358 OptTable.PrintHelp(OS, (ToolName + " input [output]").str().c_str(),
359 (ToolName + " tool").str().c_str());
360 // TODO: Replace this with libOption call once it adds extrahelp support.
361 // The CommandLine library has a cl::extrahelp class to support this,
362 // but libOption does not have that yet.
363 OS << "\nPass @FILE as argument to read options from FILE.\n";
366 // ParseObjcopyOptions returns the config and sets the input arguments. If a
367 // help flag is set then ParseObjcopyOptions will print the help messege and
368 // exit.
369 Expected<DriverConfig>
370 parseObjcopyOptions(ArrayRef<const char *> ArgsArr,
371 llvm::function_ref<Error(Error)> ErrorCallback) {
372 DriverConfig DC;
373 ObjcopyOptTable T;
374 unsigned MissingArgumentIndex, MissingArgumentCount;
375 llvm::opt::InputArgList InputArgs =
376 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
378 if (InputArgs.size() == 0) {
379 printHelp(T, errs(), "llvm-objcopy");
380 exit(1);
383 if (InputArgs.hasArg(OBJCOPY_help)) {
384 printHelp(T, outs(), "llvm-objcopy");
385 exit(0);
388 if (InputArgs.hasArg(OBJCOPY_version)) {
389 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
390 cl::PrintVersionMessage();
391 exit(0);
394 SmallVector<const char *, 2> Positional;
396 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
397 return createStringError(errc::invalid_argument, "unknown argument '%s'",
398 Arg->getAsString(InputArgs).c_str());
400 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
401 Positional.push_back(Arg->getValue());
403 if (Positional.empty())
404 return createStringError(errc::invalid_argument, "no input file specified");
406 if (Positional.size() > 2)
407 return createStringError(errc::invalid_argument,
408 "too many positional arguments");
410 CopyConfig Config;
411 Config.InputFilename = Positional[0];
412 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
413 if (InputArgs.hasArg(OBJCOPY_target) &&
414 (InputArgs.hasArg(OBJCOPY_input_target) ||
415 InputArgs.hasArg(OBJCOPY_output_target)))
416 return createStringError(
417 errc::invalid_argument,
418 "--target cannot be used with --input-target or --output-target");
420 if (InputArgs.hasArg(OBJCOPY_regex) && InputArgs.hasArg(OBJCOPY_wildcard))
421 return createStringError(errc::invalid_argument,
422 "--regex and --wildcard are incompatible");
424 MatchStyle SectionMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
425 ? MatchStyle::Regex
426 : MatchStyle::Wildcard;
427 MatchStyle SymbolMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
428 ? MatchStyle::Regex
429 : InputArgs.hasArg(OBJCOPY_wildcard)
430 ? MatchStyle::Wildcard
431 : MatchStyle::Literal;
432 StringRef InputFormat, OutputFormat;
433 if (InputArgs.hasArg(OBJCOPY_target)) {
434 InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
435 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
436 } else {
437 InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
438 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
441 // FIXME: Currently, we ignore the target for non-binary/ihex formats
442 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
443 // format by llvm::object::createBinary regardless of the option value.
444 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
445 .Case("binary", FileFormat::Binary)
446 .Case("ihex", FileFormat::IHex)
447 .Default(FileFormat::Unspecified);
449 if (InputArgs.hasArg(OBJCOPY_new_symbol_visibility))
450 Config.NewSymbolVisibility =
451 InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility);
453 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
454 .Case("binary", FileFormat::Binary)
455 .Case("ihex", FileFormat::IHex)
456 .Default(FileFormat::Unspecified);
457 if (Config.OutputFormat == FileFormat::Unspecified) {
458 if (OutputFormat.empty()) {
459 Config.OutputFormat = Config.InputFormat;
460 } else {
461 Expected<TargetInfo> Target =
462 getOutputTargetInfoByTargetName(OutputFormat);
463 if (!Target)
464 return Target.takeError();
465 Config.OutputFormat = Target->Format;
466 Config.OutputArch = Target->Machine;
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)
486 .str()
487 .c_str());
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);
502 if (!DebugOrErr)
503 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
504 auto Debug = std::move(*DebugOrErr);
505 Config.GnuDebugLinkCRC32 =
506 llvm::crc32(arrayRefFromStringRef(Debug->getBuffer()));
508 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
509 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
510 Config.BuildIdLinkInput =
511 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
512 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
513 Config.BuildIdLinkOutput =
514 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
515 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
516 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
517 Config.AllocSectionsPrefix =
518 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
519 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
520 Config.ExtractPartition = Arg->getValue();
522 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
523 if (!StringRef(Arg->getValue()).contains('='))
524 return createStringError(errc::invalid_argument,
525 "bad format for --redefine-sym");
526 auto Old2New = StringRef(Arg->getValue()).split('=');
527 if (!Config.SymbolsToRename.insert(Old2New).second)
528 return createStringError(errc::invalid_argument,
529 "multiple redefinition of symbol '%s'",
530 Old2New.first.str().c_str());
533 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
534 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
535 Arg->getValue()))
536 return std::move(E);
538 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
539 Expected<SectionRename> SR =
540 parseRenameSectionValue(StringRef(Arg->getValue()));
541 if (!SR)
542 return SR.takeError();
543 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
544 return createStringError(errc::invalid_argument,
545 "multiple renames of section '%s'",
546 SR->OriginalName.str().c_str());
548 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_alignment)) {
549 Expected<std::pair<StringRef, uint64_t>> NameAndAlign =
550 parseSetSectionAlignment(Arg->getValue());
551 if (!NameAndAlign)
552 return NameAndAlign.takeError();
553 Config.SetSectionAlignment[NameAndAlign->first] = NameAndAlign->second;
555 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
556 Expected<SectionFlagsUpdate> SFU =
557 parseSetSectionFlagValue(Arg->getValue());
558 if (!SFU)
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 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
586 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
587 return std::move(E);
588 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
589 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
590 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
591 return std::move(E);
592 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
593 if (Error E = Config.OnlySection.addMatcher(NameOrPattern::create(
594 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
595 return std::move(E);
596 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
597 StringRef ArgValue(Arg->getValue());
598 if (!ArgValue.contains('='))
599 return createStringError(errc::invalid_argument,
600 "bad format for --add-section: missing '='");
601 if (ArgValue.split("=").second.empty())
602 return createStringError(
603 errc::invalid_argument,
604 "bad format for --add-section: missing file name");
605 Config.AddSection.push_back(ArgValue);
607 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
608 Config.DumpSection.push_back(Arg->getValue());
609 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
610 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
611 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
612 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
613 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
614 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
615 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
616 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
617 Config.ExtractMainPartition =
618 InputArgs.hasArg(OBJCOPY_extract_main_partition);
619 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
620 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
621 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
622 Config.DiscardMode =
623 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
624 ? DiscardType::All
625 : DiscardType::Locals;
626 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
627 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
628 Config.DecompressDebugSections =
629 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
630 if (Config.DiscardMode == DiscardType::All)
631 Config.StripDebug = true;
632 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
633 if (Error E = Config.SymbolsToLocalize.addMatcher(NameOrPattern::create(
634 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
635 return std::move(E);
636 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
637 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
638 Arg->getValue(), SymbolMatchStyle,
639 ErrorCallback))
640 return std::move(E);
641 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
642 if (Error E = Config.SymbolsToKeepGlobal.addMatcher(NameOrPattern::create(
643 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
644 return std::move(E);
645 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
646 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
647 Arg->getValue(), SymbolMatchStyle,
648 ErrorCallback))
649 return std::move(E);
650 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
651 if (Error E = Config.SymbolsToGlobalize.addMatcher(NameOrPattern::create(
652 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
653 return std::move(E);
654 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
655 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
656 Arg->getValue(), SymbolMatchStyle,
657 ErrorCallback))
658 return std::move(E);
659 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
660 if (Error E = Config.SymbolsToWeaken.addMatcher(NameOrPattern::create(
661 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
662 return std::move(E);
663 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
664 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
665 Arg->getValue(), SymbolMatchStyle,
666 ErrorCallback))
667 return std::move(E);
668 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
669 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
670 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
671 return std::move(E);
672 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
673 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
674 Arg->getValue(), SymbolMatchStyle,
675 ErrorCallback))
676 return std::move(E);
677 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
678 if (Error E =
679 Config.UnneededSymbolsToRemove.addMatcher(NameOrPattern::create(
680 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
681 return std::move(E);
682 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
683 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
684 Arg->getValue(), SymbolMatchStyle,
685 ErrorCallback))
686 return std::move(E);
687 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
688 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
689 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
690 return std::move(E);
691 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
692 if (Error E =
693 addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc, Arg->getValue(),
694 SymbolMatchStyle, ErrorCallback))
695 return std::move(E);
696 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol))
697 Config.SymbolsToAdd.push_back(Arg->getValue());
699 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
701 Config.DeterministicArchives = InputArgs.hasFlag(
702 OBJCOPY_enable_deterministic_archives,
703 OBJCOPY_disable_deterministic_archives, /*default=*/true);
705 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
707 if (Config.PreserveDates &&
708 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
709 return createStringError(errc::invalid_argument,
710 "--preserve-dates requires a file");
712 for (auto Arg : InputArgs)
713 if (Arg->getOption().matches(OBJCOPY_set_start)) {
714 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
715 if (!EAddr)
716 return createStringError(
717 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
719 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
720 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
721 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
722 if (!EIncr)
723 return createStringError(EIncr.getError(),
724 "bad entry point increment: '%s'",
725 Arg->getValue());
726 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
727 : [](uint64_t A) { return A; };
728 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
729 return Expr(EAddr) + *EIncr;
733 if (Config.DecompressDebugSections &&
734 Config.CompressionType != DebugCompressionType::None) {
735 return createStringError(
736 errc::invalid_argument,
737 "cannot specify both --compress-debug-sections and "
738 "--decompress-debug-sections");
741 if (Config.DecompressDebugSections && !zlib::isAvailable())
742 return createStringError(
743 errc::invalid_argument,
744 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
746 if (Config.ExtractPartition && Config.ExtractMainPartition)
747 return createStringError(errc::invalid_argument,
748 "cannot specify --extract-partition together with "
749 "--extract-main-partition");
751 DC.CopyConfigs.push_back(std::move(Config));
752 return std::move(DC);
755 // ParseStripOptions returns the config and sets the input arguments. If a
756 // help flag is set then ParseStripOptions will print the help messege and
757 // exit.
758 Expected<DriverConfig>
759 parseStripOptions(ArrayRef<const char *> ArgsArr,
760 llvm::function_ref<Error(Error)> ErrorCallback) {
761 StripOptTable T;
762 unsigned MissingArgumentIndex, MissingArgumentCount;
763 llvm::opt::InputArgList InputArgs =
764 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
766 if (InputArgs.size() == 0) {
767 printHelp(T, errs(), "llvm-strip");
768 exit(1);
771 if (InputArgs.hasArg(STRIP_help)) {
772 printHelp(T, outs(), "llvm-strip");
773 exit(0);
776 if (InputArgs.hasArg(STRIP_version)) {
777 outs() << "llvm-strip, compatible with GNU strip\n";
778 cl::PrintVersionMessage();
779 exit(0);
782 SmallVector<StringRef, 2> Positional;
783 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
784 return createStringError(errc::invalid_argument, "unknown argument '%s'",
785 Arg->getAsString(InputArgs).c_str());
786 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
787 Positional.push_back(Arg->getValue());
789 if (Positional.empty())
790 return createStringError(errc::invalid_argument, "no input file specified");
792 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
793 return createStringError(
794 errc::invalid_argument,
795 "multiple input files cannot be used in combination with -o");
797 CopyConfig Config;
799 if (InputArgs.hasArg(STRIP_regex) && InputArgs.hasArg(STRIP_wildcard))
800 return createStringError(errc::invalid_argument,
801 "--regex and --wildcard are incompatible");
802 MatchStyle SectionMatchStyle =
803 InputArgs.hasArg(STRIP_regex) ? MatchStyle::Regex : MatchStyle::Wildcard;
804 MatchStyle SymbolMatchStyle = InputArgs.hasArg(STRIP_regex)
805 ? MatchStyle::Regex
806 : InputArgs.hasArg(STRIP_wildcard)
807 ? MatchStyle::Wildcard
808 : MatchStyle::Literal;
809 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
810 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
812 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
813 Config.DiscardMode =
814 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
815 ? DiscardType::All
816 : DiscardType::Locals;
817 Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
818 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
819 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
820 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
821 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
822 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
823 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
825 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
826 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
827 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
828 return std::move(E);
830 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
831 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
832 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
833 return std::move(E);
835 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
836 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
837 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
838 return std::move(E);
840 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
841 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
842 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
843 return std::move(E);
845 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
846 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
847 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
848 Config.StripAll = true;
850 if (Config.DiscardMode == DiscardType::All)
851 Config.StripDebug = true;
853 Config.DeterministicArchives =
854 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
855 STRIP_disable_deterministic_archives, /*default=*/true);
857 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
858 Config.InputFormat = FileFormat::Unspecified;
859 Config.OutputFormat = FileFormat::Unspecified;
861 DriverConfig DC;
862 if (Positional.size() == 1) {
863 Config.InputFilename = Positional[0];
864 Config.OutputFilename =
865 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
866 DC.CopyConfigs.push_back(std::move(Config));
867 } else {
868 StringMap<unsigned> InputFiles;
869 for (StringRef Filename : Positional) {
870 if (InputFiles[Filename]++ == 1) {
871 if (Filename == "-")
872 return createStringError(
873 errc::invalid_argument,
874 "cannot specify '-' as an input file more than once");
875 if (Error E = ErrorCallback(createStringError(
876 errc::invalid_argument, "'%s' was already specified",
877 Filename.str().c_str())))
878 return std::move(E);
880 Config.InputFilename = Filename;
881 Config.OutputFilename = Filename;
882 DC.CopyConfigs.push_back(Config);
886 if (Config.PreserveDates && (is_contained(Positional, "-") ||
887 InputArgs.getLastArgValue(STRIP_output) == "-"))
888 return createStringError(errc::invalid_argument,
889 "--preserve-dates requires a file");
891 return std::move(DC);
894 } // namespace objcopy
895 } // namespace llvm