-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.occ
More file actions
126 lines (99 loc) · 2.5 KB
/
memory.occ
File metadata and controls
126 lines (99 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import syscall_x86_64 from sys;
import win_syscall_x86_64 from sys;
module std {
generic<T>
struct mem_heap {
u64 len;
T* user_p;
}
generic<T>
fn __malloc_generic(u64 len) T* {
mem_heap<T>* heap;
len = 16 + len;
len = (len + 4095) & -4096;
if is_linux64 == true {
heap = syscall_x86_64::mmap(0, len, 0x1 | 0x2, 0x20 | 0x02, -1, 0);
if (heap == -1) {
syscall_x86_64::write(1, "mmap failed\n", 12);
return 0;
}
}
else if is_win64 == true {
heap = win_syscall_x86_64::VirtualAllocEx(
-1,
0,
len,
0x3000,
0x04);
if (heap == 0) {
return 0;
}
}
heap.len = len;
heap.user_p = heap + 16;
return heap.user_p;
}
generic<T>
fn __free_generic(T* ptr) {
mem_heap<T>* heap;
if ptr == 0 {
syscall_x86_64::write(1, "nullptr in free\n", 16);
return 0;
}
heap = ptr - 16;
if is_linux64 == true {
syscall_x86_64::munmap(heap, heap.len);
}
else if is_win64 == true {
win_syscall_x86_64::VirtualFreeEx(-1, heap, 0);
}
}
generic<T>
fn __realloc_generic(T* ptr, u64 new_size) T* {
if ptr == 0 {
return __malloc_generic<T>(new_size);
}
mem_heap<T>* old_heap = ptr - 16;
u64 old_len = old_heap.len;
u64 old_user_size = old_len - 16;
T* new_ptr = __malloc_generic<T>(new_size);
if new_ptr == 0 {
return 0;
}
u64 copy_size = old_user_size;
if new_size < old_user_size {
copy_size = new_size;
}
i64 i = 0;
while i < copy_size {
i8* src = ptr + i;
i8* dst = new_ptr + i;
$dst = $src;
i += 1;
}
__free_generic<T>(ptr);
return new_ptr;
}
fn realloc(i64 ptr, u64 new_size) i64 {
return __realloc_generic<i64>(ptr, new_size);
}
fn malloc(u64 len) i64 {
return __malloc_generic<i64>(len);
}
fn free(i64 ptr) {
__free_generic<i64>(ptr);
}
}
/*fn main() {
i64 addr = 0;
i64 x = win_syscall_x86_64::VirtualAllocEx(-1, addr, 4096, 0x1000 | 0x2000, 4);
return x;
}
fn main() {
u64* p = memory::malloc<u64>(8);
i64 v = 0;
$p = 10;
v = $p;
memory::free<u64>(p);
return v;
}*/