blob: 69d6180d86e0ea5907983372c10a614eed382a2d [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)
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}},
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000276};
277
Seiya Nutaecb60b72019-07-05 05:28:38 +0000278static Expected<TargetInfo>
279getOutputTargetInfoByTargetName(StringRef TargetName) {
280 StringRef OriginalTargetName = TargetName;
281 bool IsFreeBSD = TargetName.consume_back("-freebsd");
282 auto Iter = TargetMap.find(TargetName);
283 if (Iter == std::end(TargetMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000284 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000285 "invalid output format: '%s'",
Seiya Nutaecb60b72019-07-05 05:28:38 +0000286 OriginalTargetName.str().c_str());
Jordan Rupprechtb0b65ca2019-04-17 07:42:31 +0000287 MachineInfo MI = Iter->getValue();
288 if (IsFreeBSD)
289 MI.OSABI = ELF::ELFOSABI_FREEBSD;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000290
291 FileFormat Format;
292 if (TargetName.startswith("elf"))
293 Format = FileFormat::ELF;
294 else
295 // This should never happen because `TargetName` is valid (it certainly
296 // exists in the TargetMap).
297 llvm_unreachable("unknown target prefix");
298
299 return {TargetInfo{Format, MI}};
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000300}
301
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000302static Error
303addSymbolsFromFile(NameMatcher &Symbols, BumpPtrAllocator &Alloc,
304 StringRef Filename, MatchStyle MS,
305 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000306 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000307 SmallVector<StringRef, 16> Lines;
308 auto BufOrErr = MemoryBuffer::getFile(Filename);
309 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000310 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000311
312 BufOrErr.get()->getBuffer().split(Lines, '\n');
313 for (StringRef Line : Lines) {
314 // Ignore everything after '#', trim whitespace, and only add the symbol if
315 // it's not empty.
316 auto TrimmedLine = Line.split('#').first.trim();
317 if (!TrimmedLine.empty())
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000318 if (Error E = Symbols.addMatcher(NameOrPattern::create(
319 Saver.save(TrimmedLine), MS, ErrorCallback)))
320 return E;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000321 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000322
323 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000324}
325
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000326Expected<NameOrPattern>
327NameOrPattern::create(StringRef Pattern, MatchStyle MS,
328 llvm::function_ref<Error(Error)> ErrorCallback) {
329 switch (MS) {
330 case MatchStyle::Literal:
331 return NameOrPattern(Pattern);
332 case MatchStyle::Wildcard: {
333 SmallVector<char, 32> Data;
334 bool IsPositiveMatch = true;
335 if (Pattern[0] == '!') {
336 IsPositiveMatch = false;
337 Pattern = Pattern.drop_front();
338 }
339 Expected<GlobPattern> GlobOrErr = GlobPattern::create(Pattern);
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000340
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000341 // If we couldn't create it as a glob, report the error, but try again with
342 // a literal if the error reporting is non-fatal.
343 if (!GlobOrErr) {
344 if (Error E = ErrorCallback(GlobOrErr.takeError()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800345 return std::move(E);
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000346 return create(Pattern, MatchStyle::Literal, ErrorCallback);
347 }
348
349 return NameOrPattern(std::make_shared<GlobPattern>(*GlobOrErr),
350 IsPositiveMatch);
351 }
352 case MatchStyle::Regex: {
353 SmallVector<char, 32> Data;
354 return NameOrPattern(std::make_shared<Regex>(
355 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data)));
356 }
357 }
Simon Pilgrim3bd61b22019-10-18 09:59:40 +0000358 llvm_unreachable("Unhandled llvm.objcopy.MatchStyle enum");
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000359}
360
Eugene Leviant340cb872019-02-08 10:33:16 +0000361static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
362 BumpPtrAllocator &Alloc,
363 StringRef Filename) {
364 StringSaver Saver(Alloc);
365 SmallVector<StringRef, 16> Lines;
366 auto BufOrErr = MemoryBuffer::getFile(Filename);
367 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000368 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000369
370 BufOrErr.get()->getBuffer().split(Lines, '\n');
371 size_t NumLines = Lines.size();
372 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
373 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
374 if (TrimmedLine.empty())
375 continue;
376
377 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
378 StringRef NewName = Pair.second.trim();
379 if (NewName.empty())
380 return createStringError(errc::invalid_argument,
381 "%s:%zu: missing new symbol name",
382 Filename.str().c_str(), LineNo + 1);
383 SymbolsToRename.insert({Pair.first, NewName});
384 }
385 return Error::success();
386}
Eugene Leviant53350d02019-02-26 09:24:22 +0000387
388template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
389 T Result;
390 if (Val.getAsInteger(0, Result))
391 return errc::invalid_argument;
392 return Result;
393}
394
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000395static void printHelp(const opt::OptTable &OptTable, raw_ostream &OS,
396 StringRef ToolName) {
397 OptTable.PrintHelp(OS, (ToolName + " input [output]").str().c_str(),
398 (ToolName + " tool").str().c_str());
399 // TODO: Replace this with libOption call once it adds extrahelp support.
400 // The CommandLine library has a cl::extrahelp class to support this,
401 // but libOption does not have that yet.
402 OS << "\nPass @FILE as argument to read options from FILE.\n";
403}
404
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000405// ParseObjcopyOptions returns the config and sets the input arguments. If a
406// help flag is set then ParseObjcopyOptions will print the help messege and
407// exit.
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000408Expected<DriverConfig>
409parseObjcopyOptions(ArrayRef<const char *> ArgsArr,
410 llvm::function_ref<Error(Error)> ErrorCallback) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000411 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000412 ObjcopyOptTable T;
413 unsigned MissingArgumentIndex, MissingArgumentCount;
414 llvm::opt::InputArgList InputArgs =
415 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
416
417 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000418 printHelp(T, errs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000419 exit(1);
420 }
421
422 if (InputArgs.hasArg(OBJCOPY_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000423 printHelp(T, outs(), "llvm-objcopy");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000424 exit(0);
425 }
426
427 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000428 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000429 cl::PrintVersionMessage();
430 exit(0);
431 }
432
433 SmallVector<const char *, 2> Positional;
434
435 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000436 return createStringError(errc::invalid_argument, "unknown argument '%s'",
437 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000438
439 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
440 Positional.push_back(Arg->getValue());
441
442 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000443 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000444
445 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000446 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000447 "too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000448
449 CopyConfig Config;
450 Config.InputFilename = Positional[0];
451 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000452 if (InputArgs.hasArg(OBJCOPY_target) &&
453 (InputArgs.hasArg(OBJCOPY_input_target) ||
454 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000455 return createStringError(
456 errc::invalid_argument,
457 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000458
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000459 if (InputArgs.hasArg(OBJCOPY_regex) && InputArgs.hasArg(OBJCOPY_wildcard))
460 return createStringError(errc::invalid_argument,
461 "--regex and --wildcard are incompatible");
462
463 MatchStyle SectionMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
464 ? MatchStyle::Regex
465 : MatchStyle::Wildcard;
466 MatchStyle SymbolMatchStyle = InputArgs.hasArg(OBJCOPY_regex)
467 ? MatchStyle::Regex
468 : InputArgs.hasArg(OBJCOPY_wildcard)
469 ? MatchStyle::Wildcard
470 : MatchStyle::Literal;
Seiya Nutaecb60b72019-07-05 05:28:38 +0000471 StringRef InputFormat, OutputFormat;
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000472 if (InputArgs.hasArg(OBJCOPY_target)) {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000473 InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
474 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000475 } else {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000476 InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
477 OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000478 }
Seiya Nutaecb60b72019-07-05 05:28:38 +0000479
480 // FIXME: Currently, we ignore the target for non-binary/ihex formats
481 // explicitly specified by -I option (e.g. -Ielf32-x86-64) and guess the
482 // format by llvm::object::createBinary regardless of the option value.
483 Config.InputFormat = StringSwitch<FileFormat>(InputFormat)
484 .Case("binary", FileFormat::Binary)
485 .Case("ihex", FileFormat::IHex)
486 .Default(FileFormat::Unspecified);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000487
Michael Liaod19fb462019-09-24 12:43:44 +0000488 if (InputArgs.hasArg(OBJCOPY_new_symbol_visibility))
Seiya Nutac83eefc2019-09-24 09:38:23 +0000489 Config.NewSymbolVisibility =
490 InputArgs.getLastArgValue(OBJCOPY_new_symbol_visibility);
Chris Jacksonfa1fe932019-08-30 10:17:16 +0000491
Seiya Nutaecb60b72019-07-05 05:28:38 +0000492 Config.OutputFormat = StringSwitch<FileFormat>(OutputFormat)
493 .Case("binary", FileFormat::Binary)
494 .Case("ihex", FileFormat::IHex)
495 .Default(FileFormat::Unspecified);
Fangrui Songba530302019-09-14 01:36:16 +0000496 if (Config.OutputFormat == FileFormat::Unspecified) {
497 if (OutputFormat.empty()) {
498 Config.OutputFormat = Config.InputFormat;
499 } else {
500 Expected<TargetInfo> Target =
501 getOutputTargetInfoByTargetName(OutputFormat);
502 if (!Target)
503 return Target.takeError();
504 Config.OutputFormat = Target->Format;
505 Config.OutputArch = Target->Machine;
506 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000507 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000508
509 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
510 OBJCOPY_compress_debug_sections_eq)) {
511 Config.CompressionType = DebugCompressionType::Z;
512
513 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
514 Config.CompressionType =
515 StringSwitch<DebugCompressionType>(
516 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
517 .Case("zlib-gnu", DebugCompressionType::GNU)
518 .Case("zlib", DebugCompressionType::Z)
519 .Default(DebugCompressionType::None);
520 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000521 return createStringError(
522 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000523 "invalid or unsupported --compress-debug-sections format: %s",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000524 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
525 .str()
526 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000527 }
George Rimar1e930802019-03-05 11:32:14 +0000528 if (!zlib::isAvailable())
529 return createStringError(
530 errc::invalid_argument,
531 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000532 }
533
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000534 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
James Henderson9df38832019-05-14 10:59:04 +0000535 // The gnu_debuglink's target is expected to not change or else its CRC would
536 // become invalidated and get rejected. We can avoid recalculating the
537 // checksum for every target file inside an archive by precomputing the CRC
538 // here. This prevents a significant amount of I/O.
539 if (!Config.AddGnuDebugLink.empty()) {
540 auto DebugOrErr = MemoryBuffer::getFile(Config.AddGnuDebugLink);
541 if (!DebugOrErr)
542 return createFileError(Config.AddGnuDebugLink, DebugOrErr.getError());
543 auto Debug = std::move(*DebugOrErr);
Hans Wennborg1e1e3ba2019-10-09 09:06:30 +0000544 Config.GnuDebugLinkCRC32 =
545 llvm::crc32(arrayRefFromStringRef(Debug->getBuffer()));
James Henderson9df38832019-05-14 10:59:04 +0000546 }
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000547 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
548 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
549 Config.BuildIdLinkInput =
550 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
551 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
552 Config.BuildIdLinkOutput =
553 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
554 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000555 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
James Hendersonfa11fb32019-05-08 09:49:35 +0000556 Config.AllocSectionsPrefix =
557 InputArgs.getLastArgValue(OBJCOPY_prefix_alloc_sections);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000558 if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
559 Config.ExtractPartition = Arg->getValue();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000560
561 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
562 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000563 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000564 "bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000565 auto Old2New = StringRef(Arg->getValue()).split('=');
566 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000567 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000568 "multiple redefinition of symbol '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000569 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000570 }
571
Eugene Leviant340cb872019-02-08 10:33:16 +0000572 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
573 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
574 Arg->getValue()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800575 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000576
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000577 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000578 Expected<SectionRename> SR =
579 parseRenameSectionValue(StringRef(Arg->getValue()));
580 if (!SR)
581 return SR.takeError();
582 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
583 return createStringError(errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000584 "multiple renames of section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000585 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000586 }
Fangrui Song671fb342019-10-02 12:41:25 +0000587 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_alignment)) {
588 Expected<std::pair<StringRef, uint64_t>> NameAndAlign =
589 parseSetSectionAlignment(Arg->getValue());
590 if (!NameAndAlign)
591 return NameAndAlign.takeError();
592 Config.SetSectionAlignment[NameAndAlign->first] = NameAndAlign->second;
593 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000594 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000595 Expected<SectionFlagsUpdate> SFU =
596 parseSetSectionFlagValue(Arg->getValue());
597 if (!SFU)
598 return SFU.takeError();
599 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
600 return createStringError(
601 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000602 "--set-section-flags set multiple times for section '%s'",
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000603 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000604 }
605 // Prohibit combinations of --set-section-flags when the section name is used
606 // by --rename-section, either as a source or a destination.
607 for (const auto &E : Config.SectionsToRename) {
608 const SectionRename &SR = E.second;
609 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000610 return createStringError(
611 errc::invalid_argument,
612 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
613 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
614 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000615 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000616 return createStringError(
617 errc::invalid_argument,
618 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
619 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
620 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000621 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000622
623 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000624 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
625 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800626 return std::move(E);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000627 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000628 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
629 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800630 return std::move(E);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000631 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000632 if (Error E = Config.OnlySection.addMatcher(NameOrPattern::create(
633 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800634 return std::move(E);
Sergey Dmitriev899bdaa2019-07-29 16:22:40 +0000635 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) {
636 StringRef ArgValue(Arg->getValue());
637 if (!ArgValue.contains('='))
638 return createStringError(errc::invalid_argument,
639 "bad format for --add-section: missing '='");
640 if (ArgValue.split("=").second.empty())
641 return createStringError(
642 errc::invalid_argument,
643 "bad format for --add-section: missing file name");
644 Config.AddSection.push_back(ArgValue);
645 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000646 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
647 Config.DumpSection.push_back(Arg->getValue());
648 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
649 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
650 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
651 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
652 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
653 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
654 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
655 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000656 Config.ExtractMainPartition =
657 InputArgs.hasArg(OBJCOPY_extract_main_partition);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000658 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
659 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000660 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
661 Config.DiscardMode =
662 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
663 ? DiscardType::All
664 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000665 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
666 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
667 Config.DecompressDebugSections =
668 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
Sid Manning5ad18a72019-05-03 14:14:01 +0000669 if (Config.DiscardMode == DiscardType::All)
670 Config.StripDebug = true;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000671 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000672 if (Error E = Config.SymbolsToLocalize.addMatcher(NameOrPattern::create(
673 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800674 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000675 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000676 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000677 Arg->getValue(), SymbolMatchStyle,
678 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800679 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000680 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000681 if (Error E = Config.SymbolsToKeepGlobal.addMatcher(NameOrPattern::create(
682 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800683 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000684 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000685 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000686 Arg->getValue(), SymbolMatchStyle,
687 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800688 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000689 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000690 if (Error E = Config.SymbolsToGlobalize.addMatcher(NameOrPattern::create(
691 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800692 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000693 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000694 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000695 Arg->getValue(), SymbolMatchStyle,
696 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800697 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000698 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000699 if (Error E = Config.SymbolsToWeaken.addMatcher(NameOrPattern::create(
700 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800701 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000702 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000703 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000704 Arg->getValue(), SymbolMatchStyle,
705 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800706 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000707 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000708 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
709 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800710 return std::move(E);
Eugene Leviante08fe352019-02-08 14:37:54 +0000711 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000712 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000713 Arg->getValue(), SymbolMatchStyle,
714 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800715 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000716 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000717 if (Error E =
718 Config.UnneededSymbolsToRemove.addMatcher(NameOrPattern::create(
719 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800720 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000721 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000722 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000723 Arg->getValue(), SymbolMatchStyle,
724 ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800725 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000726 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000727 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
728 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800729 return std::move(E);
Yi Kongf2baddb2019-04-01 18:12:43 +0000730 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbols))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000731 if (Error E =
732 addSymbolsFromFile(Config.SymbolsToKeep, DC.Alloc, Arg->getValue(),
733 SymbolMatchStyle, ErrorCallback))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800734 return std::move(E);
Seiya Nutac83eefc2019-09-24 09:38:23 +0000735 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol))
736 Config.SymbolsToAdd.push_back(Arg->getValue());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000737
James Henderson66a9d0f2019-04-18 09:13:30 +0000738 Config.AllowBrokenLinks = InputArgs.hasArg(OBJCOPY_allow_broken_links);
739
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000740 Config.DeterministicArchives = InputArgs.hasFlag(
741 OBJCOPY_enable_deterministic_archives,
742 OBJCOPY_disable_deterministic_archives, /*default=*/true);
743
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000744 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
745
Alex Brachet899a3072019-06-15 05:32:23 +0000746 if (Config.PreserveDates &&
747 (Config.OutputFilename == "-" || Config.InputFilename == "-"))
748 return createStringError(errc::invalid_argument,
749 "--preserve-dates requires a file");
750
Eugene Leviant53350d02019-02-26 09:24:22 +0000751 for (auto Arg : InputArgs)
752 if (Arg->getOption().matches(OBJCOPY_set_start)) {
753 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
754 if (!EAddr)
755 return createStringError(
756 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
757
758 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
759 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
760 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
761 if (!EIncr)
762 return createStringError(EIncr.getError(),
763 "bad entry point increment: '%s'",
764 Arg->getValue());
765 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
766 : [](uint64_t A) { return A; };
767 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
768 return Expr(EAddr) + *EIncr;
769 };
770 }
771
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000772 if (Config.DecompressDebugSections &&
773 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000774 return createStringError(
775 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000776 "cannot specify both --compress-debug-sections and "
777 "--decompress-debug-sections");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000778 }
779
780 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000781 return createStringError(
782 errc::invalid_argument,
783 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000784
Peter Collingbourne8d58a982019-06-07 17:57:48 +0000785 if (Config.ExtractPartition && Config.ExtractMainPartition)
786 return createStringError(errc::invalid_argument,
787 "cannot specify --extract-partition together with "
788 "--extract-main-partition");
789
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000790 DC.CopyConfigs.push_back(std::move(Config));
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800791 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000792}
793
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800794// ParseInstallNameToolOptions returns the config and sets the input arguments.
795// If a help flag is set then ParseInstallNameToolOptions will print the help
796// messege and exit.
797Expected<DriverConfig>
798parseInstallNameToolOptions(ArrayRef<const char *> ArgsArr) {
799 DriverConfig DC;
800 CopyConfig Config;
801 InstallNameToolOptTable T;
802 unsigned MissingArgumentIndex, MissingArgumentCount;
803 llvm::opt::InputArgList InputArgs =
804 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
805
806 if (InputArgs.size() == 0) {
807 printHelp(T, errs(), "llvm-install-name-tool");
808 exit(1);
809 }
810
811 if (InputArgs.hasArg(INSTALL_NAME_TOOL_help)) {
812 printHelp(T, outs(), "llvm-install-name-tool");
813 exit(0);
814 }
815
816 if (InputArgs.hasArg(INSTALL_NAME_TOOL_version)) {
817 outs() << "llvm-install-name-tool, compatible with cctools "
818 "install_name_tool\n";
819 cl::PrintVersionMessage();
820 exit(0);
821 }
822
823 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_add_rpath))
824 Config.RPathToAdd.push_back(Arg->getValue());
825
826 SmallVector<StringRef, 2> Positional;
827 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_UNKNOWN))
828 return createStringError(errc::invalid_argument, "unknown argument '%s'",
829 Arg->getAsString(InputArgs).c_str());
830 for (auto Arg : InputArgs.filtered(INSTALL_NAME_TOOL_INPUT))
831 Positional.push_back(Arg->getValue());
832 if (Positional.empty())
833 return createStringError(errc::invalid_argument, "no input file specified");
834 if (Positional.size() > 1)
835 return createStringError(
836 errc::invalid_argument,
837 "llvm-install-name-tool expects a single input file");
838 Config.InputFilename = Positional[0];
839 Config.OutputFilename = Positional[0];
840
841 DC.CopyConfigs.push_back(std::move(Config));
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800842 return std::move(DC);
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800843}
844
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000845// ParseStripOptions returns the config and sets the input arguments. If a
846// help flag is set then ParseStripOptions will print the help messege and
847// exit.
Alex Brachet77477002019-06-18 00:39:10 +0000848Expected<DriverConfig>
849parseStripOptions(ArrayRef<const char *> ArgsArr,
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000850 llvm::function_ref<Error(Error)> ErrorCallback) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000851 StripOptTable T;
852 unsigned MissingArgumentIndex, MissingArgumentCount;
853 llvm::opt::InputArgList InputArgs =
854 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
855
856 if (InputArgs.size() == 0) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000857 printHelp(T, errs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000858 exit(1);
859 }
860
861 if (InputArgs.hasArg(STRIP_help)) {
Michael Pozulpc45fd0c2019-09-14 01:14:43 +0000862 printHelp(T, outs(), "llvm-strip");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000863 exit(0);
864 }
865
866 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000867 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000868 cl::PrintVersionMessage();
869 exit(0);
870 }
871
Alex Brachet899a3072019-06-15 05:32:23 +0000872 SmallVector<StringRef, 2> Positional;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000873 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000874 return createStringError(errc::invalid_argument, "unknown argument '%s'",
875 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000876 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
877 Positional.push_back(Arg->getValue());
878
879 if (Positional.empty())
Alex Brachetd54d4f92019-06-14 02:04:02 +0000880 return createStringError(errc::invalid_argument, "no input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000881
882 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000883 return createStringError(
884 errc::invalid_argument,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000885 "multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000886
887 CopyConfig Config;
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000888
889 if (InputArgs.hasArg(STRIP_regex) && InputArgs.hasArg(STRIP_wildcard))
890 return createStringError(errc::invalid_argument,
891 "--regex and --wildcard are incompatible");
892 MatchStyle SectionMatchStyle =
893 InputArgs.hasArg(STRIP_regex) ? MatchStyle::Regex : MatchStyle::Wildcard;
894 MatchStyle SymbolMatchStyle = InputArgs.hasArg(STRIP_regex)
895 ? MatchStyle::Regex
896 : InputArgs.hasArg(STRIP_wildcard)
897 ? MatchStyle::Wildcard
898 : MatchStyle::Literal;
James Henderson66a9d0f2019-04-18 09:13:30 +0000899 Config.AllowBrokenLinks = InputArgs.hasArg(STRIP_allow_broken_links);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000900 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
901
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000902 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
903 Config.DiscardMode =
904 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
905 ? DiscardType::All
906 : DiscardType::Locals;
Wolfgang Piebab751a72019-08-08 00:35:16 +0000907 Config.StripSections = InputArgs.hasArg(STRIP_strip_sections);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000908 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
James Hendersone4a89a12019-05-02 11:53:02 +0000909 if (auto Arg = InputArgs.getLastArg(STRIP_strip_all, STRIP_no_strip_all))
910 Config.StripAll = Arg->getOption().getID() == STRIP_strip_all;
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000911 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Jordan Rupprecht12ed01d2019-03-14 21:51:42 +0000912 Config.OnlyKeepDebug = InputArgs.hasArg(STRIP_only_keep_debug);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000913 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000914
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000915 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000916 if (Error E = Config.KeepSection.addMatcher(NameOrPattern::create(
917 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800918 return std::move(E);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000919
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000920 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000921 if (Error E = Config.ToRemove.addMatcher(NameOrPattern::create(
922 Arg->getValue(), SectionMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800923 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000924
Eugene Leviant2267c582019-01-31 12:16:20 +0000925 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000926 if (Error E = Config.SymbolsToRemove.addMatcher(NameOrPattern::create(
927 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800928 return std::move(E);
Eugene Leviant2267c582019-01-31 12:16:20 +0000929
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000930 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Jordan Rupprechtedeebad2019-10-17 20:51:00 +0000931 if (Error E = Config.SymbolsToKeep.addMatcher(NameOrPattern::create(
932 Arg->getValue(), SymbolMatchStyle, ErrorCallback)))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800933 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000934
James Hendersone4a89a12019-05-02 11:53:02 +0000935 if (!InputArgs.hasArg(STRIP_no_strip_all) && !Config.StripDebug &&
936 !Config.StripUnneeded && Config.DiscardMode == DiscardType::None &&
937 !Config.StripAllGNU && Config.SymbolsToRemove.empty())
Eugene Leviant2267c582019-01-31 12:16:20 +0000938 Config.StripAll = true;
939
Sid Manning5ad18a72019-05-03 14:14:01 +0000940 if (Config.DiscardMode == DiscardType::All)
941 Config.StripDebug = true;
942
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000943 Config.DeterministicArchives =
944 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
945 STRIP_disable_deterministic_archives, /*default=*/true);
946
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000947 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000948 Config.InputFormat = FileFormat::Unspecified;
949 Config.OutputFormat = FileFormat::Unspecified;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000950
951 DriverConfig DC;
952 if (Positional.size() == 1) {
953 Config.InputFilename = Positional[0];
954 Config.OutputFilename =
955 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
956 DC.CopyConfigs.push_back(std::move(Config));
957 } else {
Alex Brachet77477002019-06-18 00:39:10 +0000958 StringMap<unsigned> InputFiles;
Alex Brachet899a3072019-06-15 05:32:23 +0000959 for (StringRef Filename : Positional) {
Alex Brachet77477002019-06-18 00:39:10 +0000960 if (InputFiles[Filename]++ == 1) {
961 if (Filename == "-")
962 return createStringError(
963 errc::invalid_argument,
964 "cannot specify '-' as an input file more than once");
965 if (Error E = ErrorCallback(createStringError(
966 errc::invalid_argument, "'%s' was already specified",
967 Filename.str().c_str())))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800968 return std::move(E);
Alex Brachet77477002019-06-18 00:39:10 +0000969 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000970 Config.InputFilename = Filename;
971 Config.OutputFilename = Filename;
972 DC.CopyConfigs.push_back(Config);
973 }
974 }
975
Alex Brachet899a3072019-06-15 05:32:23 +0000976 if (Config.PreserveDates && (is_contained(Positional, "-") ||
977 InputArgs.getLastArgValue(STRIP_output) == "-"))
978 return createStringError(errc::invalid_argument,
979 "--preserve-dates requires a file");
980
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800981 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000982}
983
984} // namespace objcopy
985} // namespace llvm