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/SmallVector.h"
11#include "llvm/ADT/StringRef.h"
12#include "llvm/ADT/Twine.h"
13#include "llvm/ObjCopy/COFF/COFFObjcopy.h"
14#include "llvm/ObjCopy/CommonConfig.h"
15#include "llvm/ObjCopy/ELF/ELFConfig.h"
16#include "llvm/ObjCopy/ELF/ELFObjcopy.h"
17#include "llvm/ObjCopy/MachO/MachOObjcopy.h"
18#include "llvm/ObjCopy/ObjCopy.h"
19#include "llvm/ObjCopy/wasm/WasmObjcopy.h"
20#include "llvm/Object/Archive.h"
21#include "llvm/Object/Binary.h"
22#include "llvm/Object/COFF.h"
23#include "llvm/Object/Error.h"
24#include "llvm/Object/MachOUniversal.h"
25#include "llvm/Option/Arg.h"
26#include "llvm/Option/ArgList.h"
27#include "llvm/Option/Option.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Error.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/ErrorOr.h"
33#include "llvm/Support/FileUtilities.h"
34#include "llvm/Support/LLVMDriver.h"
35#include "llvm/Support/Memory.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Process.h"
38#include "llvm/Support/StringSaver.h"
39#include "llvm/Support/WithColor.h"
40#include "llvm/Support/raw_ostream.h"
41#include "llvm/TargetParser/Host.h"
42#include <cassert>
43#include <cstdlib>
44#include <memory>
45#include <utility>
46
47using namespace llvm;
48using namespace llvm::objcopy;
49using namespace llvm::object;
50
51// The name this program was invoked as.
52static StringRef ToolName;
53
54static ErrorSuccess reportWarning(Error E) {
55 assert(E);
56 WithColor::warning(OS&: errs(), Prefix: ToolName) << toString(E: std::move(E)) << '\n';
57 return Error::success();
58}
59
60static Expected<DriverConfig> getDriverConfig(ArrayRef<const char *> Args) {
61 StringRef Stem = sys::path::stem(path: ToolName);
62 auto Is = [=](StringRef Tool) {
63 // We need to recognize the following filenames:
64 //
65 // llvm-objcopy -> objcopy
66 // strip-10.exe -> strip
67 // powerpc64-unknown-freebsd13-objcopy -> objcopy
68 // llvm-install-name-tool -> install-name-tool
69 auto I = Stem.rfind_insensitive(Str: Tool);
70 return I != StringRef::npos &&
71 (I + Tool.size() == Stem.size() || !isAlnum(C: Stem[I + Tool.size()]));
72 };
73
74 if (Is("bitcode-strip") || Is("bitcode_strip"))
75 return parseBitcodeStripOptions(ArgsArr: Args, ErrorCallback: reportWarning);
76
77 if (Is("strip"))
78 return parseStripOptions(ArgsArr: Args, ErrorCallback: reportWarning);
79
80 if (Is("install-name-tool") || Is("install_name_tool"))
81 return parseInstallNameToolOptions(ArgsArr: Args);
82
83 if (Is("llvm-extract-bundle-entry")) {
84 Expected<SmallVector<StringRef>> ArgsOrErr =
85 parseExtractBundleEntryOptions(ArgsArr: Args);
86 if (!ArgsOrErr)
87 return ArgsOrErr.takeError();
88 if (Error Err = runExtractBundleEntry(Args: *ArgsOrErr))
89 return Err;
90
91 // The functionality of llvm-extract-bundle-entry is completely
92 // handled in runExtractBundleEntry, so we can exit(0) here.
93 std::exit(status: 0);
94 }
95 return parseObjcopyOptions(ArgsArr: Args, ErrorCallback: reportWarning);
96}
97
98/// The function executeObjcopyOnIHex does the dispatch based on the format
99/// of the output specified by the command line options.
100static 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(Config: ConfigMgr.getCommonConfig(), ELFConfig: *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.
113static 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 case FileFormat::SREC:
125 Expected<const ELFConfig &> ELFConfig = ConfigMgr.getELFConfig();
126 if (!ELFConfig)
127 return ELFConfig.takeError();
128
129 return elf::executeObjcopyOnRawBinary(Config, ELFConfig: *ELFConfig, In, Out);
130 }
131
132 llvm_unreachable("unsupported output format");
133}
134
135/// Returns the format name string for explicit file formats (binary, ihex,
136/// srec). Returns "" for all other formats so callers can fall back to the
137/// input object's own format string (e.g. "elf64-x86-64").
138static StringRef toFileFormatName(FileFormat Fmt) {
139 switch (Fmt) {
140 case FileFormat::Binary:
141 return "binary";
142 case FileFormat::IHex:
143 return "ihex";
144 case FileFormat::SREC:
145 return "srec";
146 default:
147 return "";
148 }
149}
150
151/// The function executeObjcopy does the higher level dispatch based on the type
152/// of input (raw binary, archive or single object file) and takes care of the
153/// format-agnostic modifications, i.e. preserving dates.
154static Error executeObjcopy(ConfigManager &ConfigMgr) {
155 CommonConfig &Config = ConfigMgr.Common;
156
157 Expected<FilePermissionsApplier> PermsApplierOrErr =
158 FilePermissionsApplier::create(InputFilename: Config.InputFilename);
159 if (!PermsApplierOrErr)
160 return PermsApplierOrErr.takeError();
161
162 std::function<Error(raw_ostream & OutFile)> ObjcopyFunc;
163
164 OwningBinary<llvm::object::Binary> BinaryHolder;
165 std::unique_ptr<MemoryBuffer> MemoryBufferHolder;
166
167 if (Config.InputFormat == FileFormat::Binary ||
168 Config.InputFormat == FileFormat::IHex) {
169 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
170 MemoryBuffer::getFileOrSTDIN(Filename: Config.InputFilename);
171 if (!BufOrErr)
172 return createFileError(F: Config.InputFilename, EC: BufOrErr.getError());
173 MemoryBufferHolder = std::move(*BufOrErr);
174
175 if (Config.Verbose)
176 printCopyMessage(
177 InPath: Config.InputFilename, InFormatName: toFileFormatName(Fmt: Config.InputFormat),
178 OutPath: Config.OutputFilename, OutFormatName: toFileFormatName(Fmt: Config.OutputFormat));
179
180 if (Config.InputFormat == FileFormat::Binary)
181 ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
182 // Handle FileFormat::Binary.
183 return executeObjcopyOnRawBinary(ConfigMgr, In&: *MemoryBufferHolder,
184 Out&: OutFile);
185 };
186 else
187 ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
188 // Handle FileFormat::IHex.
189 return executeObjcopyOnIHex(ConfigMgr, In&: *MemoryBufferHolder, Out&: OutFile);
190 };
191 } else {
192 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
193 createBinary(Path: Config.InputFilename);
194 if (!BinaryOrErr)
195 return createFileError(F: Config.InputFilename, E: BinaryOrErr.takeError());
196 BinaryHolder = std::move(*BinaryOrErr);
197
198 if (Archive *Ar = dyn_cast<Archive>(Val: BinaryHolder.getBinary())) {
199 if (Error E = executeObjcopyOnArchive(Config: ConfigMgr, Ar: *Ar))
200 return E;
201 } else {
202 if (Config.Verbose)
203 printCopyMessage(InPath: Config.InputFilename,
204 InFormatName: getObjectFormatName(B: *BinaryHolder.getBinary()),
205 OutPath: Config.OutputFilename,
206 OutFormatName: toFileFormatName(Fmt: Config.OutputFormat));
207 // Handle llvm::object::Binary.
208 ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
209 return executeObjcopyOnBinary(Config: ConfigMgr, In&: *BinaryHolder.getBinary(),
210 Out&: OutFile);
211 };
212 }
213 }
214
215 if (ObjcopyFunc) {
216 if (Config.SplitDWO.empty()) {
217 // Apply transformations described by Config and store result into
218 // Config.OutputFilename using specified ObjcopyFunc function.
219 if (Error E = writeToOutput(OutputFileName: Config.OutputFilename, Write: ObjcopyFunc))
220 return E;
221 } else {
222 Config.ExtractDWO = true;
223 Config.StripDWO = false;
224 // Copy .dwo tables from the Config.InputFilename into Config.SplitDWO
225 // file using specified ObjcopyFunc function.
226 if (Error E = writeToOutput(OutputFileName: Config.SplitDWO, Write: ObjcopyFunc))
227 return E;
228 Config.ExtractDWO = false;
229 Config.StripDWO = true;
230 // Apply transformations described by Config, remove .dwo tables and
231 // store result into Config.OutputFilename using specified ObjcopyFunc
232 // function.
233 if (Error E = writeToOutput(OutputFileName: Config.OutputFilename, Write: ObjcopyFunc))
234 return E;
235 }
236 }
237
238 if (Error E =
239 PermsApplierOrErr->apply(OutputFilename: Config.OutputFilename, CopyDates: Config.PreserveDates))
240 return E;
241
242 if (!Config.SplitDWO.empty())
243 if (Error E =
244 PermsApplierOrErr->apply(OutputFilename: Config.SplitDWO, CopyDates: Config.PreserveDates,
245 OverwritePermissions: static_cast<sys::fs::perms>(0666)))
246 return E;
247
248 return Error::success();
249}
250
251int llvm_objcopy_main(int argc, char **argv, const llvm::ToolContext &) {
252 ToolName = argv[0];
253
254 // Expand response files.
255 // TODO: Move these lines, which are copied from lib/Support/CommandLine.cpp,
256 // into a separate function in the CommandLine library and call that function
257 // here. This is duplicated code.
258 SmallVector<const char *, 20> NewArgv(argv, argv + argc);
259 BumpPtrAllocator A;
260 StringSaver Saver(A);
261 cl::ExpandResponseFiles(Saver,
262 Tokenizer: Triple(sys::getProcessTriple()).isOSWindows()
263 ? cl::TokenizeWindowsCommandLine
264 : cl::TokenizeGNUCommandLine,
265 Argv&: NewArgv);
266
267 auto Args = ArrayRef(NewArgv).drop_front();
268 Expected<DriverConfig> DriverConfig = getDriverConfig(Args);
269
270 if (!DriverConfig) {
271 logAllUnhandledErrors(E: DriverConfig.takeError(),
272 OS&: WithColor::error(OS&: errs(), Prefix: ToolName));
273 return 1;
274 }
275
276 int ret = 0;
277 for (ConfigManager &ConfigMgr : DriverConfig->CopyConfigs) {
278 assert(!ConfigMgr.Common.ErrorCallback);
279 ConfigMgr.Common.ErrorCallback = reportWarning;
280 if (Error E = executeObjcopy(ConfigMgr)) {
281 logAllUnhandledErrors(E: std::move(E), OS&: WithColor::error(OS&: errs(), Prefix: ToolName));
282 ret = 1;
283 }
284 }
285
286 return ret;
287}
288