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 // Parse value given with --add-symbol option and create the
182 // new symbol if possible. The value format for --add-symbol is:
184 // <name>=[<section>:]<value>[,<flags>]
187 // <name> - symbol name, can be empty string
188 // <section> - optional section name. If not given ABS symbol is created
189 // <value> - symbol value, can be decimal or hexadecimal number prefixed
191 // <flags> - optional flags affecting symbol type, binding or visibility:
192 // The following are currently supported:
194 // global, local, weak, default, hidden, file, section, object,
195 // indirect-function.
197 // The following flags are ignored and provided for GNU
198 // compatibility only:
200 // warning, debug, constructor, indirect, synthetic,
201 // unique-object, before=<symbol>.
204 std::tie(SI
.SymbolName
, Value
) = FlagValue
.split('=');
206 return createStringError(
207 errc::invalid_argument
,
208 "bad format for --add-symbol, missing '=' after '%s'",
209 SI
.SymbolName
.str().c_str());
211 if (Value
.contains(':')) {
212 std::tie(SI
.SectionName
, Value
) = Value
.split(':');
213 if (SI
.SectionName
.empty() || Value
.empty())
214 return createStringError(
215 errc::invalid_argument
,
216 "bad format for --add-symbol, missing section name or symbol value");
219 SmallVector
<StringRef
, 6> Flags
;
220 Value
.split(Flags
, ',');
221 if (Flags
[0].getAsInteger(0, SI
.Value
))
222 return createStringError(errc::invalid_argument
, "bad symbol value: '%s'",
223 Flags
[0].str().c_str());
225 using Functor
= std::function
<void(void)>;
226 SmallVector
<StringRef
, 6> UnsupportedFlags
;
227 for (size_t I
= 1, NumFlags
= Flags
.size(); I
< NumFlags
; ++I
)
228 static_cast<Functor
>(
229 StringSwitch
<Functor
>(Flags
[I
])
230 .CaseLower("global", [&SI
] { SI
.Bind
= ELF::STB_GLOBAL
; })
231 .CaseLower("local", [&SI
] { SI
.Bind
= ELF::STB_LOCAL
; })
232 .CaseLower("weak", [&SI
] { SI
.Bind
= ELF::STB_WEAK
; })
233 .CaseLower("default", [&SI
] { SI
.Visibility
= ELF::STV_DEFAULT
; })
234 .CaseLower("hidden", [&SI
] { SI
.Visibility
= ELF::STV_HIDDEN
; })
235 .CaseLower("file", [&SI
] { SI
.Type
= ELF::STT_FILE
; })
236 .CaseLower("section", [&SI
] { SI
.Type
= ELF::STT_SECTION
; })
237 .CaseLower("object", [&SI
] { SI
.Type
= ELF::STT_OBJECT
; })
238 .CaseLower("function", [&SI
] { SI
.Type
= ELF::STT_FUNC
; })
239 .CaseLower("indirect-function",
240 [&SI
] { SI
.Type
= ELF::STT_GNU_IFUNC
; })
241 .CaseLower("debug", [] {})
242 .CaseLower("constructor", [] {})
243 .CaseLower("warning", [] {})
244 .CaseLower("indirect", [] {})
245 .CaseLower("synthetic", [] {})
246 .CaseLower("unique-object", [] {})
247 .StartsWithLower("before", [] {})
248 .Default([&] { UnsupportedFlags
.push_back(Flags
[I
]); }))();
249 if (!UnsupportedFlags
.empty())
250 return createStringError(errc::invalid_argument
,
251 "unsupported flag%s for --add-symbol: '%s'",
252 UnsupportedFlags
.size() > 1 ? "s" : "",
253 join(UnsupportedFlags
, "', '").c_str());
257 static const StringMap
<MachineInfo
> ArchMap
{
258 // Name, {EMachine, 64bit, LittleEndian}
259 {"aarch64", {ELF::EM_AARCH64
, true, true}},
260 {"arm", {ELF::EM_ARM
, false, true}},
261 {"i386", {ELF::EM_386
, false, true}},
262 {"i386:x86-64", {ELF::EM_X86_64
, true, true}},
263 {"mips", {ELF::EM_MIPS
, false, false}},
264 {"powerpc:common64", {ELF::EM_PPC64
, true, true}},
265 {"riscv:rv32", {ELF::EM_RISCV
, false, true}},
266 {"riscv:rv64", {ELF::EM_RISCV
, true, true}},
267 {"sparc", {ELF::EM_SPARC
, false, false}},
268 {"sparcel", {ELF::EM_SPARC
, false, true}},
269 {"x86-64", {ELF::EM_X86_64
, true, true}},
272 static Expected
<const MachineInfo
&> getMachineInfo(StringRef Arch
) {
273 auto Iter
= ArchMap
.find(Arch
);
274 if (Iter
== std::end(ArchMap
))
275 return createStringError(errc::invalid_argument
,
276 "invalid architecture: '%s'", Arch
.str().c_str());
277 return Iter
->getValue();
285 // FIXME: consolidate with the bfd parsing used by lld.
286 static const StringMap
<MachineInfo
> TargetMap
{
287 // Name, {EMachine, 64bit, LittleEndian}
289 {"elf32-i386", {ELF::EM_386
, false, true}},
290 {"elf32-x86-64", {ELF::EM_X86_64
, false, true}},
291 {"elf64-x86-64", {ELF::EM_X86_64
, true, true}},
293 {"elf32-iamcu", {ELF::EM_IAMCU
, false, true}},
295 {"elf32-littlearm", {ELF::EM_ARM
, false, true}},
297 {"elf64-aarch64", {ELF::EM_AARCH64
, true, true}},
298 {"elf64-littleaarch64", {ELF::EM_AARCH64
, true, true}},
300 {"elf32-littleriscv", {ELF::EM_RISCV
, false, true}},
301 {"elf64-littleriscv", {ELF::EM_RISCV
, true, true}},
303 {"elf32-powerpc", {ELF::EM_PPC
, false, false}},
304 {"elf32-powerpcle", {ELF::EM_PPC
, false, true}},
305 {"elf64-powerpc", {ELF::EM_PPC64
, true, false}},
306 {"elf64-powerpcle", {ELF::EM_PPC64
, true, true}},
308 {"elf32-bigmips", {ELF::EM_MIPS
, false, false}},
309 {"elf32-ntradbigmips", {ELF::EM_MIPS
, false, false}},
310 {"elf32-ntradlittlemips", {ELF::EM_MIPS
, false, true}},
311 {"elf32-tradbigmips", {ELF::EM_MIPS
, false, false}},
312 {"elf32-tradlittlemips", {ELF::EM_MIPS
, false, true}},
313 {"elf64-tradbigmips", {ELF::EM_MIPS
, true, false}},
314 {"elf64-tradlittlemips", {ELF::EM_MIPS
, true, true}},
316 {"elf32-sparc", {ELF::EM_SPARC
, false, false}},
317 {"elf32-sparcel", {ELF::EM_SPARC
, false, true}},
320 static Expected
<TargetInfo
>
321 getOutputTargetInfoByTargetName(StringRef TargetName
) {
322 StringRef OriginalTargetName
= TargetName
;
323 bool IsFreeBSD
= TargetName
.consume_back("-freebsd");
324 auto Iter
= TargetMap
.find(TargetName
);
325 if (Iter
== std::end(TargetMap
))
326 return createStringError(errc::invalid_argument
,
327 "invalid output format: '%s'",
328 OriginalTargetName
.str().c_str());
329 MachineInfo MI
= Iter
->getValue();
331 MI
.OSABI
= ELF::ELFOSABI_FREEBSD
;
334 if (TargetName
.startswith("elf"))
335 Format
= FileFormat::ELF
;
337 // This should never happen because `TargetName` is valid (it certainly
338 // exists in the TargetMap).
339 llvm_unreachable("unknown target prefix");
341 return {TargetInfo
{Format
, MI
}};
344 static Error
addSymbolsFromFile(std::vector
<NameOrRegex
> &Symbols
,
345 BumpPtrAllocator
&Alloc
, StringRef Filename
,
347 StringSaver
Saver(Alloc
);
348 SmallVector
<StringRef
, 16> Lines
;
349 auto BufOrErr
= MemoryBuffer::getFile(Filename
);
351 return createFileError(Filename
, BufOrErr
.getError());
353 BufOrErr
.get()->getBuffer().split(Lines
, '\n');
354 for (StringRef Line
: Lines
) {
355 // Ignore everything after '#', trim whitespace, and only add the symbol if
357 auto TrimmedLine
= Line
.split('#').first
.trim();
358 if (!TrimmedLine
.empty())
359 Symbols
.emplace_back(Saver
.save(TrimmedLine
), UseRegex
);
362 return Error::success();
365 NameOrRegex::NameOrRegex(StringRef Pattern
, bool IsRegex
) {
371 SmallVector
<char, 32> Data
;
372 R
= std::make_shared
<Regex
>(
373 ("^" + Pattern
.ltrim('^').rtrim('$') + "$").toStringRef(Data
));
376 static Error
addSymbolsToRenameFromFile(StringMap
<StringRef
> &SymbolsToRename
,
377 BumpPtrAllocator
&Alloc
,
378 StringRef Filename
) {
379 StringSaver
Saver(Alloc
);
380 SmallVector
<StringRef
, 16> Lines
;
381 auto BufOrErr
= MemoryBuffer::getFile(Filename
);
383 return createFileError(Filename
, BufOrErr
.getError());
385 BufOrErr
.get()->getBuffer().split(Lines
, '\n');
386 size_t NumLines
= Lines
.size();
387 for (size_t LineNo
= 0; LineNo
< NumLines
; ++LineNo
) {
388 StringRef TrimmedLine
= Lines
[LineNo
].split('#').first
.trim();
389 if (TrimmedLine
.empty())
392 std::pair
<StringRef
, StringRef
> Pair
= Saver
.save(TrimmedLine
).split(' ');
393 StringRef NewName
= Pair
.second
.trim();
395 return createStringError(errc::invalid_argument
,
396 "%s:%zu: missing new symbol name",
397 Filename
.str().c_str(), LineNo
+ 1);
398 SymbolsToRename
.insert({Pair
.first
, NewName
});
400 return Error::success();
403 template <class T
> static ErrorOr
<T
> getAsInteger(StringRef Val
) {
405 if (Val
.getAsInteger(0, Result
))
406 return errc::invalid_argument
;
410 // ParseObjcopyOptions returns the config and sets the input arguments. If a
411 // help flag is set then ParseObjcopyOptions will print the help messege and
413 Expected
<DriverConfig
> parseObjcopyOptions(ArrayRef
<const char *> ArgsArr
) {
416 unsigned MissingArgumentIndex
, MissingArgumentCount
;
417 llvm::opt::InputArgList InputArgs
=
418 T
.ParseArgs(ArgsArr
, MissingArgumentIndex
, MissingArgumentCount
);
420 if (InputArgs
.size() == 0) {
421 T
.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
425 if (InputArgs
.hasArg(OBJCOPY_help
)) {
426 T
.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
430 if (InputArgs
.hasArg(OBJCOPY_version
)) {
431 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
432 cl::PrintVersionMessage();
436 SmallVector
<const char *, 2> Positional
;
438 for (auto Arg
: InputArgs
.filtered(OBJCOPY_UNKNOWN
))
439 return createStringError(errc::invalid_argument
, "unknown argument '%s'",
440 Arg
->getAsString(InputArgs
).c_str());
442 for (auto Arg
: InputArgs
.filtered(OBJCOPY_INPUT
))
443 Positional
.push_back(Arg
->getValue());
445 if (Positional
.empty())
446 return createStringError(errc::invalid_argument
, "no input file specified");
448 if (Positional
.size() > 2)
449 return createStringError(errc::invalid_argument
,
450 "too many positional arguments");
453 Config
.InputFilename
= Positional
[0];
454 Config
.OutputFilename
= Positional
[Positional
.size() == 1 ? 0 : 1];
455 if (InputArgs
.hasArg(OBJCOPY_target
) &&
456 (InputArgs
.hasArg(OBJCOPY_input_target
) ||
457 InputArgs
.hasArg(OBJCOPY_output_target
)))
458 return createStringError(
459 errc::invalid_argument
,
460 "--target cannot be used with --input-target or --output-target");
462 bool UseRegex
= InputArgs
.hasArg(OBJCOPY_regex
);
463 StringRef InputFormat
, OutputFormat
;
464 if (InputArgs
.hasArg(OBJCOPY_target
)) {
465 InputFormat
= InputArgs
.getLastArgValue(OBJCOPY_target
);
466 OutputFormat
= InputArgs
.getLastArgValue(OBJCOPY_target
);
468 InputFormat
= InputArgs
.getLastArgValue(OBJCOPY_input_target
);
469 OutputFormat
= InputArgs
.getLastArgValue(OBJCOPY_output_target
);
472 // FIXME: Currently, we ignore the target for non-binary/ihex formats
473 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
474 // format by llvm::object::createBinary regardless of the option value.
475 Config
.InputFormat
= StringSwitch
<FileFormat
>(InputFormat
)
476 .Case("binary", FileFormat::Binary
)
477 .Case("ihex", FileFormat::IHex
)
478 .Default(FileFormat::Unspecified
);
479 if (Config
.InputFormat
== FileFormat::Binary
) {
480 auto BinaryArch
= InputArgs
.getLastArgValue(OBJCOPY_binary_architecture
);
481 if (BinaryArch
.empty())
482 return createStringError(
483 errc::invalid_argument
,
484 "specified binary input without specifiying an architecture");
485 Expected
<const MachineInfo
&> MI
= getMachineInfo(BinaryArch
);
487 return MI
.takeError();
488 Config
.BinaryArch
= *MI
;
491 Config
.OutputFormat
= StringSwitch
<FileFormat
>(OutputFormat
)
492 .Case("binary", FileFormat::Binary
)
493 .Case("ihex", FileFormat::IHex
)
494 .Default(FileFormat::Unspecified
);
495 if (Config
.OutputFormat
== FileFormat::Unspecified
&& !OutputFormat
.empty()) {
496 Expected
<TargetInfo
> Target
= getOutputTargetInfoByTargetName(OutputFormat
);
498 return Target
.takeError();
499 Config
.OutputFormat
= Target
->Format
;
500 Config
.OutputArch
= Target
->Machine
;
503 if (auto Arg
= InputArgs
.getLastArg(OBJCOPY_compress_debug_sections
,
504 OBJCOPY_compress_debug_sections_eq
)) {
505 Config
.CompressionType
= DebugCompressionType::Z
;
507 if (Arg
->getOption().getID() == OBJCOPY_compress_debug_sections_eq
) {
508 Config
.CompressionType
=
509 StringSwitch
<DebugCompressionType
>(
510 InputArgs
.getLastArgValue(OBJCOPY_compress_debug_sections_eq
))
511 .Case("zlib-gnu", DebugCompressionType::GNU
)
512 .Case("zlib", DebugCompressionType::Z
)
513 .Default(DebugCompressionType::None
);
514 if (Config
.CompressionType
== DebugCompressionType::None
)
515 return createStringError(
516 errc::invalid_argument
,
517 "invalid or unsupported --compress-debug-sections format: %s",
518 InputArgs
.getLastArgValue(OBJCOPY_compress_debug_sections_eq
)
522 if (!zlib::isAvailable())
523 return createStringError(
524 errc::invalid_argument
,
525 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
528 Config
.AddGnuDebugLink
= InputArgs
.getLastArgValue(OBJCOPY_add_gnu_debuglink
);
529 // The gnu_debuglink's target is expected to not change or else its CRC would
530 // become invalidated and get rejected. We can avoid recalculating the
531 // checksum for every target file inside an archive by precomputing the CRC
532 // here. This prevents a significant amount of I/O.
533 if (!Config
.AddGnuDebugLink
.empty()) {
534 auto DebugOrErr
= MemoryBuffer::getFile(Config
.AddGnuDebugLink
);
536 return createFileError(Config
.AddGnuDebugLink
, DebugOrErr
.getError());
537 auto Debug
= std::move(*DebugOrErr
);
540 ArrayRef
<char>(Debug
->getBuffer().data(), Debug
->getBuffer().size()));
541 // The CRC32 value needs to be complemented because the JamCRC doesn't
542 // finalize the CRC32 value.
543 Config
.GnuDebugLinkCRC32
= ~CRC
.getCRC();
545 Config
.BuildIdLinkDir
= InputArgs
.getLastArgValue(OBJCOPY_build_id_link_dir
);
546 if (InputArgs
.hasArg(OBJCOPY_build_id_link_input
))
547 Config
.BuildIdLinkInput
=
548 InputArgs
.getLastArgValue(OBJCOPY_build_id_link_input
);
549 if (InputArgs
.hasArg(OBJCOPY_build_id_link_output
))
550 Config
.BuildIdLinkOutput
=
551 InputArgs
.getLastArgValue(OBJCOPY_build_id_link_output
);
552 Config
.SplitDWO
= InputArgs
.getLastArgValue(OBJCOPY_split_dwo
);
553 Config
.SymbolsPrefix
= InputArgs
.getLastArgValue(OBJCOPY_prefix_symbols
);
554 Config
.AllocSectionsPrefix
=
555 InputArgs
.getLastArgValue(OBJCOPY_prefix_alloc_sections
);
556 if (auto Arg
= InputArgs
.getLastArg(OBJCOPY_extract_partition
))
557 Config
.ExtractPartition
= Arg
->getValue();
559 for (auto Arg
: InputArgs
.filtered(OBJCOPY_redefine_symbol
)) {
560 if (!StringRef(Arg
->getValue()).contains('='))
561 return createStringError(errc::invalid_argument
,
562 "bad format for --redefine-sym");
563 auto Old2New
= StringRef(Arg
->getValue()).split('=');
564 if (!Config
.SymbolsToRename
.insert(Old2New
).second
)
565 return createStringError(errc::invalid_argument
,
566 "multiple redefinition of symbol '%s'",
567 Old2New
.first
.str().c_str());
570 for (auto Arg
: InputArgs
.filtered(OBJCOPY_redefine_symbols
))
571 if (Error E
= addSymbolsToRenameFromFile(Config
.SymbolsToRename
, DC
.Alloc
,
575 for (auto Arg
: InputArgs
.filtered(OBJCOPY_rename_section
)) {
576 Expected
<SectionRename
> SR
=
577 parseRenameSectionValue(StringRef(Arg
->getValue()));
579 return SR
.takeError();
580 if (!Config
.SectionsToRename
.try_emplace(SR
->OriginalName
, *SR
).second
)
581 return createStringError(errc::invalid_argument
,
582 "multiple renames of section '%s'",
583 SR
->OriginalName
.str().c_str());
585 for (auto Arg
: InputArgs
.filtered(OBJCOPY_set_section_flags
)) {
586 Expected
<SectionFlagsUpdate
> SFU
=
587 parseSetSectionFlagValue(Arg
->getValue());
589 return SFU
.takeError();
590 if (!Config
.SetSectionFlags
.try_emplace(SFU
->Name
, *SFU
).second
)
591 return createStringError(
592 errc::invalid_argument
,
593 "--set-section-flags set multiple times for section '%s'",
594 SFU
->Name
.str().c_str());
596 // Prohibit combinations of --set-section-flags when the section name is used
597 // by --rename-section, either as a source or a destination.
598 for (const auto &E
: Config
.SectionsToRename
) {
599 const SectionRename
&SR
= E
.second
;
600 if (Config
.SetSectionFlags
.count(SR
.OriginalName
))
601 return createStringError(
602 errc::invalid_argument
,
603 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
604 SR
.OriginalName
.str().c_str(), SR
.OriginalName
.str().c_str(),
605 SR
.NewName
.str().c_str());
606 if (Config
.SetSectionFlags
.count(SR
.NewName
))
607 return createStringError(
608 errc::invalid_argument
,
609 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
610 SR
.NewName
.str().c_str(), SR
.OriginalName
.str().c_str(),
611 SR
.NewName
.str().c_str());
614 for (auto Arg
: InputArgs
.filtered(OBJCOPY_remove_section
))
615 Config
.ToRemove
.emplace_back(Arg
->getValue(), UseRegex
);
616 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_section
))
617 Config
.KeepSection
.emplace_back(Arg
->getValue(), UseRegex
);
618 for (auto Arg
: InputArgs
.filtered(OBJCOPY_only_section
))
619 Config
.OnlySection
.emplace_back(Arg
->getValue(), UseRegex
);
620 for (auto Arg
: InputArgs
.filtered(OBJCOPY_add_section
))
621 Config
.AddSection
.push_back(Arg
->getValue());
622 for (auto Arg
: InputArgs
.filtered(OBJCOPY_dump_section
))
623 Config
.DumpSection
.push_back(Arg
->getValue());
624 Config
.StripAll
= InputArgs
.hasArg(OBJCOPY_strip_all
);
625 Config
.StripAllGNU
= InputArgs
.hasArg(OBJCOPY_strip_all_gnu
);
626 Config
.StripDebug
= InputArgs
.hasArg(OBJCOPY_strip_debug
);
627 Config
.StripDWO
= InputArgs
.hasArg(OBJCOPY_strip_dwo
);
628 Config
.StripSections
= InputArgs
.hasArg(OBJCOPY_strip_sections
);
629 Config
.StripNonAlloc
= InputArgs
.hasArg(OBJCOPY_strip_non_alloc
);
630 Config
.StripUnneeded
= InputArgs
.hasArg(OBJCOPY_strip_unneeded
);
631 Config
.ExtractDWO
= InputArgs
.hasArg(OBJCOPY_extract_dwo
);
632 Config
.ExtractMainPartition
=
633 InputArgs
.hasArg(OBJCOPY_extract_main_partition
);
634 Config
.LocalizeHidden
= InputArgs
.hasArg(OBJCOPY_localize_hidden
);
635 Config
.Weaken
= InputArgs
.hasArg(OBJCOPY_weaken
);
636 if (InputArgs
.hasArg(OBJCOPY_discard_all
, OBJCOPY_discard_locals
))
638 InputArgs
.hasFlag(OBJCOPY_discard_all
, OBJCOPY_discard_locals
)
640 : DiscardType::Locals
;
641 Config
.OnlyKeepDebug
= InputArgs
.hasArg(OBJCOPY_only_keep_debug
);
642 Config
.KeepFileSymbols
= InputArgs
.hasArg(OBJCOPY_keep_file_symbols
);
643 Config
.DecompressDebugSections
=
644 InputArgs
.hasArg(OBJCOPY_decompress_debug_sections
);
645 if (Config
.DiscardMode
== DiscardType::All
)
646 Config
.StripDebug
= true;
647 for (auto Arg
: InputArgs
.filtered(OBJCOPY_localize_symbol
))
648 Config
.SymbolsToLocalize
.emplace_back(Arg
->getValue(), UseRegex
);
649 for (auto Arg
: InputArgs
.filtered(OBJCOPY_localize_symbols
))
650 if (Error E
= addSymbolsFromFile(Config
.SymbolsToLocalize
, DC
.Alloc
,
651 Arg
->getValue(), UseRegex
))
653 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_global_symbol
))
654 Config
.SymbolsToKeepGlobal
.emplace_back(Arg
->getValue(), UseRegex
);
655 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_global_symbols
))
656 if (Error E
= addSymbolsFromFile(Config
.SymbolsToKeepGlobal
, DC
.Alloc
,
657 Arg
->getValue(), UseRegex
))
659 for (auto Arg
: InputArgs
.filtered(OBJCOPY_globalize_symbol
))
660 Config
.SymbolsToGlobalize
.emplace_back(Arg
->getValue(), UseRegex
);
661 for (auto Arg
: InputArgs
.filtered(OBJCOPY_globalize_symbols
))
662 if (Error E
= addSymbolsFromFile(Config
.SymbolsToGlobalize
, DC
.Alloc
,
663 Arg
->getValue(), UseRegex
))
665 for (auto Arg
: InputArgs
.filtered(OBJCOPY_weaken_symbol
))
666 Config
.SymbolsToWeaken
.emplace_back(Arg
->getValue(), UseRegex
);
667 for (auto Arg
: InputArgs
.filtered(OBJCOPY_weaken_symbols
))
668 if (Error E
= addSymbolsFromFile(Config
.SymbolsToWeaken
, DC
.Alloc
,
669 Arg
->getValue(), UseRegex
))
671 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_symbol
))
672 Config
.SymbolsToRemove
.emplace_back(Arg
->getValue(), UseRegex
);
673 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_symbols
))
674 if (Error E
= addSymbolsFromFile(Config
.SymbolsToRemove
, DC
.Alloc
,
675 Arg
->getValue(), UseRegex
))
677 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_unneeded_symbol
))
678 Config
.UnneededSymbolsToRemove
.emplace_back(Arg
->getValue(), UseRegex
);
679 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_unneeded_symbols
))
680 if (Error E
= addSymbolsFromFile(Config
.UnneededSymbolsToRemove
, DC
.Alloc
,
681 Arg
->getValue(), UseRegex
))
683 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_symbol
))
684 Config
.SymbolsToKeep
.emplace_back(Arg
->getValue(), UseRegex
);
685 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_symbols
))
686 if (Error E
= addSymbolsFromFile(Config
.SymbolsToKeep
, DC
.Alloc
,
687 Arg
->getValue(), UseRegex
))
689 for (auto Arg
: InputArgs
.filtered(OBJCOPY_add_symbol
)) {
690 Expected
<NewSymbolInfo
> NSI
= parseNewSymbolInfo(Arg
->getValue());
692 return NSI
.takeError();
693 Config
.SymbolsToAdd
.push_back(*NSI
);
696 Config
.AllowBrokenLinks
= InputArgs
.hasArg(OBJCOPY_allow_broken_links
);
698 Config
.DeterministicArchives
= InputArgs
.hasFlag(
699 OBJCOPY_enable_deterministic_archives
,
700 OBJCOPY_disable_deterministic_archives
, /*default=*/true);
702 Config
.PreserveDates
= InputArgs
.hasArg(OBJCOPY_preserve_dates
);
704 if (Config
.PreserveDates
&&
705 (Config
.OutputFilename
== "-" || Config
.InputFilename
== "-"))
706 return createStringError(errc::invalid_argument
,
707 "--preserve-dates requires a file");
709 for (auto Arg
: InputArgs
)
710 if (Arg
->getOption().matches(OBJCOPY_set_start
)) {
711 auto EAddr
= getAsInteger
<uint64_t>(Arg
->getValue());
713 return createStringError(
714 EAddr
.getError(), "bad entry point address: '%s'", Arg
->getValue());
716 Config
.EntryExpr
= [EAddr
](uint64_t) { return *EAddr
; };
717 } else if (Arg
->getOption().matches(OBJCOPY_change_start
)) {
718 auto EIncr
= getAsInteger
<int64_t>(Arg
->getValue());
720 return createStringError(EIncr
.getError(),
721 "bad entry point increment: '%s'",
723 auto Expr
= Config
.EntryExpr
? std::move(Config
.EntryExpr
)
724 : [](uint64_t A
) { return A
; };
725 Config
.EntryExpr
= [Expr
, EIncr
](uint64_t EAddr
) {
726 return Expr(EAddr
) + *EIncr
;
730 if (Config
.DecompressDebugSections
&&
731 Config
.CompressionType
!= DebugCompressionType::None
) {
732 return createStringError(
733 errc::invalid_argument
,
734 "cannot specify both --compress-debug-sections and "
735 "--decompress-debug-sections");
738 if (Config
.DecompressDebugSections
&& !zlib::isAvailable())
739 return createStringError(
740 errc::invalid_argument
,
741 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
743 if (Config
.ExtractPartition
&& Config
.ExtractMainPartition
)
744 return createStringError(errc::invalid_argument
,
745 "cannot specify --extract-partition together with "
746 "--extract-main-partition");
748 DC
.CopyConfigs
.push_back(std::move(Config
));
749 return std::move(DC
);
752 // ParseStripOptions returns the config and sets the input arguments. If a
753 // help flag is set then ParseStripOptions will print the help messege and
755 Expected
<DriverConfig
>
756 parseStripOptions(ArrayRef
<const char *> ArgsArr
,
757 std::function
<Error(Error
)> ErrorCallback
) {
759 unsigned MissingArgumentIndex
, MissingArgumentCount
;
760 llvm::opt::InputArgList InputArgs
=
761 T
.ParseArgs(ArgsArr
, MissingArgumentIndex
, MissingArgumentCount
);
763 if (InputArgs
.size() == 0) {
764 T
.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
768 if (InputArgs
.hasArg(STRIP_help
)) {
769 T
.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
773 if (InputArgs
.hasArg(STRIP_version
)) {
774 outs() << "llvm-strip, compatible with GNU strip\n";
775 cl::PrintVersionMessage();
779 SmallVector
<StringRef
, 2> Positional
;
780 for (auto Arg
: InputArgs
.filtered(STRIP_UNKNOWN
))
781 return createStringError(errc::invalid_argument
, "unknown argument '%s'",
782 Arg
->getAsString(InputArgs
).c_str());
783 for (auto Arg
: InputArgs
.filtered(STRIP_INPUT
))
784 Positional
.push_back(Arg
->getValue());
786 if (Positional
.empty())
787 return createStringError(errc::invalid_argument
, "no input file specified");
789 if (Positional
.size() > 1 && InputArgs
.hasArg(STRIP_output
))
790 return createStringError(
791 errc::invalid_argument
,
792 "multiple input files cannot be used in combination with -o");
795 bool UseRegexp
= InputArgs
.hasArg(STRIP_regex
);
796 Config
.AllowBrokenLinks
= InputArgs
.hasArg(STRIP_allow_broken_links
);
797 Config
.StripDebug
= InputArgs
.hasArg(STRIP_strip_debug
);
799 if (InputArgs
.hasArg(STRIP_discard_all
, STRIP_discard_locals
))
801 InputArgs
.hasFlag(STRIP_discard_all
, STRIP_discard_locals
)
803 : DiscardType::Locals
;
804 Config
.StripUnneeded
= InputArgs
.hasArg(STRIP_strip_unneeded
);
805 if (auto Arg
= InputArgs
.getLastArg(STRIP_strip_all
, STRIP_no_strip_all
))
806 Config
.StripAll
= Arg
->getOption().getID() == STRIP_strip_all
;
807 Config
.StripAllGNU
= InputArgs
.hasArg(STRIP_strip_all_gnu
);
808 Config
.OnlyKeepDebug
= InputArgs
.hasArg(STRIP_only_keep_debug
);
809 Config
.KeepFileSymbols
= InputArgs
.hasArg(STRIP_keep_file_symbols
);
811 for (auto Arg
: InputArgs
.filtered(STRIP_keep_section
))
812 Config
.KeepSection
.emplace_back(Arg
->getValue(), UseRegexp
);
814 for (auto Arg
: InputArgs
.filtered(STRIP_remove_section
))
815 Config
.ToRemove
.emplace_back(Arg
->getValue(), UseRegexp
);
817 for (auto Arg
: InputArgs
.filtered(STRIP_strip_symbol
))
818 Config
.SymbolsToRemove
.emplace_back(Arg
->getValue(), UseRegexp
);
820 for (auto Arg
: InputArgs
.filtered(STRIP_keep_symbol
))
821 Config
.SymbolsToKeep
.emplace_back(Arg
->getValue(), UseRegexp
);
823 if (!InputArgs
.hasArg(STRIP_no_strip_all
) && !Config
.StripDebug
&&
824 !Config
.StripUnneeded
&& Config
.DiscardMode
== DiscardType::None
&&
825 !Config
.StripAllGNU
&& Config
.SymbolsToRemove
.empty())
826 Config
.StripAll
= true;
828 if (Config
.DiscardMode
== DiscardType::All
)
829 Config
.StripDebug
= true;
831 Config
.DeterministicArchives
=
832 InputArgs
.hasFlag(STRIP_enable_deterministic_archives
,
833 STRIP_disable_deterministic_archives
, /*default=*/true);
835 Config
.PreserveDates
= InputArgs
.hasArg(STRIP_preserve_dates
);
836 Config
.InputFormat
= FileFormat::Unspecified
;
837 Config
.OutputFormat
= FileFormat::Unspecified
;
840 if (Positional
.size() == 1) {
841 Config
.InputFilename
= Positional
[0];
842 Config
.OutputFilename
=
843 InputArgs
.getLastArgValue(STRIP_output
, Positional
[0]);
844 DC
.CopyConfigs
.push_back(std::move(Config
));
846 StringMap
<unsigned> InputFiles
;
847 for (StringRef Filename
: Positional
) {
848 if (InputFiles
[Filename
]++ == 1) {
850 return createStringError(
851 errc::invalid_argument
,
852 "cannot specify '-' as an input file more than once");
853 if (Error E
= ErrorCallback(createStringError(
854 errc::invalid_argument
, "'%s' was already specified",
855 Filename
.str().c_str())))
858 Config
.InputFilename
= Filename
;
859 Config
.OutputFilename
= Filename
;
860 DC
.CopyConfigs
.push_back(Config
);
864 if (Config
.PreserveDates
&& (is_contained(Positional
, "-") ||
865 InputArgs
.getLastArgValue(STRIP_output
) == "-"))
866 return createStringError(errc::invalid_argument
,
867 "--preserve-dates requires a file");
869 return std::move(DC
);
872 } // namespace objcopy