Skip to contentSkip to conversation

testing/next: functional testing updates for gdb

PATCH Superseded Alex Bennée 3 participants 28 messages Sep 30 – Oct 2 Arm/Amlogic Meson SoC support

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

cover testing/next: functional testing updates for gdb

Hi,

This is the current state of my testing/next tree. There a are a few minor tweaks and fixes that I've picked up. The majority of the new code adds testing for the gdb stub when used via KVM. There are two approaches.

The first is an attempt to work just with the default bios code. It's a little limited and I'm not super happy with the "special" heuristics due to the fragility but it does work without symbols.

As a result I spoke to Anders who handles the tuxrun images and he was able to turn on debugging symbols and provide a vmlinux alongside the bootable image. With these updates I was able to resurrect the old test script I was running by hand and then plumb it into a functional test.

So far I've only done x86_64 but if people are happy with the result I'll do the remaining KVM hosts and test the ones where I can (do we have a riscv kvm host anywhere?).

The reason I went on the side-quest is because when working on cleaning up QEMU's internal KVM api I realised that quite a large chunk of it is not exercised by our functional tests. This would ensure that at least:

kvm_arch_update_guest_debug
kvm_arch_get_registers
kvm_arch_set_registers

is exercised and I'm less likely to break things in my r-factor ;-)

Alex.

Alex Bennée (12):
tests/functional: test_acpi_bits requires TCG tests/functional: add migration diagnostics and pace nvme activity

    (HACK!)

meson: move gdb detection into the top level build file tests/functional: add basic gdbstub test for KVM tests/functional: allow tuxrun tests to be passed "accel" tests/functional: split x86_64 tuxrun into tcg and kvm run tests/functional: split aarch64 tuxrun into tcg and kvm run tests/functional: update x86_64 tuxrun images tests/guest-debug: add --kargs option to run-test tests/guest-debug: add --symbols option to run-test tests/functional: teach tuxrun about launching gdb tests tests/functional: add tuxrun kvm gdb test for x86_64

Max Filippov (1):
tests/tcg: fix buffer overflow in multiarch/linux/linux-sigrtminmax

 meson.build                                   |  15 +-
 tests/tcg/multiarch/linux/linux-sigrtminmax.c |   2 +-
 tests/functional/aarch64/test_tuxrun.py       |  10 ++
 .../functional/gdb-scripts/kernel_gdb_test.py | 157 ++++++++++++++++++
 .../functional/gdb-scripts/kvm_fw_gdb_test.py | 119 +++++++++++++
 tests/functional/meson.build                  |   5 +-
 tests/functional/migration.py                 |  37 ++++-
 tests/functional/qemu_test/tuxruntest.py      |  99 +++++++++--
 tests/functional/x86_64/meson.build           |   1 +
 tests/functional/x86_64/test_acpi_bits.py     |   2 +
 tests/functional/x86_64/test_kvm_gdbstub.py   |  55 ++++++
 .../functional/x86_64/test_nvme_migration.py  |   1 +
 tests/functional/x86_64/test_tuxrun.py        |  45 ++++-
 tests/guest-debug/run-test.py                 |  10 ++
 tests/tcg/meson.build                         |   5 -
 15 files changed, 523 insertions(+), 40 deletions(-)
 create mode 100644 tests/functional/gdb-scripts/kernel_gdb_test.py
 create mode 100644 tests/functional/gdb-scripts/kvm_fw_gdb_test.py
 create mode 100755 tests/functional/x86_64/test_kvm_gdbstub.py
Signature · 1 line
2.47.3
#1 lore raw

PATCH 1/13 tests/functional: test_acpi_bits requires TCG

Running a full thorough test suite on a KVM-only build fails due to acpi bits needing icount, therefor tcg. Declare the restriction so the test harness can skip it.

---
 tests/functional/x86_64/test_acpi_bits.py | 2 ++
 1 file changed, 2 insertions(+)
tests/functional/x86_64/test_acpi_bits.py +2 -0
index ec716d643bf..62c57d23f6c 100755
@@ -303,6 +303,8 @@ def test_acpi_smbios_bits(self):
         """The main test case implementation."""
 
         self.set_machine('pc')
+        self.require_accelerator('tcg')
+
         iso_file = self.scratch_file('bits-%d.iso' % self.BITS_INTERNAL_VER)
 
         self.assertTrue(os.access(iso_file, os.R_OK))
Signature · 1 line
2.47.3
Reviewed-by on v1 1/13
#2 lore raw

Re: [PATCH 01/13] tests/functional: test_acpi_bits requires TCG

Quoted 3 lines · Alex Bennée

Running a full thorough test suite on a KVM-only build fails due to acpi bits needing icount, therefor tcg. Declare the restriction so the test harness can skip it.

Signature · 1 line
Marc-André Lureau <[email protected]>
#3 lore raw

PATCH 2/13 tests/functional: add migration diagnostics and pace nvme activity (HACK!)

In reply to Alex Bennée

This is a hacky patch for comment but I've included the diagnostic hacks to the migration test as well as my workaround to get itworking.

This test was failing on my KVM system. On investigation I found the nVME activity meant the migration never completed. I ended up inserting some sleeps into the workload script until I was able to get it to run.

*NOTE*: obviously this can't be merged as is but I think we could certainly do with more tracking in the test to see when things aren't working with possibly the sleep as another patch.

---
 tests/functional/migration.py                 | 37 +++++++++++++++----
 .../functional/x86_64/test_nvme_migration.py  |  1 +
 2 files changed, 31 insertions(+), 7 deletions(-)
tests/functional/migration.py +30 -7
index 8d2428efc24..e51a82c22f4 100644
@@ -22,18 +22,41 @@ class MigrationTest(QemuSystemTest):
     timeout = 10
 
     @staticmethod
-    def migration_finished(vm):
-        return vm.cmd('query-migrate')['status'] in ('completed', 'failed')
+    def migration_finished(query):
+        return query['status'] in ('completed', 'failed')
 
-    def assert_migration(self, src_vm, dst_vm):
+    def wait_for_vm(self, src_or_dst, vm):
+        "Track the state of one VM in the migration"
+        current_state = last_state = vm.cmd('query-migrate')
 
-        end = time.monotonic() + self.timeout
-        while time.monotonic() < end and not self.migration_finished(src_vm):
-            time.sleep(0.1)
+        self.log.info(f"waiting for {src_or_dst} to complete")
 
         end = time.monotonic() + self.timeout
-        while time.monotonic() < end and not self.migration_finished(dst_vm):
+        while time.monotonic() < end:
+            if self.migration_finished(current_state):
+                break
+            else:
+                last_remain = last_state['remaining']
+                current_remain = current_state['remaining']
+
+                if current_remain > last_remain:
+                    self.log.warning(f"slow migration {current_remain} > {last_remain}")
+
             time.sleep(0.1)
+            last_state = current_state
+            current_state = vm.cmd('query-migrate')
+
+
+    def assert_migration(self, src_vm, dst_vm):
+
+        self.wait_for_vm("src", src_vm)
+
+        # if we hit this we never completed...
+        self.assertEqual(src_vm.cmd('query-migrate')['status'], 'completed')
+
+        self.wait_for_vm("dst", dst_vm)
+
+        self.log.info("checking everything is OK")
 
         self.assertEqual(src_vm.cmd('query-migrate')['status'], 'completed')
         self.assertEqual(dst_vm.cmd('query-migrate')['status'], 'completed')
tests/functional/x86_64/test_nvme_migration.py +1 -0
index 890f0aab6d6..58596f63cd3 100755
@@ -109,6 +109,7 @@ def launch_source_vm(self, vm):
                 rm -f /tmp/test_nvme_mig_workload.iter_finished; \
                 echo 3 > /proc/sys/vm/drop_caches; \
                 find /usr/bin -type f -exec cksum {} \\;; \
