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