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 "CopyConfig.h"
12 #include "ELF/ELFObjcopy.h"
13 #include "COFF/COFFObjcopy.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<StringRef> ChildNameOrErr = Child.getName();
159 return createFileError(Ar.getFileName(), ChildNameOrErr.takeError());
161 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
163 return createFileError(Ar.getFileName() + "(" + *ChildNameOrErr + ")",
164 ChildOrErr.takeError());
166 MemBuffer MB(ChildNameOrErr.get());
167 if (Error E = executeObjcopyOnBinary(Config, *ChildOrErr->get(), 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 Error restoreDateOnFile(StringRef Filename,
187 const sys::fs::file_status &Stat) {
191 sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting))
192 return createFileError(Filename, EC);
194 if (auto EC = sys::fs::setLastAccessAndModificationTime(
195 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
196 return createFileError(Filename, EC);
198 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
199 return createFileError(Filename, EC);
201 return Error::success();
204 /// The function executeObjcopy does the higher level dispatch based on the type
205 /// of input (raw binary, archive or single object file) and takes care of the
206 /// format-agnostic modifications, i.e. preserving dates.
207 static Error executeObjcopy(const CopyConfig &Config) {
208 sys::fs::file_status Stat;
209 if (Config.PreserveDates)
210 if (auto EC = sys::fs::status(Config.InputFilename, Stat))
211 return createFileError(Config.InputFilename, EC);
213 if (Config.InputFormat == "binary") {
214 auto BufOrErr = MemoryBuffer::getFile(Config.InputFilename);
216 return createFileError(Config.InputFilename, BufOrErr.getError());
217 FileBuffer FB(Config.OutputFilename);
218 if (Error E = executeObjcopyOnRawBinary(Config, *BufOrErr->get(), FB))
221 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
222 createBinary(Config.InputFilename);
224 return createFileError(Config.InputFilename, BinaryOrErr.takeError());
226 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) {
227 if (Error E = executeObjcopyOnArchive(Config, *Ar))
230 FileBuffer FB(Config.OutputFilename);
231 if (Error E = executeObjcopyOnBinary(Config,
232 *BinaryOrErr.get().getBinary(), FB))
237 if (Config.PreserveDates) {
238 if (Error E = restoreDateOnFile(Config.OutputFilename, Stat))
240 if (!Config.SplitDWO.empty())
241 if (Error E = restoreDateOnFile(Config.SplitDWO, Stat))
245 return Error::success();
248 int main(int argc, char **argv) {
249 InitLLVM X(argc, argv);
251 bool IsStrip = sys::path::stem(ToolName).contains("strip");
252 Expected<DriverConfig> DriverConfig =
253 IsStrip ? parseStripOptions(makeArrayRef(argv + 1, argc))
254 : parseObjcopyOptions(makeArrayRef(argv + 1, argc));
256 logAllUnhandledErrors(DriverConfig.takeError(),
257 WithColor::error(errs(), ToolName));
260 for (const CopyConfig &CopyConfig : DriverConfig->CopyConfigs) {
261 if (Error E = executeObjcopy(CopyConfig)) {
262 logAllUnhandledErrors(std::move(E), WithColor::error(errs(), ToolName));