blob: 1cfcb06e8e4eae8c690d595692dc1df1e5e15e00 [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;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000150 StringMap<StringRef> SymbolsToRename;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000151 bool StripAll = false;
152 bool StripAllGNU = false;
153 bool StripDebug = false;
154 bool StripSections = false;
155 bool StripNonAlloc = false;
156 bool StripDWO = false;
157 bool ExtractDWO = false;
158 bool LocalizeHidden = false;
159 bool Weaken = false;
160 bool DiscardAll = false;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000161};
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000162
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000163using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000164
Jake Ehrlich777fb002017-12-15 20:17:55 +0000165bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000166
Jake Ehrlich76e91102018-01-25 22:46:17 +0000167bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000168 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000169 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000170 return false;
171 // Short of keeping the string table we want to keep everything that is a DWO
172 // section and remove everything else.
173 return !IsDWOSection(Sec);
174}
175
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000176std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj,
177 StringRef File, ElfType OutputElfType) {
178 if (Config.OutputFormat == "binary") {
179 return llvm::make_unique<BinaryWriter>(File, Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000180 }
181 // Depending on the initial ELFT and OutputFormat we need a different Writer.
182 switch (OutputElfType) {
183 case ELFT_ELF32LE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000184 return llvm::make_unique<ELFWriter<ELF32LE>>(File, Obj,
185 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000186 case ELFT_ELF64LE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000187 return llvm::make_unique<ELFWriter<ELF64LE>>(File, Obj,
188 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000189 case ELFT_ELF32BE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000190 return llvm::make_unique<ELFWriter<ELF32BE>>(File, Obj,
191 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000192 case ELFT_ELF64BE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000193 return llvm::make_unique<ELFWriter<ELF64BE>>(File, Obj,
194 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000195 }
196 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000197}
198
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000199void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
200 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000201 auto DWOFile = Reader.create();
202 DWOFile->removeSections(
203 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000204 auto Writer = CreateWriter(Config, *DWOFile, File, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000205 Writer->finalize();
206 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000207}
208
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000209// This function handles the high level operations of GNU objcopy including
210// handling command line options. It's important to outline certain properties
211// we expect to hold of the command line operations. Any operation that "keeps"
212// should keep regardless of a remove. Additionally any removal should respect
213// any previous removals. Lastly whether or not something is removed shouldn't
214// depend a) on the order the options occur in or b) on some opaque priority
215// system. The only priority is that keeps/copies overrule removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000216void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader,
217 ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000218
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000219 if (!Config.SplitDWO.empty()) {
220 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000221 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000222
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000223 SectionPred RemovePred = [](const SectionBase &) { return false; };
224
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000225 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000226 if (!Config.ToRemove.empty()) {
227 RemovePred = [&Config](const SectionBase &Sec) {
228 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
229 Sec.Name) != std::end(Config.ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000230 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000231 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000232
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000233 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000234 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000235 return IsDWOSection(Sec) || RemovePred(Sec);
236 };
237
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000238 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000239 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000240 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000241 };
242
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000243 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000244 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
245 if (RemovePred(Sec))
246 return true;
247 if ((Sec.Flags & SHF_ALLOC) != 0)
248 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000249 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000250 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000251 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000252 case SHT_SYMTAB:
253 case SHT_REL:
254 case SHT_RELA:
255 case SHT_STRTAB:
256 return true;
257 }
258 return Sec.Name.startswith(".debug");
259 };
260
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000261 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000262 RemovePred = [RemovePred](const SectionBase &Sec) {
263 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
264 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000265 }
266
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000267 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000268 RemovePred = [RemovePred](const SectionBase &Sec) {
269 return RemovePred(Sec) || Sec.Name.startswith(".debug");
270 };
271 }
272
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000273 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000274 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
275 if (RemovePred(Sec))
276 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000277 if (&Sec == Obj.SectionNames)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000278 return false;
279 return (Sec.Flags & SHF_ALLOC) == 0;
280 };
281
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000282 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000283 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
284 if (RemovePred(Sec))
285 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000286 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000287 return false;
288 if (Sec.Name.startswith(".gnu.warning"))
289 return false;
290 return (Sec.Flags & SHF_ALLOC) == 0;
291 };
292
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000293 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000294 if (!Config.OnlyKeep.empty()) {
295 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000296 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000297 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
298 Sec.Name) != std::end(Config.OnlyKeep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000299 return false;
300
301 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000302 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000303 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000304
305 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000306 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000307 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000308 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000309 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000310
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000311 // Remove everything else.
312 return true;
313 };
314 }
315
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000316 if (!Config.Keep.empty()) {
317 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000318 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000319 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
320 std::end(Config.Keep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000321 return false;
322 // Otherwise defer to RemovePred.
323 return RemovePred(Sec);
324 };
325 }
326
Jake Ehrlich76e91102018-01-25 22:46:17 +0000327 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000328
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000329 if (!Config.AddSection.empty()) {
330 for (const auto &Flag : Config.AddSection) {
331 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000332 auto SecName = SecPair.first;
333 auto File = SecPair.second;
334 auto BufOrErr = MemoryBuffer::getFile(File);
335 if (!BufOrErr)
336 reportError(File, BufOrErr.getError());
337 auto Buf = std::move(*BufOrErr);
338 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
339 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000340 Obj.addSection<OwnedDataSection>(SecName,
341 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000342 }
343 }
344
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000345 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000346 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000347
348 if (Obj.SymbolTable) {
349 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
350 if ((Config.LocalizeHidden &&
351 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
352 (!Config.SymbolsToLocalize.empty() &&
Paul Semelee5be792018-04-27 19:09:44 +0000353 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000354 Sym.Binding = STB_LOCAL;
355
Paul Semelee5be792018-04-27 19:09:44 +0000356 if (!Config.SymbolsToGlobalize.empty() &&
357 is_contained(Config.SymbolsToGlobalize, Sym.Name))
358 Sym.Binding = STB_GLOBAL;
359
Paul Semel3a8a56b2018-04-27 19:16:27 +0000360 if (!Config.SymbolsToWeaken.empty() &&
361 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
362 Sym.Binding == STB_GLOBAL)
363 Sym.Binding = STB_WEAK;
364
Paul Semel2c0510f2018-05-02 20:14:49 +0000365 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
366 Sym.getShndx() != SHN_UNDEF)
367 Sym.Binding = STB_WEAK;
368
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000369 const auto I = Config.SymbolsToRename.find(Sym.Name);
370 if (I != Config.SymbolsToRename.end())
371 Sym.Name = I->getValue();
372 });
Paul Semel41695f82018-05-02 20:19:22 +0000373
374 Obj.SymbolTable->removeSymbols([&](const Symbol &Sym) {
375 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
376 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
377 Sym.Type != STT_SECTION)
378 return true;
379 return false;
380 });
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000381 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000382}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000383
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000384std::unique_ptr<Reader> CreateReader(StringRef InputFilename,
385 ElfType &OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000386 // Right now we can only read ELF files so there's only one reader;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000387 auto Out = llvm::make_unique<ELFReader>(InputFilename);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000388 // We need to set the default ElfType for output.
389 OutputElfType = Out->getElfType();
390 return std::move(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000391}
392
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000393void ExecuteElfObjcopy(const CopyConfig &Config) {
394 ElfType OutputElfType;
395 auto Reader = CreateReader(Config.InputFilename, OutputElfType);
Jake Ehrlicha8c689e2018-04-12 00:40:50 +0000396 auto Obj = Reader->create();
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000397 auto Writer =
398 CreateWriter(Config, *Obj, Config.OutputFilename, OutputElfType);
399 HandleArgs(Config, *Obj, *Reader, OutputElfType);
Jake Ehrlicha8c689e2018-04-12 00:40:50 +0000400 Writer->finalize();
401 Writer->write();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000402}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000403
404// ParseObjcopyOptions returns the config and sets the input arguments. If a
405// help flag is set then ParseObjcopyOptions will print the help messege and
406// exit.
407CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
408 ObjcopyOptTable T;
409 unsigned MissingArgumentIndex, MissingArgumentCount;
410 llvm::opt::InputArgList InputArgs =
411 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000412
413 if (InputArgs.size() == 0) {
414 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
415 exit(1);
416 }
417
418 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000419 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
420 exit(0);
421 }
422
423 SmallVector<const char *, 2> Positional;
424
425 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
426 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
427
428 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
429 Positional.push_back(Arg->getValue());
430
431 if (Positional.empty())
432 error("No input file specified");
433
434 if (Positional.size() > 2)
435 error("Too many positional arguments");
436
437 CopyConfig Config;
438 Config.InputFilename = Positional[0];
439 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
440 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
441 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
442 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
443
444 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
445 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000446
447 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
448 if (!StringRef(Arg->getValue()).contains('='))
449 error("Bad format for --redefine-sym");
450 auto Old2New = StringRef(Arg->getValue()).split('=');
451 if (!Config.SymbolsToRename.insert(Old2New).second)
452 error("Multiple redefinition of symbol " + Old2New.first);
453 }
454
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000455 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
456 Config.ToRemove.push_back(Arg->getValue());
457 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
458 Config.Keep.push_back(Arg->getValue());
459 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
460 Config.OnlyKeep.push_back(Arg->getValue());
461 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
462 Config.AddSection.push_back(Arg->getValue());
463 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
464 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
465 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
466 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
467 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
468 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
469 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
470 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000471 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000472 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Paul Semelb4924942018-04-26 17:44:43 +0000473 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000474 Config.SymbolsToLocalize.push_back(Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000475 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
476 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000477 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
478 Config.SymbolsToWeaken.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000479
480 return Config;
481}
482
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000483// ParseStripOptions returns the config and sets the input arguments. If a
484// help flag is set then ParseStripOptions will print the help messege and
485// exit.
486CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
487 StripOptTable T;
488 unsigned MissingArgumentIndex, MissingArgumentCount;
489 llvm::opt::InputArgList InputArgs =
490 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
491
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000492 if (InputArgs.size() == 0) {
493 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
494 exit(1);
495 }
496
497 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000498 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
499 exit(0);
500 }
501
502 SmallVector<const char *, 2> Positional;
503 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
504 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
505 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
506 Positional.push_back(Arg->getValue());
507
508 if (Positional.empty())
509 error("No input file specified");
510
511 if (Positional.size() > 2)
512 error("Support for multiple input files is not implemented yet");
513
514 CopyConfig Config;
515 Config.InputFilename = Positional[0];
516 Config.OutputFilename = Positional[0];
517
518 // Strip debug info only.
519 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
520 if (!Config.StripDebug)
521 Config.StripAll = true;
522 return Config;
523}
524
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000525int main(int argc, char **argv) {
526 InitLLVM X(argc, argv);
527 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000528 CopyConfig Config;
529 if (sys::path::stem(ToolName).endswith_lower("strip"))
530 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
531 else
532 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000533 ExecuteElfObjcopy(Config);
534}