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