Skip to content

gh-115891: Fix debug byte filling in free-threaded build #116018

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions Objects/obmalloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -2460,14 +2460,23 @@ write_size_t(void *p, size_t n)
}

static void
fill_mem_debug(debug_alloc_api_t *api, void *data, int c, size_t nbytes)
fill_mem_debug(debug_alloc_api_t *api, void *data, int c, size_t nbytes,
bool is_alloc)
{
#ifdef Py_GIL_DISABLED
if (api->api_id == 'o') {
// Don't overwrite the first few bytes of a PyObject allocation in the
// free-threaded build
_PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
size_t debug_offset = tstate->mimalloc.current_object_heap->debug_offset;
size_t debug_offset;
if (is_alloc) {
debug_offset = tstate->mimalloc.current_object_heap->debug_offset;
}
else {
char *alloc = (char *)data - 2*SST; // start of the allocation
debug_offset = _mi_ptr_page(alloc)->debug_offset;
}
debug_offset -= 2*SST; // account for pymalloc extra bytes
if (debug_offset < nbytes) {
memset((char *)data + debug_offset, c, nbytes - debug_offset);
}
Expand Down Expand Up @@ -2553,7 +2562,7 @@ _PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes)
memset(p + SST + 1, PYMEM_FORBIDDENBYTE, SST-1);

if (nbytes > 0 && !use_calloc) {
fill_mem_debug(api, data, PYMEM_CLEANBYTE, nbytes);
fill_mem_debug(api, data, PYMEM_CLEANBYTE, nbytes, true);
}

/* at tail, write pad (SST bytes) and serialno (SST bytes) */
Expand Down Expand Up @@ -2603,7 +2612,7 @@ _PyMem_DebugRawFree(void *ctx, void *p)
nbytes = read_size_t(q);
nbytes += PYMEM_DEBUG_EXTRA_BYTES - 2*SST;
memset(q, PYMEM_DEADBYTE, 2*SST);
fill_mem_debug(api, p, PYMEM_DEADBYTE, nbytes);
fill_mem_debug(api, p, PYMEM_DEADBYTE, nbytes, false);
api->alloc.free(api->alloc.ctx, q);
}

Expand Down