LLVM API Documentation

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/Compressor.h"
00017 #include "llvm/System/Signals.h"
00018 #include "llvm/System/Process.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().toString();
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.toString().find('/') != std::string::npos;
00166   if (hasSlash)
00167     flags |= ArchiveMember::HasPathFlag;
00168   if (hasSlash || filePath.toString().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.toString() + "(" +
00216       member.getPath().toString()
00217       + ")";
00218     ModuleProvider* MP = GetBytecodeSymbols(
00219       (const unsigned char*)data,fSize,FullMemberName, symbols);
00220 
00221     // If the bytecode parsed successfully
00222     if ( MP ) {
00223       for (std::vector<std::string>::iterator SI = symbols.begin(),
00224            SE = symbols.end(); SI != SE; ++SI) {
00225 
00226         std::pair<SymTabType::iterator,bool> Res =
00227           symTab.insert(std::make_pair(*SI,filepos));
00228 
00229         if (Res.second) {
00230           symTabSize += SI->length() +
00231                         numVbrBytes(SI->length()) +
00232                         numVbrBytes(filepos);
00233         }
00234       }
00235       // We don't need this module any more.
00236       delete MP;
00237     } else {
00238       throw std::string("Can't parse bytecode member: ") +
00239              member.getPath().toString();
00240     }
00241   }
00242 
00243   // Determine if we actually should compress this member
00244   bool willCompress =
00245       (ShouldCompress &&
00246       !member.isCompressed() &&
00247       !member.isCompressedBytecode() &&
00248       !member.isLLVMSymbolTable() &&
00249       !member.isSVR4SymbolTable() &&
00250       !member.isBSD4SymbolTable());
00251 
00252   // Perform the compression. Note that if the file is uncompressed bytecode
00253   // then we turn the file into compressed bytecode rather than treating it as
00254   // compressed data. This is necessary since it allows us to determine that the
00255   // file contains bytecode instead of looking like a regular compressed data
00256   // member. A compressed bytecode file has its content compressed but has a
00257   // magic number of "llvc". This acounts for the +/-4 arithmetic in the code
00258   // below.
00259   int hdrSize;
00260   if (willCompress) {
00261     char* output = 0;
00262     if (member.isBytecode()) {
00263       data +=4;
00264       fSize -= 4;
00265     }
00266     fSize = Compressor::compressToNewBuffer(data,fSize,output);
00267     data = output;
00268     if (member.isBytecode())
00269       hdrSize = -fSize-4;
00270     else
00271       hdrSize = -fSize;
00272   } else {
00273     hdrSize = fSize;
00274   }
00275 
00276   // Compute the fields of the header
00277   ArchiveMemberHeader Hdr;
00278   bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
00279 
00280   // Write header to archive file
00281   ARFile.write((char*)&Hdr, sizeof(Hdr));
00282 
00283   // Write the long filename if its long
00284   if (writeLongName) {
00285     ARFile.write(member.getPath().toString().data(),
00286                  member.getPath().toString().length());
00287   }
00288 
00289   // Make sure we write the compressed bytecode magic number if we should.
00290   if (willCompress && member.isBytecode())
00291     ARFile.write("llvc",4);
00292 
00293   // Write the (possibly compressed) member's content to the file.
00294   ARFile.write(data,fSize);
00295 
00296   // Make sure the member is an even length
00297   if ((ARFile.tellp() & 1) == 1)
00298     ARFile << ARFILE_PAD;
00299 
00300   // Free the compressed data, if necessary
00301   if (willCompress) {
00302     free((void*)data);
00303   }
00304 
00305   // Close the mapped file if it was opened
00306   if (mFile != 0) {
00307     mFile->close();
00308     delete mFile;
00309   }
00310 }
00311 
00312 // Write out the LLVM symbol table as an archive member to the file.
00313 void
00314 Archive::writeSymbolTable(std::ofstream& ARFile) {
00315 
00316   // Construct the symbol table's header
00317   ArchiveMemberHeader Hdr;
00318   Hdr.init();
00319   memcpy(Hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
00320   uint64_t secondsSinceEpoch = sys::TimeValue::now().toEpochTime();
00321   char buffer[32];
00322   sprintf(buffer, "%-8o", 0644);
00323   memcpy(Hdr.mode,buffer,8);
00324   sprintf(buffer, "%-6u", sys::Process::GetCurrentUserId());
00325   memcpy(Hdr.uid,buffer,6);
00326   sprintf(buffer, "%-6u", sys::Process::GetCurrentGroupId());
00327   memcpy(Hdr.gid,buffer,6);
00328   sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
00329   memcpy(Hdr.date,buffer,12);
00330   sprintf(buffer,"%-10u",symTabSize);
00331   memcpy(Hdr.size,buffer,10);
00332 
00333   // Write the header
00334   ARFile.write((char*)&Hdr, sizeof(Hdr));
00335 
00336   // Save the starting position of the symbol tables data content.
00337   unsigned startpos = ARFile.tellp();
00338 
00339   // Write out the symbols sequentially
00340   for ( Archive::SymTabType::iterator I = symTab.begin(), E = symTab.end();
00341         I != E; ++I)
00342   {
00343     // Write out the file index
00344     writeInteger(I->second, ARFile);
00345     // Write out the length of the symbol
00346     writeInteger(I->first.length(), ARFile);
00347     // Write out the symbol
00348     ARFile.write(I->first.data(), I->first.length());
00349   }
00350 
00351   // Now that we're done with the symbol table, get the ending file position
00352   unsigned endpos = ARFile.tellp();
00353 
00354   // Make sure that the amount we wrote is what we pre-computed. This is
00355   // critical for file integrity purposes.
00356   assert(endpos - startpos == symTabSize && "Invalid symTabSize computation");
00357 
00358   // Make sure the symbol table is even sized
00359   if (symTabSize % 2 != 0 )
00360     ARFile << ARFILE_PAD;
00361 }
00362 
00363 // Write the entire archive to the file specified when the archive was created.
00364 // This writes to a temporary file first. Options are for creating a symbol
00365 // table, flattening the file names (no directories, 15 chars max) and
00366 // compressing each archive member.
00367 void
00368 Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress){
00369 
00370   // Make sure they haven't opened up the file, not loaded it,
00371   // but are now trying to write it which would wipe out the file.
00372   assert(!(members.empty() && mapfile->size() > 8) &&
00373          "Can't write an archive not opened for writing");
00374 
00375   // Create a temporary file to store the archive in
00376   sys::Path TmpArchive = archPath;
00377   TmpArchive.createTemporaryFileOnDisk();
00378 
00379   // Make sure the temporary gets removed if we crash
00380   sys::RemoveFileOnSignal(TmpArchive);
00381 
00382   // Ensure we can remove the temporary even in the face of an exception
00383   try {
00384     // Create archive file for output.
00385     std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
00386                                  std::ios::binary;
00387     std::ofstream ArchiveFile(TmpArchive.c_str(), io_mode);
00388 
00389     // Check for errors opening or creating archive file.
00390     if ( !ArchiveFile.is_open() || ArchiveFile.bad() ) {
00391       throw std::string("Error opening archive file: ") + archPath.toString();
00392     }
00393 
00394     // If we're creating a symbol table, reset it now
00395     if (CreateSymbolTable) {
00396       symTabSize = 0;
00397       symTab.clear();
00398     }
00399 
00400     // Write magic string to archive.
00401     ArchiveFile << ARFILE_MAGIC;
00402 
00403     // Loop over all member files, and write them out. Note that this also
00404     // builds the symbol table, symTab.
00405     for ( MembersList::iterator I = begin(), E = end(); I != E; ++I) {
00406       writeMember(*I,ArchiveFile,CreateSymbolTable,TruncateNames,Compress);
00407     }
00408 
00409     // Close archive file.
00410     ArchiveFile.close();
00411 
00412     // Write the symbol table
00413     if (CreateSymbolTable) {
00414       // At this point we have written a file that is a legal archive but it
00415       // doesn't have a symbol table in it. To aid in faster reading and to
00416       // ensure compatibility with other archivers we need to put the symbol
00417       // table first in the file. Unfortunately, this means mapping the file
00418       // we just wrote back in and copying it to the destination file.
00419 
00420       // Map in the archive we just wrote.
00421       sys::MappedFile arch(TmpArchive);
00422       const char* base = (const char*) arch.map();
00423 
00424       // Open another temporary file in order to avoid invalidating the mmapped data
00425       sys::Path FinalFilePath = archPath;
00426       FinalFilePath.createTemporaryFileOnDisk();
00427       sys::RemoveFileOnSignal(FinalFilePath);
00428       try {
00429           
00430   
00431         std::ofstream FinalFile(FinalFilePath.c_str(), io_mode);
00432         if ( !FinalFile.is_open() || FinalFile.bad() ) {
00433           throw std::string("Error opening archive file: ") + FinalFilePath.toString();
00434         }
00435   
00436         // Write the file magic number
00437         FinalFile << ARFILE_MAGIC;
00438   
00439         // If there is a foreign symbol table, put it into the file now. Most
00440         // ar(1) implementations require the symbol table to be first but llvm-ar
00441         // can deal with it being after a foreign symbol table. This ensures
00442         // compatibility with other ar(1) implementations as well as allowing the
00443         // archive to store both native .o and LLVM .bc files, both indexed.
00444         if (foreignST) {
00445           writeMember(*foreignST, FinalFile, false, false, false);
00446         }
00447   
00448         // Put out the LLVM symbol table now.
00449         writeSymbolTable(FinalFile);
00450   
00451         // Copy the temporary file contents being sure to skip the file's magic
00452         // number.
00453         FinalFile.write(base + sizeof(ARFILE_MAGIC)-1,
00454           arch.size()-sizeof(ARFILE_MAGIC)+1);
00455   
00456         // Close up shop
00457         FinalFile.close();
00458         arch.close();
00459         
00460         // Move the final file over top of TmpArchive
00461         FinalFilePath.renamePathOnDisk(TmpArchive);
00462       } catch (...) {
00463         // Make sure we clean up.
00464         if (FinalFilePath.exists())
00465           FinalFilePath.eraseFromDisk();
00466         throw;
00467       }
00468     }
00469     
00470     // Before we replace the actual archive, we need to forget all the
00471     // members, since they point to data in that old archive. We need to do
00472     // we cannot replace an open file on Windows.
00473     cleanUpMemory();
00474     
00475     TmpArchive.renamePathOnDisk(archPath);
00476   } catch (...) {
00477     // Make sure we clean up.
00478     if (TmpArchive.exists())
00479       TmpArchive.eraseFromDisk();
00480     throw;
00481   }
00482 }