Skip to content

Commit b2934b0

Browse files
committed
Fix integer underflow in native memory tracking
1 parent 72d62e2 commit b2934b0

File tree

1 file changed

+17
-10
lines changed
  • graalpython/com.oracle.graal.python.cext/src

1 file changed

+17
-10
lines changed

graalpython/com.oracle.graal.python.cext/src/obmalloc.c

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,11 @@ int PyTruffle_AllocMemory(size_t size) {
109109
}
110110

111111
void PyTruffle_FreeMemory(size_t size) {
112-
PyTruffle_AllocatedMemory -= size;
112+
if (PyTruffle_AllocatedMemory < size) {
113+
PyTruffle_Log(PY_TRUFFLE_LOG_INFO, "PyTruffle_FreeMemory: assertion failure: underflow of memory allocation tracking\n");
114+
PyTruffle_AllocatedMemory = size;
115+
}
116+
PyTruffle_AllocatedMemory -= size;
113117
}
114118

115119
/* This is our version of 'PyObject_Free' which is also able to free Sulong handles. */
@@ -189,22 +193,25 @@ void* PyMem_RawCalloc(size_t nelem, size_t elsize) {
189193

190194
void* PyMem_RawRealloc(void *ptr, size_t new_size) {
191195
mem_head_t* old;
196+
size_t old_size;
192197

193198
if (ptr != NULL) {
194199
old = AS_MEM_HEAD(ptr);
195-
196-
// account for the difference in size
197-
if (old->size >= new_size) {
198-
PyTruffle_FreeMemory(old->size - new_size);
199-
} else {
200-
if (PyTruffle_AllocMemory(new_size - old->size)) {
201-
return NULL;
202-
}
203-
}
200+
old_size = old->size;
204201
} else {
205202
old = NULL;
203+
old_size = 0;
206204
}
207205

206+
// account for the difference in size
207+
if (old_size >= new_size) {
208+
PyTruffle_FreeMemory(old_size - new_size);
209+
} else {
210+
if (PyTruffle_AllocMemory(new_size - old_size)) {
211+
return NULL;
212+
}
213+
}
214+
208215
mem_head_t* ptr_with_head = (mem_head_t*) realloc(old, new_size + sizeof(mem_head_t));
209216
ptr_with_head->size = new_size;
210217
return FROM_MEM_HEAD(ptr_with_head);

0 commit comments

Comments
 (0)