blob: da93602cbb283b45c64de93ba4b0abc18c4e63a6 [file] [log] [blame]
Peter Collingbourneee2e3d02015-06-08 02:32:01 +00001//===- ArchiveWriter.cpp - ar File Format implementation --------*- C++ -*-===//
2//
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//===----------------------------------------------------------------------===//
9//
10// This file defines the writeArchive function.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Object/ArchiveWriter.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/StringRef.h"
Zachary Turner19ca2b02017-06-07 03:48:56 +000017#include "llvm/BinaryFormat/Magic.h"
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000018#include "llvm/IR/LLVMContext.h"
19#include "llvm/Object/Archive.h"
20#include "llvm/Object/ObjectFile.h"
21#include "llvm/Object/SymbolicFile.h"
Benjamin Krameraa94b682015-06-17 16:02:56 +000022#include "llvm/Support/EndianStream.h"
Rafael Espindola803fe192015-06-13 17:23:04 +000023#include "llvm/Support/Errc.h"
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000024#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/Format.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/ToolOutputFile.h"
28#include "llvm/Support/raw_ostream.h"
29
James Y Knight0101af52018-10-04 18:49:21 +000030#include <map>
31
Peter Collingbourne3120bcb2015-06-08 02:43:32 +000032#if !defined(_MSC_VER) && !defined(__MINGW32__)
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000033#include <unistd.h>
Peter Collingbourne3120bcb2015-06-08 02:43:32 +000034#else
35#include <io.h>
36#endif
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000037
38using namespace llvm;
39
Peter Collingbourned9613da2016-06-29 22:27:42 +000040NewArchiveMember::NewArchiveMember(MemoryBufferRef BufRef)
Reid Kleckner0e34c352017-06-12 19:45:35 +000041 : Buf(MemoryBuffer::getMemBuffer(BufRef, false)),
42 MemberName(BufRef.getBufferIdentifier()) {}
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000043
Peter Collingbourned9613da2016-06-29 22:27:42 +000044Expected<NewArchiveMember>
45NewArchiveMember::getOldMember(const object::Archive::Child &OldMember,
46 bool Deterministic) {
Kevin Enderby2a715172016-07-29 17:44:13 +000047 Expected<llvm::MemoryBufferRef> BufOrErr = OldMember.getMemoryBufferRef();
Peter Collingbourned9613da2016-06-29 22:27:42 +000048 if (!BufOrErr)
Kevin Enderby2a715172016-07-29 17:44:13 +000049 return BufOrErr.takeError();
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000050
Peter Collingbourned9613da2016-06-29 22:27:42 +000051 NewArchiveMember M;
David Callahanbcdc1612016-11-30 22:32:58 +000052 assert(M.IsNew == false);
Peter Collingbourned9613da2016-06-29 22:27:42 +000053 M.Buf = MemoryBuffer::getMemBuffer(*BufOrErr, false);
Reid Kleckner0e34c352017-06-12 19:45:35 +000054 M.MemberName = M.Buf->getBufferIdentifier();
Peter Collingbourned9613da2016-06-29 22:27:42 +000055 if (!Deterministic) {
Pavel Labath6df95622016-10-24 13:38:27 +000056 auto ModTimeOrErr = OldMember.getLastModified();
Vedant Kumare5d15782016-08-03 19:02:50 +000057 if (!ModTimeOrErr)
58 return ModTimeOrErr.takeError();
59 M.ModTime = ModTimeOrErr.get();
60 Expected<unsigned> UIDOrErr = OldMember.getUID();
61 if (!UIDOrErr)
62 return UIDOrErr.takeError();
63 M.UID = UIDOrErr.get();
64 Expected<unsigned> GIDOrErr = OldMember.getGID();
65 if (!GIDOrErr)
66 return GIDOrErr.takeError();
67 M.GID = GIDOrErr.get();
68 Expected<sys::fs::perms> AccessModeOrErr = OldMember.getAccessMode();
69 if (!AccessModeOrErr)
70 return AccessModeOrErr.takeError();
71 M.Perms = AccessModeOrErr.get();
Peter Collingbourned9613da2016-06-29 22:27:42 +000072 }
73 return std::move(M);
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000074}
75
Peter Collingbourned9613da2016-06-29 22:27:42 +000076Expected<NewArchiveMember> NewArchiveMember::getFile(StringRef FileName,
77 bool Deterministic) {
78 sys::fs::file_status Status;
79 int FD;
80 if (auto EC = sys::fs::openFileForRead(FileName, FD))
81 return errorCodeToError(EC);
82 assert(FD != -1);
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000083
Peter Collingbourned9613da2016-06-29 22:27:42 +000084 if (auto EC = sys::fs::status(FD, Status))
85 return errorCodeToError(EC);
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000086
87 // Opening a directory doesn't make sense. Let it fail.
88 // Linux cannot open directories with open(2), although
89 // cygwin and *bsd can.
Peter Collingbourned9613da2016-06-29 22:27:42 +000090 if (Status.type() == sys::fs::file_type::directory_file)
91 return errorCodeToError(make_error_code(errc::is_a_directory));
Peter Collingbourneee2e3d02015-06-08 02:32:01 +000092
Peter Collingbourned9613da2016-06-29 22:27:42 +000093 ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
94 MemoryBuffer::getOpenFile(FD, FileName, Status.getSize(), false);
95 if (!MemberBufferOrErr)
96 return errorCodeToError(MemberBufferOrErr.getError());
97
98 if (close(FD) != 0)
99 return errorCodeToError(std::error_code(errno, std::generic_category()));
100
101 NewArchiveMember M;
David Callahanbcdc1612016-11-30 22:32:58 +0000102 M.IsNew = true;
Peter Collingbourned9613da2016-06-29 22:27:42 +0000103 M.Buf = std::move(*MemberBufferOrErr);
Reid Kleckner0e34c352017-06-12 19:45:35 +0000104 M.MemberName = M.Buf->getBufferIdentifier();
Peter Collingbourned9613da2016-06-29 22:27:42 +0000105 if (!Deterministic) {
Pavel Labath6df95622016-10-24 13:38:27 +0000106 M.ModTime = std::chrono::time_point_cast<std::chrono::seconds>(
107 Status.getLastModificationTime());
Peter Collingbourned9613da2016-06-29 22:27:42 +0000108 M.UID = Status.getUser();
109 M.GID = Status.getGroup();
110 M.Perms = Status.permissions();
111 }
112 return std::move(M);
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000113}
114
115template <typename T>
Rafael Espindolafa103002017-09-21 23:06:23 +0000116static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000117 uint64_t OldPos = OS.tell();
118 OS << Data;
119 unsigned SizeSoFar = OS.tell() - OldPos;
Rafael Espindolac155f162017-09-21 23:00:55 +0000120 assert(SizeSoFar <= Size && "Data doesn't fit in Size");
121 OS.indent(Size - SizeSoFar);
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000122}
123
James Y Knight742beb62018-10-10 21:07:02 +0000124static bool isDarwin(object::Archive::Kind Kind) {
125 return Kind == object::Archive::K_DARWIN ||
126 Kind == object::Archive::K_DARWIN64;
127}
128
Rafael Espindola13f0c802017-02-21 20:40:54 +0000129static bool isBSDLike(object::Archive::Kind Kind) {
130 switch (Kind) {
131 case object::Archive::K_GNU:
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000132 case object::Archive::K_GNU64:
Rafael Espindola13f0c802017-02-21 20:40:54 +0000133 return false;
134 case object::Archive::K_BSD:
135 case object::Archive::K_DARWIN:
Rafael Espindola2504ec92017-02-22 19:42:14 +0000136 case object::Archive::K_DARWIN64:
James Y Knight742beb62018-10-10 21:07:02 +0000137 return true;
Rafael Espindola2504ec92017-02-22 19:42:14 +0000138 case object::Archive::K_COFF:
139 break;
Rafael Espindola13f0c802017-02-21 20:40:54 +0000140 }
Rafael Espindola2504ec92017-02-22 19:42:14 +0000141 llvm_unreachable("not supported for writting");
Rafael Espindola13f0c802017-02-21 20:40:54 +0000142}
143
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000144template <class T>
145static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val) {
Peter Collingbournea68d4cc2018-05-18 19:46:24 +0000146 support::endian::write(Out, Val,
147 isBSDLike(Kind) ? support::little : support::big);
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000148}
149
Pavel Labath6df95622016-10-24 13:38:27 +0000150static void printRestOfMemberHeader(
Rafael Espindolafa103002017-09-21 23:06:23 +0000151 raw_ostream &Out, const sys::TimePoint<std::chrono::seconds> &ModTime,
Pavel Labath6df95622016-10-24 13:38:27 +0000152 unsigned UID, unsigned GID, unsigned Perms, unsigned Size) {
153 printWithSpacePadding(Out, sys::toTimeT(ModTime), 12);
Rafael Espindolac155f162017-09-21 23:00:55 +0000154
155 // The format has only 6 chars for uid and gid. Truncate if the provided
156 // values don't fit.
157 printWithSpacePadding(Out, UID % 1000000, 6);
158 printWithSpacePadding(Out, GID % 1000000, 6);
159
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000160 printWithSpacePadding(Out, format("%o", Perms), 8);
161 printWithSpacePadding(Out, Size, 10);
162 Out << "`\n";
163}
164
Pavel Labath6df95622016-10-24 13:38:27 +0000165static void
Rafael Espindolafa103002017-09-21 23:06:23 +0000166printGNUSmallMemberHeader(raw_ostream &Out, StringRef Name,
Pavel Labath6df95622016-10-24 13:38:27 +0000167 const sys::TimePoint<std::chrono::seconds> &ModTime,
168 unsigned UID, unsigned GID, unsigned Perms,
169 unsigned Size) {
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000170 printWithSpacePadding(Out, Twine(Name) + "/", 16);
171 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
172}
173
Pavel Labath6df95622016-10-24 13:38:27 +0000174static void
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000175printBSDMemberHeader(raw_ostream &Out, uint64_t Pos, StringRef Name,
Pavel Labath6df95622016-10-24 13:38:27 +0000176 const sys::TimePoint<std::chrono::seconds> &ModTime,
177 unsigned UID, unsigned GID, unsigned Perms,
178 unsigned Size) {
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000179 uint64_t PosAfterHeader = Pos + 60 + Name.size();
Rafael Espindola56240ea2015-07-09 14:54:12 +0000180 // Pad so that even 64 bit object files are aligned.
181 unsigned Pad = OffsetToAlignment(PosAfterHeader, 8);
182 unsigned NameWithPadding = Name.size() + Pad;
183 printWithSpacePadding(Out, Twine("#1/") + Twine(NameWithPadding), 16);
184 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms,
185 NameWithPadding + Size);
186 Out << Name;
Rafael Espindola56240ea2015-07-09 14:54:12 +0000187 while (Pad--)
188 Out.write(uint8_t(0));
189}
190
Rafael Espindola4c9cd282015-07-15 05:47:46 +0000191static bool useStringTable(bool Thin, StringRef Name) {
Reid Kleckner0e34c352017-06-12 19:45:35 +0000192 return Thin || Name.size() >= 16 || Name.contains('/');
Rafael Espindola4c9cd282015-07-15 05:47:46 +0000193}
194
Rafael Espindola6a37b472015-07-16 00:14:49 +0000195// Compute the relative path from From to To.
196static std::string computeRelativePath(StringRef From, StringRef To) {
197 if (sys::path::is_absolute(From) || sys::path::is_absolute(To))
198 return To;
199
200 StringRef DirFrom = sys::path::parent_path(From);
201 auto FromI = sys::path::begin(DirFrom);
202 auto ToI = sys::path::begin(To);
203 while (*FromI == *ToI) {
204 ++FromI;
205 ++ToI;
206 }
207
208 SmallString<128> Relative;
209 for (auto FromE = sys::path::end(DirFrom); FromI != FromE; ++FromI)
210 sys::path::append(Relative, "..");
211
212 for (auto ToE = sys::path::end(To); ToI != ToE; ++ToI)
213 sys::path::append(Relative, *ToI);
214
Nico Weber63033d32018-04-29 00:45:03 +0000215#ifdef _WIN32
Peter Collingbourne0f034732016-11-15 21:36:35 +0000216 // Replace backslashes with slashes so that the path is portable between *nix
217 // and Windows.
218 std::replace(Relative.begin(), Relative.end(), '\\', '/');
219#endif
220
Rafael Espindola6a37b472015-07-16 00:14:49 +0000221 return Relative.str();
222}
223
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000224static bool is64BitKind(object::Archive::Kind Kind) {
225 switch (Kind) {
226 case object::Archive::K_GNU:
227 case object::Archive::K_BSD:
228 case object::Archive::K_DARWIN:
229 case object::Archive::K_COFF:
230 return false;
231 case object::Archive::K_DARWIN64:
232 case object::Archive::K_GNU64:
233 return true;
234 }
235 llvm_unreachable("not supported for writting");
236}
237
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000238static void addToStringTable(raw_ostream &Out, StringRef ArcName,
239 const NewArchiveMember &M, bool Thin) {
240 StringRef ID = M.Buf->getBufferIdentifier();
241 if (Thin) {
242 if (M.IsNew)
243 Out << computeRelativePath(ArcName, ID);
244 else
245 Out << ID;
246 } else
247 Out << M.MemberName;
248 Out << "/\n";
249}
Rafael Espindola6a37b472015-07-16 00:14:49 +0000250
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000251static void printMemberHeader(raw_ostream &Out, uint64_t Pos,
252 raw_ostream &StringTable,
Peter Wu97de56d2018-12-19 16:15:05 +0000253 StringMap<uint64_t> &MemberNames,
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000254 object::Archive::Kind Kind, bool Thin,
255 StringRef ArcName, const NewArchiveMember &M,
James Y Knight0101af52018-10-04 18:49:21 +0000256 sys::TimePoint<std::chrono::seconds> ModTime,
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000257 unsigned Size) {
James Y Knight0101af52018-10-04 18:49:21 +0000258
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000259 if (isBSDLike(Kind))
James Y Knight0101af52018-10-04 18:49:21 +0000260 return printBSDMemberHeader(Out, Pos, M.MemberName, ModTime, M.UID, M.GID,
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000261 M.Perms, Size);
262 if (!useStringTable(Thin, M.MemberName))
James Y Knight0101af52018-10-04 18:49:21 +0000263 return printGNUSmallMemberHeader(Out, M.MemberName, ModTime, M.UID, M.GID,
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000264 M.Perms, Size);
265 Out << '/';
Peter Wu97de56d2018-12-19 16:15:05 +0000266 uint64_t NamePos;
267 if (Thin) {
268 NamePos = StringTable.tell();
269 addToStringTable(StringTable, ArcName, M, Thin);
270 } else {
Reid Kleckner80990392018-12-19 20:54:06 +0000271 auto Insertion = MemberNames.insert({M.MemberName, uint64_t(0)});
272 if (Insertion.second) {
273 Insertion.first->second = StringTable.tell();
Peter Wu97de56d2018-12-19 16:15:05 +0000274 addToStringTable(StringTable, ArcName, M, Thin);
Peter Wu97de56d2018-12-19 16:15:05 +0000275 }
Reid Kleckner80990392018-12-19 20:54:06 +0000276 NamePos = Insertion.first->second;
Peter Wu97de56d2018-12-19 16:15:05 +0000277 }
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000278 printWithSpacePadding(Out, NamePos, 15);
James Y Knight0101af52018-10-04 18:49:21 +0000279 printRestOfMemberHeader(Out, ModTime, M.UID, M.GID, M.Perms, Size);
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000280}
Rafael Espindola6a37b472015-07-16 00:14:49 +0000281
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000282namespace {
283struct MemberData {
284 std::vector<unsigned> Symbols;
285 std::string Header;
286 StringRef Data;
287 StringRef Padding;
288};
289} // namespace
290
291static MemberData computeStringTable(StringRef Names) {
292 unsigned Size = Names.size();
293 unsigned Pad = OffsetToAlignment(Size, 2);
294 std::string Header;
295 raw_string_ostream Out(Header);
296 printWithSpacePadding(Out, "//", 48);
297 printWithSpacePadding(Out, Size + Pad, 10);
298 Out << "`\n";
299 Out.flush();
300 return {{}, std::move(Header), Names, Pad ? "\n" : ""};
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000301}
302
Pavel Labath6df95622016-10-24 13:38:27 +0000303static sys::TimePoint<std::chrono::seconds> now(bool Deterministic) {
304 using namespace std::chrono;
305
Rafael Espindola168b1be2015-07-13 20:38:09 +0000306 if (!Deterministic)
Pavel Labath6df95622016-10-24 13:38:27 +0000307 return time_point_cast<seconds>(system_clock::now());
308 return sys::TimePoint<seconds>();
Rafael Espindola168b1be2015-07-13 20:38:09 +0000309}
310
Rafael Espindola0cbbfe22017-09-22 18:40:14 +0000311static bool isArchiveSymbol(const object::BasicSymbolRef &S) {
312 uint32_t Symflags = S.getFlags();
313 if (Symflags & object::SymbolRef::SF_FormatSpecific)
314 return false;
315 if (!(Symflags & object::SymbolRef::SF_Global))
316 return false;
Martin Storsjo3631b662018-07-20 20:48:29 +0000317 if (Symflags & object::SymbolRef::SF_Undefined)
Rafael Espindola0cbbfe22017-09-22 18:40:14 +0000318 return false;
319 return true;
320}
321
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000322static void printNBits(raw_ostream &Out, object::Archive::Kind Kind,
323 uint64_t Val) {
324 if (is64BitKind(Kind))
325 print<uint64_t>(Out, Kind, Val);
326 else
327 print<uint32_t>(Out, Kind, Val);
328}
329
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000330static void writeSymbolTable(raw_ostream &Out, object::Archive::Kind Kind,
331 bool Deterministic, ArrayRef<MemberData> Members,
332 StringRef StringTable) {
James Y Knight742beb62018-10-10 21:07:02 +0000333 // We don't write a symbol table on an archive with no members -- except on
334 // Darwin, where the linker will abort unless the archive has a symbol table.
335 if (StringTable.empty() && !isDarwin(Kind))
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000336 return;
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000337
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000338 unsigned NumSyms = 0;
339 for (const MemberData &M : Members)
340 NumSyms += M.Symbols.size();
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000341
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000342 unsigned Size = 0;
James Y Knight742beb62018-10-10 21:07:02 +0000343 unsigned OffsetSize = is64BitKind(Kind) ? sizeof(uint64_t) : sizeof(uint32_t);
344
345 Size += OffsetSize; // Number of entries
Rafael Espindola13f0c802017-02-21 20:40:54 +0000346 if (isBSDLike(Kind))
James Y Knight742beb62018-10-10 21:07:02 +0000347 Size += NumSyms * OffsetSize * 2; // Table
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000348 else
James Y Knight742beb62018-10-10 21:07:02 +0000349 Size += NumSyms * OffsetSize; // Table
Rafael Espindola13f0c802017-02-21 20:40:54 +0000350 if (isBSDLike(Kind))
James Y Knight742beb62018-10-10 21:07:02 +0000351 Size += OffsetSize; // byte count
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000352 Size += StringTable.size();
Rafael Espindolad3fa5052017-09-22 18:36:00 +0000353 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
354 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
355 // uniformly.
356 // We do this for all bsd formats because it simplifies aligning members.
357 unsigned Alignment = isBSDLike(Kind) ? 8 : 2;
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000358 unsigned Pad = OffsetToAlignment(Size, Alignment);
359 Size += Pad;
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000360
James Y Knight742beb62018-10-10 21:07:02 +0000361 if (isBSDLike(Kind)) {
362 const char *Name = is64BitKind(Kind) ? "__.SYMDEF_64" : "__.SYMDEF";
363 printBSDMemberHeader(Out, Out.tell(), Name, now(Deterministic), 0, 0, 0,
364 Size);
365 } else {
366 const char *Name = is64BitKind(Kind) ? "/SYM64" : "";
367 printGNUSmallMemberHeader(Out, Name, now(Deterministic), 0, 0, 0, Size);
368 }
Rafael Espindolaa55816b2015-07-09 15:56:23 +0000369
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000370 uint64_t Pos = Out.tell() + Size;
371
Rafael Espindola13f0c802017-02-21 20:40:54 +0000372 if (isBSDLike(Kind))
James Y Knight742beb62018-10-10 21:07:02 +0000373 printNBits(Out, Kind, NumSyms * 2 * OffsetSize);
Rafael Espindola13f0c802017-02-21 20:40:54 +0000374 else
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000375 printNBits(Out, Kind, NumSyms);
Rafael Espindolaa55816b2015-07-09 15:56:23 +0000376
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000377 for (const MemberData &M : Members) {
378 for (unsigned StringOffset : M.Symbols) {
379 if (isBSDLike(Kind))
James Y Knight742beb62018-10-10 21:07:02 +0000380 printNBits(Out, Kind, StringOffset);
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000381 printNBits(Out, Kind, Pos); // member offset
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000382 }
383 Pos += M.Header.size() + M.Data.size() + M.Padding.size();
384 }
385
386 if (isBSDLike(Kind))
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000387 // byte count of the string table
James Y Knight742beb62018-10-10 21:07:02 +0000388 printNBits(Out, Kind, StringTable.size());
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000389 Out << StringTable;
390
391 while (Pad--)
392 Out.write(uint8_t(0));
393}
394
395static Expected<std::vector<unsigned>>
396getSymbols(MemoryBufferRef Buf, raw_ostream &SymNames, bool &HasObject) {
397 std::vector<unsigned> Ret;
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000398
Alexander Shaposhnikovaa090872018-09-11 22:00:47 +0000399 // In the scenario when LLVMContext is populated SymbolicFile will contain a
400 // reference to it, thus SymbolicFile should be destroyed first.
401 LLVMContext Context;
402 std::unique_ptr<object::SymbolicFile> Obj;
403 if (identify_magic(Buf.getBuffer()) == file_magic::bitcode) {
404 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
405 Buf, file_magic::bitcode, &Context);
406 if (!ObjOrErr) {
407 // FIXME: check only for "not an object file" errors.
408 consumeError(ObjOrErr.takeError());
409 return Ret;
410 }
411 Obj = std::move(*ObjOrErr);
412 } else {
413 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
414 if (!ObjOrErr) {
415 // FIXME: check only for "not an object file" errors.
416 consumeError(ObjOrErr.takeError());
417 return Ret;
418 }
419 Obj = std::move(*ObjOrErr);
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000420 }
421
422 HasObject = true;
Alexander Shaposhnikovaa090872018-09-11 22:00:47 +0000423 for (const object::BasicSymbolRef &S : Obj->symbols()) {
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000424 if (!isArchiveSymbol(S))
425 continue;
426 Ret.push_back(SymNames.tell());
427 if (auto EC = S.printName(SymNames))
428 return errorCodeToError(EC);
429 SymNames << '\0';
430 }
431 return Ret;
432}
433
434static Expected<std::vector<MemberData>>
435computeMemberData(raw_ostream &StringTable, raw_ostream &SymNames,
436 object::Archive::Kind Kind, bool Thin, StringRef ArcName,
James Y Knight0101af52018-10-04 18:49:21 +0000437 bool Deterministic, ArrayRef<NewArchiveMember> NewMembers) {
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000438 static char PaddingData[8] = {'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'};
439
440 // This ignores the symbol table, but we only need the value mod 8 and the
441 // symbol table is aligned to be a multiple of 8 bytes
442 uint64_t Pos = 0;
443
444 std::vector<MemberData> Ret;
445 bool HasObject = false;
James Y Knight0101af52018-10-04 18:49:21 +0000446
Peter Wu97de56d2018-12-19 16:15:05 +0000447 // Deduplicate long member names in the string table and reuse earlier name
448 // offsets. This especially saves space for COFF Import libraries where all
449 // members have the same name.
450 StringMap<uint64_t> MemberNames;
451
James Y Knight0101af52018-10-04 18:49:21 +0000452 // UniqueTimestamps is a special case to improve debugging on Darwin:
453 //
454 // The Darwin linker does not link debug info into the final
455 // binary. Instead, it emits entries of type N_OSO in in the output
456 // binary's symbol table, containing references to the linked-in
457 // object files. Using that reference, the debugger can read the
458 // debug data directly from the object files. Alternatively, an
459 // invocation of 'dsymutil' will link the debug data from the object
460 // files into a dSYM bundle, which can be loaded by the debugger,
461 // instead of the object files.
462 //
463 // For an object file, the N_OSO entries contain the absolute path
464 // path to the file, and the file's timestamp. For an object
465 // included in an archive, the path is formatted like
466 // "/absolute/path/to/archive.a(member.o)", and the timestamp is the
467 // archive member's timestamp, rather than the archive's timestamp.
468 //
469 // However, this doesn't always uniquely identify an object within
470 // an archive -- an archive file can have multiple entries with the
471 // same filename. (This will happen commonly if the original object
472 // files started in different directories.) The only way they get
473 // distinguished, then, is via the timestamp. But this process is
474 // unable to find the correct object file in the archive when there
475 // are two files of the same name and timestamp.
476 //
477 // Additionally, timestamp==0 is treated specially, and causes the
478 // timestamp to be ignored as a match criteria.
479 //
480 // That will "usually" work out okay when creating an archive not in
481 // deterministic timestamp mode, because the objects will probably
482 // have been created at different timestamps.
483 //
484 // To ameliorate this problem, in deterministic archive mode (which
485 // is the default), on Darwin we will emit a unique non-zero
486 // timestamp for each entry with a duplicated name. This is still
487 // deterministic: the only thing affecting that timestamp is the
488 // order of the files in the resultant archive.
489 //
490 // See also the functions that handle the lookup:
491 // in lldb: ObjectContainerBSDArchive::Archive::FindObject()
492 // in llvm/tools/dsymutil: BinaryHolder::GetArchiveMemberBuffers().
James Y Knight742beb62018-10-10 21:07:02 +0000493 bool UniqueTimestamps = Deterministic && isDarwin(Kind);
James Y Knight0101af52018-10-04 18:49:21 +0000494 std::map<StringRef, unsigned> FilenameCount;
495 if (UniqueTimestamps) {
496 for (const NewArchiveMember &M : NewMembers)
497 FilenameCount[M.MemberName]++;
498 for (auto &Entry : FilenameCount)
499 Entry.second = Entry.second > 1 ? 1 : 0;
500 }
501
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000502 for (const NewArchiveMember &M : NewMembers) {
503 std::string Header;
504 raw_string_ostream Out(Header);
505
506 MemoryBufferRef Buf = M.Buf->getMemBufferRef();
507 StringRef Data = Thin ? "" : Buf.getBuffer();
508
509 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
510 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
511 // uniformly. This matches the behaviour with cctools and ensures that ld64
512 // is happy with archives that we generate.
James Y Knight742beb62018-10-10 21:07:02 +0000513 unsigned MemberPadding =
514 isDarwin(Kind) ? OffsetToAlignment(Data.size(), 8) : 0;
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000515 unsigned TailPadding = OffsetToAlignment(Data.size() + MemberPadding, 2);
516 StringRef Padding = StringRef(PaddingData, MemberPadding + TailPadding);
517
James Y Knight0101af52018-10-04 18:49:21 +0000518 sys::TimePoint<std::chrono::seconds> ModTime;
519 if (UniqueTimestamps)
520 // Increment timestamp for each file of a given name.
521 ModTime = sys::toTimePoint(FilenameCount[M.MemberName]++);
522 else
523 ModTime = M.ModTime;
Peter Wu97de56d2018-12-19 16:15:05 +0000524 printMemberHeader(Out, Pos, StringTable, MemberNames, Kind, Thin, ArcName,
525 M, ModTime, Buf.getBufferSize() + MemberPadding);
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000526 Out.flush();
527
528 Expected<std::vector<unsigned>> Symbols =
529 getSymbols(Buf, SymNames, HasObject);
530 if (auto E = Symbols.takeError())
531 return std::move(E);
532
533 Pos += Header.size() + Data.size() + Padding.size();
534 Ret.push_back({std::move(*Symbols), std::move(Header), Data, Padding});
535 }
536 // If there are no symbols, emit an empty symbol table, to satisfy Solaris
537 // tools, older versions of which expect a symbol table in a non-empty
538 // archive, regardless of whether there are any symbols in it.
539 if (HasObject && SymNames.tell() == 0)
540 SymNames << '\0' << '\0' << '\0';
541 return Ret;
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000542}
543
Rafael Espindola203c90b2017-09-21 23:13:36 +0000544Error llvm::writeArchive(StringRef ArcName,
545 ArrayRef<NewArchiveMember> NewMembers,
546 bool WriteSymtab, object::Archive::Kind Kind,
547 bool Deterministic, bool Thin,
548 std::unique_ptr<MemoryBuffer> OldArchiveBuf) {
Rafael Espindola13f0c802017-02-21 20:40:54 +0000549 assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000550
551 SmallString<0> SymNamesBuf;
552 raw_svector_ostream SymNames(SymNamesBuf);
553 SmallString<0> StringTableBuf;
554 raw_svector_ostream StringTable(StringTableBuf);
555
James Y Knight0101af52018-10-04 18:49:21 +0000556 Expected<std::vector<MemberData>> DataOrErr = computeMemberData(
557 StringTable, SymNames, Kind, Thin, ArcName, Deterministic, NewMembers);
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000558 if (Error E = DataOrErr.takeError())
559 return E;
560 std::vector<MemberData> &Data = *DataOrErr;
561
562 if (!StringTableBuf.empty())
563 Data.insert(Data.begin(), computeStringTable(StringTableBuf));
564
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000565 // We would like to detect if we need to switch to a 64-bit symbol table.
566 if (WriteSymtab) {
567 uint64_t MaxOffset = 0;
568 uint64_t LastOffset = MaxOffset;
Alexander Shaposhnikovaa090872018-09-11 22:00:47 +0000569 for (const auto &M : Data) {
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000570 // Record the start of the member's offset
571 LastOffset = MaxOffset;
572 // Account for the size of each part associated with the member.
573 MaxOffset += M.Header.size() + M.Data.size() + M.Padding.size();
574 // We assume 32-bit symbols to see if 32-bit symbols are possible or not.
575 MaxOffset += M.Symbols.size() * 4;
576 }
Peter Collingbourne59aa4502018-03-28 17:21:14 +0000577
578 // The SYM64 format is used when an archive's member offsets are larger than
579 // 32-bits can hold. The need for this shift in format is detected by
580 // writeArchive. To test this we need to generate a file with a member that
581 // has an offset larger than 32-bits but this demands a very slow test. To
582 // speed the test up we use this environment variable to pretend like the
583 // cutoff happens before 32-bits and instead happens at some much smaller
584 // value.
585 const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
586 int Sym64Threshold = 32;
587 if (Sym64Env)
588 StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
589
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000590 // If LastOffset isn't going to fit in a 32-bit varible we need to switch
591 // to 64-bit. Note that the file can be larger than 4GB as long as the last
592 // member starts before the 4GB offset.
James Y Knight742beb62018-10-10 21:07:02 +0000593 if (LastOffset >= (1ULL << Sym64Threshold)) {
594 if (Kind == object::Archive::K_DARWIN)
595 Kind = object::Archive::K_DARWIN64;
596 else
597 Kind = object::Archive::K_GNU64;
598 }
Jake Ehrlich06dbf5a2017-11-03 19:15:06 +0000599 }
600
Rafael Espindola79f20d22017-11-14 01:21:15 +0000601 Expected<sys::fs::TempFile> Temp =
602 sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
603 if (!Temp)
604 return Temp.takeError();
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000605
Rafael Espindola79f20d22017-11-14 01:21:15 +0000606 raw_fd_ostream Out(Temp->FD, false);
Rafael Espindola4c9cd282015-07-15 05:47:46 +0000607 if (Thin)
608 Out << "!<thin>\n";
609 else
610 Out << "!<arch>\n";
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000611
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000612 if (WriteSymtab)
613 writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf);
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000614
Rafael Espindola23bcd6d2017-10-03 20:59:43 +0000615 for (const MemberData &M : Data)
616 Out << M.Header << M.Data << M.Padding;
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000617
Rafael Espindola79f20d22017-11-14 01:21:15 +0000618 Out.flush();
Rafael Espindola0c067162016-05-09 13:31:11 +0000619
620 // At this point, we no longer need whatever backing memory
621 // was used to generate the NewMembers. On Windows, this buffer
622 // could be a mapped view of the file we want to replace (if
623 // we're updating an existing archive, say). In that case, the
624 // rename would still succeed, but it would leave behind a
625 // temporary file (actually the original file renamed) because
626 // a file cannot be deleted while there's a handle open on it,
627 // only renamed. So by freeing this buffer, this ensures that
628 // the last open handle on the destination file, if any, is
629 // closed before we attempt to rename.
630 OldArchiveBuf.reset();
631
Rafael Espindola79f20d22017-11-14 01:21:15 +0000632 return Temp->keep(ArcName);
Peter Collingbourneee2e3d02015-06-08 02:32:01 +0000633}