blob: c8056311018aa8f6319e7b6c869f3005a3839b18 [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"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000010
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
66enum StripID {
67 STRIP_INVALID = 0, // This is not an option ID.
68#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
69 HELPTEXT, METAVAR, VALUES) \
70 STRIP_##ID,
71#include "StripOpts.inc"
72#undef OPTION
73};
74
75#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
76#include "StripOpts.inc"
77#undef PREFIX
78
79static const opt::OptTable::Info StripInfoTable[] = {
80#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
81 HELPTEXT, METAVAR, VALUES) \
82 {STRIP_##PREFIX, NAME, HELPTEXT, \
83 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
84 PARAM, FLAGS, STRIP_##GROUP, \
85 STRIP_##ALIAS, ALIASARGS, VALUES},
86#include "StripOpts.inc"
87#undef OPTION
88};
89
90class StripOptTable : public opt::OptTable {
91public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +000092 StripOptTable() : OptTable(StripInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000093};
94
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000095} // namespace
96
97static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
98 return llvm::StringSwitch<SectionFlag>(SectionName)
James Hendersond931cf32019-04-03 14:40:27 +000099 .CaseLower("alloc", SectionFlag::SecAlloc)
100 .CaseLower("load", SectionFlag::SecLoad)
101 .CaseLower("noload", SectionFlag::SecNoload)
102 .CaseLower("readonly", SectionFlag::SecReadonly)
103 .CaseLower("debug", SectionFlag::SecDebug)
104 .CaseLower("code", SectionFlag::SecCode)
105 .CaseLower("data", SectionFlag::SecData)
106 .CaseLower("rom", SectionFlag::SecRom)
107 .CaseLower("merge", SectionFlag::SecMerge)
108 .CaseLower("strings", SectionFlag::SecStrings)
109 .CaseLower("contents", SectionFlag::SecContents)
110 .CaseLower("share", SectionFlag::SecShare)
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000111 .Default(SectionFlag::SecNone);
112}
113
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000114static Expected<SectionFlag>
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000115parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000116 SectionFlag ParsedFlags = SectionFlag::SecNone;
117 for (StringRef Flag : SectionFlags) {
118 SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
119 if (ParsedFlag == SectionFlag::SecNone)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000120 return createStringError(
121 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000122 "unrecognized section flag '%s'. Flags supported for GNU "
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000123 "compatibility: alloc, load, noload, readonly, debug, code, data, "
124 "rom, share, contents, merge, strings",
125 Flag.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000126 ParsedFlags |= ParsedFlag;
127 }
128
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000129 return ParsedFlags;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000130}
131
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000132static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000133 if (!FlagValue.contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000134 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000135 "bad format for --rename-section: missing '='");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000136
137 // Initial split: ".foo" = ".bar,f1,f2,..."
138 auto Old2New = FlagValue.split('=');
139 SectionRename SR;
140 SR.OriginalName = Old2New.first;
141
142 // Flags split: ".bar" "f1" "f2" ...
143 SmallVector<StringRef, 6> NameAndFlags;
144 Old2New.second.split(NameAndFlags, ',');
145 SR.NewName = NameAndFlags[0];
146
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000147 if (NameAndFlags.size() > 1) {
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000148 Expected<SectionFlag> ParsedFlagSet =
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000149 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
150 if (!ParsedFlagSet)
151 return ParsedFlagSet.takeError();
152 SR.NewFlags = *ParsedFlagSet;
153 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000154
155 return SR;
156}
157
Fangrui Song671fb342019-10-02 12:41:25 +0000158static Expected<std::pair<StringRef, uint64_t>>
159parseSetSectionAlignment(StringRef FlagValue) {
160 if (!FlagValue.contains('='))
161 return createStringError(
162 errc::invalid_argument,
163 "bad format for --set-section-alignment: missing '='");
164 auto Split = StringRef(FlagValue).split('=');
165 if (Split.first.empty())
166 return createStringError(
167 errc::invalid_argument,
168 "bad format for --set-section-alignment: missing section name");
169 uint64_t NewAlign;
170 if (Split.second.getAsInteger(0, NewAlign))
171 return createStringError(errc::invalid_argument,
172 "invalid alignment for --set-section-alignment: '%s'",
173 Split.second.str().c_str());
174 return std::make_pair(Split.first, NewAlign);
175}
176
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000177static Expected<SectionFlagsUpdate>
178parseSetSectionFlagValue(StringRef FlagValue) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000179 if (!StringRef(FlagValue).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000180 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000181 "bad format for --set-section-flags: missing '='");
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000182
183 // Initial split: ".foo" = "f1,f2,..."
184 auto Section2Flags = StringRef(FlagValue).split('=');
185 SectionFlagsUpdate SFU;
186 SFU.Name = Section2Flags.first;
187
188 // Flags split: "f1" "f2" ...
189 SmallVector<StringRef, 6> SectionFlags;
190 Section2Flags.second.split(SectionFlags, ',');
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000191 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000192 if (!ParsedFlagSet)
193 return ParsedFlagSet.takeError();
194 SFU.NewFlags = *ParsedFlagSet;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000195
196 return SFU;
197}
198
Seiya Nutaecb60b72019-07-05 05:28:38 +0000199struct TargetInfo {
200 FileFormat Format;
201 MachineInfo Machine;
202};
203
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000204// FIXME: consolidate with the bfd parsing used by lld.
Seiya Nutaecb60b72019-07-05 05:28:38 +0000205static const StringMap<MachineInfo> TargetMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000206 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000207 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000208 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000209 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000210 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
211 // Intel MCU
212 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
213 // ARM
214 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
215 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000216 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
217 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000218 // RISC-V
219 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
220 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
221 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000222 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
223 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
224 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
225 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000226 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000227 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
228 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000229 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000230 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
231 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000232 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
233 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Seiya Nuta13de1742019-06-17 02:03:45 +0000234 // SPARC
235 {"elf32-sparc", {ELF::EM_SPARC, false, false}},
236 {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000237};
238
Seiya Nutaecb60b72019-07-05 05:28:38 +0000239static Expected<TargetInfo>
240getOutputTargetInfoByTargetName(StringRef TargetName) {
241 StringRef OriginalTargetName = TargetName;
242 bool IsFreeBSD = TargetName.consume_back("-freebsd");
243 auto Iter = TargetMap.find(TargetName);
244 if (Iter == std::end(TargetMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000245 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000246 "invalid output format: '%s'",
Seiya Nutaecb60b72019-07-05 05:28:38 +0000247 OriginalTargetName.str().c_str());
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000248 MachineInfo MI = Iter->getValue();
249 if (IsFreeBSD)
250 MI.OSABI = ELF::ELFOSABI_FREEBSD;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000251
252 FileFormat Format;
253 if (TargetName.startswith("elf"))
254 Format = FileFormat::ELF;
255 else
256 // This should never happen because `TargetName` is valid (it certainly
257 // exists in the TargetMap).
258 llvm_unreachable("unknown target prefix");
259
260 return {TargetInfo{Format, MI}};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000261}
262
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000263static Error
264addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
265 StringRef Filename, MatchStyle MS,
266 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000267 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000268 SmallVector<StringRef, 16> Lines;
269 auto BufOrErr = MemoryBuffer::getFile(Filename);
270 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000271 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000272
273 BufOrErr.get()->getBuffer().split(Lines, '\n');
274 for (StringRef Line : Lines) {
275 // Ignore everything after '#', trim whitespace, and only add the symbol if
276 // it's not empty.
277 auto TrimmedLine = Line.split('#').first.trim();
278 if (!TrimmedLine.empty())
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000279 if (Error E = Symbols.addMatcher(NameOrPattern::create(
280 Saver.save(TrimmedLine), MS, ErrorCallback)))
281 return E;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000282 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000283
284 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000285}
286
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000287Expected<NameOrPattern>
288NameOrPattern::create(StringRef Pattern, MatchStyle MS,
289 llvm::function_ref<Error(Error)> ErrorCallback) {
290 switch (MS) {
291 case MatchStyle::Literal:
292 return NameOrPattern(Pattern);
293 case MatchStyle::Wildcard: {
294 SmallVector<char, 32> Data;
295 bool IsPositiveMatch = true;
296 if (Pattern[0] == '!') {
297 IsPositiveMatch = false;
298 Pattern = Pattern.drop_front();
299 }
300 Expected<GlobPattern> GlobOrErr = GlobPattern::create(Pattern);
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000301
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000302 // If we couldn't create it as a glob, report the error, but try again with
303 // a literal if the error reporting is non-fatal.
304 if (!GlobOrErr) {
305 if (Error E = ErrorCallback(GlobOrErr.takeError()))
306 return std::move(E);
307 return create(Pattern, MatchStyle::Literal, ErrorCallback);
308 }
309
310 return NameOrPattern(std::make_shared<GlobPattern>(*GlobOrErr),
311 IsPositiveMatch);
312 }
313 case MatchStyle::Regex: {
314 SmallVector<char, 32> Data;
315 return NameOrPattern(std::make_shared<Regex>(
316 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data)));
317 }
318 }
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000319}
320
Eugene Leviant340cb872019-02-08 10:33:16 +0000321static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
322 BumpPtrAllocator &Alloc,
323 StringRef Filename) {
324 StringSaver Saver(Alloc);
325 SmallVector<StringRef, 16> Lines;
326 auto BufOrErr = MemoryBuffer::getFile(Filename);
327 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000328 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000329
330 BufOrErr.get()->getBuffer().split(Lines, '\n');
331 size_t NumLines = Lines.size();
332 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
333 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
334 if (TrimmedLine.empty())
335 continue;
336
337 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
338 StringRef NewName = Pair.second.trim();
339 if (NewName.empty())
340 return createStringError(errc::invalid_argument,
341 "%s:%zu: missing new symbol name",
342 Filename.str().c_str(), LineNo + 1);
343 SymbolsToRename.insert({Pair.first, NewName});
344 }
345 return Error::success();
346}
Eugene Leviant53350d02019-02-26 09:24:22 +0000347
348template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
349 T Result;
350 if (Val.getAsInteger(0, Result))
351 return errc::invalid_argument;
352 return Result;
353}
354
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000355static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
356 StringRef ToolName) {
357 OptTable.PrintHelp(OS, (ToolName + " input [output]").str().c_str(),
358 (ToolName + " tool").str().c_str());
359 // TODO: Replace this with libOption call once it adds extrahelp support.
360 // The CommandLine library has a cl::extrahelp class to support this,
361 // but libOption does not have that yet.
362 OS << "\nPass @FILE as argument to read options from FILE.\n";
363}
364
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000365// ParseObjcopyOptions returns the config and sets the input arguments. If a
366// help flag is set then ParseObjcopyOptions will print the help messege and
367// exit.
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000368Expected<DriverConfig>
369parseObjcopyOptions(ArrayRef<const char *> ArgsArr,
370 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000371 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000372 ObjcopyOptTable T;
373 unsigned MissingArgumentIndex, MissingArgumentCount;
374 llvm::opt::InputArgList InputArgs =
375 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
376
377 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000378 printHelp(T, errs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000379 exit(1);
380 }
381
382 if (InputArgs.hasArg(OBJCOPY_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000383 printHelp(T, outs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000384 exit(0);
385 }
386
387 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000388 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000389 cl::PrintVersionMessage();
390 exit(0);
391 }
392
393 SmallVector<const char *, 2> Positional;
394
395 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000396 return createStringError(errc::invalid_argument, "unknown argument '%s'",
397 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000398
399 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
400 Positional.push_back(Arg->getValue());
401
402 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000403 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000404
405 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000406 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000407 "too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000408
409 CopyConfig Config;
410 Config.InputFilename = Positional[0];
411 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000412 if (InputArgs.hasArg(OBJCOPY_target) &&
413 (InputArgs.hasArg(OBJCOPY_input_target) ||
414 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000415 return createStringError(
416 errc::invalid_argument,
417 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000418
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000419 if (InputArgs.hasArg(OBJCOPY_regex) && InputArgs.hasArg(OBJCOPY_wildcard))
420 return createStringError(errc::invalid_argument,
421 "--regex and --wildcard are incompatible");
422
423 MatchStyle SectionMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
424 ? MatchStyle::Regex
425 : MatchStyle::Wildcard;
426 MatchStyle SymbolMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
427 ? MatchStyle::Regex
428 : InputArgs.hasArg(OBJCOPY_wildcard)
429 ? MatchStyle::Wildcard
430 : MatchStyle::Literal;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000431 StringRef InputFormat, OutputFormat;
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000432 if (InputArgs.hasArg(OBJCOPY_target)) {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000433 InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
434 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000435 } else {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000436 InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
437 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000438 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000439
440 // FIXME: Currently, we ignore the target for non-binary/ihex formats
441 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
442 // format by llvm::object::createBinary regardless of the option value.
443 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
444 .Case("binary", FileFormat::Binary)
445 .Case("ihex", FileFormat::IHex)
446 .Default(FileFormat::Unspecified);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000447
Michael Liaod19fb462019-09-24 12:43:44 +0000448 if (InputArgs.hasArg(OBJCOPY_new_symbol_visibility))
Seiya Nutac83eefc2019-09-24 09:38:23 +0000449 Config.NewSymbolVisibility =
450 InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility);
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000451
Seiya Nutaecb60b72019-07-05 05:28:38 +0000452 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
453 .Case("binary", FileFormat::Binary)
454 .Case("ihex", FileFormat::IHex)
455 .Default(FileFormat::Unspecified);
Fangrui Songba530302019-09-14 01:36:16 +0000456 if (Config.OutputFormat == FileFormat::Unspecified) {
457 if (OutputFormat.empty()) {
458 Config.OutputFormat = Config.InputFormat;
459 } else {
460 Expected<TargetInfo> Target =
461 getOutputTargetInfoByTargetName(OutputFormat);
462 if (!Target)
463 return Target.takeError();
464 Config.OutputFormat = Target->Format;
465 Config.OutputArch = Target->Machine;
466 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000467 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000468
469 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
470 OBJCOPY_compress_debug_sections_eq)) {
471 Config.CompressionType = DebugCompressionType::Z;
472
473 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
474 Config.CompressionType =
475 StringSwitch<DebugCompressionType>(
476 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
477 .Case("zlib-gnu", DebugCompressionType::GNU)
478 .Case("zlib", DebugCompressionType::Z)
479 .Default(DebugCompressionType::None);
480 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000481 return createStringError(
482 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000483 "invalid or unsupported --compress-debug-sections format: %s",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000484 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
485 .str()
486 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000487 }
George Rimar1e930802019-03-05 11:32:14 +0000488 if (!zlib::isAvailable())
489 return createStringError(
490 errc::invalid_argument,
491 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000492 }
493
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000494 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000495 // The gnu_debuglink's target is expected to not change or else its CRC would
496 // become invalidated and get rejected. We can avoid recalculating the
497 // checksum for every target file inside an archive by precomputing the CRC
498 // here. This prevents a significant amount of I/O.
499 if (!Config.AddGnuDebugLink.empty()) {
500 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
501 if (!DebugOrErr)
502 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
503 auto Debug = std::move(*DebugOrErr);
Hans Wennborg1e1e3ba2019-10-09 09:06:30 +0000504 Config.GnuDebugLinkCRC32 =
505 llvm::crc32(arrayRefFromStringRef(Debug->getBuffer()));
James Henderson9df38832019-05-14 10:59:04 +0000506 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000507 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
508 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
509 Config.BuildIdLinkInput =
510 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
511 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
512 Config.BuildIdLinkOutput =
513 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
514 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000515 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000516 Config.AllocSectionsPrefix =
517 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000518 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
519 Config.ExtractPartition = Arg->getValue();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000520
521 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
522 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000523 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000524 "bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000525 auto Old2New = StringRef(Arg->getValue()).split('=');
526 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000527 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000528 "multiple redefinition of symbol '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000529 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000530 }
531
Eugene Leviant340cb872019-02-08 10:33:16 +0000532 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
533 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
534 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000535 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000536
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000537 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000538 Expected<SectionRename> SR =
539 parseRenameSectionValue(StringRef(Arg->getValue()));
540 if (!SR)
541 return SR.takeError();
542 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
543 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000544 "multiple renames of section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000545 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000546 }
Fangrui Song671fb342019-10-02 12:41:25 +0000547 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_alignment)) {
548 Expected<std::pair<StringRef, uint64_t>> NameAndAlign =
549 parseSetSectionAlignment(Arg->getValue());
550 if (!NameAndAlign)
551 return NameAndAlign.takeError();
552 Config.SetSectionAlignment[NameAndAlign->first] = NameAndAlign->second;
553 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000554 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000555 Expected<SectionFlagsUpdate> SFU =
556 parseSetSectionFlagValue(Arg->getValue());
557 if (!SFU)
558 return SFU.takeError();
559 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
560 return createStringError(
561 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000562 "--set-section-flags set multiple times for section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000563 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000564 }
565 // Prohibit combinations of --set-section-flags when the section name is used
566 // by --rename-section, either as a source or a destination.
567 for (const auto &E : Config.SectionsToRename) {
568 const SectionRename &SR = E.second;
569 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000570 return createStringError(
571 errc::invalid_argument,
572 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
573 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
574 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000575 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000576 return createStringError(
577 errc::invalid_argument,
578 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
579 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
580 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000581 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000582
583 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000584 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
585 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
586 return std::move(E);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000587 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000588 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
589 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
590 return std::move(E);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000591 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000592 if (Error E = Config.OnlySection.addMatcher(NameOrPattern::create(
593 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
594 return std::move(E);
Sergey Dmitriev899bdaa2019-07-29 16:22:40 +0000595 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
596 StringRef ArgValue(Arg->getValue());
597 if (!ArgValue.contains('='))
598 return createStringError(errc::invalid_argument,
599 "bad format for --add-section: missing '='");
600 if (ArgValue.split("=").second.empty())
601 return createStringError(
602 errc::invalid_argument,
603 "bad format for --add-section: missing file name");
604 Config.AddSection.push_back(ArgValue);
605 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000606 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
607 Config.DumpSection.push_back(Arg->getValue());
608 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
609 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
610 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
611 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
612 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
613 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
614 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
615 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000616 Config.ExtractMainPartition =
617 InputArgs.hasArg(OBJCOPY_extract_main_partition);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000618 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
619 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000620 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
621 Config.DiscardMode =
622 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
623 ? DiscardType::All
624 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000625 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
626 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
627 Config.DecompressDebugSections =
628 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000629 if (Config.DiscardMode == DiscardType::All)
630 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000631 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000632 if (Error E = Config.SymbolsToLocalize.addMatcher(NameOrPattern::create(
633 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
634 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000635 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000636 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000637 Arg->getValue(), SymbolMatchStyle,
638 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000639 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000640 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000641 if (Error E = Config.SymbolsToKeepGlobal.addMatcher(NameOrPattern::create(
642 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
643 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000644 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000645 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000646 Arg->getValue(), SymbolMatchStyle,
647 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000648 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000649 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000650 if (Error E = Config.SymbolsToGlobalize.addMatcher(NameOrPattern::create(
651 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
652 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000653 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000654 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000655 Arg->getValue(), SymbolMatchStyle,
656 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000657 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000658 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000659 if (Error E = Config.SymbolsToWeaken.addMatcher(NameOrPattern::create(
660 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
661 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000662 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000663 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000664 Arg->getValue(), SymbolMatchStyle,
665 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000666 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000667 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000668 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
669 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
670 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000671 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000672 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000673 Arg->getValue(), SymbolMatchStyle,
674 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000675 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000676 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000677 if (Error E =
678 Config.UnneededSymbolsToRemove.addMatcher(NameOrPattern::create(
679 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
680 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000681 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000682 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000683 Arg->getValue(), SymbolMatchStyle,
684 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000685 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000686 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000687 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
688 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
689 return std::move(E);
Yi Kongf2baddb2019-04-01 18:12:43 +0000690 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000691 if (Error E =
692 addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc, Arg->getValue(),
693 SymbolMatchStyle, ErrorCallback))
Yi Kongf2baddb2019-04-01 18:12:43 +0000694 return std::move(E);
Seiya Nutac83eefc2019-09-24 09:38:23 +0000695 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol))
696 Config.SymbolsToAdd.push_back(Arg->getValue());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000697
James Henderson66a9d0f2019-04-18 09:13:30 +0000698 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
699
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000700 Config.DeterministicArchives = InputArgs.hasFlag(
701 OBJCOPY_enable_deterministic_archives,
702 OBJCOPY_disable_deterministic_archives, /*default=*/true);
703
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000704 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
705
Alex Brachet899a3072019-06-15 05:32:23 +0000706 if (Config.PreserveDates &&
707 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
708 return createStringError(errc::invalid_argument,
709 "--preserve-dates requires a file");
710
Eugene Leviant53350d02019-02-26 09:24:22 +0000711 for (auto Arg : InputArgs)
712 if (Arg->getOption().matches(OBJCOPY_set_start)) {
713 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
714 if (!EAddr)
715 return createStringError(
716 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
717
718 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
719 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
720 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
721 if (!EIncr)
722 return createStringError(EIncr.getError(),
723 "bad entry point increment: '%s'",
724 Arg->getValue());
725 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
726 : [](uint64_t A) { return A; };
727 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
728 return Expr(EAddr) + *EIncr;
729 };
730 }
731
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000732 if (Config.DecompressDebugSections &&
733 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000734 return createStringError(
735 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000736 "cannot specify both --compress-debug-sections and "
737 "--decompress-debug-sections");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000738 }
739
740 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000741 return createStringError(
742 errc::invalid_argument,
743 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000744
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000745 if (Config.ExtractPartition && Config.ExtractMainPartition)
746 return createStringError(errc::invalid_argument,
747 "cannot specify --extract-partition together with "
748 "--extract-main-partition");
749
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000750 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000751 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000752}
753
754// ParseStripOptions returns the config and sets the input arguments. If a
755// help flag is set then ParseStripOptions will print the help messege and
756// exit.
Alex Brachet77477002019-06-18 00:39:10 +0000757Expected<DriverConfig>
758parseStripOptions(ArrayRef<const char *> ArgsArr,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000759 llvm::function_ref<Error(Error)> ErrorCallback) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000760 StripOptTable T;
761 unsigned MissingArgumentIndex, MissingArgumentCount;
762 llvm::opt::InputArgList InputArgs =
763 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
764
765 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000766 printHelp(T, errs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000767 exit(1);
768 }
769
770 if (InputArgs.hasArg(STRIP_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000771 printHelp(T, outs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000772 exit(0);
773 }
774
775 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000776 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000777 cl::PrintVersionMessage();
778 exit(0);
779 }
780
Alex Brachet899a3072019-06-15 05:32:23 +0000781 SmallVector<StringRef, 2> Positional;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000782 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000783 return createStringError(errc::invalid_argument, "unknown argument '%s'",
784 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000785 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
786 Positional.push_back(Arg->getValue());
787
788 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000789 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000790
791 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000792 return createStringError(
793 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000794 "multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000795
796 CopyConfig Config;
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000797
798 if (InputArgs.hasArg(STRIP_regex) && InputArgs.hasArg(STRIP_wildcard))
799 return createStringError(errc::invalid_argument,
800 "--regex and --wildcard are incompatible");
801 MatchStyle SectionMatchStyle =
802 InputArgs.hasArg(STRIP_regex) ? MatchStyle::Regex : MatchStyle::Wildcard;
803 MatchStyle SymbolMatchStyle = InputArgs.hasArg(STRIP_regex)
804 ? MatchStyle::Regex
805 : InputArgs.hasArg(STRIP_wildcard)
806 ? MatchStyle::Wildcard
807 : MatchStyle::Literal;
James Henderson66a9d0f2019-04-18 09:13:30 +0000808 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000809 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
810
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000811 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
812 Config.DiscardMode =
813 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
814 ? DiscardType::All
815 : DiscardType::Locals;
Wolfgang Piebab751a72019-08-08 00:35:16 +0000816 Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000817 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000818 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
819 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000820 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000821 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000822 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000823
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000824 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000825 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
826 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
827 return std::move(E);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000828
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000829 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000830 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
831 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
832 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000833
Eugene Leviant2267c582019-01-31 12:16:20 +0000834 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000835 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
836 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
837 return std::move(E);
Eugene Leviant2267c582019-01-31 12:16:20 +0000838
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000839 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000840 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
841 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
842 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000843
James Hendersone4a89a12019-05-02 11:53:02 +0000844 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
845 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
846 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000847 Config.StripAll = true;
848
Sid Manning5ad18a72019-05-03 14:14:01 +0000849 if (Config.DiscardMode == DiscardType::All)
850 Config.StripDebug = true;
851
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000852 Config.DeterministicArchives =
853 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
854 STRIP_disable_deterministic_archives, /*default=*/true);
855
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000856 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000857 Config.InputFormat = FileFormat::Unspecified;
858 Config.OutputFormat = FileFormat::Unspecified;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000859
860 DriverConfig DC;
861 if (Positional.size() == 1) {
862 Config.InputFilename = Positional[0];
863 Config.OutputFilename =
864 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
865 DC.CopyConfigs.push_back(std::move(Config));
866 } else {
Alex Brachet77477002019-06-18 00:39:10 +0000867 StringMap<unsigned> InputFiles;
Alex Brachet899a3072019-06-15 05:32:23 +0000868 for (StringRef Filename : Positional) {
Alex Brachet77477002019-06-18 00:39:10 +0000869 if (InputFiles[Filename]++ == 1) {
870 if (Filename == "-")
871 return createStringError(
872 errc::invalid_argument,
873 "cannot specify '-' as an input file more than once");
874 if (Error E = ErrorCallback(createStringError(
875 errc::invalid_argument, "'%s' was already specified",
876 Filename.str().c_str())))
877 return std::move(E);
878 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000879 Config.InputFilename = Filename;
880 Config.OutputFilename = Filename;
881 DC.CopyConfigs.push_back(Config);
882 }
883 }
884
Alex Brachet899a3072019-06-15 05:32:23 +0000885 if (Config.PreserveDates && (is_contained(Positional, "-") ||
886 InputArgs.getLastArgValue(STRIP_output) == "-"))
887 return createStringError(errc::invalid_argument,
888 "--preserve-dates requires a file");
889
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000890 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000891}
892
893} // namespace objcopy
894} // namespace llvm