Minor cleanup related to my latest scheduler changes.
[oota-llvm.git] / lib / Archive / ArchiveWriter.cpp
1 //===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Builds up an LLVM archive file (.a) containing LLVM bitcode.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ArchiveInternals.h"
15 #include "llvm/Module.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/Process.h"
20 #include "llvm/Support/Signals.h"
21 #include "llvm/Support/system_error.h"
22 #include <fstream>
23 #include <ostream>
24 #include <iomanip>
25 using namespace llvm;
26
27 // Write an integer using variable bit rate encoding. This saves a few bytes
28 // per entry in the symbol table.
29 static inline void writeInteger(unsigned num, std::ofstream& ARFile) {
30   while (1) {
31     if (num < 0x80) { // done?
32       ARFile << (unsigned char)num;
33       return;
34     }
35
36     // Nope, we are bigger than a character, output the next 7 bits and set the
37     // high bit to say that there is more coming...
38     ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
39     num >>= 7;  // Shift out 7 bits now...
40   }
41 }
42
43 // Compute how many bytes are taken by a given VBR encoded value. This is needed
44 // to pre-compute the size of the symbol table.
45 static inline unsigned numVbrBytes(unsigned num) {
46
47   // Note that the following nested ifs are somewhat equivalent to a binary
48   // search. We split it in half by comparing against 2^14 first. This allows
49   // most reasonable values to be done in 2 comparisons instead of 1 for
50   // small ones and four for large ones. We expect this to access file offsets
51   // in the 2^10 to 2^24 range and symbol lengths in the 2^0 to 2^8 range,
52   // so this approach is reasonable.
53   if (num < 1<<14) {
54     if (num < 1<<7)
55       return 1;
56     else
57       return 2;
58   }
59   if (num < 1<<21)
60     return 3;
61
62   if (num < 1<<28)
63     return 4;
64   return 5; // anything >= 2^28 takes 5 bytes
65 }
66
67 // Create an empty archive.
68 Archive* Archive::CreateEmpty(const sys::Path& FilePath, LLVMContext& C) {
69   Archive* result = new Archive(FilePath, C);
70   return result;
71 }
72
73 // Fill the ArchiveMemberHeader with the information from a member. If
74 // TruncateNames is true, names are flattened to 15 chars or less. The sz field
75 // is provided here instead of coming from the mbr because the member might be
76 // stored compressed and the compressed size is not the ArchiveMember's size.
77 // Furthermore compressed files have negative size fields to identify them as
78 // compressed.
79 bool
80 Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
81                     int sz, bool TruncateNames) const {
82
83   // Set the permissions mode, uid and gid
84   hdr.init();
85   char buffer[32];
86   sprintf(buffer, "%-8o", mbr.getMode());
87   memcpy(hdr.mode,buffer,8);
88   sprintf(buffer,  "%-6u", mbr.getUser());
89   memcpy(hdr.uid,buffer,6);
90   sprintf(buffer,  "%-6u", mbr.getGroup());
91   memcpy(hdr.gid,buffer,6);
92
93   // Set the last modification date
94   uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
95   sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
96   memcpy(hdr.date,buffer,12);
97
98   // Get rid of trailing blanks in the name
99   std::string mbrPath = mbr.getPath().str();
100   size_t mbrLen = mbrPath.length();
101   while (mbrLen > 0 && mbrPath[mbrLen-1] == ' ') {
102     mbrPath.erase(mbrLen-1,1);
103     mbrLen--;
104   }
105
106   // Set the name field in one of its various flavors.
107   bool writeLongName = false;
108   if (mbr.isStringTable()) {
109     memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
110   } else if (mbr.isSVR4SymbolTable()) {
111     memcpy(hdr.name,ARFILE_SVR4_SYMTAB_NAME,16);
112   } else if (mbr.isBSD4SymbolTable()) {
113     memcpy(hdr.name,ARFILE_BSD4_SYMTAB_NAME,16);
114   } else if (mbr.isLLVMSymbolTable()) {
115     memcpy(hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
116   } else if (TruncateNames) {
117     const char* nm = mbrPath.c_str();
118     unsigned len = mbrPath.length();
119     size_t slashpos = mbrPath.rfind('/');
120     if (slashpos != std::string::npos) {
121       nm += slashpos + 1;
122       len -= slashpos +1;
123     }
124     if (len > 15)
125       len = 15;
126     memcpy(hdr.name,nm,len);
127     hdr.name[len] = '/';
128   } else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
129     memcpy(hdr.name,mbrPath.c_str(),mbrPath.length());
130     hdr.name[mbrPath.length()] = '/';
131   } else {
132     std::string nm = "#1/";
133     nm += utostr(mbrPath.length());
134     memcpy(hdr.name,nm.data(),nm.length());
135     if (sz < 0)
136       sz -= mbrPath.length();
137     else
138       sz += mbrPath.length();
139     writeLongName = true;
140   }
141
142   // Set the size field
143   if (sz < 0) {
144     buffer[0] = '-';
145     sprintf(&buffer[1],"%-9u",(unsigned)-sz);
146   } else {
147     sprintf(buffer, "%-10u", (unsigned)sz);
148   }
149   memcpy(hdr.size,buffer,10);
150
151   return writeLongName;
152 }
153
154 // Insert a file into the archive before some other member. This also takes care
155 // of extracting the necessary flags and information from the file.
156 bool
157 Archive::addFileBefore(const sys::Path& filePath, iterator where, 
158                         std::string* ErrMsg) {
159   if (!filePath.exists()) {
160     if (ErrMsg)
161       *ErrMsg = "Can not add a non-existent file to archive";
162     return true;
163   }
164
165   ArchiveMember* mbr = new ArchiveMember(this);
166
167   mbr->data = 0;
168   mbr->path = filePath;
169   const sys::FileStatus *FSInfo = mbr->path.getFileStatus(false, ErrMsg);
170   if (!FSInfo) {
171     delete mbr;
172     return true;
173   }
174   mbr->info = *FSInfo;
175
176   unsigned flags = 0;
177   bool hasSlash = filePath.str().find('/') != std::string::npos;
178   if (hasSlash)
179     flags |= ArchiveMember::HasPathFlag;
180   if (hasSlash || filePath.str().length() > 15)
181     flags |= ArchiveMember::HasLongFilenameFlag;
182   std::string magic;
183   mbr->path.getMagicNumber(magic,4);
184   switch (sys::IdentifyFileType(magic.c_str(),4)) {
185     case sys::Bitcode_FileType:
186       flags |= ArchiveMember::BitcodeFlag;
187       break;
188     default:
189       break;
190   }
191   mbr->flags = flags;
192   members.insert(where,mbr);
193   return false;
194 }
195
196 // Write one member out to the file.
197 bool
198 Archive::writeMember(
199   const ArchiveMember& member,
200   std::ofstream& ARFile,
201   bool CreateSymbolTable,
202   bool TruncateNames,
203   bool ShouldCompress,
204   std::string* ErrMsg
205 ) {
206
207   unsigned filepos = ARFile.tellp();
208   filepos -= 8;
209
210   // Get the data and its size either from the
211   // member's in-memory data or directly from the file.
212   size_t fSize = member.getSize();
213   const char *data = (const char*)member.getData();
214   MemoryBuffer *mFile = 0;
215   if (!data) {
216     OwningPtr<MemoryBuffer> File;
217     if (error_code ec = MemoryBuffer::getFile(member.getPath().c_str(), File)) {
218       if (ErrMsg)
219         *ErrMsg = ec.message();
220       return true;
221     }
222     mFile = File.take();
223     data = mFile->getBufferStart();
224     fSize = mFile->getBufferSize();
225   }
226
227   // Now that we have the data in memory, update the
228   // symbol table if it's a bitcode file.
229   if (CreateSymbolTable && member.isBitcode()) {
230     std::vector<std::string> symbols;
231     std::string FullMemberName = archPath.str() + "(" + member.getPath().str()
232       + ")";
233     Module* M = 
234       GetBitcodeSymbols(data, fSize, FullMemberName, Context, symbols, ErrMsg);
235
236     // If the bitcode parsed successfully
237     if ( M ) {
238       for (std::vector<std::string>::iterator SI = symbols.begin(),
239            SE = symbols.end(); SI != SE; ++SI) {
240
241         std::pair<SymTabType::iterator,bool> Res =
242           symTab.insert(std::make_pair(*SI,filepos));
243
244         if (Res.second) {
245           symTabSize += SI->length() +
246                         numVbrBytes(SI->length()) +
247                         numVbrBytes(filepos);
248         }
249       }
250       // We don't need this module any more.
251       delete M;
252     } else {
253       delete mFile;
254       if (ErrMsg)
255         *ErrMsg = "Can't parse bitcode member: " + member.getPath().str()
256           + ": " + *ErrMsg;
257       return true;
258     }
259   }
260
261   int hdrSize = fSize;
262
263   // Compute the fields of the header
264   ArchiveMemberHeader Hdr;
265   bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
266
267   // Write header to archive file
268   ARFile.write((char*)&Hdr, sizeof(Hdr));
269
270   // Write the long filename if its long
271   if (writeLongName) {
272     ARFile.write(member.getPath().str().data(),
273                  member.getPath().str().length());
274   }
275
276   // Write the (possibly compressed) member's content to the file.
277   ARFile.write(data,fSize);
278
279   // Make sure the member is an even length
280   if ((ARFile.tellp() & 1) == 1)
281     ARFile << ARFILE_PAD;
282
283   // Close the mapped file if it was opened
284   delete mFile;
285   return false;
286 }
287
288 // Write out the LLVM symbol table as an archive member to the file.
289 void
290 Archive::writeSymbolTable(std::ofstream& ARFile) {
291
292   // Construct the symbol table's header
293   ArchiveMemberHeader Hdr;
294   Hdr.init();
295   memcpy(Hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
296   uint64_t secondsSinceEpoch = sys::TimeValue::now().toEpochTime();
297   char buffer[32];
298   sprintf(buffer, "%-8o", 0644);
299   memcpy(Hdr.mode,buffer,8);
300   sprintf(buffer, "%-6u", sys::Process::GetCurrentUserId());
301   memcpy(Hdr.uid,buffer,6);
302   sprintf(buffer, "%-6u", sys::Process::GetCurrentGroupId());
303   memcpy(Hdr.gid,buffer,6);
304   sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
305   memcpy(Hdr.date,buffer,12);
306   sprintf(buffer,"%-10u",symTabSize);
307   memcpy(Hdr.size,buffer,10);
308
309   // Write the header
310   ARFile.write((char*)&Hdr, sizeof(Hdr));
311
312 #ifndef NDEBUG
313   // Save the starting position of the symbol tables data content.
314   unsigned startpos = ARFile.tellp();
315 #endif
316
317   // Write out the symbols sequentially
318   for ( Archive::SymTabType::iterator I = symTab.begin(), E = symTab.end();
319         I != E; ++I)
320   {
321     // Write out the file index
322     writeInteger(I->second, ARFile);
323     // Write out the length of the symbol
324     writeInteger(I->first.length(), ARFile);
325     // Write out the symbol
326     ARFile.write(I->first.data(), I->first.length());
327   }
328
329 #ifndef NDEBUG
330   // Now that we're done with the symbol table, get the ending file position
331   unsigned endpos = ARFile.tellp();
332 #endif
333
334   // Make sure that the amount we wrote is what we pre-computed. This is
335   // critical for file integrity purposes.
336   assert(endpos - startpos == symTabSize && "Invalid symTabSize computation");
337
338   // Make sure the symbol table is even sized
339   if (symTabSize % 2 != 0 )
340     ARFile << ARFILE_PAD;
341 }
342
343 // Write the entire archive to the file specified when the archive was created.
344 // This writes to a temporary file first. Options are for creating a symbol
345 // table, flattening the file names (no directories, 15 chars max) and
346 // compressing each archive member.
347 bool
348 Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
349                      std::string* ErrMsg)
350 {
351   // Make sure they haven't opened up the file, not loaded it,
352   // but are now trying to write it which would wipe out the file.
353   if (members.empty() && mapfile && mapfile->getBufferSize() > 8) {
354     if (ErrMsg)
355       *ErrMsg = "Can't write an archive not opened for writing";
356     return true;
357   }
358
359   // Create a temporary file to store the archive in
360   sys::Path TmpArchive = archPath;
361   if (TmpArchive.createTemporaryFileOnDisk(ErrMsg))
362     return true;
363
364   // Make sure the temporary gets removed if we crash
365   sys::RemoveFileOnSignal(TmpArchive);
366
367   // Create archive file for output.
368   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
369                                std::ios::binary;
370   std::ofstream ArchiveFile(TmpArchive.c_str(), io_mode);
371
372   // Check for errors opening or creating archive file.
373   if (!ArchiveFile.is_open() || ArchiveFile.bad()) {
374     TmpArchive.eraseFromDisk();
375     if (ErrMsg)
376       *ErrMsg = "Error opening archive file: " + archPath.str();
377     return true;
378   }
379
380   // If we're creating a symbol table, reset it now
381   if (CreateSymbolTable) {
382     symTabSize = 0;
383     symTab.clear();
384   }
385
386   // Write magic string to archive.
387   ArchiveFile << ARFILE_MAGIC;
388
389   // Loop over all member files, and write them out. Note that this also
390   // builds the symbol table, symTab.
391   for (MembersList::iterator I = begin(), E = end(); I != E; ++I) {
392     if (writeMember(*I, ArchiveFile, CreateSymbolTable,
393                      TruncateNames, Compress, ErrMsg)) {
394       TmpArchive.eraseFromDisk();
395       ArchiveFile.close();
396       return true;
397     }
398   }
399
400   // Close archive file.
401   ArchiveFile.close();
402
403   // Write the symbol table
404   if (CreateSymbolTable) {
405     // At this point we have written a file that is a legal archive but it
406     // doesn't have a symbol table in it. To aid in faster reading and to
407     // ensure compatibility with other archivers we need to put the symbol
408     // table first in the file. Unfortunately, this means mapping the file
409     // we just wrote back in and copying it to the destination file.
410     sys::Path FinalFilePath = archPath;
411
412     // Map in the archive we just wrote.
413     {
414     OwningPtr<MemoryBuffer> arch;
415     if (error_code ec = MemoryBuffer::getFile(TmpArchive.c_str(), arch)) {
416       if (ErrMsg)
417         *ErrMsg = ec.message();
418       return true;
419     }
420     const char* base = arch->getBufferStart();
421
422     // Open another temporary file in order to avoid invalidating the 
423     // mmapped data
424     if (FinalFilePath.createTemporaryFileOnDisk(ErrMsg))
425       return true;
426     sys::RemoveFileOnSignal(FinalFilePath);
427
428     std::ofstream FinalFile(FinalFilePath.c_str(), io_mode);
429     if (!FinalFile.is_open() || FinalFile.bad()) {
430       TmpArchive.eraseFromDisk();
431       if (ErrMsg)
432         *ErrMsg = "Error opening archive file: " + FinalFilePath.str();
433       return true;
434     }
435
436     // Write the file magic number
437     FinalFile << ARFILE_MAGIC;
438
439     // If there is a foreign symbol table, put it into the file now. Most
440     // ar(1) implementations require the symbol table to be first but llvm-ar
441     // can deal with it being after a foreign symbol table. This ensures
442     // compatibility with other ar(1) implementations as well as allowing the
443     // archive to store both native .o and LLVM .bc files, both indexed.
444     if (foreignST) {
445       if (writeMember(*foreignST, FinalFile, false, false, false, ErrMsg)) {
446         FinalFile.close();
447         TmpArchive.eraseFromDisk();
448         return true;
449       }
450     }
451
452     // Put out the LLVM symbol table now.
453     writeSymbolTable(FinalFile);
454
455     // Copy the temporary file contents being sure to skip the file's magic
456     // number.
457     FinalFile.write(base + sizeof(ARFILE_MAGIC)-1,
458       arch->getBufferSize()-sizeof(ARFILE_MAGIC)+1);
459
460     // Close up shop
461     FinalFile.close();
462     } // free arch.
463     
464     // Move the final file over top of TmpArchive
465     if (FinalFilePath.renamePathOnDisk(TmpArchive, ErrMsg))
466       return true;
467   }
468   
469   // Before we replace the actual archive, we need to forget all the
470   // members, since they point to data in that old archive. We need to do
471   // this because we cannot replace an open file on Windows.
472   cleanUpMemory();
473   
474   if (TmpArchive.renamePathOnDisk(archPath, ErrMsg))
475     return true;
476
477   // Set correct read and write permissions after temporary file is moved
478   // to final destination path.
479   if (archPath.makeReadableOnDisk(ErrMsg))
480     return true;
481   if (archPath.makeWriteableOnDisk(ErrMsg))
482     return true;
483
484   return false;
485 }