1//===- ObjcopyOptions.cpp -------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ObjcopyOptions.h"
10#include "llvm/ADT/SmallVector.h"
11#include "llvm/ADT/StringExtras.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/ADT/StringSwitch.h"
14#include "llvm/BinaryFormat/COFF.h"
15#include "llvm/ObjCopy/CommonConfig.h"
16#include "llvm/ObjCopy/ConfigManager.h"
17#include "llvm/ObjCopy/MachO/MachOConfig.h"
18#include "llvm/Object/Binary.h"
19#include "llvm/Option/Arg.h"
20#include "llvm/Option/ArgList.h"
21#include "llvm/Support/CRC.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Compression.h"
24#include "llvm/Support/Errc.h"
25#include "llvm/Support/Error.h"
26#include "llvm/Support/MemoryBuffer.h"
27
28using namespace llvm;
29using namespace llvm::objcopy;
30using namespace llvm::object;
31using namespace llvm::opt;
32
33namespace {
34enum ObjcopyID {
35 OBJCOPY_INVALID = 0, // This is not an option ID.
36#define OPTION(...) LLVM_MAKE_OPT_ID_WITH_ID_PREFIX(OBJCOPY_, __VA_ARGS__),
37#include "ObjcopyOpts.inc"
38#undef OPTION
39};
40
41namespace objcopy_opt {
42#define OPTTABLE_STR_TABLE_CODE
43#include "ObjcopyOpts.inc"
44#undef OPTTABLE_STR_TABLE_CODE
45
46#define OPTTABLE_PREFIXES_TABLE_CODE
47#include "ObjcopyOpts.inc"
48#undef OPTTABLE_PREFIXES_TABLE_CODE
49
50static constexpr opt::OptTable::Info ObjcopyInfoTable[] = {
51#define OPTION(...) \
52 LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(OBJCOPY_, __VA_ARGS__),
53#include "ObjcopyOpts.inc"
54#undef OPTION
55};
56} // namespace objcopy_opt
57
58class ObjcopyOptTable : public opt::GenericOptTable {
59public:
60 ObjcopyOptTable()
61 : opt::GenericOptTable(objcopy_opt::OptionStrTable,
62 objcopy_opt::OptionPrefixesTable,
63 objcopy_opt::ObjcopyInfoTable) {
64 setGroupedShortOptions(true);
65 setDashDashParsing(true);
66 }
67};
68
69enum InstallNameToolID {
70 INSTALL_NAME_TOOL_INVALID = 0, // This is not an option ID.
71#define OPTION(...) \
72 LLVM_MAKE_OPT_ID_WITH_ID_PREFIX(INSTALL_NAME_TOOL_, __VA_ARGS__),
73#include "InstallNameToolOpts.inc"
74#undef OPTION
75};
76
77namespace install_name_tool {
78#define OPTTABLE_STR_TABLE_CODE
79#include "InstallNameToolOpts.inc"
80#undef OPTTABLE_STR_TABLE_CODE
81
82#define OPTTABLE_PREFIXES_TABLE_CODE
83#include "InstallNameToolOpts.inc"
84#undef OPTTABLE_PREFIXES_TABLE_CODE
85
86static constexpr opt::OptTable::Info InstallNameToolInfoTable[] = {
87#define OPTION(...) \
88 LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(INSTALL_NAME_TOOL_, __VA_ARGS__),
89#include "InstallNameToolOpts.inc"
90#undef OPTION
91};
92} // namespace install_name_tool
93
94class InstallNameToolOptTable : public opt::GenericOptTable {
95public:
96 InstallNameToolOptTable()
97 : GenericOptTable(install_name_tool::OptionStrTable,
98 install_name_tool::OptionPrefixesTable,
99 install_name_tool::InstallNameToolInfoTable) {}
100};
101
102enum BitcodeStripID {
103 BITCODE_STRIP_INVALID = 0, // This is not an option ID.
104#define OPTION(...) \
105 LLVM_MAKE_OPT_ID_WITH_ID_PREFIX(BITCODE_STRIP_, __VA_ARGS__),
106#include "BitcodeStripOpts.inc"
107#undef OPTION
108};
109
110namespace bitcode_strip {
111#define OPTTABLE_STR_TABLE_CODE
112#include "BitcodeStripOpts.inc"
113#undef OPTTABLE_STR_TABLE_CODE
114
115#define OPTTABLE_PREFIXES_TABLE_CODE
116#include "BitcodeStripOpts.inc"
117#undef OPTTABLE_PREFIXES_TABLE_CODE
118
119static constexpr opt::OptTable::Info BitcodeStripInfoTable[] = {
120#define OPTION(...) \
121 LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(BITCODE_STRIP_, __VA_ARGS__),
122#include "BitcodeStripOpts.inc"
123#undef OPTION
124};
125} // namespace bitcode_strip
126
127class BitcodeStripOptTable : public opt::GenericOptTable {
128public:
129 BitcodeStripOptTable()
130 : opt::GenericOptTable(bitcode_strip::OptionStrTable,
131 bitcode_strip::OptionPrefixesTable,
132 bitcode_strip::BitcodeStripInfoTable) {}
133};
134
135enum StripID {
136 STRIP_INVALID = 0, // This is not an option ID.
137#define OPTION(...) LLVM_MAKE_OPT_ID_WITH_ID_PREFIX(STRIP_, __VA_ARGS__),
138#include "StripOpts.inc"
139#undef OPTION
140};
141
142namespace strip {
143#define OPTTABLE_STR_TABLE_CODE
144#include "StripOpts.inc"
145#undef OPTTABLE_STR_TABLE_CODE
146
147#define OPTTABLE_PREFIXES_TABLE_CODE
148#include "StripOpts.inc"
149#undef OPTTABLE_PREFIXES_TABLE_CODE
150
151static constexpr opt::OptTable::Info StripInfoTable[] = {
152#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(STRIP_, __VA_ARGS__),
153#include "StripOpts.inc"
154#undef OPTION
155};
156} // namespace strip
157
158class StripOptTable : public opt::GenericOptTable {
159public:
160 StripOptTable()
161 : GenericOptTable(strip::OptionStrTable, strip::OptionPrefixesTable,
162 strip::StripInfoTable) {
163 setGroupedShortOptions(true);
164 }
165};
166
167} // namespace
168
169static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
170 return llvm::StringSwitch<SectionFlag>(SectionName)
171 .CaseLower(S: "alloc", Value: SectionFlag::SecAlloc)
172 .CaseLower(S: "load", Value: SectionFlag::SecLoad)
173 .CaseLower(S: "noload", Value: SectionFlag::SecNoload)
174 .CaseLower(S: "readonly", Value: SectionFlag::SecReadonly)
175 .CaseLower(S: "debug", Value: SectionFlag::SecDebug)
176 .CaseLower(S: "code", Value: SectionFlag::SecCode)
177 .CaseLower(S: "data", Value: SectionFlag::SecData)
178 .CaseLower(S: "rom", Value: SectionFlag::SecRom)
179 .CaseLower(S: "merge", Value: SectionFlag::SecMerge)
180 .CaseLower(S: "strings", Value: SectionFlag::SecStrings)
181 .CaseLower(S: "contents", Value: SectionFlag::SecContents)
182 .CaseLower(S: "share", Value: SectionFlag::SecShare)
183 .CaseLower(S: "exclude", Value: SectionFlag::SecExclude)
184 .CaseLower(S: "large", Value: SectionFlag::SecLarge)
185 .Default(Value: SectionFlag::SecNone);
186}
187
188static Expected<SectionFlag>
189parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
190 SectionFlag ParsedFlags = SectionFlag::SecNone;
191 for (StringRef Flag : SectionFlags) {
192 SectionFlag ParsedFlag = parseSectionRenameFlag(SectionName: Flag);
193 if (ParsedFlag == SectionFlag::SecNone)
194 return createStringError(
195 EC: errc::invalid_argument,
196 Fmt: "unrecognized section flag '%s'. Flags supported for GNU "
197 "compatibility: alloc, load, noload, readonly, exclude, debug, "
198 "code, data, rom, share, contents, merge, strings, large",
199 Vals: Flag.str().c_str());
200 ParsedFlags |= ParsedFlag;
201 }
202
203 return ParsedFlags;
204}
205
206static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
207 if (!FlagValue.contains(C: '='))
208 return createStringError(EC: errc::invalid_argument,
209 S: "bad format for --rename-section: missing '='");
210
211 // Initial split: ".foo" = ".bar,f1,f2,..."
212 auto Old2New = FlagValue.split(Separator: '=');
213 SectionRename SR;
214 SR.OriginalName = Old2New.first;
215
216 // Flags split: ".bar" "f1" "f2" ...
217 SmallVector<StringRef, 6> NameAndFlags;
218 Old2New.second.split(A&: NameAndFlags, Separator: ',');
219 SR.NewName = NameAndFlags[0];
220
221 if (NameAndFlags.size() > 1) {
222 Expected<SectionFlag> ParsedFlagSet =
223 parseSectionFlagSet(SectionFlags: ArrayRef(NameAndFlags).drop_front());
224 if (!ParsedFlagSet)
225 return ParsedFlagSet.takeError();
226 SR.NewFlags = *ParsedFlagSet;
227 }
228
229 return SR;
230}
231
232static Expected<std::pair<StringRef, uint64_t>>
233parseSetSectionAttribute(StringRef Option, StringRef FlagValue) {
234 if (!FlagValue.contains(C: '='))
235 return make_error<StringError>(Args: "bad format for " + Option + ": missing '='",
236 Args: errc::invalid_argument);
237 auto Split = StringRef(FlagValue).split(Separator: '=');
238 if (Split.first.empty())
239 return make_error<StringError>(Args: "bad format for " + Option +
240 ": missing section name",
241 Args: errc::invalid_argument);
242 uint64_t Value;
243 if (Split.second.getAsInteger(Radix: 0, Result&: Value))
244 return make_error<StringError>(Args: "invalid value for " + Option + ": '" +
245 Split.second + "'",
246 Args: errc::invalid_argument);
247 return std::make_pair(x&: Split.first, y&: Value);
248}
249
250static Expected<SectionFlagsUpdate>
251parseSetSectionFlagValue(StringRef FlagValue) {
252 if (!StringRef(FlagValue).contains(C: '='))
253 return createStringError(EC: errc::invalid_argument,
254 S: "bad format for --set-section-flags: missing '='");
255
256 // Initial split: ".foo" = "f1,f2,..."
257 auto Section2Flags = StringRef(FlagValue).split(Separator: '=');
258 SectionFlagsUpdate SFU;
259 SFU.Name = Section2Flags.first;
260
261 // Flags split: "f1" "f2" ...
262 SmallVector<StringRef, 6> SectionFlags;
263 Section2Flags.second.split(A&: SectionFlags, Separator: ',');
264 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
265 if (!ParsedFlagSet)
266 return ParsedFlagSet.takeError();
267 SFU.NewFlags = *ParsedFlagSet;
268
269 return SFU;
270}
271
272static Expected<uint8_t> parseVisibilityType(StringRef VisType) {
273 const uint8_t Invalid = 0xff;
274 uint8_t type = StringSwitch<uint8_t>(VisType)
275 .Case(S: "default", Value: ELF::STV_DEFAULT)
276 .Case(S: "hidden", Value: ELF::STV_HIDDEN)
277 .Case(S: "internal", Value: ELF::STV_INTERNAL)
278 .Case(S: "protected", Value: ELF::STV_PROTECTED)
279 .Default(Value: Invalid);
280 if (type == Invalid)
281 return createStringError(EC: errc::invalid_argument,
282 Fmt: "'%s' is not a valid symbol visibility",
283 Vals: VisType.str().c_str());
284 return type;
285}
286
287namespace {
288struct TargetInfo {
289 FileFormat Format;
290 MachineInfo Machine;
291};
292} // namespace
293
294// FIXME: consolidate with the bfd parsing used by lld.
295static const StringMap<MachineInfo> TargetMap{
296 // Name, {EMachine, 64bit, LittleEndian}
297 // x86
298 {"elf32-i386", {ELF::EM_386, false, true}},
299 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
300 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
301 // Intel MCU
302 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
303 // ARM
304 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
305 // ARM AArch64
306 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
307 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
308 // RISC-V
309 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
310 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
311 // PowerPC
312 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
313 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
314 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
315 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
316 // MIPS
317 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
318 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
319 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
320 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
321 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
322 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
323 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
324 // SPARC
325 {"elf32-sparc", {ELF::EM_SPARC, false, false}},
326 {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
327 // Hexagon
328 {"elf32-hexagon", {ELF::EM_HEXAGON, false, true}},
329 // LoongArch
330 {"elf32-loongarch", {ELF::EM_LOONGARCH, false, true}},
331 {"elf64-loongarch", {ELF::EM_LOONGARCH, true, true}},
332 // SystemZ
333 {"elf64-s390", {ELF::EM_S390, true, false}},
334};
335
336static Expected<TargetInfo>
337getOutputTargetInfoByTargetName(StringRef TargetName) {
338 StringRef OriginalTargetName = TargetName;
339 bool IsFreeBSD = TargetName.consume_back(Suffix: "-freebsd");
340 auto Iter = TargetMap.find(Key: TargetName);
341 if (Iter == std::end(cont: TargetMap))
342 return createStringError(EC: errc::invalid_argument,
343 Fmt: "invalid output format: '%s'",
344 Vals: OriginalTargetName.str().c_str());
345 MachineInfo MI = Iter->getValue();
346 if (IsFreeBSD)
347 MI.OSABI = ELF::ELFOSABI_FREEBSD;
348
349 FileFormat Format;
350 if (TargetName.starts_with(Prefix: "elf"))
351 Format = FileFormat::ELF;
352 else
353 // This should never happen because `TargetName` is valid (it certainly
354 // exists in the TargetMap).
355 llvm_unreachable("unknown target prefix");
356
357 return {TargetInfo{.Format: Format, .Machine: MI}};
358}
359
360static Error addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
361 StringRef Filename, MatchStyle MS,
362 function_ref<Error(Error)> ErrorCallback) {
363 StringSaver Saver(Alloc);
364 SmallVector<StringRef, 16> Lines;
365 auto BufOrErr = MemoryBuffer::getFile(Filename);
366 if (!BufOrErr)
367 return createFileError(F: Filename, EC: BufOrErr.getError());
368
369 BufOrErr.get()->getBuffer().split(A&: Lines, Separator: '\n');
370 for (StringRef Line : Lines) {
371 // Ignore everything after '#', trim whitespace, and only add the symbol if
372 // it's not empty.
373 auto TrimmedLine = Line.split(Separator: '#').first.trim();
374 if (!TrimmedLine.empty())
375 if (Error E = Symbols.addMatcher(Matcher: NameOrPattern::create(
376 Pattern: Saver.save(S: TrimmedLine), MS, ErrorCallback)))
377 return E;
378 }
379
380 return Error::success();
381}
382
383static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
384 BumpPtrAllocator &Alloc,
385 StringRef Filename) {
386 StringSaver Saver(Alloc);
387 SmallVector<StringRef, 16> Lines;
388 auto BufOrErr = MemoryBuffer::getFile(Filename);
389 if (!BufOrErr)
390 return createFileError(F: Filename, EC: BufOrErr.getError());
391
392 BufOrErr.get()->getBuffer().split(A&: Lines, Separator: '\n');
393 size_t NumLines = Lines.size();
394 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
395 StringRef TrimmedLine = Lines[LineNo].split(Separator: '#').first.trim();
396 if (TrimmedLine.empty())
397 continue;
398
399 std::pair<StringRef, StringRef> Pair = Saver.save(S: TrimmedLine).split(Separator: ' ');
400 StringRef NewName = Pair.second.trim();
401 if (NewName.empty())
402 return createStringError(EC: errc::invalid_argument,
403 Fmt: "%s:%zu: missing new symbol name",
404 Vals: Filename.str().c_str(), Vals: LineNo + 1);
405 SymbolsToRename.insert(KV: {Pair.first, NewName});
406 }
407 return Error::success();
408}
409
410template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
411 T Result;
412 if (Val.getAsInteger(0, Result))
413 return errc::invalid_argument;
414 return Result;
415}
416
417namespace {
418
419enum class ToolType { Objcopy, Strip, InstallNameTool, BitcodeStrip };
420
421} // anonymous namespace
422
423static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
424 ToolType Tool) {
425 StringRef HelpText, ToolName;
426 switch (Tool) {
427 case ToolType::Objcopy:
428 ToolName = "llvm-objcopy";
429 HelpText = " [options] input [output]";
430 break;
431 case ToolType::Strip:
432 ToolName = "llvm-strip";
433 HelpText = " [options] inputs...";
434 break;
435 case ToolType::InstallNameTool:
436 ToolName = "llvm-install-name-tool";
437 HelpText = " [options] input";
438 break;
439 case ToolType::BitcodeStrip:
440 ToolName = "llvm-bitcode-strip";
441 HelpText = " [options] input";
442 break;
443 }
444 OptTable.printHelp(OS, Usage: (ToolName + HelpText).str().c_str(),
445 Title: (ToolName + " tool").str().c_str());
446 // TODO: Replace this with libOption call once it adds extrahelp support.
447 // The CommandLine library has a cl::extrahelp class to support this,
448 // but libOption does not have that yet.
449 OS << "\nPass @FILE as argument to read options from FILE.\n";
450}
451
452static Expected<NewSymbolInfo> parseNewSymbolInfo(StringRef FlagValue) {
453 // Parse value given with --add-symbol option and create the
454 // new symbol if possible. The value format for --add-symbol is:
455 //
456 // <name>=[<section>:]<value>[,<flags>]
457 //
458 // where:
459 // <name> - symbol name, can be empty string
460 // <section> - optional section name. If not given ABS symbol is created
461 // <value> - symbol value, can be decimal or hexadecimal number prefixed
462 // with 0x.
463 // <flags> - optional flags affecting symbol type, binding or visibility.
464 NewSymbolInfo SI;
465 StringRef Value;
466 std::tie(args&: SI.SymbolName, args&: Value) = FlagValue.split(Separator: '=');
467 if (Value.empty())
468 return createStringError(
469 EC: errc::invalid_argument,
470 Fmt: "bad format for --add-symbol, missing '=' after '%s'",
471 Vals: SI.SymbolName.str().c_str());
472
473 if (Value.contains(C: ':')) {
474 std::tie(args&: SI.SectionName, args&: Value) = Value.split(Separator: ':');
475 if (SI.SectionName.empty() || Value.empty())
476 return createStringError(
477 EC: errc::invalid_argument,
478 S: "bad format for --add-symbol, missing section name or symbol value");
479 }
480
481 SmallVector<StringRef, 6> Flags;
482 Value.split(A&: Flags, Separator: ',');
483 if (Flags[0].getAsInteger(Radix: 0, Result&: SI.Value))
484 return createStringError(EC: errc::invalid_argument, Fmt: "bad symbol value: '%s'",
485 Vals: Flags[0].str().c_str());
486
487 using Functor = std::function<void()>;
488 SmallVector<StringRef, 6> UnsupportedFlags;
489 for (size_t I = 1, NumFlags = Flags.size(); I < NumFlags; ++I)
490 static_cast<Functor>(
491 StringSwitch<Functor>(Flags[I])
492 .CaseLower(S: "global",
493 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Global); })
494 .CaseLower(S: "local", Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Local); })
495 .CaseLower(S: "weak", Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Weak); })
496 .CaseLower(S: "default",
497 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Default); })
498 .CaseLower(S: "hidden",
499 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Hidden); })
500 .CaseLower(S: "protected",
501 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Protected); })
502 .CaseLower(S: "file", Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::File); })
503 .CaseLower(S: "section",
504 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Section); })
505 .CaseLower(S: "object",
506 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Object); })
507 .CaseLower(S: "function",
508 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Function); })
509 .CaseLower(
510 S: "indirect-function",
511 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::IndirectFunction); })
512 .CaseLower(S: "debug", Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Debug); })
513 .CaseLower(S: "constructor",
514 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Constructor); })
515 .CaseLower(S: "warning",
516 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Warning); })
517 .CaseLower(S: "indirect",
518 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Indirect); })
519 .CaseLower(S: "synthetic",
520 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::Synthetic); })
521 .CaseLower(S: "unique-object",
522 Value: [&] { SI.Flags.push_back(Elt: SymbolFlag::UniqueObject); })
523 .StartsWithLower(S: "before=",
524 Value: [&] {
525 StringRef SymNamePart =
526 Flags[I].split(Separator: '=').second;
527
528 if (!SymNamePart.empty())
529 SI.BeforeSyms.push_back(Elt: SymNamePart);
530 })
531 .Default(Value: [&] { UnsupportedFlags.push_back(Elt: Flags[I]); }))();
532 if (!UnsupportedFlags.empty())
533 return createStringError(EC: errc::invalid_argument,
534 Fmt: "unsupported flag%s for --add-symbol: '%s'",
535 Vals: UnsupportedFlags.size() > 1 ? "s" : "",
536 Vals: join(R&: UnsupportedFlags, Separator: "', '").c_str());
537
538 return SI;
539}
540
541static Expected<RemoveNoteInfo> parseRemoveNoteInfo(StringRef FlagValue) {
542 // Parse value given with --remove-note option. The format is:
543 //
544 // [name/]type_id
545 //
546 // where:
547 // <name> - optional note name. If not given, all notes with the specified
548 // <type_id> are removed.
549 // <type_id> - note type value, can be decimal or hexadecimal number prefixed
550 // with 0x.
551 RemoveNoteInfo NI;
552 StringRef TypeIdStr;
553 if (auto Idx = FlagValue.find(C: '/'); Idx != StringRef::npos) {
554 if (Idx == 0)
555 return createStringError(
556 EC: errc::invalid_argument,
557 S: "bad format for --remove-note, note name is empty");
558 NI.Name = FlagValue.slice(Start: 0, End: Idx);
559 TypeIdStr = FlagValue.substr(Start: Idx + 1);
560 } else {
561 TypeIdStr = FlagValue;
562 }
563 if (TypeIdStr.empty())
564 return createStringError(EC: errc::invalid_argument,
565 S: "bad format for --remove-note, missing type_id");
566 if (TypeIdStr.getAsInteger(Radix: 0, Result&: NI.TypeId))
567 return createStringError(EC: errc::invalid_argument,
568 Fmt: "bad note type_id for --remove-note: '%s'",
569 Vals: TypeIdStr.str().c_str());
570 return NI;
571}
572
573// Parse input option \p ArgValue and load section data. This function
574// extracts section name and name of the file keeping section data from
575// ArgValue, loads data from the file, and stores section name and data
576// into the vector of new sections \p NewSections.
577static Error loadNewSectionData(StringRef ArgValue, StringRef OptionName,
578 SmallVector<NewSectionInfo, 0> &NewSections) {
579 if (!ArgValue.contains(C: '='))
580 return createStringError(EC: errc::invalid_argument,
581 S: "bad format for " + OptionName + ": missing '='");
582
583 std::pair<StringRef, StringRef> SecPair = ArgValue.split(Separator: "=");
584 if (SecPair.second.empty())
585 return createStringError(EC: errc::invalid_argument, S: "bad format for " +
586 OptionName +
587 ": missing file name");
588
589 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
590 MemoryBuffer::getFile(Filename: SecPair.second);
591 if (!BufOrErr)
592 return createFileError(F: SecPair.second,
593 E: errorCodeToError(EC: BufOrErr.getError()));
594
595 NewSections.push_back(Elt: {SecPair.first, std::move(*BufOrErr)});
596 return Error::success();
597}
598
599static Expected<int64_t> parseChangeSectionLMA(StringRef ArgValue,
600 StringRef OptionName) {
601 StringRef StringValue;
602 if (ArgValue.starts_with(Prefix: "*+")) {
603 StringValue = ArgValue.substr(Start: 2);
604 } else if (ArgValue.starts_with(Prefix: "*-")) {
605 StringValue = ArgValue.substr(Start: 1);
606 } else if (ArgValue.contains(Other: "=")) {
607 return createStringError(EC: errc::invalid_argument,
608 S: "bad format for " + OptionName +
609 ": changing LMA to a specific value is not "
610 "supported. Use *+val or *-val instead");
611 } else if (ArgValue.contains(Other: "+") || ArgValue.contains(Other: "-")) {
612 return createStringError(EC: errc::invalid_argument,
613 S: "bad format for " + OptionName +
614 ": changing a specific section LMA is not "
615 "supported. Use *+val or *-val instead");
616 }
617 if (StringValue.empty())
618 return createStringError(EC: errc::invalid_argument,
619 S: "bad format for " + OptionName +
620 ": missing LMA offset");
621
622 auto LMAValue = getAsInteger<int64_t>(Val: StringValue);
623 if (!LMAValue)
624 return createStringError(EC: LMAValue.getError(),
625 S: "bad format for " + OptionName + ": value after " +
626 ArgValue.slice(Start: 0, End: 2) + " is " + StringValue +
627 " when it should be an integer");
628 return *LMAValue;
629}
630
631static Expected<SectionPatternAddressUpdate>
632parseChangeSectionAddr(StringRef ArgValue, StringRef OptionName,
633 MatchStyle SectionMatchStyle,
634 function_ref<Error(Error)> ErrorCallback) {
635 SectionPatternAddressUpdate PatternUpdate;
636
637 size_t LastSymbolIndex = ArgValue.find_last_of(Chars: "+-=");
638 if (LastSymbolIndex == StringRef::npos)
639 return createStringError(EC: errc::invalid_argument,
640 S: "bad format for " + OptionName +
641 ": argument value " + ArgValue +
642 " is invalid. See --help");
643 char UpdateSymbol = ArgValue[LastSymbolIndex];
644
645 StringRef SectionPattern = ArgValue.slice(Start: 0, End: LastSymbolIndex);
646 if (SectionPattern.empty())
647 return createStringError(
648 EC: errc::invalid_argument,
649 S: "bad format for " + OptionName +
650 ": missing section pattern to apply address change to");
651 if (Error E = PatternUpdate.SectionPattern.addMatcher(Matcher: NameOrPattern::create(
652 Pattern: SectionPattern, MS: SectionMatchStyle, ErrorCallback)))
653 return std::move(E);
654
655 StringRef Value = ArgValue.substr(Start: LastSymbolIndex + 1);
656 if (Value.empty()) {
657 switch (UpdateSymbol) {
658 case '+':
659 case '-':
660 return createStringError(EC: errc::invalid_argument,
661 S: "bad format for " + OptionName +
662 ": missing value of offset after '" +
663 std::string({UpdateSymbol}) + "'");
664
665 case '=':
666 return createStringError(EC: errc::invalid_argument,
667 S: "bad format for " + OptionName +
668 ": missing address value after '='");
669 }
670 }
671 auto AddrValue = getAsInteger<uint64_t>(Val: Value);
672 if (!AddrValue)
673 return createStringError(EC: AddrValue.getError(),
674 S: "bad format for " + OptionName + ": value after " +
675 std::string({UpdateSymbol}) + " is " + Value +
676 " when it should be a 64-bit integer");
677
678 switch (UpdateSymbol) {
679 case '+':
680 PatternUpdate.Update.Kind = AdjustKind::Add;
681 break;
682 case '-':
683 PatternUpdate.Update.Kind = AdjustKind::Subtract;
684 break;
685 case '=':
686 PatternUpdate.Update.Kind = AdjustKind::Set;
687 }
688
689 PatternUpdate.Update.Value = *AddrValue;
690 return PatternUpdate;
691}
692
693// parseObjcopyOptions returns the config and sets the input arguments. If a
694// help flag is set then parseObjcopyOptions will print the help messege and
695// exit.
696Expected<DriverConfig>
697objcopy::parseObjcopyOptions(ArrayRef<const char *> ArgsArr,
698 function_ref<Error(Error)> ErrorCallback) {
699 DriverConfig DC;
700 ObjcopyOptTable T;
701
702 unsigned MissingArgumentIndex, MissingArgumentCount;
703 llvm::opt::InputArgList InputArgs =
704 T.ParseArgs(Args: ArgsArr, MissingArgIndex&: MissingArgumentIndex, MissingArgCount&: MissingArgumentCount);
705
706 if (MissingArgumentCount)
707 return createStringError(
708 EC: errc::invalid_argument,
709 Fmt: "argument to '%s' is missing (expected %d value(s))",
710 Vals: InputArgs.getArgString(Index: MissingArgumentIndex), Vals: MissingArgumentCount);
711
712 if (InputArgs.size() == 0) {
713 printHelp(OptTable: T, OS&: errs(), Tool: ToolType::Objcopy);
714 exit(status: 1);
715 }
716
717 if (InputArgs.hasArg(Ids: OBJCOPY_help)) {
718 printHelp(OptTable: T, OS&: outs(), Tool: ToolType::Objcopy);
719 exit(status: 0);
720 }
721
722 if (InputArgs.hasArg(Ids: OBJCOPY_version)) {
723 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
724 cl::PrintVersionMessage();
725 exit(status: 0);
726 }
727
728 SmallVector<const char *, 2> Positional;
729
730 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_UNKNOWN))
731 return createStringError(EC: errc::invalid_argument, Fmt: "unknown argument '%s'",
732 Vals: Arg->getAsString(Args: InputArgs).c_str());
733
734 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_INPUT))
735 Positional.push_back(Elt: Arg->getValue());
736
737 if (Positional.empty())
738 return createStringError(EC: errc::invalid_argument, S: "no input file specified");
739
740 if (Positional.size() > 2)
741 return createStringError(EC: errc::invalid_argument,
742 S: "too many positional arguments");
743
744 ConfigManager ConfigMgr;
745 CommonConfig &Config = ConfigMgr.Common;
746 COFFConfig &COFFConfig = ConfigMgr.COFF;
747 ELFConfig &ELFConfig = ConfigMgr.ELF;
748 MachOConfig &MachOConfig = ConfigMgr.MachO;
749 Config.InputFilename = Positional[0];
750 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
751 if (InputArgs.hasArg(Ids: OBJCOPY_target) &&
752 (InputArgs.hasArg(Ids: OBJCOPY_input_target) ||
753 InputArgs.hasArg(Ids: OBJCOPY_output_target)))
754 return createStringError(
755 EC: errc::invalid_argument,
756 S: "--target cannot be used with --input-target or --output-target");
757
758 if (InputArgs.hasArg(Ids: OBJCOPY_regex) && InputArgs.hasArg(Ids: OBJCOPY_wildcard))
759 return createStringError(EC: errc::invalid_argument,
760 S: "--regex and --wildcard are incompatible");
761
762 MatchStyle SectionMatchStyle = InputArgs.hasArg(Ids: OBJCOPY_regex)
763 ? MatchStyle::Regex
764 : MatchStyle::Wildcard;
765 MatchStyle SymbolMatchStyle
766 = InputArgs.hasArg(Ids: OBJCOPY_regex) ? MatchStyle::Regex
767 : InputArgs.hasArg(Ids: OBJCOPY_wildcard) ? MatchStyle::Wildcard
768 : MatchStyle::Literal;
769 StringRef InputFormat, OutputFormat;
770 if (InputArgs.hasArg(Ids: OBJCOPY_target)) {
771 InputFormat = InputArgs.getLastArgValue(Id: OBJCOPY_target);
772 OutputFormat = InputArgs.getLastArgValue(Id: OBJCOPY_target);
773 } else {
774 InputFormat = InputArgs.getLastArgValue(Id: OBJCOPY_input_target);
775 OutputFormat = InputArgs.getLastArgValue(Id: OBJCOPY_output_target);
776 }
777
778 // FIXME: Currently, we ignore the target for non-binary/ihex formats
779 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
780 // format by llvm::object::createBinary regardless of the option value.
781 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
782 .Case(S: "binary", Value: FileFormat::Binary)
783 .Case(S: "ihex", Value: FileFormat::IHex)
784 .Default(Value: FileFormat::Unspecified);
785
786 if (InputArgs.hasArg(Ids: OBJCOPY_new_symbol_visibility)) {
787 const uint8_t Invalid = 0xff;
788 StringRef VisibilityStr =
789 InputArgs.getLastArgValue(Id: OBJCOPY_new_symbol_visibility);
790
791 ELFConfig.NewSymbolVisibility = StringSwitch<uint8_t>(VisibilityStr)
792 .Case(S: "default", Value: ELF::STV_DEFAULT)
793 .Case(S: "hidden", Value: ELF::STV_HIDDEN)
794 .Case(S: "internal", Value: ELF::STV_INTERNAL)
795 .Case(S: "protected", Value: ELF::STV_PROTECTED)
796 .Default(Value: Invalid);
797
798 if (ELFConfig.NewSymbolVisibility == Invalid)
799 return createStringError(EC: errc::invalid_argument,
800 Fmt: "'%s' is not a valid symbol visibility",
801 Vals: VisibilityStr.str().c_str());
802 }
803
804 for (const auto *Arg : InputArgs.filtered(Ids: OBJCOPY_subsystem)) {
805 StringRef Subsystem, Version;
806 std::tie(args&: Subsystem, args&: Version) = StringRef(Arg->getValue()).split(Separator: ':');
807 COFFConfig.Subsystem =
808 StringSwitch<unsigned>(Subsystem.lower())
809 .Case(S: "boot_application",
810 Value: COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
811 .Case(S: "console", Value: COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI)
812 .Cases(S0: "efi_application", S1: "efi-app",
813 Value: COFF::IMAGE_SUBSYSTEM_EFI_APPLICATION)
814 .Cases(S0: "efi_boot_service_driver", S1: "efi-bsd",
815 Value: COFF::IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
816 .Case(S: "efi_rom", Value: COFF::IMAGE_SUBSYSTEM_EFI_ROM)
817 .Cases(S0: "efi_runtime_driver", S1: "efi-rtd",
818 Value: COFF::IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
819 .Case(S: "native", Value: COFF::IMAGE_SUBSYSTEM_NATIVE)
820 .Case(S: "posix", Value: COFF::IMAGE_SUBSYSTEM_POSIX_CUI)
821 .Case(S: "windows", Value: COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI)
822 .Default(Value: COFF::IMAGE_SUBSYSTEM_UNKNOWN);
823 if (*COFFConfig.Subsystem == COFF::IMAGE_SUBSYSTEM_UNKNOWN)
824 return createStringError(EC: errc::invalid_argument,
825 Fmt: "'%s' is not a valid subsystem",
826 Vals: Subsystem.str().c_str());
827 if (!Version.empty()) {
828 StringRef Major, Minor;
829 std::tie(args&: Major, args&: Minor) = Version.split(Separator: '.');
830 unsigned Number;
831 if (Major.getAsInteger(Radix: 10, Result&: Number))
832 return createStringError(EC: errc::invalid_argument,
833 Fmt: "'%s' is not a valid subsystem major version",
834 Vals: Major.str().c_str());
835 COFFConfig.MajorSubsystemVersion = Number;
836 Number = 0;
837 if (!Minor.empty() && Minor.getAsInteger(Radix: 10, Result&: Number))
838 return createStringError(EC: errc::invalid_argument,
839 Fmt: "'%s' is not a valid subsystem minor version",
840 Vals: Minor.str().c_str());
841 COFFConfig.MinorSubsystemVersion = Number;
842 }
843 }
844
845 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
846 .Case(S: "binary", Value: FileFormat::Binary)
847 .Case(S: "ihex", Value: FileFormat::IHex)
848 .Case(S: "srec", Value: FileFormat::SREC)
849 .Default(Value: FileFormat::Unspecified);
850 if (Config.OutputFormat == FileFormat::Unspecified) {
851 if (OutputFormat.empty()) {
852 Config.OutputFormat = Config.InputFormat;
853 } else {
854 Expected<TargetInfo> Target =
855 getOutputTargetInfoByTargetName(TargetName: OutputFormat);
856 if (!Target)
857 return Target.takeError();
858 Config.OutputFormat = Target->Format;
859 Config.OutputArch = Target->Machine;
860 }
861 }
862
863 if (const auto *A = InputArgs.getLastArg(Ids: OBJCOPY_compress_debug_sections)) {
864 Config.CompressionType = StringSwitch<DebugCompressionType>(A->getValue())
865 .Case(S: "zlib", Value: DebugCompressionType::Zlib)
866 .Case(S: "zstd", Value: DebugCompressionType::Zstd)
867 .Default(Value: DebugCompressionType::None);
868 if (Config.CompressionType == DebugCompressionType::None) {
869 return createStringError(
870 EC: errc::invalid_argument,
871 Fmt: "invalid or unsupported --compress-debug-sections format: %s",
872 Vals: A->getValue());
873 }
874 if (const char *Reason = compression::getReasonIfUnsupported(
875 F: compression::formatFor(Type: Config.CompressionType)))
876 return createStringError(EC: errc::invalid_argument, S: Reason);
877 }
878
879 for (const auto *A : InputArgs.filtered(Ids: OBJCOPY_compress_sections)) {
880 SmallVector<StringRef, 0> Fields;
881 StringRef(A->getValue()).split(A&: Fields, Separator: '=');
882 if (Fields.size() != 2 || Fields[1].empty()) {
883 return createStringError(
884 EC: errc::invalid_argument,
885 S: A->getSpelling() +
886 ": parse error, not 'section-glob=[none|zlib|zstd]'");
887 }
888
889 auto Type = StringSwitch<DebugCompressionType>(Fields[1])
890 .Case(S: "zlib", Value: DebugCompressionType::Zlib)
891 .Case(S: "zstd", Value: DebugCompressionType::Zstd)
892 .Default(Value: DebugCompressionType::None);
893 if (Type == DebugCompressionType::None && Fields[1] != "none") {
894 return createStringError(
895 EC: errc::invalid_argument,
896 Fmt: "invalid or unsupported --compress-sections format: %s",
897 Vals: A->getValue());
898 }
899
900 auto &P = Config.compressSections.emplace_back();
901 P.second = Type;
902 auto Matcher =
903 NameOrPattern::create(Pattern: Fields[0], MS: SectionMatchStyle, ErrorCallback);
904 // =none allows overriding a previous =zlib or =zstd. Reject negative
905 // patterns, which would be confusing.
906 if (Matcher && !Matcher->isPositiveMatch()) {
907 return createStringError(
908 EC: errc::invalid_argument,
909 S: "--compress-sections: negative pattern is unsupported");
910 }
911 if (Error E = P.first.addMatcher(Matcher: std::move(Matcher)))
912 return std::move(E);
913 }
914
915 Config.AddGnuDebugLink = InputArgs.getLastArgValue(Id: OBJCOPY_add_gnu_debuglink);
916 // The gnu_debuglink's target is expected to not change or else its CRC would
917 // become invalidated and get rejected. We can avoid recalculating the
918 // checksum for every target file inside an archive by precomputing the CRC
919 // here. This prevents a significant amount of I/O.
920 if (!Config.AddGnuDebugLink.empty()) {
921 auto DebugOrErr = MemoryBuffer::getFile(Filename: Config.AddGnuDebugLink);
922 if (!DebugOrErr)
923 return createFileError(F: Config.AddGnuDebugLink, EC: DebugOrErr.getError());
924 auto Debug = std::move(*DebugOrErr);
925 Config.GnuDebugLinkCRC32 =
926 llvm::crc32(Data: arrayRefFromStringRef(Input: Debug->getBuffer()));
927 }
928 Config.SplitDWO = InputArgs.getLastArgValue(Id: OBJCOPY_split_dwo);
929
930 Config.SymbolsPrefix = InputArgs.getLastArgValue(Id: OBJCOPY_prefix_symbols);
931 Config.SymbolsPrefixRemove =
932 InputArgs.getLastArgValue(Id: OBJCOPY_remove_symbol_prefix);
933
934 Config.AllocSectionsPrefix =
935 InputArgs.getLastArgValue(Id: OBJCOPY_prefix_alloc_sections);
936 if (auto Arg = InputArgs.getLastArg(Ids: OBJCOPY_extract_partition))
937 Config.ExtractPartition = Arg->getValue();
938
939 if (const auto *A = InputArgs.getLastArg(Ids: OBJCOPY_gap_fill)) {
940 if (Config.OutputFormat != FileFormat::Binary)
941 return createStringError(
942 EC: errc::invalid_argument,
943 S: "'--gap-fill' is only supported for binary output");
944 ErrorOr<uint64_t> Val = getAsInteger<uint64_t>(Val: A->getValue());
945 if (!Val)
946 return createStringError(EC: Val.getError(), Fmt: "--gap-fill: bad number: %s",
947 Vals: A->getValue());
948 uint8_t ByteVal = Val.get();
949 if (ByteVal != Val.get())
950 return createStringError(EC: std::errc::value_too_large,
951 Fmt: "gap-fill value %s is out of range (0 to 0xff)",
952 Vals: A->getValue());
953 Config.GapFill = ByteVal;
954 }
955
956 if (const auto *A = InputArgs.getLastArg(Ids: OBJCOPY_pad_to)) {
957 if (Config.OutputFormat != FileFormat::Binary)
958 return createStringError(
959 EC: errc::invalid_argument,
960 S: "'--pad-to' is only supported for binary output");
961 ErrorOr<uint64_t> Addr = getAsInteger<uint64_t>(Val: A->getValue());
962 if (!Addr)
963 return createStringError(EC: Addr.getError(), Fmt: "--pad-to: bad number: %s",
964 Vals: A->getValue());
965 Config.PadTo = *Addr;
966 }
967
968 if (const auto *Arg = InputArgs.getLastArg(Ids: OBJCOPY_change_section_lma)) {
969 Expected<int64_t> LMAValue =
970 parseChangeSectionLMA(ArgValue: Arg->getValue(), OptionName: Arg->getSpelling());
971 if (!LMAValue)
972 return LMAValue.takeError();
973 Config.ChangeSectionLMAValAll = *LMAValue;
974 }
975
976 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_change_section_address)) {
977 Expected<SectionPatternAddressUpdate> AddressUpdate =
978 parseChangeSectionAddr(ArgValue: Arg->getValue(), OptionName: Arg->getSpelling(),
979 SectionMatchStyle, ErrorCallback);
980 if (!AddressUpdate)
981 return AddressUpdate.takeError();
982 Config.ChangeSectionAddress.push_back(Elt: *AddressUpdate);
983 }
984
985 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_redefine_symbol)) {
986 if (!StringRef(Arg->getValue()).contains(C: '='))
987 return createStringError(EC: errc::invalid_argument,
988 S: "bad format for --redefine-sym");
989 auto Old2New = StringRef(Arg->getValue()).split(Separator: '=');
990 if (!Config.SymbolsToRename.insert(KV: Old2New).second)
991 return createStringError(EC: errc::invalid_argument,
992 Fmt: "multiple redefinition of symbol '%s'",
993 Vals: Old2New.first.str().c_str());
994 }
995
996 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_redefine_symbols))
997 if (Error E = addSymbolsToRenameFromFile(SymbolsToRename&: Config.SymbolsToRename, Alloc&: DC.Alloc,
998 Filename: Arg->getValue()))
999 return std::move(E);
1000
1001 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_rename_section)) {
1002 Expected<SectionRename> SR =
1003 parseRenameSectionValue(FlagValue: StringRef(Arg->getValue()));
1004 if (!SR)
1005 return SR.takeError();
1006 if (!Config.SectionsToRename.try_emplace(Key: SR->OriginalName, Args&: *SR).second)
1007 return createStringError(EC: errc::invalid_argument,
1008 Fmt: "multiple renames of section '%s'",
1009 Vals: SR->OriginalName.str().c_str());
1010 }
1011 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_set_section_alignment)) {
1012 Expected<std::pair<StringRef, uint64_t>> NameAndAlign =
1013 parseSetSectionAttribute(Option: "--set-section-alignment", FlagValue: Arg->getValue());
1014 if (!NameAndAlign)
1015 return NameAndAlign.takeError();
1016 Config.SetSectionAlignment[NameAndAlign->first] = NameAndAlign->second;
1017 }
1018 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_set_section_flags)) {
1019 Expected<SectionFlagsUpdate> SFU =
1020 parseSetSectionFlagValue(FlagValue: Arg->getValue());
1021 if (!SFU)
1022 return SFU.takeError();
1023 if (!Config.SetSectionFlags.try_emplace(Key: SFU->Name, Args&: *SFU).second)
1024 return createStringError(
1025 EC: errc::invalid_argument,
1026 Fmt: "--set-section-flags set multiple times for section '%s'",
1027 Vals: SFU->Name.str().c_str());
1028 }
1029 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_set_section_type)) {
1030 Expected<std::pair<StringRef, uint64_t>> NameAndType =
1031 parseSetSectionAttribute(Option: "--set-section-type", FlagValue: Arg->getValue());
1032 if (!NameAndType)
1033 return NameAndType.takeError();
1034 Config.SetSectionType[NameAndType->first] = NameAndType->second;
1035 }
1036 // Prohibit combinations of --set-section-{flags,type} when the section name
1037 // is used as the destination of a --rename-section.
1038 for (const auto &E : Config.SectionsToRename) {
1039 const SectionRename &SR = E.second;
1040 auto Err = [&](const char *Option) {
1041 return createStringError(
1042 EC: errc::invalid_argument,
1043 Fmt: "--set-section-%s=%s conflicts with --rename-section=%s=%s", Vals: Option,
1044 Vals: SR.NewName.str().c_str(), Vals: SR.OriginalName.str().c_str(),
1045 Vals: SR.NewName.str().c_str());
1046 };
1047 if (Config.SetSectionFlags.count(Key: SR.NewName))
1048 return Err("flags");
1049 if (Config.SetSectionType.count(Key: SR.NewName))
1050 return Err("type");
1051 }
1052
1053 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_remove_section))
1054 if (Error E = Config.ToRemove.addMatcher(Matcher: NameOrPattern::create(
1055 Pattern: Arg->getValue(), MS: SectionMatchStyle, ErrorCallback)))
1056 return std::move(E);
1057 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_keep_section))
1058 if (Error E = Config.KeepSection.addMatcher(Matcher: NameOrPattern::create(
1059 Pattern: Arg->getValue(), MS: SectionMatchStyle, ErrorCallback)))
1060 return std::move(E);
1061 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_only_section))
1062 if (Error E = Config.OnlySection.addMatcher(Matcher: NameOrPattern::create(
1063 Pattern: Arg->getValue(), MS: SectionMatchStyle, ErrorCallback)))
1064 return std::move(E);
1065 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_add_section)) {
1066 if (Error Err = loadNewSectionData(ArgValue: Arg->getValue(), OptionName: "--add-section",
1067 NewSections&: Config.AddSection))
1068 return std::move(Err);
1069 }
1070 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_update_section)) {
1071 if (Error Err = loadNewSectionData(ArgValue: Arg->getValue(), OptionName: "--update-section",
1072 NewSections&: Config.UpdateSection))
1073 return std::move(Err);
1074 }
1075 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_dump_section)) {
1076 StringRef Value(Arg->getValue());
1077 if (Value.split(Separator: '=').second.empty())
1078 return createStringError(
1079 EC: errc::invalid_argument,
1080 S: "bad format for --dump-section, expected section=file");
1081 Config.DumpSection.push_back(Elt: Value);
1082 }
1083 Config.StripAll = InputArgs.hasArg(Ids: OBJCOPY_strip_all);
1084 Config.StripAllGNU = InputArgs.hasArg(Ids: OBJCOPY_strip_all_gnu);
1085 Config.StripDebug = InputArgs.hasArg(Ids: OBJCOPY_strip_debug);
1086 Config.StripDWO = InputArgs.hasArg(Ids: OBJCOPY_strip_dwo);
1087 Config.StripSections = InputArgs.hasArg(Ids: OBJCOPY_strip_sections);
1088 Config.StripNonAlloc = InputArgs.hasArg(Ids: OBJCOPY_strip_non_alloc);
1089 Config.StripUnneeded = InputArgs.hasArg(Ids: OBJCOPY_strip_unneeded);
1090 Config.ExtractDWO = InputArgs.hasArg(Ids: OBJCOPY_extract_dwo);
1091 Config.ExtractMainPartition =
1092 InputArgs.hasArg(Ids: OBJCOPY_extract_main_partition);
1093 ELFConfig.LocalizeHidden = InputArgs.hasArg(Ids: OBJCOPY_localize_hidden);
1094 Config.Weaken = InputArgs.hasArg(Ids: OBJCOPY_weaken);
1095 if (auto *Arg =
1096 InputArgs.getLastArg(Ids: OBJCOPY_discard_all, Ids: OBJCOPY_discard_locals)) {
1097 Config.DiscardMode = Arg->getOption().matches(ID: OBJCOPY_discard_all)
1098 ? DiscardType::All
1099 : DiscardType::Locals;
1100 }
1101
1102 ELFConfig.VerifyNoteSections = InputArgs.hasFlag(
1103 Pos: OBJCOPY_verify_note_sections, Neg: OBJCOPY_no_verify_note_sections, Default: true);
1104
1105 Config.OnlyKeepDebug = InputArgs.hasArg(Ids: OBJCOPY_only_keep_debug);
1106 ELFConfig.KeepFileSymbols = InputArgs.hasArg(Ids: OBJCOPY_keep_file_symbols);
1107 MachOConfig.KeepUndefined = InputArgs.hasArg(Ids: OBJCOPY_keep_undefined);
1108 Config.DecompressDebugSections =
1109 InputArgs.hasArg(Ids: OBJCOPY_decompress_debug_sections);
1110 if (Config.DiscardMode == DiscardType::All) {
1111 Config.StripDebug = true;
1112 ELFConfig.KeepFileSymbols = true;
1113 }
1114 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_localize_symbol))
1115 if (Error E = Config.SymbolsToLocalize.addMatcher(Matcher: NameOrPattern::create(
1116 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1117 return std::move(E);
1118 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_localize_symbols))
1119 if (Error E = addSymbolsFromFile(Symbols&: Config.SymbolsToLocalize, Alloc&: DC.Alloc,
1120 Filename: Arg->getValue(), MS: SymbolMatchStyle,
1121 ErrorCallback))
1122 return std::move(E);
1123 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_keep_global_symbol))
1124 if (Error E = Config.SymbolsToKeepGlobal.addMatcher(Matcher: NameOrPattern::create(
1125 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1126 return std::move(E);
1127 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_keep_global_symbols))
1128 if (Error E = addSymbolsFromFile(Symbols&: Config.SymbolsToKeepGlobal, Alloc&: DC.Alloc,
1129 Filename: Arg->getValue(), MS: SymbolMatchStyle,
1130 ErrorCallback))
1131 return std::move(E);
1132 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_globalize_symbol))
1133 if (Error E = Config.SymbolsToGlobalize.addMatcher(Matcher: NameOrPattern::create(
1134 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1135 return std::move(E);
1136 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_globalize_symbols))
1137 if (Error E = addSymbolsFromFile(Symbols&: Config.SymbolsToGlobalize, Alloc&: DC.Alloc,
1138 Filename: Arg->getValue(), MS: SymbolMatchStyle,
1139 ErrorCallback))
1140 return std::move(E);
1141 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_weaken_symbol))
1142 if (Error E = Config.SymbolsToWeaken.addMatcher(Matcher: NameOrPattern::create(
1143 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1144 return std::move(E);
1145 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_weaken_symbols))
1146 if (Error E = addSymbolsFromFile(Symbols&: Config.SymbolsToWeaken, Alloc&: DC.Alloc,
1147 Filename: Arg->getValue(), MS: SymbolMatchStyle,
1148 ErrorCallback))
1149 return std::move(E);
1150 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_strip_symbol))
1151 if (Error E = Config.SymbolsToRemove.addMatcher(Matcher: NameOrPattern::create(
1152 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1153 return std::move(E);
1154 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_strip_symbols))
1155 if (Error E = addSymbolsFromFile(Symbols&: Config.SymbolsToRemove, Alloc&: DC.Alloc,
1156 Filename: Arg->getValue(), MS: SymbolMatchStyle,
1157 ErrorCallback))
1158 return std::move(E);
1159 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_strip_unneeded_symbol))
1160 if (Error E =
1161 Config.UnneededSymbolsToRemove.addMatcher(Matcher: NameOrPattern::create(
1162 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1163 return std::move(E);
1164 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_strip_unneeded_symbols))
1165 if (Error E = addSymbolsFromFile(Symbols&: Config.UnneededSymbolsToRemove, Alloc&: DC.Alloc,
1166 Filename: Arg->getValue(), MS: SymbolMatchStyle,
1167 ErrorCallback))
1168 return std::move(E);
1169 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_keep_symbol))
1170 if (Error E = Config.SymbolsToKeep.addMatcher(Matcher: NameOrPattern::create(
1171 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1172 return std::move(E);
1173 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_keep_symbols))
1174 if (Error E =
1175 addSymbolsFromFile(Symbols&: Config.SymbolsToKeep, Alloc&: DC.Alloc, Filename: Arg->getValue(),
1176 MS: SymbolMatchStyle, ErrorCallback))
1177 return std::move(E);
1178 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_skip_symbol))
1179 if (Error E = Config.SymbolsToSkip.addMatcher(Matcher: NameOrPattern::create(
1180 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1181 return std::move(E);
1182 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_skip_symbols))
1183 if (Error E =
1184 addSymbolsFromFile(Symbols&: Config.SymbolsToSkip, Alloc&: DC.Alloc, Filename: Arg->getValue(),
1185 MS: SymbolMatchStyle, ErrorCallback))
1186 return std::move(E);
1187 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_add_symbol)) {
1188 Expected<NewSymbolInfo> SymInfo = parseNewSymbolInfo(FlagValue: Arg->getValue());
1189 if (!SymInfo)
1190 return SymInfo.takeError();
1191
1192 Config.SymbolsToAdd.push_back(Elt: *SymInfo);
1193 }
1194 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_set_symbol_visibility)) {
1195 if (!StringRef(Arg->getValue()).contains(C: '='))
1196 return createStringError(EC: errc::invalid_argument,
1197 S: "bad format for --set-symbol-visibility");
1198 auto [Sym, Visibility] = StringRef(Arg->getValue()).split(Separator: '=');
1199 Expected<uint8_t> Type = parseVisibilityType(VisType: Visibility);
1200 if (!Type)
1201 return Type.takeError();
1202 ELFConfig.SymbolsToSetVisibility.emplace_back(args: NameMatcher(), args&: *Type);
1203 if (Error E = ELFConfig.SymbolsToSetVisibility.back().first.addMatcher(
1204 Matcher: NameOrPattern::create(Pattern: Sym, MS: SymbolMatchStyle, ErrorCallback)))
1205 return std::move(E);
1206 }
1207 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_set_symbols_visibility)) {
1208 if (!StringRef(Arg->getValue()).contains(C: '='))
1209 return createStringError(EC: errc::invalid_argument,
1210 S: "bad format for --set-symbols-visibility");
1211 auto [File, Visibility] = StringRef(Arg->getValue()).split(Separator: '=');
1212 Expected<uint8_t> Type = parseVisibilityType(VisType: Visibility);
1213 if (!Type)
1214 return Type.takeError();
1215 ELFConfig.SymbolsToSetVisibility.emplace_back(args: NameMatcher(), args&: *Type);
1216 if (Error E =
1217 addSymbolsFromFile(Symbols&: ELFConfig.SymbolsToSetVisibility.back().first,
1218 Alloc&: DC.Alloc, Filename: File, MS: SymbolMatchStyle, ErrorCallback))
1219 return std::move(E);
1220 }
1221
1222 ELFConfig.AllowBrokenLinks = InputArgs.hasArg(Ids: OBJCOPY_allow_broken_links);
1223
1224 Config.DeterministicArchives = InputArgs.hasFlag(
1225 Pos: OBJCOPY_enable_deterministic_archives,
1226 Neg: OBJCOPY_disable_deterministic_archives, /*default=*/Default: true);
1227
1228 Config.PreserveDates = InputArgs.hasArg(Ids: OBJCOPY_preserve_dates);
1229
1230 if (Config.PreserveDates &&
1231 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
1232 return createStringError(EC: errc::invalid_argument,
1233 S: "--preserve-dates requires a file");
1234
1235 for (auto *Arg : InputArgs)
1236 if (Arg->getOption().matches(ID: OBJCOPY_set_start)) {
1237 auto EAddr = getAsInteger<uint64_t>(Val: Arg->getValue());
1238 if (!EAddr)
1239 return createStringError(
1240 EC: EAddr.getError(), Fmt: "bad entry point address: '%s'", Vals: Arg->getValue());
1241
1242 ELFConfig.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
1243 } else if (Arg->getOption().matches(ID: OBJCOPY_change_start)) {
1244 auto EIncr = getAsInteger<int64_t>(Val: Arg->getValue());
1245 if (!EIncr)
1246 return createStringError(EC: EIncr.getError(),
1247 Fmt: "bad entry point increment: '%s'",
1248 Vals: Arg->getValue());
1249 auto Expr = ELFConfig.EntryExpr ? std::move(ELFConfig.EntryExpr)
1250 : [](uint64_t A) { return A; };
1251 ELFConfig.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
1252 return Expr(EAddr) + *EIncr;
1253 };
1254 }
1255
1256 for (auto *Arg : InputArgs.filtered(Ids: OBJCOPY_remove_note)) {
1257 Expected<RemoveNoteInfo> NoteInfo = parseRemoveNoteInfo(FlagValue: Arg->getValue());
1258 if (!NoteInfo)
1259 return NoteInfo.takeError();
1260
1261 ELFConfig.NotesToRemove.push_back(Elt: *NoteInfo);
1262 }
1263
1264 if (!ELFConfig.NotesToRemove.empty()) {
1265 if (!Config.ToRemove.empty())
1266 return createStringError(
1267 EC: errc::invalid_argument,
1268 S: "cannot specify both --remove-note and --remove-section");
1269 if (!Config.AddSection.empty())
1270 return createStringError(
1271 EC: errc::invalid_argument,
1272 S: "cannot specify both --remove-note and --add-section");
1273 if (!Config.UpdateSection.empty())
1274 return createStringError(
1275 EC: errc::invalid_argument,
1276 S: "cannot specify both --remove-note and --update-section");
1277 }
1278
1279 if (Config.DecompressDebugSections &&
1280 Config.CompressionType != DebugCompressionType::None) {
1281 return createStringError(
1282 EC: errc::invalid_argument,
1283 S: "cannot specify both --compress-debug-sections and "
1284 "--decompress-debug-sections");
1285 }
1286
1287 if (Config.ExtractPartition && Config.ExtractMainPartition)
1288 return createStringError(EC: errc::invalid_argument,
1289 S: "cannot specify --extract-partition together with "
1290 "--extract-main-partition");
1291
1292 DC.CopyConfigs.push_back(Elt: std::move(ConfigMgr));
1293 return std::move(DC);
1294}
1295
1296// parseInstallNameToolOptions returns the config and sets the input arguments.
1297// If a help flag is set then parseInstallNameToolOptions will print the help
1298// messege and exit.
1299Expected<DriverConfig>
1300objcopy::parseInstallNameToolOptions(ArrayRef<const char *> ArgsArr) {
1301 DriverConfig DC;
1302 ConfigManager ConfigMgr;
1303 CommonConfig &Config = ConfigMgr.Common;
1304 MachOConfig &MachOConfig = ConfigMgr.MachO;
1305 InstallNameToolOptTable T;
1306 unsigned MissingArgumentIndex, MissingArgumentCount;
1307 llvm::opt::InputArgList InputArgs =
1308 T.ParseArgs(Args: ArgsArr, MissingArgIndex&: MissingArgumentIndex, MissingArgCount&: MissingArgumentCount);
1309
1310 if (MissingArgumentCount)
1311 return createStringError(
1312 EC: errc::invalid_argument,
1313 S: "missing argument to " +
1314 StringRef(InputArgs.getArgString(Index: MissingArgumentIndex)) +
1315 " option");
1316
1317 if (InputArgs.size() == 0) {
1318 printHelp(OptTable: T, OS&: errs(), Tool: ToolType::InstallNameTool);
1319 exit(status: 1);
1320 }
1321
1322 if (InputArgs.hasArg(Ids: INSTALL_NAME_TOOL_help)) {
1323 printHelp(OptTable: T, OS&: outs(), Tool: ToolType::InstallNameTool);
1324 exit(status: 0);
1325 }
1326
1327 if (InputArgs.hasArg(Ids: INSTALL_NAME_TOOL_version)) {
1328 outs() << "llvm-install-name-tool, compatible with cctools "
1329 "install_name_tool\n";
1330 cl::PrintVersionMessage();
1331 exit(status: 0);
1332 }
1333
1334 for (auto *Arg : InputArgs.filtered(Ids: INSTALL_NAME_TOOL_add_rpath))
1335 MachOConfig.RPathToAdd.push_back(x: Arg->getValue());
1336
1337 for (auto *Arg : InputArgs.filtered(Ids: INSTALL_NAME_TOOL_prepend_rpath))
1338 MachOConfig.RPathToPrepend.push_back(x: Arg->getValue());
1339
1340 for (auto *Arg : InputArgs.filtered(Ids: INSTALL_NAME_TOOL_delete_rpath)) {
1341 StringRef RPath = Arg->getValue();
1342
1343 // Cannot add and delete the same rpath at the same time.
1344 if (is_contained(Range&: MachOConfig.RPathToAdd, Element: RPath))
1345 return createStringError(
1346 EC: errc::invalid_argument,
1347 Fmt: "cannot specify both -add_rpath '%s' and -delete_rpath '%s'",
1348 Vals: RPath.str().c_str(), Vals: RPath.str().c_str());
1349 if (is_contained(Range&: MachOConfig.RPathToPrepend, Element: RPath))
1350 return createStringError(
1351 EC: errc::invalid_argument,
1352 Fmt: "cannot specify both -prepend_rpath '%s' and -delete_rpath '%s'",
1353 Vals: RPath.str().c_str(), Vals: RPath.str().c_str());
1354
1355 MachOConfig.RPathsToRemove.insert(V: RPath);
1356 }
1357
1358 for (auto *Arg : InputArgs.filtered(Ids: INSTALL_NAME_TOOL_rpath)) {
1359 StringRef Old = Arg->getValue(N: 0);
1360 StringRef New = Arg->getValue(N: 1);
1361
1362 auto Match = [=](StringRef RPath) { return RPath == Old || RPath == New; };
1363
1364 // Cannot specify duplicate -rpath entries
1365 auto It1 = find_if(
1366 Range&: MachOConfig.RPathsToUpdate,
1367 P: [&Match](const DenseMap<StringRef, StringRef>::value_type &OldNew) {
1368 return Match(OldNew.getFirst()) || Match(OldNew.getSecond());
1369 });
1370 if (It1 != MachOConfig.RPathsToUpdate.end())
1371 return createStringError(EC: errc::invalid_argument,
1372 S: "cannot specify both -rpath '" +
1373 It1->getFirst() + "' '" + It1->getSecond() +
1374 "' and -rpath '" + Old + "' '" + New + "'");
1375
1376 // Cannot specify the same rpath under both -delete_rpath and -rpath
1377 auto It2 = find_if(Range&: MachOConfig.RPathsToRemove, P: Match);
1378 if (It2 != MachOConfig.RPathsToRemove.end())
1379 return createStringError(EC: errc::invalid_argument,
1380 S: "cannot specify both -delete_rpath '" + *It2 +
1381 "' and -rpath '" + Old + "' '" + New + "'");
1382
1383 // Cannot specify the same rpath under both -add_rpath and -rpath
1384 auto It3 = find_if(Range&: MachOConfig.RPathToAdd, P: Match);
1385 if (It3 != MachOConfig.RPathToAdd.end())
1386 return createStringError(EC: errc::invalid_argument,
1387 S: "cannot specify both -add_rpath '" + *It3 +
1388 "' and -rpath '" + Old + "' '" + New + "'");
1389
1390 // Cannot specify the same rpath under both -prepend_rpath and -rpath.
1391 auto It4 = find_if(Range&: MachOConfig.RPathToPrepend, P: Match);
1392 if (It4 != MachOConfig.RPathToPrepend.end())
1393 return createStringError(EC: errc::invalid_argument,
1394 S: "cannot specify both -prepend_rpath '" + *It4 +
1395 "' and -rpath '" + Old + "' '" + New + "'");
1396
1397 MachOConfig.RPathsToUpdate.insert(KV: {Old, New});
1398 }
1399
1400 if (auto *Arg = InputArgs.getLastArg(Ids: INSTALL_NAME_TOOL_id)) {
1401 MachOConfig.SharedLibId = Arg->getValue();
1402 if (MachOConfig.SharedLibId->empty())
1403 return createStringError(EC: errc::invalid_argument,
1404 S: "cannot specify an empty id");
1405 }
1406
1407 for (auto *Arg : InputArgs.filtered(Ids: INSTALL_NAME_TOOL_change))
1408 MachOConfig.InstallNamesToUpdate.insert(
1409 KV: {Arg->getValue(N: 0), Arg->getValue(N: 1)});
1410
1411 MachOConfig.RemoveAllRpaths =
1412 InputArgs.hasArg(Ids: INSTALL_NAME_TOOL_delete_all_rpaths);
1413
1414 SmallVector<StringRef, 2> Positional;
1415 for (auto *Arg : InputArgs.filtered(Ids: INSTALL_NAME_TOOL_UNKNOWN))
1416 return createStringError(EC: errc::invalid_argument, Fmt: "unknown argument '%s'",
1417 Vals: Arg->getAsString(Args: InputArgs).c_str());
1418 for (auto *Arg : InputArgs.filtered(Ids: INSTALL_NAME_TOOL_INPUT))
1419 Positional.push_back(Elt: Arg->getValue());
1420 if (Positional.empty())
1421 return createStringError(EC: errc::invalid_argument, S: "no input file specified");
1422 if (Positional.size() > 1)
1423 return createStringError(
1424 EC: errc::invalid_argument,
1425 S: "llvm-install-name-tool expects a single input file");
1426 Config.InputFilename = Positional[0];
1427 Config.OutputFilename = Positional[0];
1428
1429 Expected<OwningBinary<Binary>> BinaryOrErr =
1430 createBinary(Path: Config.InputFilename);
1431 if (!BinaryOrErr)
1432 return createFileError(F: Config.InputFilename, E: BinaryOrErr.takeError());
1433 auto *Binary = (*BinaryOrErr).getBinary();
1434 if (!Binary->isMachO() && !Binary->isMachOUniversalBinary())
1435 return createStringError(EC: errc::invalid_argument,
1436 Fmt: "input file: %s is not a Mach-O file",
1437 Vals: Config.InputFilename.str().c_str());
1438
1439 DC.CopyConfigs.push_back(Elt: std::move(ConfigMgr));
1440 return std::move(DC);
1441}
1442
1443Expected<DriverConfig>
1444objcopy::parseBitcodeStripOptions(ArrayRef<const char *> ArgsArr,
1445 function_ref<Error(Error)> ErrorCallback) {
1446 DriverConfig DC;
1447 ConfigManager ConfigMgr;
1448 CommonConfig &Config = ConfigMgr.Common;
1449 MachOConfig &MachOConfig = ConfigMgr.MachO;
1450 BitcodeStripOptTable T;
1451 unsigned MissingArgumentIndex, MissingArgumentCount;
1452 opt::InputArgList InputArgs =
1453 T.ParseArgs(Args: ArgsArr, MissingArgIndex&: MissingArgumentIndex, MissingArgCount&: MissingArgumentCount);
1454
1455 if (InputArgs.size() == 0) {
1456 printHelp(OptTable: T, OS&: errs(), Tool: ToolType::BitcodeStrip);
1457 exit(status: 1);
1458 }
1459
1460 if (InputArgs.hasArg(Ids: BITCODE_STRIP_help)) {
1461 printHelp(OptTable: T, OS&: outs(), Tool: ToolType::BitcodeStrip);
1462 exit(status: 0);
1463 }
1464
1465 if (InputArgs.hasArg(Ids: BITCODE_STRIP_version)) {
1466 outs() << "llvm-bitcode-strip, compatible with cctools "
1467 "bitcode_strip\n";
1468 cl::PrintVersionMessage();
1469 exit(status: 0);
1470 }
1471
1472 for (auto *Arg : InputArgs.filtered(Ids: BITCODE_STRIP_UNKNOWN))
1473 return createStringError(EC: errc::invalid_argument, Fmt: "unknown argument '%s'",
1474 Vals: Arg->getAsString(Args: InputArgs).c_str());
1475
1476 SmallVector<StringRef, 2> Positional;
1477 for (auto *Arg : InputArgs.filtered(Ids: BITCODE_STRIP_INPUT))
1478 Positional.push_back(Elt: Arg->getValue());
1479 if (Positional.size() > 1)
1480 return createStringError(EC: errc::invalid_argument,
1481 S: "llvm-bitcode-strip expects a single input file");
1482 assert(!Positional.empty());
1483 Config.InputFilename = Positional[0];
1484
1485 if (!InputArgs.hasArg(Ids: BITCODE_STRIP_output)) {
1486 return createStringError(EC: errc::invalid_argument,
1487 S: "-o is a required argument");
1488 }
1489 Config.OutputFilename = InputArgs.getLastArgValue(Id: BITCODE_STRIP_output);
1490
1491 if (!InputArgs.hasArg(Ids: BITCODE_STRIP_remove))
1492 return createStringError(EC: errc::invalid_argument, S: "no action specified");
1493
1494 // We only support -r for now, which removes all bitcode sections and
1495 // the __LLVM segment if it's now empty.
1496 cantFail(Err: Config.ToRemove.addMatcher(Matcher: NameOrPattern::create(
1497 Pattern: "__LLVM,__asm", MS: MatchStyle::Literal, ErrorCallback)));
1498 cantFail(Err: Config.ToRemove.addMatcher(Matcher: NameOrPattern::create(
1499 Pattern: "__LLVM,__bitcode", MS: MatchStyle::Literal, ErrorCallback)));
1500 cantFail(Err: Config.ToRemove.addMatcher(Matcher: NameOrPattern::create(
1501 Pattern: "__LLVM,__bundle", MS: MatchStyle::Literal, ErrorCallback)));
1502 cantFail(Err: Config.ToRemove.addMatcher(Matcher: NameOrPattern::create(
1503 Pattern: "__LLVM,__cmdline", MS: MatchStyle::Literal, ErrorCallback)));
1504 cantFail(Err: Config.ToRemove.addMatcher(Matcher: NameOrPattern::create(
1505 Pattern: "__LLVM,__swift_cmdline", MS: MatchStyle::Literal, ErrorCallback)));
1506 MachOConfig.EmptySegmentsToRemove.insert(V: "__LLVM");
1507
1508 DC.CopyConfigs.push_back(Elt: std::move(ConfigMgr));
1509 return std::move(DC);
1510}
1511
1512// parseStripOptions returns the config and sets the input arguments. If a
1513// help flag is set then parseStripOptions will print the help messege and
1514// exit.
1515Expected<DriverConfig>
1516objcopy::parseStripOptions(ArrayRef<const char *> RawArgsArr,
1517 function_ref<Error(Error)> ErrorCallback) {
1518 const char *const *DashDash =
1519 llvm::find_if(Range&: RawArgsArr, P: [](StringRef Str) { return Str == "--"; });
1520 ArrayRef<const char *> ArgsArr = ArrayRef(RawArgsArr.begin(), DashDash);
1521 if (DashDash != RawArgsArr.end())
1522 DashDash = std::next(x: DashDash);
1523
1524 StripOptTable T;
1525 unsigned MissingArgumentIndex, MissingArgumentCount;
1526 llvm::opt::InputArgList InputArgs =
1527 T.ParseArgs(Args: ArgsArr, MissingArgIndex&: MissingArgumentIndex, MissingArgCount&: MissingArgumentCount);
1528
1529 if (InputArgs.size() == 0 && DashDash == RawArgsArr.end()) {
1530 printHelp(OptTable: T, OS&: errs(), Tool: ToolType::Strip);
1531 exit(status: 1);
1532 }
1533
1534 if (InputArgs.hasArg(Ids: STRIP_help)) {
1535 printHelp(OptTable: T, OS&: outs(), Tool: ToolType::Strip);
1536 exit(status: 0);
1537 }
1538
1539 if (InputArgs.hasArg(Ids: STRIP_version)) {
1540 outs() << "llvm-strip, compatible with GNU strip\n";
1541 cl::PrintVersionMessage();
1542 exit(status: 0);
1543 }
1544
1545 SmallVector<StringRef, 2> Positional;
1546 for (auto *Arg : InputArgs.filtered(Ids: STRIP_UNKNOWN))
1547 return createStringError(EC: errc::invalid_argument, Fmt: "unknown argument '%s'",
1548 Vals: Arg->getAsString(Args: InputArgs).c_str());
1549 for (auto *Arg : InputArgs.filtered(Ids: STRIP_INPUT))
1550 Positional.push_back(Elt: Arg->getValue());
1551 std::copy(first: DashDash, last: RawArgsArr.end(), result: std::back_inserter(x&: Positional));
1552
1553 if (Positional.empty())
1554 return createStringError(EC: errc::invalid_argument, S: "no input file specified");
1555
1556 if (Positional.size() > 1 && InputArgs.hasArg(Ids: STRIP_output))
1557 return createStringError(
1558 EC: errc::invalid_argument,
1559 S: "multiple input files cannot be used in combination with -o");
1560
1561 ConfigManager ConfigMgr;
1562 CommonConfig &Config = ConfigMgr.Common;
1563 ELFConfig &ELFConfig = ConfigMgr.ELF;
1564 MachOConfig &MachOConfig = ConfigMgr.MachO;
1565
1566 if (InputArgs.hasArg(Ids: STRIP_regex) && InputArgs.hasArg(Ids: STRIP_wildcard))
1567 return createStringError(EC: errc::invalid_argument,
1568 S: "--regex and --wildcard are incompatible");
1569 MatchStyle SectionMatchStyle =
1570 InputArgs.hasArg(Ids: STRIP_regex) ? MatchStyle::Regex : MatchStyle::Wildcard;
1571 MatchStyle SymbolMatchStyle
1572 = InputArgs.hasArg(Ids: STRIP_regex) ? MatchStyle::Regex
1573 : InputArgs.hasArg(Ids: STRIP_wildcard) ? MatchStyle::Wildcard
1574 : MatchStyle::Literal;
1575 ELFConfig.AllowBrokenLinks = InputArgs.hasArg(Ids: STRIP_allow_broken_links);
1576 Config.StripDebug = InputArgs.hasArg(Ids: STRIP_strip_debug);
1577
1578 if (auto *Arg = InputArgs.getLastArg(Ids: STRIP_discard_all, Ids: STRIP_discard_locals))
1579 Config.DiscardMode = Arg->getOption().matches(ID: STRIP_discard_all)
1580 ? DiscardType::All
1581 : DiscardType::Locals;
1582 Config.StripSections = InputArgs.hasArg(Ids: STRIP_strip_sections);
1583 Config.StripUnneeded = InputArgs.hasArg(Ids: STRIP_strip_unneeded);
1584 if (auto Arg = InputArgs.getLastArg(Ids: STRIP_strip_all, Ids: STRIP_no_strip_all))
1585 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
1586 Config.StripAllGNU = InputArgs.hasArg(Ids: STRIP_strip_all_gnu);
1587 MachOConfig.StripSwiftSymbols = InputArgs.hasArg(Ids: STRIP_strip_swift_symbols);
1588 Config.OnlyKeepDebug = InputArgs.hasArg(Ids: STRIP_only_keep_debug);
1589 ELFConfig.KeepFileSymbols = InputArgs.hasArg(Ids: STRIP_keep_file_symbols);
1590 MachOConfig.KeepUndefined = InputArgs.hasArg(Ids: STRIP_keep_undefined);
1591
1592 for (auto *Arg : InputArgs.filtered(Ids: STRIP_keep_section))
1593 if (Error E = Config.KeepSection.addMatcher(Matcher: NameOrPattern::create(
1594 Pattern: Arg->getValue(), MS: SectionMatchStyle, ErrorCallback)))
1595 return std::move(E);
1596
1597 for (auto *Arg : InputArgs.filtered(Ids: STRIP_remove_section))
1598 if (Error E = Config.ToRemove.addMatcher(Matcher: NameOrPattern::create(
1599 Pattern: Arg->getValue(), MS: SectionMatchStyle, ErrorCallback)))
1600 return std::move(E);
1601
1602 for (auto *Arg : InputArgs.filtered(Ids: STRIP_strip_symbol))
1603 if (Error E = Config.SymbolsToRemove.addMatcher(Matcher: NameOrPattern::create(
1604 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1605 return std::move(E);
1606
1607 for (auto *Arg : InputArgs.filtered(Ids: STRIP_keep_symbol))
1608 if (Error E = Config.SymbolsToKeep.addMatcher(Matcher: NameOrPattern::create(
1609 Pattern: Arg->getValue(), MS: SymbolMatchStyle, ErrorCallback)))
1610 return std::move(E);
1611
1612 if (!InputArgs.hasArg(Ids: STRIP_no_strip_all) && !Config.StripDebug &&
1613 !Config.OnlyKeepDebug && !Config.StripUnneeded &&
1614 Config.DiscardMode == DiscardType::None && !Config.StripAllGNU &&
1615 Config.SymbolsToRemove.empty())
1616 Config.StripAll = true;
1617
1618 if (Config.DiscardMode == DiscardType::All) {
1619 Config.StripDebug = true;
1620 ELFConfig.KeepFileSymbols = true;
1621 }
1622
1623 Config.DeterministicArchives =
1624 InputArgs.hasFlag(Pos: STRIP_enable_deterministic_archives,
1625 Neg: STRIP_disable_deterministic_archives, /*default=*/Default: true);
1626
1627 Config.PreserveDates = InputArgs.hasArg(Ids: STRIP_preserve_dates);
1628 Config.InputFormat = FileFormat::Unspecified;
1629 Config.OutputFormat = FileFormat::Unspecified;
1630
1631 DriverConfig DC;
1632 if (Positional.size() == 1) {
1633 Config.InputFilename = Positional[0];
1634 Config.OutputFilename =
1635 InputArgs.getLastArgValue(Id: STRIP_output, Default: Positional[0]);
1636 DC.CopyConfigs.push_back(Elt: std::move(ConfigMgr));
1637 } else {
1638 StringMap<unsigned> InputFiles;
1639 for (StringRef Filename : Positional) {
1640 if (InputFiles[Filename]++ == 1) {
1641 if (Filename == "-")
1642 return createStringError(
1643 EC: errc::invalid_argument,
1644 S: "cannot specify '-' as an input file more than once");
1645 if (Error E = ErrorCallback(createStringError(
1646 EC: errc::invalid_argument, Fmt: "'%s' was already specified",
1647 Vals: Filename.str().c_str())))
1648 return std::move(E);
1649 }
1650 Config.InputFilename = Filename;
1651 Config.OutputFilename = Filename;
1652 DC.CopyConfigs.push_back(Elt: ConfigMgr);
1653 }
1654 }
1655
1656 if (Config.PreserveDates && (is_contained(Range&: Positional, Element: "-") ||
1657 InputArgs.getLastArgValue(Id: STRIP_output) == "-"))
1658 return createStringError(EC: errc::invalid_argument,
1659 S: "--preserve-dates requires a file");
1660
1661 return std::move(DC);
1662}
1663