1 //===- llvm-objcopy.cpp ---------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
58 #include <system_error>
62 using namespace llvm::objcopy
;
63 using namespace llvm::object
;
65 // The name this program was invoked as.
66 static StringRef ToolName
;
68 static ErrorSuccess
reportWarning(Error E
) {
70 WithColor::warning(errs(), ToolName
) << toString(std::move(E
)) << '\n';
71 return Error::success();
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:
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()]));
88 if (Is("bitcode-strip") || Is("bitcode_strip"))
89 return parseBitcodeStripOptions(Args
, reportWarning
);
91 return parseStripOptions(Args
, reportWarning
);
92 else if (Is("install-name-tool") || Is("install_name_tool"))
93 return parseInstallNameToolOptions(Args
);
95 return parseObjcopyOptions(Args
, reportWarning
);
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
,
102 // TODO: support output formats other than ELF.
103 Expected
<const ELFConfig
&> ELFConfig
= ConfigMgr
.getELFConfig();
105 return ELFConfig
.takeError();
107 return elf::executeObjcopyOnIHex(ConfigMgr
.getCommonConfig(), *ELFConfig
, In
,
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();
126 return ELFConfig
.takeError();
128 return elf::executeObjcopyOnRawBinary(Config
, *ELFConfig
, In
, Out
);
131 llvm_unreachable("unsupported output format");
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
;
140 Expected
<FilePermissionsApplier
> PermsApplierOrErr
=
141 FilePermissionsApplier::create(Config
.InputFilename
);
142 if (!PermsApplierOrErr
)
143 return PermsApplierOrErr
.takeError();
145 std::function
<Error(raw_ostream
& OutFile
)> ObjcopyFunc
;
147 OwningBinary
<llvm::object::Binary
> BinaryHolder
;
148 std::unique_ptr
<MemoryBuffer
> MemoryBufferHolder
;
150 if (Config
.InputFormat
== FileFormat::Binary
||
151 Config
.InputFormat
== FileFormat::IHex
) {
152 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
153 MemoryBuffer::getFileOrSTDIN(Config
.InputFilename
);
155 return createFileError(Config
.InputFilename
, BufOrErr
.getError());
156 MemoryBufferHolder
= std::move(*BufOrErr
);
158 if (Config
.InputFormat
== FileFormat::Binary
)
159 ObjcopyFunc
= [&](raw_ostream
&OutFile
) -> Error
{
160 // Handle FileFormat::Binary.
161 return executeObjcopyOnRawBinary(ConfigMgr
, *MemoryBufferHolder
,
165 ObjcopyFunc
= [&](raw_ostream
&OutFile
) -> Error
{
166 // Handle FileFormat::IHex.
167 return executeObjcopyOnIHex(ConfigMgr
, *MemoryBufferHolder
, OutFile
);
170 Expected
<OwningBinary
<llvm::object::Binary
>> BinaryOrErr
=
171 createBinary(Config
.InputFilename
);
173 return createFileError(Config
.InputFilename
, BinaryOrErr
.takeError());
174 BinaryHolder
= std::move(*BinaryOrErr
);
176 if (Archive
*Ar
= dyn_cast
<Archive
>(BinaryHolder
.getBinary())) {
178 if (Error E
= executeObjcopyOnArchive(ConfigMgr
, *Ar
))
181 // Handle llvm::object::Binary.
182 ObjcopyFunc
= [&](raw_ostream
&OutFile
) -> Error
{
183 return executeObjcopyOnBinary(ConfigMgr
, *BinaryHolder
.getBinary(),
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
))
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
))
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
207 if (Error E
= writeToOutput(Config
.OutputFilename
, ObjcopyFunc
))
213 PermsApplierOrErr
->apply(Config
.OutputFilename
, Config
.PreserveDates
))
216 if (!Config
.SplitDWO
.empty())
218 PermsApplierOrErr
->apply(Config
.SplitDWO
, Config
.PreserveDates
,
219 static_cast<sys::fs::perms
>(0666)))
222 return Error::success();
225 int llvm_objcopy_main(int argc
, char **argv
, const llvm::ToolContext
&) {
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
);
234 StringSaver
Saver(A
);
235 cl::ExpandResponseFiles(Saver
,
236 Triple(sys::getProcessTriple()).isOSWindows()
237 ? cl::TokenizeWindowsCommandLine
238 : cl::TokenizeGNUCommandLine
,
241 auto Args
= ArrayRef(NewArgv
).drop_front();
242 Expected
<DriverConfig
> DriverConfig
= getDriverConfig(Args
);
245 logAllUnhandledErrors(DriverConfig
.takeError(),
246 WithColor::error(errs(), ToolName
));
249 for (ConfigManager
&ConfigMgr
: DriverConfig
->CopyConfigs
) {
250 if (Error E
= executeObjcopy(ConfigMgr
)) {
251 logAllUnhandledErrors(std::move(E
), WithColor::error(errs(), ToolName
));