+                sleep 0.3; \
                 touch /tmp/test_nvme_mig_workload.iter_finished; \
             done) > /dev/null 2> /tmp/test_nvme_mig_workload.errors &",
             prompt, vm=vm)
Signature · 1 line
2.47.3
#4 lore raw

PATCH 3/13 tests/tcg: fix buffer overflow in multiarch/linux/linux-sigrtminmax

In reply to Alex Bennée

From: Max Filippov <[email protected]>

Fix new_argv allocation size to be (argc + 2) * sizeof(char *) bytes, which matches the way it's used to store argc + 2 pointers.

This fixes the test for me, which otherwise fails on xtensa with the following message

linux-sigrtminmax.c: 59: main: Assertion `execve(new_argv[0], new_argv, environ) == 0' failed.'.

Message-ID: <[email protected]>

---
 tests/tcg/multiarch/linux/linux-sigrtminmax.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tests/tcg/multiarch/linux/linux-sigrtminmax.c +1 -1
index a7059aacd9c..b5ea65f3d39 100644
@@ -39,7 +39,7 @@ int main(int argc, char **argv)
     assert(qemu);
 
     if (!getenv("QEMU_RTSIG_MAP")) {
-        char **new_argv = malloc((argc + 2) + sizeof(char *));
+        char **new_argv = malloc((argc + 2) * sizeof(char *));
         int tsig1, hsig1, count1, tsig2, hsig2, count2;
         char rt_sigmap[64];
 
Signature · 1 line
2.47.3
Reviewed-by on v1 3/13
#5 lore raw

Re: [PATCH 03/13] tests/tcg: fix buffer overflow in multiarch/linux/linux-sigrtminmax

Quoted 9 lines · Alex Bennée

Fix new_argv allocation size to be (argc + 2) * sizeof(char *) bytes, which matches the way it's used to store argc + 2 pointers.

This fixes the test for me, which otherwise fails on xtensa with the following message

linux-sigrtminmax.c: 59: main: Assertion `execve(new_argv[0], new_argv, environ) == 0' failed.'.

[...]

Signature · 1 line
Marc-André Lureau <[email protected]>
#6 lore raw

PATCH 4/13 meson: move gdb detection into the top level build file

In reply to Alex Bennée

Currently gdb is only used by TCG based tests but hypervisors want to use gdbstub too. To be able to test this case we need to always probe and report the gdb we have.

---
 meson.build                  | 15 +++++++--------
 tests/functional/meson.build |  5 ++---
 tests/tcg/meson.build        |  5 -----
 3 files changed, 9 insertions(+), 16 deletions(-)
meson.build +7 -8
index cae1591cd28..ea97047362c 100644
@@ -163,6 +163,12 @@ else
   iasl = find_program(get_option('iasl'), required: true)
 endif
 
+if get_option('gdb') == ''
+  gdb = find_program(['gdb-multiarch', 'gdb'], required: false)
+else
+  gdb = find_program(get_option('gdb'), required: true)
+endif
+
 edk2_targets = [ 'arm-softmmu', 'aarch64-softmmu', 'i386-softmmu', 'x86_64-softmmu', 'riscv64-softmmu', 'loongarch64-softmmu' ]
 unpack_edk2_blobs = false
 foreach target : edk2_targets
@@ -4707,14 +4713,7 @@ summary(summary_info, bool_yn: true, section: 'Directories')
 summary_info = {}
 summary_info += {'python':            '@0@ (version: @1@)'.format(python.full_path(), python.language_version())}
 summary_info += {'sphinx-build':      sphinx_build}
-
-# FIXME: the [binaries] section of machine files, which can be probed
-# with find_program(), would be great for passing gdb and genisoimage
-# paths from configure to Meson.  However, there seems to be no way to
-# hide a program (for example if gdb is too old).
-if config_host.has_key('GDB')
-  summary_info += {'gdb':             config_host['GDB']}
-endif
+summary_info += {'gdb':               gdb}
 summary_info += {'iasl':              iasl}
 summary_info += {'genisoimage':       config_host['GENISOIMAGE']}
 if host_os == 'windows' and have_ga
tests/functional/meson.build +2 -3
index c7362dd00ef..68c601d4036 100644
@@ -83,9 +83,8 @@ foreach speed : ['quick', 'thorough']
                      separator : ':')
 
     # Define the GDB environment variable if gdb is available.
-    gdb = get_option('gdb')
-    if gdb != ''
-      test_env.set('QEMU_TEST_GDB', gdb)
+    if gdb.found()
+      test_env.set('QEMU_TEST_GDB', gdb.full_path())
     endif
 
     foreach test : target_tests
tests/tcg/meson.build +0 -5
index 96d5d1249f2..5861ff5ed25 100644
@@ -1,11 +1,6 @@
 env = find_program('env')
 
 docker_wrapper = find_program('../docker/docker.py')
-if get_option('gdb') != ''
-  gdb = find_program(get_option('gdb'), required: true)
-else
-  gdb = find_program(['gdb-multiarch', 'gdb'], required: false)
-endif
 prog_check_plugin_output = find_program('./scripts/check_plugin_output.sh')
 prog_gdb_test = find_program('../guest-debug/run-test.py')
 prog_record_replay = find_program('./scripts/record_replay.sh')
Signature · 1 line
2.47.3
Reviewed-by on v1 4/13
#7 lore raw

Re: [PATCH 04/13] meson: move gdb detection into the top level build file

Quoted 11 lines · Alex Bennée

Currently gdb is only used by TCG based tests but hypervisors want to use gdbstub too. To be able to test this case we need to always probe and report the gdb we have.

---
  meson.build                  | 15 +++++++--------
  tests/functional/meson.build |  5 ++---
  tests/tcg/meson.build        |  5 -----
  3 files changed, 9 insertions(+), 16 deletions(-)
#9 lore raw

PATCH 5/13 tests/functional: add basic gdbstub test for KVM

In reply to Alex Bennée

We don't really exercise the KVM bits of gdbstub very much as the TCG tests are TCG only and the ones in functional tests are focused on record/replay and reverse debugging.

Add a basic gdbstub test case which uses heuristics to single step through the default firmware of guests and kick the tyres and check things are working as expected.

---
vAJB:
- rewrote to use gdb run-test.py framework
- simplified subprocess code

---
 .../functional/gdb-scripts/kvm_fw_gdb_test.py | 119 ++++++++++++++++++
 tests/functional/x86_64/meson.build           |   1 +
 tests/functional/x86_64/test_kvm_gdbstub.py   |  55 ++++++++
 3 files changed, 175 insertions(+)
 create mode 100644 tests/functional/gdb-scripts/kvm_fw_gdb_test.py
 create mode 100755 tests/functional/x86_64/test_kvm_gdbstub.py
tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +119 -0
new file mode 100644
index 00000000000..b38b874dc58
@@ -0,0 +1,119 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Generic GDB script to verify gdbstub functionality on guest firmware:
+#  - Single-stepping across VM-exits
+#  - Placing a hardware breakpoint at a branch or ahead in disassembly
+#  - Continuing to the breakpoint and validating that registers changed
+#
+# Copyright (c) 2026 Linaro Limited
+#
+# Author:
+#  Alex Bennée <[email protected]>
+
+import gdb
+from test_gdbstub import main, report
+
+def parse_registers():
+    """Parse 'info registers' into a name -> value dictionary."""
+    regs = {}
+    for line in gdb.execute("info registers", to_string=True).splitlines():
+        parts = line.split()
+        if len(parts) >= 2:
+            regs[parts[0]] = parts[1]
+    return regs
+
+def test_single_step():
+    """
+    Single-step a few instructions and verify PC advances
+    """
+    current_pc = int(gdb.parse_and_eval("$pc"))
+    for step in range(1, 6):
+        gdb.execute("stepi")
+        gdb.execute("x/3i $pc")
+        pc = int(gdb.parse_and_eval("$pc"))
+        report(pc != current_pc, f"single-step {step} advanced pc")
+        current_pc = pc
+
+
+def might_be_jump(asm):
+    """
+    Return true if the assembly string might contain a branch/jump instruction
+    """
+    branch_keywords = {
+        "jmp", "b", "bl", "bx", "bne", "beq", "bgt", "blt", "bge", "ble",
+        "call", "ret", "br", "jal", "jalr", "bc", "bctrl", "j"
+    }
+
+    parts = asm.split()
+    if not parts:
+        return False
+    mnemonic = parts[0].lower()
+    return mnemonic in branch_keywords
+
+
+def test_hw_bkpt():
+    """
+    Set a hwbkpt somewhere in the future.
+    """
+
+    # FIXME - this is fragile
+    disas = gdb.execute("x/10i $pc", to_string=True)
+    lines = disas.strip().splitlines()
+    insns = 0
+    bp = None
+
+    for line in lines:
+        clean = line.lstrip("=>").strip()
+        parts = clean.split(":", 1)
+        if len(parts) < 2 or not parts[1].strip():
+            continue
+        insns += 1
+
+        if might_be_jump(parts[1]):
+            # jump too close, bail out?
+            if insns < 2:
+                report(False, "found jump far enough away")
+                return
+            else:
+                addr = int(parts[0].split()[0], 16)
+                bp = gdb.Breakpoint(f"*{hex(addr)}",
+                                    type=gdb.BP_HARDWARE_BREAKPOINT)
+                break
+        elif insns == 10:
+            addr = int(parts[0].split()[0], 16)
+            bp = gdb.Breakpoint(f"*{hex(addr)}",
+                                type=gdb.BP_HARDWARE_BREAKPOINT)
+            break
+
+    report(bp is not None, f"set hwbkpt @ {bp.location}")
+    gdb.execute("continue")
+
+    end_pc = gdb.parse_and_eval('$pc')
+    report(bp.hit_count == 1,
+           "break @ %s (%d hits)" % (end_pc, bp.hit_count))
+
+    bp.delete()
+    return
+
+def test_reg_updates(regs_start):
+    regs_end = parse_registers()
+
+    changed = [k for k in regs_start
+               if k in regs_end and regs_start[k] != regs_end[k]]
+
+    report(len(changed) > 0, f"{len(changed)} registers changed.")
+
+def run_test():
+    regs_start = parse_registers()
+
+    test_single_step()
+
+    # skip any pesky mode switching code
+    gdb.execute("stepi 50")
+
+    test_hw_bkpt()
+
+    test_reg_updates(regs_start)
+
+
+main(run_test)
tests/functional/x86_64/meson.build +1 -0
index 0353b2af8e1..080e12ddef1 100644
@@ -13,6 +13,7 @@ tests_x86_64_system_quick = [
   'bad_vmstate',
   'cpu_model_versions',
   'cpu_queries',
+  'kvm_gdbstub',
   'mem_addr_space',
   'migration',
   'pc_cpu_hotplug_props',
tests/functional/x86_64/test_kvm_gdbstub.py new file +55 -0

55 lines not on this page · raw message

Signature · 1 line
2.47.3
Reviewed-by on v1 5/13
#10 lore raw

Re: [PATCH 05/13] tests/functional: add basic gdbstub test for KVM

Quoted 53 lines

We don't really exercise the KVM bits of gdbstub very much as the TCG tests are TCG only and the ones in functional tests are focused on record/replay and reverse debugging.

Add a basic gdbstub test case which uses heuristics to single step through the default firmware of guests and kick the tyres and check things are working as expected.

Message-ID: <[email protected]>

tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +35 -0
new file mode 100644
index 000000000000..b38b874dc586
@@ -0,0 +1,119 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Generic GDB script to verify gdbstub functionality on guest firmware:
+#  - Single-stepping across VM-exits
+#  - Placing a hardware breakpoint at a branch or ahead in disassembly
+#  - Continuing to the breakpoint and validating that registers changed
+#
+# Copyright (c) 2026 Linaro Limited
+#
+# Author:
+#  Alex Bennée <[email protected]>
+
+import gdb
+from test_gdbstub import main, report
+
+def parse_registers():
+    """Parse 'info registers' into a name -> value dictionary."""
+    regs = {}
+    for line in gdb.execute("info registers", to_string=True).splitlines():
+        parts = line.split()
+        if len(parts) >= 2:
+            regs[parts[0]] = parts[1]
+    return regs
+
+def test_single_step():
+    """
+    Single-step a few instructions and verify PC advances
+    """
+    current_pc = int(gdb.parse_and_eval("$pc"))
+    for step in range(1, 6):
+        gdb.execute("stepi")
+        gdb.execute("x/3i $pc")
+        pc = int(gdb.parse_and_eval("$pc"))
+        report(pc != current_pc, f"single-step {step} advanced pc")
+        current_pc = pc

tests/functional/gdb-scripts/kvm_fw_gdb_test.py line 45

Quoted 10 lines
tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +10 -0
+
+
+def might_be_jump(asm):
+    """
+    Return true if the assembly string might contain a branch/jump instruction
+    """
+    branch_keywords = {
+        "jmp", "b", "bl", "bx", "bne", "beq", "bgt", "blt", "bge", "ble",
+        "call", "ret", "br", "jal", "jalr", "bc", "bctrl", "j"
+    }

Do you plan to make this per-architecture? It doesn't cover x86 conditional jumps.

Quoted 33 lines
tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +33 -0
+
+    parts = asm.split()
+    if not parts:
+        return False
+    mnemonic = parts[0].lower()
+    return mnemonic in branch_keywords
+
+
+def test_hw_bkpt():
+    """
+    Set a hwbkpt somewhere in the future.
+    """
+
+    # FIXME - this is fragile
+    disas = gdb.execute("x/10i $pc", to_string=True)
+    lines = disas.strip().splitlines()
+    insns = 0
+    bp = None
+
+    for line in lines:
+        clean = line.lstrip("=>").strip()
+        parts = clean.split(":", 1)
+        if len(parts) < 2 or not parts[1].strip():
+            continue
+        insns += 1
+
+        if might_be_jump(parts[1]):
+            # jump too close, bail out?
+            if insns < 2:
+                report(False, "found jump far enough away")
+                return
+            else:
+                addr = int(parts[0].split()[0], 16)

tests/functional/gdb-scripts/kvm_fw_gdb_test.py line 88

Quoted 10 lines
tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +10 -0
+                bp = gdb.Breakpoint(f"*{hex(addr)}",
+                                    type=gdb.BP_HARDWARE_BREAKPOINT)
+                break
+        elif insns == 10:
+            addr = int(parts[0].split()[0], 16)
+            bp = gdb.Breakpoint(f"*{hex(addr)}",
+                                type=gdb.BP_HARDWARE_BREAKPOINT)
+            break
+
+    report(bp is not None, f"set hwbkpt @ {bp.location}")

Maybe to make debugging easier:

if bp is None:
report(False, "failed to set hwbkpt (no suitable instruction found)") return
report(True, f"set hwbkpt @ {bp.location}")

Quoted 94 lines
tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +31 -0
+    gdb.execute("continue")
+
+    end_pc = gdb.parse_and_eval('$pc')
+    report(bp.hit_count == 1,
+           "break @ %s (%d hits)" % (end_pc, bp.hit_count))
+
+    bp.delete()
+    return
+
+def test_reg_updates(regs_start):
+    regs_end = parse_registers()
+
+    changed = [k for k in regs_start
+               if k in regs_end and regs_start[k] != regs_end[k]]
+
+    report(len(changed) > 0, f"{len(changed)} registers changed.")
+
+def run_test():
+    regs_start = parse_registers()
+
+    test_single_step()
+
+    # skip any pesky mode switching code
+    gdb.execute("stepi 50")
+
+    test_hw_bkpt()
+
+    test_reg_updates(regs_start)
+
+
+main(run_test)
tests/functional/x86_64/meson.build +1 -0
index 0353b2af8e1d..080e12ddef13 100644
@@ -13,6 +13,7 @@ tests_x86_64_system_quick = [
   'bad_vmstate',
   'cpu_model_versions',
   'cpu_queries',
+  'kvm_gdbstub',
   'mem_addr_space',
   'migration',
   'pc_cpu_hotplug_props',
tests/functional/x86_64/test_kvm_gdbstub.py new file +45 -0
new file mode 100755
index 000000000000..26876c3dc580
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+#
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Functional test verifying KVM gdbstub operations on firmware:
+#  - Single-stepping across VM-exits
+#  - Register sampling across execution steps
+#  - Hardware breakpoint at branch destination or instruction
+#
+# Copyright (c) 2026 Linaro Limited
+#
+# Author:
+#  Alex Bennée <[email protected]>
+
+import os
+import subprocess
+from pathlib import Path
+from qemu_test import QemuSystemTest, skipIfMissingEnv
+
+
+class KvmGdbstubTest(QemuSystemTest):
+
+    @skipIfMissingEnv("QEMU_TEST_GDB")
+    def test_x86_64_kvm_fw_gdb(self):
+        self.require_accelerator("kvm")
+
+        gdb_path = os.getenv("QEMU_TEST_GDB")
+
+        tests_dir = Path(__file__).resolve().parents[2]
+        run_test = tests_dir / "guest-debug" / "run-test.py"
+        gdb_script = (tests_dir / "functional" / "gdb-scripts" /
+                      "kvm_fw_gdb_test.py")
+
+        qargs = "-machine pc -accel kvm -cpu host -smp 1 -m 512M -display none"
+        cmd = [
+            str(run_test),
+            "--qemu", self.qemu_bin,
+            "--qargs", qargs,
+            "--binary", "",
+            "--test", str(gdb_script),
+            "--gdb", gdb_path,
+        ]
+
+        res = subprocess.run(cmd, text=True,
+                             stdout=subprocess.PIPE,

tests/functional/x86_64/test_kvm_gdbstub.py line 55

Quoted 10 lines
tests/functional/x86_64/test_kvm_gdbstub.py new file +10 -0
+                             stderr=subprocess.STDOUT)
+        if res.stdout:
+            self.log.info('run-test.py: %s', res.stdout)
+
+        self.assertEqual(res.returncode, 0,
+                         f"run-test.py failed ({res.returncode}):\n")
+
+
+if __name__ == '__main__':
+    QemuSystemTest.main()
Signature · 1 line
Marc-André Lureau <[email protected]>
#11 lore raw

Re: [PATCH 05/13] tests/functional: add basic gdbstub test for KVM

Quoted 59 lines · [email protected] writes:
Quoted 59 lines

We don't really exercise the KVM bits of gdbstub very much as the TCG tests are TCG only and the ones in functional tests are focused on record/replay and reverse debugging.

Add a basic gdbstub test case which uses heuristics to single step through the default firmware of guests and kick the tyres and check things are working as expected.

Message-ID: <[email protected]>

tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +41 -0
new file mode 100644
index 000000000000..b38b874dc586
@@ -0,0 +1,119 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Generic GDB script to verify gdbstub functionality on guest firmware:
+#  - Single-stepping across VM-exits
+#  - Placing a hardware breakpoint at a branch or ahead in disassembly
+#  - Continuing to the breakpoint and validating that registers changed
+#
+# Copyright (c) 2026 Linaro Limited
+#
+# Author:
+#  Alex Bennée <[email protected]>
+
+import gdb
+from test_gdbstub import main, report
+
+def parse_registers():
+    """Parse 'info registers' into a name -> value dictionary."""
+    regs = {}
+    for line in gdb.execute("info registers", to_string=True).splitlines():
+        parts = line.split()
+        if len(parts) >= 2:
+            regs[parts[0]] = parts[1]
+    return regs
+
+def test_single_step():
+    """
+    Single-step a few instructions and verify PC advances
+    """
+    current_pc = int(gdb.parse_and_eval("$pc"))
+    for step in range(1, 6):
+        gdb.execute("stepi")
+        gdb.execute("x/3i $pc")
+        pc = int(gdb.parse_and_eval("$pc"))
+        report(pc != current_pc, f"single-step {step} advanced pc")
+        current_pc = pc
+
+
+def might_be_jump(asm):
+    """
+    Return true if the assembly string might contain a branch/jump instruction
+    """
Quoted 8 lines

tests/functional/gdb-scripts/kvm_fw_gdb_test.py line 45

Quoted 4 lines
tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +4 -0
+    branch_keywords = {
+        "jmp", "b", "bl", "bx", "bne", "beq", "bgt", "blt", "bge", "ble",
+        "call", "ret", "br", "jal", "jalr", "bc", "bctrl", "j"
+    }

Do you plan to make this per-architecture? It doesn't cover x86 conditional jumps.

I think I'm just going to wrap the register checking code into the other test and drop this one as the heuristics are potentially flaky. It was really just a workaround to not having symbols easily accessible (which I have now).

Quoted 158 lines
Quoted 34 lines
tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +33 -0
+
+    parts = asm.split()
+    if not parts:
+        return False
+    mnemonic = parts[0].lower()
+    return mnemonic in branch_keywords
+
+
+def test_hw_bkpt():
+    """
+    Set a hwbkpt somewhere in the future.
+    """
+
+    # FIXME - this is fragile
+    disas = gdb.execute("x/10i $pc", to_string=True)
+    lines = disas.strip().splitlines()
+    insns = 0
+    bp = None
+
+    for line in lines:
+        clean = line.lstrip("=>").strip()
+        parts = clean.split(":", 1)
+        if len(parts) < 2 or not parts[1].strip():
+            continue
+        insns += 1
+
+        if might_be_jump(parts[1]):
+            # jump too close, bail out?
+            if insns < 2:
+                report(False, "found jump far enough away")
+                return
+            else:
+                addr = int(parts[0].split()[0], 16)

tests/functional/gdb-scripts/kvm_fw_gdb_test.py line 88

Quoted 10 lines
tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +10 -0
+                bp = gdb.Breakpoint(f"*{hex(addr)}",
+                                    type=gdb.BP_HARDWARE_BREAKPOINT)
+                break
+        elif insns == 10:
+            addr = int(parts[0].split()[0], 16)
+            bp = gdb.Breakpoint(f"*{hex(addr)}",
+                                type=gdb.BP_HARDWARE_BREAKPOINT)
+            break
+
+    report(bp is not None, f"set hwbkpt @ {bp.location}")

Maybe to make debugging easier:

if bp is None:
report(False, "failed to set hwbkpt (no suitable instruction found)") return
report(True, f"set hwbkpt @ {bp.location}")

Quoted 94 lines
tests/functional/gdb-scripts/kvm_fw_gdb_test.py new file +31 -0
+    gdb.execute("continue")
+
+    end_pc = gdb.parse_and_eval('$pc')
+    report(bp.hit_count == 1,
+           "break @ %s (%d hits)" % (end_pc, bp.hit_count))
+
+    bp.delete()
+    return
+
+def test_reg_updates(regs_start):
+    regs_end = parse_registers()
+
+    changed = [k for k in regs_start
+               if k in regs_end and regs_start[k] != regs_end[k]]
+
+    report(len(changed) > 0, f"{len(changed)} registers changed.")
+
+def run_test():
+    regs_start = parse_registers()
+
+    test_single_step()
+
+    # skip any pesky mode switching code
+    gdb.execute("stepi 50")
+
+    test_hw_bkpt()
+
+    test_reg_updates(regs_start)
+
+
+main(run_test)
tests/functional/x86_64/meson.build +1 -0
index 0353b2af8e1d..080e12ddef13 100644
@@ -13,6 +13,7 @@ tests_x86_64_system_quick = [
   'bad_vmstate',
   'cpu_model_versions',
   'cpu_queries',
+  'kvm_gdbstub',
   'mem_addr_space',
   'migration',
   'pc_cpu_hotplug_props',
tests/functional/x86_64/test_kvm_gdbstub.py new file +45 -0
new file mode 100755
index 000000000000..26876c3dc580
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+#
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Functional test verifying KVM gdbstub operations on firmware:
+#  - Single-stepping across VM-exits
+#  - Register sampling across execution steps
+#  - Hardware breakpoint at branch destination or instruction
+#
+# Copyright (c) 2026 Linaro Limited
+#
+# Author:
+#  Alex Bennée <[email protected]>
+
+import os
+import subprocess
+from pathlib import Path
+from qemu_test import QemuSystemTest, skipIfMissingEnv
+
+
+class KvmGdbstubTest(QemuSystemTest):
+
+    @skipIfMissingEnv("QEMU_TEST_GDB")
+    def test_x86_64_kvm_fw_gdb(self):
+        self.require_accelerator("kvm")
+
+        gdb_path = os.getenv("QEMU_TEST_GDB")
+
+        tests_dir = Path(__file__).resolve().parents[2]
+        run_test = tests_dir / "guest-debug" / "run-test.py"
+        gdb_script = (tests_dir / "functional" / "gdb-scripts" /
+                      "kvm_fw_gdb_test.py")
+
+        qargs = "-machine pc -accel kvm -cpu host -smp 1 -m 512M -display none"
+        cmd = [
+            str(run_test),
+            "--qemu", self.qemu_bin,
+            "--qargs", qargs,
+            "--binary", "",
+            "--test", str(gdb_script),
+            "--gdb", gdb_path,
+        ]
+
+        res = subprocess.run(cmd, text=True,
+                             stdout=subprocess.PIPE,

tests/functional/x86_64/test_kvm_gdbstub.py line 55

Quoted 10 lines
tests/functional/x86_64/test_kvm_gdbstub.py new file +10 -0
+                             stderr=subprocess.STDOUT)
+        if res.stdout:
+            self.log.info('run-test.py: %s', res.stdout)
+
+        self.assertEqual(res.returncode, 0,
+                         f"run-test.py failed ({res.returncode}):\n")
+
+
+if __name__ == '__main__':
+    QemuSystemTest.main()
Signature · 2 lines
Alex Bennée
Virtualisation Tech Lead @ Linaro
#12 lore raw

PATCH 6/13 tests/functional: allow tuxrun tests to be passed "accel"

In reply to Alex Bennée

For some tests we are about to add we want the flexibility to force "kvm" so give them that ability.

---
 tests/functional/qemu_test/tuxruntest.py | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
tests/functional/qemu_test/tuxruntest.py +7 -2
index 6c442ff0dc4..ca1589fea37 100644
@@ -65,7 +65,7 @@ def fetch_tuxrun_assets(self, kernel_asset, rootfs_asset, dtb_asset=None):
 
         return (kernel_image, disk_image, dtb)
 
-    def prepare_run(self, kernel, disk, drive, dtb=None, console_index=0):
+    def prepare_run(self, accel, kernel, disk, drive, dtb=None, console_index=0):
         """
         Setup to run and add the common parameters to the system
         """
@@ -79,6 +79,10 @@ def prepare_run(self, kernel, disk, drive, dtb=None, console_index=0):
         self.kcmd_line += f" root=/dev/{self.root}"
         self.kcmd_line += f" console={self.console}"
 
+        # have we specified an accelerator?
+        if accel:
+            self.vm.add_args('-accel', accel)
+
         self.vm.add_args('-kernel', kernel,
                          '-append', self.kcmd_line,
                          '-blockdev', blockdev)
@@ -118,6 +122,7 @@ def run_tuxtest_tests(self, haltmsg):
     def common_tuxrun(self,
                       kernel_asset,
                       rootfs_asset,
+                      accel=None,
                       dtb_asset=None,
                       drive="virtio-blk-device",
                       haltmsg="reboot: System halted",
@@ -130,7 +135,7 @@ def common_tuxrun(self,
         (kernel, disk, dtb) = self.fetch_tuxrun_assets(kernel_asset, rootfs_asset,
                                                        dtb_asset)
 
-        self.prepare_run(kernel, disk, drive, dtb, console_index)
+        self.prepare_run(accel, kernel, disk, drive, dtb, console_index)
         self.vm.launch()
         self.run_tuxtest_tests(haltmsg)
         os.remove(disk)
Signature · 1 line
2.47.3
#13 lore raw

Re: [PATCH 06/13] tests/functional: allow tuxrun tests to be passed "accel"

Quoted 11 lines

For some tests we are about to add we want the flexibility to force "kvm" so give them that ability.

Message-ID: <[email protected]>

tests/functional/qemu_test/tuxruntest.py +0 -0
index 6c442ff0dc43..ca1589fea37d 100644

tests/functional/qemu_test/tuxruntest.py def fetch_tuxrun_assets(self, kernel_asset, rootfs_asset, dtb_asset=None): · line 68

Quoted 5 lines
tests/functional/qemu_test/tuxruntest.py +1 -1
@@ -65,7 +65,7 @@ def fetch_tuxrun_assets(self, kernel_asset, rootfs_asset, dtb_asset=None):
 
         return (kernel_image, disk_image, dtb)
 
-    def prepare_run(self, kernel, disk, drive, dtb=None, console_index=0):
+    def prepare_run(self, accel, kernel, disk, drive, dtb=None, console_index=0):

This breaks the direct caller in tests/functional/sh4/test_tuxrun.py which passes kernel as the first positional argument.

Signature · 1 line
Marc-André Lureau <[email protected]>
#14 lore raw

PATCH 7/13 tests/functional: split x86_64 tuxrun into tcg and kvm run

In reply to Alex Bennée

Add an explicit "kvm" run to the tuxrun tests. Although running on an x86_64 host would probably have defaulted to "kvm" anyway we want to exercise specific features later.

---
 tests/functional/x86_64/test_tuxrun.py | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)
tests/functional/x86_64/test_tuxrun.py +16 -1
index fcbc62b1b0f..729f6447d05 100755
@@ -24,13 +24,28 @@ class TuxRunX86Test(TuxRunBaselineTest):
         '4b8b2a99117519c5290e1202cb36eb6c7aaba92b357b5160f5970cf5fb78a751')
 
     def test_x86_64(self):
+        self.require_accelerator("tcg")
+
+        self.set_machine('q35')
+        self.cpu="Nehalem"
+        self.root='sda'
+        self.wait_for_shutdown=False
+        self.common_tuxrun(kernel_asset=self.ASSET_X86_64_KERNEL,
+                           rootfs_asset=self.ASSET_X86_64_ROOTFS,
+                           drive="driver=ide-hd,bus=ide.0,unit=0",
+                           accel="tcg")
+
+    def test_x86_64_kvm(self):
+        self.require_accelerator("kvm")
+
         self.set_machine('q35')
         self.cpu="Nehalem"
         self.root='sda'
         self.wait_for_shutdown=False
         self.common_tuxrun(kernel_asset=self.ASSET_X86_64_KERNEL,
                            rootfs_asset=self.ASSET_X86_64_ROOTFS,
-                           drive="driver=ide-hd,bus=ide.0,unit=0")
+                           drive="driver=ide-hd,bus=ide.0,unit=0",
+                           accel="kvm")
 
 if __name__ == '__main__':
     TuxRunBaselineTest.main()
Signature · 1 line
2.47.3
Reviewed-by on v1 7/13
#15 lore raw

Re: [PATCH 07/13] tests/functional: split x86_64 tuxrun into tcg and kvm run

Quoted 3 lines · Alex Bennée

Add an explicit "kvm" run to the tuxrun tests. Although running on an x86_64 host would probably have defaulted to "kvm" anyway we want to exercise specific features later.

Signature · 1 line
Marc-André Lureau <[email protected]>
#16 lore raw

PATCH 8/13 tests/functional: split aarch64 tuxrun into tcg and kvm run

In reply to Alex Bennée

Add an explicit "kvm" run to the tuxrun tests. Although running on an aarch64 host would probably have defaulted to "kvm" anyway we want to exercise specific features later.

---
 tests/functional/aarch64/test_tuxrun.py | 10 ++++++++++
 1 file changed, 10 insertions(+)
tests/functional/aarch64/test_tuxrun.py +10 -0
index 7dd50c3de17..3870be8b6e3 100755
@@ -32,6 +32,16 @@ def test_arm64(self):
         self.common_tuxrun(kernel_asset=self.ASSET_ARM64_KERNEL,
                            rootfs_asset=self.ASSET_ARM64_ROOTFS)
 
+    def test_arm64_kvm(self):
+        self.set_machine('virt')
+        self.require_accelerator('kvm')
+        self.cpu='cortex-a57'
+        self.console='ttyAMA0'
+        self.wait_for_shutdown=False
+        self.common_tuxrun(kernel_asset=self.ASSET_ARM64_KERNEL,
+                           rootfs_asset=self.ASSET_ARM64_ROOTFS,
+                           accel="kvm")
+
     ASSET_ARM64BE_KERNEL = Asset(
         'https://storage.tuxboot.com/buildroot/20241119/arm64be/Image',
         'fd6af4f16689d17a2c24fe0053cc212edcdf77abdcaf301800b8d38fa9f6e109')
Signature · 1 line
2.47.3
Reviewed-by on v1 8/13
#17 lore raw

Re: [PATCH 08/13] tests/functional: split aarch64 tuxrun into tcg and kvm run

Quoted 3 lines · Alex Bennée

Add an explicit "kvm" run to the tuxrun tests. Although running on an aarch64 host would probably have defaulted to "kvm" anyway we want to exercise specific features later.

Signature · 1 line
Marc-André Lureau <[email protected]>
#18 lore raw

PATCH 9/13 tests/functional: update x86_64 tuxrun images

In reply to Alex Bennée

We now split the fetching of the buildroot image from the kernel itself. This is because we will want to access additional metadata in future tests.

---
 tests/functional/x86_64/test_tuxrun.py | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
tests/functional/x86_64/test_tuxrun.py +4 -4
index 729f6447d05..026b373accb 100755
@@ -17,11 +17,11 @@
 class TuxRunX86Test(TuxRunBaselineTest):
 
     ASSET_X86_64_KERNEL = Asset(
-        'https://storage.tuxboot.com/buildroot/20241119/x86_64/bzImage',
-        'f57bfc6553bcd6e0a54aab86095bf642b33b5571d14e3af1731b18c87ed5aef8')
+        'https://storage.tuxboot.com/kernels/6.18.54/x86_64/bzImage',
+        '24a3ade610c2cc426ff821050de8a35930b0371357d94cc2c334abac6658552b')
     ASSET_X86_64_ROOTFS = Asset(
-        'https://storage.tuxboot.com/buildroot/20241119/x86_64/rootfs.ext4.zst',
-        '4b8b2a99117519c5290e1202cb36eb6c7aaba92b357b5160f5970cf5fb78a751')
+        'https://storage.tuxboot.com/buildroot/20260924/x86_64/rootfs.ext4.zst',
+        '8e310455b0244414ccff29c507f7ccfd4032e3587cc405e49ab0322738e3e27c')
 
     def test_x86_64(self):
         self.require_accelerator("tcg")
