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