2019-04-03 11:51:49 +00:00
|
|
|
#include <AK/MappedFile.h>
|
2018-10-10 09:53:07 +00:00
|
|
|
#include <sys/mman.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
#include <fcntl.h>
|
2019-04-03 11:51:49 +00:00
|
|
|
#include <unistd.h>
|
|
|
|
#include <stdio.h>
|
2018-10-10 09:53:07 +00:00
|
|
|
|
|
|
|
namespace AK {
|
|
|
|
|
2019-04-03 11:51:49 +00:00
|
|
|
MappedFile::MappedFile(const String& file_name)
|
|
|
|
: m_file_name(file_name)
|
2018-10-10 09:53:07 +00:00
|
|
|
{
|
2019-04-03 11:51:49 +00:00
|
|
|
m_file_length = PAGE_SIZE;
|
2019-01-31 16:31:23 +00:00
|
|
|
m_fd = open(m_file_name.characters(), O_RDONLY);
|
2018-10-10 09:53:07 +00:00
|
|
|
|
|
|
|
if (m_fd != -1) {
|
|
|
|
struct stat st;
|
|
|
|
fstat(m_fd, &st);
|
2019-01-31 16:31:23 +00:00
|
|
|
m_file_length = st.st_size;
|
|
|
|
m_map = mmap(nullptr, m_file_length, PROT_READ, MAP_SHARED, m_fd, 0);
|
2018-10-10 09:53:07 +00:00
|
|
|
|
|
|
|
if (m_map == MAP_FAILED)
|
|
|
|
perror("");
|
|
|
|
}
|
|
|
|
|
2019-04-03 11:51:49 +00:00
|
|
|
dbgprintf("MappedFile{%s} := { m_fd=%d, m_file_length=%zu, m_map=%p }\n", m_file_name.characters(), m_fd, m_file_length, m_map);
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
MappedFile::~MappedFile()
|
|
|
|
{
|
2019-04-03 11:51:49 +00:00
|
|
|
unmap();
|
|
|
|
}
|
|
|
|
|
|
|
|
void MappedFile::unmap()
|
|
|
|
{
|
|
|
|
if (!is_valid())
|
|
|
|
return;
|
|
|
|
ASSERT(m_fd != -1);
|
|
|
|
int rc = munmap(m_map, m_file_length);
|
|
|
|
ASSERT(rc == 0);
|
|
|
|
m_file_name = { };
|
|
|
|
m_file_length = 0;
|
|
|
|
m_fd = -1;
|
|
|
|
m_map = (void*)-1;
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
MappedFile::MappedFile(MappedFile&& other)
|
2019-04-03 11:51:49 +00:00
|
|
|
: m_file_name(move(other.m_file_name))
|
2019-01-31 16:31:23 +00:00
|
|
|
, m_file_length(other.m_file_length)
|
2018-10-10 09:53:07 +00:00
|
|
|
, m_fd(other.m_fd)
|
|
|
|
, m_map(other.m_map)
|
|
|
|
{
|
2019-01-31 16:31:23 +00:00
|
|
|
other.m_file_length = 0;
|
2018-10-10 09:53:07 +00:00
|
|
|
other.m_fd = -1;
|
|
|
|
other.m_map = (void*)-1;
|
|
|
|
}
|
|
|
|
|
2019-04-03 11:51:49 +00:00
|
|
|
MappedFile& MappedFile::operator=(MappedFile&& other)
|
|
|
|
{
|
|
|
|
if (this == &other)
|
|
|
|
return *this;
|
|
|
|
unmap();
|
|
|
|
swap(m_file_name, other.m_file_name);
|
|
|
|
swap(m_file_length, other.m_file_length);
|
|
|
|
swap(m_fd, other.m_fd);
|
|
|
|
swap(m_map, other.m_map);
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|
|
|
|
|