blob: c6c0befb90f93c937e4ddf43e5eaa1e5c729c3ee [file] [log] [blame]
Peter Collingbournefd66a482015-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 Turner264b5d92017-06-07 03:48:56 +000017#include "llvm/BinaryFormat/Magic.h"
Peter Collingbournefd66a482015-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 Kramercd278b72015-06-17 16:02:56 +000022#include "llvm/Support/EndianStream.h"
Rafael Espindola74f29322015-06-13 17:23:04 +000023#include "llvm/Support/Errc.h"
Peter Collingbournefd66a482015-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 Knight0d1bb792018-10-04 18:49:21 +000030#include <map>
31
Peter Collingbourne7ab1a3b2015-06-08 02:43:32 +000032#if !defined(_MSC_VER) && !defined(__MINGW32__)
Peter Collingbournefd66a482015-06-08 02:32:01 +000033#include <unistd.h>
Peter Collingbourne7ab1a3b2015-06-08 02:43:32 +000034#else
35#include <io.h>
36#endif
Peter Collingbournefd66a482015-06-08 02:32:01 +000037
38using namespace llvm;
39
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +000040NewArchiveMember::NewArchiveMember(MemoryBufferRef BufRef)
Reid Kleckner2f3f5032017-06-12 19:45:35 +000041 : Buf(MemoryBuffer::getMemBuffer(BufRef, false)),
42 MemberName(BufRef.getBufferIdentifier()) {}
Peter Collingbournefd66a482015-06-08 02:32:01 +000043
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +000044Expected<NewArchiveMember>
45NewArchiveMember::getOldMember(const object::Archive::Child &OldMember,
46 bool Deterministic) {
Kevin Enderbyf4586032016-07-29 17:44:13 +000047 Expected<llvm::MemoryBufferRef> BufOrErr = OldMember.getMemoryBufferRef();
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +000048 if (!BufOrErr)
Kevin Enderbyf4586032016-07-29 17:44:13 +000049 return BufOrErr.takeError();
Peter Collingbournefd66a482015-06-08 02:32:01 +000050
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +000051 NewArchiveMember M;
David Callahan5cb34077e82016-11-30 22:32:58 +000052 assert(M.IsNew == false);
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +000053 M.Buf = MemoryBuffer::getMemBuffer(*BufOrErr, false);
Reid Kleckner2f3f5032017-06-12 19:45:35 +000054 M.MemberName = M.Buf->getBufferIdentifier();
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +000055 if (!Deterministic) {
Pavel Labathbff47b52016-10-24 13:38:27 +000056 auto ModTimeOrErr = OldMember.getLastModified();
Vedant Kumar4031d9f2016-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 Collingbourne8ec68fa2016-06-29 22:27:42 +000072 }
73 return std::move(M);
Peter Collingbournefd66a482015-06-08 02:32:01 +000074}
75
Peter Collingbourne8ec68fa2016-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 Collingbournefd66a482015-06-08 02:32:01 +000083
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +000084 if (auto EC = sys::fs::status(FD, Status))
85 return errorCodeToError(EC);
Peter Collingbournefd66a482015-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 Collingbourne8ec68fa2016-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 Collingbournefd66a482015-06-08 02:32:01 +000092
Peter Collingbourne8ec68fa2016-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 Callahan5cb34077e82016-11-30 22:32:58 +0000102 M.IsNew = true;
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000103 M.Buf = std::move(*MemberBufferOrErr);
Reid Kleckner2f3f5032017-06-12 19:45:35 +0000104 M.MemberName = M.Buf->getBufferIdentifier();
Peter Collingbourne8ec68fa2016-06-29 22:27:42 +0000105 if (!Deterministic) {
Pavel Labathbff47b52016-10-24 13:38:27 +0000106 M.ModTime = std::chrono::time_point_cast<std::chrono::seconds>(
107 Status.getLastModificationTime());
Peter Collingbourne8ec68fa2016-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 Collingbournefd66a482015-06-08 02:32:01 +0000113}
114
115template <typename T>
Rafael Espindolafa083972017-09-21 23:06:23 +0000116static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
Peter Collingbournefd66a482015-06-08 02:32:01 +0000117 uint64_t OldPos = OS.tell();
118 OS << Data;
119 unsigned SizeSoFar = OS.tell() - OldPos;
Rafael Espindola540a8c72017-09-21 23:00:55 +0000120 assert(SizeSoFar <= Size && "Data doesn't fit in Size");
121 OS.indent(Size - SizeSoFar);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000122}
123
Rafael Espindola23a76be2017-02-21 20:40:54 +0000124static bool isBSDLike(object::Archive::Kind Kind) {
125 switch (Kind) {
126 case object::Archive::K_GNU:
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000127 case object::Archive::K_GNU64:
Rafael Espindola23a76be2017-02-21 20:40:54 +0000128 return false;
129 case object::Archive::K_BSD:
130 case object::Archive::K_DARWIN:
131 return true;
Rafael Espindolaf133ccb2017-02-22 19:42:14 +0000132 case object::Archive::K_DARWIN64:
133 case object::Archive::K_COFF:
134 break;
Rafael Espindola23a76be2017-02-21 20:40:54 +0000135 }
Rafael Espindolaf133ccb2017-02-22 19:42:14 +0000136 llvm_unreachable("not supported for writting");
Rafael Espindola23a76be2017-02-21 20:40:54 +0000137}
138
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000139template <class T>
140static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val) {
Peter Collingbournee3f65292018-05-18 19:46:24 +0000141 support::endian::write(Out, Val,
142 isBSDLike(Kind) ? support::little : support::big);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000143}
144
Pavel Labathbff47b52016-10-24 13:38:27 +0000145static void printRestOfMemberHeader(
Rafael Espindolafa083972017-09-21 23:06:23 +0000146 raw_ostream &Out, const sys::TimePoint<std::chrono::seconds> &ModTime,
Pavel Labathbff47b52016-10-24 13:38:27 +0000147 unsigned UID, unsigned GID, unsigned Perms, unsigned Size) {
148 printWithSpacePadding(Out, sys::toTimeT(ModTime), 12);
Rafael Espindola540a8c72017-09-21 23:00:55 +0000149
150 // The format has only 6 chars for uid and gid. Truncate if the provided
151 // values don't fit.
152 printWithSpacePadding(Out, UID % 1000000, 6);
153 printWithSpacePadding(Out, GID % 1000000, 6);
154
Peter Collingbournefd66a482015-06-08 02:32:01 +0000155 printWithSpacePadding(Out, format("%o", Perms), 8);
156 printWithSpacePadding(Out, Size, 10);
157 Out << "`\n";
158}
159
Pavel Labathbff47b52016-10-24 13:38:27 +0000160static void
Rafael Espindolafa083972017-09-21 23:06:23 +0000161printGNUSmallMemberHeader(raw_ostream &Out, StringRef Name,
Pavel Labathbff47b52016-10-24 13:38:27 +0000162 const sys::TimePoint<std::chrono::seconds> &ModTime,
163 unsigned UID, unsigned GID, unsigned Perms,
164 unsigned Size) {
Peter Collingbournefd66a482015-06-08 02:32:01 +0000165 printWithSpacePadding(Out, Twine(Name) + "/", 16);
166 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
167}
168
Pavel Labathbff47b52016-10-24 13:38:27 +0000169static void
Rafael Espindola476a7f92017-10-03 20:59:43 +0000170printBSDMemberHeader(raw_ostream &Out, uint64_t Pos, StringRef Name,
Pavel Labathbff47b52016-10-24 13:38:27 +0000171 const sys::TimePoint<std::chrono::seconds> &ModTime,
172 unsigned UID, unsigned GID, unsigned Perms,
173 unsigned Size) {
Rafael Espindola476a7f92017-10-03 20:59:43 +0000174 uint64_t PosAfterHeader = Pos + 60 + Name.size();
Rafael Espindola8cde5c02015-07-09 14:54:12 +0000175 // Pad so that even 64 bit object files are aligned.
176 unsigned Pad = OffsetToAlignment(PosAfterHeader, 8);
177 unsigned NameWithPadding = Name.size() + Pad;
178 printWithSpacePadding(Out, Twine("#1/") + Twine(NameWithPadding), 16);
179 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms,
180 NameWithPadding + Size);
181 Out << Name;
Rafael Espindola8cde5c02015-07-09 14:54:12 +0000182 while (Pad--)
183 Out.write(uint8_t(0));
184}
185
Rafael Espindolae6492582015-07-15 05:47:46 +0000186static bool useStringTable(bool Thin, StringRef Name) {
Reid Kleckner2f3f5032017-06-12 19:45:35 +0000187 return Thin || Name.size() >= 16 || Name.contains('/');
Rafael Espindolae6492582015-07-15 05:47:46 +0000188}
189
Rafael Espindola06d6d192015-07-16 00:14:49 +0000190// Compute the relative path from From to To.
191static std::string computeRelativePath(StringRef From, StringRef To) {
192 if (sys::path::is_absolute(From) || sys::path::is_absolute(To))
193 return To;
194
195 StringRef DirFrom = sys::path::parent_path(From);
196 auto FromI = sys::path::begin(DirFrom);
197 auto ToI = sys::path::begin(To);
198 while (*FromI == *ToI) {
199 ++FromI;
200 ++ToI;
201 }
202
203 SmallString<128> Relative;
204 for (auto FromE = sys::path::end(DirFrom); FromI != FromE; ++FromI)
205 sys::path::append(Relative, "..");
206
207 for (auto ToE = sys::path::end(To); ToI != ToE; ++ToI)
208 sys::path::append(Relative, *ToI);
209
Nico Weber712e8d22018-04-29 00:45:03 +0000210#ifdef _WIN32
Peter Collingbournebc9a5742016-11-15 21:36:35 +0000211 // Replace backslashes with slashes so that the path is portable between *nix
212 // and Windows.
213 std::replace(Relative.begin(), Relative.end(), '\\', '/');
214#endif
215
Rafael Espindola06d6d192015-07-16 00:14:49 +0000216 return Relative.str();
217}
218
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000219static bool is64BitKind(object::Archive::Kind Kind) {
220 switch (Kind) {
221 case object::Archive::K_GNU:
222 case object::Archive::K_BSD:
223 case object::Archive::K_DARWIN:
224 case object::Archive::K_COFF:
225 return false;
226 case object::Archive::K_DARWIN64:
227 case object::Archive::K_GNU64:
228 return true;
229 }
230 llvm_unreachable("not supported for writting");
231}
232
Rafael Espindola476a7f92017-10-03 20:59:43 +0000233static void addToStringTable(raw_ostream &Out, StringRef ArcName,
234 const NewArchiveMember &M, bool Thin) {
235 StringRef ID = M.Buf->getBufferIdentifier();
236 if (Thin) {
237 if (M.IsNew)
238 Out << computeRelativePath(ArcName, ID);
239 else
240 Out << ID;
241 } else
242 Out << M.MemberName;
243 Out << "/\n";
244}
Rafael Espindola06d6d192015-07-16 00:14:49 +0000245
Rafael Espindola476a7f92017-10-03 20:59:43 +0000246static void printMemberHeader(raw_ostream &Out, uint64_t Pos,
247 raw_ostream &StringTable,
248 object::Archive::Kind Kind, bool Thin,
249 StringRef ArcName, const NewArchiveMember &M,
James Y Knight0d1bb792018-10-04 18:49:21 +0000250 sys::TimePoint<std::chrono::seconds> ModTime,
Rafael Espindola476a7f92017-10-03 20:59:43 +0000251 unsigned Size) {
James Y Knight0d1bb792018-10-04 18:49:21 +0000252
Rafael Espindola476a7f92017-10-03 20:59:43 +0000253 if (isBSDLike(Kind))
James Y Knight0d1bb792018-10-04 18:49:21 +0000254 return printBSDMemberHeader(Out, Pos, M.MemberName, ModTime, M.UID, M.GID,
Rafael Espindola476a7f92017-10-03 20:59:43 +0000255 M.Perms, Size);
256 if (!useStringTable(Thin, M.MemberName))
James Y Knight0d1bb792018-10-04 18:49:21 +0000257 return printGNUSmallMemberHeader(Out, M.MemberName, ModTime, M.UID, M.GID,
Rafael Espindola476a7f92017-10-03 20:59:43 +0000258 M.Perms, Size);
259 Out << '/';
260 uint64_t NamePos = StringTable.tell();
261 addToStringTable(StringTable, ArcName, M, Thin);
262 printWithSpacePadding(Out, NamePos, 15);
James Y Knight0d1bb792018-10-04 18:49:21 +0000263 printRestOfMemberHeader(Out, ModTime, M.UID, M.GID, M.Perms, Size);
Rafael Espindola476a7f92017-10-03 20:59:43 +0000264}
Rafael Espindola06d6d192015-07-16 00:14:49 +0000265
Rafael Espindola476a7f92017-10-03 20:59:43 +0000266namespace {
267struct MemberData {
268 std::vector<unsigned> Symbols;
269 std::string Header;
270 StringRef Data;
271 StringRef Padding;
272};
273} // namespace
274
275static MemberData computeStringTable(StringRef Names) {
276 unsigned Size = Names.size();
277 unsigned Pad = OffsetToAlignment(Size, 2);
278 std::string Header;
279 raw_string_ostream Out(Header);
280 printWithSpacePadding(Out, "//", 48);
281 printWithSpacePadding(Out, Size + Pad, 10);
282 Out << "`\n";
283 Out.flush();
284 return {{}, std::move(Header), Names, Pad ? "\n" : ""};
Peter Collingbournefd66a482015-06-08 02:32:01 +0000285}
286
Pavel Labathbff47b52016-10-24 13:38:27 +0000287static sys::TimePoint<std::chrono::seconds> now(bool Deterministic) {
288 using namespace std::chrono;
289
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000290 if (!Deterministic)
Pavel Labathbff47b52016-10-24 13:38:27 +0000291 return time_point_cast<seconds>(system_clock::now());
292 return sys::TimePoint<seconds>();
Rafael Espindola6a8e86f2015-07-13 20:38:09 +0000293}
294
Rafael Espindolad901dee2017-09-22 18:40:14 +0000295static bool isArchiveSymbol(const object::BasicSymbolRef &S) {
296 uint32_t Symflags = S.getFlags();
297 if (Symflags & object::SymbolRef::SF_FormatSpecific)
298 return false;
299 if (!(Symflags & object::SymbolRef::SF_Global))
300 return false;
Martin Storsjoa6ffc9c2018-07-20 20:48:29 +0000301 if (Symflags & object::SymbolRef::SF_Undefined)
Rafael Espindolad901dee2017-09-22 18:40:14 +0000302 return false;
303 return true;
304}
305
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000306static void printNBits(raw_ostream &Out, object::Archive::Kind Kind,
307 uint64_t Val) {
308 if (is64BitKind(Kind))
309 print<uint64_t>(Out, Kind, Val);
310 else
311 print<uint32_t>(Out, Kind, Val);
312}
313
Rafael Espindola476a7f92017-10-03 20:59:43 +0000314static void writeSymbolTable(raw_ostream &Out, object::Archive::Kind Kind,
315 bool Deterministic, ArrayRef<MemberData> Members,
316 StringRef StringTable) {
317 if (StringTable.empty())
318 return;
Peter Collingbournefd66a482015-06-08 02:32:01 +0000319
Rafael Espindola476a7f92017-10-03 20:59:43 +0000320 unsigned NumSyms = 0;
321 for (const MemberData &M : Members)
322 NumSyms += M.Symbols.size();
Peter Collingbournefd66a482015-06-08 02:32:01 +0000323
Rafael Espindola476a7f92017-10-03 20:59:43 +0000324 unsigned Size = 0;
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000325 Size += is64BitKind(Kind) ? 8 : 4; // Number of entries
Rafael Espindola23a76be2017-02-21 20:40:54 +0000326 if (isBSDLike(Kind))
Rafael Espindola476a7f92017-10-03 20:59:43 +0000327 Size += NumSyms * 8; // Table
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000328 else if (is64BitKind(Kind))
329 Size += NumSyms * 8; // Table
Rafael Espindola476a7f92017-10-03 20:59:43 +0000330 else
331 Size += NumSyms * 4; // Table
Rafael Espindola23a76be2017-02-21 20:40:54 +0000332 if (isBSDLike(Kind))
Rafael Espindola476a7f92017-10-03 20:59:43 +0000333 Size += 4; // byte count
334 Size += StringTable.size();
Rafael Espindola0bd982b2017-09-22 18:36:00 +0000335 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
336 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
337 // uniformly.
338 // We do this for all bsd formats because it simplifies aligning members.
339 unsigned Alignment = isBSDLike(Kind) ? 8 : 2;
Rafael Espindola476a7f92017-10-03 20:59:43 +0000340 unsigned Pad = OffsetToAlignment(Size, Alignment);
341 Size += Pad;
Peter Collingbournefd66a482015-06-08 02:32:01 +0000342
Rafael Espindola476a7f92017-10-03 20:59:43 +0000343 if (isBSDLike(Kind))
344 printBSDMemberHeader(Out, Out.tell(), "__.SYMDEF", now(Deterministic), 0, 0,
345 0, Size);
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000346 else if (is64BitKind(Kind))
347 printGNUSmallMemberHeader(Out, "/SYM64", now(Deterministic), 0, 0, 0, Size);
Rafael Espindola476a7f92017-10-03 20:59:43 +0000348 else
349 printGNUSmallMemberHeader(Out, "", now(Deterministic), 0, 0, 0, Size);
Rafael Espindolac79bff62015-07-09 15:56:23 +0000350
Rafael Espindola476a7f92017-10-03 20:59:43 +0000351 uint64_t Pos = Out.tell() + Size;
352
Rafael Espindola23a76be2017-02-21 20:40:54 +0000353 if (isBSDLike(Kind))
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000354 print<uint32_t>(Out, Kind, NumSyms * 8);
Rafael Espindola23a76be2017-02-21 20:40:54 +0000355 else
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000356 printNBits(Out, Kind, NumSyms);
Rafael Espindolac79bff62015-07-09 15:56:23 +0000357
Rafael Espindola476a7f92017-10-03 20:59:43 +0000358 for (const MemberData &M : Members) {
359 for (unsigned StringOffset : M.Symbols) {
360 if (isBSDLike(Kind))
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000361 print<uint32_t>(Out, Kind, StringOffset);
362 printNBits(Out, Kind, Pos); // member offset
Rafael Espindola476a7f92017-10-03 20:59:43 +0000363 }
364 Pos += M.Header.size() + M.Data.size() + M.Padding.size();
365 }
366
367 if (isBSDLike(Kind))
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000368 // byte count of the string table
369 print<uint32_t>(Out, Kind, StringTable.size());
Rafael Espindola476a7f92017-10-03 20:59:43 +0000370 Out << StringTable;
371
372 while (Pad--)
373 Out.write(uint8_t(0));
374}
375
376static Expected<std::vector<unsigned>>
377getSymbols(MemoryBufferRef Buf, raw_ostream &SymNames, bool &HasObject) {
378 std::vector<unsigned> Ret;
Rafael Espindola476a7f92017-10-03 20:59:43 +0000379
Alexander Shaposhnikov72b27a62018-09-11 22:00:47 +0000380 // In the scenario when LLVMContext is populated SymbolicFile will contain a
381 // reference to it, thus SymbolicFile should be destroyed first.
382 LLVMContext Context;
383 std::unique_ptr<object::SymbolicFile> Obj;
384 if (identify_magic(Buf.getBuffer()) == file_magic::bitcode) {
385 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
386 Buf, file_magic::bitcode, &Context);
387 if (!ObjOrErr) {
388 // FIXME: check only for "not an object file" errors.
389 consumeError(ObjOrErr.takeError());
390 return Ret;
391 }
392 Obj = std::move(*ObjOrErr);
393 } else {
394 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
395 if (!ObjOrErr) {
396 // FIXME: check only for "not an object file" errors.
397 consumeError(ObjOrErr.takeError());
398 return Ret;
399 }
400 Obj = std::move(*ObjOrErr);
Rafael Espindola476a7f92017-10-03 20:59:43 +0000401 }
402
403 HasObject = true;
Alexander Shaposhnikov72b27a62018-09-11 22:00:47 +0000404 for (const object::BasicSymbolRef &S : Obj->symbols()) {
Rafael Espindola476a7f92017-10-03 20:59:43 +0000405 if (!isArchiveSymbol(S))
406 continue;
407 Ret.push_back(SymNames.tell());
408 if (auto EC = S.printName(SymNames))
409 return errorCodeToError(EC);
410 SymNames << '\0';
411 }
412 return Ret;
413}
414
415static Expected<std::vector<MemberData>>
416computeMemberData(raw_ostream &StringTable, raw_ostream &SymNames,
417 object::Archive::Kind Kind, bool Thin, StringRef ArcName,
James Y Knight0d1bb792018-10-04 18:49:21 +0000418 bool Deterministic, ArrayRef<NewArchiveMember> NewMembers) {
Rafael Espindola476a7f92017-10-03 20:59:43 +0000419 static char PaddingData[8] = {'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'};
420
421 // This ignores the symbol table, but we only need the value mod 8 and the
422 // symbol table is aligned to be a multiple of 8 bytes
423 uint64_t Pos = 0;
424
425 std::vector<MemberData> Ret;
426 bool HasObject = false;
James Y Knight0d1bb792018-10-04 18:49:21 +0000427
428 // UniqueTimestamps is a special case to improve debugging on Darwin:
429 //
430 // The Darwin linker does not link debug info into the final
431 // binary. Instead, it emits entries of type N_OSO in in the output
432 // binary's symbol table, containing references to the linked-in
433 // object files. Using that reference, the debugger can read the
434 // debug data directly from the object files. Alternatively, an
435 // invocation of 'dsymutil' will link the debug data from the object
436 // files into a dSYM bundle, which can be loaded by the debugger,
437 // instead of the object files.
438 //
439 // For an object file, the N_OSO entries contain the absolute path
440 // path to the file, and the file's timestamp. For an object
441 // included in an archive, the path is formatted like
442 // "/absolute/path/to/archive.a(member.o)", and the timestamp is the
443 // archive member's timestamp, rather than the archive's timestamp.
444 //
445 // However, this doesn't always uniquely identify an object within
446 // an archive -- an archive file can have multiple entries with the
447 // same filename. (This will happen commonly if the original object
448 // files started in different directories.) The only way they get
449 // distinguished, then, is via the timestamp. But this process is
450 // unable to find the correct object file in the archive when there
451 // are two files of the same name and timestamp.
452 //
453 // Additionally, timestamp==0 is treated specially, and causes the
454 // timestamp to be ignored as a match criteria.
455 //
456 // That will "usually" work out okay when creating an archive not in
457 // deterministic timestamp mode, because the objects will probably
458 // have been created at different timestamps.
459 //
460 // To ameliorate this problem, in deterministic archive mode (which
461 // is the default), on Darwin we will emit a unique non-zero
462 // timestamp for each entry with a duplicated name. This is still
463 // deterministic: the only thing affecting that timestamp is the
464 // order of the files in the resultant archive.
465 //
466 // See also the functions that handle the lookup:
467 // in lldb: ObjectContainerBSDArchive::Archive::FindObject()
468 // in llvm/tools/dsymutil: BinaryHolder::GetArchiveMemberBuffers().
469 bool UniqueTimestamps =
470 Deterministic && (Kind == object::Archive::K_DARWIN ||
471 Kind == object::Archive::K_DARWIN64);
472 std::map<StringRef, unsigned> FilenameCount;
473 if (UniqueTimestamps) {
474 for (const NewArchiveMember &M : NewMembers)
475 FilenameCount[M.MemberName]++;
476 for (auto &Entry : FilenameCount)
477 Entry.second = Entry.second > 1 ? 1 : 0;
478 }
479
Rafael Espindola476a7f92017-10-03 20:59:43 +0000480 for (const NewArchiveMember &M : NewMembers) {
481 std::string Header;
482 raw_string_ostream Out(Header);
483
484 MemoryBufferRef Buf = M.Buf->getMemBufferRef();
485 StringRef Data = Thin ? "" : Buf.getBuffer();
486
487 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
488 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
489 // uniformly. This matches the behaviour with cctools and ensures that ld64
490 // is happy with archives that we generate.
491 unsigned MemberPadding = Kind == object::Archive::K_DARWIN
492 ? OffsetToAlignment(Data.size(), 8)
493 : 0;
494 unsigned TailPadding = OffsetToAlignment(Data.size() + MemberPadding, 2);
495 StringRef Padding = StringRef(PaddingData, MemberPadding + TailPadding);
496
James Y Knight0d1bb792018-10-04 18:49:21 +0000497 sys::TimePoint<std::chrono::seconds> ModTime;
498 if (UniqueTimestamps)
499 // Increment timestamp for each file of a given name.
500 ModTime = sys::toTimePoint(FilenameCount[M.MemberName]++);
501 else
502 ModTime = M.ModTime;
503 printMemberHeader(Out, Pos, StringTable, Kind, Thin, ArcName, M, ModTime,
Rafael Espindola476a7f92017-10-03 20:59:43 +0000504 Buf.getBufferSize() + MemberPadding);
505 Out.flush();
506
507 Expected<std::vector<unsigned>> Symbols =
508 getSymbols(Buf, SymNames, HasObject);
509 if (auto E = Symbols.takeError())
510 return std::move(E);
511
512 Pos += Header.size() + Data.size() + Padding.size();
513 Ret.push_back({std::move(*Symbols), std::move(Header), Data, Padding});
514 }
515 // If there are no symbols, emit an empty symbol table, to satisfy Solaris
516 // tools, older versions of which expect a symbol table in a non-empty
517 // archive, regardless of whether there are any symbols in it.
518 if (HasObject && SymNames.tell() == 0)
519 SymNames << '\0' << '\0' << '\0';
520 return Ret;
Peter Collingbournefd66a482015-06-08 02:32:01 +0000521}
522
Rafael Espindola25cbdf22017-09-21 23:13:36 +0000523Error llvm::writeArchive(StringRef ArcName,
524 ArrayRef<NewArchiveMember> NewMembers,
525 bool WriteSymtab, object::Archive::Kind Kind,
526 bool Deterministic, bool Thin,
527 std::unique_ptr<MemoryBuffer> OldArchiveBuf) {
Rafael Espindola23a76be2017-02-21 20:40:54 +0000528 assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");
Rafael Espindola476a7f92017-10-03 20:59:43 +0000529
530 SmallString<0> SymNamesBuf;
531 raw_svector_ostream SymNames(SymNamesBuf);
532 SmallString<0> StringTableBuf;
533 raw_svector_ostream StringTable(StringTableBuf);
534
James Y Knight0d1bb792018-10-04 18:49:21 +0000535 Expected<std::vector<MemberData>> DataOrErr = computeMemberData(
536 StringTable, SymNames, Kind, Thin, ArcName, Deterministic, NewMembers);
Rafael Espindola476a7f92017-10-03 20:59:43 +0000537 if (Error E = DataOrErr.takeError())
538 return E;
539 std::vector<MemberData> &Data = *DataOrErr;
540
541 if (!StringTableBuf.empty())
542 Data.insert(Data.begin(), computeStringTable(StringTableBuf));
543
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000544 // We would like to detect if we need to switch to a 64-bit symbol table.
545 if (WriteSymtab) {
546 uint64_t MaxOffset = 0;
547 uint64_t LastOffset = MaxOffset;
Alexander Shaposhnikov72b27a62018-09-11 22:00:47 +0000548 for (const auto &M : Data) {
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000549 // Record the start of the member's offset
550 LastOffset = MaxOffset;
551 // Account for the size of each part associated with the member.
552 MaxOffset += M.Header.size() + M.Data.size() + M.Padding.size();
553 // We assume 32-bit symbols to see if 32-bit symbols are possible or not.
554 MaxOffset += M.Symbols.size() * 4;
555 }
Peter Collingbourned579c312018-03-28 17:21:14 +0000556
557 // The SYM64 format is used when an archive's member offsets are larger than
558 // 32-bits can hold. The need for this shift in format is detected by
559 // writeArchive. To test this we need to generate a file with a member that
560 // has an offset larger than 32-bits but this demands a very slow test. To
561 // speed the test up we use this environment variable to pretend like the
562 // cutoff happens before 32-bits and instead happens at some much smaller
563 // value.
564 const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
565 int Sym64Threshold = 32;
566 if (Sym64Env)
567 StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
568
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000569 // If LastOffset isn't going to fit in a 32-bit varible we need to switch
570 // to 64-bit. Note that the file can be larger than 4GB as long as the last
571 // member starts before the 4GB offset.
Jake Ehrlich1a468482017-12-01 00:54:28 +0000572 if (LastOffset >= (1ULL << Sym64Threshold))
Jake Ehrlichc3a89ee2017-11-03 19:15:06 +0000573 Kind = object::Archive::K_GNU64;
574 }
575
Rafael Espindolac02eacf2017-11-14 01:21:15 +0000576 Expected<sys::fs::TempFile> Temp =
577 sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
578 if (!Temp)
579 return Temp.takeError();
Peter Collingbournefd66a482015-06-08 02:32:01 +0000580
Rafael Espindolac02eacf2017-11-14 01:21:15 +0000581 raw_fd_ostream Out(Temp->FD, false);
Rafael Espindolae6492582015-07-15 05:47:46 +0000582 if (Thin)
583 Out << "!<thin>\n";
584 else
585 Out << "!<arch>\n";
Peter Collingbournefd66a482015-06-08 02:32:01 +0000586
Rafael Espindola476a7f92017-10-03 20:59:43 +0000587 if (WriteSymtab)
588 writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000589
Rafael Espindola476a7f92017-10-03 20:59:43 +0000590 for (const MemberData &M : Data)
591 Out << M.Header << M.Data << M.Padding;
Peter Collingbournefd66a482015-06-08 02:32:01 +0000592
Rafael Espindolac02eacf2017-11-14 01:21:15 +0000593 Out.flush();
Rafael Espindola484983f2016-05-09 13:31:11 +0000594
595 // At this point, we no longer need whatever backing memory
596 // was used to generate the NewMembers. On Windows, this buffer
597 // could be a mapped view of the file we want to replace (if
598 // we're updating an existing archive, say). In that case, the
599 // rename would still succeed, but it would leave behind a
600 // temporary file (actually the original file renamed) because
601 // a file cannot be deleted while there's a handle open on it,
602 // only renamed. So by freeing this buffer, this ensures that
603 // the last open handle on the destination file, if any, is
604 // closed before we attempt to rename.
605 OldArchiveBuf.reset();
606
Rafael Espindolac02eacf2017-11-14 01:21:15 +0000607 return Temp->keep(ArcName);
Peter Collingbournefd66a482015-06-08 02:32:01 +0000608}