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/raw_ostream.h"
39 #include <system_error>
43 using namespace object;
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) \
57 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
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},
72 class ObjcopyOptTable : public opt::OptTable {
74 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {}
79 // The name this program was invoked as.
80 static StringRef ToolName;
84 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
85 errs() << ToolName << ": " << Message << ".\n";
90 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
92 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
96 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
99 raw_string_ostream OS(Buf);
100 logAllUnhandledErrors(std::move(E), OS, "");
102 errs() << ToolName << ": '" << File << "': " << Buf;
106 } // end namespace llvm
109 StringRef OutputFilename;
110 StringRef InputFilename;
111 StringRef OutputFormat;
112 StringRef InputFormat;
113 StringRef BinaryArch;
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;
134 using SectionPred = std::function<bool(const SectionBase &Sec)>;
136 bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
138 bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
139 // We can't remove the section header string table.
140 if (&Sec == Obj.SectionNames)
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);
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);
152 // Depending on the initial ELFT and OutputFormat we need a different Writer.
153 switch (OutputElfType) {
155 return llvm::make_unique<ELFWriter<ELF32LE>>(File, Obj,
156 !Config.StripSections);
158 return llvm::make_unique<ELFWriter<ELF64LE>>(File, Obj,
159 !Config.StripSections);
161 return llvm::make_unique<ELFWriter<ELF32BE>>(File, Obj,
162 !Config.StripSections);
164 return llvm::make_unique<ELFWriter<ELF64BE>>(File, Obj,
165 !Config.StripSections);
167 llvm_unreachable("Invalid output format");
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);
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) {
190 if (!Config.SplitDWO.empty()) {
191 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
194 SectionPred RemovePred = [](const SectionBase &) { return false; };
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);
204 if (Config.StripDWO || !Config.SplitDWO.empty())
205 RemovePred = [RemovePred](const SectionBase &Sec) {
206 return IsDWOSection(Sec) || RemovePred(Sec);
209 if (Config.ExtractDWO)
210 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
211 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
214 if (Config.StripAllGNU)
215 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
218 if ((Sec.Flags & SHF_ALLOC) != 0)
220 if (&Sec == Obj.SectionNames)
229 return Sec.Name.startswith(".debug");
232 if (Config.StripSections) {
233 RemovePred = [RemovePred](const SectionBase &Sec) {
234 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
238 if (Config.StripDebug) {
239 RemovePred = [RemovePred](const SectionBase &Sec) {
240 return RemovePred(Sec) || Sec.Name.startswith(".debug");
244 if (Config.StripNonAlloc)
245 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
248 if (&Sec == Obj.SectionNames)
250 return (Sec.Flags & SHF_ALLOC) == 0;
254 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
257 if (&Sec == Obj.SectionNames)
259 if (Sec.Name.startswith(".gnu.warning"))
261 return (Sec.Flags & SHF_ALLOC) == 0;
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))
272 // Allow all implicit removes.
276 // Keep special sections.
277 if (Obj.SectionNames == &Sec)
279 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec)
282 // Remove everything else.
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))
293 // Otherwise defer to RemovePred.
294 return RemovePred(Sec);
298 Obj.removeSections(RemovePred);
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);
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));
316 if (!Config.AddGnuDebugLink.empty())
317 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
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;
327 if (!Config.SymbolsToGlobalize.empty() &&
328 is_contained(Config.SymbolsToGlobalize, Sym.Name))
329 Sym.Binding = STB_GLOBAL;
331 const auto I = Config.SymbolsToRename.find(Sym.Name);
332 if (I != Config.SymbolsToRename.end())
333 Sym.Name = I->getValue();
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);
347 void ExecuteElfObjcopy(const CopyConfig &Config) {
348 ElfType OutputElfType;
349 auto Reader = CreateReader(Config.InputFilename, OutputElfType);
350 auto Obj = Reader->create();
352 CreateWriter(Config, *Obj, Config.OutputFilename, OutputElfType);
353 HandleArgs(Config, *Obj, *Reader, OutputElfType);
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
361 CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) {
363 unsigned MissingArgumentIndex, MissingArgumentCount;
364 llvm::opt::InputArgList InputArgs =
365 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount);
367 if (InputArgs.size() == 0 || InputArgs.hasArg(OBJCOPY_help)) {
368 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool");
372 SmallVector<const char *, 2> Positional;
374 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN))
375 error("unknown argument '" + Arg->getAsString(InputArgs) + "'");
377 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT))
378 Positional.push_back(Arg->getValue());
380 if (Positional.empty())
381 error("No input file specified");
383 if (Positional.size() > 2)
384 error("Too many positional arguments");
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);
393 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo);
394 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink);
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);
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());
428 int main(int argc, char **argv) {
429 InitLLVM X(argc, argv);
432 CopyConfig Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc));
433 ExecuteElfObjcopy(Config);