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/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"
60 #include <system_error>
64 using namespace llvm::objcopy
;
65 using namespace llvm::object
;
67 // The name this program was invoked as.
68 static StringRef ToolName
;
70 static ErrorSuccess
reportWarning(Error E
) {
72 WithColor::warning(errs(), ToolName
) << toString(std::move(E
)) << '\n';
73 return Error::success();
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:
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()]));
90 if (Is("bitcode-strip") || Is("bitcode_strip"))
91 return parseBitcodeStripOptions(Args
, reportWarning
);
93 return parseStripOptions(Args
, reportWarning
);
94 else if (Is("install-name-tool") || Is("install_name_tool"))
95 return parseInstallNameToolOptions(Args
);
97 return parseObjcopyOptions(Args
, reportWarning
);
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
,
104 // TODO: support output formats other than ELF.
105 Expected
<const ELFConfig
&> ELFConfig
= ConfigMgr
.getELFConfig();
107 return ELFConfig
.takeError();
109 return elf::executeObjcopyOnIHex(ConfigMgr
.getCommonConfig(), *ELFConfig
, In
,
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();
128 return ELFConfig
.takeError();
130 return elf::executeObjcopyOnRawBinary(Config
, *ELFConfig
, In
, Out
);
133 llvm_unreachable("unsupported output format");
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
;
142 Expected
<FilePermissionsApplier
> PermsApplierOrErr
=
143 FilePermissionsApplier::create(Config
.InputFilename
);
144 if (!PermsApplierOrErr
)
145 return PermsApplierOrErr
.takeError();
147 std::function
<Error(raw_ostream
& OutFile
)> ObjcopyFunc
;
149 OwningBinary
<llvm::object::Binary
> BinaryHolder
;
150 std::unique_ptr
<MemoryBuffer
> MemoryBufferHolder
;
152 if (Config
.InputFormat
== FileFormat::Binary
||
153 Config
.InputFormat
== FileFormat::IHex
) {
154 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
155 MemoryBuffer::getFileOrSTDIN(Config
.InputFilename
);
157 return createFileError(Config
.InputFilename
, BufOrErr
.getError());
158 MemoryBufferHolder
= std::move(*BufOrErr
);
160 if (Config
.InputFormat
== FileFormat::Binary
)
161 ObjcopyFunc
= [&](raw_ostream
&OutFile
) -> Error
{
162 // Handle FileFormat::Binary.
163 return executeObjcopyOnRawBinary(ConfigMgr
, *MemoryBufferHolder
,
167 ObjcopyFunc
= [&](raw_ostream
&OutFile
) -> Error
{
168 // Handle FileFormat::IHex.
169 return executeObjcopyOnIHex(ConfigMgr
, *MemoryBufferHolder
, OutFile
);
172 Expected
<OwningBinary
<llvm::object::Binary
>> BinaryOrErr
=
173 createBinary(Config
.InputFilename
);
175 return createFileError(Config
.InputFilename
, BinaryOrErr
.takeError());
176 BinaryHolder
= std::move(*BinaryOrErr
);
178 if (Archive
*Ar
= dyn_cast
<Archive
>(BinaryHolder
.getBinary())) {
180 if (Error E
= executeObjcopyOnArchive(ConfigMgr
, *Ar
))
183 // Handle llvm::object::Binary.
184 ObjcopyFunc
= [&](raw_ostream
&OutFile
) -> Error
{
185 return executeObjcopyOnBinary(ConfigMgr
, *BinaryHolder
.getBinary(),
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
))
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
))
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
209 if (Error E
= writeToOutput(Config
.OutputFilename
, ObjcopyFunc
))
215 PermsApplierOrErr
->apply(Config
.OutputFilename
, Config
.PreserveDates
))
218 if (!Config
.SplitDWO
.empty())
220 PermsApplierOrErr
->apply(Config
.SplitDWO
, Config
.PreserveDates
,
221 static_cast<sys::fs::perms
>(0666)))
224 return Error::success();
227 int llvm_objcopy_main(int argc
, char **argv
, const llvm::ToolContext
&) {
228 InitLLVM
X(argc
, argv
);
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
);
237 StringSaver
Saver(A
);
238 cl::ExpandResponseFiles(Saver
,
239 Triple(sys::getProcessTriple()).isOSWindows()
240 ? cl::TokenizeWindowsCommandLine
241 : cl::TokenizeGNUCommandLine
,
244 auto Args
= ArrayRef(NewArgv
).drop_front();
245 Expected
<DriverConfig
> DriverConfig
= getDriverConfig(Args
);
248 logAllUnhandledErrors(DriverConfig
.takeError(),
249 WithColor::error(errs(), ToolName
));
252 for (ConfigManager
&ConfigMgr
: DriverConfig
->CopyConfigs
) {
253 if (Error E
= executeObjcopy(ConfigMgr
)) {
254 logAllUnhandledErrors(std::move(E
), WithColor::error(errs(), ToolName
));