xref: /kvmtool/builtin-debug.c (revision b7d2f0130b0f8c99a273d2e28186c1d0f15268ff)
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 const char *instance_name;
18 
19 struct debug_cmd {
20 	u32 type;
21 	u32 len;
22 };
23 
24 static const char * const debug_usage[] = {
25 	"kvm debug [--all] [-n name]",
26 	NULL
27 };
28 
29 static const struct option debug_options[] = {
30 	OPT_GROUP("General options:"),
31 	OPT_BOOLEAN('a', "all", &all, "Debug all instances"),
32 	OPT_STRING('n', "name", &instance_name, "name", "Instance name"),
33 	OPT_END()
34 };
35 
36 static void parse_debug_options(int argc, const char **argv)
37 {
38 	while (argc != 0) {
39 		argc = parse_options(argc, argv, debug_options, debug_usage,
40 				PARSE_OPT_STOP_AT_NON_OPTION);
41 		if (argc != 0)
42 			kvm_debug_help();
43 	}
44 }
45 
46 void kvm_debug_help(void)
47 {
48 	usage_with_options(debug_usage, debug_options);
49 }
50 
51 static int do_debug(const char *name, int sock)
52 {
53 	char buff[BUFFER_SIZE];
54 	struct debug_cmd cmd = {KVM_IPC_DEBUG, 0};
55 	int r;
56 
57 	r = xwrite(sock, &cmd, sizeof(cmd));
58 	if (r < 0)
59 		return r;
60 
61 	do {
62 		r = xread(sock, buff, BUFFER_SIZE);
63 		if (r < 0)
64 			return 0;
65 		printf("%.*s", r, buff);
66 	} while (r > 0);
67 
68 	return 0;
69 }
70 
71 int kvm_cmd_debug(int argc, const char **argv, const char *prefix)
72 {
73 	parse_debug_options(argc, argv);
74 
75 	if (all)
76 		return kvm__enumerate_instances(do_debug);
77 
78 	if (instance_name == NULL &&
79 	    instance == 0)
80 		kvm_debug_help();
81 
82 	if (instance_name)
83 		instance = kvm__get_sock_by_instance(instance_name);
84 
85 	if (instance <= 0)
86 		die("Failed locating instance");
87 
88 	return do_debug(instance_name, instance);
89 }
90