blob: 4ccc67cc75dbef7980f51eaf613b35f8edbace41 [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;
Jordan Rupprechtdb2036e2018-07-20 19:54:24 +0000136 StringMap<StringRef> SectionsToRename;
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000137 StringMap<StringRef> SymbolsToRename;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000138 bool StripAll = false;
139 bool StripAllGNU = false;
140 bool StripDebug = false;
141 bool StripSections = false;
142 bool StripNonAlloc = false;
143 bool StripDWO = false;
Paul Semel99dda0b2018-05-25 11:01:25 +0000144 bool StripUnneeded = false;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000145 bool ExtractDWO = false;
146 bool LocalizeHidden = false;
147 bool Weaken = false;
148 bool DiscardAll = false;
Jake Ehrliche40398a2018-05-15 20:53:53 +0000149 bool OnlyKeepDebug = false;
Paul Semelcf51c802018-05-26 08:10:37 +0000150 bool KeepFileSymbols = false;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000151};
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000152
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000153using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000154
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +0000155} // namespace
156
157namespace llvm {
158namespace objcopy {
159
160// The name this program was invoked as.
161StringRef ToolName;
162
163LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
164 errs() << ToolName << ": " << Message << ".\n";
165 errs().flush();
166 exit(1);
167}
168
169LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
170 assert(EC);
171 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
172 exit(1);
173}
174
175LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
176 assert(E);
177 std::string Buf;
178 raw_string_ostream OS(Buf);
179 logAllUnhandledErrors(std::move(E), OS, "");
180 OS.flush();
181 errs() << ToolName << ": '" << File << "': " << Buf;
182 exit(1);
183}
184
185} // end namespace objcopy
Puyan Lotfic4846a52018-07-16 22:17:05 +0000186} // end namespace llvm
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000187
Puyan Lotfic4846a52018-07-16 22:17:05 +0000188static bool IsDWOSection(const SectionBase &Sec) {
189 return Sec.Name.endswith(".dwo");
190}
191
192static bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000193 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000194 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000195 return false;
196 // Short of keeping the string table we want to keep everything that is a DWO
197 // section and remove everything else.
198 return !IsDWOSection(Sec);
199}
200
Puyan Lotfic4846a52018-07-16 22:17:05 +0000201static std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config,
202 Object &Obj, Buffer &Buf,
203 ElfType OutputElfType) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000204 if (Config.OutputFormat == "binary") {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000205 return llvm::make_unique<BinaryWriter>(Obj, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000206 }
207 // Depending on the initial ELFT and OutputFormat we need a different Writer.
208 switch (OutputElfType) {
209 case ELFT_ELF32LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000210 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000211 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000212 case ELFT_ELF64LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000213 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000214 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000215 case ELFT_ELF32BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000216 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000217 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000218 case ELFT_ELF64BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000219 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000220 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000221 }
222 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000223}
224
Puyan Lotfic4846a52018-07-16 22:17:05 +0000225static void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
226 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000227 auto DWOFile = Reader.create();
228 DWOFile->removeSections(
229 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000230 FileBuffer FB(File);
231 auto Writer = CreateWriter(Config, *DWOFile, FB, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000232 Writer->finalize();
233 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000234}
235
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000236// This function handles the high level operations of GNU objcopy including
237// handling command line options. It's important to outline certain properties
238// we expect to hold of the command line operations. Any operation that "keeps"
239// should keep regardless of a remove. Additionally any removal should respect
240// any previous removals. Lastly whether or not something is removed shouldn't
241// depend a) on the order the options occur in or b) on some opaque priority
242// system. The only priority is that keeps/copies overrule removes.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000243static void HandleArgs(const CopyConfig &Config, Object &Obj,
244 const Reader &Reader, ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000245
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000246 if (!Config.SplitDWO.empty()) {
247 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000248 }
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000249
250 // TODO: update or remove symbols only if there is an option that affects
251 // them.
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000252 if (Obj.SymbolTable) {
253 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
254 if ((Config.LocalizeHidden &&
255 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
256 (!Config.SymbolsToLocalize.empty() &&
257 is_contained(Config.SymbolsToLocalize, Sym.Name)))
258 Sym.Binding = STB_LOCAL;
259
260 if (!Config.SymbolsToGlobalize.empty() &&
261 is_contained(Config.SymbolsToGlobalize, Sym.Name))
262 Sym.Binding = STB_GLOBAL;
263
264 if (!Config.SymbolsToWeaken.empty() &&
265 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
266 Sym.Binding == STB_GLOBAL)
267 Sym.Binding = STB_WEAK;
268
269 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
270 Sym.getShndx() != SHN_UNDEF)
271 Sym.Binding = STB_WEAK;
272
273 const auto I = Config.SymbolsToRename.find(Sym.Name);
274 if (I != Config.SymbolsToRename.end())
275 Sym.Name = I->getValue();
276 });
277
Paul Semel99dda0b2018-05-25 11:01:25 +0000278 // The purpose of this loop is to mark symbols referenced by sections
279 // (like GroupSection or RelocationSection). This way, we know which
280 // symbols are still 'needed' and wich are not.
281 if (Config.StripUnneeded) {
282 for (auto &Section : Obj.sections())
283 Section.markSymbols();
284 }
285
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000286 Obj.removeSymbols([&](const Symbol &Sym) {
Paul Semelcf51c802018-05-26 08:10:37 +0000287 if ((!Config.SymbolsToKeep.empty() &&
288 is_contained(Config.SymbolsToKeep, Sym.Name)) ||
289 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000290 return false;
291
292 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
293 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
294 Sym.Type != STT_SECTION)
295 return true;
296
297 if (Config.StripAll || Config.StripAllGNU)
298 return true;
299
300 if (!Config.SymbolsToRemove.empty() &&
301 is_contained(Config.SymbolsToRemove, Sym.Name)) {
302 return true;
303 }
304
Paul Semel46201fb2018-06-01 16:19:46 +0000305 if (Config.StripUnneeded && !Sym.Referenced &&
Paul Semel99dda0b2018-05-25 11:01:25 +0000306 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
307 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
308 return true;
309
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000310 return false;
311 });
312 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000313
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000314 SectionPred RemovePred = [](const SectionBase &) { return false; };
315
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000316 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000317 if (!Config.ToRemove.empty()) {
318 RemovePred = [&Config](const SectionBase &Sec) {
319 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
320 Sec.Name) != std::end(Config.ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000321 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000322 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000323
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000324 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000325 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000326 return IsDWOSection(Sec) || RemovePred(Sec);
327 };
328
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000329 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000330 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000331 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000332 };
333
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000334 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000335 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
336 if (RemovePred(Sec))
337 return true;
338 if ((Sec.Flags & SHF_ALLOC) != 0)
339 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000340 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000341 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000342 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000343 case SHT_SYMTAB:
344 case SHT_REL:
345 case SHT_RELA:
346 case SHT_STRTAB:
347 return true;
348 }
349 return Sec.Name.startswith(".debug");
350 };
351
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000352 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000353 RemovePred = [RemovePred](const SectionBase &Sec) {
354 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
355 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000356 }
357
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000358 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000359 RemovePred = [RemovePred](const SectionBase &Sec) {
360 return RemovePred(Sec) || Sec.Name.startswith(".debug");
361 };
362 }
363
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000364 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000365 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
366 if (RemovePred(Sec))
367 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000368 if (&Sec == Obj.SectionNames)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000369 return false;
370 return (Sec.Flags & SHF_ALLOC) == 0;
371 };
372
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000373 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000374 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
375 if (RemovePred(Sec))
376 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000377 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000378 return false;
379 if (Sec.Name.startswith(".gnu.warning"))
380 return false;
381 return (Sec.Flags & SHF_ALLOC) == 0;
382 };
383
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000384 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000385 if (!Config.OnlyKeep.empty()) {
386 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000387 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000388 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
389 Sec.Name) != std::end(Config.OnlyKeep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000390 return false;
391
392 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000393 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000394 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000395
396 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000397 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000398 return false;
Stephen Hinese6e75bf2018-07-26 20:05:31 +0000399 if (Obj.SymbolTable == &Sec ||
400 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000401 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000402
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000403 // Remove everything else.
404 return true;
405 };
406 }
407
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000408 if (!Config.Keep.empty()) {
409 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000410 // Explicitly keep these sections regardless of previous removes.
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000411 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
412 std::end(Config.Keep))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000413 return false;
414 // Otherwise defer to RemovePred.
415 return RemovePred(Sec);
416 };
417 }
418
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000419 // This has to be the last predicate assignment.
420 // If the option --keep-symbol has been specified
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000421 // and at least one of those symbols is present
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000422 // (equivalently, the updated symbol table is not empty)
423 // the symbol table and the string table should not be removed.
Paul Semelcf51c802018-05-26 08:10:37 +0000424 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
Stephen Hinese6e75bf2018-07-26 20:05:31 +0000425 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000426 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
427 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
428 return false;
429 return RemovePred(Sec);
430 };
431 }
432
Jake Ehrlich76e91102018-01-25 22:46:17 +0000433 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000434
Jordan Rupprechtdb2036e2018-07-20 19:54:24 +0000435 if (!Config.SectionsToRename.empty()) {
436 for (auto &Sec : Obj.sections()) {
437 const auto Iter = Config.SectionsToRename.find(Sec.Name);
438 if (Iter != Config.SectionsToRename.end())
439 Sec.Name = Iter->second;
440 }
441 }
442
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000443 if (!Config.AddSection.empty()) {
444 for (const auto &Flag : Config.AddSection) {
445 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000446 auto SecName = SecPair.first;
447 auto File = SecPair.second;
448 auto BufOrErr = MemoryBuffer::getFile(File);
449 if (!BufOrErr)
450 reportError(File, BufOrErr.getError());
451 auto Buf = std::move(*BufOrErr);
452 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
453 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000454 Obj.addSection<OwnedDataSection>(SecName,
455 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000456 }
457 }
458
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000459 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000460 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000461}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000462
Puyan Lotfic4846a52018-07-16 22:17:05 +0000463static void ExecuteElfObjcopyOnBinary(const CopyConfig &Config, Binary &Binary,
464 Buffer &Out) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000465 ELFReader Reader(&Binary);
466 std::unique_ptr<Object> Obj = Reader.create();
467
468 HandleArgs(Config, *Obj, Reader, Reader.getElfType());
469
470 std::unique_ptr<Writer> Writer =
471 CreateWriter(Config, *Obj, Out, Reader.getElfType());
472 Writer->finalize();
473 Writer->write();
474}
475
476// For regular archives this function simply calls llvm::writeArchive,
477// For thin archives it writes the archive file itself as well as its members.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000478static Error deepWriteArchive(StringRef ArcName,
479 ArrayRef<NewArchiveMember> NewMembers,
480 bool WriteSymtab, object::Archive::Kind Kind,
481 bool Deterministic, bool Thin) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000482 Error E =
483 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
484 if (!Thin || E)
485 return E;
486 for (const NewArchiveMember &Member : NewMembers) {
487 // Internally, FileBuffer will use the buffer created by
488 // FileOutputBuffer::create, for regular files (that is the case for
489 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
490 // OnDiskBuffer uses a temporary file and then renames it. So in reality
491 // there is no inefficiency / duplicated in-memory buffers in this case. For
492 // now in-memory buffers can not be completely avoided since
493 // NewArchiveMember still requires them even though writeArchive does not
494 // write them on disk.
495 FileBuffer FB(Member.MemberName);
496 FB.allocate(Member.Buf->getBufferSize());
497 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
498 FB.getBufferStart());
499 if (auto E = FB.commit())
500 return E;
501 }
502 return Error::success();
503}
504
Puyan Lotfic4846a52018-07-16 22:17:05 +0000505static void ExecuteElfObjcopyOnArchive(const CopyConfig &Config, const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000506 std::vector<NewArchiveMember> NewArchiveMembers;
507 Error Err = Error::success();
508 for (const Archive::Child &Child : Ar.children(Err)) {
509 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
510 if (!ChildOrErr)
511 reportError(Ar.getFileName(), ChildOrErr.takeError());
512 Expected<StringRef> ChildNameOrErr = Child.getName();
513 if (!ChildNameOrErr)
514 reportError(Ar.getFileName(), ChildNameOrErr.takeError());
515
516 MemBuffer MB(ChildNameOrErr.get());
517 ExecuteElfObjcopyOnBinary(Config, **ChildOrErr, MB);
518
519 Expected<NewArchiveMember> Member =
520 NewArchiveMember::getOldMember(Child, true);
521 if (!Member)
522 reportError(Ar.getFileName(), Member.takeError());
523 Member->Buf = MB.releaseMemoryBuffer();
524 Member->MemberName = Member->Buf->getBufferIdentifier();
525 NewArchiveMembers.push_back(std::move(*Member));
526 }
527
528 if (Err)
529 reportError(Config.InputFilename, std::move(Err));
530 if (Error E =
531 deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
532 Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin()))
533 reportError(Config.OutputFilename, std::move(E));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000534}
535
Puyan Lotfic4846a52018-07-16 22:17:05 +0000536static void ExecuteElfObjcopy(const CopyConfig &Config) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000537 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
538 createBinary(Config.InputFilename);
539 if (!BinaryOrErr)
540 reportError(Config.InputFilename, BinaryOrErr.takeError());
541
542 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary()))
543 return ExecuteElfObjcopyOnArchive(Config, *Ar);
544
545 FileBuffer FB(Config.OutputFilename);
546 ExecuteElfObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000547}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000548
549// ParseObjcopyOptions returns the config and sets the input arguments. If a
550// help flag is set then ParseObjcopyOptions will print the help messege and
551// exit.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000552static CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000553 ObjcopyOptTable T;
554 unsigned MissingArgumentIndex, MissingArgumentCount;
555 llvm::opt::InputArgList InputArgs =
556 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000557
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000558 if (InputArgs.size() == 0) {
559 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
560 exit(1);
561 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000562
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000563 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000564 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
565 exit(0);
566 }
567
568 SmallVector<const char *, 2> Positional;
569
570 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
571 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
572
573 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
574 Positional.push_back(Arg->getValue());
575
576 if (Positional.empty())
577 error("No input file specified");
578
579 if (Positional.size() > 2)
580 error("Too many positional arguments");
581
582 CopyConfig Config;
583 Config.InputFilename = Positional[0];
584 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
585 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
586 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
587 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
588
589 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
590 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000591
592 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
593 if (!StringRef(Arg->getValue()).contains('='))
594 error("Bad format for --redefine-sym");
595 auto Old2New = StringRef(Arg->getValue()).split('=');
596 if (!Config.SymbolsToRename.insert(Old2New).second)
597 error("Multiple redefinition of symbol " + Old2New.first);
598 }
599
Jordan Rupprechtdb2036e2018-07-20 19:54:24 +0000600 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
601 if (!StringRef(Arg->getValue()).contains('='))
602 error("Bad format for --rename-section");
603 auto Old2New = StringRef(Arg->getValue()).split('=');
604 if (!Config.SectionsToRename.insert(Old2New).second)
605 error("Already have a section rename for " + Old2New.first);
606 }
607
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000608 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
609 Config.ToRemove.push_back(Arg->getValue());
610 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
611 Config.Keep.push_back(Arg->getValue());
612 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
613 Config.OnlyKeep.push_back(Arg->getValue());
614 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
615 Config.AddSection.push_back(Arg->getValue());
616 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
617 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
618 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
619 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
620 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
621 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
Paul Semel99dda0b2018-05-25 11:01:25 +0000622 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000623 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
624 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000625 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000626 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Jake Ehrliche40398a2018-05-15 20:53:53 +0000627 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
Paul Semelcf51c802018-05-26 08:10:37 +0000628 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
Paul Semelb4924942018-04-26 17:44:43 +0000629 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000630 Config.SymbolsToLocalize.push_back(Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000631 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
632 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000633 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
634 Config.SymbolsToWeaken.push_back(Arg->getValue());
Paul Semel4246a462018-05-09 21:36:54 +0000635 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
636 Config.SymbolsToRemove.push_back(Arg->getValue());
Paul Semel5d97c822018-05-15 14:09:37 +0000637 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
638 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000639
640 return Config;
641}
642
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000643// ParseStripOptions returns the config and sets the input arguments. If a
644// help flag is set then ParseStripOptions will print the help messege and
645// exit.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000646static CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000647 StripOptTable T;
648 unsigned MissingArgumentIndex, MissingArgumentCount;
649 llvm::opt::InputArgList InputArgs =
650 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
651
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000652 if (InputArgs.size() == 0) {
653 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
654 exit(1);
655 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000656
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000657 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000658 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
659 exit(0);
660 }
661
662 SmallVector<const char *, 2> Positional;
663 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
664 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
665 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
666 Positional.push_back(Arg->getValue());
667
668 if (Positional.empty())
669 error("No input file specified");
670
671 if (Positional.size() > 2)
672 error("Support for multiple input files is not implemented yet");
673
674 CopyConfig Config;
675 Config.InputFilename = Positional[0];
Alexander Shaposhnikovecc84832018-05-31 20:42:13 +0000676 Config.OutputFilename =
677 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000678
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000679 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000680
Alexander Shaposhnikov29407f32018-06-06 21:23:19 +0000681 Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all);
Paul Semele57bc782018-06-07 10:05:25 +0000682 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
Stephen Hinese8c3c5f2018-07-12 17:42:17 +0000683 Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
Paul Semele57bc782018-06-07 10:05:25 +0000684
685 if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll)
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000686 Config.StripAll = true;
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000687
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000688 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
689 Config.ToRemove.push_back(Arg->getValue());
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000690
Alexander Shaposhnikov35bee3e2018-05-23 19:44:19 +0000691 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
692 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000693
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000694 return Config;
695}
696
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000697int main(int argc, char **argv) {
698 InitLLVM X(argc, argv);
699 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000700 CopyConfig Config;
701 if (sys::path::stem(ToolName).endswith_lower("strip"))
702 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
703 else
704 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000705 ExecuteElfObjcopy(Config);
706}