Skip to contentSkip to conversation

plugins/next - fixes, sysfilter and vcpu_init tweaks

RFC PATCH In review Alex Bennée 2 participants 18 messages Dec 19, 2025 – Dec 22, 2025 Arm/Amlogic Meson SoC support

lore
Share & tools
lore
#0 lore raw

cover plugins/next - fixes, sysfilter and vcpu_init tweaks

Hi,

I thought I'd post the current state of the plugins/next tree for comments and reviews.

Firstly we have a bunch of fixes for the hotblocks plugins from Alex Bradbury.

We also have Ziyang Zhang's syscall filter patches which allow plugins to filter (and/or replace) syscalls. The initial use for this would be for something like Lorelei:

https://pretalx.com/kvm-forum-2025/talk/KFSGHS/

where using plugins avoids needing to integrate complex logic into linux-user itself. No doubt the reverse engineers would also find the capability useful.

There is also a discussion thread about a general purpose PC setting patch:

Message-Id: e64f4a1f-ac43-487b-f0af-08de04dbd9f1
Subject: [RFC PATCH v2 0/2] Enable PC diversion via the plugin API
From: Florian Hofhammer <[email protected]>
Date: Mon, 6 Oct 2025 15:21:21 +0200
Message-ID: <[email protected]>

but as we still need to work out a nice way to handle removing the PC from the register list I've left that out for now.

Finally I was doing some hacking around on my kvm/trap-me-harder patches and I wanted to check when IRQ's occurred and what systems registers were touched when. I then discovered that the ICC_ registers were not available to plugins due to being created after the CPUs are initialised. I've tried several approaches but it seems having a clean vCPU initialisation after machine creation is tricky so instead I've split the hooks into creation and reset and moved the plugin visable callback to reset. However this may change the assumptions about what to do in vcpu_init.

You can see some of the ugliness in the new systrace plugin which has to jump through hoops to deal with the fact the number of registers it can see changes several times. Unfortunately this seems to trigger a corruption bug which I haven't nailed down yet while running:

./qemu-system-aarch64 \
                  -machine type=virt,gic-version=3 \
                  -cpu neoverse-n1 \
                  -smp 4 \
                  -serial mon:stdio \
                  -m 1024 \
                  -accel tcg \
                  -kernel ~/lsrc/linux.git/builds/arm64.initramfs/arch/arm64/boot/Image.gz \
                  -append "console=ttyAMA0" \
                  -display none -d unimp,plugin,cpu_reset -plugin ./contrib/plugins/libsystrace.so,show_frompc=on,tracksw=msr,reg=icc\* -D boot.log

I'm open to better ideas about how to solve this particular problem.

Anyway happy holidays everyone, see you all in the new year ;-)

Alex.

Alex Bennée (5):
plugins: shorten aggressively long name
plugins: split init_hook into create and reset
target/arm: defer creation of gdb register until machine created contrib/plugins: add systrace plugin for tracking exceptions and irqs target/arm: allow gdb to read ARM_CP_NORAW regs (!upstream)

Alex Bradbury (5):
contrib/plugins/hotblocks: Correctly free sorted counts list contrib/plugins/hotblocks: Fix off by one error in iteration of sorted
blocks
contrib/plugins/hotblocks: Print uint64_t with PRIu64 rather than

    PRId64

docs/about/emulation: Add documentation for hotblocks plugin arguments contrib/plugins/hotblocks: Allow limit to be set as a command line
argument

Ziyang Zhang (2):
linux-user: add plugin API to filter syscalls
tcg tests: add a test to verify the syscall filter plugin API

 docs/about/emulation.rst                      |  12 +
 include/qemu/plugin-event.h                   |   1 +
 include/qemu/plugin.h                         |  52 +-
 include/qemu/qemu-plugin.h                    |  40 +-
 include/user/syscall-trace.h                  |  17 +
 contrib/plugins/cflow.c                       |  22 +-
 contrib/plugins/hotblocks.c                   |  20 +-
 contrib/plugins/howvec.c                      |   2 +-
 contrib/plugins/stoptrigger.c                 |  10 +-
 contrib/plugins/systrace.c                    | 572 ++++++++++++++++++
 hw/core/cpu-common.c                          |  21 +-
 linux-user/syscall.c                          |   7 +-
 plugins/api.c                                 |   9 +-
 plugins/core.c                                |  68 ++-
 target/arm/cpu.c                              |  33 +
 target/arm/gdbstub.c                          |   6 +-
 target/arm/helper.c                           |  15 +-
 .../multiarch/test-plugin-syscall-filter.c    |  35 ++
 tests/tcg/plugins/discons.c                   |  18 +-
 tests/tcg/plugins/inline.c                    |   6 +-
 tests/tcg/plugins/insn.c                      |   5 +-
 tests/tcg/plugins/syscall.c                   |  19 +
 contrib/plugins/meson.build                   |   2 +-
 tests/tcg/multiarch/Makefile.target           |   4 +-
 24 files changed, 922 insertions(+), 74 deletions(-)
 create mode 100644 contrib/plugins/systrace.c
 create mode 100644 tests/tcg/multiarch/test-plugin-syscall-filter.c
Signature · 1 line
2.47.3
#1 lore raw

RFC PATCH 1/12 contrib/plugins/hotblocks: Correctly free sorted counts list

From: Alex Bradbury <[email protected]>

g_list_free should be passed the head of the list.

Message-ID: <0529ab0212aae1e4a5ff3c287045acc0731e5d01.1764716538.git.asb@igalia.com>

---
 contrib/plugins/hotblocks.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
contrib/plugins/hotblocks.c +5 -4
index 98404b68852..d3dd23ed9fa 100644
@@ -73,15 +73,16 @@ static void exec_count_free(gpointer key, gpointer value, gpointer user_data)
 static void plugin_exit(qemu_plugin_id_t id, void *p)
 {
     g_autoptr(GString) report = g_string_new("collected ");
-    GList *counts, *it;
+    GList *counts, *sorted_counts, *it;
     int i;
 
     g_string_append_printf(report, "%d entries in the hash table\n",
                            g_hash_table_size(hotblocks));
     counts = g_hash_table_get_values(hotblocks);
-    it = g_list_sort_with_data(counts, cmp_exec_count, NULL);
+    sorted_counts = g_list_sort_with_data(counts, cmp_exec_count, NULL);
 
-    if (it) {
+    if (sorted_counts) {
+        it = sorted_counts;
         g_string_append_printf(report, "pc, tcount, icount, ecount\n");
 
         for (i = 0; i < limit && it->next; i++, it = it->next) {
@@ -94,7 +95,7 @@ static void plugin_exit(qemu_plugin_id_t id, void *p)
                     qemu_plugin_scoreboard_u64(rec->exec_count)));
         }
 
-        g_list_free(it);
+        g_list_free(sorted_counts);
     }
 
     qemu_plugin_outs(report->str);
Signature · 1 line
2.47.3
#2 lore raw

RFC PATCH 2/12 contrib/plugins/hotblocks: Fix off by one error in iteration of sorted blocks

In reply to Alex Bennée

From: Alex Bradbury <[email protected]>

The logic to iterate over the hottest blocks will never reach the last item in the list, as it checks it->next != NULL before entering the loop. It's hard to trigger this off-by-one error with the default limit=20, but it is a bug and is problematic if that default is changed to something larger.

Message-ID: <2e1c404fd21d064610391ebb2ffe24d0c536f8dd.1764716538.git.asb@igalia.com>

---
 contrib/plugins/hotblocks.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
