1 //===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Builds up an LLVM archive file (.a) containing LLVM bitcode.
12 //===----------------------------------------------------------------------===//
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"
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) {
33 if (num < 0x80) { // done?
34 ARFile << (unsigned char)num;
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...
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) {
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.
66 return 5; // anything >= 2^28 takes 5 bytes
69 // Create an empty archive.
70 Archive* Archive::CreateEmpty(StringRef FilePath, LLVMContext& C) {
71 Archive* result = new Archive(FilePath, C);
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
82 Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
85 // Set the permissions mode, uid and gid
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);
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);
100 std::string mbrPath = sys::path::filename(mbr.getPath());
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()] = '/';
114 std::string nm = "#1/";
115 nm += utostr(mbrPath.length());
116 memcpy(hdr.name,nm.data(),nm.length());
118 sz -= mbrPath.length();
120 sz += mbrPath.length();
121 writeLongName = true;
124 // Set the size field
127 sprintf(&buffer[1],"%-9u",(unsigned)-sz);
129 sprintf(buffer, "%-10u", (unsigned)sz);
131 memcpy(hdr.size,buffer,10);
133 return writeLongName;
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)) {
142 *ErrMsg = "Can not add a non-existent file to archive";
146 ArchiveMember* mbr = new ArchiveMember(this);
149 mbr->path = filePath;
150 sys::fs::file_status Status;
151 error_code EC = sys::fs::status(filePath, Status);
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);
168 if (sys::path::filename(filePath).size() > 15)
169 flags |= ArchiveMember::HasLongFilenameFlag;
171 sys::fs::file_magic type;
172 if (sys::fs::identify_magic(mbr->path, type))
173 type = sys::fs::file_magic::unknown;
175 members.insert(where,mbr);
179 // Write one member out to the file.
181 Archive::writeMember(
182 const ArchiveMember& member,
183 raw_fd_ostream& ARFile,
187 uint64_t filepos = ARFile.tell();
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;
196 OwningPtr<MemoryBuffer> File;
197 if (error_code ec = MemoryBuffer::getFile(member.getPath(), File)) {
199 *ErrMsg = ec.message();
203 data = mFile->getBufferStart();
204 fSize = mFile->getBufferSize();
209 // Compute the fields of the header
210 ArchiveMemberHeader Hdr;
211 bool writeLongName = fillHeader(member,Hdr,hdrSize);
213 // Write header to archive file
214 ARFile.write((char*)&Hdr, sizeof(Hdr));
216 // Write the long filename if its long
218 StringRef Name = sys::path::filename(member.getPath());
219 ARFile.write(Name.data(), Name.size());
222 // Write the (possibly compressed) member's content to the file.
223 ARFile.write(data,fSize);
225 // Make sure the member is an even length
226 if ((ARFile.tell() & 1) == 1)
227 ARFile << ARFILE_PAD;
229 // Close the mapped file if it was opened
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) {
243 *ErrMsg = "Can't write an archive not opened for writing";
247 // Create a temporary file to store the archive in
249 SmallString<128> TmpArchive;
250 error_code EC = sys::fs::createUniqueFile(
251 archPath + ".temp-archive-%%%%%%%.a", TmpArchiveFD, TmpArchive);
255 // Make sure the temporary gets removed if we crash
256 sys::RemoveFileOnSignal(TmpArchive);
258 // Create archive file for output.
259 raw_fd_ostream ArchiveFile(TmpArchiveFD, true);
261 // Write magic string to archive.
262 ArchiveFile << ARFILE_MAGIC;
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));
274 // Close archive file.
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.
282 if (sys::fs::rename(Twine(TmpArchive), archPath)) {
283 *ErrMsg = EC.message();