blob: 9591e5aeb77e50c01f98e2af939dad8e9de42234 [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
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000180static Expected<NewSymbolInfo> parseNewSymbolInfo(StringRef FlagValue,
181 uint8_t DefaultVisibility) {
Eugene Leviant51c1f642019-02-25 14:12:41 +0000182 // Parse value given with --add-symbol option and create the
183 // new symbol if possible. The value format for --add-symbol is:
184 //
185 // <name>=[<section>:]<value>[,<flags>]
186 //
187 // where:
188 // <name> - symbol name, can be empty string
189 // <section> - optional section name. If not given ABS symbol is created
190 // <value> - symbol value, can be decimal or hexadecimal number prefixed
191 // with 0x.
192 // <flags> - optional flags affecting symbol type, binding or visibility:
193 // The following are currently supported:
194 //
195 // global, local, weak, default, hidden, file, section, object,
196 // indirect-function.
197 //
198 // The following flags are ignored and provided for GNU
199 // compatibility only:
200 //
201 // warning, debug, constructor, indirect, synthetic,
202 // unique-object, before=<symbol>.
203 NewSymbolInfo SI;
204 StringRef Value;
205 std::tie(SI.SymbolName, Value) = FlagValue.split('=');
206 if (Value.empty())
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000207 return createStringError(
208 errc::invalid_argument,
209 "bad format for --add-symbol, missing '=' after '%s'",
210 SI.SymbolName.str().c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000211
212 if (Value.contains(':')) {
213 std::tie(SI.SectionName, Value) = Value.split(':');
214 if (SI.SectionName.empty() || Value.empty())
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000215 return createStringError(
216 errc::invalid_argument,
Eugene Leviant51c1f642019-02-25 14:12:41 +0000217 "bad format for --add-symbol, missing section name or symbol value");
218 }
219
220 SmallVector<StringRef, 6> Flags;
221 Value.split(Flags, ',');
222 if (Flags[0].getAsInteger(0, SI.Value))
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000223 return createStringError(errc::invalid_argument, "bad symbol value: '%s'",
224 Flags[0].str().c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000225
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000226 SI.Visibility = DefaultVisibility;
227
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000228 using Functor = std::function<void(void)>;
229 SmallVector<StringRef, 6> UnsupportedFlags;
230 for (size_t I = 1, NumFlags = Flags.size(); I < NumFlags; ++I)
Eugene Leviant51c1f642019-02-25 14:12:41 +0000231 static_cast<Functor>(
232 StringSwitch<Functor>(Flags[I])
233 .CaseLower("global", [&SI] { SI.Bind = ELF::STB_GLOBAL; })
234 .CaseLower("local", [&SI] { SI.Bind = ELF::STB_LOCAL; })
235 .CaseLower("weak", [&SI] { SI.Bind = ELF::STB_WEAK; })
236 .CaseLower("default", [&SI] { SI.Visibility = ELF::STV_DEFAULT; })
237 .CaseLower("hidden", [&SI] { SI.Visibility = ELF::STV_HIDDEN; })
Chris Jacksone5cdfbc2019-08-15 09:45:09 +0000238 .CaseLower("protected", [&SI] { SI.Visibility = ELF::STV_PROTECTED; })
Eugene Leviant51c1f642019-02-25 14:12:41 +0000239 .CaseLower("file", [&SI] { SI.Type = ELF::STT_FILE; })
240 .CaseLower("section", [&SI] { SI.Type = ELF::STT_SECTION; })
241 .CaseLower("object", [&SI] { SI.Type = ELF::STT_OBJECT; })
242 .CaseLower("function", [&SI] { SI.Type = ELF::STT_FUNC; })
243 .CaseLower("indirect-function",
244 [&SI] { SI.Type = ELF::STT_GNU_IFUNC; })
245 .CaseLower("debug", [] {})
246 .CaseLower("constructor", [] {})
247 .CaseLower("warning", [] {})
248 .CaseLower("indirect", [] {})
249 .CaseLower("synthetic", [] {})
250 .CaseLower("unique-object", [] {})
251 .StartsWithLower("before", [] {})
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000252 .Default([&] { UnsupportedFlags.push_back(Flags[I]); }))();
253 if (!UnsupportedFlags.empty())
254 return createStringError(errc::invalid_argument,
255 "unsupported flag%s for --add-symbol: '%s'",
256 UnsupportedFlags.size() > 1 ? "s" : "",
257 join(UnsupportedFlags, "', '").c_str());
Eugene Leviant51c1f642019-02-25 14:12:41 +0000258 return SI;
259}
260
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000261static const StringMap<MachineInfo> ArchMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000262 // Name, {EMachine, 64bit, LittleEndian}
263 {"aarch64", {ELF::EM_AARCH64, true, true}},
264 {"arm", {ELF::EM_ARM, false, true}},
265 {"i386", {ELF::EM_386, false, true}},
266 {"i386:x86-64", {ELF::EM_X86_64, true, true}},
Jordan Rupprecht2b329022019-04-18 14:22:37 +0000267 {"mips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000268 {"powerpc:common64", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000269 {"riscv:rv32", {ELF::EM_RISCV, false, true}},
270 {"riscv:rv64", {ELF::EM_RISCV, true, true}},
Seiya Nutab1027a42019-06-13 23:24:12 +0000271 {"sparc", {ELF::EM_SPARC, false, false}},
272 {"sparcel", {ELF::EM_SPARC, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000273 {"x86-64", {ELF::EM_X86_64, true, true}},
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000274};
275
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000276static Expected<const MachineInfo &> getMachineInfo(StringRef Arch) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000277 auto Iter = ArchMap.find(Arch);
278 if (Iter == std::end(ArchMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000279 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000280 "invalid architecture: '%s'", Arch.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000281 return Iter->getValue();
282}
283
Seiya Nutaecb60b72019-07-05 05:28:38 +0000284struct TargetInfo {
285 FileFormat Format;
286 MachineInfo Machine;
287};
288
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000289// FIXME: consolidate with the bfd parsing used by lld.
Seiya Nutaecb60b72019-07-05 05:28:38 +0000290static const StringMap<MachineInfo> TargetMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000291 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000292 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000293 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000294 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000295 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
296 // Intel MCU
297 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
298 // ARM
299 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
300 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000301 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
302 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000303 // RISC-V
304 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
305 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
306 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000307 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
308 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
309 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
310 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000311 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000312 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
313 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000314 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000315 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
316 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000317 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
318 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Seiya Nuta13de1742019-06-17 02:03:45 +0000319 // SPARC
320 {"elf32-sparc", {ELF::EM_SPARC, false, false}},
321 {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000322};
323
Seiya Nutaecb60b72019-07-05 05:28:38 +0000324static Expected<TargetInfo>
325getOutputTargetInfoByTargetName(StringRef TargetName) {
326 StringRef OriginalTargetName = TargetName;
327 bool IsFreeBSD = TargetName.consume_back("-freebsd");
328 auto Iter = TargetMap.find(TargetName);
329 if (Iter == std::end(TargetMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000330 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000331 "invalid output format: '%s'",
Seiya Nutaecb60b72019-07-05 05:28:38 +0000332 OriginalTargetName.str().c_str());
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000333 MachineInfo MI = Iter->getValue();
334 if (IsFreeBSD)
335 MI.OSABI = ELF::ELFOSABI_FREEBSD;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000336
337 FileFormat Format;
338 if (TargetName.startswith("elf"))
339 Format = FileFormat::ELF;
340 else
341 // This should never happen because `TargetName` is valid (it certainly
342 // exists in the TargetMap).
343 llvm_unreachable("unknown target prefix");
344
345 return {TargetInfo{Format, MI}};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000346}
347
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000348static Error addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
349 StringRef Filename, bool UseRegex) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000350 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000351 SmallVector<StringRef, 16> Lines;
352 auto BufOrErr = MemoryBuffer::getFile(Filename);
353 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000354 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000355
356 BufOrErr.get()->getBuffer().split(Lines, '\n');
357 for (StringRef Line : Lines) {
358 // Ignore everything after '#', trim whitespace, and only add the symbol if
359 // it's not empty.
360 auto TrimmedLine = Line.split('#').first.trim();
361 if (!TrimmedLine.empty())
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000362 Symbols.addMatcher({Saver.save(TrimmedLine), UseRegex});
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000363 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000364
365 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000366}
367
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000368NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
369 if (!IsRegex) {
370 Name = Pattern;
371 return;
372 }
373
374 SmallVector<char, 32> Data;
375 R = std::make_shared<Regex>(
376 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
377}
378
Eugene Leviant340cb872019-02-08 10:33:16 +0000379static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
380 BumpPtrAllocator &Alloc,
381 StringRef Filename) {
382 StringSaver Saver(Alloc);
383 SmallVector<StringRef, 16> Lines;
384 auto BufOrErr = MemoryBuffer::getFile(Filename);
385 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000386 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000387
388 BufOrErr.get()->getBuffer().split(Lines, '\n');
389 size_t NumLines = Lines.size();
390 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
391 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
392 if (TrimmedLine.empty())
393 continue;
394
395 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
396 StringRef NewName = Pair.second.trim();
397 if (NewName.empty())
398 return createStringError(errc::invalid_argument,
399 "%s:%zu: missing new symbol name",
400 Filename.str().c_str(), LineNo + 1);
401 SymbolsToRename.insert({Pair.first, NewName});
402 }
403 return Error::success();
404}
Eugene Leviant53350d02019-02-26 09:24:22 +0000405
406template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
407 T Result;
408 if (Val.getAsInteger(0, Result))
409 return errc::invalid_argument;
410 return Result;
411}
412
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000413// ParseObjcopyOptions returns the config and sets the input arguments. If a
414// help flag is set then ParseObjcopyOptions will print the help messege and
415// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000416Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000417 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000418 ObjcopyOptTable T;
419 unsigned MissingArgumentIndex, MissingArgumentCount;
420 llvm::opt::InputArgList InputArgs =
421 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
422
423 if (InputArgs.size() == 0) {
424 T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
425 exit(1);
426 }
427
428 if (InputArgs.hasArg(OBJCOPY_help)) {
429 T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
430 exit(0);
431 }
432
433 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000434 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000435 cl::PrintVersionMessage();
436 exit(0);
437 }
438
439 SmallVector<const char *, 2> Positional;
440
441 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000442 return createStringError(errc::invalid_argument, "unknown argument '%s'",
443 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000444
445 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
446 Positional.push_back(Arg->getValue());
447
448 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000449 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000450
451 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000452 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000453 "too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000454
455 CopyConfig Config;
456 Config.InputFilename = Positional[0];
457 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000458 if (InputArgs.hasArg(OBJCOPY_target) &&
459 (InputArgs.hasArg(OBJCOPY_input_target) ||
460 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000461 return createStringError(
462 errc::invalid_argument,
463 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000464
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000465 bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000466 StringRef InputFormat, OutputFormat;
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000467 if (InputArgs.hasArg(OBJCOPY_target)) {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000468 InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
469 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000470 } else {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000471 InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
472 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000473 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000474
475 // FIXME: Currently, we ignore the target for non-binary/ihex formats
476 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
477 // format by llvm::object::createBinary regardless of the option value.
478 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
479 .Case("binary", FileFormat::Binary)
480 .Case("ihex", FileFormat::IHex)
481 .Default(FileFormat::Unspecified);
482 if (Config.InputFormat == FileFormat::Binary) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000483 auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
484 if (BinaryArch.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000485 return createStringError(
486 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000487 "specified binary input without specifiying an architecture");
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000488 Expected<const MachineInfo &> MI = getMachineInfo(BinaryArch);
489 if (!MI)
490 return MI.takeError();
491 Config.BinaryArch = *MI;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000492 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000493
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000494 if (opt::Arg *A = InputArgs.getLastArg(OBJCOPY_new_symbol_visibility)) {
495 const uint8_t Invalid = 0xff;
496 Config.NewSymbolVisibility = StringSwitch<uint8_t>(A->getValue())
497 .Case("default", ELF::STV_DEFAULT)
498 .Case("hidden", ELF::STV_HIDDEN)
499 .Case("internal", ELF::STV_INTERNAL)
500 .Case("protected", ELF::STV_PROTECTED)
501 .Default(Invalid);
502
503 if (Config.NewSymbolVisibility == Invalid)
504 return createStringError(
505 errc::invalid_argument, "'%s' is not a valid symbol visibility",
506 InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility).str().c_str());
507 }
508
Seiya Nutaecb60b72019-07-05 05:28:38 +0000509 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
510 .Case("binary", FileFormat::Binary)
511 .Case("ihex", FileFormat::IHex)
512 .Default(FileFormat::Unspecified);
513 if (Config.OutputFormat == FileFormat::Unspecified && !OutputFormat.empty()) {
514 Expected<TargetInfo> Target = getOutputTargetInfoByTargetName(OutputFormat);
515 if (!Target)
516 return Target.takeError();
517 Config.OutputFormat = Target->Format;
518 Config.OutputArch = Target->Machine;
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000519 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000520
521 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
522 OBJCOPY_compress_debug_sections_eq)) {
523 Config.CompressionType = DebugCompressionType::Z;
524
525 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
526 Config.CompressionType =
527 StringSwitch<DebugCompressionType>(
528 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
529 .Case("zlib-gnu", DebugCompressionType::GNU)
530 .Case("zlib", DebugCompressionType::Z)
531 .Default(DebugCompressionType::None);
532 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000533 return createStringError(
534 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000535 "invalid or unsupported --compress-debug-sections format: %s",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000536 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
537 .str()
538 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000539 }
George Rimar1e930802019-03-05 11:32:14 +0000540 if (!zlib::isAvailable())
541 return createStringError(
542 errc::invalid_argument,
543 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000544 }
545
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000546 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000547 // The gnu_debuglink's target is expected to not change or else its CRC would
548 // become invalidated and get rejected. We can avoid recalculating the
549 // checksum for every target file inside an archive by precomputing the CRC
550 // here. This prevents a significant amount of I/O.
551 if (!Config.AddGnuDebugLink.empty()) {
552 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
553 if (!DebugOrErr)
554 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
555 auto Debug = std::move(*DebugOrErr);
556 JamCRC CRC;
557 CRC.update(
558 ArrayRef<char>(Debug->getBuffer().data(), Debug->getBuffer().size()));
559 // The CRC32 value needs to be complemented because the JamCRC doesn't
560 // finalize the CRC32 value.
561 Config.GnuDebugLinkCRC32 = ~CRC.getCRC();
562 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000563 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
564 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
565 Config.BuildIdLinkInput =
566 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
567 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
568 Config.BuildIdLinkOutput =
569 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
570 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000571 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000572 Config.AllocSectionsPrefix =
573 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000574 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
575 Config.ExtractPartition = Arg->getValue();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000576
577 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
578 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000579 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000580 "bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000581 auto Old2New = StringRef(Arg->getValue()).split('=');
582 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000583 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000584 "multiple redefinition of symbol '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000585 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000586 }
587
Eugene Leviant340cb872019-02-08 10:33:16 +0000588 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
589 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
590 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000591 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000592
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000593 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000594 Expected<SectionRename> SR =
595 parseRenameSectionValue(StringRef(Arg->getValue()));
596 if (!SR)
597 return SR.takeError();
598 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
599 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000600 "multiple renames of section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000601 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000602 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000603 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000604 Expected<SectionFlagsUpdate> SFU =
605 parseSetSectionFlagValue(Arg->getValue());
606 if (!SFU)
607 return SFU.takeError();
608 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
609 return createStringError(
610 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000611 "--set-section-flags set multiple times for section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000612 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000613 }
614 // Prohibit combinations of --set-section-flags when the section name is used
615 // by --rename-section, either as a source or a destination.
616 for (const auto &E : Config.SectionsToRename) {
617 const SectionRename &SR = E.second;
618 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000619 return createStringError(
620 errc::invalid_argument,
621 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
622 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
623 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000624 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000625 return createStringError(
626 errc::invalid_argument,
627 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
628 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
629 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000630 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000631
632 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000633 Config.ToRemove.addMatcher({Arg->getValue(), UseRegex});
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000634 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000635 Config.KeepSection.addMatcher({Arg->getValue(), UseRegex});
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000636 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000637 Config.OnlySection.addMatcher({Arg->getValue(), UseRegex});
Sergey Dmitriev899bdaa2019-07-29 16:22:40 +0000638 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
639 StringRef ArgValue(Arg->getValue());
640 if (!ArgValue.contains('='))
641 return createStringError(errc::invalid_argument,
642 "bad format for --add-section: missing '='");
643 if (ArgValue.split("=").second.empty())
644 return createStringError(
645 errc::invalid_argument,
646 "bad format for --add-section: missing file name");
647 Config.AddSection.push_back(ArgValue);
648 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000649 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
650 Config.DumpSection.push_back(Arg->getValue());
651 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
652 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
653 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
654 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
655 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
656 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
657 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
658 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000659 Config.ExtractMainPartition =
660 InputArgs.hasArg(OBJCOPY_extract_main_partition);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000661 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
662 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000663 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
664 Config.DiscardMode =
665 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
666 ? DiscardType::All
667 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000668 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
669 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
670 Config.DecompressDebugSections =
671 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000672 if (Config.DiscardMode == DiscardType::All)
673 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000674 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000675 Config.SymbolsToLocalize.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviante08fe352019-02-08 14:37:54 +0000676 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000677 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, 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_keep_global_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000681 Config.SymbolsToKeepGlobal.addMatcher({Arg->getValue(), UseRegex});
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000682 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000683 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
684 Arg->getValue(), UseRegex))
685 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000686 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000687 Config.SymbolsToGlobalize.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviante08fe352019-02-08 14:37:54 +0000688 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000689 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, 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_weaken_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000693 Config.SymbolsToWeaken.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviante08fe352019-02-08 14:37:54 +0000694 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000695 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
696 Arg->getValue(), UseRegex))
697 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000698 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000699 Config.SymbolsToRemove.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviante08fe352019-02-08 14:37:54 +0000700 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000701 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
702 Arg->getValue(), UseRegex))
703 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000704 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000705 Config.UnneededSymbolsToRemove.addMatcher({Arg->getValue(), UseRegex});
Eugene Leviant2db10622019-02-13 07:34:54 +0000706 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000707 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
708 Arg->getValue(), UseRegex))
709 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000710 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000711 Config.SymbolsToKeep.addMatcher({Arg->getValue(), UseRegex});
Yi Kongf2baddb2019-04-01 18:12:43 +0000712 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
713 if (Error E = addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc,
714 Arg->getValue(), UseRegex))
715 return std::move(E);
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000716 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol)) {
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000717 Expected<NewSymbolInfo> NSI = parseNewSymbolInfo(
718 Arg->getValue(),
719 Config.NewSymbolVisibility.getValueOr(ELF::STV_DEFAULT));
Jordan Rupprecht42bc1e22019-03-13 22:26:01 +0000720 if (!NSI)
721 return NSI.takeError();
722 Config.SymbolsToAdd.push_back(*NSI);
723 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000724
James Henderson66a9d0f2019-04-18 09:13:30 +0000725 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
726
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000727 Config.DeterministicArchives = InputArgs.hasFlag(
728 OBJCOPY_enable_deterministic_archives,
729 OBJCOPY_disable_deterministic_archives, /*default=*/true);
730
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000731 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
732
Alex Brachet899a3072019-06-15 05:32:23 +0000733 if (Config.PreserveDates &&
734 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
735 return createStringError(errc::invalid_argument,
736 "--preserve-dates requires a file");
737
Eugene Leviant53350d02019-02-26 09:24:22 +0000738 for (auto Arg : InputArgs)
739 if (Arg->getOption().matches(OBJCOPY_set_start)) {
740 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
741 if (!EAddr)
742 return createStringError(
743 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
744
745 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
746 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
747 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
748 if (!EIncr)
749 return createStringError(EIncr.getError(),
750 "bad entry point increment: '%s'",
751 Arg->getValue());
752 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
753 : [](uint64_t A) { return A; };
754 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
755 return Expr(EAddr) + *EIncr;
756 };
757 }
758
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000759 if (Config.DecompressDebugSections &&
760 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000761 return createStringError(
762 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000763 "cannot specify both --compress-debug-sections and "
764 "--decompress-debug-sections");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000765 }
766
767 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000768 return createStringError(
769 errc::invalid_argument,
770 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000771
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000772 if (Config.ExtractPartition && Config.ExtractMainPartition)
773 return createStringError(errc::invalid_argument,
774 "cannot specify --extract-partition together with "
775 "--extract-main-partition");
776
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000777 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000778 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000779}
780
781// ParseStripOptions returns the config and sets the input arguments. If a
782// help flag is set then ParseStripOptions will print the help messege and
783// exit.
Alex Brachet77477002019-06-18 00:39:10 +0000784Expected<DriverConfig>
785parseStripOptions(ArrayRef<const char *> ArgsArr,
786 std::function<Error(Error)> ErrorCallback) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000787 StripOptTable T;
788 unsigned MissingArgumentIndex, MissingArgumentCount;
789 llvm::opt::InputArgList InputArgs =
790 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
791
792 if (InputArgs.size() == 0) {
793 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
794 exit(1);
795 }
796
797 if (InputArgs.hasArg(STRIP_help)) {
798 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
799 exit(0);
800 }
801
802 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000803 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000804 cl::PrintVersionMessage();
805 exit(0);
806 }
807
Alex Brachet899a3072019-06-15 05:32:23 +0000808 SmallVector<StringRef, 2> Positional;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000809 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000810 return createStringError(errc::invalid_argument, "unknown argument '%s'",
811 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000812 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
813 Positional.push_back(Arg->getValue());
814
815 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000816 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000817
818 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000819 return createStringError(
820 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000821 "multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000822
823 CopyConfig Config;
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000824 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
James Henderson66a9d0f2019-04-18 09:13:30 +0000825 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000826 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
827
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000828 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
829 Config.DiscardMode =
830 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
831 ? DiscardType::All
832 : DiscardType::Locals;
Wolfgang Piebab751a72019-08-08 00:35:16 +0000833 Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000834 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000835 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
836 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000837 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000838 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000839 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000840
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000841 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000842 Config.KeepSection.addMatcher({Arg->getValue(), UseRegexp});
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000843
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000844 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000845 Config.ToRemove.addMatcher({Arg->getValue(), UseRegexp});
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000846
Eugene Leviant2267c582019-01-31 12:16:20 +0000847 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000848 Config.SymbolsToRemove.addMatcher({Arg->getValue(), UseRegexp});
Eugene Leviant2267c582019-01-31 12:16:20 +0000849
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000850 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Jordan Rupprecht6c6dd6a2019-08-22 19:17:50 +0000851 Config.SymbolsToKeep.addMatcher({Arg->getValue(), UseRegexp});
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000852
James Hendersone4a89a12019-05-02 11:53:02 +0000853 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
854 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
855 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000856 Config.StripAll = true;
857
Sid Manning5ad18a72019-05-03 14:14:01 +0000858 if (Config.DiscardMode == DiscardType::All)
859 Config.StripDebug = true;
860
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000861 Config.DeterministicArchives =
862 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
863 STRIP_disable_deterministic_archives, /*default=*/true);
864
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000865 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000866 Config.InputFormat = FileFormat::Unspecified;
867 Config.OutputFormat = FileFormat::Unspecified;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000868
869 DriverConfig DC;
870 if (Positional.size() == 1) {
871 Config.InputFilename = Positional[0];
872 Config.OutputFilename =
873 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
874 DC.CopyConfigs.push_back(std::move(Config));
875 } else {
Alex Brachet77477002019-06-18 00:39:10 +0000876 StringMap<unsigned> InputFiles;
Alex Brachet899a3072019-06-15 05:32:23 +0000877 for (StringRef Filename : Positional) {
Alex Brachet77477002019-06-18 00:39:10 +0000878 if (InputFiles[Filename]++ == 1) {
879 if (Filename == "-")
880 return createStringError(
881 errc::invalid_argument,
882 "cannot specify '-' as an input file more than once");
883 if (Error E = ErrorCallback(createStringError(
884 errc::invalid_argument, "'%s' was already specified",
885 Filename.str().c_str())))
886 return std::move(E);
887 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000888 Config.InputFilename = Filename;
889 Config.OutputFilename = Filename;
890 DC.CopyConfigs.push_back(Config);
891 }
892 }
893
Alex Brachet899a3072019-06-15 05:32:23 +0000894 if (Config.PreserveDates && (is_contained(Positional, "-") ||
895 InputArgs.getLastArgValue(STRIP_output) == "-"))
896 return createStringError(errc::invalid_argument,
897 "--preserve-dates requires a file");
898
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000899 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000900}
901
902} // namespace objcopy
903} // namespace llvm