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());
261 static const StringMap
<MachineInfo
> ArchMap
{
262 // Name, {EMachine, 64bit, LittleEndian}
263 {"aarch64", {ELF::EM_AARCH64
, true, true}},
264 {"arm", {ELF::EM_ARM
, false, true}},
265 {"i386", {ELF::EM_386
, false, true}},
266 {"i386:x86-64", {ELF::EM_X86_64
, true, true}},
267 {"mips", {ELF::EM_MIPS
, false, false}},
268 {"powerpc:common64", {ELF::EM_PPC64
, true, true}},
269 {"riscv:rv32", {ELF::EM_RISCV
, false, true}},
270 {"riscv:rv64", {ELF::EM_RISCV
, true, true}},
271 {"sparc", {ELF::EM_SPARC
, false, false}},
272 {"sparcel", {ELF::EM_SPARC
, false, true}},
273 {"x86-64", {ELF::EM_X86_64
, true, true}},
276 static Expected
<const MachineInfo
&> getMachineInfo(StringRef Arch
) {
277 auto Iter
= ArchMap
.find(Arch
);
278 if (Iter
== std::end(ArchMap
))
279 return createStringError(errc::invalid_argument
,
280 "invalid architecture: '%s'", Arch
.str().c_str());
281 return Iter
->getValue();
289 // FIXME: consolidate with the bfd parsing used by lld.
290 static const StringMap
<MachineInfo
> TargetMap
{
291 // Name, {EMachine, 64bit, LittleEndian}
293 {"elf32-i386", {ELF::EM_386
, false, true}},
294 {"elf32-x86-64", {ELF::EM_X86_64
, false, true}},
295 {"elf64-x86-64", {ELF::EM_X86_64
, true, true}},
297 {"elf32-iamcu", {ELF::EM_IAMCU
, false, true}},
299 {"elf32-littlearm", {ELF::EM_ARM
, false, true}},
301 {"elf64-aarch64", {ELF::EM_AARCH64
, true, true}},
302 {"elf64-littleaarch64", {ELF::EM_AARCH64
, true, true}},
304 {"elf32-littleriscv", {ELF::EM_RISCV
, false, true}},
305 {"elf64-littleriscv", {ELF::EM_RISCV
, true, true}},
307 {"elf32-powerpc", {ELF::EM_PPC
, false, false}},
308 {"elf32-powerpcle", {ELF::EM_PPC
, false, true}},
309 {"elf64-powerpc", {ELF::EM_PPC64
, true, false}},
310 {"elf64-powerpcle", {ELF::EM_PPC64
, true, true}},
312 {"elf32-bigmips", {ELF::EM_MIPS
, false, false}},
313 {"elf32-ntradbigmips", {ELF::EM_MIPS
, false, false}},
314 {"elf32-ntradlittlemips", {ELF::EM_MIPS
, false, true}},
315 {"elf32-tradbigmips", {ELF::EM_MIPS
, false, false}},
316 {"elf32-tradlittlemips", {ELF::EM_MIPS
, false, true}},
317 {"elf64-tradbigmips", {ELF::EM_MIPS
, true, false}},
318 {"elf64-tradlittlemips", {ELF::EM_MIPS
, true, true}},
320 {"elf32-sparc", {ELF::EM_SPARC
, false, false}},
321 {"elf32-sparcel", {ELF::EM_SPARC
, false, true}},
324 static Expected
<TargetInfo
>
325 getOutputTargetInfoByTargetName(StringRef TargetName
) {
326 StringRef OriginalTargetName
= TargetName
;
327 bool IsFreeBSD
= TargetName
.consume_back("-freebsd");
328 auto Iter
= TargetMap
.find(TargetName
);
329 if (Iter
== std::end(TargetMap
))
330 return createStringError(errc::invalid_argument
,
331 "invalid output format: '%s'",
332 OriginalTargetName
.str().c_str());
333 MachineInfo MI
= Iter
->getValue();
335 MI
.OSABI
= ELF::ELFOSABI_FREEBSD
;
338 if (TargetName
.startswith("elf"))
339 Format
= FileFormat::ELF
;
341 // This should never happen because `TargetName` is valid (it certainly
342 // exists in the TargetMap).
343 llvm_unreachable("unknown target prefix");
345 return {TargetInfo
{Format
, MI
}};
348 static Error
addSymbolsFromFile(NameMatcher
&Symbols
, BumpPtrAllocator
&Alloc
,
349 StringRef Filename
, bool UseRegex
) {
350 StringSaver
Saver(Alloc
);
351 SmallVector
<StringRef
, 16> Lines
;
352 auto BufOrErr
= MemoryBuffer::getFile(Filename
);
354 return createFileError(Filename
, BufOrErr
.getError());
356 BufOrErr
.get()->getBuffer().split(Lines
, '\n');
357 for (StringRef Line
: Lines
) {
358 // Ignore everything after '#', trim whitespace, and only add the symbol if
360 auto TrimmedLine
= Line
.split('#').first
.trim();
361 if (!TrimmedLine
.empty())
362 Symbols
.addMatcher({Saver
.save(TrimmedLine
), UseRegex
});
365 return Error::success();
368 NameOrRegex::NameOrRegex(StringRef Pattern
, bool IsRegex
) {
374 SmallVector
<char, 32> Data
;
375 R
= std::make_shared
<Regex
>(
376 ("^" + Pattern
.ltrim('^').rtrim('$') + "$").toStringRef(Data
));
379 static Error
addSymbolsToRenameFromFile(StringMap
<StringRef
> &SymbolsToRename
,
380 BumpPtrAllocator
&Alloc
,
381 StringRef Filename
) {
382 StringSaver
Saver(Alloc
);
383 SmallVector
<StringRef
, 16> Lines
;
384 auto BufOrErr
= MemoryBuffer::getFile(Filename
);
386 return createFileError(Filename
, BufOrErr
.getError());
388 BufOrErr
.get()->getBuffer().split(Lines
, '\n');
389 size_t NumLines
= Lines
.size();
390 for (size_t LineNo
= 0; LineNo
< NumLines
; ++LineNo
) {
391 StringRef TrimmedLine
= Lines
[LineNo
].split('#').first
.trim();
392 if (TrimmedLine
.empty())
395 std::pair
<StringRef
, StringRef
> Pair
= Saver
.save(TrimmedLine
).split(' ');
396 StringRef NewName
= Pair
.second
.trim();
398 return createStringError(errc::invalid_argument
,
399 "%s:%zu: missing new symbol name",
400 Filename
.str().c_str(), LineNo
+ 1);
401 SymbolsToRename
.insert({Pair
.first
, NewName
});
403 return Error::success();
406 template <class T
> static ErrorOr
<T
> getAsInteger(StringRef Val
) {
408 if (Val
.getAsInteger(0, Result
))
409 return errc::invalid_argument
;
413 // ParseObjcopyOptions returns the config and sets the input arguments. If a
414 // help flag is set then ParseObjcopyOptions will print the help messege and
416 Expected
<DriverConfig
> parseObjcopyOptions(ArrayRef
<const char *> ArgsArr
) {
419 unsigned MissingArgumentIndex
, MissingArgumentCount
;
420 llvm::opt::InputArgList InputArgs
=
421 T
.ParseArgs(ArgsArr
, MissingArgumentIndex
, MissingArgumentCount
);
423 if (InputArgs
.size() == 0) {
424 T
.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
428 if (InputArgs
.hasArg(OBJCOPY_help
)) {
429 T
.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
433 if (InputArgs
.hasArg(OBJCOPY_version
)) {
434 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
435 cl::PrintVersionMessage();
439 SmallVector
<const char *, 2> Positional
;
441 for (auto Arg
: InputArgs
.filtered(OBJCOPY_UNKNOWN
))
442 return createStringError(errc::invalid_argument
, "unknown argument '%s'",
443 Arg
->getAsString(InputArgs
).c_str());
445 for (auto Arg
: InputArgs
.filtered(OBJCOPY_INPUT
))
446 Positional
.push_back(Arg
->getValue());
448 if (Positional
.empty())
449 return createStringError(errc::invalid_argument
, "no input file specified");
451 if (Positional
.size() > 2)
452 return createStringError(errc::invalid_argument
,
453 "too many positional arguments");
456 Config
.InputFilename
= Positional
[0];
457 Config
.OutputFilename
= Positional
[Positional
.size() == 1 ? 0 : 1];
458 if (InputArgs
.hasArg(OBJCOPY_target
) &&
459 (InputArgs
.hasArg(OBJCOPY_input_target
) ||
460 InputArgs
.hasArg(OBJCOPY_output_target
)))
461 return createStringError(
462 errc::invalid_argument
,
463 "--target cannot be used with --input-target or --output-target");
465 bool UseRegex
= InputArgs
.hasArg(OBJCOPY_regex
);
466 StringRef InputFormat
, OutputFormat
;
467 if (InputArgs
.hasArg(OBJCOPY_target
)) {
468 InputFormat
= InputArgs
.getLastArgValue(OBJCOPY_target
);
469 OutputFormat
= InputArgs
.getLastArgValue(OBJCOPY_target
);
471 InputFormat
= InputArgs
.getLastArgValue(OBJCOPY_input_target
);
472 OutputFormat
= InputArgs
.getLastArgValue(OBJCOPY_output_target
);
475 // FIXME: Currently, we ignore the target for non-binary/ihex formats
476 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
477 // format by llvm::object::createBinary regardless of the option value.
478 Config
.InputFormat
= StringSwitch
<FileFormat
>(InputFormat
)
479 .Case("binary", FileFormat::Binary
)
480 .Case("ihex", FileFormat::IHex
)
481 .Default(FileFormat::Unspecified
);
482 if (Config
.InputFormat
== FileFormat::Binary
) {
483 auto BinaryArch
= InputArgs
.getLastArgValue(OBJCOPY_binary_architecture
);
484 if (BinaryArch
.empty())
485 return createStringError(
486 errc::invalid_argument
,
487 "specified binary input without specifiying an architecture");
488 Expected
<const MachineInfo
&> MI
= getMachineInfo(BinaryArch
);
490 return MI
.takeError();
491 Config
.BinaryArch
= *MI
;
494 if (opt::Arg
*A
= InputArgs
.getLastArg(OBJCOPY_new_symbol_visibility
)) {
495 const uint8_t Invalid
= 0xff;
496 Config
.NewSymbolVisibility
= StringSwitch
<uint8_t>(A
->getValue())
497 .Case("default", ELF::STV_DEFAULT
)
498 .Case("hidden", ELF::STV_HIDDEN
)
499 .Case("internal", ELF::STV_INTERNAL
)
500 .Case("protected", ELF::STV_PROTECTED
)
503 if (Config
.NewSymbolVisibility
== Invalid
)
504 return createStringError(
505 errc::invalid_argument
, "'%s' is not a valid symbol visibility",
506 InputArgs
.getLastArgValue(OBJCOPY_new_symbol_visibility
).str().c_str());
509 Config
.OutputFormat
= StringSwitch
<FileFormat
>(OutputFormat
)
510 .Case("binary", FileFormat::Binary
)
511 .Case("ihex", FileFormat::IHex
)
512 .Default(FileFormat::Unspecified
);
513 if (Config
.OutputFormat
== FileFormat::Unspecified
&& !OutputFormat
.empty()) {
514 Expected
<TargetInfo
> Target
= getOutputTargetInfoByTargetName(OutputFormat
);
516 return Target
.takeError();
517 Config
.OutputFormat
= Target
->Format
;
518 Config
.OutputArch
= Target
->Machine
;
521 if (auto Arg
= InputArgs
.getLastArg(OBJCOPY_compress_debug_sections
,
522 OBJCOPY_compress_debug_sections_eq
)) {
523 Config
.CompressionType
= DebugCompressionType::Z
;
525 if (Arg
->getOption().getID() == OBJCOPY_compress_debug_sections_eq
) {
526 Config
.CompressionType
=
527 StringSwitch
<DebugCompressionType
>(
528 InputArgs
.getLastArgValue(OBJCOPY_compress_debug_sections_eq
))
529 .Case("zlib-gnu", DebugCompressionType::GNU
)
530 .Case("zlib", DebugCompressionType::Z
)
531 .Default(DebugCompressionType::None
);
532 if (Config
.CompressionType
== DebugCompressionType::None
)
533 return createStringError(
534 errc::invalid_argument
,
535 "invalid or unsupported --compress-debug-sections format: %s",
536 InputArgs
.getLastArgValue(OBJCOPY_compress_debug_sections_eq
)
540 if (!zlib::isAvailable())
541 return createStringError(
542 errc::invalid_argument
,
543 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
546 Config
.AddGnuDebugLink
= InputArgs
.getLastArgValue(OBJCOPY_add_gnu_debuglink
);
547 // The gnu_debuglink's target is expected to not change or else its CRC would
548 // become invalidated and get rejected. We can avoid recalculating the
549 // checksum for every target file inside an archive by precomputing the CRC
550 // here. This prevents a significant amount of I/O.
551 if (!Config
.AddGnuDebugLink
.empty()) {
552 auto DebugOrErr
= MemoryBuffer::getFile(Config
.AddGnuDebugLink
);
554 return createFileError(Config
.AddGnuDebugLink
, DebugOrErr
.getError());
555 auto Debug
= std::move(*DebugOrErr
);
558 ArrayRef
<char>(Debug
->getBuffer().data(), Debug
->getBuffer().size()));
559 // The CRC32 value needs to be complemented because the JamCRC doesn't
560 // finalize the CRC32 value.
561 Config
.GnuDebugLinkCRC32
= ~CRC
.getCRC();
563 Config
.BuildIdLinkDir
= InputArgs
.getLastArgValue(OBJCOPY_build_id_link_dir
);
564 if (InputArgs
.hasArg(OBJCOPY_build_id_link_input
))
565 Config
.BuildIdLinkInput
=
566 InputArgs
.getLastArgValue(OBJCOPY_build_id_link_input
);
567 if (InputArgs
.hasArg(OBJCOPY_build_id_link_output
))
568 Config
.BuildIdLinkOutput
=
569 InputArgs
.getLastArgValue(OBJCOPY_build_id_link_output
);
570 Config
.SplitDWO
= InputArgs
.getLastArgValue(OBJCOPY_split_dwo
);
571 Config
.SymbolsPrefix
= InputArgs
.getLastArgValue(OBJCOPY_prefix_symbols
);
572 Config
.AllocSectionsPrefix
=
573 InputArgs
.getLastArgValue(OBJCOPY_prefix_alloc_sections
);
574 if (auto Arg
= InputArgs
.getLastArg(OBJCOPY_extract_partition
))
575 Config
.ExtractPartition
= Arg
->getValue();
577 for (auto Arg
: InputArgs
.filtered(OBJCOPY_redefine_symbol
)) {
578 if (!StringRef(Arg
->getValue()).contains('='))
579 return createStringError(errc::invalid_argument
,
580 "bad format for --redefine-sym");
581 auto Old2New
= StringRef(Arg
->getValue()).split('=');
582 if (!Config
.SymbolsToRename
.insert(Old2New
).second
)
583 return createStringError(errc::invalid_argument
,
584 "multiple redefinition of symbol '%s'",
585 Old2New
.first
.str().c_str());
588 for (auto Arg
: InputArgs
.filtered(OBJCOPY_redefine_symbols
))
589 if (Error E
= addSymbolsToRenameFromFile(Config
.SymbolsToRename
, DC
.Alloc
,
593 for (auto Arg
: InputArgs
.filtered(OBJCOPY_rename_section
)) {
594 Expected
<SectionRename
> SR
=
595 parseRenameSectionValue(StringRef(Arg
->getValue()));
597 return SR
.takeError();
598 if (!Config
.SectionsToRename
.try_emplace(SR
->OriginalName
, *SR
).second
)
599 return createStringError(errc::invalid_argument
,
600 "multiple renames of section '%s'",
601 SR
->OriginalName
.str().c_str());
603 for (auto Arg
: InputArgs
.filtered(OBJCOPY_set_section_flags
)) {
604 Expected
<SectionFlagsUpdate
> SFU
=
605 parseSetSectionFlagValue(Arg
->getValue());
607 return SFU
.takeError();
608 if (!Config
.SetSectionFlags
.try_emplace(SFU
->Name
, *SFU
).second
)
609 return createStringError(
610 errc::invalid_argument
,
611 "--set-section-flags set multiple times for section '%s'",
612 SFU
->Name
.str().c_str());
614 // Prohibit combinations of --set-section-flags when the section name is used
615 // by --rename-section, either as a source or a destination.
616 for (const auto &E
: Config
.SectionsToRename
) {
617 const SectionRename
&SR
= E
.second
;
618 if (Config
.SetSectionFlags
.count(SR
.OriginalName
))
619 return createStringError(
620 errc::invalid_argument
,
621 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
622 SR
.OriginalName
.str().c_str(), SR
.OriginalName
.str().c_str(),
623 SR
.NewName
.str().c_str());
624 if (Config
.SetSectionFlags
.count(SR
.NewName
))
625 return createStringError(
626 errc::invalid_argument
,
627 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
628 SR
.NewName
.str().c_str(), SR
.OriginalName
.str().c_str(),
629 SR
.NewName
.str().c_str());
632 for (auto Arg
: InputArgs
.filtered(OBJCOPY_remove_section
))
633 Config
.ToRemove
.addMatcher({Arg
->getValue(), UseRegex
});
634 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_section
))
635 Config
.KeepSection
.addMatcher({Arg
->getValue(), UseRegex
});
636 for (auto Arg
: InputArgs
.filtered(OBJCOPY_only_section
))
637 Config
.OnlySection
.addMatcher({Arg
->getValue(), UseRegex
});
638 for (auto Arg
: InputArgs
.filtered(OBJCOPY_add_section
)) {
639 StringRef
ArgValue(Arg
->getValue());
640 if (!ArgValue
.contains('='))
641 return createStringError(errc::invalid_argument
,
642 "bad format for --add-section: missing '='");
643 if (ArgValue
.split("=").second
.empty())
644 return createStringError(
645 errc::invalid_argument
,
646 "bad format for --add-section: missing file name");
647 Config
.AddSection
.push_back(ArgValue
);
649 for (auto Arg
: InputArgs
.filtered(OBJCOPY_dump_section
))
650 Config
.DumpSection
.push_back(Arg
->getValue());
651 Config
.StripAll
= InputArgs
.hasArg(OBJCOPY_strip_all
);
652 Config
.StripAllGNU
= InputArgs
.hasArg(OBJCOPY_strip_all_gnu
);
653 Config
.StripDebug
= InputArgs
.hasArg(OBJCOPY_strip_debug
);
654 Config
.StripDWO
= InputArgs
.hasArg(OBJCOPY_strip_dwo
);
655 Config
.StripSections
= InputArgs
.hasArg(OBJCOPY_strip_sections
);
656 Config
.StripNonAlloc
= InputArgs
.hasArg(OBJCOPY_strip_non_alloc
);
657 Config
.StripUnneeded
= InputArgs
.hasArg(OBJCOPY_strip_unneeded
);
658 Config
.ExtractDWO
= InputArgs
.hasArg(OBJCOPY_extract_dwo
);
659 Config
.ExtractMainPartition
=
660 InputArgs
.hasArg(OBJCOPY_extract_main_partition
);
661 Config
.LocalizeHidden
= InputArgs
.hasArg(OBJCOPY_localize_hidden
);
662 Config
.Weaken
= InputArgs
.hasArg(OBJCOPY_weaken
);
663 if (InputArgs
.hasArg(OBJCOPY_discard_all
, OBJCOPY_discard_locals
))
665 InputArgs
.hasFlag(OBJCOPY_discard_all
, OBJCOPY_discard_locals
)
667 : DiscardType::Locals
;
668 Config
.OnlyKeepDebug
= InputArgs
.hasArg(OBJCOPY_only_keep_debug
);
669 Config
.KeepFileSymbols
= InputArgs
.hasArg(OBJCOPY_keep_file_symbols
);
670 Config
.DecompressDebugSections
=
671 InputArgs
.hasArg(OBJCOPY_decompress_debug_sections
);
672 if (Config
.DiscardMode
== DiscardType::All
)
673 Config
.StripDebug
= true;
674 for (auto Arg
: InputArgs
.filtered(OBJCOPY_localize_symbol
))
675 Config
.SymbolsToLocalize
.addMatcher({Arg
->getValue(), UseRegex
});
676 for (auto Arg
: InputArgs
.filtered(OBJCOPY_localize_symbols
))
677 if (Error E
= addSymbolsFromFile(Config
.SymbolsToLocalize
, DC
.Alloc
,
678 Arg
->getValue(), UseRegex
))
680 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_global_symbol
))
681 Config
.SymbolsToKeepGlobal
.addMatcher({Arg
->getValue(), UseRegex
});
682 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_global_symbols
))
683 if (Error E
= addSymbolsFromFile(Config
.SymbolsToKeepGlobal
, DC
.Alloc
,
684 Arg
->getValue(), UseRegex
))
686 for (auto Arg
: InputArgs
.filtered(OBJCOPY_globalize_symbol
))
687 Config
.SymbolsToGlobalize
.addMatcher({Arg
->getValue(), UseRegex
});
688 for (auto Arg
: InputArgs
.filtered(OBJCOPY_globalize_symbols
))
689 if (Error E
= addSymbolsFromFile(Config
.SymbolsToGlobalize
, DC
.Alloc
,
690 Arg
->getValue(), UseRegex
))
692 for (auto Arg
: InputArgs
.filtered(OBJCOPY_weaken_symbol
))
693 Config
.SymbolsToWeaken
.addMatcher({Arg
->getValue(), UseRegex
});
694 for (auto Arg
: InputArgs
.filtered(OBJCOPY_weaken_symbols
))
695 if (Error E
= addSymbolsFromFile(Config
.SymbolsToWeaken
, DC
.Alloc
,
696 Arg
->getValue(), UseRegex
))
698 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_symbol
))
699 Config
.SymbolsToRemove
.addMatcher({Arg
->getValue(), UseRegex
});
700 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_symbols
))
701 if (Error E
= addSymbolsFromFile(Config
.SymbolsToRemove
, DC
.Alloc
,
702 Arg
->getValue(), UseRegex
))
704 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_unneeded_symbol
))
705 Config
.UnneededSymbolsToRemove
.addMatcher({Arg
->getValue(), UseRegex
});
706 for (auto Arg
: InputArgs
.filtered(OBJCOPY_strip_unneeded_symbols
))
707 if (Error E
= addSymbolsFromFile(Config
.UnneededSymbolsToRemove
, DC
.Alloc
,
708 Arg
->getValue(), UseRegex
))
710 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_symbol
))
711 Config
.SymbolsToKeep
.addMatcher({Arg
->getValue(), UseRegex
});
712 for (auto Arg
: InputArgs
.filtered(OBJCOPY_keep_symbols
))
713 if (Error E
= addSymbolsFromFile(Config
.SymbolsToKeep
, DC
.Alloc
,
714 Arg
->getValue(), UseRegex
))
716 for (auto Arg
: InputArgs
.filtered(OBJCOPY_add_symbol
)) {
717 Expected
<NewSymbolInfo
> NSI
= parseNewSymbolInfo(
719 Config
.NewSymbolVisibility
.getValueOr((uint8_t)ELF::STV_DEFAULT
));
721 return NSI
.takeError();
722 Config
.SymbolsToAdd
.push_back(*NSI
);
725 Config
.AllowBrokenLinks
= InputArgs
.hasArg(OBJCOPY_allow_broken_links
);
727 Config
.DeterministicArchives
= InputArgs
.hasFlag(
728 OBJCOPY_enable_deterministic_archives
,
729 OBJCOPY_disable_deterministic_archives
, /*default=*/true);
731 Config
.PreserveDates
= InputArgs
.hasArg(OBJCOPY_preserve_dates
);
733 if (Config
.PreserveDates
&&
734 (Config
.OutputFilename
== "-" || Config
.InputFilename
== "-"))
735 return createStringError(errc::invalid_argument
,
736 "--preserve-dates requires a file");
738 for (auto Arg
: InputArgs
)
739 if (Arg
->getOption().matches(OBJCOPY_set_start
)) {
740 auto EAddr
= getAsInteger
<uint64_t>(Arg
->getValue());
742 return createStringError(
743 EAddr
.getError(), "bad entry point address: '%s'", Arg
->getValue());
745 Config
.EntryExpr
= [EAddr
](uint64_t) { return *EAddr
; };
746 } else if (Arg
->getOption().matches(OBJCOPY_change_start
)) {
747 auto EIncr
= getAsInteger
<int64_t>(Arg
->getValue());
749 return createStringError(EIncr
.getError(),
750 "bad entry point increment: '%s'",
752 auto Expr
= Config
.EntryExpr
? std::move(Config
.EntryExpr
)
753 : [](uint64_t A
) { return A
; };
754 Config
.EntryExpr
= [Expr
, EIncr
](uint64_t EAddr
) {
755 return Expr(EAddr
) + *EIncr
;
759 if (Config
.DecompressDebugSections
&&
760 Config
.CompressionType
!= DebugCompressionType::None
) {
761 return createStringError(
762 errc::invalid_argument
,
763 "cannot specify both --compress-debug-sections and "
764 "--decompress-debug-sections");
767 if (Config
.DecompressDebugSections
&& !zlib::isAvailable())
768 return createStringError(
769 errc::invalid_argument
,
770 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
772 if (Config
.ExtractPartition
&& Config
.ExtractMainPartition
)
773 return createStringError(errc::invalid_argument
,
774 "cannot specify --extract-partition together with "
775 "--extract-main-partition");
777 DC
.CopyConfigs
.push_back(std::move(Config
));
778 return std::move(DC
);
781 // ParseStripOptions returns the config and sets the input arguments. If a
782 // help flag is set then ParseStripOptions will print the help messege and
784 Expected
<DriverConfig
>
785 parseStripOptions(ArrayRef
<const char *> ArgsArr
,
786 std::function
<Error(Error
)> ErrorCallback
) {
788 unsigned MissingArgumentIndex
, MissingArgumentCount
;
789 llvm::opt::InputArgList InputArgs
=
790 T
.ParseArgs(ArgsArr
, MissingArgumentIndex
, MissingArgumentCount
);
792 if (InputArgs
.size() == 0) {
793 T
.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
797 if (InputArgs
.hasArg(STRIP_help
)) {
798 T
.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
802 if (InputArgs
.hasArg(STRIP_version
)) {
803 outs() << "llvm-strip, compatible with GNU strip\n";
804 cl::PrintVersionMessage();
808 SmallVector
<StringRef
, 2> Positional
;
809 for (auto Arg
: InputArgs
.filtered(STRIP_UNKNOWN
))
810 return createStringError(errc::invalid_argument
, "unknown argument '%s'",
811 Arg
->getAsString(InputArgs
).c_str());
812 for (auto Arg
: InputArgs
.filtered(STRIP_INPUT
))
813 Positional
.push_back(Arg
->getValue());
815 if (Positional
.empty())
816 return createStringError(errc::invalid_argument
, "no input file specified");
818 if (Positional
.size() > 1 && InputArgs
.hasArg(STRIP_output
))
819 return createStringError(
820 errc::invalid_argument
,
821 "multiple input files cannot be used in combination with -o");
824 bool UseRegexp
= InputArgs
.hasArg(STRIP_regex
);
825 Config
.AllowBrokenLinks
= InputArgs
.hasArg(STRIP_allow_broken_links
);
826 Config
.StripDebug
= InputArgs
.hasArg(STRIP_strip_debug
);
828 if (InputArgs
.hasArg(STRIP_discard_all
, STRIP_discard_locals
))
830 InputArgs
.hasFlag(STRIP_discard_all
, STRIP_discard_locals
)
832 : DiscardType::Locals
;
833 Config
.StripSections
= InputArgs
.hasArg(STRIP_strip_sections
);
834 Config
.StripUnneeded
= InputArgs
.hasArg(STRIP_strip_unneeded
);
835 if (auto Arg
= InputArgs
.getLastArg(STRIP_strip_all
, STRIP_no_strip_all
))
836 Config
.StripAll
= Arg
->getOption().getID() == STRIP_strip_all
;
837 Config
.StripAllGNU
= InputArgs
.hasArg(STRIP_strip_all_gnu
);
838 Config
.OnlyKeepDebug
= InputArgs
.hasArg(STRIP_only_keep_debug
);
839 Config
.KeepFileSymbols
= InputArgs
.hasArg(STRIP_keep_file_symbols
);
841 for (auto Arg
: InputArgs
.filtered(STRIP_keep_section
))
842 Config
.KeepSection
.addMatcher({Arg
->getValue(), UseRegexp
});
844 for (auto Arg
: InputArgs
.filtered(STRIP_remove_section
))
845 Config
.ToRemove
.addMatcher({Arg
->getValue(), UseRegexp
});
847 for (auto Arg
: InputArgs
.filtered(STRIP_strip_symbol
))
848 Config
.SymbolsToRemove
.addMatcher({Arg
->getValue(), UseRegexp
});
850 for (auto Arg
: InputArgs
.filtered(STRIP_keep_symbol
))
851 Config
.SymbolsToKeep
.addMatcher({Arg
->getValue(), UseRegexp
});
853 if (!InputArgs
.hasArg(STRIP_no_strip_all
) && !Config
.StripDebug
&&
854 !Config
.StripUnneeded
&& Config
.DiscardMode
== DiscardType::None
&&
855 !Config
.StripAllGNU
&& Config
.SymbolsToRemove
.empty())
856 Config
.StripAll
= true;
858 if (Config
.DiscardMode
== DiscardType::All
)
859 Config
.StripDebug
= true;
861 Config
.DeterministicArchives
=
862 InputArgs
.hasFlag(STRIP_enable_deterministic_archives
,
863 STRIP_disable_deterministic_archives
, /*default=*/true);
865 Config
.PreserveDates
= InputArgs
.hasArg(STRIP_preserve_dates
);
866 Config
.InputFormat
= FileFormat::Unspecified
;
867 Config
.OutputFormat
= FileFormat::Unspecified
;
870 if (Positional
.size() == 1) {
871 Config
.InputFilename
= Positional
[0];
872 Config
.OutputFilename
=
873 InputArgs
.getLastArgValue(STRIP_output
, Positional
[0]);
874 DC
.CopyConfigs
.push_back(std::move(Config
));
876 StringMap
<unsigned> InputFiles
;
877 for (StringRef Filename
: Positional
) {
878 if (InputFiles
[Filename
]++ == 1) {
880 return createStringError(
881 errc::invalid_argument
,
882 "cannot specify '-' as an input file more than once");
883 if (Error E
= ErrorCallback(createStringError(
884 errc::invalid_argument
, "'%s' was already specified",
885 Filename
.str().c_str())))
888 Config
.InputFilename
= Filename
;
889 Config
.OutputFilename
= Filename
;
890 DC
.CopyConfigs
.push_back(Config
);
894 if (Config
.PreserveDates
&& (is_contained(Positional
, "-") ||
895 InputArgs
.getLastArgValue(STRIP_output
) == "-"))
896 return createStringError(errc::invalid_argument
,
897 "--preserve-dates requires a file");
899 return std::move(DC
);
902 } // namespace objcopy