blob: 3cd95665139077515c3871ee599ceba7d835ae43 [file] [log] [blame]
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001//===- CopyConfig.cpp -----------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "CopyConfig.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000010
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000011#include "llvm/ADT/Optional.h"
12#include "llvm/ADT/SmallVector.h"
13#include "llvm/ADT/StringRef.h"
Alex Brachet77477002019-06-18 00:39:10 +000014#include "llvm/ADT/StringSet.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000015#include "llvm/Option/Arg.h"
16#include "llvm/Option/ArgList.h"
17#include "llvm/Support/CommandLine.h"
18#include "llvm/Support/Compression.h"
Eugene Leviant340cb872019-02-08 10:33:16 +000019#include "llvm/Support/Errc.h"
James Henderson9df38832019-05-14 10:59:04 +000020#include "llvm/Support/JamCRC.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000021#include "llvm/Support/MemoryBuffer.h"
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +000022#include "llvm/Support/StringSaver.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000023#include <memory>
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000024
25namespace llvm {
26namespace objcopy {
27
28namespace {
29enum ObjcopyID {
30 OBJCOPY_INVALID = 0, // This is not an option ID.
31#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
32 HELPTEXT, METAVAR, VALUES) \
33 OBJCOPY_##ID,
34#include "ObjcopyOpts.inc"
35#undef OPTION
36};
37
38#define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
39#include "ObjcopyOpts.inc"
40#undef PREFIX
41
42static const opt::OptTable::Info ObjcopyInfoTable[] = {
43#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
44 HELPTEXT, METAVAR, VALUES) \
45 {OBJCOPY_##PREFIX, \
46 NAME, \
47 HELPTEXT, \
48 METAVAR, \
49 OBJCOPY_##ID, \
50 opt::Option::KIND##Class, \
51 PARAM, \
52 FLAGS, \
53 OBJCOPY_##GROUP, \
54 OBJCOPY_##ALIAS, \
55 ALIASARGS, \
56 VALUES},
57#include "ObjcopyOpts.inc"
58#undef OPTION
59};
60
61class ObjcopyOptTable : public opt::OptTable {
62public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +000063 ObjcopyOptTable() : OptTable(ObjcopyInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000064};
65
66enum StripID {
67 STRIP_INVALID = 0, // This is not an option ID.
68#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
69 HELPTEXT, METAVAR, VALUES) \
70 STRIP_##ID,
71#include "StripOpts.inc"
72#undef OPTION
73};
74
75#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
76#include "StripOpts.inc"
77#undef PREFIX
78
79static const opt::OptTable::Info StripInfoTable[] = {
80#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
81 HELPTEXT, METAVAR, VALUES) \
82 {STRIP_##PREFIX, NAME, HELPTEXT, \
83 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
84 PARAM, FLAGS, STRIP_##GROUP, \
85 STRIP_##ALIAS, ALIASARGS, VALUES},
86#include "StripOpts.inc"
87#undef OPTION
88};
89
90class StripOptTable : public opt::OptTable {
91public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +000092 StripOptTable() : OptTable(StripInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000093};
94
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000095} // namespace
96
97static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
98 return llvm::StringSwitch<SectionFlag>(SectionName)
James Hendersond931cf32019-04-03 14:40:27 +000099 .CaseLower("alloc", SectionFlag::SecAlloc)
100 .CaseLower("load", SectionFlag::SecLoad)
101 .CaseLower("noload", SectionFlag::SecNoload)
102 .CaseLower("readonly", SectionFlag::SecReadonly)
103 .CaseLower("debug", SectionFlag::SecDebug)
104 .CaseLower("code", SectionFlag::SecCode)
105 .CaseLower("data", SectionFlag::SecData)
106 .CaseLower("rom", SectionFlag::SecRom)
107 .CaseLower("merge", SectionFlag::SecMerge)
108 .CaseLower("strings", SectionFlag::SecStrings)
109 .CaseLower("contents", SectionFlag::SecContents)
110 .CaseLower("share", SectionFlag::SecShare)
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000111 .Default(SectionFlag::SecNone);
112}
113
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000114static Expected<SectionFlag>
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000115parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000116 SectionFlag ParsedFlags = SectionFlag::SecNone;
117 for (StringRef Flag : SectionFlags) {
118 SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
119 if (ParsedFlag == SectionFlag::SecNone)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000120 return createStringError(
121 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000122 "unrecognized section flag '%s'. Flags supported for GNU "
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000123 "compatibility: alloc, load, noload, readonly, debug, code, data, "
124 "rom, share, contents, merge, strings",
125 Flag.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000126 ParsedFlags |= ParsedFlag;
127 }
128
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000129 return ParsedFlags;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000130}
131
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000132static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000133 if (!FlagValue.contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000134 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000135 "bad format for --rename-section: missing '='");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000136
137 // Initial split: ".foo" = ".bar,f1,f2,..."
138 auto Old2New = FlagValue.split('=');
139 SectionRename SR;
140 SR.OriginalName = Old2New.first;
141
142 // Flags split: ".bar" "f1" "f2" ...
143 SmallVector<StringRef, 6> NameAndFlags;
144 Old2New.second.split(NameAndFlags, ',');
145 SR.NewName = NameAndFlags[0];
146
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000147 if (NameAndFlags.size() > 1) {
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000148 Expected<SectionFlag> ParsedFlagSet =
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000149 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
150 if (!ParsedFlagSet)
151 return ParsedFlagSet.takeError();
152 SR.NewFlags = *ParsedFlagSet;
153 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000154
155 return SR;
156}
157
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000158static Expected<SectionFlagsUpdate>
159parseSetSectionFlagValue(StringRef FlagValue) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000160 if (!StringRef(FlagValue).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000161 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000162 "bad format for --set-section-flags: missing '='");
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000163
164 // Initial split: ".foo" = "f1,f2,..."
165 auto Section2Flags = StringRef(FlagValue).split('=');
166 SectionFlagsUpdate SFU;
167 SFU.Name = Section2Flags.first;
168
169 // Flags split: "f1" "f2" ...
170 SmallVector<StringRef, 6> SectionFlags;
171 Section2Flags.second.split(SectionFlags, ',');
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000172 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000173 if (!ParsedFlagSet)
174 return ParsedFlagSet.takeError();
175 SFU.NewFlags = *ParsedFlagSet;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000176
177 return SFU;
178}
179
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000180static Expected<NewSymbolInfo> parseNewSymbolInfo(StringRef FlagValue) {
Eugene Leviant51c1f642019-02-25 14:12:41 +0000181 // Parse value given with --add-symbol option and create the
182 // new symbol if possible. The value format for --add-symbol is:
183 //
184 // <name>=[<section>:]<value>[,<flags>]
185 //
186 // where:
187 // <name> - symbol name, can be empty string
188 // <section> - optional section name. If not given ABS symbol is created
189 // <value> - symbol value, can be decimal or hexadecimal number prefixed
190 // with 0x.
191 // <flags> - optional flags affecting symbol type, binding or visibility:
192 // The following are currently supported:
193 //
194 // global, local, weak, default, hidden, file, section, object,
195 // indirect-function.
196 //
197 // The following flags are ignored and provided for GNU
198 // compatibility only:
199 //
200 // warning, debug, constructor, indirect, synthetic,
201 // unique-object, before=<symbol>.
202 NewSymbolInfo SI;
203 StringRef Value;
204 std::tie(SI.SymbolName, Value) = FlagValue.split('=');
205 if (Value.empty())
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000206 return createStringError(
207 errc::invalid_argument,
208 "bad format for --add-symbol, missing '=' after '%s'",
209 SI.SymbolName.str().c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000210
211 if (Value.contains(':')) {
212 std::tie(SI.SectionName, Value) = Value.split(':');
213 if (SI.SectionName.empty() || Value.empty())
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000214 return createStringError(
215 errc::invalid_argument,
Eugene Leviant51c1f642019-02-25 14:12:41 +0000216 "bad format for --add-symbol, missing section name or symbol value");
217 }
218
219 SmallVector<StringRef, 6> Flags;
220 Value.split(Flags, ',');
221 if (Flags[0].getAsInteger(0, SI.Value))
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000222 return createStringError(errc::invalid_argument, "bad symbol value: '%s'",
223 Flags[0].str().c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000224
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000225 using Functor = std::function<void(void)>;
226 SmallVector<StringRef, 6> UnsupportedFlags;
227 for (size_t I = 1, NumFlags = Flags.size(); I < NumFlags; ++I)
Eugene Leviant51c1f642019-02-25 14:12:41 +0000228 static_cast<Functor>(
229 StringSwitch<Functor>(Flags[I])
230 .CaseLower("global", [&SI] { SI.Bind = ELF::STB_GLOBAL; })
231 .CaseLower("local", [&SI] { SI.Bind = ELF::STB_LOCAL; })
232 .CaseLower("weak", [&SI] { SI.Bind = ELF::STB_WEAK; })
233 .CaseLower("default", [&SI] { SI.Visibility = ELF::STV_DEFAULT; })
234 .CaseLower("hidden", [&SI] { SI.Visibility = ELF::STV_HIDDEN; })
235 .CaseLower("file", [&SI] { SI.Type = ELF::STT_FILE; })
236 .CaseLower("section", [&SI] { SI.Type = ELF::STT_SECTION; })
237 .CaseLower("object", [&SI] { SI.Type = ELF::STT_OBJECT; })
238 .CaseLower("function", [&SI] { SI.Type = ELF::STT_FUNC; })
239 .CaseLower("indirect-function",
240 [&SI] { SI.Type = ELF::STT_GNU_IFUNC; })
241 .CaseLower("debug", [] {})
242 .CaseLower("constructor", [] {})
243 .CaseLower("warning", [] {})
244 .CaseLower("indirect", [] {})
245 .CaseLower("synthetic", [] {})
246 .CaseLower("unique-object", [] {})
247 .StartsWithLower("before", [] {})
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000248 .Default([&] { UnsupportedFlags.push_back(Flags[I]); }))();
249 if (!UnsupportedFlags.empty())
250 return createStringError(errc::invalid_argument,
251 "unsupported flag%s for --add-symbol: '%s'",
252 UnsupportedFlags.size() > 1 ? "s" : "",
253 join(UnsupportedFlags, "', '").c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000254 return SI;
255}
256
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000257static const StringMap<MachineInfo> ArchMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000258 // Name, {EMachine, 64bit, LittleEndian}
259 {"aarch64", {ELF::EM_AARCH64, true, true}},
260 {"arm", {ELF::EM_ARM, false, true}},
261 {"i386", {ELF::EM_386, false, true}},
262 {"i386:x86-64", {ELF::EM_X86_64, true, true}},
Jordan Rupprecht2b329022019-04-18 14:22:37 +0000263 {"mips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000264 {"powerpc:common64", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000265 {"riscv:rv32", {ELF::EM_RISCV, false, true}},
266 {"riscv:rv64", {ELF::EM_RISCV, true, true}},
Seiya Nutab1027a42019-06-13 23:24:12 +0000267 {"sparc", {ELF::EM_SPARC, false, false}},
268 {"sparcel", {ELF::EM_SPARC, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000269 {"x86-64", {ELF::EM_X86_64, true, true}},
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000270};
271
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000272static Expected<const MachineInfo &> getMachineInfo(StringRef Arch) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000273 auto Iter = ArchMap.find(Arch);
274 if (Iter == std::end(ArchMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000275 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000276 "invalid architecture: '%s'", Arch.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000277 return Iter->getValue();
278}
279
Seiya Nutaecb60b72019-07-05 05:28:38 +0000280struct TargetInfo {
281 FileFormat Format;
282 MachineInfo Machine;
283};
284
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000285// FIXME: consolidate with the bfd parsing used by lld.
Seiya Nutaecb60b72019-07-05 05:28:38 +0000286static const StringMap<MachineInfo> TargetMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000287 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000288 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000289 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000290 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000291 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
292 // Intel MCU
293 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
294 // ARM
295 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
296 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000297 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
298 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000299 // RISC-V
300 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
301 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
302 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000303 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
304 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
305 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
306 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000307 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000308 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
309 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000310 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000311 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
312 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000313 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
314 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Seiya Nuta13de1742019-06-17 02:03:45 +0000315 // SPARC
316 {"elf32-sparc", {ELF::EM_SPARC, false, false}},
317 {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000318};
319
Seiya Nutaecb60b72019-07-05 05:28:38 +0000320static Expected<TargetInfo>
321getOutputTargetInfoByTargetName(StringRef TargetName) {
322 StringRef OriginalTargetName = TargetName;
323 bool IsFreeBSD = TargetName.consume_back("-freebsd");
324 auto Iter = TargetMap.find(TargetName);
325 if (Iter == std::end(TargetMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000326 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000327 "invalid output format: '%s'",
Seiya Nutaecb60b72019-07-05 05:28:38 +0000328 OriginalTargetName.str().c_str());
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000329 MachineInfo MI = Iter->getValue();
330 if (IsFreeBSD)
331 MI.OSABI = ELF::ELFOSABI_FREEBSD;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000332
333 FileFormat Format;
334 if (TargetName.startswith("elf"))
335 Format = FileFormat::ELF;
336 else
337 // This should never happen because `TargetName` is valid (it certainly
338 // exists in the TargetMap).
339 llvm_unreachable("unknown target prefix");
340
341 return {TargetInfo{Format, MI}};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000342}
343
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000344static Error addSymbolsFromFile(std::vector<NameOrRegex> &Symbols,
345 BumpPtrAllocator &Alloc, StringRef Filename,
346 bool UseRegex) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000347 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000348 SmallVector<StringRef, 16> Lines;
349 auto BufOrErr = MemoryBuffer::getFile(Filename);
350 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000351 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000352
353 BufOrErr.get()->getBuffer().split(Lines, '\n');
354 for (StringRef Line : Lines) {
355 // Ignore everything after '#', trim whitespace, and only add the symbol if
356 // it's not empty.
357 auto TrimmedLine = Line.split('#').first.trim();
358 if (!TrimmedLine.empty())
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000359 Symbols.emplace_back(Saver.save(TrimmedLine), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000360 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000361
362 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000363}
364
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000365NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
366 if (!IsRegex) {
367 Name = Pattern;
368 return;
369 }
370
371 SmallVector<char, 32> Data;
372 R = std::make_shared<Regex>(
373 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
374}
375
Eugene Leviant340cb872019-02-08 10:33:16 +0000376static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
377 BumpPtrAllocator &Alloc,
378 StringRef Filename) {
379 StringSaver Saver(Alloc);
380 SmallVector<StringRef, 16> Lines;
381 auto BufOrErr = MemoryBuffer::getFile(Filename);
382 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000383 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000384
385 BufOrErr.get()->getBuffer().split(Lines, '\n');
386 size_t NumLines = Lines.size();
387 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
388 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
389 if (TrimmedLine.empty())
390 continue;
391
392 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
393 StringRef NewName = Pair.second.trim();
394 if (NewName.empty())
395 return createStringError(errc::invalid_argument,
396 "%s:%zu: missing new symbol name",
397 Filename.str().c_str(), LineNo + 1);
398 SymbolsToRename.insert({Pair.first, NewName});
399 }
400 return Error::success();
401}
Eugene Leviant53350d02019-02-26 09:24:22 +0000402
403template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
404 T Result;
405 if (Val.getAsInteger(0, Result))
406 return errc::invalid_argument;
407 return Result;
408}
409
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000410// ParseObjcopyOptions returns the config and sets the input arguments. If a
411// help flag is set then ParseObjcopyOptions will print the help messege and
412// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000413Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000414 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000415 ObjcopyOptTable T;
416 unsigned MissingArgumentIndex, MissingArgumentCount;
417 llvm::opt::InputArgList InputArgs =
418 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
419
420 if (InputArgs.size() == 0) {
421 T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
422 exit(1);
423 }
424
425 if (InputArgs.hasArg(OBJCOPY_help)) {
426 T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
427 exit(0);
428 }
429
430 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000431 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000432 cl::PrintVersionMessage();
433 exit(0);
434 }
435
436 SmallVector<const char *, 2> Positional;
437
438 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000439 return createStringError(errc::invalid_argument, "unknown argument '%s'",
440 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000441
442 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
443 Positional.push_back(Arg->getValue());
444
445 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000446 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000447
448 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000449 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000450 "too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000451
452 CopyConfig Config;
453 Config.InputFilename = Positional[0];
454 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000455 if (InputArgs.hasArg(OBJCOPY_target) &&
456 (InputArgs.hasArg(OBJCOPY_input_target) ||
457 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000458 return createStringError(
459 errc::invalid_argument,
460 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000461
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000462 bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000463 StringRef InputFormat, OutputFormat;
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000464 if (InputArgs.hasArg(OBJCOPY_target)) {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000465 InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
466 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000467 } else {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000468 InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
469 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000470 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000471
472 // FIXME: Currently, we ignore the target for non-binary/ihex formats
473 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
474 // format by llvm::object::createBinary regardless of the option value.
475 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
476 .Case("binary", FileFormat::Binary)
477 .Case("ihex", FileFormat::IHex)
478 .Default(FileFormat::Unspecified);
479 if (Config.InputFormat == FileFormat::Binary) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000480 auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
481 if (BinaryArch.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000482 return createStringError(
483 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000484 "specified binary input without specifiying an architecture");
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000485 Expected<const MachineInfo &> MI = getMachineInfo(BinaryArch);
486 if (!MI)
487 return MI.takeError();
488 Config.BinaryArch = *MI;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000489 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000490
491 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
492 .Case("binary", FileFormat::Binary)
493 .Case("ihex", FileFormat::IHex)
494 .Default(FileFormat::Unspecified);
495 if (Config.OutputFormat == FileFormat::Unspecified && !OutputFormat.empty()) {
496 Expected<TargetInfo> Target = getOutputTargetInfoByTargetName(OutputFormat);
497 if (!Target)
498 return Target.takeError();
499 Config.OutputFormat = Target->Format;
500 Config.OutputArch = Target->Machine;
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000501 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000502
503 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
504 OBJCOPY_compress_debug_sections_eq)) {
505 Config.CompressionType = DebugCompressionType::Z;
506
507 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
508 Config.CompressionType =
509 StringSwitch<DebugCompressionType>(
510 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
511 .Case("zlib-gnu", DebugCompressionType::GNU)
512 .Case("zlib", DebugCompressionType::Z)
513 .Default(DebugCompressionType::None);
514 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000515 return createStringError(
516 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000517 "invalid or unsupported --compress-debug-sections format: %s",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000518 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
519 .str()
520 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000521 }
George Rimar1e930802019-03-05 11:32:14 +0000522 if (!zlib::isAvailable())
523 return createStringError(
524 errc::invalid_argument,
525 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000526 }
527
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000528 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000529 // The gnu_debuglink's target is expected to not change or else its CRC would
530 // become invalidated and get rejected. We can avoid recalculating the
531 // checksum for every target file inside an archive by precomputing the CRC
532 // here. This prevents a significant amount of I/O.
533 if (!Config.AddGnuDebugLink.empty()) {
534 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
535 if (!DebugOrErr)
536 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
537 auto Debug = std::move(*DebugOrErr);
538 JamCRC CRC;
539 CRC.update(
540 ArrayRef<char>(Debug->getBuffer().data(), Debug->getBuffer().size()));
541 // The CRC32 value needs to be complemented because the JamCRC doesn't
542 // finalize the CRC32 value.
543 Config.GnuDebugLinkCRC32 = ~CRC.getCRC();
544 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000545 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
546 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
547 Config.BuildIdLinkInput =
548 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
549 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
550 Config.BuildIdLinkOutput =
551 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
552 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000553 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000554 Config.AllocSectionsPrefix =
555 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000556 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
557 Config.ExtractPartition = Arg->getValue();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000558
559 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
560 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000561 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000562 "bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000563 auto Old2New = StringRef(Arg->getValue()).split('=');
564 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000565 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000566 "multiple redefinition of symbol '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000567 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000568 }
569
Eugene Leviant340cb872019-02-08 10:33:16 +0000570 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
571 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
572 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000573 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000574
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000575 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000576 Expected<SectionRename> SR =
577 parseRenameSectionValue(StringRef(Arg->getValue()));
578 if (!SR)
579 return SR.takeError();
580 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
581 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000582 "multiple renames of section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000583 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000584 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000585 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000586 Expected<SectionFlagsUpdate> SFU =
587 parseSetSectionFlagValue(Arg->getValue());
588 if (!SFU)
589 return SFU.takeError();
590 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
591 return createStringError(
592 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000593 "--set-section-flags set multiple times for section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000594 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000595 }
596 // Prohibit combinations of --set-section-flags when the section name is used
597 // by --rename-section, either as a source or a destination.
598 for (const auto &E : Config.SectionsToRename) {
599 const SectionRename &SR = E.second;
600 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000601 return createStringError(
602 errc::invalid_argument,
603 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
604 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
605 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000606 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000607 return createStringError(
608 errc::invalid_argument,
609 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
610 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
611 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000612 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000613
614 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000615 Config.ToRemove.emplace_back(Arg->getValue(), UseRegex);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000616 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000617 Config.KeepSection.emplace_back(Arg->getValue(), UseRegex);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000618 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000619 Config.OnlySection.emplace_back(Arg->getValue(), UseRegex);
Sergey Dmitriev899bdaa2019-07-29 16:22:40 +0000620 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
621 StringRef ArgValue(Arg->getValue());
622 if (!ArgValue.contains('='))
623 return createStringError(errc::invalid_argument,
624 "bad format for --add-section: missing '='");
625 if (ArgValue.split("=").second.empty())
626 return createStringError(
627 errc::invalid_argument,
628 "bad format for --add-section: missing file name");
629 Config.AddSection.push_back(ArgValue);
630 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000631 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
632 Config.DumpSection.push_back(Arg->getValue());
633 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
634 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
635 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
636 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
637 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
638 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
639 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
640 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000641 Config.ExtractMainPartition =
642 InputArgs.hasArg(OBJCOPY_extract_main_partition);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000643 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
644 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000645 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
646 Config.DiscardMode =
647 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
648 ? DiscardType::All
649 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000650 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
651 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
652 Config.DecompressDebugSections =
653 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000654 if (Config.DiscardMode == DiscardType::All)
655 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000656 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000657 Config.SymbolsToLocalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000658 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000659 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
660 Arg->getValue(), UseRegex))
661 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000662 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000663 Config.SymbolsToKeepGlobal.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000664 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000665 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
666 Arg->getValue(), UseRegex))
667 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000668 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000669 Config.SymbolsToGlobalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000670 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000671 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
672 Arg->getValue(), UseRegex))
673 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000674 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000675 Config.SymbolsToWeaken.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000676 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000677 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
678 Arg->getValue(), UseRegex))
679 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000680 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000681 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000682 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000683 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
684 Arg->getValue(), UseRegex))
685 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000686 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
687 Config.UnneededSymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
688 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000689 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
690 Arg->getValue(), UseRegex))
691 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000692 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000693 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegex);
Yi Kongf2baddb2019-04-01 18:12:43 +0000694 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
695 if (Error E = addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc,
696 Arg->getValue(), UseRegex))
697 return std::move(E);
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000698 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
699 Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(Arg->getValue());
700 if (!NSI)
701 return NSI.takeError();
702 Config.SymbolsToAdd.push_back(*NSI);
703 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000704
James Henderson66a9d0f2019-04-18 09:13:30 +0000705 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
706
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000707 Config.DeterministicArchives = InputArgs.hasFlag(
708 OBJCOPY_enable_deterministic_archives,
709 OBJCOPY_disable_deterministic_archives, /*default=*/true);
710
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000711 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
712
Alex Brachet899a3072019-06-15 05:32:23 +0000713 if (Config.PreserveDates &&
714 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
715 return createStringError(errc::invalid_argument,
716 "--preserve-dates requires a file");
717
Eugene Leviant53350d02019-02-26 09:24:22 +0000718 for (auto Arg : InputArgs)
719 if (Arg->getOption().matches(OBJCOPY_set_start)) {
720 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
721 if (!EAddr)
722 return createStringError(
723 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
724
725 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
726 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
727 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
728 if (!EIncr)
729 return createStringError(EIncr.getError(),
730 "bad entry point increment: '%s'",
731 Arg->getValue());
732 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
733 : [](uint64_t A) { return A; };
734 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
735 return Expr(EAddr) + *EIncr;
736 };
737 }
738
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000739 if (Config.DecompressDebugSections &&
740 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000741 return createStringError(
742 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000743 "cannot specify both --compress-debug-sections and "
744 "--decompress-debug-sections");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000745 }
746
747 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000748 return createStringError(
749 errc::invalid_argument,
750 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000751
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000752 if (Config.ExtractPartition && Config.ExtractMainPartition)
753 return createStringError(errc::invalid_argument,
754 "cannot specify --extract-partition together with "
755 "--extract-main-partition");
756
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000757 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000758 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000759}
760
761// ParseStripOptions returns the config and sets the input arguments. If a
762// help flag is set then ParseStripOptions will print the help messege and
763// exit.
Alex Brachet77477002019-06-18 00:39:10 +0000764Expected<DriverConfig>
765parseStripOptions(ArrayRef<const char *> ArgsArr,
766 std::function<Error(Error)> ErrorCallback) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000767 StripOptTable T;
768 unsigned MissingArgumentIndex, MissingArgumentCount;
769 llvm::opt::InputArgList InputArgs =
770 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
771
772 if (InputArgs.size() == 0) {
773 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
774 exit(1);
775 }
776
777 if (InputArgs.hasArg(STRIP_help)) {
778 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
779 exit(0);
780 }
781
782 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000783 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000784 cl::PrintVersionMessage();
785 exit(0);
786 }
787
Alex Brachet899a3072019-06-15 05:32:23 +0000788 SmallVector<StringRef, 2> Positional;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000789 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000790 return createStringError(errc::invalid_argument, "unknown argument '%s'",
791 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000792 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
793 Positional.push_back(Arg->getValue());
794
795 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000796 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000797
798 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000799 return createStringError(
800 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000801 "multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000802
803 CopyConfig Config;
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000804 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
James Henderson66a9d0f2019-04-18 09:13:30 +0000805 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000806 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
807
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000808 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
809 Config.DiscardMode =
810 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
811 ? DiscardType::All
812 : DiscardType::Locals;
Wolfgang Piebab751a72019-08-08 00:35:16 +0000813 Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000814 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000815 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
816 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000817 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000818 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000819 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000820
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000821 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000822 Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000823
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000824 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000825 Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000826
Eugene Leviant2267c582019-01-31 12:16:20 +0000827 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000828 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
Eugene Leviant2267c582019-01-31 12:16:20 +0000829
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000830 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000831 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000832
James Hendersone4a89a12019-05-02 11:53:02 +0000833 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
834 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
835 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000836 Config.StripAll = true;
837
Sid Manning5ad18a72019-05-03 14:14:01 +0000838 if (Config.DiscardMode == DiscardType::All)
839 Config.StripDebug = true;
840
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000841 Config.DeterministicArchives =
842 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
843 STRIP_disable_deterministic_archives, /*default=*/true);
844
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000845 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000846 Config.InputFormat = FileFormat::Unspecified;
847 Config.OutputFormat = FileFormat::Unspecified;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000848
849 DriverConfig DC;
850 if (Positional.size() == 1) {
851 Config.InputFilename = Positional[0];
852 Config.OutputFilename =
853 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
854 DC.CopyConfigs.push_back(std::move(Config));
855 } else {
Alex Brachet77477002019-06-18 00:39:10 +0000856 StringMap<unsigned> InputFiles;
Alex Brachet899a3072019-06-15 05:32:23 +0000857 for (StringRef Filename : Positional) {
Alex Brachet77477002019-06-18 00:39:10 +0000858 if (InputFiles[Filename]++ == 1) {
859 if (Filename == "-")
860 return createStringError(
861 errc::invalid_argument,
862 "cannot specify '-' as an input file more than once");
863 if (Error E = ErrorCallback(createStringError(
864 errc::invalid_argument, "'%s' was already specified",
865 Filename.str().c_str())))
866 return std::move(E);
867 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000868 Config.InputFilename = Filename;
869 Config.OutputFilename = Filename;
870 DC.CopyConfigs.push_back(Config);
871 }
872 }
873
Alex Brachet899a3072019-06-15 05:32:23 +0000874 if (Config.PreserveDates && (is_contained(Positional, "-") ||
875 InputArgs.getLastArgValue(STRIP_output) == "-"))
876 return createStringError(errc::invalid_argument,
877 "--preserve-dates requires a file");
878
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000879 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000880}
881
882} // namespace objcopy
883} // namespace llvm