mirror of
https://github.com/c64scene-ar/llvm-6502.git
synced 2024-11-02 07:11:49 +00:00
First working version
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@17765 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
parent
5544b5e50b
commit
cf6afc6239
@ -7,18 +7,144 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// Builds up standard unix archive files (.a) containing LLVM bytecode.
|
||||
// This file contains the implementation of the Archive and ArchiveMember
|
||||
// classes that is common to both reading and writing archives..
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#include "ArchiveInternals.h"
|
||||
#include "llvm/ModuleProvider.h"
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
Archive::Archive() {
|
||||
// getMemberSize - compute the actual physical size of the file member as seen
|
||||
// on disk. This isn't the size of member's payload. Use getSize() for that.
|
||||
unsigned
|
||||
ArchiveMember::getMemberSize() const {
|
||||
// Basically its the file size plus the header size
|
||||
unsigned result = info.fileSize + sizeof(ArchiveMemberHeader);
|
||||
|
||||
// If it has a long filename, include the name length
|
||||
if (hasLongFilename())
|
||||
result += path.get().length() + 1;
|
||||
|
||||
// If its now odd lengthed, include the padding byte
|
||||
if (result % 2 != 0 )
|
||||
result++;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// This default constructor is only use by the ilist when it creates its
|
||||
// sentry node. We give it specific static values to make it stand out a bit.
|
||||
ArchiveMember::ArchiveMember()
|
||||
: next(0), prev(0), parent(0), path("<invalid>"), flags(0), data(0)
|
||||
{
|
||||
info.user = 1000;
|
||||
info.group = 1000;
|
||||
info.mode = 0777;
|
||||
info.fileSize = 0;
|
||||
info.modTime = sys::TimeValue::now();
|
||||
}
|
||||
|
||||
// This is the constructor that the Archive class uses when it is building or
|
||||
// reading an archive. It just defaults a few things and ensures the parent is
|
||||
// set for the iplist. The Archive class fills in the ArchiveMember's data.
|
||||
// This is required because correctly setting the data may depend on other
|
||||
// things in the Archive.
|
||||
ArchiveMember::ArchiveMember(Archive* PAR)
|
||||
: next(0), prev(0), parent(PAR), path(), flags(0), data(0)
|
||||
{
|
||||
}
|
||||
|
||||
// This method allows an ArchiveMember to be replaced with the data for a
|
||||
// different file, presumably as an update to the member. It also makes sure
|
||||
// the flags are reset correctly.
|
||||
void ArchiveMember::replaceWith(const sys::Path& newFile) {
|
||||
assert(newFile.exists() && "Can't replace with a non-existent file");
|
||||
data = 0;
|
||||
path = newFile;
|
||||
|
||||
// Foreign symbol tables have an empty name
|
||||
if (path.get() == ARFILE_SYMTAB_NAME)
|
||||
flags |= ForeignSymbolTableFlag;
|
||||
else
|
||||
flags &= ~ForeignSymbolTableFlag;
|
||||
|
||||
// LLVM symbol tables have a very specific name
|
||||
if (path.get() == ARFILE_LLVM_SYMTAB_NAME)
|
||||
flags |= LLVMSymbolTableFlag;
|
||||
else
|
||||
flags &= ~LLVMSymbolTableFlag;
|
||||
|
||||
// String table name
|
||||
if (path.get() == ARFILE_STRTAB_NAME)
|
||||
flags |= StringTableFlag;
|
||||
else
|
||||
flags &= ~StringTableFlag;
|
||||
|
||||
// If it has a slash then it has a path
|
||||
bool hasSlash = path.get().find('/') != std::string::npos;
|
||||
if (hasSlash)
|
||||
flags |= HasPathFlag;
|
||||
else
|
||||
flags &= ~HasPathFlag;
|
||||
|
||||
// If it has a slash or its over 15 chars then its a long filename format
|
||||
if (hasSlash || path.get().length() > 15)
|
||||
flags |= HasLongFilenameFlag;
|
||||
else
|
||||
flags &= ~HasLongFilenameFlag;
|
||||
|
||||
// Get the signature and status info
|
||||
std::string magic;
|
||||
const char* signature = (const char*) data;
|
||||
if (!signature) {
|
||||
path.getMagicNumber(magic,4);
|
||||
signature = magic.c_str();
|
||||
path.getStatusInfo(info);
|
||||
}
|
||||
|
||||
// Determine what kind of file it is
|
||||
switch (sys::IdentifyFileType(signature,4)) {
|
||||
case sys::BytecodeFileType:
|
||||
flags |= BytecodeFlag;
|
||||
break;
|
||||
case sys::CompressedBytecodeFileType:
|
||||
flags |= CompressedBytecodeFlag;
|
||||
flags &= ~CompressedFlag;
|
||||
break;
|
||||
default:
|
||||
flags &= ~(BytecodeFlag|CompressedBytecodeFlag);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Archive constructor - this is the only constructor that gets used for the
|
||||
// Archive class. Everything else (default,copy) is deprecated. This just
|
||||
// initializes and maps the file into memory, if requested.
|
||||
Archive::Archive(const sys::Path& filename, bool map )
|
||||
: archPath(filename), members(), mapfile(0), base(0), symTab(), symTabSize(0)
|
||||
{
|
||||
if (map) {
|
||||
mapfile = new sys::MappedFile(filename);
|
||||
base = (char*) mapfile->map();
|
||||
}
|
||||
}
|
||||
|
||||
// Archive destructor - just clean up memory
|
||||
Archive::~Archive() {
|
||||
// Shutdown the file mapping
|
||||
if (mapfile) {
|
||||
mapfile->unmap();
|
||||
delete mapfile;
|
||||
}
|
||||
// Delete any ModuleProviders and ArchiveMember's we've allocated as a result
|
||||
// of symbol table searches.
|
||||
for (ModuleMap::iterator I=modules.begin(), E=modules.end(); I != E; ++I ) {
|
||||
delete I->second.first;
|
||||
delete I->second.second;
|
||||
}
|
||||
}
|
||||
|
||||
// vim: sw=2 ai
|
||||
|
@ -1,284 +1,426 @@
|
||||
//===-- ArchiveWriter.cpp - LLVM archive writing --------------------------===//
|
||||
//===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
|
||||
//
|
||||
// The LLVM Compiler Infrastructure
|
||||
//
|
||||
// This file was developed by Reid Spencerand is distributed under the
|
||||
// This file was developed by Reid Spencer and is distributed under the
|
||||
// University of Illinois Open Source License. See LICENSE.TXT for details.
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// Builds up standard unix archive files (.a) containing LLVM bytecode.
|
||||
// Builds up an LLVM archive file (.a) containing LLVM bytecode.
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#include "ArchiveInternals.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/Bytecode/Reader.h"
|
||||
#include "llvm/Support/FileUtilities.h"
|
||||
#include "llvm/ADT/StringExtras.h"
|
||||
#include "llvm/System/MappedFile.h"
|
||||
#include "llvm/Support/Compressor.h"
|
||||
#include "llvm/System/Signals.h"
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace {
|
||||
|
||||
// Write an integer using variable bit rate encoding. This saves a few bytes
|
||||
// per entry in the symbol table.
|
||||
inline void writeInteger(unsigned num, std::ofstream& ARFile) {
|
||||
while (1) {
|
||||
if (num < 0x80) { // done?
|
||||
ARFile << (unsigned char)num;
|
||||
return;
|
||||
}
|
||||
|
||||
// Nope, we are bigger than a character, output the next 7 bits and set the
|
||||
// high bit to say that there is more coming...
|
||||
ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
|
||||
num >>= 7; // Shift out 7 bits now...
|
||||
}
|
||||
}
|
||||
|
||||
// Compute how many bytes are taken by a given VBR encoded value. This is needed
|
||||
// to pre-compute the size of the symbol table.
|
||||
inline unsigned numVbrBytes(unsigned num) {
|
||||
if (num < 128) // 2^7
|
||||
return 1;
|
||||
if (num < 16384) // 2^14
|
||||
return 2;
|
||||
if (num < 2097152) // 2^21
|
||||
return 3;
|
||||
if (num < 268435456) // 2^28
|
||||
return 4;
|
||||
return 5; // anything >= 2^28 takes 5 bytes
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Create an empty archive.
|
||||
Archive*
|
||||
Archive::CreateEmpty(const sys::Path& Filename) {
|
||||
Archive* result = new Archive;
|
||||
Archive::ArchiveInternals* impl = result->impl = new Archive::ArchiveInternals;
|
||||
impl->fname = Filename;
|
||||
Archive::CreateEmpty(const sys::Path& FilePath ) {
|
||||
Archive* result = new Archive(FilePath,false);
|
||||
return result;
|
||||
}
|
||||
|
||||
Archive*
|
||||
Archive::CreateFromFiles(
|
||||
const sys::Path& Filename,
|
||||
const PathList& Files,
|
||||
const std::string& StripName
|
||||
) {
|
||||
Archive* result = new Archive;
|
||||
Archive::ArchiveInternals* impl = result->impl = new Archive::ArchiveInternals;
|
||||
impl->fname = Filename;
|
||||
bool
|
||||
Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
|
||||
int sz, bool TruncateNames) const {
|
||||
|
||||
try {
|
||||
size_t strip_len = StripName.length();
|
||||
for (PathList::const_iterator P = Files.begin(), E = Files.end(); P != E ;++P)
|
||||
{
|
||||
if (P->readable()) {
|
||||
std::string name(P->get());
|
||||
if (strip_len > 0 && StripName == name.substr(0,strip_len)) {
|
||||
name.erase(0,strip_len);
|
||||
}
|
||||
if (P->isBytecodeFile()) {
|
||||
std::vector<std::string> syms;
|
||||
if (!GetBytecodeSymbols(*P, syms))
|
||||
throw std::string("Can not get symbols from: ") + P->get();
|
||||
impl->addFileMember(*P, name, &syms);
|
||||
} else {
|
||||
impl->addFileMember(*P, name);
|
||||
}
|
||||
// Set the permissions mode, uid and gid
|
||||
hdr.init();
|
||||
char buffer[32];
|
||||
sprintf(buffer, "%-8o", mbr.getMode());
|
||||
memcpy(hdr.mode,buffer,8);
|
||||
sprintf(buffer, "%-6u", mbr.getUser());
|
||||
memcpy(hdr.uid,buffer,6);
|
||||
sprintf(buffer, "%-6u", mbr.getGroup());
|
||||
memcpy(hdr.gid,buffer,6);
|
||||
|
||||
// Set the size field
|
||||
if (sz < 0 ) {
|
||||
buffer[0] = '-';
|
||||
sprintf(&buffer[1],"%-9u",(unsigned)-sz);
|
||||
} else {
|
||||
sprintf(buffer, "%-10u", (unsigned)sz);
|
||||
}
|
||||
memcpy(hdr.size,buffer,10);
|
||||
|
||||
// Set the last modification date
|
||||
uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
|
||||
sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
|
||||
memcpy(hdr.date,buffer,12);
|
||||
|
||||
// Set the name field in one of its various flavors.
|
||||
bool writeLongName = false;
|
||||
const std::string& mbrPath = mbr.getPath().get();
|
||||
if (mbr.isStringTable()) {
|
||||
memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
|
||||
} else if (mbr.isForeignSymbolTable()) {
|
||||
memcpy(hdr.name,ARFILE_SYMTAB_NAME,16);
|
||||
} else if (mbr.isLLVMSymbolTable()) {
|
||||
memcpy(hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
|
||||
} else if (TruncateNames) {
|
||||
const char* nm = mbrPath.c_str();
|
||||
unsigned len = mbrPath.length();
|
||||
size_t slashpos = mbrPath.rfind('/');
|
||||
if (slashpos != std::string::npos) {
|
||||
nm += slashpos + 1;
|
||||
len -= slashpos +1;
|
||||
}
|
||||
if (len >15)
|
||||
len = 15;
|
||||
mbrPath.copy(hdr.name,len);
|
||||
hdr.name[len] = '/';
|
||||
} else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
|
||||
mbrPath.copy(hdr.name,mbrPath.length());
|
||||
hdr.name[mbrPath.length()] = '/';
|
||||
} else {
|
||||
std::string nm = "#1/";
|
||||
nm += utostr(mbrPath.length());
|
||||
nm.copy(hdr.name,nm.length());
|
||||
writeLongName = true;
|
||||
}
|
||||
return writeLongName;
|
||||
}
|
||||
|
||||
void
|
||||
Archive::addFileBefore(const sys::Path& filePath, iterator where) {
|
||||
assert(filePath.exists() && "Can't add a non-existent file");
|
||||
|
||||
ArchiveMember* mbr = new ArchiveMember(this);
|
||||
|
||||
mbr->data = 0;
|
||||
mbr->path = filePath;
|
||||
mbr->path.getStatusInfo(mbr->info);
|
||||
|
||||
unsigned flags = 0;
|
||||
bool hasSlash = filePath.get().find('/') != std::string::npos;
|
||||
if (hasSlash)
|
||||
flags |= ArchiveMember::HasPathFlag;
|
||||
if (hasSlash || filePath.get().length() > 15)
|
||||
flags |= ArchiveMember::HasLongFilenameFlag;
|
||||
std::string magic;
|
||||
mbr->path.getMagicNumber(magic,4);
|
||||
switch (sys::IdentifyFileType(magic.c_str(),4)) {
|
||||
case sys::BytecodeFileType:
|
||||
flags |= ArchiveMember::BytecodeFlag;
|
||||
break;
|
||||
case sys::CompressedBytecodeFileType:
|
||||
flags |= ArchiveMember::CompressedBytecodeFlag;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
mbr->flags = flags;
|
||||
members.insert(where,mbr);
|
||||
}
|
||||
|
||||
void
|
||||
Archive::moveMemberBefore(iterator target, iterator where) {
|
||||
assert(target != end() && "Target iterator for moveMemberBefore is invalid");
|
||||
ArchiveMember* mbr = members.remove(target);
|
||||
members.insert(where, mbr);
|
||||
}
|
||||
|
||||
void
|
||||
Archive::remove(iterator target) {
|
||||
assert(target != end() && "Target iterator for remove is invalid");
|
||||
ArchiveMember* mbr = members.remove(target);
|
||||
delete mbr;
|
||||
}
|
||||
void
|
||||
Archive::writeMember(
|
||||
const ArchiveMember& member,
|
||||
std::ofstream& ARFile,
|
||||
bool CreateSymbolTable,
|
||||
bool TruncateNames,
|
||||
bool ShouldCompress
|
||||
) {
|
||||
|
||||
unsigned filepos = ARFile.tellp();
|
||||
filepos -= 8;
|
||||
|
||||
// Get the data and its size either from the
|
||||
// member's in-memory data or directly from the file.
|
||||
size_t fSize = member.getSize();
|
||||
const char* data = (const char*)member.getData();
|
||||
sys::MappedFile* mFile = 0;
|
||||
if (!data) {
|
||||
mFile = new sys::MappedFile(member.getPath());
|
||||
data = (const char*) mFile->map();
|
||||
fSize = mFile->size();
|
||||
}
|
||||
|
||||
// Now that we have the data in memory, update the
|
||||
// symbol table if its a bytecode file.
|
||||
if (CreateSymbolTable &&
|
||||
(member.isBytecode() || member.isCompressedBytecode())) {
|
||||
std::vector<std::string> symbols;
|
||||
GetBytecodeSymbols((const unsigned char*)data,fSize,member.getPath().get(),
|
||||
symbols);
|
||||
for (std::vector<std::string>::iterator SI = symbols.begin(),
|
||||
SE = symbols.end(); SI != SE; ++SI) {
|
||||
|
||||
std::pair<SymTabType::iterator,bool> Res =
|
||||
symTab.insert(std::make_pair(*SI,filepos));
|
||||
|
||||
if (Res.second) {
|
||||
symTabSize += SI->length() +
|
||||
numVbrBytes(SI->length()) +
|
||||
numVbrBytes(filepos);
|
||||
}
|
||||
else
|
||||
throw std::string("Can not read: ") + P->get();
|
||||
}
|
||||
|
||||
// Now that we've collected everything, write the archive
|
||||
impl->writeArchive();
|
||||
|
||||
} catch(...) {
|
||||
delete impl;
|
||||
result->impl = 0;
|
||||
delete result;
|
||||
throw;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::addFileMember(
|
||||
const sys::Path& filePath,
|
||||
const std::string& memberName,
|
||||
const StrTab* symbols
|
||||
) {
|
||||
MemberInfo info;
|
||||
info.path = filePath;
|
||||
info.name = memberName;
|
||||
filePath.getStatusInfo(info.status);
|
||||
if (symbols)
|
||||
info.symbols = *symbols;
|
||||
info.offset = 0;
|
||||
members.push_back(info);
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::writeInteger(int num, std::ofstream& ARFile) {
|
||||
char buff[4];
|
||||
buff[0] = (num >> 24) & 255;
|
||||
buff[1] = (num >> 16) & 255;
|
||||
buff[2] = (num >> 8) & 255;
|
||||
buff[3] = num & 255;
|
||||
ARFile.write(buff, sizeof(buff));
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::writeSymbolTable( std::ofstream& ARFile ) {
|
||||
|
||||
// Compute the number of symbols in the symbol table and the
|
||||
// total byte size of the string pool. While we're traversing,
|
||||
// build the string pool for supporting long file names. Also,
|
||||
// build the table of file offsets for the symbol table and
|
||||
// the
|
||||
typedef std::map<std::string,unsigned> SymbolMap;
|
||||
StrTab stringPool;
|
||||
SymbolMap symbolTable;
|
||||
std::vector<unsigned> fileOffsets;
|
||||
std::string symTabStrings;
|
||||
unsigned fileOffset = 0;
|
||||
unsigned spOffset = 0;
|
||||
unsigned numSymbols = 0;
|
||||
unsigned numSymBytes = 0;
|
||||
for (unsigned i = 0; i < members.size(); i++ ) {
|
||||
MemberInfo& mi = members[i];
|
||||
StrTab& syms = mi.symbols;
|
||||
size_t numSym = syms.size();
|
||||
numSymbols += numSym;
|
||||
for (unsigned j = 0; j < numSym; j++ ) {
|
||||
numSymBytes += syms[j].size() + 1;
|
||||
symbolTable[syms[i]] = i;
|
||||
}
|
||||
if (mi.name.length() > 15 || std::string::npos != mi.name.find('/')) {
|
||||
stringPool.push_back(mi.name + "/\n");
|
||||
mi.name = std::string("/") + utostr(spOffset);
|
||||
spOffset += mi.name.length() + 2;
|
||||
} else if (mi.name[mi.name.length()-1] != '/') {
|
||||
mi.name += "/";
|
||||
}
|
||||
fileOffsets.push_back(fileOffset);
|
||||
fileOffset += sizeof(ArchiveMemberHeader) + mi.status.fileSize;
|
||||
}
|
||||
|
||||
|
||||
// Compute the size of the symbol table file member
|
||||
unsigned symTabSize = 0;
|
||||
if (numSymbols != 0)
|
||||
symTabSize =
|
||||
sizeof(ArchiveMemberHeader) + // Size of the file header
|
||||
4 + // Size of "number of entries"
|
||||
(4 * numSymbols) + // Size of member file indices
|
||||
numSymBytes; // Size of the string table
|
||||
|
||||
// Compute the size of the string pool
|
||||
unsigned strPoolSize = 0;
|
||||
if (spOffset != 0 )
|
||||
strPoolSize =
|
||||
sizeof(ArchiveMemberHeader) + // Size of the file header
|
||||
spOffset; // Number of bytes in the string pool
|
||||
|
||||
// Compute the byte index offset created by symbol table and string pool
|
||||
unsigned firstFileOffset = symTabSize + strPoolSize;
|
||||
|
||||
// Create header for symbol table. This must be first if there is
|
||||
// a symbol table and must have a special name.
|
||||
if ( symTabSize > 0 ) {
|
||||
ArchiveMemberHeader Hdr;
|
||||
Hdr.init();
|
||||
|
||||
// Name of symbol table is '/ ' but "" is passed in
|
||||
// because the setName method always terminates with a /
|
||||
Hdr.setName(ARFILE_SYMTAB_NAME);
|
||||
Hdr.setDate();
|
||||
Hdr.setSize(symTabSize - sizeof(ArchiveMemberHeader));
|
||||
Hdr.setMode(0);
|
||||
Hdr.setUid(0);
|
||||
Hdr.setGid(0);
|
||||
|
||||
// Write header to archive file
|
||||
ARFile.write((char*)&Hdr, sizeof(Hdr));
|
||||
|
||||
// Write the number of entries in the symbol table
|
||||
this->writeInteger(numSymbols, ARFile);
|
||||
|
||||
// Write the file offset indices for each symbol and build the
|
||||
// symbol table string pool
|
||||
std::string symTabStrPool;
|
||||
symTabStrPool.reserve(256 * 1024); // Reserve 256KBytes for symbols
|
||||
for (SymbolMap::iterator I = symbolTable.begin(), E = symbolTable.end();
|
||||
I != E; ++I ) {
|
||||
this->writeInteger(firstFileOffset + fileOffsets[I->second], ARFile);
|
||||
symTabStrPool += I->first;
|
||||
symTabStrPool += "\0";
|
||||
}
|
||||
|
||||
// Write the symbol table's string pool
|
||||
ARFile.write(symTabStrPool.data(), symTabStrPool.size());
|
||||
}
|
||||
|
||||
//============== DONE WITH SYMBOL TABLE
|
||||
|
||||
if (strPoolSize > 0) {
|
||||
// Initialize the header for the string pool
|
||||
ArchiveMemberHeader Hdr;
|
||||
Hdr.init();
|
||||
Hdr.setName(ARFILE_STRTAB_NAME);
|
||||
Hdr.setDate();
|
||||
Hdr.setSize(spOffset);
|
||||
Hdr.setMode(0);
|
||||
Hdr.setUid(0);
|
||||
Hdr.setGid(0);
|
||||
|
||||
// Write the string pool header
|
||||
ARFile.write((char*)&Hdr, sizeof(Hdr));
|
||||
|
||||
// Write the string pool
|
||||
for (unsigned i = 0; i < stringPool.size(); i++) {
|
||||
ARFile.write(stringPool[i].data(), stringPool[i].size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::writeMember(
|
||||
const MemberInfo& member,
|
||||
std::ofstream& ARFile
|
||||
) {
|
||||
// Determine if we actually should compress this member
|
||||
bool willCompress =
|
||||
(ShouldCompress &&
|
||||
!member.isForeignSymbolTable() &&
|
||||
!member.isLLVMSymbolTable() &&
|
||||
!member.isCompressed() &&
|
||||
!member.isCompressedBytecode());
|
||||
|
||||
// Map the file into memory. We do this early for two reasons. First,
|
||||
// if there's any kind of error, we want to know about it. Second, we
|
||||
// want to ensure we're using the most recent size for this file.
|
||||
sys::MappedFile mFile(member.path);
|
||||
mFile.map();
|
||||
// Perform the compression. Note that if the file is uncompressed bytecode
|
||||
// then we turn the file into compressed bytecode rather than treating it as
|
||||
// compressed data. This is necessary since it allows us to determine that the
|
||||
// file contains bytecode instead of looking like a regular compressed data
|
||||
// member. A compressed bytecode file has its content compressed but has a
|
||||
// magic number of "llvc". This acounts for the +/-4 arithmetic in the code
|
||||
// below.
|
||||
int hdrSize;
|
||||
if (willCompress) {
|
||||
char* output = 0;
|
||||
if (member.isBytecode()) {
|
||||
data +=4;
|
||||
fSize -= 4;
|
||||
}
|
||||
fSize = Compressor::compressToNewBuffer(
|
||||
data,fSize,output,Compressor::COMP_TYPE_ZLIB);
|
||||
data = output;
|
||||
if (member.isBytecode())
|
||||
hdrSize = -fSize-4;
|
||||
else
|
||||
hdrSize = -fSize;
|
||||
} else {
|
||||
hdrSize = fSize;
|
||||
}
|
||||
|
||||
// Header for the archive member
|
||||
// Compute the fields of the header
|
||||
ArchiveMemberHeader Hdr;
|
||||
Hdr.init();
|
||||
|
||||
// Set the name. If its longer than 15 chars, it will have already
|
||||
// been reduced by the writeSymbolTable.
|
||||
Hdr.setName(member.name);
|
||||
|
||||
// Set the other header members
|
||||
Hdr.setSize( mFile.size() );
|
||||
Hdr.setMode( member.status.mode);
|
||||
Hdr.setUid ( member.status.user);
|
||||
Hdr.setGid ( member.status.group);
|
||||
Hdr.setDate( member.status.modTime.ToPosixTime() );
|
||||
bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
|
||||
|
||||
// Write header to archive file
|
||||
ARFile.write((char*)&Hdr, sizeof(Hdr));
|
||||
|
||||
//write to archive file
|
||||
ARFile.write(mFile.charBase(),mFile.size());
|
||||
|
||||
mFile.unmap();
|
||||
// Write the long filename if its long
|
||||
if (writeLongName) {
|
||||
ARFile << member.getPath().c_str();
|
||||
ARFile << '\n';
|
||||
}
|
||||
|
||||
// Make sure we write the compressed bytecode magic number if we should.
|
||||
if (willCompress && member.isBytecode())
|
||||
ARFile.write("llvc",4);
|
||||
|
||||
// Write the (possibly compressed) member's content to the file.
|
||||
ARFile.write(data,fSize);
|
||||
|
||||
// Make sure the member is an even length
|
||||
if (ARFile.tellp() % 2 != 0)
|
||||
ARFile << ARFILE_PAD;
|
||||
|
||||
// Free the compressed data, if necessary
|
||||
if (willCompress) {
|
||||
free((void*)data);
|
||||
}
|
||||
|
||||
// Close the mapped file if it was opened
|
||||
if (mFile != 0) {
|
||||
mFile->unmap();
|
||||
delete mFile;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::writeArchive() {
|
||||
|
||||
// Create archive file for output.
|
||||
std::ofstream ArchiveFile(fname.get().c_str());
|
||||
|
||||
// Check for errors opening or creating archive file.
|
||||
if ( !ArchiveFile.is_open() || ArchiveFile.bad() ) {
|
||||
throw std::string("Error opening archive file: ") + fname.get();
|
||||
Archive::writeSymbolTable(std::ofstream& ARFile,bool PrintSymTab ) {
|
||||
|
||||
// Construct the symbol table's header
|
||||
ArchiveMemberHeader Hdr;
|
||||
Hdr.init();
|
||||
memcpy(Hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
|
||||
uint64_t secondsSinceEpoch = sys::TimeValue::now().toEpochTime();
|
||||
char buffer[32];
|
||||
sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
|
||||
memcpy(Hdr.date,buffer,12);
|
||||
sprintf(buffer,"%-10u",symTabSize);
|
||||
memcpy(Hdr.size,buffer,10);
|
||||
|
||||
// Write the header
|
||||
ARFile.write((char*)&Hdr, sizeof(Hdr));
|
||||
|
||||
// Save the starting position of the symbol tables data content.
|
||||
unsigned startpos = ARFile.tellp();
|
||||
|
||||
// Print the symbol table header if we're supposed to
|
||||
if (PrintSymTab)
|
||||
std::cout << "Symbol Table:\n";
|
||||
|
||||
// Write out the symbols sequentially
|
||||
for ( Archive::SymTabType::iterator I = symTab.begin(), E = symTab.end();
|
||||
I != E; ++I)
|
||||
{
|
||||
// Write out the file index
|
||||
writeInteger(I->second, ARFile);
|
||||
// Write out the length of the symbol
|
||||
writeInteger(I->first.length(), ARFile);
|
||||
// Write out the symbol
|
||||
ARFile.write(I->first.data(), I->first.length());
|
||||
|
||||
// Print this entry to std::cout if we should
|
||||
if (PrintSymTab) {
|
||||
unsigned filepos = I->second + symTabSize + sizeof(ArchiveMemberHeader) +
|
||||
(symTabSize % 2 != 0) + 8;
|
||||
std::cout << " " << std::setw(9) << filepos << "\t" << I->first << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Write magic string to archive.
|
||||
ArchiveFile << ARFILE_MAGIC;
|
||||
// Now that we're done with the symbol table, get the ending file position
|
||||
unsigned endpos = ARFile.tellp();
|
||||
|
||||
// Write the symbol table and string pool
|
||||
writeSymbolTable(ArchiveFile);
|
||||
// Make sure that the amount we wrote is what we pre-computed. This is
|
||||
// critical for file integrity purposes.
|
||||
assert(endpos - startpos == symTabSize && "Invalid symTabSize computation");
|
||||
|
||||
//Loop over all member files, and add to the archive.
|
||||
for ( unsigned i = 0; i < members.size(); ++i) {
|
||||
if(ArchiveFile.tellp() % 2 != 0)
|
||||
ArchiveFile << ARFILE_PAD;
|
||||
writeMember(members[i],ArchiveFile);
|
||||
}
|
||||
|
||||
//Close archive file.
|
||||
ArchiveFile.close();
|
||||
// Make sure the symbol table is even sized
|
||||
if (symTabSize % 2 != 0 )
|
||||
ARFile << ARFILE_PAD;
|
||||
}
|
||||
|
||||
// vim: sw=2 ai
|
||||
void
|
||||
Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames,
|
||||
bool Compress, bool PrintSymTab) {
|
||||
|
||||
// Make sure they haven't opened up the file, not loaded it,
|
||||
// but are now trying to write it which would wipe out the file.
|
||||
assert(!(members.empty() && mapfile->size() > 8));
|
||||
|
||||
// Create a temporary file to store the archive in
|
||||
sys::Path TmpArchive = archPath;
|
||||
TmpArchive.createTemporaryFile();
|
||||
|
||||
// Make sure the temporary gets removed if we crash
|
||||
sys::RemoveFileOnSignal(TmpArchive);
|
||||
|
||||
// Ensure we can remove the temporary even in the face of an exception
|
||||
try {
|
||||
// Create archive file for output.
|
||||
std::ofstream ArchiveFile(TmpArchive.c_str());
|
||||
|
||||
// Check for errors opening or creating archive file.
|
||||
if ( !ArchiveFile.is_open() || ArchiveFile.bad() ) {
|
||||
throw std::string("Error opening archive file: ") + archPath.get();
|
||||
}
|
||||
|
||||
// If we're creating a symbol table, reset it now
|
||||
if (CreateSymbolTable) {
|
||||
symTabSize = 0;
|
||||
symTab.clear();
|
||||
}
|
||||
|
||||
// Write magic string to archive.
|
||||
ArchiveFile << ARFILE_MAGIC;
|
||||
|
||||
// Loop over all member files, and write them out. Note that this also
|
||||
// builds the symbol table, symTab.
|
||||
for ( MembersList::iterator I = begin(), E = end(); I != E; ++I) {
|
||||
writeMember(*I,ArchiveFile,CreateSymbolTable,TruncateNames,Compress);
|
||||
}
|
||||
|
||||
// Close archive file.
|
||||
ArchiveFile.close();
|
||||
|
||||
// Write the symbol table
|
||||
if (CreateSymbolTable) {
|
||||
// At this point we have written a file that is a legal archive but it
|
||||
// doesn't have a symbol table in it. To aid in faster reading and to
|
||||
// ensure compatibility with other archivers we need to put the symbol
|
||||
// table first in the file. Unfortunately, this means mapping the file
|
||||
// we just wrote back in and copying it to the destination file.
|
||||
sys::MappedFile arch(TmpArchive);
|
||||
const char* base = (const char*) arch.map();
|
||||
|
||||
// Open the final file to write and check it.
|
||||
std::ofstream FinalFile(archPath.c_str());
|
||||
if ( !FinalFile.is_open() || FinalFile.bad() ) {
|
||||
throw std::string("Error opening archive file: ") + archPath.get();
|
||||
}
|
||||
|
||||
// Write the file magic number
|
||||
FinalFile << ARFILE_MAGIC;
|
||||
|
||||
// Put out the symbol table
|
||||
writeSymbolTable(FinalFile,PrintSymTab);
|
||||
|
||||
// Copy the temporary file contents being sure to skip the file's magic
|
||||
// number.
|
||||
FinalFile.write(base + sizeof(ARFILE_MAGIC)-1,
|
||||
arch.size()-sizeof(ARFILE_MAGIC)+1);
|
||||
|
||||
// Close up shop
|
||||
FinalFile.close();
|
||||
arch.unmap();
|
||||
TmpArchive.destroyFile();
|
||||
|
||||
} else {
|
||||
// We don't have to insert the symbol table, so just renaming the temp
|
||||
// file to the correct name will suffice.
|
||||
TmpArchive.renameFile(archPath);
|
||||
}
|
||||
} catch (...) {
|
||||
// Make sure we clean up.
|
||||
if (TmpArchive.exists())
|
||||
TmpArchive.destroyFile();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
@ -7,18 +7,144 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// Builds up standard unix archive files (.a) containing LLVM bytecode.
|
||||
// This file contains the implementation of the Archive and ArchiveMember
|
||||
// classes that is common to both reading and writing archives..
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#include "ArchiveInternals.h"
|
||||
#include "llvm/ModuleProvider.h"
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
Archive::Archive() {
|
||||
// getMemberSize - compute the actual physical size of the file member as seen
|
||||
// on disk. This isn't the size of member's payload. Use getSize() for that.
|
||||
unsigned
|
||||
ArchiveMember::getMemberSize() const {
|
||||
// Basically its the file size plus the header size
|
||||
unsigned result = info.fileSize + sizeof(ArchiveMemberHeader);
|
||||
|
||||
// If it has a long filename, include the name length
|
||||
if (hasLongFilename())
|
||||
result += path.get().length() + 1;
|
||||
|
||||
// If its now odd lengthed, include the padding byte
|
||||
if (result % 2 != 0 )
|
||||
result++;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// This default constructor is only use by the ilist when it creates its
|
||||
// sentry node. We give it specific static values to make it stand out a bit.
|
||||
ArchiveMember::ArchiveMember()
|
||||
: next(0), prev(0), parent(0), path("<invalid>"), flags(0), data(0)
|
||||
{
|
||||
info.user = 1000;
|
||||
info.group = 1000;
|
||||
info.mode = 0777;
|
||||
info.fileSize = 0;
|
||||
info.modTime = sys::TimeValue::now();
|
||||
}
|
||||
|
||||
// This is the constructor that the Archive class uses when it is building or
|
||||
// reading an archive. It just defaults a few things and ensures the parent is
|
||||
// set for the iplist. The Archive class fills in the ArchiveMember's data.
|
||||
// This is required because correctly setting the data may depend on other
|
||||
// things in the Archive.
|
||||
ArchiveMember::ArchiveMember(Archive* PAR)
|
||||
: next(0), prev(0), parent(PAR), path(), flags(0), data(0)
|
||||
{
|
||||
}
|
||||
|
||||
// This method allows an ArchiveMember to be replaced with the data for a
|
||||
// different file, presumably as an update to the member. It also makes sure
|
||||
// the flags are reset correctly.
|
||||
void ArchiveMember::replaceWith(const sys::Path& newFile) {
|
||||
assert(newFile.exists() && "Can't replace with a non-existent file");
|
||||
data = 0;
|
||||
path = newFile;
|
||||
|
||||
// Foreign symbol tables have an empty name
|
||||
if (path.get() == ARFILE_SYMTAB_NAME)
|
||||
flags |= ForeignSymbolTableFlag;
|
||||
else
|
||||
flags &= ~ForeignSymbolTableFlag;
|
||||
|
||||
// LLVM symbol tables have a very specific name
|
||||
if (path.get() == ARFILE_LLVM_SYMTAB_NAME)
|
||||
flags |= LLVMSymbolTableFlag;
|
||||
else
|
||||
flags &= ~LLVMSymbolTableFlag;
|
||||
|
||||
// String table name
|
||||
if (path.get() == ARFILE_STRTAB_NAME)
|
||||
flags |= StringTableFlag;
|
||||
else
|
||||
flags &= ~StringTableFlag;
|
||||
|
||||
// If it has a slash then it has a path
|
||||
bool hasSlash = path.get().find('/') != std::string::npos;
|
||||
if (hasSlash)
|
||||
flags |= HasPathFlag;
|
||||
else
|
||||
flags &= ~HasPathFlag;
|
||||
|
||||
// If it has a slash or its over 15 chars then its a long filename format
|
||||
if (hasSlash || path.get().length() > 15)
|
||||
flags |= HasLongFilenameFlag;
|
||||
else
|
||||
flags &= ~HasLongFilenameFlag;
|
||||
|
||||
// Get the signature and status info
|
||||
std::string magic;
|
||||
const char* signature = (const char*) data;
|
||||
if (!signature) {
|
||||
path.getMagicNumber(magic,4);
|
||||
signature = magic.c_str();
|
||||
path.getStatusInfo(info);
|
||||
}
|
||||
|
||||
// Determine what kind of file it is
|
||||
switch (sys::IdentifyFileType(signature,4)) {
|
||||
case sys::BytecodeFileType:
|
||||
flags |= BytecodeFlag;
|
||||
break;
|
||||
case sys::CompressedBytecodeFileType:
|
||||
flags |= CompressedBytecodeFlag;
|
||||
flags &= ~CompressedFlag;
|
||||
break;
|
||||
default:
|
||||
flags &= ~(BytecodeFlag|CompressedBytecodeFlag);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Archive constructor - this is the only constructor that gets used for the
|
||||
// Archive class. Everything else (default,copy) is deprecated. This just
|
||||
// initializes and maps the file into memory, if requested.
|
||||
Archive::Archive(const sys::Path& filename, bool map )
|
||||
: archPath(filename), members(), mapfile(0), base(0), symTab(), symTabSize(0)
|
||||
{
|
||||
if (map) {
|
||||
mapfile = new sys::MappedFile(filename);
|
||||
base = (char*) mapfile->map();
|
||||
}
|
||||
}
|
||||
|
||||
// Archive destructor - just clean up memory
|
||||
Archive::~Archive() {
|
||||
// Shutdown the file mapping
|
||||
if (mapfile) {
|
||||
mapfile->unmap();
|
||||
delete mapfile;
|
||||
}
|
||||
// Delete any ModuleProviders and ArchiveMember's we've allocated as a result
|
||||
// of symbol table searches.
|
||||
for (ModuleMap::iterator I=modules.begin(), E=modules.end(); I != E; ++I ) {
|
||||
delete I->second.first;
|
||||
delete I->second.second;
|
||||
}
|
||||
}
|
||||
|
||||
// vim: sw=2 ai
|
||||
|
@ -1,284 +1,426 @@
|
||||
//===-- ArchiveWriter.cpp - LLVM archive writing --------------------------===//
|
||||
//===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
|
||||
//
|
||||
// The LLVM Compiler Infrastructure
|
||||
//
|
||||
// This file was developed by Reid Spencerand is distributed under the
|
||||
// This file was developed by Reid Spencer and is distributed under the
|
||||
// University of Illinois Open Source License. See LICENSE.TXT for details.
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// Builds up standard unix archive files (.a) containing LLVM bytecode.
|
||||
// Builds up an LLVM archive file (.a) containing LLVM bytecode.
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#include "ArchiveInternals.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/Bytecode/Reader.h"
|
||||
#include "llvm/Support/FileUtilities.h"
|
||||
#include "llvm/ADT/StringExtras.h"
|
||||
#include "llvm/System/MappedFile.h"
|
||||
#include "llvm/Support/Compressor.h"
|
||||
#include "llvm/System/Signals.h"
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
namespace {
|
||||
|
||||
// Write an integer using variable bit rate encoding. This saves a few bytes
|
||||
// per entry in the symbol table.
|
||||
inline void writeInteger(unsigned num, std::ofstream& ARFile) {
|
||||
while (1) {
|
||||
if (num < 0x80) { // done?
|
||||
ARFile << (unsigned char)num;
|
||||
return;
|
||||
}
|
||||
|
||||
// Nope, we are bigger than a character, output the next 7 bits and set the
|
||||
// high bit to say that there is more coming...
|
||||
ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
|
||||
num >>= 7; // Shift out 7 bits now...
|
||||
}
|
||||
}
|
||||
|
||||
// Compute how many bytes are taken by a given VBR encoded value. This is needed
|
||||
// to pre-compute the size of the symbol table.
|
||||
inline unsigned numVbrBytes(unsigned num) {
|
||||
if (num < 128) // 2^7
|
||||
return 1;
|
||||
if (num < 16384) // 2^14
|
||||
return 2;
|
||||
if (num < 2097152) // 2^21
|
||||
return 3;
|
||||
if (num < 268435456) // 2^28
|
||||
return 4;
|
||||
return 5; // anything >= 2^28 takes 5 bytes
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Create an empty archive.
|
||||
Archive*
|
||||
Archive::CreateEmpty(const sys::Path& Filename) {
|
||||
Archive* result = new Archive;
|
||||
Archive::ArchiveInternals* impl = result->impl = new Archive::ArchiveInternals;
|
||||
impl->fname = Filename;
|
||||
Archive::CreateEmpty(const sys::Path& FilePath ) {
|
||||
Archive* result = new Archive(FilePath,false);
|
||||
return result;
|
||||
}
|
||||
|
||||
Archive*
|
||||
Archive::CreateFromFiles(
|
||||
const sys::Path& Filename,
|
||||
const PathList& Files,
|
||||
const std::string& StripName
|
||||
) {
|
||||
Archive* result = new Archive;
|
||||
Archive::ArchiveInternals* impl = result->impl = new Archive::ArchiveInternals;
|
||||
impl->fname = Filename;
|
||||
bool
|
||||
Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
|
||||
int sz, bool TruncateNames) const {
|
||||
|
||||
try {
|
||||
size_t strip_len = StripName.length();
|
||||
for (PathList::const_iterator P = Files.begin(), E = Files.end(); P != E ;++P)
|
||||
{
|
||||
if (P->readable()) {
|
||||
std::string name(P->get());
|
||||
if (strip_len > 0 && StripName == name.substr(0,strip_len)) {
|
||||
name.erase(0,strip_len);
|
||||
}
|
||||
if (P->isBytecodeFile()) {
|
||||
std::vector<std::string> syms;
|
||||
if (!GetBytecodeSymbols(*P, syms))
|
||||
throw std::string("Can not get symbols from: ") + P->get();
|
||||
impl->addFileMember(*P, name, &syms);
|
||||
} else {
|
||||
impl->addFileMember(*P, name);
|
||||
}
|
||||
// Set the permissions mode, uid and gid
|
||||
hdr.init();
|
||||
char buffer[32];
|
||||
sprintf(buffer, "%-8o", mbr.getMode());
|
||||
memcpy(hdr.mode,buffer,8);
|
||||
sprintf(buffer, "%-6u", mbr.getUser());
|
||||
memcpy(hdr.uid,buffer,6);
|
||||
sprintf(buffer, "%-6u", mbr.getGroup());
|
||||
memcpy(hdr.gid,buffer,6);
|
||||
|
||||
// Set the size field
|
||||
if (sz < 0 ) {
|
||||
buffer[0] = '-';
|
||||
sprintf(&buffer[1],"%-9u",(unsigned)-sz);
|
||||
} else {
|
||||
sprintf(buffer, "%-10u", (unsigned)sz);
|
||||
}
|
||||
memcpy(hdr.size,buffer,10);
|
||||
|
||||
// Set the last modification date
|
||||
uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
|
||||
sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
|
||||
memcpy(hdr.date,buffer,12);
|
||||
|
||||
// Set the name field in one of its various flavors.
|
||||
bool writeLongName = false;
|
||||
const std::string& mbrPath = mbr.getPath().get();
|
||||
if (mbr.isStringTable()) {
|
||||
memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
|
||||
} else if (mbr.isForeignSymbolTable()) {
|
||||
memcpy(hdr.name,ARFILE_SYMTAB_NAME,16);
|
||||
} else if (mbr.isLLVMSymbolTable()) {
|
||||
memcpy(hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
|
||||
} else if (TruncateNames) {
|
||||
const char* nm = mbrPath.c_str();
|
||||
unsigned len = mbrPath.length();
|
||||
size_t slashpos = mbrPath.rfind('/');
|
||||
if (slashpos != std::string::npos) {
|
||||
nm += slashpos + 1;
|
||||
len -= slashpos +1;
|
||||
}
|
||||
if (len >15)
|
||||
len = 15;
|
||||
mbrPath.copy(hdr.name,len);
|
||||
hdr.name[len] = '/';
|
||||
} else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
|
||||
mbrPath.copy(hdr.name,mbrPath.length());
|
||||
hdr.name[mbrPath.length()] = '/';
|
||||
} else {
|
||||
std::string nm = "#1/";
|
||||
nm += utostr(mbrPath.length());
|
||||
nm.copy(hdr.name,nm.length());
|
||||
writeLongName = true;
|
||||
}
|
||||
return writeLongName;
|
||||
}
|
||||
|
||||
void
|
||||
Archive::addFileBefore(const sys::Path& filePath, iterator where) {
|
||||
assert(filePath.exists() && "Can't add a non-existent file");
|
||||
|
||||
ArchiveMember* mbr = new ArchiveMember(this);
|
||||
|
||||
mbr->data = 0;
|
||||
mbr->path = filePath;
|
||||
mbr->path.getStatusInfo(mbr->info);
|
||||
|
||||
unsigned flags = 0;
|
||||
bool hasSlash = filePath.get().find('/') != std::string::npos;
|
||||
if (hasSlash)
|
||||
flags |= ArchiveMember::HasPathFlag;
|
||||
if (hasSlash || filePath.get().length() > 15)
|
||||
flags |= ArchiveMember::HasLongFilenameFlag;
|
||||
std::string magic;
|
||||
mbr->path.getMagicNumber(magic,4);
|
||||
switch (sys::IdentifyFileType(magic.c_str(),4)) {
|
||||
case sys::BytecodeFileType:
|
||||
flags |= ArchiveMember::BytecodeFlag;
|
||||
break;
|
||||
case sys::CompressedBytecodeFileType:
|
||||
flags |= ArchiveMember::CompressedBytecodeFlag;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
mbr->flags = flags;
|
||||
members.insert(where,mbr);
|
||||
}
|
||||
|
||||
void
|
||||
Archive::moveMemberBefore(iterator target, iterator where) {
|
||||
assert(target != end() && "Target iterator for moveMemberBefore is invalid");
|
||||
ArchiveMember* mbr = members.remove(target);
|
||||
members.insert(where, mbr);
|
||||
}
|
||||
|
||||
void
|
||||
Archive::remove(iterator target) {
|
||||
assert(target != end() && "Target iterator for remove is invalid");
|
||||
ArchiveMember* mbr = members.remove(target);
|
||||
delete mbr;
|
||||
}
|
||||
void
|
||||
Archive::writeMember(
|
||||
const ArchiveMember& member,
|
||||
std::ofstream& ARFile,
|
||||
bool CreateSymbolTable,
|
||||
bool TruncateNames,
|
||||
bool ShouldCompress
|
||||
) {
|
||||
|
||||
unsigned filepos = ARFile.tellp();
|
||||
filepos -= 8;
|
||||
|
||||
// Get the data and its size either from the
|
||||
// member's in-memory data or directly from the file.
|
||||
size_t fSize = member.getSize();
|
||||
const char* data = (const char*)member.getData();
|
||||
sys::MappedFile* mFile = 0;
|
||||
if (!data) {
|
||||
mFile = new sys::MappedFile(member.getPath());
|
||||
data = (const char*) mFile->map();
|
||||
fSize = mFile->size();
|
||||
}
|
||||
|
||||
// Now that we have the data in memory, update the
|
||||
// symbol table if its a bytecode file.
|
||||
if (CreateSymbolTable &&
|
||||
(member.isBytecode() || member.isCompressedBytecode())) {
|
||||
std::vector<std::string> symbols;
|
||||
GetBytecodeSymbols((const unsigned char*)data,fSize,member.getPath().get(),
|
||||
symbols);
|
||||
for (std::vector<std::string>::iterator SI = symbols.begin(),
|
||||
SE = symbols.end(); SI != SE; ++SI) {
|
||||
|
||||
std::pair<SymTabType::iterator,bool> Res =
|
||||
symTab.insert(std::make_pair(*SI,filepos));
|
||||
|
||||
if (Res.second) {
|
||||
symTabSize += SI->length() +
|
||||
numVbrBytes(SI->length()) +
|
||||
numVbrBytes(filepos);
|
||||
}
|
||||
else
|
||||
throw std::string("Can not read: ") + P->get();
|
||||
}
|
||||
|
||||
// Now that we've collected everything, write the archive
|
||||
impl->writeArchive();
|
||||
|
||||
} catch(...) {
|
||||
delete impl;
|
||||
result->impl = 0;
|
||||
delete result;
|
||||
throw;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::addFileMember(
|
||||
const sys::Path& filePath,
|
||||
const std::string& memberName,
|
||||
const StrTab* symbols
|
||||
) {
|
||||
MemberInfo info;
|
||||
info.path = filePath;
|
||||
info.name = memberName;
|
||||
filePath.getStatusInfo(info.status);
|
||||
if (symbols)
|
||||
info.symbols = *symbols;
|
||||
info.offset = 0;
|
||||
members.push_back(info);
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::writeInteger(int num, std::ofstream& ARFile) {
|
||||
char buff[4];
|
||||
buff[0] = (num >> 24) & 255;
|
||||
buff[1] = (num >> 16) & 255;
|
||||
buff[2] = (num >> 8) & 255;
|
||||
buff[3] = num & 255;
|
||||
ARFile.write(buff, sizeof(buff));
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::writeSymbolTable( std::ofstream& ARFile ) {
|
||||
|
||||
// Compute the number of symbols in the symbol table and the
|
||||
// total byte size of the string pool. While we're traversing,
|
||||
// build the string pool for supporting long file names. Also,
|
||||
// build the table of file offsets for the symbol table and
|
||||
// the
|
||||
typedef std::map<std::string,unsigned> SymbolMap;
|
||||
StrTab stringPool;
|
||||
SymbolMap symbolTable;
|
||||
std::vector<unsigned> fileOffsets;
|
||||
std::string symTabStrings;
|
||||
unsigned fileOffset = 0;
|
||||
unsigned spOffset = 0;
|
||||
unsigned numSymbols = 0;
|
||||
unsigned numSymBytes = 0;
|
||||
for (unsigned i = 0; i < members.size(); i++ ) {
|
||||
MemberInfo& mi = members[i];
|
||||
StrTab& syms = mi.symbols;
|
||||
size_t numSym = syms.size();
|
||||
numSymbols += numSym;
|
||||
for (unsigned j = 0; j < numSym; j++ ) {
|
||||
numSymBytes += syms[j].size() + 1;
|
||||
symbolTable[syms[i]] = i;
|
||||
}
|
||||
if (mi.name.length() > 15 || std::string::npos != mi.name.find('/')) {
|
||||
stringPool.push_back(mi.name + "/\n");
|
||||
mi.name = std::string("/") + utostr(spOffset);
|
||||
spOffset += mi.name.length() + 2;
|
||||
} else if (mi.name[mi.name.length()-1] != '/') {
|
||||
mi.name += "/";
|
||||
}
|
||||
fileOffsets.push_back(fileOffset);
|
||||
fileOffset += sizeof(ArchiveMemberHeader) + mi.status.fileSize;
|
||||
}
|
||||
|
||||
|
||||
// Compute the size of the symbol table file member
|
||||
unsigned symTabSize = 0;
|
||||
if (numSymbols != 0)
|
||||
symTabSize =
|
||||
sizeof(ArchiveMemberHeader) + // Size of the file header
|
||||
4 + // Size of "number of entries"
|
||||
(4 * numSymbols) + // Size of member file indices
|
||||
numSymBytes; // Size of the string table
|
||||
|
||||
// Compute the size of the string pool
|
||||
unsigned strPoolSize = 0;
|
||||
if (spOffset != 0 )
|
||||
strPoolSize =
|
||||
sizeof(ArchiveMemberHeader) + // Size of the file header
|
||||
spOffset; // Number of bytes in the string pool
|
||||
|
||||
// Compute the byte index offset created by symbol table and string pool
|
||||
unsigned firstFileOffset = symTabSize + strPoolSize;
|
||||
|
||||
// Create header for symbol table. This must be first if there is
|
||||
// a symbol table and must have a special name.
|
||||
if ( symTabSize > 0 ) {
|
||||
ArchiveMemberHeader Hdr;
|
||||
Hdr.init();
|
||||
|
||||
// Name of symbol table is '/ ' but "" is passed in
|
||||
// because the setName method always terminates with a /
|
||||
Hdr.setName(ARFILE_SYMTAB_NAME);
|
||||
Hdr.setDate();
|
||||
Hdr.setSize(symTabSize - sizeof(ArchiveMemberHeader));
|
||||
Hdr.setMode(0);
|
||||
Hdr.setUid(0);
|
||||
Hdr.setGid(0);
|
||||
|
||||
// Write header to archive file
|
||||
ARFile.write((char*)&Hdr, sizeof(Hdr));
|
||||
|
||||
// Write the number of entries in the symbol table
|
||||
this->writeInteger(numSymbols, ARFile);
|
||||
|
||||
// Write the file offset indices for each symbol and build the
|
||||
// symbol table string pool
|
||||
std::string symTabStrPool;
|
||||
symTabStrPool.reserve(256 * 1024); // Reserve 256KBytes for symbols
|
||||
for (SymbolMap::iterator I = symbolTable.begin(), E = symbolTable.end();
|
||||
I != E; ++I ) {
|
||||
this->writeInteger(firstFileOffset + fileOffsets[I->second], ARFile);
|
||||
symTabStrPool += I->first;
|
||||
symTabStrPool += "\0";
|
||||
}
|
||||
|
||||
// Write the symbol table's string pool
|
||||
ARFile.write(symTabStrPool.data(), symTabStrPool.size());
|
||||
}
|
||||
|
||||
//============== DONE WITH SYMBOL TABLE
|
||||
|
||||
if (strPoolSize > 0) {
|
||||
// Initialize the header for the string pool
|
||||
ArchiveMemberHeader Hdr;
|
||||
Hdr.init();
|
||||
Hdr.setName(ARFILE_STRTAB_NAME);
|
||||
Hdr.setDate();
|
||||
Hdr.setSize(spOffset);
|
||||
Hdr.setMode(0);
|
||||
Hdr.setUid(0);
|
||||
Hdr.setGid(0);
|
||||
|
||||
// Write the string pool header
|
||||
ARFile.write((char*)&Hdr, sizeof(Hdr));
|
||||
|
||||
// Write the string pool
|
||||
for (unsigned i = 0; i < stringPool.size(); i++) {
|
||||
ARFile.write(stringPool[i].data(), stringPool[i].size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::writeMember(
|
||||
const MemberInfo& member,
|
||||
std::ofstream& ARFile
|
||||
) {
|
||||
// Determine if we actually should compress this member
|
||||
bool willCompress =
|
||||
(ShouldCompress &&
|
||||
!member.isForeignSymbolTable() &&
|
||||
!member.isLLVMSymbolTable() &&
|
||||
!member.isCompressed() &&
|
||||
!member.isCompressedBytecode());
|
||||
|
||||
// Map the file into memory. We do this early for two reasons. First,
|
||||
// if there's any kind of error, we want to know about it. Second, we
|
||||
// want to ensure we're using the most recent size for this file.
|
||||
sys::MappedFile mFile(member.path);
|
||||
mFile.map();
|
||||
// Perform the compression. Note that if the file is uncompressed bytecode
|
||||
// then we turn the file into compressed bytecode rather than treating it as
|
||||
// compressed data. This is necessary since it allows us to determine that the
|
||||
// file contains bytecode instead of looking like a regular compressed data
|
||||
// member. A compressed bytecode file has its content compressed but has a
|
||||
// magic number of "llvc". This acounts for the +/-4 arithmetic in the code
|
||||
// below.
|
||||
int hdrSize;
|
||||
if (willCompress) {
|
||||
char* output = 0;
|
||||
if (member.isBytecode()) {
|
||||
data +=4;
|
||||
fSize -= 4;
|
||||
}
|
||||
fSize = Compressor::compressToNewBuffer(
|
||||
data,fSize,output,Compressor::COMP_TYPE_ZLIB);
|
||||
data = output;
|
||||
if (member.isBytecode())
|
||||
hdrSize = -fSize-4;
|
||||
else
|
||||
hdrSize = -fSize;
|
||||
} else {
|
||||
hdrSize = fSize;
|
||||
}
|
||||
|
||||
// Header for the archive member
|
||||
// Compute the fields of the header
|
||||
ArchiveMemberHeader Hdr;
|
||||
Hdr.init();
|
||||
|
||||
// Set the name. If its longer than 15 chars, it will have already
|
||||
// been reduced by the writeSymbolTable.
|
||||
Hdr.setName(member.name);
|
||||
|
||||
// Set the other header members
|
||||
Hdr.setSize( mFile.size() );
|
||||
Hdr.setMode( member.status.mode);
|
||||
Hdr.setUid ( member.status.user);
|
||||
Hdr.setGid ( member.status.group);
|
||||
Hdr.setDate( member.status.modTime.ToPosixTime() );
|
||||
bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
|
||||
|
||||
// Write header to archive file
|
||||
ARFile.write((char*)&Hdr, sizeof(Hdr));
|
||||
|
||||
//write to archive file
|
||||
ARFile.write(mFile.charBase(),mFile.size());
|
||||
|
||||
mFile.unmap();
|
||||
// Write the long filename if its long
|
||||
if (writeLongName) {
|
||||
ARFile << member.getPath().c_str();
|
||||
ARFile << '\n';
|
||||
}
|
||||
|
||||
// Make sure we write the compressed bytecode magic number if we should.
|
||||
if (willCompress && member.isBytecode())
|
||||
ARFile.write("llvc",4);
|
||||
|
||||
// Write the (possibly compressed) member's content to the file.
|
||||
ARFile.write(data,fSize);
|
||||
|
||||
// Make sure the member is an even length
|
||||
if (ARFile.tellp() % 2 != 0)
|
||||
ARFile << ARFILE_PAD;
|
||||
|
||||
// Free the compressed data, if necessary
|
||||
if (willCompress) {
|
||||
free((void*)data);
|
||||
}
|
||||
|
||||
// Close the mapped file if it was opened
|
||||
if (mFile != 0) {
|
||||
mFile->unmap();
|
||||
delete mFile;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
Archive::ArchiveInternals::writeArchive() {
|
||||
|
||||
// Create archive file for output.
|
||||
std::ofstream ArchiveFile(fname.get().c_str());
|
||||
|
||||
// Check for errors opening or creating archive file.
|
||||
if ( !ArchiveFile.is_open() || ArchiveFile.bad() ) {
|
||||
throw std::string("Error opening archive file: ") + fname.get();
|
||||
Archive::writeSymbolTable(std::ofstream& ARFile,bool PrintSymTab ) {
|
||||
|
||||
// Construct the symbol table's header
|
||||
ArchiveMemberHeader Hdr;
|
||||
Hdr.init();
|
||||
memcpy(Hdr.name,ARFILE_LLVM_SYMTAB_NAME,16);
|
||||
uint64_t secondsSinceEpoch = sys::TimeValue::now().toEpochTime();
|
||||
char buffer[32];
|
||||
sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
|
||||
memcpy(Hdr.date,buffer,12);
|
||||
sprintf(buffer,"%-10u",symTabSize);
|
||||
memcpy(Hdr.size,buffer,10);
|
||||
|
||||
// Write the header
|
||||
ARFile.write((char*)&Hdr, sizeof(Hdr));
|
||||
|
||||
// Save the starting position of the symbol tables data content.
|
||||
unsigned startpos = ARFile.tellp();
|
||||
|
||||
// Print the symbol table header if we're supposed to
|
||||
if (PrintSymTab)
|
||||
std::cout << "Symbol Table:\n";
|
||||
|
||||
// Write out the symbols sequentially
|
||||
for ( Archive::SymTabType::iterator I = symTab.begin(), E = symTab.end();
|
||||
I != E; ++I)
|
||||
{
|
||||
// Write out the file index
|
||||
writeInteger(I->second, ARFile);
|
||||
// Write out the length of the symbol
|
||||
writeInteger(I->first.length(), ARFile);
|
||||
// Write out the symbol
|
||||
ARFile.write(I->first.data(), I->first.length());
|
||||
|
||||
// Print this entry to std::cout if we should
|
||||
if (PrintSymTab) {
|
||||
unsigned filepos = I->second + symTabSize + sizeof(ArchiveMemberHeader) +
|
||||
(symTabSize % 2 != 0) + 8;
|
||||
std::cout << " " << std::setw(9) << filepos << "\t" << I->first << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Write magic string to archive.
|
||||
ArchiveFile << ARFILE_MAGIC;
|
||||
// Now that we're done with the symbol table, get the ending file position
|
||||
unsigned endpos = ARFile.tellp();
|
||||
|
||||
// Write the symbol table and string pool
|
||||
writeSymbolTable(ArchiveFile);
|
||||
// Make sure that the amount we wrote is what we pre-computed. This is
|
||||
// critical for file integrity purposes.
|
||||
assert(endpos - startpos == symTabSize && "Invalid symTabSize computation");
|
||||
|
||||
//Loop over all member files, and add to the archive.
|
||||
for ( unsigned i = 0; i < members.size(); ++i) {
|
||||
if(ArchiveFile.tellp() % 2 != 0)
|
||||
ArchiveFile << ARFILE_PAD;
|
||||
writeMember(members[i],ArchiveFile);
|
||||
}
|
||||
|
||||
//Close archive file.
|
||||
ArchiveFile.close();
|
||||
// Make sure the symbol table is even sized
|
||||
if (symTabSize % 2 != 0 )
|
||||
ARFile << ARFILE_PAD;
|
||||
}
|
||||
|
||||
// vim: sw=2 ai
|
||||
void
|
||||
Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames,
|
||||
bool Compress, bool PrintSymTab) {
|
||||
|
||||
// Make sure they haven't opened up the file, not loaded it,
|
||||
// but are now trying to write it which would wipe out the file.
|
||||
assert(!(members.empty() && mapfile->size() > 8));
|
||||
|
||||
// Create a temporary file to store the archive in
|
||||
sys::Path TmpArchive = archPath;
|
||||
TmpArchive.createTemporaryFile();
|
||||
|
||||
// Make sure the temporary gets removed if we crash
|
||||
sys::RemoveFileOnSignal(TmpArchive);
|
||||
|
||||
// Ensure we can remove the temporary even in the face of an exception
|
||||
try {
|
||||
// Create archive file for output.
|
||||
std::ofstream ArchiveFile(TmpArchive.c_str());
|
||||
|
||||
// Check for errors opening or creating archive file.
|
||||
if ( !ArchiveFile.is_open() || ArchiveFile.bad() ) {
|
||||
throw std::string("Error opening archive file: ") + archPath.get();
|
||||
}
|
||||
|
||||
// If we're creating a symbol table, reset it now
|
||||
if (CreateSymbolTable) {
|
||||
symTabSize = 0;
|
||||
symTab.clear();
|
||||
}
|
||||
|
||||
// Write magic string to archive.
|
||||
ArchiveFile << ARFILE_MAGIC;
|
||||
|
||||
// Loop over all member files, and write them out. Note that this also
|
||||
// builds the symbol table, symTab.
|
||||
for ( MembersList::iterator I = begin(), E = end(); I != E; ++I) {
|
||||
writeMember(*I,ArchiveFile,CreateSymbolTable,TruncateNames,Compress);
|
||||
}
|
||||
|
||||
// Close archive file.
|
||||
ArchiveFile.close();
|
||||
|
||||
// Write the symbol table
|
||||
if (CreateSymbolTable) {
|
||||
// At this point we have written a file that is a legal archive but it
|
||||
// doesn't have a symbol table in it. To aid in faster reading and to
|
||||
// ensure compatibility with other archivers we need to put the symbol
|
||||
// table first in the file. Unfortunately, this means mapping the file
|
||||
// we just wrote back in and copying it to the destination file.
|
||||
sys::MappedFile arch(TmpArchive);
|
||||
const char* base = (const char*) arch.map();
|
||||
|
||||
// Open the final file to write and check it.
|
||||
std::ofstream FinalFile(archPath.c_str());
|
||||
if ( !FinalFile.is_open() || FinalFile.bad() ) {
|
||||
throw std::string("Error opening archive file: ") + archPath.get();
|
||||
}
|
||||
|
||||
// Write the file magic number
|
||||
FinalFile << ARFILE_MAGIC;
|
||||
|
||||
// Put out the symbol table
|
||||
writeSymbolTable(FinalFile,PrintSymTab);
|
||||
|
||||
// Copy the temporary file contents being sure to skip the file's magic
|
||||
// number.
|
||||
FinalFile.write(base + sizeof(ARFILE_MAGIC)-1,
|
||||
arch.size()-sizeof(ARFILE_MAGIC)+1);
|
||||
|
||||
// Close up shop
|
||||
FinalFile.close();
|
||||
arch.unmap();
|
||||
TmpArchive.destroyFile();
|
||||
|
||||
} else {
|
||||
// We don't have to insert the symbol table, so just renaming the temp
|
||||
// file to the correct name will suffice.
|
||||
TmpArchive.renameFile(archPath);
|
||||
}
|
||||
} catch (...) {
|
||||
// Make sure we clean up.
|
||||
if (TmpArchive.exists())
|
||||
TmpArchive.destroyFile();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user