Fixes problem when calling llvm-ar from an unmodifiable directory.
[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   mbr->flags = flags;
187   members.insert(where,mbr);
188   return false;
189 }
190
191 // Write one member out to the file.
192 bool
193 Archive::writeMember(
194   const ArchiveMember& member,
195   raw_fd_ostream& ARFile,
196   bool TruncateNames,
197   std::string* ErrMsg
198 ) {
199
200   uint64_t filepos = ARFile.tell();
201   filepos -= 8;
202
203   // Get the data and its size either from the
204   // member's in-memory data or directly from the file.
205   size_t fSize = member.getSize();
206   const char *data = (const char*)member.getData();
207   MemoryBuffer *mFile = 0;
208   if (!data) {
209     OwningPtr<MemoryBuffer> File;
210     if (error_code ec = MemoryBuffer::getFile(member.getPath(), File)) {
211       if (ErrMsg)
212         *ErrMsg = ec.message();
213       return true;
214     }
215     mFile = File.take();
216     data = mFile->getBufferStart();
217     fSize = mFile->getBufferSize();
218   }
219
220   int hdrSize = fSize;
221
222   // Compute the fields of the header
223   ArchiveMemberHeader Hdr;
224   bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
225
226   // Write header to archive file
227   ARFile.write((char*)&Hdr, sizeof(Hdr));
228
229   // Write the long filename if its long
230   if (writeLongName) {
231     StringRef Name = sys::path::filename(member.getPath());
232     ARFile.write(Name.data(), Name.size());
233   }
234
235   // Write the (possibly compressed) member's content to the file.
236   ARFile.write(data,fSize);
237
238   // Make sure the member is an even length
239   if ((ARFile.tell() & 1) == 1)
240     ARFile << ARFILE_PAD;
241
242   // Close the mapped file if it was opened
243   delete mFile;
244   return false;
245 }
246
247 // Write the entire archive to the file specified when the archive was created.
248 // This writes to a temporary file first. Options are for creating a symbol
249 // table, flattening the file names (no directories, 15 chars max) and
250 // compressing each archive member.
251 bool Archive::writeToDisk(bool TruncateNames, std::string *ErrMsg) {
252   // Make sure they haven't opened up the file, not loaded it,
253   // but are now trying to write it which would wipe out the file.
254   if (members.empty() && mapfile && mapfile->getBufferSize() > 8) {
255     if (ErrMsg)
256       *ErrMsg = "Can't write an archive not opened for writing";
257     return true;
258   }
259
260   // Create a temporary file to store the archive in
261   int TmpArchiveFD;
262   SmallString<128> TmpArchive;
263   error_code EC = sys::fs::createUniqueFile(
264       archPath + ".temp-archive-%%%%%%%.a", TmpArchiveFD, TmpArchive);
265   if (EC)
266     return true;
267
268   // Make sure the temporary gets removed if we crash
269   sys::RemoveFileOnSignal(TmpArchive);
270
271   // Create archive file for output.
272   raw_fd_ostream ArchiveFile(TmpArchiveFD, true);
273
274   // Write magic string to archive.
275   ArchiveFile << ARFILE_MAGIC;
276
277   // Loop over all member files, and write them out. Note that this also
278   // builds the symbol table, symTab.
279   for (MembersList::iterator I = begin(), E = end(); I != E; ++I) {
280     if (writeMember(*I, ArchiveFile, TruncateNames, ErrMsg)) {
281       sys::fs::remove(Twine(TmpArchive));
282       ArchiveFile.close();
283       return true;
284     }
285   }
286
287   // Close archive file.
288   ArchiveFile.close();
289
290   // Before we replace the actual archive, we need to forget all the
291   // members, since they point to data in that old archive. We need to do
292   // this because we cannot replace an open file on Windows.
293   cleanUpMemory();
294
295   if (sys::fs::rename(Twine(TmpArchive), archPath)) {
296     *ErrMsg = EC.message();
297     return true;
298   }
299
300   return false;
301 }