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"
28 struct sys::MappedFileInfo {
33 void MappedFile::initialize() {
35 info_ = new MappedFileInfo;
37 if (options_&READ_ACCESS)
38 if (options_&WRITE_ACCESS)
42 else if (options_&WRITE_ACCESS)
44 info_->fd_ = ::open(path_.c_str(),mode);
48 ThrowErrno(std::string("Can't open file: ") + path_.get());
51 if(::fstat(info_->fd_, &info_->sbuf_) < 0) {
55 ThrowErrno(std::string("Can't stat file: ") + path_.get());
60 void MappedFile::terminate() {
61 assert(info_ && "MappedFile not initialized");
68 void MappedFile::unmap() {
69 assert(info_ && "MappedFile not initialized");
71 if (options_ & WRITE_ACCESS)
72 ::msync(base_, info_->sbuf_.st_size, MS_SYNC);
73 ::munmap(base_, info_->sbuf_.st_size);
77 void* MappedFile::map() {
88 if (options_ & READ_ACCESS)
90 if (options_ & WRITE_ACCESS)
92 if (options_ & EXEC_ACCESS)
94 if (options_ & SHARED_MAPPING)
99 size_t map_size = ((info_->sbuf_.st_size / Process::GetPageSize())+1) *
100 Process::GetPageSize();
102 base_ = ::mmap(0, map_size, prot, flags, info_->fd_, 0);
103 if (base_ == MAP_FAILED)
104 ThrowErrno(std::string("Can't map file:") + path_.get());
109 size_t MappedFile::size() {
110 assert(info_ && "MappedFile not initialized");
111 return info_->sbuf_.st_size;
114 void MappedFile::size(size_t new_size) {
115 assert(info_ && "MappedFile not initialized");
117 // Take the mapping out of memory
120 // Adjust the current size to a page boundary
121 size_t cur_size = ((info_->sbuf_.st_size / Process::GetPageSize())+1) *
122 Process::GetPageSize();
124 // Adjust the new_size to a page boundary
125 new_size = ((new_size / Process::GetPageSize())+1) *
126 Process::GetPageSize();
128 // If the file needs to be extended
129 if (new_size > cur_size) {
130 // Ensure we can allocate at least the idodes necessary to handle the
131 // file size requested.
132 ::lseek(info_->fd_, new_size, SEEK_SET);
133 ::write(info_->fd_, "\0", 1);
136 // Seek to current end of file.
142 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab