Add an AllocateRW to match AllocateRWX.
[oota-llvm.git] / lib / System / Win32 / Memory.inc
1 //===- Win32/Memory.cpp - Win32 Memory Implementation -----------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides the Win32 specific implementation of various Memory
11 // management utilities
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Win32.h"
16 #include "llvm/System/Process.h"
17
18 namespace llvm {
19 using namespace sys;
20
21 //===----------------------------------------------------------------------===//
22 //=== WARNING: Implementation here must contain only Win32 specific code 
23 //===          and must not be UNIX code
24 //===----------------------------------------------------------------------===//
25
26 MemoryBlock Memory::AllocateRWX(unsigned NumBytes,
27                                 const MemoryBlock *NearBlock,
28                                 std::string *ErrMsg) {
29   if (NumBytes == 0) return MemoryBlock();
30
31   static const long pageSize = Process::GetPageSize();
32   unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
33
34   //FIXME: support NearBlock if ever needed on Win64.
35
36   void *pa = VirtualAlloc(NULL, NumPages*pageSize, MEM_COMMIT,
37                   PAGE_EXECUTE_READWRITE);
38   if (pa == NULL) {
39     MakeErrMsg(ErrMsg, "Can't allocate RWX Memory: ");
40     return MemoryBlock();
41   }
42
43   MemoryBlock result;
44   result.Address = pa;
45   result.Size = NumPages*pageSize;
46   return result;
47 }
48
49 MemoryBlock Memory::AllocateRW(unsigned NumBytes,
50                                 const MemoryBlock *NearBlock,
51                                 std::string *ErrMsg) {
52   if (NumBytes == 0) return MemoryBlock();
53
54   static const long pageSize = Process::GetPageSize();
55   unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
56
57   //FIXME: support NearBlock if ever needed on Win64.
58
59   void *pa = VirtualAlloc(NULL, NumPages*pageSize, MEM_COMMIT,
60                   PAGE_READWRITE);
61   if (pa == NULL) {
62     MakeErrMsg(ErrMsg, "Can't allocate RWX Memory: ");
63     return MemoryBlock();
64   }
65
66   MemoryBlock result;
67   result.Address = pa;
68   result.Size = NumPages*pageSize;
69   return result;
70 }
71
72 bool Memory::ReleaseRWX(MemoryBlock &M, std::string *ErrMsg) {
73   if (M.Address == 0 || M.Size == 0) return false;
74   if (!VirtualFree(M.Address, 0, MEM_RELEASE))
75     return MakeErrMsg(ErrMsg, "Can't release RWX Memory: ");
76   return false;
77 }
78
79 }
80