blob: db5609ea2294c2d4142ffc1b4cd07a13b69d5ff8 [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"
Alexander Shaposhnikov8d0b74c2018-10-11 22:33:50 +000011#include "CopyConfig.h"
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +000012#include "ELF/ELFObjcopy.h"
Alex Brachetb3498342019-06-01 07:36:57 +000013#include "COFF/COFFObjcopy.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) {
Alex Brachetd54d4f92019-06-14 02:04:02 +000056 WithColor::error(errs(), ToolName) << Message << "\n";
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000057 exit(1);
58}
59
Jordan Rupprecht881cae72019-01-22 23:49:16 +000060LLVM_ATTRIBUTE_NORETURN void error(Error E) {
61 assert(E);
62 std::string Buf;
63 raw_string_ostream OS(Buf);
64 logAllUnhandledErrors(std::move(E), OS);
65 OS.flush();
66 WithColor::error(errs(), ToolName) << Buf;
67 exit(1);
68}
69
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000070LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
Eugene Leviant317f9e72019-02-11 09:49:37 +000071 assert(EC);
72 error(createFileError(File, EC));
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000073}
74
75LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
76 assert(E);
77 std::string Buf;
78 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +000079 logAllUnhandledErrors(std::move(E), OS);
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000080 OS.flush();
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000081 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000082 exit(1);
83}
84
Alex Brachet77477002019-06-18 00:39:10 +000085ErrorSuccess reportWarning(Error E) {
86 assert(E);
87 WithColor::warning(errs(), ToolName) << toString(std::move(E));
88 return Error::success();
89}
90
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000091} // end namespace objcopy
Puyan Lotfic4846a52018-07-16 22:17:05 +000092} // end namespace llvm
Jake Ehrlich5de70d92017-11-03 18:58:41 +000093
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +000094using namespace llvm;
95using namespace llvm::object;
96using namespace llvm::objcopy;
97
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000098// For regular archives this function simply calls llvm::writeArchive,
99// For thin archives it writes the archive file itself as well as its members.
Puyan Lotfic4846a52018-07-16 22:17:05 +0000100static Error deepWriteArchive(StringRef ArcName,
101 ArrayRef<NewArchiveMember> NewMembers,
102 bool WriteSymtab, object::Archive::Kind Kind,
103 bool Deterministic, bool Thin) {
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000104 if (Error E = writeArchive(ArcName, NewMembers, WriteSymtab, Kind,
105 Deterministic, Thin))
106 return createFileError(ArcName, std::move(E));
107
108 if (!Thin)
109 return Error::success();
110
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000111 for (const NewArchiveMember &Member : NewMembers) {
112 // Internally, FileBuffer will use the buffer created by
113 // FileOutputBuffer::create, for regular files (that is the case for
114 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
115 // OnDiskBuffer uses a temporary file and then renames it. So in reality
116 // there is no inefficiency / duplicated in-memory buffers in this case. For
117 // now in-memory buffers can not be completely avoided since
118 // NewArchiveMember still requires them even though writeArchive does not
119 // write them on disk.
120 FileBuffer FB(Member.MemberName);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000121 if (Error E = FB.allocate(Member.Buf->getBufferSize()))
122 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000123 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
124 FB.getBufferStart());
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000125 if (Error E = FB.commit())
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000126 return E;
127 }
128 return Error::success();
129}
130
Eugene Leviant86b7f862019-06-13 09:56:14 +0000131/// The function executeObjcopyOnIHex does the dispatch based on the format
132/// of the output specified by the command line options.
133static Error executeObjcopyOnIHex(const CopyConfig &Config, MemoryBuffer &In,
134 Buffer &Out) {
135 // TODO: support output formats other than ELF.
136 return elf::executeObjcopyOnIHex(Config, In, Out);
137}
138
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000139/// The function executeObjcopyOnRawBinary does the dispatch based on the format
140/// of the output specified by the command line options.
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000141static Error executeObjcopyOnRawBinary(const CopyConfig &Config,
142 MemoryBuffer &In, Buffer &Out) {
Rumeet Dhindsa4ee933c2019-06-26 03:00:57 +0000143 // TODO: llvm-objcopy should parse CopyConfig.OutputFormat to recognize
144 // formats other than ELF / "binary" and invoke
145 // elf::executeObjcopyOnRawBinary, macho::executeObjcopyOnRawBinary or
146 // coff::executeObjcopyOnRawBinary accordingly.
147 return elf::executeObjcopyOnRawBinary(Config, In, Out);
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000148}
149
150/// The function executeObjcopyOnBinary does the dispatch based on the format
151/// of the input binary (ELF, MachO or COFF).
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000152static Error executeObjcopyOnBinary(const CopyConfig &Config,
153 object::Binary &In, Buffer &Out) {
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000154 if (auto *ELFBinary = dyn_cast<object::ELFObjectFileBase>(&In))
155 return elf::executeObjcopyOnBinary(Config, *ELFBinary, Out);
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000156 else if (auto *COFFBinary = dyn_cast<object::COFFObjectFile>(&In))
157 return coff::executeObjcopyOnBinary(Config, *COFFBinary, Out);
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000158 else if (auto *MachOBinary = dyn_cast<object::MachOObjectFile>(&In))
159 return macho::executeObjcopyOnBinary(Config, *MachOBinary, Out);
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000160 else
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000161 return createStringError(object_error::invalid_file_type,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000162 "unsupported object file format");
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000163}
164
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000165static Error executeObjcopyOnArchive(const CopyConfig &Config,
166 const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000167 std::vector<NewArchiveMember> NewArchiveMembers;
168 Error Err = Error::success();
169 for (const Archive::Child &Child : Ar.children(Err)) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000170 Expected<StringRef> ChildNameOrErr = Child.getName();
171 if (!ChildNameOrErr)
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000172 return createFileError(Ar.getFileName(), ChildNameOrErr.takeError());
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000173
James Henderson5a2b5ca2019-05-08 13:28:58 +0000174 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
175 if (!ChildOrErr)
176 return createFileError(Ar.getFileName() + "(" + *ChildNameOrErr + ")",
177 ChildOrErr.takeError());
178
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000179 MemBuffer MB(ChildNameOrErr.get());
James Henderson5a2b5ca2019-05-08 13:28:58 +0000180 if (Error E = executeObjcopyOnBinary(Config, *ChildOrErr->get(), MB))
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000181 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000182
183 Expected<NewArchiveMember> Member =
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000184 NewArchiveMember::getOldMember(Child, Config.DeterministicArchives);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000185 if (!Member)
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000186 return createFileError(Ar.getFileName(), Member.takeError());
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000187 Member->Buf = MB.releaseMemoryBuffer();
188 Member->MemberName = Member->Buf->getBufferIdentifier();
189 NewArchiveMembers.push_back(std::move(*Member));
190 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000191 if (Err)
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000192 return createFileError(Config.InputFilename, std::move(Err));
193
194 return deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
195 Ar.hasSymbolTable(), Ar.kind(),
196 Config.DeterministicArchives, Ar.isThin());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000197}
198
Alex Brachet7439a9a2019-07-04 22:45:27 +0000199static Error restoreStatOnFile(StringRef Filename,
200 const sys::fs::file_status &Stat,
201 bool PreserveDates) {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000202 int FD;
203
Alex Brachet7439a9a2019-07-04 22:45:27 +0000204 // Writing to stdout should not be treated as an error here, just
205 // do not set access/modification times or permissions.
206 if (Filename == "-")
207 return Error::success();
208
Jordan Rupprecht74815402018-08-29 23:21:56 +0000209 if (auto EC =
210 sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000211 return createFileError(Filename, EC);
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000212
Alex Brachet7439a9a2019-07-04 22:45:27 +0000213 if (PreserveDates)
214 if (auto EC = sys::fs::setLastAccessAndModificationTime(
215 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
216 return createFileError(Filename, EC);
217
218 if (auto EC = sys::fs::setPermissions(Filename, Stat.permissions()))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000219 return createFileError(Filename, EC);
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000220
221 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000222 return createFileError(Filename, EC);
223
224 return Error::success();
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000225}
226
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000227/// The function executeObjcopy does the higher level dispatch based on the type
228/// of input (raw binary, archive or single object file) and takes care of the
229/// format-agnostic modifications, i.e. preserving dates.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000230static Error executeObjcopy(const CopyConfig &Config) {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000231 sys::fs::file_status Stat;
Alex Brachet7439a9a2019-07-04 22:45:27 +0000232 if (Config.InputFilename != "-") {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000233 if (auto EC = sys::fs::status(Config.InputFilename, Stat))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000234 return createFileError(Config.InputFilename, EC);
Alex Brachet7439a9a2019-07-04 22:45:27 +0000235 } else {
236 Stat.permissions(static_cast<sys::fs::perms>(0777));
237 }
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000238
Eugene Leviant86b7f862019-06-13 09:56:14 +0000239 typedef Error (*ProcessRawFn)(const CopyConfig &, MemoryBuffer &, Buffer &);
Rumeet Dhindsa4ee933c2019-06-26 03:00:57 +0000240 auto ProcessRaw = StringSwitch<ProcessRawFn>(Config.InputFormat)
241 .Case("binary", executeObjcopyOnRawBinary)
242 .Case("ihex", executeObjcopyOnIHex)
243 .Default(nullptr);
Eugene Leviant86b7f862019-06-13 09:56:14 +0000244
245 if (ProcessRaw) {
246 auto BufOrErr = MemoryBuffer::getFileOrSTDIN(Config.InputFilename);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000247 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000248 return createFileError(Config.InputFilename, BufOrErr.getError());
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000249 FileBuffer FB(Config.OutputFilename);
Eugene Leviant86b7f862019-06-13 09:56:14 +0000250 if (Error E = ProcessRaw(Config, *BufOrErr->get(), FB))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000251 return E;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000252 } else {
253 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
254 createBinary(Config.InputFilename);
255 if (!BinaryOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000256 return createFileError(Config.InputFilename, BinaryOrErr.takeError());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000257
258 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) {
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000259 if (Error E = executeObjcopyOnArchive(Config, *Ar))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000260 return E;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000261 } else {
262 FileBuffer FB(Config.OutputFilename);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000263 if (Error E = executeObjcopyOnBinary(Config,
264 *BinaryOrErr.get().getBinary(), FB))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000265 return E;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000266 }
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000267 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000268
Alex Brachet7439a9a2019-07-04 22:45:27 +0000269 if (Error E =
270 restoreStatOnFile(Config.OutputFilename, Stat, Config.PreserveDates))
271 return E;
272
273 if (!Config.SplitDWO.empty()) {
274 Stat.permissions(static_cast<sys::fs::perms>(0666));
275 if (Error E =
276 restoreStatOnFile(Config.SplitDWO, Stat, Config.PreserveDates))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000277 return E;
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000278 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000279
280 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000281}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000282
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000283int main(int argc, char **argv) {
284 InitLLVM X(argc, argv);
285 ToolName = argv[0];
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000286 bool IsStrip = sys::path::stem(ToolName).contains("strip");
287 Expected<DriverConfig> DriverConfig =
Alex Brachet77477002019-06-18 00:39:10 +0000288 IsStrip ? parseStripOptions(makeArrayRef(argv + 1, argc), reportWarning)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000289 : parseObjcopyOptions(makeArrayRef(argv + 1, argc));
290 if (!DriverConfig) {
291 logAllUnhandledErrors(DriverConfig.takeError(),
292 WithColor::error(errs(), ToolName));
293 return 1;
294 }
295 for (const CopyConfig &CopyConfig : DriverConfig->CopyConfigs) {
296 if (Error E = executeObjcopy(CopyConfig)) {
297 logAllUnhandledErrors(std::move(E), WithColor::error(errs(), ToolName));
298 return 1;
299 }
300 }
301
302 return 0;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000303}