Signature · 1 line
2.47.3
Reviewed-by on v1 9/13
#19 lore raw

Re: [PATCH 09/13] tests/functional: update x86_64 tuxrun images

Quoted 3 lines · Alex Bennée

We now split the fetching of the buildroot image from the kernel itself. This is because we will want to access additional metadata in future tests.

Signature · 1 line
Marc-André Lureau <[email protected]>
#20 lore raw

PATCH 10/13 tests/guest-debug: add --kargs option to run-test

In reply to Alex Bennée

When passing kernel arguments to QEMU with --append we need to take care that things are properly escaped. It's easier if we get the run script to do it for us that constructed the nested escaped --qargs.

---
 tests/guest-debug/run-test.py | 5 +++++
 1 file changed, 5 insertions(+)
tests/guest-debug/run-test.py +5 -0
index 838c1c26971..4aa24939b7d 100755
@@ -25,6 +25,7 @@ def get_args():
                         required=True)
     parser.add_argument("--qargs", help="Qemu arguments for test")
     parser.add_argument("--pargs", help="Program arguments for test")
+    parser.add_argument("--kargs", help="Kernel args to --append")
     parser.add_argument("--binary", help="Binary to debug",
                         required=True)
     parser.add_argument("--test", help="GDB test script")
@@ -82,6 +83,8 @@ def log(output, msg):
             suspend = ' -S'
         cmd = f'{args.qemu} {args.qargs} {args.binary}' \
             f'{suspend} -gdb unix:path={socket_name},server=on'
