blob: 0a5b5b0d06629f672e5979bad9802ac5a6232850 [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
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000058#define PREFIX(NAME, VALUE) const char *const OBJCOPY_##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) \
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000065 {OBJCOPY_##PREFIX, \
66 NAME, \
67 HELPTEXT, \
68 METAVAR, \
69 OBJCOPY_##ID, \
70 opt::Option::KIND##Class, \
71 PARAM, \
72 FLAGS, \
73 OBJCOPY_##GROUP, \
74 OBJCOPY_##ALIAS, \
75 ALIASARGS, \
76 VALUES},
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000077#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000078#undef OPTION
79};
80
81class ObjcopyOptTable : public opt::OptTable {
82public:
83 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
84};
85
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000086enum StripID {
87 STRIP_INVALID = 0, // This is not an option ID.
88#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
89 HELPTEXT, METAVAR, VALUES) \
90 STRIP_##ID,
91#include "StripOpts.inc"
92#undef OPTION
93};
94
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000095#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
96#include "StripOpts.inc"
97#undef PREFIX
98
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000099static const opt::OptTable::Info StripInfoTable[] = {
100#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
101 HELPTEXT, METAVAR, VALUES) \
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000102 {STRIP_##PREFIX, NAME, HELPTEXT, \
103 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
104 PARAM, FLAGS, STRIP_##GROUP, \
105 STRIP_##ALIAS, ALIASARGS, VALUES},
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000106#include "StripOpts.inc"
107#undef OPTION
108};
109
110class StripOptTable : public opt::OptTable {
111public:
112 StripOptTable() : OptTable(StripInfoTable, true) {}
113};
114
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000115} // namespace
116
Petr Hosek05a04cb2017-08-01 00:33:58 +0000117// The name this program was invoked as.
118static StringRef ToolName;
119
120namespace llvm {
121
Zachary Turner41a9ee92017-10-11 23:54:34 +0000122LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000123 errs() << ToolName << ": " << Message << ".\n";
124 errs().flush();
125 exit(1);
126}
127
128LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
129 assert(EC);
130 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
131 exit(1);
132}
133
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000134LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000135 assert(E);
136 std::string Buf;
137 raw_string_ostream OS(Buf);
138 logAllUnhandledErrors(std::move(E), OS, "");
139 OS.flush();
140 errs() << ToolName << ": '" << File << "': " << Buf;
141 exit(1);
142}
Petr Hosek05a04cb2017-08-01 00:33:58 +0000143
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000144} // end namespace llvm
145
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000146struct CopyConfig {
147 StringRef OutputFilename;
148 StringRef InputFilename;
149 StringRef OutputFormat;
150 StringRef InputFormat;
151 StringRef BinaryArch;
Alexander Shaposhnikovfedb0162018-02-09 23:33:31 +0000152
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000153 StringRef SplitDWO;
154 StringRef AddGnuDebugLink;
155 std::vector<StringRef> ToRemove;
156 std::vector<StringRef> Keep;
157 std::vector<StringRef> OnlyKeep;
158 std::vector<StringRef> AddSection;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000159 std::vector<StringRef> SymbolsToLocalize;
Paul Semelee5be792018-04-27 19:09:44 +0000160 std::vector<StringRef> SymbolsToGlobalize;
Paul Semel3a8a56b2018-04-27 19:16:27 +0000161 std::vector<StringRef> SymbolsToWeaken;
Paul Semel4246a462018-05-09 21:36:54 +0000162 std::vector<StringRef> SymbolsToRemove;
Paul Semel5d97c822018-05-15 14:09:37 +0000163 std::vector<StringRef> SymbolsToKeep;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000164 StringMap<StringRef> SymbolsToRename;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000165 bool StripAll = false;
166 bool StripAllGNU = false;
167 bool StripDebug = false;
168 bool StripSections = false;
169 bool StripNonAlloc = false;
170 bool StripDWO = false;
Paul Semel99dda0b2018-05-25 11:01:25 +0000171 bool StripUnneeded = false;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000172 bool ExtractDWO = false;
173 bool LocalizeHidden = false;
174 bool Weaken = false;
175 bool DiscardAll = false;
Jake Ehrliche40398a2018-05-15 20:53:53 +0000176 bool OnlyKeepDebug = false;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000177};
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000178
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000179using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000180
Jake Ehrlich777fb002017-12-15 20:17:55 +0000181bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000182
Jake Ehrlich76e91102018-01-25 22:46:17 +0000183bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000184 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000185 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000186 return false;
187 // Short of keeping the string table we want to keep everything that is a DWO
188 // section and remove everything else.
189 return !IsDWOSection(Sec);
190}
191
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000192std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj,
193 StringRef File, ElfType OutputElfType) {
194 if (Config.OutputFormat == "binary") {
195 return llvm::make_unique<BinaryWriter>(File, Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000196 }
197 // Depending on the initial ELFT and OutputFormat we need a different Writer.
198 switch (OutputElfType) {
199 case ELFT_ELF32LE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000200 return llvm::make_unique<ELFWriter<ELF32LE>>(File, Obj,
201 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000202 case ELFT_ELF64LE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000203 return llvm::make_unique<ELFWriter<ELF64LE>>(File, Obj,
204 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000205 case ELFT_ELF32BE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000206 return llvm::make_unique<ELFWriter<ELF32BE>>(File, Obj,
207 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000208 case ELFT_ELF64BE:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000209 return llvm::make_unique<ELFWriter<ELF64BE>>(File, Obj,
210 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000211 }
212 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000213}
214
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000215void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
216 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000217 auto DWOFile = Reader.create();
218 DWOFile->removeSections(
219 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000220 auto Writer = CreateWriter(Config, *DWOFile, File, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000221 Writer->finalize();
222 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000223}
224
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000225// This function handles the high level operations of GNU objcopy including
226// handling command line options. It's important to outline certain properties
227// we expect to hold of the command line operations. Any operation that "keeps"
228// should keep regardless of a remove. Additionally any removal should respect
229// any previous removals. Lastly whether or not something is removed shouldn't
230// depend a) on the order the options occur in or b) on some opaque priority
231// system. The only priority is that keeps/copies overrule removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000232void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader,
233 ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000234
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000235 if (!Config.SplitDWO.empty()) {
236 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000237 }
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000238
239 // TODO: update or remove symbols only if there is an option that affects
240 // them.
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000241 if (Obj.SymbolTable) {
242 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
243 if ((Config.LocalizeHidden &&
244 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
245 (!Config.SymbolsToLocalize.empty() &&
246 is_contained(Config.SymbolsToLocalize, Sym.Name)))
247 Sym.Binding = STB_LOCAL;
248
249 if (!Config.SymbolsToGlobalize.empty() &&
250 is_contained(Config.SymbolsToGlobalize, Sym.Name))
251 Sym.Binding = STB_GLOBAL;
252
253 if (!Config.SymbolsToWeaken.empty() &&
254 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
255 Sym.Binding == STB_GLOBAL)
256 Sym.Binding = STB_WEAK;
257
258 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
259 Sym.getShndx() != SHN_UNDEF)
260 Sym.Binding = STB_WEAK;
261
262 const auto I = Config.SymbolsToRename.find(Sym.Name);
263 if (I != Config.SymbolsToRename.end())
264 Sym.Name = I->getValue();
265 });
266
Paul Semel99dda0b2018-05-25 11:01:25 +0000267 // The purpose of this loop is to mark symbols referenced by sections
268 // (like GroupSection or RelocationSection). This way, we know which
269 // symbols are still 'needed' and wich are not.
270 if (Config.StripUnneeded) {
271 for (auto &Section : Obj.sections())
272 Section.markSymbols();
273 }
274
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000275 Obj.removeSymbols([&](const Symbol &Sym) {
276 if (!Config.SymbolsToKeep.empty() &&
277 is_contained(Config.SymbolsToKeep, Sym.Name))
278 return false;
279
280 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
281 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
282 Sym.Type != STT_SECTION)
283 return true;
284
285 if (Config.StripAll || Config.StripAllGNU)
286 return true;
287
288 if (!Config.SymbolsToRemove.empty() &&
289 is_contained(Config.SymbolsToRemove, Sym.Name)) {
290 return true;
291 }
292
Paul Semel99dda0b2018-05-25 11:01:25 +0000293 // TODO: We might handle the 'null symbol' in a different way
294 // by probably handling it the same way as we handle 'null section' ?
295 if (Config.StripUnneeded && !Sym.Referenced && Sym.Index != 0 &&
296 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
297 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
298 return true;
299
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000300 return false;
301 });
302 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000303
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000304 SectionPred RemovePred = [](const SectionBase &) { return false; };
305
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000306 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000307 if (!Config.ToRemove.empty()) {
308 RemovePred = [&Config](const SectionBase &Sec) {
309 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
310 Sec.Name) != std::end(Config.ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000311 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000312 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000313
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000314 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000315 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000316 return IsDWOSection(Sec) || RemovePred(Sec);
317 };
318
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000319 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000320 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000321 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000322 };
323
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000324 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000325 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
326 if (RemovePred(Sec))
327 return true;
328 if ((Sec.Flags & SHF_ALLOC) != 0)
329 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000330 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000331 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000332 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000333 case SHT_SYMTAB:
334 case SHT_REL:
335 case SHT_RELA:
336 case SHT_STRTAB:
337 return true;
338 }
339 return Sec.Name.startswith(".debug");
340 };
341
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000342 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000343 RemovePred = [RemovePred](const SectionBase &Sec) {
344 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
345 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000346 }
347
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000348 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000349 RemovePred = [RemovePred](const SectionBase &Sec) {
350 return RemovePred(Sec) || Sec.Name.startswith(".debug");
351 };
352 }
353
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000354 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000355 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
356 if (RemovePred(Sec))
357 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000358 if (&Sec == Obj.SectionNames)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000359 return false;
360 return (Sec.Flags & SHF_ALLOC) == 0;
361 };
362
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000363 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000364 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
365 if (RemovePred(Sec))
366 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000367 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000368 return false;
369 if (Sec.Name.startswith(".gnu.warning"))
370 return false;
371 return (Sec.Flags & SHF_ALLOC) == 0;
372 };
373
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000374 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000375 if (!Config.OnlyKeep.empty()) {
376 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000377 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000378 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
379 Sec.Name) != std::end(Config.OnlyKeep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000380 return false;
381
382 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000383 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000384 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000385
386 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000387 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000388 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000389 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000390 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000391
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000392 // Remove everything else.
393 return true;
394 };
395 }
396
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000397 if (!Config.Keep.empty()) {
398 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000399 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000400 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
401 std::end(Config.Keep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000402 return false;
403 // Otherwise defer to RemovePred.
404 return RemovePred(Sec);
405 };
406 }
407
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000408 // This has to be the last predicate assignment.
409 // If the option --keep-symbol has been specified
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000410 // and at least one of those symbols is present
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000411 // (equivalently, the updated symbol table is not empty)
412 // the symbol table and the string table should not be removed.
413 if (!Config.SymbolsToKeep.empty() && !Obj.SymbolTable->empty()) {
414 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
415 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
416 return false;
417 return RemovePred(Sec);
418 };
419 }
420
Jake Ehrlich76e91102018-01-25 22:46:17 +0000421 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000422
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000423 if (!Config.AddSection.empty()) {
424 for (const auto &Flag : Config.AddSection) {
425 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000426 auto SecName = SecPair.first;
427 auto File = SecPair.second;
428 auto BufOrErr = MemoryBuffer::getFile(File);
429 if (!BufOrErr)
430 reportError(File, BufOrErr.getError());
431 auto Buf = std::move(*BufOrErr);
432 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
433 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000434 Obj.addSection<OwnedDataSection>(SecName,
435 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000436 }
437 }
438
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000439 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000440 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000441}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000442
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000443std::unique_ptr<Reader> CreateReader(StringRef InputFilename,
444 ElfType &OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000445 // Right now we can only read ELF files so there's only one reader;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000446 auto Out = llvm::make_unique<ELFReader>(InputFilename);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000447 // We need to set the default ElfType for output.
448 OutputElfType = Out->getElfType();
449 return std::move(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000450}
451
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000452void ExecuteElfObjcopy(const CopyConfig &Config) {
453 ElfType OutputElfType;
454 auto Reader = CreateReader(Config.InputFilename, OutputElfType);
Jake Ehrlicha8c689e2018-04-12 00:40:50 +0000455 auto Obj = Reader->create();
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000456 auto Writer =
457 CreateWriter(Config, *Obj, Config.OutputFilename, OutputElfType);
458 HandleArgs(Config, *Obj, *Reader, OutputElfType);
Jake Ehrlicha8c689e2018-04-12 00:40:50 +0000459 Writer->finalize();
460 Writer->write();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000461}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000462
463// ParseObjcopyOptions returns the config and sets the input arguments. If a
464// help flag is set then ParseObjcopyOptions will print the help messege and
465// exit.
466CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
467 ObjcopyOptTable T;
468 unsigned MissingArgumentIndex, MissingArgumentCount;
469 llvm::opt::InputArgList InputArgs =
470 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000471
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000472 if (InputArgs.size() == 0) {
473 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
474 exit(1);
475 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000476
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000477 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000478 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
479 exit(0);
480 }
481
482 SmallVector<const char *, 2> Positional;
483
484 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
485 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
486
487 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
488 Positional.push_back(Arg->getValue());
489
490 if (Positional.empty())
491 error("No input file specified");
492
493 if (Positional.size() > 2)
494 error("Too many positional arguments");
495
496 CopyConfig Config;
497 Config.InputFilename = Positional[0];
498 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
499 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
500 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
501 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
502
503 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
504 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000505
506 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
507 if (!StringRef(Arg->getValue()).contains('='))
508 error("Bad format for --redefine-sym");
509 auto Old2New = StringRef(Arg->getValue()).split('=');
510 if (!Config.SymbolsToRename.insert(Old2New).second)
511 error("Multiple redefinition of symbol " + Old2New.first);
512 }
513
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000514 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
515 Config.ToRemove.push_back(Arg->getValue());
516 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
517 Config.Keep.push_back(Arg->getValue());
518 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
519 Config.OnlyKeep.push_back(Arg->getValue());
520 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
521 Config.AddSection.push_back(Arg->getValue());
522 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
523 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
524 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
525 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
526 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
527 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
Paul Semel99dda0b2018-05-25 11:01:25 +0000528 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000529 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
530 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000531 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000532 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Jake Ehrliche40398a2018-05-15 20:53:53 +0000533 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
Paul Semelb4924942018-04-26 17:44:43 +0000534 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000535 Config.SymbolsToLocalize.push_back(Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000536 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
537 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000538 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
539 Config.SymbolsToWeaken.push_back(Arg->getValue());
Paul Semel4246a462018-05-09 21:36:54 +0000540 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
541 Config.SymbolsToRemove.push_back(Arg->getValue());
Paul Semel5d97c822018-05-15 14:09:37 +0000542 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
543 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000544
545 return Config;
546}
547
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000548// ParseStripOptions returns the config and sets the input arguments. If a
549// help flag is set then ParseStripOptions will print the help messege and
550// exit.
551CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
552 StripOptTable T;
553 unsigned MissingArgumentIndex, MissingArgumentCount;
554 llvm::opt::InputArgList InputArgs =
555 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
556
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000557 if (InputArgs.size() == 0) {
558 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
559 exit(1);
560 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000561
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000562 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000563 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
564 exit(0);
565 }
566
567 SmallVector<const char *, 2> Positional;
568 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
569 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
570 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
571 Positional.push_back(Arg->getValue());
572
573 if (Positional.empty())
574 error("No input file specified");
575
576 if (Positional.size() > 2)
577 error("Support for multiple input files is not implemented yet");
578
579 CopyConfig Config;
580 Config.InputFilename = Positional[0];
581 Config.OutputFilename = Positional[0];
582
583 // Strip debug info only.
584 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
585 if (!Config.StripDebug)
586 Config.StripAll = true;
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000587
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000588 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
589 Config.ToRemove.push_back(Arg->getValue());
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000590
Alexander Shaposhnikov35bee3e2018-05-23 19:44:19 +0000591 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
592 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000593
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000594 return Config;
595}
596
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000597int main(int argc, char **argv) {
598 InitLLVM X(argc, argv);
599 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000600 CopyConfig Config;
601 if (sys::path::stem(ToolName).endswith_lower("strip"))
602 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
603 else
604 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000605 ExecuteElfObjcopy(Config);
606}