blob: 21a1622db7652659eb44837760ba903561d9b314 [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
Fangrui Songfdfe2a92018-07-27 22:51:36 +0000188static bool IsDebugSection(const SectionBase &Sec) {
Fangrui Song87b4b8f2018-07-31 21:26:35 +0000189 return Sec.Name.startswith(".debug") || Sec.Name.startswith(".zdebug") ||
190 Sec.Name == ".gdb_index";
Fangrui Songfdfe2a92018-07-27 22:51:36 +0000191}
192
Puyan Lotfic4846a52018-07-16 22:17:05 +0000193static bool IsDWOSection(const SectionBase &Sec) {
194 return Sec.Name.endswith(".dwo");
195}
196
197static bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000198 // We can't remove the section header string table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000199 if (&Sec == Obj.SectionNames)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000200 return false;
201 // Short of keeping the string table we want to keep everything that is a DWO
202 // section and remove everything else.
203 return !IsDWOSection(Sec);
204}
205
Puyan Lotfic4846a52018-07-16 22:17:05 +0000206static std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config,
207 Object &Obj, Buffer &Buf,
208 ElfType OutputElfType) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000209 if (Config.OutputFormat == "binary") {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000210 return llvm::make_unique<BinaryWriter>(Obj, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000211 }
212 // Depending on the initial ELFT and OutputFormat we need a different Writer.
213 switch (OutputElfType) {
214 case ELFT_ELF32LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000215 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000216 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000217 case ELFT_ELF64LE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000218 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000219 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000220 case ELFT_ELF32BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000221 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000222 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000223 case ELFT_ELF64BE:
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000224 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000225 !Config.StripSections);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000226 }
227 llvm_unreachable("Invalid output format");
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000228}
229
Puyan Lotfic4846a52018-07-16 22:17:05 +0000230static void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
231 StringRef File, ElfType OutputElfType) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000232 auto DWOFile = Reader.create();
233 DWOFile->removeSections(
234 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000235 FileBuffer FB(File);
236 auto Writer = CreateWriter(Config, *DWOFile, FB, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000237 Writer->finalize();
238 Writer->write();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000239}
240
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000241// This function handles the high level operations of GNU objcopy including
242// handling command line options. It's important to outline certain properties
243// we expect to hold of the command line operations. Any operation that "keeps"
244// should keep regardless of a remove. Additionally any removal should respect
245// any previous removals. Lastly whether or not something is removed shouldn't
246// depend a) on the order the options occur in or b) on some opaque priority
247// system. The only priority is that keeps/copies overrule removes.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000248static void HandleArgs(const CopyConfig &Config, Object &Obj,
249 const Reader &Reader, ElfType OutputElfType) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000250
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000251 if (!Config.SplitDWO.empty()) {
252 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000253 }
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000254
255 // TODO: update or remove symbols only if there is an option that affects
256 // them.
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000257 if (Obj.SymbolTable) {
258 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
259 if ((Config.LocalizeHidden &&
260 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
261 (!Config.SymbolsToLocalize.empty() &&
262 is_contained(Config.SymbolsToLocalize, Sym.Name)))
263 Sym.Binding = STB_LOCAL;
264
265 if (!Config.SymbolsToGlobalize.empty() &&
266 is_contained(Config.SymbolsToGlobalize, Sym.Name))
267 Sym.Binding = STB_GLOBAL;
268
269 if (!Config.SymbolsToWeaken.empty() &&
270 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
271 Sym.Binding == STB_GLOBAL)
272 Sym.Binding = STB_WEAK;
273
274 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
275 Sym.getShndx() != SHN_UNDEF)
276 Sym.Binding = STB_WEAK;
277
278 const auto I = Config.SymbolsToRename.find(Sym.Name);
279 if (I != Config.SymbolsToRename.end())
280 Sym.Name = I->getValue();
281 });
282
Paul Semel99dda0b2018-05-25 11:01:25 +0000283 // The purpose of this loop is to mark symbols referenced by sections
284 // (like GroupSection or RelocationSection). This way, we know which
285 // symbols are still 'needed' and wich are not.
286 if (Config.StripUnneeded) {
287 for (auto &Section : Obj.sections())
288 Section.markSymbols();
289 }
290
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000291 Obj.removeSymbols([&](const Symbol &Sym) {
Paul Semelcf51c802018-05-26 08:10:37 +0000292 if ((!Config.SymbolsToKeep.empty() &&
293 is_contained(Config.SymbolsToKeep, Sym.Name)) ||
294 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000295 return false;
296
297 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
298 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
299 Sym.Type != STT_SECTION)
300 return true;
301
302 if (Config.StripAll || Config.StripAllGNU)
303 return true;
304
305 if (!Config.SymbolsToRemove.empty() &&
306 is_contained(Config.SymbolsToRemove, Sym.Name)) {
307 return true;
308 }
309
Paul Semel46201fb2018-06-01 16:19:46 +0000310 if (Config.StripUnneeded && !Sym.Referenced &&
Paul Semel99dda0b2018-05-25 11:01:25 +0000311 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
312 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
313 return true;
314
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000315 return false;
316 });
317 }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000318
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000319 SectionPred RemovePred = [](const SectionBase &) { return false; };
320
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000321 // Removes:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000322 if (!Config.ToRemove.empty()) {
323 RemovePred = [&Config](const SectionBase &Sec) {
Fangrui Songfdfe2a92018-07-27 22:51:36 +0000324 return find(Config.ToRemove, Sec.Name) != Config.ToRemove.end();
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000325 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000326 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000327
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000328 if (Config.StripDWO || !Config.SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000329 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000330 return IsDWOSection(Sec) || RemovePred(Sec);
331 };
332
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000333 if (Config.ExtractDWO)
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000334 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000335 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000336 };
337
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000338 if (Config.StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000339 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
340 if (RemovePred(Sec))
341 return true;
342 if ((Sec.Flags & SHF_ALLOC) != 0)
343 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000344 if (&Sec == Obj.SectionNames)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000345 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000346 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000347 case SHT_SYMTAB:
348 case SHT_REL:
349 case SHT_RELA:
350 case SHT_STRTAB:
351 return true;
352 }
Fangrui Songfdfe2a92018-07-27 22:51:36 +0000353 return IsDebugSection(Sec);
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000354 };
355
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000356 if (Config.StripSections) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000357 RemovePred = [RemovePred](const SectionBase &Sec) {
358 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
359 };
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000360 }
361
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000362 if (Config.StripDebug) {
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000363 RemovePred = [RemovePred](const SectionBase &Sec) {
Fangrui Songfdfe2a92018-07-27 22:51:36 +0000364 return RemovePred(Sec) || IsDebugSection(Sec);
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000365 };
366 }
367
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000368 if (Config.StripNonAlloc)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000369 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
370 if (RemovePred(Sec))
371 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000372 if (&Sec == Obj.SectionNames)
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000373 return false;
374 return (Sec.Flags & SHF_ALLOC) == 0;
375 };
376
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000377 if (Config.StripAll)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000378 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
379 if (RemovePred(Sec))
380 return true;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000381 if (&Sec == Obj.SectionNames)
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000382 return false;
383 if (Sec.Name.startswith(".gnu.warning"))
384 return false;
385 return (Sec.Flags & SHF_ALLOC) == 0;
386 };
387
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000388 // Explicit copies:
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000389 if (!Config.OnlyKeep.empty()) {
390 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000391 // Explicitly keep these sections regardless of previous removes.
Fangrui Songfdfe2a92018-07-27 22:51:36 +0000392 if (find(Config.OnlyKeep, Sec.Name) != Config.OnlyKeep.end())
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000393 return false;
394
395 // Allow all implicit removes.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000396 if (RemovePred(Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000397 return true;
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000398
399 // Keep special sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000400 if (Obj.SectionNames == &Sec)
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000401 return false;
Stephen Hinese6e75bf2018-07-26 20:05:31 +0000402 if (Obj.SymbolTable == &Sec ||
403 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000404 return false;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000405
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000406 // Remove everything else.
407 return true;
408 };
409 }
410
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000411 if (!Config.Keep.empty()) {
412 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000413 // Explicitly keep these sections regardless of previous removes.
Fangrui Songfdfe2a92018-07-27 22:51:36 +0000414 if (find(Config.Keep, Sec.Name) != Config.Keep.end())
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000415 return false;
416 // Otherwise defer to RemovePred.
417 return RemovePred(Sec);
418 };
419 }
420
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000421 // This has to be the last predicate assignment.
422 // If the option --keep-symbol has been specified
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000423 // and at least one of those symbols is present
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000424 // (equivalently, the updated symbol table is not empty)
425 // the symbol table and the string table should not be removed.
Paul Semelcf51c802018-05-26 08:10:37 +0000426 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
Stephen Hinese6e75bf2018-07-26 20:05:31 +0000427 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
Alexander Shaposhnikov6e7814c2018-05-22 18:24:07 +0000428 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
429 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
430 return false;
431 return RemovePred(Sec);
432 };
433 }
434
Jake Ehrlich76e91102018-01-25 22:46:17 +0000435 Obj.removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000436
Jordan Rupprechtdb2036e2018-07-20 19:54:24 +0000437 if (!Config.SectionsToRename.empty()) {
438 for (auto &Sec : Obj.sections()) {
439 const auto Iter = Config.SectionsToRename.find(Sec.Name);
440 if (Iter != Config.SectionsToRename.end())
441 Sec.Name = Iter->second;
442 }
443 }
444
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000445 if (!Config.AddSection.empty()) {
446 for (const auto &Flag : Config.AddSection) {
447 auto SecPair = Flag.split("=");
Jake Ehrliche8437de2017-12-19 00:47:30 +0000448 auto SecName = SecPair.first;
449 auto File = SecPair.second;
450 auto BufOrErr = MemoryBuffer::getFile(File);
451 if (!BufOrErr)
452 reportError(File, BufOrErr.getError());
453 auto Buf = std::move(*BufOrErr);
454 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
455 auto BufSize = Buf->getBufferSize();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000456 Obj.addSection<OwnedDataSection>(SecName,
457 ArrayRef<uint8_t>(BufPtr, BufSize));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000458 }
459 }
460
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000461 if (!Config.AddGnuDebugLink.empty())
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000462 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000463}
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000464
Puyan Lotfic4846a52018-07-16 22:17:05 +0000465static void ExecuteElfObjcopyOnBinary(const CopyConfig &Config, Binary &Binary,
466 Buffer &Out) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000467 ELFReader Reader(&Binary);
468 std::unique_ptr<Object> Obj = Reader.create();
469
470 HandleArgs(Config, *Obj, Reader, Reader.getElfType());
471
472 std::unique_ptr<Writer> Writer =
473 CreateWriter(Config, *Obj, Out, Reader.getElfType());
474 Writer->finalize();
475 Writer->write();
476}
477
478// For regular archives this function simply calls llvm::writeArchive,
479// For thin archives it writes the archive file itself as well as its members.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000480static Error deepWriteArchive(StringRef ArcName,
481 ArrayRef<NewArchiveMember> NewMembers,
482 bool WriteSymtab, object::Archive::Kind Kind,
483 bool Deterministic, bool Thin) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000484 Error E =
485 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
486 if (!Thin || E)
487 return E;
488 for (const NewArchiveMember &Member : NewMembers) {
489 // Internally, FileBuffer will use the buffer created by
490 // FileOutputBuffer::create, for regular files (that is the case for
491 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
492 // OnDiskBuffer uses a temporary file and then renames it. So in reality
493 // there is no inefficiency / duplicated in-memory buffers in this case. For
494 // now in-memory buffers can not be completely avoided since
495 // NewArchiveMember still requires them even though writeArchive does not
496 // write them on disk.
497 FileBuffer FB(Member.MemberName);
498 FB.allocate(Member.Buf->getBufferSize());
499 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
500 FB.getBufferStart());
501 if (auto E = FB.commit())
502 return E;
503 }
504 return Error::success();
505}
506
Puyan Lotfic4846a52018-07-16 22:17:05 +0000507static void ExecuteElfObjcopyOnArchive(const CopyConfig &Config, const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000508 std::vector<NewArchiveMember> NewArchiveMembers;
509 Error Err = Error::success();
510 for (const Archive::Child &Child : Ar.children(Err)) {
511 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
512 if (!ChildOrErr)
513 reportError(Ar.getFileName(), ChildOrErr.takeError());
514 Expected<StringRef> ChildNameOrErr = Child.getName();
515 if (!ChildNameOrErr)
516 reportError(Ar.getFileName(), ChildNameOrErr.takeError());
517
518 MemBuffer MB(ChildNameOrErr.get());
519 ExecuteElfObjcopyOnBinary(Config, **ChildOrErr, MB);
520
521 Expected<NewArchiveMember> Member =
522 NewArchiveMember::getOldMember(Child, true);
523 if (!Member)
524 reportError(Ar.getFileName(), Member.takeError());
525 Member->Buf = MB.releaseMemoryBuffer();
526 Member->MemberName = Member->Buf->getBufferIdentifier();
527 NewArchiveMembers.push_back(std::move(*Member));
528 }
529
530 if (Err)
531 reportError(Config.InputFilename, std::move(Err));
532 if (Error E =
533 deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
534 Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin()))
535 reportError(Config.OutputFilename, std::move(E));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000536}
537
Puyan Lotfic4846a52018-07-16 22:17:05 +0000538static void ExecuteElfObjcopy(const CopyConfig &Config) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000539 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
540 createBinary(Config.InputFilename);
541 if (!BinaryOrErr)
542 reportError(Config.InputFilename, BinaryOrErr.takeError());
543
544 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary()))
545 return ExecuteElfObjcopyOnArchive(Config, *Ar);
546
547 FileBuffer FB(Config.OutputFilename);
548 ExecuteElfObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000549}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000550
551// ParseObjcopyOptions returns the config and sets the input arguments. If a
552// help flag is set then ParseObjcopyOptions will print the help messege and
553// exit.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000554static CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000555 ObjcopyOptTable T;
556 unsigned MissingArgumentIndex, MissingArgumentCount;
557 llvm::opt::InputArgList InputArgs =
558 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000559
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000560 if (InputArgs.size() == 0) {
561 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
562 exit(1);
563 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000564
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000565 if (InputArgs.hasArg(OBJCOPY_help)) {
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000566 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
567 exit(0);
568 }
569
570 SmallVector<const char *, 2> Positional;
571
572 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
573 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
574
575 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
576 Positional.push_back(Arg->getValue());
577
578 if (Positional.empty())
579 error("No input file specified");
580
581 if (Positional.size() > 2)
582 error("Too many positional arguments");
583
584 CopyConfig Config;
585 Config.InputFilename = Positional[0];
586 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
587 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
588 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
589 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
590
591 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
592 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000593
594 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
595 if (!StringRef(Arg->getValue()).contains('='))
596 error("Bad format for --redefine-sym");
597 auto Old2New = StringRef(Arg->getValue()).split('=');
598 if (!Config.SymbolsToRename.insert(Old2New).second)
599 error("Multiple redefinition of symbol " + Old2New.first);
600 }
601
Jordan Rupprechtdb2036e2018-07-20 19:54:24 +0000602 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) {
603 if (!StringRef(Arg->getValue()).contains('='))
604 error("Bad format for --rename-section");
605 auto Old2New = StringRef(Arg->getValue()).split('=');
606 if (!Config.SectionsToRename.insert(Old2New).second)
607 error("Already have a section rename for " + Old2New.first);
608 }
609
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000610 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
611 Config.ToRemove.push_back(Arg->getValue());
612 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
613 Config.Keep.push_back(Arg->getValue());
614 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
615 Config.OnlyKeep.push_back(Arg->getValue());
616 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
617 Config.AddSection.push_back(Arg->getValue());
618 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
619 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
620 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
621 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
622 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
623 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
Paul Semel99dda0b2018-05-25 11:01:25 +0000624 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000625 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
626 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
Paul Semel2c0510f2018-05-02 20:14:49 +0000627 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
Paul Semel41695f82018-05-02 20:19:22 +0000628 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
Jake Ehrliche40398a2018-05-15 20:53:53 +0000629 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
Paul Semelcf51c802018-05-26 08:10:37 +0000630 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols);
Paul Semelb4924942018-04-26 17:44:43 +0000631 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000632 Config.SymbolsToLocalize.push_back(Arg->getValue());
Paul Semelee5be792018-04-27 19:09:44 +0000633 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
634 Config.SymbolsToGlobalize.push_back(Arg->getValue());
Paul Semel3a8a56b2018-04-27 19:16:27 +0000635 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
636 Config.SymbolsToWeaken.push_back(Arg->getValue());
Paul Semel4246a462018-05-09 21:36:54 +0000637 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
638 Config.SymbolsToRemove.push_back(Arg->getValue());
Paul Semel5d97c822018-05-15 14:09:37 +0000639 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
640 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000641
642 return Config;
643}
644
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000645// ParseStripOptions returns the config and sets the input arguments. If a
646// help flag is set then ParseStripOptions will print the help messege and
647// exit.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000648static CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000649 StripOptTable T;
650 unsigned MissingArgumentIndex, MissingArgumentCount;
651 llvm::opt::InputArgList InputArgs =
652 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
653
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000654 if (InputArgs.size() == 0) {
655 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
656 exit(1);
657 }
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000658
Alexander Shaposhnikovb07c22b2018-05-08 17:12:54 +0000659 if (InputArgs.hasArg(STRIP_help)) {
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000660 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
661 exit(0);
662 }
663
664 SmallVector<const char *, 2> Positional;
665 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
666 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
667 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
668 Positional.push_back(Arg->getValue());
669
670 if (Positional.empty())
671 error("No input file specified");
672
673 if (Positional.size() > 2)
674 error("Support for multiple input files is not implemented yet");
675
676 CopyConfig Config;
677 Config.InputFilename = Positional[0];
Alexander Shaposhnikovecc84832018-05-31 20:42:13 +0000678 Config.OutputFilename =
679 InputArgs.getLastArgValue(STRIP_output, Positional[0]);
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000680
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000681 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000682
Alexander Shaposhnikov29407f32018-06-06 21:23:19 +0000683 Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all);
Paul Semele57bc782018-06-07 10:05:25 +0000684 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded);
Stephen Hinese8c3c5f2018-07-12 17:42:17 +0000685 Config.StripAll = InputArgs.hasArg(STRIP_strip_all);
Paul Semele57bc782018-06-07 10:05:25 +0000686
687 if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll)
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000688 Config.StripAll = true;
Alexander Shaposhnikovd29bf4c2018-05-18 04:18:41 +0000689
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000690 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
691 Config.ToRemove.push_back(Arg->getValue());
Alexander Shaposhnikovc7277e62018-05-23 20:39:52 +0000692
Alexander Shaposhnikov35bee3e2018-05-23 19:44:19 +0000693 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol))
694 Config.SymbolsToKeep.push_back(Arg->getValue());
Alexander Shaposhnikov18b5fb72018-05-11 05:27:06 +0000695
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000696 return Config;
697}
698
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000699int main(int argc, char **argv) {
700 InitLLVM X(argc, argv);
701 ToolName = argv[0];
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000702 CopyConfig Config;
703 if (sys::path::stem(ToolName).endswith_lower("strip"))
704 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
705 else
706 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000707 ExecuteElfObjcopy(Config);
708}