1 //===- llvm-objcopy.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ObjcopyOptions.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/BinaryFormat/ELF.h"
15 #include "llvm/ObjCopy/COFF/COFFConfig.h"
16 #include "llvm/ObjCopy/COFF/COFFObjcopy.h"
17 #include "llvm/ObjCopy/CommonConfig.h"
18 #include "llvm/ObjCopy/ELF/ELFConfig.h"
19 #include "llvm/ObjCopy/ELF/ELFObjcopy.h"
20 #include "llvm/ObjCopy/MachO/MachOConfig.h"
21 #include "llvm/ObjCopy/MachO/MachOObjcopy.h"
22 #include "llvm/ObjCopy/ObjCopy.h"
23 #include "llvm/ObjCopy/wasm/WasmConfig.h"
24 #include "llvm/ObjCopy/wasm/WasmObjcopy.h"
25 #include "llvm/Object/Archive.h"
26 #include "llvm/Object/ArchiveWriter.h"
27 #include "llvm/Object/Binary.h"
28 #include "llvm/Object/COFF.h"
29 #include "llvm/Object/ELFObjectFile.h"
30 #include "llvm/Object/ELFTypes.h"
31 #include "llvm/Object/Error.h"
32 #include "llvm/Object/MachO.h"
33 #include "llvm/Object/MachOUniversal.h"
34 #include "llvm/Object/Wasm.h"
35 #include "llvm/Option/Arg.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Option/Option.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Errc.h"
41 #include "llvm/Support/Error.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/ErrorOr.h"
44 #include "llvm/Support/FileUtilities.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/LLVMDriver.h"
47 #include "llvm/Support/Memory.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/Process.h"
50 #include "llvm/Support/SmallVectorMemoryBuffer.h"
51 #include "llvm/Support/StringSaver.h"
52 #include "llvm/Support/WithColor.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/TargetParser/Host.h"
55 #include <algorithm>
56 #include <cassert>
57 #include <cstdlib>
58 #include <memory>
59 #include <string>
60 #include <system_error>
61 #include <utility>
62 
63 using namespace llvm;
64 using namespace llvm::objcopy;
65 using namespace llvm::object;
66 
67 // The name this program was invoked as.
68 static StringRef ToolName;
69 
70 static ErrorSuccess reportWarning(Error E) {
71   assert(E);
72   WithColor::warning(errs(), ToolName) << toString(std::move(E)) << '\n';
73   return Error::success();
74 }
75 
76 static Expected<DriverConfig> getDriverConfig(ArrayRef<const char *> Args) {
77   StringRef Stem = sys::path::stem(ToolName);
78   auto Is = [=](StringRef Tool) {
79     // We need to recognize the following filenames:
80     //
81     // llvm-objcopy -> objcopy
82     // strip-10.exe -> strip
83     // powerpc64-unknown-freebsd13-objcopy -> objcopy
84     // llvm-install-name-tool -> install-name-tool
85     auto I = Stem.rfind_insensitive(Tool);
86     return I != StringRef::npos &&
87            (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
88   };
89 
90   if (Is("bitcode-strip") || Is("bitcode_strip"))
91     return parseBitcodeStripOptions(Args, reportWarning);
92   else if (Is("strip"))
93     return parseStripOptions(Args, reportWarning);
94   else if (Is("install-name-tool") || Is("install_name_tool"))
95     return parseInstallNameToolOptions(Args);
96   else
97     return parseObjcopyOptions(Args, reportWarning);
98 }
99 
100 /// The function executeObjcopyOnIHex does the dispatch based on the format
101 /// of the output specified by the command line options.
102 static Error executeObjcopyOnIHex(ConfigManager &ConfigMgr, MemoryBuffer &In,
103                                   raw_ostream &Out) {
104   // TODO: support output formats other than ELF.
105   Expected<const ELFConfig &> ELFConfig = ConfigMgr.getELFConfig();
106   if (!ELFConfig)
107     return ELFConfig.takeError();
108 
109   return elf::executeObjcopyOnIHex(ConfigMgr.getCommonConfig(), *ELFConfig, In,
110                                    Out);
111 }
112 
113 /// The function executeObjcopyOnRawBinary does the dispatch based on the format
114 /// of the output specified by the command line options.
115 static Error executeObjcopyOnRawBinary(ConfigManager &ConfigMgr,
116                                        MemoryBuffer &In, raw_ostream &Out) {
117   const CommonConfig &Config = ConfigMgr.getCommonConfig();
118   switch (Config.OutputFormat) {
119   case FileFormat::ELF:
120   // FIXME: Currently, we call elf::executeObjcopyOnRawBinary even if the
121   // output format is binary/ihex or it's not given. This behavior differs from
122   // GNU objcopy. See https://bugs.llvm.org/show_bug.cgi?id=42171 for details.
123   case FileFormat::Binary:
124   case FileFormat::IHex:
125   case FileFormat::Unspecified:
126     Expected<const ELFConfig &> ELFConfig = ConfigMgr.getELFConfig();
127     if (!ELFConfig)
128       return ELFConfig.takeError();
129 
130     return elf::executeObjcopyOnRawBinary(Config, *ELFConfig, In, Out);
131   }
132 
133   llvm_unreachable("unsupported output format");
134 }
135 
136 /// The function executeObjcopy does the higher level dispatch based on the type
137 /// of input (raw binary, archive or single object file) and takes care of the
138 /// format-agnostic modifications, i.e. preserving dates.
139 static Error executeObjcopy(ConfigManager &ConfigMgr) {
140   CommonConfig &Config = ConfigMgr.Common;
141 
142   Expected<FilePermissionsApplier> PermsApplierOrErr =
143       FilePermissionsApplier::create(Config.InputFilename);
144   if (!PermsApplierOrErr)
145     return PermsApplierOrErr.takeError();
146 
147   std::function<Error(raw_ostream & OutFile)> ObjcopyFunc;
148 
149   OwningBinary<llvm::object::Binary> BinaryHolder;
150   std::unique_ptr<MemoryBuffer> MemoryBufferHolder;
151 
152   if (Config.InputFormat == FileFormat::Binary ||
153       Config.InputFormat == FileFormat::IHex) {
154     ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
155         MemoryBuffer::getFileOrSTDIN(Config.InputFilename);
156     if (!BufOrErr)
157       return createFileError(Config.InputFilename, BufOrErr.getError());
158     MemoryBufferHolder = std::move(*BufOrErr);
159 
160     if (Config.InputFormat == FileFormat::Binary)
161       ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
162         // Handle FileFormat::Binary.
163         return executeObjcopyOnRawBinary(ConfigMgr, *MemoryBufferHolder,
164                                          OutFile);
165       };
166     else
167       ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
168         // Handle FileFormat::IHex.
169         return executeObjcopyOnIHex(ConfigMgr, *MemoryBufferHolder, OutFile);
170       };
171   } else {
172     Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
173         createBinary(Config.InputFilename);
174     if (!BinaryOrErr)
175       return createFileError(Config.InputFilename, BinaryOrErr.takeError());
176     BinaryHolder = std::move(*BinaryOrErr);
177 
178     if (Archive *Ar = dyn_cast<Archive>(BinaryHolder.getBinary())) {
179       // Handle Archive.
180       if (Error E = executeObjcopyOnArchive(ConfigMgr, *Ar))
181         return E;
182     } else {
183       // Handle llvm::object::Binary.
184       ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
185         return executeObjcopyOnBinary(ConfigMgr, *BinaryHolder.getBinary(),
186                                       OutFile);
187       };
188     }
189   }
190 
191   if (ObjcopyFunc) {
192     if (Config.SplitDWO.empty()) {
193       // Apply transformations described by Config and store result into
194       // Config.OutputFilename using specified ObjcopyFunc function.
195       if (Error E = writeToOutput(Config.OutputFilename, ObjcopyFunc))
196         return E;
197     } else {
198       Config.ExtractDWO = true;
199       Config.StripDWO = false;
200       // Copy .dwo tables from the Config.InputFilename into Config.SplitDWO
201       // file using specified ObjcopyFunc function.
202       if (Error E = writeToOutput(Config.SplitDWO, ObjcopyFunc))
203         return E;
204       Config.ExtractDWO = false;
205       Config.StripDWO = true;
206       // Apply transformations described by Config, remove .dwo tables and
207       // store result into Config.OutputFilename using specified ObjcopyFunc
208       // function.
209       if (Error E = writeToOutput(Config.OutputFilename, ObjcopyFunc))
210         return E;
211     }
212   }
213 
214   if (Error E =
215           PermsApplierOrErr->apply(Config.OutputFilename, Config.PreserveDates))
216     return E;
217 
218   if (!Config.SplitDWO.empty())
219     if (Error E =
220             PermsApplierOrErr->apply(Config.SplitDWO, Config.PreserveDates,
221                                      static_cast<sys::fs::perms>(0666)))
222       return E;
223 
224   return Error::success();
225 }
226 
227 int llvm_objcopy_main(int argc, char **argv, const llvm::ToolContext &) {
228   InitLLVM X(argc, argv);
229   ToolName = argv[0];
230 
231   // Expand response files.
232   // TODO: Move these lines, which are copied from lib/Support/CommandLine.cpp,
233   // into a separate function in the CommandLine library and call that function
234   // here. This is duplicated code.
235   SmallVector<const char *, 20> NewArgv(argv, argv + argc);
236   BumpPtrAllocator A;
237   StringSaver Saver(A);
238   cl::ExpandResponseFiles(Saver,
239                           Triple(sys::getProcessTriple()).isOSWindows()
240                               ? cl::TokenizeWindowsCommandLine
241                               : cl::TokenizeGNUCommandLine,
242                           NewArgv);
243 
244   auto Args = ArrayRef(NewArgv).drop_front();
245   Expected<DriverConfig> DriverConfig = getDriverConfig(Args);
246 
247   if (!DriverConfig) {
248     logAllUnhandledErrors(DriverConfig.takeError(),
249                           WithColor::error(errs(), ToolName));
250     return 1;
251   }
252   for (ConfigManager &ConfigMgr : DriverConfig->CopyConfigs) {
253     if (Error E = executeObjcopy(ConfigMgr)) {
254       logAllUnhandledErrors(std::move(E), WithColor::error(errs(), ToolName));
255       return 1;
256     }
257   }
258 
259   return 0;
260 }
261