blob: 09553e85202d87df94bfaadf5ddfb555e0c5b8c8 [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>
Jake Ehrlich11216622017-11-14 20:36:04 +000078 OutputFormat("O", cl::desc("Set output format to one of the following:"
Petr Hosekc4df10e2017-08-04 21:09:26 +000079 "\n\tbinary"));
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000080static cl::list<std::string> ToRemove("remove-section",
Jake Ehrlich11216622017-11-14 20:36:04 +000081 cl::desc("Remove <section>"),
82 cl::value_desc("section"));
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000083static cl::alias ToRemoveA("R", cl::desc("Alias for remove-section"),
84 cl::aliasopt(ToRemove));
Jake Ehrlich6ad72d02017-11-27 18:56:01 +000085static cl::opt<bool> StripAll(
86 "strip-all",
87 cl::desc(
88 "Removes non-allocated sections other than .gnu.warning* sections"));
89static cl::opt<bool>
90 StripAllGNU("strip-all-gnu",
91 cl::desc("Removes symbol, relocation, and debug information"));
Jake Ehrlich1bfefc12017-11-13 22:13:08 +000092static cl::opt<bool> StripDebug("strip-debug",
93 cl::desc("Removes all debug information"));
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000094static cl::opt<bool> StripSections("strip-sections",
95 cl::desc("Remove all section headers"));
Jake Ehrlichd56725a2017-11-14 18:50:24 +000096static cl::opt<bool> StripNonAlloc("strip-non-alloc",
97 cl::desc("Remove all non-allocated sections"));
Jake Ehrlich5de70d92017-11-03 18:58:41 +000098static cl::opt<bool>
Jake Ehrlich11216622017-11-14 20:36:04 +000099 StripDWO("strip-dwo", cl::desc("Remove all DWARF .dwo sections from file"));
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000100static cl::opt<bool> ExtractDWO(
101 "extract-dwo",
Jake Ehrlich11216622017-11-14 20:36:04 +0000102 cl::desc("Remove all sections that are not DWARF .dwo sections from file"));
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000103static cl::opt<std::string>
104 SplitDWO("split-dwo",
Jake Ehrlich11216622017-11-14 20:36:04 +0000105 cl::desc("Equivalent to extract-dwo on the input file to "
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000106 "<dwo-file>, then strip-dwo on the input file"),
107 cl::value_desc("dwo-file"));
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000108
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000109using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000110
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000111bool IsDWOSection(const SectionBase &Sec) {
112 return Sec.Name.endswith(".dwo");
113}
114
115template <class ELFT>
116bool OnlyKeepDWOPred(const Object<ELFT> &Obj, const SectionBase &Sec) {
117 // We can't remove the section header string table.
118 if (&Sec == Obj.getSectionHeaderStrTab())
119 return false;
120 // Short of keeping the string table we want to keep everything that is a DWO
121 // section and remove everything else.
122 return !IsDWOSection(Sec);
123}
124
125template <class ELFT>
126void WriteObjectFile(const Object<ELFT> &Obj, StringRef File) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000127 std::unique_ptr<FileOutputBuffer> Buffer;
Rafael Espindolae0df3572017-11-08 01:05:44 +0000128 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000129 FileOutputBuffer::create(File, Obj.totalSize(),
130 FileOutputBuffer::F_executable);
Rafael Espindola85593c22017-11-08 21:15:21 +0000131 handleAllErrors(BufferOrErr.takeError(), [](const ErrorInfoBase &) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000132 error("failed to open " + OutputFilename);
Rafael Espindola85593c22017-11-08 21:15:21 +0000133 });
134 Buffer = std::move(*BufferOrErr);
135
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000136 Obj.write(*Buffer);
Rafael Espindola0d7a38a2017-11-08 01:50:29 +0000137 if (auto E = Buffer->commit())
138 reportError(File, errorToErrorCode(std::move(E)));
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000139}
140
141template <class ELFT>
142void SplitDWOToFile(const ELFObjectFile<ELFT> &ObjFile, StringRef File) {
143 // Construct a second output file for the DWO sections.
144 ELFObject<ELFT> DWOFile(ObjFile);
145
146 DWOFile.removeSections([&](const SectionBase &Sec) {
147 return OnlyKeepDWOPred<ELFT>(DWOFile, Sec);
148 });
149 DWOFile.finalize();
150 WriteObjectFile(DWOFile, File);
151}
152
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000153template <class ELFT>
154void CopyBinary(const ELFObjectFile<ELFT> &ObjFile) {
155 std::unique_ptr<Object<ELFT>> Obj;
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000156
Petr Hosekc4df10e2017-08-04 21:09:26 +0000157 if (!OutputFormat.empty() && OutputFormat != "binary")
158 error("invalid output format '" + OutputFormat + "'");
Petr Hosekc4df10e2017-08-04 21:09:26 +0000159 if (!OutputFormat.empty() && OutputFormat == "binary")
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000160 Obj = llvm::make_unique<BinaryObject<ELFT>>(ObjFile);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000161 else
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000162 Obj = llvm::make_unique<ELFObject<ELFT>>(ObjFile);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000163
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000164 if (!SplitDWO.empty())
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000165 SplitDWOToFile<ELFT>(ObjFile, SplitDWO.getValue());
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000166
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000167 SectionPred RemovePred = [](const SectionBase &) { return false; };
168
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000169 if (!ToRemove.empty()) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000170 RemovePred = [&](const SectionBase &Sec) {
Jake Ehrlichfcc05622017-10-10 23:02:43 +0000171 return std::find(std::begin(ToRemove), std::end(ToRemove), Sec.Name) !=
172 std::end(ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000173 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000174 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000175
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000176 if (StripDWO || !SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000177 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000178 return IsDWOSection(Sec) || RemovePred(Sec);
179 };
180
181 if (ExtractDWO)
182 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
183 return OnlyKeepDWOPred(*Obj, Sec) || RemovePred(Sec);
184 };
185
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000186 if (StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000187 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
188 if (RemovePred(Sec))
189 return true;
190 if ((Sec.Flags & SHF_ALLOC) != 0)
191 return false;
192 if (&Sec == Obj->getSectionHeaderStrTab())
193 return false;
194 switch(Sec.Type) {
195 case SHT_SYMTAB:
196 case SHT_REL:
197 case SHT_RELA:
198 case SHT_STRTAB:
199 return true;
200 }
201 return Sec.Name.startswith(".debug");
202 };
203
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000204 if (StripSections) {
205 RemovePred = [RemovePred](const SectionBase &Sec) {
206 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
207 };
208 Obj->WriteSectionHeaders = false;
209 }
210
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000211 if (StripDebug) {
212 RemovePred = [RemovePred](const SectionBase &Sec) {
213 return RemovePred(Sec) || Sec.Name.startswith(".debug");
214 };
215 }
216
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000217 if (StripNonAlloc)
218 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
219 if (RemovePred(Sec))
220 return true;
221 if (&Sec == Obj->getSectionHeaderStrTab())
222 return false;
223 return (Sec.Flags & SHF_ALLOC) == 0;
224 };
225
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000226 if (StripAll)
227 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
228 if (RemovePred(Sec))
229 return true;
230 if (&Sec == Obj->getSectionHeaderStrTab())
231 return false;
232 if (Sec.Name.startswith(".gnu.warning"))
233 return false;
234 return (Sec.Flags & SHF_ALLOC) == 0;
235 };
236
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000237 Obj->removeSections(RemovePred);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000238 Obj->finalize();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000239 WriteObjectFile(*Obj, OutputFilename.getValue());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000240}
241
242int main(int argc, char **argv) {
243 // Print a stack trace if we signal out.
244 sys::PrintStackTraceOnErrorSignal(argv[0]);
245 PrettyStackTraceProgram X(argc, argv);
246 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
247 cl::ParseCommandLineOptions(argc, argv, "llvm objcopy utility\n");
248 ToolName = argv[0];
249 if (InputFilename.empty()) {
250 cl::PrintHelpMessage();
251 return 2;
252 }
253 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(InputFilename);
254 if (!BinaryOrErr)
255 reportError(InputFilename, BinaryOrErr.takeError());
256 Binary &Binary = *BinaryOrErr.get().getBinary();
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000257 if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(&Binary)) {
258 CopyBinary(*o);
259 return 0;
260 }
261 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(&Binary)) {
262 CopyBinary(*o);
263 return 0;
264 }
265 if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(&Binary)) {
266 CopyBinary(*o);
267 return 0;
268 }
269 if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(&Binary)) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000270 CopyBinary(*o);
271 return 0;
272 }
273 reportError(InputFilename, object_error::invalid_file_type);
274}