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 "llvm-objcopy.h"
11 #include "COFF/COFFObjcopy.h"
12 #include "CopyConfig.h"
13 #include "ELF/ELFObjcopy.h"
14 #include "MachO/MachOObjcopy.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ArchiveWriter.h"
22 #include "llvm/Object/Binary.h"
23 #include "llvm/Object/COFF.h"
24 #include "llvm/Object/ELFObjectFile.h"
25 #include "llvm/Object/ELFTypes.h"
26 #include "llvm/Object/Error.h"
27 #include "llvm/Object/MachO.h"
28 #include "llvm/Option/Arg.h"
29 #include "llvm/Option/ArgList.h"
30 #include "llvm/Option/Option.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/Error.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ErrorOr.h"
35 #include "llvm/Support/InitLLVM.h"
36 #include "llvm/Support/Memory.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/WithColor.h"
40 #include "llvm/Support/raw_ostream.h"
46 #include <system_error>
52 // The name this program was invoked as.
55 LLVM_ATTRIBUTE_NORETURN
void error(Twine Message
) {
56 WithColor::error(errs(), ToolName
) << Message
<< ".\n";
61 LLVM_ATTRIBUTE_NORETURN
void error(Error E
) {
64 raw_string_ostream
OS(Buf
);
65 logAllUnhandledErrors(std::move(E
), OS
);
67 WithColor::error(errs(), ToolName
) << Buf
;
71 LLVM_ATTRIBUTE_NORETURN
void reportError(StringRef File
, std::error_code EC
) {
73 error(createFileError(File
, EC
));
76 LLVM_ATTRIBUTE_NORETURN
void reportError(StringRef File
, Error E
) {
79 raw_string_ostream
OS(Buf
);
80 logAllUnhandledErrors(std::move(E
), OS
);
82 WithColor::error(errs(), ToolName
) << "'" << File
<< "': " << Buf
;
86 } // end namespace objcopy
87 } // end namespace llvm
90 using namespace llvm::object
;
91 using namespace llvm::objcopy
;
93 // For regular archives this function simply calls llvm::writeArchive,
94 // For thin archives it writes the archive file itself as well as its members.
95 static Error
deepWriteArchive(StringRef ArcName
,
96 ArrayRef
<NewArchiveMember
> NewMembers
,
97 bool WriteSymtab
, object::Archive::Kind Kind
,
98 bool Deterministic
, bool Thin
) {
99 if (Error E
= writeArchive(ArcName
, NewMembers
, WriteSymtab
, Kind
,
100 Deterministic
, Thin
))
101 return createFileError(ArcName
, std::move(E
));
104 return Error::success();
106 for (const NewArchiveMember
&Member
: NewMembers
) {
107 // Internally, FileBuffer will use the buffer created by
108 // FileOutputBuffer::create, for regular files (that is the case for
109 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
110 // OnDiskBuffer uses a temporary file and then renames it. So in reality
111 // there is no inefficiency / duplicated in-memory buffers in this case. For
112 // now in-memory buffers can not be completely avoided since
113 // NewArchiveMember still requires them even though writeArchive does not
114 // write them on disk.
115 FileBuffer
FB(Member
.MemberName
);
116 if (Error E
= FB
.allocate(Member
.Buf
->getBufferSize()))
118 std::copy(Member
.Buf
->getBufferStart(), Member
.Buf
->getBufferEnd(),
119 FB
.getBufferStart());
120 if (Error E
= FB
.commit())
123 return Error::success();
126 /// The function executeObjcopyOnRawBinary does the dispatch based on the format
127 /// of the output specified by the command line options.
128 static Error
executeObjcopyOnRawBinary(const CopyConfig
&Config
,
129 MemoryBuffer
&In
, Buffer
&Out
) {
130 // TODO: llvm-objcopy should parse CopyConfig.OutputFormat to recognize
131 // formats other than ELF / "binary" and invoke
132 // elf::executeObjcopyOnRawBinary, macho::executeObjcopyOnRawBinary or
133 // coff::executeObjcopyOnRawBinary accordingly.
134 return elf::executeObjcopyOnRawBinary(Config
, In
, Out
);
137 /// The function executeObjcopyOnBinary does the dispatch based on the format
138 /// of the input binary (ELF, MachO or COFF).
139 static Error
executeObjcopyOnBinary(const CopyConfig
&Config
,
140 object::Binary
&In
, Buffer
&Out
) {
141 if (auto *ELFBinary
= dyn_cast
<object::ELFObjectFileBase
>(&In
))
142 return elf::executeObjcopyOnBinary(Config
, *ELFBinary
, Out
);
143 else if (auto *COFFBinary
= dyn_cast
<object::COFFObjectFile
>(&In
))
144 return coff::executeObjcopyOnBinary(Config
, *COFFBinary
, Out
);
145 else if (auto *MachOBinary
= dyn_cast
<object::MachOObjectFile
>(&In
))
146 return macho::executeObjcopyOnBinary(Config
, *MachOBinary
, Out
);
148 return createStringError(object_error::invalid_file_type
,
149 "Unsupported object file format");
152 static Error
executeObjcopyOnArchive(const CopyConfig
&Config
,
154 std::vector
<NewArchiveMember
> NewArchiveMembers
;
155 Error Err
= Error::success();
156 for (const Archive::Child
&Child
: Ar
.children(Err
)) {
157 Expected
<std::unique_ptr
<Binary
>> ChildOrErr
= Child
.getAsBinary();
159 return createFileError(Ar
.getFileName(), ChildOrErr
.takeError());
160 Binary
*Bin
= ChildOrErr
->get();
162 Expected
<StringRef
> ChildNameOrErr
= Child
.getName();
164 return createFileError(Ar
.getFileName(), ChildNameOrErr
.takeError());
166 MemBuffer
MB(ChildNameOrErr
.get());
167 if (Error E
= executeObjcopyOnBinary(Config
, *Bin
, MB
))
170 Expected
<NewArchiveMember
> Member
=
171 NewArchiveMember::getOldMember(Child
, Config
.DeterministicArchives
);
173 return createFileError(Ar
.getFileName(), Member
.takeError());
174 Member
->Buf
= MB
.releaseMemoryBuffer();
175 Member
->MemberName
= Member
->Buf
->getBufferIdentifier();
176 NewArchiveMembers
.push_back(std::move(*Member
));
179 return createFileError(Config
.InputFilename
, std::move(Err
));
181 return deepWriteArchive(Config
.OutputFilename
, NewArchiveMembers
,
182 Ar
.hasSymbolTable(), Ar
.kind(),
183 Config
.DeterministicArchives
, Ar
.isThin());
186 static void restoreDateOnFile(StringRef Filename
,
187 const sys::fs::file_status
&Stat
) {
191 sys::fs::openFileForWrite(Filename
, FD
, sys::fs::CD_OpenExisting
))
192 reportError(Filename
, EC
);
194 if (auto EC
= sys::fs::setLastAccessAndModificationTime(
195 FD
, Stat
.getLastAccessedTime(), Stat
.getLastModificationTime()))
196 reportError(Filename
, EC
);
198 if (auto EC
= sys::Process::SafelyCloseFileDescriptor(FD
))
199 reportError(Filename
, EC
);
202 /// The function executeObjcopy does the higher level dispatch based on the type
203 /// of input (raw binary, archive or single object file) and takes care of the
204 /// format-agnostic modifications, i.e. preserving dates.
205 static void executeObjcopy(const CopyConfig
&Config
) {
206 sys::fs::file_status Stat
;
207 if (Config
.PreserveDates
)
208 if (auto EC
= sys::fs::status(Config
.InputFilename
, Stat
))
209 reportError(Config
.InputFilename
, EC
);
211 if (Config
.InputFormat
== "binary") {
212 auto BufOrErr
= MemoryBuffer::getFile(Config
.InputFilename
);
214 reportError(Config
.InputFilename
, BufOrErr
.getError());
215 FileBuffer
FB(Config
.OutputFilename
);
216 if (Error E
= executeObjcopyOnRawBinary(Config
, *BufOrErr
->get(), FB
))
219 Expected
<OwningBinary
<llvm::object::Binary
>> BinaryOrErr
=
220 createBinary(Config
.InputFilename
);
222 reportError(Config
.InputFilename
, BinaryOrErr
.takeError());
224 if (Archive
*Ar
= dyn_cast
<Archive
>(BinaryOrErr
.get().getBinary())) {
225 if (Error E
= executeObjcopyOnArchive(Config
, *Ar
))
228 FileBuffer
FB(Config
.OutputFilename
);
229 if (Error E
= executeObjcopyOnBinary(Config
,
230 *BinaryOrErr
.get().getBinary(), FB
))
235 if (Config
.PreserveDates
) {
236 restoreDateOnFile(Config
.OutputFilename
, Stat
);
237 if (!Config
.SplitDWO
.empty())
238 restoreDateOnFile(Config
.SplitDWO
, Stat
);
242 int main(int argc
, char **argv
) {
243 InitLLVM
X(argc
, argv
);
245 DriverConfig DriverConfig
;
246 if (sys::path::stem(ToolName
).contains("strip"))
247 DriverConfig
= parseStripOptions(makeArrayRef(argv
+ 1, argc
));
249 DriverConfig
= parseObjcopyOptions(makeArrayRef(argv
+ 1, argc
));
250 for (const CopyConfig
&CopyConfig
: DriverConfig
.CopyConfigs
)
251 executeObjcopy(CopyConfig
);