blob: 93fa3d764adbbdb37224b6854dbdd0f0bd147478 [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"
Simon Pilgrim090cf452020-05-17 18:51:21 +010010
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)
Sergey Dmitrieve4463222020-01-20 17:06:03 -0800149 .CaseLower("exclude", SectionFlag::SecExclude)
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000150 .Default(SectionFlag::SecNone);
151}
152
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000153static Expected<SectionFlag>
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000154parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000155 SectionFlag ParsedFlags = SectionFlag::SecNone;
156 for (StringRef Flag : SectionFlags) {
157 SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
158 if (ParsedFlag == SectionFlag::SecNone)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000159 return createStringError(
160 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000161 "unrecognized section flag '%s'. Flags supported for GNU "
Sergey Dmitrieve4463222020-01-20 17:06:03 -0800162 "compatibility: alloc, load, noload, readonly, exclude, debug, "
163 "code, data, rom, share, contents, merge, strings",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000164 Flag.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000165 ParsedFlags |= ParsedFlag;
166 }
167
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000168 return ParsedFlags;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000169}
170
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000171static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000172 if (!FlagValue.contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000173 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000174 "bad format for --rename-section: missing '='");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000175
176 // Initial split: ".foo" = ".bar,f1,f2,..."
177 auto Old2New = FlagValue.split('=');
178 SectionRename SR;
179 SR.OriginalName = Old2New.first;
180
181 // Flags split: ".bar" "f1" "f2" ...
182 SmallVector<StringRef, 6> NameAndFlags;
183 Old2New.second.split(NameAndFlags, ',');
184 SR.NewName = NameAndFlags[0];
185
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000186 if (NameAndFlags.size() > 1) {
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000187 Expected<SectionFlag> ParsedFlagSet =
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000188 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
189 if (!ParsedFlagSet)
190 return ParsedFlagSet.takeError();
191 SR.NewFlags = *ParsedFlagSet;
192 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000193
194 return SR;
195}
196
Fangrui Song671fb342019-10-02 12:41:25 +0000197static Expected<std::pair<StringRef, uint64_t>>
198parseSetSectionAlignment(StringRef FlagValue) {
199 if (!FlagValue.contains('='))
200 return createStringError(
201 errc::invalid_argument,
202 "bad format for --set-section-alignment: missing '='");
203 auto Split = StringRef(FlagValue).split('=');
204 if (Split.first.empty())
205 return createStringError(
206 errc::invalid_argument,
207 "bad format for --set-section-alignment: missing section name");
208 uint64_t NewAlign;
209 if (Split.second.getAsInteger(0, NewAlign))
210 return createStringError(errc::invalid_argument,
211 "invalid alignment for --set-section-alignment: '%s'",
212 Split.second.str().c_str());
213 return std::make_pair(Split.first, NewAlign);
214}
215
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000216static Expected<SectionFlagsUpdate>
217parseSetSectionFlagValue(StringRef FlagValue) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000218 if (!StringRef(FlagValue).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000219 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000220 "bad format for --set-section-flags: missing '='");
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000221
222 // Initial split: ".foo" = "f1,f2,..."
223 auto Section2Flags = StringRef(FlagValue).split('=');
224 SectionFlagsUpdate SFU;
225 SFU.Name = Section2Flags.first;
226
227 // Flags split: "f1" "f2" ...
228 SmallVector<StringRef, 6> SectionFlags;
229 Section2Flags.second.split(SectionFlags, ',');
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000230 Expected<SectionFlag> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000231 if (!ParsedFlagSet)
232 return ParsedFlagSet.takeError();
233 SFU.NewFlags = *ParsedFlagSet;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000234
235 return SFU;
236}
237
Seiya Nutaecb60b72019-07-05 05:28:38 +0000238struct TargetInfo {
239 FileFormat Format;
240 MachineInfo Machine;
241};
242
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000243// FIXME: consolidate with the bfd parsing used by lld.
Seiya Nutaecb60b72019-07-05 05:28:38 +0000244static const StringMap<MachineInfo> TargetMap{
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000245 // Name, {EMachine, 64bit, LittleEndian}
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000246 // x86
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000247 {"elf32-i386", {ELF::EM_386, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000248 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000249 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
250 // Intel MCU
251 {"elf32-iamcu", {ELF::EM_IAMCU, false, true}},
252 // ARM
253 {"elf32-littlearm", {ELF::EM_ARM, false, true}},
254 // ARM AArch64
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000255 {"elf64-aarch64", {ELF::EM_AARCH64, true, true}},
256 {"elf64-littleaarch64", {ELF::EM_AARCH64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000257 // RISC-V
258 {"elf32-littleriscv", {ELF::EM_RISCV, false, true}},
259 {"elf64-littleriscv", {ELF::EM_RISCV, true, true}},
260 // PowerPC
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000261 {"elf32-powerpc", {ELF::EM_PPC, false, false}},
262 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
263 {"elf64-powerpc", {ELF::EM_PPC64, true, false}},
264 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000265 // MIPS
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000266 {"elf32-bigmips", {ELF::EM_MIPS, false, false}},
267 {"elf32-ntradbigmips", {ELF::EM_MIPS, false, false}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000268 {"elf32-ntradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprecht96bbb1d2019-04-30 15:21:36 +0000269 {"elf32-tradbigmips", {ELF::EM_MIPS, false, false}},
270 {"elf32-tradlittlemips", {ELF::EM_MIPS, false, true}},
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000271 {"elf64-tradbigmips", {ELF::EM_MIPS, true, false}},
272 {"elf64-tradlittlemips", {ELF::EM_MIPS, true, true}},
Seiya Nuta13de1742019-06-17 02:03:45 +0000273 // SPARC
274 {"elf32-sparc", {ELF::EM_SPARC, false, false}},
275 {"elf32-sparcel", {ELF::EM_SPARC, false, true}},
Sid Manning50028632020-04-06 12:40:19 -0500276 {"elf32-hexagon", {ELF::EM_HEXAGON, false, true}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000277};
278
Seiya Nutaecb60b72019-07-05 05:28:38 +0000279static Expected<TargetInfo>
280getOutputTargetInfoByTargetName(StringRef TargetName) {
281 StringRef OriginalTargetName = TargetName;
282 bool IsFreeBSD = TargetName.consume_back("-freebsd");
283 auto Iter = TargetMap.find(TargetName);
284 if (Iter == std::end(TargetMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000285 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000286 "invalid output format: '%s'",
Seiya Nutaecb60b72019-07-05 05:28:38 +0000287 OriginalTargetName.str().c_str());
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000288 MachineInfo MI = Iter->getValue();
289 if (IsFreeBSD)
290 MI.OSABI = ELF::ELFOSABI_FREEBSD;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000291
292 FileFormat Format;
293 if (TargetName.startswith("elf"))
294 Format = FileFormat::ELF;
295 else
296 // This should never happen because `TargetName` is valid (it certainly
297 // exists in the TargetMap).
298 llvm_unreachable("unknown target prefix");
299
300 return {TargetInfo{Format, MI}};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000301}
302
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000303static Error
304addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
305 StringRef Filename, MatchStyle MS,
306 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000307 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000308 SmallVector<StringRef, 16> Lines;
309 auto BufOrErr = MemoryBuffer::getFile(Filename);
310 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000311 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000312
313 BufOrErr.get()->getBuffer().split(Lines, '\n');
314 for (StringRef Line : Lines) {
315 // Ignore everything after '#', trim whitespace, and only add the symbol if
316 // it's not empty.
317 auto TrimmedLine = Line.split('#').first.trim();
318 if (!TrimmedLine.empty())
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000319 if (Error E = Symbols.addMatcher(NameOrPattern::create(
320 Saver.save(TrimmedLine), MS, ErrorCallback)))
321 return E;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000322 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000323
324 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000325}
326
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000327Expected<NameOrPattern>
328NameOrPattern::create(StringRef Pattern, MatchStyle MS,
329 llvm::function_ref<Error(Error)> ErrorCallback) {
330 switch (MS) {
331 case MatchStyle::Literal:
332 return NameOrPattern(Pattern);
333 case MatchStyle::Wildcard: {
334 SmallVector<char, 32> Data;
335 bool IsPositiveMatch = true;
336 if (Pattern[0] == '!') {
337 IsPositiveMatch = false;
338 Pattern = Pattern.drop_front();
339 }
340 Expected<GlobPattern> GlobOrErr = GlobPattern::create(Pattern);
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000341
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000342 // If we couldn't create it as a glob, report the error, but try again with
343 // a literal if the error reporting is non-fatal.
344 if (!GlobOrErr) {
345 if (Error E = ErrorCallback(GlobOrErr.takeError()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800346 return std::move(E);
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000347 return create(Pattern, MatchStyle::Literal, ErrorCallback);
348 }
349
350 return NameOrPattern(std::make_shared<GlobPattern>(*GlobOrErr),
351 IsPositiveMatch);
352 }
353 case MatchStyle::Regex: {
354 SmallVector<char, 32> Data;
355 return NameOrPattern(std::make_shared<Regex>(
356 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data)));
357 }
358 }
Simon Pilgrim3bd61b22019-10-18 09:59:40 +0000359 llvm_unreachable("Unhandled llvm.objcopy.MatchStyle enum");
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000360}
361
Eugene Leviant340cb872019-02-08 10:33:16 +0000362static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
363 BumpPtrAllocator &Alloc,
364 StringRef Filename) {
365 StringSaver Saver(Alloc);
366 SmallVector<StringRef, 16> Lines;
367 auto BufOrErr = MemoryBuffer::getFile(Filename);
368 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000369 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000370
371 BufOrErr.get()->getBuffer().split(Lines, '\n');
372 size_t NumLines = Lines.size();
373 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
374 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
375 if (TrimmedLine.empty())
376 continue;
377
378 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
379 StringRef NewName = Pair.second.trim();
380 if (NewName.empty())
381 return createStringError(errc::invalid_argument,
382 "%s:%zu: missing new symbol name",
383 Filename.str().c_str(), LineNo + 1);
384 SymbolsToRename.insert({Pair.first, NewName});
385 }
386 return Error::success();
387}
Eugene Leviant53350d02019-02-26 09:24:22 +0000388
389template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
390 T Result;
391 if (Val.getAsInteger(0, Result))
392 return errc::invalid_argument;
393 return Result;
394}
395
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000396static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
397 StringRef ToolName) {
398 OptTable.PrintHelp(OS, (ToolName + " input [output]").str().c_str(),
399 (ToolName + " tool").str().c_str());
400 // TODO: Replace this with libOption call once it adds extrahelp support.
401 // The CommandLine library has a cl::extrahelp class to support this,
402 // but libOption does not have that yet.
403 OS << "\nPass @FILE as argument to read options from FILE.\n";
404}
405
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000406// ParseObjcopyOptions returns the config and sets the input arguments. If a
407// help flag is set then ParseObjcopyOptions will print the help messege and
408// exit.
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000409Expected<DriverConfig>
410parseObjcopyOptions(ArrayRef<const char *> ArgsArr,
411 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000412 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000413 ObjcopyOptTable T;
414 unsigned MissingArgumentIndex, MissingArgumentCount;
415 llvm::opt::InputArgList InputArgs =
416 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
417
418 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000419 printHelp(T, errs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000420 exit(1);
421 }
422
423 if (InputArgs.hasArg(OBJCOPY_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000424 printHelp(T, outs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000425 exit(0);
426 }
427
428 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000429 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000430 cl::PrintVersionMessage();
431 exit(0);
432 }
433
434 SmallVector<const char *, 2> Positional;
435
436 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000437 return createStringError(errc::invalid_argument, "unknown argument '%s'",
438 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000439
440 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
441 Positional.push_back(Arg->getValue());
442
443 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000444 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000445
446 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000447 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000448 "too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000449
450 CopyConfig Config;
451 Config.InputFilename = Positional[0];
452 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000453 if (InputArgs.hasArg(OBJCOPY_target) &&
454 (InputArgs.hasArg(OBJCOPY_input_target) ||
455 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000456 return createStringError(
457 errc::invalid_argument,
458 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000459
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000460 if (InputArgs.hasArg(OBJCOPY_regex) && InputArgs.hasArg(OBJCOPY_wildcard))
461 return createStringError(errc::invalid_argument,
462 "--regex and --wildcard are incompatible");
463
464 MatchStyle SectionMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
465 ? MatchStyle::Regex
466 : MatchStyle::Wildcard;
467 MatchStyle SymbolMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
468 ? MatchStyle::Regex
469 : InputArgs.hasArg(OBJCOPY_wildcard)
470 ? MatchStyle::Wildcard
471 : MatchStyle::Literal;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000472 StringRef InputFormat, OutputFormat;
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000473 if (InputArgs.hasArg(OBJCOPY_target)) {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000474 InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
475 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000476 } else {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000477 InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
478 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000479 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000480
481 // FIXME: Currently, we ignore the target for non-binary/ihex formats
482 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
483 // format by llvm::object::createBinary regardless of the option value.
484 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
485 .Case("binary", FileFormat::Binary)
486 .Case("ihex", FileFormat::IHex)
487 .Default(FileFormat::Unspecified);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000488
Michael Liaod19fb462019-09-24 12:43:44 +0000489 if (InputArgs.hasArg(OBJCOPY_new_symbol_visibility))
Seiya Nutac83eefc2019-09-24 09:38:23 +0000490 Config.NewSymbolVisibility =
491 InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility);
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000492
Seiya Nutaecb60b72019-07-05 05:28:38 +0000493 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
494 .Case("binary", FileFormat::Binary)
495 .Case("ihex", FileFormat::IHex)
496 .Default(FileFormat::Unspecified);
Fangrui Songba530302019-09-14 01:36:16 +0000497 if (Config.OutputFormat == FileFormat::Unspecified) {
498 if (OutputFormat.empty()) {
499 Config.OutputFormat = Config.InputFormat;
500 } else {
501 Expected<TargetInfo> Target =
502 getOutputTargetInfoByTargetName(OutputFormat);
503 if (!Target)
504 return Target.takeError();
505 Config.OutputFormat = Target->Format;
506 Config.OutputArch = Target->Machine;
507 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000508 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000509
510 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
511 OBJCOPY_compress_debug_sections_eq)) {
512 Config.CompressionType = DebugCompressionType::Z;
513
514 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
515 Config.CompressionType =
516 StringSwitch<DebugCompressionType>(
517 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
518 .Case("zlib-gnu", DebugCompressionType::GNU)
519 .Case("zlib", DebugCompressionType::Z)
520 .Default(DebugCompressionType::None);
521 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000522 return createStringError(
523 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000524 "invalid or unsupported --compress-debug-sections format: %s",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000525 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
526 .str()
527 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000528 }
George Rimar1e930802019-03-05 11:32:14 +0000529 if (!zlib::isAvailable())
530 return createStringError(
531 errc::invalid_argument,
532 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000533 }
534
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000535 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000536 // The gnu_debuglink's target is expected to not change or else its CRC would
537 // become invalidated and get rejected. We can avoid recalculating the
538 // checksum for every target file inside an archive by precomputing the CRC
539 // here. This prevents a significant amount of I/O.
540 if (!Config.AddGnuDebugLink.empty()) {
541 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
542 if (!DebugOrErr)
543 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
544 auto Debug = std::move(*DebugOrErr);
Hans Wennborg1e1e3ba2019-10-09 09:06:30 +0000545 Config.GnuDebugLinkCRC32 =
546 llvm::crc32(arrayRefFromStringRef(Debug->getBuffer()));
James Henderson9df38832019-05-14 10:59:04 +0000547 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000548 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
549 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
550 Config.BuildIdLinkInput =
551 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
552 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
553 Config.BuildIdLinkOutput =
554 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
555 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000556 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000557 Config.AllocSectionsPrefix =
558 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000559 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
560 Config.ExtractPartition = Arg->getValue();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000561
562 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
563 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000564 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000565 "bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000566 auto Old2New = StringRef(Arg->getValue()).split('=');
567 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000568 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000569 "multiple redefinition of symbol '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000570 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000571 }
572
Eugene Leviant340cb872019-02-08 10:33:16 +0000573 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
574 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
575 Arg->getValue()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800576 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000577
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000578 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000579 Expected<SectionRename> SR =
580 parseRenameSectionValue(StringRef(Arg->getValue()));
581 if (!SR)
582 return SR.takeError();
583 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
584 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000585 "multiple renames of section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000586 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000587 }
Fangrui Song671fb342019-10-02 12:41:25 +0000588 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_alignment)) {
589 Expected<std::pair<StringRef, uint64_t>> NameAndAlign =
590 parseSetSectionAlignment(Arg->getValue());
591 if (!NameAndAlign)
592 return NameAndAlign.takeError();
593 Config.SetSectionAlignment[NameAndAlign->first] = NameAndAlign->second;
594 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000595 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000596 Expected<SectionFlagsUpdate> SFU =
597 parseSetSectionFlagValue(Arg->getValue());
598 if (!SFU)
599 return SFU.takeError();
600 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
601 return createStringError(
602 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000603 "--set-section-flags set multiple times for section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000604 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000605 }
606 // Prohibit combinations of --set-section-flags when the section name is used
607 // by --rename-section, either as a source or a destination.
608 for (const auto &E : Config.SectionsToRename) {
609 const SectionRename &SR = E.second;
610 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000611 return createStringError(
612 errc::invalid_argument,
613 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
614 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
615 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000616 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000617 return createStringError(
618 errc::invalid_argument,
619 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
620 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
621 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000622 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000623
624 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000625 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
626 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800627 return std::move(E);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000628 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000629 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
630 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800631 return std::move(E);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000632 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000633 if (Error E = Config.OnlySection.addMatcher(NameOrPattern::create(
634 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800635 return std::move(E);
Sergey Dmitriev899bdaa2019-07-29 16:22:40 +0000636 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
637 StringRef ArgValue(Arg->getValue());
638 if (!ArgValue.contains('='))
639 return createStringError(errc::invalid_argument,
640 "bad format for --add-section: missing '='");
641 if (ArgValue.split("=").second.empty())
642 return createStringError(
643 errc::invalid_argument,
644 "bad format for --add-section: missing file name");
645 Config.AddSection.push_back(ArgValue);
646 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000647 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
648 Config.DumpSection.push_back(Arg->getValue());
649 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
650 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
651 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
652 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
653 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
654 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
655 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
656 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000657 Config.ExtractMainPartition =
658 InputArgs.hasArg(OBJCOPY_extract_main_partition);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000659 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
660 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000661 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
662 Config.DiscardMode =
663 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
664 ? DiscardType::All
665 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000666 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
667 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
668 Config.DecompressDebugSections =
669 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Fangrui Songb14e9e32020-03-24 15:38:48 +0800670 if (Config.DiscardMode == DiscardType::All) {
Sid Manning5ad18a72019-05-03 14:14:01 +0000671 Config.StripDebug = true;
Fangrui Songb14e9e32020-03-24 15:38:48 +0800672 Config.KeepFileSymbols = true;
673 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000674 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000675 if (Error E = Config.SymbolsToLocalize.addMatcher(NameOrPattern::create(
676 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800677 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000678 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000679 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000680 Arg->getValue(), SymbolMatchStyle,
681 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800682 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000683 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000684 if (Error E = Config.SymbolsToKeepGlobal.addMatcher(NameOrPattern::create(
685 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800686 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000687 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000688 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000689 Arg->getValue(), SymbolMatchStyle,
690 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800691 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000692 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000693 if (Error E = Config.SymbolsToGlobalize.addMatcher(NameOrPattern::create(
694 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800695 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000696 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000697 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000698 Arg->getValue(), SymbolMatchStyle,
699 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800700 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000701 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000702 if (Error E = Config.SymbolsToWeaken.addMatcher(NameOrPattern::create(
703 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800704 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000705 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000706 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000707 Arg->getValue(), SymbolMatchStyle,
708 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800709 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000710 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000711 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
712 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800713 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000714 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000715 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000716 Arg->getValue(), SymbolMatchStyle,
717 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800718 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000719 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000720 if (Error E =
721 Config.UnneededSymbolsToRemove.addMatcher(NameOrPattern::create(
722 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800723 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000724 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000725 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000726 Arg->getValue(), SymbolMatchStyle,
727 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800728 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000729 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000730 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
731 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800732 return std::move(E);
Yi Kongf2baddb2019-04-01 18:12:43 +0000733 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000734 if (Error E =
735 addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc, Arg->getValue(),
736 SymbolMatchStyle, ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800737 return std::move(E);
Seiya Nutac83eefc2019-09-24 09:38:23 +0000738 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol))
739 Config.SymbolsToAdd.push_back(Arg->getValue());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000740
James Henderson66a9d0f2019-04-18 09:13:30 +0000741 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
742
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000743 Config.DeterministicArchives = InputArgs.hasFlag(
744 OBJCOPY_enable_deterministic_archives,
745 OBJCOPY_disable_deterministic_archives, /*default=*/true);
746
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000747 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
748
Alex Brachet899a3072019-06-15 05:32:23 +0000749 if (Config.PreserveDates &&
750 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
751 return createStringError(errc::invalid_argument,
752 "--preserve-dates requires a file");
753
Eugene Leviant53350d02019-02-26 09:24:22 +0000754 for (auto Arg : InputArgs)
755 if (Arg->getOption().matches(OBJCOPY_set_start)) {
756 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
757 if (!EAddr)
758 return createStringError(
759 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
760
761 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
762 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
763 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
764 if (!EIncr)
765 return createStringError(EIncr.getError(),
766 "bad entry point increment: '%s'",
767 Arg->getValue());
768 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
769 : [](uint64_t A) { return A; };
770 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
771 return Expr(EAddr) + *EIncr;
772 };
773 }
774
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000775 if (Config.DecompressDebugSections &&
776 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000777 return createStringError(
778 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000779 "cannot specify both --compress-debug-sections and "
780 "--decompress-debug-sections");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000781 }
782
783 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000784 return createStringError(
785 errc::invalid_argument,
786 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000787
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000788 if (Config.ExtractPartition && Config.ExtractMainPartition)
789 return createStringError(errc::invalid_argument,
790 "cannot specify --extract-partition together with "
791 "--extract-main-partition");
792
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000793 DC.CopyConfigs.push_back(std::move(Config));
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800794 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000795}
796
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800797// ParseInstallNameToolOptions returns the config and sets the input arguments.
798// If a help flag is set then ParseInstallNameToolOptions will print the help
799// messege and exit.
800Expected<DriverConfig>
801parseInstallNameToolOptions(ArrayRef<const char *> ArgsArr) {
802 DriverConfig DC;
803 CopyConfig Config;
804 InstallNameToolOptTable T;
805 unsigned MissingArgumentIndex, MissingArgumentCount;
806 llvm::opt::InputArgList InputArgs =
807 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
808
809 if (InputArgs.size() == 0) {
810 printHelp(T, errs(), "llvm-install-name-tool");
811 exit(1);
812 }
813
814 if (InputArgs.hasArg(INSTALL_NAME_TOOL_help)) {
815 printHelp(T, outs(), "llvm-install-name-tool");
816 exit(0);
817 }
818
819 if (InputArgs.hasArg(INSTALL_NAME_TOOL_version)) {
820 outs() << "llvm-install-name-tool, compatible with cctools "
821 "install_name_tool\n";
822 cl::PrintVersionMessage();
823 exit(0);
824 }
825
826 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_add_rpath))
827 Config.RPathToAdd.push_back(Arg->getValue());
828
Alexander Shaposhnikovd332ec92020-06-22 16:49:14 -0700829 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_delete_rpath)) {
830 StringRef RPath = Arg->getValue();
831
832 // Cannot add and delete the same rpath at the same time.
833 if (is_contained(Config.RPathToAdd, RPath))
834 return createStringError(
835 errc::invalid_argument,
836 "cannot specify both -add_rpath %s and -delete_rpath %s",
837 RPath.str().c_str(), RPath.str().c_str());
838
839 Config.RPathsToRemove.insert(RPath);
840 }
841
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800842 SmallVector<StringRef, 2> Positional;
843 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_UNKNOWN))
844 return createStringError(errc::invalid_argument, "unknown argument '%s'",
845 Arg->getAsString(InputArgs).c_str());
846 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_INPUT))
847 Positional.push_back(Arg->getValue());
848 if (Positional.empty())
849 return createStringError(errc::invalid_argument, "no input file specified");
850 if (Positional.size() > 1)
851 return createStringError(
852 errc::invalid_argument,
853 "llvm-install-name-tool expects a single input file");
854 Config.InputFilename = Positional[0];
855 Config.OutputFilename = Positional[0];
856
857 DC.CopyConfigs.push_back(std::move(Config));
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800858 return std::move(DC);
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800859}
860
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000861// ParseStripOptions returns the config and sets the input arguments. If a
862// help flag is set then ParseStripOptions will print the help messege and
863// exit.
Alex Brachet77477002019-06-18 00:39:10 +0000864Expected<DriverConfig>
865parseStripOptions(ArrayRef<const char *> ArgsArr,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000866 llvm::function_ref<Error(Error)> ErrorCallback) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000867 StripOptTable T;
868 unsigned MissingArgumentIndex, MissingArgumentCount;
869 llvm::opt::InputArgList InputArgs =
870 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
871
872 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000873 printHelp(T, errs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000874 exit(1);
875 }
876
877 if (InputArgs.hasArg(STRIP_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000878 printHelp(T, outs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000879 exit(0);
880 }
881
882 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000883 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000884 cl::PrintVersionMessage();
885 exit(0);
886 }
887
Alex Brachet899a3072019-06-15 05:32:23 +0000888 SmallVector<StringRef, 2> Positional;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000889 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000890 return createStringError(errc::invalid_argument, "unknown argument '%s'",
891 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000892 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
893 Positional.push_back(Arg->getValue());
894
895 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000896 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000897
898 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000899 return createStringError(
900 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000901 "multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000902
903 CopyConfig Config;
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000904
905 if (InputArgs.hasArg(STRIP_regex) && InputArgs.hasArg(STRIP_wildcard))
906 return createStringError(errc::invalid_argument,
907 "--regex and --wildcard are incompatible");
908 MatchStyle SectionMatchStyle =
909 InputArgs.hasArg(STRIP_regex) ? MatchStyle::Regex : MatchStyle::Wildcard;
910 MatchStyle SymbolMatchStyle = InputArgs.hasArg(STRIP_regex)
911 ? MatchStyle::Regex
912 : InputArgs.hasArg(STRIP_wildcard)
913 ? MatchStyle::Wildcard
914 : MatchStyle::Literal;
James Henderson66a9d0f2019-04-18 09:13:30 +0000915 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000916 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
917
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000918 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
919 Config.DiscardMode =
920 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
921 ? DiscardType::All
922 : DiscardType::Locals;
Wolfgang Piebab751a72019-08-08 00:35:16 +0000923 Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000924 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000925 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
926 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000927 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Alexander Shaposhnikov842a8cc2020-05-26 16:49:56 -0700928 Config.StripSwiftSymbols = InputArgs.hasArg(STRIP_strip_swift_symbols);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000929 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000930 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000931
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000932 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000933 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
934 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800935 return std::move(E);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000936
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000937 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000938 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
939 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800940 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000941
Eugene Leviant2267c582019-01-31 12:16:20 +0000942 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000943 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
944 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800945 return std::move(E);
Eugene Leviant2267c582019-01-31 12:16:20 +0000946
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000947 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000948 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
949 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800950 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000951
James Hendersone4a89a12019-05-02 11:53:02 +0000952 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
953 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
954 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000955 Config.StripAll = true;
956
Fangrui Songb14e9e32020-03-24 15:38:48 +0800957 if (Config.DiscardMode == DiscardType::All) {
Sid Manning5ad18a72019-05-03 14:14:01 +0000958 Config.StripDebug = true;
Fangrui Songb14e9e32020-03-24 15:38:48 +0800959 Config.KeepFileSymbols = true;
960 }
Sid Manning5ad18a72019-05-03 14:14:01 +0000961
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000962 Config.DeterministicArchives =
963 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
964 STRIP_disable_deterministic_archives, /*default=*/true);
965
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000966 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000967 Config.InputFormat = FileFormat::Unspecified;
968 Config.OutputFormat = FileFormat::Unspecified;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000969
970 DriverConfig DC;
971 if (Positional.size() == 1) {
972 Config.InputFilename = Positional[0];
973 Config.OutputFilename =
974 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
975 DC.CopyConfigs.push_back(std::move(Config));
976 } else {
Alex Brachet77477002019-06-18 00:39:10 +0000977 StringMap<unsigned> InputFiles;
Alex Brachet899a3072019-06-15 05:32:23 +0000978 for (StringRef Filename : Positional) {
Alex Brachet77477002019-06-18 00:39:10 +0000979 if (InputFiles[Filename]++ == 1) {
980 if (Filename == "-")
981 return createStringError(
982 errc::invalid_argument,
983 "cannot specify '-' as an input file more than once");
984 if (Error E = ErrorCallback(createStringError(
985 errc::invalid_argument, "'%s' was already specified",
986 Filename.str().c_str())))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800987 return std::move(E);
Alex Brachet77477002019-06-18 00:39:10 +0000988 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000989 Config.InputFilename = Filename;
990 Config.OutputFilename = Filename;
991 DC.CopyConfigs.push_back(Config);
992 }
993 }
994
Alex Brachet899a3072019-06-15 05:32:23 +0000995 if (Config.PreserveDates && (is_contained(Positional, "-") ||
996 InputArgs.getLastArgValue(STRIP_output) == "-"))
997 return createStringError(errc::invalid_argument,
998 "--preserve-dates requires a file");
999
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08001000 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +00001001}
1002
1003} // namespace objcopy
1004} // namespace llvm