Skip to content

Commit 5e981c5

Browse files
committed
refcount_insertion: fix use-after-realloc in updateInState + guard
Bug python#14: phx_rc_env_block_state reallocs block_states array, invalidating pred state pointers from collectPredStates. Fix: allocate current block's state BEFORE collecting pred pointers. Also add NULL/empty guard in initializeInState for predecessors whose out-state hasn't been populated yet (backedge case). Found via ASAN: heap-use-after-free in phx_sm_get called from phx_rc_initialize_in_state. match/case pattern matching now compiles.
1 parent 9f44b20 commit 5e981c5

1 file changed

Lines changed: 7 additions & 1 deletion

File tree

Python/jit/hir/refcount_pass_c.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,7 @@ void phx_rc_initialize_in_state(
461461
/* Clear the auto-added copy (model) since we'll add copies manually */
462462
phx_rs_kill_copy(rs, model);
463463

464+
if (!pred_state || pred_state->capacity == 0) continue;
464465
const PhxRegState *pred_rs = phx_sm_get(pred_state, model);
465466
if (!pred_rs) continue;
466467

@@ -566,10 +567,15 @@ void phx_rc_update_in_state(PhxRefcountEnv *env, void *block) {
566567
return;
567568
}
568569

570+
/* Pre-allocate block state BEFORE collecting pred pointers,
571+
* to prevent realloc from invalidating pred state pointers. */
572+
PhxBlockState *bstate = phx_rc_env_block_state(env, block);
573+
569574
size_t n_preds = 0;
570575
PhxPredState *preds = phx_rc_collect_pred_states(env, block, &n_preds);
571576

572-
PhxBlockState *bstate = phx_rc_env_block_state(env, block);
577+
/* Re-fetch after collectPredStates (no realloc since block already allocated) */
578+
bstate = phx_rc_env_block_state(env, block);
573579
PhxStateMap *in_state = &bstate->in;
574580

575581
/* First visit: initialize in-state */

0 commit comments

Comments
 (0)