blob: 94c0a5bc6316b8ae4efe0c0be5395682b52b0427 [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"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000014#include "llvm/Option/Arg.h"
15#include "llvm/Option/ArgList.h"
16#include "llvm/Support/CommandLine.h"
17#include "llvm/Support/Compression.h"
Eugene Leviant340cb872019-02-08 10:33:16 +000018#include "llvm/Support/Errc.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000019#include "llvm/Support/MemoryBuffer.h"
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +000020#include "llvm/Support/StringSaver.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000021#include <memory>
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000022
23namespace llvm {
24namespace objcopy {
25
26namespace {
27enum ObjcopyID {
28 OBJCOPY_INVALID = 0, // This is not an option ID.
29#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
30 HELPTEXT, METAVAR, VALUES) \
31 OBJCOPY_##ID,
32#include "ObjcopyOpts.inc"
33#undef OPTION
34};
35
36#define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
37#include "ObjcopyOpts.inc"
38#undef PREFIX
39
40static const opt::OptTable::Info ObjcopyInfoTable[] = {
41#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
42 HELPTEXT, METAVAR, VALUES) \
43 {OBJCOPY_##PREFIX, \
44 NAME, \
45 HELPTEXT, \
46 METAVAR, \
47 OBJCOPY_##ID, \
48 opt::Option::KIND##Class, \
49 PARAM, \
50 FLAGS, \
51 OBJCOPY_##GROUP, \
52 OBJCOPY_##ALIAS, \
53 ALIASARGS, \
54 VALUES},
55#include "ObjcopyOpts.inc"
56#undef OPTION
57};
58
59class ObjcopyOptTable : public opt::OptTable {
60public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +000061 ObjcopyOptTable() : OptTable(ObjcopyInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000062};
63
64enum StripID {
65 STRIP_INVALID = 0, // This is not an option ID.
66#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
67 HELPTEXT, METAVAR, VALUES) \
68 STRIP_##ID,
69#include "StripOpts.inc"
70#undef OPTION
71};
72
73#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
74#include "StripOpts.inc"
75#undef PREFIX
76
77static const opt::OptTable::Info StripInfoTable[] = {
78#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
79 HELPTEXT, METAVAR, VALUES) \
80 {STRIP_##PREFIX, NAME, HELPTEXT, \
81 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
82 PARAM, FLAGS, STRIP_##GROUP, \
83 STRIP_##ALIAS, ALIASARGS, VALUES},
84#include "StripOpts.inc"
85#undef OPTION
86};
87
88class StripOptTable : public opt::OptTable {
89public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +000090 StripOptTable() : OptTable(StripInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000091};
92
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000093} // namespace
94
95static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
96 return llvm::StringSwitch<SectionFlag>(SectionName)
James Hendersond931cf32019-04-03 14:40:27 +000097 .CaseLower("alloc", SectionFlag::SecAlloc)
98 .CaseLower("load", SectionFlag::SecLoad)
99 .CaseLower("noload", SectionFlag::SecNoload)
100 .CaseLower("readonly", SectionFlag::SecReadonly)
101 .CaseLower("debug", SectionFlag::SecDebug)
102 .CaseLower("code", SectionFlag::SecCode)
103 .CaseLower("data", SectionFlag::SecData)
104 .CaseLower("rom", SectionFlag::SecRom)
105 .CaseLower("merge", SectionFlag::SecMerge)
106 .CaseLower("strings", SectionFlag::SecStrings)
107 .CaseLower("contents", SectionFlag::SecContents)
108 .CaseLower("share", SectionFlag::SecShare)
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000109 .Default(SectionFlag::SecNone);
110}
111
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000112static Expected<SectionFlag>
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000113parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000114 SectionFlag ParsedFlags = SectionFlag::SecNone;
115 for (StringRef Flag : SectionFlags) {
116 SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
117 if (ParsedFlag == SectionFlag::SecNone)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000118 return createStringError(
119 errc::invalid_argument,
120 "Unrecognized section flag '%s'. Flags supported for GNU "
121 "compatibility: alloc, load, noload, readonly, debug, code, data, "
122 "rom, share, contents, merge, strings",
123 Flag.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000124 ParsedFlags |= ParsedFlag;
125 }
126
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000127 return ParsedFlags;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000128}
129
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000130static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000131 if (!FlagValue.contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000132 return createStringError(errc::invalid_argument,
133 "Bad format for --rename-section: missing '='");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000134
135 // Initial split: ".foo" = ".bar,f1,f2,..."
136 auto Old2New = FlagValue.split('=');
137 SectionRename SR;
138 SR.OriginalName = Old2New.first;
139
140 // Flags split: ".bar" "f1" "f2" ...
141 SmallVector<StringRef, 6> NameAndFlags;
142 Old2New.second.split(NameAndFlags, ',');
143 SR.NewName = NameAndFlags[0];
144
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000145 if (NameAndFlags.size() > 1) {
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000146 Expected<SectionFlag> ParsedFlagSet =
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000147 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
148 if (!ParsedFlagSet)
149 return ParsedFlagSet.takeError();
150 SR.NewFlags = *ParsedFlagSet;
151 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000152
153 return SR;
154}
155
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000156static Expected<SectionFlagsUpdate>
157parseSetSectionFlagValue(StringRef FlagValue) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000158 if (!StringRef(FlagValue).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000159 return createStringError(errc::invalid_argument,
160 "Bad format for --set-section-flags: missing '='");
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000161
162 // Initial split: ".foo" = "f1,f2,..."
163 auto Section2Flags = StringRef(FlagValue).split('=');
164 SectionFlagsUpdate SFU;
165 SFU.Name = Section2Flags.first;
166
167 // Flags split: "f1" "f2" ...
168 SmallVector<StringRef, 6> SectionFlags;
169 Section2Flags.second.split(SectionFlags, ',');
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000170 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000171 if (!ParsedFlagSet)
172 return ParsedFlagSet.takeError();
173 SFU.NewFlags = *ParsedFlagSet;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000174
175 return SFU;
176}
177
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000178static Expected<NewSymbolInfo> parseNewSymbolInfo(StringRef FlagValue) {
Eugene Leviant51c1f642019-02-25 14:12:41 +0000179 // Parse value given with --add-symbol option and create the
180 // new symbol if possible. The value format for --add-symbol is:
181 //
182 // <name>=[<section>:]<value>[,<flags>]
183 //
184 // where:
185 // <name> - symbol name, can be empty string
186 // <section> - optional section name. If not given ABS symbol is created
187 // <value> - symbol value, can be decimal or hexadecimal number prefixed
188 // with 0x.
189 // <flags> - optional flags affecting symbol type, binding or visibility:
190 // The following are currently supported:
191 //
192 // global, local, weak, default, hidden, file, section, object,
193 // indirect-function.
194 //
195 // The following flags are ignored and provided for GNU
196 // compatibility only:
197 //
198 // warning, debug, constructor, indirect, synthetic,
199 // unique-object, before=<symbol>.
200 NewSymbolInfo SI;
201 StringRef Value;
202 std::tie(SI.SymbolName, Value) = FlagValue.split('=');
203 if (Value.empty())
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000204 return createStringError(
205 errc::invalid_argument,
206 "bad format for --add-symbol, missing '=' after '%s'",
207 SI.SymbolName.str().c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000208
209 if (Value.contains(':')) {
210 std::tie(SI.SectionName, Value) = Value.split(':');
211 if (SI.SectionName.empty() || Value.empty())
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000212 return createStringError(
213 errc::invalid_argument,
Eugene Leviant51c1f642019-02-25 14:12:41 +0000214 "bad format for --add-symbol, missing section name or symbol value");
215 }
216
217 SmallVector<StringRef, 6> Flags;
218 Value.split(Flags, ',');
219 if (Flags[0].getAsInteger(0, SI.Value))
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000220 return createStringError(errc::invalid_argument, "bad symbol value: '%s'",
221 Flags[0].str().c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000222
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000223 using Functor = std::function<void(void)>;
224 SmallVector<StringRef, 6> UnsupportedFlags;
225 for (size_t I = 1, NumFlags = Flags.size(); I < NumFlags; ++I)
Eugene Leviant51c1f642019-02-25 14:12:41 +0000226 static_cast<Functor>(
227 StringSwitch<Functor>(Flags[I])
228 .CaseLower("global", [&SI] { SI.Bind = ELF::STB_GLOBAL; })
229 .CaseLower("local", [&SI] { SI.Bind = ELF::STB_LOCAL; })
230 .CaseLower("weak", [&SI] { SI.Bind = ELF::STB_WEAK; })
231 .CaseLower("default", [&SI] { SI.Visibility = ELF::STV_DEFAULT; })
232 .CaseLower("hidden", [&SI] { SI.Visibility = ELF::STV_HIDDEN; })
233 .CaseLower("file", [&SI] { SI.Type = ELF::STT_FILE; })
234 .CaseLower("section", [&SI] { SI.Type = ELF::STT_SECTION; })
235 .CaseLower("object", [&SI] { SI.Type = ELF::STT_OBJECT; })
236 .CaseLower("function", [&SI] { SI.Type = ELF::STT_FUNC; })
237 .CaseLower("indirect-function",
238 [&SI] { SI.Type = ELF::STT_GNU_IFUNC; })
239 .CaseLower("debug", [] {})
240 .CaseLower("constructor", [] {})
241 .CaseLower("warning", [] {})
242 .CaseLower("indirect", [] {})
243 .CaseLower("synthetic", [] {})
244 .CaseLower("unique-object", [] {})
245 .StartsWithLower("before", [] {})
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000246 .Default([&] { UnsupportedFlags.push_back(Flags[I]); }))();
247 if (!UnsupportedFlags.empty())
248 return createStringError(errc::invalid_argument,
249 "unsupported flag%s for --add-symbol: '%s'",
250 UnsupportedFlags.size() > 1 ? "s" : "",
251 join(UnsupportedFlags, "', '").c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000252 return SI;
253}
254
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000255static const StringMap<MachineInfo> ArchMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000256 // Name, {EMachine, 64bit, LittleEndian}
257 {"aarch64", {ELF::EM_AARCH64, true, true}},
258 {"arm", {ELF::EM_ARM, false, true}},
259 {"i386", {ELF::EM_386, false, true}},
260 {"i386:x86-64", {ELF::EM_X86_64, true, true}},
Jordan Rupprecht2b329022019-04-18 14:22:37 +0000261 {"mips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000262 {"powerpc:common64", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000263 {"riscv:rv32", {ELF::EM_RISCV, false, true}},
264 {"riscv:rv64", {ELF::EM_RISCV, true, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000265 {"sparc", {ELF::EM_SPARC, false, true}},
266 {"x86-64", {ELF::EM_X86_64, true, true}},
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000267};
268
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000269static Expected<const MachineInfo &> getMachineInfo(StringRef Arch) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000270 auto Iter = ArchMap.find(Arch);
271 if (Iter == std::end(ArchMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000272 return createStringError(errc::invalid_argument,
273 "Invalid architecture: '%s'", Arch.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000274 return Iter->getValue();
275}
276
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000277// FIXME: consolidate with the bfd parsing used by lld.
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000278static const StringMap<MachineInfo> OutputFormatMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000279 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000280 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000281 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000282 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000283 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
284 // Intel MCU
285 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
286 // ARM
287 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
288 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000289 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
290 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000291 // RISC-V
292 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
293 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
294 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000295 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
296 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
297 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
298 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000299 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000300 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
301 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000302 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000303 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
304 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000305 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
306 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000307};
308
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000309static Expected<MachineInfo> getOutputFormatMachineInfo(StringRef Format) {
310 StringRef OriginalFormat = Format;
311 bool IsFreeBSD = Format.consume_back("-freebsd");
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000312 auto Iter = OutputFormatMap.find(Format);
313 if (Iter == std::end(OutputFormatMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000314 return createStringError(errc::invalid_argument,
315 "Invalid output format: '%s'",
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000316 OriginalFormat.str().c_str());
317 MachineInfo MI = Iter->getValue();
318 if (IsFreeBSD)
319 MI.OSABI = ELF::ELFOSABI_FREEBSD;
320 return {MI};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000321}
322
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000323static Error addSymbolsFromFile(std::vector<NameOrRegex> &Symbols,
324 BumpPtrAllocator &Alloc, StringRef Filename,
325 bool UseRegex) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000326 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000327 SmallVector<StringRef, 16> Lines;
328 auto BufOrErr = MemoryBuffer::getFile(Filename);
329 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000330 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000331
332 BufOrErr.get()->getBuffer().split(Lines, '\n');
333 for (StringRef Line : Lines) {
334 // Ignore everything after '#', trim whitespace, and only add the symbol if
335 // it's not empty.
336 auto TrimmedLine = Line.split('#').first.trim();
337 if (!TrimmedLine.empty())
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000338 Symbols.emplace_back(Saver.save(TrimmedLine), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000339 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000340
341 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000342}
343
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000344NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
345 if (!IsRegex) {
346 Name = Pattern;
347 return;
348 }
349
350 SmallVector<char, 32> Data;
351 R = std::make_shared<Regex>(
352 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
353}
354
Eugene Leviant340cb872019-02-08 10:33:16 +0000355static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
356 BumpPtrAllocator &Alloc,
357 StringRef Filename) {
358 StringSaver Saver(Alloc);
359 SmallVector<StringRef, 16> Lines;
360 auto BufOrErr = MemoryBuffer::getFile(Filename);
361 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000362 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000363
364 BufOrErr.get()->getBuffer().split(Lines, '\n');
365 size_t NumLines = Lines.size();
366 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
367 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
368 if (TrimmedLine.empty())
369 continue;
370
371 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
372 StringRef NewName = Pair.second.trim();
373 if (NewName.empty())
374 return createStringError(errc::invalid_argument,
375 "%s:%zu: missing new symbol name",
376 Filename.str().c_str(), LineNo + 1);
377 SymbolsToRename.insert({Pair.first, NewName});
378 }
379 return Error::success();
380}
Eugene Leviant53350d02019-02-26 09:24:22 +0000381
382template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
383 T Result;
384 if (Val.getAsInteger(0, Result))
385 return errc::invalid_argument;
386 return Result;
387}
388
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000389// ParseObjcopyOptions returns the config and sets the input arguments. If a
390// help flag is set then ParseObjcopyOptions will print the help messege and
391// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000392Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000393 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000394 ObjcopyOptTable T;
395 unsigned MissingArgumentIndex, MissingArgumentCount;
396 llvm::opt::InputArgList InputArgs =
397 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
398
399 if (InputArgs.size() == 0) {
400 T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
401 exit(1);
402 }
403
404 if (InputArgs.hasArg(OBJCOPY_help)) {
405 T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
406 exit(0);
407 }
408
409 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000410 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000411 cl::PrintVersionMessage();
412 exit(0);
413 }
414
415 SmallVector<const char *, 2> Positional;
416
417 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000418 return createStringError(errc::invalid_argument, "unknown argument '%s'",
419 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000420
421 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
422 Positional.push_back(Arg->getValue());
423
424 if (Positional.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000425 return createStringError(errc::invalid_argument, "No input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000426
427 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000428 return createStringError(errc::invalid_argument,
429 "Too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000430
431 CopyConfig Config;
432 Config.InputFilename = Positional[0];
433 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000434 if (InputArgs.hasArg(OBJCOPY_target) &&
435 (InputArgs.hasArg(OBJCOPY_input_target) ||
436 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000437 return createStringError(
438 errc::invalid_argument,
439 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000440
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000441 bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000442 if (InputArgs.hasArg(OBJCOPY_target)) {
443 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
444 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
445 } else {
446 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
447 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
448 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000449 if (Config.InputFormat == "binary") {
450 auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
451 if (BinaryArch.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000452 return createStringError(
453 errc::invalid_argument,
454 "Specified binary input without specifiying an architecture");
455 Expected<const MachineInfo &> MI = getMachineInfo(BinaryArch);
456 if (!MI)
457 return MI.takeError();
458 Config.BinaryArch = *MI;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000459 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000460 if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary") {
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000461 Expected<MachineInfo> MI = getOutputFormatMachineInfo(Config.OutputFormat);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000462 if (!MI)
463 return MI.takeError();
464 Config.OutputArch = *MI;
465 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000466
467 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
468 OBJCOPY_compress_debug_sections_eq)) {
469 Config.CompressionType = DebugCompressionType::Z;
470
471 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
472 Config.CompressionType =
473 StringSwitch<DebugCompressionType>(
474 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
475 .Case("zlib-gnu", DebugCompressionType::GNU)
476 .Case("zlib", DebugCompressionType::Z)
477 .Default(DebugCompressionType::None);
478 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000479 return createStringError(
480 errc::invalid_argument,
481 "Invalid or unsupported --compress-debug-sections format: %s",
482 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
483 .str()
484 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000485 }
George Rimar1e930802019-03-05 11:32:14 +0000486 if (!zlib::isAvailable())
487 return createStringError(
488 errc::invalid_argument,
489 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000490 }
491
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000492 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000493 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
494 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
495 Config.BuildIdLinkInput =
496 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
497 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
498 Config.BuildIdLinkOutput =
499 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
500 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000501 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000502 Config.AllocSectionsPrefix =
503 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000504
505 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
506 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000507 return createStringError(errc::invalid_argument,
508 "Bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000509 auto Old2New = StringRef(Arg->getValue()).split('=');
510 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000511 return createStringError(errc::invalid_argument,
512 "Multiple redefinition of symbol %s",
513 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000514 }
515
Eugene Leviant340cb872019-02-08 10:33:16 +0000516 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
517 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
518 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000519 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000520
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000521 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000522 Expected<SectionRename> SR =
523 parseRenameSectionValue(StringRef(Arg->getValue()));
524 if (!SR)
525 return SR.takeError();
526 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
527 return createStringError(errc::invalid_argument,
528 "Multiple renames of section %s",
529 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000530 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000531 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000532 Expected<SectionFlagsUpdate> SFU =
533 parseSetSectionFlagValue(Arg->getValue());
534 if (!SFU)
535 return SFU.takeError();
536 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
537 return createStringError(
538 errc::invalid_argument,
539 "--set-section-flags set multiple times for section %s",
540 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000541 }
542 // Prohibit combinations of --set-section-flags when the section name is used
543 // by --rename-section, either as a source or a destination.
544 for (const auto &E : Config.SectionsToRename) {
545 const SectionRename &SR = E.second;
546 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000547 return createStringError(
548 errc::invalid_argument,
549 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
550 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
551 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000552 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000553 return createStringError(
554 errc::invalid_argument,
555 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
556 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
557 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000558 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000559
560 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000561 Config.ToRemove.emplace_back(Arg->getValue(), UseRegex);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000562 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000563 Config.KeepSection.emplace_back(Arg->getValue(), UseRegex);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000564 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000565 Config.OnlySection.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000566 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
567 Config.AddSection.push_back(Arg->getValue());
568 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
569 Config.DumpSection.push_back(Arg->getValue());
570 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
571 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
572 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
573 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
574 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
575 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
576 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
577 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
578 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
579 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000580 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
581 Config.DiscardMode =
582 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
583 ? DiscardType::All
584 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000585 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
586 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
587 Config.DecompressDebugSections =
588 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000589 if (Config.DiscardMode == DiscardType::All)
590 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000591 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000592 Config.SymbolsToLocalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000593 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000594 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
595 Arg->getValue(), UseRegex))
596 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000597 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000598 Config.SymbolsToKeepGlobal.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000599 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000600 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
601 Arg->getValue(), UseRegex))
602 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000603 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000604 Config.SymbolsToGlobalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000605 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000606 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
607 Arg->getValue(), UseRegex))
608 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000609 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000610 Config.SymbolsToWeaken.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000611 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000612 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
613 Arg->getValue(), UseRegex))
614 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000615 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000616 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000617 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000618 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
619 Arg->getValue(), UseRegex))
620 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000621 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
622 Config.UnneededSymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
623 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000624 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
625 Arg->getValue(), UseRegex))
626 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000627 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000628 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegex);
Yi Kongf2baddb2019-04-01 18:12:43 +0000629 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
630 if (Error E = addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc,
631 Arg->getValue(), UseRegex))
632 return std::move(E);
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000633 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
634 Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(Arg->getValue());
635 if (!NSI)
636 return NSI.takeError();
637 Config.SymbolsToAdd.push_back(*NSI);
638 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000639
James Henderson66a9d0f2019-04-18 09:13:30 +0000640 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
641
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000642 Config.DeterministicArchives = InputArgs.hasFlag(
643 OBJCOPY_enable_deterministic_archives,
644 OBJCOPY_disable_deterministic_archives, /*default=*/true);
645
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000646 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
647
Eugene Leviant53350d02019-02-26 09:24:22 +0000648 for (auto Arg : InputArgs)
649 if (Arg->getOption().matches(OBJCOPY_set_start)) {
650 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
651 if (!EAddr)
652 return createStringError(
653 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
654
655 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
656 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
657 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
658 if (!EIncr)
659 return createStringError(EIncr.getError(),
660 "bad entry point increment: '%s'",
661 Arg->getValue());
662 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
663 : [](uint64_t A) { return A; };
664 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
665 return Expr(EAddr) + *EIncr;
666 };
667 }
668
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000669 if (Config.DecompressDebugSections &&
670 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000671 return createStringError(
672 errc::invalid_argument,
673 "Cannot specify --compress-debug-sections at the same time as "
674 "--decompress-debug-sections at the same time");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000675 }
676
677 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000678 return createStringError(
679 errc::invalid_argument,
680 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000681
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000682 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000683 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000684}
685
686// ParseStripOptions returns the config and sets the input arguments. If a
687// help flag is set then ParseStripOptions will print the help messege and
688// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000689Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000690 StripOptTable T;
691 unsigned MissingArgumentIndex, MissingArgumentCount;
692 llvm::opt::InputArgList InputArgs =
693 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
694
695 if (InputArgs.size() == 0) {
696 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
697 exit(1);
698 }
699
700 if (InputArgs.hasArg(STRIP_help)) {
701 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
702 exit(0);
703 }
704
705 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000706 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000707 cl::PrintVersionMessage();
708 exit(0);
709 }
710
711 SmallVector<const char *, 2> Positional;
712 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000713 return createStringError(errc::invalid_argument, "unknown argument '%s'",
714 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000715 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
716 Positional.push_back(Arg->getValue());
717
718 if (Positional.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000719 return createStringError(errc::invalid_argument, "No input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000720
721 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000722 return createStringError(
723 errc::invalid_argument,
724 "Multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000725
726 CopyConfig Config;
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000727 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
James Henderson66a9d0f2019-04-18 09:13:30 +0000728 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000729 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
730
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000731 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
732 Config.DiscardMode =
733 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
734 ? DiscardType::All
735 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000736 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000737 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
738 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000739 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000740 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000741 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000742
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000743 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000744 Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000745
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000746 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000747 Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000748
Eugene Leviant2267c582019-01-31 12:16:20 +0000749 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000750 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
Eugene Leviant2267c582019-01-31 12:16:20 +0000751
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000752 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000753 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000754
James Hendersone4a89a12019-05-02 11:53:02 +0000755 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
756 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
757 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000758 Config.StripAll = true;
759
Sid Manning5ad18a72019-05-03 14:14:01 +0000760 if (Config.DiscardMode == DiscardType::All)
761 Config.StripDebug = true;
762
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000763 Config.DeterministicArchives =
764 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
765 STRIP_disable_deterministic_archives, /*default=*/true);
766
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000767 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
768
769 DriverConfig DC;
770 if (Positional.size() == 1) {
771 Config.InputFilename = Positional[0];
772 Config.OutputFilename =
773 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
774 DC.CopyConfigs.push_back(std::move(Config));
775 } else {
776 for (const char *Filename : Positional) {
777 Config.InputFilename = Filename;
778 Config.OutputFilename = Filename;
779 DC.CopyConfigs.push_back(Config);
780 }
781 }
782
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000783 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000784}
785
786} // namespace objcopy
787} // namespace llvm