blob: e08648ea0af3a5c4c14da98b7b3e3e7d816722ae [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;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000151 StringMap<StringRef> SymbolsToRename;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000152 bool StripAll = false;
153 bool StripAllGNU = false;
154 bool StripDebug = false;
155 bool StripSections = false;
156 bool StripNonAlloc = false;
157 bool StripDWO = false;
158 bool ExtractDWO = false;
159 bool LocalizeHidden = false;
160 bool Weaken = false;
161 bool DiscardAll = false;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000162};
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000163
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000164using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000165
Jake Ehrlich777fb002017-12-15 20:17:55 +0000166bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000167
Jake Ehrlich76e91102018-01-25 22:46:17 +0000168bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000169 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000170 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000171 return false;
172 // Short of keeping the string table we want to keep everything that is a DWO
173 // section and remove everything else.
174 return !IsDWOSection(Sec);
175}
176
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000177std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj,
178 StringRef File, ElfType OutputElfType) {
179 if (Config.OutputFormat == "binary") {
180 return llvm::make_unique<BinaryWriter>(File, Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000181 }
182 // Depending on the initial ELFT and OutputFormat we need a different Writer.
183 switch (OutputElfType) {
184 case ELFT_ELF32LE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000185 return llvm::make_unique<ELFWriter<ELF32LE>>(File, Obj,
186 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000187 case ELFT_ELF64LE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000188 return llvm::make_unique<ELFWriter<ELF64LE>>(File, Obj,
189 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000190 case ELFT_ELF32BE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000191 return llvm::make_unique<ELFWriter<ELF32BE>>(File, Obj,
192 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000193 case ELFT_ELF64BE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000194 return llvm::make_unique<ELFWriter<ELF64BE>>(File, Obj,
195 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000196 }
197 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000198}
199
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000200void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
201 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000202 auto DWOFile = Reader.create();
203 DWOFile->removeSections(
204 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000205 auto Writer = CreateWriter(Config, *DWOFile, File, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000206 Writer->finalize();
207 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000208}
209
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000210// This function handles the high level operations of GNU objcopy including
211// handling command line options. It's important to outline certain properties
212// we expect to hold of the command line operations. Any operation that "keeps"
213// should keep regardless of a remove. Additionally any removal should respect
214// any previous removals. Lastly whether or not something is removed shouldn't
215// depend a) on the order the options occur in or b) on some opaque priority
216// system. The only priority is that keeps/copies overrule removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000217void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader,
218 ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000219
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000220 if (!Config.SplitDWO.empty()) {
221 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000222 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000223
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000224 SectionPred RemovePred = [](const SectionBase &) { return false; };
225
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000226 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000227 if (!Config.ToRemove.empty()) {
228 RemovePred = [&Config](const SectionBase &Sec) {
229 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
230 Sec.Name) != std::end(Config.ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000231 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000232 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000233
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000234 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000235 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000236 return IsDWOSection(Sec) || RemovePred(Sec);
237 };
238
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000239 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000240 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000241 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000242 };
243
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000244 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000245 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
246 if (RemovePred(Sec))
247 return true;
248 if ((Sec.Flags & SHF_ALLOC) != 0)
249 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000250 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000251 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000252 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000253 case SHT_SYMTAB:
254 case SHT_REL:
255 case SHT_RELA:
256 case SHT_STRTAB:
257 return true;
258 }
259 return Sec.Name.startswith(".debug");
260 };
261
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000262 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000263 RemovePred = [RemovePred](const SectionBase &Sec) {
264 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
265 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000266 }
267
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000268 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000269 RemovePred = [RemovePred](const SectionBase &Sec) {
270 return RemovePred(Sec) || Sec.Name.startswith(".debug");
271 };
272 }
273
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000274 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000275 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
276 if (RemovePred(Sec))
277 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000278 if (&Sec == Obj.SectionNames)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000279 return false;
280 return (Sec.Flags & SHF_ALLOC) == 0;
281 };
282
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000283 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000284 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
285 if (RemovePred(Sec))
286 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000287 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000288 return false;
289 if (Sec.Name.startswith(".gnu.warning"))
290 return false;
291 return (Sec.Flags & SHF_ALLOC) == 0;
292 };
293
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000294 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000295 if (!Config.OnlyKeep.empty()) {
296 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000297 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000298 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
299 Sec.Name) != std::end(Config.OnlyKeep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000300 return false;
301
302 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000303 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000304 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000305
306 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000307 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000308 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000309 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000310 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000311
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000312 // Remove everything else.
313 return true;
314 };
315 }
316
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000317 if (!Config.Keep.empty()) {
318 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000319 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000320 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
321 std::end(Config.Keep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000322 return false;
323 // Otherwise defer to RemovePred.
324 return RemovePred(Sec);
325 };
326 }
327
Jake Ehrlich76e91102018-01-25 22:46:17 +0000328 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000329
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000330 if (!Config.AddSection.empty()) {
331 for (const auto &Flag : Config.AddSection) {
332 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000333 auto SecName = SecPair.first;
334 auto File = SecPair.second;
335 auto BufOrErr = MemoryBuffer::getFile(File);
336 if (!BufOrErr)
337 reportError(File, BufOrErr.getError());
338 auto Buf = std::move(*BufOrErr);
339 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
340 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000341 Obj.addSection<OwnedDataSection>(SecName,
342 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000343 }
344 }
345
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000346 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000347 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000348
349 if (Obj.SymbolTable) {
350 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
351 if ((Config.LocalizeHidden &&
352 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
353 (!Config.SymbolsToLocalize.empty() &&
Paul Semelee5be792018-04-27 19:09:44 +0000354 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000355 Sym.Binding = STB_LOCAL;
356
Paul Semelee5be792018-04-27 19:09:44 +0000357 if (!Config.SymbolsToGlobalize.empty() &&
358 is_contained(Config.SymbolsToGlobalize, Sym.Name))
359 Sym.Binding = STB_GLOBAL;
360
Paul Semel3a8a56b2018-04-27 19:16:27 +0000361 if (!Config.SymbolsToWeaken.empty() &&
362 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
363 Sym.Binding == STB_GLOBAL)
364 Sym.Binding = STB_WEAK;
365
Paul Semel2c0510f2018-05-02 20:14:49 +0000366 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
367 Sym.getShndx() != SHN_UNDEF)
368 Sym.Binding = STB_WEAK;
369
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000370 const auto I = Config.SymbolsToRename.find(Sym.Name);
371 if (I != Config.SymbolsToRename.end())
372 Sym.Name = I->getValue();
373 });
Paul Semel41695f82018-05-02 20:19:22 +0000374
Paul Semel4246a462018-05-09 21:36:54 +0000375 Obj.removeSymbols([&](const Symbol &Sym) {
Paul Semel41695f82018-05-02 20:19:22 +0000376 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
377 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
378 Sym.Type != STT_SECTION)
379 return true;
Paul Semel4246a462018-05-09 21:36:54 +0000380
381 if (!Config.SymbolsToRemove.empty() &&
382 is_contained(Config.SymbolsToRemove, Sym.Name)) {
383 return true;
384 }
385
Paul Semel41695f82018-05-02 20:19:22 +0000386 return false;
387 });
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000388 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000389}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000390
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000391std::unique_ptr<Reader> CreateReader(StringRef InputFilename,
392 ElfType &OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000393 // Right now we can only read ELF files so there's only one reader;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000394 auto Out = llvm::make_unique<ELFReader>(InputFilename);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000395 // We need to set the default ElfType for output.
396 OutputElfType = Out->getElfType();
397 return std::move(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000398}
399
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000400void ExecuteElfObjcopy(const CopyConfig &Config) {
401 ElfType OutputElfType;
402 auto Reader = CreateReader(Config.InputFilename, OutputElfType);
Jake Ehrlicha8c689e2018-04-12 00:40:50 +0000403 auto Obj = Reader->create();
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000404 auto Writer =
405 CreateWriter(Config, *Obj, Config.OutputFilename, OutputElfType);
406 HandleArgs(Config, *Obj, *Reader, OutputElfType);
Jake Ehrlicha8c689e2018-04-12 00:40:50 +0000407 Writer->finalize();
408 Writer->write();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000409}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000410
411// ParseObjcopyOptions returns the config and sets the input arguments. If a
412// help flag is set then ParseObjcopyOptions will print the help messege and
413// exit.
414CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
415 ObjcopyOptTable T;
416 unsigned MissingArgumentIndex, MissingArgumentCount;
417 llvm::opt::InputArgList InputArgs =
418 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000419
420 if (InputArgs.size() == 0) {
421 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
422 exit(1);
423 }
424
425 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000426 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
427 exit(0);
428 }
429
430 SmallVector<const char *, 2> Positional;
431
432 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
433 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
434
435 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
436 Positional.push_back(Arg->getValue());
437
438 if (Positional.empty())
439 error("No input file specified");
440
441 if (Positional.size() > 2)
442 error("Too many positional arguments");
443
444 CopyConfig Config;
445 Config.InputFilename = Positional[0];
446 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
447 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
448 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
449 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
450
451 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
452 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000453
454 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
455 if (!StringRef(Arg->getValue()).contains('='))
456 error("Bad format for --redefine-sym");
457 auto Old2New = StringRef(Arg->getValue()).split('=');
458 if (!Config.SymbolsToRename.insert(Old2New).second)
459 error("Multiple redefinition of symbol " + Old2New.first);
460 }
461
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000462 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
463 Config.ToRemove.push_back(Arg->getValue());
464 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
465 Config.Keep.push_back(Arg->getValue());
466 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
467 Config.OnlyKeep.push_back(Arg->getValue());
468 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
469 Config.AddSection.push_back(Arg->getValue());
470 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
471 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
472 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
473 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
474 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
475 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
476 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
477 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000478 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000479 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Paul Semelb4924942018-04-26 17:44:43 +0000480 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000481 Config.SymbolsToLocalize.push_back(Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000482 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
483 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000484 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
485 Config.SymbolsToWeaken.push_back(Arg->getValue());
Paul Semel4246a462018-05-09 21:36:54 +0000486 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
487 Config.SymbolsToRemove.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000488
489 return Config;
490}
491
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000492// ParseStripOptions returns the config and sets the input arguments. If a
493// help flag is set then ParseStripOptions will print the help messege and
494// exit.
495CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
496 StripOptTable T;
497 unsigned MissingArgumentIndex, MissingArgumentCount;
498 llvm::opt::InputArgList InputArgs =
499 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
500
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000501 if (InputArgs.size() == 0) {
502 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
503 exit(1);
504 }
505
506 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000507 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
508 exit(0);
509 }
510
511 SmallVector<const char *, 2> Positional;
512 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
513 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
514 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
515 Positional.push_back(Arg->getValue());
516
517 if (Positional.empty())
518 error("No input file specified");
519
520 if (Positional.size() > 2)
521 error("Support for multiple input files is not implemented yet");
522
523 CopyConfig Config;
524 Config.InputFilename = Positional[0];
525 Config.OutputFilename = Positional[0];
526
527 // Strip debug info only.
528 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
529 if (!Config.StripDebug)
530 Config.StripAll = true;
531 return Config;
532}
533
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000534int main(int argc, char **argv) {
535 InitLLVM X(argc, argv);
536 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000537 CopyConfig Config;
538 if (sys::path::stem(ToolName).endswith_lower("strip"))
539 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
540 else
541 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000542 ExecuteElfObjcopy(Config);
543}