blob: 1e8ca51043cc403276cf7846619b74405344d310 [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}
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000374// ParseObjcopyOptions returns the config and sets the input arguments. If a
375// help flag is set then ParseObjcopyOptions will print the help messege and
376// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000377Expected<DriverConfig> parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Jordan Rupprecht5745c5f2019-02-04 18:38:00 +0000378 DriverConfig DC;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000379 ObjcopyOptTable T;
380 unsigned MissingArgumentIndex, MissingArgumentCount;
381 llvm::opt::InputArgList InputArgs =
382 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
383
384 if (InputArgs.size() == 0) {
385 T.PrintHelp(errs(), "llvm-objcopy input [output]", "objcopy tool");
386 exit(1);
387 }
388
389 if (InputArgs.hasArg(OBJCOPY_help)) {
390 T.PrintHelp(outs(), "llvm-objcopy input [output]", "objcopy tool");
391 exit(0);
392 }
393
394 if (InputArgs.hasArg(OBJCOPY_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000395 outs() << "llvm-objcopy, compatible with GNU objcopy\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000396 cl::PrintVersionMessage();
397 exit(0);
398 }
399
400 SmallVector<const char *, 2> Positional;
401
402 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000403 return createStringError(errc::invalid_argument, "unknown argument '%s'",
404 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000405
406 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
407 Positional.push_back(Arg->getValue());
408
409 if (Positional.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000410 return createStringError(errc::invalid_argument, "No input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000411
412 if (Positional.size() > 2)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000413 return createStringError(errc::invalid_argument,
414 "Too many positional arguments");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000415
416 CopyConfig Config;
417 Config.InputFilename = Positional[0];
418 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000419 if (InputArgs.hasArg(OBJCOPY_target) &&
420 (InputArgs.hasArg(OBJCOPY_input_target) ||
421 InputArgs.hasArg(OBJCOPY_output_target)))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000422 return createStringError(
423 errc::invalid_argument,
424 "--target cannot be used with --input-target or --output-target");
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000425
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000426 bool UseRegex = InputArgs.hasArg(OBJCOPY_regex);
Jordan Rupprechtbb4588e2018-10-12 00:36:01 +0000427 if (InputArgs.hasArg(OBJCOPY_target)) {
428 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
429 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_target);
430 } else {
431 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
432 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
433 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000434 if (Config.InputFormat == "binary") {
435 auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
436 if (BinaryArch.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000437 return createStringError(
438 errc::invalid_argument,
439 "Specified binary input without specifiying an architecture");
440 Expected<const MachineInfo &> MI = getMachineInfo(BinaryArch);
441 if (!MI)
442 return MI.takeError();
443 Config.BinaryArch = *MI;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000444 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000445 if (!Config.OutputFormat.empty() && Config.OutputFormat != "binary") {
446 Expected<const MachineInfo &> MI =
447 getOutputFormatMachineInfo(Config.OutputFormat);
448 if (!MI)
449 return MI.takeError();
450 Config.OutputArch = *MI;
451 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000452
453 if (auto Arg = InputArgs.getLastArg(OBJCOPY_compress_debug_sections,
454 OBJCOPY_compress_debug_sections_eq)) {
455 Config.CompressionType = DebugCompressionType::Z;
456
457 if (Arg->getOption().getID() == OBJCOPY_compress_debug_sections_eq) {
458 Config.CompressionType =
459 StringSwitch<DebugCompressionType>(
460 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq))
461 .Case("zlib-gnu", DebugCompressionType::GNU)
462 .Case("zlib", DebugCompressionType::Z)
463 .Default(DebugCompressionType::None);
464 if (Config.CompressionType == DebugCompressionType::None)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000465 return createStringError(
466 errc::invalid_argument,
467 "Invalid or unsupported --compress-debug-sections format: %s",
468 InputArgs.getLastArgValue(OBJCOPY_compress_debug_sections_eq)
469 .str()
470 .c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000471 if (!zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000472 return createStringError(
473 errc::invalid_argument,
474 "LLVM was not compiled with LLVM_ENABLE_ZLIB: can not compress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000475 }
476 }
477
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000478 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000479 Config.BuildIdLinkDir = InputArgs.getLastArgValue(OBJCOPY_build_id_link_dir);
480 if (InputArgs.hasArg(OBJCOPY_build_id_link_input))
481 Config.BuildIdLinkInput =
482 InputArgs.getLastArgValue(OBJCOPY_build_id_link_input);
483 if (InputArgs.hasArg(OBJCOPY_build_id_link_output))
484 Config.BuildIdLinkOutput =
485 InputArgs.getLastArgValue(OBJCOPY_build_id_link_output);
486 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000487 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
488
489 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
490 if (!StringRef(Arg->getValue()).contains('='))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000491 return createStringError(errc::invalid_argument,
492 "Bad format for --redefine-sym");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000493 auto Old2New = StringRef(Arg->getValue()).split('=');
494 if (!Config.SymbolsToRename.insert(Old2New).second)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000495 return createStringError(errc::invalid_argument,
496 "Multiple redefinition of symbol %s",
497 Old2New.first.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000498 }
499
Eugene Leviant340cb872019-02-08 10:33:16 +0000500 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbols))
501 if (Error E = addSymbolsToRenameFromFile(Config.SymbolsToRename, DC.Alloc,
502 Arg->getValue()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000503 return std::move(E);
Eugene Leviant340cb872019-02-08 10:33:16 +0000504
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000505 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000506 Expected<SectionRename> SR =
507 parseRenameSectionValue(StringRef(Arg->getValue()));
508 if (!SR)
509 return SR.takeError();
510 if (!Config.SectionsToRename.try_emplace(SR->OriginalName, *SR).second)
511 return createStringError(errc::invalid_argument,
512 "Multiple renames of section %s",
513 SR->OriginalName.str().c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000514 }
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000515 for (auto Arg : InputArgs.filtered(OBJCOPY_set_section_flags)) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000516 Expected<SectionFlagsUpdate> SFU =
517 parseSetSectionFlagValue(Arg->getValue());
518 if (!SFU)
519 return SFU.takeError();
520 if (!Config.SetSectionFlags.try_emplace(SFU->Name, *SFU).second)
521 return createStringError(
522 errc::invalid_argument,
523 "--set-section-flags set multiple times for section %s",
524 SFU->Name.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000525 }
526 // Prohibit combinations of --set-section-flags when the section name is used
527 // by --rename-section, either as a source or a destination.
528 for (const auto &E : Config.SectionsToRename) {
529 const SectionRename &SR = E.second;
530 if (Config.SetSectionFlags.count(SR.OriginalName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000531 return createStringError(
532 errc::invalid_argument,
533 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
534 SR.OriginalName.str().c_str(), SR.OriginalName.str().c_str(),
535 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000536 if (Config.SetSectionFlags.count(SR.NewName))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000537 return createStringError(
538 errc::invalid_argument,
539 "--set-section-flags=%s conflicts with --rename-section=%s=%s",
540 SR.NewName.str().c_str(), SR.OriginalName.str().c_str(),
541 SR.NewName.str().c_str());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000542 }
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000543
544 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000545 Config.ToRemove.emplace_back(Arg->getValue(), UseRegex);
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000546 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000547 Config.KeepSection.emplace_back(Arg->getValue(), UseRegex);
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000548 for (auto Arg : InputArgs.filtered(OBJCOPY_only_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000549 Config.OnlySection.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000550 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
551 Config.AddSection.push_back(Arg->getValue());
552 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
553 Config.DumpSection.push_back(Arg->getValue());
554 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
555 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
556 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
557 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
558 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
559 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
560 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
561 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
562 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
563 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000564 if (InputArgs.hasArg(OBJCOPY_discard_all, OBJCOPY_discard_locals))
565 Config.DiscardMode =
566 InputArgs.hasFlag(OBJCOPY_discard_all, OBJCOPY_discard_locals)
567 ? DiscardType::All
568 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000569 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
570 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
571 Config.DecompressDebugSections =
572 InputArgs.hasArg(OBJCOPY_decompress_debug_sections);
573 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000574 Config.SymbolsToLocalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000575 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000576 if (Error E = addSymbolsFromFile(Config.SymbolsToLocalize, DC.Alloc,
577 Arg->getValue(), UseRegex))
578 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000579 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000580 Config.SymbolsToKeepGlobal.emplace_back(Arg->getValue(), UseRegex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000581 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000582 if (Error E = addSymbolsFromFile(Config.SymbolsToKeepGlobal, DC.Alloc,
583 Arg->getValue(), UseRegex))
584 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000585 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000586 Config.SymbolsToGlobalize.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000587 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000588 if (Error E = addSymbolsFromFile(Config.SymbolsToGlobalize, DC.Alloc,
589 Arg->getValue(), UseRegex))
590 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000591 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000592 Config.SymbolsToWeaken.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000593 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000594 if (Error E = addSymbolsFromFile(Config.SymbolsToWeaken, DC.Alloc,
595 Arg->getValue(), UseRegex))
596 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000597 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000598 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviante08fe352019-02-08 14:37:54 +0000599 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000600 if (Error E = addSymbolsFromFile(Config.SymbolsToRemove, DC.Alloc,
601 Arg->getValue(), UseRegex))
602 return std::move(E);
Eugene Leviant2db10622019-02-13 07:34:54 +0000603 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbol))
604 Config.UnneededSymbolsToRemove.emplace_back(Arg->getValue(), UseRegex);
605 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_unneeded_symbols))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000606 if (Error E = addSymbolsFromFile(Config.UnneededSymbolsToRemove, DC.Alloc,
607 Arg->getValue(), UseRegex))
608 return std::move(E);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000609 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000610 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegex);
Eugene Leviant51c1f642019-02-25 14:12:41 +0000611 for (auto Arg : InputArgs.filtered(OBJCOPY_add_symbol))
612 Config.SymbolsToAdd.push_back(parseNewSymbolInfo(Arg->getValue()));
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000613
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000614 Config.DeterministicArchives = InputArgs.hasFlag(
615 OBJCOPY_enable_deterministic_archives,
616 OBJCOPY_disable_deterministic_archives, /*default=*/true);
617
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000618 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
619
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000620 if (Config.DecompressDebugSections &&
621 Config.CompressionType != DebugCompressionType::None) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000622 return createStringError(
623 errc::invalid_argument,
624 "Cannot specify --compress-debug-sections at the same time as "
625 "--decompress-debug-sections at the same time");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000626 }
627
628 if (Config.DecompressDebugSections && !zlib::isAvailable())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000629 return createStringError(
630 errc::invalid_argument,
631 "LLVM was not compiled with LLVM_ENABLE_ZLIB: cannot decompress");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000632
Jordan Rupprechtab9f6622018-10-23 20:54:51 +0000633 DC.CopyConfigs.push_back(std::move(Config));
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000634 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000635}
636
637// ParseStripOptions returns the config and sets the input arguments. If a
638// help flag is set then ParseStripOptions will print the help messege and
639// exit.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000640Expected<DriverConfig> parseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000641 StripOptTable T;
642 unsigned MissingArgumentIndex, MissingArgumentCount;
643 llvm::opt::InputArgList InputArgs =
644 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
645
646 if (InputArgs.size() == 0) {
647 T.PrintHelp(errs(), "llvm-strip [options] file...", "strip tool");
648 exit(1);
649 }
650
651 if (InputArgs.hasArg(STRIP_help)) {
652 T.PrintHelp(outs(), "llvm-strip [options] file...", "strip tool");
653 exit(0);
654 }
655
656 if (InputArgs.hasArg(STRIP_version)) {
Martin Storsjoe9af7152018-11-28 06:51:50 +0000657 outs() << "llvm-strip, compatible with GNU strip\n";
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000658 cl::PrintVersionMessage();
659 exit(0);
660 }
661
662 SmallVector<const char *, 2> Positional;
663 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000664 return createStringError(errc::invalid_argument, "unknown argument '%s'",
665 Arg->getAsString(InputArgs).c_str());
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000666 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
667 Positional.push_back(Arg->getValue());
668
669 if (Positional.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000670 return createStringError(errc::invalid_argument, "No input file specified");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000671
672 if (Positional.size() > 1 && InputArgs.hasArg(STRIP_output))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000673 return createStringError(
674 errc::invalid_argument,
675 "Multiple input files cannot be used in combination with -o");
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000676
677 CopyConfig Config;
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000678 bool UseRegexp = InputArgs.hasArg(STRIP_regex);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000679 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
680
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000681 if (InputArgs.hasArg(STRIP_discard_all, STRIP_discard_locals))
682 Config.DiscardMode =
683 InputArgs.hasFlag(STRIP_discard_all, STRIP_discard_locals)
684 ? DiscardType::All
685 : DiscardType::Locals;
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000686 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
687 Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000688 Config.StripAllGNU = InputArgs.hasArg(STRIP_strip_all_gnu);
Eugene Leviant05a3f992019-02-01 15:25:15 +0000689 Config.KeepFileSymbols = InputArgs.hasArg(STRIP_keep_file_symbols);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000690
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000691 for (auto Arg : InputArgs.filtered(STRIP_keep_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000692 Config.KeepSection.emplace_back(Arg->getValue(), UseRegexp);
Jordan Rupprecht30d1b192018-11-01 17:48:46 +0000693
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000694 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000695 Config.ToRemove.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000696
Eugene Leviant2267c582019-01-31 12:16:20 +0000697 for (auto Arg : InputArgs.filtered(STRIP_strip_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000698 Config.SymbolsToRemove.emplace_back(Arg->getValue(), UseRegexp);
Eugene Leviant2267c582019-01-31 12:16:20 +0000699
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000700 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
Eugene Leviantf324f6d2019-02-06 11:00:07 +0000701 Config.SymbolsToKeep.emplace_back(Arg->getValue(), UseRegexp);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000702
Eugene Leviant2267c582019-01-31 12:16:20 +0000703 if (!Config.StripDebug && !Config.StripUnneeded &&
704 Config.DiscardMode == DiscardType::None && !Config.StripAllGNU && Config.SymbolsToRemove.empty())
705 Config.StripAll = true;
706
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000707 Config.DeterministicArchives =
708 InputArgs.hasFlag(STRIP_enable_deterministic_archives,
709 STRIP_disable_deterministic_archives, /*default=*/true);
710
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000711 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
712
713 DriverConfig DC;
714 if (Positional.size() == 1) {
715 Config.InputFilename = Positional[0];
716 Config.OutputFilename =
717 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
718 DC.CopyConfigs.push_back(std::move(Config));
719 } else {
720 for (const char *Filename : Positional) {
721 Config.InputFilename = Filename;
722 Config.OutputFilename = Filename;
723 DC.CopyConfigs.push_back(Config);
724 }
725 }
726
Jordan Rupprecht93ad8b32019-02-21 17:24:55 +0000727 return std::move(DC);
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +0000728}
729
730} // namespace objcopy
731} // namespace llvm