+        if args.kargs:
+            cmd += f" --append '{args.kargs}'"
         # There is no guest program command-line in system mode.
         assert not args.pargs
     else:
@@ -93,6 +96,8 @@ def log(output, msg):
             f' {args.binary}'
         if args.pargs:
             cmd += f' {args.pargs}'
+        # There are no appended args in user-mode
+        assert not args.kargs
 
     log(output, "QEMU CMD: %s" % (cmd))
     inferior = subprocess.Popen(shlex.split(cmd))
Signature · 1 line
2.47.3
Reviewed-by on v1 10/13
#21 lore raw

Re: [PATCH 10/13] tests/guest-debug: add --kargs option to run-test

Quoted 3 lines · Alex Bennée

When passing kernel arguments to QEMU with --append we need to take care that things are properly escaped. It's easier if we get the run script to do it for us that constructed the nested escaped --qargs.

Signature · 1 line
Marc-André Lureau <[email protected]>
#22 lore raw

PATCH 11/13 tests/guest-debug: add --symbols option to run-test

In reply to Alex Bennée

Sometimes the debug symbols are not in the kernel binary image but in a separate elf blob. Provide --symbols to facilitate using them.

---
 tests/guest-debug/run-test.py | 5 +++++
 1 file changed, 5 insertions(+)
