Simplify the sys::Memory interface per Chris' request.
[oota-llvm.git] / lib / System / Darwin / Memory.cpp
1 //===- Darwin/Memory.cpp - Darwin Memory Implementation ---------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides the Darwin specific implementation of various Memory
11 // management utilities
12 //
13 //===----------------------------------------------------------------------===//
14
15 // Include the generic unix implementation
16 #include "../Unix/Memory.cpp"
17 #include "llvm/System/Process.h"
18 #include <sys/mman.h>
19
20 namespace llvm {
21 using namespace sys;
22
23 //===----------------------------------------------------------------------===//
24 //=== WARNING: Implementation here must contain only Darwin specific code 
25 //===          and must not be generic UNIX code (see ../Unix/Memory.cpp)
26 //===----------------------------------------------------------------------===//
27
28 /// AllocateRWXMemory - Allocate a slab of memory with read/write/execute
29 /// permissions.  This is typically used for JIT applications where we want
30 /// to emit code to the memory then jump to it.  Getting this type of memory
31 /// is very OS specific.
32 ///
33 MemoryBlock Memory::AllocateRWX(unsigned NumBytes) {
34   if (NumBytes == 0) return MemoryBlock();
35
36   static const long pageSize = Process::GetPageSize();
37   unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
38
39   void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
40                   MAP_PRIVATE|MAP_ANON, -1, 0);
41   if (pa == MAP_FAILED) {
42     char msg[MAXPATHLEN];
43     strerror_r(errno, msg, MAXPATHLEN-1);
44     throw std::string("Can't allocate RWX Memory: ") + msg;
45   }
46   MemoryBlock result;
47   result.Address = pa;
48   result.Size = NumPages*pageSize;
49   return result;
50 }
51
52 void Memory::ReleaseRWX(MemoryBlock& M) {
53   if (M.Address == 0 || M.Size == 0) return;
54   if (0 != munmap(M.Address, M.Size)) {
55     char msg[MAXPATHLEN];
56     strerror_r(errno, msg, MAXPATHLEN-1);
57     throw std::string("Can't release RWX Memory: ") + msg;
58   }
59 }
60
61 }
62
63 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab