Remove support for truncating names in archives.
[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) 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 (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
111     memcpy(hdr.name,mbrPath.c_str(),mbrPath.length());
112     hdr.name[mbrPath.length()] = '/';
113   } else {
114     std::string nm = "#1/";
115     nm += utostr(mbrPath.length());
116     memcpy(hdr.name,nm.data(),nm.length());
117     if (sz < 0)
118       sz -= mbrPath.length();
119     else
120       sz += mbrPath.length();
121     writeLongName = true;
122   }
123
124   // Set the size field
125   if (sz < 0) {
126     buffer[0] = '-';
127     sprintf(&buffer[1],"%-9u",(unsigned)-sz);
128   } else {
129     sprintf(buffer, "%-10u", (unsigned)sz);
130   }
131   memcpy(hdr.size,buffer,10);
132
133   return writeLongName;
134 }
135
136 // Insert a file into the archive before some other member. This also takes care
137 // of extracting the necessary flags and information from the file.
138 bool Archive::addFileBefore(StringRef filePath, iterator where,
139                             std::string *ErrMsg) {
140   if (!sys::fs::exists(filePath)) {
141     if (ErrMsg)
142       *ErrMsg = "Can not add a non-existent file to archive";
143     return true;
144   }
145
146   ArchiveMember* mbr = new ArchiveMember(this);
147
148   mbr->data = 0;
149   mbr->path = filePath;
150   sys::fs::file_status Status;
151   error_code EC = sys::fs::status(filePath, Status);
152   if (EC) {
153     delete mbr;
154     return true;
155   }
156   mbr->User = Status.getUser();
157   mbr->Group = Status.getGroup();
158   mbr->Mode = Status.permissions();
159   mbr->ModTime = Status.getLastModificationTime();
160   // FIXME: On posix this is a second stat.
161   EC =  sys::fs::file_size(filePath, mbr->Size);
162   if (EC) {
163     delete mbr;
164     return true;
165   }
166
167   unsigned flags = 0;
168   if (sys::path::filename(filePath).size() > 15)
169     flags |= ArchiveMember::HasLongFilenameFlag;
170
171   sys::fs::file_magic type;
172   if (sys::fs::identify_magic(mbr->path, type))
173     type = sys::fs::file_magic::unknown;
174   mbr->flags = flags;
175   members.insert(where,mbr);
176   return false;
177 }
178
179 // Write one member out to the file.
180 bool
181 Archive::writeMember(
182   const ArchiveMember& member,
183   raw_fd_ostream& ARFile,
184   std::string* ErrMsg
185 ) {
186
187   uint64_t filepos = ARFile.tell();
188   filepos -= 8;
189
190   // Get the data and its size either from the
191   // member's in-memory data or directly from the file.
192   size_t fSize = member.getSize();
193   const char *data = (const char*)member.getData();
194   MemoryBuffer *mFile = 0;
195   if (!data) {
196     OwningPtr<MemoryBuffer> File;
197     if (error_code ec = MemoryBuffer::getFile(member.getPath(), File)) {
198       if (ErrMsg)
199         *ErrMsg = ec.message();
200       return true;
201     }
202     mFile = File.take();
203     data = mFile->getBufferStart();
204     fSize = mFile->getBufferSize();
205   }
206
207   int hdrSize = fSize;
208
209   // Compute the fields of the header
210   ArchiveMemberHeader Hdr;
211   bool writeLongName = fillHeader(member,Hdr,hdrSize);
212
213   // Write header to archive file
214   ARFile.write((char*)&Hdr, sizeof(Hdr));
215
216   // Write the long filename if its long
217   if (writeLongName) {
218     StringRef Name = sys::path::filename(member.getPath());
219     ARFile.write(Name.data(), Name.size());
220   }
221
222   // Write the (possibly compressed) member's content to the file.
223   ARFile.write(data,fSize);
224
225   // Make sure the member is an even length
226   if ((ARFile.tell() & 1) == 1)
227     ARFile << ARFILE_PAD;
228
229   // Close the mapped file if it was opened
230   delete mFile;
231   return false;
232 }
233
234 // Write the entire archive to the file specified when the archive was created.
235 // This writes to a temporary file first. Options are for creating a symbol
236 // table, flattening the file names (no directories, 15 chars max) and
237 // compressing each archive member.
238 bool Archive::writeToDisk(std::string *ErrMsg) {
239   // Make sure they haven't opened up the file, not loaded it,
240   // but are now trying to write it which would wipe out the file.
241   if (members.empty() && mapfile && mapfile->getBufferSize() > 8) {
242     if (ErrMsg)
243       *ErrMsg = "Can't write an archive not opened for writing";
244     return true;
245   }
246
247   // Create a temporary file to store the archive in
248   int TmpArchiveFD;
249   SmallString<128> TmpArchive;
250   error_code EC = sys::fs::createUniqueFile(
251       archPath + ".temp-archive-%%%%%%%.a", TmpArchiveFD, TmpArchive);
252   if (EC)
253     return true;
254
255   // Make sure the temporary gets removed if we crash
256   sys::RemoveFileOnSignal(TmpArchive);
257
258   // Create archive file for output.
259   raw_fd_ostream ArchiveFile(TmpArchiveFD, true);
260
261   // Write magic string to archive.
262   ArchiveFile << ARFILE_MAGIC;
263
264   // Loop over all member files, and write them out. Note that this also
265   // builds the symbol table, symTab.
266   for (MembersList::iterator I = begin(), E = end(); I != E; ++I) {
267     if (writeMember(*I, ArchiveFile, ErrMsg)) {
268       sys::fs::remove(Twine(TmpArchive));
269       ArchiveFile.close();
270       return true;
271     }
272   }
273
274   // Close archive file.
275   ArchiveFile.close();
276
277   // Before we replace the actual archive, we need to forget all the
278   // members, since they point to data in that old archive. We need to do
279   // this because we cannot replace an open file on Windows.
280   cleanUpMemory();
281
282   if (sys::fs::rename(Twine(TmpArchive), archPath)) {
283     *ErrMsg = EC.message();
284     return true;
285   }
286
287   return false;
288 }