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 //===----------------------------------------------------------------------===//
14 #include "ArchiveInternals.h"
15 #include "llvm/Module.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/Process.h"
20 #include "llvm/Support/Signals.h"
21 #include "llvm/Support/system_error.h"
27 // Write an integer using variable bit rate encoding. This saves a few bytes
28 // per entry in the symbol table.
29 static inline void writeInteger(unsigned num, std::ofstream& ARFile) {
31 if (num < 0x80) { // done?
32 ARFile << (unsigned char)num;
36 // Nope, we are bigger than a character, output the next 7 bits and set the
37 // high bit to say that there is more coming...
38 ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
39 num >>= 7; // Shift out 7 bits now...
43 // Compute how many bytes are taken by a given VBR encoded value. This is needed
44 // to pre-compute the size of the symbol table.
45 static inline unsigned numVbrBytes(unsigned num) {
47 // Note that the following nested ifs are somewhat equivalent to a binary
48 // search. We split it in half by comparing against 2^14 first. This allows
49 // most reasonable values to be done in 2 comparisons instead of 1 for
50 // small ones and four for large ones. We expect this to access file offsets
51 // in the 2^10 to 2^24 range and symbol lengths in the 2^0 to 2^8 range,
52 // so this approach is reasonable.
64 return 5; // anything >= 2^28 takes 5 bytes
67 // Create an empty archive.
68 Archive* Archive::CreateEmpty(const sys::Path& FilePath, LLVMContext& C) {
69 Archive* result = new Archive(FilePath, C);
73 // Fill the ArchiveMemberHeader with the information from a member. If
74 // TruncateNames is true, names are flattened to 15 chars or less. The sz field
75 // is provided here instead of coming from the mbr because the member might be
76 // stored compressed and the compressed size is not the ArchiveMember's size.
77 // Furthermore compressed files have negative size fields to identify them as
80 Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
81 int sz, bool TruncateNames) const {
83 // Set the permissions mode, uid and gid
86 sprintf(buffer, "%-8o", mbr.getMode());
87 memcpy(hdr.mode,buffer,8);
88 sprintf(buffer, "%-6u", mbr.getUser());
89 memcpy(hdr.uid,buffer,6);
90 sprintf(buffer, "%-6u", mbr.getGroup());
91 memcpy(hdr.gid,buffer,6);
93 // Set the last modification date
94 uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
95 sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
96 memcpy(hdr.date,buffer,12);
98 // Get rid of trailing blanks in the name
99 std::string mbrPath = mbr.getPath().str();
100 size_t mbrLen = mbrPath.length();
101 while (mbrLen > 0 && mbrPath[mbrLen-1] == ' ') {
102 mbrPath.erase(mbrLen-1,1);
106 // Set the name field in one of its various flavors.
107 bool writeLongName = false;
108 if (mbr.isStringTable()) {
109 memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
110 } else if (mbr.isSVR4SymbolTable()) {
111 memcpy(hdr.name,ARFILE_SVR4_SYMTAB_NAME,16);
112 } else if (mbr.isBSD4SymbolTable()) {
113 memcpy(hdr.name,ARFILE_BSD4_SYMTAB_NAME,16);
114 } else if (mbr.isLLVMSymbolTable()) {
115 memcpy(hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
116 } else if (TruncateNames) {
117 const char* nm = mbrPath.c_str();
118 unsigned len = mbrPath.length();
119 size_t slashpos = mbrPath.rfind('/');
120 if (slashpos != std::string::npos) {
126 memcpy(hdr.name,nm,len);
128 } else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
129 memcpy(hdr.name,mbrPath.c_str(),mbrPath.length());
130 hdr.name[mbrPath.length()] = '/';
132 std::string nm = "#1/";
133 nm += utostr(mbrPath.length());
134 memcpy(hdr.name,nm.data(),nm.length());
136 sz -= mbrPath.length();
138 sz += mbrPath.length();
139 writeLongName = true;
142 // Set the size field
145 sprintf(&buffer[1],"%-9u",(unsigned)-sz);
147 sprintf(buffer, "%-10u", (unsigned)sz);
149 memcpy(hdr.size,buffer,10);
151 return writeLongName;
154 // Insert a file into the archive before some other member. This also takes care
155 // of extracting the necessary flags and information from the file.
157 Archive::addFileBefore(const sys::Path& filePath, iterator where,
158 std::string* ErrMsg) {
159 if (!filePath.exists()) {
161 *ErrMsg = "Can not add a non-existent file to archive";
165 ArchiveMember* mbr = new ArchiveMember(this);
168 mbr->path = filePath;
169 const sys::FileStatus *FSInfo = mbr->path.getFileStatus(false, ErrMsg);
177 bool hasSlash = filePath.str().find('/') != std::string::npos;
179 flags |= ArchiveMember::HasPathFlag;
180 if (hasSlash || filePath.str().length() > 15)
181 flags |= ArchiveMember::HasLongFilenameFlag;
183 mbr->path.getMagicNumber(magic,4);
184 switch (sys::IdentifyFileType(magic.c_str(),4)) {
185 case sys::Bitcode_FileType:
186 flags |= ArchiveMember::BitcodeFlag;
192 members.insert(where,mbr);
196 // Write one member out to the file.
198 Archive::writeMember(
199 const ArchiveMember& member,
200 std::ofstream& ARFile,
201 bool CreateSymbolTable,
207 unsigned filepos = ARFile.tellp();
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;
216 OwningPtr<MemoryBuffer> File;
217 if (error_code ec = MemoryBuffer::getFile(member.getPath().c_str(), File)) {
219 *ErrMsg = ec.message();
223 data = mFile->getBufferStart();
224 fSize = mFile->getBufferSize();
227 // Now that we have the data in memory, update the
228 // symbol table if it's a bitcode file.
229 if (CreateSymbolTable && member.isBitcode()) {
230 std::vector<std::string> symbols;
231 std::string FullMemberName = archPath.str() + "(" + member.getPath().str()
234 GetBitcodeSymbols(data, fSize, FullMemberName, Context, symbols, ErrMsg);
236 // If the bitcode parsed successfully
238 for (std::vector<std::string>::iterator SI = symbols.begin(),
239 SE = symbols.end(); SI != SE; ++SI) {
241 std::pair<SymTabType::iterator,bool> Res =
242 symTab.insert(std::make_pair(*SI,filepos));
245 symTabSize += SI->length() +
246 numVbrBytes(SI->length()) +
247 numVbrBytes(filepos);
250 // We don't need this module any more.
255 *ErrMsg = "Can't parse bitcode member: " + member.getPath().str()
263 // Compute the fields of the header
264 ArchiveMemberHeader Hdr;
265 bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
267 // Write header to archive file
268 ARFile.write((char*)&Hdr, sizeof(Hdr));
270 // Write the long filename if its long
272 ARFile.write(member.getPath().str().data(),
273 member.getPath().str().length());
276 // Write the (possibly compressed) member's content to the file.
277 ARFile.write(data,fSize);
279 // Make sure the member is an even length
280 if ((ARFile.tellp() & 1) == 1)
281 ARFile << ARFILE_PAD;
283 // Close the mapped file if it was opened
288 // Write out the LLVM symbol table as an archive member to the file.
290 Archive::writeSymbolTable(std::ofstream& ARFile) {
292 // Construct the symbol table's header
293 ArchiveMemberHeader Hdr;
295 memcpy(Hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
296 uint64_t secondsSinceEpoch = sys::TimeValue::now().toEpochTime();
298 sprintf(buffer, "%-8o", 0644);
299 memcpy(Hdr.mode,buffer,8);
300 sprintf(buffer, "%-6u", sys::Process::GetCurrentUserId());
301 memcpy(Hdr.uid,buffer,6);
302 sprintf(buffer, "%-6u", sys::Process::GetCurrentGroupId());
303 memcpy(Hdr.gid,buffer,6);
304 sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
305 memcpy(Hdr.date,buffer,12);
306 sprintf(buffer,"%-10u",symTabSize);
307 memcpy(Hdr.size,buffer,10);
310 ARFile.write((char*)&Hdr, sizeof(Hdr));
313 // Save the starting position of the symbol tables data content.
314 unsigned startpos = ARFile.tellp();
317 // Write out the symbols sequentially
318 for ( Archive::SymTabType::iterator I = symTab.begin(), E = symTab.end();
321 // Write out the file index
322 writeInteger(I->second, ARFile);
323 // Write out the length of the symbol
324 writeInteger(I->first.length(), ARFile);
325 // Write out the symbol
326 ARFile.write(I->first.data(), I->first.length());
330 // Now that we're done with the symbol table, get the ending file position
331 unsigned endpos = ARFile.tellp();
334 // Make sure that the amount we wrote is what we pre-computed. This is
335 // critical for file integrity purposes.
336 assert(endpos - startpos == symTabSize && "Invalid symTabSize computation");
338 // Make sure the symbol table is even sized
339 if (symTabSize % 2 != 0 )
340 ARFile << ARFILE_PAD;
343 // Write the entire archive to the file specified when the archive was created.
344 // This writes to a temporary file first. Options are for creating a symbol
345 // table, flattening the file names (no directories, 15 chars max) and
346 // compressing each archive member.
348 Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames, bool Compress,
351 // Make sure they haven't opened up the file, not loaded it,
352 // but are now trying to write it which would wipe out the file.
353 if (members.empty() && mapfile && mapfile->getBufferSize() > 8) {
355 *ErrMsg = "Can't write an archive not opened for writing";
359 // Create a temporary file to store the archive in
360 sys::Path TmpArchive = archPath;
361 if (TmpArchive.createTemporaryFileOnDisk(ErrMsg))
364 // Make sure the temporary gets removed if we crash
365 sys::RemoveFileOnSignal(TmpArchive);
367 // Create archive file for output.
368 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
370 std::ofstream ArchiveFile(TmpArchive.c_str(), io_mode);
372 // Check for errors opening or creating archive file.
373 if (!ArchiveFile.is_open() || ArchiveFile.bad()) {
374 TmpArchive.eraseFromDisk();
376 *ErrMsg = "Error opening archive file: " + archPath.str();
380 // If we're creating a symbol table, reset it now
381 if (CreateSymbolTable) {
386 // Write magic string to archive.
387 ArchiveFile << ARFILE_MAGIC;
389 // Loop over all member files, and write them out. Note that this also
390 // builds the symbol table, symTab.
391 for (MembersList::iterator I = begin(), E = end(); I != E; ++I) {
392 if (writeMember(*I, ArchiveFile, CreateSymbolTable,
393 TruncateNames, Compress, ErrMsg)) {
394 TmpArchive.eraseFromDisk();
400 // Close archive file.
403 // Write the symbol table
404 if (CreateSymbolTable) {
405 // At this point we have written a file that is a legal archive but it
406 // doesn't have a symbol table in it. To aid in faster reading and to
407 // ensure compatibility with other archivers we need to put the symbol
408 // table first in the file. Unfortunately, this means mapping the file
409 // we just wrote back in and copying it to the destination file.
410 sys::Path FinalFilePath = archPath;
412 // Map in the archive we just wrote.
414 OwningPtr<MemoryBuffer> arch;
415 if (error_code ec = MemoryBuffer::getFile(TmpArchive.c_str(), arch)) {
417 *ErrMsg = ec.message();
420 const char* base = arch->getBufferStart();
422 // Open another temporary file in order to avoid invalidating the
424 if (FinalFilePath.createTemporaryFileOnDisk(ErrMsg))
426 sys::RemoveFileOnSignal(FinalFilePath);
428 std::ofstream FinalFile(FinalFilePath.c_str(), io_mode);
429 if (!FinalFile.is_open() || FinalFile.bad()) {
430 TmpArchive.eraseFromDisk();
432 *ErrMsg = "Error opening archive file: " + FinalFilePath.str();
436 // Write the file magic number
437 FinalFile << ARFILE_MAGIC;
439 // If there is a foreign symbol table, put it into the file now. Most
440 // ar(1) implementations require the symbol table to be first but llvm-ar
441 // can deal with it being after a foreign symbol table. This ensures
442 // compatibility with other ar(1) implementations as well as allowing the
443 // archive to store both native .o and LLVM .bc files, both indexed.
445 if (writeMember(*foreignST, FinalFile, false, false, false, ErrMsg)) {
447 TmpArchive.eraseFromDisk();
452 // Put out the LLVM symbol table now.
453 writeSymbolTable(FinalFile);
455 // Copy the temporary file contents being sure to skip the file's magic
457 FinalFile.write(base + sizeof(ARFILE_MAGIC)-1,
458 arch->getBufferSize()-sizeof(ARFILE_MAGIC)+1);
464 // Move the final file over top of TmpArchive
465 if (FinalFilePath.renamePathOnDisk(TmpArchive, ErrMsg))
469 // Before we replace the actual archive, we need to forget all the
470 // members, since they point to data in that old archive. We need to do
471 // this because we cannot replace an open file on Windows.
474 if (TmpArchive.renamePathOnDisk(archPath, ErrMsg))
477 // Set correct read and write permissions after temporary file is moved
478 // to final destination path.
479 if (archPath.makeReadableOnDisk(ErrMsg))
481 if (archPath.makeWriteableOnDisk(ErrMsg))