1 //===- llvm-objcopy.cpp ---------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm-objcopy.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/BinaryFormat/ELF.h"
16 #include "llvm/Object/Binary.h"
17 #include "llvm/Object/ELFObjectFile.h"
18 #include "llvm/Object/ELFTypes.h"
19 #include "llvm/Object/Error.h"
20 #include "llvm/Option/Arg.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/Option/Option.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ErrorOr.h"
29 #include "llvm/Support/FileOutputBuffer.h"
30 #include "llvm/Support/InitLLVM.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/raw_ostream.h"
40 #include <system_error>
44 using namespace object;
50 OBJCOPY_INVALID = 0, // This is not an option ID.
51 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
52 HELPTEXT, METAVAR, VALUES) \
54 #include "ObjcopyOpts.inc"
58 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
59 #include "ObjcopyOpts.inc"
62 static const opt::OptTable::Info ObjcopyInfoTable[] = {
63 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
64 HELPTEXT, METAVAR, VALUES) \
65 {PREFIX, NAME, HELPTEXT, \
66 METAVAR, OBJCOPY_##ID, opt::Option::KIND##Class, \
67 PARAM, FLAGS, OBJCOPY_##GROUP, \
68 OBJCOPY_##ALIAS, ALIASARGS, VALUES},
69 #include "ObjcopyOpts.inc"
73 class ObjcopyOptTable : public opt::OptTable {
75 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
79 STRIP_INVALID = 0, // This is not an option ID.
80 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
81 HELPTEXT, METAVAR, VALUES) \
83 #include "StripOpts.inc"
87 static const opt::OptTable::Info StripInfoTable[] = {
88 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
89 HELPTEXT, METAVAR, VALUES) \
90 {PREFIX, NAME, HELPTEXT, \
91 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \
92 PARAM, FLAGS, STRIP_##GROUP, \
93 STRIP_##ALIAS, ALIASARGS, VALUES},
94 #include "StripOpts.inc"
98 class StripOptTable : public opt::OptTable {
100 StripOptTable() : OptTable(StripInfoTable, true) {}
105 // The name this program was invoked as.
106 static StringRef ToolName;
110 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
111 errs() << ToolName << ": " << Message << ".\n";
116 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
118 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
122 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
125 raw_string_ostream OS(Buf);
126 logAllUnhandledErrors(std::move(E), OS, "");
128 errs() << ToolName << ": '" << File << "': " << Buf;
132 } // end namespace llvm
135 StringRef OutputFilename;
136 StringRef InputFilename;
137 StringRef OutputFormat;
138 StringRef InputFormat;
139 StringRef BinaryArch;
142 StringRef AddGnuDebugLink;
143 std::vector<StringRef> ToRemove;
144 std::vector<StringRef> Keep;
145 std::vector<StringRef> OnlyKeep;
146 std::vector<StringRef> AddSection;
147 std::vector<StringRef> SymbolsToLocalize;
148 std::vector<StringRef> SymbolsToGlobalize;
149 std::vector<StringRef> SymbolsToWeaken;
150 std::vector<StringRef> SymbolsToRemove;
151 std::vector<StringRef> SymbolsToKeep;
152 StringMap<StringRef> SymbolsToRename;
153 bool StripAll = false;
154 bool StripAllGNU = false;
155 bool StripDebug = false;
156 bool StripSections = false;
157 bool StripNonAlloc = false;
158 bool StripDWO = false;
159 bool ExtractDWO = false;
160 bool LocalizeHidden = false;
162 bool DiscardAll = false;
163 bool OnlyKeepDebug = false;
166 using SectionPred = std::function<bool(const SectionBase &Sec)>;
168 bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
170 bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
171 // We can't remove the section header string table.
172 if (&Sec == Obj.SectionNames)
174 // Short of keeping the string table we want to keep everything that is a DWO
175 // section and remove everything else.
176 return !IsDWOSection(Sec);
179 std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj,
180 StringRef File, ElfType OutputElfType) {
181 if (Config.OutputFormat == "binary") {
182 return llvm::make_unique<BinaryWriter>(File, Obj);
184 // Depending on the initial ELFT and OutputFormat we need a different Writer.
185 switch (OutputElfType) {
187 return llvm::make_unique<ELFWriter<ELF32LE>>(File, Obj,
188 !Config.StripSections);
190 return llvm::make_unique<ELFWriter<ELF64LE>>(File, Obj,
191 !Config.StripSections);
193 return llvm::make_unique<ELFWriter<ELF32BE>>(File, Obj,
194 !Config.StripSections);
196 return llvm::make_unique<ELFWriter<ELF64BE>>(File, Obj,
197 !Config.StripSections);
199 llvm_unreachable("Invalid output format");
202 void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
203 StringRef File, ElfType OutputElfType) {
204 auto DWOFile = Reader.create();
205 DWOFile->removeSections(
206 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
207 auto Writer = CreateWriter(Config, *DWOFile, File, OutputElfType);
212 // This function handles the high level operations of GNU objcopy including
213 // handling command line options. It's important to outline certain properties
214 // we expect to hold of the command line operations. Any operation that "keeps"
215 // should keep regardless of a remove. Additionally any removal should respect
216 // any previous removals. Lastly whether or not something is removed shouldn't
217 // depend a) on the order the options occur in or b) on some opaque priority
218 // system. The only priority is that keeps/copies overrule removes.
219 void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader,
220 ElfType OutputElfType) {
222 if (!Config.SplitDWO.empty()) {
223 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
226 SectionPred RemovePred = [](const SectionBase &) { return false; };
229 if (!Config.ToRemove.empty()) {
230 RemovePred = [&Config](const SectionBase &Sec) {
231 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
232 Sec.Name) != std::end(Config.ToRemove);
236 if (Config.StripDWO || !Config.SplitDWO.empty())
237 RemovePred = [RemovePred](const SectionBase &Sec) {
238 return IsDWOSection(Sec) || RemovePred(Sec);
241 if (Config.ExtractDWO)
242 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
243 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
246 if (Config.StripAllGNU)
247 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
250 if ((Sec.Flags & SHF_ALLOC) != 0)
252 if (&Sec == Obj.SectionNames)
261 return Sec.Name.startswith(".debug");
264 if (Config.StripSections) {
265 RemovePred = [RemovePred](const SectionBase &Sec) {
266 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
270 if (Config.StripDebug) {
271 RemovePred = [RemovePred](const SectionBase &Sec) {
272 return RemovePred(Sec) || Sec.Name.startswith(".debug");
276 if (Config.StripNonAlloc)
277 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
280 if (&Sec == Obj.SectionNames)
282 return (Sec.Flags & SHF_ALLOC) == 0;
286 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
289 if (&Sec == Obj.SectionNames)
291 if (Sec.Name.startswith(".gnu.warning"))
293 return (Sec.Flags & SHF_ALLOC) == 0;
297 if (!Config.OnlyKeep.empty()) {
298 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
299 // Explicitly keep these sections regardless of previous removes.
300 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
301 Sec.Name) != std::end(Config.OnlyKeep))
304 // Allow all implicit removes.
308 // Keep special sections.
309 if (Obj.SectionNames == &Sec)
311 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
314 // Remove everything else.
319 if (!Config.Keep.empty()) {
320 RemovePred = [Config, RemovePred](const SectionBase &Sec) {
321 // Explicitly keep these sections regardless of previous removes.
322 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
323 std::end(Config.Keep))
325 // Otherwise defer to RemovePred.
326 return RemovePred(Sec);
330 Obj.removeSections(RemovePred);
332 if (!Config.AddSection.empty()) {
333 for (const auto &Flag : Config.AddSection) {
334 auto SecPair = Flag.split("=");
335 auto SecName = SecPair.first;
336 auto File = SecPair.second;
337 auto BufOrErr = MemoryBuffer::getFile(File);
339 reportError(File, BufOrErr.getError());
340 auto Buf = std::move(*BufOrErr);
341 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
342 auto BufSize = Buf->getBufferSize();
343 Obj.addSection<OwnedDataSection>(SecName,
344 ArrayRef<uint8_t>(BufPtr, BufSize));
348 if (!Config.AddGnuDebugLink.empty())
349 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
351 if (Obj.SymbolTable) {
352 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
353 if ((Config.LocalizeHidden &&
354 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
355 (!Config.SymbolsToLocalize.empty() &&
356 is_contained(Config.SymbolsToLocalize, Sym.Name)))
357 Sym.Binding = STB_LOCAL;
359 if (!Config.SymbolsToGlobalize.empty() &&
360 is_contained(Config.SymbolsToGlobalize, Sym.Name))
361 Sym.Binding = STB_GLOBAL;
363 if (!Config.SymbolsToWeaken.empty() &&
364 is_contained(Config.SymbolsToWeaken, Sym.Name) &&
365 Sym.Binding == STB_GLOBAL)
366 Sym.Binding = STB_WEAK;
368 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
369 Sym.getShndx() != SHN_UNDEF)
370 Sym.Binding = STB_WEAK;
372 const auto I = Config.SymbolsToRename.find(Sym.Name);
373 if (I != Config.SymbolsToRename.end())
374 Sym.Name = I->getValue();
377 Obj.removeSymbols([&](const Symbol &Sym) {
378 if (!Config.SymbolsToKeep.empty() &&
379 is_contained(Config.SymbolsToKeep, Sym.Name))
382 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
383 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
384 Sym.Type != STT_SECTION)
387 if (!Config.SymbolsToRemove.empty() &&
388 is_contained(Config.SymbolsToRemove, Sym.Name)) {
397 std::unique_ptr<Reader> CreateReader(StringRef InputFilename,
398 ElfType &OutputElfType) {
399 // Right now we can only read ELF files so there's only one reader;
400 auto Out = llvm::make_unique<ELFReader>(InputFilename);
401 // We need to set the default ElfType for output.
402 OutputElfType = Out->getElfType();
403 return std::move(Out);
406 void ExecuteElfObjcopy(const CopyConfig &Config) {
407 ElfType OutputElfType;
408 auto Reader = CreateReader(Config.InputFilename, OutputElfType);
409 auto Obj = Reader->create();
411 CreateWriter(Config, *Obj, Config.OutputFilename, OutputElfType);
412 HandleArgs(Config, *Obj, *Reader, OutputElfType);
417 // ParseObjcopyOptions returns the config and sets the input arguments. If a
418 // help flag is set then ParseObjcopyOptions will print the help messege and
420 CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
422 unsigned MissingArgumentIndex, MissingArgumentCount;
423 llvm::opt::InputArgList InputArgs =
424 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
426 if (InputArgs.size() == 0) {
427 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
431 if (InputArgs.hasArg(OBJCOPY_help)) {
432 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
436 SmallVector<const char *, 2> Positional;
438 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
439 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
441 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
442 Positional.push_back(Arg->getValue());
444 if (Positional.empty())
445 error("No input file specified");
447 if (Positional.size() > 2)
448 error("Too many positional arguments");
451 Config.InputFilename = Positional[0];
452 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
453 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
454 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
455 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
457 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
458 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
460 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
461 if (!StringRef(Arg->getValue()).contains('='))
462 error("Bad format for --redefine-sym");
463 auto Old2New = StringRef(Arg->getValue()).split('=');
464 if (!Config.SymbolsToRename.insert(Old2New).second)
465 error("Multiple redefinition of symbol " + Old2New.first);
468 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
469 Config.ToRemove.push_back(Arg->getValue());
470 for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
471 Config.Keep.push_back(Arg->getValue());
472 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
473 Config.OnlyKeep.push_back(Arg->getValue());
474 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
475 Config.AddSection.push_back(Arg->getValue());
476 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
477 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
478 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
479 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
480 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
481 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
482 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
483 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
484 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
485 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all);
486 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug);
487 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
488 Config.SymbolsToLocalize.push_back(Arg->getValue());
489 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
490 Config.SymbolsToGlobalize.push_back(Arg->getValue());
491 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
492 Config.SymbolsToWeaken.push_back(Arg->getValue());
493 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol))
494 Config.SymbolsToRemove.push_back(Arg->getValue());
495 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol))
496 Config.SymbolsToKeep.push_back(Arg->getValue());
501 // ParseStripOptions returns the config and sets the input arguments. If a
502 // help flag is set then ParseStripOptions will print the help messege and
504 CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) {
506 unsigned MissingArgumentIndex, MissingArgumentCount;
507 llvm::opt::InputArgList InputArgs =
508 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
510 if (InputArgs.size() == 0) {
511 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool");
515 if (InputArgs.hasArg(STRIP_help)) {
516 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool");
520 SmallVector<const char *, 2> Positional;
521 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN))
522 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
523 for (auto Arg : InputArgs.filtered(STRIP_INPUT))
524 Positional.push_back(Arg->getValue());
526 if (Positional.empty())
527 error("No input file specified");
529 if (Positional.size() > 2)
530 error("Support for multiple input files is not implemented yet");
533 Config.InputFilename = Positional[0];
534 Config.OutputFilename = Positional[0];
536 // Strip debug info only.
537 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug);
538 if (!Config.StripDebug)
539 Config.StripAll = true;
541 for (auto Arg : InputArgs.filtered(STRIP_remove_section))
542 Config.ToRemove.push_back(Arg->getValue());
547 int main(int argc, char **argv) {
548 InitLLVM X(argc, argv);
551 if (sys::path::stem(ToolName).endswith_lower("strip"))
552 Config = ParseStripOptions(makeArrayRef(argv + 1, argc));
554 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
555 ExecuteElfObjcopy(Config);