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