blob: eb1d0de90d5ce290929aece40372822f92ea2f7b [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>"),
Jake Ehrlich777fb002017-12-15 20:17:55 +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 Ehrlichef3b80c2017-11-30 20:14:53 +000092static cl::list<std::string> Keep("keep", cl::desc("Keep <section>"),
93 cl::value_desc("section"));
94static cl::list<std::string> OnlyKeep("only-keep",
95 cl::desc("Remove all but <section>"),
96 cl::value_desc("section"));
97static cl::alias OnlyKeepA("j", cl::desc("Alias for only-keep"),
98 cl::aliasopt(OnlyKeep));
Jake Ehrlich1bfefc12017-11-13 22:13:08 +000099static cl::opt<bool> StripDebug("strip-debug",
100 cl::desc("Removes all debug information"));
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000101static cl::opt<bool> StripSections("strip-sections",
102 cl::desc("Remove all section headers"));
Jake Ehrlich777fb002017-12-15 20:17:55 +0000103static cl::opt<bool>
104 StripNonAlloc("strip-non-alloc",
105 cl::desc("Remove all non-allocated sections"));
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000106static cl::opt<bool>
Jake Ehrlich11216622017-11-14 20:36:04 +0000107 StripDWO("strip-dwo", cl::desc("Remove all DWARF .dwo sections from file"));
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000108static cl::opt<bool> ExtractDWO(
109 "extract-dwo",
Jake Ehrlich11216622017-11-14 20:36:04 +0000110 cl::desc("Remove all sections that are not DWARF .dwo sections from file"));
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000111static cl::opt<std::string>
112 SplitDWO("split-dwo",
Jake Ehrlich11216622017-11-14 20:36:04 +0000113 cl::desc("Equivalent to extract-dwo on the input file to "
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000114 "<dwo-file>, then strip-dwo on the input file"),
115 cl::value_desc("dwo-file"));
Jake Ehrliche8437de2017-12-19 00:47:30 +0000116static cl::list<std::string> AddSection(
117 "add-section",
118 cl::desc("Make a section named <section> with the contents of <file>."),
119 cl::value_desc("section=file"));
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000120static cl::opt<bool> LocalizeHidden(
121 "localize-hidden",
122 cl::desc(
123 "Mark all symbols that have hidden or internal visibility as local"));
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000124
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000125using SectionPred = std::function<bool(const SectionBase &Sec)>;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000126
Jake Ehrlich777fb002017-12-15 20:17:55 +0000127bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); }
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000128
129template <class ELFT>
130bool OnlyKeepDWOPred(const Object<ELFT> &Obj, const SectionBase &Sec) {
131 // We can't remove the section header string table.
132 if (&Sec == Obj.getSectionHeaderStrTab())
133 return false;
134 // Short of keeping the string table we want to keep everything that is a DWO
135 // section and remove everything else.
136 return !IsDWOSection(Sec);
137}
138
139template <class ELFT>
140void WriteObjectFile(const Object<ELFT> &Obj, StringRef File) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000141 std::unique_ptr<FileOutputBuffer> Buffer;
Rafael Espindolae0df3572017-11-08 01:05:44 +0000142 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000143 FileOutputBuffer::create(File, Obj.totalSize(),
144 FileOutputBuffer::F_executable);
Rafael Espindola85593c22017-11-08 21:15:21 +0000145 handleAllErrors(BufferOrErr.takeError(), [](const ErrorInfoBase &) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000146 error("failed to open " + OutputFilename);
Rafael Espindola85593c22017-11-08 21:15:21 +0000147 });
148 Buffer = std::move(*BufferOrErr);
149
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000150 Obj.write(*Buffer);
Rafael Espindola0d7a38a2017-11-08 01:50:29 +0000151 if (auto E = Buffer->commit())
152 reportError(File, errorToErrorCode(std::move(E)));
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000153}
154
155template <class ELFT>
156void SplitDWOToFile(const ELFObjectFile<ELFT> &ObjFile, StringRef File) {
157 // Construct a second output file for the DWO sections.
158 ELFObject<ELFT> DWOFile(ObjFile);
159
160 DWOFile.removeSections([&](const SectionBase &Sec) {
161 return OnlyKeepDWOPred<ELFT>(DWOFile, Sec);
162 });
163 DWOFile.finalize();
164 WriteObjectFile(DWOFile, File);
165}
166
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000167// This function handles the high level operations of GNU objcopy including
168// handling command line options. It's important to outline certain properties
169// we expect to hold of the command line operations. Any operation that "keeps"
170// should keep regardless of a remove. Additionally any removal should respect
171// any previous removals. Lastly whether or not something is removed shouldn't
172// depend a) on the order the options occur in or b) on some opaque priority
173// system. The only priority is that keeps/copies overrule removes.
Jake Ehrlich777fb002017-12-15 20:17:55 +0000174template <class ELFT> void CopyBinary(const ELFObjectFile<ELFT> &ObjFile) {
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000175 std::unique_ptr<Object<ELFT>> Obj;
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000176
Petr Hosekc4df10e2017-08-04 21:09:26 +0000177 if (!OutputFormat.empty() && OutputFormat != "binary")
178 error("invalid output format '" + OutputFormat + "'");
Petr Hosekc4df10e2017-08-04 21:09:26 +0000179 if (!OutputFormat.empty() && OutputFormat == "binary")
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000180 Obj = llvm::make_unique<BinaryObject<ELFT>>(ObjFile);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000181 else
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000182 Obj = llvm::make_unique<ELFObject<ELFT>>(ObjFile);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000183
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000184 if (!SplitDWO.empty())
Jake Ehrliche8437de2017-12-19 00:47:30 +0000185 SplitDWOToFile<ELFT>(ObjFile, SplitDWO.getValue());
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000186
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000187 // Localize:
188
189 if (LocalizeHidden) {
190 Obj->getSymTab()->localize([](const Symbol &Sym) {
191 return Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL;
192 });
193 }
194
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000195 SectionPred RemovePred = [](const SectionBase &) { return false; };
196
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000197 // Removes:
198
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000199 if (!ToRemove.empty()) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000200 RemovePred = [&](const SectionBase &Sec) {
Jake Ehrlichfcc05622017-10-10 23:02:43 +0000201 return std::find(std::begin(ToRemove), std::end(ToRemove), Sec.Name) !=
202 std::end(ToRemove);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000203 };
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000204 }
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000205
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000206 if (StripDWO || !SplitDWO.empty())
David Blaikie998ff812017-11-03 20:57:09 +0000207 RemovePred = [RemovePred](const SectionBase &Sec) {
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000208 return IsDWOSection(Sec) || RemovePred(Sec);
209 };
210
211 if (ExtractDWO)
212 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
213 return OnlyKeepDWOPred(*Obj, Sec) || RemovePred(Sec);
214 };
215
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000216 if (StripAllGNU)
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000217 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
218 if (RemovePred(Sec))
219 return true;
220 if ((Sec.Flags & SHF_ALLOC) != 0)
221 return false;
222 if (&Sec == Obj->getSectionHeaderStrTab())
223 return false;
Jake Ehrlich777fb002017-12-15 20:17:55 +0000224 switch (Sec.Type) {
Jake Ehrlichfabddf12017-11-13 22:02:07 +0000225 case SHT_SYMTAB:
226 case SHT_REL:
227 case SHT_RELA:
228 case SHT_STRTAB:
229 return true;
230 }
231 return Sec.Name.startswith(".debug");
232 };
233
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000234 if (StripSections) {
235 RemovePred = [RemovePred](const SectionBase &Sec) {
236 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
237 };
238 Obj->WriteSectionHeaders = false;
239 }
240
Jake Ehrlich1bfefc12017-11-13 22:13:08 +0000241 if (StripDebug) {
242 RemovePred = [RemovePred](const SectionBase &Sec) {
243 return RemovePred(Sec) || Sec.Name.startswith(".debug");
244 };
245 }
246
Jake Ehrlichd56725a2017-11-14 18:50:24 +0000247 if (StripNonAlloc)
248 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
249 if (RemovePred(Sec))
250 return true;
251 if (&Sec == Obj->getSectionHeaderStrTab())
252 return false;
253 return (Sec.Flags & SHF_ALLOC) == 0;
254 };
255
Jake Ehrlich6ad72d02017-11-27 18:56:01 +0000256 if (StripAll)
257 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
258 if (RemovePred(Sec))
259 return true;
260 if (&Sec == Obj->getSectionHeaderStrTab())
261 return false;
262 if (Sec.Name.startswith(".gnu.warning"))
263 return false;
264 return (Sec.Flags & SHF_ALLOC) == 0;
265 };
266
Jake Ehrlichef3b80c2017-11-30 20:14:53 +0000267 // Explicit copies:
268
269 if (!OnlyKeep.empty()) {
270 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
271 // Explicitly keep these sections regardless of previous removes.
272 if (std::find(std::begin(OnlyKeep), std::end(OnlyKeep), Sec.Name) !=
273 std::end(OnlyKeep))
274 return false;
275
276 // Allow all implicit removes.
277 if (RemovePred(Sec)) {
278 return true;
279 }
280
281 // Keep special sections.
282 if (Obj->getSectionHeaderStrTab() == &Sec) {
283 return false;
284 }
285 if (Obj->getSymTab() == &Sec || Obj->getSymTab()->getStrTab() == &Sec) {
286 return false;
287 }
288 // Remove everything else.
289 return true;
290 };
291 }
292
293 if (!Keep.empty()) {
294 RemovePred = [RemovePred](const SectionBase &Sec) {
295 // Explicitly keep these sections regardless of previous removes.
296 if (std::find(std::begin(Keep), std::end(Keep), Sec.Name) !=
297 std::end(Keep))
298 return false;
299 // Otherwise defer to RemovePred.
300 return RemovePred(Sec);
301 };
302 }
303
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000304 Obj->removeSections(RemovePred);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000305
306 if (!AddSection.empty()) {
307 for (const auto &Flag : AddSection) {
308 auto SecPair = StringRef(Flag).split("=");
309 auto SecName = SecPair.first;
310 auto File = SecPair.second;
311 auto BufOrErr = MemoryBuffer::getFile(File);
312 if (!BufOrErr)
313 reportError(File, BufOrErr.getError());
314 auto Buf = std::move(*BufOrErr);
315 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart());
316 auto BufSize = Buf->getBufferSize();
317 Obj->addSection(SecName, ArrayRef<uint8_t>(BufPtr, BufSize));
318 }
319 }
320
Petr Hosekc4df10e2017-08-04 21:09:26 +0000321 Obj->finalize();
Jake Ehrlich5de70d92017-11-03 18:58:41 +0000322 WriteObjectFile(*Obj, OutputFilename.getValue());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000323}
324
325int main(int argc, char **argv) {
326 // Print a stack trace if we signal out.
327 sys::PrintStackTraceOnErrorSignal(argv[0]);
328 PrettyStackTraceProgram X(argc, argv);
329 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
330 cl::ParseCommandLineOptions(argc, argv, "llvm objcopy utility\n");
331 ToolName = argv[0];
332 if (InputFilename.empty()) {
333 cl::PrintHelpMessage();
334 return 2;
335 }
336 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(InputFilename);
337 if (!BinaryOrErr)
338 reportError(InputFilename, BinaryOrErr.takeError());
339 Binary &Binary = *BinaryOrErr.get().getBinary();
Jake Ehrlich99e2c412017-11-14 18:41:47 +0000340 if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(&Binary)) {
341 CopyBinary(*o);
342 return 0;
343 }
344 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(&Binary)) {
345 CopyBinary(*o);
346 return 0;
347 }
348 if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(&Binary)) {
349 CopyBinary(*o);
350 return 0;
351 }
352 if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(&Binary)) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000353 CopyBinary(*o);
354 return 0;
355 }
356 reportError(InputFilename, object_error::invalid_file_type);
357}