Elfspy/MFile.cpp

42 lines
775 B
C++
Raw Normal View History

2016-09-16 17:45:35 +02:00
#include "elfspy/MFile.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include "elfspy/Fail.h"
2018-03-15 19:53:38 +01:00
2016-09-16 17:45:35 +02:00
namespace spy
{
MFile::MFile(const char* file_name)
{
fd_ = open(file_name, O_RDONLY, 0);
if (fd_ < 0) {
Fail() << "Cannot open " << file_name;
}
2018-03-15 19:53:38 +01:00
struct stat file_info;
if (fstat(fd_, &file_info) < 0) {
2016-09-16 17:45:35 +02:00
Fail() << "Cannot fstat " << file_name;
}
2018-03-15 19:53:38 +01:00
size_ = file_info.st_size;
2016-09-16 17:45:35 +02:00
address_ = reinterpret_cast<unsigned char*>(
mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_, 0));
if (address_ == MAP_FAILED) {
Fail() << "Cannot mmap " << file_name;
}
}
MFile::~MFile()
{
munmap(address_, size_);
close(fd_);
}
} // namespace spy