1 //===- llvm-objcopy.cpp ---------------------------------------------------===//
2 //
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 //===----------------------------------------------------------------------===//
9 
10 #include "llvm-objcopy.h"
11 #include "Object.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/Support/Casting.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/ErrorOr.h"
26 #include "llvm/Support/FileOutputBuffer.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/Signals.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 #include <cassert>
33 #include <cstdlib>
34 #include <functional>
35 #include <iterator>
36 #include <memory>
37 #include <string>
38 #include <system_error>
39 #include <utility>
40 
41 using namespace llvm;
42 using namespace object;
43 using namespace ELF;
44 
45 // The name this program was invoked as.
46 static StringRef ToolName;
47 
48 namespace llvm {
49 
50 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
51   errs() << ToolName << ": " << Message << ".\n";
52   errs().flush();
53   exit(1);
54 }
55 
56 LLVM_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 
62 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
63   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 }
71 
72 } // end namespace llvm
73 
74 static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input>"));
75 static cl::opt<std::string> OutputFilename(cl::Positional, cl::desc("<output>"),
76                                     cl::init("-"));
77 static cl::opt<std::string>
78     OutputFormat("O", cl::desc("Set output format to one of the following:"
79                                "\n\tbinary"));
80 static cl::list<std::string> ToRemove("remove-section",
81                                       cl::desc("Remove <section>"),
82                                       cl::value_desc("section"));
83 static cl::alias ToRemoveA("R", cl::desc("Alias for remove-section"),
84                            cl::aliasopt(ToRemove));
85 static cl::opt<bool> StripAll(
86     "strip-all",
87     cl::desc(
88         "Removes non-allocated sections other than .gnu.warning* sections"));
89 static cl::opt<bool>
90     StripAllGNU("strip-all-gnu",
91                 cl::desc("Removes symbol, relocation, and debug information"));
92 static cl::list<std::string> Keep("keep", cl::desc("Keep <section>"),
93                                   cl::value_desc("section"));
94 static cl::list<std::string> OnlyKeep("only-keep",
95                                       cl::desc("Remove all but <section>"),
96                                       cl::value_desc("section"));
97 static cl::alias OnlyKeepA("j", cl::desc("Alias for only-keep"),
98                            cl::aliasopt(OnlyKeep));
99 static cl::opt<bool> StripDebug("strip-debug",
100                                 cl::desc("Removes all debug information"));
101 static cl::opt<bool> StripSections("strip-sections",
102                                    cl::desc("Remove all section headers"));
103 static cl::opt<bool> StripNonAlloc("strip-non-alloc",
104                                    cl::desc("Remove all non-allocated sections"));
105 static cl::opt<bool>
106     StripDWO("strip-dwo", cl::desc("Remove all DWARF .dwo sections from file"));
107 static cl::opt<bool> ExtractDWO(
108     "extract-dwo",
109     cl::desc("Remove all sections that are not DWARF .dwo sections from file"));
110 static cl::opt<std::string>
111     SplitDWO("split-dwo",
112              cl::desc("Equivalent to extract-dwo on the input file to "
113                       "<dwo-file>, then strip-dwo on the input file"),
114              cl::value_desc("dwo-file"));
115 
116 using SectionPred = std::function<bool(const SectionBase &Sec)>;
117 
118 bool IsDWOSection(const SectionBase &Sec) {
119   return Sec.Name.endswith(".dwo");
120 }
121 
122 template <class ELFT>
123 bool OnlyKeepDWOPred(const Object<ELFT> &Obj, const SectionBase &Sec) {
124   // We can't remove the section header string table.
125   if (&Sec == Obj.getSectionHeaderStrTab())
126     return false;
127   // Short of keeping the string table we want to keep everything that is a DWO
128   // section and remove everything else.
129   return !IsDWOSection(Sec);
130 }
131 
132 template <class ELFT>
133 void WriteObjectFile(const Object<ELFT> &Obj, StringRef File) {
134   std::unique_ptr<FileOutputBuffer> Buffer;
135   Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
136       FileOutputBuffer::create(File, Obj.totalSize(),
137                                FileOutputBuffer::F_executable);
138   handleAllErrors(BufferOrErr.takeError(), [](const ErrorInfoBase &) {
139     error("failed to open " + OutputFilename);
140   });
141   Buffer = std::move(*BufferOrErr);
142 
143   Obj.write(*Buffer);
144   if (auto E = Buffer->commit())
145     reportError(File, errorToErrorCode(std::move(E)));
146 }
147 
148 template <class ELFT>
149 void SplitDWOToFile(const ELFObjectFile<ELFT> &ObjFile, StringRef File) {
150   // Construct a second output file for the DWO sections.
151   ELFObject<ELFT> DWOFile(ObjFile);
152 
153   DWOFile.removeSections([&](const SectionBase &Sec) {
154     return OnlyKeepDWOPred<ELFT>(DWOFile, Sec);
155   });
156   DWOFile.finalize();
157   WriteObjectFile(DWOFile, File);
158 }
159 
160 // This function handles the high level operations of GNU objcopy including
161 // handling command line options. It's important to outline certain properties
162 // we expect to hold of the command line operations. Any operation that "keeps"
163 // should keep regardless of a remove. Additionally any removal should respect
164 // any previous removals. Lastly whether or not something is removed shouldn't
165 // depend a) on the order the options occur in or b) on some opaque priority
166 // system. The only priority is that keeps/copies overrule removes.
167 template <class ELFT>
168 void CopyBinary(const ELFObjectFile<ELFT> &ObjFile) {
169   std::unique_ptr<Object<ELFT>> Obj;
170 
171   if (!OutputFormat.empty() && OutputFormat != "binary")
172     error("invalid output format '" + OutputFormat + "'");
173   if (!OutputFormat.empty() && OutputFormat == "binary")
174     Obj = llvm::make_unique<BinaryObject<ELFT>>(ObjFile);
175   else
176     Obj = llvm::make_unique<ELFObject<ELFT>>(ObjFile);
177 
178   if (!SplitDWO.empty())
179     SplitDWOToFile<ELFT>(ObjFile, SplitDWO.getValue());
180 
181   SectionPred RemovePred = [](const SectionBase &) { return false; };
182 
183   // Removes:
184 
185   if (!ToRemove.empty()) {
186     RemovePred = [&](const SectionBase &Sec) {
187       return std::find(std::begin(ToRemove), std::end(ToRemove), Sec.Name) !=
188              std::end(ToRemove);
189     };
190   }
191 
192   if (StripDWO || !SplitDWO.empty())
193     RemovePred = [RemovePred](const SectionBase &Sec) {
194       return IsDWOSection(Sec) || RemovePred(Sec);
195     };
196 
197   if (ExtractDWO)
198     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
199       return OnlyKeepDWOPred(*Obj, Sec) || RemovePred(Sec);
200     };
201 
202   if (StripAllGNU)
203     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
204       if (RemovePred(Sec))
205         return true;
206       if ((Sec.Flags & SHF_ALLOC) != 0)
207         return false;
208       if (&Sec == Obj->getSectionHeaderStrTab())
209         return false;
210       switch(Sec.Type) {
211       case SHT_SYMTAB:
212       case SHT_REL:
213       case SHT_RELA:
214       case SHT_STRTAB:
215         return true;
216       }
217       return Sec.Name.startswith(".debug");
218     };
219 
220   if (StripSections) {
221     RemovePred = [RemovePred](const SectionBase &Sec) {
222       return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
223     };
224     Obj->WriteSectionHeaders = false;
225   }
226 
227   if (StripDebug) {
228     RemovePred = [RemovePred](const SectionBase &Sec) {
229       return RemovePred(Sec) || Sec.Name.startswith(".debug");
230     };
231   }
232 
233   if (StripNonAlloc)
234     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
235       if (RemovePred(Sec))
236         return true;
237       if (&Sec == Obj->getSectionHeaderStrTab())
238         return false;
239       return (Sec.Flags & SHF_ALLOC) == 0;
240     };
241 
242   if (StripAll)
243     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
244       if (RemovePred(Sec))
245         return true;
246       if (&Sec == Obj->getSectionHeaderStrTab())
247         return false;
248       if (Sec.Name.startswith(".gnu.warning"))
249         return false;
250       return (Sec.Flags & SHF_ALLOC) == 0;
251     };
252 
253   // Explicit copies:
254 
255   if (!OnlyKeep.empty()) {
256     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
257       // Explicitly keep these sections regardless of previous removes.
258       if (std::find(std::begin(OnlyKeep), std::end(OnlyKeep), Sec.Name) !=
259           std::end(OnlyKeep))
260         return false;
261 
262       // Allow all implicit removes.
263       if (RemovePred(Sec)) {
264         return true;
265       }
266 
267       // Keep special sections.
268       if (Obj->getSectionHeaderStrTab() == &Sec) {
269         return false;
270       }
271       if (Obj->getSymTab() == &Sec || Obj->getSymTab()->getStrTab() == &Sec) {
272         return false;
273       }
274       // Remove everything else.
275       return true;
276     };
277   }
278 
279   if (!Keep.empty()) {
280     RemovePred = [RemovePred](const SectionBase &Sec) {
281       // Explicitly keep these sections regardless of previous removes.
282       if (std::find(std::begin(Keep), std::end(Keep), Sec.Name) !=
283           std::end(Keep))
284         return false;
285       // Otherwise defer to RemovePred.
286       return RemovePred(Sec);
287     };
288   }
289 
290   Obj->removeSections(RemovePred);
291   Obj->finalize();
292   WriteObjectFile(*Obj, OutputFilename.getValue());
293 }
294 
295 int main(int argc, char **argv) {
296   // Print a stack trace if we signal out.
297   sys::PrintStackTraceOnErrorSignal(argv[0]);
298   PrettyStackTraceProgram X(argc, argv);
299   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
300   cl::ParseCommandLineOptions(argc, argv, "llvm objcopy utility\n");
301   ToolName = argv[0];
302   if (InputFilename.empty()) {
303     cl::PrintHelpMessage();
304     return 2;
305   }
306   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(InputFilename);
307   if (!BinaryOrErr)
308     reportError(InputFilename, BinaryOrErr.takeError());
309   Binary &Binary = *BinaryOrErr.get().getBinary();
310   if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(&Binary)) {
311     CopyBinary(*o);
312     return 0;
313   }
314   if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(&Binary)) {
315     CopyBinary(*o);
316     return 0;
317   }
318   if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(&Binary)) {
319     CopyBinary(*o);
320     return 0;
321   }
322   if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(&Binary)) {
323     CopyBinary(*o);
324     return 0;
325   }
326   reportError(InputFilename, object_error::invalid_file_type);
327 }
328