contrib/plugins/hotblocks.c +1 -2
index d3dd23ed9fa..cf4d6b8c363 100644
@@ -82,10 +82,9 @@ static void plugin_exit(qemu_plugin_id_t id, void *p)
     sorted_counts = g_list_sort_with_data(counts, cmp_exec_count, NULL);
 
     if (sorted_counts) {
-        it = sorted_counts;
         g_string_append_printf(report, "pc, tcount, icount, ecount\n");
 
-        for (i = 0; i < limit && it->next; i++, it = it->next) {
+        for (i = 0, it = sorted_counts; i < limit && it; i++, it = it->next) {
             ExecCount *rec = (ExecCount *) it->data;
             g_string_append_printf(
                 report, "0x%016"PRIx64", %d, %ld, %"PRId64"\n",
Signature · 1 line
2.47.3
#3 lore raw

RFC PATCH 3/12 contrib/plugins/hotblocks: Print uint64_t with PRIu64 rather than PRId64

In reply to Alex Bennée

From: Alex Bradbury <[email protected]>

qemu_plugin_u64_sum returns a uint64_t, so PRIu64 is the correct format specifier.

Message-ID: <46f83ac83c6cabace91b9be85da2547ff7b08204.1764716538.git.asb@igalia.com>

---
 contrib/plugins/hotblocks.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
contrib/plugins/hotblocks.c +1 -1
index cf4d6b8c363..40d8dae1cd3 100644
@@ -87,7 +87,7 @@ static void plugin_exit(qemu_plugin_id_t id, void *p)
         for (i = 0, it = sorted_counts; i < limit && it; i++, it = it->next) {
             ExecCount *rec = (ExecCount *) it->data;
             g_string_append_printf(
-                report, "0x%016"PRIx64", %d, %ld, %"PRId64"\n",
+                report, "0x%016"PRIx64", %d, %ld, %"PRIu64"\n",
                 rec->start_addr, rec->trans_count,
                 rec->insns,
                 qemu_plugin_u64_sum(
Signature · 1 line
2.47.3
#4 lore raw

RFC PATCH 4/12 docs/about/emulation: Add documentation for hotblocks plugin arguments

In reply to Alex Bennée

From: Alex Bradbury <[email protected]>

Currently just 'inline'.

Message-ID: <60f1ad20663f7e5c6cb00dd83fe0f1f5aa6ca4de.1764716538.git.asb@igalia.com>

---
 docs/about/emulation.rst | 10 ++++++++++
 1 file changed, 10 insertions(+)
docs/about/emulation.rst +10 -0
index 4a7d1f41780..543efc4d7dc 100644
@@ -463,6 +463,16 @@ Example::
   0x000000004002b0, 1, 4, 66087
   ...
 
+Behaviour can be tweaked with the following arguments:
+
+.. list-table:: Hot Blocks plugin arguments
+  :widths: 20 80
+  :header-rows: 1
+
+  * - Option
+    - Description
+  * - inline=true|false
+    - Use faster inline addition of a single counter.
 
 Hot Pages
 .........
Signature · 1 line
2.47.3
#5 lore raw

RFC PATCH 5/12 contrib/plugins/hotblocks: Allow limit to be set as a command line argument

In reply to Alex Bennée

From: Alex Bradbury <[email protected]>

Also add documentation for this argument. This allows the default of 20 to be overridden, and is helpful for using the hotblocks plugin for analysis scripts that require collecting data on a larger number of blocks (e.g. setting limit=0 to dump information on all blocks).

Message-ID: <bf04947f9a694a4d3adf5f0775dbb8d5013fd8c9.1764716538.git.asb@igalia.com>

---
 docs/about/emulation.rst    |  2 ++
 contrib/plugins/hotblocks.c | 10 +++++++++-
 2 files changed, 11 insertions(+), 1 deletion(-)
docs/about/emulation.rst +2 -0
index 543efc4d7dc..e8793b0f9ce 100644
@@ -473,6 +473,8 @@ Behaviour can be tweaked with the following arguments:
     - Description
   * - inline=true|false
     - Use faster inline addition of a single counter.
+  * - limit=N
+    - The number of blocks to be printed. (Default: N = 20, use 0 for no limit).
 
 Hot Pages
 .........
contrib/plugins/hotblocks.c +9 -1
index 40d8dae1cd3..8ecf0339974 100644
@@ -84,7 +84,8 @@ static void plugin_exit(qemu_plugin_id_t id, void *p)
     if (sorted_counts) {
         g_string_append_printf(report, "pc, tcount, icount, ecount\n");
 
-        for (i = 0, it = sorted_counts; i < limit && it; i++, it = it->next) {
+        for (i = 0, it = sorted_counts; (limit == 0 || i < limit) && it;
+             i++, it = it->next) {
             ExecCount *rec = (ExecCount *) it->data;
             g_string_append_printf(
                 report, "0x%016"PRIx64", %d, %ld, %"PRIu64"\n",
@@ -170,6 +171,13 @@ int qemu_plugin_install(qemu_plugin_id_t id, const qemu_info_t *info,
                 fprintf(stderr, "boolean argument parsing failed: %s\n", opt);
                 return -1;
             }
+        } else if (g_strcmp0(tokens[0], "limit") == 0) {
+            char *endptr = NULL;
+            limit = g_ascii_strtoull(tokens[1], &endptr, 10);
+            if (endptr == tokens[1] || *endptr != '\0') {
+                fprintf(stderr, "unsigned integer parsing failed: %s\n", opt);
+                return -1;
+            }
         } else {
             fprintf(stderr, "option parsing failed: %s\n", opt);
             return -1;
Signature · 1 line
2.47.3
#6 lore raw

RFC PATCH 6/12 plugins: shorten aggressively long name

In reply to Alex Bennée

The old name comes in at a 51 characters, contains at least one redundant token and exec is arguably implied by inline as all inline operations occur when instructions are executing.

By putting the name on a substantial diet we can reduce it by 15% and gain valuable white-space in the process.

---
 include/qemu/qemu-plugin.h    |  4 ++--
 contrib/plugins/cflow.c       | 22 +++++++++++-----------
 contrib/plugins/howvec.c      |  2 +-
 contrib/plugins/stoptrigger.c | 10 ++++++----
 plugins/api.c                 |  2 +-
 tests/tcg/plugins/discons.c   | 18 +++++++++---------
 tests/tcg/plugins/inline.c    |  6 +++---
 tests/tcg/plugins/insn.c      |  5 +++--
 8 files changed, 36 insertions(+), 33 deletions(-)
include/qemu/qemu-plugin.h +2 -2
index 60de4fdd3fa..29663591ebf 100644
@@ -516,7 +516,7 @@ void qemu_plugin_register_vcpu_insn_exec_cond_cb(
     void *userdata);
 
 /**
- * qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu() - insn exec inline op
+ * qemu_plugin_register_inline_per_vcpu() - insn exec inline op
  * @insn: the opaque qemu_plugin_insn handle for an instruction
  * @op: the type of qemu_plugin_op (e.g. ADD_U64)
  * @entry: entry to run op
@@ -525,7 +525,7 @@ void qemu_plugin_register_vcpu_insn_exec_cond_cb(
  * Insert an inline op to every time an instruction executes.
  */
 QEMU_PLUGIN_API
-void qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+void qemu_plugin_register_inline_per_vcpu(
     struct qemu_plugin_insn *insn,
     enum qemu_plugin_op op,
     qemu_plugin_u64 entry,
contrib/plugins/cflow.c +11 -11
index b5e33f25f9b..cef5ae2239f 100644
@@ -320,14 +320,14 @@ static void vcpu_tb_trans(qemu_plugin_id_t id, struct qemu_plugin_tb *tb)
      * check where we are at. Do this on the first instruction and not
      * the TB so we don't get mixed up with above.
      */
-    qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(first_insn,
-                                                      QEMU_PLUGIN_INLINE_STORE_U64,
-                                                      end_block, qemu_plugin_insn_vaddr(last_insn));
-    qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(first_insn,
-                                                      QEMU_PLUGIN_INLINE_STORE_U64,
-                                                      pc_after_block,
-                                                      qemu_plugin_insn_vaddr(last_insn) +
-                                                      qemu_plugin_insn_size(last_insn));
+    qemu_plugin_register_inline_per_vcpu(first_insn,
+                                         QEMU_PLUGIN_INLINE_STORE_U64,
+                                         end_block, qemu_plugin_insn_vaddr(last_insn));
+    qemu_plugin_register_inline_per_vcpu(first_insn,
+                                         QEMU_PLUGIN_INLINE_STORE_U64,
+                                         pc_after_block,
+                                         qemu_plugin_insn_vaddr(last_insn) +
+                                         qemu_plugin_insn_size(last_insn));
 
     for (int idx = 0; idx < qemu_plugin_tb_n_insns(tb); ++idx) {
         struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb, idx);
@@ -355,9 +355,9 @@ static void vcpu_tb_trans(qemu_plugin_id_t id, struct qemu_plugin_tb *tb)
         }
 
         /* Store the PC of what we are about to execute */
-        qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(insn,
-                                                            QEMU_PLUGIN_INLINE_STORE_U64,
-                                                            last_pc, ipc);
+        qemu_plugin_register_inline_per_vcpu(insn,
+                                             QEMU_PLUGIN_INLINE_STORE_U64,
+                                             last_pc, ipc);
     }
 }
 
contrib/plugins/howvec.c +1 -1
index 42bddb6566d..c60737d57f1 100644
@@ -321,7 +321,7 @@ static void vcpu_tb_trans(qemu_plugin_id_t id, struct qemu_plugin_tb *tb)
 
         if (cnt) {
             if (do_inline) {
-                qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+                qemu_plugin_register_inline_per_vcpu(
                     insn, QEMU_PLUGIN_INLINE_ADD_U64,
                     qemu_plugin_scoreboard_u64(cnt), 1);
             } else {
contrib/plugins/stoptrigger.c +6 -4
index b3a6ed66a7b..68c0ed432af 100644
@@ -73,10 +73,12 @@ static void vcpu_tb_trans(qemu_plugin_id_t id, struct qemu_plugin_tb *tb)
 
         if (exit_on_icount) {
             /* Increment and check scoreboard for each instruction */
-            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
-                insn, QEMU_PLUGIN_INLINE_ADD_U64, insn_count, 1);
-            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
-                insn, QEMU_PLUGIN_INLINE_STORE_U64, current_pc, insn_vaddr);
+            qemu_plugin_register_inline_per_vcpu(insn,
+                                                 QEMU_PLUGIN_INLINE_ADD_U64,
+                                                 insn_count, 1);
+            qemu_plugin_register_inline_per_vcpu(insn,
+                                                 QEMU_PLUGIN_INLINE_STORE_U64,
+                                                 current_pc, insn_vaddr);
             qemu_plugin_register_vcpu_insn_exec_cond_cb(
                 insn, exit_icount_reached, QEMU_PLUGIN_CB_NO_REGS,
                 QEMU_PLUGIN_COND_EQ, insn_count, icount + 1, NULL);
plugins/api.c +1 -1
index eac04cc1f6b..267fa2fd503 100644
@@ -154,7 +154,7 @@ void qemu_plugin_register_vcpu_insn_exec_cond_cb(
                                        cond, entry, imm, udata);
 }
 
-void qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+void qemu_plugin_register_inline_per_vcpu(
     struct qemu_plugin_insn *insn,
     enum qemu_plugin_op op,
     qemu_plugin_u64 entry,
tests/tcg/plugins/discons.c +9 -9
index 2e0e664e823..1348d6e5020 100644
@@ -156,15 +156,15 @@ static void vcpu_tb_trans(qemu_plugin_id_t id, struct qemu_plugin_tb *tb)
         uint64_t next_pc = pc + qemu_plugin_insn_size(insn);
         uint64_t has_next = (i + 1) < n_insns;
 
-        qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(insn,
-                                                            QEMU_PLUGIN_INLINE_STORE_U64,
-                                                            last_pc, pc);
-        qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(insn,
-                                                            QEMU_PLUGIN_INLINE_STORE_U64,
-                                                            from_pc, next_pc);
-        qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(insn,
-                                                            QEMU_PLUGIN_INLINE_STORE_U64,
-                                                            has_from, has_next);
+        qemu_plugin_register_inline_per_vcpu(insn,
+                                             QEMU_PLUGIN_INLINE_STORE_U64,
+                                             last_pc, pc);
+        qemu_plugin_register_inline_per_vcpu(insn,
+                                             QEMU_PLUGIN_INLINE_STORE_U64,
+                                             from_pc, next_pc);
+        qemu_plugin_register_inline_per_vcpu(insn,
+                                             QEMU_PLUGIN_INLINE_STORE_U64,
+                                             has_from, has_next);
         qemu_plugin_register_vcpu_insn_exec_cb(insn, insn_exec,
                                                QEMU_PLUGIN_CB_NO_REGS, NULL);
     }
tests/tcg/plugins/inline.c +3 -3
index 73dde995781..35307501105 100644
@@ -244,15 +244,15 @@ static void vcpu_tb_trans(qemu_plugin_id_t id, struct qemu_plugin_tb *tb)
         void *insn_store = insn;
         void *mem_store = (char *)insn_store + 0xff;
 
-        qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+        qemu_plugin_register_inline_per_vcpu(
             insn, QEMU_PLUGIN_INLINE_STORE_U64, data_insn,
             (uintptr_t) insn_store);
         qemu_plugin_register_vcpu_insn_exec_cb(
             insn, vcpu_insn_exec, QEMU_PLUGIN_CB_NO_REGS, insn_store);
-        qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+        qemu_plugin_register_inline_per_vcpu(
             insn, QEMU_PLUGIN_INLINE_ADD_U64, count_insn_inline, 1);
 
-        qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
+        qemu_plugin_register_inline_per_vcpu(
             insn, QEMU_PLUGIN_INLINE_ADD_U64, insn_cond_track_count, 1);
         qemu_plugin_register_vcpu_insn_exec_cond_cb(
             insn, vcpu_insn_cond_exec, QEMU_PLUGIN_CB_NO_REGS,
tests/tcg/plugins/insn.c +3 -2
index 0c723cb9ed8..b337fda9f13 100644
@@ -147,8 +147,9 @@ static void vcpu_tb_trans(qemu_plugin_id_t id, struct qemu_plugin_tb *tb)
         struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb, i);
 
         if (do_inline) {
-            qemu_plugin_register_vcpu_insn_exec_inline_per_vcpu(
-                insn, QEMU_PLUGIN_INLINE_ADD_U64, insn_count, 1);
+            qemu_plugin_register_inline_per_vcpu(insn,
+                                                 QEMU_PLUGIN_INLINE_ADD_U64,
+                                                 insn_count, 1);
         } else {
             qemu_plugin_register_vcpu_insn_exec_cb(
                 insn, vcpu_insn_exec_before, QEMU_PLUGIN_CB_NO_REGS, NULL);
Signature · 1 line
2.47.3
Reviewed-by on v1 6/12
#7 lore raw

Re: [RFC PATCH 06/12] plugins: shorten aggressively long name

Quoted 8 lines · Alex Bennée

The old name comes in at a 51 characters, contains at least one redundant token and exec is arguably implied by inline as all inline operations occur when instructions are executing.

By putting the name on a substantial diet we can reduce it by 15% and gain valuable white-space in the process.

Quoted 10 lines
---
  include/qemu/qemu-plugin.h    |  4 ++--
  contrib/plugins/cflow.c       | 22 +++++++++++-----------
  contrib/plugins/howvec.c      |  2 +-
  contrib/plugins/stoptrigger.c | 10 ++++++----
  plugins/api.c                 |  2 +-
  tests/tcg/plugins/discons.c   | 18 +++++++++---------
  tests/tcg/plugins/inline.c    |  6 +++---
  tests/tcg/plugins/insn.c      |  5 +++--
  8 files changed, 36 insertions(+), 33 deletions(-)
#8 lore raw

RFC PATCH 7/12 linux-user: add plugin API to filter syscalls

In reply to Alex Bennée

From: Ziyang Zhang <[email protected]>

This commit adds a syscall filter API to the TCG plugin API set. Plugins can register a filter callback to QEMU to decide whether to intercept a syscall, process it and bypass the QEMU syscall handler.

Message-ID: <[email protected]>

---
 include/qemu/plugin-event.h  |  1 +
 include/qemu/plugin.h        | 33 +++++++++++++++++++++++---------
 include/qemu/qemu-plugin.h   | 32 +++++++++++++++++++++++++++++++
 include/user/syscall-trace.h | 17 +++++++++++++++++
 linux-user/syscall.c         |  7 +++++--
 plugins/api.c                |  7 +++++++
 plugins/core.c               | 37 ++++++++++++++++++++++++++++++++++++
 7 files changed, 123 insertions(+), 11 deletions(-)
include/qemu/plugin-event.h +1 -0
index 1100dae2123..7f3c5927f1f 100644
@@ -23,6 +23,7 @@ enum qemu_plugin_event {
     QEMU_PLUGIN_EV_VCPU_INTERRUPT,
     QEMU_PLUGIN_EV_VCPU_EXCEPTION,
     QEMU_PLUGIN_EV_VCPU_HOSTCALL,
+    QEMU_PLUGIN_EV_VCPU_SYSCALL_FILTER,
     QEMU_PLUGIN_EV_MAX, /* total number of plugin events we support */
 };
 
include/qemu/plugin.h +24 -9
index cea0a68858b..91df1e78d2c 100644
@@ -55,15 +55,16 @@ void qemu_plugin_opt_parse(const char *optstr, QemuPluginList *head);
 int qemu_plugin_load_list(QemuPluginList *head, Error **errp);
 
 union qemu_plugin_cb_sig {
-    qemu_plugin_simple_cb_t          simple;
-    qemu_plugin_udata_cb_t           udata;
-    qemu_plugin_vcpu_simple_cb_t     vcpu_simple;
-    qemu_plugin_vcpu_udata_cb_t      vcpu_udata;
-    qemu_plugin_vcpu_discon_cb_t     vcpu_discon;
-    qemu_plugin_vcpu_tb_trans_cb_t   vcpu_tb_trans;
-    qemu_plugin_vcpu_mem_cb_t        vcpu_mem;
-    qemu_plugin_vcpu_syscall_cb_t    vcpu_syscall;
-    qemu_plugin_vcpu_syscall_ret_cb_t vcpu_syscall_ret;
+    qemu_plugin_simple_cb_t              simple;
+    qemu_plugin_udata_cb_t               udata;
+    qemu_plugin_vcpu_simple_cb_t         vcpu_simple;
+    qemu_plugin_vcpu_udata_cb_t          vcpu_udata;
+    qemu_plugin_vcpu_discon_cb_t         vcpu_discon;
+    qemu_plugin_vcpu_tb_trans_cb_t       vcpu_tb_trans;
+    qemu_plugin_vcpu_mem_cb_t            vcpu_mem;
+    qemu_plugin_vcpu_syscall_cb_t        vcpu_syscall;
+    qemu_plugin_vcpu_syscall_ret_cb_t    vcpu_syscall_ret;
+    qemu_plugin_vcpu_syscall_filter_cb_t vcpu_syscall_filter;
     void *generic;
 };
 
@@ -169,6 +170,11 @@ qemu_plugin_vcpu_syscall(CPUState *cpu, int64_t num, uint64_t a1,
                          uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5,
                          uint64_t a6, uint64_t a7, uint64_t a8);
 void qemu_plugin_vcpu_syscall_ret(CPUState *cpu, int64_t num, int64_t ret);
+bool
+qemu_plugin_vcpu_syscall_filter(CPUState *cpu, int64_t num, uint64_t a1,
+                                uint64_t a2, uint64_t a3, uint64_t a4,
+                                uint64_t a5, uint64_t a6, uint64_t a7,
+                                uint64_t a8, uint64_t *ret);
 
 void qemu_plugin_vcpu_mem_cb(CPUState *cpu, uint64_t vaddr,
                              uint64_t value_low,
@@ -280,6 +286,15 @@ static inline
 void qemu_plugin_vcpu_syscall_ret(CPUState *cpu, int64_t num, int64_t ret)
 { }
 
+static inline bool
+qemu_plugin_vcpu_syscall_filter(CPUState *cpu, int64_t num, uint64_t a1,
+                                uint64_t a2, uint64_t a3, uint64_t a4,
+                                uint64_t a5, uint64_t a6, uint64_t a7,
+                                uint64_t a8, uint64_t *ret)
+{
+    return false;
+}
+
 static inline void qemu_plugin_vcpu_mem_cb(CPUState *cpu, uint64_t vaddr,
                                            uint64_t value_low,
                                            uint64_t value_high,
include/qemu/qemu-plugin.h +32 -0
index 29663591ebf..e8db7a72545 100644
@@ -798,6 +798,33 @@ typedef void
                                  uint64_t a3, uint64_t a4, uint64_t a5,
                                  uint64_t a6, uint64_t a7, uint64_t a8);
 
+/**
+ * typedef qemu_plugin_vcpu_syscall_filter_cb_t - vCPU syscall filter callback
+ * function type
+ * @id: plugin id
+ * @vcpu_index: the executing vCPU
+ * @num: the syscall number
+ * @a1: the 1st syscall argument
+ * @a2: the 2nd syscall argument
+ * @a3: the 3rd syscall argument
+ * @a4: the 4th syscall argument
+ * @a5: the 5th syscall argument
+ * @a6: the 6th syscall argument
+ * @a7: the 7th syscall argument
+ * @a8: the 8th syscall argument
+ * @sysret: reference of the syscall return value, must set this if filtered
+ *
+ * Returns true if you want to filter this syscall (i.e. stop it being
+ * handled further), otherwise returns false.
+ */
+typedef bool
+(*qemu_plugin_vcpu_syscall_filter_cb_t)(qemu_plugin_id_t id,
+                                        unsigned int vcpu_index,
+                                        int64_t num, uint64_t a1, uint64_t a2,
+                                        uint64_t a3, uint64_t a4, uint64_t a5,
+                                        uint64_t a6, uint64_t a7, uint64_t a8,
+                                        uint64_t *sysret);
+
 QEMU_PLUGIN_API
 void qemu_plugin_register_vcpu_syscall_cb(qemu_plugin_id_t id,
                                           qemu_plugin_vcpu_syscall_cb_t cb);
@@ -811,6 +838,11 @@ void
 qemu_plugin_register_vcpu_syscall_ret_cb(qemu_plugin_id_t id,
                                          qemu_plugin_vcpu_syscall_ret_cb_t cb);
 
+QEMU_PLUGIN_API
+void
+qemu_plugin_register_vcpu_syscall_filter_cb(qemu_plugin_id_t id,
+                                            qemu_plugin_vcpu_syscall_filter_cb_t cb);
+
 
 /**
  * qemu_plugin_insn_disas() - return disassembly string for instruction
include/user/syscall-trace.h +17 -0
index 9bd7ca19c84..4ee6c4e5134 100644
@@ -39,5 +39,22 @@ static inline void record_syscall_return(CPUState *cpu, int num, abi_long ret)
     gdb_syscall_return(cpu, num);
 }
 
+static bool send_through_syscall_filters(CPUState *cpu, int num,
+                                         abi_long arg1, abi_long arg2,
+                                         abi_long arg3, abi_long arg4,
+                                         abi_long arg5, abi_long arg6,
+                                         abi_long arg7, abi_long arg8,
+                                         abi_long *sysret)
+{
+    uint64_t sysret64 = 0;
+    bool filtered = qemu_plugin_vcpu_syscall_filter(cpu, num, arg1, arg2,
+                                                    arg3, arg4, arg5, arg6,
+                                                    arg7, arg8, &sysret64);
+    if (filtered) {
+        *sysret = sysret64;
+    }
+    return filtered;
+}
+
 
 #endif /* SYSCALL_TRACE_H */
linux-user/syscall.c +5 -2
index 2060e561a20..9ae3c5bfbd7 100644
@@ -14201,8 +14201,11 @@ abi_long do_syscall(CPUArchState *cpu_env, int num, abi_long arg1,
         print_syscall(cpu_env, num, arg1, arg2, arg3, arg4, arg5, arg6);
     }
 
-    ret = do_syscall1(cpu_env, num, arg1, arg2, arg3, arg4,
-                      arg5, arg6, arg7, arg8);
+    if (!send_through_syscall_filters(cpu, num, arg1, arg2, arg3, arg4, arg5,
+                                      arg6, arg7, arg8, &ret)) {
+        ret = do_syscall1(cpu_env, num, arg1, arg2, arg3, arg4,
+                          arg5, arg6, arg7, arg8);
+    }
 
     if (unlikely(qemu_loglevel_mask(LOG_STRACE))) {
         print_syscall_ret(cpu_env, num, ret, arg1, arg2,
plugins/api.c +7 -0
index 267fa2fd503..a98c0d3e41a 100644
@@ -208,6 +208,13 @@ qemu_plugin_register_vcpu_syscall_ret_cb(qemu_plugin_id_t id,
     plugin_register_cb(id, QEMU_PLUGIN_EV_VCPU_SYSCALL_RET, cb);
 }
 
+void
+qemu_plugin_register_vcpu_syscall_filter_cb(qemu_plugin_id_t id,
+                                            qemu_plugin_vcpu_syscall_filter_cb_t cb)
+{
+    plugin_register_cb(id, QEMU_PLUGIN_EV_VCPU_SYSCALL_FILTER, cb);
+}
+
 /*
  * Plugin Queries
  *
plugins/core.c +37 -0
index b4b783008f7..85fabf9ec81 100644
@@ -564,6 +564,43 @@ void qemu_plugin_vcpu_syscall_ret(CPUState *cpu, int64_t num, int64_t ret)
     }
 }
 
+/*
+ * Disable CFI checks.
+ * The callback function has been loaded from an external library so we do not
+ * have type information
+ */
+QEMU_DISABLE_CFI
+bool
+qemu_plugin_vcpu_syscall_filter(CPUState *cpu, int64_t num, uint64_t a1,
+                                uint64_t a2, uint64_t a3, uint64_t a4,
+                                uint64_t a5, uint64_t a6, uint64_t a7,
+                                uint64_t a8, uint64_t *sysret)
+{
+    struct qemu_plugin_cb *cb, *next;
+    enum qemu_plugin_event ev = QEMU_PLUGIN_EV_VCPU_SYSCALL_FILTER;
+    bool filtered = false;
+
+    if (!test_bit(ev, cpu->plugin_state->event_mask)) {
+        return false;
+    }
+
+    qemu_plugin_set_cb_flags(cpu, QEMU_PLUGIN_CB_RW_REGS);
+
+    QLIST_FOREACH_SAFE_RCU(cb, &plugin.cb_lists[ev], entry, next) {
+        qemu_plugin_vcpu_syscall_filter_cb_t func = cb->f.vcpu_syscall_filter;
+
+        if (func(cb->ctx->id, cpu->cpu_index, num, a1, a2, a3, a4,
+                 a5, a6, a7, a8, sysret)) {
+            filtered = true;
+            break;
+        }
+    }
+
+    qemu_plugin_set_cb_flags(cpu, QEMU_PLUGIN_CB_NO_REGS);
+
+    return filtered;
+}
+
 void qemu_plugin_vcpu_idle_cb(CPUState *cpu)
 {
     /* idle and resume cb may be called before init, ignore in this case */
Signature · 1 line
2.47.3
#9 lore raw

RFC PATCH 8/12 tcg tests: add a test to verify the syscall filter plugin API

In reply to Alex Bennée

From: Ziyang Zhang <[email protected]>

Register a syscall filter callback in tests/tcg/plugins/sycall.c, returns a specific value for a magic system call number, and check it in tests/tcg/multiarch/test-plugin-syscall-filter.c.

Message-ID: <[email protected]>

---
 .../multiarch/test-plugin-syscall-filter.c    | 35 +++++++++++++++++++
 tests/tcg/plugins/syscall.c                   | 19 ++++++++++
 tests/tcg/multiarch/Makefile.target           |  4 ++-
 3 files changed, 57 insertions(+), 1 deletion(-)
 create mode 100644 tests/tcg/multiarch/test-plugin-syscall-filter.c
tests/tcg/multiarch/test-plugin-syscall-filter.c new file +35 -0
new file mode 100644
index 00000000000..caa2063a461
@@ -0,0 +1,35 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * This test attempts to execute a magic syscall. The syscall test plugin
+ * should intercept this and return an expected value.
+ */
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+int main(int argc, char *argv[])
+{
+    /*
+     * We cannot use a very large magic syscall number, because on some ISAs,
+     * QEMU will treat it as an illegal instruction and trigger a critical
+     * exception. For instance, on arm32, the syscall number cannot exceed
+     * ARM_NR_BASE (0xf0000), as can be seen in
+     * "linux-user/arm/cpu_loop.c:cpu_loop".
+     *
+     * Therefore, we pick 2048 because, as of now, no ISA in Linux uses this
+     * number. This is just a test case; replace this number as needed in the
+     * future.
+     *
+     * The corresponding syscall filter is implemented in
+     * "tests/tcg/plugins/syscall.c".
+     */
+    long ret = syscall(2048, 0x66CCFF);
+    if (ret != 0xFFCC66) {
+        fprintf(stderr, "Error: unexpected syscall return value %ld\n", ret);
+        return EXIT_FAILURE;
+    }
+    return EXIT_SUCCESS;
+}
tests/tcg/plugins/syscall.c +19 -0
index 42801f5c863..e7d4e9b5895 100644
@@ -170,6 +170,24 @@ static void vcpu_syscall_ret(qemu_plugin_id_t id, unsigned int vcpu_idx,
     }
 }
 
+static bool vcpu_syscall_filter(qemu_plugin_id_t id, unsigned int vcpu_index,
+                                int64_t num, uint64_t a1, uint64_t a2,
+                                uint64_t a3, uint64_t a4, uint64_t a5,
+                                uint64_t a6, uint64_t a7, uint64_t a8,
+                                uint64_t *sysret)
+{
+    /* Special syscall to test the filter functionality. */
+    if (num == 2048 && a1 == 0x66CCFF) {
+        *sysret = 0xFFCC66;
+
+        if (!statistics) {
+            qemu_plugin_outs("magic syscall filtered, set magic return\n");
+        }
+        return true;
+    }
+    return false;
+}
+
 static void print_entry(gpointer val, gpointer user_data)
 {
     SyscallStats *entry = (SyscallStats *) val;
@@ -255,6 +273,7 @@ QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,
 
     qemu_plugin_register_vcpu_syscall_cb(id, vcpu_syscall);
     qemu_plugin_register_vcpu_syscall_ret_cb(id, vcpu_syscall_ret);
+    qemu_plugin_register_vcpu_syscall_filter_cb(id, vcpu_syscall_filter);
     qemu_plugin_register_atexit_cb(id, plugin_exit, NULL);
     return 0;
 }
tests/tcg/multiarch/Makefile.target +3 -1
index f5b4d2b8138..4005e3a8a9a 100644
@@ -202,8 +202,10 @@ run-plugin-test-plugin-mem-access-with-libmem.so: \
 	CHECK_PLUGIN_OUTPUT_COMMAND= \
 	$(SRC_PATH)/tests/tcg/multiarch/check-plugin-output.sh \
 	$(QEMU) $<
+run-plugin-test-plugin-syscall-filter-with-libsyscall.so:
 
-EXTRA_RUNS_WITH_PLUGIN += run-plugin-test-plugin-mem-access-with-libmem.so
+EXTRA_RUNS_WITH_PLUGIN += run-plugin-test-plugin-mem-access-with-libmem.so \
+			   			  run-plugin-test-plugin-syscall-filter-with-libsyscall.so
 endif
 
 # Update TESTS
Signature · 1 line
2.47.3
#10 lore raw

RFC PATCH 9/12 plugins: split init_hook into create and reset

In reply to Alex Bennée

We need to move the plugin vcpu_init callback to the reset phase so all register information is available to plugins. However so as not to complicate the initialisation code we still want the call once to do our housekeeping.

---
 include/qemu/plugin.h      | 19 ++++++++++++++-----
 include/qemu/qemu-plugin.h |  4 +++-
 hw/core/cpu-common.c       | 21 +++++++++++++++------
 plugins/core.c             | 31 +++++++++++++++++++++++--------
 4 files changed, 55 insertions(+), 20 deletions(-)
include/qemu/plugin.h +14 -5
index 91df1e78d2c..6d38b923c73 100644
@@ -150,14 +150,23 @@ struct CPUPluginState {
 };
 
 /**
- * qemu_plugin_create_vcpu_state: allocate plugin state
+ * qemu_plugin_vcpu_create_hook() - called on vcpu creation
+ * @cpu: vCPU CPUState
  *
- * The returned data must be released with g_free()
- * when no longer required.
+ * We don't expose creation to plugins but we need to do internal
+ * housekeeping of stuff. Called once per vCPU creation.
  */
-CPUPluginState *qemu_plugin_create_vcpu_state(void);
+void qemu_plugin_vcpu_create_hook(CPUState *cpu);
+
+/**
+ * qemu_plugin_vcpu_reset_hook() - called on vcpu reset
+ * @cpu: vCPU CPUState
+ *
+ * Called each time the vcpu is reset. This can happen multiple times
+ * for a given vCPU. We expose this to plugins as vcpu_init.
+ */
+void qemu_plugin_vcpu_reset_hook(CPUState *cpu);
 
-void qemu_plugin_vcpu_init_hook(CPUState *cpu);
 void qemu_plugin_vcpu_exit_hook(CPUState *cpu);
 void qemu_plugin_tb_trans_cb(CPUState *cpu, struct qemu_plugin_tb *tb);
 void qemu_plugin_vcpu_idle_cb(CPUState *cpu);
include/qemu/qemu-plugin.h +3 -1
index e8db7a72545..a75e323f31d 100644
@@ -238,7 +238,9 @@ void qemu_plugin_reset(qemu_plugin_id_t id, qemu_plugin_simple_cb_t cb);
  * @id: plugin ID
  * @cb: callback function
  *
- * The @cb function is called every time a vCPU is initialized.
+ * The @cb function is called every time a vCPU is initialised. This
+ * includes resets. NOTE: not all register information may be
+ * available the first time this is called.
  *
  * See also: qemu_plugin_register_vcpu_exit_cb()
  */
hw/core/cpu-common.c +15 -6
index 8c306c89e45..8113d83713f 100644
@@ -100,8 +100,18 @@ void cpu_dump_state(CPUState *cpu, FILE *f, int flags)
 void cpu_reset(CPUState *cpu)
 {
     device_cold_reset(DEVICE(cpu));
-
     trace_cpu_reset(cpu->cpu_index);
+
+#ifdef CONFIG_TCG
+    /*
+     * Because vCPUs get "started" before the machine is ready we often
+     * can't provide all the information plugins need during
+     * cpu_common_initfn. However the vCPU will be reset a few times
+     * before we eventually set things going giving plugins an
+     * opportunity to update things.
+     */
+    qemu_plugin_vcpu_reset_hook(cpu);
+#endif
 }
 
 static void cpu_common_reset_hold(Object *obj, ResetType type)
@@ -328,14 +338,13 @@ static void cpu_common_initfn(Object *obj)
     cpu_exec_initfn(cpu);
 
     /*
-     * Plugin initialization must wait until the cpu start executing
-     * code, but we must queue this work before the threads are
-     * created to ensure we don't race.
+     * Called once at vCPU creation so the plugin subsystem can do its
+     * housekeeping. See also cpu_reset() and
+     * qemu_plugin_vcpu_reset_hook() above.
      */
 #ifdef CONFIG_PLUGIN
     if (tcg_enabled()) {
-        cpu->plugin_state = qemu_plugin_create_vcpu_state();
-        qemu_plugin_vcpu_init_hook(cpu);
+        qemu_plugin_vcpu_create_hook(cpu);
     }
 #endif
 }
plugins/core.c +23 -8
index 85fabf9ec81..d303256c851 100644
@@ -226,7 +226,7 @@ plugin_register_cb_udata(qemu_plugin_id_t id, enum qemu_plugin_event ev,
     do_plugin_register_cb(id, ev, func, udata);
 }
 
-CPUPluginState *qemu_plugin_create_vcpu_state(void)
+static CPUPluginState *qemu_plugin_create_vcpu_state(void)
 {
     return g_new0(CPUPluginState, 1);
 }
@@ -279,7 +279,25 @@ static void plugin_grow_scoreboards__locked(CPUState *cpu)
     end_exclusive();
 }
 
-static void qemu_plugin_vcpu_init__async(CPUState *cpu, run_on_cpu_data unused)
+static void qemu_plugin_vcpu_reset__async(CPUState *cpu, run_on_cpu_data unused)
+{
+    assert(cpu->cpu_index != UNASSIGNED_CPU_INDEX);
+
+    qemu_plugin_set_cb_flags(cpu, QEMU_PLUGIN_CB_RW_REGS);
+    plugin_vcpu_cb__simple(cpu, QEMU_PLUGIN_EV_VCPU_INIT);
+    qemu_plugin_set_cb_flags(cpu, QEMU_PLUGIN_CB_NO_REGS);
+}
+
+void qemu_plugin_vcpu_reset_hook(CPUState *cpu)
+{
+    async_run_on_cpu(cpu, qemu_plugin_vcpu_reset__async, RUN_ON_CPU_NULL);
+}
+
+/*
+ * This is purely internal to plugins as we need to expand scoreboards
+ * each time a new vCPU is created.
+ */
+static void qemu_plugin_vcpu_create__async(CPUState *cpu, run_on_cpu_data unused)
 {
     bool success;
 
@@ -292,16 +310,13 @@ static void qemu_plugin_vcpu_init__async(CPUState *cpu, run_on_cpu_data unused)
     g_assert(success);
     plugin_grow_scoreboards__locked(cpu);
     qemu_rec_mutex_unlock(&plugin.lock);
-
-    qemu_plugin_set_cb_flags(cpu, QEMU_PLUGIN_CB_RW_REGS);
-    plugin_vcpu_cb__simple(cpu, QEMU_PLUGIN_EV_VCPU_INIT);
-    qemu_plugin_set_cb_flags(cpu, QEMU_PLUGIN_CB_NO_REGS);
 }
 
-void qemu_plugin_vcpu_init_hook(CPUState *cpu)
+void qemu_plugin_vcpu_create_hook(CPUState *cpu)
 {
+    cpu->plugin_state = qemu_plugin_create_vcpu_state();
     /* Plugin initialization must wait until the cpu start executing code */
-    async_run_on_cpu(cpu, qemu_plugin_vcpu_init__async, RUN_ON_CPU_NULL);
+    async_run_on_cpu(cpu, qemu_plugin_vcpu_create__async, RUN_ON_CPU_NULL);
 }
 
 void qemu_plugin_vcpu_exit_hook(CPUState *cpu)
Signature · 1 line
2.47.3
#11 lore raw

Re: [RFC PATCH 09/12] plugins: split init_hook into create and reset

Quoted 5 lines · Alex Bennée

We need to move the plugin vcpu_init callback to the reset phase so all register information is available to plugins. However so as not to complicate the initialisation code we still want the call once to do our housekeeping.

Quoted 7 lines
---
  include/qemu/plugin.h      | 19 ++++++++++++++-----
  include/qemu/qemu-plugin.h |  4 +++-
  hw/core/cpu-common.c       | 21 +++++++++++++++------
  plugins/core.c             | 31 +++++++++++++++++++++++--------
  4 files changed, 55 insertions(+), 20 deletions(-)

From our conversation about GIC registers not being visible at cpu init time, it really seems like the root issue is that we have an external component that should not be able to dynamically define new cpu registers, and that cpu should deal with it directly when creating its own registers.

From what I understood, those registers are defined dynamically in:
void gicv3_init_cpuif(GICv3State *s)

Any chance this could be reversed in terms of dependency to be initialized *before* the cpus, so that GICv3State could be passed as a parameter for initialization on cpu side?

Regards,
Pierrick

#12 lore raw

RFC PATCH 10/12 target/arm: defer creation of gdb register until machine created

In reply to Alex Bennée

When running machine emulation we may create additional cp_regs for things like the GIC interface. To include them for gdbstub and plugins defer the creation until the machine is finalized.

---
 target/arm/cpu.c | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
target/arm/cpu.c +33 -0
index 39292fb9bc1..81997bac06a 100644
@@ -41,6 +41,7 @@
 #ifdef CONFIG_TCG
 #include "hw/intc/armv7m_nvic.h"
 #endif /* CONFIG_TCG */
+#include "system/system.h"
 #endif /* !CONFIG_USER_ONLY */
 #include "system/tcg.h"
 #include "system/qtest.h"
@@ -1535,6 +1536,23 @@ static void arm_cpu_post_init(Object *obj)
     qdev_property_add_static(DEVICE(obj), &arm_cpu_cfgend_property);
 }
 
+#ifndef CONFIG_USER_ONLY
+static void arm_finalize_gdb_regs(Notifier *notifier, void *unused)
+{
+    CPUState *cs;
+
+    CPU_FOREACH(cs) {
+        ARMCPU *cpu = ARM_CPU(cs);
+        arm_cpu_register_gdb_regs_for_features(cpu);
+        arm_cpu_register_gdb_commands(cpu);
+    }
+}
+
+static Notifier arm_machine_setup_gdb_notify = {
+    .notify = arm_finalize_gdb_regs,
+};
+#endif
+
 static void arm_cpu_finalizefn(Object *obj)
 {
     ARMCPU *cpu = ARM_CPU(obj);
@@ -2138,8 +2156,15 @@ static void arm_cpu_realizefn(DeviceState *dev, Error **errp)
 #endif
 
     register_cp_regs_for_features(cpu);
+
+#ifdef CONFIG_USER_ONLY
+    /*
+     * For system emulation not everything is done yet - see
+     * arm_machine_setup_gdb_notify
+     */
     arm_cpu_register_gdb_regs_for_features(cpu);
     arm_cpu_register_gdb_commands(cpu);
+#endif
 
     arm_init_cpreg_list(cpu);
 
@@ -2392,6 +2417,14 @@ static void arm_cpu_class_init(ObjectClass *oc, const void *data)
     cc->gdb_write_register = arm_cpu_gdb_write_register;
 #ifndef CONFIG_USER_ONLY
     cc->sysemu_ops = &arm_sysemu_ops;
+    /*
+     * For system emulation we defer setting up GDB registers until
+     * the whole machine in setup. This is because we may still have
+     * some to define for emulated HW (e.g. the GIC).
+     */
+    qemu_add_machine_init_done_notifier(&arm_machine_setup_gdb_notify);
+#else
+
 #endif
     cc->gdb_arch_name = arm_gdb_arch_name;
     cc->gdb_get_core_xml_file = arm_gdb_get_core_xml_file;
Signature · 1 line
2.47.3
Reviewed-by on v1 10/12
#13 lore raw

Re: [RFC PATCH 10/12] target/arm: defer creation of gdb register until machine created

Quoted 8 lines · Alex Bennée

When running machine emulation we may create additional cp_regs for things like the GIC interface. To include them for gdbstub and plugins defer the creation until the machine is finalized.

---
  target/arm/cpu.c | 33 +++++++++++++++++++++++++++++++++
  1 file changed, 33 insertions(+)
#14 lore raw

RFC PATCH 11/12 contrib/plugins: add systrace plugin for tracking exceptions and irqs

In reply to Alex Bennée

I'm hunting for lost IRQs and want to trace what various registers are being set to when IRQs happen. This combines the discontinuity tracking API with register value tracking to do so.

It supports:

tracksw - to keep track of the last thing that wrote to a register show_frompc - show the line executing before the discontinuity

As we might not have disassembly for the nominal last pc for an async IRQ we also track the pc of the last executed instruction in a block and use that as a fallback.

---
 contrib/plugins/systrace.c  | 572 ++++++++++++++++++++++++++++++++++++
 contrib/plugins/meson.build |   2 +-
 2 files changed, 573 insertions(+), 1 deletion(-)
 create mode 100644 contrib/plugins/systrace.c
contrib/plugins/systrace.c new file +572 -0
new file mode 100644
index 00000000000..6c8f6d91f87
@@ -0,0 +1,572 @@
+/*
+ * Copyright (C) 2025, Alex Bennée <[email protected]>
+ *
+ * System tracing tool. Log changes to system registers and where IRQ
+ * and exceptions occur in the code.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include <glib.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <qemu-plugin.h>
+
+QEMU_PLUGIN_EXPORT int qemu_plugin_version = QEMU_PLUGIN_VERSION;
+
+/* The base register we are tracking */
+typedef struct {
+    struct qemu_plugin_register *handle;
+    const char *name;
+    int index;
+    int instrumentation_count;
+} BaseRegister;
+
+/*
+ * Array of BaseRegister - the position in the array will also
+ * control the index into the access score board. As the list may grow
+ * dynamically as additional vCPUs are initialised we need to protect
+ * the list with a lock.
+ */
+static GArray *base_registers;
+static GMutex base_reg_lock;
+static struct qemu_plugin_scoreboard *base_reg_hits;
+
+#define MAX_TRACKING_REGISTERS 32
+
+/*
+ * Scoreboard for tracking last sysreg write - usually the last one
+ * touched is the one that triggered something ;-)
+ */
+static bool track_sysreg_write;
+static char *sysreg_ins;
+static struct qemu_plugin_scoreboard *last_sysreg_write;
+
+/*
+ * Scoreboard for tracking last executed PC. It's possible to be
+ * missing a translation of from_pc due to the fact we may have
+ * advanced the PC before attempting the translation. However the last
+ * insn in a block will generally be the last thing we did.
+ */
+static struct qemu_plugin_scoreboard *last_exec_pc;
+
+/* per-vcpu initialisation lock */
+static GMutex vcpu_init_lock;
+
+/* the passed matching parameters */
+static GPtrArray *rmatches;
+
+/* The per-cpu register tracking structure */
+typedef struct {
+    GByteArray *last;
+    uint64_t last_dump_count;
+    int index;
+} Register;
+
+/* CPU specific data */
+typedef struct CPU {
+    /* Track available registers over multiple vcpu_init calls */
+    int available_reg_count;
+    /* Ptr array of Register */
+    GPtrArray *registers;
+} CPU;
+
+/* This is defined at start time */
+static GArray *cpus;
+
+/* Track the disassembly */
+static GHashTable *haddr_disas;
+static GMutex disas_lock;
+
+static bool show_from_pc;
+
+static CPU *get_cpu(int vcpu_index)
+{
+    CPU *c = &g_array_index(cpus, CPU, vcpu_index);
+    return c;
+}
+
+/*
+ * BaseRegister handling
+ *
+ * We return copies of the BaseRegister entry so we don't get
+ * surprised by resizing of the underlying array.
+ */
+
+static BaseRegister get_base_reg(int index)
+{
+    BaseRegister info, *entry;
+
+    g_mutex_lock(&base_reg_lock);
+
+    entry = &g_array_index(base_registers, BaseRegister, index);
+    info = *entry;
+
+    g_mutex_unlock(&base_reg_lock);
+
+    return info;
+}
+
+static BaseRegister find_or_add_base_register(qemu_plugin_reg_descriptor * rd)
+{
+    g_autofree gchar *lower = g_utf8_strdown(rd->name, -1);
+    BaseRegister base;
+    bool found = false;
+
+    g_mutex_lock(&base_reg_lock);
+
+    for (int i = 0; i < base_registers->len; i++) {
+        BaseRegister *check = &g_array_index(base_registers, BaseRegister, i);
+        if (check->handle == rd->handle) {
+            base = *check;
+            found = true;
+            break;
+        }
+    }
+
+    /* didn't find, then add it */
+    if (!found) {
+        base.handle = rd->handle;
+        base.name = g_intern_string(lower);
+        base.index = base_registers->len;
+
+        g_array_append_val(base_registers, base);
+    }
+
+    g_assert(base_registers->len < MAX_TRACKING_REGISTERS);
+
+    g_mutex_unlock(&base_reg_lock);
+
+    return base;
+}
+
+/* Sets *info on find */
+static bool find_base_reg_by_str(const gchar *insn_arg, BaseRegister *info)
+{
+    bool reg_hit = false;
+
+    g_mutex_lock(&base_reg_lock);
+
+    for (int n = 0; n < base_registers->len; n++) {
+        BaseRegister *base = &g_array_index(base_registers, BaseRegister, n);
+        if (g_strrstr(insn_arg, base->name)) {
+            *info = *base;
+            reg_hit = true;
+            break;
+        }
+    }
+
+    g_mutex_unlock(&base_reg_lock);
+
+    return reg_hit;
+}
+
+/**
+ * On translation block new translation
+ *
+ * QEMU convert code by translation block (TB). We are only going to
+ * add hooks to instructions that modify the registers we care about.
+ * However we do need a record of every instruction we come across so
+ * we can resolve information for the discontinuities.
+ */
+static void vcpu_tb_trans(qemu_plugin_id_t id, struct qemu_plugin_tb *tb)
+{
+    struct qemu_plugin_insn *insn;
+    uint64_t vaddr;
+
+    g_mutex_lock(&disas_lock);
+
+    size_t n_insns = qemu_plugin_tb_n_insns(tb);
+    for (size_t i = 0; i < n_insns; i++) {
+        g_autofree char *insn_disas = NULL;
+        const gchar *intern_disas;
+
+        /*
+         * `insn` is shared between translations in QEMU, copy needed
+         * data here.
+         *
+         * We will generate an interned string from the disassembly
+         * and save it in out hash table indexed by the vaddr.
+         *
+         * This is vulnerable to old pages being swapped out because
+         * we aren't tracking the underlying physical address. But
+         * generally we expect this to be sane.
+         *
+         * The interned strings are never free'd but hopefully there
+         * is enough repetition we don't need a string for every
+         * instruction we execute.
+         */
+        insn = qemu_plugin_tb_get_insn(tb, i);
+        insn_disas = qemu_plugin_insn_disas(insn);
+        intern_disas = g_intern_string(insn_disas);
+        /* haddr = qemu_plugin_insn_haddr(insn); */
+        vaddr = qemu_plugin_insn_vaddr(insn);
+
+        /* replaces any existing interned string */
+        g_hash_table_insert(haddr_disas,
+                            GUINT_TO_POINTER(vaddr),
+                            (gpointer) intern_disas);
+
+        /*
+         * Check the disassembly to see if a register we care about
+         * will be affected by this instruction. This relies on the
+         * dissembler doing something sensible for the registers we
+         * care about.
+         */
+        g_auto(GStrv) args = g_strsplit_set(insn_disas, " \t", 2);
+
+        if (args && args[1]) {
+            BaseRegister info;
+
+            if (find_base_reg_by_str(args[1], &info)) {
+                qemu_plugin_u64 cnt = {
+                    .score = base_reg_hits,
+                    .offset = (size_t)info.index * sizeof(uint64_t)
+                };
+                qemu_plugin_register_inline_per_vcpu(insn,
+                                                    QEMU_PLUGIN_INLINE_ADD_U64,
+                                                     cnt, 1);
+            }
+        }
+
+        /*
+         * If we are tracking system register writes lets check here.
+         */
+        if (args && track_sysreg_write) {
+            if (g_strrstr(args[0], sysreg_ins)) {
+                qemu_plugin_u64 write_pc = {
+                    .score = last_sysreg_write,
+                };
+                qemu_plugin_register_inline_per_vcpu(
+                    insn, QEMU_PLUGIN_INLINE_STORE_U64,
+                    write_pc, vaddr);
+            }
+        }
+    }
+
+    /*
+     * On the last instruction store the PC so we can recover if we
+     * are missing translations we haven't done yet.
+     */
+    if (n_insns > 0) {
+        qemu_plugin_u64 last_pc = { .score = last_exec_pc };
+        qemu_plugin_register_inline_per_vcpu(
+                insn, QEMU_PLUGIN_INLINE_STORE_U64,
+                last_pc, vaddr);
+    }
+
+    g_mutex_unlock(&disas_lock);
+}
+
+static void dump_reg(GString *out, GByteArray *value) {
+    /* TODO: handle BE properly */
+    for (int j = value->len - 1; j >= 0; j--) {
+        g_string_append_printf(out, "%02x", value->data[j]);
+    }
+}
+
+static void check_reg_changes(unsigned int vcpu_index, CPU *cpu, GString *out)
+{
+    uint64_t *hits = qemu_plugin_scoreboard_find(base_reg_hits, vcpu_index);
+
+    for (int i = 0; i < cpu->registers->len; i++) {
+        Register *reg = g_ptr_array_index(cpu->registers, i);
+        uint64_t hit_count = hits[reg->index];
+        if (hit_count > reg->last_dump_count) {
+            BaseRegister base = get_base_reg(reg->index);
+            g_autoptr(GByteArray) new_val = g_byte_array_new();
+            int bytes = qemu_plugin_read_register(base.handle, new_val);
+            g_assert(bytes > 0);
+            g_assert(bytes == reg->last->len);
+            if (memcmp(reg->last->data, new_val->data, reg->last->len) != 0) {
+                g_string_append_printf(out, "  REG: %s is ", base.name);
+                dump_reg(out, new_val);
+                g_string_append_printf(out, " (previously ");
+                dump_reg(out, reg->last);
+                g_string_append_printf(out, ", %"PRId64" to %"PRId64" hits)\n", reg->last_dump_count, hit_count);
+
+                /* record the new value */
+                g_byte_array_set_size(reg->last, 0);
+                g_byte_array_append(reg->last, new_val->data, new_val->len);
+            }
+            reg->last_dump_count = hit_count;
+        }
+    }
+}
+
+
+static void vcpu_discon(qemu_plugin_id_t id, unsigned int vcpu_index,
+                        enum qemu_plugin_discon_type type, uint64_t from_pc,
+                        uint64_t to_pc)
+{
+    CPU *cpu = get_cpu(vcpu_index);
+    g_autoptr(GString) report = g_string_new("");
+    const char *type_string;
+    uint64_t from_hwaddr;
+    const char *disas;
+
+    qemu_plugin_translate_vaddr(from_pc, &from_hwaddr);
+
+    switch (type) {
+    case QEMU_PLUGIN_DISCON_INTERRUPT:
+        type_string = "irq";
+        break;
+    case QEMU_PLUGIN_DISCON_EXCEPTION:
+        type_string = "exception";
+        break;
+    case QEMU_PLUGIN_DISCON_HOSTCALL:
+        type_string = "host call";
+        break;
+    default:
+        g_assert_not_reached();
+        break;
+    }
+
+    g_string_append_printf(report,
+                           "CPU: %d taking %s from 0x%" PRIx64 " to 0x%" PRIx64 "\n",
+                           vcpu_index, type_string, from_pc, to_pc);
+
+    g_mutex_lock(&disas_lock);
+
+    if (show_from_pc) {
+        bool le_fallback = false;
+        uint64_t *le_pc = qemu_plugin_scoreboard_find(last_exec_pc, vcpu_index);
+        disas = g_hash_table_lookup(haddr_disas, GUINT_TO_POINTER(from_pc));
+        if (!disas) {
+            le_fallback = true;
+            disas = g_hash_table_lookup(haddr_disas, GUINT_TO_POINTER(*le_pc));
+            g_assert(disas);
+        }
+        g_string_append_printf(report, "  FROM: 0x%" PRIx64 " %s\t(%s)\n",
+                               le_fallback ? *le_pc : from_pc, disas,
+                               le_fallback ? "lepc" : "fpc");
+    }
+
+    if (track_sysreg_write) {
+        uint64_t *last_write = qemu_plugin_scoreboard_find(last_sysreg_write, vcpu_index);
+        disas = g_hash_table_lookup(haddr_disas, GUINT_TO_POINTER(*last_write));
+        if (disas) {
+            g_string_append_printf(report, "  LAST SYSREG: 0x%"PRIx64" %s\n", *last_write, disas);
+        }
+    }
+
+    g_mutex_unlock(&disas_lock);
+
+    if (base_reg_hits && cpu->registers) {
+        check_reg_changes(vcpu_index, cpu, report);
+    }
+
+    qemu_plugin_outs(report->str);
+}
+
+/**
+ * On vcpu exit, print the final state of the registers
+ */
+static void vcpu_exit(qemu_plugin_id_t id, unsigned int cpu_index)
+{
+    g_autoptr(GString) result = g_string_new("Register, Value, Accesses ");
+    g_autoptr(GByteArray) value = g_byte_array_new();
+
+    g_string_append_printf(result, "for CPU%d\n", cpu_index);
+    for (int i = 0; i < base_registers->len; i++) {
+        BaseRegister *base = &g_array_index(base_registers, BaseRegister, i);
+        qemu_plugin_u64 cnt = {
+            .score = base_reg_hits,
+            .offset = (size_t)base->index * sizeof(uint64_t)
+        };
+        uint64_t sum_hits = qemu_plugin_u64_get(cnt, cpu_index );
+
+        if (sum_hits > 0) {
+            g_string_append_printf(result, "%s, ", base->name);
+            qemu_plugin_read_register(base->handle, value);
+            dump_reg(result, value);
+            g_string_append_printf(result, ", % "PRId64"\n", sum_hits);
+        }
+    }
+    qemu_plugin_outs(result->str);
+}
+
+
+/*
+ * g_pattern_match_string has been deprecated in Glib since 2.70 and
+ * will complain about it if you try to use it. Fortunately the
+ * signature of both functions is the same making it easy to work
+ * around.
+ */
+static inline
+gboolean g_pattern_spec_match_string_qemu(GPatternSpec *pspec,
+                                          const gchar *string)
+{
+#if GLIB_CHECK_VERSION(2, 70, 0)
+    return g_pattern_spec_match_string(pspec, string);
+#else
+    return g_pattern_match_string(pspec, string);
+#endif
+};
+#define g_pattern_spec_match_string(p, s) g_pattern_spec_match_string_qemu(p, s)
+
+
+static Register *init_vcpu_register(BaseRegister *base)
+{
+    Register *reg = g_new0(Register, 1);
+    int r;
+
+    reg->index = base->index;
+    reg->last = g_byte_array_new();
+
+    /* read the initial value */
+    r = qemu_plugin_read_register(base->handle, reg->last);
+    /* we currently don't handle the bigger ones */
+    g_assert(r > 0);
+    g_assert(r <= 8);
+    return reg;
+}
+
+static void free_vcpu_register(gpointer data)
+{
+    Register *reg = (Register *)data;
+    g_byte_array_unref(reg->last);
+    g_free(reg);
+}
+
+static GPtrArray *registers_init(GArray *reg_list, int vcpu_index)
+{
+    g_autoptr(GPtrArray) registers = g_ptr_array_new_with_free_func(free_vcpu_register);
+
+    if (!rmatches) {
+        return NULL;
+    }
+
+    /*
+     * Go through each register in the complete list and
+     * see if we want to track it.
+     */
+    for (int r = 0; r < reg_list->len; r++) {
+        qemu_plugin_reg_descriptor *rd = &g_array_index(
+            reg_list, qemu_plugin_reg_descriptor, r);
+        for (int p = 0; p < rmatches->len; p++) {
+            g_autoptr(GPatternSpec) pat = g_pattern_spec_new(rmatches->pdata[p]);
+            g_autofree gchar *rd_lower = g_utf8_strdown(rd->name, -1);
+            if (g_pattern_spec_match_string(pat, rd->name) ||
+                g_pattern_spec_match_string(pat, rd_lower)) {
+                BaseRegister base = find_or_add_base_register(rd);
+                Register *reg = init_vcpu_register(&base);
+                g_ptr_array_add(registers, reg);
+            }
+        }
+    }
+
+    return registers->len ? g_steal_pointer(&registers) : NULL;
+}
+
+/*
+ * Initialise a new vcpu with:
+ *   - initial value of registers
+ *   - scoreboard to track reg hits
+ *   - optional scoreboard to track sysreg writes
+ */
+static void vcpu_init(qemu_plugin_id_t id, unsigned int vcpu_index)
+{
+    CPU *c;
+    g_autoptr(GArray) reg_list = qemu_plugin_get_registers();
+
+    g_mutex_lock(&vcpu_init_lock);
+
+    c = get_cpu(vcpu_index);
+
+    /* Are more registers available now? */
+    if (c->registers && (reg_list->len > c->available_reg_count)) {
+        fprintf(stderr, "%s: reset list....\n", __func__);
+        g_ptr_array_free(c->registers, true);
+        c->registers = NULL;
+    }
+
+    c->available_reg_count = reg_list->len;
+
+    if (!c->registers) {
+        c->registers = registers_init(reg_list, vcpu_index);
+        fprintf(stderr, "%s:%d reglen %d\n", __func__, vcpu_index, c->registers ? c->registers->len : 0);
+    }
+
+    if (track_sysreg_write && !last_sysreg_write) {
+        last_sysreg_write = qemu_plugin_scoreboard_new(sizeof(uint64_t));
+    }
+
+    if (!last_exec_pc) {
+        last_exec_pc = qemu_plugin_scoreboard_new(sizeof(uint64_t));
+    }
+
+    g_mutex_unlock(&vcpu_init_lock);
+}
+
+/*
+ * We have to wait until vCPUs are started before we can check the
+ * patterns find anything.
+ */
+static void add_regpat(char *regpat)
+{
+    if (!rmatches) {
+        rmatches = g_ptr_array_new();
+    }
+    g_ptr_array_add(rmatches, g_strdup(regpat));
+}
+
+/**
+ * Install the plugin
+ */
+QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,
+                                           const qemu_info_t *info, int argc,
+                                           char **argv)
+{
+    /* We only work for system emulation */
+    if (!info->system_emulation) {
+        qemu_plugin_outs("The systrace plugin is for system emulation only.");
+        return -1;
+    }
+
+    /*
+     * Initialize dynamic array to cache vCPU instruction. We also
+     * need a hash table to track disassembly.
+     */
+    cpus = g_array_sized_new(true, true, sizeof(CPU), info->system.max_vcpus);
+    g_array_set_size(cpus, info->system.max_vcpus);
+    haddr_disas = g_hash_table_new(NULL, NULL);
+
+    base_registers = g_array_new(true, true, sizeof(BaseRegister));
+    base_reg_hits = qemu_plugin_scoreboard_new(MAX_TRACKING_REGISTERS * sizeof(uint64_t));
+
+    for (int i = 0; i < argc; i++) {
+        char *opt = argv[i];
+        g_auto(GStrv) tokens = g_strsplit(opt, "=", 2);
+        if (g_strcmp0(tokens[0], "reg") == 0) {
+            add_regpat(tokens[1]);
+        } else if (g_strcmp0(tokens[0], "tracksw") == 0) {
+            track_sysreg_write = true;
+            if (tokens[1]) {
+                sysreg_ins = g_strdup(tokens[1]);
+            } else {
+                sysreg_ins = g_strdup("msr");
+            }
+        } else if (g_strcmp0(tokens[0], "show_frompc") == 0) {
+            if (!qemu_plugin_bool_parse(tokens[0], tokens[1], &show_from_pc)) {
+                fprintf(stderr, "boolean argument parsing failed: %s\n", opt);
+                return -1;
+            }
+        } else {
+            fprintf(stderr, "option parsing failed: %s\n", opt);
+            return -1;
+        }
+    }
+
+    /* Register init, translation block and exit callbacks */
+    qemu_plugin_register_vcpu_init_cb(id, vcpu_init);
+    qemu_plugin_register_vcpu_tb_trans_cb(id, vcpu_tb_trans);
+    qemu_plugin_register_vcpu_discon_cb(id, QEMU_PLUGIN_DISCON_ALL, vcpu_discon);
+    qemu_plugin_register_vcpu_exit_cb(id, vcpu_exit);
+
+    return 0;
+}
contrib/plugins/meson.build +1 -1
index eb944b5159a..3d1365da433 100644
@@ -1,6 +1,6 @@
 contrib_plugins = ['bbv', 'cache', 'cflow', 'drcov', 'execlog', 'hotblocks',
                    'hotpages', 'howvec', 'hwprofile', 'ips', 'stoptrigger',
-                   'traps', 'uftrace']
+                   'systrace', 'traps', 'uftrace']
 if host_os != 'windows'
   # lockstep uses socket.h
   contrib_plugins += 'lockstep'
Signature · 1 line
2.47.3
Reviewed-by on v1 11/12
#15 lore raw

Re: [RFC PATCH 11/12] contrib/plugins: add systrace plugin for tracking exceptions and irqs

Quoted 13 lines · Alex Bennée

I'm hunting for lost IRQs and want to trace what various registers are being set to when IRQs happen. This combines the discontinuity tracking API with register value tracking to do so.

It supports:

tracksw - to keep track of the last thing that wrote to a register show_frompc - show the line executing before the discontinuity

As we might not have disassembly for the nominal last pc for an async IRQ we also track the pc of the last executed instruction in a block and use that as a fallback.

Quoted 6 lines
---
  contrib/plugins/systrace.c  | 572 ++++++++++++++++++++++++++++++++++++
  contrib/plugins/meson.build |   2 +-
  2 files changed, 573 insertions(+), 1 deletion(-)

create mode 100644 contrib/plugins/systrace.c

#16 lore raw

RFC PATCH 12/12 target/arm: allow gdb to read ARM_CP_NORAW regs (!upstream)

In reply to Alex Bennée

Before this we suppress all ARM_CP_NORAW registers being listed under GDB. This includes useful registers like CurrentEL which gets tagged as ARM_CP_NO_RAW because it is one of the ARM_CP_SPECIAL_MASK registers. These are registers TCG can directly compute because we have the information at compile time but until now with no readfn.

Add a .readfn to return the CurrentEL and then loosen the restrictions in arm_register_sysreg_for_feature to allow ARM_CP_NORAW registers to be read if there is a readfn available.

Message-ID: <[email protected]>

---
vRFC
- this is a useful debugging aid but a bit haphazard for up-streaming. See thread comments for details.

---
 target/arm/gdbstub.c |  6 +++++-
 target/arm/helper.c  | 15 ++++++++++++++-
 2 files changed, 19 insertions(+), 2 deletions(-)
target/arm/gdbstub.c +5 -1
index 8865f27089d..205bab811da 100644
@@ -292,7 +292,11 @@ static void arm_register_sysreg_for_feature(gpointer key, gpointer value,
     CPUARMState *env = &cpu->env;
     DynamicGDBFeatureInfo *dyn_feature = &cpu->dyn_sysreg_feature;
 
-    if (!(ri->type & (ARM_CP_NO_RAW | ARM_CP_NO_GDB))) {
+    if (!(ri->type & ARM_CP_NO_GDB)) {
+        /* skip ARM_CP_NO_RAW if there are no helper functions */
+        if ((ri->type & ARM_CP_NO_RAW) && !ri->readfn) {
+            return;
+        }
         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
             if (ri->state == ARM_CP_STATE_AA64) {
                 arm_gen_one_feature_sysreg(&param->builder, dyn_feature,
target/arm/helper.c +14 -1
index 27ebc6f29b8..1fbc45263d5 100644
@@ -3529,6 +3529,17 @@ static void ic_ivau_write(CPUARMState *env, const ARMCPRegInfo *ri,
 }
 #endif
 
+/*
+ * Normally the current_el is known at translation time and we can
+ * emit the result directly in TCG code. However this helper exists
+ * only so we can also expose CURRENTEL to gdb.
+ */
+static uint64_t aa64_currentel_read(CPUARMState *env, const ARMCPRegInfo *ri)
+{
+    int el = arm_current_el(env);
+    return el;
+}
+
 static const ARMCPRegInfo v8_cp_reginfo[] = {
     /*
      * Minimal set of EL0-visible registers. This will need to be expanded
@@ -3567,7 +3578,9 @@ static const ARMCPRegInfo v8_cp_reginfo[] = {
     },
     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
-      .access = PL1_R, .type = ARM_CP_CURRENTEL },
+      .access = PL1_R, .type = ARM_CP_CURRENTEL,
+      .readfn = aa64_currentel_read
+    },
     /*
      * Instruction cache ops. All of these except `IC IVAU` NOP because we
      * don't emulate caches.
Signature · 1 line
2.47.3
Reviewed-by on v1 12/12
#17 lore raw

Re: [RFC PATCH 12/12] target/arm: allow gdb to read ARM_CP_NORAW regs (!upstream)

Quoted 13 lines · Alex Bennée

Before this we suppress all ARM_CP_NORAW registers being listed under GDB. This includes useful registers like CurrentEL which gets tagged as ARM_CP_NO_RAW because it is one of the ARM_CP_SPECIAL_MASK registers. These are registers TCG can directly compute because we have the information at compile time but until now with no readfn.

Add a .readfn to return the CurrentEL and then loosen the restrictions in arm_register_sysreg_for_feature to allow ARM_CP_NORAW registers to be read if there is a readfn available.

Message-ID: <[email protected]>

Quoted 8 lines

---
vRFC
- this is a useful debugging aid but a bit haphazard for up-streaming. See thread comments for details.

---
  target/arm/gdbstub.c |  6 +++++-
  target/arm/helper.c  | 15 ++++++++++++++-
  2 files changed, 19 insertions(+), 2 deletions(-)