blob: 59fb7bdd3ffdb20abe0717cb1697af29eb5ef364 [file] [log] [blame]
Reid Spencercf6afc62004-11-14 21:56:59 +00001//===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Reid Spencer362cbf02004-11-06 08:51:45 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Reid Spencer362cbf02004-11-06 08:51:45 +00008//===----------------------------------------------------------------------===//
9//
Gabor Greifa99be512007-07-05 17:07:56 +000010// Builds up an LLVM archive file (.a) containing LLVM bitcode.
Reid Spencer362cbf02004-11-06 08:51:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "ArchiveInternals.h"
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000015#include "llvm/Module.h"
Chris Lattner7f6b4472008-04-01 04:26:46 +000016#include "llvm/ADT/OwningPtr.h"
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000017#include "llvm/Bitcode/ReaderWriter.h"
Michael J. Spencer54453f22011-01-10 02:34:23 +000018#include "llvm/Support/FileSystem.h"
Chris Lattner7f6b4472008-04-01 04:26:46 +000019#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000020#include "llvm/Support/Process.h"
Michael J. Spencere7a820c2011-01-16 23:39:59 +000021#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000022#include "llvm/Support/Signals.h"
Michael J. Spencer333fb042010-12-09 17:36:48 +000023#include "llvm/Support/system_error.h"
Reid Spencer362cbf02004-11-06 08:51:45 +000024#include <fstream>
Bill Wendlinga21900d2006-11-28 22:49:32 +000025#include <ostream>
Reid Spencercf6afc62004-11-14 21:56:59 +000026#include <iomanip>
Reid Spencer362cbf02004-11-06 08:51:45 +000027using namespace llvm;
28
Reid Spencercf6afc62004-11-14 21:56:59 +000029// Write an integer using variable bit rate encoding. This saves a few bytes
30// per entry in the symbol table.
Michael J. Spencere7a820c2011-01-16 23:39:59 +000031static inline void writeInteger(unsigned num, raw_ostream& ARFile) {
Reid Spencercf6afc62004-11-14 21:56:59 +000032 while (1) {
33 if (num < 0x80) { // done?
34 ARFile << (unsigned char)num;
35 return;
36 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +000037
Reid Spencercf6afc62004-11-14 21:56:59 +000038 // Nope, we are bigger than a character, output the next 7 bits and set the
39 // high bit to say that there is more coming...
40 ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
41 num >>= 7; // Shift out 7 bits now...
42 }
43}
44
45// Compute how many bytes are taken by a given VBR encoded value. This is needed
46// to pre-compute the size of the symbol table.
Dan Gohman844731a2008-05-13 00:00:25 +000047static inline unsigned numVbrBytes(unsigned num) {
Reid Spencercf6afc62004-11-14 21:56:59 +000048
Reid Spencer87f90722004-11-16 06:47:30 +000049 // Note that the following nested ifs are somewhat equivalent to a binary
50 // search. We split it in half by comparing against 2^14 first. This allows
Misha Brukman2b37d7c2005-04-21 21:13:18 +000051 // most reasonable values to be done in 2 comparisons instead of 1 for
Reid Spencer87f90722004-11-16 06:47:30 +000052 // small ones and four for large ones. We expect this to access file offsets
Misha Brukman2b37d7c2005-04-21 21:13:18 +000053 // in the 2^10 to 2^24 range and symbol lengths in the 2^0 to 2^8 range,
Reid Spencer87f90722004-11-16 06:47:30 +000054 // so this approach is reasonable.
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +000055 if (num < 1<<14) {
Reid Spencer87f90722004-11-16 06:47:30 +000056 if (num < 1<<7)
57 return 1;
58 else
59 return 2;
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +000060 }
Reid Spencer87f90722004-11-16 06:47:30 +000061 if (num < 1<<21)
62 return 3;
63
64 if (num < 1<<28)
65 return 4;
66 return 5; // anything >= 2^28 takes 5 bytes
Reid Spencercf6afc62004-11-14 21:56:59 +000067}
68
69// Create an empty archive.
Owen Anderson4434ed42009-07-01 23:13:44 +000070Archive* Archive::CreateEmpty(const sys::Path& FilePath, LLVMContext& C) {
Owen Anderson8b477ed2009-07-01 16:58:40 +000071 Archive* result = new Archive(FilePath, C);
Reid Spencer362cbf02004-11-06 08:51:45 +000072 return result;
73}
74
Misha Brukman2b37d7c2005-04-21 21:13:18 +000075// Fill the ArchiveMemberHeader with the information from a member. If
Reid Spencer87f90722004-11-16 06:47:30 +000076// TruncateNames is true, names are flattened to 15 chars or less. The sz field
Misha Brukman2b37d7c2005-04-21 21:13:18 +000077// is provided here instead of coming from the mbr because the member might be
78// stored compressed and the compressed size is not the ArchiveMember's size.
79// Furthermore compressed files have negative size fields to identify them as
Reid Spencer87f90722004-11-16 06:47:30 +000080// compressed.
Reid Spencercf6afc62004-11-14 21:56:59 +000081bool
82Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
83 int sz, bool TruncateNames) const {
Reid Spencer362cbf02004-11-06 08:51:45 +000084
Reid Spencercf6afc62004-11-14 21:56:59 +000085 // Set the permissions mode, uid and gid
86 hdr.init();
87 char buffer[32];
88 sprintf(buffer, "%-8o", mbr.getMode());
89 memcpy(hdr.mode,buffer,8);
90 sprintf(buffer, "%-6u", mbr.getUser());
91 memcpy(hdr.uid,buffer,6);
92 sprintf(buffer, "%-6u", mbr.getGroup());
93 memcpy(hdr.gid,buffer,6);
94
Reid Spencercf6afc62004-11-14 21:56:59 +000095 // Set the last modification date
96 uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
97 sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
98 memcpy(hdr.date,buffer,12);
99
Reid Spencerd4543da2004-11-17 18:28:29 +0000100 // Get rid of trailing blanks in the name
Chris Lattner74382b72009-08-23 22:45:37 +0000101 std::string mbrPath = mbr.getPath().str();
Reid Spencerd4543da2004-11-17 18:28:29 +0000102 size_t mbrLen = mbrPath.length();
103 while (mbrLen > 0 && mbrPath[mbrLen-1] == ' ') {
104 mbrPath.erase(mbrLen-1,1);
105 mbrLen--;
106 }
107
Reid Spencercf6afc62004-11-14 21:56:59 +0000108 // Set the name field in one of its various flavors.
109 bool writeLongName = false;
Reid Spencercf6afc62004-11-14 21:56:59 +0000110 if (mbr.isStringTable()) {
111 memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
Reid Spencer9a29db42004-11-20 07:29:40 +0000112 } else if (mbr.isSVR4SymbolTable()) {
113 memcpy(hdr.name,ARFILE_SVR4_SYMTAB_NAME,16);
114 } else if (mbr.isBSD4SymbolTable()) {
115 memcpy(hdr.name,ARFILE_BSD4_SYMTAB_NAME,16);
Reid Spencercf6afc62004-11-14 21:56:59 +0000116 } else if (mbr.isLLVMSymbolTable()) {
117 memcpy(hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
118 } else if (TruncateNames) {
119 const char* nm = mbrPath.c_str();
120 unsigned len = mbrPath.length();
121 size_t slashpos = mbrPath.rfind('/');
122 if (slashpos != std::string::npos) {
123 nm += slashpos + 1;
124 len -= slashpos +1;
125 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000126 if (len > 15)
Reid Spencercf6afc62004-11-14 21:56:59 +0000127 len = 15;
Reid Spencer87f90722004-11-16 06:47:30 +0000128 memcpy(hdr.name,nm,len);
Reid Spencercf6afc62004-11-14 21:56:59 +0000129 hdr.name[len] = '/';
130 } else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
Reid Spencerd4543da2004-11-17 18:28:29 +0000131 memcpy(hdr.name,mbrPath.c_str(),mbrPath.length());
Reid Spencercf6afc62004-11-14 21:56:59 +0000132 hdr.name[mbrPath.length()] = '/';
133 } else {
134 std::string nm = "#1/";
135 nm += utostr(mbrPath.length());
Reid Spencerd4543da2004-11-17 18:28:29 +0000136 memcpy(hdr.name,nm.data(),nm.length());
Reid Spencer96ce3352004-11-17 16:14:21 +0000137 if (sz < 0)
138 sz -= mbrPath.length();
139 else
140 sz += mbrPath.length();
Reid Spencercf6afc62004-11-14 21:56:59 +0000141 writeLongName = true;
142 }
Reid Spencer96ce3352004-11-17 16:14:21 +0000143
144 // Set the size field
145 if (sz < 0) {
146 buffer[0] = '-';
147 sprintf(&buffer[1],"%-9u",(unsigned)-sz);
148 } else {
149 sprintf(buffer, "%-10u", (unsigned)sz);
150 }
151 memcpy(hdr.size,buffer,10);
152
Reid Spencercf6afc62004-11-14 21:56:59 +0000153 return writeLongName;
154}
155
Reid Spencer87f90722004-11-16 06:47:30 +0000156// Insert a file into the archive before some other member. This also takes care
157// of extracting the necessary flags and information from the file.
Reid Spencer0ff2d312006-08-24 23:45:08 +0000158bool
Michael J. Spencer83a113b2011-01-10 02:34:40 +0000159Archive::addFileBefore(const sys::Path& filePath, iterator where,
Reid Spencer0ff2d312006-08-24 23:45:08 +0000160 std::string* ErrMsg) {
Michael J. Spencer54453f22011-01-10 02:34:23 +0000161 bool Exists;
162 if (sys::fs::exists(filePath.str(), Exists) || !Exists) {
Reid Spencercd5561a2006-12-15 19:44:51 +0000163 if (ErrMsg)
164 *ErrMsg = "Can not add a non-existent file to archive";
165 return true;
166 }
Reid Spencercf6afc62004-11-14 21:56:59 +0000167
168 ArchiveMember* mbr = new ArchiveMember(this);
169
170 mbr->data = 0;
171 mbr->path = filePath;
Reid Spencer8475ec02007-03-29 19:05:44 +0000172 const sys::FileStatus *FSInfo = mbr->path.getFileStatus(false, ErrMsg);
Duncan Sands861d20a2009-06-11 08:09:49 +0000173 if (!FSInfo) {
174 delete mbr;
Reid Spencer0ff2d312006-08-24 23:45:08 +0000175 return true;
Duncan Sands861d20a2009-06-11 08:09:49 +0000176 }
177 mbr->info = *FSInfo;
Reid Spencercf6afc62004-11-14 21:56:59 +0000178
179 unsigned flags = 0;
Chris Lattner74382b72009-08-23 22:45:37 +0000180 bool hasSlash = filePath.str().find('/') != std::string::npos;
Reid Spencercf6afc62004-11-14 21:56:59 +0000181 if (hasSlash)
182 flags |= ArchiveMember::HasPathFlag;
Chris Lattner74382b72009-08-23 22:45:37 +0000183 if (hasSlash || filePath.str().length() > 15)
Reid Spencercf6afc62004-11-14 21:56:59 +0000184 flags |= ArchiveMember::HasLongFilenameFlag;
Michael J. Spencer3c98e142011-01-16 21:13:51 +0000185
186 sys::LLVMFileType type;
187 if (sys::fs::identify_magic(mbr->path.str(), type))
188 type = sys::Unknown_FileType;
189 switch (type) {
Chris Lattnere07c15c2007-05-06 06:18:07 +0000190 case sys::Bitcode_FileType:
Gabor Greife75ca3d2007-07-06 13:38:17 +0000191 flags |= ArchiveMember::BitcodeFlag;
Reid Spencercf6afc62004-11-14 21:56:59 +0000192 break;
193 default:
194 break;
195 }
196 mbr->flags = flags;
197 members.insert(where,mbr);
Reid Spencer0ff2d312006-08-24 23:45:08 +0000198 return false;
Reid Spencercf6afc62004-11-14 21:56:59 +0000199}
200
Reid Spencer87f90722004-11-16 06:47:30 +0000201// Write one member out to the file.
Reid Spencer3039b992006-07-07 19:09:14 +0000202bool
Reid Spencercf6afc62004-11-14 21:56:59 +0000203Archive::writeMember(
204 const ArchiveMember& member,
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000205 raw_ostream& ARFile,
Reid Spencercf6afc62004-11-14 21:56:59 +0000206 bool CreateSymbolTable,
207 bool TruncateNames,
Reid Spencer3039b992006-07-07 19:09:14 +0000208 bool ShouldCompress,
Reid Spencer0ff2d312006-08-24 23:45:08 +0000209 std::string* ErrMsg
Reid Spencercf6afc62004-11-14 21:56:59 +0000210) {
211
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000212 unsigned filepos = ARFile.tell();
Reid Spencercf6afc62004-11-14 21:56:59 +0000213 filepos -= 8;
214
215 // Get the data and its size either from the
216 // member's in-memory data or directly from the file.
217 size_t fSize = member.getSize();
Chris Lattner7f6b4472008-04-01 04:26:46 +0000218 const char *data = (const char*)member.getData();
219 MemoryBuffer *mFile = 0;
Reid Spencercf6afc62004-11-14 21:56:59 +0000220 if (!data) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000221 OwningPtr<MemoryBuffer> File;
222 if (error_code ec = MemoryBuffer::getFile(member.getPath().c_str(), File)) {
Michael J. Spencer333fb042010-12-09 17:36:48 +0000223 if (ErrMsg)
224 *ErrMsg = ec.message();
Reid Spencer0ff2d312006-08-24 23:45:08 +0000225 return true;
Michael J. Spencer333fb042010-12-09 17:36:48 +0000226 }
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000227 mFile = File.take();
Chris Lattner7f6b4472008-04-01 04:26:46 +0000228 data = mFile->getBufferStart();
229 fSize = mFile->getBufferSize();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000230 }
Reid Spencercf6afc62004-11-14 21:56:59 +0000231
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000232 // Now that we have the data in memory, update the
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000233 // symbol table if it's a bitcode file.
Gabor Greife75ca3d2007-07-06 13:38:17 +0000234 if (CreateSymbolTable && member.isBitcode()) {
Reid Spencercf6afc62004-11-14 21:56:59 +0000235 std::vector<std::string> symbols;
Chris Lattner74382b72009-08-23 22:45:37 +0000236 std::string FullMemberName = archPath.str() + "(" + member.getPath().str()
Reid Spencerd4543da2004-11-17 18:28:29 +0000237 + ")";
Michael J. Spencer83a113b2011-01-10 02:34:40 +0000238 Module* M =
Benjamin Kramer9d44e702010-04-19 16:15:31 +0000239 GetBitcodeSymbols(data, fSize, FullMemberName, Context, symbols, ErrMsg);
Reid Spencercf6afc62004-11-14 21:56:59 +0000240
Gabor Greifa99be512007-07-05 17:07:56 +0000241 // If the bitcode parsed successfully
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000242 if ( M ) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000243 for (std::vector<std::string>::iterator SI = symbols.begin(),
Reid Spencer766b7932004-11-15 01:20:11 +0000244 SE = symbols.end(); SI != SE; ++SI) {
Reid Spencercf6afc62004-11-14 21:56:59 +0000245
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000246 std::pair<SymTabType::iterator,bool> Res =
Reid Spencer766b7932004-11-15 01:20:11 +0000247 symTab.insert(std::make_pair(*SI,filepos));
248
249 if (Res.second) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000250 symTabSize += SI->length() +
251 numVbrBytes(SI->length()) +
Reid Spencer766b7932004-11-15 01:20:11 +0000252 numVbrBytes(filepos);
253 }
Reid Spencer362cbf02004-11-06 08:51:45 +0000254 }
Reid Spencer766b7932004-11-15 01:20:11 +0000255 // We don't need this module any more.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000256 delete M;
Reid Spencer766b7932004-11-15 01:20:11 +0000257 } else {
Chris Lattner7f6b4472008-04-01 04:26:46 +0000258 delete mFile;
Reid Spencer0ff2d312006-08-24 23:45:08 +0000259 if (ErrMsg)
Chris Lattner74382b72009-08-23 22:45:37 +0000260 *ErrMsg = "Can't parse bitcode member: " + member.getPath().str()
Reid Spencer0b5a5042006-08-25 17:43:11 +0000261 + ": " + *ErrMsg;
Reid Spencer0ff2d312006-08-24 23:45:08 +0000262 return true;
Reid Spencer362cbf02004-11-06 08:51:45 +0000263 }
264 }
Reid Spencer362cbf02004-11-06 08:51:45 +0000265
Chris Lattnere07c15c2007-05-06 06:18:07 +0000266 int hdrSize = fSize;
Reid Spencer362cbf02004-11-06 08:51:45 +0000267
Reid Spencercf6afc62004-11-14 21:56:59 +0000268 // Compute the fields of the header
Reid Spencer362cbf02004-11-06 08:51:45 +0000269 ArchiveMemberHeader Hdr;
Reid Spencercf6afc62004-11-14 21:56:59 +0000270 bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
Reid Spencer362cbf02004-11-06 08:51:45 +0000271
272 // Write header to archive file
273 ARFile.write((char*)&Hdr, sizeof(Hdr));
Reid Spencer362cbf02004-11-06 08:51:45 +0000274
Reid Spencercf6afc62004-11-14 21:56:59 +0000275 // Write the long filename if its long
276 if (writeLongName) {
Chris Lattner74382b72009-08-23 22:45:37 +0000277 ARFile.write(member.getPath().str().data(),
278 member.getPath().str().length());
Reid Spencercf6afc62004-11-14 21:56:59 +0000279 }
280
Reid Spencercf6afc62004-11-14 21:56:59 +0000281 // Write the (possibly compressed) member's content to the file.
282 ARFile.write(data,fSize);
283
284 // Make sure the member is an even length
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000285 if ((ARFile.tell() & 1) == 1)
Reid Spencercf6afc62004-11-14 21:56:59 +0000286 ARFile << ARFILE_PAD;
287
Reid Spencercf6afc62004-11-14 21:56:59 +0000288 // Close the mapped file if it was opened
Chris Lattner7f6b4472008-04-01 04:26:46 +0000289 delete mFile;
Reid Spencer0ff2d312006-08-24 23:45:08 +0000290 return false;
Reid Spencer362cbf02004-11-06 08:51:45 +0000291}
292
Reid Spencer87f90722004-11-16 06:47:30 +0000293// Write out the LLVM symbol table as an archive member to the file.
Reid Spencer362cbf02004-11-06 08:51:45 +0000294void
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000295Archive::writeSymbolTable(raw_ostream& ARFile) {
Reid Spencercf6afc62004-11-14 21:56:59 +0000296
297 // Construct the symbol table's header
298 ArchiveMemberHeader Hdr;
299 Hdr.init();
300 memcpy(Hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
301 uint64_t secondsSinceEpoch = sys::TimeValue::now().toEpochTime();
302 char buffer[32];
Misha Brukman4b2afe62005-04-20 03:55:35 +0000303 sprintf(buffer, "%-8o", 0644);
304 memcpy(Hdr.mode,buffer,8);
Reid Spencer3468e572005-04-21 16:15:19 +0000305 sprintf(buffer, "%-6u", sys::Process::GetCurrentUserId());
Misha Brukman4b2afe62005-04-20 03:55:35 +0000306 memcpy(Hdr.uid,buffer,6);
Reid Spencer3468e572005-04-21 16:15:19 +0000307 sprintf(buffer, "%-6u", sys::Process::GetCurrentGroupId());
Misha Brukman4b2afe62005-04-20 03:55:35 +0000308 memcpy(Hdr.gid,buffer,6);
Reid Spencercf6afc62004-11-14 21:56:59 +0000309 sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
310 memcpy(Hdr.date,buffer,12);
311 sprintf(buffer,"%-10u",symTabSize);
312 memcpy(Hdr.size,buffer,10);
313
314 // Write the header
315 ARFile.write((char*)&Hdr, sizeof(Hdr));
316
Devang Patel59500c82008-11-21 20:00:59 +0000317#ifndef NDEBUG
Reid Spencercf6afc62004-11-14 21:56:59 +0000318 // Save the starting position of the symbol tables data content.
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000319 unsigned startpos = ARFile.tell();
Devang Patel59500c82008-11-21 20:00:59 +0000320#endif
Reid Spencercf6afc62004-11-14 21:56:59 +0000321
Reid Spencercf6afc62004-11-14 21:56:59 +0000322 // Write out the symbols sequentially
323 for ( Archive::SymTabType::iterator I = symTab.begin(), E = symTab.end();
324 I != E; ++I)
325 {
326 // Write out the file index
327 writeInteger(I->second, ARFile);
328 // Write out the length of the symbol
329 writeInteger(I->first.length(), ARFile);
330 // Write out the symbol
331 ARFile.write(I->first.data(), I->first.length());
Reid Spencer362cbf02004-11-06 08:51:45 +0000332 }
333
Devang Patel59500c82008-11-21 20:00:59 +0000334#ifndef NDEBUG
Reid Spencercf6afc62004-11-14 21:56:59 +0000335 // Now that we're done with the symbol table, get the ending file position
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000336 unsigned endpos = ARFile.tell();
Devang Patel59500c82008-11-21 20:00:59 +0000337#endif
Reid Spencer362cbf02004-11-06 08:51:45 +0000338
Reid Spencercf6afc62004-11-14 21:56:59 +0000339 // Make sure that the amount we wrote is what we pre-computed. This is
340 // critical for file integrity purposes.
341 assert(endpos - startpos == symTabSize && "Invalid symTabSize computation");
Reid Spencer362cbf02004-11-06 08:51:45 +0000342
Reid Spencercf6afc62004-11-14 21:56:59 +0000343 // Make sure the symbol table is even sized
344 if (symTabSize % 2 != 0 )
345 ARFile << ARFILE_PAD;
Reid Spencer362cbf02004-11-06 08:51:45 +0000346}
347
Reid Spencer87f90722004-11-16 06:47:30 +0000348// Write the entire archive to the file specified when the archive was created.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000349// This writes to a temporary file first. Options are for creating a symbol
350// table, flattening the file names (no directories, 15 chars max) and
Reid Spencer87f90722004-11-16 06:47:30 +0000351// compressing each archive member.
Reid Spencer3039b992006-07-07 19:09:14 +0000352bool
353Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
Reid Spencer0ff2d312006-08-24 23:45:08 +0000354 std::string* ErrMsg)
Reid Spencer3039b992006-07-07 19:09:14 +0000355{
Reid Spencercf6afc62004-11-14 21:56:59 +0000356 // Make sure they haven't opened up the file, not loaded it,
357 // but are now trying to write it which would wipe out the file.
Chris Lattner7f6b4472008-04-01 04:26:46 +0000358 if (members.empty() && mapfile && mapfile->getBufferSize() > 8) {
Reid Spencercd5561a2006-12-15 19:44:51 +0000359 if (ErrMsg)
360 *ErrMsg = "Can't write an archive not opened for writing";
361 return true;
362 }
Reid Spencercf6afc62004-11-14 21:56:59 +0000363
364 // Create a temporary file to store the archive in
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000365 SmallString<128> TempArchivePath;
366 int ArchFD;
367 if (error_code ec = sys::fs::unique_file("%%-%%-%%-%%" + archPath.str(),
368 ArchFD, TempArchivePath)) {
369 if (ErrMsg) *ErrMsg = ec.message();
Michael J. Spencerc8509652011-01-16 01:43:22 +0000370 return true;
371 }
Michael J. Spencer770772e2011-01-15 21:43:37 +0000372
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000373 // Make sure the temporary gets removed if we crash
374 sys::RemoveFileOnSignal(sys::Path(TempArchivePath.str()));
375
376 // Create archive file for output.
377 raw_fd_ostream ArchiveFile(ArchFD, true);
378
Reid Spencer3039b992006-07-07 19:09:14 +0000379 // If we're creating a symbol table, reset it now
380 if (CreateSymbolTable) {
381 symTabSize = 0;
382 symTab.clear();
383 }
384
385 // Write magic string to archive.
386 ArchiveFile << ARFILE_MAGIC;
387
388 // Loop over all member files, and write them out. Note that this also
389 // builds the symbol table, symTab.
Chris Lattner0c332312006-07-28 22:29:50 +0000390 for (MembersList::iterator I = begin(), E = end(); I != E; ++I) {
Reid Spencer0ff2d312006-08-24 23:45:08 +0000391 if (writeMember(*I, ArchiveFile, CreateSymbolTable,
392 TruncateNames, Compress, ErrMsg)) {
Reid Spencer3039b992006-07-07 19:09:14 +0000393 ArchiveFile.close();
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000394 bool existed;
395 sys::fs::remove(TempArchivePath.str(), existed);
Reid Spencer0ff2d312006-08-24 23:45:08 +0000396 return true;
Reid Spencer3039b992006-07-07 19:09:14 +0000397 }
398 }
399
400 // Close archive file.
401 ArchiveFile.close();
402
403 // Write the symbol table
404 if (CreateSymbolTable) {
405 // At this point we have written a file that is a legal archive but it
406 // doesn't have a symbol table in it. To aid in faster reading and to
407 // ensure compatibility with other archivers we need to put the symbol
408 // table first in the file. Unfortunately, this means mapping the file
409 // we just wrote back in and copying it to the destination file.
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000410 SmallString<128> TempArchiveWithSymbolTablePath;
Reid Spencer3039b992006-07-07 19:09:14 +0000411
412 // Map in the archive we just wrote.
Chris Lattner7f6b4472008-04-01 04:26:46 +0000413 {
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000414 OwningPtr<MemoryBuffer> arch;
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000415 if (error_code ec = MemoryBuffer::getFile(TempArchivePath.c_str(), arch)) {
Michael J. Spencer333fb042010-12-09 17:36:48 +0000416 if (ErrMsg)
417 *ErrMsg = ec.message();
418 return true;
419 }
Chris Lattner7f6b4472008-04-01 04:26:46 +0000420 const char* base = arch->getBufferStart();
Reid Spencer3039b992006-07-07 19:09:14 +0000421
Michael J. Spencer83a113b2011-01-10 02:34:40 +0000422 // Open another temporary file in order to avoid invalidating the
Reid Spencer3039b992006-07-07 19:09:14 +0000423 // mmapped data
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000424 if (error_code ec = sys::fs::unique_file("%%-%%-%%-%%" + archPath.str(),
425 ArchFD, TempArchiveWithSymbolTablePath)) {
426 if (ErrMsg) *ErrMsg = ec.message();
Reid Spencer0ff2d312006-08-24 23:45:08 +0000427 return true;
Reid Spencer3039b992006-07-07 19:09:14 +0000428 }
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000429 sys::RemoveFileOnSignal(sys::Path(TempArchiveWithSymbolTablePath.str()));
430
431 raw_fd_ostream FinalFile(ArchFD, true);
Reid Spencer3039b992006-07-07 19:09:14 +0000432
433 // Write the file magic number
434 FinalFile << ARFILE_MAGIC;
435
436 // If there is a foreign symbol table, put it into the file now. Most
437 // ar(1) implementations require the symbol table to be first but llvm-ar
438 // can deal with it being after a foreign symbol table. This ensures
439 // compatibility with other ar(1) implementations as well as allowing the
440 // archive to store both native .o and LLVM .bc files, both indexed.
441 if (foreignST) {
Reid Spencer0ff2d312006-08-24 23:45:08 +0000442 if (writeMember(*foreignST, FinalFile, false, false, false, ErrMsg)) {
Reid Spencer8d8a7ff2006-07-07 20:56:50 +0000443 FinalFile.close();
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000444 bool existed;
445 sys::fs::remove(TempArchiveWithSymbolTablePath.str(), existed);
Reid Spencer0ff2d312006-08-24 23:45:08 +0000446 return true;
Reid Spencer8d8a7ff2006-07-07 20:56:50 +0000447 }
Reid Spencer3039b992006-07-07 19:09:14 +0000448 }
449
450 // Put out the LLVM symbol table now.
451 writeSymbolTable(FinalFile);
452
453 // Copy the temporary file contents being sure to skip the file's magic
454 // number.
455 FinalFile.write(base + sizeof(ARFILE_MAGIC)-1,
Chris Lattner7f6b4472008-04-01 04:26:46 +0000456 arch->getBufferSize()-sizeof(ARFILE_MAGIC)+1);
Reid Spencer3039b992006-07-07 19:09:14 +0000457
458 // Close up shop
459 FinalFile.close();
Chris Lattner7f6b4472008-04-01 04:26:46 +0000460 } // free arch.
Michael J. Spencer83a113b2011-01-10 02:34:40 +0000461
Reid Spencer3039b992006-07-07 19:09:14 +0000462 // Move the final file over top of TmpArchive
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000463 if (error_code ec = sys::fs::rename(TempArchiveWithSymbolTablePath.str(),
464 TempArchivePath.str())) {
465 if (ErrMsg) *ErrMsg = ec.message();
Reid Spencer0ff2d312006-08-24 23:45:08 +0000466 return true;
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000467 }
Reid Spencer3039b992006-07-07 19:09:14 +0000468 }
Michael J. Spencer83a113b2011-01-10 02:34:40 +0000469
Reid Spencer3039b992006-07-07 19:09:14 +0000470 // Before we replace the actual archive, we need to forget all the
471 // members, since they point to data in that old archive. We need to do
472 // this because we cannot replace an open file on Windows.
473 cleanUpMemory();
Michael J. Spencer83a113b2011-01-10 02:34:40 +0000474
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000475 if (error_code ec = sys::fs::rename(TempArchivePath.str(),
476 archPath.str())) {
477 if (ErrMsg) *ErrMsg = ec.message();
Reid Spencer0ff2d312006-08-24 23:45:08 +0000478 return true;
Michael J. Spencere7a820c2011-01-16 23:39:59 +0000479 }
Reid Spencer3039b992006-07-07 19:09:14 +0000480
Owen Andersona5464f32008-05-24 05:42:29 +0000481 // Set correct read and write permissions after temporary file is moved
482 // to final destination path.
483 if (archPath.makeReadableOnDisk(ErrMsg))
484 return true;
485 if (archPath.makeWriteableOnDisk(ErrMsg))
486 return true;
487
Reid Spencer0ff2d312006-08-24 23:45:08 +0000488 return false;
Reid Spencercf6afc62004-11-14 21:56:59 +0000489}