tests/guest-debug/run-test.py +5 -0
index 4aa24939b7d..0c7cbd137ef 100755
@@ -28,6 +28,7 @@ def get_args():
     parser.add_argument("--kargs", help="Kernel args to --append")
     parser.add_argument("--binary", help="Binary to debug",
                         required=True)
+    parser.add_argument("--symbols", help="Symbol file for binary to debug")
     parser.add_argument("--test", help="GDB test script")
     parser.add_argument('test_args', nargs='*',
                         help="Additional args for GDB test script. "
@@ -114,6 +115,10 @@ def log(output, msg):
     gdb_cmd += " -ex 'set confirm off'"
     # connect to remote
     gdb_cmd += " -ex 'target remote %s'" % (socket_name)
+
+    if args.symbols:
+        gdb_cmd += " -ex 'symbol-file %s'" % args.symbols
+
     # finally the test script itself
     if args.test:
         if args.test_args:
Signature · 1 line
2.47.3
#24 lore raw

PATCH 12/13 tests/functional: teach tuxrun about launching gdb tests

In reply to Alex Bennée

This resurrects the hand run test script from d84842be6c5 (tests:
remove test-gdbstub.py) and modernises it to use the shared test infrastructure for run-test.

We then tweak the common tuxrun code to over an alternative "launch via gdbstub" helper which reuses the existing code but:

- needs a vmlinux with symbols
- passes kargs directly
- runs with the gdb run-test script
- log the run-test output to the console log

---
 .../functional/gdb-scripts/kernel_gdb_test.py | 157 ++++++++++++++++++
 tests/functional/qemu_test/tuxruntest.py      |  92 +++++++++-
 2 files changed, 240 insertions(+), 9 deletions(-)
 create mode 100644 tests/functional/gdb-scripts/kernel_gdb_test.py
tests/functional/gdb-scripts/kernel_gdb_test.py new file +157 -0
new file mode 100644
index 00000000000..5ca9aa43de3
@@ -0,0 +1,157 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Generic Kernel GDB script to verify functionality:
+#  - Single-stepping
+#  - Hardware breakpoints
+#  - Software breakpoints
+#  - Watchpoints
+#
+# It relies on fairly common kernel points to break at and symbols for
+# the kernel. Address space randomisation (kaslr) needs to be disabled.
+#
+# Copyright (c) 2026 Linaro Limited
+#
+# Author:
+#  Alex Bennée <[email protected]>
+#
+# This is launched by the tuxrun functional tests via tests/guest-debug/run-test.py
+
+import gdb
+from test_gdbstub import main, report
+
+failcount = 0
+
+
+def check_step():
+    "Step an instruction, check it moved."
+    start_pc = gdb.parse_and_eval('$pc')
+    gdb.execute("si")
+    end_pc = gdb.parse_and_eval('$pc')
+
+    return not (start_pc == end_pc)
+
+
+def check_break(sym_name):
+    "Setup breakpoint, continue and check we stopped."
+    sym, ok = gdb.lookup_symbol(sym_name)
+    bp = gdb.Breakpoint(sym_name)
+
+    gdb.execute("c")
+
+    # hopefully we came back
+    end_pc = gdb.parse_and_eval('$pc')
+    print ("%s == %s %d" % (end_pc, sym.value(), bp.hit_count))
+    bp.delete()
+
+    # can we test we hit bp?
+    return end_pc == sym.value()
+
+
+# We need to do hbreak manually as the python interface doesn't export it
+def check_hbreak(sym_name):
+    "Setup hardware breakpoint, continue and check we stopped."
+    sym, ok = gdb.lookup_symbol(sym_name)
+    gdb.execute("hbreak %s" % (sym_name))
+    gdb.execute("c")
+
+    # hopefully we came back
+    end_pc = gdb.parse_and_eval('$pc')
+    print ("%s == %s" % (end_pc, sym.value()))
+
+    if end_pc == sym.value():
+        gdb.execute("d 1")
+        return True
+    else:
+        return False
+
+
+class WatchPoint(gdb.Breakpoint):
+
+    def get_wpstr(self, sym_name):
+        "Setup sym and wp_str for given symbol."
+        self.sym, ok = gdb.lookup_symbol(sym_name)
+        wp_addr = gdb.parse_and_eval(sym_name).address
+        self.wp_str = '*(%(type)s)(&%(address)s)' % dict(
+            type = wp_addr.type, address = sym_name)
+
+        return(self.wp_str)
+
+    def __init__(self, sym_name, type):
+        wp_str = self.get_wpstr(sym_name)
+        super(WatchPoint, self).__init__(wp_str, gdb.BP_WATCHPOINT, type)
+
+    def stop(self):
+        end_pc = gdb.parse_and_eval('$pc')
+        print ("HIT WP @ %s" % (end_pc))
+        return True
+
+
+def do_one_watch(sym, wtype, text):
+
+    wp = WatchPoint(sym, wtype)
+    gdb.execute("c")
+    report_str = "%s for %s (%s)" % (text, sym, wp.sym.value())
+
+    if wp.hit_count > 0:
+        report(True, report_str)
+        wp.delete()
+    else:
+        report(False, report_str)
+
+
+def check_watches(sym_name):
+    "Watch a symbol for any access."
+
+    # Should hit for any read
+    do_one_watch(sym_name, gdb.WP_ACCESS, "awatch")
+
+    # Again should hit for reads
+    do_one_watch(sym_name, gdb.WP_READ, "rwatch")
+
+    # Finally when it is written
+    do_one_watch(sym_name, gdb.WP_WRITE, "watch")
+
+
+class CatchBreakpoint(gdb.Breakpoint):
+    def __init__(self, sym_name):
+        super(CatchBreakpoint, self).__init__(sym_name)
+        self.sym, ok = gdb.lookup_symbol(sym_name)
+
+    def stop(self):
+        end_pc = gdb.parse_and_eval('$pc')
+        print ("CB: %s == %s" % (end_pc, self.sym.value()))
+        if end_pc == self.sym.value():
+            report(False, "Hit final catchpoint")
+
+
+def run_test():
+    "Run through the tests one by one"
+
+    print ("Checking we can step the first few instructions")
+    step_ok = 0
+    for i in range(3):
+        if check_step():
+            step_ok += 1
+
+    report(step_ok == 3, "single step in boot code")
+
+    print ("Checking HW breakpoint works")
+    break_ok = check_hbreak("kernel_init")
+    report(break_ok, "hbreak @ kernel_init")
+
+    # Can't set this up until we are in the kernel proper
+    # if we make it to run_init_process we've over-run and
+    # one of the tests failed
+    print ("Setup catch-all for run_init_process")
+    cbp = CatchBreakpoint("run_init_process")
+    cpb2 = CatchBreakpoint("try_to_run_init_process")
+
+    print ("Checking Normal breakpoint works")
+    break_ok = check_break("wait_for_completion")
+    report(break_ok, "break @ wait_for_completion")
+
+    print ("Checking watchpoint works")
+    check_watches("system_state")
+
+
+main(run_test)
tests/functional/qemu_test/tuxruntest.py +83 -9

133 lines not on this page · raw message

Signature · 1 line
2.47.3
#25 lore raw

Re: [PATCH 12/13] tests/functional: teach tuxrun about launching gdb tests

Quoted 73 lines

This resurrects the hand run test script from d84842be6c5 (tests:
remove test-gdbstub.py) and modernises it to use the shared test infrastructure for run-test.

We then tweak the common tuxrun code to over an alternative "launch via gdbstub" helper which reuses the existing code but:

- needs a vmlinux with symbols
- passes kargs directly
- runs with the gdb run-test script
- log the run-test output to the console log

Message-ID: <[email protected]>

tests/functional/gdb-scripts/kernel_gdb_test.py new file +52 -0
new file mode 100644
index 000000000000..5ca9aa43de3c
@@ -0,0 +1,157 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Generic Kernel GDB script to verify functionality:
+#  - Single-stepping
+#  - Hardware breakpoints
+#  - Software breakpoints
+#  - Watchpoints
+#
+# It relies on fairly common kernel points to break at and symbols for
+# the kernel. Address space randomisation (kaslr) needs to be disabled.
+#
+# Copyright (c) 2026 Linaro Limited
+#
+# Author:
+#  Alex Bennée <[email protected]>
+#
+# This is launched by the tuxrun functional tests via tests/guest-debug/run-test.py
+
+import gdb
+from test_gdbstub import main, report
+
+failcount = 0
+
+
+def check_step():
+    "Step an instruction, check it moved."
+    start_pc = gdb.parse_and_eval('$pc')
+    gdb.execute("si")
+    end_pc = gdb.parse_and_eval('$pc')
+
+    return not (start_pc == end_pc)
+
+
+def check_break(sym_name):
+    "Setup breakpoint, continue and check we stopped."
+    sym, ok = gdb.lookup_symbol(sym_name)
+    bp = gdb.Breakpoint(sym_name)
+
+    gdb.execute("c")
+
+    # hopefully we came back
+    end_pc = gdb.parse_and_eval('$pc')
+    print ("%s == %s %d" % (end_pc, sym.value(), bp.hit_count))
+    bp.delete()
+
+    # can we test we hit bp?
+    return end_pc == sym.value()
+
+
+# We need to do hbreak manually as the python interface doesn't export it
+def check_hbreak(sym_name):
+    "Setup hardware breakpoint, continue and check we stopped."

tests/functional/gdb-scripts/kernel_gdb_test.py line 62

Quoted 10 lines
tests/functional/gdb-scripts/kernel_gdb_test.py new file +10 -0
+    sym, ok = gdb.lookup_symbol(sym_name)
+    gdb.execute("hbreak %s" % (sym_name))
+    gdb.execute("c")
+
+    # hopefully we came back
+    end_pc = gdb.parse_and_eval('$pc')
+    print ("%s == %s" % (end_pc, sym.value()))
+
+    if end_pc == sym.value():
+        gdb.execute("d 1")

It may be worth to use gdb.Breakpoint() which gives a proper object with .delete() instead.

Quoted 75 lines
tests/functional/gdb-scripts/kernel_gdb_test.py new file +75 -0
+        return True
+    else:
+        return False
+
+
+class WatchPoint(gdb.Breakpoint):
+
+    def get_wpstr(self, sym_name):
+        "Setup sym and wp_str for given symbol."
+        self.sym, ok = gdb.lookup_symbol(sym_name)
+        wp_addr = gdb.parse_and_eval(sym_name).address
+        self.wp_str = '*(%(type)s)(&%(address)s)' % dict(
+            type = wp_addr.type, address = sym_name)
+
+        return(self.wp_str)
+
+    def __init__(self, sym_name, type):
+        wp_str = self.get_wpstr(sym_name)
+        super(WatchPoint, self).__init__(wp_str, gdb.BP_WATCHPOINT, type)
+
+    def stop(self):
+        end_pc = gdb.parse_and_eval('$pc')
+        print ("HIT WP @ %s" % (end_pc))
+        return True
+
+
+def do_one_watch(sym, wtype, text):
+
+    wp = WatchPoint(sym, wtype)
+    gdb.execute("c")
+    report_str = "%s for %s (%s)" % (text, sym, wp.sym.value())
+
+    if wp.hit_count > 0:
+        report(True, report_str)
+        wp.delete()
+    else:
+        report(False, report_str)
+
+
+def check_watches(sym_name):
+    "Watch a symbol for any access."
+
+    # Should hit for any read
+    do_one_watch(sym_name, gdb.WP_ACCESS, "awatch")
+
+    # Again should hit for reads
+    do_one_watch(sym_name, gdb.WP_READ, "rwatch")
+
+    # Finally when it is written
+    do_one_watch(sym_name, gdb.WP_WRITE, "watch")
+
+
+class CatchBreakpoint(gdb.Breakpoint):
+    def __init__(self, sym_name):
+        super(CatchBreakpoint, self).__init__(sym_name)
+        self.sym, ok = gdb.lookup_symbol(sym_name)
+
+    def stop(self):
+        end_pc = gdb.parse_and_eval('$pc')
+        print ("CB: %s == %s" % (end_pc, self.sym.value()))
+        if end_pc == self.sym.value():
+            report(False, "Hit final catchpoint")
+
+
+def run_test():
+    "Run through the tests one by one"
+
+    print ("Checking we can step the first few instructions")
+    step_ok = 0
+    for i in range(3):
+        if check_step():
+            step_ok += 1
+
+    report(step_ok == 3, "single step in boot code")
+

tests/functional/gdb-scripts/kernel_gdb_test.py line 147

Quoted 10 lines
tests/functional/gdb-scripts/kernel_gdb_test.py new file +10 -0
+    print ("Checking HW breakpoint works")
+    break_ok = check_hbreak("kernel_init")
+    report(break_ok, "hbreak @ kernel_init")
+
+    # Can't set this up until we are in the kernel proper
+    # if we make it to run_init_process we've over-run and
+    # one of the tests failed
+    print ("Setup catch-all for run_init_process")
+    cbp = CatchBreakpoint("run_init_process")
+    cpb2 = CatchBreakpoint("try_to_run_init_process")

cbp2 ?

Quoted 25 lines
tests/functional/gdb-scripts/kernel_gdb_test.py new file +10 -0
+
+    print ("Checking Normal breakpoint works")
+    break_ok = check_break("wait_for_completion")
+    report(break_ok, "break @ wait_for_completion")
+
+    print ("Checking watchpoint works")
+    check_watches("system_state")
+
+
+main(run_test)
tests/functional/qemu_test/tuxruntest.py +2 -0
index ca1589fea37d..e6b32fbcab26 100644
@@ -9,7 +9,9 @@
 #
 # SPDX-License-Identifier: GPL-2.0-or-later
 
+import logging
 import os
+import subprocess
 
 from qemu_test import QemuSystemTest
 from qemu_test import exec_command_and_wait_for_pattern

tests/functional/qemu_test/tuxruntest.py line 23

Quoted 5 lines
tests/functional/qemu_test/tuxruntest.py +1 -1
@@ -18,7 +20,7 @@
 
 class TuxRunBaselineTest(QemuSystemTest):
 
-    KERNEL_COMMON_COMMAND_LINE = 'printk.time=0'
+    KERNEL_COMMON_COMMAND_LINE = 'printk.time=0 nokaslr'

This affects every tuxrun test, worth to mention in commit message. Or adjust the test to limit the scope

Signature · 1 line
Marc-André Lureau <[email protected]>
#26 lore raw

PATCH 13/13 tests/functional: add tuxrun kvm gdb test for x86_64

In reply to Alex Bennée

With all the bits in place we can now exercise the KVM gdb interfaces.

---
 tests/functional/x86_64/test_tuxrun.py | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
tests/functional/x86_64/test_tuxrun.py +19 -1
index 026b373accb..1a1138d16ae 100755
@@ -11,7 +11,7 @@
 #
 # SPDX-License-Identifier: GPL-2.0-or-later
 
-from qemu_test import Asset
+from qemu_test import Asset, skipIfMissingEnv
 from qemu_test.tuxruntest import TuxRunBaselineTest
 
 class TuxRunX86Test(TuxRunBaselineTest):
@@ -19,6 +19,9 @@ class TuxRunX86Test(TuxRunBaselineTest):
     ASSET_X86_64_KERNEL = Asset(
         'https://storage.tuxboot.com/kernels/6.18.54/x86_64/bzImage',
         '24a3ade610c2cc426ff821050de8a35930b0371357d94cc2c334abac6658552b')
+    ASSET_X86_64_VMLINUX = Asset(
+        'https://storage.tuxboot.com/kernels/6.18.54/x86_64/vmlinux.xz',
+        '77bf44cca48c9c1b9c142e16a2311d58b8ae3462b61bce44bcaf9243b5f26628')
     ASSET_X86_64_ROOTFS = Asset(
         'https://storage.tuxboot.com/buildroot/20260924/x86_64/rootfs.ext4.zst',
         '8e310455b0244414ccff29c507f7ccfd4032e3587cc405e49ab0322738e3e27c')
@@ -47,5 +50,20 @@ def test_x86_64_kvm(self):
                            drive="driver=ide-hd,bus=ide.0,unit=0",
                            accel="kvm")
 
+    @skipIfMissingEnv("QEMU_TEST_GDB")
+    def test_x86_64_kvm_gdb(self):
+        self.require_accelerator("kvm")
+
+        self.set_machine('q35')
+        self.cpu="Nehalem"
+        self.root='sda'
+        self.wait_for_shutdown=False
+        self.common_tuxrun_gdb(kernel_asset=self.ASSET_X86_64_KERNEL,
+                               vmlinux_asset=self.ASSET_X86_64_VMLINUX,
+                               rootfs_asset=self.ASSET_X86_64_ROOTFS,
+                               drive="driver=ide-hd,bus=ide.0,unit=0",
+                               accel="kvm")
+
+
 if __name__ == '__main__':
     TuxRunBaselineTest.main()
Signature · 1 line
2.47.3