Repository navigation
Expand file tree
/
Copy pathmalloc.py
More file actions
185 lines (138 loc) · 4.77 KB
/
Copy pathmalloc.py
File metadata and controls
185 lines (138 loc) · 4.77 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
from __future__ import annotations
import sys
from typing import Any, Optional, TypeVar
from ._cstd import c_free, c_malloc, c_realloc
from .base_pointers import BaseAllocatedPointer, IterDereferencable
from .exceptions import AllocationError, InvalidSizeError
from .stack_pointer import StackAllocatedPointer
from .util import handle
__all__ = ("AllocatedPointer", "malloc", "free", "realloc")
T = TypeVar("T")
A = TypeVar("A", bound=BaseAllocatedPointer)
class AllocatedPointer(IterDereferencable[T], BaseAllocatedPointer[T]):
"""Pointer to allocated memory."""
def __init__(
self,
address: int,
size: int,
assigned: bool = False,
parent: AllocatedPointer[T] | None = None,
) -> None:
"""
Args:
address: Address of the allocated memory.
size: Size of the allocated memory.
assigned: Whether an object is currently inside the memory.
"""
self._address = address
self._size = size
self._freed = False
self._assigned = assigned
self._parent: AllocatedPointer[T] | None = parent
def _indexed(self, amount: int) -> AllocatedPointer[T]:
return AllocatedPointer(
self.ensure() + amount,
self.size - amount,
self.assigned,
parent=self._parent,
)
def _get_parent(self) -> AllocatedPointer[T]:
parent = self
while parent._parent:
parent = parent._parent
return parent
@property
def freed(self) -> bool:
return self._get_parent()._freed
@freed.setter
def freed(self, value: bool) -> None:
self._get_parent()._freed = value
@property
def address(self) -> Optional[int]:
return self._address
@address.setter
def address(self, value: int) -> None:
self._address = value
def __repr__(self) -> str:
return f"AllocatedPointer(address={self.address}, size={self.size})"
def __add__(self, amount: int) -> AllocatedPointer[T]:
return self._indexed(amount)
def __sub__(self, amount: int) -> AllocatedPointer[T]:
return self._indexed(amount)
@handle
def free(self) -> None:
self.ensure_valid()
c_free(self.make_ct_pointer())
self.freed = True
@handle
def __getitem__(self, index: int) -> AllocatedPointer[T]:
if not isinstance(index, int):
raise ValueError(
f"memory indices must be int, not {type(index).__name__}",
)
return self._indexed(index)
@handle
def __setitem__(self, index: int, value: T) -> None:
if not isinstance(index, int):
raise ValueError(
f"memory indices must be int, not {type(index).__name__}",
)
ptr = self._indexed(index)
ptr <<= value
def malloc(size: int) -> AllocatedPointer[Any]:
"""Allocate memory of a given size.
Args:
size: Allocation size.
Returns:
Pointer to allocated memory.
Raises:
AllocationError: Raised when allocation fails, presumably due to no memory.
Example:
```py
ptr = malloc(1)
```
""" # noqa
mem = c_malloc(size)
if not mem:
raise AllocationError("failed to allocate memory")
return AllocatedPointer(mem, size)
def free(target: BaseAllocatedPointer):
"""Equivalent to `target.free()`
Args:
target: Pointer to free.
Example:
```py
ptr = malloc(1)
free(ptr) # is the same as `ptr.free()`
```"""
target.free()
@handle
def realloc(target: A, size: int) -> A:
"""Resize a memory block created by malloc.
Args:
target: Pointer to reallocate.
size: New allocation size.
Returns:
Original object.
Raises:
InvalidSizeError: Object inside allocation is larger than attempted reallocation.
AllocationError: Raised when allocation fails, presumably due to no memory.
Example:
```py
ptr = malloc(1)
realloc(ptr, 2)
```
""" # noqa
if type(target) is StackAllocatedPointer:
raise TypeError("pointers to items on the stack may not be resized")
tsize: int = sys.getsizeof(~target)
if target.assigned and (tsize > size):
raise InvalidSizeError(
f"object inside memory is of size {tsize}, so memory cannot be set to size {size}", # noqa
)
addr = c_realloc(target.address, size)
if not addr:
raise AllocationError("failed to resize memory")
target.size = size
target.address = addr
return target