2019-07-08 11:59:10 +00:00
|
|
|
#include <AK/AKString.h>
|
2019-04-03 11:51:49 +00:00
|
|
|
#include <AK/MappedFile.h>
|
2019-05-28 09:53:16 +00:00
|
|
|
#include <fcntl.h>
|
|
|
|
#include <stdio.h>
|
2018-10-10 09:53:07 +00:00
|
|
|
#include <sys/mman.h>
|
|
|
|
#include <sys/stat.h>
|
2019-04-03 11:51:49 +00:00
|
|
|
#include <unistd.h>
|
2018-10-10 09:53:07 +00:00
|
|
|
|
2019-04-03 12:15:35 +00:00
|
|
|
//#define DEBUG_MAPPED_FILE
|
|
|
|
|
2018-10-10 09:53:07 +00:00
|
|
|
namespace AK {
|
|
|
|
|
2019-06-02 12:58:02 +00:00
|
|
|
MappedFile::MappedFile(const StringView& file_name)
|
2018-10-10 09:53:07 +00:00
|
|
|
{
|
2019-04-03 12:15:35 +00:00
|
|
|
m_size = PAGE_SIZE;
|
2019-08-05 12:26:56 +00:00
|
|
|
int fd = open_with_path_length(file_name.characters_without_null_termination(), file_name.length(), O_RDONLY | O_CLOEXEC, 0);
|
2019-05-28 09:53:16 +00:00
|
|
|
|
2019-08-05 12:26:56 +00:00
|
|
|
if (fd == -1) {
|
|
|
|
perror("open");
|
|
|
|
return;
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|
|
|
|
|
2019-08-05 12:26:56 +00:00
|
|
|
struct stat st;
|
|
|
|
fstat(fd, &st);
|
|
|
|
m_size = st.st_size;
|
|
|
|
m_map = mmap(nullptr, m_size, PROT_READ, MAP_SHARED, fd, 0);
|
|
|
|
|
|
|
|
if (m_map == MAP_FAILED)
|
|
|
|
perror("mmap");
|
|
|
|
|
2019-04-03 12:15:35 +00:00
|
|
|
#ifdef DEBUG_MAPPED_FILE
|
2019-08-05 12:26:56 +00:00
|
|
|
dbgprintf("MappedFile{%s} := { fd=%d, m_size=%u, m_map=%p }\n", file_name.characters(), fd, m_size, m_map);
|
2019-04-03 12:15:35 +00:00
|
|
|
#endif
|
2019-08-05 12:26:56 +00:00
|
|
|
|
|
|
|
close(fd);
|
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;
|
2019-04-03 12:15:35 +00:00
|
|
|
int rc = munmap(m_map, m_size);
|
|
|
|
ASSERT(rc == 0);
|
|
|
|
m_size = 0;
|
2019-04-03 11:51:49 +00:00
|
|
|
m_map = (void*)-1;
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
MappedFile::MappedFile(MappedFile&& other)
|
2019-06-02 12:58:02 +00:00
|
|
|
: m_size(other.m_size)
|
2018-10-10 09:53:07 +00:00
|
|
|
, m_map(other.m_map)
|
|
|
|
{
|
2019-04-03 12:15:35 +00:00
|
|
|
other.m_size = 0;
|
2018-10-10 09:53:07 +00:00
|
|
|
other.m_map = (void*)-1;
|
|
|
|
}
|
|
|
|
|
2019-04-03 11:51:49 +00:00
|
|
|
MappedFile& MappedFile::operator=(MappedFile&& other)
|
|
|
|
{
|
|
|
|
if (this == &other)
|
|
|
|
return *this;
|
|
|
|
unmap();
|
2019-04-03 12:15:35 +00:00
|
|
|
swap(m_size, other.m_size);
|
2019-04-03 11:51:49 +00:00
|
|
|
swap(m_map, other.m_map);
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|