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 return parseObjcopyOptions(ArgsArr: Args, ErrorCallback: reportWarning);
84}
85
86/// The function executeObjcopyOnIHex does the dispatch based on the format
87/// of the output specified by the command line options.
88static Error executeObjcopyOnIHex(ConfigManager &ConfigMgr, MemoryBuffer &In,
89 raw_ostream &Out) {
90 // TODO: support output formats other than ELF.
91 Expected<const ELFConfig &> ELFConfig = ConfigMgr.getELFConfig();
92 if (!ELFConfig)
93 return ELFConfig.takeError();
94
95 return elf::executeObjcopyOnIHex(Config: ConfigMgr.getCommonConfig(), ELFConfig: *ELFConfig, In,
96 Out);
97}
98
99/// The function executeObjcopyOnRawBinary does the dispatch based on the format
100/// of the output specified by the command line options.
101static Error executeObjcopyOnRawBinary(ConfigManager &ConfigMgr,
102 MemoryBuffer &In, raw_ostream &Out) {
103 const CommonConfig &Config = ConfigMgr.getCommonConfig();
104 switch (Config.OutputFormat) {
105 case FileFormat::ELF:
106 // FIXME: Currently, we call elf::executeObjcopyOnRawBinary even if the
107 // output format is binary/ihex or it's not given. This behavior differs from
108 // GNU objcopy. See https://bugs.llvm.org/show_bug.cgi?id=42171 for details.
109 case FileFormat::Binary:
110 case FileFormat::IHex:
111 case FileFormat::Unspecified:
112 case FileFormat::SREC:
113 Expected<const ELFConfig &> ELFConfig = ConfigMgr.getELFConfig();
114 if (!ELFConfig)
115 return ELFConfig.takeError();
116
117 return elf::executeObjcopyOnRawBinary(Config, ELFConfig: *ELFConfig, In, Out);
118 }
119
120 llvm_unreachable("unsupported output format");
121}
122
123/// The function executeObjcopy does the higher level dispatch based on the type
124/// of input (raw binary, archive or single object file) and takes care of the
125/// format-agnostic modifications, i.e. preserving dates.
126static Error executeObjcopy(ConfigManager &ConfigMgr) {
127 CommonConfig &Config = ConfigMgr.Common;
128
129 Expected<FilePermissionsApplier> PermsApplierOrErr =
130 FilePermissionsApplier::create(InputFilename: Config.InputFilename);
131 if (!PermsApplierOrErr)
132 return PermsApplierOrErr.takeError();
133
134 std::function<Error(raw_ostream & OutFile)> ObjcopyFunc;
135
136 OwningBinary<llvm::object::Binary> BinaryHolder;
137 std::unique_ptr<MemoryBuffer> MemoryBufferHolder;
138
139 if (Config.InputFormat == FileFormat::Binary ||
140 Config.InputFormat == FileFormat::IHex) {
141 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
142 MemoryBuffer::getFileOrSTDIN(Filename: Config.InputFilename);
143 if (!BufOrErr)
144 return createFileError(F: Config.InputFilename, EC: BufOrErr.getError());
145 MemoryBufferHolder = std::move(*BufOrErr);
146
147 if (Config.InputFormat == FileFormat::Binary)
148 ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
149 // Handle FileFormat::Binary.
150 return executeObjcopyOnRawBinary(ConfigMgr, In&: *MemoryBufferHolder,
151 Out&: OutFile);
152 };
153 else
154 ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
155 // Handle FileFormat::IHex.
156 return executeObjcopyOnIHex(ConfigMgr, In&: *MemoryBufferHolder, Out&: OutFile);
157 };
158 } else {
159 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
160 createBinary(Path: Config.InputFilename);
161 if (!BinaryOrErr)
162 return createFileError(F: Config.InputFilename, E: BinaryOrErr.takeError());
163 BinaryHolder = std::move(*BinaryOrErr);
164
165 if (Archive *Ar = dyn_cast<Archive>(Val: BinaryHolder.getBinary())) {
166 // Handle Archive.
167 if (Error E = executeObjcopyOnArchive(Config: ConfigMgr, Ar: *Ar))
168 return E;
169 } else {
170 // Handle llvm::object::Binary.
171 ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
172 return executeObjcopyOnBinary(Config: ConfigMgr, In&: *BinaryHolder.getBinary(),
173 Out&: OutFile);
174 };
175 }
176 }
177
178 if (ObjcopyFunc) {
179 if (Config.SplitDWO.empty()) {
180 // Apply transformations described by Config and store result into
181 // Config.OutputFilename using specified ObjcopyFunc function.
182 if (Error E = writeToOutput(OutputFileName: Config.OutputFilename, Write: ObjcopyFunc))
183 return E;
184 } else {
185 Config.ExtractDWO = true;
186 Config.StripDWO = false;
187 // Copy .dwo tables from the Config.InputFilename into Config.SplitDWO
188 // file using specified ObjcopyFunc function.
189 if (Error E = writeToOutput(OutputFileName: Config.SplitDWO, Write: ObjcopyFunc))
190 return E;
191 Config.ExtractDWO = false;
192 Config.StripDWO = true;
193 // Apply transformations described by Config, remove .dwo tables and
194 // store result into Config.OutputFilename using specified ObjcopyFunc
195 // function.
196 if (Error E = writeToOutput(OutputFileName: Config.OutputFilename, Write: ObjcopyFunc))
197 return E;
198 }
199 }
200
201 if (Error E =
202 PermsApplierOrErr->apply(OutputFilename: Config.OutputFilename, CopyDates: Config.PreserveDates))
203 return E;
204
205 if (!Config.SplitDWO.empty())
206 if (Error E =
207 PermsApplierOrErr->apply(OutputFilename: Config.SplitDWO, CopyDates: Config.PreserveDates,
208 OverwritePermissions: static_cast<sys::fs::perms>(0666)))
209 return E;
210
211 return Error::success();
212}
213
214int llvm_objcopy_main(int argc, char **argv, const llvm::ToolContext &) {
215 ToolName = argv[0];
216
217 // Expand response files.
218 // TODO: Move these lines, which are copied from lib/Support/CommandLine.cpp,
219 // into a separate function in the CommandLine library and call that function
220 // here. This is duplicated code.
221 SmallVector<const char *, 20> NewArgv(argv, argv + argc);
222 BumpPtrAllocator A;
223 StringSaver Saver(A);
224 cl::ExpandResponseFiles(Saver,
225 Tokenizer: Triple(sys::getProcessTriple()).isOSWindows()
226 ? cl::TokenizeWindowsCommandLine
227 : cl::TokenizeGNUCommandLine,
228 Argv&: NewArgv);
229
230 auto Args = ArrayRef(NewArgv).drop_front();
231 Expected<DriverConfig> DriverConfig = getDriverConfig(Args);
232
233 if (!DriverConfig) {
234 logAllUnhandledErrors(E: DriverConfig.takeError(),
235 OS&: WithColor::error(OS&: errs(), Prefix: ToolName));
236 return 1;
237 }
238
239 int ret = 0;
240 for (ConfigManager &ConfigMgr : DriverConfig->CopyConfigs) {
241 assert(!ConfigMgr.Common.ErrorCallback);
242 ConfigMgr.Common.ErrorCallback = reportWarning;
243 if (Error E = executeObjcopy(ConfigMgr)) {
244 logAllUnhandledErrors(E: std::move(E), OS&: WithColor::error(OS&: errs(), Prefix: ToolName));
245 ret = 1;
246 }
247 }
248
249 return ret;
250}
251