blob: 12e9ca17e1990b1145554819f386526be63df192 [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;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000046using namespace llvm::objcopy;
Petr Hosek05a04cb2017-08-01 00:33:58 +000047using namespace object;
48using namespace ELF;
49
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000050namespace {
51
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000052enum ObjcopyID {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000053 OBJCOPY_INVALID = 0, // This is not an option ID.
54#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
55 HELPTEXT, METAVAR, VALUES) \
56 OBJCOPY_##ID,
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000057#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000058#undef OPTION
59};
60
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000061#define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000062#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000063#undef PREFIX
64
Alexander Shaposhnikov3326e782018-04-24 06:23:22 +000065static const opt::OptTable::Info ObjcopyInfoTable[] = {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000066#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
67 HELPTEXT, METAVAR, VALUES) \
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000068 {OBJCOPY_##PREFIX, \
69 NAME, \
70 HELPTEXT, \
71 METAVAR, \
72 OBJCOPY_##ID, \
73 opt::Option::KIND##Class, \
74 PARAM, \
75 FLAGS, \
76 OBJCOPY_##GROUP, \
77 OBJCOPY_##ALIAS, \
78 ALIASARGS, \
79 VALUES},
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000080#include "ObjcopyOpts.inc"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000081#undef OPTION
82};
83
84class ObjcopyOptTable : public opt::OptTable {
85public:
86 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
87};
88
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000089enum StripID {
90 STRIP_INVALID = 0, // This is not an option ID.
91#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
92 HELPTEXT, METAVAR, VALUES) \
93 STRIP_##ID,
94#include "StripOpts.inc"
95#undef OPTION
96};
97
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +000098#define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE;
99#include "StripOpts.inc"
100#undef PREFIX
101
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000102static const opt::OptTable::Info StripInfoTable[] = {
103#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
104 HELPTEXT, METAVAR, VALUES) \
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000105 {STRIP_##PREFIX, NAME, HELPTEXT, \
106 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
107 PARAM, FLAGS, STRIP_##GROUP, \
108 STRIP_##ALIAS, ALIASARGS, VALUES},
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000109#include "StripOpts.inc"
110#undef OPTION
111};
112
113class StripOptTable : public opt::OptTable {
114public:
115 StripOptTable() : OptTable(StripInfoTable, true) {}
116};
117
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000118struct CopyConfig {
119 StringRef OutputFilename;
120 StringRef InputFilename;
121 StringRef OutputFormat;
122 StringRef InputFormat;
123 StringRef BinaryArch;
Alexander Shaposhnikovfedb0162018-02-09 23:33:31 +0000124
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000125 StringRef SplitDWO;
126 StringRef AddGnuDebugLink;
127 std::vector<StringRef> ToRemove;
128 std::vector<StringRef> Keep;
129 std::vector<StringRef> OnlyKeep;
130 std::vector<StringRef> AddSection;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000131 std::vector<StringRef> SymbolsToLocalize;
Paul Semelee5be792018-04-27 19:09:44 +0000132 std::vector<StringRef> SymbolsToGlobalize;
Paul Semel3a8a56b2018-04-27 19:16:27 +0000133 std::vector<StringRef> SymbolsToWeaken;
Paul Semel4246a462018-05-09 21:36:54 +0000134 std::vector<StringRef> SymbolsToRemove;
Paul Semel5d97c822018-05-15 14:09:37 +0000135 std::vector<StringRef> SymbolsToKeep;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000136 StringMap<StringRef> SymbolsToRename;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000137 bool StripAll = false;
138 bool StripAllGNU = false;
139 bool StripDebug = false;
140 bool StripSections = false;
141 bool StripNonAlloc = false;
142 bool StripDWO = false;
Paul Semel99dda0b2018-05-25 11:01:25 +0000143 bool StripUnneeded = false;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000144 bool ExtractDWO = false;
145 bool LocalizeHidden = false;
146 bool Weaken = false;
147 bool DiscardAll = false;
Jake Ehrliche40398a2018-05-15 20:53:53 +0000148 bool OnlyKeepDebug = false;
Paul Semelcf51c802018-05-26 08:10:37 +0000149 bool KeepFileSymbols = false;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000150};
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000151
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000152using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000153
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +0000154} // namespace
155
156namespace llvm {
157namespace objcopy {
158
159// The name this program was invoked as.
160StringRef ToolName;
161
162LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
163 errs() << ToolName << ": " << Message << ".\n";
164 errs().flush();
165 exit(1);
166}
167
168LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
169 assert(EC);
170 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
171 exit(1);
172}
173
174LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
175 assert(E);
176 std::string Buf;
177 raw_string_ostream OS(Buf);
178 logAllUnhandledErrors(std::move(E), OS, "");
179 OS.flush();
180 errs() << ToolName << ": '" << File << "': " << Buf;
181 exit(1);
182}
183
184} // end namespace objcopy
Puyan Lotfic4846a52018-07-16 22:17:05 +0000185} // end namespace llvm
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000186
Puyan Lotfic4846a52018-07-16 22:17:05 +0000187static bool IsDWOSection(const SectionBase &Sec) {
188 return Sec.Name.endswith(".dwo");
189}
190
191static bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000192 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000193 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000194 return false;
195 // Short of keeping the string table we want to keep everything that is a DWO
196 // section and remove everything else.
197 return !IsDWOSection(Sec);
198}
199
Puyan Lotfic4846a52018-07-16 22:17:05 +0000200static std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config,
201 Object &Obj, Buffer &Buf,
202 ElfType OutputElfType) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000203 if (Config.OutputFormat == "binary") {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000204 return llvm::make_unique<BinaryWriter>(Obj, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000205 }
206 // Depending on the initial ELFT and OutputFormat we need a different Writer.
207 switch (OutputElfType) {
208 case ELFT_ELF32LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000209 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000210 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000211 case ELFT_ELF64LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000212 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000213 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000214 case ELFT_ELF32BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000215 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000216 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000217 case ELFT_ELF64BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000218 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000219 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000220 }
221 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000222}
223
Puyan Lotfic4846a52018-07-16 22:17:05 +0000224static void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
225 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000226 auto DWOFile = Reader.create();
227 DWOFile->removeSections(
228 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000229 FileBuffer FB(File);
230 auto Writer = CreateWriter(Config, *DWOFile, FB, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000231 Writer->finalize();
232 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000233}
234
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000235// This function handles the high level operations of GNU objcopy including
236// handling command line options. It's important to outline certain properties
237// we expect to hold of the command line operations. Any operation that "keeps"
238// should keep regardless of a remove. Additionally any removal should respect
239// any previous removals. Lastly whether or not something is removed shouldn't
240// depend a) on the order the options occur in or b) on some opaque priority
241// system. The only priority is that keeps/copies overrule removes.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000242static void HandleArgs(const CopyConfig &Config, Object &Obj,
243 const Reader &Reader, ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000244
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000245 if (!Config.SplitDWO.empty()) {
246 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000247 }
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000248
249 // TODO: update or remove symbols only if there is an option that affects
250 // them.
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000251 if (Obj.SymbolTable) {
252 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
253 if ((Config.LocalizeHidden &&
254 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
255 (!Config.SymbolsToLocalize.empty() &&
256 is_contained(Config.SymbolsToLocalize, Sym.Name)))
257 Sym.Binding = STB_LOCAL;
258
259 if (!Config.SymbolsToGlobalize.empty() &&
260 is_contained(Config.SymbolsToGlobalize, Sym.Name))
261 Sym.Binding = STB_GLOBAL;
262
263 if (!Config.SymbolsToWeaken.empty() &&
264 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
265 Sym.Binding == STB_GLOBAL)
266 Sym.Binding = STB_WEAK;
267
268 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
269 Sym.getShndx() != SHN_UNDEF)
270 Sym.Binding = STB_WEAK;
271
272 const auto I = Config.SymbolsToRename.find(Sym.Name);
273 if (I != Config.SymbolsToRename.end())
274 Sym.Name = I->getValue();
275 });
276
Paul Semel99dda0b2018-05-25 11:01:25 +0000277 // The purpose of this loop is to mark symbols referenced by sections
278 // (like GroupSection or RelocationSection). This way, we know which
279 // symbols are still 'needed' and wich are not.
280 if (Config.StripUnneeded) {
281 for (auto &Section : Obj.sections())
282 Section.markSymbols();
283 }
284
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000285 Obj.removeSymbols([&](const Symbol &Sym) {
Paul Semelcf51c802018-05-26 08:10:37 +0000286 if ((!Config.SymbolsToKeep.empty() &&
287 is_contained(Config.SymbolsToKeep, Sym.Name)) ||
288 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000289 return false;
290
291 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
292 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
293 Sym.Type != STT_SECTION)
294 return true;
295
296 if (Config.StripAll || Config.StripAllGNU)
297 return true;
298
299 if (!Config.SymbolsToRemove.empty() &&
300 is_contained(Config.SymbolsToRemove, Sym.Name)) {
301 return true;
302 }
303
Paul Semel46201fb2018-06-01 16:19:46 +0000304 if (Config.StripUnneeded && !Sym.Referenced &&
Paul Semel99dda0b2018-05-25 11:01:25 +0000305 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
306 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
307 return true;
308
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000309 return false;
310 });
311 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000312
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000313 SectionPred RemovePred = [](const SectionBase &) { return false; };
314
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000315 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000316 if (!Config.ToRemove.empty()) {
317 RemovePred = [&Config](const SectionBase &Sec) {
318 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
319 Sec.Name) != std::end(Config.ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000320 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000321 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000322
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000323 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000324 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000325 return IsDWOSection(Sec) || RemovePred(Sec);
326 };
327
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000328 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000329 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000330 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000331 };
332
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000333 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000334 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
335 if (RemovePred(Sec))
336 return true;
337 if ((Sec.Flags & SHF_ALLOC) != 0)
338 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000339 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000340 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000341 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000342 case SHT_SYMTAB:
343 case SHT_REL:
344 case SHT_RELA:
345 case SHT_STRTAB:
346 return true;
347 }
348 return Sec.Name.startswith(".debug");
349 };
350
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000351 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000352 RemovePred = [RemovePred](const SectionBase &Sec) {
353 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
354 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000355 }
356
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000357 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000358 RemovePred = [RemovePred](const SectionBase &Sec) {
359 return RemovePred(Sec) || Sec.Name.startswith(".debug");
360 };
361 }
362
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000363 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +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 Ehrlichd56725a2017-11-14 18:50:24 +0000368 return false;
369 return (Sec.Flags & SHF_ALLOC) == 0;
370 };
371
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000372 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000373 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
374 if (RemovePred(Sec))
375 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000376 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000377 return false;
378 if (Sec.Name.startswith(".gnu.warning"))
379 return false;
380 return (Sec.Flags & SHF_ALLOC) == 0;
381 };
382
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000383 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000384 if (!Config.OnlyKeep.empty()) {
385 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000386 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000387 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
388 Sec.Name) != std::end(Config.OnlyKeep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000389 return false;
390
391 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000392 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000393 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000394
395 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000396 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000397 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000398 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000399 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000400
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000401 // Remove everything else.
402 return true;
403 };
404 }
405
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000406 if (!Config.Keep.empty()) {
407 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000408 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000409 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
410 std::end(Config.Keep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000411 return false;
412 // Otherwise defer to RemovePred.
413 return RemovePred(Sec);
414 };
415 }
416
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000417 // This has to be the last predicate assignment.
418 // If the option --keep-symbol has been specified
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000419 // and at least one of those symbols is present
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000420 // (equivalently, the updated symbol table is not empty)
421 // the symbol table and the string table should not be removed.
Paul Semelcf51c802018-05-26 08:10:37 +0000422 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
423 !Obj.SymbolTable->empty()) {
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000424 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
425 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
426 return false;
427 return RemovePred(Sec);
428 };
429 }
430
Jake Ehrlich76e91102018-01-25 22:46:17 +0000431 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000432
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000433 if (!Config.AddSection.empty()) {
434 for (const auto &Flag : Config.AddSection) {
435 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000436 auto SecName = SecPair.first;
437 auto File = SecPair.second;
438 auto BufOrErr = MemoryBuffer::getFile(File);
439 if (!BufOrErr)
440 reportError(File, BufOrErr.getError());
441 auto Buf = std::move(*BufOrErr);
442 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
443 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000444 Obj.addSection<OwnedDataSection>(SecName,
445 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000446 }
447 }
448
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000449 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000450 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000451}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000452
Puyan Lotfic4846a52018-07-16 22:17:05 +0000453static void ExecuteElfObjcopyOnBinary(const CopyConfig &Config, Binary &Binary,
454 Buffer &Out) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000455 ELFReader Reader(&Binary);
456 std::unique_ptr<Object> Obj = Reader.create();
457
458 HandleArgs(Config, *Obj, Reader, Reader.getElfType());
459
460 std::unique_ptr<Writer> Writer =
461 CreateWriter(Config, *Obj, Out, Reader.getElfType());
462 Writer->finalize();
463 Writer->write();
464}
465
466// For regular archives this function simply calls llvm::writeArchive,
467// For thin archives it writes the archive file itself as well as its members.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000468static Error deepWriteArchive(StringRef ArcName,
469 ArrayRef<NewArchiveMember> NewMembers,
470 bool WriteSymtab, object::Archive::Kind Kind,
471 bool Deterministic, bool Thin) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000472 Error E =
473 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
474 if (!Thin || E)
475 return E;
476 for (const NewArchiveMember &Member : NewMembers) {
477 // Internally, FileBuffer will use the buffer created by
478 // FileOutputBuffer::create, for regular files (that is the case for
479 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
480 // OnDiskBuffer uses a temporary file and then renames it. So in reality
481 // there is no inefficiency / duplicated in-memory buffers in this case. For
482 // now in-memory buffers can not be completely avoided since
483 // NewArchiveMember still requires them even though writeArchive does not
484 // write them on disk.
485 FileBuffer FB(Member.MemberName);
486 FB.allocate(Member.Buf->getBufferSize());
487 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
488 FB.getBufferStart());
489 if (auto E = FB.commit())
490 return E;
491 }
492 return Error::success();
493}
494
Puyan Lotfic4846a52018-07-16 22:17:05 +0000495static void ExecuteElfObjcopyOnArchive(const CopyConfig &Config, const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000496 std::vector<NewArchiveMember> NewArchiveMembers;
497 Error Err = Error::success();
498 for (const Archive::Child &Child : Ar.children(Err)) {
499 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
500 if (!ChildOrErr)
501 reportError(Ar.getFileName(), ChildOrErr.takeError());
502 Expected<StringRef> ChildNameOrErr = Child.getName();
503 if (!ChildNameOrErr)
504 reportError(Ar.getFileName(), ChildNameOrErr.takeError());
505
506 MemBuffer MB(ChildNameOrErr.get());
507 ExecuteElfObjcopyOnBinary(Config, **ChildOrErr, MB);
508
509 Expected<NewArchiveMember> Member =
510 NewArchiveMember::getOldMember(Child, true);
511 if (!Member)
512 reportError(Ar.getFileName(), Member.takeError());
513 Member->Buf = MB.releaseMemoryBuffer();
514 Member->MemberName = Member->Buf->getBufferIdentifier();
515 NewArchiveMembers.push_back(std::move(*Member));
516 }
517
518 if (Err)
519 reportError(Config.InputFilename, std::move(Err));
520 if (Error E =
521 deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
522 Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin()))
523 reportError(Config.OutputFilename, std::move(E));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000524}
525
Puyan Lotfic4846a52018-07-16 22:17:05 +0000526static void ExecuteElfObjcopy(const CopyConfig &Config) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000527 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
528 createBinary(Config.InputFilename);
529 if (!BinaryOrErr)
530 reportError(Config.InputFilename, BinaryOrErr.takeError());
531
532 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary()))
533 return ExecuteElfObjcopyOnArchive(Config, *Ar);
534
535 FileBuffer FB(Config.OutputFilename);
536 ExecuteElfObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000537}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000538
539// ParseObjcopyOptions returns the config and sets the input arguments. If a
540// help flag is set then ParseObjcopyOptions will print the help messege and
541// exit.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000542static CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000543 ObjcopyOptTable T;
544 unsigned MissingArgumentIndex, MissingArgumentCount;
545 llvm::opt::InputArgList InputArgs =
546 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000547
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000548 if (InputArgs.size() == 0) {
549 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
550 exit(1);
551 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000552
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000553 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000554 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
555 exit(0);
556 }
557
558 SmallVector<const char *, 2> Positional;
559
560 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
561 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
562
563 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
564 Positional.push_back(Arg->getValue());
565
566 if (Positional.empty())
567 error("No input file specified");
568
569 if (Positional.size() > 2)
570 error("Too many positional arguments");
571
572 CopyConfig Config;
573 Config.InputFilename = Positional[0];
574 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
575 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
576 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
577 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
578
579 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
580 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000581
582 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
583 if (!StringRef(Arg->getValue()).contains('='))
584 error("Bad format for --redefine-sym");
585 auto Old2New = StringRef(Arg->getValue()).split('=');
586 if (!Config.SymbolsToRename.insert(Old2New).second)
587 error("Multiple redefinition of symbol " + Old2New.first);
588 }
589
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000590 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
591 Config.ToRemove.push_back(Arg->getValue());
592 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
593 Config.Keep.push_back(Arg->getValue());
594 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
595 Config.OnlyKeep.push_back(Arg->getValue());
596 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
597 Config.AddSection.push_back(Arg->getValue());
598 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
599 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
600 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
601 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
602 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
603 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
Paul Semel99dda0b2018-05-25 11:01:25 +0000604 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000605 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
606 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000607 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000608 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Jake Ehrliche40398a2018-05-15 20:53:53 +0000609 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
Paul Semelcf51c802018-05-26 08:10:37 +0000610 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
Paul Semelb4924942018-04-26 17:44:43 +0000611 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000612 Config.SymbolsToLocalize.push_back(Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000613 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
614 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000615 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
616 Config.SymbolsToWeaken.push_back(Arg->getValue());
Paul Semel4246a462018-05-09 21:36:54 +0000617 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
618 Config.SymbolsToRemove.push_back(Arg->getValue());
Paul Semel5d97c822018-05-15 14:09:37 +0000619 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
620 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000621
622 return Config;
623}
624
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000625// ParseStripOptions returns the config and sets the input arguments. If a
626// help flag is set then ParseStripOptions will print the help messege and
627// exit.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000628static CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000629 StripOptTable T;
630 unsigned MissingArgumentIndex, MissingArgumentCount;
631 llvm::opt::InputArgList InputArgs =
632 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
633
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000634 if (InputArgs.size() == 0) {
635 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
636 exit(1);
637 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000638
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000639 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000640 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
641 exit(0);
642 }
643
644 SmallVector<const char *, 2> Positional;
645 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
646 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
647 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
648 Positional.push_back(Arg->getValue());
649
650 if (Positional.empty())
651 error("No input file specified");
652
653 if (Positional.size() > 2)
654 error("Support for multiple input files is not implemented yet");
655
656 CopyConfig Config;
657 Config.InputFilename = Positional[0];
Alexander Shaposhnikovecc84832018-05-31 20:42:13 +0000658 Config.OutputFilename =
659 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000660
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000661 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000662
Alexander Shaposhnikov29407f32018-06-06 21:23:19 +0000663 Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all);
Paul Semele57bc782018-06-07 10:05:25 +0000664 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
Stephen Hinese8c3c5f2018-07-12 17:42:17 +0000665 Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
Paul Semele57bc782018-06-07 10:05:25 +0000666
667 if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll)
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000668 Config.StripAll = true;
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000669
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000670 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
671 Config.ToRemove.push_back(Arg->getValue());
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000672
Alexander Shaposhnikov35bee3e2018-05-23 19:44:19 +0000673 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
674 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000675
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000676 return Config;
677}
678
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000679int main(int argc, char **argv) {
680 InitLLVM X(argc, argv);
681 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000682 CopyConfig Config;
683 if (sys::path::stem(ToolName).endswith_lower("strip"))
684 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
685 else
686 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000687 ExecuteElfObjcopy(Config);
688}