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,
83 int sz, bool TruncateNames) const {
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 (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) {
120 memcpy(hdr.name,nm,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()] = '/';
126 std::string nm = "#1/";
127 nm += utostr(mbrPath.length());
128 memcpy(hdr.name,nm.data(),nm.length());
130 sz -= mbrPath.length();
132 sz += mbrPath.length();
133 writeLongName = true;
136 // Set the size field
139 sprintf(&buffer[1],"%-9u",(unsigned)-sz);
141 sprintf(buffer, "%-10u", (unsigned)sz);
143 memcpy(hdr.size,buffer,10);
145 return writeLongName;
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)) {
154 *ErrMsg = "Can not add a non-existent file to archive";
158 ArchiveMember* mbr = new ArchiveMember(this);
161 mbr->path = filePath;
162 sys::fs::file_status Status;
163 error_code EC = sys::fs::status(filePath, Status);
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);
180 if (sys::path::filename(filePath).size() > 15)
181 flags |= ArchiveMember::HasLongFilenameFlag;
183 sys::fs::file_magic type;
184 if (sys::fs::identify_magic(mbr->path, type))
185 type = sys::fs::file_magic::unknown;
187 members.insert(where,mbr);
191 // Write one member out to the file.
193 Archive::writeMember(
194 const ArchiveMember& member,
195 raw_fd_ostream& ARFile,
200 uint64_t filepos = ARFile.tell();
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;
209 OwningPtr<MemoryBuffer> File;
210 if (error_code ec = MemoryBuffer::getFile(member.getPath(), File)) {
212 *ErrMsg = ec.message();
216 data = mFile->getBufferStart();
217 fSize = mFile->getBufferSize();
222 // Compute the fields of the header
223 ArchiveMemberHeader Hdr;
224 bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
226 // Write header to archive file
227 ARFile.write((char*)&Hdr, sizeof(Hdr));
229 // Write the long filename if its long
231 StringRef Name = sys::path::filename(member.getPath());
232 ARFile.write(Name.data(), Name.size());
235 // Write the (possibly compressed) member's content to the file.
236 ARFile.write(data,fSize);
238 // Make sure the member is an even length
239 if ((ARFile.tell() & 1) == 1)
240 ARFile << ARFILE_PAD;
242 // Close the mapped file if it was opened
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) {
256 *ErrMsg = "Can't write an archive not opened for writing";
260 // Create a temporary file to store the archive in
262 SmallString<128> TmpArchive;
263 error_code EC = sys::fs::unique_file("temp-archive-%%%%%%%.a", TmpArchiveFD,
264 TmpArchive, true, sys::fs::all_read | sys::fs::all_write);
268 // Make sure the temporary gets removed if we crash
269 sys::RemoveFileOnSignal(TmpArchive);
271 // Create archive file for output.
272 raw_fd_ostream ArchiveFile(TmpArchiveFD, true);
274 // Write magic string to archive.
275 ArchiveFile << ARFILE_MAGIC;
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));
287 // Close archive file.
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.
295 if (sys::fs::rename(Twine(TmpArchive), archPath)) {
296 *ErrMsg = EC.message();