blob: 3972a56a06b979df8fd40ddb19d0a7078480f3f9 [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"
10#include "llvm-objcopy.h"
11
12#include "llvm/ADT/BitmaskEnum.h"
13#include "llvm/ADT/Optional.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/ADT/StringRef.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000016#include "llvm/Option/Arg.h"
17#include "llvm/Option/ArgList.h"
18#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
66enum StripID {
67 STRIP_INVALID = 0, // This is not an option ID.
68#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
69 HELPTEXT, METAVAR, VALUES) \
70 STRIP_##ID,
71#include "StripOpts.inc"
72#undef OPTION
73};
74
75#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
76#include "StripOpts.inc"
77#undef PREFIX
78
79static const opt::OptTable::Info StripInfoTable[] = {
80#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
81 HELPTEXT, METAVAR, VALUES) \
82 {STRIP_##PREFIX, NAME, HELPTEXT, \
83 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
84 PARAM, FLAGS, STRIP_##GROUP, \
85 STRIP_##ALIAS, ALIASARGS, VALUES},
86#include "StripOpts.inc"
87#undef OPTION
88};
89
90class StripOptTable : public opt::OptTable {
91public:
Jordan Rupprechtaaeaa0a2018-10-23 18:46:33 +000092 StripOptTable() : OptTable(StripInfoTable) {}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000093};
94
95enum SectionFlag {
96 SecNone = 0,
97 SecAlloc = 1 << 0,
98 SecLoad = 1 << 1,
99 SecNoload = 1 << 2,
100 SecReadonly = 1 << 3,
101 SecDebug = 1 << 4,
102 SecCode = 1 << 5,
103 SecData = 1 << 6,
104 SecRom = 1 << 7,
105 SecMerge = 1 << 8,
106 SecStrings = 1 << 9,
107 SecContents = 1 << 10,
108 SecShare = 1 << 11,
109 LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ SecShare)
110};
111
112} // namespace
113
114static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
115 return llvm::StringSwitch<SectionFlag>(SectionName)
116 .Case("alloc", SectionFlag::SecAlloc)
117 .Case("load", SectionFlag::SecLoad)
118 .Case("noload", SectionFlag::SecNoload)
119 .Case("readonly", SectionFlag::SecReadonly)
120 .Case("debug", SectionFlag::SecDebug)
121 .Case("code", SectionFlag::SecCode)
122 .Case("data", SectionFlag::SecData)
123 .Case("rom", SectionFlag::SecRom)
124 .Case("merge", SectionFlag::SecMerge)
125 .Case("strings", SectionFlag::SecStrings)
126 .Case("contents", SectionFlag::SecContents)
127 .Case("share", SectionFlag::SecShare)
128 .Default(SectionFlag::SecNone);
129}
130
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000131static Expected<uint64_t>
132parseSectionFlagSet(ArrayRef<StringRef> SectionFlags) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000133 SectionFlag ParsedFlags = SectionFlag::SecNone;
134 for (StringRef Flag : SectionFlags) {
135 SectionFlag ParsedFlag = parseSectionRenameFlag(Flag);
136 if (ParsedFlag == SectionFlag::SecNone)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000137 return createStringError(
138 errc::invalid_argument,
139 "Unrecognized section flag '%s'. Flags supported for GNU "
140 "compatibility: alloc, load, noload, readonly, debug, code, data, "
141 "rom, share, contents, merge, strings",
142 Flag.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000143 ParsedFlags |= ParsedFlag;
144 }
145
146 uint64_t NewFlags = 0;
147 if (ParsedFlags & SectionFlag::SecAlloc)
148 NewFlags |= ELF::SHF_ALLOC;
149 if (!(ParsedFlags & SectionFlag::SecReadonly))
150 NewFlags |= ELF::SHF_WRITE;
151 if (ParsedFlags & SectionFlag::SecCode)
152 NewFlags |= ELF::SHF_EXECINSTR;
153 if (ParsedFlags & SectionFlag::SecMerge)
154 NewFlags |= ELF::SHF_MERGE;
155 if (ParsedFlags & SectionFlag::SecStrings)
156 NewFlags |= ELF::SHF_STRINGS;
157 return NewFlags;
158}
159
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000160static Expected<SectionRename> parseRenameSectionValue(StringRef FlagValue) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000161 if (!FlagValue.contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000162 return createStringError(errc::invalid_argument,
163 "Bad format for --rename-section: missing '='");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000164
165 // Initial split: ".foo" = ".bar,f1,f2,..."
166 auto Old2New = FlagValue.split('=');
167 SectionRename SR;
168 SR.OriginalName = Old2New.first;
169
170 // Flags split: ".bar" "f1" "f2" ...
171 SmallVector<StringRef, 6> NameAndFlags;
172 Old2New.second.split(NameAndFlags, ',');
173 SR.NewName = NameAndFlags[0];
174
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000175 if (NameAndFlags.size() > 1) {
176 Expected<uint64_t> ParsedFlagSet =
177 parseSectionFlagSet(makeArrayRef(NameAndFlags).drop_front());
178 if (!ParsedFlagSet)
179 return ParsedFlagSet.takeError();
180 SR.NewFlags = *ParsedFlagSet;
181 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000182
183 return SR;
184}
185
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000186static Expected<SectionFlagsUpdate>
187parseSetSectionFlagValue(StringRef FlagValue) {
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000188 if (!StringRef(FlagValue).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000189 return createStringError(errc::invalid_argument,
190 "Bad format for --set-section-flags: missing '='");
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000191
192 // Initial split: ".foo" = "f1,f2,..."
193 auto Section2Flags = StringRef(FlagValue).split('=');
194 SectionFlagsUpdate SFU;
195 SFU.Name = Section2Flags.first;
196
197 // Flags split: "f1" "f2" ...
198 SmallVector<StringRef, 6> SectionFlags;
199 Section2Flags.second.split(SectionFlags, ',');
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000200 Expected<uint64_t> ParsedFlagSet = parseSectionFlagSet(SectionFlags);
201 if (!ParsedFlagSet)
202 return ParsedFlagSet.takeError();
203 SFU.NewFlags = *ParsedFlagSet;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000204
205 return SFU;
206}
207
Eugene Leviant51c1f642019-02-25 14:12:41 +0000208static NewSymbolInfo parseNewSymbolInfo(StringRef FlagValue) {
209 // Parse value given with --add-symbol option and create the
210 // new symbol if possible. The value format for --add-symbol is:
211 //
212 // <name>=[<section>:]<value>[,<flags>]
213 //
214 // where:
215 // <name> - symbol name, can be empty string
216 // <section> - optional section name. If not given ABS symbol is created
217 // <value> - symbol value, can be decimal or hexadecimal number prefixed
218 // with 0x.
219 // <flags> - optional flags affecting symbol type, binding or visibility:
220 // The following are currently supported:
221 //
222 // global, local, weak, default, hidden, file, section, object,
223 // indirect-function.
224 //
225 // The following flags are ignored and provided for GNU
226 // compatibility only:
227 //
228 // warning, debug, constructor, indirect, synthetic,
229 // unique-object, before=<symbol>.
230 NewSymbolInfo SI;
231 StringRef Value;
232 std::tie(SI.SymbolName, Value) = FlagValue.split('=');
233 if (Value.empty())
234 error("bad format for --add-symbol, missing '=' after '" + SI.SymbolName +
235 "'");
236
237 if (Value.contains(':')) {
238 std::tie(SI.SectionName, Value) = Value.split(':');
239 if (SI.SectionName.empty() || Value.empty())
240 error(
241 "bad format for --add-symbol, missing section name or symbol value");
242 }
243
244 SmallVector<StringRef, 6> Flags;
245 Value.split(Flags, ',');
246 if (Flags[0].getAsInteger(0, SI.Value))
247 error("bad symbol value: '" + Flags[0] + "'");
248
249 typedef std::function<void(void)> Functor;
250 size_t NumFlags = Flags.size();
251 for (size_t I = 1; I < NumFlags; ++I)
252 static_cast<Functor>(
253 StringSwitch<Functor>(Flags[I])
254 .CaseLower("global", [&SI] { SI.Bind = ELF::STB_GLOBAL; })
255 .CaseLower("local", [&SI] { SI.Bind = ELF::STB_LOCAL; })
256 .CaseLower("weak", [&SI] { SI.Bind = ELF::STB_WEAK; })
257 .CaseLower("default", [&SI] { SI.Visibility = ELF::STV_DEFAULT; })
258 .CaseLower("hidden", [&SI] { SI.Visibility = ELF::STV_HIDDEN; })
259 .CaseLower("file", [&SI] { SI.Type = ELF::STT_FILE; })
260 .CaseLower("section", [&SI] { SI.Type = ELF::STT_SECTION; })
261 .CaseLower("object", [&SI] { SI.Type = ELF::STT_OBJECT; })
262 .CaseLower("function", [&SI] { SI.Type = ELF::STT_FUNC; })
263 .CaseLower("indirect-function",
264 [&SI] { SI.Type = ELF::STT_GNU_IFUNC; })
265 .CaseLower("debug", [] {})
266 .CaseLower("constructor", [] {})
267 .CaseLower("warning", [] {})
268 .CaseLower("indirect", [] {})
269 .CaseLower("synthetic", [] {})
270 .CaseLower("unique-object", [] {})
271 .StartsWithLower("before", [] {})
272 .Default([&] {
273 error("unsupported flag '" + Flags[I] + "' for --add-symbol");
274 }))();
275 return SI;
276}
277
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000278static const StringMap<MachineInfo> ArchMap{
279 // Name, {EMachine, 64bit, LittleEndian}
280 {"aarch64", {ELF::EM_AARCH64, true, true}},
281 {"arm", {ELF::EM_ARM, false, true}},
282 {"i386", {ELF::EM_386, false, true}},
283 {"i386:x86-64", {ELF::EM_X86_64, true, true}},
284 {"powerpc:common64", {ELF::EM_PPC64, true, true}},
285 {"sparc", {ELF::EM_SPARC, false, true}},
286 {"x86-64", {ELF::EM_X86_64, true, true}},
287};
288
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000289static Expected<const MachineInfo &> getMachineInfo(StringRef Arch) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000290 auto Iter = ArchMap.find(Arch);
291 if (Iter == std::end(ArchMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000292 return createStringError(errc::invalid_argument,
293 "Invalid architecture: '%s'", Arch.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000294 return Iter->getValue();
295}
296
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000297static const StringMap<MachineInfo> OutputFormatMap{
298 // Name, {EMachine, 64bit, LittleEndian}
299 {"elf32-i386", {ELF::EM_386, false, true}},
300 {"elf32-powerpcle", {ELF::EM_PPC, false, true}},
301 {"elf32-x86-64", {ELF::EM_X86_64, false, true}},
302 {"elf64-powerpcle", {ELF::EM_PPC64, true, true}},
303 {"elf64-x86-64", {ELF::EM_X86_64, true, true}},
304};
305
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000306static Expected<const MachineInfo &>
307getOutputFormatMachineInfo(StringRef Format) {
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000308 auto Iter = OutputFormatMap.find(Format);
309 if (Iter == std::end(OutputFormatMap))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000310 return createStringError(errc::invalid_argument,
311 "Invalid output format: '%s'",
312 Format.str().c_str());
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000313 return Iter->getValue();
314}
315
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000316static Error addSymbolsFromFile(std::vector<NameOrRegex> &Symbols,
317 BumpPtrAllocator &Alloc, StringRef Filename,
318 bool UseRegex) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000319 StringSaver Saver(Alloc);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000320 SmallVector<StringRef, 16> Lines;
321 auto BufOrErr = MemoryBuffer::getFile(Filename);
322 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000323 return createFileError(Filename, BufOrErr.getError());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000324
325 BufOrErr.get()->getBuffer().split(Lines, '\n');
326 for (StringRef Line : Lines) {
327 // Ignore everything after '#', trim whitespace, and only add the symbol if
328 // it's not empty.
329 auto TrimmedLine = Line.split('#').first.trim();
330 if (!TrimmedLine.empty())
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000331 Symbols.emplace_back(Saver.save(TrimmedLine), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000332 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000333
334 return Error::success();
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000335}
336
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000337NameOrRegex::NameOrRegex(StringRef Pattern, bool IsRegex) {
338 if (!IsRegex) {
339 Name = Pattern;
340 return;
341 }
342
343 SmallVector<char, 32> Data;
344 R = std::make_shared<Regex>(
345 ("^" + Pattern.ltrim('^').rtrim('$') + "$").toStringRef(Data));
346}
347
Eugene Leviant340cb872019-02-08 10:33:16 +0000348static Error addSymbolsToRenameFromFile(StringMap<StringRef> &SymbolsToRename,
349 BumpPtrAllocator &Alloc,
350 StringRef Filename) {
351 StringSaver Saver(Alloc);
352 SmallVector<StringRef, 16> Lines;
353 auto BufOrErr = MemoryBuffer::getFile(Filename);
354 if (!BufOrErr)
Eugene Leviant317f9e72019-02-11 09:49:37 +0000355 return createFileError(Filename, BufOrErr.getError());
Eugene Leviant340cb872019-02-08 10:33:16 +0000356
357 BufOrErr.get()->getBuffer().split(Lines, '\n');
358 size_t NumLines = Lines.size();
359 for (size_t LineNo = 0; LineNo < NumLines; ++LineNo) {
360 StringRef TrimmedLine = Lines[LineNo].split('#').first.trim();
361 if (TrimmedLine.empty())
362 continue;
363
364 std::pair<StringRef, StringRef> Pair = Saver.save(TrimmedLine).split(' ');
365 StringRef NewName = Pair.second.trim();
366 if (NewName.empty())
367 return createStringError(errc::invalid_argument,
368 "%s:%zu: missing new symbol name",
369 Filename.str().c_str(), LineNo + 1);
370 SymbolsToRename.insert({Pair.first, NewName});
371 }
372 return Error::success();
373}
Eugene Leviant53350d02019-02-26 09:24:22 +0000374
375template <class T> static ErrorOr<T> getAsInteger(StringRef Val) {
376 T Result;
377 if (Val.getAsInteger(0, Result))
378 return errc::invalid_argument;
379 return Result;
380}
381
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000382// ParseObjcopyOptions returns the config and sets the input arguments. If a
383// help flag is set then ParseObjcopyOptions will print the help messege and
384// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000385Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000386 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000387 ObjcopyOptTable T;
388 unsigned MissingArgumentIndex, MissingArgumentCount;
389 llvm::opt::InputArgList InputArgs =
390 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
391
392 if (InputArgs.size() == 0) {
393 T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
394 exit(1);
395 }
396
397 if (InputArgs.hasArg(OBJCOPY_help)) {
398 T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
399 exit(0);
400 }
401
402 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000403 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000404 cl::PrintVersionMessage();
405 exit(0);
406 }
407
408 SmallVector<const char *, 2> Positional;
409
410 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000411 return createStringError(errc::invalid_argument, "unknown argument '%s'",
412 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000413
414 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
415 Positional.push_back(Arg->getValue());
416
417 if (Positional.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000418 return createStringError(errc::invalid_argument, "No input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000419
420 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000421 return createStringError(errc::invalid_argument,
422 "Too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000423
424 CopyConfig Config;
425 Config.InputFilename = Positional[0];
426 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000427 if (InputArgs.hasArg(OBJCOPY_target) &&
428 (InputArgs.hasArg(OBJCOPY_input_target) ||
429 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000430 return createStringError(
431 errc::invalid_argument,
432 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000433
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000434 bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000435 if (InputArgs.hasArg(OBJCOPY_target)) {
436 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
437 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
438 } else {
439 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
440 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
441 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000442 if (Config.InputFormat == "binary") {
443 auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
444 if (BinaryArch.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000445 return createStringError(
446 errc::invalid_argument,
447 "Specified binary input without specifiying an architecture");
448 Expected<const MachineInfo &> MI = getMachineInfo(BinaryArch);
449 if (!MI)
450 return MI.takeError();
451 Config.BinaryArch = *MI;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000452 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000453 if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary") {
454 Expected<const MachineInfo &> MI =
455 getOutputFormatMachineInfo(Config.OutputFormat);
456 if (!MI)
457 return MI.takeError();
458 Config.OutputArch = *MI;
459 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000460
461 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
462 OBJCOPY_compress_debug_sections_eq)) {
463 Config.CompressionType = DebugCompressionType::Z;
464
465 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
466 Config.CompressionType =
467 StringSwitch<DebugCompressionType>(
468 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
469 .Case("zlib-gnu", DebugCompressionType::GNU)
470 .Case("zlib", DebugCompressionType::Z)
471 .Default(DebugCompressionType::None);
472 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000473 return createStringError(
474 errc::invalid_argument,
475 "Invalid or unsupported --compress-debug-sections format: %s",
476 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
477 .str()
478 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000479 if (!zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000480 return createStringError(
481 errc::invalid_argument,
482 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000483 }
484 }
485
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000486 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000487 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
488 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
489 Config.BuildIdLinkInput =
490 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
491 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
492 Config.BuildIdLinkOutput =
493 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
494 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000495 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
496
497 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
498 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000499 return createStringError(errc::invalid_argument,
500 "Bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000501 auto Old2New = StringRef(Arg->getValue()).split('=');
502 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000503 return createStringError(errc::invalid_argument,
504 "Multiple redefinition of symbol %s",
505 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000506 }
507
Eugene Leviant340cb872019-02-08 10:33:16 +0000508 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
509 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
510 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000511 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000512
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000513 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000514 Expected<SectionRename> SR =
515 parseRenameSectionValue(StringRef(Arg->getValue()));
516 if (!SR)
517 return SR.takeError();
518 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
519 return createStringError(errc::invalid_argument,
520 "Multiple renames of section %s",
521 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000522 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000523 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000524 Expected<SectionFlagsUpdate> SFU =
525 parseSetSectionFlagValue(Arg->getValue());
526 if (!SFU)
527 return SFU.takeError();
528 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
529 return createStringError(
530 errc::invalid_argument,
531 "--set-section-flags set multiple times for section %s",
532 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000533 }
534 // Prohibit combinations of --set-section-flags when the section name is used
535 // by --rename-section, either as a source or a destination.
536 for (const auto &E : Config.SectionsToRename) {
537 const SectionRename &SR = E.second;
538 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000539 return createStringError(
540 errc::invalid_argument,
541 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
542 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
543 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000544 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000545 return createStringError(
546 errc::invalid_argument,
547 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
548 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
549 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000550 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000551
552 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000553 Config.ToRemove.emplace_back(Arg->getValue(), UseRegex);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000554 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000555 Config.KeepSection.emplace_back(Arg->getValue(), UseRegex);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000556 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000557 Config.OnlySection.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000558 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
559 Config.AddSection.push_back(Arg->getValue());
560 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
561 Config.DumpSection.push_back(Arg->getValue());
562 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
563 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
564 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
565 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
566 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
567 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
568 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
569 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
570 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
571 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000572 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
573 Config.DiscardMode =
574 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
575 ? DiscardType::All
576 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000577 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
578 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
579 Config.DecompressDebugSections =
580 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
581 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000582 Config.SymbolsToLocalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000583 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000584 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
585 Arg->getValue(), UseRegex))
586 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000587 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000588 Config.SymbolsToKeepGlobal.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000589 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000590 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
591 Arg->getValue(), UseRegex))
592 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000593 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000594 Config.SymbolsToGlobalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000595 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000596 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
597 Arg->getValue(), UseRegex))
598 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000599 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000600 Config.SymbolsToWeaken.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000601 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000602 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
603 Arg->getValue(), UseRegex))
604 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000605 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000606 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000607 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000608 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
609 Arg->getValue(), UseRegex))
610 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000611 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
612 Config.UnneededSymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
613 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000614 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
615 Arg->getValue(), UseRegex))
616 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000617 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000618 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviant51c1f642019-02-25 14:12:41 +0000619 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol))
620 Config.SymbolsToAdd.push_back(parseNewSymbolInfo(Arg->getValue()));
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000621
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000622 Config.DeterministicArchives = InputArgs.hasFlag(
623 OBJCOPY_enable_deterministic_archives,
624 OBJCOPY_disable_deterministic_archives, /*default=*/true);
625
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000626 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
627
Eugene Leviant53350d02019-02-26 09:24:22 +0000628 for (auto Arg : InputArgs)
629 if (Arg->getOption().matches(OBJCOPY_set_start)) {
630 auto EAddr = getAsInteger<uint64_t>(Arg->getValue());
631 if (!EAddr)
632 return createStringError(
633 EAddr.getError(), "bad entry point address: '%s'", Arg->getValue());
634
635 Config.EntryExpr = [EAddr](uint64_t) { return *EAddr; };
636 } else if (Arg->getOption().matches(OBJCOPY_change_start)) {
637 auto EIncr = getAsInteger<int64_t>(Arg->getValue());
638 if (!EIncr)
639 return createStringError(EIncr.getError(),
640 "bad entry point increment: '%s'",
641 Arg->getValue());
642 auto Expr = Config.EntryExpr ? std::move(Config.EntryExpr)
643 : [](uint64_t A) { return A; };
644 Config.EntryExpr = [Expr, EIncr](uint64_t EAddr) {
645 return Expr(EAddr) + *EIncr;
646 };
647 }
648
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000649 if (Config.DecompressDebugSections &&
650 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000651 return createStringError(
652 errc::invalid_argument,
653 "Cannot specify --compress-debug-sections at the same time as "
654 "--decompress-debug-sections at the same time");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000655 }
656
657 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000658 return createStringError(
659 errc::invalid_argument,
660 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000661
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000662 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000663 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000664}
665
666// ParseStripOptions returns the config and sets the input arguments. If a
667// help flag is set then ParseStripOptions will print the help messege and
668// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000669Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000670 StripOptTable T;
671 unsigned MissingArgumentIndex, MissingArgumentCount;
672 llvm::opt::InputArgList InputArgs =
673 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
674
675 if (InputArgs.size() == 0) {
676 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
677 exit(1);
678 }
679
680 if (InputArgs.hasArg(STRIP_help)) {
681 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
682 exit(0);
683 }
684
685 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000686 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000687 cl::PrintVersionMessage();
688 exit(0);
689 }
690
691 SmallVector<const char *, 2> Positional;
692 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000693 return createStringError(errc::invalid_argument, "unknown argument '%s'",
694 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000695 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
696 Positional.push_back(Arg->getValue());
697
698 if (Positional.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000699 return createStringError(errc::invalid_argument, "No input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000700
701 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000702 return createStringError(
703 errc::invalid_argument,
704 "Multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000705
706 CopyConfig Config;
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000707 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000708 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
709
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000710 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
711 Config.DiscardMode =
712 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
713 ? DiscardType::All
714 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000715 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
716 Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000717 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000718 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000719
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000720 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000721 Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000722
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000723 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000724 Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000725
Eugene Leviant2267c582019-01-31 12:16:20 +0000726 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000727 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
Eugene Leviant2267c582019-01-31 12:16:20 +0000728
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000729 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000730 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000731
Eugene Leviant2267c582019-01-31 12:16:20 +0000732 if (!Config.StripDebug && !Config.StripUnneeded &&
733 Config.DiscardMode == DiscardType::None && !Config.StripAllGNU && Config.SymbolsToRemove.empty())
734 Config.StripAll = true;
735
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000736 Config.DeterministicArchives =
737 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
738 STRIP_disable_deterministic_archives, /*default=*/true);
739
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000740 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
741
742 DriverConfig DC;
743 if (Positional.size() == 1) {
744 Config.InputFilename = Positional[0];
745 Config.OutputFilename =
746 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
747 DC.CopyConfigs.push_back(std::move(Config));
748 } else {
749 for (const char *Filename : Positional) {
750 Config.InputFilename = Filename;
751 Config.OutputFilename = Filename;
752 DC.CopyConfigs.push_back(Config);
753 }
754 }
755
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000756 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000757}
758
759} // namespace objcopy
760} // namespace llvm