Skip to content

Commit 21484fb

Browse files
committed
Fix T2C memory visibility race
The T2C compilation thread could set hot2 flag before compiled code was fully visible to the main thread, causing execution of invalid function pointers. This resulted in incorrect calculation results in the pi test. Fixed by declaring hot2 as volatile to ensure proper cross-thread visibility. The volatile qualifier guarantees fresh reads from memory and prevents compiler optimizations that could reorder accesses.
1 parent c75998b commit 21484fb

File tree

3 files changed

+5
-2
lines changed

3 files changed

+5
-2
lines changed

src/emulate.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,11 +1122,13 @@ void rv_step(void *arg)
11221122
#if RV32_HAS(T2C)
11231123
/* executed through the tier-2 JIT compiler */
11241124
if (block->hot2) {
1125+
/* hot2 is volatile, ensuring visibility across threads */
11251126
((exec_t2c_func_t) block->func)(rv);
11261127
prev = NULL;
11271128
continue;
11281129
} /* check if invoking times of t1 generated code exceed threshold */
11291130
else if (!block->compiled && block->n_invoke >= THRESHOLD) {
1131+
/* Mark block as queued for compilation to avoid re-queueing */
11301132
block->compiled = true;
11311133
queue_entry_t *entry = malloc(sizeof(queue_entry_t));
11321134
entry->block = block;

src/riscv_private.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,8 @@ typedef struct block {
8585

8686
rv_insn_t *ir_head, *ir_tail; /**< the first and last ir for this block */
8787
#if RV32_HAS(JIT)
88-
bool hot; /**< Determine the block is potential hotspot or not */
89-
bool hot2; /**< Determine the block is strong hotspot or not */
88+
bool hot; /**< Determine the block is potential hotspot or not */
89+
volatile bool hot2; /**< Determine the block is strong hotspot or not */
9090
bool
9191
translatable; /**< Determine the block has RV32AF insturctions or not */
9292
bool has_loops; /**< Determine the block has loop or not */

src/t2c.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,7 @@ void t2c_compile(riscv_t *rv, block_t *block)
346346

347347
jit_cache_update(rv->jit_cache, key, block->func);
348348

349+
/* hot2 is declared volatile, ensuring visibility across threads */
349350
block->hot2 = true;
350351
}
351352

0 commit comments

Comments
 (0)