[PATCH] accel/tcg: fix self-modify-code problem when modify code in a single tb loop

liweiwei@kubuds.cn posted 1 patch 1 month, 4 weeks ago
Patches applied successfully (tree, apply log)
git fetch https://github.com/patchew-project/qemu tags/patchew/6F6BF0F431B23852+20250917124734.443966-1-liweiwei@kubuds.cn
Maintainers: Richard Henderson <richard.henderson@linaro.org>, Paolo Bonzini <pbonzini@redhat.com>
accel/tcg/cpu-exec.c | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
[PATCH] accel/tcg: fix self-modify-code problem when modify code in a single tb loop
Posted by liweiwei@kubuds.cn 1 month, 4 weeks ago
From: Weiwei Li <liweiwei@kubuds.cn>

The problem is triggered in following conditions:
- thread 1:
    run spin loop(ended with a direct jump) like "0x0000006f, // jal zero, #0"
- thread 2:
    do something, and then modify the loop code of thread 1 to nop isntruction,
    finally wait thread 1 exit.

The loop tb which is patched to jump to itself, will not be updated in this case
and will never exit.

Signed-off-by: Weiwei Li <liweiwei@kubuds.cn>
---
 accel/tcg/cpu-exec.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/accel/tcg/cpu-exec.c b/accel/tcg/cpu-exec.c
index 8491e5badd..6919d068c8 100644
--- a/accel/tcg/cpu-exec.c
+++ b/accel/tcg/cpu-exec.c
@@ -973,8 +973,12 @@ cpu_exec_loop(CPUState *cpu, SyncClocks *sc)
                 last_tb = NULL;
             }
 #endif
-            /* See if we can patch the calling TB. */
-            if (last_tb) {
+            /*
+             * See if we can patch the calling TB.
+             * To make self-modifying code work, we prevent patching the single
+             * tb loop.
+             */
+            if (last_tb && last_tb != tb) {
                 tb_add_jump(last_tb, tb_exit, tb);
             }
 
-- 
2.43.0
Re: [PATCH] accel/tcg: fix self-modify-code problem when modify code in a single tb loop
Posted by Richard Henderson 1 month, 3 weeks ago
On 9/17/25 05:47, liweiwei@kubuds.cn wrote:
> From: Weiwei Li <liweiwei@kubuds.cn>
> 
> The problem is triggered in following conditions:
> - thread 1:
>      run spin loop(ended with a direct jump) like "0x0000006f, // jal zero, #0"
> - thread 2:
>      do something, and then modify the loop code of thread 1 to nop isntruction,
>      finally wait thread 1 exit.
> 
> The loop tb which is patched to jump to itself, will not be updated in this case
> and will never exit.
> 
> Signed-off-by: Weiwei Li <liweiwei@kubuds.cn>
> ---
>   accel/tcg/cpu-exec.c | 8 ++++++--
>   1 file changed, 6 insertions(+), 2 deletions(-)

If there's a problem with 1 tb, there's also a problem with 2 tb like

	jal	zero, #4
	jal	zero, #-4

But unlinking the tb should be part of invalidation, so I don't quite see where the 
problem is.  You need to expand on the description of the problem.


r~