blob: b4c579c20d96f169d19cd523db79f54396318ae7 [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
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;
Paul Semelcf51c802018-05-26 08:10:37 +0000177 bool KeepFileSymbols = false;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000178};
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000179
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000180using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000181
Puyan Lotfic4846a52018-07-16 22:17:05 +0000182} // end namespace llvm
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000183
Puyan Lotfic4846a52018-07-16 22:17:05 +0000184static bool IsDWOSection(const SectionBase &Sec) {
185 return Sec.Name.endswith(".dwo");
186}
187
188static bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000189 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000190 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000191 return false;
192 // Short of keeping the string table we want to keep everything that is a DWO
193 // section and remove everything else.
194 return !IsDWOSection(Sec);
195}
196
Puyan Lotfic4846a52018-07-16 22:17:05 +0000197static std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config,
198 Object &Obj, Buffer &Buf,
199 ElfType OutputElfType) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000200 if (Config.OutputFormat == "binary") {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000201 return llvm::make_unique<BinaryWriter>(Obj, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000202 }
203 // Depending on the initial ELFT and OutputFormat we need a different Writer.
204 switch (OutputElfType) {
205 case ELFT_ELF32LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000206 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000207 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000208 case ELFT_ELF64LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000209 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000210 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000211 case ELFT_ELF32BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000212 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000213 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000214 case ELFT_ELF64BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000215 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000216 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000217 }
218 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000219}
220
Puyan Lotfic4846a52018-07-16 22:17:05 +0000221static void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
222 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000223 auto DWOFile = Reader.create();
224 DWOFile->removeSections(
225 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000226 FileBuffer FB(File);
227 auto Writer = CreateWriter(Config, *DWOFile, FB, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000228 Writer->finalize();
229 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000230}
231
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000232// This function handles the high level operations of GNU objcopy including
233// handling command line options. It's important to outline certain properties
234// we expect to hold of the command line operations. Any operation that "keeps"
235// should keep regardless of a remove. Additionally any removal should respect
236// any previous removals. Lastly whether or not something is removed shouldn't
237// depend a) on the order the options occur in or b) on some opaque priority
238// system. The only priority is that keeps/copies overrule removes.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000239static void HandleArgs(const CopyConfig &Config, Object &Obj,
240 const Reader &Reader, ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000241
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000242 if (!Config.SplitDWO.empty()) {
243 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000244 }
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000245
246 // TODO: update or remove symbols only if there is an option that affects
247 // them.
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000248 if (Obj.SymbolTable) {
249 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
250 if ((Config.LocalizeHidden &&
251 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
252 (!Config.SymbolsToLocalize.empty() &&
253 is_contained(Config.SymbolsToLocalize, Sym.Name)))
254 Sym.Binding = STB_LOCAL;
255
256 if (!Config.SymbolsToGlobalize.empty() &&
257 is_contained(Config.SymbolsToGlobalize, Sym.Name))
258 Sym.Binding = STB_GLOBAL;
259
260 if (!Config.SymbolsToWeaken.empty() &&
261 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
262 Sym.Binding == STB_GLOBAL)
263 Sym.Binding = STB_WEAK;
264
265 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
266 Sym.getShndx() != SHN_UNDEF)
267 Sym.Binding = STB_WEAK;
268
269 const auto I = Config.SymbolsToRename.find(Sym.Name);
270 if (I != Config.SymbolsToRename.end())
271 Sym.Name = I->getValue();
272 });
273
Paul Semel99dda0b2018-05-25 11:01:25 +0000274 // The purpose of this loop is to mark symbols referenced by sections
275 // (like GroupSection or RelocationSection). This way, we know which
276 // symbols are still 'needed' and wich are not.
277 if (Config.StripUnneeded) {
278 for (auto &Section : Obj.sections())
279 Section.markSymbols();
280 }
281
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000282 Obj.removeSymbols([&](const Symbol &Sym) {
Paul Semelcf51c802018-05-26 08:10:37 +0000283 if ((!Config.SymbolsToKeep.empty() &&
284 is_contained(Config.SymbolsToKeep, Sym.Name)) ||
285 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000286 return false;
287
288 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
289 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
290 Sym.Type != STT_SECTION)
291 return true;
292
293 if (Config.StripAll || Config.StripAllGNU)
294 return true;
295
296 if (!Config.SymbolsToRemove.empty() &&
297 is_contained(Config.SymbolsToRemove, Sym.Name)) {
298 return true;
299 }
300
Paul Semel46201fb2018-06-01 16:19:46 +0000301 if (Config.StripUnneeded && !Sym.Referenced &&
Paul Semel99dda0b2018-05-25 11:01:25 +0000302 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
303 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
304 return true;
305
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000306 return false;
307 });
308 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000309
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000310 SectionPred RemovePred = [](const SectionBase &) { return false; };
311
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000312 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000313 if (!Config.ToRemove.empty()) {
314 RemovePred = [&Config](const SectionBase &Sec) {
315 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
316 Sec.Name) != std::end(Config.ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000317 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000318 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000319
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000320 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000321 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000322 return IsDWOSection(Sec) || RemovePred(Sec);
323 };
324
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000325 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000326 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000327 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000328 };
329
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000330 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000331 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
332 if (RemovePred(Sec))
333 return true;
334 if ((Sec.Flags & SHF_ALLOC) != 0)
335 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000336 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000337 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000338 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000339 case SHT_SYMTAB:
340 case SHT_REL:
341 case SHT_RELA:
342 case SHT_STRTAB:
343 return true;
344 }
345 return Sec.Name.startswith(".debug");
346 };
347
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000348 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000349 RemovePred = [RemovePred](const SectionBase &Sec) {
350 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
351 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000352 }
353
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000354 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000355 RemovePred = [RemovePred](const SectionBase &Sec) {
356 return RemovePred(Sec) || Sec.Name.startswith(".debug");
357 };
358 }
359
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000360 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000361 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
362 if (RemovePred(Sec))
363 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000364 if (&Sec == Obj.SectionNames)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000365 return false;
366 return (Sec.Flags & SHF_ALLOC) == 0;
367 };
368
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000369 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000370 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
371 if (RemovePred(Sec))
372 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000373 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000374 return false;
375 if (Sec.Name.startswith(".gnu.warning"))
376 return false;
377 return (Sec.Flags & SHF_ALLOC) == 0;
378 };
379
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000380 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000381 if (!Config.OnlyKeep.empty()) {
382 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000383 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000384 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
385 Sec.Name) != std::end(Config.OnlyKeep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000386 return false;
387
388 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000389 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000390 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000391
392 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000393 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000394 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000395 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000396 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000397
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000398 // Remove everything else.
399 return true;
400 };
401 }
402
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000403 if (!Config.Keep.empty()) {
404 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000405 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000406 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
407 std::end(Config.Keep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000408 return false;
409 // Otherwise defer to RemovePred.
410 return RemovePred(Sec);
411 };
412 }
413
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000414 // This has to be the last predicate assignment.
415 // If the option --keep-symbol has been specified
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000416 // and at least one of those symbols is present
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000417 // (equivalently, the updated symbol table is not empty)
418 // the symbol table and the string table should not be removed.
Paul Semelcf51c802018-05-26 08:10:37 +0000419 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
420 !Obj.SymbolTable->empty()) {
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000421 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
422 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
423 return false;
424 return RemovePred(Sec);
425 };
426 }
427
Jake Ehrlich76e91102018-01-25 22:46:17 +0000428 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000429
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000430 if (!Config.AddSection.empty()) {
431 for (const auto &Flag : Config.AddSection) {
432 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000433 auto SecName = SecPair.first;
434 auto File = SecPair.second;
435 auto BufOrErr = MemoryBuffer::getFile(File);
436 if (!BufOrErr)
437 reportError(File, BufOrErr.getError());
438 auto Buf = std::move(*BufOrErr);
439 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
440 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000441 Obj.addSection<OwnedDataSection>(SecName,
442 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000443 }
444 }
445
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000446 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000447 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000448}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000449
Puyan Lotfic4846a52018-07-16 22:17:05 +0000450static void ExecuteElfObjcopyOnBinary(const CopyConfig &Config, Binary &Binary,
451 Buffer &Out) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000452 ELFReader Reader(&Binary);
453 std::unique_ptr<Object> Obj = Reader.create();
454
455 HandleArgs(Config, *Obj, Reader, Reader.getElfType());
456
457 std::unique_ptr<Writer> Writer =
458 CreateWriter(Config, *Obj, Out, Reader.getElfType());
459 Writer->finalize();
460 Writer->write();
461}
462
463// For regular archives this function simply calls llvm::writeArchive,
464// For thin archives it writes the archive file itself as well as its members.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000465static Error deepWriteArchive(StringRef ArcName,
466 ArrayRef<NewArchiveMember> NewMembers,
467 bool WriteSymtab, object::Archive::Kind Kind,
468 bool Deterministic, bool Thin) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000469 Error E =
470 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
471 if (!Thin || E)
472 return E;
473 for (const NewArchiveMember &Member : NewMembers) {
474 // Internally, FileBuffer will use the buffer created by
475 // FileOutputBuffer::create, for regular files (that is the case for
476 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
477 // OnDiskBuffer uses a temporary file and then renames it. So in reality
478 // there is no inefficiency / duplicated in-memory buffers in this case. For
479 // now in-memory buffers can not be completely avoided since
480 // NewArchiveMember still requires them even though writeArchive does not
481 // write them on disk.
482 FileBuffer FB(Member.MemberName);
483 FB.allocate(Member.Buf->getBufferSize());
484 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
485 FB.getBufferStart());
486 if (auto E = FB.commit())
487 return E;
488 }
489 return Error::success();
490}
491
Puyan Lotfic4846a52018-07-16 22:17:05 +0000492static void ExecuteElfObjcopyOnArchive(const CopyConfig &Config, const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000493 std::vector<NewArchiveMember> NewArchiveMembers;
494 Error Err = Error::success();
495 for (const Archive::Child &Child : Ar.children(Err)) {
496 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
497 if (!ChildOrErr)
498 reportError(Ar.getFileName(), ChildOrErr.takeError());
499 Expected<StringRef> ChildNameOrErr = Child.getName();
500 if (!ChildNameOrErr)
501 reportError(Ar.getFileName(), ChildNameOrErr.takeError());
502
503 MemBuffer MB(ChildNameOrErr.get());
504 ExecuteElfObjcopyOnBinary(Config, **ChildOrErr, MB);
505
506 Expected<NewArchiveMember> Member =
507 NewArchiveMember::getOldMember(Child, true);
508 if (!Member)
509 reportError(Ar.getFileName(), Member.takeError());
510 Member->Buf = MB.releaseMemoryBuffer();
511 Member->MemberName = Member->Buf->getBufferIdentifier();
512 NewArchiveMembers.push_back(std::move(*Member));
513 }
514
515 if (Err)
516 reportError(Config.InputFilename, std::move(Err));
517 if (Error E =
518 deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
519 Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin()))
520 reportError(Config.OutputFilename, std::move(E));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000521}
522
Puyan Lotfic4846a52018-07-16 22:17:05 +0000523static void ExecuteElfObjcopy(const CopyConfig &Config) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000524 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
525 createBinary(Config.InputFilename);
526 if (!BinaryOrErr)
527 reportError(Config.InputFilename, BinaryOrErr.takeError());
528
529 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary()))
530 return ExecuteElfObjcopyOnArchive(Config, *Ar);
531
532 FileBuffer FB(Config.OutputFilename);
533 ExecuteElfObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000534}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000535
536// ParseObjcopyOptions returns the config and sets the input arguments. If a
537// help flag is set then ParseObjcopyOptions will print the help messege and
538// exit.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000539static CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000540 ObjcopyOptTable T;
541 unsigned MissingArgumentIndex, MissingArgumentCount;
542 llvm::opt::InputArgList InputArgs =
543 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000544
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000545 if (InputArgs.size() == 0) {
546 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
547 exit(1);
548 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000549
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000550 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000551 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
552 exit(0);
553 }
554
555 SmallVector<const char *, 2> Positional;
556
557 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
558 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
559
560 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
561 Positional.push_back(Arg->getValue());
562
563 if (Positional.empty())
564 error("No input file specified");
565
566 if (Positional.size() > 2)
567 error("Too many positional arguments");
568
569 CopyConfig Config;
570 Config.InputFilename = Positional[0];
571 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
572 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
573 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
574 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
575
576 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
577 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000578
579 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
580 if (!StringRef(Arg->getValue()).contains('='))
581 error("Bad format for --redefine-sym");
582 auto Old2New = StringRef(Arg->getValue()).split('=');
583 if (!Config.SymbolsToRename.insert(Old2New).second)
584 error("Multiple redefinition of symbol " + Old2New.first);
585 }
586
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000587 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
588 Config.ToRemove.push_back(Arg->getValue());
589 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
590 Config.Keep.push_back(Arg->getValue());
591 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
592 Config.OnlyKeep.push_back(Arg->getValue());
593 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
594 Config.AddSection.push_back(Arg->getValue());
595 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
596 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
597 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
598 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
599 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
600 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
Paul Semel99dda0b2018-05-25 11:01:25 +0000601 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000602 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
603 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000604 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000605 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Jake Ehrliche40398a2018-05-15 20:53:53 +0000606 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
Paul Semelcf51c802018-05-26 08:10:37 +0000607 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
Paul Semelb4924942018-04-26 17:44:43 +0000608 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000609 Config.SymbolsToLocalize.push_back(Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000610 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
611 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000612 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
613 Config.SymbolsToWeaken.push_back(Arg->getValue());
Paul Semel4246a462018-05-09 21:36:54 +0000614 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
615 Config.SymbolsToRemove.push_back(Arg->getValue());
Paul Semel5d97c822018-05-15 14:09:37 +0000616 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
617 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000618
619 return Config;
620}
621
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000622// ParseStripOptions returns the config and sets the input arguments. If a
623// help flag is set then ParseStripOptions will print the help messege and
624// exit.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000625static CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000626 StripOptTable T;
627 unsigned MissingArgumentIndex, MissingArgumentCount;
628 llvm::opt::InputArgList InputArgs =
629 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
630
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000631 if (InputArgs.size() == 0) {
632 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
633 exit(1);
634 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000635
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000636 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000637 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
638 exit(0);
639 }
640
641 SmallVector<const char *, 2> Positional;
642 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
643 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
644 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
645 Positional.push_back(Arg->getValue());
646
647 if (Positional.empty())
648 error("No input file specified");
649
650 if (Positional.size() > 2)
651 error("Support for multiple input files is not implemented yet");
652
653 CopyConfig Config;
654 Config.InputFilename = Positional[0];
Alexander Shaposhnikovecc84832018-05-31 20:42:13 +0000655 Config.OutputFilename =
656 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000657
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000658 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000659
Alexander Shaposhnikov29407f32018-06-06 21:23:19 +0000660 Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all);
Paul Semele57bc782018-06-07 10:05:25 +0000661 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
Stephen Hinese8c3c5f2018-07-12 17:42:17 +0000662 Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
Paul Semele57bc782018-06-07 10:05:25 +0000663
664 if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll)
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000665 Config.StripAll = true;
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000666
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000667 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
668 Config.ToRemove.push_back(Arg->getValue());
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000669
Alexander Shaposhnikov35bee3e2018-05-23 19:44:19 +0000670 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
671 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000672
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000673 return Config;
674}
675
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000676int main(int argc, char **argv) {
677 InitLLVM X(argc, argv);
678 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000679 CopyConfig Config;
680 if (sys::path::stem(ToolName).endswith_lower("strip"))
681 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
682 else
683 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000684 ExecuteElfObjcopy(Config);
685}