Debian Codegraph @

pypy/module/_hpy_universal/_vendored/hpy/debug/src/memprotect.c

raw symbols SCIP
1 #include "debug_internal.h"
2
3 // Implements OS dependent abstraction of memory protection
4
5 #ifdef _HPY_DEBUG_MEM_PROTECT_USEMMAP
6
7 #ifndef _WIN32
8
9 // On UNIX systems we use mmap and mprotect
10
11 #include <sys/mman.h>
12 #include <string.h>
13
14 void *raw_data_copy(const void* data, HPy_ssize_t size, bool write_protect) {
15 void* new_ptr;
16 new_ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
17 if (new_ptr == NULL)
18 return NULL;
19 memcpy(new_ptr, data, size);
20 if (write_protect) {
21 mprotect(new_ptr, size, PROT_READ);
22 }
23 return new_ptr;
24 }
25
26 void raw_data_protect(void* data, HPy_ssize_t size) {
27 mprotect(data, size, PROT_NONE);
28 }
29
30 int raw_data_free(void *data, HPy_ssize_t size) {
31 return munmap(data, size);
32 }
33
34 #else
35
36 // On Windows systems we use VirtualAlloc and VirtualProtect
37
38 #include <windows.h>
39 #include <memoryapi.h>
40
41 void *raw_data_copy(const void* data, HPy_ssize_t size, bool write_protect) {
42 void* new_ptr;
43 DWORD old;
44 new_ptr = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
45 if (new_ptr == NULL)
46 return NULL;
47 memcpy(new_ptr, data, size);
48 if (write_protect) {
49 VirtualProtect(new_ptr, size, PAGE_READONLY, &old);
50 }
51 return new_ptr;
52 }
53
54 void raw_data_protect(void* data, HPy_ssize_t size) {
55 DWORD old;
56 VirtualProtect(data, size, PAGE_NOACCESS, &old);
57 }
58
59 int raw_data_free(void *data, HPy_ssize_t size) {
60 return !VirtualFree(data, 0, MEM_RELEASE);
61 }
62
63 #endif /* _WIN32 */
64
65 #else
66
67 // Generic fallback that should work for any OS with decent C compiler: copy
68 // the memory and then override it with garbage to "protect" it from reading.
69
70 #include <stdlib.h>
71 #include <string.h>
72
73 void *raw_data_copy(const void* data, HPy_ssize_t size, bool write_protect) {
74 void *new_data = malloc(size);
75 memcpy(new_data, data, size);
76 return new_data;
77 }
78
79 void raw_data_protect(void* data, HPy_ssize_t size) {
80 // Override the data with some garbage in hope that the program will
81 // eventually crash or give incorrect result if it reads the garbage
82 char poison[] = {0xBA, 0xD0, 0xDA, 0x7A};
83 for (HPy_ssize_t dataIdx = 0, poisonIdx = 0; dataIdx < size; ++dataIdx) {
84 ((char*)data)[dataIdx] = poison[poisonIdx];
85 poisonIdx = (poisonIdx + 1) % sizeof(poison);
86 }
87 }
88
89 int raw_data_free(void *data, HPy_ssize_t size) {
90 free(data);
91 return 0;
92 }
93
94 #endif