blob: 370b318955eadcfdd99cfad34eeabcad827fde4f [file] [log] [blame]
Reid Spencer41b21bf2004-09-11 04:57:25 +00001//===- Unix/Memory.cpp - Generic UNIX System Configuration ------*- 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 defines some functions for various memory management utilities.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Unix.h"
Reid Spencer07c00d32004-12-27 06:17:03 +000015#include "llvm/System/Process.h"
16
17#ifdef HAVE_SYS_MMAN_H
18#include <sys/mman.h>
19#endif
Reid Spencer41b21bf2004-09-11 04:57:25 +000020
21namespace llvm {
22
Reid Spencer07c00d32004-12-27 06:17:03 +000023/// AllocateRWXMemory - Allocate a slab of memory with read/write/execute
24/// permissions. This is typically used for JIT applications where we want
25/// to emit code to the memory then jump to it. Getting this type of memory
26/// is very OS specific.
27///
28MemoryBlock Memory::AllocateRWX(unsigned NumBytes) {
29 if (NumBytes == 0) return MemoryBlock();
30
31 long pageSize = Process::GetPageSize();
32 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
33
34 int fd = -1;
35#ifdef NEED_DEV_ZERO_FOR_MMAP
36 static int zero_fd = open("/dev/zero", O_RDWR);
37 if (zero_fd == -1) {
38 ThrowErrno("Can't open /dev/zero device");
39 }
40 fd = zero_fd;
41#endif
42
43 int flags = MAP_PRIVATE |
44#ifdef HAVE_MMAP_ANONYMOUS
45 MAP_ANONYMOUS
46#else
47 MAP_ANON
48#endif
49 ;
50 void *pa = ::mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
51 flags, fd, 0);
52 if (pa == MAP_FAILED) {
53 ThrowErrno("Can't allocate RWX Memory");
54 }
55 MemoryBlock result;
56 result.Address = pa;
57 result.Size = NumPages*pageSize;
58 return result;
59}
60
61void Memory::ReleaseRWX(MemoryBlock& M) {
62 if (M.Address == 0 || M.Size == 0) return;
63 if (0 != ::munmap(M.Address, M.Size)) {
64 ThrowErrno("Can't release RWX Memory");
65 }
66}
67
Reid Spencer41b21bf2004-09-11 04:57:25 +000068}
69
70// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab