blob: ba74759a34c2d59d77de8deefa87b1385d74dbad [file] [log] [blame]
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001//===- CopyConfig.cpp -----------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "CopyConfig.h"
Simon Pilgrim090cf452020-05-17 18:51:21 +010010
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000011#include "llvm/ADT/Optional.h"
12#include "llvm/ADT/SmallVector.h"
13#include "llvm/ADT/StringRef.h"
Alex Brachet77477002019-06-18 00:39:10 +000014#include "llvm/ADT/StringSet.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000015#include "llvm/Option/Arg.h"
16#include "llvm/Option/ArgList.h"
Hans Wennborg1e1e3ba2019-10-09 09:06:30 +000017#include "llvm/Support/CRC.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000018#include "llvm/Support/CommandLine.h"
19#include "llvm/Support/Compression.h"
Eugene Leviant340cb872019-02-08 10:33:16 +000020#include "llvm/Support/Errc.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000021#include "llvm/Support/MemoryBuffer.h"
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +000022#include "llvm/Support/StringSaver.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000023#include <memory>
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000024
25namespace llvm {
26namespace objcopy {
27
28namespace {
29enum ObjcopyID {
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) \
33 OBJCOPY_##ID,
34#include "ObjcopyOpts.inc"
35#undef OPTION
36};
37
38#define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
39#include "ObjcopyOpts.inc"
40#undef PREFIX
41
42static const opt::OptTable::Info ObjcopyInfoTable[] = {
43#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
44 HELPTEXT, METAVAR, VALUES) \
45 {OBJCOPY_##PREFIX, \
46 NAME, \
47 HELPTEXT, \
48 METAVAR, \
49 OBJCOPY_##ID, \
50 opt::Option::KIND##Class, \
51 PARAM, \
52 FLAGS, \
53 OBJCOPY_##GROUP, \
54 OBJCOPY_##ALIAS, \
55 ALIASARGS, \
56 VALUES},
57#include "ObjcopyOpts.inc"
58#undef OPTION
59};
60
61class ObjcopyOptTable : public opt::OptTable {
62public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +000063 ObjcopyOptTable() : OptTable(ObjcopyInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000064};
65
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -080066enum InstallNameToolID {
67 INSTALL_NAME_TOOL_INVALID = 0, // This is not an option ID.
68#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
69 HELPTEXT, METAVAR, VALUES) \
70 INSTALL_NAME_TOOL_##ID,
71#include "InstallNameToolOpts.inc"
72#undef OPTION
73};
74
75#define PREFIX(NAME, VALUE) \
76 const char *const INSTALL_NAME_TOOL_##NAME[] = VALUE;
77#include "InstallNameToolOpts.inc"
78#undef PREFIX
79
80static const opt::OptTable::Info InstallNameToolInfoTable[] = {
81#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
82 HELPTEXT, METAVAR, VALUES) \
83 {INSTALL_NAME_TOOL_##PREFIX, \
84 NAME, \
85 HELPTEXT, \
86 METAVAR, \
87 INSTALL_NAME_TOOL_##ID, \
88 opt::Option::KIND##Class, \
89 PARAM, \
90 FLAGS, \
91 INSTALL_NAME_TOOL_##GROUP, \
92 INSTALL_NAME_TOOL_##ALIAS, \
93 ALIASARGS, \
94 VALUES},
95#include "InstallNameToolOpts.inc"
96#undef OPTION
97};
98
99class InstallNameToolOptTable : public opt::OptTable {
100public:
101 InstallNameToolOptTable() : OptTable(InstallNameToolInfoTable) {}
102};
103
Alexander Shaposhnikov5495b692020-09-18 18:11:22 -0700104enum BitcodeStripID {
105 BITCODE_STRIP_INVALID = 0, // This is not an option ID.
106#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
107 HELPTEXT, METAVAR, VALUES) \
108 BITCODE_STRIP_##ID,
109#include "BitcodeStripOpts.inc"
110#undef OPTION
111};
112
113#define PREFIX(NAME, VALUE) const char *const BITCODE_STRIP_##NAME[] = VALUE;
114#include "BitcodeStripOpts.inc"
115#undef PREFIX
116
117static const opt::OptTable::Info BitcodeStripInfoTable[] = {
118#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
119 HELPTEXT, METAVAR, VALUES) \
120 {BITCODE_STRIP_##PREFIX, \
121 NAME, \
122 HELPTEXT, \
123 METAVAR, \
124 BITCODE_STRIP_##ID, \
125 opt::Option::KIND##Class, \
126 PARAM, \
127 FLAGS, \
128 BITCODE_STRIP_##GROUP, \
129 BITCODE_STRIP_##ALIAS, \
130 ALIASARGS, \
131 VALUES},
132#include "BitcodeStripOpts.inc"
133#undef OPTION
134};
135
136class BitcodeStripOptTable : public opt::OptTable {
137public:
138 BitcodeStripOptTable() : OptTable(BitcodeStripInfoTable) {}
139};
140
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000141enum StripID {
142 STRIP_INVALID = 0, // This is not an option ID.
143#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
144 HELPTEXT, METAVAR, VALUES) \
145 STRIP_##ID,
146#include "StripOpts.inc"
147#undef OPTION
148};
149
150#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
151#include "StripOpts.inc"
152#undef PREFIX
153
154static const opt::OptTable::Info StripInfoTable[] = {
155#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
156 HELPTEXT, METAVAR, VALUES) \
157 {STRIP_##PREFIX, NAME, HELPTEXT, \
158 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
159 PARAM, FLAGS, STRIP_##GROUP, \
160 STRIP_##ALIAS, ALIASARGS, VALUES},
161#include "StripOpts.inc"
162#undef OPTION
163};
164
165class StripOptTable : public opt::OptTable {
166public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +0000167 StripOptTable() : OptTable(StripInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000168};
169
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000170} // namespace
171
172static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
173 return llvm::StringSwitch<SectionFlag>(SectionName)
James Hendersond931cf32019-04-03 14:40:27 +0000174 .CaseLower("alloc", SectionFlag::SecAlloc)
175 .CaseLower("load", SectionFlag::SecLoad)
176 .CaseLower("noload", SectionFlag::SecNoload)
177 .CaseLower("readonly", SectionFlag::SecReadonly)
178 .CaseLower("debug", SectionFlag::SecDebug)
179 .CaseLower("code", SectionFlag::SecCode)
180 .CaseLower("data", SectionFlag::SecData)
181 .CaseLower("rom", SectionFlag::SecRom)
182 .CaseLower("merge", SectionFlag::SecMerge)
183 .CaseLower("strings", SectionFlag::SecStrings)
184 .CaseLower("contents", SectionFlag::SecContents)
185 .CaseLower("share", SectionFlag::SecShare)
Sergey Dmitrieve4463222020-01-20 17:06:03 -0800186 .CaseLower("exclude", SectionFlag::SecExclude)
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000187 .Default(SectionFlag::SecNone);
188}
189
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000190static Expected<SectionFlag>
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000191parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000192 SectionFlag ParsedFlags = SectionFlag::SecNone;
193 for (StringRef Flag : SectionFlags) {
194 SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
195 if (ParsedFlag == SectionFlag::SecNone)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000196 return createStringError(
197 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000198 "unrecognized section flag '%s'. Flags supported for GNU "
Sergey Dmitrieve4463222020-01-20 17:06:03 -0800199 "compatibility: alloc, load, noload, readonly, exclude, debug, "
200 "code, data, rom, share, contents, merge, strings",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000201 Flag.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000202 ParsedFlags |= ParsedFlag;
203 }
204
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000205 return ParsedFlags;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000206}
207
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000208static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000209 if (!FlagValue.contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000210 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000211 "bad format for --rename-section: missing '='");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000212
213 // Initial split: ".foo" = ".bar,f1,f2,..."
214 auto Old2New = FlagValue.split('=');
215 SectionRename SR;
216 SR.OriginalName = Old2New.first;
217
218 // Flags split: ".bar" "f1" "f2" ...
219 SmallVector<StringRef, 6> NameAndFlags;
220 Old2New.second.split(NameAndFlags, ',');
221 SR.NewName = NameAndFlags[0];
222
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000223 if (NameAndFlags.size() > 1) {
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000224 Expected<SectionFlag> ParsedFlagSet =
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000225 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
226 if (!ParsedFlagSet)
227 return ParsedFlagSet.takeError();
228 SR.NewFlags = *ParsedFlagSet;
229 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000230
231 return SR;
232}
233
Fangrui Song671fb342019-10-02 12:41:25 +0000234static Expected<std::pair<StringRef, uint64_t>>
235parseSetSectionAlignment(StringRef FlagValue) {
236 if (!FlagValue.contains('='))
237 return createStringError(
238 errc::invalid_argument,
239 "bad format for --set-section-alignment: missing '='");
240 auto Split = StringRef(FlagValue).split('=');
241 if (Split.first.empty())
242 return createStringError(
243 errc::invalid_argument,
244 "bad format for --set-section-alignment: missing section name");
245 uint64_t NewAlign;
246 if (Split.second.getAsInteger(0, NewAlign))
247 return createStringError(errc::invalid_argument,
248 "invalid alignment for --set-section-alignment: '%s'",
249 Split.second.str().c_str());
250 return std::make_pair(Split.first, NewAlign);
251}
252
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000253static Expected<SectionFlagsUpdate>
254parseSetSectionFlagValue(StringRef FlagValue) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000255 if (!StringRef(FlagValue).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000256 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000257 "bad format for --set-section-flags: missing '='");
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000258
259 // Initial split: ".foo" = "f1,f2,..."
260 auto Section2Flags = StringRef(FlagValue).split('=');
261 SectionFlagsUpdate SFU;
262 SFU.Name = Section2Flags.first;
263
264 // Flags split: "f1" "f2" ...
265 SmallVector<StringRef, 6> SectionFlags;
266 Section2Flags.second.split(SectionFlags, ',');
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000267 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000268 if (!ParsedFlagSet)
269 return ParsedFlagSet.takeError();
270 SFU.NewFlags = *ParsedFlagSet;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000271
272 return SFU;
273}
274
Seiya Nutaecb60b72019-07-05 05:28:38 +0000275struct TargetInfo {
276 FileFormat Format;
277 MachineInfo Machine;
278};
279
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000280// FIXME: consolidate with the bfd parsing used by lld.
Seiya Nutaecb60b72019-07-05 05:28:38 +0000281static const StringMap<MachineInfo> TargetMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000282 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000283 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000284 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000285 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000286 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
287 // Intel MCU
288 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
289 // ARM
290 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
291 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000292 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
293 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000294 // RISC-V
295 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
296 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
297 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000298 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
299 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
300 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
301 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000302 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000303 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
304 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000305 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000306 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
307 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000308 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
309 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Seiya Nuta13de1742019-06-17 02:03:45 +0000310 // SPARC
311 {"elf32-sparc", {ELF::EM_SPARC, false, false}},
312 {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
Sid Manning50028632020-04-06 12:40:19 -0500313 {"elf32-hexagon", {ELF::EM_HEXAGON, false, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000314};
315
Seiya Nutaecb60b72019-07-05 05:28:38 +0000316static Expected<TargetInfo>
317getOutputTargetInfoByTargetName(StringRef TargetName) {
318 StringRef OriginalTargetName = TargetName;
319 bool IsFreeBSD = TargetName.consume_back("-freebsd");
320 auto Iter = TargetMap.find(TargetName);
321 if (Iter == std::end(TargetMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000322 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000323 "invalid output format: '%s'",
Seiya Nutaecb60b72019-07-05 05:28:38 +0000324 OriginalTargetName.str().c_str());
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000325 MachineInfo MI = Iter->getValue();
326 if (IsFreeBSD)
327 MI.OSABI = ELF::ELFOSABI_FREEBSD;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000328
329 FileFormat Format;
330 if (TargetName.startswith("elf"))
331 Format = FileFormat::ELF;
332 else
333 // This should never happen because `TargetName` is valid (it certainly
334 // exists in the TargetMap).
335 llvm_unreachable("unknown target prefix");
336
337 return {TargetInfo{Format, MI}};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000338}
339
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000340static Error
341addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
342 StringRef Filename, MatchStyle MS,
343 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000344 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000345 SmallVector<StringRef, 16> Lines;
346 auto BufOrErr = MemoryBuffer::getFile(Filename);
347 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000348 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000349
350 BufOrErr.get()->getBuffer().split(Lines, '\n');
351 for (StringRef Line : Lines) {
352 // Ignore everything after '#', trim whitespace, and only add the symbol if
353 // it's not empty.
354 auto TrimmedLine = Line.split('#').first.trim();
355 if (!TrimmedLine.empty())
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000356 if (Error E = Symbols.addMatcher(NameOrPattern::create(
357 Saver.save(TrimmedLine), MS, ErrorCallback)))
358 return E;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000359 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000360
361 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000362}
363
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000364Expected<NameOrPattern>
365NameOrPattern::create(StringRef Pattern, MatchStyle MS,
366 llvm::function_ref<Error(Error)> ErrorCallback) {
367 switch (MS) {
368 case MatchStyle::Literal:
369 return NameOrPattern(Pattern);
370 case MatchStyle::Wildcard: {
371 SmallVector<char, 32> Data;
372 bool IsPositiveMatch = true;
373 if (Pattern[0] == '!') {
374 IsPositiveMatch = false;
375 Pattern = Pattern.drop_front();
376 }
377 Expected<GlobPattern> GlobOrErr = GlobPattern::create(Pattern);
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000378
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000379 // If we couldn't create it as a glob, report the error, but try again with
380 // a literal if the error reporting is non-fatal.
381 if (!GlobOrErr) {
382 if (Error E = ErrorCallback(GlobOrErr.takeError()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800383 return std::move(E);
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000384 return create(Pattern, MatchStyle::Literal, ErrorCallback);
385 }
386
387 return NameOrPattern(std::make_shared<GlobPattern>(*GlobOrErr),
388 IsPositiveMatch);
389 }
390 case MatchStyle::Regex: {
391 SmallVector<char, 32> Data;
392 return NameOrPattern(std::make_shared<Regex>(
393 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data)));
394 }
395 }
Simon Pilgrim3bd61b22019-10-18 09:59:40 +0000396 llvm_unreachable("Unhandled llvm.objcopy.MatchStyle enum");
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000397}
398
Eugene Leviant340cb872019-02-08 10:33:16 +0000399static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
400 BumpPtrAllocator &Alloc,
401 StringRef Filename) {
402 StringSaver Saver(Alloc);
403 SmallVector<StringRef, 16> Lines;
404 auto BufOrErr = MemoryBuffer::getFile(Filename);
405 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000406 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000407
408 BufOrErr.get()->getBuffer().split(Lines, '\n');
409 size_t NumLines = Lines.size();
410 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
411 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
412 if (TrimmedLine.empty())
413 continue;
414
415 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
416 StringRef NewName = Pair.second.trim();
417 if (NewName.empty())
418 return createStringError(errc::invalid_argument,
419 "%s:%zu: missing new symbol name",
420 Filename.str().c_str(), LineNo + 1);
421 SymbolsToRename.insert({Pair.first, NewName});
422 }
423 return Error::success();
424}
Eugene Leviant53350d02019-02-26 09:24:22 +0000425
426template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
427 T Result;
428 if (Val.getAsInteger(0, Result))
429 return errc::invalid_argument;
430 return Result;
431}
432
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -0700433namespace {
434
Alexander Shaposhnikov5495b692020-09-18 18:11:22 -0700435enum class ToolType { Objcopy, Strip, InstallNameTool, BitcodeStrip };
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -0700436
437} // anonymous namespace
438
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000439static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -0700440 ToolType Tool) {
441 StringRef HelpText, ToolName;
442 switch (Tool) {
443 case ToolType::Objcopy:
444 ToolName = "llvm-objcopy";
445 HelpText = " [options] input [output]";
446 break;
447 case ToolType::Strip:
448 ToolName = "llvm-strip";
449 HelpText = " [options] inputs...";
450 break;
451 case ToolType::InstallNameTool:
452 ToolName = "llvm-install-name-tool";
453 HelpText = " [options] input";
454 break;
Alexander Shaposhnikov5495b692020-09-18 18:11:22 -0700455 case ToolType::BitcodeStrip:
456 ToolName = "llvm-bitcode-strip";
457 HelpText = " [options] input";
458 break;
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -0700459 }
460 OptTable.PrintHelp(OS, (ToolName + HelpText).str().c_str(),
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000461 (ToolName + " tool").str().c_str());
462 // TODO: Replace this with libOption call once it adds extrahelp support.
463 // The CommandLine library has a cl::extrahelp class to support this,
464 // but libOption does not have that yet.
465 OS << "\nPass @FILE as argument to read options from FILE.\n";
466}
467
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000468// ParseObjcopyOptions returns the config and sets the input arguments. If a
469// help flag is set then ParseObjcopyOptions will print the help messege and
470// exit.
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000471Expected<DriverConfig>
472parseObjcopyOptions(ArrayRef<const char *> ArgsArr,
473 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000474 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000475 ObjcopyOptTable T;
476 unsigned MissingArgumentIndex, MissingArgumentCount;
477 llvm::opt::InputArgList InputArgs =
478 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
479
480 if (InputArgs.size() == 0) {
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -0700481 printHelp(T, errs(), ToolType::Objcopy);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000482 exit(1);
483 }
484
485 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -0700486 printHelp(T, outs(), ToolType::Objcopy);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000487 exit(0);
488 }
489
490 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000491 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000492 cl::PrintVersionMessage();
493 exit(0);
494 }
495
496 SmallVector<const char *, 2> Positional;
497
498 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000499 return createStringError(errc::invalid_argument, "unknown argument '%s'",
500 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000501
502 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
503 Positional.push_back(Arg->getValue());
504
505 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000506 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000507
508 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000509 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000510 "too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000511
512 CopyConfig Config;
513 Config.InputFilename = Positional[0];
514 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000515 if (InputArgs.hasArg(OBJCOPY_target) &&
516 (InputArgs.hasArg(OBJCOPY_input_target) ||
517 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000518 return createStringError(
519 errc::invalid_argument,
520 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000521
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000522 if (InputArgs.hasArg(OBJCOPY_regex) && InputArgs.hasArg(OBJCOPY_wildcard))
523 return createStringError(errc::invalid_argument,
524 "--regex and --wildcard are incompatible");
525
526 MatchStyle SectionMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
527 ? MatchStyle::Regex
528 : MatchStyle::Wildcard;
529 MatchStyle SymbolMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
530 ? MatchStyle::Regex
531 : InputArgs.hasArg(OBJCOPY_wildcard)
532 ? MatchStyle::Wildcard
533 : MatchStyle::Literal;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000534 StringRef InputFormat, OutputFormat;
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000535 if (InputArgs.hasArg(OBJCOPY_target)) {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000536 InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
537 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000538 } else {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000539 InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
540 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000541 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000542
543 // FIXME: Currently, we ignore the target for non-binary/ihex formats
544 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
545 // format by llvm::object::createBinary regardless of the option value.
546 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
547 .Case("binary", FileFormat::Binary)
548 .Case("ihex", FileFormat::IHex)
549 .Default(FileFormat::Unspecified);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000550
Michael Liaod19fb462019-09-24 12:43:44 +0000551 if (InputArgs.hasArg(OBJCOPY_new_symbol_visibility))
Seiya Nutac83eefc2019-09-24 09:38:23 +0000552 Config.NewSymbolVisibility =
553 InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility);
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000554
Seiya Nutaecb60b72019-07-05 05:28:38 +0000555 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
556 .Case("binary", FileFormat::Binary)
557 .Case("ihex", FileFormat::IHex)
558 .Default(FileFormat::Unspecified);
Fangrui Songba530302019-09-14 01:36:16 +0000559 if (Config.OutputFormat == FileFormat::Unspecified) {
560 if (OutputFormat.empty()) {
561 Config.OutputFormat = Config.InputFormat;
562 } else {
563 Expected<TargetInfo> Target =
564 getOutputTargetInfoByTargetName(OutputFormat);
565 if (!Target)
566 return Target.takeError();
567 Config.OutputFormat = Target->Format;
568 Config.OutputArch = Target->Machine;
569 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000570 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000571
572 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
573 OBJCOPY_compress_debug_sections_eq)) {
574 Config.CompressionType = DebugCompressionType::Z;
575
576 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
577 Config.CompressionType =
578 StringSwitch<DebugCompressionType>(
579 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
580 .Case("zlib-gnu", DebugCompressionType::GNU)
581 .Case("zlib", DebugCompressionType::Z)
582 .Default(DebugCompressionType::None);
583 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000584 return createStringError(
585 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000586 "invalid or unsupported --compress-debug-sections format: %s",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000587 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
588 .str()
589 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000590 }
George Rimar1e930802019-03-05 11:32:14 +0000591 if (!zlib::isAvailable())
592 return createStringError(
593 errc::invalid_argument,
594 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000595 }
596
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000597 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000598 // The gnu_debuglink's target is expected to not change or else its CRC would
599 // become invalidated and get rejected. We can avoid recalculating the
600 // checksum for every target file inside an archive by precomputing the CRC
601 // here. This prevents a significant amount of I/O.
602 if (!Config.AddGnuDebugLink.empty()) {
603 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
604 if (!DebugOrErr)
605 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
606 auto Debug = std::move(*DebugOrErr);
Hans Wennborg1e1e3ba2019-10-09 09:06:30 +0000607 Config.GnuDebugLinkCRC32 =
608 llvm::crc32(arrayRefFromStringRef(Debug->getBuffer()));
James Henderson9df38832019-05-14 10:59:04 +0000609 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000610 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
611 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
612 Config.BuildIdLinkInput =
613 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
614 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
615 Config.BuildIdLinkOutput =
616 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
617 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000618 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000619 Config.AllocSectionsPrefix =
620 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000621 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
622 Config.ExtractPartition = Arg->getValue();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000623
624 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
625 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000626 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000627 "bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000628 auto Old2New = StringRef(Arg->getValue()).split('=');
629 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000630 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000631 "multiple redefinition of symbol '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000632 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000633 }
634
Eugene Leviant340cb872019-02-08 10:33:16 +0000635 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
636 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
637 Arg->getValue()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800638 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000639
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000640 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000641 Expected<SectionRename> SR =
642 parseRenameSectionValue(StringRef(Arg->getValue()));
643 if (!SR)
644 return SR.takeError();
645 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
646 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000647 "multiple renames of section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000648 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000649 }
Fangrui Song671fb342019-10-02 12:41:25 +0000650 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_alignment)) {
651 Expected<std::pair<StringRef, uint64_t>> NameAndAlign =
652 parseSetSectionAlignment(Arg->getValue());
653 if (!NameAndAlign)
654 return NameAndAlign.takeError();
655 Config.SetSectionAlignment[NameAndAlign->first] = NameAndAlign->second;
656 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000657 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000658 Expected<SectionFlagsUpdate> SFU =
659 parseSetSectionFlagValue(Arg->getValue());
660 if (!SFU)
661 return SFU.takeError();
662 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
663 return createStringError(
664 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000665 "--set-section-flags set multiple times for section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000666 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000667 }
668 // Prohibit combinations of --set-section-flags when the section name is used
669 // by --rename-section, either as a source or a destination.
670 for (const auto &E : Config.SectionsToRename) {
671 const SectionRename &SR = E.second;
672 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000673 return createStringError(
674 errc::invalid_argument,
675 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
676 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
677 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000678 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000679 return createStringError(
680 errc::invalid_argument,
681 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
682 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
683 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000684 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000685
686 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000687 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
688 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800689 return std::move(E);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000690 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000691 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
692 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800693 return std::move(E);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000694 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000695 if (Error E = Config.OnlySection.addMatcher(NameOrPattern::create(
696 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800697 return std::move(E);
Sergey Dmitriev899bdaa2019-07-29 16:22:40 +0000698 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
699 StringRef ArgValue(Arg->getValue());
700 if (!ArgValue.contains('='))
701 return createStringError(errc::invalid_argument,
702 "bad format for --add-section: missing '='");
703 if (ArgValue.split("=").second.empty())
704 return createStringError(
705 errc::invalid_argument,
706 "bad format for --add-section: missing file name");
707 Config.AddSection.push_back(ArgValue);
708 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000709 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
710 Config.DumpSection.push_back(Arg->getValue());
711 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
712 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
713 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
714 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
715 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
716 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
717 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
718 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000719 Config.ExtractMainPartition =
720 InputArgs.hasArg(OBJCOPY_extract_main_partition);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000721 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
722 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000723 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
724 Config.DiscardMode =
725 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
726 ? DiscardType::All
727 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000728 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
729 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
730 Config.DecompressDebugSections =
731 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Fangrui Songb14e9e32020-03-24 15:38:48 +0800732 if (Config.DiscardMode == DiscardType::All) {
Sid Manning5ad18a72019-05-03 14:14:01 +0000733 Config.StripDebug = true;
Fangrui Songb14e9e32020-03-24 15:38:48 +0800734 Config.KeepFileSymbols = true;
735 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000736 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000737 if (Error E = Config.SymbolsToLocalize.addMatcher(NameOrPattern::create(
738 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800739 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000740 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000741 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000742 Arg->getValue(), SymbolMatchStyle,
743 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800744 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000745 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000746 if (Error E = Config.SymbolsToKeepGlobal.addMatcher(NameOrPattern::create(
747 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800748 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000749 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000750 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000751 Arg->getValue(), SymbolMatchStyle,
752 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800753 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000754 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000755 if (Error E = Config.SymbolsToGlobalize.addMatcher(NameOrPattern::create(
756 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800757 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000758 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000759 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000760 Arg->getValue(), SymbolMatchStyle,
761 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800762 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000763 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000764 if (Error E = Config.SymbolsToWeaken.addMatcher(NameOrPattern::create(
765 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800766 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000767 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000768 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000769 Arg->getValue(), SymbolMatchStyle,
770 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800771 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000772 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000773 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
774 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800775 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000776 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000777 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000778 Arg->getValue(), SymbolMatchStyle,
779 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800780 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000781 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000782 if (Error E =
783 Config.UnneededSymbolsToRemove.addMatcher(NameOrPattern::create(
784 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800785 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000786 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000787 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000788 Arg->getValue(), SymbolMatchStyle,
789 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800790 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000791 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000792 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
793 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800794 return std::move(E);
Yi Kongf2baddb2019-04-01 18:12:43 +0000795 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000796 if (Error E =
797 addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc, Arg->getValue(),
798 SymbolMatchStyle, ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800799 return std::move(E);
Seiya Nutac83eefc2019-09-24 09:38:23 +0000800 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol))
801 Config.SymbolsToAdd.push_back(Arg->getValue());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000802
James Henderson66a9d0f2019-04-18 09:13:30 +0000803 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
804
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000805 Config.DeterministicArchives = InputArgs.hasFlag(
806 OBJCOPY_enable_deterministic_archives,
807 OBJCOPY_disable_deterministic_archives, /*default=*/true);
808
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000809 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
810
Alex Brachet899a3072019-06-15 05:32:23 +0000811 if (Config.PreserveDates &&
812 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
813 return createStringError(errc::invalid_argument,
814 "--preserve-dates requires a file");
815
Eugene Leviant53350d02019-02-26 09:24:22 +0000816 for (auto Arg : InputArgs)
817 if (Arg->getOption().matches(OBJCOPY_set_start)) {
818 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
819 if (!EAddr)
820 return createStringError(
821 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
822
823 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
824 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
825 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
826 if (!EIncr)
827 return createStringError(EIncr.getError(),
828 "bad entry point increment: '%s'",
829 Arg->getValue());
830 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
831 : [](uint64_t A) { return A; };
832 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
833 return Expr(EAddr) + *EIncr;
834 };
835 }
836
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000837 if (Config.DecompressDebugSections &&
838 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000839 return createStringError(
840 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000841 "cannot specify both --compress-debug-sections and "
842 "--decompress-debug-sections");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000843 }
844
845 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000846 return createStringError(
847 errc::invalid_argument,
848 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000849
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000850 if (Config.ExtractPartition && Config.ExtractMainPartition)
851 return createStringError(errc::invalid_argument,
852 "cannot specify --extract-partition together with "
853 "--extract-main-partition");
854
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000855 DC.CopyConfigs.push_back(std::move(Config));
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800856 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000857}
858
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800859// ParseInstallNameToolOptions returns the config and sets the input arguments.
860// If a help flag is set then ParseInstallNameToolOptions will print the help
861// messege and exit.
862Expected<DriverConfig>
863parseInstallNameToolOptions(ArrayRef<const char *> ArgsArr) {
864 DriverConfig DC;
865 CopyConfig Config;
866 InstallNameToolOptTable T;
867 unsigned MissingArgumentIndex, MissingArgumentCount;
868 llvm::opt::InputArgList InputArgs =
869 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
870
Alexander Shaposhnikovb925ca32020-06-26 17:22:15 -0700871 if (MissingArgumentCount)
872 return createStringError(
873 errc::invalid_argument,
874 "missing argument to " +
875 StringRef(InputArgs.getArgString(MissingArgumentIndex)) +
876 " option");
877
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800878 if (InputArgs.size() == 0) {
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -0700879 printHelp(T, errs(), ToolType::InstallNameTool);
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800880 exit(1);
881 }
882
883 if (InputArgs.hasArg(INSTALL_NAME_TOOL_help)) {
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -0700884 printHelp(T, outs(), ToolType::InstallNameTool);
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800885 exit(0);
886 }
887
888 if (InputArgs.hasArg(INSTALL_NAME_TOOL_version)) {
889 outs() << "llvm-install-name-tool, compatible with cctools "
890 "install_name_tool\n";
891 cl::PrintVersionMessage();
892 exit(0);
893 }
894
895 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_add_rpath))
896 Config.RPathToAdd.push_back(Arg->getValue());
897
Keith Smiley77cbf252020-10-23 15:00:25 -0700898 for (auto *Arg : InputArgs.filtered(INSTALL_NAME_TOOL_prepend_rpath))
899 Config.RPathToPrepend.push_back(Arg->getValue());
900
Alexander Shaposhnikovd332ec92020-06-22 16:49:14 -0700901 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_delete_rpath)) {
902 StringRef RPath = Arg->getValue();
903
904 // Cannot add and delete the same rpath at the same time.
905 if (is_contained(Config.RPathToAdd, RPath))
906 return createStringError(
907 errc::invalid_argument,
Keith Smiley51f8d462020-10-28 14:56:03 -0700908 "cannot specify both -add_rpath '%s' and -delete_rpath '%s'",
Alexander Shaposhnikovd332ec92020-06-22 16:49:14 -0700909 RPath.str().c_str(), RPath.str().c_str());
Keith Smiley77cbf252020-10-23 15:00:25 -0700910 if (is_contained(Config.RPathToPrepend, RPath))
911 return createStringError(
912 errc::invalid_argument,
Keith Smiley51f8d462020-10-28 14:56:03 -0700913 "cannot specify both -prepend_rpath '%s' and -delete_rpath '%s'",
Keith Smiley77cbf252020-10-23 15:00:25 -0700914 RPath.str().c_str(), RPath.str().c_str());
Alexander Shaposhnikovd332ec92020-06-22 16:49:14 -0700915
916 Config.RPathsToRemove.insert(RPath);
917 }
918
Alexander Shaposhnikovb925ca32020-06-26 17:22:15 -0700919 for (auto *Arg : InputArgs.filtered(INSTALL_NAME_TOOL_rpath)) {
920 StringRef Old = Arg->getValue(0);
921 StringRef New = Arg->getValue(1);
922
923 auto Match = [=](StringRef RPath) { return RPath == Old || RPath == New; };
924
925 // Cannot specify duplicate -rpath entries
Sameer Arora3b5db7f2020-07-06 14:53:24 -0700926 auto It1 = find_if(
927 Config.RPathsToUpdate,
928 [&Match](const DenseMap<StringRef, StringRef>::value_type &OldNew) {
929 return Match(OldNew.getFirst()) || Match(OldNew.getSecond());
930 });
Alexander Shaposhnikovb925ca32020-06-26 17:22:15 -0700931 if (It1 != Config.RPathsToUpdate.end())
Sameer Arora3b5db7f2020-07-06 14:53:24 -0700932 return createStringError(errc::invalid_argument,
Keith Smiley51f8d462020-10-28 14:56:03 -0700933 "cannot specify both -rpath '" +
934 It1->getFirst() + "' '" + It1->getSecond() +
935 "' and -rpath '" + Old + "' '" + New + "'");
Alexander Shaposhnikovb925ca32020-06-26 17:22:15 -0700936
937 // Cannot specify the same rpath under both -delete_rpath and -rpath
938 auto It2 = find_if(Config.RPathsToRemove, Match);
939 if (It2 != Config.RPathsToRemove.end())
Sameer Arora3b5db7f2020-07-06 14:53:24 -0700940 return createStringError(errc::invalid_argument,
Keith Smiley51f8d462020-10-28 14:56:03 -0700941 "cannot specify both -delete_rpath '" + *It2 +
942 "' and -rpath '" + Old + "' '" + New + "'");
Alexander Shaposhnikovb925ca32020-06-26 17:22:15 -0700943
944 // Cannot specify the same rpath under both -add_rpath and -rpath
945 auto It3 = find_if(Config.RPathToAdd, Match);
946 if (It3 != Config.RPathToAdd.end())
Sameer Arora3b5db7f2020-07-06 14:53:24 -0700947 return createStringError(errc::invalid_argument,
Keith Smiley51f8d462020-10-28 14:56:03 -0700948 "cannot specify both -add_rpath '" + *It3 +
949 "' and -rpath '" + Old + "' '" + New + "'");
Alexander Shaposhnikovb925ca32020-06-26 17:22:15 -0700950
Keith Smiley77cbf252020-10-23 15:00:25 -0700951 // Cannot specify the same rpath under both -prepend_rpath and -rpath.
952 auto It4 = find_if(Config.RPathToPrepend, Match);
953 if (It4 != Config.RPathToPrepend.end())
954 return createStringError(errc::invalid_argument,
Keith Smiley51f8d462020-10-28 14:56:03 -0700955 "cannot specify both -prepend_rpath '" + *It4 +
956 "' and -rpath '" + Old + "' '" + New + "'");
Keith Smiley77cbf252020-10-23 15:00:25 -0700957
Sameer Arora3b5db7f2020-07-06 14:53:24 -0700958 Config.RPathsToUpdate.insert({Old, New});
Alexander Shaposhnikovb925ca32020-06-26 17:22:15 -0700959 }
960
Alexander Shaposhnikove9f90272020-09-18 17:50:08 -0700961 if (auto *Arg = InputArgs.getLastArg(INSTALL_NAME_TOOL_id)) {
Sameer Aroraca518c42020-06-30 11:01:45 -0700962 Config.SharedLibId = Arg->getValue();
Alexander Shaposhnikove9f90272020-09-18 17:50:08 -0700963 if (Config.SharedLibId->empty())
964 return createStringError(errc::invalid_argument,
965 "cannot specify an empty id");
Sameer Arora2bdcd8b2020-06-30 11:01:51 -0700966 }
967
Alexander Shaposhnikove9f90272020-09-18 17:50:08 -0700968 for (auto *Arg : InputArgs.filtered(INSTALL_NAME_TOOL_change))
969 Config.InstallNamesToUpdate.insert({Arg->getValue(0), Arg->getValue(1)});
970
Tobias Hieta61133e02020-10-13 00:45:14 -0700971 Config.RemoveAllRpaths =
972 InputArgs.hasArg(INSTALL_NAME_TOOL_delete_all_rpaths);
973
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800974 SmallVector<StringRef, 2> Positional;
975 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_UNKNOWN))
976 return createStringError(errc::invalid_argument, "unknown argument '%s'",
977 Arg->getAsString(InputArgs).c_str());
978 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_INPUT))
979 Positional.push_back(Arg->getValue());
980 if (Positional.empty())
981 return createStringError(errc::invalid_argument, "no input file specified");
982 if (Positional.size() > 1)
983 return createStringError(
984 errc::invalid_argument,
985 "llvm-install-name-tool expects a single input file");
986 Config.InputFilename = Positional[0];
987 Config.OutputFilename = Positional[0];
988
989 DC.CopyConfigs.push_back(std::move(Config));
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800990 return std::move(DC);
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800991}
992
Alexander Shaposhnikov5495b692020-09-18 18:11:22 -0700993Expected<DriverConfig>
994parseBitcodeStripOptions(ArrayRef<const char *> ArgsArr) {
995 DriverConfig DC;
996 CopyConfig Config;
997 BitcodeStripOptTable T;
998 unsigned MissingArgumentIndex, MissingArgumentCount;
999 opt::InputArgList InputArgs =
1000 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
1001
1002 if (InputArgs.size() == 0) {
1003 printHelp(T, errs(), ToolType::BitcodeStrip);
1004 exit(1);
1005 }
1006
1007 if (InputArgs.hasArg(BITCODE_STRIP_help)) {
1008 printHelp(T, outs(), ToolType::BitcodeStrip);
1009 exit(0);
1010 }
1011
1012 if (InputArgs.hasArg(BITCODE_STRIP_version)) {
1013 outs() << "llvm-bitcode-strip, compatible with cctools "
1014 "bitcode_strip\n";
1015 cl::PrintVersionMessage();
1016 exit(0);
1017 }
1018
1019 for (auto *Arg : InputArgs.filtered(BITCODE_STRIP_UNKNOWN))
1020 return createStringError(errc::invalid_argument, "unknown argument '%s'",
1021 Arg->getAsString(InputArgs).c_str());
1022
1023 SmallVector<StringRef, 2> Positional;
1024 for (auto *Arg : InputArgs.filtered(BITCODE_STRIP_INPUT))
1025 Positional.push_back(Arg->getValue());
1026 if (Positional.size() > 1)
1027 return createStringError(errc::invalid_argument,
1028 "llvm-bitcode-strip expects a single input file");
1029 assert(!Positional.empty());
1030 Config.InputFilename = Positional[0];
1031 Config.OutputFilename = Positional[0];
1032
1033 DC.CopyConfigs.push_back(std::move(Config));
1034 return std::move(DC);
1035}
1036
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001037// ParseStripOptions returns the config and sets the input arguments. If a
1038// help flag is set then ParseStripOptions will print the help messege and
1039// exit.
Alex Brachet77477002019-06-18 00:39:10 +00001040Expected<DriverConfig>
1041parseStripOptions(ArrayRef<const char *> ArgsArr,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +00001042 llvm::function_ref<Error(Error)> ErrorCallback) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001043 StripOptTable T;
1044 unsigned MissingArgumentIndex, MissingArgumentCount;
1045 llvm::opt::InputArgList InputArgs =
1046 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
1047
1048 if (InputArgs.size() == 0) {
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -07001049 printHelp(T, errs(), ToolType::Strip);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001050 exit(1);
1051 }
1052
1053 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovca133cd2020-06-24 11:19:31 -07001054 printHelp(T, outs(), ToolType::Strip);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001055 exit(0);
1056 }
1057
1058 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +00001059 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001060 cl::PrintVersionMessage();
1061 exit(0);
1062 }
1063
Alex Brachet899a3072019-06-15 05:32:23 +00001064 SmallVector<StringRef, 2> Positional;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001065 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +00001066 return createStringError(errc::invalid_argument, "unknown argument '%s'",
1067 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001068 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
1069 Positional.push_back(Arg->getValue());
1070
1071 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +00001072 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001073
1074 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +00001075 return createStringError(
1076 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +00001077 "multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001078
1079 CopyConfig Config;
Jordan Rupprechtedeebad2019-10-17 20:51:00 +00001080
1081 if (InputArgs.hasArg(STRIP_regex) && InputArgs.hasArg(STRIP_wildcard))
1082 return createStringError(errc::invalid_argument,
1083 "--regex and --wildcard are incompatible");
1084 MatchStyle SectionMatchStyle =
1085 InputArgs.hasArg(STRIP_regex) ? MatchStyle::Regex : MatchStyle::Wildcard;
1086 MatchStyle SymbolMatchStyle = InputArgs.hasArg(STRIP_regex)
1087 ? MatchStyle::Regex
1088 : InputArgs.hasArg(STRIP_wildcard)
1089 ? MatchStyle::Wildcard
1090 : MatchStyle::Literal;
James Henderson66a9d0f2019-04-18 09:13:30 +00001091 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001092 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
1093
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +00001094 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
1095 Config.DiscardMode =
1096 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
1097 ? DiscardType::All
1098 : DiscardType::Locals;
Wolfgang Piebab751a72019-08-08 00:35:16 +00001099 Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001100 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +00001101 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
1102 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +00001103 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Alexander Shaposhnikov842a8cc2020-05-26 16:49:56 -07001104 Config.StripSwiftSymbols = InputArgs.hasArg(STRIP_strip_swift_symbols);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +00001105 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +00001106 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001107
Jordan Rupprechtc5bae782018-11-13 19:32:27 +00001108 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +00001109 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
1110 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08001111 return std::move(E);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +00001112
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001113 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +00001114 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
1115 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08001116 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001117
Eugene Leviant2267c582019-01-31 12:16:20 +00001118 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +00001119 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
1120 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08001121 return std::move(E);
Eugene Leviant2267c582019-01-31 12:16:20 +00001122
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001123 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +00001124 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
1125 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08001126 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001127
James Hendersone4a89a12019-05-02 11:53:02 +00001128 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
1129 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
1130 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +00001131 Config.StripAll = true;
1132
Fangrui Songb14e9e32020-03-24 15:38:48 +08001133 if (Config.DiscardMode == DiscardType::All) {
Sid Manning5ad18a72019-05-03 14:14:01 +00001134 Config.StripDebug = true;
Fangrui Songb14e9e32020-03-24 15:38:48 +08001135 Config.KeepFileSymbols = true;
1136 }
Sid Manning5ad18a72019-05-03 14:14:01 +00001137
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +00001138 Config.DeterministicArchives =
1139 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
1140 STRIP_disable_deterministic_archives, /*default=*/true);
1141
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001142 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
Seiya Nutaecb60b72019-07-05 05:28:38 +00001143 Config.InputFormat = FileFormat::Unspecified;
1144 Config.OutputFormat = FileFormat::Unspecified;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001145
1146 DriverConfig DC;
1147 if (Positional.size() == 1) {
1148 Config.InputFilename = Positional[0];
1149 Config.OutputFilename =
1150 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
1151 DC.CopyConfigs.push_back(std::move(Config));
1152 } else {
Alex Brachet77477002019-06-18 00:39:10 +00001153 StringMap<unsigned> InputFiles;
Alex Brachet899a3072019-06-15 05:32:23 +00001154 for (StringRef Filename : Positional) {
Alex Brachet77477002019-06-18 00:39:10 +00001155 if (InputFiles[Filename]++ == 1) {
1156 if (Filename == "-")
1157 return createStringError(
1158 errc::invalid_argument,
1159 "cannot specify '-' as an input file more than once");
1160 if (Error E = ErrorCallback(createStringError(
1161 errc::invalid_argument, "'%s' was already specified",
1162 Filename.str().c_str())))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08001163 return std::move(E);
Alex Brachet77477002019-06-18 00:39:10 +00001164 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001165 Config.InputFilename = Filename;
1166 Config.OutputFilename = Filename;
1167 DC.CopyConfigs.push_back(Config);
1168 }
1169 }
1170
Alex Brachet899a3072019-06-15 05:32:23 +00001171 if (Config.PreserveDates && (is_contained(Positional, "-") ||
1172 InputArgs.getLastArgValue(STRIP_output) == "-"))
1173 return createStringError(errc::invalid_argument,
1174 "--preserve-dates requires a file");
1175
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08001176 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001177}
1178
1179} // namespace objcopy
1180} // namespace llvm