blob: 5a09f8f18dbbb33214438b4dbc0a4d78bd9bb043 [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"
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/Support/Casting.h"
Petr Hosek05a04cb2017-08-01 00:33:58 +000021#include "llvm/Support/CommandLine.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000022#include "llvm/Support/Compiler.h"
23#include "llvm/Support/Error.h"
24#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/ErrorOr.h"
Petr Hosek05a04cb2017-08-01 00:33:58 +000026#include "llvm/Support/FileOutputBuffer.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000027#include "llvm/Support/ManagedStatic.h"
Petr Hosek05a04cb2017-08-01 00:33:58 +000028#include "llvm/Support/PrettyStackTrace.h"
29#include "llvm/Support/Signals.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000030#include "llvm/Support/raw_ostream.h"
31#include <algorithm>
32#include <cassert>
33#include <cstdlib>
34#include <functional>
35#include <iterator>
Petr Hosek05a04cb2017-08-01 00:33:58 +000036#include <memory>
37#include <string>
38#include <system_error>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000039#include <utility>
Petr Hosek05a04cb2017-08-01 00:33:58 +000040
41using namespace llvm;
42using namespace object;
43using namespace ELF;
44
45// The name this program was invoked as.
46static StringRef ToolName;
47
48namespace llvm {
49
Zachary Turner41a9ee92017-10-11 23:54:34 +000050LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
Petr Hosek05a04cb2017-08-01 00:33:58 +000051 errs() << ToolName << ": " << Message << ".\n";
52 errs().flush();
53 exit(1);
54}
55
56LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
57 assert(EC);
58 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
59 exit(1);
60}
61
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000062LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
Petr Hosek05a04cb2017-08-01 00:33:58 +000063 assert(E);
64 std::string Buf;
65 raw_string_ostream OS(Buf);
66 logAllUnhandledErrors(std::move(E), OS, "");
67 OS.flush();
68 errs() << ToolName << ": '" << File << "': " << Buf;
69 exit(1);
70}
Petr Hosek05a04cb2017-08-01 00:33:58 +000071
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000072} // end namespace llvm
73
74static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input>"));
75static cl::opt<std::string> OutputFilename(cl::Positional, cl::desc("<output>"),
Petr Hosek05a04cb2017-08-01 00:33:58 +000076 cl::init("-"));
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000077static cl::opt<std::string>
Petr Hosekc4df10e2017-08-04 21:09:26 +000078 OutputFormat("O", cl::desc("set output format to one of the following:"
79 "\n\tbinary"));
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000080static cl::list<std::string> ToRemove("remove-section",
81 cl::desc("Remove a specific section"));
82static cl::alias ToRemoveA("R", cl::desc("Alias for remove-section"),
83 cl::aliasopt(ToRemove));
84static cl::opt<bool> StripSections("strip-sections",
85 cl::desc("Remove all section headers"));
Jake Ehrlich5de70d92017-11-03 18:58:41 +000086static cl::opt<bool>
87 StripDWO("strip-dwo", cl::desc("remove all DWARF .dwo sections from file"));
88static cl::opt<bool> ExtractDWO(
89 "extract-dwo",
90 cl::desc("remove all sections that are not DWARF .dwo sections from file"));
91static cl::opt<std::string>
92 SplitDWO("split-dwo",
93 cl::desc("equivalent to extract-dwo on the input file to "
94 "<dwo-file>, then strip-dwo on the input file"),
95 cl::value_desc("dwo-file"));
Jake Ehrlichf03384d2017-10-11 18:09:18 +000096
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000097using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +000098
Jake Ehrlich5de70d92017-11-03 18:58:41 +000099bool IsDWOSection(const SectionBase &Sec) {
100 return Sec.Name.endswith(".dwo");
101}
102
103template <class ELFT>
104bool OnlyKeepDWOPred(const Object<ELFT> &Obj, const SectionBase &Sec) {
105 // We can't remove the section header string table.
106 if (&Sec == Obj.getSectionHeaderStrTab())
107 return false;
108 // Short of keeping the string table we want to keep everything that is a DWO
109 // section and remove everything else.
110 return !IsDWOSection(Sec);
111}
112
113template <class ELFT>
114void WriteObjectFile(const Object<ELFT> &Obj, StringRef File) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000115 std::unique_ptr<FileOutputBuffer> Buffer;
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000116 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
117 FileOutputBuffer::create(File, Obj.totalSize(),
118 FileOutputBuffer::F_executable);
119 if (BufferOrErr.getError())
120 error("failed to open " + OutputFilename);
121 else
122 Buffer = std::move(*BufferOrErr);
123 Obj.write(*Buffer);
124 if (auto EC = Buffer->commit())
125 reportError(File, EC);
126}
127
128template <class ELFT>
129void SplitDWOToFile(const ELFObjectFile<ELFT> &ObjFile, StringRef File) {
130 // Construct a second output file for the DWO sections.
131 ELFObject<ELFT> DWOFile(ObjFile);
132
133 DWOFile.removeSections([&](const SectionBase &Sec) {
134 return OnlyKeepDWOPred<ELFT>(DWOFile, Sec);
135 });
136 DWOFile.finalize();
137 WriteObjectFile(DWOFile, File);
138}
139
140void CopyBinary(const ELFObjectFile<ELF64LE> &ObjFile) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000141 std::unique_ptr<Object<ELF64LE>> Obj;
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000142
Petr Hosekc4df10e2017-08-04 21:09:26 +0000143 if (!OutputFormat.empty() && OutputFormat != "binary")
144 error("invalid output format '" + OutputFormat + "'");
Petr Hosekc4df10e2017-08-04 21:09:26 +0000145 if (!OutputFormat.empty() && OutputFormat == "binary")
146 Obj = llvm::make_unique<BinaryObject<ELF64LE>>(ObjFile);
147 else
148 Obj = llvm::make_unique<ELFObject<ELF64LE>>(ObjFile);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000149
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000150 if (!SplitDWO.empty())
151 SplitDWOToFile<ELF64LE>(ObjFile, SplitDWO.getValue());
152
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000153 SectionPred RemovePred = [](const SectionBase &) { return false; };
154
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000155 if (!ToRemove.empty()) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000156 RemovePred = [&](const SectionBase &Sec) {
Jake Ehrlichfcc05622017-10-10 23:02:43 +0000157 return std::find(std::begin(ToRemove), std::end(ToRemove), Sec.Name) !=
158 std::end(ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000159 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000160 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000161
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000162 if (StripDWO || !SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000163 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000164 return IsDWOSection(Sec) || RemovePred(Sec);
165 };
166
167 if (ExtractDWO)
168 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
169 return OnlyKeepDWOPred(*Obj, Sec) || RemovePred(Sec);
170 };
171
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000172 if (StripSections) {
173 RemovePred = [RemovePred](const SectionBase &Sec) {
174 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
175 };
176 Obj->WriteSectionHeaders = false;
177 }
178
179 Obj->removeSections(RemovePred);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000180 Obj->finalize();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000181 WriteObjectFile(*Obj, OutputFilename.getValue());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000182}
183
184int main(int argc, char **argv) {
185 // Print a stack trace if we signal out.
186 sys::PrintStackTraceOnErrorSignal(argv[0]);
187 PrettyStackTraceProgram X(argc, argv);
188 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
189 cl::ParseCommandLineOptions(argc, argv, "llvm objcopy utility\n");
190 ToolName = argv[0];
191 if (InputFilename.empty()) {
192 cl::PrintHelpMessage();
193 return 2;
194 }
195 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(InputFilename);
196 if (!BinaryOrErr)
197 reportError(InputFilename, BinaryOrErr.takeError());
198 Binary &Binary = *BinaryOrErr.get().getBinary();
199 if (ELFObjectFile<ELF64LE> *o = dyn_cast<ELFObjectFile<ELF64LE>>(&Binary)) {
200 CopyBinary(*o);
201 return 0;
202 }
203 reportError(InputFilename, object_error::invalid_file_type);
204}