blob: 24ec18817c9c2bf46efad4ceb8af6e1c1607b401 [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"
11#include "Object.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000012#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/Twine.h"
15#include "llvm/BinaryFormat/ELF.h"
16#include "llvm/Object/Binary.h"
17#include "llvm/Object/ELFObjectFile.h"
18#include "llvm/Object/ELFTypes.h"
19#include "llvm/Object/Error.h"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000020#include "llvm/Option/Arg.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/Option/Option.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000023#include "llvm/Support/Casting.h"
Petr Hosek05a04cb2017-08-01 00:33:58 +000024#include "llvm/Support/CommandLine.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000025#include "llvm/Support/Compiler.h"
26#include "llvm/Support/Error.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/ErrorOr.h"
Petr Hosek05a04cb2017-08-01 00:33:58 +000029#include "llvm/Support/FileOutputBuffer.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000030#include "llvm/Support/InitLLVM.h"
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000031#include "llvm/Support/Path.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000032#include "llvm/Support/raw_ostream.h"
33#include <algorithm>
34#include <cassert>
35#include <cstdlib>
36#include <functional>
37#include <iterator>
Petr Hosek05a04cb2017-08-01 00:33:58 +000038#include <memory>
39#include <string>
40#include <system_error>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000041#include <utility>
Petr Hosek05a04cb2017-08-01 00:33:58 +000042
43using namespace llvm;
44using namespace object;
45using namespace ELF;
46
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000047namespace {
48
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000049enum ObjcopyID {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000050 OBJCOPY_INVALID = 0, // This is not an option ID.
51#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
52 HELPTEXT, METAVAR, VALUES) \
53 OBJCOPY_##ID,
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000054#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000055#undef OPTION
56};
57
58#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000059#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000060#undef PREFIX
61
Alexander Shaposhnikov3326e782018-04-24 06:23:22 +000062static const opt::OptTable::Info ObjcopyInfoTable[] = {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000063#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
64 HELPTEXT, METAVAR, VALUES) \
65 {PREFIX, NAME, HELPTEXT, \
66 METAVAR, OBJCOPY_##ID, opt::Option::KIND##Class, \
67 PARAM, FLAGS, OBJCOPY_##GROUP, \
68 OBJCOPY_##ALIAS, ALIASARGS, VALUES},
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000069#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000070#undef OPTION
71};
72
73class ObjcopyOptTable : public opt::OptTable {
74public:
75 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
76};
77
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000078enum StripID {
79 STRIP_INVALID = 0, // This is not an option ID.
80#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
81 HELPTEXT, METAVAR, VALUES) \
82 STRIP_##ID,
83#include "StripOpts.inc"
84#undef OPTION
85};
86
87static const opt::OptTable::Info StripInfoTable[] = {
88#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
89 HELPTEXT, METAVAR, VALUES) \
90 {PREFIX, NAME, HELPTEXT, \
91 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
92 PARAM, FLAGS, STRIP_##GROUP, \
93 STRIP_##ALIAS, ALIASARGS, VALUES},
94#include "StripOpts.inc"
95#undef OPTION
96};
97
98class StripOptTable : public opt::OptTable {
99public:
100 StripOptTable() : OptTable(StripInfoTable, true) {}
101};
102
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000103} // namespace
104
Petr Hosek05a04cb2017-08-01 00:33:58 +0000105// The name this program was invoked as.
106static StringRef ToolName;
107
108namespace llvm {
109
Zachary Turner41a9ee92017-10-11 23:54:34 +0000110LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000111 errs() << ToolName << ": " << Message << ".\n";
112 errs().flush();
113 exit(1);
114}
115
116LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
117 assert(EC);
118 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
119 exit(1);
120}
121
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000122LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000123 assert(E);
124 std::string Buf;
125 raw_string_ostream OS(Buf);
126 logAllUnhandledErrors(std::move(E), OS, "");
127 OS.flush();
128 errs() << ToolName << ": '" << File << "': " << Buf;
129 exit(1);
130}
Petr Hosek05a04cb2017-08-01 00:33:58 +0000131
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000132} // end namespace llvm
133
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000134struct CopyConfig {
135 StringRef OutputFilename;
136 StringRef InputFilename;
137 StringRef OutputFormat;
138 StringRef InputFormat;
139 StringRef BinaryArch;
Alexander Shaposhnikovfedb0162018-02-09 23:33:31 +0000140
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000141 StringRef SplitDWO;
142 StringRef AddGnuDebugLink;
143 std::vector<StringRef> ToRemove;
144 std::vector<StringRef> Keep;
145 std::vector<StringRef> OnlyKeep;
146 std::vector<StringRef> AddSection;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000147 std::vector<StringRef> SymbolsToLocalize;
Paul Semelee5be792018-04-27 19:09:44 +0000148 std::vector<StringRef> SymbolsToGlobalize;
Paul Semel3a8a56b2018-04-27 19:16:27 +0000149 std::vector<StringRef> SymbolsToWeaken;
Paul Semel4246a462018-05-09 21:36:54 +0000150 std::vector<StringRef> SymbolsToRemove;
Paul Semel5d97c822018-05-15 14:09:37 +0000151 std::vector<StringRef> SymbolsToKeep;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000152 StringMap<StringRef> SymbolsToRename;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000153 bool StripAll = false;
154 bool StripAllGNU = false;
155 bool StripDebug = false;
156 bool StripSections = false;
157 bool StripNonAlloc = false;
158 bool StripDWO = false;
159 bool ExtractDWO = false;
160 bool LocalizeHidden = false;
161 bool Weaken = false;
162 bool DiscardAll = false;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000163};
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000164
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000165using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000166
Jake Ehrlich777fb002017-12-15 20:17:55 +0000167bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000168
Jake Ehrlich76e91102018-01-25 22:46:17 +0000169bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000170 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000171 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000172 return false;
173 // Short of keeping the string table we want to keep everything that is a DWO
174 // section and remove everything else.
175 return !IsDWOSection(Sec);
176}
177
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000178std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj,
179 StringRef File, ElfType OutputElfType) {
180 if (Config.OutputFormat == "binary") {
181 return llvm::make_unique<BinaryWriter>(File, Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000182 }
183 // Depending on the initial ELFT and OutputFormat we need a different Writer.
184 switch (OutputElfType) {
185 case ELFT_ELF32LE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000186 return llvm::make_unique<ELFWriter<ELF32LE>>(File, Obj,
187 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000188 case ELFT_ELF64LE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000189 return llvm::make_unique<ELFWriter<ELF64LE>>(File, Obj,
190 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000191 case ELFT_ELF32BE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000192 return llvm::make_unique<ELFWriter<ELF32BE>>(File, Obj,
193 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000194 case ELFT_ELF64BE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000195 return llvm::make_unique<ELFWriter<ELF64BE>>(File, Obj,
196 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000197 }
198 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000199}
200
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000201void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
202 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000203 auto DWOFile = Reader.create();
204 DWOFile->removeSections(
205 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000206 auto Writer = CreateWriter(Config, *DWOFile, File, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000207 Writer->finalize();
208 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000209}
210
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000211// This function handles the high level operations of GNU objcopy including
212// handling command line options. It's important to outline certain properties
213// we expect to hold of the command line operations. Any operation that "keeps"
214// should keep regardless of a remove. Additionally any removal should respect
215// any previous removals. Lastly whether or not something is removed shouldn't
216// depend a) on the order the options occur in or b) on some opaque priority
217// system. The only priority is that keeps/copies overrule removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000218void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader,
219 ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000220
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000221 if (!Config.SplitDWO.empty()) {
222 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000223 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000224
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000225 SectionPred RemovePred = [](const SectionBase &) { return false; };
226
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000227 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000228 if (!Config.ToRemove.empty()) {
229 RemovePred = [&Config](const SectionBase &Sec) {
230 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
231 Sec.Name) != std::end(Config.ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000232 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000233 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000234
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000235 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000236 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000237 return IsDWOSection(Sec) || RemovePred(Sec);
238 };
239
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000240 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000241 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000242 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000243 };
244
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000245 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000246 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
247 if (RemovePred(Sec))
248 return true;
249 if ((Sec.Flags & SHF_ALLOC) != 0)
250 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000251 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000252 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000253 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000254 case SHT_SYMTAB:
255 case SHT_REL:
256 case SHT_RELA:
257 case SHT_STRTAB:
258 return true;
259 }
260 return Sec.Name.startswith(".debug");
261 };
262
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000263 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000264 RemovePred = [RemovePred](const SectionBase &Sec) {
265 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
266 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000267 }
268
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000269 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000270 RemovePred = [RemovePred](const SectionBase &Sec) {
271 return RemovePred(Sec) || Sec.Name.startswith(".debug");
272 };
273 }
274
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000275 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000276 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
277 if (RemovePred(Sec))
278 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000279 if (&Sec == Obj.SectionNames)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000280 return false;
281 return (Sec.Flags & SHF_ALLOC) == 0;
282 };
283
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000284 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000285 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
286 if (RemovePred(Sec))
287 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000288 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000289 return false;
290 if (Sec.Name.startswith(".gnu.warning"))
291 return false;
292 return (Sec.Flags & SHF_ALLOC) == 0;
293 };
294
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000295 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000296 if (!Config.OnlyKeep.empty()) {
297 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000298 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000299 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
300 Sec.Name) != std::end(Config.OnlyKeep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000301 return false;
302
303 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000304 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000305 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000306
307 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000308 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000309 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000310 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000311 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000312
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000313 // Remove everything else.
314 return true;
315 };
316 }
317
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000318 if (!Config.Keep.empty()) {
319 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000320 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000321 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
322 std::end(Config.Keep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000323 return false;
324 // Otherwise defer to RemovePred.
325 return RemovePred(Sec);
326 };
327 }
328
Jake Ehrlich76e91102018-01-25 22:46:17 +0000329 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000330
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000331 if (!Config.AddSection.empty()) {
332 for (const auto &Flag : Config.AddSection) {
333 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000334 auto SecName = SecPair.first;
335 auto File = SecPair.second;
336 auto BufOrErr = MemoryBuffer::getFile(File);
337 if (!BufOrErr)
338 reportError(File, BufOrErr.getError());
339 auto Buf = std::move(*BufOrErr);
340 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
341 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000342 Obj.addSection<OwnedDataSection>(SecName,
343 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000344 }
345 }
346
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000347 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000348 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000349
350 if (Obj.SymbolTable) {
351 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
352 if ((Config.LocalizeHidden &&
353 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
354 (!Config.SymbolsToLocalize.empty() &&
Paul Semelee5be792018-04-27 19:09:44 +0000355 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000356 Sym.Binding = STB_LOCAL;
357
Paul Semelee5be792018-04-27 19:09:44 +0000358 if (!Config.SymbolsToGlobalize.empty() &&
359 is_contained(Config.SymbolsToGlobalize, Sym.Name))
360 Sym.Binding = STB_GLOBAL;
361
Paul Semel3a8a56b2018-04-27 19:16:27 +0000362 if (!Config.SymbolsToWeaken.empty() &&
363 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
364 Sym.Binding == STB_GLOBAL)
365 Sym.Binding = STB_WEAK;
366
Paul Semel2c0510f2018-05-02 20:14:49 +0000367 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
368 Sym.getShndx() != SHN_UNDEF)
369 Sym.Binding = STB_WEAK;
370
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000371 const auto I = Config.SymbolsToRename.find(Sym.Name);
372 if (I != Config.SymbolsToRename.end())
373 Sym.Name = I->getValue();
374 });
Paul Semel41695f82018-05-02 20:19:22 +0000375
Paul Semel4246a462018-05-09 21:36:54 +0000376 Obj.removeSymbols([&](const Symbol &Sym) {
Paul Semel5d97c822018-05-15 14:09:37 +0000377 if (!Config.SymbolsToKeep.empty() &&
378 is_contained(Config.SymbolsToKeep, Sym.Name))
379 return false;
380
Paul Semel41695f82018-05-02 20:19:22 +0000381 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
382 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
383 Sym.Type != STT_SECTION)
384 return true;
Paul Semel4246a462018-05-09 21:36:54 +0000385
386 if (!Config.SymbolsToRemove.empty() &&
387 is_contained(Config.SymbolsToRemove, Sym.Name)) {
388 return true;
389 }
390
Paul Semel41695f82018-05-02 20:19:22 +0000391 return false;
392 });
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000393 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000394}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000395
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000396std::unique_ptr<Reader> CreateReader(StringRef InputFilename,
397 ElfType &OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000398 // Right now we can only read ELF files so there's only one reader;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000399 auto Out = llvm::make_unique<ELFReader>(InputFilename);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000400 // We need to set the default ElfType for output.
401 OutputElfType = Out->getElfType();
402 return std::move(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000403}
404
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000405void ExecuteElfObjcopy(const CopyConfig &Config) {
406 ElfType OutputElfType;
407 auto Reader = CreateReader(Config.InputFilename, OutputElfType);
Jake Ehrlicha8c689e2018-04-12 00:40:50 +0000408 auto Obj = Reader->create();
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000409 auto Writer =
410 CreateWriter(Config, *Obj, Config.OutputFilename, OutputElfType);
411 HandleArgs(Config, *Obj, *Reader, OutputElfType);
Jake Ehrlicha8c689e2018-04-12 00:40:50 +0000412 Writer->finalize();
413 Writer->write();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000414}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000415
416// ParseObjcopyOptions returns the config and sets the input arguments. If a
417// help flag is set then ParseObjcopyOptions will print the help messege and
418// exit.
419CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
420 ObjcopyOptTable T;
421 unsigned MissingArgumentIndex, MissingArgumentCount;
422 llvm::opt::InputArgList InputArgs =
423 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000424
425 if (InputArgs.size() == 0) {
426 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
427 exit(1);
428 }
429
430 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000431 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
432 exit(0);
433 }
434
435 SmallVector<const char *, 2> Positional;
436
437 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
438 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
439
440 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
441 Positional.push_back(Arg->getValue());
442
443 if (Positional.empty())
444 error("No input file specified");
445
446 if (Positional.size() > 2)
447 error("Too many positional arguments");
448
449 CopyConfig Config;
450 Config.InputFilename = Positional[0];
451 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
452 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
453 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
454 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
455
456 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
457 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000458
459 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
460 if (!StringRef(Arg->getValue()).contains('='))
461 error("Bad format for --redefine-sym");
462 auto Old2New = StringRef(Arg->getValue()).split('=');
463 if (!Config.SymbolsToRename.insert(Old2New).second)
464 error("Multiple redefinition of symbol " + Old2New.first);
465 }
466
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000467 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
468 Config.ToRemove.push_back(Arg->getValue());
469 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
470 Config.Keep.push_back(Arg->getValue());
471 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
472 Config.OnlyKeep.push_back(Arg->getValue());
473 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
474 Config.AddSection.push_back(Arg->getValue());
475 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
476 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
477 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
478 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
479 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
480 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
481 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
482 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000483 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000484 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Paul Semelb4924942018-04-26 17:44:43 +0000485 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000486 Config.SymbolsToLocalize.push_back(Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000487 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
488 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000489 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
490 Config.SymbolsToWeaken.push_back(Arg->getValue());
Paul Semel4246a462018-05-09 21:36:54 +0000491 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
492 Config.SymbolsToRemove.push_back(Arg->getValue());
Paul Semel5d97c822018-05-15 14:09:37 +0000493 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
494 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000495
496 return Config;
497}
498
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000499// ParseStripOptions returns the config and sets the input arguments. If a
500// help flag is set then ParseStripOptions will print the help messege and
501// exit.
502CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
503 StripOptTable T;
504 unsigned MissingArgumentIndex, MissingArgumentCount;
505 llvm::opt::InputArgList InputArgs =
506 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
507
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000508 if (InputArgs.size() == 0) {
509 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
510 exit(1);
511 }
512
513 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000514 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
515 exit(0);
516 }
517
518 SmallVector<const char *, 2> Positional;
519 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
520 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
521 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
522 Positional.push_back(Arg->getValue());
523
524 if (Positional.empty())
525 error("No input file specified");
526
527 if (Positional.size() > 2)
528 error("Support for multiple input files is not implemented yet");
529
530 CopyConfig Config;
531 Config.InputFilename = Positional[0];
532 Config.OutputFilename = Positional[0];
533
534 // Strip debug info only.
535 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
536 if (!Config.StripDebug)
537 Config.StripAll = true;
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000538
539 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
540 Config.ToRemove.push_back(Arg->getValue());
541
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000542 return Config;
543}
544
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000545int main(int argc, char **argv) {
546 InitLLVM X(argc, argv);
547 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000548 CopyConfig Config;
549 if (sys::path::stem(ToolName).endswith_lower("strip"))
550 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
551 else
552 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000553 ExecuteElfObjcopy(Config);
554}