From a349b1724b0f66c3141ee380edcbaef532c92ef5 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 3 Jun 2026 23:58:19 +0200 Subject: [PATCH 01/42] remap --- Lib/test/test_external_inspection.py | 8 + Modules/Setup.stdlib.in | 2 +- Modules/_remote_debugging/_remote_debugging.h | 82 ++++ Modules/_remote_debugging/alias_read.c | 359 ++++++++++++++++++ Modules/_remote_debugging/frames.c | 163 ++++++++ Modules/_remote_debugging/module.c | 56 ++- Modules/_remote_debugging/threads.c | 29 ++ 7 files changed, 697 insertions(+), 2 deletions(-) create mode 100644 Modules/_remote_debugging/alias_read.c diff --git a/Lib/test/test_external_inspection.py b/Lib/test/test_external_inspection.py index d6243c3fc818ea..6a0368f58529fa 100644 --- a/Lib/test/test_external_inspection.py +++ b/Lib/test/test_external_inspection.py @@ -4470,6 +4470,14 @@ def test_get_stats(self): "batched_read_misses", "batched_read_segments_requested", "batched_read_segments_completed", + "alias_hits", + "alias_misses", + "alias_remap_failures", + "alias_validation_fails", + "alias_evictions", + "alias_identity_mismatches", + "alias_disabled_at_init", + "alias_disabled_at_runtime", "batched_read_success_rate", "batched_read_segment_completion_rate", ] diff --git a/Modules/Setup.stdlib.in b/Modules/Setup.stdlib.in index d8cd8de10dfe08..1f88e52021193f 100644 --- a/Modules/Setup.stdlib.in +++ b/Modules/Setup.stdlib.in @@ -41,7 +41,7 @@ @MODULE__PICKLE_TRUE@_pickle _pickle.c @MODULE__QUEUE_TRUE@_queue _queuemodule.c @MODULE__RANDOM_TRUE@_random _randommodule.c -@MODULE__REMOTE_DEBUGGING_TRUE@_remote_debugging _remote_debugging/module.c _remote_debugging/gc_stats.c _remote_debugging/object_reading.c _remote_debugging/code_objects.c _remote_debugging/frames.c _remote_debugging/frame_cache.c _remote_debugging/threads.c _remote_debugging/asyncio.c _remote_debugging/binary_io_writer.c _remote_debugging/binary_io_reader.c _remote_debugging/subprocess.c _remote_debugging/interpreters.c +@MODULE__REMOTE_DEBUGGING_TRUE@_remote_debugging _remote_debugging/module.c _remote_debugging/gc_stats.c _remote_debugging/object_reading.c _remote_debugging/code_objects.c _remote_debugging/frames.c _remote_debugging/frame_cache.c _remote_debugging/threads.c _remote_debugging/asyncio.c _remote_debugging/alias_read.c _remote_debugging/binary_io_writer.c _remote_debugging/binary_io_reader.c _remote_debugging/subprocess.c _remote_debugging/interpreters.c @MODULE__STRUCT_TRUE@_struct _struct.c # build supports subinterpreters diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 79fa4a92e745bd..168b2bcc75fda7 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -271,6 +271,44 @@ typedef struct { uintptr_t frame_addr; } RemoteReadPrefetch; +#if defined(__APPLE__) && TARGET_OS_OSX +typedef enum { + ALIAS_STABLE_RUNTIME, + ALIAS_TSTATE, + ALIAS_FRAME_PAGE +} AliasReadKind; + +#define MAX_ALIAS_PAGES 256 +#define ALIAS_PROBE_MASK 0x3ff +#define ALIAS_FAILURE_WINDOW 100 +#define ALIAS_FAILURE_THRESHOLD 10 + +typedef struct { + uintptr_t remote_page_base; + mach_vm_address_t local_page_base; + mach_vm_size_t size; + mach_port_t task_port; + uint64_t target_start_tvsec; + uint64_t target_start_tvusec; + uint64_t access_seq; + int valid; +} AliasPageEntry; + +typedef struct { + AliasPageEntry pages[MAX_ALIAS_PAGES]; + uint64_t access_seq; + uint64_t target_start_tvsec; + uint64_t target_start_tvusec; + uint32_t probe_counter; + uint32_t remap_failure_index; + uint32_t remap_failure_samples; + uint32_t remap_failure_count; + unsigned char remap_failure_window[ALIAS_FAILURE_WINDOW]; + int disabled_at_init; + int disabled_at_runtime; +} AliasReadCache; +#endif + /* Statistics for profiling performance analysis */ typedef struct { uint64_t total_samples; // Total number of get_stack_trace calls @@ -289,6 +327,14 @@ typedef struct { uint64_t batched_read_misses; // Attempts that fell back or partially read uint64_t batched_read_segments_requested; // Segments requested by batched reads uint64_t batched_read_segments_completed; // Segments completed by batched reads + uint64_t alias_hits; // macOS alias-cache hits + uint64_t alias_misses; // macOS alias-cache misses + uint64_t alias_remap_failures; // macOS remap/protect failures + uint64_t alias_validation_fails; // macOS alias snapshot validation failures + uint64_t alias_evictions; // macOS alias-cache LRU evictions + uint64_t alias_identity_mismatches; // macOS target identity mismatches + uint64_t alias_disabled_at_init; // macOS aliasing disabled during init (0/1) + uint64_t alias_disabled_at_runtime; // macOS aliasing disabled at runtime (0/1) } UnwinderStats; #if defined(__GNUC__) || defined(__clang__) @@ -391,6 +437,9 @@ typedef struct { #ifdef __APPLE__ uint64_t thread_id_offset; int thread_id_offset_initialized; +# if TARGET_OS_OSX + AliasReadCache alias_cache; +# endif #endif #ifdef MS_WINDOWS PVOID win_process_buffer; @@ -657,6 +706,38 @@ extern int collect_frames_with_cache( FrameWalkContext *ctx, uint64_t thread_id); +#if defined(__APPLE__) && TARGET_OS_OSX +extern int parse_frame_object_aliased( + RemoteUnwinderObject *unwinder, + uintptr_t expected_parent, + PyObject **result, + uintptr_t address, + uintptr_t *address_of_code_object, + uintptr_t *previous_frame +); + +extern int _Py_RemoteDebug_ValidateInterpreterSnapshot( + RemoteUnwinderObject *unwinder, + const char *interp_state_buffer +); +extern int _Py_RemoteDebug_ValidateThreadStateSnapshot( + RemoteUnwinderObject *unwinder, + const char *tstate_buffer, + uintptr_t tstate_addr, + uintptr_t current_interpreter +); +extern int _Py_RemoteDebug_AliasedRead( + RemoteUnwinderObject *unwinder, + AliasReadKind kind, + uintptr_t remote_addr, + size_t len, + void *dst); +extern void _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder); +extern void _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder); +extern void _Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, uintptr_t remote_addr); +extern int _Py_RemoteDebug_AliasProbe(RemoteUnwinderObject *unwinder, uintptr_t probe_addr); +#endif + /* ============================================================================ * THREAD FUNCTION DECLARATIONS * ============================================================================ */ @@ -685,6 +766,7 @@ extern int get_thread_status(RemoteUnwinderObject *unwinder, uint64_t tid, uint6 extern PyObject* unwind_stack_for_thread( RemoteUnwinderObject *unwinder, + uintptr_t current_interpreter, uintptr_t *current_tstate, uintptr_t gil_holder_tstate, uintptr_t gc_frame, diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c new file mode 100644 index 00000000000000..b7882214ad0311 --- /dev/null +++ b/Modules/_remote_debugging/alias_read.c @@ -0,0 +1,359 @@ +#include "_remote_debugging.h" + +#if defined(__APPLE__) && TARGET_OS_OSX + +#ifndef VM_FLAGS_RETURN_DATA_ADDR +# define VM_FLAGS_RETURN_DATA_ADDR 0 +#endif + +static int +alias_direct_read(RemoteUnwinderObject *unwinder, + uintptr_t remote_addr, + size_t len, + void *dst) +{ + return _Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst); +} + +static int +read_target_identity(RemoteUnwinderObject *unwinder, + uint64_t *start_tvsec, + uint64_t *start_tvusec) +{ + struct proc_bsdinfo info; + int n = proc_pidinfo(unwinder->handle.pid, PROC_PIDTBSDINFO, 0, + &info, sizeof(info)); + if (n != (int)sizeof(info)) { + return -1; + } + if (info.pbi_start_tvsec == 0 && info.pbi_start_tvusec == 0) { + return -1; + } + *start_tvsec = (uint64_t)info.pbi_start_tvsec; + *start_tvusec = (uint64_t)info.pbi_start_tvusec; + return 0; +} + +static void +alias_deallocate_entry(AliasPageEntry *entry) +{ + if (!entry->valid) { + return; + } + (void)mach_vm_deallocate(mach_task_self(), entry->local_page_base, + entry->size); + memset(entry, 0, sizeof(*entry)); +} + +void +_Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder) +{ + AliasReadCache *cache = &unwinder->alias_cache; + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + alias_deallocate_entry(&cache->pages[i]); + } +} + +static void +alias_disable_runtime(RemoteUnwinderObject *unwinder) +{ + AliasReadCache *cache = &unwinder->alias_cache; + cache->disabled_at_runtime = 1; + unwinder->stats.alias_disabled_at_runtime = 1; + _Py_RemoteDebug_AliasCacheClear(unwinder); +} + +void +_Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, + uintptr_t remote_addr) +{ + AliasReadCache *cache = &unwinder->alias_cache; + size_t page_size = (size_t)unwinder->handle.page_size; + uintptr_t page_base = remote_addr & ~(uintptr_t)(page_size - 1); + + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + AliasPageEntry *entry = &cache->pages[i]; + if (entry->valid + && entry->remote_page_base == page_base + && entry->task_port == unwinder->handle.task + && entry->target_start_tvsec == cache->target_start_tvsec + && entry->target_start_tvusec == cache->target_start_tvusec) { + alias_deallocate_entry(entry); + } + } +} + +void +_Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) +{ + AliasReadCache *cache = &unwinder->alias_cache; + memset(cache, 0, sizeof(*cache)); + + uint64_t start_tvsec = 0; + uint64_t start_tvusec = 0; + uint64_t reprobe_tvsec = 0; + uint64_t reprobe_tvusec = 0; + if (read_target_identity(unwinder, &start_tvsec, &start_tvusec) < 0 + || read_target_identity(unwinder, &reprobe_tvsec, + &reprobe_tvusec) < 0 + || start_tvsec != reprobe_tvsec + || start_tvusec != reprobe_tvusec) { + cache->disabled_at_init = 1; + } + else { + cache->target_start_tvsec = start_tvsec; + cache->target_start_tvusec = start_tvusec; + } + unwinder->stats.alias_disabled_at_init = + (uint64_t)cache->disabled_at_init; +} + +static int +alias_identity_matches(RemoteUnwinderObject *unwinder) +{ + AliasReadCache *cache = &unwinder->alias_cache; + uint64_t start_tvsec = 0; + uint64_t start_tvusec = 0; + if (read_target_identity(unwinder, &start_tvsec, &start_tvusec) < 0) { + return 0; + } + return start_tvsec == cache->target_start_tvsec + && start_tvusec == cache->target_start_tvusec; +} + +static int +alias_maybe_probe_identity(RemoteUnwinderObject *unwinder) +{ + AliasReadCache *cache = &unwinder->alias_cache; + if ((++cache->probe_counter & ALIAS_PROBE_MASK) != 0) { + return 1; + } + if (alias_identity_matches(unwinder)) { + return 1; + } + STATS_INC(unwinder, alias_identity_mismatches); + alias_disable_runtime(unwinder); + return 0; +} + +static void +alias_record_remap_outcome(RemoteUnwinderObject *unwinder, int failed) +{ + AliasReadCache *cache = &unwinder->alias_cache; + unsigned char old = cache->remap_failure_window[cache->remap_failure_index]; + if (old) { + cache->remap_failure_count--; + } + cache->remap_failure_window[cache->remap_failure_index] = + (unsigned char)(failed != 0); + if (failed) { + cache->remap_failure_count++; + } + cache->remap_failure_index = + (cache->remap_failure_index + 1) % ALIAS_FAILURE_WINDOW; + if (cache->remap_failure_samples < ALIAS_FAILURE_WINDOW) { + cache->remap_failure_samples++; + } + + if (cache->remap_failure_samples == ALIAS_FAILURE_WINDOW + && cache->remap_failure_count >= ALIAS_FAILURE_THRESHOLD) { + alias_disable_runtime(unwinder); + } +} + +static AliasPageEntry * +alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) +{ + AliasReadCache *cache = &unwinder->alias_cache; + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + AliasPageEntry *entry = &cache->pages[i]; + if (entry->valid + && entry->remote_page_base == page_base + && entry->task_port == unwinder->handle.task + && entry->target_start_tvsec == cache->target_start_tvsec + && entry->target_start_tvusec == cache->target_start_tvusec) { + return entry; + } + } + return NULL; +} + +static AliasPageEntry * +alias_alloc_entry(RemoteUnwinderObject *unwinder) +{ + AliasReadCache *cache = &unwinder->alias_cache; + AliasPageEntry *oldest = NULL; + + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + AliasPageEntry *entry = &cache->pages[i]; + if (!entry->valid) { + return entry; + } + if (oldest == NULL || entry->access_seq < oldest->access_seq) { + oldest = entry; + } + } + + assert(oldest != NULL); + alias_deallocate_entry(oldest); + STATS_INC(unwinder, alias_evictions); + return oldest; +} + +static int +alias_remap_page(RemoteUnwinderObject *unwinder, + uintptr_t page_base, + AliasPageEntry **entry_out) +{ + AliasReadCache *cache = &unwinder->alias_cache; + mach_vm_size_t page_size = (mach_vm_size_t)unwinder->handle.page_size; + mach_vm_address_t local_addr = 0; + vm_prot_t cur_protection = VM_PROT_NONE; + vm_prot_t max_protection = VM_PROT_NONE; + + kern_return_t kr = mach_vm_remap( + mach_task_self(), + &local_addr, + page_size, + 0, + VM_FLAGS_ANYWHERE | VM_FLAGS_RETURN_DATA_ADDR, + unwinder->handle.task, + (mach_vm_address_t)page_base, + FALSE, + &cur_protection, + &max_protection, + VM_INHERIT_NONE); + if (kr != KERN_SUCCESS) { + STATS_INC(unwinder, alias_remap_failures); + alias_record_remap_outcome(unwinder, 1); + return -1; + } + if ((cur_protection & VM_PROT_READ) == 0) { + (void)mach_vm_deallocate(mach_task_self(), local_addr, page_size); + STATS_INC(unwinder, alias_remap_failures); + alias_record_remap_outcome(unwinder, 1); + return -1; + } + + kr = mach_vm_protect(mach_task_self(), local_addr, page_size, FALSE, + VM_PROT_READ); + if (kr != KERN_SUCCESS) { + (void)mach_vm_deallocate(mach_task_self(), local_addr, page_size); + STATS_INC(unwinder, alias_remap_failures); + alias_record_remap_outcome(unwinder, 1); + return -1; + } + + AliasPageEntry *entry = alias_alloc_entry(unwinder); + memset(entry, 0, sizeof(*entry)); + entry->remote_page_base = page_base; + entry->local_page_base = local_addr; + entry->size = page_size; + entry->task_port = unwinder->handle.task; + entry->target_start_tvsec = cache->target_start_tvsec; + entry->target_start_tvusec = cache->target_start_tvusec; + entry->access_seq = ++cache->access_seq; + entry->valid = 1; + + alias_record_remap_outcome(unwinder, 0); + *entry_out = entry; + return 0; +} + +int +_Py_RemoteDebug_AliasProbe(RemoteUnwinderObject *unwinder, + uintptr_t probe_addr) +{ + AliasReadCache *cache = &unwinder->alias_cache; + if (cache->disabled_at_init || cache->disabled_at_runtime) { + return -1; + } + + size_t page_size = (size_t)unwinder->handle.page_size; + uintptr_t page_base = probe_addr & ~(uintptr_t)(page_size - 1); + mach_vm_address_t local_addr = 0; + vm_prot_t cur_protection = VM_PROT_NONE; + vm_prot_t max_protection = VM_PROT_NONE; + kern_return_t kr = mach_vm_remap( + mach_task_self(), + &local_addr, + (mach_vm_size_t)page_size, + 0, + VM_FLAGS_ANYWHERE | VM_FLAGS_RETURN_DATA_ADDR, + unwinder->handle.task, + (mach_vm_address_t)page_base, + FALSE, + &cur_protection, + &max_protection, + VM_INHERIT_NONE); + if (kr != KERN_SUCCESS || (cur_protection & VM_PROT_READ) == 0) { + if (kr == KERN_SUCCESS) { + (void)mach_vm_deallocate(mach_task_self(), local_addr, + (mach_vm_size_t)page_size); + } + STATS_INC(unwinder, alias_remap_failures); + alias_record_remap_outcome(unwinder, 1); + return -1; + } + + kr = mach_vm_protect(mach_task_self(), local_addr, + (mach_vm_size_t)page_size, FALSE, VM_PROT_READ); + (void)mach_vm_deallocate(mach_task_self(), local_addr, + (mach_vm_size_t)page_size); + if (kr != KERN_SUCCESS) { + STATS_INC(unwinder, alias_remap_failures); + alias_record_remap_outcome(unwinder, 1); + return -1; + } + + alias_record_remap_outcome(unwinder, 0); + return 0; +} + +int +_Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, + AliasReadKind kind, + uintptr_t remote_addr, + size_t len, + void *dst) +{ + (void)kind; + AliasReadCache *cache = &unwinder->alias_cache; + if (len == 0) { + return 0; + } + if (cache->disabled_at_init || cache->disabled_at_runtime) { + return alias_direct_read(unwinder, remote_addr, len, dst); + } + + size_t page_size = (size_t)unwinder->handle.page_size; + uintptr_t page_base = remote_addr & ~(uintptr_t)(page_size - 1); + size_t offset = (size_t)(remote_addr - page_base); + if (offset >= page_size || len > page_size - offset) { + return alias_direct_read(unwinder, remote_addr, len, dst); + } + + AliasPageEntry *entry = alias_find_entry(unwinder, page_base); + if (entry != NULL) { + if (!alias_maybe_probe_identity(unwinder)) { + return alias_direct_read(unwinder, remote_addr, len, dst); + } + entry->access_seq = ++cache->access_seq; + memcpy(dst, (const char *)entry->local_page_base + offset, len); + STATS_INC(unwinder, alias_hits); + return 0; + } + + STATS_INC(unwinder, alias_misses); + if (alias_remap_page(unwinder, page_base, &entry) < 0) { + return alias_direct_read(unwinder, remote_addr, len, dst); + } + if (cache->disabled_at_runtime) { + return alias_direct_read(unwinder, remote_addr, len, dst); + } + memcpy(dst, (const char *)entry->local_page_base + offset, len); + return 0; +} + +#endif /* defined(__APPLE__) && TARGET_OS_OSX */ diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index f5b9ed72f1f98e..b57286810473be 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -227,6 +227,148 @@ parse_frame_buffer( return parse_code_object(unwinder, result, &code_ctx); } +#if defined(__APPLE__) && TARGET_OS_OSX +static int +remote_pointer_plausible(RemoteUnwinderObject *unwinder, uintptr_t ptr) +{ + if (ptr == 0) { + return 1; + } + if ((ptr & (uintptr_t)(sizeof(void *) - 1)) != 0) { + return 0; + } + if (ptr < (uintptr_t)unwinder->handle.page_size) { + return 0; + } +#if UINTPTR_MAX > 0xffffffffU +# if defined(__x86_64__) + if (ptr >= (1ULL << 47)) { + return 0; + } +# elif defined(__arm64__) || defined(__aarch64__) + if ((ptr >> 56) != 0) { + return 0; + } +# else + if (ptr >= (UINTPTR_MAX >> 1)) { + return 0; + } +# endif +#endif + return 1; +} + +int +_Py_RemoteDebug_ValidateInterpreterSnapshot( + RemoteUnwinderObject *unwinder, + const char *interp_state_buffer) +{ + uintptr_t threads_head = GET_MEMBER(uintptr_t, interp_state_buffer, + unwinder->debug_offsets.interpreter_state.threads_head); + uintptr_t threads_main = GET_MEMBER(uintptr_t, interp_state_buffer, + unwinder->debug_offsets.interpreter_state.threads_main); + uintptr_t next = GET_MEMBER(uintptr_t, interp_state_buffer, + unwinder->debug_offsets.interpreter_state.next); + uintptr_t gil_holder_tstate = GET_MEMBER(uintptr_t, interp_state_buffer, + unwinder->debug_offsets.interpreter_state.gil_runtime_state_holder); + uintptr_t gc_frame = GET_MEMBER(uintptr_t, interp_state_buffer, + unwinder->debug_offsets.interpreter_state.gc + + unwinder->debug_offsets.gc.frame); + + return remote_pointer_plausible(unwinder, threads_head) + && remote_pointer_plausible(unwinder, threads_main) + && remote_pointer_plausible(unwinder, next) + && remote_pointer_plausible(unwinder, gil_holder_tstate) + && remote_pointer_plausible(unwinder, gc_frame); +} + +int +_Py_RemoteDebug_ValidateThreadStateSnapshot( + RemoteUnwinderObject *unwinder, + const char *tstate_buffer, + uintptr_t tstate_addr, + uintptr_t current_interpreter) +{ + uintptr_t interp = GET_MEMBER(uintptr_t, tstate_buffer, + unwinder->debug_offsets.thread_state.interp); + if (interp != current_interpreter) { + return 0; + } + + uintptr_t current_frame = GET_MEMBER(uintptr_t, tstate_buffer, + unwinder->debug_offsets.thread_state.current_frame); + uintptr_t base_frame = GET_MEMBER(uintptr_t, tstate_buffer, + unwinder->debug_offsets.thread_state.base_frame); + uintptr_t next = GET_MEMBER(uintptr_t, tstate_buffer, + unwinder->debug_offsets.thread_state.next); + uintptr_t last_profiled_frame = GET_MEMBER(uintptr_t, tstate_buffer, + unwinder->debug_offsets.thread_state.last_profiled_frame); + + return next != tstate_addr + && remote_pointer_plausible(unwinder, current_frame) + && remote_pointer_plausible(unwinder, base_frame) + && remote_pointer_plausible(unwinder, next) + && remote_pointer_plausible(unwinder, last_profiled_frame); +} + +static int +validate_frame_snapshot( + RemoteUnwinderObject *unwinder, + const char *frame, + uintptr_t expected_parent) +{ + int owner = (unsigned char)GET_MEMBER(char, frame, + unwinder->debug_offsets.interpreter_frame.owner); + if (owner < FRAME_OWNED_BY_THREAD || owner > FRAME_OWNED_BY_INTERPRETER) { + return 0; + } + + uintptr_t executable = GET_MEMBER_NO_TAG(uintptr_t, frame, + unwinder->debug_offsets.interpreter_frame.executable); + uintptr_t previous = GET_MEMBER(uintptr_t, frame, + unwinder->debug_offsets.interpreter_frame.previous); + if (!remote_pointer_plausible(unwinder, executable) + || !remote_pointer_plausible(unwinder, previous)) { + return 0; + } + if (expected_parent != 0 && previous != expected_parent) { + return 0; + } + return 1; +} + +int +parse_frame_object_aliased( + RemoteUnwinderObject *unwinder, + uintptr_t expected_parent, + PyObject **result, + uintptr_t address, + uintptr_t *address_of_code_object, + uintptr_t *previous_frame) +{ + char frame[SIZEOF_INTERP_FRAME]; + if (_Py_RemoteDebug_AliasedRead( + unwinder, ALIAS_FRAME_PAGE, address, SIZEOF_INTERP_FRAME, + frame) < 0) { + set_exception_cause(unwinder, PyExc_RuntimeError, + "Failed to read interpreter frame"); + return -1; + } + STATS_INC(unwinder, memory_reads); + STATS_ADD(unwinder, memory_bytes_read, SIZEOF_INTERP_FRAME); + + if (!validate_frame_snapshot(unwinder, frame, expected_parent)) { + STATS_INC(unwinder, alias_validation_fails); + _Py_RemoteDebug_AliasCacheInvalidatePage(unwinder, address); + return parse_frame_object(unwinder, result, address, + address_of_code_object, previous_frame); + } + + return parse_frame_buffer(unwinder, result, frame, + address_of_code_object, previous_frame); +} +#endif + int parse_frame_object( RemoteUnwinderObject *unwinder, @@ -342,9 +484,19 @@ process_frame_chain( &address_of_code_object, &next_frame_addr); } else { +#if defined(__APPLE__) && TARGET_OS_OSX + if (unwinder->cache_frames) { + parse_result = parse_frame_object_aliased( + unwinder, 0, &frame, frame_addr, + &address_of_code_object, &next_frame_addr); + } + else +#endif + { parse_result = parse_frame_object( unwinder, &frame, frame_addr, &address_of_code_object, &next_frame_addr); + } } if (parse_result < 0) { set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to parse frame object in chain"); @@ -545,6 +697,7 @@ try_full_cache_hit( PyObject *current_frame = NULL; uintptr_t code_object_addr = 0; uintptr_t previous_frame = 0; + uintptr_t expected_parent = entry->num_addrs >= 2 ? entry->addrs[1] : 0; int parse_result; if (ctx->prefetch.frame && ctx->prefetch.frame_addr == ctx->frame_addr) { parse_result = parse_frame_buffer(unwinder, ¤t_frame, @@ -552,8 +705,18 @@ try_full_cache_hit( &code_object_addr, &previous_frame); } else { +#if defined(__APPLE__) && TARGET_OS_OSX + if (unwinder->cache_frames) { + parse_result = parse_frame_object_aliased( + unwinder, expected_parent, ¤t_frame, ctx->frame_addr, + &code_object_addr, &previous_frame); + } + else +#endif + { parse_result = parse_frame_object(unwinder, ¤t_frame, ctx->frame_addr, &code_object_addr, &previous_frame); + } } if (parse_result < 0) { return -1; diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index efb6d600247bf7..1752dd9e6bab29 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -383,6 +383,9 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, set_exception_cause(self, PyExc_RuntimeError, "Failed to initialize process handle"); return -1; } +#if defined(__APPLE__) && TARGET_OS_OSX + _Py_RemoteDebug_AliasCacheInit(self); +#endif self->runtime_start_address = _Py_RemoteDebug_GetPyRuntimeAddress(&self->handle); if (self->runtime_start_address == 0) { @@ -425,6 +428,9 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, set_exception_cause(self, PyExc_RuntimeError, "Failed to populate initial state data"); return -1; } +#if defined(__APPLE__) && TARGET_OS_OSX + (void)_Py_RemoteDebug_AliasProbe(self, self->interpreter_addr); +#endif self->code_object_cache = _Py_hashtable_new_full( _Py_hashtable_hash_ptr, @@ -608,6 +614,30 @@ read_interp_state_and_maybe_thread_frame( { prefetch->tstate = NULL; prefetch->frame = NULL; +#if defined(__APPLE__) && TARGET_OS_OSX + if (unwinder->cache_frames) { + if (_Py_RemoteDebug_AliasedRead( + unwinder, + ALIAS_STABLE_RUNTIME, + interpreter_addr, + INTERP_STATE_BUFFER_SIZE, + interp_state_buffer) < 0) { + return -1; + } + if (!_Py_RemoteDebug_ValidateInterpreterSnapshot( + unwinder, interp_state_buffer)) { + STATS_INC(unwinder, alias_validation_fails); + _Py_RemoteDebug_AliasCacheInvalidatePage(unwinder, + interpreter_addr); + return _Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, + interpreter_addr, + INTERP_STATE_BUFFER_SIZE, + interp_state_buffer); + } + return 0; + } +#endif if (prefetch->tstate_addr != 0) { size_t tstate_size = (size_t)unwinder->debug_offsets.thread_state.size; _Py_RemoteReadSegment segments[3] = { @@ -801,7 +831,9 @@ _remote_debugging_RemoteUnwinder_get_stack_trace_impl(RemoteUnwinderObject *self while (current_tstate != 0) { uintptr_t prev_tstate = current_tstate; - PyObject* frame_info = unwind_stack_for_thread(self, ¤t_tstate, + PyObject* frame_info = unwind_stack_for_thread(self, + current_interpreter, + ¤t_tstate, gil_holder_tstate, gc_frame, main_thread_tstate, @@ -1110,6 +1142,17 @@ RemoteUnwinder was created with stats=True. batched reads - batched_read_segments_completed: Segments completed by batched reads + - alias_hits: macOS alias-cache hits + - alias_misses: macOS alias-cache misses + - alias_remap_failures: macOS remap/protect failures + - alias_validation_fails: macOS alias snapshot validation + failures + - alias_evictions: macOS alias-cache LRU evictions + - alias_identity_mismatches: macOS target identity mismatches + - alias_disabled_at_init: Whether aliasing was disabled + during initialization + - alias_disabled_at_runtime: Whether aliasing was disabled + at runtime - frame_cache_hit_rate: Percentage of samples that hit the cache - code_object_cache_hit_rate: Percentage of code object @@ -1165,6 +1208,14 @@ _remote_debugging_RemoteUnwinder_get_stats_impl(RemoteUnwinderObject *self) ADD_STAT(batched_read_misses); ADD_STAT(batched_read_segments_requested); ADD_STAT(batched_read_segments_completed); + ADD_STAT(alias_hits); + ADD_STAT(alias_misses); + ADD_STAT(alias_remap_failures); + ADD_STAT(alias_validation_fails); + ADD_STAT(alias_evictions); + ADD_STAT(alias_identity_mismatches); + ADD_STAT(alias_disabled_at_init); + ADD_STAT(alias_disabled_at_runtime); #undef ADD_STAT @@ -1331,6 +1382,9 @@ RemoteUnwinder_dealloc(PyObject *op) if (self->tlbc_cache) { _Py_hashtable_destroy(self->tlbc_cache); } +#endif +#if defined(__APPLE__) && TARGET_OS_OSX + _Py_RemoteDebug_AliasCacheClear(self); #endif if (self->handle.pid != 0) { _Py_RemoteDebug_ClearCache(&self->handle); diff --git a/Modules/_remote_debugging/threads.c b/Modules/_remote_debugging/threads.c index 120065022ddc8e..d605ef571f276f 100644 --- a/Modules/_remote_debugging/threads.c +++ b/Modules/_remote_debugging/threads.c @@ -296,6 +296,7 @@ typedef struct { static int read_thread_state_and_maybe_frame( RemoteUnwinderObject *unwinder, + uintptr_t current_interpreter, uintptr_t tstate_addr, size_t tstate_size, char *tstate_buffer, @@ -304,6 +305,29 @@ read_thread_state_and_maybe_frame( int *frame_read) { *frame_read = 0; +#if defined(__APPLE__) && TARGET_OS_OSX + if (unwinder->cache_frames) { + if (_Py_RemoteDebug_AliasedRead( + unwinder, + ALIAS_TSTATE, + tstate_addr, + tstate_size, + tstate_buffer) < 0) { + return -1; + } + if (!_Py_RemoteDebug_ValidateThreadStateSnapshot( + unwinder, tstate_buffer, tstate_addr, + current_interpreter)) { + STATS_INC(unwinder, alias_validation_fails); + _Py_RemoteDebug_AliasCacheInvalidatePage(unwinder, tstate_addr); + return _Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, tstate_addr, tstate_size, tstate_buffer); + } + return 0; + } +#else + (void)current_interpreter; +#endif if (predicted_frame_addr != 0) { _Py_RemoteReadSegment segments[2] = { {tstate_addr, tstate_buffer, tstate_size}, @@ -331,12 +355,16 @@ read_thread_state_and_maybe_frame( PyObject* unwind_stack_for_thread( RemoteUnwinderObject *unwinder, + uintptr_t current_interpreter, uintptr_t *current_tstate, uintptr_t gil_holder_tstate, uintptr_t gc_frame, uintptr_t main_thread_tstate, const RemoteReadPrefetch *prefetch ) { +#if !defined(__APPLE__) || !TARGET_OS_OSX + (void)current_interpreter; +#endif PyObject *frame_info = NULL; PyObject *thread_id = NULL; PyObject *result = NULL; @@ -363,6 +391,7 @@ unwind_stack_for_thread( int rc = read_thread_state_and_maybe_frame( unwinder, + current_interpreter, *current_tstate, (size_t)unwinder->debug_offsets.thread_state.size, local_ts, From 8a748a47280acb80db3f3a4fe7a701dd74924462 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 00:36:34 +0200 Subject: [PATCH 02/42] no kind for now --- Modules/_remote_debugging/_remote_debugging.h | 7 ------- Modules/_remote_debugging/alias_read.c | 2 -- Modules/_remote_debugging/frames.c | 2 +- Modules/_remote_debugging/module.c | 1 - Modules/_remote_debugging/threads.c | 1 - 5 files changed, 1 insertion(+), 12 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 168b2bcc75fda7..08473121d22989 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -272,12 +272,6 @@ typedef struct { } RemoteReadPrefetch; #if defined(__APPLE__) && TARGET_OS_OSX -typedef enum { - ALIAS_STABLE_RUNTIME, - ALIAS_TSTATE, - ALIAS_FRAME_PAGE -} AliasReadKind; - #define MAX_ALIAS_PAGES 256 #define ALIAS_PROBE_MASK 0x3ff #define ALIAS_FAILURE_WINDOW 100 @@ -728,7 +722,6 @@ extern int _Py_RemoteDebug_ValidateThreadStateSnapshot( ); extern int _Py_RemoteDebug_AliasedRead( RemoteUnwinderObject *unwinder, - AliasReadKind kind, uintptr_t remote_addr, size_t len, void *dst); diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index b7882214ad0311..0fa8e6327f19ea 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -313,12 +313,10 @@ _Py_RemoteDebug_AliasProbe(RemoteUnwinderObject *unwinder, int _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, - AliasReadKind kind, uintptr_t remote_addr, size_t len, void *dst) { - (void)kind; AliasReadCache *cache = &unwinder->alias_cache; if (len == 0) { return 0; diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index b57286810473be..9678ff340bc697 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -348,7 +348,7 @@ parse_frame_object_aliased( { char frame[SIZEOF_INTERP_FRAME]; if (_Py_RemoteDebug_AliasedRead( - unwinder, ALIAS_FRAME_PAGE, address, SIZEOF_INTERP_FRAME, + unwinder, address, SIZEOF_INTERP_FRAME, frame) < 0) { set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read interpreter frame"); diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 1752dd9e6bab29..253af97b3f5190 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -618,7 +618,6 @@ read_interp_state_and_maybe_thread_frame( if (unwinder->cache_frames) { if (_Py_RemoteDebug_AliasedRead( unwinder, - ALIAS_STABLE_RUNTIME, interpreter_addr, INTERP_STATE_BUFFER_SIZE, interp_state_buffer) < 0) { diff --git a/Modules/_remote_debugging/threads.c b/Modules/_remote_debugging/threads.c index d605ef571f276f..82663d0a91a5f7 100644 --- a/Modules/_remote_debugging/threads.c +++ b/Modules/_remote_debugging/threads.c @@ -309,7 +309,6 @@ read_thread_state_and_maybe_frame( if (unwinder->cache_frames) { if (_Py_RemoteDebug_AliasedRead( unwinder, - ALIAS_TSTATE, tstate_addr, tstate_size, tstate_buffer) < 0) { From 69848a408b955b7ba4fa94c083995bda844dbedc Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 00:44:04 +0200 Subject: [PATCH 03/42] simpler --- Modules/_remote_debugging/alias_read.c | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 0fa8e6327f19ea..f2759745f6dea1 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -92,13 +92,7 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) uint64_t start_tvsec = 0; uint64_t start_tvusec = 0; - uint64_t reprobe_tvsec = 0; - uint64_t reprobe_tvusec = 0; - if (read_target_identity(unwinder, &start_tvsec, &start_tvusec) < 0 - || read_target_identity(unwinder, &reprobe_tvsec, - &reprobe_tvusec) < 0 - || start_tvsec != reprobe_tvsec - || start_tvusec != reprobe_tvusec) { + if (read_target_identity(unwinder, &start_tvsec, &start_tvusec) < 0) { cache->disabled_at_init = 1; } else { From dcdcaf45c70528aaf80d9781bdd621e7f903ebfe Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 00:44:14 +0200 Subject: [PATCH 04/42] do not continue if the probe failed --- Modules/_remote_debugging/module.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 253af97b3f5190..e64c418e63d1b5 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -429,7 +429,10 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, return -1; } #if defined(__APPLE__) && TARGET_OS_OSX - (void)_Py_RemoteDebug_AliasProbe(self, self->interpreter_addr); + if (_Py_RemoteDebug_AliasProbe(self, self->interpreter_addr) < 0) { + self->alias_cache.disabled_at_init = 1; + self->stats.alias_disabled_at_init = 1; + } #endif self->code_object_cache = _Py_hashtable_new_full( From 1574e871c2a1fa1e969a29559b5988bb2f80873a Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 00:46:28 +0200 Subject: [PATCH 05/42] left-over --- Modules/_remote_debugging/_remote_debugging.h | 2 -- Modules/_remote_debugging/alias_read.c | 23 ++++++------------- 2 files changed, 7 insertions(+), 18 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 08473121d22989..98bec431f21aea 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -283,7 +283,6 @@ typedef struct { mach_vm_size_t size; mach_port_t task_port; uint64_t target_start_tvsec; - uint64_t target_start_tvusec; uint64_t access_seq; int valid; } AliasPageEntry; @@ -292,7 +291,6 @@ typedef struct { AliasPageEntry pages[MAX_ALIAS_PAGES]; uint64_t access_seq; uint64_t target_start_tvsec; - uint64_t target_start_tvusec; uint32_t probe_counter; uint32_t remap_failure_index; uint32_t remap_failure_samples; diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index f2759745f6dea1..f2d62bc8a3c135 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -18,8 +18,7 @@ alias_direct_read(RemoteUnwinderObject *unwinder, static int read_target_identity(RemoteUnwinderObject *unwinder, - uint64_t *start_tvsec, - uint64_t *start_tvusec) + uint64_t *start_tvsec) { struct proc_bsdinfo info; int n = proc_pidinfo(unwinder->handle.pid, PROC_PIDTBSDINFO, 0, @@ -27,11 +26,10 @@ read_target_identity(RemoteUnwinderObject *unwinder, if (n != (int)sizeof(info)) { return -1; } - if (info.pbi_start_tvsec == 0 && info.pbi_start_tvusec == 0) { + if (info.pbi_start_tvsec == 0) { return -1; } *start_tvsec = (uint64_t)info.pbi_start_tvsec; - *start_tvusec = (uint64_t)info.pbi_start_tvusec; return 0; } @@ -77,8 +75,7 @@ _Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, if (entry->valid && entry->remote_page_base == page_base && entry->task_port == unwinder->handle.task - && entry->target_start_tvsec == cache->target_start_tvsec - && entry->target_start_tvusec == cache->target_start_tvusec) { + && entry->target_start_tvsec == cache->target_start_tvsec) { alias_deallocate_entry(entry); } } @@ -91,13 +88,11 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) memset(cache, 0, sizeof(*cache)); uint64_t start_tvsec = 0; - uint64_t start_tvusec = 0; - if (read_target_identity(unwinder, &start_tvsec, &start_tvusec) < 0) { + if (read_target_identity(unwinder, &start_tvsec) < 0) { cache->disabled_at_init = 1; } else { cache->target_start_tvsec = start_tvsec; - cache->target_start_tvusec = start_tvusec; } unwinder->stats.alias_disabled_at_init = (uint64_t)cache->disabled_at_init; @@ -108,12 +103,10 @@ alias_identity_matches(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; uint64_t start_tvsec = 0; - uint64_t start_tvusec = 0; - if (read_target_identity(unwinder, &start_tvsec, &start_tvusec) < 0) { + if (read_target_identity(unwinder, &start_tvsec) < 0) { return 0; } - return start_tvsec == cache->target_start_tvsec - && start_tvusec == cache->target_start_tvusec; + return start_tvsec == cache->target_start_tvsec; } static int @@ -165,8 +158,7 @@ alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) if (entry->valid && entry->remote_page_base == page_base && entry->task_port == unwinder->handle.task - && entry->target_start_tvsec == cache->target_start_tvsec - && entry->target_start_tvusec == cache->target_start_tvusec) { + && entry->target_start_tvsec == cache->target_start_tvsec) { return entry; } } @@ -246,7 +238,6 @@ alias_remap_page(RemoteUnwinderObject *unwinder, entry->size = page_size; entry->task_port = unwinder->handle.task; entry->target_start_tvsec = cache->target_start_tvsec; - entry->target_start_tvusec = cache->target_start_tvusec; entry->access_seq = ++cache->access_seq; entry->valid = 1; From 835d0709e1a7f078a211d745572f5dfd28ae8a46 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 00:54:40 +0200 Subject: [PATCH 06/42] this is implicit from the RemoteUnwinder --- Modules/_remote_debugging/_remote_debugging.h | 2 -- Modules/_remote_debugging/alias_read.c | 12 ++---------- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 98bec431f21aea..72576f003e5a9f 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -281,8 +281,6 @@ typedef struct { uintptr_t remote_page_base; mach_vm_address_t local_page_base; mach_vm_size_t size; - mach_port_t task_port; - uint64_t target_start_tvsec; uint64_t access_seq; int valid; } AliasPageEntry; diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index f2d62bc8a3c135..d4b0cbfec640fe 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -72,10 +72,7 @@ _Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, for (int i = 0; i < MAX_ALIAS_PAGES; i++) { AliasPageEntry *entry = &cache->pages[i]; - if (entry->valid - && entry->remote_page_base == page_base - && entry->task_port == unwinder->handle.task - && entry->target_start_tvsec == cache->target_start_tvsec) { + if (entry->valid && entry->remote_page_base == page_base) { alias_deallocate_entry(entry); } } @@ -155,10 +152,7 @@ alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) AliasReadCache *cache = &unwinder->alias_cache; for (int i = 0; i < MAX_ALIAS_PAGES; i++) { AliasPageEntry *entry = &cache->pages[i]; - if (entry->valid - && entry->remote_page_base == page_base - && entry->task_port == unwinder->handle.task - && entry->target_start_tvsec == cache->target_start_tvsec) { + if (entry->valid && entry->remote_page_base == page_base) { return entry; } } @@ -236,8 +230,6 @@ alias_remap_page(RemoteUnwinderObject *unwinder, entry->remote_page_base = page_base; entry->local_page_base = local_addr; entry->size = page_size; - entry->task_port = unwinder->handle.task; - entry->target_start_tvsec = cache->target_start_tvsec; entry->access_seq = ++cache->access_seq; entry->valid = 1; From 9177fdd21f8649e3a27227ba9171ca01f33205aa Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 01:00:43 +0200 Subject: [PATCH 07/42] use _Py_RemoteDebug_ReadRemoteMemory directly --- Modules/_remote_debugging/_remote_debugging.h | 3 +- Modules/_remote_debugging/alias_read.c | 36 +++++++------------ Modules/_remote_debugging/module.c | 2 +- 3 files changed, 15 insertions(+), 26 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 72576f003e5a9f..bfbb33af2b4048 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -294,8 +294,7 @@ typedef struct { uint32_t remap_failure_samples; uint32_t remap_failure_count; unsigned char remap_failure_window[ALIAS_FAILURE_WINDOW]; - int disabled_at_init; - int disabled_at_runtime; + int disabled; } AliasReadCache; #endif diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index d4b0cbfec640fe..a8f95de75801da 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -6,16 +6,6 @@ # define VM_FLAGS_RETURN_DATA_ADDR 0 #endif -static int -alias_direct_read(RemoteUnwinderObject *unwinder, - uintptr_t remote_addr, - size_t len, - void *dst) -{ - return _Py_RemoteDebug_ReadRemoteMemory( - &unwinder->handle, remote_addr, len, dst); -} - static int read_target_identity(RemoteUnwinderObject *unwinder, uint64_t *start_tvsec) @@ -57,7 +47,7 @@ static void alias_disable_runtime(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; - cache->disabled_at_runtime = 1; + cache->disabled = 1; unwinder->stats.alias_disabled_at_runtime = 1; _Py_RemoteDebug_AliasCacheClear(unwinder); } @@ -86,13 +76,12 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) uint64_t start_tvsec = 0; if (read_target_identity(unwinder, &start_tvsec) < 0) { - cache->disabled_at_init = 1; + cache->disabled = 1; + unwinder->stats.alias_disabled_at_init = 1; } else { cache->target_start_tvsec = start_tvsec; } - unwinder->stats.alias_disabled_at_init = - (uint64_t)cache->disabled_at_init; } static int @@ -243,7 +232,7 @@ _Py_RemoteDebug_AliasProbe(RemoteUnwinderObject *unwinder, uintptr_t probe_addr) { AliasReadCache *cache = &unwinder->alias_cache; - if (cache->disabled_at_init || cache->disabled_at_runtime) { + if (cache->disabled) { return -1; } @@ -298,21 +287,24 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, if (len == 0) { return 0; } - if (cache->disabled_at_init || cache->disabled_at_runtime) { - return alias_direct_read(unwinder, remote_addr, len, dst); + if (cache->disabled) { + return _Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst); } size_t page_size = (size_t)unwinder->handle.page_size; uintptr_t page_base = remote_addr & ~(uintptr_t)(page_size - 1); size_t offset = (size_t)(remote_addr - page_base); if (offset >= page_size || len > page_size - offset) { - return alias_direct_read(unwinder, remote_addr, len, dst); + return _Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst); } AliasPageEntry *entry = alias_find_entry(unwinder, page_base); if (entry != NULL) { if (!alias_maybe_probe_identity(unwinder)) { - return alias_direct_read(unwinder, remote_addr, len, dst); + return _Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst); } entry->access_seq = ++cache->access_seq; memcpy(dst, (const char *)entry->local_page_base + offset, len); @@ -322,10 +314,8 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, STATS_INC(unwinder, alias_misses); if (alias_remap_page(unwinder, page_base, &entry) < 0) { - return alias_direct_read(unwinder, remote_addr, len, dst); - } - if (cache->disabled_at_runtime) { - return alias_direct_read(unwinder, remote_addr, len, dst); + return _Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst); } memcpy(dst, (const char *)entry->local_page_base + offset, len); return 0; diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index e64c418e63d1b5..2f1b0f33308391 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -430,7 +430,7 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, } #if defined(__APPLE__) && TARGET_OS_OSX if (_Py_RemoteDebug_AliasProbe(self, self->interpreter_addr) < 0) { - self->alias_cache.disabled_at_init = 1; + self->alias_cache.disabled = 1; self->stats.alias_disabled_at_init = 1; } #endif From 0ac2c111401e6857f65711b8ac0ed9fab20decd2 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 01:06:33 +0200 Subject: [PATCH 08/42] disable on remap failure immediately --- Modules/_remote_debugging/_remote_debugging.h | 6 ---- Modules/_remote_debugging/alias_read.c | 36 ++----------------- 2 files changed, 3 insertions(+), 39 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index bfbb33af2b4048..1530d8afec7595 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -274,8 +274,6 @@ typedef struct { #if defined(__APPLE__) && TARGET_OS_OSX #define MAX_ALIAS_PAGES 256 #define ALIAS_PROBE_MASK 0x3ff -#define ALIAS_FAILURE_WINDOW 100 -#define ALIAS_FAILURE_THRESHOLD 10 typedef struct { uintptr_t remote_page_base; @@ -290,10 +288,6 @@ typedef struct { uint64_t access_seq; uint64_t target_start_tvsec; uint32_t probe_counter; - uint32_t remap_failure_index; - uint32_t remap_failure_samples; - uint32_t remap_failure_count; - unsigned char remap_failure_window[ALIAS_FAILURE_WINDOW]; int disabled; } AliasReadCache; #endif diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index a8f95de75801da..67b3af57cbc872 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -110,31 +110,6 @@ alias_maybe_probe_identity(RemoteUnwinderObject *unwinder) return 0; } -static void -alias_record_remap_outcome(RemoteUnwinderObject *unwinder, int failed) -{ - AliasReadCache *cache = &unwinder->alias_cache; - unsigned char old = cache->remap_failure_window[cache->remap_failure_index]; - if (old) { - cache->remap_failure_count--; - } - cache->remap_failure_window[cache->remap_failure_index] = - (unsigned char)(failed != 0); - if (failed) { - cache->remap_failure_count++; - } - cache->remap_failure_index = - (cache->remap_failure_index + 1) % ALIAS_FAILURE_WINDOW; - if (cache->remap_failure_samples < ALIAS_FAILURE_WINDOW) { - cache->remap_failure_samples++; - } - - if (cache->remap_failure_samples == ALIAS_FAILURE_WINDOW - && cache->remap_failure_count >= ALIAS_FAILURE_THRESHOLD) { - alias_disable_runtime(unwinder); - } -} - static AliasPageEntry * alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) { @@ -195,13 +170,13 @@ alias_remap_page(RemoteUnwinderObject *unwinder, VM_INHERIT_NONE); if (kr != KERN_SUCCESS) { STATS_INC(unwinder, alias_remap_failures); - alias_record_remap_outcome(unwinder, 1); + alias_disable_runtime(unwinder); return -1; } if ((cur_protection & VM_PROT_READ) == 0) { (void)mach_vm_deallocate(mach_task_self(), local_addr, page_size); STATS_INC(unwinder, alias_remap_failures); - alias_record_remap_outcome(unwinder, 1); + alias_disable_runtime(unwinder); return -1; } @@ -210,19 +185,17 @@ alias_remap_page(RemoteUnwinderObject *unwinder, if (kr != KERN_SUCCESS) { (void)mach_vm_deallocate(mach_task_self(), local_addr, page_size); STATS_INC(unwinder, alias_remap_failures); - alias_record_remap_outcome(unwinder, 1); + alias_disable_runtime(unwinder); return -1; } AliasPageEntry *entry = alias_alloc_entry(unwinder); - memset(entry, 0, sizeof(*entry)); entry->remote_page_base = page_base; entry->local_page_base = local_addr; entry->size = page_size; entry->access_seq = ++cache->access_seq; entry->valid = 1; - alias_record_remap_outcome(unwinder, 0); *entry_out = entry; return 0; } @@ -259,7 +232,6 @@ _Py_RemoteDebug_AliasProbe(RemoteUnwinderObject *unwinder, (mach_vm_size_t)page_size); } STATS_INC(unwinder, alias_remap_failures); - alias_record_remap_outcome(unwinder, 1); return -1; } @@ -269,11 +241,9 @@ _Py_RemoteDebug_AliasProbe(RemoteUnwinderObject *unwinder, (mach_vm_size_t)page_size); if (kr != KERN_SUCCESS) { STATS_INC(unwinder, alias_remap_failures); - alias_record_remap_outcome(unwinder, 1); return -1; } - alias_record_remap_outcome(unwinder, 0); return 0; } From 89a50d0febfeaf1a0cc88cfa7bf76547ab7585fc Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 01:21:23 +0200 Subject: [PATCH 09/42] dedup `AliasProbe` and `alias_remap_page` --- Modules/_remote_debugging/alias_read.c | 57 +++++++++----------------- 1 file changed, 19 insertions(+), 38 deletions(-) diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 67b3af57cbc872..5f4fe0c6bfd9de 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -146,11 +146,10 @@ alias_alloc_entry(RemoteUnwinderObject *unwinder) } static int -alias_remap_page(RemoteUnwinderObject *unwinder, - uintptr_t page_base, - AliasPageEntry **entry_out) +alias_map_readonly_page(RemoteUnwinderObject *unwinder, + uintptr_t page_base, + mach_vm_address_t *local_addr_out) { - AliasReadCache *cache = &unwinder->alias_cache; mach_vm_size_t page_size = (mach_vm_size_t)unwinder->handle.page_size; mach_vm_address_t local_addr = 0; vm_prot_t cur_protection = VM_PROT_NONE; @@ -169,21 +168,30 @@ alias_remap_page(RemoteUnwinderObject *unwinder, &max_protection, VM_INHERIT_NONE); if (kr != KERN_SUCCESS) { - STATS_INC(unwinder, alias_remap_failures); - alias_disable_runtime(unwinder); return -1; } if ((cur_protection & VM_PROT_READ) == 0) { (void)mach_vm_deallocate(mach_task_self(), local_addr, page_size); - STATS_INC(unwinder, alias_remap_failures); - alias_disable_runtime(unwinder); return -1; } - kr = mach_vm_protect(mach_task_self(), local_addr, page_size, FALSE, VM_PROT_READ); if (kr != KERN_SUCCESS) { (void)mach_vm_deallocate(mach_task_self(), local_addr, page_size); + return -1; + } + *local_addr_out = local_addr; + return 0; +} + +static int +alias_remap_page(RemoteUnwinderObject *unwinder, + uintptr_t page_base, + AliasPageEntry **entry_out) +{ + AliasReadCache *cache = &unwinder->alias_cache; + mach_vm_address_t local_addr = 0; + if (alias_map_readonly_page(unwinder, page_base, &local_addr) < 0) { STATS_INC(unwinder, alias_remap_failures); alias_disable_runtime(unwinder); return -1; @@ -192,7 +200,7 @@ alias_remap_page(RemoteUnwinderObject *unwinder, AliasPageEntry *entry = alias_alloc_entry(unwinder); entry->remote_page_base = page_base; entry->local_page_base = local_addr; - entry->size = page_size; + entry->size = (mach_vm_size_t)unwinder->handle.page_size; entry->access_seq = ++cache->access_seq; entry->valid = 1; @@ -208,42 +216,15 @@ _Py_RemoteDebug_AliasProbe(RemoteUnwinderObject *unwinder, if (cache->disabled) { return -1; } - size_t page_size = (size_t)unwinder->handle.page_size; uintptr_t page_base = probe_addr & ~(uintptr_t)(page_size - 1); mach_vm_address_t local_addr = 0; - vm_prot_t cur_protection = VM_PROT_NONE; - vm_prot_t max_protection = VM_PROT_NONE; - kern_return_t kr = mach_vm_remap( - mach_task_self(), - &local_addr, - (mach_vm_size_t)page_size, - 0, - VM_FLAGS_ANYWHERE | VM_FLAGS_RETURN_DATA_ADDR, - unwinder->handle.task, - (mach_vm_address_t)page_base, - FALSE, - &cur_protection, - &max_protection, - VM_INHERIT_NONE); - if (kr != KERN_SUCCESS || (cur_protection & VM_PROT_READ) == 0) { - if (kr == KERN_SUCCESS) { - (void)mach_vm_deallocate(mach_task_self(), local_addr, - (mach_vm_size_t)page_size); - } + if (alias_map_readonly_page(unwinder, page_base, &local_addr) < 0) { STATS_INC(unwinder, alias_remap_failures); return -1; } - - kr = mach_vm_protect(mach_task_self(), local_addr, - (mach_vm_size_t)page_size, FALSE, VM_PROT_READ); (void)mach_vm_deallocate(mach_task_self(), local_addr, (mach_vm_size_t)page_size); - if (kr != KERN_SUCCESS) { - STATS_INC(unwinder, alias_remap_failures); - return -1; - } - return 0; } From ebb527c9ec7e37da3152e975c3988a3f424b7277 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 01:46:05 +0200 Subject: [PATCH 10/42] FreeBSD style! --- Modules/_remote_debugging/alias_read.c | 36 ++++++++++++-------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 5f4fe0c6bfd9de..15ec945cbec92f 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -34,6 +34,19 @@ alias_deallocate_entry(AliasPageEntry *entry) memset(entry, 0, sizeof(*entry)); } +static AliasPageEntry * +alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) +{ + AliasReadCache *cache = &unwinder->alias_cache; + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + AliasPageEntry *entry = &cache->pages[i]; + if (entry->valid && entry->remote_page_base == page_base) { + return entry; + } + } + return NULL; +} + void _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder) { @@ -56,15 +69,11 @@ void _Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, uintptr_t remote_addr) { - AliasReadCache *cache = &unwinder->alias_cache; size_t page_size = (size_t)unwinder->handle.page_size; uintptr_t page_base = remote_addr & ~(uintptr_t)(page_size - 1); - - for (int i = 0; i < MAX_ALIAS_PAGES; i++) { - AliasPageEntry *entry = &cache->pages[i]; - if (entry->valid && entry->remote_page_base == page_base) { - alias_deallocate_entry(entry); - } + AliasPageEntry *entry; + while ((entry = alias_find_entry(unwinder, page_base)) != NULL) { + alias_deallocate_entry(entry); } } @@ -110,19 +119,6 @@ alias_maybe_probe_identity(RemoteUnwinderObject *unwinder) return 0; } -static AliasPageEntry * -alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) -{ - AliasReadCache *cache = &unwinder->alias_cache; - for (int i = 0; i < MAX_ALIAS_PAGES; i++) { - AliasPageEntry *entry = &cache->pages[i]; - if (entry->valid && entry->remote_page_base == page_base) { - return entry; - } - } - return NULL; -} - static AliasPageEntry * alias_alloc_entry(RemoteUnwinderObject *unwinder) { From af4afa15ee582eecd96e7efe6182da982b4ffdd4 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 12:15:20 +0200 Subject: [PATCH 11/42] make clinic, expected_parent is macos-only --- Modules/_remote_debugging/clinic/module.c.h | 14 +++++++++++++- Modules/_remote_debugging/frames.c | 3 ++- Modules/_remote_debugging/module.c | 5 +++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/Modules/_remote_debugging/clinic/module.c.h b/Modules/_remote_debugging/clinic/module.c.h index 349113c36fb5f0..394fe78388ee41 100644 --- a/Modules/_remote_debugging/clinic/module.c.h +++ b/Modules/_remote_debugging/clinic/module.c.h @@ -445,6 +445,18 @@ PyDoc_STRVAR(_remote_debugging_RemoteUnwinder_get_stats__doc__, " batched reads\n" " - batched_read_segments_completed: Segments completed by\n" " batched reads\n" +" - alias_hits: macOS alias-cache hits\n" +" - alias_misses: macOS alias-cache misses\n" +" - alias_remap_failures: macOS remap/protect failures\n" +" - alias_validation_fails: macOS alias snapshot validation\n" +" failures\n" +" - alias_evictions: macOS alias-cache LRU evictions\n" +" - alias_identity_mismatches: macOS target identity\n" +" mismatches\n" +" - alias_disabled_at_init: Whether aliasing was disabled\n" +" during initialization\n" +" - alias_disabled_at_runtime: Whether aliasing was disabled\n" +" at runtime\n" " - frame_cache_hit_rate: Percentage of samples that hit the\n" " cache\n" " - code_object_cache_hit_rate: Percentage of code object\n" @@ -1711,4 +1723,4 @@ _remote_debugging_get_gc_stats(PyObject *module, PyObject *const *args, Py_ssize exit: return return_value; } -/*[clinic end generated code: output=8424a993a85ef2bd input=a9049054013a1b77]*/ +/*[clinic end generated code: output=ea113af6460eeced input=a9049054013a1b77]*/ diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index 9678ff340bc697..16113e1f91ba5a 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -697,7 +697,6 @@ try_full_cache_hit( PyObject *current_frame = NULL; uintptr_t code_object_addr = 0; uintptr_t previous_frame = 0; - uintptr_t expected_parent = entry->num_addrs >= 2 ? entry->addrs[1] : 0; int parse_result; if (ctx->prefetch.frame && ctx->prefetch.frame_addr == ctx->frame_addr) { parse_result = parse_frame_buffer(unwinder, ¤t_frame, @@ -707,6 +706,8 @@ try_full_cache_hit( else { #if defined(__APPLE__) && TARGET_OS_OSX if (unwinder->cache_frames) { + uintptr_t expected_parent = + entry->num_addrs >= 2 ? entry->addrs[1] : 0; parse_result = parse_frame_object_aliased( unwinder, expected_parent, ¤t_frame, ctx->frame_addr, &code_object_addr, &previous_frame); diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 2f1b0f33308391..a2e96593718a8c 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -1150,7 +1150,8 @@ RemoteUnwinder was created with stats=True. - alias_validation_fails: macOS alias snapshot validation failures - alias_evictions: macOS alias-cache LRU evictions - - alias_identity_mismatches: macOS target identity mismatches + - alias_identity_mismatches: macOS target identity + mismatches - alias_disabled_at_init: Whether aliasing was disabled during initialization - alias_disabled_at_runtime: Whether aliasing was disabled @@ -1170,7 +1171,7 @@ RemoteUnwinder was created with stats=True. static PyObject * _remote_debugging_RemoteUnwinder_get_stats_impl(RemoteUnwinderObject *self) -/*[clinic end generated code: output=21e36477122be2a0 input=87905c65038fb06e]*/ +/*[clinic end generated code: output=21e36477122be2a0 input=4407dc8956eadfa3]*/ { if (!self->collect_stats) { PyErr_SetString(PyExc_RuntimeError, From 2069d9d8d3312d31e1a4bd4a901b37c48d09afba Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 4 Jun 2026 13:39:48 +0200 Subject: [PATCH 12/42] stop abusing stats for debugging --- Lib/test/test_external_inspection.py | 2 -- Modules/_remote_debugging/_remote_debugging.h | 2 -- Modules/_remote_debugging/alias_read.c | 2 -- Modules/_remote_debugging/clinic/module.c.h | 6 +----- Modules/_remote_debugging/module.c | 9 +-------- 5 files changed, 2 insertions(+), 19 deletions(-) diff --git a/Lib/test/test_external_inspection.py b/Lib/test/test_external_inspection.py index 6a0368f58529fa..85993557065907 100644 --- a/Lib/test/test_external_inspection.py +++ b/Lib/test/test_external_inspection.py @@ -4476,8 +4476,6 @@ def test_get_stats(self): "alias_validation_fails", "alias_evictions", "alias_identity_mismatches", - "alias_disabled_at_init", - "alias_disabled_at_runtime", "batched_read_success_rate", "batched_read_segment_completion_rate", ] diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 1530d8afec7595..2cd66291607fb4 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -316,8 +316,6 @@ typedef struct { uint64_t alias_validation_fails; // macOS alias snapshot validation failures uint64_t alias_evictions; // macOS alias-cache LRU evictions uint64_t alias_identity_mismatches; // macOS target identity mismatches - uint64_t alias_disabled_at_init; // macOS aliasing disabled during init (0/1) - uint64_t alias_disabled_at_runtime; // macOS aliasing disabled at runtime (0/1) } UnwinderStats; #if defined(__GNUC__) || defined(__clang__) diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 15ec945cbec92f..f09badae938a3b 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -61,7 +61,6 @@ alias_disable_runtime(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; cache->disabled = 1; - unwinder->stats.alias_disabled_at_runtime = 1; _Py_RemoteDebug_AliasCacheClear(unwinder); } @@ -86,7 +85,6 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) uint64_t start_tvsec = 0; if (read_target_identity(unwinder, &start_tvsec) < 0) { cache->disabled = 1; - unwinder->stats.alias_disabled_at_init = 1; } else { cache->target_start_tvsec = start_tvsec; diff --git a/Modules/_remote_debugging/clinic/module.c.h b/Modules/_remote_debugging/clinic/module.c.h index 394fe78388ee41..caa023c46f1d10 100644 --- a/Modules/_remote_debugging/clinic/module.c.h +++ b/Modules/_remote_debugging/clinic/module.c.h @@ -453,10 +453,6 @@ PyDoc_STRVAR(_remote_debugging_RemoteUnwinder_get_stats__doc__, " - alias_evictions: macOS alias-cache LRU evictions\n" " - alias_identity_mismatches: macOS target identity\n" " mismatches\n" -" - alias_disabled_at_init: Whether aliasing was disabled\n" -" during initialization\n" -" - alias_disabled_at_runtime: Whether aliasing was disabled\n" -" at runtime\n" " - frame_cache_hit_rate: Percentage of samples that hit the\n" " cache\n" " - code_object_cache_hit_rate: Percentage of code object\n" @@ -1723,4 +1719,4 @@ _remote_debugging_get_gc_stats(PyObject *module, PyObject *const *args, Py_ssize exit: return return_value; } -/*[clinic end generated code: output=ea113af6460eeced input=a9049054013a1b77]*/ +/*[clinic end generated code: output=da4742c66728d59d input=a9049054013a1b77]*/ diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index a2e96593718a8c..0acd193332091e 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -431,7 +431,6 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, #if defined(__APPLE__) && TARGET_OS_OSX if (_Py_RemoteDebug_AliasProbe(self, self->interpreter_addr) < 0) { self->alias_cache.disabled = 1; - self->stats.alias_disabled_at_init = 1; } #endif @@ -1152,10 +1151,6 @@ RemoteUnwinder was created with stats=True. - alias_evictions: macOS alias-cache LRU evictions - alias_identity_mismatches: macOS target identity mismatches - - alias_disabled_at_init: Whether aliasing was disabled - during initialization - - alias_disabled_at_runtime: Whether aliasing was disabled - at runtime - frame_cache_hit_rate: Percentage of samples that hit the cache - code_object_cache_hit_rate: Percentage of code object @@ -1171,7 +1166,7 @@ RemoteUnwinder was created with stats=True. static PyObject * _remote_debugging_RemoteUnwinder_get_stats_impl(RemoteUnwinderObject *self) -/*[clinic end generated code: output=21e36477122be2a0 input=4407dc8956eadfa3]*/ +/*[clinic end generated code: output=21e36477122be2a0 input=17992a9cb30c6add]*/ { if (!self->collect_stats) { PyErr_SetString(PyExc_RuntimeError, @@ -1217,8 +1212,6 @@ _remote_debugging_RemoteUnwinder_get_stats_impl(RemoteUnwinderObject *self) ADD_STAT(alias_validation_fails); ADD_STAT(alias_evictions); ADD_STAT(alias_identity_mismatches); - ADD_STAT(alias_disabled_at_init); - ADD_STAT(alias_disabled_at_runtime); #undef ADD_STAT From 5f7fa96d56b6694858b7b426955849fb18cce90a Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Fri, 5 Jun 2026 00:06:55 +0200 Subject: [PATCH 13/42] lazy fail is ok --- Modules/_remote_debugging/_remote_debugging.h | 1 - Modules/_remote_debugging/alias_read.c | 20 ------------------- Modules/_remote_debugging/module.c | 5 ----- 3 files changed, 26 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 2cd66291607fb4..59d3a5dc2dfe30 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -715,7 +715,6 @@ extern int _Py_RemoteDebug_AliasedRead( extern void _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder); extern void _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder); extern void _Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, uintptr_t remote_addr); -extern int _Py_RemoteDebug_AliasProbe(RemoteUnwinderObject *unwinder, uintptr_t probe_addr); #endif /* ============================================================================ diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index f09badae938a3b..0c0dc482ed112e 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -202,26 +202,6 @@ alias_remap_page(RemoteUnwinderObject *unwinder, return 0; } -int -_Py_RemoteDebug_AliasProbe(RemoteUnwinderObject *unwinder, - uintptr_t probe_addr) -{ - AliasReadCache *cache = &unwinder->alias_cache; - if (cache->disabled) { - return -1; - } - size_t page_size = (size_t)unwinder->handle.page_size; - uintptr_t page_base = probe_addr & ~(uintptr_t)(page_size - 1); - mach_vm_address_t local_addr = 0; - if (alias_map_readonly_page(unwinder, page_base, &local_addr) < 0) { - STATS_INC(unwinder, alias_remap_failures); - return -1; - } - (void)mach_vm_deallocate(mach_task_self(), local_addr, - (mach_vm_size_t)page_size); - return 0; -} - int _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, uintptr_t remote_addr, diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 0acd193332091e..7a9fc9c544527d 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -428,11 +428,6 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, set_exception_cause(self, PyExc_RuntimeError, "Failed to populate initial state data"); return -1; } -#if defined(__APPLE__) && TARGET_OS_OSX - if (_Py_RemoteDebug_AliasProbe(self, self->interpreter_addr) < 0) { - self->alias_cache.disabled = 1; - } -#endif self->code_object_cache = _Py_hashtable_new_full( _Py_hashtable_hash_ptr, From ed09b5efe0335b5570f8fa99b48a7e2dcf385846 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Fri, 5 Jun 2026 00:12:09 +0200 Subject: [PATCH 14/42] avoid seq scan in lru; try a set --- Modules/_remote_debugging/_remote_debugging.h | 8 +-- Modules/_remote_debugging/alias_read.c | 53 ++++++++++--------- 2 files changed, 33 insertions(+), 28 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 59d3a5dc2dfe30..1ecaeac3d446b4 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -272,20 +272,20 @@ typedef struct { } RemoteReadPrefetch; #if defined(__APPLE__) && TARGET_OS_OSX -#define MAX_ALIAS_PAGES 256 +#define ALIAS_CACHE_SETS 64 +#define ALIAS_CACHE_WAYS 2 #define ALIAS_PROBE_MASK 0x3ff typedef struct { uintptr_t remote_page_base; mach_vm_address_t local_page_base; mach_vm_size_t size; - uint64_t access_seq; int valid; } AliasPageEntry; typedef struct { - AliasPageEntry pages[MAX_ALIAS_PAGES]; - uint64_t access_seq; + AliasPageEntry pages[ALIAS_CACHE_SETS][ALIAS_CACHE_WAYS]; + uint8_t victim[ALIAS_CACHE_SETS]; uint64_t target_start_tvsec; uint32_t probe_counter; int disabled; diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 0c0dc482ed112e..f920ea4b9f81f4 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -34,14 +34,22 @@ alias_deallocate_entry(AliasPageEntry *entry) memset(entry, 0, sizeof(*entry)); } +static size_t +alias_set_index(RemoteUnwinderObject *unwinder, uintptr_t page_base) +{ + size_t page_size = (size_t)unwinder->handle.page_size; + uintptr_t page_index = page_base >> __builtin_ctzll(page_size); + return (size_t)(page_index & (ALIAS_CACHE_SETS - 1)); +} + static AliasPageEntry * alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) { AliasReadCache *cache = &unwinder->alias_cache; - for (int i = 0; i < MAX_ALIAS_PAGES; i++) { - AliasPageEntry *entry = &cache->pages[i]; - if (entry->valid && entry->remote_page_base == page_base) { - return entry; + AliasPageEntry *ways = cache->pages[alias_set_index(unwinder, page_base)]; + for (int w = 0; w < ALIAS_CACHE_WAYS; w++) { + if (ways[w].valid && ways[w].remote_page_base == page_base) { + return &ways[w]; } } return NULL; @@ -51,8 +59,10 @@ void _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; - for (int i = 0; i < MAX_ALIAS_PAGES; i++) { - alias_deallocate_entry(&cache->pages[i]); + for (size_t s = 0; s < ALIAS_CACHE_SETS; s++) { + for (int w = 0; w < ALIAS_CACHE_WAYS; w++) { + alias_deallocate_entry(&cache->pages[s][w]); + } } } @@ -70,8 +80,8 @@ _Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, { size_t page_size = (size_t)unwinder->handle.page_size; uintptr_t page_base = remote_addr & ~(uintptr_t)(page_size - 1); - AliasPageEntry *entry; - while ((entry = alias_find_entry(unwinder, page_base)) != NULL) { + AliasPageEntry *entry = alias_find_entry(unwinder, page_base); + if (entry != NULL) { alias_deallocate_entry(entry); } } @@ -118,25 +128,23 @@ alias_maybe_probe_identity(RemoteUnwinderObject *unwinder) } static AliasPageEntry * -alias_alloc_entry(RemoteUnwinderObject *unwinder) +alias_alloc_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) { AliasReadCache *cache = &unwinder->alias_cache; - AliasPageEntry *oldest = NULL; + size_t set = alias_set_index(unwinder, page_base); + AliasPageEntry *ways = cache->pages[set]; - for (int i = 0; i < MAX_ALIAS_PAGES; i++) { - AliasPageEntry *entry = &cache->pages[i]; - if (!entry->valid) { - return entry; - } - if (oldest == NULL || entry->access_seq < oldest->access_seq) { - oldest = entry; + for (int w = 0; w < ALIAS_CACHE_WAYS; w++) { + if (!ways[w].valid) { + return &ways[w]; } } - assert(oldest != NULL); - alias_deallocate_entry(oldest); + uint8_t victim = cache->victim[set]; + cache->victim[set] = (uint8_t)((victim + 1) % ALIAS_CACHE_WAYS); + alias_deallocate_entry(&ways[victim]); STATS_INC(unwinder, alias_evictions); - return oldest; + return &ways[victim]; } static int @@ -183,7 +191,6 @@ alias_remap_page(RemoteUnwinderObject *unwinder, uintptr_t page_base, AliasPageEntry **entry_out) { - AliasReadCache *cache = &unwinder->alias_cache; mach_vm_address_t local_addr = 0; if (alias_map_readonly_page(unwinder, page_base, &local_addr) < 0) { STATS_INC(unwinder, alias_remap_failures); @@ -191,11 +198,10 @@ alias_remap_page(RemoteUnwinderObject *unwinder, return -1; } - AliasPageEntry *entry = alias_alloc_entry(unwinder); + AliasPageEntry *entry = alias_alloc_entry(unwinder, page_base); entry->remote_page_base = page_base; entry->local_page_base = local_addr; entry->size = (mach_vm_size_t)unwinder->handle.page_size; - entry->access_seq = ++cache->access_seq; entry->valid = 1; *entry_out = entry; @@ -231,7 +237,6 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, return _Py_RemoteDebug_ReadRemoteMemory( &unwinder->handle, remote_addr, len, dst); } - entry->access_seq = ++cache->access_seq; memcpy(dst, (const char *)entry->local_page_base + offset, len); STATS_INC(unwinder, alias_hits); return 0; From 888e300c2048c4e06bd69d4b44a6da42b7be8168 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Fri, 5 Jun 2026 00:34:22 +0200 Subject: [PATCH 15/42] Revert "avoid seq scan in lru; try a set" This reverts commit c439b6f5f2bba1402ae79edcbbe070aaa6727add. --- Modules/_remote_debugging/_remote_debugging.h | 8 +-- Modules/_remote_debugging/alias_read.c | 53 +++++++++---------- 2 files changed, 28 insertions(+), 33 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 1ecaeac3d446b4..59d3a5dc2dfe30 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -272,20 +272,20 @@ typedef struct { } RemoteReadPrefetch; #if defined(__APPLE__) && TARGET_OS_OSX -#define ALIAS_CACHE_SETS 64 -#define ALIAS_CACHE_WAYS 2 +#define MAX_ALIAS_PAGES 256 #define ALIAS_PROBE_MASK 0x3ff typedef struct { uintptr_t remote_page_base; mach_vm_address_t local_page_base; mach_vm_size_t size; + uint64_t access_seq; int valid; } AliasPageEntry; typedef struct { - AliasPageEntry pages[ALIAS_CACHE_SETS][ALIAS_CACHE_WAYS]; - uint8_t victim[ALIAS_CACHE_SETS]; + AliasPageEntry pages[MAX_ALIAS_PAGES]; + uint64_t access_seq; uint64_t target_start_tvsec; uint32_t probe_counter; int disabled; diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index f920ea4b9f81f4..0c0dc482ed112e 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -34,22 +34,14 @@ alias_deallocate_entry(AliasPageEntry *entry) memset(entry, 0, sizeof(*entry)); } -static size_t -alias_set_index(RemoteUnwinderObject *unwinder, uintptr_t page_base) -{ - size_t page_size = (size_t)unwinder->handle.page_size; - uintptr_t page_index = page_base >> __builtin_ctzll(page_size); - return (size_t)(page_index & (ALIAS_CACHE_SETS - 1)); -} - static AliasPageEntry * alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) { AliasReadCache *cache = &unwinder->alias_cache; - AliasPageEntry *ways = cache->pages[alias_set_index(unwinder, page_base)]; - for (int w = 0; w < ALIAS_CACHE_WAYS; w++) { - if (ways[w].valid && ways[w].remote_page_base == page_base) { - return &ways[w]; + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + AliasPageEntry *entry = &cache->pages[i]; + if (entry->valid && entry->remote_page_base == page_base) { + return entry; } } return NULL; @@ -59,10 +51,8 @@ void _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; - for (size_t s = 0; s < ALIAS_CACHE_SETS; s++) { - for (int w = 0; w < ALIAS_CACHE_WAYS; w++) { - alias_deallocate_entry(&cache->pages[s][w]); - } + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + alias_deallocate_entry(&cache->pages[i]); } } @@ -80,8 +70,8 @@ _Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, { size_t page_size = (size_t)unwinder->handle.page_size; uintptr_t page_base = remote_addr & ~(uintptr_t)(page_size - 1); - AliasPageEntry *entry = alias_find_entry(unwinder, page_base); - if (entry != NULL) { + AliasPageEntry *entry; + while ((entry = alias_find_entry(unwinder, page_base)) != NULL) { alias_deallocate_entry(entry); } } @@ -128,23 +118,25 @@ alias_maybe_probe_identity(RemoteUnwinderObject *unwinder) } static AliasPageEntry * -alias_alloc_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) +alias_alloc_entry(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; - size_t set = alias_set_index(unwinder, page_base); - AliasPageEntry *ways = cache->pages[set]; + AliasPageEntry *oldest = NULL; - for (int w = 0; w < ALIAS_CACHE_WAYS; w++) { - if (!ways[w].valid) { - return &ways[w]; + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + AliasPageEntry *entry = &cache->pages[i]; + if (!entry->valid) { + return entry; + } + if (oldest == NULL || entry->access_seq < oldest->access_seq) { + oldest = entry; } } - uint8_t victim = cache->victim[set]; - cache->victim[set] = (uint8_t)((victim + 1) % ALIAS_CACHE_WAYS); - alias_deallocate_entry(&ways[victim]); + assert(oldest != NULL); + alias_deallocate_entry(oldest); STATS_INC(unwinder, alias_evictions); - return &ways[victim]; + return oldest; } static int @@ -191,6 +183,7 @@ alias_remap_page(RemoteUnwinderObject *unwinder, uintptr_t page_base, AliasPageEntry **entry_out) { + AliasReadCache *cache = &unwinder->alias_cache; mach_vm_address_t local_addr = 0; if (alias_map_readonly_page(unwinder, page_base, &local_addr) < 0) { STATS_INC(unwinder, alias_remap_failures); @@ -198,10 +191,11 @@ alias_remap_page(RemoteUnwinderObject *unwinder, return -1; } - AliasPageEntry *entry = alias_alloc_entry(unwinder, page_base); + AliasPageEntry *entry = alias_alloc_entry(unwinder); entry->remote_page_base = page_base; entry->local_page_base = local_addr; entry->size = (mach_vm_size_t)unwinder->handle.page_size; + entry->access_seq = ++cache->access_seq; entry->valid = 1; *entry_out = entry; @@ -237,6 +231,7 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, return _Py_RemoteDebug_ReadRemoteMemory( &unwinder->handle, remote_addr, len, dst); } + entry->access_seq = ++cache->access_seq; memcpy(dst, (const char *)entry->local_page_base + offset, len); STATS_INC(unwinder, alias_hits); return 0; From 91531273ed825e5e77149a7edc71580b9c971d56 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Tue, 9 Jun 2026 22:20:40 +0200 Subject: [PATCH 16/42] there's task_info, no need to rely on pid+ts --- Modules/_remote_debugging/_remote_debugging.h | 1 - Modules/_remote_debugging/alias_read.c | 38 ++++--------------- 2 files changed, 7 insertions(+), 32 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 59d3a5dc2dfe30..4ad1e6a5216916 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -286,7 +286,6 @@ typedef struct { typedef struct { AliasPageEntry pages[MAX_ALIAS_PAGES]; uint64_t access_seq; - uint64_t target_start_tvsec; uint32_t probe_counter; int disabled; } AliasReadCache; diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 0c0dc482ed112e..3046e08f069259 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -6,23 +6,6 @@ # define VM_FLAGS_RETURN_DATA_ADDR 0 #endif -static int -read_target_identity(RemoteUnwinderObject *unwinder, - uint64_t *start_tvsec) -{ - struct proc_bsdinfo info; - int n = proc_pidinfo(unwinder->handle.pid, PROC_PIDTBSDINFO, 0, - &info, sizeof(info)); - if (n != (int)sizeof(info)) { - return -1; - } - if (info.pbi_start_tvsec == 0) { - return -1; - } - *start_tvsec = (uint64_t)info.pbi_start_tvsec; - return 0; -} - static void alias_deallocate_entry(AliasPageEntry *entry) { @@ -81,25 +64,18 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; memset(cache, 0, sizeof(*cache)); - - uint64_t start_tvsec = 0; - if (read_target_identity(unwinder, &start_tvsec) < 0) { - cache->disabled = 1; - } - else { - cache->target_start_tvsec = start_tvsec; - } } static int alias_identity_matches(RemoteUnwinderObject *unwinder) { - AliasReadCache *cache = &unwinder->alias_cache; - uint64_t start_tvsec = 0; - if (read_target_identity(unwinder, &start_tvsec) < 0) { - return 0; - } - return start_tvsec == cache->target_start_tvsec; + task_basic_info_data_t task_basic_info; + mach_msg_type_number_t task_info_count = TASK_BASIC_INFO_COUNT; + kern_return_t task_valid_check = task_info(unwinder->handle.task, + TASK_BASIC_INFO, + (task_info_t)&task_basic_info, + &task_info_count); + return task_valid_check == KERN_SUCCESS; } static int From 0d73d106696174c11046a08772e8cda20f5ef29c Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Tue, 9 Jun 2026 22:23:44 +0200 Subject: [PATCH 17/42] never observed stale interp in the wild --- Modules/_remote_debugging/_remote_debugging.h | 4 ---- Modules/_remote_debugging/frames.c | 24 ------------------- Modules/_remote_debugging/module.c | 11 --------- 3 files changed, 39 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 4ad1e6a5216916..4b3b5aefe48686 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -696,10 +696,6 @@ extern int parse_frame_object_aliased( uintptr_t *previous_frame ); -extern int _Py_RemoteDebug_ValidateInterpreterSnapshot( - RemoteUnwinderObject *unwinder, - const char *interp_state_buffer -); extern int _Py_RemoteDebug_ValidateThreadStateSnapshot( RemoteUnwinderObject *unwinder, const char *tstate_buffer, diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index 16113e1f91ba5a..6492ba5d7d0021 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -258,30 +258,6 @@ remote_pointer_plausible(RemoteUnwinderObject *unwinder, uintptr_t ptr) return 1; } -int -_Py_RemoteDebug_ValidateInterpreterSnapshot( - RemoteUnwinderObject *unwinder, - const char *interp_state_buffer) -{ - uintptr_t threads_head = GET_MEMBER(uintptr_t, interp_state_buffer, - unwinder->debug_offsets.interpreter_state.threads_head); - uintptr_t threads_main = GET_MEMBER(uintptr_t, interp_state_buffer, - unwinder->debug_offsets.interpreter_state.threads_main); - uintptr_t next = GET_MEMBER(uintptr_t, interp_state_buffer, - unwinder->debug_offsets.interpreter_state.next); - uintptr_t gil_holder_tstate = GET_MEMBER(uintptr_t, interp_state_buffer, - unwinder->debug_offsets.interpreter_state.gil_runtime_state_holder); - uintptr_t gc_frame = GET_MEMBER(uintptr_t, interp_state_buffer, - unwinder->debug_offsets.interpreter_state.gc - + unwinder->debug_offsets.gc.frame); - - return remote_pointer_plausible(unwinder, threads_head) - && remote_pointer_plausible(unwinder, threads_main) - && remote_pointer_plausible(unwinder, next) - && remote_pointer_plausible(unwinder, gil_holder_tstate) - && remote_pointer_plausible(unwinder, gc_frame); -} - int _Py_RemoteDebug_ValidateThreadStateSnapshot( RemoteUnwinderObject *unwinder, diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 7a9fc9c544527d..6ff699b1029a6b 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -620,17 +620,6 @@ read_interp_state_and_maybe_thread_frame( interp_state_buffer) < 0) { return -1; } - if (!_Py_RemoteDebug_ValidateInterpreterSnapshot( - unwinder, interp_state_buffer)) { - STATS_INC(unwinder, alias_validation_fails); - _Py_RemoteDebug_AliasCacheInvalidatePage(unwinder, - interpreter_addr); - return _Py_RemoteDebug_ReadRemoteMemory( - &unwinder->handle, - interpreter_addr, - INTERP_STATE_BUFFER_SIZE, - interp_state_buffer); - } return 0; } #endif From 7fd32ee69f67da543fc3fdd356f0c77e85fc2c4f Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Tue, 9 Jun 2026 22:36:50 +0200 Subject: [PATCH 18/42] mach_port_type... --- Modules/_remote_debugging/alias_read.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 3046e08f069259..76c2185d1c1477 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -69,13 +69,14 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) static int alias_identity_matches(RemoteUnwinderObject *unwinder) { - task_basic_info_data_t task_basic_info; - mach_msg_type_number_t task_info_count = TASK_BASIC_INFO_COUNT; - kern_return_t task_valid_check = task_info(unwinder->handle.task, - TASK_BASIC_INFO, - (task_info_t)&task_basic_info, - &task_info_count); - return task_valid_check == KERN_SUCCESS; + mach_port_type_t type = 0; + kern_return_t kr = mach_port_type(mach_task_self(), + unwinder->handle.task, &type); + if (kr != KERN_SUCCESS) { + return 0; + } + return ((type & MACH_PORT_TYPE_SEND) && + !(type & MACH_PORT_TYPE_DEAD_NAME)) ? 1 : 0; } static int From 92062b712b7d1fc22d8500731985de8115c9ba96 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Tue, 9 Jun 2026 22:46:27 +0200 Subject: [PATCH 19/42] notify about death --- Modules/_remote_debugging/_remote_debugging.h | 2 + Modules/_remote_debugging/alias_read.c | 79 ++++++++++++++++++- 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 4b3b5aefe48686..ccd4bc2f291105 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -285,8 +285,10 @@ typedef struct { typedef struct { AliasPageEntry pages[MAX_ALIAS_PAGES]; + mach_port_t notify_port; uint64_t access_seq; uint32_t probe_counter; + int notify_armed; int disabled; } AliasReadCache; #endif diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 76c2185d1c1477..123e98b1cfc42a 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -2,6 +2,8 @@ #if defined(__APPLE__) && TARGET_OS_OSX +#include + #ifndef VM_FLAGS_RETURN_DATA_ADDR # define VM_FLAGS_RETURN_DATA_ADDR 0 #endif @@ -37,6 +39,12 @@ _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder) for (int i = 0; i < MAX_ALIAS_PAGES; i++) { alias_deallocate_entry(&cache->pages[i]); } + if (cache->notify_port != MACH_PORT_NULL) { + (void)mach_port_mod_refs(mach_task_self(), cache->notify_port, + MACH_PORT_RIGHT_RECEIVE, -1); + cache->notify_port = MACH_PORT_NULL; + } + cache->notify_armed = 0; } static void @@ -64,10 +72,38 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; memset(cache, 0, sizeof(*cache)); + + mach_port_t notify_port = MACH_PORT_NULL; + kern_return_t kr = mach_port_allocate(mach_task_self(), + MACH_PORT_RIGHT_RECEIVE, + ¬ify_port); + if (kr != KERN_SUCCESS) { + return; + } + + mach_port_t previous = MACH_PORT_NULL; + kr = mach_port_request_notification(mach_task_self(), + unwinder->handle.task, + MACH_NOTIFY_DEAD_NAME, + 1, + notify_port, + MACH_MSG_TYPE_MAKE_SEND_ONCE, + &previous); + if (previous != MACH_PORT_NULL) { + (void)mach_port_deallocate(mach_task_self(), previous); + } + if (kr != KERN_SUCCESS) { + (void)mach_port_mod_refs(mach_task_self(), notify_port, + MACH_PORT_RIGHT_RECEIVE, -1); + return; + } + + cache->notify_port = notify_port; + cache->notify_armed = 1; } static int -alias_identity_matches(RemoteUnwinderObject *unwinder) +alias_identity_matches_fallback(RemoteUnwinderObject *unwinder) { mach_port_type_t type = 0; kern_return_t kr = mach_port_type(mach_task_self(), @@ -79,6 +115,47 @@ alias_identity_matches(RemoteUnwinderObject *unwinder) !(type & MACH_PORT_TYPE_DEAD_NAME)) ? 1 : 0; } +static int +alias_identity_matches(RemoteUnwinderObject *unwinder) +{ + AliasReadCache *cache = &unwinder->alias_cache; + if (!cache->notify_armed) { + return alias_identity_matches_fallback(unwinder); + } + + union { + mach_dead_name_notification_t dead_name; + struct { + mach_msg_header_t header; + mach_msg_trailer_t trailer; + } msg; + char storage[sizeof(mach_dead_name_notification_t) + + sizeof(mach_msg_trailer_t)]; + } msg; + memset(&msg, 0, sizeof(msg)); + + mach_msg_return_t mr = mach_msg(&msg.msg.header, + MACH_RCV_MSG | MACH_RCV_TIMEOUT, + 0, + (mach_msg_size_t)sizeof(msg), + cache->notify_port, + 0, + MACH_PORT_NULL); + if (mr == MACH_RCV_TIMED_OUT) { + return 1; + } + if (mr == MACH_MSG_SUCCESS && + msg.msg.header.msgh_id == MACH_NOTIFY_DEAD_NAME) + { + if (msg.dead_name.not_port != MACH_PORT_NULL) { + (void)mach_port_deallocate(mach_task_self(), + msg.dead_name.not_port); + } + return 0; + } + return 0; +} + static int alias_maybe_probe_identity(RemoteUnwinderObject *unwinder) { From 6316fb6e13163e9ad257357084b71a7ecffe9f04 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Tue, 9 Jun 2026 22:49:16 +0200 Subject: [PATCH 20/42] mach_vm_remap(FIXED|OVERWRITE) --- Modules/_remote_debugging/_remote_debugging.h | 1 + Modules/_remote_debugging/alias_read.c | 67 +++++++++++++------ 2 files changed, 46 insertions(+), 22 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index ccd4bc2f291105..b8f50d0cf89544 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -285,6 +285,7 @@ typedef struct { typedef struct { AliasPageEntry pages[MAX_ALIAS_PAGES]; + mach_vm_address_t region_base; mach_port_t notify_port; uint64_t access_seq; uint32_t probe_counter; diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 123e98b1cfc42a..fb246795ce9129 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -9,13 +9,8 @@ #endif static void -alias_deallocate_entry(AliasPageEntry *entry) +alias_invalidate_entry(AliasPageEntry *entry) { - if (!entry->valid) { - return; - } - (void)mach_vm_deallocate(mach_task_self(), entry->local_page_base, - entry->size); memset(entry, 0, sizeof(*entry)); } @@ -37,7 +32,15 @@ _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; for (int i = 0; i < MAX_ALIAS_PAGES; i++) { - alias_deallocate_entry(&cache->pages[i]); + alias_invalidate_entry(&cache->pages[i]); + } + if (cache->region_base != 0) { + mach_vm_size_t region_size = + (mach_vm_size_t)MAX_ALIAS_PAGES * + (mach_vm_size_t)unwinder->handle.page_size; + (void)mach_vm_deallocate(mach_task_self(), cache->region_base, + region_size); + cache->region_base = 0; } if (cache->notify_port != MACH_PORT_NULL) { (void)mach_port_mod_refs(mach_task_self(), cache->notify_port, @@ -63,7 +66,7 @@ _Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, uintptr_t page_base = remote_addr & ~(uintptr_t)(page_size - 1); AliasPageEntry *entry; while ((entry = alias_find_entry(unwinder, page_base)) != NULL) { - alias_deallocate_entry(entry); + alias_invalidate_entry(entry); } } @@ -73,10 +76,31 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) AliasReadCache *cache = &unwinder->alias_cache; memset(cache, 0, sizeof(*cache)); + mach_vm_size_t region_size = + (mach_vm_size_t)MAX_ALIAS_PAGES * + (mach_vm_size_t)unwinder->handle.page_size; + kern_return_t kr = mach_vm_allocate(mach_task_self(), + &cache->region_base, + region_size, + VM_FLAGS_ANYWHERE); + if (kr != KERN_SUCCESS) { + cache->disabled = 1; + return; + } + kr = mach_vm_protect(mach_task_self(), cache->region_base, region_size, + FALSE, VM_PROT_NONE); + if (kr != KERN_SUCCESS) { + (void)mach_vm_deallocate(mach_task_self(), cache->region_base, + region_size); + cache->region_base = 0; + cache->disabled = 1; + return; + } + mach_port_t notify_port = MACH_PORT_NULL; - kern_return_t kr = mach_port_allocate(mach_task_self(), - MACH_PORT_RIGHT_RECEIVE, - ¬ify_port); + kr = mach_port_allocate(mach_task_self(), + MACH_PORT_RIGHT_RECEIVE, + ¬ify_port); if (kr != KERN_SUCCESS) { return; } @@ -188,7 +212,7 @@ alias_alloc_entry(RemoteUnwinderObject *unwinder) } assert(oldest != NULL); - alias_deallocate_entry(oldest); + alias_invalidate_entry(oldest); STATS_INC(unwinder, alias_evictions); return oldest; } @@ -196,10 +220,12 @@ alias_alloc_entry(RemoteUnwinderObject *unwinder) static int alias_map_readonly_page(RemoteUnwinderObject *unwinder, uintptr_t page_base, - mach_vm_address_t *local_addr_out) + AliasPageEntry *entry) { + AliasReadCache *cache = &unwinder->alias_cache; mach_vm_size_t page_size = (mach_vm_size_t)unwinder->handle.page_size; - mach_vm_address_t local_addr = 0; + mach_vm_address_t local_addr = + cache->region_base + (entry - cache->pages) * page_size; vm_prot_t cur_protection = VM_PROT_NONE; vm_prot_t max_protection = VM_PROT_NONE; @@ -208,7 +234,7 @@ alias_map_readonly_page(RemoteUnwinderObject *unwinder, &local_addr, page_size, 0, - VM_FLAGS_ANYWHERE | VM_FLAGS_RETURN_DATA_ADDR, + VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE | VM_FLAGS_RETURN_DATA_ADDR, unwinder->handle.task, (mach_vm_address_t)page_base, FALSE, @@ -219,16 +245,14 @@ alias_map_readonly_page(RemoteUnwinderObject *unwinder, return -1; } if ((cur_protection & VM_PROT_READ) == 0) { - (void)mach_vm_deallocate(mach_task_self(), local_addr, page_size); return -1; } kr = mach_vm_protect(mach_task_self(), local_addr, page_size, FALSE, VM_PROT_READ); if (kr != KERN_SUCCESS) { - (void)mach_vm_deallocate(mach_task_self(), local_addr, page_size); return -1; } - *local_addr_out = local_addr; + entry->local_page_base = local_addr; return 0; } @@ -238,16 +262,15 @@ alias_remap_page(RemoteUnwinderObject *unwinder, AliasPageEntry **entry_out) { AliasReadCache *cache = &unwinder->alias_cache; - mach_vm_address_t local_addr = 0; - if (alias_map_readonly_page(unwinder, page_base, &local_addr) < 0) { + AliasPageEntry *entry = alias_alloc_entry(unwinder); + if (alias_map_readonly_page(unwinder, page_base, entry) < 0) { + alias_invalidate_entry(entry); STATS_INC(unwinder, alias_remap_failures); alias_disable_runtime(unwinder); return -1; } - AliasPageEntry *entry = alias_alloc_entry(unwinder); entry->remote_page_base = page_base; - entry->local_page_base = local_addr; entry->size = (mach_vm_size_t)unwinder->handle.page_size; entry->access_seq = ++cache->access_seq; entry->valid = 1; From 2bdf0ac07309e8b4dbb3608b12aaef972b750eed Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Tue, 9 Jun 2026 22:52:05 +0200 Subject: [PATCH 21/42] Revert "notify about death" This reverts commit 5d71de0b12857b6437c227438188c1b4205080e9. --- Modules/_remote_debugging/_remote_debugging.h | 2 - Modules/_remote_debugging/alias_read.c | 79 +------------------ 2 files changed, 1 insertion(+), 80 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index b8f50d0cf89544..22f0e544d24ca8 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -286,10 +286,8 @@ typedef struct { typedef struct { AliasPageEntry pages[MAX_ALIAS_PAGES]; mach_vm_address_t region_base; - mach_port_t notify_port; uint64_t access_seq; uint32_t probe_counter; - int notify_armed; int disabled; } AliasReadCache; #endif diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index fb246795ce9129..7cc154e1e896bb 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -2,8 +2,6 @@ #if defined(__APPLE__) && TARGET_OS_OSX -#include - #ifndef VM_FLAGS_RETURN_DATA_ADDR # define VM_FLAGS_RETURN_DATA_ADDR 0 #endif @@ -42,12 +40,6 @@ _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder) region_size); cache->region_base = 0; } - if (cache->notify_port != MACH_PORT_NULL) { - (void)mach_port_mod_refs(mach_task_self(), cache->notify_port, - MACH_PORT_RIGHT_RECEIVE, -1); - cache->notify_port = MACH_PORT_NULL; - } - cache->notify_armed = 0; } static void @@ -96,38 +88,10 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) cache->disabled = 1; return; } - - mach_port_t notify_port = MACH_PORT_NULL; - kr = mach_port_allocate(mach_task_self(), - MACH_PORT_RIGHT_RECEIVE, - ¬ify_port); - if (kr != KERN_SUCCESS) { - return; - } - - mach_port_t previous = MACH_PORT_NULL; - kr = mach_port_request_notification(mach_task_self(), - unwinder->handle.task, - MACH_NOTIFY_DEAD_NAME, - 1, - notify_port, - MACH_MSG_TYPE_MAKE_SEND_ONCE, - &previous); - if (previous != MACH_PORT_NULL) { - (void)mach_port_deallocate(mach_task_self(), previous); - } - if (kr != KERN_SUCCESS) { - (void)mach_port_mod_refs(mach_task_self(), notify_port, - MACH_PORT_RIGHT_RECEIVE, -1); - return; - } - - cache->notify_port = notify_port; - cache->notify_armed = 1; } static int -alias_identity_matches_fallback(RemoteUnwinderObject *unwinder) +alias_identity_matches(RemoteUnwinderObject *unwinder) { mach_port_type_t type = 0; kern_return_t kr = mach_port_type(mach_task_self(), @@ -139,47 +103,6 @@ alias_identity_matches_fallback(RemoteUnwinderObject *unwinder) !(type & MACH_PORT_TYPE_DEAD_NAME)) ? 1 : 0; } -static int -alias_identity_matches(RemoteUnwinderObject *unwinder) -{ - AliasReadCache *cache = &unwinder->alias_cache; - if (!cache->notify_armed) { - return alias_identity_matches_fallback(unwinder); - } - - union { - mach_dead_name_notification_t dead_name; - struct { - mach_msg_header_t header; - mach_msg_trailer_t trailer; - } msg; - char storage[sizeof(mach_dead_name_notification_t) + - sizeof(mach_msg_trailer_t)]; - } msg; - memset(&msg, 0, sizeof(msg)); - - mach_msg_return_t mr = mach_msg(&msg.msg.header, - MACH_RCV_MSG | MACH_RCV_TIMEOUT, - 0, - (mach_msg_size_t)sizeof(msg), - cache->notify_port, - 0, - MACH_PORT_NULL); - if (mr == MACH_RCV_TIMED_OUT) { - return 1; - } - if (mr == MACH_MSG_SUCCESS && - msg.msg.header.msgh_id == MACH_NOTIFY_DEAD_NAME) - { - if (msg.dead_name.not_port != MACH_PORT_NULL) { - (void)mach_port_deallocate(mach_task_self(), - msg.dead_name.not_port); - } - return 0; - } - return 0; -} - static int alias_maybe_probe_identity(RemoteUnwinderObject *unwinder) { From 97e67e68cf47179b946278ecbffb6cb1a456903c Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 00:37:39 +0200 Subject: [PATCH 22/42] NEVER happened in the wild, across 47m samples with lots of churn; shadowed by owner gate --- Modules/_remote_debugging/frames.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index 6492ba5d7d0021..47774f16ee1650 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -299,12 +299,9 @@ validate_frame_snapshot( return 0; } - uintptr_t executable = GET_MEMBER_NO_TAG(uintptr_t, frame, - unwinder->debug_offsets.interpreter_frame.executable); uintptr_t previous = GET_MEMBER(uintptr_t, frame, unwinder->debug_offsets.interpreter_frame.previous); - if (!remote_pointer_plausible(unwinder, executable) - || !remote_pointer_plausible(unwinder, previous)) { + if (!remote_pointer_plausible(unwinder, previous)) { return 0; } if (expected_parent != 0 && previous != expected_parent) { From 272bb782a3963121ffe19dd21b895f371c604e74 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 01:07:04 +0200 Subject: [PATCH 23/42] poor man's AIMD mach_vm_region_recurse() --- Lib/test/test_external_inspection.py | 2 + Modules/_remote_debugging/_remote_debugging.h | 9 +- Modules/_remote_debugging/alias_read.c | 114 +++++++++++++----- Modules/_remote_debugging/clinic/module.c.h | 4 +- Modules/_remote_debugging/module.c | 6 +- 5 files changed, 102 insertions(+), 33 deletions(-) diff --git a/Lib/test/test_external_inspection.py b/Lib/test/test_external_inspection.py index 85993557065907..14f62a43dfeb18 100644 --- a/Lib/test/test_external_inspection.py +++ b/Lib/test/test_external_inspection.py @@ -4476,6 +4476,8 @@ def test_get_stats(self): "alias_validation_fails", "alias_evictions", "alias_identity_mismatches", + "alias_probe_checks", + "alias_probe_recycles", "batched_read_success_rate", "batched_read_segment_completion_rate", ] diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 22f0e544d24ca8..b7b9e68d228c41 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -273,7 +273,9 @@ typedef struct { #if defined(__APPLE__) && TARGET_OS_OSX #define MAX_ALIAS_PAGES 256 -#define ALIAS_PROBE_MASK 0x3ff +#define ALIAS_PROBE_DEFAULT_MASK 0x3ff +#define ALIAS_PROBE_MIN_MASK 0x3f +#define ALIAS_PROBE_MAX_MASK 0x3fff typedef struct { uintptr_t remote_page_base; @@ -281,6 +283,8 @@ typedef struct { mach_vm_size_t size; uint64_t access_seq; int valid; + uint64_t map_objid; + uint64_t map_offset; } AliasPageEntry; typedef struct { @@ -288,6 +292,7 @@ typedef struct { mach_vm_address_t region_base; uint64_t access_seq; uint32_t probe_counter; + uint32_t probe_mask; int disabled; } AliasReadCache; #endif @@ -316,6 +321,8 @@ typedef struct { uint64_t alias_validation_fails; // macOS alias snapshot validation failures uint64_t alias_evictions; // macOS alias-cache LRU evictions uint64_t alias_identity_mismatches; // macOS target identity mismatches + uint64_t alias_probe_checks; // macOS alias object identity probes + uint64_t alias_probe_recycles; // macOS alias recycled-page detections } UnwinderStats; #if defined(__GNUC__) || defined(__clang__) diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 7cc154e1e896bb..75e27f48318c78 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -6,6 +6,36 @@ # define VM_FLAGS_RETURN_DATA_ADDR 0 #endif +static int +alias_query_region(task_t task, + mach_vm_address_t addr, + uint64_t *objid, + uint64_t *offset) +{ + mach_vm_address_t region_addr = addr; + mach_vm_size_t region_size = 0; + natural_t depth = 0; + vm_region_submap_info_data_64_t info; + mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64; + + kern_return_t kr = mach_vm_region_recurse( + task, ®ion_addr, ®ion_size, &depth, + (vm_region_recurse_info_t)&info, &count); + if (kr == MACH_SEND_INVALID_DEST || kr == KERN_INVALID_ARGUMENT) { + return -1; + } + if (kr != KERN_SUCCESS || addr < region_addr || + (mach_vm_size_t)(addr - region_addr) >= region_size || + info.is_submap) + { + return 1; + } + + *objid = info.object_id_full; + *offset = info.offset + (uint64_t)(addr - region_addr); + return 0; +} + static void alias_invalidate_entry(AliasPageEntry *entry) { @@ -67,6 +97,7 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) { AliasReadCache *cache = &unwinder->alias_cache; memset(cache, 0, sizeof(*cache)); + cache->probe_mask = ALIAS_PROBE_DEFAULT_MASK; mach_vm_size_t region_size = (mach_vm_size_t)MAX_ALIAS_PAGES * @@ -91,30 +122,38 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) } static int -alias_identity_matches(RemoteUnwinderObject *unwinder) -{ - mach_port_type_t type = 0; - kern_return_t kr = mach_port_type(mach_task_self(), - unwinder->handle.task, &type); - if (kr != KERN_SUCCESS) { - return 0; - } - return ((type & MACH_PORT_TYPE_SEND) && - !(type & MACH_PORT_TYPE_DEAD_NAME)) ? 1 : 0; -} - -static int -alias_maybe_probe_identity(RemoteUnwinderObject *unwinder) +alias_maybe_probe_entry(RemoteUnwinderObject *unwinder, + AliasPageEntry *entry) { AliasReadCache *cache = &unwinder->alias_cache; - if ((++cache->probe_counter & ALIAS_PROBE_MASK) != 0) { + if ((++cache->probe_counter & cache->probe_mask) != 0) { return 1; } - if (alias_identity_matches(unwinder)) { + STATS_INC(unwinder, alias_probe_checks); + + uint64_t objid = 0; + uint64_t offset = 0; + int rc = alias_query_region(unwinder->handle.task, + entry->remote_page_base, + &objid, &offset); + if (rc < 0) { + STATS_INC(unwinder, alias_identity_mismatches); + alias_disable_runtime(unwinder); + return -1; + } + if (rc == 0 && objid == entry->map_objid && + offset == entry->map_offset) + { + if (cache->probe_mask < ALIAS_PROBE_MAX_MASK) { + cache->probe_mask = (cache->probe_mask << 1) | 1; + } return 1; } - STATS_INC(unwinder, alias_identity_mismatches); - alias_disable_runtime(unwinder); + STATS_INC(unwinder, alias_probe_recycles); + if (cache->probe_mask > ALIAS_PROBE_MIN_MASK) { + cache->probe_mask >>= 1; + } + alias_invalidate_entry(entry); return 0; } @@ -140,7 +179,7 @@ alias_alloc_entry(RemoteUnwinderObject *unwinder) return oldest; } -static int +static kern_return_t alias_map_readonly_page(RemoteUnwinderObject *unwinder, uintptr_t page_base, AliasPageEntry *entry) @@ -165,18 +204,18 @@ alias_map_readonly_page(RemoteUnwinderObject *unwinder, &max_protection, VM_INHERIT_NONE); if (kr != KERN_SUCCESS) { - return -1; + return kr; } if ((cur_protection & VM_PROT_READ) == 0) { - return -1; + return KERN_PROTECTION_FAILURE; } kr = mach_vm_protect(mach_task_self(), local_addr, page_size, FALSE, VM_PROT_READ); if (kr != KERN_SUCCESS) { - return -1; + return kr; } entry->local_page_base = local_addr; - return 0; + return KERN_SUCCESS; } static int @@ -186,10 +225,14 @@ alias_remap_page(RemoteUnwinderObject *unwinder, { AliasReadCache *cache = &unwinder->alias_cache; AliasPageEntry *entry = alias_alloc_entry(unwinder); - if (alias_map_readonly_page(unwinder, page_base, entry) < 0) { + kern_return_t kr = alias_map_readonly_page(unwinder, page_base, entry); + if (kr != KERN_SUCCESS) { alias_invalidate_entry(entry); STATS_INC(unwinder, alias_remap_failures); - alias_disable_runtime(unwinder); + if (kr == MACH_SEND_INVALID_DEST || kr == KERN_INVALID_ARGUMENT) { + STATS_INC(unwinder, alias_identity_mismatches); + alias_disable_runtime(unwinder); + } return -1; } @@ -198,6 +241,14 @@ alias_remap_page(RemoteUnwinderObject *unwinder, entry->access_seq = ++cache->access_seq; entry->valid = 1; + if (alias_query_region(mach_task_self(), entry->local_page_base, + &entry->map_objid, &entry->map_offset) != 0) + { + alias_invalidate_entry(entry); + STATS_INC(unwinder, alias_remap_failures); + return -1; + } + *entry_out = entry; return 0; } @@ -227,14 +278,17 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, AliasPageEntry *entry = alias_find_entry(unwinder, page_base); if (entry != NULL) { - if (!alias_maybe_probe_identity(unwinder)) { + int probe = alias_maybe_probe_entry(unwinder, entry); + if (probe < 0) { return _Py_RemoteDebug_ReadRemoteMemory( &unwinder->handle, remote_addr, len, dst); } - entry->access_seq = ++cache->access_seq; - memcpy(dst, (const char *)entry->local_page_base + offset, len); - STATS_INC(unwinder, alias_hits); - return 0; + if (probe > 0) { + entry->access_seq = ++cache->access_seq; + memcpy(dst, (const char *)entry->local_page_base + offset, len); + STATS_INC(unwinder, alias_hits); + return 0; + } } STATS_INC(unwinder, alias_misses); diff --git a/Modules/_remote_debugging/clinic/module.c.h b/Modules/_remote_debugging/clinic/module.c.h index caa023c46f1d10..06a4c582e2086a 100644 --- a/Modules/_remote_debugging/clinic/module.c.h +++ b/Modules/_remote_debugging/clinic/module.c.h @@ -453,6 +453,8 @@ PyDoc_STRVAR(_remote_debugging_RemoteUnwinder_get_stats__doc__, " - alias_evictions: macOS alias-cache LRU evictions\n" " - alias_identity_mismatches: macOS target identity\n" " mismatches\n" +" - alias_probe_checks: macOS alias object identity probes\n" +" - alias_probe_recycles: macOS alias recycled-page detections\n" " - frame_cache_hit_rate: Percentage of samples that hit the\n" " cache\n" " - code_object_cache_hit_rate: Percentage of code object\n" @@ -1719,4 +1721,4 @@ _remote_debugging_get_gc_stats(PyObject *module, PyObject *const *args, Py_ssize exit: return return_value; } -/*[clinic end generated code: output=da4742c66728d59d input=a9049054013a1b77]*/ +/*[clinic end generated code: output=170c53b2d66aed30 input=a9049054013a1b77]*/ diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 6ff699b1029a6b..e4d5ee1ee6ae8e 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -1135,6 +1135,8 @@ RemoteUnwinder was created with stats=True. - alias_evictions: macOS alias-cache LRU evictions - alias_identity_mismatches: macOS target identity mismatches + - alias_probe_checks: macOS alias object identity probes + - alias_probe_recycles: macOS alias recycled-page detections - frame_cache_hit_rate: Percentage of samples that hit the cache - code_object_cache_hit_rate: Percentage of code object @@ -1150,7 +1152,7 @@ RemoteUnwinder was created with stats=True. static PyObject * _remote_debugging_RemoteUnwinder_get_stats_impl(RemoteUnwinderObject *self) -/*[clinic end generated code: output=21e36477122be2a0 input=17992a9cb30c6add]*/ +/*[clinic end generated code: output=21e36477122be2a0 input=d9bce4858ca7cbc7]*/ { if (!self->collect_stats) { PyErr_SetString(PyExc_RuntimeError, @@ -1196,6 +1198,8 @@ _remote_debugging_RemoteUnwinder_get_stats_impl(RemoteUnwinderObject *self) ADD_STAT(alias_validation_fails); ADD_STAT(alias_evictions); ADD_STAT(alias_identity_mismatches); + ADD_STAT(alias_probe_checks); + ADD_STAT(alias_probe_recycles); #undef ADD_STAT From 1a7ee5cafee360184fd576f6a2c3b6989f64ebd4 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 02:38:37 +0200 Subject: [PATCH 24/42] 0/800m calls w/ very churny scenarios --- Modules/_remote_debugging/frames.c | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index 47774f16ee1650..a9b9922697ea6c 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -273,18 +273,12 @@ _Py_RemoteDebug_ValidateThreadStateSnapshot( uintptr_t current_frame = GET_MEMBER(uintptr_t, tstate_buffer, unwinder->debug_offsets.thread_state.current_frame); - uintptr_t base_frame = GET_MEMBER(uintptr_t, tstate_buffer, - unwinder->debug_offsets.thread_state.base_frame); uintptr_t next = GET_MEMBER(uintptr_t, tstate_buffer, unwinder->debug_offsets.thread_state.next); - uintptr_t last_profiled_frame = GET_MEMBER(uintptr_t, tstate_buffer, - unwinder->debug_offsets.thread_state.last_profiled_frame); return next != tstate_addr && remote_pointer_plausible(unwinder, current_frame) - && remote_pointer_plausible(unwinder, base_frame) - && remote_pointer_plausible(unwinder, next) - && remote_pointer_plausible(unwinder, last_profiled_frame); + && remote_pointer_plausible(unwinder, next); } static int From 01f1503e0321a32b56bbf8bf639648a04eb4d84b Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 04:22:39 +0200 Subject: [PATCH 25/42] interp_window_{start,size}; 3.4MHz --- Modules/_remote_debugging/_remote_debugging.h | 2 + Modules/_remote_debugging/module.c | 66 +++++++++++++++---- 2 files changed, 56 insertions(+), 12 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index b7b9e68d228c41..3c4745c0a6cb6a 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -392,6 +392,8 @@ typedef struct { proc_handle_t handle; uintptr_t runtime_start_address; struct _Py_DebugOffsets debug_offsets; + size_t interp_window_start; + size_t interp_window_size; int async_debug_offsets_available; struct _Py_AsyncioModuleDebugOffsets async_debug_offsets; uintptr_t interpreter_addr; diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index e4d5ee1ee6ae8e..9f35e2ce09f67c 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -208,6 +208,43 @@ is_prerelease_version(uint64_t version) return (version & 0xF0) != 0xF0; } +static void +calculate_interp_state_window(RemoteUnwinderObject *self) +{ + const struct _Py_DebugOffsets *off = &self->debug_offsets; + const struct { uint64_t offset; size_t size; } fields[] = { + {off->interpreter_state.id, sizeof(int64_t)}, + {off->interpreter_state.next, sizeof(uintptr_t)}, + {off->interpreter_state.threads_head, sizeof(uintptr_t)}, + {off->interpreter_state.threads_main, sizeof(uintptr_t)}, + {off->interpreter_state.gil_runtime_state_locked, sizeof(int)}, + {off->interpreter_state.gil_runtime_state_holder, sizeof(uintptr_t)}, + {off->interpreter_state.code_object_generation, sizeof(uint64_t)}, +#ifdef Py_GIL_DISABLED + {off->interpreter_state.tlbc_generation, sizeof(uint32_t)}, +#endif + {off->interpreter_state.gc + off->gc.frame, sizeof(uintptr_t)}, + }; + uint64_t start = UINT64_MAX; + uint64_t end = 0; + for (size_t i = 0; i < Py_ARRAY_LENGTH(fields); i++) { + if (fields[i].offset < start) { + start = fields[i].offset; + } + if (fields[i].offset + fields[i].size > end) { + end = fields[i].offset + fields[i].size; + } + } + start &= ~(uint64_t)7; + if (end > INTERP_STATE_BUFFER_SIZE || start >= end) { + self->interp_window_start = 0; + self->interp_window_size = INTERP_STATE_BUFFER_SIZE; + return; + } + self->interp_window_start = (size_t)start; + self->interp_window_size = (size_t)(end - start); +} + int validate_debug_offsets(struct _Py_DebugOffsets *debug_offsets) { @@ -407,6 +444,8 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, return -1; } + calculate_interp_state_window(self); + // Try to read async debug offsets, but don't fail if they're not available self->async_debug_offsets_available = 1; int async_debug_result = read_async_debug(self); @@ -589,9 +628,9 @@ refresh_generation_caches_for_interpreter( char interp_state_buffer[INTERP_STATE_BUFFER_SIZE]; if (_Py_RemoteDebug_ReadRemoteMemory( &self->handle, - interpreter_addr, - INTERP_STATE_BUFFER_SIZE, - interp_state_buffer) < 0) { + interpreter_addr + self->interp_window_start, + self->interp_window_size, + interp_state_buffer + self->interp_window_start) < 0) { set_exception_cause(self, PyExc_RuntimeError, "Failed to read interpreter state buffer"); return -1; @@ -611,13 +650,15 @@ read_interp_state_and_maybe_thread_frame( { prefetch->tstate = NULL; prefetch->frame = NULL; + size_t iw_start = unwinder->interp_window_start; + size_t iw_size = unwinder->interp_window_size; #if defined(__APPLE__) && TARGET_OS_OSX if (unwinder->cache_frames) { if (_Py_RemoteDebug_AliasedRead( unwinder, - interpreter_addr, - INTERP_STATE_BUFFER_SIZE, - interp_state_buffer) < 0) { + interpreter_addr + iw_start, + iw_size, + interp_state_buffer + iw_start) < 0) { return -1; } return 0; @@ -626,7 +667,8 @@ read_interp_state_and_maybe_thread_frame( if (prefetch->tstate_addr != 0) { size_t tstate_size = (size_t)unwinder->debug_offsets.thread_state.size; _Py_RemoteReadSegment segments[3] = { - {interpreter_addr, interp_state_buffer, INTERP_STATE_BUFFER_SIZE}, + {interpreter_addr + iw_start, interp_state_buffer + iw_start, + iw_size}, {prefetch->tstate_addr, tstate_buffer, tstate_size}, {prefetch->frame_addr, frame_buffer, SIZEOF_INTERP_FRAME}, }; @@ -634,9 +676,9 @@ read_interp_state_and_maybe_thread_frame( Py_ssize_t nread = _Py_RemoteDebug_BatchedReadRemoteMemory( &unwinder->handle, segments, nsegs); int completed = 0; - if (nread >= (Py_ssize_t)INTERP_STATE_BUFFER_SIZE) { + if (nread >= (Py_ssize_t)iw_size) { completed = 1; - Py_ssize_t with_tstate = (Py_ssize_t)INTERP_STATE_BUFFER_SIZE + Py_ssize_t with_tstate = (Py_ssize_t)iw_size + (Py_ssize_t)tstate_size; if (nread >= with_tstate) { completed = 2; @@ -659,9 +701,9 @@ read_interp_state_and_maybe_thread_frame( } return _Py_RemoteDebug_ReadRemoteMemory( &unwinder->handle, - interpreter_addr, - INTERP_STATE_BUFFER_SIZE, - interp_state_buffer); + interpreter_addr + iw_start, + iw_size, + interp_state_buffer + iw_start); } /*[clinic input] From 6c24960304bc57b0d9471db17295fc824bd8a39e Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 05:47:21 +0200 Subject: [PATCH 26/42] vm_max_address --- Modules/_remote_debugging/_remote_debugging.h | 1 + Modules/_remote_debugging/frames.c | 3 +++ Modules/_remote_debugging/module.c | 8 ++++++++ 3 files changed, 12 insertions(+) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 3c4745c0a6cb6a..05171b9dff04b5 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -394,6 +394,7 @@ typedef struct { struct _Py_DebugOffsets debug_offsets; size_t interp_window_start; size_t interp_window_size; + uintptr_t vm_max_address; int async_debug_offsets_available; struct _Py_AsyncioModuleDebugOffsets async_debug_offsets; uintptr_t interpreter_addr; diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index a9b9922697ea6c..2ab91dcce64eec 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -240,6 +240,9 @@ remote_pointer_plausible(RemoteUnwinderObject *unwinder, uintptr_t ptr) if (ptr < (uintptr_t)unwinder->handle.page_size) { return 0; } + if (unwinder->vm_max_address != 0) { + return ptr < unwinder->vm_max_address; + } #if UINTPTR_MAX > 0xffffffffU # if defined(__x86_64__) if (ptr >= (1ULL << 47)) { diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 9f35e2ce09f67c..c7f3ad35cbe095 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -420,8 +420,16 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, set_exception_cause(self, PyExc_RuntimeError, "Failed to initialize process handle"); return -1; } + self->vm_max_address = 0; #if defined(__APPLE__) && TARGET_OS_OSX _Py_RemoteDebug_AliasCacheInit(self); + task_vm_info_data_t vm_info; + mach_msg_type_number_t vm_count = TASK_VM_INFO_COUNT; + if (task_info(self->handle.task, TASK_VM_INFO, + (task_info_t)&vm_info, &vm_count) == KERN_SUCCESS + && vm_info.max_address > vm_info.min_address) { + self->vm_max_address = (uintptr_t)vm_info.max_address; + } #endif self->runtime_start_address = _Py_RemoteDebug_GetPyRuntimeAddress(&self->handle); From c7aedce4378a43744fa87aa0fad5f686d5627fc0 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 06:04:59 +0200 Subject: [PATCH 27/42] some love --- Modules/_remote_debugging/_remote_debugging.h | 9 --------- Modules/_remote_debugging/alias_read.c | 6 ++++-- Modules/_remote_debugging/frames.c | 5 +++-- 3 files changed, 7 insertions(+), 13 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 05171b9dff04b5..641cbbe52aa81c 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -280,7 +280,6 @@ typedef struct { typedef struct { uintptr_t remote_page_base; mach_vm_address_t local_page_base; - mach_vm_size_t size; uint64_t access_seq; int valid; uint64_t map_objid; @@ -698,14 +697,6 @@ extern int collect_frames_with_cache( uint64_t thread_id); #if defined(__APPLE__) && TARGET_OS_OSX -extern int parse_frame_object_aliased( - RemoteUnwinderObject *unwinder, - uintptr_t expected_parent, - PyObject **result, - uintptr_t address, - uintptr_t *address_of_code_object, - uintptr_t *previous_frame -); extern int _Py_RemoteDebug_ValidateThreadStateSnapshot( RemoteUnwinderObject *unwinder, diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 75e27f48318c78..344b51353d9a18 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -15,7 +15,7 @@ alias_query_region(task_t task, mach_vm_address_t region_addr = addr; mach_vm_size_t region_size = 0; natural_t depth = 0; - vm_region_submap_info_data_64_t info; + vm_region_submap_info_data_64_t info = {0}; mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64; kern_return_t kr = mach_vm_region_recurse( @@ -233,11 +233,13 @@ alias_remap_page(RemoteUnwinderObject *unwinder, STATS_INC(unwinder, alias_identity_mismatches); alias_disable_runtime(unwinder); } + else if (kr == KERN_NOT_SUPPORTED) { + alias_disable_runtime(unwinder); + } return -1; } entry->remote_page_base = page_base; - entry->size = (mach_vm_size_t)unwinder->handle.page_size; entry->access_seq = ++cache->access_seq; entry->valid = 1; diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index 2ab91dcce64eec..5f91ed60f79a83 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -292,7 +292,8 @@ validate_frame_snapshot( { int owner = (unsigned char)GET_MEMBER(char, frame, unwinder->debug_offsets.interpreter_frame.owner); - if (owner < FRAME_OWNED_BY_THREAD || owner > FRAME_OWNED_BY_INTERPRETER) { + if (owner < FRAME_OWNED_BY_THREAD || owner > FRAME_OWNED_BY_INTERPRETER + || owner == FRAME_OWNED_BY_FRAME_OBJECT) { return 0; } @@ -307,7 +308,7 @@ validate_frame_snapshot( return 1; } -int +static int parse_frame_object_aliased( RemoteUnwinderObject *unwinder, uintptr_t expected_parent, From 23d185f629c5dd163065bba2d0b7a322986e5fe3 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 06:19:45 +0200 Subject: [PATCH 28/42] dead prefetch computation on macos --- Modules/_remote_debugging/module.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index c7f3ad35cbe095..58dd39e66c168b 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -787,6 +787,7 @@ _remote_debugging_RemoteUnwinder_get_stack_trace_impl(RemoteUnwinderObject *self char prefetched_tstate[SIZEOF_THREAD_STATE]; char prefetched_frame[SIZEOF_INTERP_FRAME]; RemoteReadPrefetch prefetch = {0}; +#if !(defined(__APPLE__) && TARGET_OS_OSX) if (self->cache_frames) { prefetch.tstate_addr = get_cached_tstate_for_interpreter( self, current_interpreter); @@ -797,6 +798,7 @@ _remote_debugging_RemoteUnwinder_get_stack_trace_impl(RemoteUnwinderObject *self prefetch.frame_addr = entry->addrs[0]; } } +#endif if (read_interp_state_and_maybe_thread_frame( self, From 6dc781070056720d4cd60b4e3b3a5c6321be27a8 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 06:29:04 +0200 Subject: [PATCH 29/42] do it well, it's now confirmed to bring 3.4-3.6Mhz --- .../debug_offsets_validation.h | 33 +++++++++++++++++++ Modules/_remote_debugging/module.c | 23 +------------ 2 files changed, 34 insertions(+), 22 deletions(-) diff --git a/Modules/_remote_debugging/debug_offsets_validation.h b/Modules/_remote_debugging/debug_offsets_validation.h index 66c35e5522a9c7..9674f2eee47f71 100644 --- a/Modules/_remote_debugging/debug_offsets_validation.h +++ b/Modules/_remote_debugging/debug_offsets_validation.h @@ -488,6 +488,39 @@ _PyRemoteDebug_ValidateAsyncDebugOffsets( return 0; } +static inline void +_PyRemoteDebug_InterpStateWindow(const struct _Py_DebugOffsets *off, + uint64_t *start_out, uint64_t *end_out) +{ + uint64_t start = UINT64_MAX; + uint64_t end = 0; +#define PY_REMOTE_DEBUG_WINDOW_FIELD(section, field, field_size, align, buffer_size) \ + do { \ + uint64_t field_off = off->section.field; \ + if (field_off != 0) { \ + if (field_off < start) { \ + start = field_off; \ + } \ + if (field_off + (field_size) > end) { \ + end = field_off + (field_size); \ + } \ + } \ + } while (0) + PY_REMOTE_DEBUG_INTERPRETER_STATE_FIELDS(PY_REMOTE_DEBUG_WINDOW_FIELD, 0); +#undef PY_REMOTE_DEBUG_WINDOW_FIELD + uint64_t gc_frame_off = off->interpreter_state.gc + off->gc.frame; + if (gc_frame_off != 0) { + if (gc_frame_off < start) { + start = gc_frame_off; + } + if (gc_frame_off + sizeof(uintptr_t) > end) { + end = gc_frame_off + sizeof(uintptr_t); + } + } + *start_out = start; + *end_out = end; +} + #undef PY_REMOTE_DEBUG_VALIDATE_SECTION #undef PY_REMOTE_DEBUG_VALIDATE_READ_SECTION #undef PY_REMOTE_DEBUG_VALIDATE_FIELD diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 58dd39e66c168b..487779dc9dee93 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -211,30 +211,9 @@ is_prerelease_version(uint64_t version) static void calculate_interp_state_window(RemoteUnwinderObject *self) { - const struct _Py_DebugOffsets *off = &self->debug_offsets; - const struct { uint64_t offset; size_t size; } fields[] = { - {off->interpreter_state.id, sizeof(int64_t)}, - {off->interpreter_state.next, sizeof(uintptr_t)}, - {off->interpreter_state.threads_head, sizeof(uintptr_t)}, - {off->interpreter_state.threads_main, sizeof(uintptr_t)}, - {off->interpreter_state.gil_runtime_state_locked, sizeof(int)}, - {off->interpreter_state.gil_runtime_state_holder, sizeof(uintptr_t)}, - {off->interpreter_state.code_object_generation, sizeof(uint64_t)}, -#ifdef Py_GIL_DISABLED - {off->interpreter_state.tlbc_generation, sizeof(uint32_t)}, -#endif - {off->interpreter_state.gc + off->gc.frame, sizeof(uintptr_t)}, - }; uint64_t start = UINT64_MAX; uint64_t end = 0; - for (size_t i = 0; i < Py_ARRAY_LENGTH(fields); i++) { - if (fields[i].offset < start) { - start = fields[i].offset; - } - if (fields[i].offset + fields[i].size > end) { - end = fields[i].offset + fields[i].size; - } - } + _PyRemoteDebug_InterpStateWindow(&self->debug_offsets, &start, &end); start &= ~(uint64_t)7; if (end > INTERP_STATE_BUFFER_SIZE || start >= end) { self->interp_window_start = 0; From ddbeacd74b4bc3a4e5e3065f20de7ce96da16afe Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 06:30:02 +0200 Subject: [PATCH 30/42] build warning --- Modules/_remote_debugging/module.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 487779dc9dee93..789befa53c7e2c 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -522,6 +522,7 @@ interpreter_thread_cache_index(uintptr_t interpreter_addr) & (INTERPRETER_THREAD_CACHE_SIZE - 1); } +#if !(defined(__APPLE__) && TARGET_OS_OSX) static inline uintptr_t get_cached_tstate_for_interpreter( RemoteUnwinderObject *self, @@ -544,6 +545,7 @@ get_cached_tstate_for_interpreter( } return 0; } +#endif static inline void set_cached_tstate_for_interpreter( From 01369b7073d0bd0084870dc635864b6d093f87ea Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 06:49:26 +0200 Subject: [PATCH 31/42] harden --- .../_remote_debugging/debug_offsets_validation.h | 14 +++++++++++--- Modules/_remote_debugging/module.c | 11 +++++++++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/Modules/_remote_debugging/debug_offsets_validation.h b/Modules/_remote_debugging/debug_offsets_validation.h index 9674f2eee47f71..db6afcff9f3c1b 100644 --- a/Modules/_remote_debugging/debug_offsets_validation.h +++ b/Modules/_remote_debugging/debug_offsets_validation.h @@ -488,16 +488,20 @@ _PyRemoteDebug_ValidateAsyncDebugOffsets( return 0; } -static inline void +static inline int _PyRemoteDebug_InterpStateWindow(const struct _Py_DebugOffsets *off, uint64_t *start_out, uint64_t *end_out) { uint64_t start = UINT64_MAX; uint64_t end = 0; + int zero_skipped = 0; #define PY_REMOTE_DEBUG_WINDOW_FIELD(section, field, field_size, align, buffer_size) \ do { \ uint64_t field_off = off->section.field; \ - if (field_off != 0) { \ + if (field_off == 0) { \ + zero_skipped++; \ + } \ + else { \ if (field_off < start) { \ start = field_off; \ } \ @@ -509,7 +513,10 @@ _PyRemoteDebug_InterpStateWindow(const struct _Py_DebugOffsets *off, PY_REMOTE_DEBUG_INTERPRETER_STATE_FIELDS(PY_REMOTE_DEBUG_WINDOW_FIELD, 0); #undef PY_REMOTE_DEBUG_WINDOW_FIELD uint64_t gc_frame_off = off->interpreter_state.gc + off->gc.frame; - if (gc_frame_off != 0) { + if (gc_frame_off == 0) { + zero_skipped++; + } + else { if (gc_frame_off < start) { start = gc_frame_off; } @@ -519,6 +526,7 @@ _PyRemoteDebug_InterpStateWindow(const struct _Py_DebugOffsets *off, } *start_out = start; *end_out = end; + return zero_skipped; } #undef PY_REMOTE_DEBUG_VALIDATE_SECTION diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 789befa53c7e2c..53f37e22e78218 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -213,9 +213,16 @@ calculate_interp_state_window(RemoteUnwinderObject *self) { uint64_t start = UINT64_MAX; uint64_t end = 0; - _PyRemoteDebug_InterpStateWindow(&self->debug_offsets, &start, &end); + int zero_skipped = + _PyRemoteDebug_InterpStateWindow(&self->debug_offsets, &start, &end); +#ifdef Py_GIL_DISABLED + const int expected_zero_offsets = 0; +#else + const int expected_zero_offsets = 1; +#endif start &= ~(uint64_t)7; - if (end > INTERP_STATE_BUFFER_SIZE || start >= end) { + if (zero_skipped != expected_zero_offsets + || end > INTERP_STATE_BUFFER_SIZE || start >= end) { self->interp_window_start = 0; self->interp_window_size = INTERP_STATE_BUFFER_SIZE; return; From c8ee9c60339bec6c6ca15186a88ed8047f218dff Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 06:49:39 +0200 Subject: [PATCH 32/42] disable if target != local vm size --- Modules/_remote_debugging/module.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 53f37e22e78218..8ccc8759bc3c8f 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -412,9 +412,16 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, task_vm_info_data_t vm_info; mach_msg_type_number_t vm_count = TASK_VM_INFO_COUNT; if (task_info(self->handle.task, TASK_VM_INFO, - (task_info_t)&vm_info, &vm_count) == KERN_SUCCESS - && vm_info.max_address > vm_info.min_address) { - self->vm_max_address = (uintptr_t)vm_info.max_address; + (task_info_t)&vm_info, &vm_count) == KERN_SUCCESS) { + if (vm_info.max_address > vm_info.min_address) { + self->vm_max_address = (uintptr_t)vm_info.max_address; + } + if (vm_info.page_size > 0 + && (vm_info.page_size & (vm_info.page_size - 1)) == 0 + && (size_t)vm_info.page_size != (size_t)self->handle.page_size) { + self->alias_cache.disabled = 1; + _Py_RemoteDebug_AliasCacheClear(self); + } } #endif From 48d8c8ef4ddf7333e2c215e7ad47aead18a97602 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Wed, 10 Jun 2026 23:59:09 +0200 Subject: [PATCH 33/42] invalid frame != stale map it took me a while to understand it. --- Modules/_remote_debugging/frames.c | 1 - Modules/_remote_debugging/threads.c | 1 - 2 files changed, 2 deletions(-) diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index 5f91ed60f79a83..26c6162dd9c32b 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -330,7 +330,6 @@ parse_frame_object_aliased( if (!validate_frame_snapshot(unwinder, frame, expected_parent)) { STATS_INC(unwinder, alias_validation_fails); - _Py_RemoteDebug_AliasCacheInvalidatePage(unwinder, address); return parse_frame_object(unwinder, result, address, address_of_code_object, previous_frame); } diff --git a/Modules/_remote_debugging/threads.c b/Modules/_remote_debugging/threads.c index 82663d0a91a5f7..6b36f5b32349de 100644 --- a/Modules/_remote_debugging/threads.c +++ b/Modules/_remote_debugging/threads.c @@ -318,7 +318,6 @@ read_thread_state_and_maybe_frame( unwinder, tstate_buffer, tstate_addr, current_interpreter)) { STATS_INC(unwinder, alias_validation_fails); - _Py_RemoteDebug_AliasCacheInvalidatePage(unwinder, tstate_addr); return _Py_RemoteDebug_ReadRemoteMemory( &unwinder->handle, tstate_addr, tstate_size, tstate_buffer); } From aa1da19220d0082c17c9545efde1be56b8aa26ac Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 11 Jun 2026 01:16:20 +0200 Subject: [PATCH 34/42] probe check --- Modules/_remote_debugging/alias_read.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 344b51353d9a18..d05ce5127db9a2 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -285,6 +285,11 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, return _Py_RemoteDebug_ReadRemoteMemory( &unwinder->handle, remote_addr, len, dst); } + if (probe == 0) { + PyErr_SetString(PyExc_RuntimeError, + "alias page recycled under sample"); + return -1; + } if (probe > 0) { entry->access_seq = ++cache->access_seq; memcpy(dst, (const char *)entry->local_page_base + offset, len); From a097833b783160a6e71116802f3546428d23657a Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 11 Jun 2026 01:46:03 +0200 Subject: [PATCH 35/42] do not disable permanently on a single remap fail --- Modules/_remote_debugging/alias_read.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index d05ce5127db9a2..f3e5f7534b8254 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -137,8 +137,7 @@ alias_maybe_probe_entry(RemoteUnwinderObject *unwinder, entry->remote_page_base, &objid, &offset); if (rc < 0) { - STATS_INC(unwinder, alias_identity_mismatches); - alias_disable_runtime(unwinder); + alias_invalidate_entry(entry); return -1; } if (rc == 0 && objid == entry->map_objid && From d3dbcfcc1cd0cfaeb4da65be1221b10e1f5647c9 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 11 Jun 2026 01:46:42 +0200 Subject: [PATCH 36/42] KERN_NOT_SUPPORTED + fix stats --- Modules/_remote_debugging/alias_read.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index f3e5f7534b8254..81a303b88c6acc 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -228,11 +228,8 @@ alias_remap_page(RemoteUnwinderObject *unwinder, if (kr != KERN_SUCCESS) { alias_invalidate_entry(entry); STATS_INC(unwinder, alias_remap_failures); - if (kr == MACH_SEND_INVALID_DEST || kr == KERN_INVALID_ARGUMENT) { - STATS_INC(unwinder, alias_identity_mismatches); - alias_disable_runtime(unwinder); - } - else if (kr == KERN_NOT_SUPPORTED) { + if (kr == MACH_SEND_INVALID_DEST || kr == KERN_TERMINATED + || kr == KERN_NOT_SUPPORTED) { alias_disable_runtime(unwinder); } return -1; From e6f55b7d9641d653752bc33f0bb30d9ee56afc95 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 11 Jun 2026 02:50:41 +0200 Subject: [PATCH 37/42] better stats, better err handling --- Lib/test/test_external_inspection.py | 1 - Modules/_remote_debugging/_remote_debugging.h | 5 +++- Modules/_remote_debugging/alias_read.c | 30 +++++++++++++------ Modules/_remote_debugging/clinic/module.c.h | 4 +-- Modules/_remote_debugging/frames.c | 12 ++++---- Modules/_remote_debugging/module.c | 5 +--- Modules/_remote_debugging/threads.c | 13 ++++---- 7 files changed, 40 insertions(+), 30 deletions(-) diff --git a/Lib/test/test_external_inspection.py b/Lib/test/test_external_inspection.py index 14f62a43dfeb18..9de86a3401591b 100644 --- a/Lib/test/test_external_inspection.py +++ b/Lib/test/test_external_inspection.py @@ -4475,7 +4475,6 @@ def test_get_stats(self): "alias_remap_failures", "alias_validation_fails", "alias_evictions", - "alias_identity_mismatches", "alias_probe_checks", "alias_probe_recycles", "batched_read_success_rate", diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index 641cbbe52aa81c..c208dc6d42a536 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -319,7 +319,6 @@ typedef struct { uint64_t alias_remap_failures; // macOS remap/protect failures uint64_t alias_validation_fails; // macOS alias snapshot validation failures uint64_t alias_evictions; // macOS alias-cache LRU evictions - uint64_t alias_identity_mismatches; // macOS target identity mismatches uint64_t alias_probe_checks; // macOS alias object identity probes uint64_t alias_probe_recycles; // macOS alias recycled-page detections } UnwinderStats; @@ -704,6 +703,10 @@ extern int _Py_RemoteDebug_ValidateThreadStateSnapshot( uintptr_t tstate_addr, uintptr_t current_interpreter ); +/* Returns 0 if bytes were served from an aliased page snapshot (callers + * should validate), 1 if no snapshot was involved (live syscall read or + * zero-length no-op; skip validation), -1 on error with an exception + * set. */ extern int _Py_RemoteDebug_AliasedRead( RemoteUnwinderObject *unwinder, uintptr_t remote_addr, diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 81a303b88c6acc..20b5e80377c3d9 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -259,27 +259,36 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, { AliasReadCache *cache = &unwinder->alias_cache; if (len == 0) { - return 0; + return 1; } if (cache->disabled) { - return _Py_RemoteDebug_ReadRemoteMemory( - &unwinder->handle, remote_addr, len, dst); + if (_Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst) < 0) { + return -1; + } + return 1; } size_t page_size = (size_t)unwinder->handle.page_size; uintptr_t page_base = remote_addr & ~(uintptr_t)(page_size - 1); size_t offset = (size_t)(remote_addr - page_base); if (offset >= page_size || len > page_size - offset) { - return _Py_RemoteDebug_ReadRemoteMemory( - &unwinder->handle, remote_addr, len, dst); + if (_Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst) < 0) { + return -1; + } + return 1; } AliasPageEntry *entry = alias_find_entry(unwinder, page_base); if (entry != NULL) { int probe = alias_maybe_probe_entry(unwinder, entry); if (probe < 0) { - return _Py_RemoteDebug_ReadRemoteMemory( - &unwinder->handle, remote_addr, len, dst); + if (_Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst) < 0) { + return -1; + } + return 1; } if (probe == 0) { PyErr_SetString(PyExc_RuntimeError, @@ -296,8 +305,11 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, STATS_INC(unwinder, alias_misses); if (alias_remap_page(unwinder, page_base, &entry) < 0) { - return _Py_RemoteDebug_ReadRemoteMemory( - &unwinder->handle, remote_addr, len, dst); + if (_Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst) < 0) { + return -1; + } + return 1; } memcpy(dst, (const char *)entry->local_page_base + offset, len); return 0; diff --git a/Modules/_remote_debugging/clinic/module.c.h b/Modules/_remote_debugging/clinic/module.c.h index 06a4c582e2086a..3054fc2aa54131 100644 --- a/Modules/_remote_debugging/clinic/module.c.h +++ b/Modules/_remote_debugging/clinic/module.c.h @@ -451,8 +451,6 @@ PyDoc_STRVAR(_remote_debugging_RemoteUnwinder_get_stats__doc__, " - alias_validation_fails: macOS alias snapshot validation\n" " failures\n" " - alias_evictions: macOS alias-cache LRU evictions\n" -" - alias_identity_mismatches: macOS target identity\n" -" mismatches\n" " - alias_probe_checks: macOS alias object identity probes\n" " - alias_probe_recycles: macOS alias recycled-page detections\n" " - frame_cache_hit_rate: Percentage of samples that hit the\n" @@ -1721,4 +1719,4 @@ _remote_debugging_get_gc_stats(PyObject *module, PyObject *const *args, Py_ssize exit: return return_value; } -/*[clinic end generated code: output=170c53b2d66aed30 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=0daf86715e784985 input=a9049054013a1b77]*/ diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index 26c6162dd9c32b..eddf7a6b2a8046 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -318,22 +318,22 @@ parse_frame_object_aliased( uintptr_t *previous_frame) { char frame[SIZEOF_INTERP_FRAME]; - if (_Py_RemoteDebug_AliasedRead( - unwinder, address, SIZEOF_INTERP_FRAME, - frame) < 0) { + int rc = _Py_RemoteDebug_AliasedRead( + unwinder, address, SIZEOF_INTERP_FRAME, frame); + if (rc < 0) { set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read interpreter frame"); return -1; } - STATS_INC(unwinder, memory_reads); - STATS_ADD(unwinder, memory_bytes_read, SIZEOF_INTERP_FRAME); - if (!validate_frame_snapshot(unwinder, frame, expected_parent)) { + if (rc == 0 && !validate_frame_snapshot(unwinder, frame, expected_parent)) { STATS_INC(unwinder, alias_validation_fails); return parse_frame_object(unwinder, result, address, address_of_code_object, previous_frame); } + STATS_INC(unwinder, memory_reads); + STATS_ADD(unwinder, memory_bytes_read, SIZEOF_INTERP_FRAME); return parse_frame_buffer(unwinder, result, frame, address_of_code_object, previous_frame); } diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 8ccc8759bc3c8f..134fc3e27ee96a 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -1180,8 +1180,6 @@ RemoteUnwinder was created with stats=True. - alias_validation_fails: macOS alias snapshot validation failures - alias_evictions: macOS alias-cache LRU evictions - - alias_identity_mismatches: macOS target identity - mismatches - alias_probe_checks: macOS alias object identity probes - alias_probe_recycles: macOS alias recycled-page detections - frame_cache_hit_rate: Percentage of samples that hit the @@ -1199,7 +1197,7 @@ RemoteUnwinder was created with stats=True. static PyObject * _remote_debugging_RemoteUnwinder_get_stats_impl(RemoteUnwinderObject *self) -/*[clinic end generated code: output=21e36477122be2a0 input=d9bce4858ca7cbc7]*/ +/*[clinic end generated code: output=21e36477122be2a0 input=913e10ed7cabd40d]*/ { if (!self->collect_stats) { PyErr_SetString(PyExc_RuntimeError, @@ -1244,7 +1242,6 @@ _remote_debugging_RemoteUnwinder_get_stats_impl(RemoteUnwinderObject *self) ADD_STAT(alias_remap_failures); ADD_STAT(alias_validation_fails); ADD_STAT(alias_evictions); - ADD_STAT(alias_identity_mismatches); ADD_STAT(alias_probe_checks); ADD_STAT(alias_probe_recycles); diff --git a/Modules/_remote_debugging/threads.c b/Modules/_remote_debugging/threads.c index 6b36f5b32349de..ba85d03a03380d 100644 --- a/Modules/_remote_debugging/threads.c +++ b/Modules/_remote_debugging/threads.c @@ -307,14 +307,15 @@ read_thread_state_and_maybe_frame( *frame_read = 0; #if defined(__APPLE__) && TARGET_OS_OSX if (unwinder->cache_frames) { - if (_Py_RemoteDebug_AliasedRead( - unwinder, - tstate_addr, - tstate_size, - tstate_buffer) < 0) { + int rc = _Py_RemoteDebug_AliasedRead( + unwinder, + tstate_addr, + tstate_size, + tstate_buffer); + if (rc < 0) { return -1; } - if (!_Py_RemoteDebug_ValidateThreadStateSnapshot( + if (rc == 0 && !_Py_RemoteDebug_ValidateThreadStateSnapshot( unwinder, tstate_buffer, tstate_addr, current_interpreter)) { STATS_INC(unwinder, alias_validation_fails); From fcab0de1874d04a383fca0ca32117609186edd7c Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Thu, 11 Jun 2026 18:27:59 +0200 Subject: [PATCH 38/42] dead code --- Modules/_remote_debugging/_remote_debugging.h | 1 - Modules/_remote_debugging/alias_read.c | 12 ------------ 2 files changed, 13 deletions(-) diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index c208dc6d42a536..a7d3a3bf21984a 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -714,7 +714,6 @@ extern int _Py_RemoteDebug_AliasedRead( void *dst); extern void _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder); extern void _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder); -extern void _Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, uintptr_t remote_addr); #endif /* ============================================================================ diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 20b5e80377c3d9..56bb84340f733e 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -80,18 +80,6 @@ alias_disable_runtime(RemoteUnwinderObject *unwinder) _Py_RemoteDebug_AliasCacheClear(unwinder); } -void -_Py_RemoteDebug_AliasCacheInvalidatePage(RemoteUnwinderObject *unwinder, - uintptr_t remote_addr) -{ - size_t page_size = (size_t)unwinder->handle.page_size; - uintptr_t page_base = remote_addr & ~(uintptr_t)(page_size - 1); - AliasPageEntry *entry; - while ((entry = alias_find_entry(unwinder, page_base)) != NULL) { - alias_invalidate_entry(entry); - } -} - void _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) { From d0e2f53e0602c30eb4012b8128108b83cb117b73 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:06:37 +0100 Subject: [PATCH 39/42] aliased read_last_profiled_anchor --- Modules/_remote_debugging/frame_cache.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Modules/_remote_debugging/frame_cache.c b/Modules/_remote_debugging/frame_cache.c index 1b2d9a60f408b9..bc36b83b6fcf89 100644 --- a/Modules/_remote_debugging/frame_cache.c +++ b/Modules/_remote_debugging/frame_cache.c @@ -167,12 +167,21 @@ read_last_profiled_anchor(RemoteUnwinderObject *unwinder, // remote-memory read. if (seq_offset == frame_offset + sizeof(uintptr_t)) { uintptr_t live_anchor[2]; +#if defined(__APPLE__) && TARGET_OS_OSX + if (_Py_RemoteDebug_AliasedRead(unwinder, + thread_state_addr + frame_offset, + sizeof(live_anchor), + live_anchor) < 0) { + return -1; + } +#else if (_Py_RemoteDebug_ReadRemoteMemory(&unwinder->handle, thread_state_addr + frame_offset, sizeof(live_anchor), live_anchor) < 0) { return -1; } +#endif anchor->frame = live_anchor[0]; anchor->seq = live_anchor[1]; return 0; From bc94a395291bb5c641dbff3600a0e8f2315939b9 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:57:14 +0100 Subject: [PATCH 40/42] move to proc_handle_t --- Lib/test/test_external_inspection.py | 37 ++++++++++++ Modules/_remote_debugging/_remote_debugging.h | 30 ---------- Modules/_remote_debugging/alias_read.c | 58 ++++++++----------- Modules/_remote_debugging/module.c | 8 +-- Python/remote_debug.h | 46 ++++++++++++++- 5 files changed, 108 insertions(+), 71 deletions(-) diff --git a/Lib/test/test_external_inspection.py b/Lib/test/test_external_inspection.py index 9de86a3401591b..0ce4602136869d 100644 --- a/Lib/test/test_external_inspection.py +++ b/Lib/test/test_external_inspection.py @@ -4485,6 +4485,43 @@ def test_get_stats(self): self.assertEqual(stats["total_samples"], 1) + @unittest.skipUnless(sys.platform == "darwin", "macOS alias cache") + def test_alias_cache_lifetime(self): + script_body = """\ + def target(): + sock.sendall(b"ready") + sock.recv(16) + + target() + """ + + with self._target_process(script_body) as (p, client_socket, _): + _wait_for_signal(client_socket, b"ready") + for _ in range(3): + unwinder = RemoteUnwinder( + p.pid, all_threads=True, cache_frames=True, stats=True + ) + stats = unwinder.get_stats() + self.assertEqual(stats["alias_hits"], 0) + self.assertEqual(stats["alias_misses"], 0) + + for _ in range(2): + trace = unwinder.get_stack_trace() + self.assertIsNotNone(self._find_frame_in_trace( + trace, lambda frame: frame.funcname == "target" + )) + + stats = unwinder.get_stats() + self.assertEqual(stats["total_samples"], 2) + if (stats["alias_hits"] == 0 and + stats["alias_misses"] == stats["alias_remap_failures"]): + self.skipTest("Aliased reads are unavailable") + self.assertGreater(stats["alias_hits"], 0) + self.assertGreater(stats["alias_misses"], 0) + del unwinder + + client_socket.sendall(b"done") + @skip_if_not_supported @unittest.skipIf( sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, diff --git a/Modules/_remote_debugging/_remote_debugging.h b/Modules/_remote_debugging/_remote_debugging.h index a7d3a3bf21984a..994490983c64fc 100644 --- a/Modules/_remote_debugging/_remote_debugging.h +++ b/Modules/_remote_debugging/_remote_debugging.h @@ -271,31 +271,6 @@ typedef struct { uintptr_t frame_addr; } RemoteReadPrefetch; -#if defined(__APPLE__) && TARGET_OS_OSX -#define MAX_ALIAS_PAGES 256 -#define ALIAS_PROBE_DEFAULT_MASK 0x3ff -#define ALIAS_PROBE_MIN_MASK 0x3f -#define ALIAS_PROBE_MAX_MASK 0x3fff - -typedef struct { - uintptr_t remote_page_base; - mach_vm_address_t local_page_base; - uint64_t access_seq; - int valid; - uint64_t map_objid; - uint64_t map_offset; -} AliasPageEntry; - -typedef struct { - AliasPageEntry pages[MAX_ALIAS_PAGES]; - mach_vm_address_t region_base; - uint64_t access_seq; - uint32_t probe_counter; - uint32_t probe_mask; - int disabled; -} AliasReadCache; -#endif - /* Statistics for profiling performance analysis */ typedef struct { uint64_t total_samples; // Total number of get_stack_trace calls @@ -426,9 +401,6 @@ typedef struct { #ifdef __APPLE__ uint64_t thread_id_offset; int thread_id_offset_initialized; -# if TARGET_OS_OSX - AliasReadCache alias_cache; -# endif #endif #ifdef MS_WINDOWS PVOID win_process_buffer; @@ -712,8 +684,6 @@ extern int _Py_RemoteDebug_AliasedRead( uintptr_t remote_addr, size_t len, void *dst); -extern void _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder); -extern void _Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder); #endif /* ============================================================================ diff --git a/Modules/_remote_debugging/alias_read.c b/Modules/_remote_debugging/alias_read.c index 56bb84340f733e..eb2650a45fa237 100644 --- a/Modules/_remote_debugging/alias_read.c +++ b/Modules/_remote_debugging/alias_read.c @@ -45,7 +45,7 @@ alias_invalidate_entry(AliasPageEntry *entry) static AliasPageEntry * alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) { - AliasReadCache *cache = &unwinder->alias_cache; + AliasReadCache *cache = &unwinder->handle.alias_cache; for (int i = 0; i < MAX_ALIAS_PAGES; i++) { AliasPageEntry *entry = &cache->pages[i]; if (entry->valid && entry->remote_page_base == page_base) { @@ -55,48 +55,28 @@ alias_find_entry(RemoteUnwinderObject *unwinder, uintptr_t page_base) return NULL; } -void -_Py_RemoteDebug_AliasCacheClear(RemoteUnwinderObject *unwinder) -{ - AliasReadCache *cache = &unwinder->alias_cache; - for (int i = 0; i < MAX_ALIAS_PAGES; i++) { - alias_invalidate_entry(&cache->pages[i]); - } - if (cache->region_base != 0) { - mach_vm_size_t region_size = - (mach_vm_size_t)MAX_ALIAS_PAGES * - (mach_vm_size_t)unwinder->handle.page_size; - (void)mach_vm_deallocate(mach_task_self(), cache->region_base, - region_size); - cache->region_base = 0; - } -} - static void alias_disable_runtime(RemoteUnwinderObject *unwinder) { - AliasReadCache *cache = &unwinder->alias_cache; + AliasReadCache *cache = &unwinder->handle.alias_cache; cache->disabled = 1; - _Py_RemoteDebug_AliasCacheClear(unwinder); + _Py_RemoteDebug_AliasCacheClear(&unwinder->handle); } -void -_Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) +static int +alias_reserve_window(proc_handle_t *handle) { - AliasReadCache *cache = &unwinder->alias_cache; - memset(cache, 0, sizeof(*cache)); - cache->probe_mask = ALIAS_PROBE_DEFAULT_MASK; - + AliasReadCache *cache = &handle->alias_cache; mach_vm_size_t region_size = (mach_vm_size_t)MAX_ALIAS_PAGES * - (mach_vm_size_t)unwinder->handle.page_size; + (mach_vm_size_t)handle->page_size; kern_return_t kr = mach_vm_allocate(mach_task_self(), &cache->region_base, region_size, VM_FLAGS_ANYWHERE); if (kr != KERN_SUCCESS) { cache->disabled = 1; - return; + return -1; } kr = mach_vm_protect(mach_task_self(), cache->region_base, region_size, FALSE, VM_PROT_NONE); @@ -105,15 +85,16 @@ _Py_RemoteDebug_AliasCacheInit(RemoteUnwinderObject *unwinder) region_size); cache->region_base = 0; cache->disabled = 1; - return; + return -1; } + return 0; } static int alias_maybe_probe_entry(RemoteUnwinderObject *unwinder, AliasPageEntry *entry) { - AliasReadCache *cache = &unwinder->alias_cache; + AliasReadCache *cache = &unwinder->handle.alias_cache; if ((++cache->probe_counter & cache->probe_mask) != 0) { return 1; } @@ -147,7 +128,7 @@ alias_maybe_probe_entry(RemoteUnwinderObject *unwinder, static AliasPageEntry * alias_alloc_entry(RemoteUnwinderObject *unwinder) { - AliasReadCache *cache = &unwinder->alias_cache; + AliasReadCache *cache = &unwinder->handle.alias_cache; AliasPageEntry *oldest = NULL; for (int i = 0; i < MAX_ALIAS_PAGES; i++) { @@ -171,7 +152,7 @@ alias_map_readonly_page(RemoteUnwinderObject *unwinder, uintptr_t page_base, AliasPageEntry *entry) { - AliasReadCache *cache = &unwinder->alias_cache; + AliasReadCache *cache = &unwinder->handle.alias_cache; mach_vm_size_t page_size = (mach_vm_size_t)unwinder->handle.page_size; mach_vm_address_t local_addr = cache->region_base + (entry - cache->pages) * page_size; @@ -210,7 +191,7 @@ alias_remap_page(RemoteUnwinderObject *unwinder, uintptr_t page_base, AliasPageEntry **entry_out) { - AliasReadCache *cache = &unwinder->alias_cache; + AliasReadCache *cache = &unwinder->handle.alias_cache; AliasPageEntry *entry = alias_alloc_entry(unwinder); kern_return_t kr = alias_map_readonly_page(unwinder, page_base, entry); if (kr != KERN_SUCCESS) { @@ -245,7 +226,7 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, size_t len, void *dst) { - AliasReadCache *cache = &unwinder->alias_cache; + AliasReadCache *cache = &unwinder->handle.alias_cache; if (len == 0) { return 1; } @@ -268,6 +249,15 @@ _Py_RemoteDebug_AliasedRead(RemoteUnwinderObject *unwinder, return 1; } + if (cache->region_base == 0 && + alias_reserve_window(&unwinder->handle) < 0) { + if (_Py_RemoteDebug_ReadRemoteMemory( + &unwinder->handle, remote_addr, len, dst) < 0) { + return -1; + } + return 1; + } + AliasPageEntry *entry = alias_find_entry(unwinder, page_base); if (entry != NULL) { int probe = alias_maybe_probe_entry(unwinder, entry); diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index 134fc3e27ee96a..d31e950820554e 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -408,7 +408,6 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, } self->vm_max_address = 0; #if defined(__APPLE__) && TARGET_OS_OSX - _Py_RemoteDebug_AliasCacheInit(self); task_vm_info_data_t vm_info; mach_msg_type_number_t vm_count = TASK_VM_INFO_COUNT; if (task_info(self->handle.task, TASK_VM_INFO, @@ -419,8 +418,8 @@ _remote_debugging_RemoteUnwinder___init___impl(RemoteUnwinderObject *self, if (vm_info.page_size > 0 && (vm_info.page_size & (vm_info.page_size - 1)) == 0 && (size_t)vm_info.page_size != (size_t)self->handle.page_size) { - self->alias_cache.disabled = 1; - _Py_RemoteDebug_AliasCacheClear(self); + self->handle.alias_cache.disabled = 1; + _Py_RemoteDebug_AliasCacheClear(&self->handle); } } #endif @@ -1410,9 +1409,6 @@ RemoteUnwinder_dealloc(PyObject *op) if (self->tlbc_cache) { _Py_hashtable_destroy(self->tlbc_cache); } -#endif -#if defined(__APPLE__) && TARGET_OS_OSX - _Py_RemoteDebug_AliasCacheClear(self); #endif if (self->handle.pid != 0) { _Py_RemoteDebug_ClearCache(&self->handle); diff --git a/Python/remote_debug.h b/Python/remote_debug.h index a4a3a010926a7b..05ea591e18381c 100644 --- a/Python/remote_debug.h +++ b/Python/remote_debug.h @@ -167,11 +167,37 @@ typedef struct page_cache_entry { #define MAX_PAGES 1024 +#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX +#define MAX_ALIAS_PAGES 256 +#define ALIAS_PROBE_DEFAULT_MASK 0x3ff +#define ALIAS_PROBE_MIN_MASK 0x3f +#define ALIAS_PROBE_MAX_MASK 0x3fff + +typedef struct { + uintptr_t remote_page_base; + mach_vm_address_t local_page_base; + uint64_t access_seq; + int valid; + uint64_t map_objid; + uint64_t map_offset; +} AliasPageEntry; + +typedef struct { + AliasPageEntry pages[MAX_ALIAS_PAGES]; + mach_vm_address_t region_base; + uint64_t access_seq; + uint32_t probe_counter; + uint32_t probe_mask; + int disabled; +} AliasReadCache; +#endif + // Define a platform-independent process handle structure typedef struct { pid_t pid; #if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX mach_port_t task; + AliasReadCache alias_cache; #elif defined(MS_WINDOWS) HANDLE hProcess; #elif defined(__linux__) @@ -232,6 +258,20 @@ _Py_RemoteDebug_ClearCache(proc_handle_t *handle) } #if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX +static void +_Py_RemoteDebug_AliasCacheClear(proc_handle_t *handle) +{ + AliasReadCache *cache = &handle->alias_cache; + memset(cache->pages, 0, sizeof(cache->pages)); + if (cache->region_base != 0) { + mach_vm_size_t region_size = + (mach_vm_size_t)MAX_ALIAS_PAGES * (mach_vm_size_t)handle->page_size; + (void)mach_vm_deallocate(mach_task_self(), cache->region_base, + region_size); + cache->region_base = 0; + } +} + static mach_port_t pid_to_task(pid_t pid); #endif @@ -241,6 +281,8 @@ _Py_RemoteDebug_InitProcHandle(proc_handle_t *handle, pid_t pid) { handle->pid = 0; #if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX handle->task = 0; + memset(&handle->alias_cache, 0, sizeof(handle->alias_cache)); + handle->alias_cache.probe_mask = ALIAS_PROBE_DEFAULT_MASK; #elif defined(MS_WINDOWS) handle->hProcess = NULL; #elif defined(__linux__) @@ -277,7 +319,9 @@ _Py_RemoteDebug_InitProcHandle(proc_handle_t *handle, pid_t pid) { // Clean up the process handle UNUSED static void _Py_RemoteDebug_CleanupProcHandle(proc_handle_t *handle) { -#ifdef MS_WINDOWS +#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX + _Py_RemoteDebug_AliasCacheClear(handle); +#elif defined(MS_WINDOWS) if (handle->hProcess != NULL) { CloseHandle(handle->hProcess); handle->hProcess = NULL; From a1402771e4b54aa86ca4cdf090fa89d4c5f95840 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:42:44 +0100 Subject: [PATCH 41/42] read_stack_chunk --- Modules/_remote_debugging/frames.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index eddf7a6b2a8046..e2222dda3050d3 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -20,6 +20,19 @@ cleanup_stack_chunks(StackChunkList *chunks) PyMem_RawFree(chunks->chunks); } +static int +read_stack_chunk(proc_handle_t *handle, uintptr_t addr, size_t size, void *out) +{ +#if defined(__APPLE__) && TARGET_OS_OSX + if (!handle->alias_cache.disabled) { + // Read stack chunks directly to avoid validating cached VM aliases + // on every chunk read. + return _Py_RemoteDebug_ReadRemoteMemory(handle, addr, size, out); + } +#endif + return _Py_RemoteDebug_PagedReadRemoteMemory(handle, addr, size, out); +} + static int process_single_stack_chunk( RemoteUnwinderObject *unwinder, @@ -36,7 +49,7 @@ process_single_stack_chunk( return -1; } - if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, chunk_addr, current_size, this_chunk) < 0) { + if (read_stack_chunk(&unwinder->handle, chunk_addr, current_size, this_chunk) < 0) { PyMem_RawFree(this_chunk); set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read stack chunk"); return -1; @@ -65,7 +78,7 @@ process_single_stack_chunk( } this_chunk = tmp; - if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, chunk_addr, actual_size, this_chunk) < 0) { + if (read_stack_chunk(&unwinder->handle, chunk_addr, actual_size, this_chunk) < 0) { PyMem_RawFree(this_chunk); set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to reread stack chunk with correct size"); return -1; From 1b3859e87179e9e8129b7d47dc9aca3c46dd3376 Mon Sep 17 00:00:00 2001 From: maurycy <5383+maurycy@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:50:40 +0100 Subject: [PATCH 42/42] up --- Modules/_remote_debugging/frame_cache.c | 16 +- Modules/_remote_debugging/frames.c | 4 +- Modules/_remote_debugging/module.c | 21 ++ Modules/_remote_debugging/threads.c | 15 +- Python/remote_debug.h | 373 +++++++++++++++++++++++- 5 files changed, 419 insertions(+), 10 deletions(-) diff --git a/Modules/_remote_debugging/frame_cache.c b/Modules/_remote_debugging/frame_cache.c index 1b2d9a60f408b9..3f38c39c3fc225 100644 --- a/Modules/_remote_debugging/frame_cache.c +++ b/Modules/_remote_debugging/frame_cache.c @@ -167,10 +167,18 @@ read_last_profiled_anchor(RemoteUnwinderObject *unwinder, // remote-memory read. if (seq_offset == frame_offset + sizeof(uintptr_t)) { uintptr_t live_anchor[2]; - if (_Py_RemoteDebug_ReadRemoteMemory(&unwinder->handle, - thread_state_addr + frame_offset, - sizeof(live_anchor), - live_anchor) < 0) { + int rc = _Py_RemoteDebug_AliasedReadRemoteMemory(&unwinder->handle, + thread_state_addr + frame_offset, + sizeof(live_anchor), + live_anchor); + if (rc < 0) { + return -1; + } + if (rc > 0 + && _Py_RemoteDebug_ReadRemoteMemory(&unwinder->handle, + thread_state_addr + frame_offset, + sizeof(live_anchor), + live_anchor) < 0) { return -1; } anchor->frame = live_anchor[0]; diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index f5b9ed72f1f98e..1e0e98729ade7a 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -36,7 +36,7 @@ process_single_stack_chunk( return -1; } - if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, chunk_addr, current_size, this_chunk) < 0) { + if (_Py_RemoteDebug_ReadRemoteMemory(&unwinder->handle, chunk_addr, current_size, this_chunk) < 0) { PyMem_RawFree(this_chunk); set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read stack chunk"); return -1; @@ -65,7 +65,7 @@ process_single_stack_chunk( } this_chunk = tmp; - if (_Py_RemoteDebug_PagedReadRemoteMemory(&unwinder->handle, chunk_addr, actual_size, this_chunk) < 0) { + if (_Py_RemoteDebug_ReadRemoteMemory(&unwinder->handle, chunk_addr, actual_size, this_chunk) < 0) { PyMem_RawFree(this_chunk); set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to reread stack chunk with correct size"); return -1; diff --git a/Modules/_remote_debugging/module.c b/Modules/_remote_debugging/module.c index efb6d600247bf7..48e859175d2cf7 100644 --- a/Modules/_remote_debugging/module.c +++ b/Modules/_remote_debugging/module.c @@ -608,6 +608,27 @@ read_interp_state_and_maybe_thread_frame( { prefetch->tstate = NULL; prefetch->frame = NULL; + int aliased = _Py_RemoteDebug_AliasedReadRemoteMemory( + &unwinder->handle, interpreter_addr, INTERP_STATE_BUFFER_SIZE, + interp_state_buffer); + if (aliased < 0) { + return -1; + } + if (aliased == 0) { + if (prefetch->tstate_addr != 0) { + size_t tstate_size = (size_t)unwinder->debug_offsets.thread_state.size; + int rc = _Py_RemoteDebug_AliasedReadRemoteMemory( + &unwinder->handle, prefetch->tstate_addr, tstate_size, + tstate_buffer); + if (rc == 0) { + prefetch->tstate = tstate_buffer; + } + else if (rc < 0) { + PyErr_Clear(); + } + } + return 0; + } if (prefetch->tstate_addr != 0) { size_t tstate_size = (size_t)unwinder->debug_offsets.thread_state.size; _Py_RemoteReadSegment segments[3] = { diff --git a/Modules/_remote_debugging/threads.c b/Modules/_remote_debugging/threads.c index 120065022ddc8e..9e25796ae2046d 100644 --- a/Modules/_remote_debugging/threads.c +++ b/Modules/_remote_debugging/threads.c @@ -304,6 +304,11 @@ read_thread_state_and_maybe_frame( int *frame_read) { *frame_read = 0; + int aliased = _Py_RemoteDebug_AliasedReadRemoteMemory( + &unwinder->handle, tstate_addr, tstate_size, tstate_buffer); + if (aliased <= 0) { + return aliased; + } if (predicted_frame_addr != 0) { _Py_RemoteReadSegment segments[2] = { {tstate_addr, tstate_buffer, tstate_size}, @@ -380,11 +385,15 @@ unwind_stack_for_thread( } } else { - int rc = _Py_RemoteDebug_ReadRemoteMemory( - &unwinder->handle, + int unused_frame_read = 0; + int rc = read_thread_state_and_maybe_frame( + unwinder, *current_tstate, (size_t)unwinder->debug_offsets.thread_state.size, - local_ts); + local_ts, + 0, + NULL, + &unused_frame_read); if (rc < 0) { set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to read thread state"); goto error; diff --git a/Python/remote_debug.h b/Python/remote_debug.h index a4a3a010926a7b..8804435f8b16b7 100644 --- a/Python/remote_debug.h +++ b/Python/remote_debug.h @@ -167,11 +167,41 @@ typedef struct page_cache_entry { #define MAX_PAGES 1024 +#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX +// Read-only aliases of remote pages mapped into this process with +// mach_vm_remap(copy=FALSE). Reads served from an alias see the live +// remote memory without a syscall. +#define MAX_ALIAS_PAGES 256 +#define ALIAS_PROBE_DEFAULT_MASK 0x3ff +#define ALIAS_PROBE_MIN_MASK 0x3f +#define ALIAS_PROBE_MAX_MASK 0x3fff + +typedef struct { + uintptr_t remote_page_base; + mach_vm_address_t local_page_base; + uint64_t access_seq; + int valid; + uint64_t map_objid; + uint64_t map_offset; +} alias_page_entry_t; + +typedef struct { + alias_page_entry_t pages[MAX_ALIAS_PAGES]; + mach_vm_address_t region_base; + uint64_t access_seq; + uint32_t probe_counter; + uint32_t probe_mask; + int initialized; + int disabled; +} alias_read_cache_t; +#endif + // Define a platform-independent process handle structure typedef struct { pid_t pid; #if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX mach_port_t task; + alias_read_cache_t alias; #elif defined(MS_WINDOWS) HANDLE hProcess; #elif defined(__linux__) @@ -241,6 +271,7 @@ _Py_RemoteDebug_InitProcHandle(proc_handle_t *handle, pid_t pid) { handle->pid = 0; #if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX handle->task = 0; + memset(&handle->alias, 0, sizeof(handle->alias)); #elif defined(MS_WINDOWS) handle->hProcess = NULL; #elif defined(__linux__) @@ -274,10 +305,17 @@ _Py_RemoteDebug_InitProcHandle(proc_handle_t *handle, pid_t pid) { return 0; } +#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX +static void +_Py_RemoteDebug_AliasCacheClear(proc_handle_t *handle); +#endif + // Clean up the process handle UNUSED static void _Py_RemoteDebug_CleanupProcHandle(proc_handle_t *handle) { -#ifdef MS_WINDOWS +#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX + _Py_RemoteDebug_AliasCacheClear(handle); +#elif defined(MS_WINDOWS) if (handle->hProcess != NULL) { CloseHandle(handle->hProcess); handle->hProcess = NULL; @@ -1553,6 +1591,332 @@ _Py_RemoteDebug_WriteRemoteMemory(proc_handle_t *handle, uintptr_t remote_addres #endif } +#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX + +#ifndef VM_FLAGS_RETURN_DATA_ADDR +# define VM_FLAGS_RETURN_DATA_ADDR 0 +#endif + +static int +alias_query_region(task_t task, + mach_vm_address_t addr, + uint64_t *objid, + uint64_t *offset) +{ + mach_vm_address_t region_addr = addr; + mach_vm_size_t region_size = 0; + natural_t depth = 0; + vm_region_submap_info_data_64_t info = {0}; + mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64; + + kern_return_t kr = mach_vm_region_recurse( + task, ®ion_addr, ®ion_size, &depth, + (vm_region_recurse_info_t)&info, &count); + if (kr == MACH_SEND_INVALID_DEST || kr == KERN_INVALID_ARGUMENT) { + return -1; + } + if (kr != KERN_SUCCESS || addr < region_addr || + (mach_vm_size_t)(addr - region_addr) >= region_size || + info.is_submap) + { + return 1; + } + + *objid = info.object_id_full; + *offset = info.offset + (uint64_t)(addr - region_addr); + return 0; +} + +static void +alias_invalidate_entry(alias_page_entry_t *entry) +{ + memset(entry, 0, sizeof(*entry)); +} + +static alias_page_entry_t * +alias_find_entry(proc_handle_t *handle, uintptr_t page_base) +{ + alias_read_cache_t *cache = &handle->alias; + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + alias_page_entry_t *entry = &cache->pages[i]; + if (entry->valid && entry->remote_page_base == page_base) { + return entry; + } + } + return NULL; +} + +static void +_Py_RemoteDebug_AliasCacheClear(proc_handle_t *handle) +{ + alias_read_cache_t *cache = &handle->alias; + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + alias_invalidate_entry(&cache->pages[i]); + } + if (cache->region_base != 0) { + mach_vm_size_t region_size = + (mach_vm_size_t)MAX_ALIAS_PAGES * + (mach_vm_size_t)handle->page_size; + (void)mach_vm_deallocate(mach_task_self(), cache->region_base, + region_size); + cache->region_base = 0; + } +} + +static void +alias_disable_runtime(proc_handle_t *handle) +{ + handle->alias.disabled = 1; + _Py_RemoteDebug_AliasCacheClear(handle); +} + +// Reserve the local window the aliases are mapped into. Runs on the first +// aliased read so handles that never read through the page cache (for +// example sys.remote_exec) pay nothing. +static void +alias_cache_init(proc_handle_t *handle) +{ + alias_read_cache_t *cache = &handle->alias; + cache->initialized = 1; + cache->probe_mask = ALIAS_PROBE_DEFAULT_MASK; + + task_vm_info_data_t vm_info; + mach_msg_type_number_t vm_count = TASK_VM_INFO_COUNT; + if (task_info(handle->task, TASK_VM_INFO, + (task_info_t)&vm_info, &vm_count) == KERN_SUCCESS + && vm_info.page_size > 0 + && (vm_info.page_size & (vm_info.page_size - 1)) == 0 + && (size_t)vm_info.page_size != (size_t)handle->page_size) + { + cache->disabled = 1; + return; + } + + mach_vm_size_t region_size = + (mach_vm_size_t)MAX_ALIAS_PAGES * + (mach_vm_size_t)handle->page_size; + kern_return_t kr = mach_vm_allocate(mach_task_self(), + &cache->region_base, + region_size, + VM_FLAGS_ANYWHERE); + if (kr != KERN_SUCCESS) { + cache->disabled = 1; + return; + } + kr = mach_vm_protect(mach_task_self(), cache->region_base, region_size, + FALSE, VM_PROT_NONE); + if (kr != KERN_SUCCESS) { + (void)mach_vm_deallocate(mach_task_self(), cache->region_base, + region_size); + cache->region_base = 0; + cache->disabled = 1; + return; + } +} + +static int +alias_maybe_probe_entry(proc_handle_t *handle, alias_page_entry_t *entry) +{ + alias_read_cache_t *cache = &handle->alias; + if ((++cache->probe_counter & cache->probe_mask) != 0) { + return 1; + } + + uint64_t objid = 0; + uint64_t offset = 0; + int rc = alias_query_region(handle->task, entry->remote_page_base, + &objid, &offset); + if (rc < 0) { + alias_invalidate_entry(entry); + return -1; + } + if (rc == 0 && objid == entry->map_objid && + offset == entry->map_offset) + { + if (cache->probe_mask < ALIAS_PROBE_MAX_MASK) { + cache->probe_mask = (cache->probe_mask << 1) | 1; + } + return 1; + } + if (cache->probe_mask > ALIAS_PROBE_MIN_MASK) { + cache->probe_mask >>= 1; + } + alias_invalidate_entry(entry); + return 0; +} + +static alias_page_entry_t * +alias_alloc_entry(proc_handle_t *handle) +{ + alias_read_cache_t *cache = &handle->alias; + alias_page_entry_t *oldest = NULL; + + for (int i = 0; i < MAX_ALIAS_PAGES; i++) { + alias_page_entry_t *entry = &cache->pages[i]; + if (!entry->valid) { + return entry; + } + if (oldest == NULL || entry->access_seq < oldest->access_seq) { + oldest = entry; + } + } + + assert(oldest != NULL); + alias_invalidate_entry(oldest); + return oldest; +} + +static kern_return_t +alias_map_readonly_page(proc_handle_t *handle, + uintptr_t page_base, + alias_page_entry_t *entry) +{ + alias_read_cache_t *cache = &handle->alias; + mach_vm_size_t page_size = (mach_vm_size_t)handle->page_size; + mach_vm_address_t local_addr = + cache->region_base + (entry - cache->pages) * page_size; + vm_prot_t cur_protection = VM_PROT_NONE; + vm_prot_t max_protection = VM_PROT_NONE; + + kern_return_t kr = mach_vm_remap( + mach_task_self(), + &local_addr, + page_size, + 0, + VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE | VM_FLAGS_RETURN_DATA_ADDR, + handle->task, + (mach_vm_address_t)page_base, + FALSE, + &cur_protection, + &max_protection, + VM_INHERIT_NONE); + if (kr != KERN_SUCCESS) { + return kr; + } + if ((cur_protection & VM_PROT_READ) == 0) { + return KERN_PROTECTION_FAILURE; + } + kr = mach_vm_protect(mach_task_self(), local_addr, page_size, FALSE, + VM_PROT_READ); + if (kr != KERN_SUCCESS) { + return kr; + } + entry->local_page_base = local_addr; + return KERN_SUCCESS; +} + +static int +alias_remap_page(proc_handle_t *handle, + uintptr_t page_base, + alias_page_entry_t **entry_out) +{ + alias_read_cache_t *cache = &handle->alias; + alias_page_entry_t *entry = alias_alloc_entry(handle); + kern_return_t kr = alias_map_readonly_page(handle, page_base, entry); + if (kr != KERN_SUCCESS) { + alias_invalidate_entry(entry); + if (kr == MACH_SEND_INVALID_DEST || kr == KERN_TERMINATED + || kr == KERN_NOT_SUPPORTED) { + alias_disable_runtime(handle); + } + return -1; + } + + entry->remote_page_base = page_base; + entry->access_seq = ++cache->access_seq; + entry->valid = 1; + + if (alias_query_region(mach_task_self(), entry->local_page_base, + &entry->map_objid, &entry->map_offset) != 0) + { + alias_invalidate_entry(entry); + return -1; + } + + *entry_out = entry; + return 0; +} + +// Returns 0 with *entry_out set to a probed alias of page_base, 1 when the +// page has to be read with a syscall, -1 with an exception set when the +// alias was recycled under the caller. +static int +alias_lookup_page(proc_handle_t *handle, + uintptr_t page_base, + alias_page_entry_t **entry_out) +{ + alias_read_cache_t *cache = &handle->alias; + if (!cache->initialized) { + alias_cache_init(handle); + } + if (cache->disabled) { + return 1; + } + + alias_page_entry_t *entry = alias_find_entry(handle, page_base); + if (entry != NULL) { + int probe = alias_maybe_probe_entry(handle, entry); + if (probe < 0) { + return 1; + } + if (probe == 0) { + PyErr_SetString(PyExc_RuntimeError, + "alias page recycled under sample"); + return -1; + } + entry->access_seq = ++cache->access_seq; + *entry_out = entry; + return 0; + } + + if (alias_remap_page(handle, page_base, &entry) < 0) { + return 1; + } + *entry_out = entry; + return 0; +} + +#endif /* defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX */ + +// Optional fast path: serve the read from a mapping of the remote pages when +// the platform supports it. Returns 0 on success, 1 when the read must be +// done another way and -1 with an exception set when a mapped page was +// recycled under the sample. Only for memory whose mapping is stable for the +// lifetime of the target structure; data stack chunks are not. +UNUSED static int +_Py_RemoteDebug_AliasedReadRemoteMemory(proc_handle_t *handle, uintptr_t remote_address, size_t len, void* dst) +{ +#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX + size_t page_size = handle->page_size; + if (len == 0 || len > 2 * page_size) { + return 1; + } + uintptr_t addr = remote_address; + size_t remaining = len; + char *out = dst; + while (remaining > 0) { + uintptr_t page_base = addr & ~(page_size - 1); + size_t offset_in_page = addr - page_base; + size_t span = page_size - offset_in_page; + if (span > remaining) { + span = remaining; + } + alias_page_entry_t *alias = NULL; + int rc = alias_lookup_page(handle, page_base, &alias); + if (rc != 0) { + return rc; + } + memcpy(out, (const char *)alias->local_page_base + offset_in_page, span); + addr += span; + out += span; + remaining -= span; + } + return 0; +#else + return 1; +#endif +} + UNUSED static int _Py_RemoteDebug_PagedReadRemoteMemory(proc_handle_t *handle, uintptr_t addr, @@ -1567,6 +1931,13 @@ _Py_RemoteDebug_PagedReadRemoteMemory(proc_handle_t *handle, return _Py_RemoteDebug_ReadRemoteMemory(handle, addr, size, out); } + // Aliases copy only the requested bytes, with no page snapshot, so + // repeated reads of one page within a sample may differ. + int aliased = _Py_RemoteDebug_AliasedReadRemoteMemory(handle, addr, size, out); + if (aliased <= 0) { + return aliased; + } + // Search only the pages used since the last clear. The cache is cleared // between profiler samples, so entries are packed at the front. for (int i = 0; i < handle->page_cache_count; i++) {