summaryrefslogtreecommitdiff
path: root/AK/MappedFile.cpp
blob: 3cf7570bc1498b427fd855e0ba05015fd89bb7f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "MappedFile.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdio>

namespace AK {

MappedFile::MappedFile(String&& file_name)
    : m_file_name(std::move(file_name))
{
    m_file_length = 1024;
    m_fd = open(m_file_name.characters(), O_RDONLY);
    
    if (m_fd != -1) {
        struct stat st;
        fstat(m_fd, &st);
        m_file_length = st.st_size;
        m_map = mmap(nullptr, m_file_length, PROT_READ, MAP_SHARED, m_fd, 0);

        if (m_map == MAP_FAILED)
            perror("");
    }

    printf("MappedFile{%s} := { m_fd=%d, m_file_length=%zu, m_map=%p }\n", m_file_name.characters(), m_fd, m_file_length, m_map);
}

MappedFile::~MappedFile()
{
    if (m_map != (void*)-1) {
        ASSERT(m_fd != -1);
        munmap(m_map, m_file_length);
    }
}

MappedFile::MappedFile(MappedFile&& other)
    : m_file_name(std::move(other.m_file_name))
    , m_file_length(other.m_file_length)
    , m_fd(other.m_fd)
    , m_map(other.m_map)
{
    other.m_file_length = 0;
    other.m_fd = -1;
    other.m_map = (void*)-1;
}

}