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 a specific section"));
82 static cl::alias ToRemoveA("R", cl::desc("Alias for remove-section"),
83                            cl::aliasopt(ToRemove));
84 static cl::opt<bool> StripSections("strip-sections",
85                                    cl::desc("Remove all section headers"));
86 static cl::opt<bool>
87     StripDWO("strip-dwo", cl::desc("remove all DWARF .dwo sections from file"));
88 static cl::opt<bool> ExtractDWO(
89     "extract-dwo",
90     cl::desc("remove all sections that are not DWARF .dwo sections from file"));
91 static 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"));
96 
97 using SectionPred = std::function<bool(const SectionBase &Sec)>;
98 
99 bool IsDWOSection(const SectionBase &Sec) {
100   return Sec.Name.endswith(".dwo");
101 }
102 
103 template <class ELFT>
104 bool 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 
113 template <class ELFT>
114 void WriteObjectFile(const Object<ELFT> &Obj, StringRef File) {
115   std::unique_ptr<FileOutputBuffer> Buffer;
116   Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
117       FileOutputBuffer::create(File, Obj.totalSize(),
118                                FileOutputBuffer::F_executable);
119   if (BufferOrErr.takeError())
120     error("failed to open " + OutputFilename);
121   else
122     Buffer = std::move(*BufferOrErr);
123   Obj.write(*Buffer);
124   if (auto E = Buffer->commit())
125     reportError(File, errorToErrorCode(std::move(E)));
126 }
127 
128 template <class ELFT>
129 void 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 
140 void CopyBinary(const ELFObjectFile<ELF64LE> &ObjFile) {
141   std::unique_ptr<Object<ELF64LE>> Obj;
142 
143   if (!OutputFormat.empty() && OutputFormat != "binary")
144     error("invalid output format '" + OutputFormat + "'");
145   if (!OutputFormat.empty() && OutputFormat == "binary")
146     Obj = llvm::make_unique<BinaryObject<ELF64LE>>(ObjFile);
147   else
148     Obj = llvm::make_unique<ELFObject<ELF64LE>>(ObjFile);
149 
150   if (!SplitDWO.empty())
151     SplitDWOToFile<ELF64LE>(ObjFile, SplitDWO.getValue());
152 
153   SectionPred RemovePred = [](const SectionBase &) { return false; };
154 
155   if (!ToRemove.empty()) {
156     RemovePred = [&](const SectionBase &Sec) {
157       return std::find(std::begin(ToRemove), std::end(ToRemove), Sec.Name) !=
158              std::end(ToRemove);
159     };
160   }
161 
162   if (StripDWO || !SplitDWO.empty())
163     RemovePred = [RemovePred](const SectionBase &Sec) {
164       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 
172   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);
180   Obj->finalize();
181   WriteObjectFile(*Obj, OutputFilename.getValue());
182 }
183 
184 int 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 }
205