#define DEBUG_TYPE "Data-stream"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/DataStream.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/system_error.h"
#include <string>
#include <cerrno>
#include <cstdio>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
using namespace llvm;
STATISTIC(NumStreamFetches, "Number of calls to Data stream fetch");
namespace llvm {
DataStreamer::~DataStreamer() {}
}
namespace {
class DataFileStreamer : public DataStreamer {
int Fd;
public:
DataFileStreamer() : Fd(0) {}
virtual ~DataFileStreamer() {
close(Fd);
}
virtual size_t GetBytes(unsigned char *buf, size_t len) {
NumStreamFetches++;
return read(Fd, buf, len);
}
error_code OpenFile(const std::string &Filename) {
if (Filename == "-") {
Fd = 0;
sys::Program::ChangeStdinToBinary();
return error_code::success();
}
int OpenFlags = O_RDONLY;
#ifdef O_BINARY
OpenFlags |= O_BINARY; #endif
Fd = ::open(Filename.c_str(), OpenFlags);
if (Fd == -1)
return error_code(errno, posix_category());
return error_code::success();
}
};
}
namespace llvm {
DataStreamer *getDataFileStreamer(const std::string &Filename,
std::string *StrError) {
DataFileStreamer *s = new DataFileStreamer();
if (error_code e = s->OpenFile(Filename)) {
*StrError = std::string("Could not open ") + Filename + ": " +
e.message() + "\n";
return NULL;
}
return s;
}
}