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
<SectionFlagsUpdate
>
159 parseSetSectionFlagValue(StringRef FlagValue
) {
160 if (!StringRef(FlagValue
).contains('='))
161 return createStringError(errc::invalid_argument
,
162 "bad format for --set-section-flags: missing '='");
164 // Initial split: ".foo" = "f1,f2,..."
165 auto Section2Flags
= StringRef(FlagValue
).split('=');
166 SectionFlagsUpdate SFU
;
167 SFU
.Name
= Section2Flags
.first
;
169 // Flags split: "f1" "f2" ...
170 SmallVector
<StringRef
, 6> SectionFlags
;
171 Section2Flags
.second
.split(SectionFlags
, ',');
172 Expected
<SectionFlag
> ParsedFlagSet
= parseSectionFlagSet(SectionFlags
);
174 return ParsedFlagSet
.takeError();
175 SFU
.NewFlags
= *ParsedFlagSet
;
180 static Expected
<NewSymbolInfo
> parseNewSymbolInfo(StringRef FlagValue
,
181 uint8_t DefaultVisibility
) {
182 // Parse value given with --add-symbol option and create the
183 // new symbol if possible. The value format for --add-symbol is:
185 // <name>=[<section>:]<value>[,<flags>]
188 // <name> - symbol name, can be empty string
189 // <section> - optional section name. If not given ABS symbol is created
190 // <value> - symbol value, can be decimal or hexadecimal number prefixed
192 // <flags> - optional flags affecting symbol type, binding or visibility:
193 // The following are currently supported:
195 // global, local, weak, default, hidden, file, section, object,
196 // indirect-function.
198 // The following flags are ignored and provided for GNU
199 // compatibility only:
201 // warning, debug, constructor, indirect, synthetic,
202 // unique-object, before=<symbol>.
205 std::tie(SI
.SymbolName
, Value
) = FlagValue
.split('=');
207 return createStringError(
208 errc::invalid_argument
,
209 "bad format for --add-symbol, missing '=' after '%s'",
210 SI
.SymbolName
.str().c_str());
212 if (Value
.contains(':')) {
213 std::tie(SI
.SectionName
, Value
) = Value
.split(':');
214 if (SI
.SectionName
.empty() || Value
.empty())
215 return createStringError(
216 errc::invalid_argument
,
217 "bad format for --add-symbol, missing section name or symbol value");
220 SmallVector
<StringRef
, 6> Flags
;
221 Value
.split(Flags
, ',');
222 if (Flags
[0].getAsInteger(0, SI
.Value
))
223 return createStringError(errc::invalid_argument
, "bad symbol value: '%s'",
224 Flags
[0].str().c_str());
226 SI
.Visibility
= DefaultVisibility
;
228 using Functor
= std::function
<void(void)>;
229 SmallVector
<StringRef
, 6> UnsupportedFlags
;
230 for (size_t I
= 1, NumFlags
= Flags
.size(); I
< NumFlags
; ++I
)
231 static_cast<Functor
>(
232 StringSwitch
<Functor
>(Flags
[I
])
233 .CaseLower("global", [&SI
] { SI
.Bind
= ELF::STB_GLOBAL
; })
234 .CaseLower("local", [&SI
] { SI
.Bind
= ELF::STB_LOCAL
; })
235 .CaseLower("weak", [&SI
] { SI
.Bind
= ELF::STB_WEAK
; })
236 .CaseLower("default", [&SI
] { SI
.Visibility
= ELF::STV_DEFAULT
; })
237 .CaseLower("hidden", [&SI
] { SI
.Visibility
= ELF::STV_HIDDEN
; })
238 .CaseLower("protected", [&SI
] { SI
.Visibility
= ELF::STV_PROTECTED
; })
239 .CaseLower("file", [&SI
] { SI
.Type
= ELF::STT_FILE
; })
240 .CaseLower("section", [&SI
] { SI
.Type
= ELF::STT_SECTION
; })
241 .CaseLower("object", [&SI
] { SI
.Type
= ELF::STT_OBJECT
; })
242 .CaseLower("function", [&SI
] { SI
.Type
= ELF::STT_FUNC
; })
243 .CaseLower("indirect-function",
244 [&SI
] { SI
.Type
= ELF::STT_GNU_IFUNC
; })
245 .CaseLower("debug", [] {})
246 .CaseLower("constructor", [] {})
247 .CaseLower("warning", [] {})
248 .CaseLower("indirect", [] {})
249 .CaseLower("synthetic", [] {})
250 .CaseLower("unique-object", [] {})
251 .StartsWithLower("before", [] {})
252 .Default([&] { UnsupportedFlags
.push_back(Flags
[I
]); }))();
253 if (!UnsupportedFlags
.empty())
254 return createStringError(errc::invalid_argument
,
255 "unsupported flag%s for --add-symbol: '%s'",
256 UnsupportedFlags
.size() > 1 ? "s" : "",
257 join(UnsupportedFlags
, "', '").c_str());
266 // FIXME: consolidate with the bfd parsing used by lld.
267 static const StringMap
<MachineInfo
> TargetMap
{
268 // Name, {EMachine, 64bit, LittleEndian}
270 {"elf32-i386", {ELF::EM_386
, false, true}},
271 {"elf32-x86-64", {ELF::EM_X86_64
, false, true}},
272 {"elf64-x86-64", {ELF::EM_X86_64
, true, true}},
274 {"elf32-iamcu", {ELF::EM_IAMCU
, false, true}},
276 {"elf32-littlearm", {ELF::EM_ARM
, false, true}},
278 {"elf64-aarch64", {ELF::EM_AARCH64
, true, true}},
279 {"elf64-littleaarch64", {ELF::EM_AARCH64
, true, true}},
281 {"elf32-littleriscv", {ELF::EM_RISCV
, false, true}},
282 {"elf64-littleriscv", {ELF::EM_RISCV
, true, true}},
284 {"elf32-powerpc", {ELF::EM_PPC
, false, false}},
285 {"elf32-powerpcle", {ELF::EM_PPC
, false, true}},
286 {"elf64-powerpc", {ELF::EM_PPC64
, true, false}},
287 {"elf64-powerpcle", {ELF::EM_PPC64
, true, true}},
289 {"elf32-bigmips", {ELF::EM_MIPS
, false, false}},
290 {"elf32-ntradbigmips", {ELF::EM_MIPS
, false, false}},
291 {"elf32-ntradlittlemips", {ELF::EM_MIPS
, false, true}},
292 {"elf32-tradbigmips", {ELF::EM_MIPS
, false, false}},
293 {"elf32-tradlittlemips", {ELF::EM_MIPS
, false, true}},
294 {"elf64-tradbigmips", {ELF::EM_MIPS
, true, false}},
295 {"elf64-tradlittlemips", {ELF::EM_MIPS
, true, true}},
297 {"elf32-sparc", {ELF::EM_SPARC
, false, false}},
298 {"elf32-sparcel", {ELF::EM_SPARC
, false, true}},
301 static Expected
<TargetInfo
>
302 getOutputTargetInfoByTargetName(StringRef TargetName
) {
303 StringRef OriginalTargetName
= TargetName
;
304 bool IsFreeBSD
= TargetName
.consume_back("-freebsd");
305 auto Iter
= TargetMap
.find(TargetName
);
306 if (Iter
== std::end(TargetMap
))
307 return createStringError(errc::invalid_argument
,
308 "invalid output format: '%s'",
309 OriginalTargetName
.str().c_str());
310 MachineInfo MI
= Iter
->getValue();
312 MI
.OSABI
= ELF::ELFOSABI_FREEBSD
;
315 if (TargetName
.startswith("elf"))
316 Format
= FileFormat::ELF
;
318 // This should never happen because `TargetName` is valid (it certainly
319 // exists in the TargetMap).
320 llvm_unreachable("unknown target prefix");
322 return {TargetInfo
{Format
, MI
}};
325 static Error
addSymbolsFromFile(NameMatcher
&Symbols
, BumpPtrAllocator
&Alloc
,
326 StringRef Filename
, bool UseRegex
) {
327 StringSaver
Saver(Alloc
);
328 SmallVector
<StringRef
, 16> Lines
;
329 auto BufOrErr
= MemoryBuffer::getFile(Filename
);
331 return createFileError(Filename
, BufOrErr
.getError());
333 BufOrErr
.get()->getBuffer().split(Lines
, '\n');
334 for (StringRef Line
: Lines
) {
335 // Ignore everything after '#', trim whitespace, and only add the symbol if
337 auto TrimmedLine
= Line
.split('#').first
.trim();
338 if (!TrimmedLine
.empty())
339 Symbols
.addMatcher({Saver
.save(TrimmedLine
), UseRegex
});
342 return Error::success();
345 NameOrRegex::NameOrRegex(StringRef Pattern
, bool IsRegex
) {
351 SmallVector
<char, 32> Data
;
352 R
= std::make_shared
<Regex
>(
353 ("^" + Pattern
.ltrim('^').rtrim('$') + "$").toStringRef(Data
));
356 static Error
addSymbolsToRenameFromFile(StringMap
<StringRef
> &SymbolsToRename
,
357 BumpPtrAllocator
&Alloc
,
358 StringRef Filename
) {
359 StringSaver
Saver(Alloc
);
360 SmallVector
<StringRef
, 16> Lines
;
361 auto BufOrErr
= MemoryBuffer::getFile(Filename
);
363 return createFileError(Filename
, BufOrErr
.getError());
365 BufOrErr
.get()->getBuffer().split(Lines
, '\n');
366 size_t NumLines
= Lines
.size();
367 for (size_t LineNo
= 0; LineNo
< NumLines
; ++LineNo
) {
368 StringRef TrimmedLine
= Lines
[LineNo
].split('#').first
.trim();
369 if (TrimmedLine
.empty())
372 std::pair
<StringRef
, StringRef
> Pair
= Saver
.save(TrimmedLine
).split(' ');
373 StringRef NewName
= Pair
.second
.trim();
375 return createStringError(errc::invalid_argument
,
376 "%s:%zu: missing new symbol name",
377 Filename
.str().c_str(), LineNo
+ 1);
378 SymbolsToRename
.insert({Pair
.first
, NewName
});
380 return Error::success();
383 template <class T
> static ErrorOr
<T
> getAsInteger(StringRef Val
) {
385 if (Val
.getAsInteger(0, Result
))
386 return errc::invalid_argument
;
390 static void printHelp(const opt::OptTable
&OptTable
, raw_ostream
&OS
,
391 StringRef ToolName
) {
392 OptTable
.PrintHelp(OS
, (ToolName
+ " input [output]").str().c_str(),
393 (ToolName
+ " tool").str().c_str());
394 // TODO: Replace this with libOption call once it adds extrahelp support.
395 // The CommandLine library has a cl::extrahelp class to support this,
396 // but libOption does not have that yet.
397 OS
<< "\nPass @FILE as argument to read options from FILE.\n";
400 // ParseObjcopyOptions returns the config and sets the input arguments. If a
401 // help flag is set then ParseObjcopyOptions will print the help messege and
403 Expected
<DriverConfig
> parseObjcopyOptions(ArrayRef
<const char *> ArgsArr
) {
406 unsigned MissingArgumentIndex
, MissingArgumentCount
;
407 llvm::opt::InputArgList InputArgs
=
408 T
.ParseArgs(ArgsArr
, MissingArgumentIndex
, MissingArgumentCount
);
410 if (InputArgs
.size() == 0) {
411 printHelp(T
, errs(), "llvm-objcopy");
415 if (InputArgs
.hasArg(OBJCOPY_help
)) {
416 printHelp(T
, outs(), "llvm-objcopy");
420 if (InputArgs
.hasArg(OBJCOPY_version
)) {
421 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
422 cl::PrintVersionMessage();
426 SmallVector
<const char *, 2> Positional
;
428 for (auto Arg
: InputArgs
.filtered(OBJCOPY_UNKNOWN
))
429 return createStringError(errc::invalid_argument
, "unknown argument '%s'",
430 Arg
->getAsString(InputArgs
).c_str());
432 for (auto Arg
: InputArgs
.filtered(OBJCOPY_INPUT
))
433 Positional
.push_back(Arg
->getValue());
435 if (Positional
.empty())
436 return createStringError(errc::invalid_argument
, "no input file specified");
438 if (Positional
.size() > 2)
439 return createStringError(errc::invalid_argument
,
440 "too many positional arguments");
443 Config
.InputFilename
= Positional
[0];
444 Config
.OutputFilename
= Positional
[Positional
.size() == 1 ? 0 : 1];
445 if (InputArgs
.hasArg(OBJCOPY_target
) &&
446 (InputArgs
.hasArg(OBJCOPY_input_target
) ||
447 InputArgs
.hasArg(OBJCOPY_output_target
)))
448 return createStringError(
449 errc::invalid_argument
,
450 "--target cannot be used with --input-target or --output-target");
452 bool UseRegex
= InputArgs
.hasArg(OBJCOPY_regex
);
453 StringRef InputFormat
, OutputFormat
;
454 if (InputArgs
.hasArg(OBJCOPY_target
)) {
455 InputFormat
= InputArgs
.getLastArgValue(OBJCOPY_target
);
456 OutputFormat
= InputArgs
.getLastArgValue(OBJCOPY_target
);
458 InputFormat
= InputArgs
.getLastArgValue(OBJCOPY_input_target
);
459 OutputFormat
= InputArgs
.getLastArgValue(OBJCOPY_output_target
);
462 // FIXME: Currently, we ignore the target for non-binary/ihex formats
463 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
464 // format by llvm::object::createBinary regardless of the option value.
465 Config
.InputFormat
= StringSwitch
<FileFormat
>(InputFormat
)
466 .Case("binary", FileFormat::Binary
)
467 .Case("ihex", FileFormat::IHex
)
468 .Default(FileFormat::Unspecified
);
470 if (opt::Arg
*A
= InputArgs
.getLastArg(OBJCOPY_new_symbol_visibility
)) {
471 const uint8_t Invalid
= 0xff;
472 Config
.NewSymbolVisibility
= StringSwitch
<uint8_t>(A
->getValue())
473 .Case("default", ELF::STV_DEFAULT
)
474 .Case("hidden", ELF::STV_HIDDEN
)
475 .Case("internal", ELF::STV_INTERNAL
)
476 .Case("protected", ELF::STV_PROTECTED
)
479 if (Config
.NewSymbolVisibility
== Invalid
)
480 return createStringError(
481 errc::invalid_argument
, "'%s' is not a valid symbol visibility",
482 InputArgs
.getLastArgValue(OBJCOPY_new_symbol_visibility
).str().c_str());
485 Config
.OutputFormat
= StringSwitch
<FileFormat
>(OutputFormat
)
486 .Case("binary", FileFormat::Binary
)
487 .Case("ihex", FileFormat::IHex
)
488 .Default(FileFormat::Unspecified
);
489 if (Config
.OutputFormat
== FileFormat::Unspecified
) {
490 if (OutputFormat
.empty()) {
491 Config
.OutputFormat
= Config
.InputFormat
;
493 Expected
<TargetInfo
> Target
=
494 getOutputTargetInfoByTargetName(OutputFormat
);
496 return Target
.takeError();
497 Config
.OutputFormat
= Target
->Format
;
498 Config
.OutputArch
= Target
->Machine
;
502 if (auto Arg
= InputArgs
.getLastArg(OBJCOPY_compress_debug_sections
,
503 OBJCOPY_compress_debug_sections_eq
)) {
504 Config
.CompressionType
= DebugCompressionType::Z
;
506 if (Arg
->getOption().getID() == OBJCOPY_compress_debug_sections_eq
) {
507 Config
.CompressionType
=
508 StringSwitch
<DebugCompressionType
>(
509 InputArgs
.getLastArgValue(OBJCOPY_compress_debug_sections_eq
))
510 .Case("zlib-gnu", DebugCompressionType::GNU
)
511 .Case("zlib", DebugCompressionType::Z
)
512 .Default(DebugCompressionType::None
);
513 if (Config
.CompressionType
== DebugCompressionType::None
)
514 return createStringError(
515 errc::invalid_argument
,
516 "invalid or unsupported --compress-debug-sections format: %s",
517 InputArgs
.getLastArgValue(OBJCOPY_compress_debug_sections_eq
)
521 if (!zlib::isAvailable())
522 return createStringError(
523 errc::invalid_argument
,
524 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
527 Config
.AddGnuDebugLink
= InputArgs
.getLastArgValue(OBJCOPY_add_gnu_debuglink
);
528 // The gnu_debuglink's target is expected to not change or else its CRC would
529 // become invalidated and get rejected. We can avoid recalculating the
530 // checksum for every target file inside an archive by precomputing the CRC
531 // here. This prevents a significant amount of I/O.
532 if (!Config
.AddGnuDebugLink
.empty()) {
533 auto DebugOrErr
= MemoryBuffer::getFile(Config
.AddGnuDebugLink
);
535 return createFileError(Config
.AddGnuDebugLink
, DebugOrErr
.getError());
536 auto Debug
= std::move(*DebugOrErr
);
539 ArrayRef
<char>(Debug
->getBuffer().data(), Debug
->getBuffer().size()));
540 // The CRC32 value needs to be complemented because the JamCRC doesn't
541 // finalize the CRC32 value.
542 Config
.GnuDebugLinkCRC32
= ~CRC
.getCRC();
544 Config
.BuildIdLinkDir
= InputArgs
.getLastArgValue(OBJCOPY_build_id_link_dir
);
545 if (InputArgs
.hasArg(OBJCOPY_build_id_link_input
))
546 Config
.BuildIdLinkInput
=
547 InputArgs
.getLastArgValue(OBJCOPY_build_id_link_input
);
548 if (InputArgs
.hasArg(OBJCOPY_build_id_link_output
))
549 Config
.BuildIdLinkOutput
=
550 InputArgs
.getLastArgValue(OBJCOPY_build_id_link_output
);
551 Config
.SplitDWO
= InputArgs
.getLastArgValue(OBJCOPY_split_dwo
);
552 Config
.SymbolsPrefix
= InputArgs
.getLastArgValue(OBJCOPY_prefix_symbols
);
553 Config
.AllocSectionsPrefix
=
554 InputArgs
.getLastArgValue(OBJCOPY_prefix_alloc_sections
);
555 if (auto Arg
= InputArgs
.getLastArg(OBJCOPY_extract_partition
))
556 Config
.ExtractPartition
= Arg
->getValue();
558 for (auto Arg
: InputArgs
.filtered(OBJCOPY_redefine_symbol
)) {
559 if (!StringRef(Arg
->getValue()).contains('='))
560 return createStringError(errc::invalid_argument
,
561 "bad format for --redefine-sym");
562 auto Old2New
= StringRef(Arg
->getValue()).split('=');
563 if (!Config
.SymbolsToRename
.insert(Old2New
).second
)
564 return createStringError(errc::invalid_argument
,
565 "multiple redefinition of symbol '%s'",
566 Old2New
.first
.str().c_str());
569 for (auto Arg
: InputArgs
.filtered(OBJCOPY_redefine_symbols
))
570 if (Error E
= addSymbolsToRenameFromFile(Config
.SymbolsToRename
, DC
.Alloc
,
574 for (auto Arg
: InputArgs
.filtered(OBJCOPY_rename_section
)) {
575 Expected
<SectionRename
> SR
=
576 parseRenameSectionValue(StringRef(Arg
->getValue()));
578 return SR
.takeError();
579 if (!Config
.SectionsToRename
.try_emplace(SR
->OriginalName
, *SR
).second
)
580 return createStringError(errc::invalid_argument
,
581 "multiple renames of section '%s'",
582 SR
->OriginalName
.str().c_str());
584 for (auto Arg
: InputArgs
.filtered(OBJCOPY_set_section_flags
)) {
585 Expected
<SectionFlagsUpdate
> SFU
=
586 parseSetSectionFlagValue(Arg
->getValue());
588 return SFU
.takeError();
589 if (!Config
.SetSectionFlags
.try_emplace(SFU
->Name
, *SFU
).second
)
590 return createStringError(
591 errc::invalid_argument
,
592 "--set-section-flags set multiple times for section '%s'",
593 SFU
->Name
.str().c_str());
595 // Prohibit combinations of --set-section-flags when the section name is used
596 // by --rename-section, either as a source or a destination.
597 for (const auto &E
: Config
.SectionsToRename
) {
598 const SectionRename
&SR
= E
.second
;
599 if (Config
.SetSectionFlags
.count(SR
.OriginalName
))
600 return createStringError(
601 errc::invalid_argument
,
602 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
603 SR
.OriginalName
.str().c_str(), SR
.OriginalName
.str().c_str(),
604 SR
.NewName
.str().c_str());
605 if (Config
.SetSectionFlags
.count(SR
.NewName
))
606 return createStringError(
607 errc::invalid_argument
,
608 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
609 SR
.NewName
.str().c_str(), SR
.OriginalName
.str().c_str(),
610 SR
.NewName
.str().c_str());
613 for (auto Arg
: InputArgs
.filtered(OBJCOPY_remove_section
))
614 Config
.ToRemove
.addMatcher({Arg
->getValue(), UseRegex
});
615 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_section
))
616 Config
.KeepSection
.addMatcher({Arg
->getValue(), UseRegex
});
617 for (auto Arg
: InputArgs
.filtered(OBJCOPY_only_section
))
618 Config
.OnlySection
.addMatcher({Arg
->getValue(), UseRegex
});
619 for (auto Arg
: InputArgs
.filtered(OBJCOPY_add_section
)) {
620 StringRef
ArgValue(Arg
->getValue());
621 if (!ArgValue
.contains('='))
622 return createStringError(errc::invalid_argument
,
623 "bad format for --add-section: missing '='");
624 if (ArgValue
.split("=").second
.empty())
625 return createStringError(
626 errc::invalid_argument
,
627 "bad format for --add-section: missing file name");
628 Config
.AddSection
.push_back(ArgValue
);
630 for (auto Arg
: InputArgs
.filtered(OBJCOPY_dump_section
))
631 Config
.DumpSection
.push_back(Arg
->getValue());
632 Config
.StripAll
= InputArgs
.hasArg(OBJCOPY_strip_all
);
633 Config
.StripAllGNU
= InputArgs
.hasArg(OBJCOPY_strip_all_gnu
);
634 Config
.StripDebug
= InputArgs
.hasArg(OBJCOPY_strip_debug
);
635 Config
.StripDWO
= InputArgs
.hasArg(OBJCOPY_strip_dwo
);
636 Config
.StripSections
= InputArgs
.hasArg(OBJCOPY_strip_sections
);
637 Config
.StripNonAlloc
= InputArgs
.hasArg(OBJCOPY_strip_non_alloc
);
638 Config
.StripUnneeded
= InputArgs
.hasArg(OBJCOPY_strip_unneeded
);
639 Config
.ExtractDWO
= InputArgs
.hasArg(OBJCOPY_extract_dwo
);
640 Config
.ExtractMainPartition
=
641 InputArgs
.hasArg(OBJCOPY_extract_main_partition
);
642 Config
.LocalizeHidden
= InputArgs
.hasArg(OBJCOPY_localize_hidden
);
643 Config
.Weaken
= InputArgs
.hasArg(OBJCOPY_weaken
);
644 if (InputArgs
.hasArg(OBJCOPY_discard_all
, OBJCOPY_discard_locals
))
646 InputArgs
.hasFlag(OBJCOPY_discard_all
, OBJCOPY_discard_locals
)
648 : DiscardType::Locals
;
649 Config
.OnlyKeepDebug
= InputArgs
.hasArg(OBJCOPY_only_keep_debug
);
650 Config
.KeepFileSymbols
= InputArgs
.hasArg(OBJCOPY_keep_file_symbols
);
651 Config
.DecompressDebugSections
=
652 InputArgs
.hasArg(OBJCOPY_decompress_debug_sections
);
653 if (Config
.DiscardMode
== DiscardType::All
)
654 Config
.StripDebug
= true;
655 for (auto Arg
: InputArgs
.filtered(OBJCOPY_localize_symbol
))
656 Config
.SymbolsToLocalize
.addMatcher({Arg
->getValue(), UseRegex
});
657 for (auto Arg
: InputArgs
.filtered(OBJCOPY_localize_symbols
))
658 if (Error E
= addSymbolsFromFile(Config
.SymbolsToLocalize
, DC
.Alloc
,
659 Arg
->getValue(), UseRegex
))
661 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_global_symbol
))
662 Config
.SymbolsToKeepGlobal
.addMatcher({Arg
->getValue(), UseRegex
});
663 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_global_symbols
))
664 if (Error E
= addSymbolsFromFile(Config
.SymbolsToKeepGlobal
, DC
.Alloc
,
665 Arg
->getValue(), UseRegex
))
667 for (auto Arg
: InputArgs
.filtered(OBJCOPY_globalize_symbol
))
668 Config
.SymbolsToGlobalize
.addMatcher({Arg
->getValue(), UseRegex
});
669 for (auto Arg
: InputArgs
.filtered(OBJCOPY_globalize_symbols
))
670 if (Error E
= addSymbolsFromFile(Config
.SymbolsToGlobalize
, DC
.Alloc
,
671 Arg
->getValue(), UseRegex
))
673 for (auto Arg
: InputArgs
.filtered(OBJCOPY_weaken_symbol
))
674 Config
.SymbolsToWeaken
.addMatcher({Arg
->getValue(), UseRegex
});
675 for (auto Arg
: InputArgs
.filtered(OBJCOPY_weaken_symbols
))
676 if (Error E
= addSymbolsFromFile(Config
.SymbolsToWeaken
, DC
.Alloc
,
677 Arg
->getValue(), UseRegex
))
679 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_symbol
))
680 Config
.SymbolsToRemove
.addMatcher({Arg
->getValue(), UseRegex
});
681 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_symbols
))
682 if (Error E
= addSymbolsFromFile(Config
.SymbolsToRemove
, DC
.Alloc
,
683 Arg
->getValue(), UseRegex
))
685 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_unneeded_symbol
))
686 Config
.UnneededSymbolsToRemove
.addMatcher({Arg
->getValue(), UseRegex
});
687 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_unneeded_symbols
))
688 if (Error E
= addSymbolsFromFile(Config
.UnneededSymbolsToRemove
, DC
.Alloc
,
689 Arg
->getValue(), UseRegex
))
691 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_symbol
))
692 Config
.SymbolsToKeep
.addMatcher({Arg
->getValue(), UseRegex
});
693 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_symbols
))
694 if (Error E
= addSymbolsFromFile(Config
.SymbolsToKeep
, DC
.Alloc
,
695 Arg
->getValue(), UseRegex
))
697 for (auto Arg
: InputArgs
.filtered(OBJCOPY_add_symbol
)) {
698 Expected
<NewSymbolInfo
> NSI
= parseNewSymbolInfo(
700 Config
.NewSymbolVisibility
.getValueOr((uint8_t)ELF::STV_DEFAULT
));
702 return NSI
.takeError();
703 Config
.SymbolsToAdd
.push_back(*NSI
);
706 Config
.AllowBrokenLinks
= InputArgs
.hasArg(OBJCOPY_allow_broken_links
);
708 Config
.DeterministicArchives
= InputArgs
.hasFlag(
709 OBJCOPY_enable_deterministic_archives
,
710 OBJCOPY_disable_deterministic_archives
, /*default=*/true);
712 Config
.PreserveDates
= InputArgs
.hasArg(OBJCOPY_preserve_dates
);
714 if (Config
.PreserveDates
&&
715 (Config
.OutputFilename
== "-" || Config
.InputFilename
== "-"))
716 return createStringError(errc::invalid_argument
,
717 "--preserve-dates requires a file");
719 for (auto Arg
: InputArgs
)
720 if (Arg
->getOption().matches(OBJCOPY_set_start
)) {
721 auto EAddr
= getAsInteger
<uint64_t>(Arg
->getValue());
723 return createStringError(
724 EAddr
.getError(), "bad entry point address: '%s'", Arg
->getValue());
726 Config
.EntryExpr
= [EAddr
](uint64_t) { return *EAddr
; };
727 } else if (Arg
->getOption().matches(OBJCOPY_change_start
)) {
728 auto EIncr
= getAsInteger
<int64_t>(Arg
->getValue());
730 return createStringError(EIncr
.getError(),
731 "bad entry point increment: '%s'",
733 auto Expr
= Config
.EntryExpr
? std::move(Config
.EntryExpr
)
734 : [](uint64_t A
) { return A
; };
735 Config
.EntryExpr
= [Expr
, EIncr
](uint64_t EAddr
) {
736 return Expr(EAddr
) + *EIncr
;
740 if (Config
.DecompressDebugSections
&&
741 Config
.CompressionType
!= DebugCompressionType::None
) {
742 return createStringError(
743 errc::invalid_argument
,
744 "cannot specify both --compress-debug-sections and "
745 "--decompress-debug-sections");
748 if (Config
.DecompressDebugSections
&& !zlib::isAvailable())
749 return createStringError(
750 errc::invalid_argument
,
751 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
753 if (Config
.ExtractPartition
&& Config
.ExtractMainPartition
)
754 return createStringError(errc::invalid_argument
,
755 "cannot specify --extract-partition together with "
756 "--extract-main-partition");
758 DC
.CopyConfigs
.push_back(std::move(Config
));
759 return std::move(DC
);
762 // ParseStripOptions returns the config and sets the input arguments. If a
763 // help flag is set then ParseStripOptions will print the help messege and
765 Expected
<DriverConfig
>
766 parseStripOptions(ArrayRef
<const char *> ArgsArr
,
767 std::function
<Error(Error
)> ErrorCallback
) {
769 unsigned MissingArgumentIndex
, MissingArgumentCount
;
770 llvm::opt::InputArgList InputArgs
=
771 T
.ParseArgs(ArgsArr
, MissingArgumentIndex
, MissingArgumentCount
);
773 if (InputArgs
.size() == 0) {
774 printHelp(T
, errs(), "llvm-strip");
778 if (InputArgs
.hasArg(STRIP_help
)) {
779 printHelp(T
, outs(), "llvm-strip");
783 if (InputArgs
.hasArg(STRIP_version
)) {
784 outs() << "llvm-strip, compatible with GNU strip\n";
785 cl::PrintVersionMessage();
789 SmallVector
<StringRef
, 2> Positional
;
790 for (auto Arg
: InputArgs
.filtered(STRIP_UNKNOWN
))
791 return createStringError(errc::invalid_argument
, "unknown argument '%s'",
792 Arg
->getAsString(InputArgs
).c_str());
793 for (auto Arg
: InputArgs
.filtered(STRIP_INPUT
))
794 Positional
.push_back(Arg
->getValue());
796 if (Positional
.empty())
797 return createStringError(errc::invalid_argument
, "no input file specified");
799 if (Positional
.size() > 1 && InputArgs
.hasArg(STRIP_output
))
800 return createStringError(
801 errc::invalid_argument
,
802 "multiple input files cannot be used in combination with -o");
805 bool UseRegexp
= InputArgs
.hasArg(STRIP_regex
);
806 Config
.AllowBrokenLinks
= InputArgs
.hasArg(STRIP_allow_broken_links
);
807 Config
.StripDebug
= InputArgs
.hasArg(STRIP_strip_debug
);
809 if (InputArgs
.hasArg(STRIP_discard_all
, STRIP_discard_locals
))
811 InputArgs
.hasFlag(STRIP_discard_all
, STRIP_discard_locals
)
813 : DiscardType::Locals
;
814 Config
.StripSections
= InputArgs
.hasArg(STRIP_strip_sections
);
815 Config
.StripUnneeded
= InputArgs
.hasArg(STRIP_strip_unneeded
);
816 if (auto Arg
= InputArgs
.getLastArg(STRIP_strip_all
, STRIP_no_strip_all
))
817 Config
.StripAll
= Arg
->getOption().getID() == STRIP_strip_all
;
818 Config
.StripAllGNU
= InputArgs
.hasArg(STRIP_strip_all_gnu
);
819 Config
.OnlyKeepDebug
= InputArgs
.hasArg(STRIP_only_keep_debug
);
820 Config
.KeepFileSymbols
= InputArgs
.hasArg(STRIP_keep_file_symbols
);
822 for (auto Arg
: InputArgs
.filtered(STRIP_keep_section
))
823 Config
.KeepSection
.addMatcher({Arg
->getValue(), UseRegexp
});
825 for (auto Arg
: InputArgs
.filtered(STRIP_remove_section
))
826 Config
.ToRemove
.addMatcher({Arg
->getValue(), UseRegexp
});
828 for (auto Arg
: InputArgs
.filtered(STRIP_strip_symbol
))
829 Config
.SymbolsToRemove
.addMatcher({Arg
->getValue(), UseRegexp
});
831 for (auto Arg
: InputArgs
.filtered(STRIP_keep_symbol
))
832 Config
.SymbolsToKeep
.addMatcher({Arg
->getValue(), UseRegexp
});
834 if (!InputArgs
.hasArg(STRIP_no_strip_all
) && !Config
.StripDebug
&&
835 !Config
.StripUnneeded
&& Config
.DiscardMode
== DiscardType::None
&&
836 !Config
.StripAllGNU
&& Config
.SymbolsToRemove
.empty())
837 Config
.StripAll
= true;
839 if (Config
.DiscardMode
== DiscardType::All
)
840 Config
.StripDebug
= true;
842 Config
.DeterministicArchives
=
843 InputArgs
.hasFlag(STRIP_enable_deterministic_archives
,
844 STRIP_disable_deterministic_archives
, /*default=*/true);
846 Config
.PreserveDates
= InputArgs
.hasArg(STRIP_preserve_dates
);
847 Config
.InputFormat
= FileFormat::Unspecified
;
848 Config
.OutputFormat
= FileFormat::Unspecified
;
851 if (Positional
.size() == 1) {
852 Config
.InputFilename
= Positional
[0];
853 Config
.OutputFilename
=
854 InputArgs
.getLastArgValue(STRIP_output
, Positional
[0]);
855 DC
.CopyConfigs
.push_back(std::move(Config
));
857 StringMap
<unsigned> InputFiles
;
858 for (StringRef Filename
: Positional
) {
859 if (InputFiles
[Filename
]++ == 1) {
861 return createStringError(
862 errc::invalid_argument
,
863 "cannot specify '-' as an input file more than once");
864 if (Error E
= ErrorCallback(createStringError(
865 errc::invalid_argument
, "'%s' was already specified",
866 Filename
.str().c_str())))
869 Config
.InputFilename
= Filename
;
870 Config
.OutputFilename
= Filename
;
871 DC
.CopyConfigs
.push_back(Config
);
875 if (Config
.PreserveDates
&& (is_contained(Positional
, "-") ||
876 InputArgs
.getLastArgValue(STRIP_output
) == "-"))
877 return createStringError(errc::invalid_argument
,
878 "--preserve-dates requires a file");
880 return std::move(DC
);
883 } // namespace objcopy