Kill ModuleProvider and ghost linkage by inverting the relationship between
[oota-llvm.git] / lib / Archive / ArchiveWriter.cpp
index c3fda5fe1a94d8634409af0b5627e3b1765e5fe8..58fbbf44141ccdfba512fb92173129b1b374b726 100644 (file)
@@ -2,29 +2,30 @@
 //
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by Reid Spencer and is distributed under the
-// University of Illinois Open Source License. See LICENSE.TXT for details.
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
 //
-// Builds up an LLVM archive file (.a) containing LLVM bytecode.
+// Builds up an LLVM archive file (.a) containing LLVM bitcode.
 //
 //===----------------------------------------------------------------------===//
 
 #include "ArchiveInternals.h"
-#include "llvm/Bytecode/Reader.h"
-#include "llvm/Support/Compressor.h"
-#include "llvm/System/Signals.h"
+#include "llvm/Module.h"
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/Bitcode/ReaderWriter.h"
+#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/System/Process.h"
+#include "llvm/System/Signals.h"
 #include <fstream>
-#include <iostream>
+#include <ostream>
 #include <iomanip>
-
 using namespace llvm;
 
 // Write an integer using variable bit rate encoding. This saves a few bytes
 // per entry in the symbol table.
-inline void writeInteger(unsigned num, std::ofstream& ARFile) {
+static inline void writeInteger(unsigned num, std::ofstream& ARFile) {
   while (1) {
     if (num < 0x80) { // done?
       ARFile << (unsigned char)num;
@@ -40,7 +41,7 @@ inline void writeInteger(unsigned num, std::ofstream& ARFile) {
 
 // Compute how many bytes are taken by a given VBR encoded value. This is needed
 // to pre-compute the size of the symbol table.
-inline unsigned numVbrBytes(unsigned num) {
+static inline unsigned numVbrBytes(unsigned num) {
 
   // Note that the following nested ifs are somewhat equivalent to a binary
   // search. We split it in half by comparing against 2^14 first. This allows
@@ -48,11 +49,12 @@ inline unsigned numVbrBytes(unsigned num) {
   // small ones and four for large ones. We expect this to access file offsets
   // in the 2^10 to 2^24 range and symbol lengths in the 2^0 to 2^8 range,
   // so this approach is reasonable.
-  if (num < 1<<14)
+  if (num < 1<<14) {
     if (num < 1<<7)
       return 1;
     else
       return 2;
+  }
   if (num < 1<<21)
     return 3;
 
@@ -62,9 +64,8 @@ inline unsigned numVbrBytes(unsigned num) {
 }
 
 // Create an empty archive.
-Archive*
-Archive::CreateEmpty(const sys::Path& FilePath ) {
-  Archive* result = new Archive(FilePath,false);
+Archive* Archive::CreateEmpty(const sys::Path& FilePath, LLVMContext& C) {
+  Archive* result = new Archive(FilePath, C);
   return result;
 }
 
@@ -94,7 +95,7 @@ Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
   memcpy(hdr.date,buffer,12);
 
   // Get rid of trailing blanks in the name
-  std::string mbrPath = mbr.getPath().toString();
+  std::string mbrPath = mbr.getPath().str();
   size_t mbrLen = mbrPath.length();
   while (mbrLen > 0 && mbrPath[mbrLen-1] == ' ') {
     mbrPath.erase(mbrLen-1,1);
@@ -151,38 +152,44 @@ Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
 
 // Insert a file into the archive before some other member. This also takes care
 // of extracting the necessary flags and information from the file.
-void
-Archive::addFileBefore(const sys::Path& filePath, iterator where) {
-  assert(filePath.exists() && "Can't add a non-existent file");
+bool
+Archive::addFileBefore(const sys::Path& filePath, iterator where, 
+                        std::string* ErrMsg) {
+  if (!filePath.exists()) {
+    if (ErrMsg)
+      *ErrMsg = "Can not add a non-existent file to archive";
+    return true;
+  }
 
   ArchiveMember* mbr = new ArchiveMember(this);
 
   mbr->data = 0;
   mbr->path = filePath;
-  std::string err;
-  if (mbr->path.getFileStatus(mbr->info, &err))
-    throw err;
+  const sys::FileStatus *FSInfo = mbr->path.getFileStatus(false, ErrMsg);
+  if (!FSInfo) {
+    delete mbr;
+    return true;
+  }
+  mbr->info = *FSInfo;
 
   unsigned flags = 0;
-  bool hasSlash = filePath.toString().find('/') != std::string::npos;
+  bool hasSlash = filePath.str().find('/') != std::string::npos;
   if (hasSlash)
     flags |= ArchiveMember::HasPathFlag;
-  if (hasSlash || filePath.toString().length() > 15)
+  if (hasSlash || filePath.str().length() > 15)
     flags |= ArchiveMember::HasLongFilenameFlag;
   std::string magic;
   mbr->path.getMagicNumber(magic,4);
   switch (sys::IdentifyFileType(magic.c_str(),4)) {
-    case sys::BytecodeFileType:
-      flags |= ArchiveMember::BytecodeFlag;
-      break;
-    case sys::CompressedBytecodeFileType:
-      flags |= ArchiveMember::CompressedBytecodeFlag;
+    case sys::Bitcode_FileType:
+      flags |= ArchiveMember::BitcodeFlag;
       break;
     default:
       break;
   }
   mbr->flags = flags;
   members.insert(where,mbr);
+  return false;
 }
 
 // Write one member out to the file.
@@ -193,7 +200,7 @@ Archive::writeMember(
   bool CreateSymbolTable,
   bool TruncateNames,
   bool ShouldCompress,
-  std::string* error
+  std::string* ErrMsg
 ) {
 
   unsigned filepos = ARFile.tellp();
@@ -202,31 +209,28 @@ Archive::writeMember(
   // Get the data and its size either from the
   // member's in-memory data or directly from the file.
   size_t fSize = member.getSize();
-  const chardata = (const char*)member.getData();
-  sys::MappedFile* mFile = 0;
+  const char *data = (const char*)member.getData();
+  MemoryBuffer *mFile = 0;
   if (!data) {
-    std::string ErrMsg;
-    mFile = new sys::MappedFile();
-    if (mFile->open(member.getPath(), sys::MappedFile::READ_ACCESS, &ErrMsg))
-      throw ErrMsg;
-    if (!(data = (const char*) mFile->map(&ErrMsg)))
-      throw ErrMsg;
-    fSize = mFile->size();
+    mFile = MemoryBuffer::getFile(member.getPath().c_str(), ErrMsg);
+    if (mFile == 0)
+      return true;
+    data = mFile->getBufferStart();
+    fSize = mFile->getBufferSize();
   }
 
   // Now that we have the data in memory, update the
-  // symbol table if its a bytecode file.
-  if (CreateSymbolTable &&
-      (member.isBytecode() || member.isCompressedBytecode())) {
+  // symbol table if its a bitcode file.
+  if (CreateSymbolTable && member.isBitcode()) {
     std::vector<std::string> symbols;
-    std::string FullMemberName = archPath.toString() + "(" +
-      member.getPath().toString()
+    std::string FullMemberName = archPath.str() + "(" + member.getPath().str()
       + ")";
-    ModuleProvider* MP = GetBytecodeSymbols(
-      (const unsigned char*)data,fSize,FullMemberName, symbols);
+    Module* M = 
+      GetBitcodeSymbols((const unsigned char*)data,fSize,
+                        FullMemberName, Context, symbols, ErrMsg);
 
-    // If the bytecode parsed successfully
-    if ( MP ) {
+    // If the bitcode parsed successfully
+    if ( M ) {
       for (std::vector<std::string>::iterator SI = symbols.begin(),
            SE = symbols.end(); SI != SE; ++SI) {
 
@@ -240,51 +244,17 @@ Archive::writeMember(
         }
       }
       // We don't need this module any more.
-      delete MP;
+      delete M;
     } else {
-      if (mFile != 0) {
-        mFile->close();
-        delete mFile;
-      }
-      if (error)
-        *error = "Can't parse bytecode member: " + member.getPath().toString();
+      delete mFile;
+      if (ErrMsg)
+        *ErrMsg = "Can't parse bitcode member: " + member.getPath().str()
+          + ": " + *ErrMsg;
+      return true;
     }
   }
 
-  // Determine if we actually should compress this member
-  bool willCompress =
-      (ShouldCompress &&
-      !member.isCompressed() &&
-      !member.isCompressedBytecode() &&
-      !member.isLLVMSymbolTable() &&
-      !member.isSVR4SymbolTable() &&
-      !member.isBSD4SymbolTable());
-
-  // Perform the compression. Note that if the file is uncompressed bytecode
-  // then we turn the file into compressed bytecode rather than treating it as
-  // compressed data. This is necessary since it allows us to determine that the
-  // file contains bytecode instead of looking like a regular compressed data
-  // member. A compressed bytecode file has its content compressed but has a
-  // magic number of "llvc". This acounts for the +/-4 arithmetic in the code
-  // below.
-  int hdrSize;
-  if (willCompress) {
-    char* output = 0;
-    if (member.isBytecode()) {
-      data +=4;
-      fSize -= 4;
-    }
-    fSize = Compressor::compressToNewBuffer(data,fSize,output,error);
-    if (fSize == 0)
-      return false;
-    data = output;
-    if (member.isBytecode())
-      hdrSize = -fSize-4;
-    else
-      hdrSize = -fSize;
-  } else {
-    hdrSize = fSize;
-  }
+  int hdrSize = fSize;
 
   // Compute the fields of the header
   ArchiveMemberHeader Hdr;
@@ -295,14 +265,10 @@ Archive::writeMember(
 
   // Write the long filename if its long
   if (writeLongName) {
-    ARFile.write(member.getPath().toString().data(),
-                 member.getPath().toString().length());
+    ARFile.write(member.getPath().str().data(),
+                 member.getPath().str().length());
   }
 
-  // Make sure we write the compressed bytecode magic number if we should.
-  if (willCompress && member.isBytecode())
-    ARFile.write("llvc",4);
-
   // Write the (possibly compressed) member's content to the file.
   ARFile.write(data,fSize);
 
@@ -310,17 +276,9 @@ Archive::writeMember(
   if ((ARFile.tellp() & 1) == 1)
     ARFile << ARFILE_PAD;
 
-  // Free the compressed data, if necessary
-  if (willCompress) {
-    free((void*)data);
-  }
-
   // Close the mapped file if it was opened
-  if (mFile != 0) {
-    mFile->close();
-    delete mFile;
-  }
-  return true;
+  delete mFile;
+  return false;
 }
 
 // Write out the LLVM symbol table as an archive member to the file.
@@ -347,8 +305,10 @@ Archive::writeSymbolTable(std::ofstream& ARFile) {
   // Write the header
   ARFile.write((char*)&Hdr, sizeof(Hdr));
 
+#ifndef NDEBUG
   // Save the starting position of the symbol tables data content.
   unsigned startpos = ARFile.tellp();
+#endif
 
   // Write out the symbols sequentially
   for ( Archive::SymTabType::iterator I = symTab.begin(), E = symTab.end();
@@ -362,8 +322,10 @@ Archive::writeSymbolTable(std::ofstream& ARFile) {
     ARFile.write(I->first.data(), I->first.length());
   }
 
+#ifndef NDEBUG
   // Now that we're done with the symbol table, get the ending file position
   unsigned endpos = ARFile.tellp();
+#endif
 
   // Make sure that the amount we wrote is what we pre-computed. This is
   // critical for file integrity purposes.
@@ -380,17 +342,20 @@ Archive::writeSymbolTable(std::ofstream& ARFile) {
 // compressing each archive member.
 bool
 Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
-                     std::string* error)
+                     std::string* ErrMsg)
 {
   // Make sure they haven't opened up the file, not loaded it,
   // but are now trying to write it which would wipe out the file.
-  assert(!(members.empty() && mapfile->size() > 8) &&
-         "Can't write an archive not opened for writing");
+  if (members.empty() && mapfile && mapfile->getBufferSize() > 8) {
+    if (ErrMsg)
+      *ErrMsg = "Can't write an archive not opened for writing";
+    return true;
+  }
 
   // Create a temporary file to store the archive in
   sys::Path TmpArchive = archPath;
-  if (TmpArchive.createTemporaryFileOnDisk(error))
-    return false;
+  if (TmpArchive.createTemporaryFileOnDisk(ErrMsg))
+    return true;
 
   // Make sure the temporary gets removed if we crash
   sys::RemoveFileOnSignal(TmpArchive);
@@ -404,9 +369,9 @@ Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
   if (!ArchiveFile.is_open() || ArchiveFile.bad()) {
     if (TmpArchive.exists())
       TmpArchive.eraseFromDisk();
-    if (error)
-      *error = "Error opening archive file: " + archPath.toString();
-    return false;
+    if (ErrMsg)
+      *ErrMsg = "Error opening archive file: " + archPath.str();
+    return true;
   }
 
   // If we're creating a symbol table, reset it now
@@ -421,12 +386,12 @@ Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
   // Loop over all member files, and write them out. Note that this also
   // builds the symbol table, symTab.
   for (MembersList::iterator I = begin(), E = end(); I != E; ++I) {
-    if (!writeMember(*I, ArchiveFile, CreateSymbolTable,
-                     TruncateNames, Compress, error)) {
+    if (writeMember(*I, ArchiveFile, CreateSymbolTable,
+                     TruncateNames, Compress, ErrMsg)) {
       if (TmpArchive.exists())
         TmpArchive.eraseFromDisk();
       ArchiveFile.close();
-      return false;
+      return true;
     }
   }
 
@@ -440,30 +405,27 @@ Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
     // ensure compatibility with other archivers we need to put the symbol
     // table first in the file. Unfortunately, this means mapping the file
     // we just wrote back in and copying it to the destination file.
+    sys::Path FinalFilePath = archPath;
 
     // Map in the archive we just wrote.
-    sys::MappedFile arch;
-    std::string ErrMsg;
-    if (arch.open(TmpArchive, sys::MappedFile::READ_ACCESS, &ErrMsg))
-      throw ErrMsg;
-    const char* base;
-    if (!(base = (const char*) arch.map(&ErrMsg)))
-      throw ErrMsg;
+    {
+    OwningPtr<MemoryBuffer> arch(MemoryBuffer::getFile(TmpArchive.c_str()));
+    if (arch == 0) return true;
+    const char* base = arch->getBufferStart();
 
     // Open another temporary file in order to avoid invalidating the 
     // mmapped data
-    sys::Path FinalFilePath = archPath;
-    if (FinalFilePath.createTemporaryFileOnDisk(error))
-      return false;
+    if (FinalFilePath.createTemporaryFileOnDisk(ErrMsg))
+      return true;
     sys::RemoveFileOnSignal(FinalFilePath);
 
     std::ofstream FinalFile(FinalFilePath.c_str(), io_mode);
     if (!FinalFile.is_open() || FinalFile.bad()) {
       if (TmpArchive.exists())
         TmpArchive.eraseFromDisk();
-      if (error)
-        *error = "Error opening archive file: " + FinalFilePath.toString();
-      return false;
+      if (ErrMsg)
+        *ErrMsg = "Error opening archive file: " + FinalFilePath.str();
+      return true;
     }
 
     // Write the file magic number
@@ -475,11 +437,11 @@ Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
     // compatibility with other ar(1) implementations as well as allowing the
     // archive to store both native .o and LLVM .bc files, both indexed.
     if (foreignST) {
-      if (!writeMember(*foreignST, FinalFile, false, false, false, error)) {
+      if (writeMember(*foreignST, FinalFile, false, false, false, ErrMsg)) {
         FinalFile.close();
         if (TmpArchive.exists())
           TmpArchive.eraseFromDisk();
-        return false;
+        return true;
       }
     }
 
@@ -489,14 +451,15 @@ Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
     // Copy the temporary file contents being sure to skip the file's magic
     // number.
     FinalFile.write(base + sizeof(ARFILE_MAGIC)-1,
-      arch.size()-sizeof(ARFILE_MAGIC)+1);
+      arch->getBufferSize()-sizeof(ARFILE_MAGIC)+1);
 
     // Close up shop
     FinalFile.close();
-    arch.close();
+    } // free arch.
     
     // Move the final file over top of TmpArchive
-    FinalFilePath.renamePathOnDisk(TmpArchive);
+    if (FinalFilePath.renamePathOnDisk(TmpArchive, ErrMsg))
+      return true;
   }
   
   // Before we replace the actual archive, we need to forget all the
@@ -504,7 +467,15 @@ Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
   // this because we cannot replace an open file on Windows.
   cleanUpMemory();
   
-  TmpArchive.renamePathOnDisk(archPath);
+  if (TmpArchive.renamePathOnDisk(archPath, ErrMsg))
+    return true;
+
+  // Set correct read and write permissions after temporary file is moved
+  // to final destination path.
+  if (archPath.makeReadableOnDisk(ErrMsg))
+    return true;
+  if (archPath.makeWriteableOnDisk(ErrMsg))
+    return true;
 
-  return true;
+  return false;
 }