plugins/execlog: fix segfault/race-cond on per-vCPU structures
PATCH v2 1/2 plugins/execlog: fix segfault/race-cond on per-vCPU structures
From: Harry van Haaren <[email protected]>
The existing code in execlog was never upgraded to the Scoreboard API, resulting in a bespoke implementation of per-vCPU datastructure handling. This had some race-conditions, and causes segfaults with a simple multi-threaded program and two instances of execlog running.
The patch here refactors the custom GArray and GRWLock code away, and uses the scoreboard APIs like the other plugins. This solves the "printing while expanding" race-condition of two plugins with multiple threads in the guest, and hence fixes a segfault.
---
Hi Qemu-Devel!
This is my first contribution to QEMU itself, but I have worked on DPDK, OVS, and QEMU-RS a bit in the past. I have experience with mailing lists for patches and some QEMU internals. I've read the 'submitting a patch' guide, and ran checkpatch... so basics should be OK I hope!
Please note that LLMs were used to investigate and fix this bug, but all code in this patch has been reviewed by me, and I believe it to be a good solution.
--- contrib/plugins/execlog.c | 65 +++++++++++++++------------------------ 1 file changed, 25 insertions(+), 40 deletions(-)
contrib/plugins/execlog.c +25 -40
@@ -31,33 +31,28 @@ typedef struct CPU { QEMU_PLUGIN_EXPORT int qemu_plugin_version = QEMU_PLUGIN_VERSION; -static GArray *cpus; -static GRWLock expand_array_lock; +/* +* Per-vCPU state stored in a qemu_plugin_scoreboard. The scoreboard manages +* per-vCPU storage automatically, eliminating the need for manual array +* growth, locks, or pointer-stability workarounds. +*/ +static struct qemu_plugin_scoreboard *cpus;static GPtrArray *imatches;static GArray *amatches;static GPtrArray *rmatches;static bool disas_assist;static GMutex add_reg_name_lock; +static GMutex execlog_output_mutex;static GPtrArray *all_reg_names; -static CPU *get_cpu (int vcpu_index) -{ -CPU *c; -g_rw_lock_reader_lock (&expand_array_lock); - c = &g_array_index (cpus,CPU , vcpu_index); -g_rw_lock_reader_unlock (&expand_array_lock); - -return c; -} -/** * Add memory read or write information to current instruction log */ static void vcpu_mem (unsigned int cpu_index,qemu_plugin_meminfo_t info,uint64_t vaddr,void *udata) { -CPU *c =get_cpu (cpu_index); +CPU *c =qemu_plugin_scoreboard_find (cpus, cpu_index);GString *s = c->last_exec;/* Find vCPU in array */
@@ -117,7 +112,7 @@ static void insn_check_regs(CPU *cpu)/* Log last instruction while checking registers */ static void vcpu_insn_exec_with_regs (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) {
@@ -125,8 +120,10 @@ static void vcpu_insn_exec_with_regs(unsigned int cpu_index, void *udata)insn_check_regs (cpu); } +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (cpu->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); }/* Store new instruction in cache */
@@ -138,7 +135,7 @@ static void vcpu_insn_exec_with_regs(unsigned int cpu_index, void *udata)/* Log last instruction while checking registers, ignore next */ static void vcpu_insn_exec_only_regs (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) {
@@ -146,8 +143,10 @@ static void vcpu_insn_exec_only_regs(unsigned int cpu_index, void *udata)insn_check_regs (cpu); } +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (cpu->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); }/* reset */
@@ -157,12 +156,14 @@ static void vcpu_insn_exec_only_regs(unsigned int cpu_index, void *udata)/* Log last instruction without checking regs, setup next */ static void vcpu_insn_exec (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) { +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (cpu->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); }/* Store new instruction in cache */
@@ -378,21 +379,10 @@ static GPtrArray *registers_init(int vcpu_index)* - last_exec tracking data * - list of tracked registers * - initial value of registers -* -* As we could have multiple threads trying to do this we need to -* serialise the expansion under a lock. */ static void vcpu_init (qemu_plugin_id_t id,unsigned int vcpu_index) { -CPU *c; - -g_rw_lock_writer_lock (&expand_array_lock); -if (vcpu_index >= cpus->len) { -g_array_set_size (cpus, vcpu_index +1 ); - } -g_rw_lock_writer_unlock (&expand_array_lock); - - c =get_cpu (vcpu_index); +CPU *c =qemu_plugin_scoreboard_find (cpus, vcpu_index); c->last_exec =g_string_new (NULL ); c->registers =registers_init (vcpu_index); }
@@ -402,16 +392,15 @@ static void vcpu_init(qemu_plugin_id_t id, unsigned int vcpu_index)*/ static void plugin_exit (qemu_plugin_id_t id,void *p) { -guint i; -g_rw_lock_reader_lock (&expand_array_lock); -for (i =0 ; i < cpus->len; i++) { -CPU *c =get_cpu (i); -if (c->last_exec && c->last_exec->str) { +int n =qemu_plugin_num_vcpus (); +for (int i =0 ; i < n; i++) { +CPU *c =qemu_plugin_scoreboard_find (cpus, i); +if (c->last_exec && c->last_exec->len) {qemu_plugin_outs (c->last_exec->str);qemu_plugin_outs ("\n" ); } } -g_rw_lock_reader_unlock (&expand_array_lock); +qemu_plugin_scoreboard_free (cpus); }/* Add a match to the array of matches */
@@ -452,12 +441,8 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id, const qemu_info_t *info, int argc, char **argv) { -/* -* Initialize dynamic array to cache vCPU instruction. In user mode -* we don't know the size before emulation. -*/ - cpus =g_array_sized_new (true, true,sizeof (CPU ), - info->system_emulation ? info->system.max_vcpus :1 ); +/* Initialize scoreboard to cache per-vCPU instruction state. */ + cpus =qemu_plugin_scoreboard_new (sizeof (CPU ));for (int i =0 ; i < argc; i++) {char *opt = argv[i];
--
2.54.0
The content, data, and any attached documents to this email are addressed exclusively to the addressee and are confidential and/or may be subject to a non-disclosure agreement. Any use, forwarding, disclosure, and/or copying, in whole or in part, without authorization is prohibited. If you have received this email in error, we apologize and, please notify the sender or Openchip immediately, and delete it from your system.
El contenido, los datos y cualquier documento adjunto a este correo electrónico están dirigidos exclusivamente al destinatario y son confidenciales y/o pueden estar sujetas a un acuerdo de no revelación. Está prohibido cualquier uso, reenvío, divulgación o copia, total o parcial, sin autorización. Si has recibido este correo por error, te pedimos disculpas y agradecemos que lo notifiques de inmediato al remitente o a Openchip, y lo elimines de tu sistema.
El contingut, les dades i qualsevol document adjunt a aquest correu electrònic estan dirigits exclusivament al destinatari i són confidencials i/o poden estar subjectes a un acord de no revelació. Està prohibit qualsevol ús, reenviament, divulgació o còpia, total o parcial, sense autorització. Si has rebut aquest correu per error, et demanem disculpes i agraïm que ho notifiquis d'immediat al remitent o a Openchip, i l'eliminis del teu sistema
Hi Harry,
Quoted 16 lines · Harry van Haaren | OPENCHIP
From: Harry van Haaren <[email protected]>
The existing code in execlog was never upgraded to the Scoreboard API, resulting in a bespoke implementation of per-vCPU datastructure handling. This had some race-conditions, and causes segfaults with a simple multi-threaded program and two instances of execlog running.
The patch here refactors the custom GArray and GRWLock code away, and uses the scoreboard APIs like the other plugins. This solves the "printing while expanding" race-condition of two plugins with multiple threads in the guest, and hence fixes a segfault.
Signed-off-by Harry van Haaren <[email protected]>---
Quoted 8 lines
Hi Qemu-Devel!
This is my first contribution to QEMU itself, but I have worked on DPDK, OVS, and QEMU-RS a bit in the past. I have experience with mailing lists for patches and some QEMU internals. I've read the 'submitting a patch' guide, and ran checkpatch... so basics should be OK I hope!
Welcome, and thanks for taking the time to contribute this!
It seems like there is no cover letter for your series, which is where this paragraph should go ideally. Also, I think its presence is kind of mandatory for tools manipulating it when having more than one patch, but not 100% sure.
I recommend you to use git-publish
(https://github.com/stefanha/git-publish) which does the right thing out of the box and make sure your series looks like any other. Yet another tool, sorry, but at least it's one of the "standard" here.
For the rest, I'll comment inline on the patches.
Quoted 174 lines
Please note that LLMs were used to investigate and fix this bug, but all code in this patch has been reviewed by me, and I believe it to be a good solution.
--- contrib/plugins/execlog.c | 65 +++++++++++++++------------------------ 1 file changed, 25 insertions(+), 40 deletions(-)contrib/plugins/execlog.c +25
-41@@ -31,33 +31,28 @@ typedef struct CPU { QEMU_PLUGIN_EXPORT int qemu_plugin_version = QEMU_PLUGIN_VERSION; -static GArray *cpus; -static GRWLock expand_array_lock; +/* +* Per-vCPU state stored in a qemu_plugin_scoreboard. The scoreboard manages +* per-vCPU storage automatically, eliminating the need for manual array +* growth, locks, or pointer-stability workarounds. +*/ +static struct qemu_plugin_scoreboard *cpus;static GPtrArray *imatches;static GArray *amatches;static GPtrArray *rmatches;static bool disas_assist;static GMutex add_reg_name_lock; +static GMutex execlog_output_mutex;static GPtrArray *all_reg_names; -static CPU *get_cpu (int vcpu_index) -{ -CPU *c; -g_rw_lock_reader_lock (&expand_array_lock); - c = &g_array_index (cpus,CPU , vcpu_index); -g_rw_lock_reader_unlock (&expand_array_lock); - -return c; -} -/** * Add memory read or write information to current instruction log */ static void vcpu_mem (unsigned int cpu_index,qemu_plugin_meminfo_t info,uint64_t vaddr,void *udata) { -CPU *c =get_cpu (cpu_index); +CPU *c =qemu_plugin_scoreboard_find (cpus, cpu_index);GString *s = c->last_exec;/* Find vCPU in array */ @@ -117,7 +112,7 @@ static void insn_check_regs(CPU *cpu)/* Log last instruction while checking registers */ static void vcpu_insn_exec_with_regs (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) {@@ -125,8 +120,10 @@ static void vcpu_insn_exec_with_regs(unsigned int cpu_index, void *udata)insn_check_regs (cpu); } +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (cpu->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); }/* Store new instruction in cache */ @@ -138,7 +135,7 @@ static void vcpu_insn_exec_with_regs(unsigned int cpu_index, void *udata)/* Log last instruction while checking registers, ignore next */ static void vcpu_insn_exec_only_regs (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) {@@ -146,8 +143,10 @@ static void vcpu_insn_exec_only_regs(unsigned int cpu_index, void *udata)insn_check_regs (cpu); } +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (cpu->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); }/* reset */ @@ -157,12 +156,14 @@ static void vcpu_insn_exec_only_regs(unsigned int cpu_index, void *udata)/* Log last instruction without checking regs, setup next */ static void vcpu_insn_exec (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) { +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (cpu->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); }/* Store new instruction in cache */ @@ -378,21 +379,10 @@ static GPtrArray *registers_init(int vcpu_index)* - last_exec tracking data * - list of tracked registers * - initial value of registers -* -* As we could have multiple threads trying to do this we need to -* serialise the expansion under a lock. */ static void vcpu_init (qemu_plugin_id_t id,unsigned int vcpu_index) { -CPU *c; - -g_rw_lock_writer_lock (&expand_array_lock); -if (vcpu_index >= cpus->len) { -g_array_set_size (cpus, vcpu_index +1 ); - } -g_rw_lock_writer_unlock (&expand_array_lock); - - c =get_cpu (vcpu_index); +CPU *c =qemu_plugin_scoreboard_find (cpus, vcpu_index); c->last_exec =g_string_new (NULL ); c->registers =registers_init (vcpu_index); }@@ -402,16 +392,15 @@ static void vcpu_init(qemu_plugin_id_t id, unsigned int vcpu_index)*/ static void plugin_exit (qemu_plugin_id_t id,void *p) { -guint i; -g_rw_lock_reader_lock (&expand_array_lock); -for (i =0 ; i < cpus->len; i++) { -CPU *c =get_cpu (i); -if (c->last_exec && c->last_exec->str) { +int n =qemu_plugin_num_vcpus (); +for (int i =0 ; i < n; i++) { +CPU *c =qemu_plugin_scoreboard_find (cpus, i); +if (c->last_exec && c->last_exec->len) {qemu_plugin_outs (c->last_exec->str);qemu_plugin_outs ("\n" ); } } -g_rw_lock_reader_unlock (&expand_array_lock); +qemu_plugin_scoreboard_free (cpus); }/* Add a match to the array of matches */ @@ -452,12 +441,8 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id, const qemu_info_t *info, int argc, char **argv) { -/* -* Initialize dynamic array to cache vCPU instruction. In user mode -* we don't know the size before emulation. -*/ - cpus =g_array_sized_new (true, true,sizeof (CPU ), - info->system_emulation ? info->system.max_vcpus :1 ); +/* Initialize scoreboard to cache per-vCPU instruction state. */ + cpus =qemu_plugin_scoreboard_new (sizeof (CPU ));for (int i =0 ; i < argc; i++) {char *opt = argv[i]; --2.54.0
Quoted 5 lines
The content, data, and any attached documents to this email are addressed exclusively to the addressee and are confidential and/or may be subject to a non-disclosure agreement. Any use, forwarding, disclosure, and/or copying, in whole or in part, without authorization is prohibited. If you have received this email in error, we apologize and, please notify the sender or Openchip immediately, and delete it from your system.
El contenido, los datos y cualquier documento adjunto a este correo electrónico están dirigidos exclusivamente al destinatario y son confidenciales y/o pueden estar sujetas a un acuerdo de no revelación. Está prohibido cualquier uso, reenvío, divulgación o copia, total o parcial, sin autorización. Si has recibido este correo por error, te pedimos disculpas y agradecemos que lo notifiques de inmediato al remitente o a Openchip, y lo elimines de tu sistema.
El contingut, les dades i qualsevol document adjunt a aquest correu electrònic estan dirigits exclusivament al destinatari i són confidencials i/o poden estar subjectes a un acord de no revelació. Està prohibit qualsevol ús, reenviament, divulgació o còpia, total o parcial, sense autorització. Si has rebut aquest correu per error, et demanem disculpes i agraïm que ho notifiquis d'immediat al remitent o a Openchip, i l'eliminis del teu sistema
Regards,
Pierrick
Quoted 27 lines
From: Pierrick Bouvier <[email protected]>
Sent: Tuesday 16 June 2026 7:32 pm
To: Harry van Haaren | OPENCHIP <[email protected]>; [email protected] <[email protected]>
Cc: [email protected] <[email protected]>; [email protected] <[email protected]>
Subject: Re: [PATCH 1/2] plugins/execlog: fix segfault/race-cond on per-vCPU structuresHi Harry,
Quoted 18 lines · Harry van Haaren | OPENCHIP
From: Harry van Haaren <[email protected]>
The existing code in execlog was never upgraded to the Scoreboard API, resulting in a bespoke implementation of per-vCPU datastructure handling. This had some race-conditions, and causes segfaults with a simple multi-threaded program and two instances of execlog running.
The patch here refactors the custom GArray and GRWLock code away, and uses the scoreboard APIs like the other plugins. This solves the "printing while expanding" race-condition of two plugins with multiple threads in the guest, and hence fixes a segfault.
Signed-off-by Harry van Haaren <[email protected]>---
Hi Qemu-Devel!
Quoted 8 lines
Quoted 6 lines
This is my first contribution to QEMU itself, but I have worked on DPDK, OVS, and QEMU-RS a bit in the past. I have experience with mailing lists for patches and some QEMU internals. I've read the 'submitting a patch' guide, and ran checkpatch... so basics should be OK I hope!
Welcome, and thanks for taking the time to contribute this!
Thank you!
Quoted 9 lines
It seems like there is no cover letter for your series, which is where this paragraph should go ideally. Also, I think its presence is kind of mandatory for tools manipulating it when having more than one patch, but not 100% sure.
I recommend you to use git-publish
(https://github.com/stefanha/git-publish) which does the right thing out of the box and make sure your series looks like any other. Yet another tool, sorry, but at least it's one of the "standard" here.
Understood - have used cover letters before, but not using the git-publish tool, will use this for future patches/sets.
Quoted 1 line
For the rest, I'll comment inline on the patches.
Thanks for the quick response!
I've not yet respun the patchset as I'm also getting the "footer" removed (I wasn't expecting it to be added). Will resend patchset (in-reply-to the 1st patch) with cover letter etc. once that is completed.
Regards, -Harry
<snip: rest of message content, including footer>
The content, data, and any attached documents to this email are addressed exclusively to the addressee and are confidential and/or may be subject to a non-disclosure agreement. Any use, forwarding, disclosure, and/or copying, in whole or in part, without authorization is prohibited. If you have received this email in error, we apologize and, please notify the sender or Openchip immediately, and delete it from your system.
El contenido, los datos y cualquier documento adjunto a este correo electrónico están dirigidos exclusivamente al destinatario y son confidenciales y/o pueden estar sujetas a un acuerdo de no revelación. Está prohibido cualquier uso, reenvío, divulgación o copia, total o parcial, sin autorización. Si has recibido este correo por error, te pedimos disculpas y agradecemos que lo notifiques de inmediato al remitente o a Openchip, y lo elimines de tu sistema.
El contingut, les dades i qualsevol document adjunt a aquest correu electrònic estan dirigits exclusivament al destinatari i són confidencials i/o poden estar subjectes a un acord de no revelació. Està prohibit qualsevol ús, reenviament, divulgació o còpia, total o parcial, sense autorització. Si has rebut aquest correu per error, et demanem disculpes i agraïm que ho notifiquis d'immediat al remitent o a Openchip, i l'eliminis del teu sistema
Quoted 2 lines · Harry van Haaren | OPENCHIP
From: Harry van Haaren <[email protected]>
No needed for this From: tag since you are already the sender and have a signed-off-by.
Quoted 10 lines
The existing code in execlog was never upgraded to the Scoreboard API, resulting in a bespoke implementation of per-vCPU datastructure handling. This had some race-conditions, and causes segfaults with a simple multi-threaded program and two instances of execlog running.
The patch here refactors the custom GArray and GRWLock code away, and uses the scoreboard APIs like the other plugins. This solves the "printing while expanding" race-condition of two plugins with multiple threads in the guest, and hence fixes a segfault.
Great!
Quoted 32 lines
Signed-off-by Harry van Haaren <[email protected]>---
Hi Qemu-Devel!
This is my first contribution to QEMU itself, but I have worked on DPDK, OVS, and QEMU-RS a bit in the past. I have experience with mailing lists for patches and some QEMU internals. I've read the 'submitting a patch' guide, and ran checkpatch... so basics should be OK I hope!
Please note that LLMs were used to investigate and fix this bug, but all code in this patch has been reviewed by me, and I believe it to be a good solution.
--- contrib/plugins/execlog.c | 65 +++++++++++++++------------------------ 1 file changed, 25 insertions(+), 40 deletions(-)contrib/plugins/execlog.c +3
-2@@ -31,33 +31,28 @@ typedef struct CPU { QEMU_PLUGIN_EXPORT int qemu_plugin_version = QEMU_PLUGIN_VERSION; -static GArray *cpus; -static GRWLock expand_array_lock; +/* +* Per-vCPU state stored in a qemu_plugin_scoreboard. The scoreboard manages +* per-vCPU storage automatically, eliminating the need for manual array
contrib/plugins/execlog.c typedef struct CPU { · line 46
Quoted 10 lines
contrib/plugins/execlog.c +4
-0+* growth, locks, or pointer-stability workarounds. +*/ +static struct qemu_plugin_scoreboard *cpus;static GPtrArray *imatches;static GArray *amatches;static GPtrArray *rmatches;static bool disas_assist;static GMutex add_reg_name_lock; +static GMutex execlog_output_mutex;
QEMU log already has some locking mechanism, you just need to make sure you output everything in a single call at a time if you want atomicity. To help with string manipulation, you can use a GString to build a message. (see other plugins, it's a common pattern).
So you can remove this mutex and code associated, and make sure you have a single call to qemu_plugin_outs in every function.
Quoted 144 lines
contrib/plugins/execlog.c +18
-39static GPtrArray *all_reg_names; -static CPU *get_cpu (int vcpu_index) -{ -CPU *c; -g_rw_lock_reader_lock (&expand_array_lock); - c = &g_array_index (cpus,CPU , vcpu_index); -g_rw_lock_reader_unlock (&expand_array_lock); - -return c; -} -/** * Add memory read or write information to current instruction log */ static void vcpu_mem (unsigned int cpu_index,qemu_plugin_meminfo_t info,uint64_t vaddr,void *udata) { -CPU *c =get_cpu (cpu_index); +CPU *c =qemu_plugin_scoreboard_find (cpus, cpu_index);GString *s = c->last_exec;/* Find vCPU in array */ @@ -117,7 +112,7 @@ static void insn_check_regs(CPU *cpu)/* Log last instruction while checking registers */ static void vcpu_insn_exec_with_regs (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) {@@ -125,8 +120,10 @@ static void vcpu_insn_exec_with_regs(unsigned int cpu_index, void *udata)insn_check_regs (cpu); } +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (cpu->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); }/* Store new instruction in cache */ @@ -138,7 +135,7 @@ static void vcpu_insn_exec_with_regs(unsigned int cpu_index, void *udata)/* Log last instruction while checking registers, ignore next */ static void vcpu_insn_exec_only_regs (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) {@@ -146,8 +143,10 @@ static void vcpu_insn_exec_only_regs(unsigned int cpu_index, void *udata)insn_check_regs (cpu); } +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (cpu->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); }/* reset */ @@ -157,12 +156,14 @@ static void vcpu_insn_exec_only_regs(unsigned int cpu_index, void *udata)/* Log last instruction without checking regs, setup next */ static void vcpu_insn_exec (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) { +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (cpu->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); }/* Store new instruction in cache */ @@ -378,21 +379,10 @@ static GPtrArray *registers_init(int vcpu_index)* - last_exec tracking data * - list of tracked registers * - initial value of registers -* -* As we could have multiple threads trying to do this we need to -* serialise the expansion under a lock. */ static void vcpu_init (qemu_plugin_id_t id,unsigned int vcpu_index) { -CPU *c; - -g_rw_lock_writer_lock (&expand_array_lock); -if (vcpu_index >= cpus->len) { -g_array_set_size (cpus, vcpu_index +1 ); - } -g_rw_lock_writer_unlock (&expand_array_lock); - - c =get_cpu (vcpu_index); +CPU *c =qemu_plugin_scoreboard_find (cpus, vcpu_index); c->last_exec =g_string_new (NULL ); c->registers =registers_init (vcpu_index); }@@ -402,16 +392,15 @@ static void vcpu_init(qemu_plugin_id_t id, unsigned int vcpu_index)*/ static void plugin_exit (qemu_plugin_id_t id,void *p) { -guint i; -g_rw_lock_reader_lock (&expand_array_lock); -for (i =0 ; i < cpus->len; i++) { -CPU *c =get_cpu (i); -if (c->last_exec && c->last_exec->str) { +int n =qemu_plugin_num_vcpus (); +for (int i =0 ; i < n; i++) { +CPU *c =qemu_plugin_scoreboard_find (cpus, i); +if (c->last_exec && c->last_exec->len) {qemu_plugin_outs (c->last_exec->str);qemu_plugin_outs ("\n" ); } } -g_rw_lock_reader_unlock (&expand_array_lock); +qemu_plugin_scoreboard_free (cpus); }/* Add a match to the array of matches */ @@ -452,12 +441,8 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id, const qemu_info_t *info, int argc, char **argv) { -/* -* Initialize dynamic array to cache vCPU instruction. In user mode -* we don't know the size before emulation. -*/ - cpus =g_array_sized_new (true, true,sizeof (CPU ), - info->system_emulation ? info->system.max_vcpus :1 ); +/* Initialize scoreboard to cache per-vCPU instruction state. */ + cpus =qemu_plugin_scoreboard_new (sizeof (CPU ));for (int i =0 ; i < argc; i++) {char *opt = argv[i]; --2.54.0
Quoted 5 lines
The content, data, and any attached documents to this email are addressed exclusively to the addressee and are confidential and/or may be subject to a non-disclosure agreement. Any use, forwarding, disclosure, and/or copying, in whole or in part, without authorization is prohibited. If you have received this email in error, we apologize and, please notify the sender or Openchip immediately, and delete it from your system.
El contenido, los datos y cualquier documento adjunto a este correo electrónico están dirigidos exclusivamente al destinatario y son confidenciales y/o pueden estar sujetas a un acuerdo de no revelación. Está prohibido cualquier uso, reenvío, divulgación o copia, total o parcial, sin autorización. Si has recibido este correo por error, te pedimos disculpas y agradecemos que lo notifiques de inmediato al remitente o a Openchip, y lo elimines de tu sistema.
El contingut, les dades i qualsevol document adjunt a aquest correu electrònic estan dirigits exclusivament al destinatari i són confidencials i/o poden estar subjectes a un acord de no revelació. Està prohibit qualsevol ús, reenviament, divulgació o còpia, total o parcial, sense autorització. Si has rebut aquest correu per error, et demanem disculpes i agraïm que ho notifiquis d'immediat al remitent o a Openchip, i l'eliminis del teu sistema
Regards,
Pierrick
Quoted 6 lines · Pierrick Bouvier
Quoted 2 lines · Harry van Haaren | OPENCHIP
From: Harry van Haaren <[email protected]>
No needed for this From: tag since you are already the sender and have a signed-off-by.
But the message From: field has "| OPENCHIP" in the name which I think is intended to be removed by this tag so it's OK to have it. If it was the same as the From: field of the message it would not be needed indeed.
Regards,
BALATON Zoltan
Quoted 5 lines · BALATON Zoltan
Quoted 4 lines · Pierrick Bouvier
Quoted 2 lines · Harry van Haaren | OPENCHIP
From: Harry van Haaren <[email protected]>
Quoted 7 lines
Quoted 2 lines
No needed for this From: tag since you are already the sender and have a signed-off-by.
But the message From: field has "| OPENCHIP" in the name which I think is intended to be removed by this tag so it's OK to have it. If it was the same as the From: field of the message it would not be needed indeed.
Good catch Zoltan!
I didn't even notice the '| OPENCHIP' in the name to be honest.
Quoted 2 lines
Regards,
BALATON Zoltan
PATCH v2 2/2 plugins/execlog: fix execlog vcpu_exit execution print loss
In reply to Harry van Haaren | OPENCHIPFrom: Harry van Haaren <[email protected]>
Executed instructions are cached in string format inside the execlog plugin. These strings are flushed on exit of a TB, improving performance. This causes executed instructions to be lost when an 'ecall' (riscv system call) occurs that causes the thread to terminate.
The fix in this patch registers an 'on_exit()' callback, and flushes any content in the c->last_exec buffer, to ensure all instructions are present in the final instruction log.
A mutex lock/unlock is added around the plugin exit, to ensure the lines are not corrupted.
---
Please note that LLMs were used to investigate and fix this bug, but all code in this patch has been reviewed by me, and I believe it to be a good solution.
--- contrib/plugins/execlog.c | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-)
contrib/plugins/execlog.c +25 -1
@@ -388,7 +388,28 @@ static void vcpu_init(qemu_plugin_id_t id, unsigned int vcpu_index) }/** -* On plugin exit, print last instruction in cache +* On vCPU exit, flush the last cached instruction for this vCPU. +* +* The one-instruction-delay pattern stores each instruction in last_exec and +* only prints it when the *next* callback fires. When a thread exits via +* syscall (e.g. ecall/exit), no subsequent callback fires for that vCPU and +* the final instruction is silently dropped. Flushing here guarantees it is +* written before the vCPU is torn down. +*/ +static void vcpu_exit (qemu_plugin_id_t id,unsigned int vcpu_index) +{ +CPU *c =qemu_plugin_scoreboard_find (cpus, vcpu_index); +if (c->last_exec && c->last_exec->len) { +g_mutex_lock (&execlog_output_mutex); +qemu_plugin_outs (c->last_exec->str); +qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); +g_string_truncate (c->last_exec,0 ); + } +} + +/** +* On plugin exit, flush any remaining cached instructions and free state. */ static void plugin_exit (qemu_plugin_id_t id,void *p) {
@@ -396,8 +417,10 @@ static void plugin_exit(qemu_plugin_id_t id, void *p)for (int i =0 ; i < n; i++) {CPU *c =qemu_plugin_scoreboard_find (cpus, i);if (c->last_exec && c->last_exec->len) { +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (c->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); } }qemu_plugin_scoreboard_free (cpus);
@@ -467,6 +490,7 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,/* Register init, translation block and exit callbacks */ qemu_plugin_register_vcpu_init_cb (id, vcpu_init); +qemu_plugin_register_vcpu_exit_cb (id, vcpu_exit);qemu_plugin_register_vcpu_tb_trans_cb (id, vcpu_tb_trans);qemu_plugin_register_atexit_cb (id, plugin_exit,NULL );
--
2.54.0
The content, data, and any attached documents to this email are addressed exclusively to the addressee and are confidential and/or may be subject to a non-disclosure agreement. Any use, forwarding, disclosure, and/or copying, in whole or in part, without authorization is prohibited. If you have received this email in error, we apologize and, please notify the sender or Openchip immediately, and delete it from your system.
El contenido, los datos y cualquier documento adjunto a este correo electrónico están dirigidos exclusivamente al destinatario y son confidenciales y/o pueden estar sujetas a un acuerdo de no revelación. Está prohibido cualquier uso, reenvío, divulgación o copia, total o parcial, sin autorización. Si has recibido este correo por error, te pedimos disculpas y agradecemos que lo notifiques de inmediato al remitente o a Openchip, y lo elimines de tu sistema.
El contingut, les dades i qualsevol document adjunt a aquest correu electrònic estan dirigits exclusivament al destinatari i són confidencials i/o poden estar subjectes a un acord de no revelació. Està prohibit qualsevol ús, reenviament, divulgació o còpia, total o parcial, sense autorització. Si has rebut aquest correu per error, et demanem disculpes i agraïm que ho notifiquis d'immediat al remitent o a Openchip, i l'eliminis del teu sistema
Re: [PATCH 2/2] plugins/execlog: fix execlog vcpu_exit execution print loss
Quoted 71 lines · Harry van Haaren | OPENCHIP
From: Harry van Haaren <[email protected]>
Executed instructions are cached in string format inside the execlog plugin. These strings are flushed on exit of a TB, improving performance. This causes executed instructions to be lost when an 'ecall' (riscv system call) occurs that causes the thread to terminate.
The fix in this patch registers an '
on_exit()' callback, and flushes any content in thec->last_execbuffer, to ensure all instructions are present in the final instruction log.A mutex lock/unlock is added around the plugin exit, to ensure the lines are not corrupted.
Signed-off-by Harry van Haaren <[email protected]>---
Please note that LLMs were used to investigate and fix this bug, but all code in this patch has been reviewed by me, and I believe it to be a good solution.
--- contrib/plugins/execlog.c | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-)contrib/plugins/execlog.c +24
-1@@ -388,7 +388,28 @@ static void vcpu_init(qemu_plugin_id_t id, unsigned int vcpu_index) }/** -* On plugin exit, print last instruction in cache +* On vCPU exit, flush the last cached instruction for this vCPU. +* +* The one-instruction-delay pattern stores each instruction in last_exec and +* only prints it when the *next* callback fires. When a thread exits via +* syscall (e.g. ecall/exit), no subsequent callback fires for that vCPU and +* the final instruction is silently dropped. Flushing here guarantees it is +* written before the vCPU is torn down. +*/ +static void vcpu_exit (qemu_plugin_id_t id,unsigned int vcpu_index) +{ +CPU *c =qemu_plugin_scoreboard_find (cpus, vcpu_index); +if (c->last_exec && c->last_exec->len) { +g_mutex_lock (&execlog_output_mutex); +qemu_plugin_outs (c->last_exec->str); +qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); +g_string_truncate (c->last_exec,0 ); + } +} + +/** +* On plugin exit, flush any remaining cached instructions and free state. */ static void plugin_exit (qemu_plugin_id_t id,void *p) {@@ -396,8 +417,10 @@ static void plugin_exit(qemu_plugin_id_t id, void *p)for (int i =0 ; i < n; i++) {CPU *c =qemu_plugin_scoreboard_find (cpus, i);if (c->last_exec && c->last_exec->len) { +g_mutex_lock (&execlog_output_mutex);qemu_plugin_outs (c->last_exec->str);qemu_plugin_outs ("\n" ); +g_mutex_unlock (&execlog_output_mutex); } }qemu_plugin_scoreboard_free (cpus);
contrib/plugins/execlog.c QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id, · line 496
Quoted 7 lines
contrib/plugins/execlog.c +1
-0@@ -467,6 +490,7 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,/* Register init, translation block and exit callbacks */ qemu_plugin_register_vcpu_init_cb (id, vcpu_init); +qemu_plugin_register_vcpu_exit_cb (id, vcpu_exit);qemu_plugin_register_vcpu_tb_trans_cb (id, vcpu_tb_trans);qemu_plugin_register_atexit_cb (id, plugin_exit,NULL );
Why not simply make this flush in atexit callback?
Quoted 10 lines
--
2.54.0The content, data, and any attached documents to this email are addressed exclusively to the addressee and are confidential and/or may be subject to a non-disclosure agreement. Any use, forwarding, disclosure, and/or copying, in whole or in part, without authorization is prohibited. If you have received this email in error, we apologize and, please notify the sender or Openchip immediately, and delete it from your system.
El contenido, los datos y cualquier documento adjunto a este correo electrónico están dirigidos exclusivamente al destinatario y son confidenciales y/o pueden estar sujetas a un acuerdo de no revelación. Está prohibido cualquier uso, reenvío, divulgación o copia, total o parcial, sin autorización. Si has recibido este correo por error, te pedimos disculpas y agradecemos que lo notifiques de inmediato al remitente o a Openchip, y lo elimines de tu sistema.
El contingut, les dades i qualsevol document adjunt a aquest correu electrònic estan dirigits exclusivament al destinatari i són confidencials i/o poden estar subjectes a un acord de no revelació. Està prohibit qualsevol ús, reenviament, divulgació o còpia, total o parcial, sense autorització. Si has rebut aquest correu per error, et demanem disculpes i agraïm que ho notifiquis d'immediat al remitent o a Openchip, i l'eliminis del teu sistema
Re: [PATCH 2/2] plugins/execlog: fix execlog vcpu_exit execution print loss
Quoted 22 lines
From: Pierrick Bouvier <[email protected]>
Sent: Tuesday 16 June 2026 7:40 pm
To: Harry van Haaren | OPENCHIP <[email protected]>; [email protected] <[email protected]>
Cc: [email protected] <[email protected]>; [email protected] <[email protected]>
Subject: Re: [PATCH 2/2] plugins/execlog: fix execlogvcpu_exitexecution print lossQuoted 15 lines · Harry van Haaren | OPENCHIP
From: Harry van Haaren <[email protected]>
Executed instructions are cached in string format inside the execlog plugin. These strings are flushed on exit of a TB, improving performance. This causes executed instructions to be lost when an 'ecall' (riscv system call) occurs that causes the thread to terminate.
The fix in this patch registers an '
on_exit()' callback, and flushes any content in thec->last_execbuffer, to ensure all instructions are present in the final instruction log.A mutex lock/unlock is added around the plugin exit, to ensure the lines are not corrupted.
Signed-off-by Harry van Haaren <[email protected]>
<snip>
Quoted 18 lines
Quoted 18 lines
+/**
+ * On plugin exit, flush any remaining cached instructions and free state. */
static voidplugin_exit(qemu_plugin_id_t id, void *p)
{contrib/plugins/execlog.c +2
-0@@ -396,8 +417,10 @@ static void plugin_exit(qemu_plugin_id_t id, void *p) for (int i = 0; i < n; i++) { CPU *c = qemu_plugin_scoreboard_find(cpus, i); if (c->last_exec && c->last_exec->len) { + g_mutex_lock(&execlog_output_mutex); qemu_plugin_outs(c->last_exec->str); qemu_plugin_outs("\n"); + g_mutex_unlock(&execlog_output_mutex); } } qemu_plugin_scoreboard_free(cpus);@@ -467,6 +490,7 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,
Quoted 8 lines
contrib/plugins/execlog.c QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id, · line 496
Quoted 6 lines
contrib/plugins/execlog.c +1
-0/* Register init, translation block and exit callbacks */ qemu_plugin_register_vcpu_init_cb(id, vcpu_init); + qemu_plugin_register_vcpu_exit_cb(id, vcpu_exit); qemu_plugin_register_vcpu_tb_trans_cb(id, vcpu_tb_trans); qemu_plugin_register_atexit_cb(id, plugin_exit, NULL);Why not simply make this flush in atexit callback?
I think on guest-thread join, the pthread stops, and qemu calls vcpu exit callback.
At that point in time, its nice to flush the "ecall" (to printf or disk or whatever the output is) so the user sees it immidiately.
The risk of not flushing here, is we wait until:
A) the plugin (not thread) exits, which could cause other threads to interleave/finish first (confusing, interleaved and delayed output)
or
B) a new thread is spawned by the guest, and the vcpu is re-used. This will correctly flush the previous-thread final instruction, but after an application-dependent delay.
Given that thread-exit is already heavy-weight and rare, I think the best for the user that the final instruction flushes immediately when a thread is finished. Unless I get strong feedback for a different approach, I'll respin the patchset and send (with git-publish, with footer removed, and "| Openchip" fixed... hopefully!)
Regards, -Harry
Re: [PATCH 2/2] plugins/execlog: fix execlog vcpu_exit execution print loss
Quoted 52 lines · Harry van Haaren
Quoted 22 lines
From: Pierrick Bouvier <[email protected]>
Sent: Tuesday 16 June 2026 7:40 pm
To: Harry van Haaren | OPENCHIP <[email protected]>; [email protected] <[email protected]>
Cc: [email protected] <[email protected]>; [email protected] <[email protected]>
Subject: Re: [PATCH 2/2] plugins/execlog: fix execlogvcpu_exitexecution print lossQuoted 15 lines · Harry van Haaren | OPENCHIP
From: Harry van Haaren <[email protected]>
Executed instructions are cached in string format inside the execlog plugin. These strings are flushed on exit of a TB, improving performance. This causes executed instructions to be lost when an 'ecall' (riscv system call) occurs that causes the thread to terminate.
The fix in this patch registers an '
on_exit()' callback, and flushes any content in thec->last_execbuffer, to ensure all instructions are present in the final instruction log.A mutex lock/unlock is added around the plugin exit, to ensure the lines are not corrupted.
Signed-off-by Harry van Haaren <[email protected]><snip>
Quoted 18 lines
Quoted 18 lines
+/**
+ * On plugin exit, flush any remaining cached instructions and free state. */
static voidplugin_exit(qemu_plugin_id_t id, void *p)
{contrib/plugins/execlog.c +2
-0@@ -396,8 +417,10 @@ static void plugin_exit(qemu_plugin_id_t id, void *p) for (int i = 0; i < n; i++) { CPU *c = qemu_plugin_scoreboard_find(cpus, i); if (c->last_exec && c->last_exec->len) { + g_mutex_lock(&execlog_output_mutex); qemu_plugin_outs(c->last_exec->str); qemu_plugin_outs("\n"); + g_mutex_unlock(&execlog_output_mutex); } } qemu_plugin_scoreboard_free(cpus);@@ -467,6 +490,7 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,Quoted 8 lines
contrib/plugins/execlog.c QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id, · line 496
Quoted 6 lines
contrib/plugins/execlog.c +1
-0/* Register init, translation block and exit callbacks */ qemu_plugin_register_vcpu_init_cb(id, vcpu_init); + qemu_plugin_register_vcpu_exit_cb(id, vcpu_exit); qemu_plugin_register_vcpu_tb_trans_cb(id, vcpu_tb_trans); qemu_plugin_register_atexit_cb(id, plugin_exit, NULL);Why not simply make this flush in atexit callback?
Quoted 5 lines
I think on guest-thread join, the pthread stops, and qemu calls vcpu exit callback.
At that point in time, its nice to flush the "ecall" (to printf or disk or whatever the output is) so the user sees it immidiately.The risk of not flushing here, is we wait until:
A) the plugin (not thread) exits, which could cause other threads to interleave/finish first (confusing, interleaved and delayed output)
Taking a look here, I can see that we have two different mechanic for
atexit: one for system (relies on libc atexit), and one for user, which indeed can race between threads.
It should be refactored, I'll take a look to remove the need to use any lock in atexit handlers for plugins.
Quoted 3 lines
or
B) a new thread is spawned by the guest, and the vcpu is re-used. This will correctly flush the previous-thread final instruction, but after an application-dependent delay.
That's a good concern, and fixing it with vcpu_exit seems like a good idea given this argument.
Quoted 4 lines
Given that thread-exit is already heavy-weight and rare, I think the best for the user that the final instruction flushes immediately when a thread is finished. Unless I get strong feedback for a different approach, I'll respin the patchset and send (with git-publish, with footer removed, and "| Openchip" fixed... hopefully!)
Regards, -Harry
Yes, you can keep the current approach.
Thanks,
Pierrick
v2 cover plugins/execlog: fix segfault and flush output on vcpu exit
In reply to Harry van Haaren | OPENCHIPFrom: Harry van Haaren <[email protected]>
Hi Qemu-Dev & CCs,
This is my first contribution to QEMU itself, but I have worked on DPDK, OVS, and QEMU-RS a bit in the past. I have experience with mailing lists for patches and some QEMU internals.
This is a "git publish" reply to the original patches that weren't in a patchset:
https://patchwork.kernel.org/project/qemu-devel/patch/[email protected]/
https://patchwork.kernel.org/project/qemu-devel/patch/[email protected]/
Thanks for reviews and input, the v2 reworks as follows:
- I expect email to no longer have "| OPENCHIP" in my name, and the email footer removed
- git publish used to send, with "--number 2" to hopefully get a v2 patchset out
- rebased to latest branch, atexit() function signatures changed
- avoid adding mutex for output, rely on QEMUs logging mutex (thanks Pierrick) --- use single call to log to avoid line-breaks corrupting output
Please note that LLMs were used to investigate and fix this bug, but all code in this patch has been reviewed by me, and I believe it to be a good solution.
Regards, -Harry
Harry van Haaren (2):
plugins/execlog: fix segfault/race-cond on per-vCPU structures plugins/execlog: fix execlog vcpu_exit execution print loss
contrib/plugins/execlog.c | 88 +++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 45 deletions(-)
Signature · 1 line
2.54.0
PATCH v2 1/2 plugins/execlog: fix segfault/race-cond on per-vCPU structures
From: Harry van Haaren <[email protected]>
The existing code in execlog was never upgraded to the Scoreboard API, resulting in a bespoke implementation of per-vCPU datastructure handling. This had some race-conditions, and causes segfaults with a simple multi-threaded program and two instances of execlog running.
The patch here refactors the custom GArray and GRWLock code away, and uses the scoreboard APIs like the other plugins. This solves the "printing while expanding" race-condition of two plugins with multiple threads in the guest, and hence fixes a segfault.
Output remains atomic per instruction by building the full line (including the trailing newline) in the per-vCPU GString before making a single qemu_plugin_outs() call, relying on QEMU's own log locking rather than an additional mutex.
--- contrib/plugins/execlog.c | 68 +++++++++++++-------------------------- 1 file changed, 23 insertions(+), 45 deletions(-)
contrib/plugins/execlog.c +23 -45
@@ -31,8 +31,12 @@ typedef struct CPU { QEMU_PLUGIN_EXPORT int qemu_plugin_version = QEMU_PLUGIN_VERSION; -static GArray *cpus; -static GRWLock expand_array_lock; +/* +* Per-vCPU state stored in a qemu_plugin_scoreboard. The scoreboard manages +* per-vCPU storage automatically, eliminating the need for manual array +* growth, locks, or pointer-stability workarounds. +*/ +static struct qemu_plugin_scoreboard *cpus;static GPtrArray *imatches;static GArray *amatches;
@@ -41,23 +45,13 @@ static bool disas_assist;static GMutex add_reg_name_lock;static GPtrArray *all_reg_names; -static CPU *get_cpu (int vcpu_index) -{ -CPU *c; -g_rw_lock_reader_lock (&expand_array_lock); - c = &g_array_index (cpus,CPU , vcpu_index); -g_rw_lock_reader_unlock (&expand_array_lock); - -return c; -} -/** * Add memory read or write information to current instruction log */ static void vcpu_mem (unsigned int cpu_index,qemu_plugin_meminfo_t info,uint64_t vaddr,void *udata) { -CPU *c =get_cpu (cpu_index); +CPU *c =qemu_plugin_scoreboard_find (cpus, cpu_index);GString *s = c->last_exec;/* Find vCPU in array */
@@ -117,7 +111,7 @@ static void insn_check_regs(CPU *cpu)/* Log last instruction while checking registers */ static void vcpu_insn_exec_with_regs (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) {
@@ -125,8 +119,8 @@ static void vcpu_insn_exec_with_regs(unsigned int cpu_index, void *udata)insn_check_regs (cpu); } +g_string_append_c (cpu->last_exec,'\n' );qemu_plugin_outs (cpu->last_exec->str); -qemu_plugin_outs ("\n" ); }/* Store new instruction in cache */
@@ -138,7 +132,7 @@ static void vcpu_insn_exec_with_regs(unsigned int cpu_index, void *udata)/* Log last instruction while checking registers, ignore next */ static void vcpu_insn_exec_only_regs (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) {
@@ -146,8 +140,8 @@ static void vcpu_insn_exec_only_regs(unsigned int cpu_index, void *udata)insn_check_regs (cpu); } +g_string_append_c (cpu->last_exec,'\n' );qemu_plugin_outs (cpu->last_exec->str); -qemu_plugin_outs ("\n" ); }/* reset */
@@ -157,12 +151,12 @@ static void vcpu_insn_exec_only_regs(unsigned int cpu_index, void *udata)/* Log last instruction without checking regs, setup next */ static void vcpu_insn_exec (unsigned int cpu_index,void *udata) { -CPU *cpu =get_cpu (cpu_index); +CPU *cpu =qemu_plugin_scoreboard_find (cpus, cpu_index);/* Print previous instruction in cache */ if (cpu->last_exec->len) { +g_string_append_c (cpu->last_exec,'\n' );qemu_plugin_outs (cpu->last_exec->str); -qemu_plugin_outs ("\n" ); }/* Store new instruction in cache */
@@ -378,40 +372,28 @@ static GPtrArray *registers_init(int vcpu_index)* - last_exec tracking data * - list of tracked registers * - initial value of registers -* -* As we could have multiple threads trying to do this we need to -* serialise the expansion under a lock. */ static void vcpu_init (unsigned int vcpu_index,void *userdata) { -CPU *c; - -g_rw_lock_writer_lock (&expand_array_lock); -if (vcpu_index >= cpus->len) { -g_array_set_size (cpus, vcpu_index +1 ); - } -g_rw_lock_writer_unlock (&expand_array_lock); - - c =get_cpu (vcpu_index); +CPU *c =qemu_plugin_scoreboard_find (cpus, vcpu_index); c->last_exec =g_string_new (NULL ); c->registers =registers_init (vcpu_index); }/** -* On plugin exit, print last instruction in cache +* On plugin exit, flush any remaining cached instructions and free state. */ static void plugin_exit (void *p) { -guint i; -g_rw_lock_reader_lock (&expand_array_lock); -for (i =0 ; i < cpus->len; i++) { -CPU *c =get_cpu (i); -if (c->last_exec && c->last_exec->str) { +int n =qemu_plugin_num_vcpus (); +for (int i =0 ; i < n; i++) { +CPU *c =qemu_plugin_scoreboard_find (cpus, i); +if (c->last_exec && c->last_exec->len) { +g_string_append_c (c->last_exec,'\n' );qemu_plugin_outs (c->last_exec->str); -qemu_plugin_outs ("\n" ); } } -g_rw_lock_reader_unlock (&expand_array_lock); +qemu_plugin_scoreboard_free (cpus); }/* Add a match to the array of matches */
@@ -452,12 +434,8 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id, const qemu_info_t *info, int argc, char **argv) { -/* -* Initialize dynamic array to cache vCPU instruction. In user mode -* we don't know the size before emulation. -*/ - cpus =g_array_sized_new (true, true,sizeof (CPU ), - info->system_emulation ? info->system.max_vcpus :1 ); +/* Initialize scoreboard to cache per-vCPU instruction state. */ + cpus =qemu_plugin_scoreboard_new (sizeof (CPU ));for (int i =0 ; i < argc; i++) {char *opt = argv[i];
Signature · 1 line
2.54.0
PATCH v2 2/2 plugins/execlog: fix execlog vcpu_exit execution print loss
In reply to Harry van HaarenFrom: Harry van Haaren <[email protected]>
Executed instructions are cached in string format inside the execlog plugin. These strings are flushed on exit of a TB, improving performance. This causes executed instructions to be lost when an 'ecall' (riscv system call) occurs that causes the thread to terminate.
The fix in this patch registers a 'vcpu_exit' callback, and flushes any content in the c->last_exec buffer, to ensure all instructions are present in the final instruction log.
--- contrib/plugins/execlog.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+)
contrib/plugins/execlog.c +20 -0
@@ -380,6 +380,25 @@ static void vcpu_init(unsigned int vcpu_index, void *userdata) c->registers =registers_init (vcpu_index); } +/** +* On vCPU exit, flush the last cached instruction for this vCPU. +* +* The one-instruction-delay pattern stores each instruction in last_exec and +* only prints it when the *next* callback fires. When a thread exits via +* syscall (e.g. ecall/exit), no subsequent callback fires for that vCPU and +* the final instruction is silently dropped. Flushing here guarantees it is +* written before the vCPU is torn down. +*/ +static void vcpu_exit (unsigned int vcpu_index,void *udata) +{ +CPU *c =qemu_plugin_scoreboard_find (cpus, vcpu_index); +if (c->last_exec && c->last_exec->len) { +g_string_append_c (c->last_exec,'\n' ); +qemu_plugin_outs (c->last_exec->str); +g_string_truncate (c->last_exec,0 ); + } +} +/** * On plugin exit, flush any remaining cached instructions and free state. */
@@ -461,6 +480,7 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,/* Register init, translation block and exit callbacks */ qemu_plugin_register_vcpu_init_cb (id, vcpu_init,NULL );qemu_plugin_register_vcpu_tb_trans_cb (id, vcpu_tb_trans,NULL ); +qemu_plugin_register_vcpu_exit_cb (id, vcpu_exit,NULL );qemu_plugin_register_atexit_cb (id, plugin_exit,NULL );return 0 ;
Signature · 1 line
2.54.0
Re: [PATCH v2 0/2] plugins/execlog: fix segfault and flush output on vcpu exit
In reply to Harry van HaarenHi Harry,
Quoted 9 lines · Harry van Haaren
From: Harry van Haaren <[email protected]>
Hi Qemu-Dev & CCs,
This is my first contribution to QEMU itself, but I have worked on DPDK, OVS, and QEMU-RS a bit in the past. I have experience with mailing lists for patches and some QEMU internals.
This is a "git publish" reply to the original patches that weren't in a patchset:
When sending new version, you should not reply to v1 series, but send a proper new thread. Not sure if you added some extra parameters to git-publish, but it should not be needed.
No need to resend that now, but just an information for your future series :).
Quoted 14 lines
https://patchwork.kernel.org/project/qemu-devel/patch/[email protected]/
https://patchwork.kernel.org/project/qemu-devel/patch/[email protected]/Thanks for reviews and input, the v2 reworks as follows:
- I expect email to no longer have "| OPENCHIP" in my name, and the email footer removed
- git publish used to send, with "--number 2" to hopefully get a v2 patchset out
- rebased to latest branch,atexit()function signatures changed
- avoid adding mutex for output, rely on QEMUs logging mutex (thanks Pierrick) --- use single call to log to avoid line-breaks corrupting outputPlease note that LLMs were used to investigate and fix this bug, but all code in this patch has been reviewed by me, and I believe it to be a good solution.
Quoted 9 lines
Regards, -Harry
Harry van Haaren (2):
plugins/execlog: fix segfault/race-cond on per-vCPU structures plugins/execlog: fix execlogvcpu_exitexecution print losscontrib/plugins/execlog.c | 88 +++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 45 deletions(-)
Regards,
Pierrick
Re: [PATCH v2 0/2] plugins/execlog: fix segfault and flush output on vcpu exit
In reply to Harry van HaarenQuoted 23 lines · Harry van Haaren
From: Harry van Haaren <[email protected]>
Hi Qemu-Dev & CCs,
This is my first contribution to QEMU itself, but I have worked on DPDK, OVS, and QEMU-RS a bit in the past. I have experience with mailing lists for patches and some QEMU internals.
This is a "git publish" reply to the original patches that weren't in a patchset:
https://patchwork.kernel.org/project/qemu-devel/patch/[email protected]/
https://patchwork.kernel.org/project/qemu-devel/patch/[email protected]/Thanks for reviews and input, the v2 reworks as follows:
- I expect email to no longer have "| OPENCHIP" in my name, and the email footer removed
- git publish used to send, with "--number 2" to hopefully get a v2 patchset out
- rebased to latest branch,atexit()function signatures changed
- avoid adding mutex for output, rely on QEMUs logging mutex (thanks Pierrick) --- use single call to log to avoid line-breaks corrupting outputPlease note that LLMs were used to investigate and fix this bug, but all code in this patch has been reviewed by me, and I believe it to be a good solution.
Quoted 9 lines
Regards, -Harry
Harry van Haaren (2):
plugins/execlog: fix segfault/race-cond on per-vCPU structures plugins/execlog: fix execlogvcpu_exitexecution print losscontrib/plugins/execlog.c | 88 +++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 45 deletions(-)
For the series:
I'll pull this today.
Regards,
Pierrick
Re: [PATCH v2 0/2] plugins/execlog: fix segfault and flush output on vcpu exit
In reply to Harry van HaarenQuoted 23 lines · Harry van Haaren
From: Harry van Haaren <[email protected]>
Hi Qemu-Dev & CCs,
This is my first contribution to QEMU itself, but I have worked on DPDK, OVS, and QEMU-RS a bit in the past. I have experience with mailing lists for patches and some QEMU internals.
This is a "git publish" reply to the original patches that weren't in a patchset:
https://patchwork.kernel.org/project/qemu-devel/patch/[email protected]/
https://patchwork.kernel.org/project/qemu-devel/patch/[email protected]/Thanks for reviews and input, the v2 reworks as follows:
- I expect email to no longer have "| OPENCHIP" in my name, and the email footer removed
- git publish used to send, with "--number 2" to hopefully get a v2 patchset out
- rebased to latest branch,atexit()function signatures changed
- avoid adding mutex for output, rely on QEMUs logging mutex (thanks Pierrick) --- use single call to log to avoid line-breaks corrupting outputPlease note that LLMs were used to investigate and fix this bug, but all code in this patch has been reviewed by me, and I believe it to be a good solution.
Quoted 9 lines
Regards, -Harry
Harry van Haaren (2):
plugins/execlog: fix segfault/race-cond on per-vCPU structures plugins/execlog: fix execlogvcpu_exitexecution print losscontrib/plugins/execlog.c | 88 +++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 45 deletions(-)
This was merged into master (3b49fccda43ef0953d1b0e226c7b1d7b64b62dd7). Thank you for your contribution!
Regards,
Pierrick