invert the sense of this switch and its name
[oota-llvm.git] / lib / Archive / ArchiveWriter.cpp
index 64c256718e8726711815e50a2288e4edc70aac53..be34356a56d5dd74a4388083c1f788d0ee2ccf4b 100644 (file)
@@ -1,10 +1,10 @@
 //===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
-// 
+//
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by Reid Spencer and is distributed under the 
+// This file was developed by Reid Spencer and 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.
@@ -13,9 +13,9 @@
 
 #include "ArchiveInternals.h"
 #include "llvm/Bytecode/Reader.h"
-#include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/Compressor.h"
 #include "llvm/System/Signals.h"
+#include "llvm/System/Process.h"
 #include <fstream>
 #include <iostream>
 #include <iomanip>
@@ -30,7 +30,7 @@ inline void writeInteger(unsigned num, std::ofstream& ARFile) {
       ARFile << (unsigned char)num;
       return;
     }
-    
+
     // Nope, we are bigger than a character, output the next 7 bits and set the
     // high bit to say that there is more coming...
     ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
@@ -44,9 +44,9 @@ 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
-  // most reasonable values to be done in 2 comparisons instead of 1 for 
+  // most reasonable values to be done in 2 comparisons instead of 1 for
   // 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, 
+  // 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<<7)
@@ -62,17 +62,17 @@ inline unsigned numVbrBytes(unsigned num) {
 }
 
 // Create an empty archive.
-Archive* 
+Archive*
 Archive::CreateEmpty(const sys::Path& FilePath ) {
   Archive* result = new Archive(FilePath,false);
   return result;
 }
 
-// Fill the ArchiveMemberHeader with the information from a member. If 
+// Fill the ArchiveMemberHeader with the information from a member. If
 // TruncateNames is true, names are flattened to 15 chars or less. The sz field
-// is provided here instead of coming from the mbr because the member might be 
-// stored compressed and the compressed size is not the ArchiveMember's size. 
-// Furthermore compressed files have negative size fields to identify them as 
+// is provided here instead of coming from the mbr because the member might be
+// stored compressed and the compressed size is not the ArchiveMember's size.
+// Furthermore compressed files have negative size fields to identify them as
 // compressed.
 bool
 Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
@@ -119,7 +119,7 @@ Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
       nm += slashpos + 1;
       len -= slashpos +1;
     }
-    if (len > 15) 
+    if (len > 15)
       len = 15;
     memcpy(hdr.name,nm,len);
     hdr.name[len] = '/';
@@ -190,7 +190,7 @@ Archive::writeMember(
   std::ofstream& ARFile,
   bool CreateSymbolTable,
   bool TruncateNames,
-  bool ShouldCompress 
+  bool ShouldCompress
 ) {
 
   unsigned filepos = ARFile.tellp();
@@ -205,45 +205,45 @@ Archive::writeMember(
     mFile = new sys::MappedFile(member.getPath());
     data = (const char*) mFile->map();
     fSize = mFile->size();
-  } 
+  }
 
-  // Now that we have the data in memory, update the 
+  // Now that we have the data in memory, update the
   // symbol table if its a bytecode file.
-  if (CreateSymbolTable && 
+  if (CreateSymbolTable &&
       (member.isBytecode() || member.isCompressedBytecode())) {
     std::vector<std::string> symbols;
-    std::string FullMemberName = archPath.toString() + "(" + 
-      member.getPath().toString() 
+    std::string FullMemberName = archPath.toString() + "(" +
+      member.getPath().toString()
       + ")";
     ModuleProvider* MP = GetBytecodeSymbols(
       (const unsigned char*)data,fSize,FullMemberName, symbols);
 
     // If the bytecode parsed successfully
     if ( MP ) {
-      for (std::vector<std::string>::iterator SI = symbols.begin(), 
+      for (std::vector<std::string>::iterator SI = symbols.begin(),
            SE = symbols.end(); SI != SE; ++SI) {
 
-        std::pair<SymTabType::iterator,bool> Res = 
+        std::pair<SymTabType::iterator,bool> Res =
           symTab.insert(std::make_pair(*SI,filepos));
 
         if (Res.second) {
-          symTabSize += SI->length() + 
-                        numVbrBytes(SI->length()) + 
+          symTabSize += SI->length() +
+                        numVbrBytes(SI->length()) +
                         numVbrBytes(filepos);
         }
       }
       // We don't need this module any more.
       delete MP;
     } else {
-      throw std::string("Can't parse bytecode member: ") + 
+      throw std::string("Can't parse bytecode member: ") +
              member.getPath().toString();
     }
   }
 
   // Determine if we actually should compress this member
-  bool willCompress = 
-      (ShouldCompress && 
-      !member.isCompressed() && 
+  bool willCompress =
+      (ShouldCompress &&
+      !member.isCompressed() &&
       !member.isCompressedBytecode() &&
       !member.isLLVMSymbolTable() &&
       !member.isSVR4SymbolTable() &&
@@ -266,7 +266,7 @@ Archive::writeMember(
     fSize = Compressor::compressToNewBuffer(data,fSize,output);
     data = output;
     if (member.isBytecode())
-      hdrSize = -fSize-4; 
+      hdrSize = -fSize-4;
     else
       hdrSize = -fSize;
   } else {
@@ -294,7 +294,7 @@ Archive::writeMember(
   ARFile.write(data,fSize);
 
   // Make sure the member is an even length
-  if (ARFile.tellp() & 1 == 1)
+  if ((ARFile.tellp() & 1) == 1)
     ARFile << ARFILE_PAD;
 
   // Free the compressed data, if necessary
@@ -304,7 +304,7 @@ Archive::writeMember(
 
   // Close the mapped file if it was opened
   if (mFile != 0) {
-    mFile->unmap();
+    mFile->close();
     delete mFile;
   }
 }
@@ -319,6 +319,12 @@ Archive::writeSymbolTable(std::ofstream& ARFile) {
   memcpy(Hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
   uint64_t secondsSinceEpoch = sys::TimeValue::now().toEpochTime();
   char buffer[32];
+  sprintf(buffer, "%-8o", 0644);
+  memcpy(Hdr.mode,buffer,8);
+  sprintf(buffer, "%-6u", sys::Process::GetCurrentUserId());
+  memcpy(Hdr.uid,buffer,6);
+  sprintf(buffer, "%-6u", sys::Process::GetCurrentGroupId());
+  memcpy(Hdr.gid,buffer,6);
   sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
   memcpy(Hdr.date,buffer,12);
   sprintf(buffer,"%-10u",symTabSize);
@@ -355,20 +361,20 @@ Archive::writeSymbolTable(std::ofstream& ARFile) {
 }
 
 // Write the entire archive to the file specified when the archive was created.
-// This writes to a temporary file first. Options are for creating a symbol 
-// table, flattening the file names (no directories, 15 chars max) and 
+// This writes to a temporary file first. Options are for creating a symbol
+// table, flattening the file names (no directories, 15 chars max) and
 // compressing each archive member.
 void
 Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress){
-  
+
   // 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) && 
+  assert(!(members.empty() && mapfile->size() > 8) &&
          "Can't write an archive not opened for writing");
 
   // Create a temporary file to store the archive in
   sys::Path TmpArchive = archPath;
-  TmpArchive.createTemporaryFile();
+  TmpArchive.createTemporaryFileOnDisk();
 
   // Make sure the temporary gets removed if we crash
   sys::RemoveFileOnSignal(TmpArchive);
@@ -376,8 +382,10 @@ Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress){
   // Ensure we can remove the temporary even in the face of an exception
   try {
     // Create archive file for output.
-    std::ofstream ArchiveFile(TmpArchive.c_str());
-  
+    std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
+                                 std::ios::binary;
+    std::ofstream ArchiveFile(TmpArchive.c_str(), io_mode);
+
     // Check for errors opening or creating archive file.
     if ( !ArchiveFile.is_open() || ArchiveFile.bad() ) {
       throw std::string("Error opening archive file: ") + archPath.toString();
@@ -413,46 +421,62 @@ Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress){
       sys::MappedFile arch(TmpArchive);
       const char* base = (const char*) arch.map();
 
-      // Open the final file to write and check it.
-      std::ofstream FinalFile(archPath.c_str());
-      if ( !FinalFile.is_open() || FinalFile.bad() ) {
-        throw std::string("Error opening archive file: ") + archPath.toString();
-      }
-
-      // Write the file magic number
-      FinalFile << ARFILE_MAGIC;
-
-      // If there is a foreign symbol table, put it into the file now. Most
-      // ar(1) implementations require the symbol table to be first but llvm-ar
-      // can deal with it being after a foreign symbol table. This ensures
-      // 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) {
-        writeMember(*foreignST, FinalFile, false, false, false);
+      // Open another temporary file in order to avoid invalidating the mmapped data
+      sys::Path FinalFilePath = archPath;
+      FinalFilePath.createTemporaryFileOnDisk();
+      sys::RemoveFileOnSignal(FinalFilePath);
+      try {
+          
+  
+        std::ofstream FinalFile(FinalFilePath.c_str(), io_mode);
+        if ( !FinalFile.is_open() || FinalFile.bad() ) {
+          throw std::string("Error opening archive file: ") + FinalFilePath.toString();
+        }
+  
+        // Write the file magic number
+        FinalFile << ARFILE_MAGIC;
+  
+        // If there is a foreign symbol table, put it into the file now. Most
+        // ar(1) implementations require the symbol table to be first but llvm-ar
+        // can deal with it being after a foreign symbol table. This ensures
+        // 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) {
+          writeMember(*foreignST, FinalFile, false, false, false);
+        }
+  
+        // Put out the LLVM symbol table now.
+        writeSymbolTable(FinalFile);
+  
+        // 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);
+  
+        // Close up shop
+        FinalFile.close();
+        arch.close();
+        
+        // Move the final file over top of TmpArchive
+        FinalFilePath.renamePathOnDisk(TmpArchive);
+      } catch (...) {
+        // Make sure we clean up.
+        if (FinalFilePath.exists())
+          FinalFilePath.eraseFromDisk();
+        throw;
       }
-
-      // Put out the LLVM symbol table now.
-      writeSymbolTable(FinalFile);
-
-      // 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);
-
-      // Close up shop
-      FinalFile.close();
-      arch.unmap();
-      TmpArchive.destroyFile();
-
-    } else {
-      // We don't have to insert the symbol table, so just renaming the temp
-      // file to the correct name will suffice.
-      TmpArchive.renameFile(archPath);
     }
+    
+    // Before we replace the actual archive, we need to forget all the
+    // members, since they point to data in that old archive. We need to do
+    // we cannot replace an open file on Windows.
+    cleanUpMemory();
+    
+    TmpArchive.renamePathOnDisk(archPath);
   } catch (...) {
     // Make sure we clean up.
     if (TmpArchive.exists())
-      TmpArchive.destroyFile();
+      TmpArchive.eraseFromDisk();
     throw;
   }
 }