blob: 14253218840424f033d9232c433869cccf2f7db2 [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"
17#include "llvm/Support/CommandLine.h"
18#include "llvm/Support/Compression.h"
Eugene Leviant340cb872019-02-08 10:33:16 +000019#include "llvm/Support/Errc.h"
James Henderson9df38832019-05-14 10:59:04 +000020#include "llvm/Support/JamCRC.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
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000158static Expected<SectionFlagsUpdate>
159parseSetSectionFlagValue(StringRef FlagValue) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000160 if (!StringRef(FlagValue).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000161 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000162 "bad format for --set-section-flags: missing '='");
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000163
164 // Initial split: ".foo" = "f1,f2,..."
165 auto Section2Flags = StringRef(FlagValue).split('=');
166 SectionFlagsUpdate SFU;
167 SFU.Name = Section2Flags.first;
168
169 // Flags split: "f1" "f2" ...
170 SmallVector<StringRef, 6> SectionFlags;
171 Section2Flags.second.split(SectionFlags, ',');
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000172 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000173 if (!ParsedFlagSet)
174 return ParsedFlagSet.takeError();
175 SFU.NewFlags = *ParsedFlagSet;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000176
177 return SFU;
178}
179
Seiya Nutaecb60b72019-07-05 05:28:38 +0000180struct TargetInfo {
181 FileFormat Format;
182 MachineInfo Machine;
183};
184
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000185// FIXME: consolidate with the bfd parsing used by lld.
Seiya Nutaecb60b72019-07-05 05:28:38 +0000186static const StringMap<MachineInfo> TargetMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000187 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000188 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000189 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000190 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000191 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
192 // Intel MCU
193 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
194 // ARM
195 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
196 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000197 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
198 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000199 // RISC-V
200 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
201 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
202 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000203 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
204 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
205 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
206 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000207 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000208 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
209 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000210 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000211 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
212 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000213 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
214 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Seiya Nuta13de1742019-06-17 02:03:45 +0000215 // SPARC
216 {"elf32-sparc", {ELF::EM_SPARC, false, false}},
217 {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000218};
219
Seiya Nutaecb60b72019-07-05 05:28:38 +0000220static Expected<TargetInfo>
221getOutputTargetInfoByTargetName(StringRef TargetName) {
222 StringRef OriginalTargetName = TargetName;
223 bool IsFreeBSD = TargetName.consume_back("-freebsd");
224 auto Iter = TargetMap.find(TargetName);
225 if (Iter == std::end(TargetMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000226 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000227 "invalid output format: '%s'",
Seiya Nutaecb60b72019-07-05 05:28:38 +0000228 OriginalTargetName.str().c_str());
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000229 MachineInfo MI = Iter->getValue();
230 if (IsFreeBSD)
231 MI.OSABI = ELF::ELFOSABI_FREEBSD;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000232
233 FileFormat Format;
234 if (TargetName.startswith("elf"))
235 Format = FileFormat::ELF;
236 else
237 // This should never happen because `TargetName` is valid (it certainly
238 // exists in the TargetMap).
239 llvm_unreachable("unknown target prefix");
240
241 return {TargetInfo{Format, MI}};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000242}
243
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000244static Error addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
245 StringRef Filename, bool UseRegex) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000246 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000247 SmallVector<StringRef, 16> Lines;
248 auto BufOrErr = MemoryBuffer::getFile(Filename);
249 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000250 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000251
252 BufOrErr.get()->getBuffer().split(Lines, '\n');
253 for (StringRef Line : Lines) {
254 // Ignore everything after '#', trim whitespace, and only add the symbol if
255 // it's not empty.
256 auto TrimmedLine = Line.split('#').first.trim();
257 if (!TrimmedLine.empty())
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000258 Symbols.addMatcher({Saver.save(TrimmedLine), UseRegex});
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000259 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000260
261 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000262}
263
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000264NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
265 if (!IsRegex) {
266 Name = Pattern;
267 return;
268 }
269
270 SmallVector<char, 32> Data;
271 R = std::make_shared<Regex>(
272 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
273}
274
Eugene Leviant340cb872019-02-08 10:33:16 +0000275static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
276 BumpPtrAllocator &Alloc,
277 StringRef Filename) {
278 StringSaver Saver(Alloc);
279 SmallVector<StringRef, 16> Lines;
280 auto BufOrErr = MemoryBuffer::getFile(Filename);
281 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000282 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000283
284 BufOrErr.get()->getBuffer().split(Lines, '\n');
285 size_t NumLines = Lines.size();
286 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
287 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
288 if (TrimmedLine.empty())
289 continue;
290
291 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
292 StringRef NewName = Pair.second.trim();
293 if (NewName.empty())
294 return createStringError(errc::invalid_argument,
295 "%s:%zu: missing new symbol name",
296 Filename.str().c_str(), LineNo + 1);
297 SymbolsToRename.insert({Pair.first, NewName});
298 }
299 return Error::success();
300}
Eugene Leviant53350d02019-02-26 09:24:22 +0000301
302template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
303 T Result;
304 if (Val.getAsInteger(0, Result))
305 return errc::invalid_argument;
306 return Result;
307}
308
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000309static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
310 StringRef ToolName) {
311 OptTable.PrintHelp(OS, (ToolName + " input [output]").str().c_str(),
312 (ToolName + " tool").str().c_str());
313 // TODO: Replace this with libOption call once it adds extrahelp support.
314 // The CommandLine library has a cl::extrahelp class to support this,
315 // but libOption does not have that yet.
316 OS << "\nPass @FILE as argument to read options from FILE.\n";
317}
318
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000319// ParseObjcopyOptions returns the config and sets the input arguments. If a
320// help flag is set then ParseObjcopyOptions will print the help messege and
321// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000322Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000323 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000324 ObjcopyOptTable T;
325 unsigned MissingArgumentIndex, MissingArgumentCount;
326 llvm::opt::InputArgList InputArgs =
327 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
328
329 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000330 printHelp(T, errs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000331 exit(1);
332 }
333
334 if (InputArgs.hasArg(OBJCOPY_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000335 printHelp(T, outs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000336 exit(0);
337 }
338
339 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000340 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000341 cl::PrintVersionMessage();
342 exit(0);
343 }
344
345 SmallVector<const char *, 2> Positional;
346
347 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000348 return createStringError(errc::invalid_argument, "unknown argument '%s'",
349 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000350
351 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
352 Positional.push_back(Arg->getValue());
353
354 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000355 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000356
357 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000358 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000359 "too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000360
361 CopyConfig Config;
362 Config.InputFilename = Positional[0];
363 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000364 if (InputArgs.hasArg(OBJCOPY_target) &&
365 (InputArgs.hasArg(OBJCOPY_input_target) ||
366 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000367 return createStringError(
368 errc::invalid_argument,
369 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000370
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000371 bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000372 StringRef InputFormat, OutputFormat;
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000373 if (InputArgs.hasArg(OBJCOPY_target)) {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000374 InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
375 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000376 } else {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000377 InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
378 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000379 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000380
381 // FIXME: Currently, we ignore the target for non-binary/ihex formats
382 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
383 // format by llvm::object::createBinary regardless of the option value.
384 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
385 .Case("binary", FileFormat::Binary)
386 .Case("ihex", FileFormat::IHex)
387 .Default(FileFormat::Unspecified);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000388
Seiya Nutac83eefc2019-09-24 09:38:23 +0000389 if (opt::Arg *A = InputArgs.getLastArg(OBJCOPY_new_symbol_visibility))
390 Config.NewSymbolVisibility =
391 InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility);
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000392
Seiya Nutaecb60b72019-07-05 05:28:38 +0000393 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
394 .Case("binary", FileFormat::Binary)
395 .Case("ihex", FileFormat::IHex)
396 .Default(FileFormat::Unspecified);
Fangrui Songba530302019-09-14 01:36:16 +0000397 if (Config.OutputFormat == FileFormat::Unspecified) {
398 if (OutputFormat.empty()) {
399 Config.OutputFormat = Config.InputFormat;
400 } else {
401 Expected<TargetInfo> Target =
402 getOutputTargetInfoByTargetName(OutputFormat);
403 if (!Target)
404 return Target.takeError();
405 Config.OutputFormat = Target->Format;
406 Config.OutputArch = Target->Machine;
407 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000408 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000409
410 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
411 OBJCOPY_compress_debug_sections_eq)) {
412 Config.CompressionType = DebugCompressionType::Z;
413
414 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
415 Config.CompressionType =
416 StringSwitch<DebugCompressionType>(
417 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
418 .Case("zlib-gnu", DebugCompressionType::GNU)
419 .Case("zlib", DebugCompressionType::Z)
420 .Default(DebugCompressionType::None);
421 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000422 return createStringError(
423 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000424 "invalid or unsupported --compress-debug-sections format: %s",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000425 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
426 .str()
427 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000428 }
George Rimar1e930802019-03-05 11:32:14 +0000429 if (!zlib::isAvailable())
430 return createStringError(
431 errc::invalid_argument,
432 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000433 }
434
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000435 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000436 // The gnu_debuglink's target is expected to not change or else its CRC would
437 // become invalidated and get rejected. We can avoid recalculating the
438 // checksum for every target file inside an archive by precomputing the CRC
439 // here. This prevents a significant amount of I/O.
440 if (!Config.AddGnuDebugLink.empty()) {
441 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
442 if (!DebugOrErr)
443 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
444 auto Debug = std::move(*DebugOrErr);
445 JamCRC CRC;
446 CRC.update(
447 ArrayRef<char>(Debug->getBuffer().data(), Debug->getBuffer().size()));
448 // The CRC32 value needs to be complemented because the JamCRC doesn't
449 // finalize the CRC32 value.
450 Config.GnuDebugLinkCRC32 = ~CRC.getCRC();
451 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000452 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
453 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
454 Config.BuildIdLinkInput =
455 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
456 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
457 Config.BuildIdLinkOutput =
458 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
459 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000460 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000461 Config.AllocSectionsPrefix =
462 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000463 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
464 Config.ExtractPartition = Arg->getValue();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000465
466 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
467 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000468 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000469 "bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000470 auto Old2New = StringRef(Arg->getValue()).split('=');
471 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000472 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000473 "multiple redefinition of symbol '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000474 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000475 }
476
Eugene Leviant340cb872019-02-08 10:33:16 +0000477 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
478 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
479 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000480 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000481
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000482 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000483 Expected<SectionRename> SR =
484 parseRenameSectionValue(StringRef(Arg->getValue()));
485 if (!SR)
486 return SR.takeError();
487 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
488 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000489 "multiple renames of section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000490 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000491 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000492 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000493 Expected<SectionFlagsUpdate> SFU =
494 parseSetSectionFlagValue(Arg->getValue());
495 if (!SFU)
496 return SFU.takeError();
497 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
498 return createStringError(
499 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000500 "--set-section-flags set multiple times for section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000501 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000502 }
503 // Prohibit combinations of --set-section-flags when the section name is used
504 // by --rename-section, either as a source or a destination.
505 for (const auto &E : Config.SectionsToRename) {
506 const SectionRename &SR = E.second;
507 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000508 return createStringError(
509 errc::invalid_argument,
510 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
511 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
512 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000513 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000514 return createStringError(
515 errc::invalid_argument,
516 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
517 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
518 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000519 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000520
521 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000522 Config.ToRemove.addMatcher({Arg->getValue(), UseRegex});
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000523 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000524 Config.KeepSection.addMatcher({Arg->getValue(), UseRegex});
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000525 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000526 Config.OnlySection.addMatcher({Arg->getValue(), UseRegex});
Sergey Dmitriev899bdaa2019-07-29 16:22:40 +0000527 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
528 StringRef ArgValue(Arg->getValue());
529 if (!ArgValue.contains('='))
530 return createStringError(errc::invalid_argument,
531 "bad format for --add-section: missing '='");
532 if (ArgValue.split("=").second.empty())
533 return createStringError(
534 errc::invalid_argument,
535 "bad format for --add-section: missing file name");
536 Config.AddSection.push_back(ArgValue);
537 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000538 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
539 Config.DumpSection.push_back(Arg->getValue());
540 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
541 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
542 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
543 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
544 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
545 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
546 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
547 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000548 Config.ExtractMainPartition =
549 InputArgs.hasArg(OBJCOPY_extract_main_partition);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000550 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
551 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000552 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
553 Config.DiscardMode =
554 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
555 ? DiscardType::All
556 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000557 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
558 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
559 Config.DecompressDebugSections =
560 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000561 if (Config.DiscardMode == DiscardType::All)
562 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000563 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000564 Config.SymbolsToLocalize.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviante08fe352019-02-08 14:37:54 +0000565 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000566 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
567 Arg->getValue(), UseRegex))
568 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000569 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000570 Config.SymbolsToKeepGlobal.addMatcher({Arg->getValue(), UseRegex});
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000571 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000572 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
573 Arg->getValue(), UseRegex))
574 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000575 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000576 Config.SymbolsToGlobalize.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviante08fe352019-02-08 14:37:54 +0000577 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000578 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
579 Arg->getValue(), UseRegex))
580 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000581 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000582 Config.SymbolsToWeaken.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviante08fe352019-02-08 14:37:54 +0000583 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000584 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
585 Arg->getValue(), UseRegex))
586 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000587 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000588 Config.SymbolsToRemove.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviante08fe352019-02-08 14:37:54 +0000589 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000590 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
591 Arg->getValue(), UseRegex))
592 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000593 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000594 Config.UnneededSymbolsToRemove.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviant2db10622019-02-13 07:34:54 +0000595 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000596 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
597 Arg->getValue(), UseRegex))
598 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000599 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000600 Config.SymbolsToKeep.addMatcher({Arg->getValue(), UseRegex});
Yi Kongf2baddb2019-04-01 18:12:43 +0000601 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
602 if (Error E = addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc,
603 Arg->getValue(), UseRegex))
604 return std::move(E);
Seiya Nutac83eefc2019-09-24 09:38:23 +0000605 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol))
606 Config.SymbolsToAdd.push_back(Arg->getValue());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000607
James Henderson66a9d0f2019-04-18 09:13:30 +0000608 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
609
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000610 Config.DeterministicArchives = InputArgs.hasFlag(
611 OBJCOPY_enable_deterministic_archives,
612 OBJCOPY_disable_deterministic_archives, /*default=*/true);
613
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000614 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
615
Alex Brachet899a3072019-06-15 05:32:23 +0000616 if (Config.PreserveDates &&
617 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
618 return createStringError(errc::invalid_argument,
619 "--preserve-dates requires a file");
620
Eugene Leviant53350d02019-02-26 09:24:22 +0000621 for (auto Arg : InputArgs)
622 if (Arg->getOption().matches(OBJCOPY_set_start)) {
623 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
624 if (!EAddr)
625 return createStringError(
626 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
627
628 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
629 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
630 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
631 if (!EIncr)
632 return createStringError(EIncr.getError(),
633 "bad entry point increment: '%s'",
634 Arg->getValue());
635 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
636 : [](uint64_t A) { return A; };
637 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
638 return Expr(EAddr) + *EIncr;
639 };
640 }
641
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000642 if (Config.DecompressDebugSections &&
643 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000644 return createStringError(
645 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000646 "cannot specify both --compress-debug-sections and "
647 "--decompress-debug-sections");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000648 }
649
650 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000651 return createStringError(
652 errc::invalid_argument,
653 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000654
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000655 if (Config.ExtractPartition && Config.ExtractMainPartition)
656 return createStringError(errc::invalid_argument,
657 "cannot specify --extract-partition together with "
658 "--extract-main-partition");
659
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000660 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000661 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000662}
663
664// ParseStripOptions returns the config and sets the input arguments. If a
665// help flag is set then ParseStripOptions will print the help messege and
666// exit.
Alex Brachet77477002019-06-18 00:39:10 +0000667Expected<DriverConfig>
668parseStripOptions(ArrayRef<const char *> ArgsArr,
669 std::function<Error(Error)> ErrorCallback) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000670 StripOptTable T;
671 unsigned MissingArgumentIndex, MissingArgumentCount;
672 llvm::opt::InputArgList InputArgs =
673 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
674
675 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000676 printHelp(T, errs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000677 exit(1);
678 }
679
680 if (InputArgs.hasArg(STRIP_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000681 printHelp(T, outs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000682 exit(0);
683 }
684
685 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000686 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000687 cl::PrintVersionMessage();
688 exit(0);
689 }
690
Alex Brachet899a3072019-06-15 05:32:23 +0000691 SmallVector<StringRef, 2> Positional;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000692 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000693 return createStringError(errc::invalid_argument, "unknown argument '%s'",
694 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000695 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
696 Positional.push_back(Arg->getValue());
697
698 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000699 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000700
701 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000702 return createStringError(
703 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000704 "multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000705
706 CopyConfig Config;
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000707 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
James Henderson66a9d0f2019-04-18 09:13:30 +0000708 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000709 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
710
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000711 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
712 Config.DiscardMode =
713 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
714 ? DiscardType::All
715 : DiscardType::Locals;
Wolfgang Piebab751a72019-08-08 00:35:16 +0000716 Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000717 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000718 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
719 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000720 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000721 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000722 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000723
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000724 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000725 Config.KeepSection.addMatcher({Arg->getValue(), UseRegexp});
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000726
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000727 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000728 Config.ToRemove.addMatcher({Arg->getValue(), UseRegexp});
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000729
Eugene Leviant2267c582019-01-31 12:16:20 +0000730 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000731 Config.SymbolsToRemove.addMatcher({Arg->getValue(), UseRegexp});
Eugene Leviant2267c582019-01-31 12:16:20 +0000732
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000733 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000734 Config.SymbolsToKeep.addMatcher({Arg->getValue(), UseRegexp});
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000735
James Hendersone4a89a12019-05-02 11:53:02 +0000736 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
737 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
738 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000739 Config.StripAll = true;
740
Sid Manning5ad18a72019-05-03 14:14:01 +0000741 if (Config.DiscardMode == DiscardType::All)
742 Config.StripDebug = true;
743
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000744 Config.DeterministicArchives =
745 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
746 STRIP_disable_deterministic_archives, /*default=*/true);
747
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000748 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000749 Config.InputFormat = FileFormat::Unspecified;
750 Config.OutputFormat = FileFormat::Unspecified;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000751
752 DriverConfig DC;
753 if (Positional.size() == 1) {
754 Config.InputFilename = Positional[0];
755 Config.OutputFilename =
756 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
757 DC.CopyConfigs.push_back(std::move(Config));
758 } else {
Alex Brachet77477002019-06-18 00:39:10 +0000759 StringMap<unsigned> InputFiles;
Alex Brachet899a3072019-06-15 05:32:23 +0000760 for (StringRef Filename : Positional) {
Alex Brachet77477002019-06-18 00:39:10 +0000761 if (InputFiles[Filename]++ == 1) {
762 if (Filename == "-")
763 return createStringError(
764 errc::invalid_argument,
765 "cannot specify '-' as an input file more than once");
766 if (Error E = ErrorCallback(createStringError(
767 errc::invalid_argument, "'%s' was already specified",
768 Filename.str().c_str())))
769 return std::move(E);
770 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000771 Config.InputFilename = Filename;
772 Config.OutputFilename = Filename;
773 DC.CopyConfigs.push_back(Config);
774 }
775 }
776
Alex Brachet899a3072019-06-15 05:32:23 +0000777 if (Config.PreserveDates && (is_contained(Positional, "-") ||
778 InputArgs.getLastArgValue(STRIP_output) == "-"))
779 return createStringError(errc::invalid_argument,
780 "--preserve-dates requires a file");
781
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000782 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000783}
784
785} // namespace objcopy
786} // namespace llvm