[PATCH v2] accel/tcg: Do not chain from a TB freed by tb_gen_code's flush

Stian Halseth posted 1 patch 4 weeks, 1 day ago
Patches applied successfully (tree, apply log)
git fetch https://github.com/patchew-project/qemu tags/patchew/20261024070347.1202239-1-stian@itx.no
Maintainers: Richard Henderson <richard.henderson@linaro.org>, Paolo Bonzini <pbonzini@redhat.com>
accel/tcg/cpu-exec.c | 6 ++++++
1 file changed, 6 insertions(+)
[PATCH v2] accel/tcg: Do not chain from a TB freed by tb_gen_code's flush
Posted by Stian Halseth 4 weeks, 1 day ago
In a serial context, tb_gen_code() flushes a full code buffer and
retries in place. cpu_exec_loop() then chains its last_tb, now freed,
into the new TB. When that TB is invalidated, tb_jmp_unlink() follows
the stale entry and qemu crashes inside its SIGSEGV handler.

Drop last_tb when tb_gen_code() has flushed.

Since commit 25e5c6a320db ("accel/tcg: Allow cross-page goto_tb
chaining in user-only builds"), user-only builds hit this easily,
e.g. qemu-sparc64 -tb-size 1 on a program writing next to its PLT.

Cc: qemu-stable@nongnu.org
Fixes: ebf7a5d294a3 ("accel/tcg: Improve buffer overflow in tb_gen_code")
Signed-off-by: Stian Halseth <stian@itx.no>
Reviewed-by: Matt Turner <mattst88@gmail.com>
---
v2:
- Drop the second Fixes: tag. 25e5c6a320db only makes it easy to hit (Matt)
- Cc qemu-stable (Matt)
- Rebased on master, code unchanged

v1: https://lore.kernel.org/qemu-devel/20261023113245.562358-1-stian@itx.no/

 accel/tcg/cpu-exec.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/accel/tcg/cpu-exec.c b/accel/tcg/cpu-exec.c
index 5b4bca5084..600e8c5fa8 100644
--- a/accel/tcg/cpu-exec.c
+++ b/accel/tcg/cpu-exec.c
@@ -968,11 +968,17 @@ cpu_exec_loop(CPUState *cpu, SyncClocks *sc)
             if (tb == NULL) {
                 CPUJumpCache *jc;
                 uint32_t h;
+                unsigned flush_count = qatomic_read(&tb_ctx.tb_flush_count);
 
                 mmap_lock();
                 tb = tb_gen_code(cpu, s);
                 mmap_unlock();
 
+                /* tb_gen_code may have flushed, freeing last_tb. */
+                if (flush_count != qatomic_read(&tb_ctx.tb_flush_count)) {
+                    last_tb = NULL;
+                }
+
                 /*
                  * We add the TB in the virtual pc hash table
                  * for the fast lookup
-- 
2.43.0