blob: b138544fcd7c7430bdb3ee5723c9b1f96cbf4290 [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"
James Henderson9df38832019-05-14 10:59:04 +000019#include "llvm/Support/JamCRC.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000020#include "llvm/Support/MemoryBuffer.h"
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +000021#include "llvm/Support/StringSaver.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000022#include <memory>
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000023
24namespace llvm {
25namespace objcopy {
26
27namespace {
28enum ObjcopyID {
29 OBJCOPY_INVALID = 0, // This is not an option ID.
30#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
31 HELPTEXT, METAVAR, VALUES) \
32 OBJCOPY_##ID,
33#include "ObjcopyOpts.inc"
34#undef OPTION
35};
36
37#define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
38#include "ObjcopyOpts.inc"
39#undef PREFIX
40
41static const opt::OptTable::Info ObjcopyInfoTable[] = {
42#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
43 HELPTEXT, METAVAR, VALUES) \
44 {OBJCOPY_##PREFIX, \
45 NAME, \
46 HELPTEXT, \
47 METAVAR, \
48 OBJCOPY_##ID, \
49 opt::Option::KIND##Class, \
50 PARAM, \
51 FLAGS, \
52 OBJCOPY_##GROUP, \
53 OBJCOPY_##ALIAS, \
54 ALIASARGS, \
55 VALUES},
56#include "ObjcopyOpts.inc"
57#undef OPTION
58};
59
60class ObjcopyOptTable : public opt::OptTable {
61public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +000062 ObjcopyOptTable() : OptTable(ObjcopyInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000063};
64
65enum StripID {
66 STRIP_INVALID = 0, // This is not an option ID.
67#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
68 HELPTEXT, METAVAR, VALUES) \
69 STRIP_##ID,
70#include "StripOpts.inc"
71#undef OPTION
72};
73
74#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
75#include "StripOpts.inc"
76#undef PREFIX
77
78static const opt::OptTable::Info StripInfoTable[] = {
79#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
80 HELPTEXT, METAVAR, VALUES) \
81 {STRIP_##PREFIX, NAME, HELPTEXT, \
82 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
83 PARAM, FLAGS, STRIP_##GROUP, \
84 STRIP_##ALIAS, ALIASARGS, VALUES},
85#include "StripOpts.inc"
86#undef OPTION
87};
88
89class StripOptTable : public opt::OptTable {
90public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +000091 StripOptTable() : OptTable(StripInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000092};
93
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000094} // namespace
95
96static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
97 return llvm::StringSwitch<SectionFlag>(SectionName)
James Hendersond931cf32019-04-03 14:40:27 +000098 .CaseLower("alloc", SectionFlag::SecAlloc)
99 .CaseLower("load", SectionFlag::SecLoad)
100 .CaseLower("noload", SectionFlag::SecNoload)
101 .CaseLower("readonly", SectionFlag::SecReadonly)
102 .CaseLower("debug", SectionFlag::SecDebug)
103 .CaseLower("code", SectionFlag::SecCode)
104 .CaseLower("data", SectionFlag::SecData)
105 .CaseLower("rom", SectionFlag::SecRom)
106 .CaseLower("merge", SectionFlag::SecMerge)
107 .CaseLower("strings", SectionFlag::SecStrings)
108 .CaseLower("contents", SectionFlag::SecContents)
109 .CaseLower("share", SectionFlag::SecShare)
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000110 .Default(SectionFlag::SecNone);
111}
112
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000113static Expected<SectionFlag>
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000114parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000115 SectionFlag ParsedFlags = SectionFlag::SecNone;
116 for (StringRef Flag : SectionFlags) {
117 SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
118 if (ParsedFlag == SectionFlag::SecNone)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000119 return createStringError(
120 errc::invalid_argument,
121 "Unrecognized section flag '%s'. Flags supported for GNU "
122 "compatibility: alloc, load, noload, readonly, debug, code, data, "
123 "rom, share, contents, merge, strings",
124 Flag.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000125 ParsedFlags |= ParsedFlag;
126 }
127
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000128 return ParsedFlags;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000129}
130
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000131static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000132 if (!FlagValue.contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000133 return createStringError(errc::invalid_argument,
134 "Bad format for --rename-section: missing '='");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000135
136 // Initial split: ".foo" = ".bar,f1,f2,..."
137 auto Old2New = FlagValue.split('=');
138 SectionRename SR;
139 SR.OriginalName = Old2New.first;
140
141 // Flags split: ".bar" "f1" "f2" ...
142 SmallVector<StringRef, 6> NameAndFlags;
143 Old2New.second.split(NameAndFlags, ',');
144 SR.NewName = NameAndFlags[0];
145
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000146 if (NameAndFlags.size() > 1) {
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000147 Expected<SectionFlag> ParsedFlagSet =
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000148 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
149 if (!ParsedFlagSet)
150 return ParsedFlagSet.takeError();
151 SR.NewFlags = *ParsedFlagSet;
152 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000153
154 return SR;
155}
156
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000157static Expected<SectionFlagsUpdate>
158parseSetSectionFlagValue(StringRef FlagValue) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000159 if (!StringRef(FlagValue).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000160 return createStringError(errc::invalid_argument,
161 "Bad format for --set-section-flags: missing '='");
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000162
163 // Initial split: ".foo" = "f1,f2,..."
164 auto Section2Flags = StringRef(FlagValue).split('=');
165 SectionFlagsUpdate SFU;
166 SFU.Name = Section2Flags.first;
167
168 // Flags split: "f1" "f2" ...
169 SmallVector<StringRef, 6> SectionFlags;
170 Section2Flags.second.split(SectionFlags, ',');
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000171 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000172 if (!ParsedFlagSet)
173 return ParsedFlagSet.takeError();
174 SFU.NewFlags = *ParsedFlagSet;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000175
176 return SFU;
177}
178
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000179static Expected<NewSymbolInfo> parseNewSymbolInfo(StringRef FlagValue) {
Eugene Leviant51c1f642019-02-25 14:12:41 +0000180 // Parse value given with --add-symbol option and create the
181 // new symbol if possible. The value format for --add-symbol is:
182 //
183 // <name>=[<section>:]<value>[,<flags>]
184 //
185 // where:
186 // <name> - symbol name, can be empty string
187 // <section> - optional section name. If not given ABS symbol is created
188 // <value> - symbol value, can be decimal or hexadecimal number prefixed
189 // with 0x.
190 // <flags> - optional flags affecting symbol type, binding or visibility:
191 // The following are currently supported:
192 //
193 // global, local, weak, default, hidden, file, section, object,
194 // indirect-function.
195 //
196 // The following flags are ignored and provided for GNU
197 // compatibility only:
198 //
199 // warning, debug, constructor, indirect, synthetic,
200 // unique-object, before=<symbol>.
201 NewSymbolInfo SI;
202 StringRef Value;
203 std::tie(SI.SymbolName, Value) = FlagValue.split('=');
204 if (Value.empty())
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000205 return createStringError(
206 errc::invalid_argument,
207 "bad format for --add-symbol, missing '=' after '%s'",
208 SI.SymbolName.str().c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000209
210 if (Value.contains(':')) {
211 std::tie(SI.SectionName, Value) = Value.split(':');
212 if (SI.SectionName.empty() || Value.empty())
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000213 return createStringError(
214 errc::invalid_argument,
Eugene Leviant51c1f642019-02-25 14:12:41 +0000215 "bad format for --add-symbol, missing section name or symbol value");
216 }
217
218 SmallVector<StringRef, 6> Flags;
219 Value.split(Flags, ',');
220 if (Flags[0].getAsInteger(0, SI.Value))
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000221 return createStringError(errc::invalid_argument, "bad symbol value: '%s'",
222 Flags[0].str().c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000223
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000224 using Functor = std::function<void(void)>;
225 SmallVector<StringRef, 6> UnsupportedFlags;
226 for (size_t I = 1, NumFlags = Flags.size(); I < NumFlags; ++I)
Eugene Leviant51c1f642019-02-25 14:12:41 +0000227 static_cast<Functor>(
228 StringSwitch<Functor>(Flags[I])
229 .CaseLower("global", [&SI] { SI.Bind = ELF::STB_GLOBAL; })
230 .CaseLower("local", [&SI] { SI.Bind = ELF::STB_LOCAL; })
231 .CaseLower("weak", [&SI] { SI.Bind = ELF::STB_WEAK; })
232 .CaseLower("default", [&SI] { SI.Visibility = ELF::STV_DEFAULT; })
233 .CaseLower("hidden", [&SI] { SI.Visibility = ELF::STV_HIDDEN; })
234 .CaseLower("file", [&SI] { SI.Type = ELF::STT_FILE; })
235 .CaseLower("section", [&SI] { SI.Type = ELF::STT_SECTION; })
236 .CaseLower("object", [&SI] { SI.Type = ELF::STT_OBJECT; })
237 .CaseLower("function", [&SI] { SI.Type = ELF::STT_FUNC; })
238 .CaseLower("indirect-function",
239 [&SI] { SI.Type = ELF::STT_GNU_IFUNC; })
240 .CaseLower("debug", [] {})
241 .CaseLower("constructor", [] {})
242 .CaseLower("warning", [] {})
243 .CaseLower("indirect", [] {})
244 .CaseLower("synthetic", [] {})
245 .CaseLower("unique-object", [] {})
246 .StartsWithLower("before", [] {})
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000247 .Default([&] { UnsupportedFlags.push_back(Flags[I]); }))();
248 if (!UnsupportedFlags.empty())
249 return createStringError(errc::invalid_argument,
250 "unsupported flag%s for --add-symbol: '%s'",
251 UnsupportedFlags.size() > 1 ? "s" : "",
252 join(UnsupportedFlags, "', '").c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000253 return SI;
254}
255
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000256static const StringMap<MachineInfo> ArchMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000257 // Name, {EMachine, 64bit, LittleEndian}
258 {"aarch64", {ELF::EM_AARCH64, true, true}},
259 {"arm", {ELF::EM_ARM, false, true}},
260 {"i386", {ELF::EM_386, false, true}},
261 {"i386:x86-64", {ELF::EM_X86_64, true, true}},
Jordan Rupprecht2b329022019-04-18 14:22:37 +0000262 {"mips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000263 {"powerpc:common64", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000264 {"riscv:rv32", {ELF::EM_RISCV, false, true}},
265 {"riscv:rv64", {ELF::EM_RISCV, true, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000266 {"sparc", {ELF::EM_SPARC, false, true}},
267 {"x86-64", {ELF::EM_X86_64, true, true}},
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000268};
269
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000270static Expected<const MachineInfo &> getMachineInfo(StringRef Arch) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000271 auto Iter = ArchMap.find(Arch);
272 if (Iter == std::end(ArchMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000273 return createStringError(errc::invalid_argument,
274 "Invalid architecture: '%s'", Arch.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000275 return Iter->getValue();
276}
277
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000278// FIXME: consolidate with the bfd parsing used by lld.
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000279static const StringMap<MachineInfo> OutputFormatMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000280 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000281 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000282 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000283 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000284 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
285 // Intel MCU
286 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
287 // ARM
288 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
289 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000290 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
291 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000292 // RISC-V
293 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
294 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
295 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000296 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
297 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
298 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
299 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000300 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000301 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
302 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000303 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000304 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
305 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000306 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
307 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000308};
309
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000310static Expected<MachineInfo> getOutputFormatMachineInfo(StringRef Format) {
311 StringRef OriginalFormat = Format;
312 bool IsFreeBSD = Format.consume_back("-freebsd");
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000313 auto Iter = OutputFormatMap.find(Format);
314 if (Iter == std::end(OutputFormatMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000315 return createStringError(errc::invalid_argument,
316 "Invalid output format: '%s'",
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000317 OriginalFormat.str().c_str());
318 MachineInfo MI = Iter->getValue();
319 if (IsFreeBSD)
320 MI.OSABI = ELF::ELFOSABI_FREEBSD;
321 return {MI};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000322}
323
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000324static Error addSymbolsFromFile(std::vector<NameOrRegex> &Symbols,
325 BumpPtrAllocator &Alloc, StringRef Filename,
326 bool UseRegex) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000327 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000328 SmallVector<StringRef, 16> Lines;
329 auto BufOrErr = MemoryBuffer::getFile(Filename);
330 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000331 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000332
333 BufOrErr.get()->getBuffer().split(Lines, '\n');
334 for (StringRef Line : Lines) {
335 // Ignore everything after '#', trim whitespace, and only add the symbol if
336 // it's not empty.
337 auto TrimmedLine = Line.split('#').first.trim();
338 if (!TrimmedLine.empty())
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000339 Symbols.emplace_back(Saver.save(TrimmedLine), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000340 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000341
342 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000343}
344
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000345NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
346 if (!IsRegex) {
347 Name = Pattern;
348 return;
349 }
350
351 SmallVector<char, 32> Data;
352 R = std::make_shared<Regex>(
353 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
354}
355
Eugene Leviant340cb872019-02-08 10:33:16 +0000356static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
357 BumpPtrAllocator &Alloc,
358 StringRef Filename) {
359 StringSaver Saver(Alloc);
360 SmallVector<StringRef, 16> Lines;
361 auto BufOrErr = MemoryBuffer::getFile(Filename);
362 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000363 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000364
365 BufOrErr.get()->getBuffer().split(Lines, '\n');
366 size_t NumLines = Lines.size();
367 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
368 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
369 if (TrimmedLine.empty())
370 continue;
371
372 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
373 StringRef NewName = Pair.second.trim();
374 if (NewName.empty())
375 return createStringError(errc::invalid_argument,
376 "%s:%zu: missing new symbol name",
377 Filename.str().c_str(), LineNo + 1);
378 SymbolsToRename.insert({Pair.first, NewName});
379 }
380 return Error::success();
381}
Eugene Leviant53350d02019-02-26 09:24:22 +0000382
383template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
384 T Result;
385 if (Val.getAsInteger(0, Result))
386 return errc::invalid_argument;
387 return Result;
388}
389
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000390// ParseObjcopyOptions returns the config and sets the input arguments. If a
391// help flag is set then ParseObjcopyOptions will print the help messege and
392// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000393Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000394 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000395 ObjcopyOptTable T;
396 unsigned MissingArgumentIndex, MissingArgumentCount;
397 llvm::opt::InputArgList InputArgs =
398 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
399
400 if (InputArgs.size() == 0) {
401 T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
402 exit(1);
403 }
404
405 if (InputArgs.hasArg(OBJCOPY_help)) {
406 T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
407 exit(0);
408 }
409
410 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000411 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000412 cl::PrintVersionMessage();
413 exit(0);
414 }
415
416 SmallVector<const char *, 2> Positional;
417
418 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000419 return createStringError(errc::invalid_argument, "unknown argument '%s'",
420 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000421
422 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
423 Positional.push_back(Arg->getValue());
424
425 if (Positional.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000426 return createStringError(errc::invalid_argument, "No input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000427
428 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000429 return createStringError(errc::invalid_argument,
430 "Too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000431
432 CopyConfig Config;
433 Config.InputFilename = Positional[0];
434 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000435 if (InputArgs.hasArg(OBJCOPY_target) &&
436 (InputArgs.hasArg(OBJCOPY_input_target) ||
437 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000438 return createStringError(
439 errc::invalid_argument,
440 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000441
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000442 bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000443 if (InputArgs.hasArg(OBJCOPY_target)) {
444 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
445 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
446 } else {
447 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
448 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
449 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000450 if (Config.InputFormat == "binary") {
451 auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
452 if (BinaryArch.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000453 return createStringError(
454 errc::invalid_argument,
455 "Specified binary input without specifiying an architecture");
456 Expected<const MachineInfo &> MI = getMachineInfo(BinaryArch);
457 if (!MI)
458 return MI.takeError();
459 Config.BinaryArch = *MI;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000460 }
Eugene Levianta6fb1832019-05-29 11:37:16 +0000461 if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary" &&
462 Config.OutputFormat != "ihex") {
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000463 Expected<MachineInfo> MI = getOutputFormatMachineInfo(Config.OutputFormat);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000464 if (!MI)
465 return MI.takeError();
466 Config.OutputArch = *MI;
467 }
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,
483 "Invalid or unsupported --compress-debug-sections format: %s",
484 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);
504 JamCRC CRC;
505 CRC.update(
506 ArrayRef<char>(Debug->getBuffer().data(), Debug->getBuffer().size()));
507 // The CRC32 value needs to be complemented because the JamCRC doesn't
508 // finalize the CRC32 value.
509 Config.GnuDebugLinkCRC32 = ~CRC.getCRC();
510 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000511 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
512 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
513 Config.BuildIdLinkInput =
514 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
515 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
516 Config.BuildIdLinkOutput =
517 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
518 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000519 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000520 Config.AllocSectionsPrefix =
521 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000522
523 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
524 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000525 return createStringError(errc::invalid_argument,
526 "Bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000527 auto Old2New = StringRef(Arg->getValue()).split('=');
528 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000529 return createStringError(errc::invalid_argument,
530 "Multiple redefinition of symbol %s",
531 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000532 }
533
Eugene Leviant340cb872019-02-08 10:33:16 +0000534 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
535 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
536 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000537 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000538
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000539 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000540 Expected<SectionRename> SR =
541 parseRenameSectionValue(StringRef(Arg->getValue()));
542 if (!SR)
543 return SR.takeError();
544 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
545 return createStringError(errc::invalid_argument,
546 "Multiple renames of section %s",
547 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000548 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000549 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000550 Expected<SectionFlagsUpdate> SFU =
551 parseSetSectionFlagValue(Arg->getValue());
552 if (!SFU)
553 return SFU.takeError();
554 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
555 return createStringError(
556 errc::invalid_argument,
557 "--set-section-flags set multiple times for section %s",
558 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000559 }
560 // Prohibit combinations of --set-section-flags when the section name is used
561 // by --rename-section, either as a source or a destination.
562 for (const auto &E : Config.SectionsToRename) {
563 const SectionRename &SR = E.second;
564 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000565 return createStringError(
566 errc::invalid_argument,
567 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
568 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
569 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000570 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000571 return createStringError(
572 errc::invalid_argument,
573 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
574 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
575 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000576 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000577
578 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000579 Config.ToRemove.emplace_back(Arg->getValue(), UseRegex);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000580 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000581 Config.KeepSection.emplace_back(Arg->getValue(), UseRegex);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000582 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000583 Config.OnlySection.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000584 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
585 Config.AddSection.push_back(Arg->getValue());
586 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
587 Config.DumpSection.push_back(Arg->getValue());
588 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
589 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
590 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
591 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
592 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
593 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
594 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
595 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
596 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
597 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000598 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
599 Config.DiscardMode =
600 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
601 ? DiscardType::All
602 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000603 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
604 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
605 Config.DecompressDebugSections =
606 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000607 if (Config.DiscardMode == DiscardType::All)
608 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000609 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000610 Config.SymbolsToLocalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000611 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000612 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, 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_keep_global_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000616 Config.SymbolsToKeepGlobal.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000617 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000618 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
619 Arg->getValue(), UseRegex))
620 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000621 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000622 Config.SymbolsToGlobalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000623 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000624 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, 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_weaken_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000628 Config.SymbolsToWeaken.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000629 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000630 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
631 Arg->getValue(), UseRegex))
632 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000633 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000634 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000635 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000636 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
637 Arg->getValue(), UseRegex))
638 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000639 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
640 Config.UnneededSymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
641 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000642 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
643 Arg->getValue(), UseRegex))
644 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000645 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000646 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegex);
Yi Kongf2baddb2019-04-01 18:12:43 +0000647 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
648 if (Error E = addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc,
649 Arg->getValue(), UseRegex))
650 return std::move(E);
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000651 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
652 Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(Arg->getValue());
653 if (!NSI)
654 return NSI.takeError();
655 Config.SymbolsToAdd.push_back(*NSI);
656 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000657
James Henderson66a9d0f2019-04-18 09:13:30 +0000658 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
659
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000660 Config.DeterministicArchives = InputArgs.hasFlag(
661 OBJCOPY_enable_deterministic_archives,
662 OBJCOPY_disable_deterministic_archives, /*default=*/true);
663
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000664 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
665
Eugene Leviant53350d02019-02-26 09:24:22 +0000666 for (auto Arg : InputArgs)
667 if (Arg->getOption().matches(OBJCOPY_set_start)) {
668 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
669 if (!EAddr)
670 return createStringError(
671 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
672
673 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
674 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
675 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
676 if (!EIncr)
677 return createStringError(EIncr.getError(),
678 "bad entry point increment: '%s'",
679 Arg->getValue());
680 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
681 : [](uint64_t A) { return A; };
682 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
683 return Expr(EAddr) + *EIncr;
684 };
685 }
686
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000687 if (Config.DecompressDebugSections &&
688 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000689 return createStringError(
690 errc::invalid_argument,
691 "Cannot specify --compress-debug-sections at the same time as "
692 "--decompress-debug-sections at the same time");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000693 }
694
695 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000696 return createStringError(
697 errc::invalid_argument,
698 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000699
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000700 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000701 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000702}
703
704// ParseStripOptions returns the config and sets the input arguments. If a
705// help flag is set then ParseStripOptions will print the help messege and
706// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000707Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000708 StripOptTable T;
709 unsigned MissingArgumentIndex, MissingArgumentCount;
710 llvm::opt::InputArgList InputArgs =
711 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
712
713 if (InputArgs.size() == 0) {
714 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
715 exit(1);
716 }
717
718 if (InputArgs.hasArg(STRIP_help)) {
719 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
720 exit(0);
721 }
722
723 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000724 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000725 cl::PrintVersionMessage();
726 exit(0);
727 }
728
729 SmallVector<const char *, 2> Positional;
730 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000731 return createStringError(errc::invalid_argument, "unknown argument '%s'",
732 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000733 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
734 Positional.push_back(Arg->getValue());
735
736 if (Positional.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000737 return createStringError(errc::invalid_argument, "No input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000738
739 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000740 return createStringError(
741 errc::invalid_argument,
742 "Multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000743
744 CopyConfig Config;
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000745 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
James Henderson66a9d0f2019-04-18 09:13:30 +0000746 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000747 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
748
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000749 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
750 Config.DiscardMode =
751 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
752 ? DiscardType::All
753 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000754 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000755 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
756 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000757 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000758 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000759 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000760
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000761 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000762 Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000763
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000764 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000765 Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000766
Eugene Leviant2267c582019-01-31 12:16:20 +0000767 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000768 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
Eugene Leviant2267c582019-01-31 12:16:20 +0000769
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000770 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000771 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000772
James Hendersone4a89a12019-05-02 11:53:02 +0000773 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
774 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
775 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000776 Config.StripAll = true;
777
Sid Manning5ad18a72019-05-03 14:14:01 +0000778 if (Config.DiscardMode == DiscardType::All)
779 Config.StripDebug = true;
780
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000781 Config.DeterministicArchives =
782 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
783 STRIP_disable_deterministic_archives, /*default=*/true);
784
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000785 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
786
787 DriverConfig DC;
788 if (Positional.size() == 1) {
789 Config.InputFilename = Positional[0];
790 Config.OutputFilename =
791 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
792 DC.CopyConfigs.push_back(std::move(Config));
793 } else {
794 for (const char *Filename : Positional) {
795 Config.InputFilename = Filename;
796 Config.OutputFilename = Filename;
797 DC.CopyConfigs.push_back(Config);
798 }
799 }
800
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000801 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000802}
803
804} // namespace objcopy
805} // namespace llvm