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