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_.get());
50 if(::fstat(info_->fd_, &info_->sbuf_) < 0) {
54 ThrowErrno(std::string("Can't stat file: ") + path_.get());
59 void MappedFile::terminate() {
60 assert(info_ && "MappedFile not initialized");
67 void MappedFile::unmap() {
68 assert(info_ && "MappedFile not initialized");
70 if (options_ & WRITE_ACCESS)
71 ::msync(base_, info_->sbuf_.st_size, MS_SYNC);
72 ::munmap(base_, info_->sbuf_.st_size);
76 void* MappedFile::map() {
87 if (options_ & READ_ACCESS)
89 if (options_ & WRITE_ACCESS)
91 if (options_ & EXEC_ACCESS)
93 if (options_ & SHARED_MAPPING)
98 size_t map_size = ((info_->sbuf_.st_size / Process::GetPageSize())+1) *
99 Process::GetPageSize();
101 base_ = ::mmap(0, map_size, prot, flags, info_->fd_, 0);
102 if (base_ == MAP_FAILED)
103 ThrowErrno(std::string("Can't map file:") + path_.get());
108 size_t MappedFile::size() {
109 assert(info_ && "MappedFile not initialized");
110 return info_->sbuf_.st_size;
113 void MappedFile::size(size_t new_size) {
114 assert(info_ && "MappedFile not initialized");
116 // Take the mapping out of memory
119 // Adjust the current size to a page boundary
120 size_t cur_size = ((info_->sbuf_.st_size / Process::GetPageSize())+1) *
121 Process::GetPageSize();
123 // Adjust the new_size to a page boundary
124 new_size = ((new_size / Process::GetPageSize())+1) *
125 Process::GetPageSize();
127 // If the file needs to be extended
128 if (new_size > cur_size) {
129 // Ensure we can allocate at least the idodes necessary to handle the
130 // file size requested.
131 ::lseek(info_->fd_, new_size, SEEK_SET);
132 ::write(info_->fd_, "\0", 1);
135 // Seek to current end of file.
141 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab