blob: c28862f073a0712738f222a647b49ea8b8f9256a [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"
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000016#include "llvm/Object/Archive.h"
17#include "llvm/Object/ArchiveWriter.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000018#include "llvm/Object/Binary.h"
19#include "llvm/Object/ELFObjectFile.h"
20#include "llvm/Object/ELFTypes.h"
21#include "llvm/Object/Error.h"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000022#include "llvm/Option/Arg.h"
23#include "llvm/Option/ArgList.h"
24#include "llvm/Option/Option.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000025#include "llvm/Support/Casting.h"
Petr Hosek05a04cb2017-08-01 00:33:58 +000026#include "llvm/Support/CommandLine.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000027#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Error.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/ErrorOr.h"
Petr Hosek05a04cb2017-08-01 00:33:58 +000031#include "llvm/Support/FileOutputBuffer.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000032#include "llvm/Support/InitLLVM.h"
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000033#include "llvm/Support/Path.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000034#include "llvm/Support/raw_ostream.h"
35#include <algorithm>
36#include <cassert>
37#include <cstdlib>
38#include <functional>
39#include <iterator>
Petr Hosek05a04cb2017-08-01 00:33:58 +000040#include <memory>
41#include <string>
42#include <system_error>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000043#include <utility>
Petr Hosek05a04cb2017-08-01 00:33:58 +000044
45using namespace llvm;
46using namespace object;
47using namespace ELF;
48
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000049namespace {
50
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000051enum ObjcopyID {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000052 OBJCOPY_INVALID = 0, // This is not an option ID.
53#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
54 HELPTEXT, METAVAR, VALUES) \
55 OBJCOPY_##ID,
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000056#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000057#undef OPTION
58};
59
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000060#define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000061#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000062#undef PREFIX
63
Alexander Shaposhnikov3326e782018-04-24 06:23:22 +000064static const opt::OptTable::Info ObjcopyInfoTable[] = {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000065#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
66 HELPTEXT, METAVAR, VALUES) \
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000067 {OBJCOPY_##PREFIX, \
68 NAME, \
69 HELPTEXT, \
70 METAVAR, \
71 OBJCOPY_##ID, \
72 opt::Option::KIND##Class, \
73 PARAM, \
74 FLAGS, \
75 OBJCOPY_##GROUP, \
76 OBJCOPY_##ALIAS, \
77 ALIASARGS, \
78 VALUES},
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000079#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000080#undef OPTION
81};
82
83class ObjcopyOptTable : public opt::OptTable {
84public:
85 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
86};
87
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000088enum StripID {
89 STRIP_INVALID = 0, // This is not an option ID.
90#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
91 HELPTEXT, METAVAR, VALUES) \
92 STRIP_##ID,
93#include "StripOpts.inc"
94#undef OPTION
95};
96
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000097#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
98#include "StripOpts.inc"
99#undef PREFIX
100
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000101static const opt::OptTable::Info StripInfoTable[] = {
102#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
103 HELPTEXT, METAVAR, VALUES) \
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000104 {STRIP_##PREFIX, NAME, HELPTEXT, \
105 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
106 PARAM, FLAGS, STRIP_##GROUP, \
107 STRIP_##ALIAS, ALIASARGS, VALUES},
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000108#include "StripOpts.inc"
109#undef OPTION
110};
111
112class StripOptTable : public opt::OptTable {
113public:
114 StripOptTable() : OptTable(StripInfoTable, true) {}
115};
116
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000117} // namespace
118
Petr Hosek05a04cb2017-08-01 00:33:58 +0000119// The name this program was invoked as.
120static StringRef ToolName;
121
122namespace llvm {
123
Zachary Turner41a9ee92017-10-11 23:54:34 +0000124LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000125 errs() << ToolName << ": " << Message << ".\n";
126 errs().flush();
127 exit(1);
128}
129
130LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
131 assert(EC);
132 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
133 exit(1);
134}
135
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000136LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000137 assert(E);
138 std::string Buf;
139 raw_string_ostream OS(Buf);
140 logAllUnhandledErrors(std::move(E), OS, "");
141 OS.flush();
142 errs() << ToolName << ": '" << File << "': " << Buf;
143 exit(1);
144}
Petr Hosek05a04cb2017-08-01 00:33:58 +0000145
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000146} // end namespace llvm
147
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000148struct CopyConfig {
149 StringRef OutputFilename;
150 StringRef InputFilename;
151 StringRef OutputFormat;
152 StringRef InputFormat;
153 StringRef BinaryArch;
Alexander Shaposhnikovfedb0162018-02-09 23:33:31 +0000154
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000155 StringRef SplitDWO;
156 StringRef AddGnuDebugLink;
157 std::vector<StringRef> ToRemove;
158 std::vector<StringRef> Keep;
159 std::vector<StringRef> OnlyKeep;
160 std::vector<StringRef> AddSection;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000161 std::vector<StringRef> SymbolsToLocalize;
Paul Semelee5be792018-04-27 19:09:44 +0000162 std::vector<StringRef> SymbolsToGlobalize;
Paul Semel3a8a56b2018-04-27 19:16:27 +0000163 std::vector<StringRef> SymbolsToWeaken;
Paul Semel4246a462018-05-09 21:36:54 +0000164 std::vector<StringRef> SymbolsToRemove;
Paul Semel5d97c822018-05-15 14:09:37 +0000165 std::vector<StringRef> SymbolsToKeep;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000166 StringMap<StringRef> SymbolsToRename;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000167 bool StripAll = false;
168 bool StripAllGNU = false;
169 bool StripDebug = false;
170 bool StripSections = false;
171 bool StripNonAlloc = false;
172 bool StripDWO = false;
Paul Semel99dda0b2018-05-25 11:01:25 +0000173 bool StripUnneeded = false;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000174 bool ExtractDWO = false;
175 bool LocalizeHidden = false;
176 bool Weaken = false;
177 bool DiscardAll = false;
Jake Ehrliche40398a2018-05-15 20:53:53 +0000178 bool OnlyKeepDebug = false;
Paul Semelcf51c802018-05-26 08:10:37 +0000179 bool KeepFileSymbols = false;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000180};
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000181
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000182using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000183
Jake Ehrlich777fb002017-12-15 20:17:55 +0000184bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000185
Jake Ehrlich76e91102018-01-25 22:46:17 +0000186bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000187 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000188 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000189 return false;
190 // Short of keeping the string table we want to keep everything that is a DWO
191 // section and remove everything else.
192 return !IsDWOSection(Sec);
193}
194
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000195std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj,
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000196 Buffer &Buf, ElfType OutputElfType) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000197 if (Config.OutputFormat == "binary") {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000198 return llvm::make_unique<BinaryWriter>(Obj, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000199 }
200 // Depending on the initial ELFT and OutputFormat we need a different Writer.
201 switch (OutputElfType) {
202 case ELFT_ELF32LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000203 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000204 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000205 case ELFT_ELF64LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000206 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000207 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000208 case ELFT_ELF32BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000209 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000210 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000211 case ELFT_ELF64BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000212 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000213 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000214 }
215 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000216}
217
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000218void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
219 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000220 auto DWOFile = Reader.create();
221 DWOFile->removeSections(
222 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000223 FileBuffer FB(File);
224 auto Writer = CreateWriter(Config, *DWOFile, FB, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000225 Writer->finalize();
226 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000227}
228
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000229// This function handles the high level operations of GNU objcopy including
230// handling command line options. It's important to outline certain properties
231// we expect to hold of the command line operations. Any operation that "keeps"
232// should keep regardless of a remove. Additionally any removal should respect
233// any previous removals. Lastly whether or not something is removed shouldn't
234// depend a) on the order the options occur in or b) on some opaque priority
235// system. The only priority is that keeps/copies overrule removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000236void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader,
237 ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000238
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000239 if (!Config.SplitDWO.empty()) {
240 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000241 }
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000242
243 // TODO: update or remove symbols only if there is an option that affects
244 // them.
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000245 if (Obj.SymbolTable) {
246 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
247 if ((Config.LocalizeHidden &&
248 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
249 (!Config.SymbolsToLocalize.empty() &&
250 is_contained(Config.SymbolsToLocalize, Sym.Name)))
251 Sym.Binding = STB_LOCAL;
252
253 if (!Config.SymbolsToGlobalize.empty() &&
254 is_contained(Config.SymbolsToGlobalize, Sym.Name))
255 Sym.Binding = STB_GLOBAL;
256
257 if (!Config.SymbolsToWeaken.empty() &&
258 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
259 Sym.Binding == STB_GLOBAL)
260 Sym.Binding = STB_WEAK;
261
262 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
263 Sym.getShndx() != SHN_UNDEF)
264 Sym.Binding = STB_WEAK;
265
266 const auto I = Config.SymbolsToRename.find(Sym.Name);
267 if (I != Config.SymbolsToRename.end())
268 Sym.Name = I->getValue();
269 });
270
Paul Semel99dda0b2018-05-25 11:01:25 +0000271 // The purpose of this loop is to mark symbols referenced by sections
272 // (like GroupSection or RelocationSection). This way, we know which
273 // symbols are still 'needed' and wich are not.
274 if (Config.StripUnneeded) {
275 for (auto &Section : Obj.sections())
276 Section.markSymbols();
277 }
278
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000279 Obj.removeSymbols([&](const Symbol &Sym) {
Paul Semelcf51c802018-05-26 08:10:37 +0000280 if ((!Config.SymbolsToKeep.empty() &&
281 is_contained(Config.SymbolsToKeep, Sym.Name)) ||
282 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000283 return false;
284
285 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
286 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
287 Sym.Type != STT_SECTION)
288 return true;
289
290 if (Config.StripAll || Config.StripAllGNU)
291 return true;
292
293 if (!Config.SymbolsToRemove.empty() &&
294 is_contained(Config.SymbolsToRemove, Sym.Name)) {
295 return true;
296 }
297
Paul Semel46201fb2018-06-01 16:19:46 +0000298 if (Config.StripUnneeded && !Sym.Referenced &&
Paul Semel99dda0b2018-05-25 11:01:25 +0000299 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
300 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
301 return true;
302
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000303 return false;
304 });
305 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000306
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000307 SectionPred RemovePred = [](const SectionBase &) { return false; };
308
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000309 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000310 if (!Config.ToRemove.empty()) {
311 RemovePred = [&Config](const SectionBase &Sec) {
312 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
313 Sec.Name) != std::end(Config.ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000314 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000315 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000316
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000317 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000318 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000319 return IsDWOSection(Sec) || RemovePred(Sec);
320 };
321
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000322 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000323 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000324 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000325 };
326
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000327 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000328 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
329 if (RemovePred(Sec))
330 return true;
331 if ((Sec.Flags & SHF_ALLOC) != 0)
332 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000333 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000334 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000335 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000336 case SHT_SYMTAB:
337 case SHT_REL:
338 case SHT_RELA:
339 case SHT_STRTAB:
340 return true;
341 }
342 return Sec.Name.startswith(".debug");
343 };
344
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000345 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000346 RemovePred = [RemovePred](const SectionBase &Sec) {
347 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
348 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000349 }
350
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000351 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000352 RemovePred = [RemovePred](const SectionBase &Sec) {
353 return RemovePred(Sec) || Sec.Name.startswith(".debug");
354 };
355 }
356
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000357 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000358 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
359 if (RemovePred(Sec))
360 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000361 if (&Sec == Obj.SectionNames)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000362 return false;
363 return (Sec.Flags & SHF_ALLOC) == 0;
364 };
365
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000366 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000367 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
368 if (RemovePred(Sec))
369 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000370 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000371 return false;
372 if (Sec.Name.startswith(".gnu.warning"))
373 return false;
374 return (Sec.Flags & SHF_ALLOC) == 0;
375 };
376
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000377 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000378 if (!Config.OnlyKeep.empty()) {
379 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000380 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000381 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
382 Sec.Name) != std::end(Config.OnlyKeep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000383 return false;
384
385 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000386 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000387 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000388
389 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000390 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000391 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000392 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000393 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000394
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000395 // Remove everything else.
396 return true;
397 };
398 }
399
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000400 if (!Config.Keep.empty()) {
401 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000402 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000403 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
404 std::end(Config.Keep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000405 return false;
406 // Otherwise defer to RemovePred.
407 return RemovePred(Sec);
408 };
409 }
410
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000411 // This has to be the last predicate assignment.
412 // If the option --keep-symbol has been specified
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000413 // and at least one of those symbols is present
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000414 // (equivalently, the updated symbol table is not empty)
415 // the symbol table and the string table should not be removed.
Paul Semelcf51c802018-05-26 08:10:37 +0000416 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
417 !Obj.SymbolTable->empty()) {
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000418 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
419 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
420 return false;
421 return RemovePred(Sec);
422 };
423 }
424
Jake Ehrlich76e91102018-01-25 22:46:17 +0000425 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000426
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000427 if (!Config.AddSection.empty()) {
428 for (const auto &Flag : Config.AddSection) {
429 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000430 auto SecName = SecPair.first;
431 auto File = SecPair.second;
432 auto BufOrErr = MemoryBuffer::getFile(File);
433 if (!BufOrErr)
434 reportError(File, BufOrErr.getError());
435 auto Buf = std::move(*BufOrErr);
436 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
437 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000438 Obj.addSection<OwnedDataSection>(SecName,
439 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000440 }
441 }
442
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000443 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000444 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000445}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000446
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000447void ExecuteElfObjcopyOnBinary(const CopyConfig &Config, Binary &Binary,
448 Buffer &Out) {
449 ELFReader Reader(&Binary);
450 std::unique_ptr<Object> Obj = Reader.create();
451
452 HandleArgs(Config, *Obj, Reader, Reader.getElfType());
453
454 std::unique_ptr<Writer> Writer =
455 CreateWriter(Config, *Obj, Out, Reader.getElfType());
456 Writer->finalize();
457 Writer->write();
458}
459
460// For regular archives this function simply calls llvm::writeArchive,
461// For thin archives it writes the archive file itself as well as its members.
462Error deepWriteArchive(StringRef ArcName, ArrayRef<NewArchiveMember> NewMembers,
463 bool WriteSymtab, object::Archive::Kind Kind,
464 bool Deterministic, bool Thin) {
465 Error E =
466 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
467 if (!Thin || E)
468 return E;
469 for (const NewArchiveMember &Member : NewMembers) {
470 // Internally, FileBuffer will use the buffer created by
471 // FileOutputBuffer::create, for regular files (that is the case for
472 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
473 // OnDiskBuffer uses a temporary file and then renames it. So in reality
474 // there is no inefficiency / duplicated in-memory buffers in this case. For
475 // now in-memory buffers can not be completely avoided since
476 // NewArchiveMember still requires them even though writeArchive does not
477 // write them on disk.
478 FileBuffer FB(Member.MemberName);
479 FB.allocate(Member.Buf->getBufferSize());
480 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
481 FB.getBufferStart());
482 if (auto E = FB.commit())
483 return E;
484 }
485 return Error::success();
486}
487
488void ExecuteElfObjcopyOnArchive(const CopyConfig &Config, const Archive &Ar) {
489 std::vector<NewArchiveMember> NewArchiveMembers;
490 Error Err = Error::success();
491 for (const Archive::Child &Child : Ar.children(Err)) {
492 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
493 if (!ChildOrErr)
494 reportError(Ar.getFileName(), ChildOrErr.takeError());
495 Expected<StringRef> ChildNameOrErr = Child.getName();
496 if (!ChildNameOrErr)
497 reportError(Ar.getFileName(), ChildNameOrErr.takeError());
498
499 MemBuffer MB(ChildNameOrErr.get());
500 ExecuteElfObjcopyOnBinary(Config, **ChildOrErr, MB);
501
502 Expected<NewArchiveMember> Member =
503 NewArchiveMember::getOldMember(Child, true);
504 if (!Member)
505 reportError(Ar.getFileName(), Member.takeError());
506 Member->Buf = MB.releaseMemoryBuffer();
507 Member->MemberName = Member->Buf->getBufferIdentifier();
508 NewArchiveMembers.push_back(std::move(*Member));
509 }
510
511 if (Err)
512 reportError(Config.InputFilename, std::move(Err));
513 if (Error E =
514 deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
515 Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin()))
516 reportError(Config.OutputFilename, std::move(E));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000517}
518
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000519void ExecuteElfObjcopy(const CopyConfig &Config) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000520 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
521 createBinary(Config.InputFilename);
522 if (!BinaryOrErr)
523 reportError(Config.InputFilename, BinaryOrErr.takeError());
524
525 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary()))
526 return ExecuteElfObjcopyOnArchive(Config, *Ar);
527
528 FileBuffer FB(Config.OutputFilename);
529 ExecuteElfObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000530}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000531
532// ParseObjcopyOptions returns the config and sets the input arguments. If a
533// help flag is set then ParseObjcopyOptions will print the help messege and
534// exit.
535CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
536 ObjcopyOptTable T;
537 unsigned MissingArgumentIndex, MissingArgumentCount;
538 llvm::opt::InputArgList InputArgs =
539 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000540
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000541 if (InputArgs.size() == 0) {
542 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
543 exit(1);
544 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000545
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000546 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000547 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
548 exit(0);
549 }
550
551 SmallVector<const char *, 2> Positional;
552
553 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
554 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
555
556 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
557 Positional.push_back(Arg->getValue());
558
559 if (Positional.empty())
560 error("No input file specified");
561
562 if (Positional.size() > 2)
563 error("Too many positional arguments");
564
565 CopyConfig Config;
566 Config.InputFilename = Positional[0];
567 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
568 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
569 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
570 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
571
572 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
573 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000574
575 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
576 if (!StringRef(Arg->getValue()).contains('='))
577 error("Bad format for --redefine-sym");
578 auto Old2New = StringRef(Arg->getValue()).split('=');
579 if (!Config.SymbolsToRename.insert(Old2New).second)
580 error("Multiple redefinition of symbol " + Old2New.first);
581 }
582
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000583 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
584 Config.ToRemove.push_back(Arg->getValue());
585 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
586 Config.Keep.push_back(Arg->getValue());
587 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
588 Config.OnlyKeep.push_back(Arg->getValue());
589 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
590 Config.AddSection.push_back(Arg->getValue());
591 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
592 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
593 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
594 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
595 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
596 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
Paul Semel99dda0b2018-05-25 11:01:25 +0000597 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000598 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
599 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000600 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000601 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Jake Ehrliche40398a2018-05-15 20:53:53 +0000602 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
Paul Semelcf51c802018-05-26 08:10:37 +0000603 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
Paul Semelb4924942018-04-26 17:44:43 +0000604 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000605 Config.SymbolsToLocalize.push_back(Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000606 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
607 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000608 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
609 Config.SymbolsToWeaken.push_back(Arg->getValue());
Paul Semel4246a462018-05-09 21:36:54 +0000610 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
611 Config.SymbolsToRemove.push_back(Arg->getValue());
Paul Semel5d97c822018-05-15 14:09:37 +0000612 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
613 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000614
615 return Config;
616}
617
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000618// ParseStripOptions returns the config and sets the input arguments. If a
619// help flag is set then ParseStripOptions will print the help messege and
620// exit.
621CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
622 StripOptTable T;
623 unsigned MissingArgumentIndex, MissingArgumentCount;
624 llvm::opt::InputArgList InputArgs =
625 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
626
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000627 if (InputArgs.size() == 0) {
628 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
629 exit(1);
630 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000631
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000632 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000633 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
634 exit(0);
635 }
636
637 SmallVector<const char *, 2> Positional;
638 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
639 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
640 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
641 Positional.push_back(Arg->getValue());
642
643 if (Positional.empty())
644 error("No input file specified");
645
646 if (Positional.size() > 2)
647 error("Support for multiple input files is not implemented yet");
648
649 CopyConfig Config;
650 Config.InputFilename = Positional[0];
Alexander Shaposhnikovecc84832018-05-31 20:42:13 +0000651 Config.OutputFilename =
652 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000653
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000654 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000655
Alexander Shaposhnikov29407f32018-06-06 21:23:19 +0000656 Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all);
Paul Semele57bc782018-06-07 10:05:25 +0000657 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
658
659 if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll)
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000660 Config.StripAll = true;
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000661
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000662 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
663 Config.ToRemove.push_back(Arg->getValue());
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000664
Alexander Shaposhnikov35bee3e2018-05-23 19:44:19 +0000665 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
666 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000667
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000668 return Config;
669}
670
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000671int main(int argc, char **argv) {
672 InitLLVM X(argc, argv);
673 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000674 CopyConfig Config;
675 if (sys::path::stem(ToolName).endswith_lower("strip"))
676 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
677 else
678 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000679 ExecuteElfObjcopy(Config);
680}