Create the file with the right permissions instead of setting it afterwards.
[oota-llvm.git] / tools / llvm-ar / 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 "Archive.h"
15 #include "ArchiveInternals.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Process.h"
22 #include "llvm/Support/Signals.h"
23 #include "llvm/Support/system_error.h"
24 #include <fstream>
25 #include <iomanip>
26 #include <ostream>
27 using namespace llvm;
28
29 // Write an integer using variable bit rate encoding. This saves a few bytes
30 // per entry in the symbol table.
31 static inline void writeInteger(unsigned num, std::ofstream& ARFile) {
32   while (1) {
33     if (num < 0x80) { // done?
34       ARFile << (unsigned char)num;
35       return;
36     }
37
38     // Nope, we are bigger than a character, output the next 7 bits and set the
39     // high bit to say that there is more coming...
40     ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
41     num >>= 7;  // Shift out 7 bits now...
42   }
43 }
44
45 // Compute how many bytes are taken by a given VBR encoded value. This is needed
46 // to pre-compute the size of the symbol table.
47 static inline unsigned numVbrBytes(unsigned num) {
48
49   // Note that the following nested ifs are somewhat equivalent to a binary
50   // search. We split it in half by comparing against 2^14 first. This allows
51   // most reasonable values to be done in 2 comparisons instead of 1 for
52   // small ones and four for large ones. We expect this to access file offsets
53   // in the 2^10 to 2^24 range and symbol lengths in the 2^0 to 2^8 range,
54   // so this approach is reasonable.
55   if (num < 1<<14) {
56     if (num < 1<<7)
57       return 1;
58     else
59       return 2;
60   }
61   if (num < 1<<21)
62     return 3;
63
64   if (num < 1<<28)
65     return 4;
66   return 5; // anything >= 2^28 takes 5 bytes
67 }
68
69 // Create an empty archive.
70 Archive* Archive::CreateEmpty(StringRef FilePath, LLVMContext& C) {
71   Archive* result = new Archive(FilePath, C);
72   return result;
73 }
74
75 // Fill the ArchiveMemberHeader with the information from a member. If
76 // TruncateNames is true, names are flattened to 15 chars or less. The sz field
77 // is provided here instead of coming from the mbr because the member might be
78 // stored compressed and the compressed size is not the ArchiveMember's size.
79 // Furthermore compressed files have negative size fields to identify them as
80 // compressed.
81 bool
82 Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
83                     int sz, bool TruncateNames) const {
84
85   // Set the permissions mode, uid and gid
86   hdr.init();
87   char buffer[32];
88   sprintf(buffer, "%-8o", mbr.getMode());
89   memcpy(hdr.mode,buffer,8);
90   sprintf(buffer,  "%-6u", mbr.getUser());
91   memcpy(hdr.uid,buffer,6);
92   sprintf(buffer,  "%-6u", mbr.getGroup());
93   memcpy(hdr.gid,buffer,6);
94
95   // Set the last modification date
96   uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
97   sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
98   memcpy(hdr.date,buffer,12);
99
100   std::string mbrPath = sys::path::filename(mbr.getPath());
101
102   // Set the name field in one of its various flavors.
103   bool writeLongName = false;
104   if (mbr.isStringTable()) {
105     memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
106   } else if (mbr.isSVR4SymbolTable()) {
107     memcpy(hdr.name,ARFILE_SVR4_SYMTAB_NAME,16);
108   } else if (mbr.isBSD4SymbolTable()) {
109     memcpy(hdr.name,ARFILE_BSD4_SYMTAB_NAME,16);
110   } else if (TruncateNames) {
111     const char* nm = mbrPath.c_str();
112     unsigned len = mbrPath.length();
113     size_t slashpos = mbrPath.rfind('/');
114     if (slashpos != std::string::npos) {
115       nm += slashpos + 1;
116       len -= slashpos +1;
117     }
118     if (len > 15)
119       len = 15;
120     memcpy(hdr.name,nm,len);
121     hdr.name[len] = '/';
122   } else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
123     memcpy(hdr.name,mbrPath.c_str(),mbrPath.length());
124     hdr.name[mbrPath.length()] = '/';
125   } else {
126     std::string nm = "#1/";
127     nm += utostr(mbrPath.length());
128     memcpy(hdr.name,nm.data(),nm.length());
129     if (sz < 0)
130       sz -= mbrPath.length();
131     else
132       sz += mbrPath.length();
133     writeLongName = true;
134   }
135
136   // Set the size field
137   if (sz < 0) {
138     buffer[0] = '-';
139     sprintf(&buffer[1],"%-9u",(unsigned)-sz);
140   } else {
141     sprintf(buffer, "%-10u", (unsigned)sz);
142   }
143   memcpy(hdr.size,buffer,10);
144
145   return writeLongName;
146 }
147
148 // Insert a file into the archive before some other member. This also takes care
149 // of extracting the necessary flags and information from the file.
150 bool Archive::addFileBefore(StringRef filePath, iterator where,
151                             std::string *ErrMsg) {
152   if (!sys::fs::exists(filePath)) {
153     if (ErrMsg)
154       *ErrMsg = "Can not add a non-existent file to archive";
155     return true;
156   }
157
158   ArchiveMember* mbr = new ArchiveMember(this);
159
160   mbr->data = 0;
161   mbr->path = filePath;
162   sys::fs::file_status Status;
163   error_code EC = sys::fs::status(filePath, Status);
164   if (EC) {
165     delete mbr;
166     return true;
167   }
168   mbr->User = Status.getUser();
169   mbr->Group = Status.getGroup();
170   mbr->Mode = Status.permissions();
171   mbr->ModTime = Status.getLastModificationTime();
172   // FIXME: On posix this is a second stat.
173   EC =  sys::fs::file_size(filePath, mbr->Size);
174   if (EC) {
175     delete mbr;
176     return true;
177   }
178
179   unsigned flags = 0;
180   if (sys::path::filename(filePath).size() > 15)
181     flags |= ArchiveMember::HasLongFilenameFlag;
182
183   sys::fs::file_magic type;
184   if (sys::fs::identify_magic(mbr->path, type))
185     type = sys::fs::file_magic::unknown;
186   switch (type) {
187     case sys::fs::file_magic::bitcode:
188       flags |= ArchiveMember::BitcodeFlag;
189       break;
190     default:
191       break;
192   }
193   mbr->flags = flags;
194   members.insert(where,mbr);
195   return false;
196 }
197
198 // Write one member out to the file.
199 bool
200 Archive::writeMember(
201   const ArchiveMember& member,
202   raw_fd_ostream& ARFile,
203   bool TruncateNames,
204   std::string* ErrMsg
205 ) {
206
207   uint64_t filepos = ARFile.tell();
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(), 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   int hdrSize = fSize;
228
229   // Compute the fields of the header
230   ArchiveMemberHeader Hdr;
231   bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
232
233   // Write header to archive file
234   ARFile.write((char*)&Hdr, sizeof(Hdr));
235
236   // Write the long filename if its long
237   if (writeLongName) {
238     StringRef Name = sys::path::filename(member.getPath());
239     ARFile.write(Name.data(), Name.size());
240   }
241
242   // Write the (possibly compressed) member's content to the file.
243   ARFile.write(data,fSize);
244
245   // Make sure the member is an even length
246   if ((ARFile.tell() & 1) == 1)
247     ARFile << ARFILE_PAD;
248
249   // Close the mapped file if it was opened
250   delete mFile;
251   return false;
252 }
253
254 // Write the entire archive to the file specified when the archive was created.
255 // This writes to a temporary file first. Options are for creating a symbol
256 // table, flattening the file names (no directories, 15 chars max) and
257 // compressing each archive member.
258 bool Archive::writeToDisk(bool TruncateNames, std::string *ErrMsg) {
259   // Make sure they haven't opened up the file, not loaded it,
260   // but are now trying to write it which would wipe out the file.
261   if (members.empty() && mapfile && mapfile->getBufferSize() > 8) {
262     if (ErrMsg)
263       *ErrMsg = "Can't write an archive not opened for writing";
264     return true;
265   }
266
267   // Create a temporary file to store the archive in
268   int TmpArchiveFD;
269   SmallString<128> TmpArchive;
270   error_code EC = sys::fs::unique_file("temp-archive-%%%%%%%.a", TmpArchiveFD,
271                                        TmpArchive, true, 0666);
272   if (EC)
273     return true;
274
275   // Make sure the temporary gets removed if we crash
276   sys::RemoveFileOnSignal(TmpArchive);
277
278   // Create archive file for output.
279   raw_fd_ostream ArchiveFile(TmpArchiveFD, true);
280
281   // Write magic string to archive.
282   ArchiveFile << ARFILE_MAGIC;
283
284   // Loop over all member files, and write them out. Note that this also
285   // builds the symbol table, symTab.
286   for (MembersList::iterator I = begin(), E = end(); I != E; ++I) {
287     if (writeMember(*I, ArchiveFile, TruncateNames, ErrMsg)) {
288       sys::fs::remove(Twine(TmpArchive));
289       ArchiveFile.close();
290       return true;
291     }
292   }
293
294   // Close archive file.
295   ArchiveFile.close();
296
297   // Before we replace the actual archive, we need to forget all the
298   // members, since they point to data in that old archive. We need to do
299   // this because we cannot replace an open file on Windows.
300   cleanUpMemory();
301
302   if (sys::fs::rename(Twine(TmpArchive), archPath)) {
303     *ErrMsg = EC.message();
304     return true;
305   }
306
307   return false;
308 }