blob: 9c0145ffee5034202d597a818bcec8a0a3106960 [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);
Fangrui Songebd50292019-08-20 15:00:07 +000087 WithColor::warning(errs(), ToolName) << toString(std::move(E)) << '\n';
Alex Brachet77477002019-06-18 00:39:10 +000088 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) {
Seiya Nutaecb60b72019-07-05 05:28:38 +0000143 switch (Config.OutputFormat) {
144 case FileFormat::ELF:
145 // FIXME: Currently, we call elf::executeObjcopyOnRawBinary even if the
146 // output format is binary/ihex or it's not given. This behavior differs from
147 // GNU objcopy. See https://bugs.llvm.org/show_bug.cgi?id=42171 for details.
148 case FileFormat::Binary:
149 case FileFormat::IHex:
150 case FileFormat::Unspecified:
151 return elf::executeObjcopyOnRawBinary(Config, In, Out);
152 }
153
154 llvm_unreachable("unsupported output format");
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000155}
156
157/// The function executeObjcopyOnBinary does the dispatch based on the format
158/// of the input binary (ELF, MachO or COFF).
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000159static Error executeObjcopyOnBinary(const CopyConfig &Config,
160 object::Binary &In, Buffer &Out) {
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000161 if (auto *ELFBinary = dyn_cast<object::ELFObjectFileBase>(&In))
162 return elf::executeObjcopyOnBinary(Config, *ELFBinary, Out);
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000163 else if (auto *COFFBinary = dyn_cast<object::COFFObjectFile>(&In))
164 return coff::executeObjcopyOnBinary(Config, *COFFBinary, Out);
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000165 else if (auto *MachOBinary = dyn_cast<object::MachOObjectFile>(&In))
166 return macho::executeObjcopyOnBinary(Config, *MachOBinary, Out);
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000167 else
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000168 return createStringError(object_error::invalid_file_type,
Alex Brachetd54d4f92019-06-14 02:04:02 +0000169 "unsupported object file format");
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000170}
171
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000172static Error executeObjcopyOnArchive(const CopyConfig &Config,
173 const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000174 std::vector<NewArchiveMember> NewArchiveMembers;
175 Error Err = Error::success();
176 for (const Archive::Child &Child : Ar.children(Err)) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000177 Expected<StringRef> ChildNameOrErr = Child.getName();
178 if (!ChildNameOrErr)
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000179 return createFileError(Ar.getFileName(), ChildNameOrErr.takeError());
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000180
James Henderson5a2b5ca2019-05-08 13:28:58 +0000181 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
182 if (!ChildOrErr)
183 return createFileError(Ar.getFileName() + "(" + *ChildNameOrErr + ")",
184 ChildOrErr.takeError());
185
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000186 MemBuffer MB(ChildNameOrErr.get());
James Henderson5a2b5ca2019-05-08 13:28:58 +0000187 if (Error E = executeObjcopyOnBinary(Config, *ChildOrErr->get(), MB))
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000188 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000189
190 Expected<NewArchiveMember> Member =
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000191 NewArchiveMember::getOldMember(Child, Config.DeterministicArchives);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000192 if (!Member)
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000193 return createFileError(Ar.getFileName(), Member.takeError());
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000194 Member->Buf = MB.releaseMemoryBuffer();
195 Member->MemberName = Member->Buf->getBufferIdentifier();
196 NewArchiveMembers.push_back(std::move(*Member));
197 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000198 if (Err)
Jordan Rupprecht18886db2019-02-01 17:08:07 +0000199 return createFileError(Config.InputFilename, std::move(Err));
200
201 return deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
202 Ar.hasSymbolTable(), Ar.kind(),
203 Config.DeterministicArchives, Ar.isThin());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000204}
205
Alex Brachet7439a9a2019-07-04 22:45:27 +0000206static Error restoreStatOnFile(StringRef Filename,
207 const sys::fs::file_status &Stat,
208 bool PreserveDates) {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000209 int FD;
210
Alex Brachet7439a9a2019-07-04 22:45:27 +0000211 // Writing to stdout should not be treated as an error here, just
212 // do not set access/modification times or permissions.
213 if (Filename == "-")
214 return Error::success();
215
Jordan Rupprecht74815402018-08-29 23:21:56 +0000216 if (auto EC =
217 sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000218 return createFileError(Filename, EC);
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000219
Alex Brachet7439a9a2019-07-04 22:45:27 +0000220 if (PreserveDates)
221 if (auto EC = sys::fs::setLastAccessAndModificationTime(
222 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
223 return createFileError(Filename, EC);
224
Fangrui Song6dc59622019-07-11 10:17:59 +0000225 sys::fs::file_status OStat;
226 if (std::error_code EC = sys::fs::status(FD, OStat))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000227 return createFileError(Filename, EC);
Fangrui Song6dc59622019-07-11 10:17:59 +0000228 if (OStat.type() == sys::fs::file_type::regular_file)
229#ifdef _WIN32
230 if (auto EC = sys::fs::setPermissions(
231 Filename, static_cast<sys::fs::perms>(Stat.permissions() &
232 ~sys::fs::getUmask())))
233#else
234 if (auto EC = sys::fs::setPermissions(
235 FD, static_cast<sys::fs::perms>(Stat.permissions() &
236 ~sys::fs::getUmask())))
237#endif
238 return createFileError(Filename, EC);
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000239
240 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000241 return createFileError(Filename, EC);
242
243 return Error::success();
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000244}
245
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000246/// The function executeObjcopy does the higher level dispatch based on the type
247/// of input (raw binary, archive or single object file) and takes care of the
248/// format-agnostic modifications, i.e. preserving dates.
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000249static Error executeObjcopy(const CopyConfig &Config) {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000250 sys::fs::file_status Stat;
Alex Brachet7439a9a2019-07-04 22:45:27 +0000251 if (Config.InputFilename != "-") {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000252 if (auto EC = sys::fs::status(Config.InputFilename, Stat))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000253 return createFileError(Config.InputFilename, EC);
Alex Brachet7439a9a2019-07-04 22:45:27 +0000254 } else {
255 Stat.permissions(static_cast<sys::fs::perms>(0777));
256 }
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000257
Eugene Leviant86b7f862019-06-13 09:56:14 +0000258 typedef Error (*ProcessRawFn)(const CopyConfig &, MemoryBuffer &, Buffer &);
Seiya Nutaecb60b72019-07-05 05:28:38 +0000259 ProcessRawFn ProcessRaw;
260 switch (Config.InputFormat) {
261 case FileFormat::Binary:
262 ProcessRaw = executeObjcopyOnRawBinary;
263 break;
264 case FileFormat::IHex:
265 ProcessRaw = executeObjcopyOnIHex;
266 break;
267 default:
268 ProcessRaw = nullptr;
269 }
Eugene Leviant86b7f862019-06-13 09:56:14 +0000270
271 if (ProcessRaw) {
272 auto BufOrErr = MemoryBuffer::getFileOrSTDIN(Config.InputFilename);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000273 if (!BufOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000274 return createFileError(Config.InputFilename, BufOrErr.getError());
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000275 FileBuffer FB(Config.OutputFilename);
Eugene Leviant86b7f862019-06-13 09:56:14 +0000276 if (Error E = ProcessRaw(Config, *BufOrErr->get(), FB))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000277 return E;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000278 } else {
279 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
280 createBinary(Config.InputFilename);
281 if (!BinaryOrErr)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000282 return createFileError(Config.InputFilename, BinaryOrErr.takeError());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000283
284 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) {
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000285 if (Error E = executeObjcopyOnArchive(Config, *Ar))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000286 return E;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000287 } else {
288 FileBuffer FB(Config.OutputFilename);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000289 if (Error E = executeObjcopyOnBinary(Config,
290 *BinaryOrErr.get().getBinary(), FB))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000291 return E;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000292 }
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000293 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000294
Alex Brachet7439a9a2019-07-04 22:45:27 +0000295 if (Error E =
296 restoreStatOnFile(Config.OutputFilename, Stat, Config.PreserveDates))
297 return E;
298
299 if (!Config.SplitDWO.empty()) {
300 Stat.permissions(static_cast<sys::fs::perms>(0666));
301 if (Error E =
302 restoreStatOnFile(Config.SplitDWO, Stat, Config.PreserveDates))
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000303 return E;
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000304 }
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000305
306 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000307}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000308
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000309int main(int argc, char **argv) {
310 InitLLVM X(argc, argv);
311 ToolName = argv[0];
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000312 bool IsStrip = sys::path::stem(ToolName).contains("strip");
313 Expected<DriverConfig> DriverConfig =
Alex Brachet77477002019-06-18 00:39:10 +0000314 IsStrip ? parseStripOptions(makeArrayRef(argv + 1, argc), reportWarning)
Jordan Rupprechtad29d292019-02-21 17:05:19 +0000315 : parseObjcopyOptions(makeArrayRef(argv + 1, argc));
316 if (!DriverConfig) {
317 logAllUnhandledErrors(DriverConfig.takeError(),
318 WithColor::error(errs(), ToolName));
319 return 1;
320 }
321 for (const CopyConfig &CopyConfig : DriverConfig->CopyConfigs) {
322 if (Error E = executeObjcopy(CopyConfig)) {
323 logAllUnhandledErrors(std::move(E), WithColor::error(errs(), ToolName));
324 return 1;
325 }
326 }
327
328 return 0;
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000329}