xref: /kvmtool/kvm-cmd.c (revision 16b2bb87b9c0191fcac3bff58acca88ec2a033fc)
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 
5 #include <assert.h>
6 
7 /* user defined header files */
8 #include "kvm/kvm-debug.h"
9 #include "kvm/kvm-pause.h"
10 #include "kvm/kvm-balloon.h"
11 #include "kvm/kvm-list.h"
12 #include "kvm/kvm-version.h"
13 #include "kvm/kvm-help.h"
14 #include "kvm/kvm-cmd.h"
15 #include "kvm/kvm-run.h"
16 
17 struct cmd_struct kvm_commands[] = {
18 	{ "pause",	kvm_cmd_pause,		NULL,         0 },
19 	{ "debug",	kvm_cmd_debug,		NULL,         0 },
20 	{ "balloon",	kvm_cmd_balloon,	NULL,         0 },
21 	{ "list",	kvm_cmd_list,		NULL,         0 },
22 	{ "version",	kvm_cmd_version,	NULL,         0 },
23 	{ "help",	kvm_cmd_help,		NULL,         0 },
24 	{ "run",	kvm_cmd_run,		kvm_run_help, 0 },
25 	{ NULL,		NULL,			NULL,         0 },
26 };
27 
28 /*
29  * kvm_get_command: Searches the command in an array of the commands and
30  * returns a pointer to cmd_struct if a match is found.
31  *
32  * Input parameters:
33  * command: Array of possible commands. The last entry in the array must be
34  *          NULL.
35  * cmd: A string command to search in the array
36  *
37  * Return Value:
38  * NULL: If the cmd is not matched with any of the command in the command array
39  * p: Pointer to cmd_struct of the matching command
40  */
41 struct cmd_struct *kvm_get_command(struct cmd_struct *command,
42 		const char *cmd)
43 {
44 	struct cmd_struct *p = command;
45 
46 	while (p->cmd) {
47 		if (!strcmp(p->cmd, cmd))
48 			return p;
49 		p++;
50 	}
51 	return NULL;
52 }
53 
54 int handle_command(struct cmd_struct *command, int argc, const char **argv)
55 {
56 	struct cmd_struct *p;
57 	const char *prefix = NULL;
58 
59 	if (!argv || !*argv) {
60 		p = kvm_get_command(command, "help");
61 		assert(p);
62 		return p->fn(argc, argv, prefix);
63 	}
64 
65 	p = kvm_get_command(command, argv[0]);
66 	if (!p) {
67 		p = kvm_get_command(command, "help");
68 		assert(p);
69 		p->fn(0, NULL, prefix);
70 		return EINVAL;
71 	}
72 
73 	return p->fn(argc - 1, &argv[1], prefix);
74 }
75