blob: a033aaecb986fb6cddc743023eeebd9c968c2d98 [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- llvm-objcopy.cpp ---------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00009
Petr Hosek05a04cb2017-08-01 00:33:58 +000010#include "llvm-objcopy.h"
Alexander Shaposhnikov3d4c4ac2018-10-16 05:40:18 +000011#include "Buffer.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"
22#include "llvm/Object/ELFObjectFile.h"
23#include "llvm/Object/ELFTypes.h"
24#include "llvm/Object/Error.h"
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +000025#include "llvm/Option/Arg.h"
26#include "llvm/Option/ArgList.h"
27#include "llvm/Option/Option.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000028#include "llvm/Support/Casting.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000029#include "llvm/Support/Error.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/ErrorOr.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000032#include "llvm/Support/InitLLVM.h"
Jordan Rupprechtcf676332018-08-17 18:51:11 +000033#include "llvm/Support/Memory.h"
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +000034#include "llvm/Support/Path.h"
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +000035#include "llvm/Support/Process.h"
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000036#include "llvm/Support/WithColor.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000037#include "llvm/Support/raw_ostream.h"
38#include <algorithm>
39#include <cassert>
40#include <cstdlib>
Petr Hosek05a04cb2017-08-01 00:33:58 +000041#include <memory>
42#include <string>
43#include <system_error>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000044#include <utility>
Petr Hosek05a04cb2017-08-01 00:33:58 +000045
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000046namespace llvm {
47namespace objcopy {
48
49// The name this program was invoked as.
50StringRef ToolName;
51
52LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000053 WithColor::error(errs(), ToolName) << Message << ".\n";
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000054 errs().flush();
55 exit(1);
56}
57
58LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
59 assert(EC);
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000060 WithColor::error(errs(), ToolName)
61 << "'" << File << "': " << EC.message() << ".\n";
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000062 exit(1);
63}
64
65LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
66 assert(E);
67 std::string Buf;
68 raw_string_ostream OS(Buf);
69 logAllUnhandledErrors(std::move(E), OS, "");
70 OS.flush();
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +000071 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000072 exit(1);
73}
74
75} // end namespace objcopy
Puyan Lotfic4846a52018-07-16 22:17:05 +000076} // end namespace llvm
Jake Ehrlich5de70d92017-11-03 18:58:41 +000077
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +000078using namespace llvm;
79using namespace llvm::object;
80using namespace llvm::objcopy;
81
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000082// For regular archives this function simply calls llvm::writeArchive,
83// For thin archives it writes the archive file itself as well as its members.
Puyan Lotfic4846a52018-07-16 22:17:05 +000084static Error deepWriteArchive(StringRef ArcName,
85 ArrayRef<NewArchiveMember> NewMembers,
86 bool WriteSymtab, object::Archive::Kind Kind,
87 bool Deterministic, bool Thin) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000088 Error E =
89 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin);
90 if (!Thin || E)
91 return E;
92 for (const NewArchiveMember &Member : NewMembers) {
93 // Internally, FileBuffer will use the buffer created by
94 // FileOutputBuffer::create, for regular files (that is the case for
95 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
96 // OnDiskBuffer uses a temporary file and then renames it. So in reality
97 // there is no inefficiency / duplicated in-memory buffers in this case. For
98 // now in-memory buffers can not be completely avoided since
99 // NewArchiveMember still requires them even though writeArchive does not
100 // write them on disk.
101 FileBuffer FB(Member.MemberName);
102 FB.allocate(Member.Buf->getBufferSize());
103 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
104 FB.getBufferStart());
105 if (auto E = FB.commit())
106 return E;
107 }
108 return Error::success();
109}
110
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000111/// The function executeObjcopyOnRawBinary does the dispatch based on the format
112/// of the output specified by the command line options.
113static void executeObjcopyOnRawBinary(const CopyConfig &Config,
114 MemoryBuffer &In, Buffer &Out) {
115 // TODO: llvm-objcopy should parse CopyConfig.OutputFormat to recognize
116 // formats other than ELF / "binary" and invoke
117 // elf::executeObjcopyOnRawBinary, macho::executeObjcopyOnRawBinary or
118 // coff::executeObjcopyOnRawBinary accordingly.
119 return elf::executeObjcopyOnRawBinary(Config, In, Out);
120}
121
122/// The function executeObjcopyOnBinary does the dispatch based on the format
123/// of the input binary (ELF, MachO or COFF).
124static void executeObjcopyOnBinary(const CopyConfig &Config, object::Binary &In,
125 Buffer &Out) {
126 if (auto *ELFBinary = dyn_cast<object::ELFObjectFileBase>(&In))
127 return elf::executeObjcopyOnBinary(Config, *ELFBinary, Out);
128 else
129 error("Unsupported object file format");
130}
131
132static void executeObjcopyOnArchive(const CopyConfig &Config,
133 const Archive &Ar) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000134 std::vector<NewArchiveMember> NewArchiveMembers;
135 Error Err = Error::success();
136 for (const Archive::Child &Child : Ar.children(Err)) {
137 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
138 if (!ChildOrErr)
139 reportError(Ar.getFileName(), ChildOrErr.takeError());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000140 Binary *Bin = ChildOrErr->get();
141
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000142 Expected<StringRef> ChildNameOrErr = Child.getName();
143 if (!ChildNameOrErr)
144 reportError(Ar.getFileName(), ChildNameOrErr.takeError());
145
146 MemBuffer MB(ChildNameOrErr.get());
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000147 executeObjcopyOnBinary(Config, *Bin, MB);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000148
149 Expected<NewArchiveMember> Member =
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000150 NewArchiveMember::getOldMember(Child, Config.DeterministicArchives);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000151 if (!Member)
152 reportError(Ar.getFileName(), Member.takeError());
153 Member->Buf = MB.releaseMemoryBuffer();
154 Member->MemberName = Member->Buf->getBufferIdentifier();
155 NewArchiveMembers.push_back(std::move(*Member));
156 }
157
158 if (Err)
159 reportError(Config.InputFilename, std::move(Err));
Jordan Rupprechtfc780bb2018-11-01 17:36:37 +0000160 if (Error E = deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
161 Ar.hasSymbolTable(), Ar.kind(),
162 Config.DeterministicArchives, Ar.isThin()))
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000163 reportError(Config.OutputFilename, std::move(E));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000164}
165
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000166static void restoreDateOnFile(StringRef Filename,
167 const sys::fs::file_status &Stat) {
168 int FD;
169
Jordan Rupprecht74815402018-08-29 23:21:56 +0000170 if (auto EC =
171 sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting))
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000172 reportError(Filename, EC);
173
174 if (auto EC = sys::fs::setLastAccessAndModificationTime(
175 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
176 reportError(Filename, EC);
177
178 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
179 reportError(Filename, EC);
180}
181
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000182/// The function executeObjcopy does the higher level dispatch based on the type
183/// of input (raw binary, archive or single object file) and takes care of the
184/// format-agnostic modifications, i.e. preserving dates.
185static void executeObjcopy(const CopyConfig &Config) {
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000186 sys::fs::file_status Stat;
187 if (Config.PreserveDates)
188 if (auto EC = sys::fs::status(Config.InputFilename, Stat))
189 reportError(Config.InputFilename, EC);
190
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000191 if (Config.InputFormat == "binary") {
192 auto BufOrErr = MemoryBuffer::getFile(Config.InputFilename);
193 if (!BufOrErr)
194 reportError(Config.InputFilename, BufOrErr.getError());
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000195 FileBuffer FB(Config.OutputFilename);
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000196 executeObjcopyOnRawBinary(Config, *BufOrErr->get(), FB);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000197 } else {
198 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
199 createBinary(Config.InputFilename);
200 if (!BinaryOrErr)
201 reportError(Config.InputFilename, BinaryOrErr.takeError());
202
203 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) {
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000204 executeObjcopyOnArchive(Config, *Ar);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000205 } else {
206 FileBuffer FB(Config.OutputFilename);
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000207 executeObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB);
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000208 }
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000209 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000210
Jordan Rupprechtd1767dc2018-08-16 18:29:40 +0000211 if (Config.PreserveDates) {
212 restoreDateOnFile(Config.OutputFilename, Stat);
213 if (!Config.SplitDWO.empty())
214 restoreDateOnFile(Config.SplitDWO, Stat);
215 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000216}
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000217
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000218int main(int argc, char **argv) {
219 InitLLVM X(argc, argv);
220 ToolName = argv[0];
Jordan Rupprecht591d8892018-09-05 13:10:03 +0000221 DriverConfig DriverConfig;
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000222 if (sys::path::stem(ToolName).endswith_lower("strip"))
Jordan Rupprecht591d8892018-09-05 13:10:03 +0000223 DriverConfig = parseStripOptions(makeArrayRef(argv + 1, argc));
Alexander Shaposhnikovcca69982018-05-07 19:32:09 +0000224 else
Jordan Rupprecht591d8892018-09-05 13:10:03 +0000225 DriverConfig = parseObjcopyOptions(makeArrayRef(argv + 1, argc));
226 for (const CopyConfig &CopyConfig : DriverConfig.CopyConfigs)
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +0000227 executeObjcopy(CopyConfig);
Alexander Shaposhnikovd6884792018-04-24 05:43:32 +0000228}