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/ADT/StringSet.h"
15 #include "llvm/Option/Arg.h"
16 #include "llvm/Option/ArgList.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Compression.h"
19 #include "llvm/Support/Errc.h"
20 #include "llvm/Support/JamCRC.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/StringSaver.h"
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) \
34 #include "ObjcopyOpts.inc"
38 #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
39 #include "ObjcopyOpts.inc"
42 static const opt::OptTable::Info ObjcopyInfoTable
[] = {
43 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
44 HELPTEXT, METAVAR, VALUES) \
50 opt::Option::KIND##Class, \
57 #include "ObjcopyOpts.inc"
61 class ObjcopyOptTable
: public opt::OptTable
{
63 ObjcopyOptTable() : OptTable(ObjcopyInfoTable
) {}
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) \
71 #include "StripOpts.inc"
75 #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
76 #include "StripOpts.inc"
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"
90 class StripOptTable
: public opt::OptTable
{
92 StripOptTable() : OptTable(StripInfoTable
) {}
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",
126 ParsedFlags
|= ParsedFlag
;
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('=');
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());
151 return ParsedFlagSet
.takeError();
152 SR
.NewFlags
= *ParsedFlagSet
;
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");
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
);
193 return ParsedFlagSet
.takeError();
194 SFU
.NewFlags
= *ParsedFlagSet
;
204 // FIXME: consolidate with the bfd parsing used by lld.
205 static const StringMap
<MachineInfo
> TargetMap
{
206 // Name, {EMachine, 64bit, LittleEndian}
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}},
212 {"elf32-iamcu", {ELF::EM_IAMCU
, false, true}},
214 {"elf32-littlearm", {ELF::EM_ARM
, false, true}},
216 {"elf64-aarch64", {ELF::EM_AARCH64
, true, true}},
217 {"elf64-littleaarch64", {ELF::EM_AARCH64
, true, true}},
219 {"elf32-littleriscv", {ELF::EM_RISCV
, false, true}},
220 {"elf64-littleriscv", {ELF::EM_RISCV
, true, true}},
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}},
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}},
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();
250 MI
.OSABI
= ELF::ELFOSABI_FREEBSD
;
253 if (TargetName
.startswith("elf"))
254 Format
= FileFormat::ELF
;
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
addSymbolsFromFile(NameMatcher
&Symbols
, BumpPtrAllocator
&Alloc
,
264 StringRef Filename
, bool UseRegex
) {
265 StringSaver
Saver(Alloc
);
266 SmallVector
<StringRef
, 16> Lines
;
267 auto BufOrErr
= MemoryBuffer::getFile(Filename
);
269 return createFileError(Filename
, BufOrErr
.getError());
271 BufOrErr
.get()->getBuffer().split(Lines
, '\n');
272 for (StringRef Line
: Lines
) {
273 // Ignore everything after '#', trim whitespace, and only add the symbol if
275 auto TrimmedLine
= Line
.split('#').first
.trim();
276 if (!TrimmedLine
.empty())
277 Symbols
.addMatcher({Saver
.save(TrimmedLine
), UseRegex
});
280 return Error::success();
283 NameOrRegex::NameOrRegex(StringRef Pattern
, bool IsRegex
) {
289 SmallVector
<char, 32> Data
;
290 R
= std::make_shared
<Regex
>(
291 ("^" + Pattern
.ltrim('^').rtrim('$') + "$").toStringRef(Data
));
294 static Error
addSymbolsToRenameFromFile(StringMap
<StringRef
> &SymbolsToRename
,
295 BumpPtrAllocator
&Alloc
,
296 StringRef Filename
) {
297 StringSaver
Saver(Alloc
);
298 SmallVector
<StringRef
, 16> Lines
;
299 auto BufOrErr
= MemoryBuffer::getFile(Filename
);
301 return createFileError(Filename
, BufOrErr
.getError());
303 BufOrErr
.get()->getBuffer().split(Lines
, '\n');
304 size_t NumLines
= Lines
.size();
305 for (size_t LineNo
= 0; LineNo
< NumLines
; ++LineNo
) {
306 StringRef TrimmedLine
= Lines
[LineNo
].split('#').first
.trim();
307 if (TrimmedLine
.empty())
310 std::pair
<StringRef
, StringRef
> Pair
= Saver
.save(TrimmedLine
).split(' ');
311 StringRef NewName
= Pair
.second
.trim();
313 return createStringError(errc::invalid_argument
,
314 "%s:%zu: missing new symbol name",
315 Filename
.str().c_str(), LineNo
+ 1);
316 SymbolsToRename
.insert({Pair
.first
, NewName
});
318 return Error::success();
321 template <class T
> static ErrorOr
<T
> getAsInteger(StringRef Val
) {
323 if (Val
.getAsInteger(0, Result
))
324 return errc::invalid_argument
;
328 static void printHelp(const opt::OptTable
&OptTable
, raw_ostream
&OS
,
329 StringRef ToolName
) {
330 OptTable
.PrintHelp(OS
, (ToolName
+ " input [output]").str().c_str(),
331 (ToolName
+ " tool").str().c_str());
332 // TODO: Replace this with libOption call once it adds extrahelp support.
333 // The CommandLine library has a cl::extrahelp class to support this,
334 // but libOption does not have that yet.
335 OS
<< "\nPass @FILE as argument to read options from FILE.\n";
338 // ParseObjcopyOptions returns the config and sets the input arguments. If a
339 // help flag is set then ParseObjcopyOptions will print the help messege and
341 Expected
<DriverConfig
> parseObjcopyOptions(ArrayRef
<const char *> ArgsArr
) {
344 unsigned MissingArgumentIndex
, MissingArgumentCount
;
345 llvm::opt::InputArgList InputArgs
=
346 T
.ParseArgs(ArgsArr
, MissingArgumentIndex
, MissingArgumentCount
);
348 if (InputArgs
.size() == 0) {
349 printHelp(T
, errs(), "llvm-objcopy");
353 if (InputArgs
.hasArg(OBJCOPY_help
)) {
354 printHelp(T
, outs(), "llvm-objcopy");
358 if (InputArgs
.hasArg(OBJCOPY_version
)) {
359 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
360 cl::PrintVersionMessage();
364 SmallVector
<const char *, 2> Positional
;
366 for (auto Arg
: InputArgs
.filtered(OBJCOPY_UNKNOWN
))
367 return createStringError(errc::invalid_argument
, "unknown argument '%s'",
368 Arg
->getAsString(InputArgs
).c_str());
370 for (auto Arg
: InputArgs
.filtered(OBJCOPY_INPUT
))
371 Positional
.push_back(Arg
->getValue());
373 if (Positional
.empty())
374 return createStringError(errc::invalid_argument
, "no input file specified");
376 if (Positional
.size() > 2)
377 return createStringError(errc::invalid_argument
,
378 "too many positional arguments");
381 Config
.InputFilename
= Positional
[0];
382 Config
.OutputFilename
= Positional
[Positional
.size() == 1 ? 0 : 1];
383 if (InputArgs
.hasArg(OBJCOPY_target
) &&
384 (InputArgs
.hasArg(OBJCOPY_input_target
) ||
385 InputArgs
.hasArg(OBJCOPY_output_target
)))
386 return createStringError(
387 errc::invalid_argument
,
388 "--target cannot be used with --input-target or --output-target");
390 bool UseRegex
= InputArgs
.hasArg(OBJCOPY_regex
);
391 StringRef InputFormat
, OutputFormat
;
392 if (InputArgs
.hasArg(OBJCOPY_target
)) {
393 InputFormat
= InputArgs
.getLastArgValue(OBJCOPY_target
);
394 OutputFormat
= InputArgs
.getLastArgValue(OBJCOPY_target
);
396 InputFormat
= InputArgs
.getLastArgValue(OBJCOPY_input_target
);
397 OutputFormat
= InputArgs
.getLastArgValue(OBJCOPY_output_target
);
400 // FIXME: Currently, we ignore the target for non-binary/ihex formats
401 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
402 // format by llvm::object::createBinary regardless of the option value.
403 Config
.InputFormat
= StringSwitch
<FileFormat
>(InputFormat
)
404 .Case("binary", FileFormat::Binary
)
405 .Case("ihex", FileFormat::IHex
)
406 .Default(FileFormat::Unspecified
);
408 if (InputArgs
.hasArg(OBJCOPY_new_symbol_visibility
))
409 Config
.NewSymbolVisibility
=
410 InputArgs
.getLastArgValue(OBJCOPY_new_symbol_visibility
);
412 Config
.OutputFormat
= StringSwitch
<FileFormat
>(OutputFormat
)
413 .Case("binary", FileFormat::Binary
)
414 .Case("ihex", FileFormat::IHex
)
415 .Default(FileFormat::Unspecified
);
416 if (Config
.OutputFormat
== FileFormat::Unspecified
) {
417 if (OutputFormat
.empty()) {
418 Config
.OutputFormat
= Config
.InputFormat
;
420 Expected
<TargetInfo
> Target
=
421 getOutputTargetInfoByTargetName(OutputFormat
);
423 return Target
.takeError();
424 Config
.OutputFormat
= Target
->Format
;
425 Config
.OutputArch
= Target
->Machine
;
429 if (auto Arg
= InputArgs
.getLastArg(OBJCOPY_compress_debug_sections
,
430 OBJCOPY_compress_debug_sections_eq
)) {
431 Config
.CompressionType
= DebugCompressionType::Z
;
433 if (Arg
->getOption().getID() == OBJCOPY_compress_debug_sections_eq
) {
434 Config
.CompressionType
=
435 StringSwitch
<DebugCompressionType
>(
436 InputArgs
.getLastArgValue(OBJCOPY_compress_debug_sections_eq
))
437 .Case("zlib-gnu", DebugCompressionType::GNU
)
438 .Case("zlib", DebugCompressionType::Z
)
439 .Default(DebugCompressionType::None
);
440 if (Config
.CompressionType
== DebugCompressionType::None
)
441 return createStringError(
442 errc::invalid_argument
,
443 "invalid or unsupported --compress-debug-sections format: %s",
444 InputArgs
.getLastArgValue(OBJCOPY_compress_debug_sections_eq
)
448 if (!zlib::isAvailable())
449 return createStringError(
450 errc::invalid_argument
,
451 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
454 Config
.AddGnuDebugLink
= InputArgs
.getLastArgValue(OBJCOPY_add_gnu_debuglink
);
455 // The gnu_debuglink's target is expected to not change or else its CRC would
456 // become invalidated and get rejected. We can avoid recalculating the
457 // checksum for every target file inside an archive by precomputing the CRC
458 // here. This prevents a significant amount of I/O.
459 if (!Config
.AddGnuDebugLink
.empty()) {
460 auto DebugOrErr
= MemoryBuffer::getFile(Config
.AddGnuDebugLink
);
462 return createFileError(Config
.AddGnuDebugLink
, DebugOrErr
.getError());
463 auto Debug
= std::move(*DebugOrErr
);
466 ArrayRef
<char>(Debug
->getBuffer().data(), Debug
->getBuffer().size()));
467 // The CRC32 value needs to be complemented because the JamCRC doesn't
468 // finalize the CRC32 value.
469 Config
.GnuDebugLinkCRC32
= ~CRC
.getCRC();
471 Config
.BuildIdLinkDir
= InputArgs
.getLastArgValue(OBJCOPY_build_id_link_dir
);
472 if (InputArgs
.hasArg(OBJCOPY_build_id_link_input
))
473 Config
.BuildIdLinkInput
=
474 InputArgs
.getLastArgValue(OBJCOPY_build_id_link_input
);
475 if (InputArgs
.hasArg(OBJCOPY_build_id_link_output
))
476 Config
.BuildIdLinkOutput
=
477 InputArgs
.getLastArgValue(OBJCOPY_build_id_link_output
);
478 Config
.SplitDWO
= InputArgs
.getLastArgValue(OBJCOPY_split_dwo
);
479 Config
.SymbolsPrefix
= InputArgs
.getLastArgValue(OBJCOPY_prefix_symbols
);
480 Config
.AllocSectionsPrefix
=
481 InputArgs
.getLastArgValue(OBJCOPY_prefix_alloc_sections
);
482 if (auto Arg
= InputArgs
.getLastArg(OBJCOPY_extract_partition
))
483 Config
.ExtractPartition
= Arg
->getValue();
485 for (auto Arg
: InputArgs
.filtered(OBJCOPY_redefine_symbol
)) {
486 if (!StringRef(Arg
->getValue()).contains('='))
487 return createStringError(errc::invalid_argument
,
488 "bad format for --redefine-sym");
489 auto Old2New
= StringRef(Arg
->getValue()).split('=');
490 if (!Config
.SymbolsToRename
.insert(Old2New
).second
)
491 return createStringError(errc::invalid_argument
,
492 "multiple redefinition of symbol '%s'",
493 Old2New
.first
.str().c_str());
496 for (auto Arg
: InputArgs
.filtered(OBJCOPY_redefine_symbols
))
497 if (Error E
= addSymbolsToRenameFromFile(Config
.SymbolsToRename
, DC
.Alloc
,
501 for (auto Arg
: InputArgs
.filtered(OBJCOPY_rename_section
)) {
502 Expected
<SectionRename
> SR
=
503 parseRenameSectionValue(StringRef(Arg
->getValue()));
505 return SR
.takeError();
506 if (!Config
.SectionsToRename
.try_emplace(SR
->OriginalName
, *SR
).second
)
507 return createStringError(errc::invalid_argument
,
508 "multiple renames of section '%s'",
509 SR
->OriginalName
.str().c_str());
511 for (auto Arg
: InputArgs
.filtered(OBJCOPY_set_section_alignment
)) {
512 Expected
<std::pair
<StringRef
, uint64_t>> NameAndAlign
=
513 parseSetSectionAlignment(Arg
->getValue());
515 return NameAndAlign
.takeError();
516 Config
.SetSectionAlignment
[NameAndAlign
->first
] = NameAndAlign
->second
;
518 for (auto Arg
: InputArgs
.filtered(OBJCOPY_set_section_flags
)) {
519 Expected
<SectionFlagsUpdate
> SFU
=
520 parseSetSectionFlagValue(Arg
->getValue());
522 return SFU
.takeError();
523 if (!Config
.SetSectionFlags
.try_emplace(SFU
->Name
, *SFU
).second
)
524 return createStringError(
525 errc::invalid_argument
,
526 "--set-section-flags set multiple times for section '%s'",
527 SFU
->Name
.str().c_str());
529 // Prohibit combinations of --set-section-flags when the section name is used
530 // by --rename-section, either as a source or a destination.
531 for (const auto &E
: Config
.SectionsToRename
) {
532 const SectionRename
&SR
= E
.second
;
533 if (Config
.SetSectionFlags
.count(SR
.OriginalName
))
534 return createStringError(
535 errc::invalid_argument
,
536 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
537 SR
.OriginalName
.str().c_str(), SR
.OriginalName
.str().c_str(),
538 SR
.NewName
.str().c_str());
539 if (Config
.SetSectionFlags
.count(SR
.NewName
))
540 return createStringError(
541 errc::invalid_argument
,
542 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
543 SR
.NewName
.str().c_str(), SR
.OriginalName
.str().c_str(),
544 SR
.NewName
.str().c_str());
547 for (auto Arg
: InputArgs
.filtered(OBJCOPY_remove_section
))
548 Config
.ToRemove
.addMatcher({Arg
->getValue(), UseRegex
});
549 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_section
))
550 Config
.KeepSection
.addMatcher({Arg
->getValue(), UseRegex
});
551 for (auto Arg
: InputArgs
.filtered(OBJCOPY_only_section
))
552 Config
.OnlySection
.addMatcher({Arg
->getValue(), UseRegex
});
553 for (auto Arg
: InputArgs
.filtered(OBJCOPY_add_section
)) {
554 StringRef
ArgValue(Arg
->getValue());
555 if (!ArgValue
.contains('='))
556 return createStringError(errc::invalid_argument
,
557 "bad format for --add-section: missing '='");
558 if (ArgValue
.split("=").second
.empty())
559 return createStringError(
560 errc::invalid_argument
,
561 "bad format for --add-section: missing file name");
562 Config
.AddSection
.push_back(ArgValue
);
564 for (auto Arg
: InputArgs
.filtered(OBJCOPY_dump_section
))
565 Config
.DumpSection
.push_back(Arg
->getValue());
566 Config
.StripAll
= InputArgs
.hasArg(OBJCOPY_strip_all
);
567 Config
.StripAllGNU
= InputArgs
.hasArg(OBJCOPY_strip_all_gnu
);
568 Config
.StripDebug
= InputArgs
.hasArg(OBJCOPY_strip_debug
);
569 Config
.StripDWO
= InputArgs
.hasArg(OBJCOPY_strip_dwo
);
570 Config
.StripSections
= InputArgs
.hasArg(OBJCOPY_strip_sections
);
571 Config
.StripNonAlloc
= InputArgs
.hasArg(OBJCOPY_strip_non_alloc
);
572 Config
.StripUnneeded
= InputArgs
.hasArg(OBJCOPY_strip_unneeded
);
573 Config
.ExtractDWO
= InputArgs
.hasArg(OBJCOPY_extract_dwo
);
574 Config
.ExtractMainPartition
=
575 InputArgs
.hasArg(OBJCOPY_extract_main_partition
);
576 Config
.LocalizeHidden
= InputArgs
.hasArg(OBJCOPY_localize_hidden
);
577 Config
.Weaken
= InputArgs
.hasArg(OBJCOPY_weaken
);
578 if (InputArgs
.hasArg(OBJCOPY_discard_all
, OBJCOPY_discard_locals
))
580 InputArgs
.hasFlag(OBJCOPY_discard_all
, OBJCOPY_discard_locals
)
582 : DiscardType::Locals
;
583 Config
.OnlyKeepDebug
= InputArgs
.hasArg(OBJCOPY_only_keep_debug
);
584 Config
.KeepFileSymbols
= InputArgs
.hasArg(OBJCOPY_keep_file_symbols
);
585 Config
.DecompressDebugSections
=
586 InputArgs
.hasArg(OBJCOPY_decompress_debug_sections
);
587 if (Config
.DiscardMode
== DiscardType::All
)
588 Config
.StripDebug
= true;
589 for (auto Arg
: InputArgs
.filtered(OBJCOPY_localize_symbol
))
590 Config
.SymbolsToLocalize
.addMatcher({Arg
->getValue(), UseRegex
});
591 for (auto Arg
: InputArgs
.filtered(OBJCOPY_localize_symbols
))
592 if (Error E
= addSymbolsFromFile(Config
.SymbolsToLocalize
, DC
.Alloc
,
593 Arg
->getValue(), UseRegex
))
595 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_global_symbol
))
596 Config
.SymbolsToKeepGlobal
.addMatcher({Arg
->getValue(), UseRegex
});
597 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_global_symbols
))
598 if (Error E
= addSymbolsFromFile(Config
.SymbolsToKeepGlobal
, DC
.Alloc
,
599 Arg
->getValue(), UseRegex
))
601 for (auto Arg
: InputArgs
.filtered(OBJCOPY_globalize_symbol
))
602 Config
.SymbolsToGlobalize
.addMatcher({Arg
->getValue(), UseRegex
});
603 for (auto Arg
: InputArgs
.filtered(OBJCOPY_globalize_symbols
))
604 if (Error E
= addSymbolsFromFile(Config
.SymbolsToGlobalize
, DC
.Alloc
,
605 Arg
->getValue(), UseRegex
))
607 for (auto Arg
: InputArgs
.filtered(OBJCOPY_weaken_symbol
))
608 Config
.SymbolsToWeaken
.addMatcher({Arg
->getValue(), UseRegex
});
609 for (auto Arg
: InputArgs
.filtered(OBJCOPY_weaken_symbols
))
610 if (Error E
= addSymbolsFromFile(Config
.SymbolsToWeaken
, DC
.Alloc
,
611 Arg
->getValue(), UseRegex
))
613 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_symbol
))
614 Config
.SymbolsToRemove
.addMatcher({Arg
->getValue(), UseRegex
});
615 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_symbols
))
616 if (Error E
= addSymbolsFromFile(Config
.SymbolsToRemove
, DC
.Alloc
,
617 Arg
->getValue(), UseRegex
))
619 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_unneeded_symbol
))
620 Config
.UnneededSymbolsToRemove
.addMatcher({Arg
->getValue(), UseRegex
});
621 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_unneeded_symbols
))
622 if (Error E
= addSymbolsFromFile(Config
.UnneededSymbolsToRemove
, DC
.Alloc
,
623 Arg
->getValue(), UseRegex
))
625 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_symbol
))
626 Config
.SymbolsToKeep
.addMatcher({Arg
->getValue(), UseRegex
});
627 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_symbols
))
628 if (Error E
= addSymbolsFromFile(Config
.SymbolsToKeep
, DC
.Alloc
,
629 Arg
->getValue(), UseRegex
))
631 for (auto Arg
: InputArgs
.filtered(OBJCOPY_add_symbol
))
632 Config
.SymbolsToAdd
.push_back(Arg
->getValue());
634 Config
.AllowBrokenLinks
= InputArgs
.hasArg(OBJCOPY_allow_broken_links
);
636 Config
.DeterministicArchives
= InputArgs
.hasFlag(
637 OBJCOPY_enable_deterministic_archives
,
638 OBJCOPY_disable_deterministic_archives
, /*default=*/true);
640 Config
.PreserveDates
= InputArgs
.hasArg(OBJCOPY_preserve_dates
);
642 if (Config
.PreserveDates
&&
643 (Config
.OutputFilename
== "-" || Config
.InputFilename
== "-"))
644 return createStringError(errc::invalid_argument
,
645 "--preserve-dates requires a file");
647 for (auto Arg
: InputArgs
)
648 if (Arg
->getOption().matches(OBJCOPY_set_start
)) {
649 auto EAddr
= getAsInteger
<uint64_t>(Arg
->getValue());
651 return createStringError(
652 EAddr
.getError(), "bad entry point address: '%s'", Arg
->getValue());
654 Config
.EntryExpr
= [EAddr
](uint64_t) { return *EAddr
; };
655 } else if (Arg
->getOption().matches(OBJCOPY_change_start
)) {
656 auto EIncr
= getAsInteger
<int64_t>(Arg
->getValue());
658 return createStringError(EIncr
.getError(),
659 "bad entry point increment: '%s'",
661 auto Expr
= Config
.EntryExpr
? std::move(Config
.EntryExpr
)
662 : [](uint64_t A
) { return A
; };
663 Config
.EntryExpr
= [Expr
, EIncr
](uint64_t EAddr
) {
664 return Expr(EAddr
) + *EIncr
;
668 if (Config
.DecompressDebugSections
&&
669 Config
.CompressionType
!= DebugCompressionType::None
) {
670 return createStringError(
671 errc::invalid_argument
,
672 "cannot specify both --compress-debug-sections and "
673 "--decompress-debug-sections");
676 if (Config
.DecompressDebugSections
&& !zlib::isAvailable())
677 return createStringError(
678 errc::invalid_argument
,
679 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
681 if (Config
.ExtractPartition
&& Config
.ExtractMainPartition
)
682 return createStringError(errc::invalid_argument
,
683 "cannot specify --extract-partition together with "
684 "--extract-main-partition");
686 DC
.CopyConfigs
.push_back(std::move(Config
));
687 return std::move(DC
);
690 // ParseStripOptions returns the config and sets the input arguments. If a
691 // help flag is set then ParseStripOptions will print the help messege and
693 Expected
<DriverConfig
>
694 parseStripOptions(ArrayRef
<const char *> ArgsArr
,
695 std::function
<Error(Error
)> ErrorCallback
) {
697 unsigned MissingArgumentIndex
, MissingArgumentCount
;
698 llvm::opt::InputArgList InputArgs
=
699 T
.ParseArgs(ArgsArr
, MissingArgumentIndex
, MissingArgumentCount
);
701 if (InputArgs
.size() == 0) {
702 printHelp(T
, errs(), "llvm-strip");
706 if (InputArgs
.hasArg(STRIP_help
)) {
707 printHelp(T
, outs(), "llvm-strip");
711 if (InputArgs
.hasArg(STRIP_version
)) {
712 outs() << "llvm-strip, compatible with GNU strip\n";
713 cl::PrintVersionMessage();
717 SmallVector
<StringRef
, 2> Positional
;
718 for (auto Arg
: InputArgs
.filtered(STRIP_UNKNOWN
))
719 return createStringError(errc::invalid_argument
, "unknown argument '%s'",
720 Arg
->getAsString(InputArgs
).c_str());
721 for (auto Arg
: InputArgs
.filtered(STRIP_INPUT
))
722 Positional
.push_back(Arg
->getValue());
724 if (Positional
.empty())
725 return createStringError(errc::invalid_argument
, "no input file specified");
727 if (Positional
.size() > 1 && InputArgs
.hasArg(STRIP_output
))
728 return createStringError(
729 errc::invalid_argument
,
730 "multiple input files cannot be used in combination with -o");
733 bool UseRegexp
= InputArgs
.hasArg(STRIP_regex
);
734 Config
.AllowBrokenLinks
= InputArgs
.hasArg(STRIP_allow_broken_links
);
735 Config
.StripDebug
= InputArgs
.hasArg(STRIP_strip_debug
);
737 if (InputArgs
.hasArg(STRIP_discard_all
, STRIP_discard_locals
))
739 InputArgs
.hasFlag(STRIP_discard_all
, STRIP_discard_locals
)
741 : DiscardType::Locals
;
742 Config
.StripSections
= InputArgs
.hasArg(STRIP_strip_sections
);
743 Config
.StripUnneeded
= InputArgs
.hasArg(STRIP_strip_unneeded
);
744 if (auto Arg
= InputArgs
.getLastArg(STRIP_strip_all
, STRIP_no_strip_all
))
745 Config
.StripAll
= Arg
->getOption().getID() == STRIP_strip_all
;
746 Config
.StripAllGNU
= InputArgs
.hasArg(STRIP_strip_all_gnu
);
747 Config
.OnlyKeepDebug
= InputArgs
.hasArg(STRIP_only_keep_debug
);
748 Config
.KeepFileSymbols
= InputArgs
.hasArg(STRIP_keep_file_symbols
);
750 for (auto Arg
: InputArgs
.filtered(STRIP_keep_section
))
751 Config
.KeepSection
.addMatcher({Arg
->getValue(), UseRegexp
});
753 for (auto Arg
: InputArgs
.filtered(STRIP_remove_section
))
754 Config
.ToRemove
.addMatcher({Arg
->getValue(), UseRegexp
});
756 for (auto Arg
: InputArgs
.filtered(STRIP_strip_symbol
))
757 Config
.SymbolsToRemove
.addMatcher({Arg
->getValue(), UseRegexp
});
759 for (auto Arg
: InputArgs
.filtered(STRIP_keep_symbol
))
760 Config
.SymbolsToKeep
.addMatcher({Arg
->getValue(), UseRegexp
});
762 if (!InputArgs
.hasArg(STRIP_no_strip_all
) && !Config
.StripDebug
&&
763 !Config
.StripUnneeded
&& Config
.DiscardMode
== DiscardType::None
&&
764 !Config
.StripAllGNU
&& Config
.SymbolsToRemove
.empty())
765 Config
.StripAll
= true;
767 if (Config
.DiscardMode
== DiscardType::All
)
768 Config
.StripDebug
= true;
770 Config
.DeterministicArchives
=
771 InputArgs
.hasFlag(STRIP_enable_deterministic_archives
,
772 STRIP_disable_deterministic_archives
, /*default=*/true);
774 Config
.PreserveDates
= InputArgs
.hasArg(STRIP_preserve_dates
);
775 Config
.InputFormat
= FileFormat::Unspecified
;
776 Config
.OutputFormat
= FileFormat::Unspecified
;
779 if (Positional
.size() == 1) {
780 Config
.InputFilename
= Positional
[0];
781 Config
.OutputFilename
=
782 InputArgs
.getLastArgValue(STRIP_output
, Positional
[0]);
783 DC
.CopyConfigs
.push_back(std::move(Config
));
785 StringMap
<unsigned> InputFiles
;
786 for (StringRef Filename
: Positional
) {
787 if (InputFiles
[Filename
]++ == 1) {
789 return createStringError(
790 errc::invalid_argument
,
791 "cannot specify '-' as an input file more than once");
792 if (Error E
= ErrorCallback(createStringError(
793 errc::invalid_argument
, "'%s' was already specified",
794 Filename
.str().c_str())))
797 Config
.InputFilename
= Filename
;
798 Config
.OutputFilename
= Filename
;
799 DC
.CopyConfigs
.push_back(Config
);
803 if (Config
.PreserveDates
&& (is_contained(Positional
, "-") ||
804 InputArgs
.getLastArgValue(STRIP_output
) == "-"))
805 return createStringError(errc::invalid_argument
,
806 "--preserve-dates requires a file");
808 return std::move(DC
);
811 } // namespace objcopy