OSDN Git Service

[llvm-objcopy] Add --globalize-symbol option
[android-x86/external-llvm.git] / tools / llvm-objcopy / llvm-objcopy.cpp
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   StringMap<StringRef> SymbolsToRename;
124   bool StripAll;
125   bool StripAllGNU;
126   bool StripDebug;
127   bool StripSections;
128   bool StripNonAlloc;
129   bool StripDWO;
130   bool ExtractDWO;
131   bool LocalizeHidden;
132 };
133
134 using SectionPred = std::function<bool(const SectionBase &Sec)>;
135
136 bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
137
138 bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
139   // We can't remove the section header string table.
140   if (&Sec == Obj.SectionNames)
141     return false;
142   // Short of keeping the string table we want to keep everything that is a DWO
143   // section and remove everything else.
144   return !IsDWOSection(Sec);
145 }
146
147 std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj,
148                                      StringRef File, ElfType OutputElfType) {
149   if (Config.OutputFormat == "binary") {
150     return llvm::make_unique<BinaryWriter>(File, Obj);
151   }
152   // Depending on the initial ELFT and OutputFormat we need a different Writer.
153   switch (OutputElfType) {
154   case ELFT_ELF32LE:
155     return llvm::make_unique<ELFWriter<ELF32LE>>(File, Obj,
156                                                  !Config.StripSections);
157   case ELFT_ELF64LE:
158     return llvm::make_unique<ELFWriter<ELF64LE>>(File, Obj,
159                                                  !Config.StripSections);
160   case ELFT_ELF32BE:
161     return llvm::make_unique<ELFWriter<ELF32BE>>(File, Obj,
162                                                  !Config.StripSections);
163   case ELFT_ELF64BE:
164     return llvm::make_unique<ELFWriter<ELF64BE>>(File, Obj,
165                                                  !Config.StripSections);
166   }
167   llvm_unreachable("Invalid output format");
168 }
169
170 void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader,
171                     StringRef File, ElfType OutputElfType) {
172   auto DWOFile = Reader.create();
173   DWOFile->removeSections(
174       [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); });
175   auto Writer = CreateWriter(Config, *DWOFile, File, OutputElfType);
176   Writer->finalize();
177   Writer->write();
178 }
179
180 // This function handles the high level operations of GNU objcopy including
181 // handling command line options. It's important to outline certain properties
182 // we expect to hold of the command line operations. Any operation that "keeps"
183 // should keep regardless of a remove. Additionally any removal should respect
184 // any previous removals. Lastly whether or not something is removed shouldn't
185 // depend a) on the order the options occur in or b) on some opaque priority
186 // system. The only priority is that keeps/copies overrule removes.
187 void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader,
188                 ElfType OutputElfType) {
189
190   if (!Config.SplitDWO.empty()) {
191     SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
192   }
193
194   SectionPred RemovePred = [](const SectionBase &) { return false; };
195
196   // Removes:
197   if (!Config.ToRemove.empty()) {
198     RemovePred = [&Config](const SectionBase &Sec) {
199       return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove),
200                        Sec.Name) != std::end(Config.ToRemove);
201     };
202   }
203
204   if (Config.StripDWO || !Config.SplitDWO.empty())
205     RemovePred = [RemovePred](const SectionBase &Sec) {
206       return IsDWOSection(Sec) || RemovePred(Sec);
207     };
208
209   if (Config.ExtractDWO)
210     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
211       return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
212     };
213
214   if (Config.StripAllGNU)
215     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
216       if (RemovePred(Sec))
217         return true;
218       if ((Sec.Flags & SHF_ALLOC) != 0)
219         return false;
220       if (&Sec == Obj.SectionNames)
221         return false;
222       switch (Sec.Type) {
223       case SHT_SYMTAB:
224       case SHT_REL:
225       case SHT_RELA:
226       case SHT_STRTAB:
227         return true;
228       }
229       return Sec.Name.startswith(".debug");
230     };
231
232   if (Config.StripSections) {
233     RemovePred = [RemovePred](const SectionBase &Sec) {
234       return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
235     };
236   }
237
238   if (Config.StripDebug) {
239     RemovePred = [RemovePred](const SectionBase &Sec) {
240       return RemovePred(Sec) || Sec.Name.startswith(".debug");
241     };
242   }
243
244   if (Config.StripNonAlloc)
245     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
246       if (RemovePred(Sec))
247         return true;
248       if (&Sec == Obj.SectionNames)
249         return false;
250       return (Sec.Flags & SHF_ALLOC) == 0;
251     };
252
253   if (Config.StripAll)
254     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
255       if (RemovePred(Sec))
256         return true;
257       if (&Sec == Obj.SectionNames)
258         return false;
259       if (Sec.Name.startswith(".gnu.warning"))
260         return false;
261       return (Sec.Flags & SHF_ALLOC) == 0;
262     };
263
264   // Explicit copies:
265   if (!Config.OnlyKeep.empty()) {
266     RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
267       // Explicitly keep these sections regardless of previous removes.
268       if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep),
269                     Sec.Name) != std::end(Config.OnlyKeep))
270         return false;
271
272       // Allow all implicit removes.
273       if (RemovePred(Sec))
274         return true;
275
276       // Keep special sections.
277       if (Obj.SectionNames == &Sec)
278         return false;
279       if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
280         return false;
281
282       // Remove everything else.
283       return true;
284     };
285   }
286
287   if (!Config.Keep.empty()) {
288     RemovePred = [Config, RemovePred](const SectionBase &Sec) {
289       // Explicitly keep these sections regardless of previous removes.
290       if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) !=
291           std::end(Config.Keep))
292         return false;
293       // Otherwise defer to RemovePred.
294       return RemovePred(Sec);
295     };
296   }
297
298   Obj.removeSections(RemovePred);
299
300   if (!Config.AddSection.empty()) {
301     for (const auto &Flag : Config.AddSection) {
302       auto SecPair = Flag.split("=");
303       auto SecName = SecPair.first;
304       auto File = SecPair.second;
305       auto BufOrErr = MemoryBuffer::getFile(File);
306       if (!BufOrErr)
307         reportError(File, BufOrErr.getError());
308       auto Buf = std::move(*BufOrErr);
309       auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
310       auto BufSize = Buf->getBufferSize();
311       Obj.addSection<OwnedDataSection>(SecName,
312                                        ArrayRef<uint8_t>(BufPtr, BufSize));
313     }
314   }
315
316   if (!Config.AddGnuDebugLink.empty())
317     Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
318
319   if (Obj.SymbolTable) {
320     Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
321       if ((Config.LocalizeHidden &&
322            (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
323           (!Config.SymbolsToLocalize.empty() &&
324            is_contained(Config.SymbolsToLocalize, Sym.Name)))
325         Sym.Binding = STB_LOCAL;
326
327       if (!Config.SymbolsToGlobalize.empty() &&
328           is_contained(Config.SymbolsToGlobalize, Sym.Name))
329         Sym.Binding = STB_GLOBAL;
330
331       const auto I = Config.SymbolsToRename.find(Sym.Name);
332       if (I != Config.SymbolsToRename.end())
333         Sym.Name = I->getValue();
334     });
335   }
336 }
337
338 std::unique_ptr<Reader> CreateReader(StringRef InputFilename,
339                                      ElfType &OutputElfType) {
340   // Right now we can only read ELF files so there's only one reader;
341   auto Out = llvm::make_unique<ELFReader>(InputFilename);
342   // We need to set the default ElfType for output.
343   OutputElfType = Out->getElfType();
344   return std::move(Out);
345 }
346
347 void ExecuteElfObjcopy(const CopyConfig &Config) {
348   ElfType OutputElfType;
349   auto Reader = CreateReader(Config.InputFilename, OutputElfType);
350   auto Obj = Reader->create();
351   auto Writer =
352       CreateWriter(Config, *Obj, Config.OutputFilename, OutputElfType);
353   HandleArgs(Config, *Obj, *Reader, OutputElfType);
354   Writer->finalize();
355   Writer->write();
356 }
357
358 // ParseObjcopyOptions returns the config and sets the input arguments. If a
359 // help flag is set then ParseObjcopyOptions will print the help messege and
360 // exit.
361 CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
362   ObjcopyOptTable T;
363   unsigned MissingArgumentIndex, MissingArgumentCount;
364   llvm::opt::InputArgList InputArgs =
365       T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
366
367   if (InputArgs.size() == 0 || InputArgs.hasArg(OBJCOPY_help)) {
368     T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
369     exit(0);
370   }
371
372   SmallVector<const char *, 2> Positional;
373
374   for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
375     error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
376
377   for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
378     Positional.push_back(Arg->getValue());
379
380   if (Positional.empty())
381     error("No input file specified");
382
383   if (Positional.size() > 2)
384     error("Too many positional arguments");
385
386   CopyConfig Config;
387   Config.InputFilename = Positional[0];
388   Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1];
389   Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target);
390   Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target);
391   Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture);
392
393   Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
394   Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
395
396   for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) {
397     if (!StringRef(Arg->getValue()).contains('='))
398       error("Bad format for --redefine-sym");
399     auto Old2New = StringRef(Arg->getValue()).split('=');
400     if (!Config.SymbolsToRename.insert(Old2New).second)
401       error("Multiple redefinition of symbol " + Old2New.first);
402   }
403
404   for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section))
405     Config.ToRemove.push_back(Arg->getValue());
406   for (auto Arg : InputArgs.filtered(OBJCOPY_keep))
407     Config.Keep.push_back(Arg->getValue());
408   for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep))
409     Config.OnlyKeep.push_back(Arg->getValue());
410   for (auto Arg : InputArgs.filtered(OBJCOPY_add_section))
411     Config.AddSection.push_back(Arg->getValue());
412   Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all);
413   Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu);
414   Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug);
415   Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo);
416   Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections);
417   Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc);
418   Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo);
419   Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden);
420   for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol))
421     Config.SymbolsToLocalize.push_back(Arg->getValue());
422   for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol))
423     Config.SymbolsToGlobalize.push_back(Arg->getValue());
424
425   return Config;
426 }
427
428 int main(int argc, char **argv) {
429   InitLLVM X(argc, argv);
430   ToolName = argv[0];
431
432   CopyConfig Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
433   ExecuteElfObjcopy(Config);
434 }