blob: db29128f95eb5b7e7bc58d3255a80d010bd1a7c5 [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- llvm-objcopy.cpp ---------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Petr Hosek05a04cb2017-08-01 00:33:58 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00008
Petr Hosek05a04cb2017-08-01 00:33:58 +00009#include "llvm-objcopy.h"
Alexander Shaposhnikov3d4c4ac2018-10-16 05:40:18 +000010#include "Buffer.h"
Martin Storsjoe84a0b52018-12-19 07:24:38 +000011#include "COFF/COFFObjcopy.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000012#include "CopyConfig.h"
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +000013#include "ELF/ELFObjcopy.h"
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000014#include "MachO/MachOObjcopy.h"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000015
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000016#include "llvm/ADT/STLExtras.h"
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +000017#include "llvm/ADT/SmallVector.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000018#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000020#include "llvm/Object/Archive.h"
21#include "llvm/Object/ArchiveWriter.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000022#include "llvm/Object/Binary.h"
Martin Storsjoe84a0b52018-12-19 07:24:38 +000023#include "llvm/Object/COFF.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000024#include "llvm/Object/ELFObjectFile.h"
25#include "llvm/Object/ELFTypes.h"
26#include "llvm/Object/Error.h"
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000027#include "llvm/Object/MachO.h"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000028#include "llvm/Option/Arg.h"
29#include "llvm/Option/ArgList.h"
30#include "llvm/Option/Option.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000031#include "llvm/Support/Casting.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000032#include "llvm/Support/Error.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/ErrorOr.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000035#include "llvm/Support/InitLLVM.h"
Jordan Rupprechtcf676332018-08-17 18:51:11 +000036#include "llvm/Support/Memory.h"
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000037#include "llvm/Support/Path.h"
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +000038#include "llvm/Support/Process.h"
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000039#include "llvm/Support/WithColor.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000040#include "llvm/Support/raw_ostream.h"
41#include <algorithm>
42#include <cassert>
43#include <cstdlib>
Petr Hosek05a04cb2017-08-01 00:33:58 +000044#include <memory>
45#include <string>
46#include <system_error>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000047#include <utility>
Petr Hosek05a04cb2017-08-01 00:33:58 +000048
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000049namespace llvm {
50namespace objcopy {
51
52// The name this program was invoked as.
53StringRef ToolName;
54
55LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000056 WithColor::error(errs(), ToolName) << Message << ".\n";
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000057 errs().flush();
58 exit(1);
59}
60
Jordan Rupprecht881cae72019-01-22 23:49:16 +000061LLVM_ATTRIBUTE_NORETURN void error(Error E) {
62 assert(E);
63 std::string Buf;
64 raw_string_ostream OS(Buf);
65 logAllUnhandledErrors(std::move(E), OS);
66 OS.flush();
67 WithColor::error(errs(), ToolName) << Buf;
68 exit(1);
69}
70
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000071LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
Eugene Leviant317f9e72019-02-11 09:49:37 +000072 assert(EC);
73 error(createFileError(File, EC));
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000074}
75
76LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
77 assert(E);
78 std::string Buf;
79 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +000080 logAllUnhandledErrors(std::move(E), OS);
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000081 OS.flush();
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000082 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000083 exit(1);
84}
85
86} // end namespace objcopy
Puyan Lotfic4846a52018-07-16 22:17:05 +000087} // end namespace llvm
Jake Ehrlich5de70d92017-11-03 18:58:41 +000088
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +000089using namespace llvm;
90using namespace llvm::object;
91using namespace llvm::objcopy;
92
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000093// For regular archives this function simply calls llvm::writeArchive,
94// For thin archives it writes the archive file itself as well as its members.
Puyan Lotfic4846a52018-07-16 22:17:05 +000095static Error deepWriteArchive(StringRef ArcName,
96 ArrayRef<NewArchiveMember> NewMembers,
97 bool WriteSymtab, object::Archive::Kind Kind,
98 bool Deterministic, bool Thin) {
Jordan Rupprecht18886db2019-02-01 17:08:07 +000099 if (Error E = writeArchive(ArcName, NewMembers, WriteSymtab, Kind,
100 Deterministic, Thin))
101 return createFileError(ArcName, std::move(E));
102
103 if (!Thin)
104 return Error::success();
105
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000106 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);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000116 if (Error E = FB.allocate(Member.Buf->getBufferSize()))
117 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000118 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
119 FB.getBufferStart());
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000120 if (Error E = FB.commit())
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000121 return E;
122 }
123 return Error::success();
124}
125
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000126/// The function executeObjcopyOnRawBinary does the dispatch based on the format
127/// of the output specified by the command line options.
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000128static Error executeObjcopyOnRawBinary(const CopyConfig &Config,
129 MemoryBuffer &In, Buffer &Out) {
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000130 // 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);
135}
136
137/// The function executeObjcopyOnBinary does the dispatch based on the format
138/// of the input binary (ELF, MachO or COFF).
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000139static Error executeObjcopyOnBinary(const CopyConfig &Config,
140 object::Binary &In, Buffer &Out) {
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000141 if (auto *ELFBinary = dyn_cast<object::ELFObjectFileBase>(&In))
142 return elf::executeObjcopyOnBinary(Config, *ELFBinary, Out);
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000143 else if (auto *COFFBinary = dyn_cast<object::COFFObjectFile>(&In))
144 return coff::executeObjcopyOnBinary(Config, *COFFBinary, Out);
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000145 else if (auto *MachOBinary = dyn_cast<object::MachOObjectFile>(&In))
146 return macho::executeObjcopyOnBinary(Config, *MachOBinary, Out);
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000147 else
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000148 return createStringError(object_error::invalid_file_type,
149 "Unsupported object file format");
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000150}
151
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000152static Error executeObjcopyOnArchive(const CopyConfig &Config,
153 const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000154 std::vector<NewArchiveMember> NewArchiveMembers;
155 Error Err = Error::success();
156 for (const Archive::Child &Child : Ar.children(Err)) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000157 Expected<StringRef> ChildNameOrErr = Child.getName();
158 if (!ChildNameOrErr)
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000159 return createFileError(Ar.getFileName(), ChildNameOrErr.takeError());
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000160
James Henderson5a2b5ca2019-05-08 13:28:58 +0000161 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
162 if (!ChildOrErr)
163 return createFileError(Ar.getFileName() + "(" + *ChildNameOrErr + ")",
164 ChildOrErr.takeError());
165
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000166 MemBuffer MB(ChildNameOrErr.get());
James Henderson5a2b5ca2019-05-08 13:28:58 +0000167 if (Error E = executeObjcopyOnBinary(Config, *ChildOrErr->get(), MB))
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000168 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000169
170 Expected<NewArchiveMember> Member =
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000171 NewArchiveMember::getOldMember(Child, Config.DeterministicArchives);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000172 if (!Member)
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000173 return createFileError(Ar.getFileName(), Member.takeError());
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000174 Member->Buf = MB.releaseMemoryBuffer();
175 Member->MemberName = Member->Buf->getBufferIdentifier();
176 NewArchiveMembers.push_back(std::move(*Member));
177 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000178 if (Err)
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000179 return createFileError(Config.InputFilename, std::move(Err));
180
181 return deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
182 Ar.hasSymbolTable(), Ar.kind(),
183 Config.DeterministicArchives, Ar.isThin());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000184}
185
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000186static Error restoreDateOnFile(StringRef Filename,
187 const sys::fs::file_status &Stat) {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000188 int FD;
189
Jordan Rupprecht74815402018-08-29 23:21:56 +0000190 if (auto EC =
191 sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000192 return createFileError(Filename, EC);
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000193
194 if (auto EC = sys::fs::setLastAccessAndModificationTime(
195 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000196 return createFileError(Filename, EC);
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000197
198 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000199 return createFileError(Filename, EC);
200
201 return Error::success();
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000202}
203
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000204/// 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.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000207static Error executeObjcopy(const CopyConfig &Config) {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000208 sys::fs::file_status Stat;
209 if (Config.PreserveDates)
210 if (auto EC = sys::fs::status(Config.InputFilename, Stat))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000211 return createFileError(Config.InputFilename, EC);
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000212
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000213 if (Config.InputFormat == "binary") {
214 auto BufOrErr = MemoryBuffer::getFile(Config.InputFilename);
215 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000216 return createFileError(Config.InputFilename, BufOrErr.getError());
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000217 FileBuffer FB(Config.OutputFilename);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000218 if (Error E = executeObjcopyOnRawBinary(Config, *BufOrErr->get(), FB))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000219 return E;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000220 } else {
221 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
222 createBinary(Config.InputFilename);
223 if (!BinaryOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000224 return createFileError(Config.InputFilename, BinaryOrErr.takeError());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000225
226 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) {
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000227 if (Error E = executeObjcopyOnArchive(Config, *Ar))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000228 return E;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000229 } else {
230 FileBuffer FB(Config.OutputFilename);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000231 if (Error E = executeObjcopyOnBinary(Config,
232 *BinaryOrErr.get().getBinary(), FB))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000233 return E;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000234 }
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000235 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000236
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000237 if (Config.PreserveDates) {
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000238 if (Error E = restoreDateOnFile(Config.OutputFilename, Stat))
239 return E;
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000240 if (!Config.SplitDWO.empty())
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000241 if (Error E = restoreDateOnFile(Config.SplitDWO, Stat))
242 return E;
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000243 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000244
245 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000246}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000247
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000248int main(int argc, char **argv) {
249 InitLLVM X(argc, argv);
250 ToolName = argv[0];
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000251 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));
255 if (!DriverConfig) {
256 logAllUnhandledErrors(DriverConfig.takeError(),
257 WithColor::error(errs(), ToolName));
258 return 1;
259 }
260 for (const CopyConfig &CopyConfig : DriverConfig->CopyConfigs) {
261 if (Error E = executeObjcopy(CopyConfig)) {
262 logAllUnhandledErrors(std::move(E), WithColor::error(errs(), ToolName));
263 return 1;
264 }
265 }
266
267 return 0;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000268}