Skip to content

Commit adeccdc

Browse files
colesburyadorilson
authored andcommitted
pythongh-115891: Fix debug byte filling in free-threaded build (python#116018)
The previous code had two bugs. First, the debug offset in the mimalloc heap includes the two pymalloc debug words, but the pointer passed to fill_mem_debug does not include them. Second, the current object heap is correct source for allocations, but not deallocations.
1 parent 7c6c093 commit adeccdc

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

Objects/obmalloc.c

+13-4
Original file line numberDiff line numberDiff line change
@@ -2460,14 +2460,23 @@ write_size_t(void *p, size_t n)
24602460
}
24612461

24622462
static void
2463-
fill_mem_debug(debug_alloc_api_t *api, void *data, int c, size_t nbytes)
2463+
fill_mem_debug(debug_alloc_api_t *api, void *data, int c, size_t nbytes,
2464+
bool is_alloc)
24642465
{
24652466
#ifdef Py_GIL_DISABLED
24662467
if (api->api_id == 'o') {
24672468
// Don't overwrite the first few bytes of a PyObject allocation in the
24682469
// free-threaded build
24692470
_PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
2470-
size_t debug_offset = tstate->mimalloc.current_object_heap->debug_offset;
2471+
size_t debug_offset;
2472+
if (is_alloc) {
2473+
debug_offset = tstate->mimalloc.current_object_heap->debug_offset;
2474+
}
2475+
else {
2476+
char *alloc = (char *)data - 2*SST; // start of the allocation
2477+
debug_offset = _mi_ptr_page(alloc)->debug_offset;
2478+
}
2479+
debug_offset -= 2*SST; // account for pymalloc extra bytes
24712480
if (debug_offset < nbytes) {
24722481
memset((char *)data + debug_offset, c, nbytes - debug_offset);
24732482
}
@@ -2553,7 +2562,7 @@ _PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
25532562
memset(p + SST + 1, PYMEM_FORBIDDENBYTE, SST-1);
25542563

25552564
if (nbytes > 0 && !use_calloc) {
2556-
fill_mem_debug(api, data, PYMEM_CLEANBYTE, nbytes);
2565+
fill_mem_debug(api, data, PYMEM_CLEANBYTE, nbytes, true);
25572566
}
25582567

25592568
/* at tail, write pad (SST bytes) and serialno (SST bytes) */
@@ -2603,7 +2612,7 @@ _PyMem_DebugRawFree(void *ctx, void *p)
26032612
nbytes = read_size_t(q);
26042613
nbytes += PYMEM_DEBUG_EXTRA_BYTES - 2*SST;
26052614
memset(q, PYMEM_DEADBYTE, 2*SST);
2606-
fill_mem_debug(api, p, PYMEM_DEADBYTE, nbytes);
2615+
fill_mem_debug(api, p, PYMEM_DEADBYTE, nbytes, false);
26072616
api->alloc.free(api->alloc.ctx, q);
26082617
}
26092618

0 commit comments

Comments
 (0)