1#!/usr/bin/env python3
2
3from signal import SIGINT
4import argparse
5import sys
6import psutil  # type: ignore
7
8
9def find_vscode_process(current_process):
10    parent_process = current_process.parent()
11
12    while parent_process.name() != "node":
13        parent_process = parent_process.parent()
14
15        if parent_process.pid == 1:
16            return None
17
18    return parent_process
19
20
21def find_run_process(vscode_process, run_path):
22    for child_process in vscode_process.children():
23        args = child_process.cmdline()
24        if len(args) < 2:
25            continue
26
27        if args[0] != "/bin/sh":
28            continue
29
30        if args[1] != run_path:
31            continue
32
33        return child_process
34
35    return None
36
37
38def main():
39    parser = argparse.ArgumentParser(description="Kill QEMU from within VSCode")
40    parser.add_argument("run_path", type=str, help="Path to Trusty run script")
41    args = parser.parse_args()
42
43    current_process = psutil.Process()
44
45    vscode_process = find_vscode_process(current_process)
46    if vscode_process is None:
47        print("Could not find vscode's node process", file=sys.stderr)
48        sys.exit(1)
49
50    run_process = find_run_process(vscode_process, args.run_path)
51    if run_process is None:
52        print("Could not find the run process", file=sys.stderr)
53        sys.exit(1)
54
55    try:
56        qemu_py_process = run_process.children()[0]
57    except IndexError:
58        print("Could not find the qemu.py process", file=sys.stderr)
59        sys.exit(1)
60
61    qemu_py_process.send_signal(SIGINT)
62
63
64if __name__ == "__main__":
65    main()
66