1"""Helper functions for gdbstub testing
2
3"""
4from __future__ import print_function
5import argparse
6import gdb
7import os
8import sys
9import traceback
10
11fail_count = 0
12
13
14def gdb_exit(status):
15    gdb.execute(f"exit {status}")
16
17
18class arg_parser(argparse.ArgumentParser):
19    def exit(self, status=None, message=""):
20        print("Wrong GDB script test argument! " + message)
21        gdb_exit(1)
22
23
24def report(cond, msg):
25    """Report success/fail of a test"""
26    if cond:
27        print("PASS: {}".format(msg))
28    else:
29        print("FAIL: {}".format(msg))
30        global fail_count
31        fail_count += 1
32
33
34def main(test, expected_arch=None):
35    """Run a test function
36
37    This runs as the script it sourced (via -x, via run-test.py)."""
38    try:
39        inferior = gdb.selected_inferior()
40        arch = inferior.architecture()
41        print("ATTACHED: {}".format(arch.name()))
42        if expected_arch is not None:
43            report(arch.name() == expected_arch,
44                   "connected to {}".format(expected_arch))
45    except (gdb.error, AttributeError):
46        print("SKIP: not connected")
47        gdb_exit(0)
48
49    if gdb.parse_and_eval("$pc") == 0:
50        print("SKIP: PC not set")
51        gdb_exit(0)
52
53    try:
54        test()
55    except:
56        print("GDB Exception:")
57        traceback.print_exc(file=sys.stdout)
58        global fail_count
59        fail_count += 1
60        if "QEMU_TEST_INTERACTIVE" in os.environ:
61            import code
62            code.InteractiveConsole(locals=globals()).interact()
63        raise
64
65    try:
66        gdb.execute("kill")
67    except gdb.error:
68        pass
69
70    print("All tests complete: {} failures".format(fail_count))
71    gdb_exit(fail_count)
72