blob: 73ed00b5cb2ab07307dda52dcc9eaa8ae2d818ed [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"
Hans Wennborg1e1e3ba2019-10-09 09:06:30 +000017#include "llvm/Support/CRC.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000018#include "llvm/Support/CommandLine.h"
19#include "llvm/Support/Compression.h"
Eugene Leviant340cb872019-02-08 10:33:16 +000020#include "llvm/Support/Errc.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
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -080066enum InstallNameToolID {
67 INSTALL_NAME_TOOL_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 INSTALL_NAME_TOOL_##ID,
71#include "InstallNameToolOpts.inc"
72#undef OPTION
73};
74
75#define PREFIX(NAME, VALUE) \
76 const char *const INSTALL_NAME_TOOL_##NAME[] = VALUE;
77#include "InstallNameToolOpts.inc"
78#undef PREFIX
79
80static const opt::OptTable::Info InstallNameToolInfoTable[] = {
81#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
82 HELPTEXT, METAVAR, VALUES) \
83 {INSTALL_NAME_TOOL_##PREFIX, \
84 NAME, \
85 HELPTEXT, \
86 METAVAR, \
87 INSTALL_NAME_TOOL_##ID, \
88 opt::Option::KIND##Class, \
89 PARAM, \
90 FLAGS, \
91 INSTALL_NAME_TOOL_##GROUP, \
92 INSTALL_NAME_TOOL_##ALIAS, \
93 ALIASARGS, \
94 VALUES},
95#include "InstallNameToolOpts.inc"
96#undef OPTION
97};
98
99class InstallNameToolOptTable : public opt::OptTable {
100public:
101 InstallNameToolOptTable() : OptTable(InstallNameToolInfoTable) {}
102};
103
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000104enum StripID {
105 STRIP_INVALID = 0, // This is not an option ID.
106#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
107 HELPTEXT, METAVAR, VALUES) \
108 STRIP_##ID,
109#include "StripOpts.inc"
110#undef OPTION
111};
112
113#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
114#include "StripOpts.inc"
115#undef PREFIX
116
117static const opt::OptTable::Info StripInfoTable[] = {
118#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
119 HELPTEXT, METAVAR, VALUES) \
120 {STRIP_##PREFIX, NAME, HELPTEXT, \
121 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
122 PARAM, FLAGS, STRIP_##GROUP, \
123 STRIP_##ALIAS, ALIASARGS, VALUES},
124#include "StripOpts.inc"
125#undef OPTION
126};
127
128class StripOptTable : public opt::OptTable {
129public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +0000130 StripOptTable() : OptTable(StripInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000131};
132
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000133} // namespace
134
135static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
136 return llvm::StringSwitch<SectionFlag>(SectionName)
James Hendersond931cf32019-04-03 14:40:27 +0000137 .CaseLower("alloc", SectionFlag::SecAlloc)
138 .CaseLower("load", SectionFlag::SecLoad)
139 .CaseLower("noload", SectionFlag::SecNoload)
140 .CaseLower("readonly", SectionFlag::SecReadonly)
141 .CaseLower("debug", SectionFlag::SecDebug)
142 .CaseLower("code", SectionFlag::SecCode)
143 .CaseLower("data", SectionFlag::SecData)
144 .CaseLower("rom", SectionFlag::SecRom)
145 .CaseLower("merge", SectionFlag::SecMerge)
146 .CaseLower("strings", SectionFlag::SecStrings)
147 .CaseLower("contents", SectionFlag::SecContents)
148 .CaseLower("share", SectionFlag::SecShare)
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000149 .Default(SectionFlag::SecNone);
150}
151
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000152static Expected<SectionFlag>
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000153parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000154 SectionFlag ParsedFlags = SectionFlag::SecNone;
155 for (StringRef Flag : SectionFlags) {
156 SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
157 if (ParsedFlag == SectionFlag::SecNone)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000158 return createStringError(
159 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000160 "unrecognized section flag '%s'. Flags supported for GNU "
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000161 "compatibility: alloc, load, noload, readonly, debug, code, data, "
162 "rom, share, contents, merge, strings",
163 Flag.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000164 ParsedFlags |= ParsedFlag;
165 }
166
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000167 return ParsedFlags;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000168}
169
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000170static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000171 if (!FlagValue.contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000172 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000173 "bad format for --rename-section: missing '='");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000174
175 // Initial split: ".foo" = ".bar,f1,f2,..."
176 auto Old2New = FlagValue.split('=');
177 SectionRename SR;
178 SR.OriginalName = Old2New.first;
179
180 // Flags split: ".bar" "f1" "f2" ...
181 SmallVector<StringRef, 6> NameAndFlags;
182 Old2New.second.split(NameAndFlags, ',');
183 SR.NewName = NameAndFlags[0];
184
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000185 if (NameAndFlags.size() > 1) {
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000186 Expected<SectionFlag> ParsedFlagSet =
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000187 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
188 if (!ParsedFlagSet)
189 return ParsedFlagSet.takeError();
190 SR.NewFlags = *ParsedFlagSet;
191 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000192
193 return SR;
194}
195
Fangrui Song671fb342019-10-02 12:41:25 +0000196static Expected<std::pair<StringRef, uint64_t>>
197parseSetSectionAlignment(StringRef FlagValue) {
198 if (!FlagValue.contains('='))
199 return createStringError(
200 errc::invalid_argument,
201 "bad format for --set-section-alignment: missing '='");
202 auto Split = StringRef(FlagValue).split('=');
203 if (Split.first.empty())
204 return createStringError(
205 errc::invalid_argument,
206 "bad format for --set-section-alignment: missing section name");
207 uint64_t NewAlign;
208 if (Split.second.getAsInteger(0, NewAlign))
209 return createStringError(errc::invalid_argument,
210 "invalid alignment for --set-section-alignment: '%s'",
211 Split.second.str().c_str());
212 return std::make_pair(Split.first, NewAlign);
213}
214
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000215static Expected<SectionFlagsUpdate>
216parseSetSectionFlagValue(StringRef FlagValue) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000217 if (!StringRef(FlagValue).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000218 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000219 "bad format for --set-section-flags: missing '='");
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000220
221 // Initial split: ".foo" = "f1,f2,..."
222 auto Section2Flags = StringRef(FlagValue).split('=');
223 SectionFlagsUpdate SFU;
224 SFU.Name = Section2Flags.first;
225
226 // Flags split: "f1" "f2" ...
227 SmallVector<StringRef, 6> SectionFlags;
228 Section2Flags.second.split(SectionFlags, ',');
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000229 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000230 if (!ParsedFlagSet)
231 return ParsedFlagSet.takeError();
232 SFU.NewFlags = *ParsedFlagSet;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000233
234 return SFU;
235}
236
Seiya Nutaecb60b72019-07-05 05:28:38 +0000237struct TargetInfo {
238 FileFormat Format;
239 MachineInfo Machine;
240};
241
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000242// FIXME: consolidate with the bfd parsing used by lld.
Seiya Nutaecb60b72019-07-05 05:28:38 +0000243static const StringMap<MachineInfo> TargetMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000244 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000245 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000246 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000247 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000248 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
249 // Intel MCU
250 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
251 // ARM
252 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
253 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000254 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
255 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000256 // RISC-V
257 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
258 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
259 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000260 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
261 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
262 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
263 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000264 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000265 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
266 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000267 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000268 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
269 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000270 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
271 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Seiya Nuta13de1742019-06-17 02:03:45 +0000272 // SPARC
273 {"elf32-sparc", {ELF::EM_SPARC, false, false}},
274 {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000275};
276
Seiya Nutaecb60b72019-07-05 05:28:38 +0000277static Expected<TargetInfo>
278getOutputTargetInfoByTargetName(StringRef TargetName) {
279 StringRef OriginalTargetName = TargetName;
280 bool IsFreeBSD = TargetName.consume_back("-freebsd");
281 auto Iter = TargetMap.find(TargetName);
282 if (Iter == std::end(TargetMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000283 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000284 "invalid output format: '%s'",
Seiya Nutaecb60b72019-07-05 05:28:38 +0000285 OriginalTargetName.str().c_str());
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000286 MachineInfo MI = Iter->getValue();
287 if (IsFreeBSD)
288 MI.OSABI = ELF::ELFOSABI_FREEBSD;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000289
290 FileFormat Format;
291 if (TargetName.startswith("elf"))
292 Format = FileFormat::ELF;
293 else
294 // This should never happen because `TargetName` is valid (it certainly
295 // exists in the TargetMap).
296 llvm_unreachable("unknown target prefix");
297
298 return {TargetInfo{Format, MI}};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000299}
300
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000301static Error
302addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
303 StringRef Filename, MatchStyle MS,
304 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000305 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000306 SmallVector<StringRef, 16> Lines;
307 auto BufOrErr = MemoryBuffer::getFile(Filename);
308 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000309 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000310
311 BufOrErr.get()->getBuffer().split(Lines, '\n');
312 for (StringRef Line : Lines) {
313 // Ignore everything after '#', trim whitespace, and only add the symbol if
314 // it's not empty.
315 auto TrimmedLine = Line.split('#').first.trim();
316 if (!TrimmedLine.empty())
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000317 if (Error E = Symbols.addMatcher(NameOrPattern::create(
318 Saver.save(TrimmedLine), MS, ErrorCallback)))
319 return E;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000320 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000321
322 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000323}
324
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000325Expected<NameOrPattern>
326NameOrPattern::create(StringRef Pattern, MatchStyle MS,
327 llvm::function_ref<Error(Error)> ErrorCallback) {
328 switch (MS) {
329 case MatchStyle::Literal:
330 return NameOrPattern(Pattern);
331 case MatchStyle::Wildcard: {
332 SmallVector<char, 32> Data;
333 bool IsPositiveMatch = true;
334 if (Pattern[0] == '!') {
335 IsPositiveMatch = false;
336 Pattern = Pattern.drop_front();
337 }
338 Expected<GlobPattern> GlobOrErr = GlobPattern::create(Pattern);
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000339
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000340 // If we couldn't create it as a glob, report the error, but try again with
341 // a literal if the error reporting is non-fatal.
342 if (!GlobOrErr) {
343 if (Error E = ErrorCallback(GlobOrErr.takeError()))
344 return std::move(E);
345 return create(Pattern, MatchStyle::Literal, ErrorCallback);
346 }
347
348 return NameOrPattern(std::make_shared<GlobPattern>(*GlobOrErr),
349 IsPositiveMatch);
350 }
351 case MatchStyle::Regex: {
352 SmallVector<char, 32> Data;
353 return NameOrPattern(std::make_shared<Regex>(
354 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data)));
355 }
356 }
Simon Pilgrim3bd61b22019-10-18 09:59:40 +0000357 llvm_unreachable("Unhandled llvm.objcopy.MatchStyle enum");
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000358}
359
Eugene Leviant340cb872019-02-08 10:33:16 +0000360static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
361 BumpPtrAllocator &Alloc,
362 StringRef Filename) {
363 StringSaver Saver(Alloc);
364 SmallVector<StringRef, 16> Lines;
365 auto BufOrErr = MemoryBuffer::getFile(Filename);
366 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000367 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000368
369 BufOrErr.get()->getBuffer().split(Lines, '\n');
370 size_t NumLines = Lines.size();
371 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
372 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
373 if (TrimmedLine.empty())
374 continue;
375
376 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
377 StringRef NewName = Pair.second.trim();
378 if (NewName.empty())
379 return createStringError(errc::invalid_argument,
380 "%s:%zu: missing new symbol name",
381 Filename.str().c_str(), LineNo + 1);
382 SymbolsToRename.insert({Pair.first, NewName});
383 }
384 return Error::success();
385}
Eugene Leviant53350d02019-02-26 09:24:22 +0000386
387template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
388 T Result;
389 if (Val.getAsInteger(0, Result))
390 return errc::invalid_argument;
391 return Result;
392}
393
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000394static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
395 StringRef ToolName) {
396 OptTable.PrintHelp(OS, (ToolName + " input [output]").str().c_str(),
397 (ToolName + " tool").str().c_str());
398 // TODO: Replace this with libOption call once it adds extrahelp support.
399 // The CommandLine library has a cl::extrahelp class to support this,
400 // but libOption does not have that yet.
401 OS << "\nPass @FILE as argument to read options from FILE.\n";
402}
403
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000404// ParseObjcopyOptions returns the config and sets the input arguments. If a
405// help flag is set then ParseObjcopyOptions will print the help messege and
406// exit.
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000407Expected<DriverConfig>
408parseObjcopyOptions(ArrayRef<const char *> ArgsArr,
409 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000410 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000411 ObjcopyOptTable T;
412 unsigned MissingArgumentIndex, MissingArgumentCount;
413 llvm::opt::InputArgList InputArgs =
414 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
415
416 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000417 printHelp(T, errs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000418 exit(1);
419 }
420
421 if (InputArgs.hasArg(OBJCOPY_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000422 printHelp(T, outs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000423 exit(0);
424 }
425
426 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000427 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000428 cl::PrintVersionMessage();
429 exit(0);
430 }
431
432 SmallVector<const char *, 2> Positional;
433
434 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000435 return createStringError(errc::invalid_argument, "unknown argument '%s'",
436 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000437
438 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
439 Positional.push_back(Arg->getValue());
440
441 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000442 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000443
444 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000445 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000446 "too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000447
448 CopyConfig Config;
449 Config.InputFilename = Positional[0];
450 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000451 if (InputArgs.hasArg(OBJCOPY_target) &&
452 (InputArgs.hasArg(OBJCOPY_input_target) ||
453 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000454 return createStringError(
455 errc::invalid_argument,
456 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000457
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000458 if (InputArgs.hasArg(OBJCOPY_regex) && InputArgs.hasArg(OBJCOPY_wildcard))
459 return createStringError(errc::invalid_argument,
460 "--regex and --wildcard are incompatible");
461
462 MatchStyle SectionMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
463 ? MatchStyle::Regex
464 : MatchStyle::Wildcard;
465 MatchStyle SymbolMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
466 ? MatchStyle::Regex
467 : InputArgs.hasArg(OBJCOPY_wildcard)
468 ? MatchStyle::Wildcard
469 : MatchStyle::Literal;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000470 StringRef InputFormat, OutputFormat;
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000471 if (InputArgs.hasArg(OBJCOPY_target)) {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000472 InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
473 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000474 } else {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000475 InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
476 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000477 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000478
479 // FIXME: Currently, we ignore the target for non-binary/ihex formats
480 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
481 // format by llvm::object::createBinary regardless of the option value.
482 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
483 .Case("binary", FileFormat::Binary)
484 .Case("ihex", FileFormat::IHex)
485 .Default(FileFormat::Unspecified);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000486
Michael Liaod19fb462019-09-24 12:43:44 +0000487 if (InputArgs.hasArg(OBJCOPY_new_symbol_visibility))
Seiya Nutac83eefc2019-09-24 09:38:23 +0000488 Config.NewSymbolVisibility =
489 InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility);
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000490
Seiya Nutaecb60b72019-07-05 05:28:38 +0000491 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
492 .Case("binary", FileFormat::Binary)
493 .Case("ihex", FileFormat::IHex)
494 .Default(FileFormat::Unspecified);
Fangrui Songba530302019-09-14 01:36:16 +0000495 if (Config.OutputFormat == FileFormat::Unspecified) {
496 if (OutputFormat.empty()) {
497 Config.OutputFormat = Config.InputFormat;
498 } else {
499 Expected<TargetInfo> Target =
500 getOutputTargetInfoByTargetName(OutputFormat);
501 if (!Target)
502 return Target.takeError();
503 Config.OutputFormat = Target->Format;
504 Config.OutputArch = Target->Machine;
505 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000506 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000507
508 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
509 OBJCOPY_compress_debug_sections_eq)) {
510 Config.CompressionType = DebugCompressionType::Z;
511
512 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
513 Config.CompressionType =
514 StringSwitch<DebugCompressionType>(
515 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
516 .Case("zlib-gnu", DebugCompressionType::GNU)
517 .Case("zlib", DebugCompressionType::Z)
518 .Default(DebugCompressionType::None);
519 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000520 return createStringError(
521 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000522 "invalid or unsupported --compress-debug-sections format: %s",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000523 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
524 .str()
525 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000526 }
George Rimar1e930802019-03-05 11:32:14 +0000527 if (!zlib::isAvailable())
528 return createStringError(
529 errc::invalid_argument,
530 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000531 }
532
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000533 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000534 // The gnu_debuglink's target is expected to not change or else its CRC would
535 // become invalidated and get rejected. We can avoid recalculating the
536 // checksum for every target file inside an archive by precomputing the CRC
537 // here. This prevents a significant amount of I/O.
538 if (!Config.AddGnuDebugLink.empty()) {
539 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
540 if (!DebugOrErr)
541 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
542 auto Debug = std::move(*DebugOrErr);
Hans Wennborg1e1e3ba2019-10-09 09:06:30 +0000543 Config.GnuDebugLinkCRC32 =
544 llvm::crc32(arrayRefFromStringRef(Debug->getBuffer()));
James Henderson9df38832019-05-14 10:59:04 +0000545 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000546 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
547 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
548 Config.BuildIdLinkInput =
549 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
550 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
551 Config.BuildIdLinkOutput =
552 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
553 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000554 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000555 Config.AllocSectionsPrefix =
556 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000557 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
558 Config.ExtractPartition = Arg->getValue();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000559
560 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
561 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000562 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000563 "bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000564 auto Old2New = StringRef(Arg->getValue()).split('=');
565 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000566 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000567 "multiple redefinition of symbol '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000568 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000569 }
570
Eugene Leviant340cb872019-02-08 10:33:16 +0000571 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
572 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
573 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000574 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000575
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000576 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000577 Expected<SectionRename> SR =
578 parseRenameSectionValue(StringRef(Arg->getValue()));
579 if (!SR)
580 return SR.takeError();
581 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
582 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000583 "multiple renames of section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000584 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000585 }
Fangrui Song671fb342019-10-02 12:41:25 +0000586 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_alignment)) {
587 Expected<std::pair<StringRef, uint64_t>> NameAndAlign =
588 parseSetSectionAlignment(Arg->getValue());
589 if (!NameAndAlign)
590 return NameAndAlign.takeError();
591 Config.SetSectionAlignment[NameAndAlign->first] = NameAndAlign->second;
592 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000593 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000594 Expected<SectionFlagsUpdate> SFU =
595 parseSetSectionFlagValue(Arg->getValue());
596 if (!SFU)
597 return SFU.takeError();
598 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
599 return createStringError(
600 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000601 "--set-section-flags set multiple times for section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000602 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000603 }
604 // Prohibit combinations of --set-section-flags when the section name is used
605 // by --rename-section, either as a source or a destination.
606 for (const auto &E : Config.SectionsToRename) {
607 const SectionRename &SR = E.second;
608 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000609 return createStringError(
610 errc::invalid_argument,
611 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
612 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
613 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000614 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000615 return createStringError(
616 errc::invalid_argument,
617 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
618 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
619 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000620 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000621
622 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000623 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
624 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
625 return std::move(E);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000626 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000627 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
628 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
629 return std::move(E);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000630 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000631 if (Error E = Config.OnlySection.addMatcher(NameOrPattern::create(
632 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
633 return std::move(E);
Sergey Dmitriev899bdaa2019-07-29 16:22:40 +0000634 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
635 StringRef ArgValue(Arg->getValue());
636 if (!ArgValue.contains('='))
637 return createStringError(errc::invalid_argument,
638 "bad format for --add-section: missing '='");
639 if (ArgValue.split("=").second.empty())
640 return createStringError(
641 errc::invalid_argument,
642 "bad format for --add-section: missing file name");
643 Config.AddSection.push_back(ArgValue);
644 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000645 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
646 Config.DumpSection.push_back(Arg->getValue());
647 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
648 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
649 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
650 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
651 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
652 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
653 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
654 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000655 Config.ExtractMainPartition =
656 InputArgs.hasArg(OBJCOPY_extract_main_partition);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000657 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
658 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000659 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
660 Config.DiscardMode =
661 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
662 ? DiscardType::All
663 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000664 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
665 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
666 Config.DecompressDebugSections =
667 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000668 if (Config.DiscardMode == DiscardType::All)
669 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000670 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000671 if (Error E = Config.SymbolsToLocalize.addMatcher(NameOrPattern::create(
672 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
673 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000674 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000675 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000676 Arg->getValue(), SymbolMatchStyle,
677 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000678 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000679 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000680 if (Error E = Config.SymbolsToKeepGlobal.addMatcher(NameOrPattern::create(
681 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
682 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000683 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000684 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000685 Arg->getValue(), SymbolMatchStyle,
686 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000687 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000688 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000689 if (Error E = Config.SymbolsToGlobalize.addMatcher(NameOrPattern::create(
690 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
691 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000692 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000693 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000694 Arg->getValue(), SymbolMatchStyle,
695 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000696 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000697 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000698 if (Error E = Config.SymbolsToWeaken.addMatcher(NameOrPattern::create(
699 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
700 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000701 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000702 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000703 Arg->getValue(), SymbolMatchStyle,
704 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000705 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000706 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000707 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
708 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
709 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000710 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000711 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000712 Arg->getValue(), SymbolMatchStyle,
713 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000714 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000715 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000716 if (Error E =
717 Config.UnneededSymbolsToRemove.addMatcher(NameOrPattern::create(
718 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
719 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000720 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000721 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000722 Arg->getValue(), SymbolMatchStyle,
723 ErrorCallback))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000724 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000725 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000726 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
727 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
728 return std::move(E);
Yi Kongf2baddb2019-04-01 18:12:43 +0000729 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000730 if (Error E =
731 addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc, Arg->getValue(),
732 SymbolMatchStyle, ErrorCallback))
Yi Kongf2baddb2019-04-01 18:12:43 +0000733 return std::move(E);
Seiya Nutac83eefc2019-09-24 09:38:23 +0000734 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol))
735 Config.SymbolsToAdd.push_back(Arg->getValue());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000736
James Henderson66a9d0f2019-04-18 09:13:30 +0000737 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
738
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000739 Config.DeterministicArchives = InputArgs.hasFlag(
740 OBJCOPY_enable_deterministic_archives,
741 OBJCOPY_disable_deterministic_archives, /*default=*/true);
742
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000743 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
744
Alex Brachet899a3072019-06-15 05:32:23 +0000745 if (Config.PreserveDates &&
746 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
747 return createStringError(errc::invalid_argument,
748 "--preserve-dates requires a file");
749
Eugene Leviant53350d02019-02-26 09:24:22 +0000750 for (auto Arg : InputArgs)
751 if (Arg->getOption().matches(OBJCOPY_set_start)) {
752 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
753 if (!EAddr)
754 return createStringError(
755 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
756
757 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
758 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
759 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
760 if (!EIncr)
761 return createStringError(EIncr.getError(),
762 "bad entry point increment: '%s'",
763 Arg->getValue());
764 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
765 : [](uint64_t A) { return A; };
766 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
767 return Expr(EAddr) + *EIncr;
768 };
769 }
770
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000771 if (Config.DecompressDebugSections &&
772 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000773 return createStringError(
774 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000775 "cannot specify both --compress-debug-sections and "
776 "--decompress-debug-sections");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000777 }
778
779 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000780 return createStringError(
781 errc::invalid_argument,
782 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000783
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000784 if (Config.ExtractPartition && Config.ExtractMainPartition)
785 return createStringError(errc::invalid_argument,
786 "cannot specify --extract-partition together with "
787 "--extract-main-partition");
788
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000789 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000790 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000791}
792
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800793// ParseInstallNameToolOptions returns the config and sets the input arguments.
794// If a help flag is set then ParseInstallNameToolOptions will print the help
795// messege and exit.
796Expected<DriverConfig>
797parseInstallNameToolOptions(ArrayRef<const char *> ArgsArr) {
798 DriverConfig DC;
799 CopyConfig Config;
800 InstallNameToolOptTable T;
801 unsigned MissingArgumentIndex, MissingArgumentCount;
802 llvm::opt::InputArgList InputArgs =
803 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
804
805 if (InputArgs.size() == 0) {
806 printHelp(T, errs(), "llvm-install-name-tool");
807 exit(1);
808 }
809
810 if (InputArgs.hasArg(INSTALL_NAME_TOOL_help)) {
811 printHelp(T, outs(), "llvm-install-name-tool");
812 exit(0);
813 }
814
815 if (InputArgs.hasArg(INSTALL_NAME_TOOL_version)) {
816 outs() << "llvm-install-name-tool, compatible with cctools "
817 "install_name_tool\n";
818 cl::PrintVersionMessage();
819 exit(0);
820 }
821
822 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_add_rpath))
823 Config.RPathToAdd.push_back(Arg->getValue());
824
825 SmallVector<StringRef, 2> Positional;
826 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_UNKNOWN))
827 return createStringError(errc::invalid_argument, "unknown argument '%s'",
828 Arg->getAsString(InputArgs).c_str());
829 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_INPUT))
830 Positional.push_back(Arg->getValue());
831 if (Positional.empty())
832 return createStringError(errc::invalid_argument, "no input file specified");
833 if (Positional.size() > 1)
834 return createStringError(
835 errc::invalid_argument,
836 "llvm-install-name-tool expects a single input file");
837 Config.InputFilename = Positional[0];
838 Config.OutputFilename = Positional[0];
839
840 DC.CopyConfigs.push_back(std::move(Config));
841 return std::move(DC);
842}
843
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000844// ParseStripOptions returns the config and sets the input arguments. If a
845// help flag is set then ParseStripOptions will print the help messege and
846// exit.
Alex Brachet77477002019-06-18 00:39:10 +0000847Expected<DriverConfig>
848parseStripOptions(ArrayRef<const char *> ArgsArr,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000849 llvm::function_ref<Error(Error)> ErrorCallback) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000850 StripOptTable T;
851 unsigned MissingArgumentIndex, MissingArgumentCount;
852 llvm::opt::InputArgList InputArgs =
853 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
854
855 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000856 printHelp(T, errs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000857 exit(1);
858 }
859
860 if (InputArgs.hasArg(STRIP_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000861 printHelp(T, outs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000862 exit(0);
863 }
864
865 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000866 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000867 cl::PrintVersionMessage();
868 exit(0);
869 }
870
Alex Brachet899a3072019-06-15 05:32:23 +0000871 SmallVector<StringRef, 2> Positional;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000872 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000873 return createStringError(errc::invalid_argument, "unknown argument '%s'",
874 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000875 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
876 Positional.push_back(Arg->getValue());
877
878 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000879 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000880
881 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000882 return createStringError(
883 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000884 "multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000885
886 CopyConfig Config;
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000887
888 if (InputArgs.hasArg(STRIP_regex) && InputArgs.hasArg(STRIP_wildcard))
889 return createStringError(errc::invalid_argument,
890 "--regex and --wildcard are incompatible");
891 MatchStyle SectionMatchStyle =
892 InputArgs.hasArg(STRIP_regex) ? MatchStyle::Regex : MatchStyle::Wildcard;
893 MatchStyle SymbolMatchStyle = InputArgs.hasArg(STRIP_regex)
894 ? MatchStyle::Regex
895 : InputArgs.hasArg(STRIP_wildcard)
896 ? MatchStyle::Wildcard
897 : MatchStyle::Literal;
James Henderson66a9d0f2019-04-18 09:13:30 +0000898 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000899 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
900
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000901 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
902 Config.DiscardMode =
903 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
904 ? DiscardType::All
905 : DiscardType::Locals;
Wolfgang Piebab751a72019-08-08 00:35:16 +0000906 Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000907 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000908 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
909 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000910 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000911 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000912 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000913
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000914 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000915 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
916 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
917 return std::move(E);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000918
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000919 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000920 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
921 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
922 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000923
Eugene Leviant2267c582019-01-31 12:16:20 +0000924 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000925 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
926 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
927 return std::move(E);
Eugene Leviant2267c582019-01-31 12:16:20 +0000928
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000929 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000930 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
931 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
932 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000933
James Hendersone4a89a12019-05-02 11:53:02 +0000934 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
935 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
936 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000937 Config.StripAll = true;
938
Sid Manning5ad18a72019-05-03 14:14:01 +0000939 if (Config.DiscardMode == DiscardType::All)
940 Config.StripDebug = true;
941
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000942 Config.DeterministicArchives =
943 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
944 STRIP_disable_deterministic_archives, /*default=*/true);
945
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000946 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000947 Config.InputFormat = FileFormat::Unspecified;
948 Config.OutputFormat = FileFormat::Unspecified;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000949
950 DriverConfig DC;
951 if (Positional.size() == 1) {
952 Config.InputFilename = Positional[0];
953 Config.OutputFilename =
954 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
955 DC.CopyConfigs.push_back(std::move(Config));
956 } else {
Alex Brachet77477002019-06-18 00:39:10 +0000957 StringMap<unsigned> InputFiles;
Alex Brachet899a3072019-06-15 05:32:23 +0000958 for (StringRef Filename : Positional) {
Alex Brachet77477002019-06-18 00:39:10 +0000959 if (InputFiles[Filename]++ == 1) {
960 if (Filename == "-")
961 return createStringError(
962 errc::invalid_argument,
963 "cannot specify '-' as an input file more than once");
964 if (Error E = ErrorCallback(createStringError(
965 errc::invalid_argument, "'%s' was already specified",
966 Filename.str().c_str())))
967 return std::move(E);
968 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000969 Config.InputFilename = Filename;
970 Config.OutputFilename = Filename;
971 DC.CopyConfigs.push_back(Config);
972 }
973 }
974
Alex Brachet899a3072019-06-15 05:32:23 +0000975 if (Config.PreserveDates && (is_contained(Positional, "-") ||
976 InputArgs.getLastArgValue(STRIP_output) == "-"))
977 return createStringError(errc::invalid_argument,
978 "--preserve-dates requires a file");
979
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000980 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000981}
982
983} // namespace objcopy
984} // namespace llvm