Serenity Operating System
at hosted 97 lines 2.8 kB view raw
1/* 2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright notice, this 9 * list of conditions and the following disclaimer. 10 * 11 * 2. Redistributions in binary form must reproduce the above copyright notice, 12 * this list of conditions and the following disclaimer in the documentation 13 * and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27#include <AK/String.h> 28#include <AK/MappedFile.h> 29#include <fcntl.h> 30#include <stdio.h> 31#include <sys/mman.h> 32#include <sys/stat.h> 33#include <unistd.h> 34 35//#define DEBUG_MAPPED_FILE 36 37namespace AK { 38 39MappedFile::MappedFile(const StringView& file_name) 40{ 41 m_size = PAGE_SIZE; 42 int fd = open_with_path_length(file_name.characters_without_null_termination(), file_name.length(), O_RDONLY | O_CLOEXEC, 0); 43 44 if (fd == -1) { 45 perror("open"); 46 return; 47 } 48 49 struct stat st; 50 fstat(fd, &st); 51 m_size = st.st_size; 52 m_map = mmap(nullptr, m_size, PROT_READ, MAP_SHARED, fd, 0); 53 54 if (m_map == MAP_FAILED) 55 perror("mmap"); 56 57#ifdef DEBUG_MAPPED_FILE 58 dbgprintf("MappedFile{%s} := { fd=%d, m_size=%u, m_map=%p }\n", file_name.characters(), fd, m_size, m_map); 59#endif 60 61 close(fd); 62} 63 64MappedFile::~MappedFile() 65{ 66 unmap(); 67} 68 69void MappedFile::unmap() 70{ 71 if (!is_valid()) 72 return; 73 int rc = munmap(m_map, m_size); 74 ASSERT(rc == 0); 75 m_size = 0; 76 m_map = (void*)-1; 77} 78 79MappedFile::MappedFile(MappedFile&& other) 80 : m_size(other.m_size) 81 , m_map(other.m_map) 82{ 83 other.m_size = 0; 84 other.m_map = (void*)-1; 85} 86 87MappedFile& MappedFile::operator=(MappedFile&& other) 88{ 89 if (this == &other) 90 return *this; 91 unmap(); 92 swap(m_size, other.m_size); 93 swap(m_map, other.m_map); 94 return *this; 95} 96 97}