blob: 0b0023f52d8ab1c67f517f6cc9e4684a20ec7f5d [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 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000461 if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary") {
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000462 Expected<MachineInfo> MI = getOutputFormatMachineInfo(Config.OutputFormat);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000463 if (!MI)
464 return MI.takeError();
465 Config.OutputArch = *MI;
466 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000467
468 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
469 OBJCOPY_compress_debug_sections_eq)) {
470 Config.CompressionType = DebugCompressionType::Z;
471
472 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
473 Config.CompressionType =
474 StringSwitch<DebugCompressionType>(
475 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
476 .Case("zlib-gnu", DebugCompressionType::GNU)
477 .Case("zlib", DebugCompressionType::Z)
478 .Default(DebugCompressionType::None);
479 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000480 return createStringError(
481 errc::invalid_argument,
482 "Invalid or unsupported --compress-debug-sections format: %s",
483 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
484 .str()
485 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000486 }
George Rimar1e930802019-03-05 11:32:14 +0000487 if (!zlib::isAvailable())
488 return createStringError(
489 errc::invalid_argument,
490 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000491 }
492
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000493 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000494 // The gnu_debuglink's target is expected to not change or else its CRC would
495 // become invalidated and get rejected. We can avoid recalculating the
496 // checksum for every target file inside an archive by precomputing the CRC
497 // here. This prevents a significant amount of I/O.
498 if (!Config.AddGnuDebugLink.empty()) {
499 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
500 if (!DebugOrErr)
501 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
502 auto Debug = std::move(*DebugOrErr);
503 JamCRC CRC;
504 CRC.update(
505 ArrayRef<char>(Debug->getBuffer().data(), Debug->getBuffer().size()));
506 // The CRC32 value needs to be complemented because the JamCRC doesn't
507 // finalize the CRC32 value.
508 Config.GnuDebugLinkCRC32 = ~CRC.getCRC();
509 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000510 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
511 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
512 Config.BuildIdLinkInput =
513 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
514 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
515 Config.BuildIdLinkOutput =
516 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
517 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000518 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000519 Config.AllocSectionsPrefix =
520 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000521
522 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
523 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000524 return createStringError(errc::invalid_argument,
525 "Bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000526 auto Old2New = StringRef(Arg->getValue()).split('=');
527 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000528 return createStringError(errc::invalid_argument,
529 "Multiple redefinition of symbol %s",
530 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000531 }
532
Eugene Leviant340cb872019-02-08 10:33:16 +0000533 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
534 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
535 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000536 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000537
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000538 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000539 Expected<SectionRename> SR =
540 parseRenameSectionValue(StringRef(Arg->getValue()));
541 if (!SR)
542 return SR.takeError();
543 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
544 return createStringError(errc::invalid_argument,
545 "Multiple renames of section %s",
546 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000547 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000548 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000549 Expected<SectionFlagsUpdate> SFU =
550 parseSetSectionFlagValue(Arg->getValue());
551 if (!SFU)
552 return SFU.takeError();
553 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
554 return createStringError(
555 errc::invalid_argument,
556 "--set-section-flags set multiple times for section %s",
557 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000558 }
559 // Prohibit combinations of --set-section-flags when the section name is used
560 // by --rename-section, either as a source or a destination.
561 for (const auto &E : Config.SectionsToRename) {
562 const SectionRename &SR = E.second;
563 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000564 return createStringError(
565 errc::invalid_argument,
566 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
567 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
568 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000569 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000570 return createStringError(
571 errc::invalid_argument,
572 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
573 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
574 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000575 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000576
577 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000578 Config.ToRemove.emplace_back(Arg->getValue(), UseRegex);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000579 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000580 Config.KeepSection.emplace_back(Arg->getValue(), UseRegex);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000581 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000582 Config.OnlySection.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000583 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
584 Config.AddSection.push_back(Arg->getValue());
585 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
586 Config.DumpSection.push_back(Arg->getValue());
587 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
588 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
589 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
590 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
591 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
592 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
593 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
594 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
595 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
596 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000597 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
598 Config.DiscardMode =
599 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
600 ? DiscardType::All
601 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000602 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
603 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
604 Config.DecompressDebugSections =
605 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000606 if (Config.DiscardMode == DiscardType::All)
607 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000608 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000609 Config.SymbolsToLocalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000610 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000611 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
612 Arg->getValue(), UseRegex))
613 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000614 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000615 Config.SymbolsToKeepGlobal.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000616 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000617 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
618 Arg->getValue(), UseRegex))
619 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000620 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000621 Config.SymbolsToGlobalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000622 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000623 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
624 Arg->getValue(), UseRegex))
625 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000626 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000627 Config.SymbolsToWeaken.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000628 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000629 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
630 Arg->getValue(), UseRegex))
631 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000632 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000633 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000634 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000635 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
636 Arg->getValue(), UseRegex))
637 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000638 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
639 Config.UnneededSymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
640 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000641 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
642 Arg->getValue(), UseRegex))
643 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000644 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000645 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegex);
Yi Kongf2baddb2019-04-01 18:12:43 +0000646 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
647 if (Error E = addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc,
648 Arg->getValue(), UseRegex))
649 return std::move(E);
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000650 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
651 Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(Arg->getValue());
652 if (!NSI)
653 return NSI.takeError();
654 Config.SymbolsToAdd.push_back(*NSI);
655 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000656
James Henderson66a9d0f2019-04-18 09:13:30 +0000657 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
658
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000659 Config.DeterministicArchives = InputArgs.hasFlag(
660 OBJCOPY_enable_deterministic_archives,
661 OBJCOPY_disable_deterministic_archives, /*default=*/true);
662
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000663 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
664
Eugene Leviant53350d02019-02-26 09:24:22 +0000665 for (auto Arg : InputArgs)
666 if (Arg->getOption().matches(OBJCOPY_set_start)) {
667 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
668 if (!EAddr)
669 return createStringError(
670 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
671
672 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
673 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
674 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
675 if (!EIncr)
676 return createStringError(EIncr.getError(),
677 "bad entry point increment: '%s'",
678 Arg->getValue());
679 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
680 : [](uint64_t A) { return A; };
681 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
682 return Expr(EAddr) + *EIncr;
683 };
684 }
685
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000686 if (Config.DecompressDebugSections &&
687 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000688 return createStringError(
689 errc::invalid_argument,
690 "Cannot specify --compress-debug-sections at the same time as "
691 "--decompress-debug-sections at the same time");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000692 }
693
694 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000695 return createStringError(
696 errc::invalid_argument,
697 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000698
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000699 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000700 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000701}
702
703// ParseStripOptions returns the config and sets the input arguments. If a
704// help flag is set then ParseStripOptions will print the help messege and
705// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000706Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000707 StripOptTable T;
708 unsigned MissingArgumentIndex, MissingArgumentCount;
709 llvm::opt::InputArgList InputArgs =
710 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
711
712 if (InputArgs.size() == 0) {
713 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
714 exit(1);
715 }
716
717 if (InputArgs.hasArg(STRIP_help)) {
718 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
719 exit(0);
720 }
721
722 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000723 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000724 cl::PrintVersionMessage();
725 exit(0);
726 }
727
728 SmallVector<const char *, 2> Positional;
729 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000730 return createStringError(errc::invalid_argument, "unknown argument '%s'",
731 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000732 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
733 Positional.push_back(Arg->getValue());
734
735 if (Positional.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000736 return createStringError(errc::invalid_argument, "No input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000737
738 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000739 return createStringError(
740 errc::invalid_argument,
741 "Multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000742
743 CopyConfig Config;
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000744 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
James Henderson66a9d0f2019-04-18 09:13:30 +0000745 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000746 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
747
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000748 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
749 Config.DiscardMode =
750 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
751 ? DiscardType::All
752 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000753 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000754 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
755 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000756 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000757 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000758 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000759
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000760 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000761 Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000762
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000763 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000764 Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000765
Eugene Leviant2267c582019-01-31 12:16:20 +0000766 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000767 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
Eugene Leviant2267c582019-01-31 12:16:20 +0000768
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000769 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000770 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000771
James Hendersone4a89a12019-05-02 11:53:02 +0000772 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
773 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
774 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000775 Config.StripAll = true;
776
Sid Manning5ad18a72019-05-03 14:14:01 +0000777 if (Config.DiscardMode == DiscardType::All)
778 Config.StripDebug = true;
779
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000780 Config.DeterministicArchives =
781 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
782 STRIP_disable_deterministic_archives, /*default=*/true);
783
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000784 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
785
786 DriverConfig DC;
787 if (Positional.size() == 1) {
788 Config.InputFilename = Positional[0];
789 Config.OutputFilename =
790 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
791 DC.CopyConfigs.push_back(std::move(Config));
792 } else {
793 for (const char *Filename : Positional) {
794 Config.InputFilename = Filename;
795 Config.OutputFilename = Filename;
796 DC.CopyConfigs.push_back(Config);
797 }
798 }
799
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000800 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000801}
802
803} // namespace objcopy
804} // namespace llvm