blob: f7a94f5f891e23eb25c03bee28df5cbc7a929ee8 [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));
Jake Ehrlichfabddf12017-11-13 22:02:07 +000084static cl::opt<bool> StripAll("strip-all",
85 cl::desc("Removes symbol, relocation, and debug information"));
Jake Ehrlich1bfefc12017-11-13 22:13:08 +000086static cl::opt<bool> StripDebug("strip-debug",
87 cl::desc("Removes all debug information"));
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000088static cl::opt<bool> StripSections("strip-sections",
89 cl::desc("Remove all section headers"));
Jake Ehrlich5de70d92017-11-03 18:58:41 +000090static cl::opt<bool>
91 StripDWO("strip-dwo", cl::desc("remove all DWARF .dwo sections from file"));
92static cl::opt<bool> ExtractDWO(
93 "extract-dwo",
94 cl::desc("remove all sections that are not DWARF .dwo sections from file"));
95static cl::opt<std::string>
96 SplitDWO("split-dwo",
97 cl::desc("equivalent to extract-dwo on the input file to "
98 "<dwo-file>, then strip-dwo on the input file"),
99 cl::value_desc("dwo-file"));
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000100
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000101using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000102
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000103bool IsDWOSection(const SectionBase &Sec) {
104 return Sec.Name.endswith(".dwo");
105}
106
107template <class ELFT>
108bool OnlyKeepDWOPred(const Object<ELFT> &Obj, const SectionBase &Sec) {
109 // We can't remove the section header string table.
110 if (&Sec == Obj.getSectionHeaderStrTab())
111 return false;
112 // Short of keeping the string table we want to keep everything that is a DWO
113 // section and remove everything else.
114 return !IsDWOSection(Sec);
115}
116
117template <class ELFT>
118void WriteObjectFile(const Object<ELFT> &Obj, StringRef File) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000119 std::unique_ptr<FileOutputBuffer> Buffer;
Rafael Espindolae0df3572017-11-08 01:05:44 +0000120 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000121 FileOutputBuffer::create(File, Obj.totalSize(),
122 FileOutputBuffer::F_executable);
Rafael Espindola85593c22017-11-08 21:15:21 +0000123 handleAllErrors(BufferOrErr.takeError(), [](const ErrorInfoBase &) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000124 error("failed to open " + OutputFilename);
Rafael Espindola85593c22017-11-08 21:15:21 +0000125 });
126 Buffer = std::move(*BufferOrErr);
127
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000128 Obj.write(*Buffer);
Rafael Espindola0d7a38a2017-11-08 01:50:29 +0000129 if (auto E = Buffer->commit())
130 reportError(File, errorToErrorCode(std::move(E)));
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000131}
132
133template <class ELFT>
134void SplitDWOToFile(const ELFObjectFile<ELFT> &ObjFile, StringRef File) {
135 // Construct a second output file for the DWO sections.
136 ELFObject<ELFT> DWOFile(ObjFile);
137
138 DWOFile.removeSections([&](const SectionBase &Sec) {
139 return OnlyKeepDWOPred<ELFT>(DWOFile, Sec);
140 });
141 DWOFile.finalize();
142 WriteObjectFile(DWOFile, File);
143}
144
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000145template <class ELFT>
146void CopyBinary(const ELFObjectFile<ELFT> &ObjFile) {
147 std::unique_ptr<Object<ELFT>> Obj;
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000148
Petr Hosekc4df10e2017-08-04 21:09:26 +0000149 if (!OutputFormat.empty() && OutputFormat != "binary")
150 error("invalid output format '" + OutputFormat + "'");
Petr Hosekc4df10e2017-08-04 21:09:26 +0000151 if (!OutputFormat.empty() && OutputFormat == "binary")
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000152 Obj = llvm::make_unique<BinaryObject<ELFT>>(ObjFile);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000153 else
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000154 Obj = llvm::make_unique<ELFObject<ELFT>>(ObjFile);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000155
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000156 if (!SplitDWO.empty())
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000157 SplitDWOToFile<ELFT>(ObjFile, SplitDWO.getValue());
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000158
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000159 SectionPred RemovePred = [](const SectionBase &) { return false; };
160
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000161 if (!ToRemove.empty()) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000162 RemovePred = [&](const SectionBase &Sec) {
Jake Ehrlichfcc05622017-10-10 23:02:43 +0000163 return std::find(std::begin(ToRemove), std::end(ToRemove), Sec.Name) !=
164 std::end(ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000165 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000166 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000167
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000168 if (StripDWO || !SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000169 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000170 return IsDWOSection(Sec) || RemovePred(Sec);
171 };
172
173 if (ExtractDWO)
174 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
175 return OnlyKeepDWOPred(*Obj, Sec) || RemovePred(Sec);
176 };
177
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000178 if (StripAll)
179 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
180 if (RemovePred(Sec))
181 return true;
182 if ((Sec.Flags & SHF_ALLOC) != 0)
183 return false;
184 if (&Sec == Obj->getSectionHeaderStrTab())
185 return false;
186 switch(Sec.Type) {
187 case SHT_SYMTAB:
188 case SHT_REL:
189 case SHT_RELA:
190 case SHT_STRTAB:
191 return true;
192 }
193 return Sec.Name.startswith(".debug");
194 };
195
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000196 if (StripSections) {
197 RemovePred = [RemovePred](const SectionBase &Sec) {
198 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
199 };
200 Obj->WriteSectionHeaders = false;
201 }
202
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000203 if (StripDebug) {
204 RemovePred = [RemovePred](const SectionBase &Sec) {
205 return RemovePred(Sec) || Sec.Name.startswith(".debug");
206 };
207 }
208
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000209 Obj->removeSections(RemovePred);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000210 Obj->finalize();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000211 WriteObjectFile(*Obj, OutputFilename.getValue());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000212}
213
214int main(int argc, char **argv) {
215 // Print a stack trace if we signal out.
216 sys::PrintStackTraceOnErrorSignal(argv[0]);
217 PrettyStackTraceProgram X(argc, argv);
218 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
219 cl::ParseCommandLineOptions(argc, argv, "llvm objcopy utility\n");
220 ToolName = argv[0];
221 if (InputFilename.empty()) {
222 cl::PrintHelpMessage();
223 return 2;
224 }
225 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(InputFilename);
226 if (!BinaryOrErr)
227 reportError(InputFilename, BinaryOrErr.takeError());
228 Binary &Binary = *BinaryOrErr.get().getBinary();
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000229 if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(&Binary)) {
230 CopyBinary(*o);
231 return 0;
232 }
233 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(&Binary)) {
234 CopyBinary(*o);
235 return 0;
236 }
237 if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(&Binary)) {
238 CopyBinary(*o);
239 return 0;
240 }
241 if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(&Binary)) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000242 CopyBinary(*o);
243 return 0;
244 }
245 reportError(InputFilename, object_error::invalid_file_type);
246}