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