blob: 9f03c7cdae61a52e2e2ae5bd142051e988b34939 [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,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000121 "unrecognized section flag '%s'. Flags supported for GNU "
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000122 "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,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000134 "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,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000161 "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}},
Seiya Nutab1027a42019-06-13 23:24:12 +0000266 {"sparc", {ELF::EM_SPARC, false, false}},
267 {"sparcel", {ELF::EM_SPARC, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000268 {"x86-64", {ELF::EM_X86_64, true, true}},
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000269};
270
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000271static Expected<const MachineInfo &> getMachineInfo(StringRef Arch) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000272 auto Iter = ArchMap.find(Arch);
273 if (Iter == std::end(ArchMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000274 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000275 "invalid architecture: '%s'", Arch.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000276 return Iter->getValue();
277}
278
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000279// FIXME: consolidate with the bfd parsing used by lld.
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000280static const StringMap<MachineInfo> OutputFormatMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000281 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000282 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000283 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000284 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000285 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
286 // Intel MCU
287 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
288 // ARM
289 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
290 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000291 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
292 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000293 // RISC-V
294 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
295 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
296 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000297 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
298 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
299 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
300 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000301 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000302 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
303 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000304 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000305 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
306 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000307 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
308 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000309};
310
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000311static Expected<MachineInfo> getOutputFormatMachineInfo(StringRef Format) {
312 StringRef OriginalFormat = Format;
313 bool IsFreeBSD = Format.consume_back("-freebsd");
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000314 auto Iter = OutputFormatMap.find(Format);
315 if (Iter == std::end(OutputFormatMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000316 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000317 "invalid output format: '%s'",
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000318 OriginalFormat.str().c_str());
319 MachineInfo MI = Iter->getValue();
320 if (IsFreeBSD)
321 MI.OSABI = ELF::ELFOSABI_FREEBSD;
322 return {MI};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000323}
324
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000325static Error addSymbolsFromFile(std::vector<NameOrRegex> &Symbols,
326 BumpPtrAllocator &Alloc, StringRef Filename,
327 bool UseRegex) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000328 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000329 SmallVector<StringRef, 16> Lines;
330 auto BufOrErr = MemoryBuffer::getFile(Filename);
331 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000332 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000333
334 BufOrErr.get()->getBuffer().split(Lines, '\n');
335 for (StringRef Line : Lines) {
336 // Ignore everything after '#', trim whitespace, and only add the symbol if
337 // it's not empty.
338 auto TrimmedLine = Line.split('#').first.trim();
339 if (!TrimmedLine.empty())
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000340 Symbols.emplace_back(Saver.save(TrimmedLine), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000341 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000342
343 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000344}
345
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000346NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
347 if (!IsRegex) {
348 Name = Pattern;
349 return;
350 }
351
352 SmallVector<char, 32> Data;
353 R = std::make_shared<Regex>(
354 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
355}
356
Eugene Leviant340cb872019-02-08 10:33:16 +0000357static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
358 BumpPtrAllocator &Alloc,
359 StringRef Filename) {
360 StringSaver Saver(Alloc);
361 SmallVector<StringRef, 16> Lines;
362 auto BufOrErr = MemoryBuffer::getFile(Filename);
363 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000364 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000365
366 BufOrErr.get()->getBuffer().split(Lines, '\n');
367 size_t NumLines = Lines.size();
368 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
369 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
370 if (TrimmedLine.empty())
371 continue;
372
373 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
374 StringRef NewName = Pair.second.trim();
375 if (NewName.empty())
376 return createStringError(errc::invalid_argument,
377 "%s:%zu: missing new symbol name",
378 Filename.str().c_str(), LineNo + 1);
379 SymbolsToRename.insert({Pair.first, NewName});
380 }
381 return Error::success();
382}
Eugene Leviant53350d02019-02-26 09:24:22 +0000383
384template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
385 T Result;
386 if (Val.getAsInteger(0, Result))
387 return errc::invalid_argument;
388 return Result;
389}
390
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000391// ParseObjcopyOptions returns the config and sets the input arguments. If a
392// help flag is set then ParseObjcopyOptions will print the help messege and
393// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000394Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000395 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000396 ObjcopyOptTable T;
397 unsigned MissingArgumentIndex, MissingArgumentCount;
398 llvm::opt::InputArgList InputArgs =
399 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
400
401 if (InputArgs.size() == 0) {
402 T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
403 exit(1);
404 }
405
406 if (InputArgs.hasArg(OBJCOPY_help)) {
407 T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
408 exit(0);
409 }
410
411 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000412 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000413 cl::PrintVersionMessage();
414 exit(0);
415 }
416
417 SmallVector<const char *, 2> Positional;
418
419 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000420 return createStringError(errc::invalid_argument, "unknown argument '%s'",
421 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000422
423 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
424 Positional.push_back(Arg->getValue());
425
426 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000427 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000428
429 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000430 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000431 "too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000432
433 CopyConfig Config;
434 Config.InputFilename = Positional[0];
435 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000436 if (InputArgs.hasArg(OBJCOPY_target) &&
437 (InputArgs.hasArg(OBJCOPY_input_target) ||
438 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000439 return createStringError(
440 errc::invalid_argument,
441 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000442
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000443 bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000444 if (InputArgs.hasArg(OBJCOPY_target)) {
445 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
446 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
447 } else {
448 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
449 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
450 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000451 if (Config.InputFormat == "binary") {
452 auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
453 if (BinaryArch.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000454 return createStringError(
455 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000456 "specified binary input without specifiying an architecture");
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000457 Expected<const MachineInfo &> MI = getMachineInfo(BinaryArch);
458 if (!MI)
459 return MI.takeError();
460 Config.BinaryArch = *MI;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000461 }
Eugene Levianta6fb1832019-05-29 11:37:16 +0000462 if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary" &&
463 Config.OutputFormat != "ihex") {
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000464 Expected<MachineInfo> MI = getOutputFormatMachineInfo(Config.OutputFormat);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000465 if (!MI)
466 return MI.takeError();
467 Config.OutputArch = *MI;
468 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000469
470 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
471 OBJCOPY_compress_debug_sections_eq)) {
472 Config.CompressionType = DebugCompressionType::Z;
473
474 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
475 Config.CompressionType =
476 StringSwitch<DebugCompressionType>(
477 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
478 .Case("zlib-gnu", DebugCompressionType::GNU)
479 .Case("zlib", DebugCompressionType::Z)
480 .Default(DebugCompressionType::None);
481 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000482 return createStringError(
483 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000484 "invalid or unsupported --compress-debug-sections format: %s",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000485 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
486 .str()
487 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000488 }
George Rimar1e930802019-03-05 11:32:14 +0000489 if (!zlib::isAvailable())
490 return createStringError(
491 errc::invalid_argument,
492 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000493 }
494
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000495 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000496 // The gnu_debuglink's target is expected to not change or else its CRC would
497 // become invalidated and get rejected. We can avoid recalculating the
498 // checksum for every target file inside an archive by precomputing the CRC
499 // here. This prevents a significant amount of I/O.
500 if (!Config.AddGnuDebugLink.empty()) {
501 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
502 if (!DebugOrErr)
503 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
504 auto Debug = std::move(*DebugOrErr);
505 JamCRC CRC;
506 CRC.update(
507 ArrayRef<char>(Debug->getBuffer().data(), Debug->getBuffer().size()));
508 // The CRC32 value needs to be complemented because the JamCRC doesn't
509 // finalize the CRC32 value.
510 Config.GnuDebugLinkCRC32 = ~CRC.getCRC();
511 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000512 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
513 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
514 Config.BuildIdLinkInput =
515 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
516 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
517 Config.BuildIdLinkOutput =
518 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
519 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000520 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000521 Config.AllocSectionsPrefix =
522 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000523 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
524 Config.ExtractPartition = Arg->getValue();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000525
526 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
527 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000528 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000529 "bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000530 auto Old2New = StringRef(Arg->getValue()).split('=');
531 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000532 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000533 "multiple redefinition of symbol '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000534 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000535 }
536
Eugene Leviant340cb872019-02-08 10:33:16 +0000537 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
538 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
539 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000540 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000541
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000542 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000543 Expected<SectionRename> SR =
544 parseRenameSectionValue(StringRef(Arg->getValue()));
545 if (!SR)
546 return SR.takeError();
547 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
548 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000549 "multiple renames of section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000550 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000551 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000552 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000553 Expected<SectionFlagsUpdate> SFU =
554 parseSetSectionFlagValue(Arg->getValue());
555 if (!SFU)
556 return SFU.takeError();
557 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
558 return createStringError(
559 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000560 "--set-section-flags set multiple times for section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000561 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000562 }
563 // Prohibit combinations of --set-section-flags when the section name is used
564 // by --rename-section, either as a source or a destination.
565 for (const auto &E : Config.SectionsToRename) {
566 const SectionRename &SR = E.second;
567 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000568 return createStringError(
569 errc::invalid_argument,
570 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
571 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
572 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000573 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000574 return createStringError(
575 errc::invalid_argument,
576 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
577 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
578 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000579 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000580
581 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000582 Config.ToRemove.emplace_back(Arg->getValue(), UseRegex);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000583 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000584 Config.KeepSection.emplace_back(Arg->getValue(), UseRegex);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000585 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000586 Config.OnlySection.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000587 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
588 Config.AddSection.push_back(Arg->getValue());
589 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
590 Config.DumpSection.push_back(Arg->getValue());
591 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
592 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
593 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
594 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
595 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
596 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
597 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
598 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000599 Config.ExtractMainPartition =
600 InputArgs.hasArg(OBJCOPY_extract_main_partition);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000601 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
602 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000603 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
604 Config.DiscardMode =
605 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
606 ? DiscardType::All
607 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000608 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
609 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
610 Config.DecompressDebugSections =
611 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000612 if (Config.DiscardMode == DiscardType::All)
613 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000614 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000615 Config.SymbolsToLocalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000616 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000617 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, 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_keep_global_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000621 Config.SymbolsToKeepGlobal.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000622 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000623 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, 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_globalize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000627 Config.SymbolsToGlobalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000628 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000629 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, 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_weaken_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000633 Config.SymbolsToWeaken.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000634 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000635 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
636 Arg->getValue(), UseRegex))
637 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000638 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000639 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000640 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000641 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
642 Arg->getValue(), UseRegex))
643 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000644 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
645 Config.UnneededSymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
646 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000647 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
648 Arg->getValue(), UseRegex))
649 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000650 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000651 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegex);
Yi Kongf2baddb2019-04-01 18:12:43 +0000652 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
653 if (Error E = addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc,
654 Arg->getValue(), UseRegex))
655 return std::move(E);
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000656 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
657 Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(Arg->getValue());
658 if (!NSI)
659 return NSI.takeError();
660 Config.SymbolsToAdd.push_back(*NSI);
661 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000662
James Henderson66a9d0f2019-04-18 09:13:30 +0000663 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
664
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000665 Config.DeterministicArchives = InputArgs.hasFlag(
666 OBJCOPY_enable_deterministic_archives,
667 OBJCOPY_disable_deterministic_archives, /*default=*/true);
668
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000669 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
670
Eugene Leviant53350d02019-02-26 09:24:22 +0000671 for (auto Arg : InputArgs)
672 if (Arg->getOption().matches(OBJCOPY_set_start)) {
673 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
674 if (!EAddr)
675 return createStringError(
676 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
677
678 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
679 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
680 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
681 if (!EIncr)
682 return createStringError(EIncr.getError(),
683 "bad entry point increment: '%s'",
684 Arg->getValue());
685 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
686 : [](uint64_t A) { return A; };
687 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
688 return Expr(EAddr) + *EIncr;
689 };
690 }
691
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000692 if (Config.DecompressDebugSections &&
693 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000694 return createStringError(
695 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000696 "cannot specify both --compress-debug-sections and "
697 "--decompress-debug-sections");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000698 }
699
700 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000701 return createStringError(
702 errc::invalid_argument,
703 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000704
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000705 if (Config.ExtractPartition && Config.ExtractMainPartition)
706 return createStringError(errc::invalid_argument,
707 "cannot specify --extract-partition together with "
708 "--extract-main-partition");
709
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000710 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000711 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000712}
713
714// ParseStripOptions returns the config and sets the input arguments. If a
715// help flag is set then ParseStripOptions will print the help messege and
716// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000717Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000718 StripOptTable T;
719 unsigned MissingArgumentIndex, MissingArgumentCount;
720 llvm::opt::InputArgList InputArgs =
721 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
722
723 if (InputArgs.size() == 0) {
724 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
725 exit(1);
726 }
727
728 if (InputArgs.hasArg(STRIP_help)) {
729 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
730 exit(0);
731 }
732
733 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000734 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000735 cl::PrintVersionMessage();
736 exit(0);
737 }
738
739 SmallVector<const char *, 2> Positional;
740 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000741 return createStringError(errc::invalid_argument, "unknown argument '%s'",
742 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000743 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
744 Positional.push_back(Arg->getValue());
745
746 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000747 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000748
749 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000750 return createStringError(
751 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000752 "multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000753
754 CopyConfig Config;
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000755 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
James Henderson66a9d0f2019-04-18 09:13:30 +0000756 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000757 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
758
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000759 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
760 Config.DiscardMode =
761 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
762 ? DiscardType::All
763 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000764 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000765 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
766 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000767 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000768 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000769 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000770
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000771 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000772 Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000773
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000774 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000775 Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000776
Eugene Leviant2267c582019-01-31 12:16:20 +0000777 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000778 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
Eugene Leviant2267c582019-01-31 12:16:20 +0000779
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000780 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000781 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000782
James Hendersone4a89a12019-05-02 11:53:02 +0000783 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
784 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
785 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000786 Config.StripAll = true;
787
Sid Manning5ad18a72019-05-03 14:14:01 +0000788 if (Config.DiscardMode == DiscardType::All)
789 Config.StripDebug = true;
790
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000791 Config.DeterministicArchives =
792 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
793 STRIP_disable_deterministic_archives, /*default=*/true);
794
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000795 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
796
797 DriverConfig DC;
798 if (Positional.size() == 1) {
799 Config.InputFilename = Positional[0];
800 Config.OutputFilename =
801 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
802 DC.CopyConfigs.push_back(std::move(Config));
803 } else {
804 for (const char *Filename : Positional) {
805 Config.InputFilename = Filename;
806 Config.OutputFilename = Filename;
807 DC.CopyConfigs.push_back(Config);
808 }
809 }
810
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000811 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000812}
813
814} // namespace objcopy
815} // namespace llvm