blob: 75d513546b716b942e0a97e317e860c9389990a8 [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 Shaposhnikov8d0b74c2018-10-11 22:33:50 +000014
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000015#include "llvm/ADT/STLExtras.h"
Jordan Rupprechtd67c1e12018-08-01 16:23:22 +000016#include "llvm/ADT/SmallVector.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000017#include "llvm/ADT/StringRef.h"
18#include "llvm/ADT/Twine.h"
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000019#include "llvm/Object/Archive.h"
20#include "llvm/Object/ArchiveWriter.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000021#include "llvm/Object/Binary.h"
Martin Storsjoe84a0b52018-12-19 07:24:38 +000022#include "llvm/Object/COFF.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000023#include "llvm/Object/ELFObjectFile.h"
24#include "llvm/Object/ELFTypes.h"
25#include "llvm/Object/Error.h"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000026#include "llvm/Option/Arg.h"
27#include "llvm/Option/ArgList.h"
28#include "llvm/Option/Option.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000029#include "llvm/Support/Casting.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000030#include "llvm/Support/Error.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/ErrorOr.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000033#include "llvm/Support/InitLLVM.h"
Jordan Rupprechtcf676332018-08-17 18:51:11 +000034#include "llvm/Support/Memory.h"
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000035#include "llvm/Support/Path.h"
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +000036#include "llvm/Support/Process.h"
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000037#include "llvm/Support/WithColor.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000038#include "llvm/Support/raw_ostream.h"
39#include <algorithm>
40#include <cassert>
41#include <cstdlib>
Petr Hosek05a04cb2017-08-01 00:33:58 +000042#include <memory>
43#include <string>
44#include <system_error>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000045#include <utility>
Petr Hosek05a04cb2017-08-01 00:33:58 +000046
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000047namespace llvm {
48namespace objcopy {
49
50// The name this program was invoked as.
51StringRef ToolName;
52
53LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000054 WithColor::error(errs(), ToolName) << Message << ".\n";
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000055 errs().flush();
56 exit(1);
57}
58
Jordan Rupprecht881cae72019-01-22 23:49:16 +000059LLVM_ATTRIBUTE_NORETURN void error(Error E) {
60 assert(E);
61 std::string Buf;
62 raw_string_ostream OS(Buf);
63 logAllUnhandledErrors(std::move(E), OS);
64 OS.flush();
65 WithColor::error(errs(), ToolName) << Buf;
66 exit(1);
67}
68
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000069LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
70 assert(EC);
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000071 WithColor::error(errs(), ToolName)
72 << "'" << File << "': " << EC.message() << ".\n";
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000073 exit(1);
74}
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) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000099 Error E =
100 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
101 if (!Thin || E)
102 return E;
103 for (const NewArchiveMember &Member : NewMembers) {
104 // Internally, FileBuffer will use the buffer created by
105 // FileOutputBuffer::create, for regular files (that is the case for
106 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
107 // OnDiskBuffer uses a temporary file and then renames it. So in reality
108 // there is no inefficiency / duplicated in-memory buffers in this case. For
109 // now in-memory buffers can not be completely avoided since
110 // NewArchiveMember still requires them even though writeArchive does not
111 // write them on disk.
112 FileBuffer FB(Member.MemberName);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000113 if (Error E = FB.allocate(Member.Buf->getBufferSize()))
114 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000115 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
116 FB.getBufferStart());
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000117 if (Error E = FB.commit())
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000118 return E;
119 }
120 return Error::success();
121}
122
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000123/// The function executeObjcopyOnRawBinary does the dispatch based on the format
124/// of the output specified by the command line options.
125static void executeObjcopyOnRawBinary(const CopyConfig &Config,
126 MemoryBuffer &In, Buffer &Out) {
127 // TODO: llvm-objcopy should parse CopyConfig.OutputFormat to recognize
128 // formats other than ELF / "binary" and invoke
129 // elf::executeObjcopyOnRawBinary, macho::executeObjcopyOnRawBinary or
130 // coff::executeObjcopyOnRawBinary accordingly.
131 return elf::executeObjcopyOnRawBinary(Config, In, Out);
132}
133
134/// The function executeObjcopyOnBinary does the dispatch based on the format
135/// of the input binary (ELF, MachO or COFF).
136static void executeObjcopyOnBinary(const CopyConfig &Config, object::Binary &In,
137 Buffer &Out) {
138 if (auto *ELFBinary = dyn_cast<object::ELFObjectFileBase>(&In))
139 return elf::executeObjcopyOnBinary(Config, *ELFBinary, Out);
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000140 else if (auto *COFFBinary = dyn_cast<object::COFFObjectFile>(&In))
141 return coff::executeObjcopyOnBinary(Config, *COFFBinary, Out);
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000142 else
143 error("Unsupported object file format");
144}
145
146static void executeObjcopyOnArchive(const CopyConfig &Config,
147 const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000148 std::vector<NewArchiveMember> NewArchiveMembers;
149 Error Err = Error::success();
150 for (const Archive::Child &Child : Ar.children(Err)) {
151 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
152 if (!ChildOrErr)
153 reportError(Ar.getFileName(), ChildOrErr.takeError());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000154 Binary *Bin = ChildOrErr->get();
155
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000156 Expected<StringRef> ChildNameOrErr = Child.getName();
157 if (!ChildNameOrErr)
158 reportError(Ar.getFileName(), ChildNameOrErr.takeError());
159
160 MemBuffer MB(ChildNameOrErr.get());
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000161 executeObjcopyOnBinary(Config, *Bin, MB);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000162
163 Expected<NewArchiveMember> Member =
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000164 NewArchiveMember::getOldMember(Child, Config.DeterministicArchives);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000165 if (!Member)
166 reportError(Ar.getFileName(), Member.takeError());
167 Member->Buf = MB.releaseMemoryBuffer();
168 Member->MemberName = Member->Buf->getBufferIdentifier();
169 NewArchiveMembers.push_back(std::move(*Member));
170 }
171
172 if (Err)
173 reportError(Config.InputFilename, std::move(Err));
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000174 if (Error E = deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
175 Ar.hasSymbolTable(), Ar.kind(),
176 Config.DeterministicArchives, Ar.isThin()))
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000177 reportError(Config.OutputFilename, std::move(E));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000178}
179
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000180static void restoreDateOnFile(StringRef Filename,
181 const sys::fs::file_status &Stat) {
182 int FD;
183
Jordan Rupprecht74815402018-08-29 23:21:56 +0000184 if (auto EC =
185 sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting))
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000186 reportError(Filename, EC);
187
188 if (auto EC = sys::fs::setLastAccessAndModificationTime(
189 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
190 reportError(Filename, EC);
191
192 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
193 reportError(Filename, EC);
194}
195
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000196/// The function executeObjcopy does the higher level dispatch based on the type
197/// of input (raw binary, archive or single object file) and takes care of the
198/// format-agnostic modifications, i.e. preserving dates.
199static void executeObjcopy(const CopyConfig &Config) {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000200 sys::fs::file_status Stat;
201 if (Config.PreserveDates)
202 if (auto EC = sys::fs::status(Config.InputFilename, Stat))
203 reportError(Config.InputFilename, EC);
204
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000205 if (Config.InputFormat == "binary") {
206 auto BufOrErr = MemoryBuffer::getFile(Config.InputFilename);
207 if (!BufOrErr)
208 reportError(Config.InputFilename, BufOrErr.getError());
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000209 FileBuffer FB(Config.OutputFilename);
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000210 executeObjcopyOnRawBinary(Config, *BufOrErr->get(), FB);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000211 } else {
212 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
213 createBinary(Config.InputFilename);
214 if (!BinaryOrErr)
215 reportError(Config.InputFilename, BinaryOrErr.takeError());
216
217 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) {
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000218 executeObjcopyOnArchive(Config, *Ar);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000219 } else {
220 FileBuffer FB(Config.OutputFilename);
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000221 executeObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000222 }
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000223 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000224
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000225 if (Config.PreserveDates) {
226 restoreDateOnFile(Config.OutputFilename, Stat);
227 if (!Config.SplitDWO.empty())
228 restoreDateOnFile(Config.SplitDWO, Stat);
229 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000230}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000231
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000232int main(int argc, char **argv) {
233 InitLLVM X(argc, argv);
234 ToolName = argv[0];
Jordan Rupprecht591d8892018-09-05 13:10:03 +0000235 DriverConfig DriverConfig;
Fangrui Song4a670352018-11-07 03:02:11 +0000236 if (sys::path::stem(ToolName).contains("strip"))
Jordan Rupprecht591d8892018-09-05 13:10:03 +0000237 DriverConfig = parseStripOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000238 else
Jordan Rupprecht591d8892018-09-05 13:10:03 +0000239 DriverConfig = parseObjcopyOptions(makeArrayRef(argv + 1, argc));
240 for (const CopyConfig &CopyConfig : DriverConfig.CopyConfigs)
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000241 executeObjcopy(CopyConfig);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000242}