xref: /kvmtool/builtin-debug.c (revision 4b1c6f6e947ba8c35c0dc49346916817e943786f)
1 #include <kvm/util.h>
2 #include <kvm/kvm-cmd.h>
3 #include <kvm/builtin-debug.h>
4 #include <kvm/kvm.h>
5 #include <kvm/parse-options.h>
6 #include <kvm/kvm-ipc.h>
7 #include <kvm/read-write.h>
8 
9 #include <stdio.h>
10 #include <string.h>
11 #include <signal.h>
12 
13 #define BUFFER_SIZE 100
14 
15 static bool all;
16 static int instance;
17 static int nmi = -1;
18 static bool dump;
19 static const char *instance_name;
20 
21 static const char * const debug_usage[] = {
22 	"kvm debug [--all] [-n name]",
23 	NULL
24 };
25 
26 static const struct option debug_options[] = {
27 	OPT_GROUP("General options:"),
28 	OPT_BOOLEAN('a', "all", &all, "Debug all instances"),
29 	OPT_STRING('n', "name", &instance_name, "name", "Instance name"),
30 	OPT_BOOLEAN('d', "dump", &dump, "Generate a debug dump from guest"),
31 	OPT_INTEGER('m', "nmi", &nmi, "Generate NMI on VCPU"),
32 	OPT_END()
33 };
34 
35 static void parse_debug_options(int argc, const char **argv)
36 {
37 	while (argc != 0) {
38 		argc = parse_options(argc, argv, debug_options, debug_usage,
39 				PARSE_OPT_STOP_AT_NON_OPTION);
40 		if (argc != 0)
41 			kvm_debug_help();
42 	}
43 }
44 
45 void kvm_debug_help(void)
46 {
47 	usage_with_options(debug_usage, debug_options);
48 }
49 
50 static int do_debug(const char *name, int sock)
51 {
52 	char buff[BUFFER_SIZE];
53 	struct debug_cmd cmd = {KVM_IPC_DEBUG, 2 * sizeof(u32)};
54 	int r;
55 
56 	if (dump)
57 		cmd.dbg_type |= KVM_DEBUG_CMD_TYPE_DUMP;
58 
59 	if (nmi != -1) {
60 		cmd.dbg_type |= KVM_DEBUG_CMD_TYPE_NMI;
61 		cmd.cpu = nmi;
62 	}
63 
64 	r = xwrite(sock, &cmd, sizeof(cmd));
65 	if (r < 0)
66 		return r;
67 
68 	if (!dump)
69 		return 0;
70 
71 	do {
72 		r = xread(sock, buff, BUFFER_SIZE);
73 		if (r < 0)
74 			return 0;
75 		printf("%.*s", r, buff);
76 	} while (r > 0);
77 
78 	return 0;
79 }
80 
81 int kvm_cmd_debug(int argc, const char **argv, const char *prefix)
82 {
83 	parse_debug_options(argc, argv);
84 
85 	if (all)
86 		return kvm__enumerate_instances(do_debug);
87 
88 	if (instance_name == NULL &&
89 	    instance == 0)
90 		kvm_debug_help();
91 
92 	if (instance_name)
93 		instance = kvm__get_sock_by_instance(instance_name);
94 
95 	if (instance <= 0)
96 		die("Failed locating instance");
97 
98 	return do_debug(instance_name, instance);
99 }
100