xref: /llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.cpp (revision 2c0510f04047a99bd8d57f8b4f24123a320dd45a)
1 //===- llvm-objcopy.cpp ---------------------------------------------------===//
2 //
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 //===----------------------------------------------------------------------===//
9 
10 #include "llvm-objcopy.h"
11 #include "Object.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/raw_ostream.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstdlib>
35 #include <functional>
36 #include <iterator>
37 #include <memory>
38 #include <string>
39 #include <system_error>
40 #include <utility>
41 
42 using namespace llvm;
43 using namespace object;
44 using namespace ELF;
45 
46 namespace {
47 
48 enum ID {
49   OBJCOPY_INVALID = 0, // This is not an option ID.
50 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
51                HELPTEXT, METAVAR, VALUES)                                      \
52   OBJCOPY_##ID,
53 #include "Opts.inc"
54 #undef OPTION
55 };
56 
57 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
58 #include "Opts.inc"
59 #undef PREFIX
60 
61 static const opt::OptTable::Info ObjcopyInfoTable[] = {
62 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
63                HELPTEXT, METAVAR, VALUES)                                      \
64   {PREFIX,          NAME,         HELPTEXT,                                    \
65    METAVAR,         OBJCOPY_##ID, opt::Option::KIND##Class,                    \
66    PARAM,           FLAGS,        OBJCOPY_##GROUP,                             \
67    OBJCOPY_##ALIAS, ALIASARGS,    VALUES},
68 #include "Opts.inc"
69 #undef OPTION
70 };
71 
72 class ObjcopyOptTable : public opt::OptTable {
73 public:
74   ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
75 };
76 
77 } // namespace
78 
79 // The name this program was invoked as.
80 static StringRef ToolName;
81 
82 namespace llvm {
83 
84 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
85   errs() << ToolName << ": " << Message << ".\n";
86   errs().flush();
87   exit(1);
88 }
89 
90 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
91   assert(EC);
92   errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
93   exit(1);
94 }
95 
96 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
97   assert(E);
98   std::string Buf;
99   raw_string_ostream OS(Buf);
100   logAllUnhandledErrors(std::move(E), OS, "");
101   OS.flush();
102   errs() << ToolName << ": '" << File << "': " << Buf;
103   exit(1);
104 }
105 
106 } // end namespace llvm
107 
108 struct CopyConfig {
109   StringRef OutputFilename;
110   StringRef InputFilename;
111   StringRef OutputFormat;
112   StringRef InputFormat;
113   StringRef BinaryArch;
114 
115   StringRef SplitDWO;
116   StringRef AddGnuDebugLink;
117   std::vector<StringRef> ToRemove;
118   std::vector<StringRef> Keep;
119   std::vector<StringRef> OnlyKeep;
120   std::vector<StringRef> AddSection;
121   std::vector<StringRef> SymbolsToLocalize;
122   std::vector<StringRef> SymbolsToGlobalize;
123   std::vector<StringRef> SymbolsToWeaken;
124   StringMap<StringRef> SymbolsToRename;
125   bool StripAll;
126   bool StripAllGNU;
127   bool StripDebug;
128   bool StripSections;
129   bool StripNonAlloc;
130   bool StripDWO;
131   bool ExtractDWO;
132   bool LocalizeHidden;
133   bool Weaken;
134 };
135 
136 using SectionPred = std::function<bool(const SectionBase &Sec)>;
137 
138 bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
139 
140 bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
141   // We can't remove the section header string table.
142   if (&Sec == Obj.SectionNames)
143     return false;
144   // Short of keeping the string table we want to keep everything that is a DWO
145   // section and remove everything else.
146   return !IsDWOSection(Sec);
147 }
148 
149 std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj,
150                                      StringRef File, ElfType OutputElfType) {
151   if (Config.OutputFormat == "binary") {
152     return llvm::make_unique<BinaryWriter>(File, Obj);
153   }
154   // Depending on the initial ELFT and OutputFormat we need a different Writer.
155   switch (OutputElfType) {
156   case ELFT_ELF32LE:
157     return llvm::make_unique<ELFWriter<ELF32LE>>(File, Obj,
158                                                  !Config.StripSections);
159   case ELFT_ELF64LE:
160     return llvm::make_unique<ELFWriter<ELF64LE>>(File, Obj,
161                                                  !Config.StripSections);
162   case ELFT_ELF32BE:
163     return llvm::make_unique<ELFWriter<ELF32BE>>(File, Obj,
164                                                  !Config.StripSections);
165   case ELFT_ELF64BE:
166     return llvm::make_unique<ELFWriter<ELF64BE>>(File, Obj,
167                                                  !Config.StripSections);
168   }
169   llvm_unreachable("Invalid output format");
170 }
171 
172 void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
173                     StringRef File, ElfType OutputElfType) {
174   auto DWOFile = Reader.create();
175   DWOFile->removeSections(
176       [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
177   auto Writer = CreateWriter(Config, *DWOFile, File, OutputElfType);
178   Writer->finalize();
179   Writer->write();
180 }
181 
182 // This function handles the high level operations of GNU objcopy including
183 // handling command line options. It's important to outline certain properties
184 // we expect to hold of the command line operations. Any operation that "keeps"
185 // should keep regardless of a remove. Additionally any removal should respect
186 // any previous removals. Lastly whether or not something is removed shouldn't
187 // depend a) on the order the options occur in or b) on some opaque priority
188 // system. The only priority is that keeps/copies overrule removes.
189 void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader,
190                 ElfType OutputElfType) {
191 
192   if (!Config.SplitDWO.empty()) {
193     SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
194   }
195 
196   SectionPred RemovePred = [](const SectionBase &) { return false; };
197 
198   // Removes:
199   if (!Config.ToRemove.empty()) {
200     RemovePred = [&Config](const SectionBase &Sec) {
201       return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
202                        Sec.Name) != std::end(Config.ToRemove);
203     };
204   }
205 
206   if (Config.StripDWO || !Config.SplitDWO.empty())
207     RemovePred = [RemovePred](const SectionBase &Sec) {
208       return IsDWOSection(Sec) || RemovePred(Sec);
209     };
210 
211   if (Config.ExtractDWO)
212     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
213       return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
214     };
215 
216   if (Config.StripAllGNU)
217     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
218       if (RemovePred(Sec))
219         return true;
220       if ((Sec.Flags & SHF_ALLOC) != 0)
221         return false;
222       if (&Sec == Obj.SectionNames)
223         return false;
224       switch (Sec.Type) {
225       case SHT_SYMTAB:
226       case SHT_REL:
227       case SHT_RELA:
228       case SHT_STRTAB:
229         return true;
230       }
231       return Sec.Name.startswith(".debug");
232     };
233 
234   if (Config.StripSections) {
235     RemovePred = [RemovePred](const SectionBase &Sec) {
236       return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
237     };
238   }
239 
240   if (Config.StripDebug) {
241     RemovePred = [RemovePred](const SectionBase &Sec) {
242       return RemovePred(Sec) || Sec.Name.startswith(".debug");
243     };
244   }
245 
246   if (Config.StripNonAlloc)
247     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
248       if (RemovePred(Sec))
249         return true;
250       if (&Sec == Obj.SectionNames)
251         return false;
252       return (Sec.Flags & SHF_ALLOC) == 0;
253     };
254 
255   if (Config.StripAll)
256     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
257       if (RemovePred(Sec))
258         return true;
259       if (&Sec == Obj.SectionNames)
260         return false;
261       if (Sec.Name.startswith(".gnu.warning"))
262         return false;
263       return (Sec.Flags & SHF_ALLOC) == 0;
264     };
265 
266   // Explicit copies:
267   if (!Config.OnlyKeep.empty()) {
268     RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
269       // Explicitly keep these sections regardless of previous removes.
270       if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
271                     Sec.Name) != std::end(Config.OnlyKeep))
272         return false;
273 
274       // Allow all implicit removes.
275       if (RemovePred(Sec))
276         return true;
277 
278       // Keep special sections.
279       if (Obj.SectionNames == &Sec)
280         return false;
281       if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
282         return false;
283 
284       // Remove everything else.
285       return true;
286     };
287   }
288 
289   if (!Config.Keep.empty()) {
290     RemovePred = [Config, RemovePred](const SectionBase &Sec) {
291       // Explicitly keep these sections regardless of previous removes.
292       if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
293           std::end(Config.Keep))
294         return false;
295       // Otherwise defer to RemovePred.
296       return RemovePred(Sec);
297     };
298   }
299 
300   Obj.removeSections(RemovePred);
301 
302   if (!Config.AddSection.empty()) {
303     for (const auto &Flag : Config.AddSection) {
304       auto SecPair = Flag.split("=");
305       auto SecName = SecPair.first;
306       auto File = SecPair.second;
307       auto BufOrErr = MemoryBuffer::getFile(File);
308       if (!BufOrErr)
309         reportError(File, BufOrErr.getError());
310       auto Buf = std::move(*BufOrErr);
311       auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
312       auto BufSize = Buf->getBufferSize();
313       Obj.addSection<OwnedDataSection>(SecName,
314                                        ArrayRef<uint8_t>(BufPtr, BufSize));
315     }
316   }
317 
318   if (!Config.AddGnuDebugLink.empty())
319     Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
320 
321   if (Obj.SymbolTable) {
322     Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
323       if ((Config.LocalizeHidden &&
324            (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
325           (!Config.SymbolsToLocalize.empty() &&
326            is_contained(Config.SymbolsToLocalize, Sym.Name)))
327         Sym.Binding = STB_LOCAL;
328 
329       if (!Config.SymbolsToGlobalize.empty() &&
330           is_contained(Config.SymbolsToGlobalize, Sym.Name))
331         Sym.Binding = STB_GLOBAL;
332 
333       if (!Config.SymbolsToWeaken.empty() &&
334           is_contained(Config.SymbolsToWeaken, Sym.Name) &&
335           Sym.Binding == STB_GLOBAL)
336         Sym.Binding = STB_WEAK;
337 
338       if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
339           Sym.getShndx() != SHN_UNDEF)
340         Sym.Binding = STB_WEAK;
341 
342       const auto I = Config.SymbolsToRename.find(Sym.Name);
343       if (I != Config.SymbolsToRename.end())
344         Sym.Name = I->getValue();
345     });
346   }
347 }
348 
349 std::unique_ptr<Reader> CreateReader(StringRef InputFilename,
350                                      ElfType &OutputElfType) {
351   // Right now we can only read ELF files so there's only one reader;
352   auto Out = llvm::make_unique<ELFReader>(InputFilename);
353   // We need to set the default ElfType for output.
354   OutputElfType = Out->getElfType();
355   return std::move(Out);
356 }
357 
358 void ExecuteElfObjcopy(const CopyConfig &Config) {
359   ElfType OutputElfType;
360   auto Reader = CreateReader(Config.InputFilename, OutputElfType);
361   auto Obj = Reader->create();
362   auto Writer =
363       CreateWriter(Config, *Obj, Config.OutputFilename, OutputElfType);
364   HandleArgs(Config, *Obj, *Reader, OutputElfType);
365   Writer->finalize();
366   Writer->write();
367 }
368 
369 // ParseObjcopyOptions returns the config and sets the input arguments. If a
370 // help flag is set then ParseObjcopyOptions will print the help messege and
371 // exit.
372 CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
373   ObjcopyOptTable T;
374   unsigned MissingArgumentIndex, MissingArgumentCount;
375   llvm::opt::InputArgList InputArgs =
376       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
377 
378   if (InputArgs.size() == 0 || InputArgs.hasArg(OBJCOPY_help)) {
379     T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
380     exit(0);
381   }
382 
383   SmallVector<const char *, 2> Positional;
384 
385   for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
386     error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
387 
388   for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
389     Positional.push_back(Arg->getValue());
390 
391   if (Positional.empty())
392     error("No input file specified");
393 
394   if (Positional.size() > 2)
395     error("Too many positional arguments");
396 
397   CopyConfig Config;
398   Config.InputFilename = Positional[0];
399   Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
400   Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
401   Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
402   Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
403 
404   Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
405   Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
406 
407   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
408     if (!StringRef(Arg->getValue()).contains('='))
409       error("Bad format for --redefine-sym");
410     auto Old2New = StringRef(Arg->getValue()).split('=');
411     if (!Config.SymbolsToRename.insert(Old2New).second)
412       error("Multiple redefinition of symbol " + Old2New.first);
413   }
414 
415   for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
416     Config.ToRemove.push_back(Arg->getValue());
417   for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
418     Config.Keep.push_back(Arg->getValue());
419   for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
420     Config.OnlyKeep.push_back(Arg->getValue());
421   for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
422     Config.AddSection.push_back(Arg->getValue());
423   Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
424   Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
425   Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
426   Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
427   Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
428   Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
429   Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
430   Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
431   Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken);
432   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
433     Config.SymbolsToLocalize.push_back(Arg->getValue());
434   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
435     Config.SymbolsToGlobalize.push_back(Arg->getValue());
436   for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol))
437     Config.SymbolsToWeaken.push_back(Arg->getValue());
438 
439   return Config;
440 }
441 
442 int main(int argc, char **argv) {
443   InitLLVM X(argc, argv);
444   ToolName = argv[0];
445 
446   CopyConfig Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
447   ExecuteElfObjcopy(Config);
448 }
449