Properly close mapped files.
[oota-llvm.git] / lib / Archive / ArchiveWriter.cpp
1 //===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the 
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // Builds up an LLVM archive file (.a) containing LLVM bytecode.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ArchiveInternals.h"
15 #include "llvm/Bytecode/Reader.h"
16 #include "llvm/Support/Compressor.h"
17 #include "llvm/System/Signals.h"
18 #include <fstream>
19 #include <iostream>
20 #include <iomanip>
21
22 using namespace llvm;
23
24 // Write an integer using variable bit rate encoding. This saves a few bytes
25 // per entry in the symbol table.
26 inline void writeInteger(unsigned num, std::ofstream& ARFile) {
27   while (1) {
28     if (num < 0x80) { // done?
29       ARFile << (unsigned char)num;
30       return;
31     }
32     
33     // Nope, we are bigger than a character, output the next 7 bits and set the
34     // high bit to say that there is more coming...
35     ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
36     num >>= 7;  // Shift out 7 bits now...
37   }
38 }
39
40 // Compute how many bytes are taken by a given VBR encoded value. This is needed
41 // to pre-compute the size of the symbol table.
42 inline unsigned numVbrBytes(unsigned num) {
43
44   // Note that the following nested ifs are somewhat equivalent to a binary
45   // search. We split it in half by comparing against 2^14 first. This allows
46   // most reasonable values to be done in 2 comparisons instead of 1 for 
47   // small ones and four for large ones. We expect this to access file offsets
48   // in the 2^10 to 2^24 range and symbol lengths in the 2^0 to 2^8 range, 
49   // so this approach is reasonable.
50   if (num < 1<<14)
51     if (num < 1<<7)
52       return 1;
53     else
54       return 2;
55   if (num < 1<<21)
56     return 3;
57
58   if (num < 1<<28)
59     return 4;
60   return 5; // anything >= 2^28 takes 5 bytes
61 }
62
63 // Create an empty archive.
64 Archive* 
65 Archive::CreateEmpty(const sys::Path& FilePath ) {
66   Archive* result = new Archive(FilePath,false);
67   return result;
68 }
69
70 // Fill the ArchiveMemberHeader with the information from a member. If 
71 // TruncateNames is true, names are flattened to 15 chars or less. The sz field
72 // is provided here instead of coming from the mbr because the member might be 
73 // stored compressed and the compressed size is not the ArchiveMember's size. 
74 // Furthermore compressed files have negative size fields to identify them as 
75 // compressed.
76 bool
77 Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
78                     int sz, bool TruncateNames) const {
79
80   // Set the permissions mode, uid and gid
81   hdr.init();
82   char buffer[32];
83   sprintf(buffer, "%-8o", mbr.getMode());
84   memcpy(hdr.mode,buffer,8);
85   sprintf(buffer,  "%-6u", mbr.getUser());
86   memcpy(hdr.uid,buffer,6);
87   sprintf(buffer,  "%-6u", mbr.getGroup());
88   memcpy(hdr.gid,buffer,6);
89
90   // Set the last modification date
91   uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
92   sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
93   memcpy(hdr.date,buffer,12);
94
95   // Get rid of trailing blanks in the name
96   std::string mbrPath = mbr.getPath().toString();
97   size_t mbrLen = mbrPath.length();
98   while (mbrLen > 0 && mbrPath[mbrLen-1] == ' ') {
99     mbrPath.erase(mbrLen-1,1);
100     mbrLen--;
101   }
102
103   // Set the name field in one of its various flavors.
104   bool writeLongName = false;
105   if (mbr.isStringTable()) {
106     memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
107   } else if (mbr.isSVR4SymbolTable()) {
108     memcpy(hdr.name,ARFILE_SVR4_SYMTAB_NAME,16);
109   } else if (mbr.isBSD4SymbolTable()) {
110     memcpy(hdr.name,ARFILE_BSD4_SYMTAB_NAME,16);
111   } else if (mbr.isLLVMSymbolTable()) {
112     memcpy(hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
113   } else if (TruncateNames) {
114     const char* nm = mbrPath.c_str();
115     unsigned len = mbrPath.length();
116     size_t slashpos = mbrPath.rfind('/');
117     if (slashpos != std::string::npos) {
118       nm += slashpos + 1;
119       len -= slashpos +1;
120     }
121     if (len > 15) 
122       len = 15;
123     memcpy(hdr.name,nm,len);
124     hdr.name[len] = '/';
125   } else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
126     memcpy(hdr.name,mbrPath.c_str(),mbrPath.length());
127     hdr.name[mbrPath.length()] = '/';
128   } else {
129     std::string nm = "#1/";
130     nm += utostr(mbrPath.length());
131     memcpy(hdr.name,nm.data(),nm.length());
132     if (sz < 0)
133       sz -= mbrPath.length();
134     else
135       sz += mbrPath.length();
136     writeLongName = true;
137   }
138
139   // Set the size field
140   if (sz < 0) {
141     buffer[0] = '-';
142     sprintf(&buffer[1],"%-9u",(unsigned)-sz);
143   } else {
144     sprintf(buffer, "%-10u", (unsigned)sz);
145   }
146   memcpy(hdr.size,buffer,10);
147
148   return writeLongName;
149 }
150
151 // Insert a file into the archive before some other member. This also takes care
152 // of extracting the necessary flags and information from the file.
153 void
154 Archive::addFileBefore(const sys::Path& filePath, iterator where) {
155   assert(filePath.exists() && "Can't add a non-existent file");
156
157   ArchiveMember* mbr = new ArchiveMember(this);
158
159   mbr->data = 0;
160   mbr->path = filePath;
161   mbr->path.getStatusInfo(mbr->info);
162
163   unsigned flags = 0;
164   bool hasSlash = filePath.toString().find('/') != std::string::npos;
165   if (hasSlash)
166     flags |= ArchiveMember::HasPathFlag;
167   if (hasSlash || filePath.toString().length() > 15)
168     flags |= ArchiveMember::HasLongFilenameFlag;
169   std::string magic;
170   mbr->path.getMagicNumber(magic,4);
171   switch (sys::IdentifyFileType(magic.c_str(),4)) {
172     case sys::BytecodeFileType:
173       flags |= ArchiveMember::BytecodeFlag;
174       break;
175     case sys::CompressedBytecodeFileType:
176       flags |= ArchiveMember::CompressedBytecodeFlag;
177       break;
178     default:
179       break;
180   }
181   mbr->flags = flags;
182   members.insert(where,mbr);
183 }
184
185 // Write one member out to the file.
186 void
187 Archive::writeMember(
188   const ArchiveMember& member,
189   std::ofstream& ARFile,
190   bool CreateSymbolTable,
191   bool TruncateNames,
192   bool ShouldCompress 
193 ) {
194
195   unsigned filepos = ARFile.tellp();
196   filepos -= 8;
197
198   // Get the data and its size either from the
199   // member's in-memory data or directly from the file.
200   size_t fSize = member.getSize();
201   const char* data = (const char*)member.getData();
202   sys::MappedFile* mFile = 0;
203   if (!data) {
204     mFile = new sys::MappedFile(member.getPath());
205     data = (const char*) mFile->map();
206     fSize = mFile->size();
207   } 
208
209   // Now that we have the data in memory, update the 
210   // symbol table if its a bytecode file.
211   if (CreateSymbolTable && 
212       (member.isBytecode() || member.isCompressedBytecode())) {
213     std::vector<std::string> symbols;
214     std::string FullMemberName = archPath.toString() + "(" + 
215       member.getPath().toString() 
216       + ")";
217     ModuleProvider* MP = GetBytecodeSymbols(
218       (const unsigned char*)data,fSize,FullMemberName, symbols);
219
220     // If the bytecode parsed successfully
221     if ( MP ) {
222       for (std::vector<std::string>::iterator SI = symbols.begin(), 
223            SE = symbols.end(); SI != SE; ++SI) {
224
225         std::pair<SymTabType::iterator,bool> Res = 
226           symTab.insert(std::make_pair(*SI,filepos));
227
228         if (Res.second) {
229           symTabSize += SI->length() + 
230                         numVbrBytes(SI->length()) + 
231                         numVbrBytes(filepos);
232         }
233       }
234       // We don't need this module any more.
235       delete MP;
236     } else {
237       throw std::string("Can't parse bytecode member: ") + 
238              member.getPath().toString();
239     }
240   }
241
242   // Determine if we actually should compress this member
243   bool willCompress = 
244       (ShouldCompress && 
245       !member.isCompressed() && 
246       !member.isCompressedBytecode() &&
247       !member.isLLVMSymbolTable() &&
248       !member.isSVR4SymbolTable() &&
249       !member.isBSD4SymbolTable());
250
251   // Perform the compression. Note that if the file is uncompressed bytecode
252   // then we turn the file into compressed bytecode rather than treating it as
253   // compressed data. This is necessary since it allows us to determine that the
254   // file contains bytecode instead of looking like a regular compressed data
255   // member. A compressed bytecode file has its content compressed but has a
256   // magic number of "llvc". This acounts for the +/-4 arithmetic in the code
257   // below.
258   int hdrSize;
259   if (willCompress) {
260     char* output = 0;
261     if (member.isBytecode()) {
262       data +=4;
263       fSize -= 4;
264     }
265     fSize = Compressor::compressToNewBuffer(data,fSize,output);
266     data = output;
267     if (member.isBytecode())
268       hdrSize = -fSize-4; 
269     else
270       hdrSize = -fSize;
271   } else {
272     hdrSize = fSize;
273   }
274
275   // Compute the fields of the header
276   ArchiveMemberHeader Hdr;
277   bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
278
279   // Write header to archive file
280   ARFile.write((char*)&Hdr, sizeof(Hdr));
281
282   // Write the long filename if its long
283   if (writeLongName) {
284     ARFile.write(member.getPath().toString().data(),
285                  member.getPath().toString().length());
286   }
287
288   // Make sure we write the compressed bytecode magic number if we should.
289   if (willCompress && member.isBytecode())
290     ARFile.write("llvc",4);
291
292   // Write the (possibly compressed) member's content to the file.
293   ARFile.write(data,fSize);
294
295   // Make sure the member is an even length
296   if ((ARFile.tellp() & 1) == 1)
297     ARFile << ARFILE_PAD;
298
299   // Free the compressed data, if necessary
300   if (willCompress) {
301     free((void*)data);
302   }
303
304   // Close the mapped file if it was opened
305   if (mFile != 0) {
306     mFile->close();
307     delete mFile;
308   }
309 }
310
311 // Write out the LLVM symbol table as an archive member to the file.
312 void
313 Archive::writeSymbolTable(std::ofstream& ARFile) {
314
315   // Construct the symbol table's header
316   ArchiveMemberHeader Hdr;
317   Hdr.init();
318   memcpy(Hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
319   uint64_t secondsSinceEpoch = sys::TimeValue::now().toEpochTime();
320   char buffer[32];
321   sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
322   memcpy(Hdr.date,buffer,12);
323   sprintf(buffer,"%-10u",symTabSize);
324   memcpy(Hdr.size,buffer,10);
325
326   // Write the header
327   ARFile.write((char*)&Hdr, sizeof(Hdr));
328
329   // Save the starting position of the symbol tables data content.
330   unsigned startpos = ARFile.tellp();
331
332   // Write out the symbols sequentially
333   for ( Archive::SymTabType::iterator I = symTab.begin(), E = symTab.end();
334         I != E; ++I)
335   {
336     // Write out the file index
337     writeInteger(I->second, ARFile);
338     // Write out the length of the symbol
339     writeInteger(I->first.length(), ARFile);
340     // Write out the symbol
341     ARFile.write(I->first.data(), I->first.length());
342   }
343
344   // Now that we're done with the symbol table, get the ending file position
345   unsigned endpos = ARFile.tellp();
346
347   // Make sure that the amount we wrote is what we pre-computed. This is
348   // critical for file integrity purposes.
349   assert(endpos - startpos == symTabSize && "Invalid symTabSize computation");
350
351   // Make sure the symbol table is even sized
352   if (symTabSize % 2 != 0 )
353     ARFile << ARFILE_PAD;
354 }
355
356 // Write the entire archive to the file specified when the archive was created.
357 // This writes to a temporary file first. Options are for creating a symbol 
358 // table, flattening the file names (no directories, 15 chars max) and 
359 // compressing each archive member.
360 void
361 Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress){
362   
363   // Make sure they haven't opened up the file, not loaded it,
364   // but are now trying to write it which would wipe out the file.
365   assert(!(members.empty() && mapfile->size() > 8) && 
366          "Can't write an archive not opened for writing");
367
368   // Create a temporary file to store the archive in
369   sys::Path TmpArchive = archPath;
370   TmpArchive.createTemporaryFile();
371
372   // Make sure the temporary gets removed if we crash
373   sys::RemoveFileOnSignal(TmpArchive);
374
375   // Ensure we can remove the temporary even in the face of an exception
376   try {
377     // Create archive file for output.
378     std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
379                                  std::ios::binary;
380     std::ofstream ArchiveFile(TmpArchive.c_str(), io_mode);
381   
382     // Check for errors opening or creating archive file.
383     if ( !ArchiveFile.is_open() || ArchiveFile.bad() ) {
384       throw std::string("Error opening archive file: ") + archPath.toString();
385     }
386
387     // If we're creating a symbol table, reset it now
388     if (CreateSymbolTable) {
389       symTabSize = 0;
390       symTab.clear();
391     }
392
393     // Write magic string to archive.
394     ArchiveFile << ARFILE_MAGIC;
395
396     // Loop over all member files, and write them out. Note that this also
397     // builds the symbol table, symTab.
398     for ( MembersList::iterator I = begin(), E = end(); I != E; ++I) {
399       writeMember(*I,ArchiveFile,CreateSymbolTable,TruncateNames,Compress);
400     }
401
402     // Close archive file.
403     ArchiveFile.close();
404
405     // Write the symbol table
406     if (CreateSymbolTable) {
407       // At this point we have written a file that is a legal archive but it
408       // doesn't have a symbol table in it. To aid in faster reading and to
409       // ensure compatibility with other archivers we need to put the symbol
410       // table first in the file. Unfortunately, this means mapping the file
411       // we just wrote back in and copying it to the destination file.
412
413       // Map in the archive we just wrote.
414       sys::MappedFile arch(TmpArchive);
415       const char* base = (const char*) arch.map();
416
417       // Open the final file to write and check it.
418       std::ofstream FinalFile(archPath.c_str(), io_mode);
419       if ( !FinalFile.is_open() || FinalFile.bad() ) {
420         throw std::string("Error opening archive file: ") + archPath.toString();
421       }
422
423       // Write the file magic number
424       FinalFile << ARFILE_MAGIC;
425
426       // If there is a foreign symbol table, put it into the file now. Most
427       // ar(1) implementations require the symbol table to be first but llvm-ar
428       // can deal with it being after a foreign symbol table. This ensures
429       // compatibility with other ar(1) implementations as well as allowing the
430       // archive to store both native .o and LLVM .bc files, both indexed.
431       if (foreignST) {
432         writeMember(*foreignST, FinalFile, false, false, false);
433       }
434
435       // Put out the LLVM symbol table now.
436       writeSymbolTable(FinalFile);
437
438       // Copy the temporary file contents being sure to skip the file's magic
439       // number.
440       FinalFile.write(base + sizeof(ARFILE_MAGIC)-1, 
441         arch.size()-sizeof(ARFILE_MAGIC)+1);
442
443       // Close up shop
444       FinalFile.close();
445       arch.close();
446       TmpArchive.destroyFile();
447
448     } else {
449       // We don't have to insert the symbol table, so just renaming the temp
450       // file to the correct name will suffice.
451       TmpArchive.renameFile(archPath);
452     }
453   } catch (...) {
454     // Make sure we clean up.
455     if (TmpArchive.exists())
456       TmpArchive.destroyFile();
457     throw;
458   }
459 }