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