LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

ArchiveWriter.cpp

Go to the documentation of this file.
00001 //===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by Reid Spencer and is distributed under the 
00006 // University of Illinois Open Source License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Builds up an LLVM archive file (.a) containing LLVM bytecode.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "ArchiveInternals.h"
00015 #include "llvm/Bytecode/Reader.h"
00016 #include "llvm/Support/FileUtilities.h"
00017 #include "llvm/Support/Compressor.h"
00018 #include "llvm/System/Signals.h"
00019 #include <fstream>
00020 #include <iostream>
00021 #include <iomanip>
00022 
00023 using namespace llvm;
00024 
00025 // Write an integer using variable bit rate encoding. This saves a few bytes
00026 // per entry in the symbol table.
00027 inline void writeInteger(unsigned num, std::ofstream& ARFile) {
00028   while (1) {
00029     if (num < 0x80) { // done?
00030       ARFile << (unsigned char)num;
00031       return;
00032     }
00033     
00034     // Nope, we are bigger than a character, output the next 7 bits and set the
00035     // high bit to say that there is more coming...
00036     ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
00037     num >>= 7;  // Shift out 7 bits now...
00038   }
00039 }
00040 
00041 // Compute how many bytes are taken by a given VBR encoded value. This is needed
00042 // to pre-compute the size of the symbol table.
00043 inline unsigned numVbrBytes(unsigned num) {
00044 
00045   // Note that the following nested ifs are somewhat equivalent to a binary
00046   // search. We split it in half by comparing against 2^14 first. This allows
00047   // most reasonable values to be done in 2 comparisons instead of 1 for 
00048   // small ones and four for large ones. We expect this to access file offsets
00049   // in the 2^10 to 2^24 range and symbol lengths in the 2^0 to 2^8 range, 
00050   // so this approach is reasonable.
00051   if (num < 1<<14)
00052     if (num < 1<<7)
00053       return 1;
00054     else
00055       return 2;
00056   if (num < 1<<21)
00057     return 3;
00058 
00059   if (num < 1<<28)
00060     return 4;
00061   return 5; // anything >= 2^28 takes 5 bytes
00062 }
00063 
00064 // Create an empty archive.
00065 Archive* 
00066 Archive::CreateEmpty(const sys::Path& FilePath ) {
00067   Archive* result = new Archive(FilePath,false);
00068   return result;
00069 }
00070 
00071 // Fill the ArchiveMemberHeader with the information from a member. If 
00072 // TruncateNames is true, names are flattened to 15 chars or less. The sz field
00073 // is provided here instead of coming from the mbr because the member might be 
00074 // stored compressed and the compressed size is not the ArchiveMember's size. 
00075 // Furthermore compressed files have negative size fields to identify them as 
00076 // compressed.
00077 bool
00078 Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
00079                     int sz, bool TruncateNames) const {
00080 
00081   // Set the permissions mode, uid and gid
00082   hdr.init();
00083   char buffer[32];
00084   sprintf(buffer, "%-8o", mbr.getMode());
00085   memcpy(hdr.mode,buffer,8);
00086   sprintf(buffer,  "%-6u", mbr.getUser());
00087   memcpy(hdr.uid,buffer,6);
00088   sprintf(buffer,  "%-6u", mbr.getGroup());
00089   memcpy(hdr.gid,buffer,6);
00090 
00091   // Set the last modification date
00092   uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
00093   sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
00094   memcpy(hdr.date,buffer,12);
00095 
00096   // Get rid of trailing blanks in the name
00097   std::string mbrPath = mbr.getPath().get();
00098   size_t mbrLen = mbrPath.length();
00099   while (mbrLen > 0 && mbrPath[mbrLen-1] == ' ') {
00100     mbrPath.erase(mbrLen-1,1);
00101     mbrLen--;
00102   }
00103 
00104   // Set the name field in one of its various flavors.
00105   bool writeLongName = false;
00106   if (mbr.isStringTable()) {
00107     memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
00108   } else if (mbr.isSVR4SymbolTable()) {
00109     memcpy(hdr.name,ARFILE_SVR4_SYMTAB_NAME,16);
00110   } else if (mbr.isBSD4SymbolTable()) {
00111     memcpy(hdr.name,ARFILE_BSD4_SYMTAB_NAME,16);
00112   } else if (mbr.isLLVMSymbolTable()) {
00113     memcpy(hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
00114   } else if (TruncateNames) {
00115     const char* nm = mbrPath.c_str();
00116     unsigned len = mbrPath.length();
00117     size_t slashpos = mbrPath.rfind('/');
00118     if (slashpos != std::string::npos) {
00119       nm += slashpos + 1;
00120       len -= slashpos +1;
00121     }
00122     if (len > 15) 
00123       len = 15;
00124     memcpy(hdr.name,nm,len);
00125     hdr.name[len] = '/';
00126   } else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
00127     memcpy(hdr.name,mbrPath.c_str(),mbrPath.length());
00128     hdr.name[mbrPath.length()] = '/';
00129   } else {
00130     std::string nm = "#1/";
00131     nm += utostr(mbrPath.length());
00132     memcpy(hdr.name,nm.data(),nm.length());
00133     if (sz < 0)
00134       sz -= mbrPath.length();
00135     else
00136       sz += mbrPath.length();
00137     writeLongName = true;
00138   }
00139 
00140   // Set the size field
00141   if (sz < 0) {
00142     buffer[0] = '-';
00143     sprintf(&buffer[1],"%-9u",(unsigned)-sz);
00144   } else {
00145     sprintf(buffer, "%-10u", (unsigned)sz);
00146   }
00147   memcpy(hdr.size,buffer,10);
00148 
00149   return writeLongName;
00150 }
00151 
00152 // Insert a file into the archive before some other member. This also takes care
00153 // of extracting the necessary flags and information from the file.
00154 void
00155 Archive::addFileBefore(const sys::Path& filePath, iterator where) {
00156   assert(filePath.exists() && "Can't add a non-existent file");
00157 
00158   ArchiveMember* mbr = new ArchiveMember(this);
00159 
00160   mbr->data = 0;
00161   mbr->path = filePath;
00162   mbr->path.getStatusInfo(mbr->info);
00163 
00164   unsigned flags = 0;
00165   bool hasSlash = filePath.get().find('/') != std::string::npos;
00166   if (hasSlash)
00167     flags |= ArchiveMember::HasPathFlag;
00168   if (hasSlash || filePath.get().length() > 15)
00169     flags |= ArchiveMember::HasLongFilenameFlag;
00170   std::string magic;
00171   mbr->path.getMagicNumber(magic,4);
00172   switch (sys::IdentifyFileType(magic.c_str(),4)) {
00173     case sys::BytecodeFileType:
00174       flags |= ArchiveMember::BytecodeFlag;
00175       break;
00176     case sys::CompressedBytecodeFileType:
00177       flags |= ArchiveMember::CompressedBytecodeFlag;
00178       break;
00179     default:
00180       break;
00181   }
00182   mbr->flags = flags;
00183   members.insert(where,mbr);
00184 }
00185 
00186 // Write one member out to the file.
00187 void
00188 Archive::writeMember(
00189   const ArchiveMember& member,
00190   std::ofstream& ARFile,
00191   bool CreateSymbolTable,
00192   bool TruncateNames,
00193   bool ShouldCompress 
00194 ) {
00195 
00196   unsigned filepos = ARFile.tellp();
00197   filepos -= 8;
00198 
00199   // Get the data and its size either from the
00200   // member's in-memory data or directly from the file.
00201   size_t fSize = member.getSize();
00202   const char* data = (const char*)member.getData();
00203   sys::MappedFile* mFile = 0;
00204   if (!data) {
00205     mFile = new sys::MappedFile(member.getPath());
00206     data = (const char*) mFile->map();
00207     fSize = mFile->size();
00208   } 
00209 
00210   // Now that we have the data in memory, update the 
00211   // symbol table if its a bytecode file.
00212   if (CreateSymbolTable && 
00213       (member.isBytecode() || member.isCompressedBytecode())) {
00214     std::vector<std::string> symbols;
00215     std::string FullMemberName = archPath.get() + "(" + member.getPath().get() 
00216       + ")";
00217     ModuleProvider* MP = GetBytecodeSymbols(
00218       (const unsigned char*)data,fSize,FullMemberName, symbols);
00219 
00220     // If the bytecode parsed successfully
00221     if ( MP ) {
00222       for (std::vector<std::string>::iterator SI = symbols.begin(), 
00223            SE = symbols.end(); SI != SE; ++SI) {
00224 
00225         std::pair<SymTabType::iterator,bool> Res = 
00226           symTab.insert(std::make_pair(*SI,filepos));
00227 
00228         if (Res.second) {
00229           symTabSize += SI->length() + 
00230                         numVbrBytes(SI->length()) + 
00231                         numVbrBytes(filepos);
00232         }
00233       }
00234       // We don't need this module any more.
00235       delete MP;
00236     } else {
00237       throw std::string("Can't parse bytecode member: ") + 
00238              member.getPath().get();
00239     }
00240   }
00241 
00242   // Determine if we actually should compress this member
00243   bool willCompress = 
00244       (ShouldCompress && 
00245       !member.isCompressed() && 
00246       !member.isCompressedBytecode() &&
00247       !member.isLLVMSymbolTable() &&
00248       !member.isSVR4SymbolTable() &&
00249       !member.isBSD4SymbolTable());
00250 
00251   // Perform the compression. Note that if the file is uncompressed bytecode
00252   // then we turn the file into compressed bytecode rather than treating it as
00253   // compressed data. This is necessary since it allows us to determine that the
00254   // file contains bytecode instead of looking like a regular compressed data
00255   // member. A compressed bytecode file has its content compressed but has a
00256   // magic number of "llvc". This acounts for the +/-4 arithmetic in the code
00257   // below.
00258   int hdrSize;
00259   if (willCompress) {
00260     char* output = 0;
00261     if (member.isBytecode()) {
00262       data +=4;
00263       fSize -= 4;
00264     }
00265     fSize = Compressor::compressToNewBuffer(data,fSize,output);
00266     data = output;
00267     if (member.isBytecode())
00268       hdrSize = -fSize-4; 
00269     else
00270       hdrSize = -fSize;
00271   } else {
00272     hdrSize = fSize;
00273   }
00274 
00275   // Compute the fields of the header
00276   ArchiveMemberHeader Hdr;
00277   bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
00278 
00279   // Write header to archive file
00280   ARFile.write((char*)&Hdr, sizeof(Hdr));
00281 
00282   // Write the long filename if its long
00283   if (writeLongName) {
00284     ARFile.write(member.getPath().get().data(),member.getPath().get().length());
00285   }
00286 
00287   // Make sure we write the compressed bytecode magic number if we should.
00288   if (willCompress && member.isBytecode())
00289     ARFile.write("llvc",4);
00290 
00291   // Write the (possibly compressed) member's content to the file.
00292   ARFile.write(data,fSize);
00293 
00294   // Make sure the member is an even length
00295   if (ARFile.tellp() & 1 == 1)
00296     ARFile << ARFILE_PAD;
00297 
00298   // Free the compressed data, if necessary
00299   if (willCompress) {
00300     free((void*)data);
00301   }
00302 
00303   // Close the mapped file if it was opened
00304   if (mFile != 0) {
00305     mFile->unmap();
00306     delete mFile;
00307   }
00308 }
00309 
00310 // Write out the LLVM symbol table as an archive member to the file.
00311 void
00312 Archive::writeSymbolTable(std::ofstream& ARFile) {
00313 
00314   // Construct the symbol table's header
00315   ArchiveMemberHeader Hdr;
00316   Hdr.init();
00317   memcpy(Hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
00318   uint64_t secondsSinceEpoch = sys::TimeValue::now().toEpochTime();
00319   char buffer[32];
00320   sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
00321   memcpy(Hdr.date,buffer,12);
00322   sprintf(buffer,"%-10u",symTabSize);
00323   memcpy(Hdr.size,buffer,10);
00324 
00325   // Write the header
00326   ARFile.write((char*)&Hdr, sizeof(Hdr));
00327 
00328   // Save the starting position of the symbol tables data content.
00329   unsigned startpos = ARFile.tellp();
00330 
00331   // Write out the symbols sequentially
00332   for ( Archive::SymTabType::iterator I = symTab.begin(), E = symTab.end();
00333         I != E; ++I)
00334   {
00335     // Write out the file index
00336     writeInteger(I->second, ARFile);
00337     // Write out the length of the symbol
00338     writeInteger(I->first.length(), ARFile);
00339     // Write out the symbol
00340     ARFile.write(I->first.data(), I->first.length());
00341   }
00342 
00343   // Now that we're done with the symbol table, get the ending file position
00344   unsigned endpos = ARFile.tellp();
00345 
00346   // Make sure that the amount we wrote is what we pre-computed. This is
00347   // critical for file integrity purposes.
00348   assert(endpos - startpos == symTabSize && "Invalid symTabSize computation");
00349 
00350   // Make sure the symbol table is even sized
00351   if (symTabSize % 2 != 0 )
00352     ARFile << ARFILE_PAD;
00353 }
00354 
00355 // Write the entire archive to the file specified when the archive was created.
00356 // This writes to a temporary file first. Options are for creating a symbol 
00357 // table, flattening the file names (no directories, 15 chars max) and 
00358 // compressing each archive member.
00359 void
00360 Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress){
00361   
00362   // Make sure they haven't opened up the file, not loaded it,
00363   // but are now trying to write it which would wipe out the file.
00364   assert(!(members.empty() && mapfile->size() > 8) && 
00365          "Can't write an archive not opened for writing");
00366 
00367   // Create a temporary file to store the archive in
00368   sys::Path TmpArchive = archPath;
00369   TmpArchive.createTemporaryFile();
00370 
00371   // Make sure the temporary gets removed if we crash
00372   sys::RemoveFileOnSignal(TmpArchive);
00373 
00374   // Ensure we can remove the temporary even in the face of an exception
00375   try {
00376     // Create archive file for output.
00377     std::ofstream ArchiveFile(TmpArchive.c_str());
00378   
00379     // Check for errors opening or creating archive file.
00380     if ( !ArchiveFile.is_open() || ArchiveFile.bad() ) {
00381       throw std::string("Error opening archive file: ") + archPath.get();
00382     }
00383 
00384     // If we're creating a symbol table, reset it now
00385     if (CreateSymbolTable) {
00386       symTabSize = 0;
00387       symTab.clear();
00388     }
00389 
00390     // Write magic string to archive.
00391     ArchiveFile << ARFILE_MAGIC;
00392 
00393     // Loop over all member files, and write them out. Note that this also
00394     // builds the symbol table, symTab.
00395     for ( MembersList::iterator I = begin(), E = end(); I != E; ++I) {
00396       writeMember(*I,ArchiveFile,CreateSymbolTable,TruncateNames,Compress);
00397     }
00398 
00399     // Close archive file.
00400     ArchiveFile.close();
00401 
00402     // Write the symbol table
00403     if (CreateSymbolTable) {
00404       // At this point we have written a file that is a legal archive but it
00405       // doesn't have a symbol table in it. To aid in faster reading and to
00406       // ensure compatibility with other archivers we need to put the symbol
00407       // table first in the file. Unfortunately, this means mapping the file
00408       // we just wrote back in and copying it to the destination file.
00409 
00410       // Map in the archive we just wrote.
00411       sys::MappedFile arch(TmpArchive);
00412       const char* base = (const char*) arch.map();
00413 
00414       // Open the final file to write and check it.
00415       std::ofstream FinalFile(archPath.c_str());
00416       if ( !FinalFile.is_open() || FinalFile.bad() ) {
00417         throw std::string("Error opening archive file: ") + archPath.get();
00418       }
00419 
00420       // Write the file magic number
00421       FinalFile << ARFILE_MAGIC;
00422 
00423       // If there is a foreign symbol table, put it into the file now. Most
00424       // ar(1) implementations require the symbol table to be first but llvm-ar
00425       // can deal with it being after a foreign symbol table. This ensures
00426       // compatibility with other ar(1) implementations as well as allowing the
00427       // archive to store both native .o and LLVM .bc files, both indexed.
00428       if (foreignST) {
00429         writeMember(*foreignST, FinalFile, false, false, false);
00430       }
00431 
00432       // Put out the LLVM symbol table now.
00433       writeSymbolTable(FinalFile);
00434 
00435       // Copy the temporary file contents being sure to skip the file's magic
00436       // number.
00437       FinalFile.write(base + sizeof(ARFILE_MAGIC)-1, 
00438         arch.size()-sizeof(ARFILE_MAGIC)+1);
00439 
00440       // Close up shop
00441       FinalFile.close();
00442       arch.unmap();
00443       TmpArchive.destroyFile();
00444 
00445     } else {
00446       // We don't have to insert the symbol table, so just renaming the temp
00447       // file to the correct name will suffice.
00448       TmpArchive.renameFile(archPath);
00449     }
00450   } catch (...) {
00451     // Make sure we clean up.
00452     if (TmpArchive.exists())
00453       TmpArchive.destroyFile();
00454     throw;
00455   }
00456 }