blob: 0bf9bc47d01cb4d120c6225e3e0bb4e40760d80d [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- llvm-objcopy.cpp ---------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00009
Petr Hosek05a04cb2017-08-01 00:33:58 +000010#include "llvm-objcopy.h"
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000011
Petr Hosek05a04cb2017-08-01 00:33:58 +000012#include "Object.h"
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +000013#include "llvm/ADT/BitmaskEnum.h"
14#include "llvm/ADT/Optional.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000015#include "llvm/ADT/STLExtras.h"
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +000016#include "llvm/ADT/SmallVector.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000017#include "llvm/ADT/StringRef.h"
18#include "llvm/ADT/Twine.h"
19#include "llvm/BinaryFormat/ELF.h"
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000020#include "llvm/Object/Archive.h"
21#include "llvm/Object/ArchiveWriter.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000022#include "llvm/Object/Binary.h"
23#include "llvm/Object/ELFObjectFile.h"
24#include "llvm/Object/ELFTypes.h"
25#include "llvm/Object/Error.h"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000026#include "llvm/Option/Arg.h"
27#include "llvm/Option/ArgList.h"
28#include "llvm/Option/Option.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000029#include "llvm/Support/Casting.h"
Petr Hosek05a04cb2017-08-01 00:33:58 +000030#include "llvm/Support/CommandLine.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000031#include "llvm/Support/Compiler.h"
32#include "llvm/Support/Error.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/ErrorOr.h"
Petr Hosek05a04cb2017-08-01 00:33:58 +000035#include "llvm/Support/FileOutputBuffer.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000036#include "llvm/Support/InitLLVM.h"
Jordan Rupprechtcf676332018-08-17 18:51:11 +000037#include "llvm/Support/Memory.h"
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000038#include "llvm/Support/Path.h"
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +000039#include "llvm/Support/Process.h"
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000040#include "llvm/Support/WithColor.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000041#include "llvm/Support/raw_ostream.h"
42#include <algorithm>
43#include <cassert>
44#include <cstdlib>
45#include <functional>
46#include <iterator>
Petr Hosek05a04cb2017-08-01 00:33:58 +000047#include <memory>
48#include <string>
49#include <system_error>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000050#include <utility>
Petr Hosek05a04cb2017-08-01 00:33:58 +000051
52using namespace llvm;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000053using namespace llvm::objcopy;
Petr Hosek05a04cb2017-08-01 00:33:58 +000054using namespace object;
55using namespace ELF;
56
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000057namespace {
58
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000059enum ObjcopyID {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000060 OBJCOPY_INVALID = 0, // This is not an option ID.
61#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
62 HELPTEXT, METAVAR, VALUES) \
63 OBJCOPY_##ID,
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000064#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000065#undef OPTION
66};
67
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000068#define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000069#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000070#undef PREFIX
71
Alexander Shaposhnikov3326e782018-04-24 06:23:22 +000072static const opt::OptTable::Info ObjcopyInfoTable[] = {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000073#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
74 HELPTEXT, METAVAR, VALUES) \
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000075 {OBJCOPY_##PREFIX, \
76 NAME, \
77 HELPTEXT, \
78 METAVAR, \
79 OBJCOPY_##ID, \
80 opt::Option::KIND##Class, \
81 PARAM, \
82 FLAGS, \
83 OBJCOPY_##GROUP, \
84 OBJCOPY_##ALIAS, \
85 ALIASARGS, \
86 VALUES},
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000087#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000088#undef OPTION
89};
90
91class ObjcopyOptTable : public opt::OptTable {
92public:
93 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
94};
95
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000096enum StripID {
97 STRIP_INVALID = 0, // This is not an option ID.
98#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
99 HELPTEXT, METAVAR, VALUES) \
100 STRIP_##ID,
101#include "StripOpts.inc"
102#undef OPTION
103};
104
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000105#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
106#include "StripOpts.inc"
107#undef PREFIX
108
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000109static const opt::OptTable::Info StripInfoTable[] = {
110#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
111 HELPTEXT, METAVAR, VALUES) \
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000112 {STRIP_##PREFIX, NAME, HELPTEXT, \
113 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
114 PARAM, FLAGS, STRIP_##GROUP, \
115 STRIP_##ALIAS, ALIASARGS, VALUES},
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000116#include "StripOpts.inc"
117#undef OPTION
118};
119
120class StripOptTable : public opt::OptTable {
121public:
122 StripOptTable() : OptTable(StripInfoTable, true) {}
123};
124
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +0000125struct SectionRename {
126 StringRef OriginalName;
127 StringRef NewName;
128 Optional<uint64_t> NewFlags;
129};
130
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000131struct CopyConfig {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000132 // Main input/output options
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000133 StringRef InputFilename;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000134 StringRef InputFormat;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000135 StringRef OutputFilename;
136 StringRef OutputFormat;
Alexander Shaposhnikovfedb0162018-02-09 23:33:31 +0000137
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000138 // Only applicable for --input-format=Binary
139 MachineInfo BinaryArch;
140
141 // Advanced options
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000142 StringRef AddGnuDebugLink;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000143 StringRef SplitDWO;
Paul Semel7a3dc2c2018-08-09 17:49:04 +0000144 StringRef SymbolsPrefix;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000145
146 // Repeated options
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000147 std::vector<StringRef> AddSection;
Paul Semela42dec72018-08-09 17:05:21 +0000148 std::vector<StringRef> DumpSection;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000149 std::vector<StringRef> Keep;
150 std::vector<StringRef> OnlyKeep;
Paul Semelee5be792018-04-27 19:09:44 +0000151 std::vector<StringRef> SymbolsToGlobalize;
Paul Semel5d97c822018-05-15 14:09:37 +0000152 std::vector<StringRef> SymbolsToKeep;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000153 std::vector<StringRef> SymbolsToLocalize;
154 std::vector<StringRef> SymbolsToRemove;
155 std::vector<StringRef> SymbolsToWeaken;
156 std::vector<StringRef> ToRemove;
Jordan Rupprechtbe8ebcc2018-08-17 22:34:48 +0000157 std::vector<std::string> SymbolsToKeepGlobal;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000158
159 // Map options
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +0000160 StringMap<SectionRename> SectionsToRename;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000161 StringMap<StringRef> SymbolsToRename;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000162
163 // Boolean options
164 bool DiscardAll = false;
165 bool ExtractDWO = false;
166 bool KeepFileSymbols = false;
167 bool LocalizeHidden = false;
168 bool OnlyKeepDebug = false;
169 bool PreserveDates = false;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000170 bool StripAll = false;
171 bool StripAllGNU = false;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000172 bool StripDWO = false;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000173 bool StripDebug = false;
174 bool StripNonAlloc = false;
175 bool StripSections = false;
Paul Semel99dda0b2018-05-25 11:01:25 +0000176 bool StripUnneeded = false;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000177 bool Weaken = false;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000178};
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000179
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000180using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000181
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +0000182enum SectionFlag {
183 SecNone = 0,
184 SecAlloc = 1 << 0,
185 SecLoad = 1 << 1,
186 SecNoload = 1 << 2,
187 SecReadonly = 1 << 3,
188 SecDebug = 1 << 4,
189 SecCode = 1 << 5,
190 SecData = 1 << 6,
191 SecRom = 1 << 7,
192 SecMerge = 1 << 8,
193 SecStrings = 1 << 9,
194 SecContents = 1 << 10,
195 SecShare = 1 << 11,
196 LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ SecShare)
197};
198
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +0000199} // namespace
200
201namespace llvm {
202namespace objcopy {
203
204// The name this program was invoked as.
205StringRef ToolName;
206
207LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +0000208 WithColor::error(errs(), ToolName) << Message << ".\n";
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +0000209 errs().flush();
210 exit(1);
211}
212
213LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
214 assert(EC);
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +0000215 WithColor::error(errs(), ToolName)
216 << "'" << File << "': " << EC.message() << ".\n";
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +0000217 exit(1);
218}
219
220LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
221 assert(E);
222 std::string Buf;
223 raw_string_ostream OS(Buf);
224 logAllUnhandledErrors(std::move(E), OS, "");
225 OS.flush();
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +0000226 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +0000227 exit(1);
228}
229
230} // end namespace objcopy
Puyan Lotfic4846a52018-07-16 22:17:05 +0000231} // end namespace llvm
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000232
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000233static SectionFlag parseSectionRenameFlag(StringRef SectionName) {
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +0000234 return llvm::StringSwitch<SectionFlag>(SectionName)
235 .Case("alloc", SectionFlag::SecAlloc)
236 .Case("load", SectionFlag::SecLoad)
237 .Case("noload", SectionFlag::SecNoload)
238 .Case("readonly", SectionFlag::SecReadonly)
239 .Case("debug", SectionFlag::SecDebug)
240 .Case("code", SectionFlag::SecCode)
241 .Case("data", SectionFlag::SecData)
242 .Case("rom", SectionFlag::SecRom)
243 .Case("merge", SectionFlag::SecMerge)
244 .Case("strings", SectionFlag::SecStrings)
245 .Case("contents", SectionFlag::SecContents)
246 .Case("share", SectionFlag::SecShare)
247 .Default(SectionFlag::SecNone);
248}
249
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000250static SectionRename parseRenameSectionValue(StringRef FlagValue) {
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +0000251 if (!FlagValue.contains('='))
252 error("Bad format for --rename-section: missing '='");
253
254 // Initial split: ".foo" = ".bar,f1,f2,..."
255 auto Old2New = FlagValue.split('=');
256 SectionRename SR;
257 SR.OriginalName = Old2New.first;
258
259 // Flags split: ".bar" "f1" "f2" ...
260 SmallVector<StringRef, 6> NameAndFlags;
261 Old2New.second.split(NameAndFlags, ',');
262 SR.NewName = NameAndFlags[0];
263
264 if (NameAndFlags.size() > 1) {
265 SectionFlag Flags = SectionFlag::SecNone;
266 for (size_t I = 1, Size = NameAndFlags.size(); I < Size; ++I) {
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000267 SectionFlag Flag = parseSectionRenameFlag(NameAndFlags[I]);
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +0000268 if (Flag == SectionFlag::SecNone)
269 error("Unrecognized section flag '" + NameAndFlags[I] +
270 "'. Flags supported for GNU compatibility: alloc, load, noload, "
271 "readonly, debug, code, data, rom, share, contents, merge, "
272 "strings.");
273 Flags |= Flag;
274 }
275
276 SR.NewFlags = 0;
277 if (Flags & SectionFlag::SecAlloc)
278 *SR.NewFlags |= ELF::SHF_ALLOC;
279 if (!(Flags & SectionFlag::SecReadonly))
280 *SR.NewFlags |= ELF::SHF_WRITE;
281 if (Flags & SectionFlag::SecCode)
282 *SR.NewFlags |= ELF::SHF_EXECINSTR;
283 if (Flags & SectionFlag::SecMerge)
284 *SR.NewFlags |= ELF::SHF_MERGE;
285 if (Flags & SectionFlag::SecStrings)
286 *SR.NewFlags |= ELF::SHF_STRINGS;
287 }
288
289 return SR;
290}
291
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000292static bool isDebugSection(const SectionBase &Sec) {
Fangrui Song87b4b8f2018-07-31 21:26:35 +0000293 return Sec.Name.startswith(".debug") || Sec.Name.startswith(".zdebug") ||
294 Sec.Name == ".gdb_index";
Fangrui Songfdfe2a92018-07-27 22:51:36 +0000295}
296
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000297static bool isDWOSection(const SectionBase &Sec) {
Puyan Lotfic4846a52018-07-16 22:17:05 +0000298 return Sec.Name.endswith(".dwo");
299}
300
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000301static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000302 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000303 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000304 return false;
305 // Short of keeping the string table we want to keep everything that is a DWO
306 // section and remove everything else.
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000307 return !isDWOSection(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000308}
309
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000310static const StringMap<MachineInfo> ArchMap{
311 // Name, {EMachine, 64bit, LittleEndian}
312 {"aarch64", {EM_AARCH64, true, true}},
313 {"arm", {EM_ARM, false, true}},
314 {"i386", {EM_386, false, true}},
315 {"i386:x86-64", {EM_X86_64, true, true}},
316 {"powerpc:common64", {EM_PPC64, true, true}},
317 {"sparc", {EM_SPARC, false, true}},
318 {"x86-64", {EM_X86_64, true, true}},
319};
320
321static const MachineInfo &getMachineInfo(StringRef Arch) {
322 auto Iter = ArchMap.find(Arch);
323 if (Iter == std::end(ArchMap))
324 error("Invalid architecture: '" + Arch + "'");
325 return Iter->getValue();
326}
327
328static ElfType getOutputElfType(const Binary &Bin) {
329 // Infer output ELF type from the input ELF object
330 if (isa<ELFObjectFile<ELF32LE>>(Bin))
331 return ELFT_ELF32LE;
332 if (isa<ELFObjectFile<ELF64LE>>(Bin))
333 return ELFT_ELF64LE;
334 if (isa<ELFObjectFile<ELF32BE>>(Bin))
335 return ELFT_ELF32BE;
336 if (isa<ELFObjectFile<ELF64BE>>(Bin))
337 return ELFT_ELF64BE;
338 llvm_unreachable("Invalid ELFType");
339}
340
341static ElfType getOutputElfType(const MachineInfo &MI) {
342 // Infer output ELF type from the binary arch specified
343 if (MI.Is64Bit)
344 return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
345 else
346 return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
347}
348
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000349static std::unique_ptr<Writer> createWriter(const CopyConfig &Config,
Puyan Lotfic4846a52018-07-16 22:17:05 +0000350 Object &Obj, Buffer &Buf,
351 ElfType OutputElfType) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000352 if (Config.OutputFormat == "binary") {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000353 return llvm::make_unique<BinaryWriter>(Obj, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000354 }
355 // Depending on the initial ELFT and OutputFormat we need a different Writer.
356 switch (OutputElfType) {
357 case ELFT_ELF32LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000358 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000359 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000360 case ELFT_ELF64LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000361 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000362 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000363 case ELFT_ELF32BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000364 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000365 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000366 case ELFT_ELF64BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000367 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000368 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000369 }
370 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000371}
372
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000373static void splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
Puyan Lotfic4846a52018-07-16 22:17:05 +0000374 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000375 auto DWOFile = Reader.create();
376 DWOFile->removeSections(
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000377 [&](const SectionBase &Sec) { return onlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000378 FileBuffer FB(File);
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000379 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000380 Writer->finalize();
381 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000382}
383
Paul Semela42dec72018-08-09 17:05:21 +0000384static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
385 Object &Obj) {
386 for (auto &Sec : Obj.sections()) {
387 if (Sec.Name == SecName) {
388 if (Sec.OriginalData.size() == 0)
389 return make_error<StringError>("Can't dump section \"" + SecName +
390 "\": it has no contents",
391 object_error::parse_failed);
392 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
393 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
394 if (!BufferOrErr)
395 return BufferOrErr.takeError();
396 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
397 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
398 Buf->getBufferStart());
399 if (Error E = Buf->commit())
400 return E;
401 return Error::success();
402 }
403 }
404 return make_error<StringError>("Section not found",
405 object_error::parse_failed);
406}
407
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000408// This function handles the high level operations of GNU objcopy including
409// handling command line options. It's important to outline certain properties
410// we expect to hold of the command line operations. Any operation that "keeps"
411// should keep regardless of a remove. Additionally any removal should respect
412// any previous removals. Lastly whether or not something is removed shouldn't
413// depend a) on the order the options occur in or b) on some opaque priority
414// system. The only priority is that keeps/copies overrule removes.
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000415static void handleArgs(const CopyConfig &Config, Object &Obj,
Puyan Lotfic4846a52018-07-16 22:17:05 +0000416 const Reader &Reader, ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000417
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000418 if (!Config.SplitDWO.empty()) {
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000419 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000420 }
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000421
422 // TODO: update or remove symbols only if there is an option that affects
423 // them.
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000424 if (Obj.SymbolTable) {
425 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
426 if ((Config.LocalizeHidden &&
427 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
428 (!Config.SymbolsToLocalize.empty() &&
429 is_contained(Config.SymbolsToLocalize, Sym.Name)))
430 Sym.Binding = STB_LOCAL;
431
Jordan Rupprechtbe8ebcc2018-08-17 22:34:48 +0000432 // Note: these two globalize flags have very similar names but different
433 // meanings:
434 //
435 // --globalize-symbol: promote a symbol to global
436 // --keep-global-symbol: all symbols except for these should be made local
437 //
438 // If --globalize-symbol is specified for a given symbol, it will be
439 // global in the output file even if it is not included via
440 // --keep-global-symbol. Because of that, make sure to check
441 // --globalize-symbol second.
442 if (!Config.SymbolsToKeepGlobal.empty() &&
443 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name))
444 Sym.Binding = STB_LOCAL;
445
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000446 if (!Config.SymbolsToGlobalize.empty() &&
447 is_contained(Config.SymbolsToGlobalize, Sym.Name))
448 Sym.Binding = STB_GLOBAL;
449
450 if (!Config.SymbolsToWeaken.empty() &&
451 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
452 Sym.Binding == STB_GLOBAL)
453 Sym.Binding = STB_WEAK;
454
455 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
456 Sym.getShndx() != SHN_UNDEF)
457 Sym.Binding = STB_WEAK;
458
459 const auto I = Config.SymbolsToRename.find(Sym.Name);
460 if (I != Config.SymbolsToRename.end())
461 Sym.Name = I->getValue();
Paul Semel7a3dc2c2018-08-09 17:49:04 +0000462
463 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
464 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000465 });
466
Paul Semel99dda0b2018-05-25 11:01:25 +0000467 // The purpose of this loop is to mark symbols referenced by sections
468 // (like GroupSection or RelocationSection). This way, we know which
469 // symbols are still 'needed' and wich are not.
470 if (Config.StripUnneeded) {
471 for (auto &Section : Obj.sections())
472 Section.markSymbols();
473 }
474
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000475 Obj.removeSymbols([&](const Symbol &Sym) {
Paul Semelcf51c802018-05-26 08:10:37 +0000476 if ((!Config.SymbolsToKeep.empty() &&
477 is_contained(Config.SymbolsToKeep, Sym.Name)) ||
478 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000479 return false;
480
481 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
482 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
483 Sym.Type != STT_SECTION)
484 return true;
485
486 if (Config.StripAll || Config.StripAllGNU)
487 return true;
488
489 if (!Config.SymbolsToRemove.empty() &&
490 is_contained(Config.SymbolsToRemove, Sym.Name)) {
491 return true;
492 }
493
Paul Semel46201fb2018-06-01 16:19:46 +0000494 if (Config.StripUnneeded && !Sym.Referenced &&
Paul Semel99dda0b2018-05-25 11:01:25 +0000495 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
496 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
497 return true;
498
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000499 return false;
500 });
501 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000502
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000503 SectionPred RemovePred = [](const SectionBase &) { return false; };
504
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000505 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000506 if (!Config.ToRemove.empty()) {
507 RemovePred = [&Config](const SectionBase &Sec) {
Fangrui Song0e49ef92018-08-21 00:13:52 +0000508 return is_contained(Config.ToRemove, Sec.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000509 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000510 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000511
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000512 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000513 RemovePred = [RemovePred](const SectionBase &Sec) {
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000514 return isDWOSection(Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000515 };
516
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000517 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000518 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000519 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000520 };
521
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000522 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000523 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
524 if (RemovePred(Sec))
525 return true;
526 if ((Sec.Flags & SHF_ALLOC) != 0)
527 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000528 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000529 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000530 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000531 case SHT_SYMTAB:
532 case SHT_REL:
533 case SHT_RELA:
534 case SHT_STRTAB:
535 return true;
536 }
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000537 return isDebugSection(Sec);
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000538 };
539
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000540 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000541 RemovePred = [RemovePred](const SectionBase &Sec) {
542 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
543 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000544 }
545
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000546 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000547 RemovePred = [RemovePred](const SectionBase &Sec) {
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000548 return RemovePred(Sec) || isDebugSection(Sec);
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000549 };
550 }
551
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000552 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000553 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
554 if (RemovePred(Sec))
555 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000556 if (&Sec == Obj.SectionNames)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000557 return false;
558 return (Sec.Flags & SHF_ALLOC) == 0;
559 };
560
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000561 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000562 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
563 if (RemovePred(Sec))
564 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000565 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000566 return false;
567 if (Sec.Name.startswith(".gnu.warning"))
568 return false;
569 return (Sec.Flags & SHF_ALLOC) == 0;
570 };
571
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000572 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000573 if (!Config.OnlyKeep.empty()) {
574 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000575 // Explicitly keep these sections regardless of previous removes.
Fangrui Song0e49ef92018-08-21 00:13:52 +0000576 if (is_contained(Config.OnlyKeep, Sec.Name))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000577 return false;
578
579 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000580 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000581 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000582
583 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000584 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000585 return false;
Stephen Hinese6e75bf2018-07-26 20:05:31 +0000586 if (Obj.SymbolTable == &Sec ||
587 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000588 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000589
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000590 // Remove everything else.
591 return true;
592 };
593 }
594
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000595 if (!Config.Keep.empty()) {
596 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000597 // Explicitly keep these sections regardless of previous removes.
Fangrui Song0e49ef92018-08-21 00:13:52 +0000598 if (is_contained(Config.Keep, Sec.Name))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000599 return false;
600 // Otherwise defer to RemovePred.
601 return RemovePred(Sec);
602 };
603 }
604
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000605 // This has to be the last predicate assignment.
606 // If the option --keep-symbol has been specified
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000607 // and at least one of those symbols is present
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000608 // (equivalently, the updated symbol table is not empty)
609 // the symbol table and the string table should not be removed.
Paul Semelcf51c802018-05-26 08:10:37 +0000610 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
Stephen Hinese6e75bf2018-07-26 20:05:31 +0000611 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000612 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
613 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
614 return false;
615 return RemovePred(Sec);
616 };
617 }
618
Jake Ehrlich76e91102018-01-25 22:46:17 +0000619 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000620
Jordan Rupprechtdb2036e2018-07-20 19:54:24 +0000621 if (!Config.SectionsToRename.empty()) {
622 for (auto &Sec : Obj.sections()) {
623 const auto Iter = Config.SectionsToRename.find(Sec.Name);
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +0000624 if (Iter != Config.SectionsToRename.end()) {
625 const SectionRename &SR = Iter->second;
626 Sec.Name = SR.NewName;
627 if (SR.NewFlags.hasValue()) {
628 // Preserve some flags which should not be dropped when setting flags.
629 // Also, preserve anything OS/processor dependant.
630 const uint64_t PreserveMask = ELF::SHF_COMPRESSED | ELF::SHF_EXCLUDE |
631 ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
632 ELF::SHF_MASKOS | ELF::SHF_MASKPROC |
633 ELF::SHF_TLS | ELF::SHF_INFO_LINK;
634 Sec.Flags = (Sec.Flags & PreserveMask) |
635 (SR.NewFlags.getValue() & ~PreserveMask);
636 }
637 }
Jordan Rupprechtdb2036e2018-07-20 19:54:24 +0000638 }
639 }
640
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000641 if (!Config.AddSection.empty()) {
642 for (const auto &Flag : Config.AddSection) {
643 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000644 auto SecName = SecPair.first;
645 auto File = SecPair.second;
646 auto BufOrErr = MemoryBuffer::getFile(File);
647 if (!BufOrErr)
648 reportError(File, BufOrErr.getError());
649 auto Buf = std::move(*BufOrErr);
650 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
651 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000652 Obj.addSection<OwnedDataSection>(SecName,
653 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000654 }
655 }
656
Paul Semela42dec72018-08-09 17:05:21 +0000657 if (!Config.DumpSection.empty()) {
658 for (const auto &Flag : Config.DumpSection) {
659 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
660 StringRef SecName = SecPair.first;
661 StringRef File = SecPair.second;
662 if (Error E = dumpSectionToFile(SecName, File, Obj))
663 reportError(Config.InputFilename, std::move(E));
664 }
665 }
666
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000667 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000668 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000669}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000670
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000671static void executeElfObjcopyOnBinary(const CopyConfig &Config, Reader &Reader,
672 Buffer &Out, ElfType OutputElfType) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000673 std::unique_ptr<Object> Obj = Reader.create();
674
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000675 handleArgs(Config, *Obj, Reader, OutputElfType);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000676
677 std::unique_ptr<Writer> Writer =
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000678 createWriter(Config, *Obj, Out, OutputElfType);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000679 Writer->finalize();
680 Writer->write();
681}
682
683// For regular archives this function simply calls llvm::writeArchive,
684// For thin archives it writes the archive file itself as well as its members.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000685static Error deepWriteArchive(StringRef ArcName,
686 ArrayRef<NewArchiveMember> NewMembers,
687 bool WriteSymtab, object::Archive::Kind Kind,
688 bool Deterministic, bool Thin) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000689 Error E =
690 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
691 if (!Thin || E)
692 return E;
693 for (const NewArchiveMember &Member : NewMembers) {
694 // Internally, FileBuffer will use the buffer created by
695 // FileOutputBuffer::create, for regular files (that is the case for
696 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
697 // OnDiskBuffer uses a temporary file and then renames it. So in reality
698 // there is no inefficiency / duplicated in-memory buffers in this case. For
699 // now in-memory buffers can not be completely avoided since
700 // NewArchiveMember still requires them even though writeArchive does not
701 // write them on disk.
702 FileBuffer FB(Member.MemberName);
703 FB.allocate(Member.Buf->getBufferSize());
704 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
705 FB.getBufferStart());
706 if (auto E = FB.commit())
707 return E;
708 }
709 return Error::success();
710}
711
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000712static void executeElfObjcopyOnArchive(const CopyConfig &Config,
Puyan Lotfi97604b42018-08-02 18:16:52 +0000713 const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000714 std::vector<NewArchiveMember> NewArchiveMembers;
715 Error Err = Error::success();
716 for (const Archive::Child &Child : Ar.children(Err)) {
717 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
718 if (!ChildOrErr)
719 reportError(Ar.getFileName(), ChildOrErr.takeError());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000720 Binary *Bin = ChildOrErr->get();
721
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000722 Expected<StringRef> ChildNameOrErr = Child.getName();
723 if (!ChildNameOrErr)
724 reportError(Ar.getFileName(), ChildNameOrErr.takeError());
725
726 MemBuffer MB(ChildNameOrErr.get());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000727 ELFReader Reader(Bin);
728 executeElfObjcopyOnBinary(Config, Reader, MB, getOutputElfType(*Bin));
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000729
730 Expected<NewArchiveMember> Member =
731 NewArchiveMember::getOldMember(Child, true);
732 if (!Member)
733 reportError(Ar.getFileName(), Member.takeError());
734 Member->Buf = MB.releaseMemoryBuffer();
735 Member->MemberName = Member->Buf->getBufferIdentifier();
736 NewArchiveMembers.push_back(std::move(*Member));
737 }
738
739 if (Err)
740 reportError(Config.InputFilename, std::move(Err));
741 if (Error E =
742 deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
743 Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin()))
744 reportError(Config.OutputFilename, std::move(E));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000745}
746
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000747static void restoreDateOnFile(StringRef Filename,
748 const sys::fs::file_status &Stat) {
749 int FD;
750
751 if (auto EC = sys::fs::openFileForWrite(Filename, FD))
752 reportError(Filename, EC);
753
754 if (auto EC = sys::fs::setLastAccessAndModificationTime(
755 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
756 reportError(Filename, EC);
757
758 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
759 reportError(Filename, EC);
760}
761
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000762static void executeElfObjcopy(const CopyConfig &Config) {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000763 sys::fs::file_status Stat;
764 if (Config.PreserveDates)
765 if (auto EC = sys::fs::status(Config.InputFilename, Stat))
766 reportError(Config.InputFilename, EC);
767
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000768 if (Config.InputFormat == "binary") {
769 auto BufOrErr = MemoryBuffer::getFile(Config.InputFilename);
770 if (!BufOrErr)
771 reportError(Config.InputFilename, BufOrErr.getError());
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000772
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000773 FileBuffer FB(Config.OutputFilename);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000774 BinaryReader Reader(Config.BinaryArch, BufOrErr->get());
775 executeElfObjcopyOnBinary(Config, Reader, FB,
776 getOutputElfType(Config.BinaryArch));
777 } else {
778 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
779 createBinary(Config.InputFilename);
780 if (!BinaryOrErr)
781 reportError(Config.InputFilename, BinaryOrErr.takeError());
782
783 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) {
784 executeElfObjcopyOnArchive(Config, *Ar);
785 } else {
786 FileBuffer FB(Config.OutputFilename);
787 Binary *Bin = BinaryOrErr.get().getBinary();
788 ELFReader Reader(Bin);
789 executeElfObjcopyOnBinary(Config, Reader, FB, getOutputElfType(*Bin));
790 }
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000791 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000792
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000793 if (Config.PreserveDates) {
794 restoreDateOnFile(Config.OutputFilename, Stat);
795 if (!Config.SplitDWO.empty())
796 restoreDateOnFile(Config.SplitDWO, Stat);
797 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000798}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000799
Jordan Rupprechtbe8ebcc2018-08-17 22:34:48 +0000800static void addGlobalSymbolsFromFile(std::vector<std::string> &Symbols,
801 StringRef Filename) {
802 SmallVector<StringRef, 16> Lines;
803 auto BufOrErr = MemoryBuffer::getFile(Filename);
804 if (!BufOrErr)
805 reportError(Filename, BufOrErr.getError());
806
807 BufOrErr.get()->getBuffer().split(Lines, '\n');
808 for (StringRef Line : Lines) {
809 // Ignore everything after '#', trim whitespace, and only add the symbol if
810 // it's not empty.
811 auto TrimmedLine = Line.split('#').first.trim();
812 if (!TrimmedLine.empty())
813 Symbols.push_back(TrimmedLine.str());
814 }
815}
816
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000817// ParseObjcopyOptions returns the config and sets the input arguments. If a
818// help flag is set then ParseObjcopyOptions will print the help messege and
819// exit.
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000820static CopyConfig parseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000821 ObjcopyOptTable T;
822 unsigned MissingArgumentIndex, MissingArgumentCount;
823 llvm::opt::InputArgList InputArgs =
824 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000825
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000826 if (InputArgs.size() == 0) {
827 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
828 exit(1);
829 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000830
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000831 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000832 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
833 exit(0);
834 }
835
836 SmallVector<const char *, 2> Positional;
837
838 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
839 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
840
841 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
842 Positional.push_back(Arg->getValue());
843
844 if (Positional.empty())
845 error("No input file specified");
846
847 if (Positional.size() > 2)
848 error("Too many positional arguments");
849
850 CopyConfig Config;
851 Config.InputFilename = Positional[0];
852 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
853 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
854 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000855 if (Config.InputFormat == "binary") {
856 auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
857 if (BinaryArch.empty())
858 error("Specified binary input without specifiying an architecture");
859 Config.BinaryArch = getMachineInfo(BinaryArch);
860 }
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000861
862 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
863 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Paul Semel7a3dc2c2018-08-09 17:49:04 +0000864 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000865
866 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
867 if (!StringRef(Arg->getValue()).contains('='))
868 error("Bad format for --redefine-sym");
869 auto Old2New = StringRef(Arg->getValue()).split('=');
870 if (!Config.SymbolsToRename.insert(Old2New).second)
871 error("Multiple redefinition of symbol " + Old2New.first);
872 }
873
Jordan Rupprechtdb2036e2018-07-20 19:54:24 +0000874 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000875 SectionRename SR = parseRenameSectionValue(StringRef(Arg->getValue()));
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +0000876 if (!Config.SectionsToRename.try_emplace(SR.OriginalName, SR).second)
877 error("Multiple renames of section " + SR.OriginalName);
Jordan Rupprechtdb2036e2018-07-20 19:54:24 +0000878 }
879
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000880 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
881 Config.ToRemove.push_back(Arg->getValue());
882 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
883 Config.Keep.push_back(Arg->getValue());
884 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
885 Config.OnlyKeep.push_back(Arg->getValue());
886 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
887 Config.AddSection.push_back(Arg->getValue());
Paul Semela42dec72018-08-09 17:05:21 +0000888 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section))
889 Config.DumpSection.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000890 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
891 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
892 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
893 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
894 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
895 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
Paul Semel99dda0b2018-05-25 11:01:25 +0000896 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000897 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
898 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000899 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000900 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Jake Ehrliche40398a2018-05-15 20:53:53 +0000901 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
Paul Semelcf51c802018-05-26 08:10:37 +0000902 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
Paul Semelb4924942018-04-26 17:44:43 +0000903 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000904 Config.SymbolsToLocalize.push_back(Arg->getValue());
Jordan Rupprechtbe8ebcc2018-08-17 22:34:48 +0000905 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol))
906 Config.SymbolsToKeepGlobal.push_back(Arg->getValue());
907 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols))
908 addGlobalSymbolsFromFile(Config.SymbolsToKeepGlobal, Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000909 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
910 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000911 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
912 Config.SymbolsToWeaken.push_back(Arg->getValue());
Paul Semel4246a462018-05-09 21:36:54 +0000913 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
914 Config.SymbolsToRemove.push_back(Arg->getValue());
Paul Semel5d97c822018-05-15 14:09:37 +0000915 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
916 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000917
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000918 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates);
919
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000920 return Config;
921}
922
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000923// ParseStripOptions returns the config and sets the input arguments. If a
924// help flag is set then ParseStripOptions will print the help messege and
925// exit.
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000926static CopyConfig parseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000927 StripOptTable T;
928 unsigned MissingArgumentIndex, MissingArgumentCount;
929 llvm::opt::InputArgList InputArgs =
930 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
931
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000932 if (InputArgs.size() == 0) {
Fangrui Songffbc3e22018-08-20 23:01:57 +0000933 T.PrintHelp(errs(), "llvm-strip", "strip tool");
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000934 exit(1);
935 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000936
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000937 if (InputArgs.hasArg(STRIP_help)) {
Fangrui Songffbc3e22018-08-20 23:01:57 +0000938 T.PrintHelp(outs(), "llvm-strip", "strip tool");
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000939 exit(0);
940 }
941
942 SmallVector<const char *, 2> Positional;
943 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
944 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
945 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
946 Positional.push_back(Arg->getValue());
947
948 if (Positional.empty())
949 error("No input file specified");
950
Fangrui Songffbc3e22018-08-20 23:01:57 +0000951 if (Positional.size() > 1)
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000952 error("Support for multiple input files is not implemented yet");
953
954 CopyConfig Config;
955 Config.InputFilename = Positional[0];
Alexander Shaposhnikovecc84832018-05-31 20:42:13 +0000956 Config.OutputFilename =
957 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000958
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000959 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000960
Alexander Shaposhnikov29407f32018-06-06 21:23:19 +0000961 Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all);
Paul Semele57bc782018-06-07 10:05:25 +0000962 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
Stephen Hinese8c3c5f2018-07-12 17:42:17 +0000963 Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
Paul Semele57bc782018-06-07 10:05:25 +0000964
965 if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll)
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000966 Config.StripAll = true;
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000967
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000968 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
969 Config.ToRemove.push_back(Arg->getValue());
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000970
Alexander Shaposhnikov35bee3e2018-05-23 19:44:19 +0000971 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
972 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000973
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000974 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates);
975
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000976 return Config;
977}
978
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000979int main(int argc, char **argv) {
980 InitLLVM X(argc, argv);
981 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000982 CopyConfig Config;
983 if (sys::path::stem(ToolName).endswith_lower("strip"))
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000984 Config = parseStripOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000985 else
Jordan Rupprecht6b575392018-08-13 21:30:27 +0000986 Config = parseObjcopyOptions(makeArrayRef(argv + 1, argc));
987 executeElfObjcopy(Config);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000988}