summaryrefslogtreecommitdiff
path: root/lib/System/Unix/MappedFile.inc
blob: 92dc6660439e43c9596a0d4f5ebc7d9d5b04ec34 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//===- Unix/MappedFile.inc - Unix MappedFile Implementation -----*- C++ -*-===//
// 
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
// 
//===----------------------------------------------------------------------===//
//
// This file provides the generic Unix implementation of the MappedFile concept.
//
//===----------------------------------------------------------------------===//

#include "Unix.h"
#include "llvm/System/Process.h"

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif

#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif

using namespace llvm;
using namespace sys;

namespace llvm {
  namespace sys {
    struct MappedFileInfo {
      int   FD;
      off_t Size;
    };
  }
}

bool MappedFile::initialize(std::string* ErrMsg) {
  int FD = ::open(Path.c_str(), O_RDONLY);
  if (FD < 0) {
    MakeErrMsg(ErrMsg, "can't open file '" + Path.toString() + "'");
    return true;
  } 
  const FileStatus *Status = Path.getFileStatus(false, ErrMsg);
  if (!Status) {
    ::close(FD);
    return true;
  }
  MapInfo = new MappedFileInfo();
  MapInfo->FD = FD;
  MapInfo->Size = Status->getSize();
  return false;
}

void MappedFile::terminate() {
  assert(MapInfo && "MappedFile not initialized");
  ::close(MapInfo->FD);
  delete MapInfo;
  MapInfo = 0;
}

void MappedFile::unmap() {
  assert(MapInfo && "MappedFile not initialized");
  if (!isMapped()) return;
  
  ::munmap(BasePtr, MapInfo->Size);
  BasePtr = 0;  // Mark this as non-mapped.
}

void* MappedFile::map(std::string* ErrMsg) {
  assert(MapInfo && "MappedFile not initialized");
  if (isMapped()) return BasePtr;
  
  int prot = PROT_READ;
  int flags = MAP_PRIVATE;
#ifdef MAP_FILE
  flags |= MAP_FILE;
#endif
  size_t PageSize = Process::GetPageSize();
  size_t map_size = ((MapInfo->Size / PageSize)+1) * PageSize;

  BasePtr = ::mmap(0, map_size, prot, flags, MapInfo->FD, 0);
  if (BasePtr == MAP_FAILED) {
    MakeErrMsg(ErrMsg, "Can't map file:" + Path.toString());
    return 0;
  }
  return BasePtr;
}

size_t MappedFile::size() const {
  assert(MapInfo && "MappedFile not initialized");
  return MapInfo->Size;
}