1 //===- Unix/MappedFile.cpp - Unix MappedFile Implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides the generic Unix implementation of the MappedFile concept.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //=== is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/System/Process.h"
27 struct sys::MappedFileInfo {
32 void MappedFile::initialize() {
34 info_ = new MappedFileInfo;
36 if (options_&READ_ACCESS)
37 if (options_&WRITE_ACCESS)
41 else if (options_&WRITE_ACCESS)
43 info_->fd_ = ::open(path_.c_str(),mode);
47 ThrowErrno(std::string("Can't open file: ") + path_.toString());
50 if(::fstat(info_->fd_, &info_->sbuf_) < 0) {
54 ThrowErrno(std::string("Can't stat file: ") + path_.toString());
57 throw std::string("Can't open file: ") + path_.toString();
61 void MappedFile::terminate() {
62 assert(info_ && "MappedFile not initialized");
69 void MappedFile::unmap() {
70 assert(info_ && "MappedFile not initialized");
72 if (options_ & WRITE_ACCESS)
73 ::msync(base_, info_->sbuf_.st_size, MS_SYNC);
74 ::munmap(base_, info_->sbuf_.st_size);
78 void* MappedFile::map() {
79 assert(info_ && "MappedFile not initialized");
90 if (options_ & READ_ACCESS)
92 if (options_ & WRITE_ACCESS)
94 if (options_ & EXEC_ACCESS)
96 if (options_ & SHARED_MAPPING)
101 size_t map_size = ((info_->sbuf_.st_size / Process::GetPageSize())+1) *
102 Process::GetPageSize();
104 base_ = ::mmap(0, map_size, prot, flags, info_->fd_, 0);
105 if (base_ == MAP_FAILED)
106 ThrowErrno(std::string("Can't map file:") + path_.toString());
111 size_t MappedFile::size() const {
112 assert(info_ && "MappedFile not initialized");
113 return info_->sbuf_.st_size;
116 void MappedFile::size(size_t new_size) {
117 assert(info_ && "MappedFile not initialized");
119 // Take the mapping out of memory
122 // Adjust the current size to a page boundary
123 size_t cur_size = ((info_->sbuf_.st_size / Process::GetPageSize())+1) *
124 Process::GetPageSize();
126 // Adjust the new_size to a page boundary
127 new_size = ((new_size / Process::GetPageSize())+1) *
128 Process::GetPageSize();
130 // If the file needs to be extended
131 if (new_size > cur_size) {
132 // Ensure we can allocate at least the idodes necessary to handle the
133 // file size requested.
134 ::lseek(info_->fd_, new_size, SEEK_SET);
135 ::write(info_->fd_, "\0", 1);
138 // Seek to current end of file.
144 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab