1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef rr_ExecutableMemory_hpp
16 #define rr_ExecutableMemory_hpp
17
18 #include <cstddef>
19 #include <cstdint>
20 #include <cstring>
21
22 namespace rr {
23
24 size_t memoryPageSize();
25
26 enum MemoryPermission
27 {
28 PERMISSION_READ = 1,
29 PERMISSION_WRITE = 2,
30 PERMISSION_EXECUTE = 4,
31 };
32
33 // Allocates memory with the specified permissions. If |need_exec| is true then
34 // the allocate memory can be made marked executable using protectMemoryPages().
35 void *allocateMemoryPages(size_t bytes, int permissions, bool need_exec);
36
37 // Sets permissions for memory allocated with allocateMemoryPages().
38 void protectMemoryPages(void *memory, size_t bytes, int permissions);
39
40 // Releases memory allocated with allocateMemoryPages().
41 void deallocateMemoryPages(void *memory, size_t bytes);
42
43 template<typename P>
unaligned_read(void * address)44 P unaligned_read(void *address)
45 {
46 P value;
47 memcpy(&value, address, sizeof(P));
48 return value;
49 }
50
51 template<typename P>
unaligned_write(void * address,P value)52 void unaligned_write(void *address, P value)
53 {
54 memcpy(address, &value, sizeof(P));
55 }
56
57 template<typename P>
58 class unaligned_ref
59 {
60 public:
unaligned_ref(void * ptr)61 explicit unaligned_ref(void *ptr)
62 : ptr(ptr)
63 {}
64
operator =(P value)65 unaligned_ref &operator=(P value)
66 {
67 unaligned_write(ptr, value);
68 return *this;
69 }
70
operator P()71 operator P()
72 {
73 return unaligned_read<P>(ptr);
74 }
75
76 private:
77 void *ptr;
78 };
79
80 template<typename P>
81 class unaligned_ptr
82 {
83 public:
unaligned_ptr(void * ptr)84 unaligned_ptr(void *ptr)
85 : ptr(ptr)
86 {}
87
operator *()88 unaligned_ref<P> operator*()
89 {
90 return unaligned_ref<P>(ptr);
91 }
92
operator intptr_t()93 explicit operator intptr_t()
94 {
95 return (intptr_t)ptr;
96 }
97
98 private:
99 void *ptr;
100 };
101
102 } // namespace rr
103
104 #endif // rr_ExecutableMemory_hpp
105