xref: /openbmc/qemu/monitor/hmp.c (revision cc1838c2)
1 /*
2  * QEMU monitor
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include <dirent.h>
27 #include "hw/qdev-core.h"
28 #include "monitor-internal.h"
29 #include "qapi/error.h"
30 #include "qapi/qmp/qdict.h"
31 #include "qapi/qmp/qnum.h"
32 #include "qemu/config-file.h"
33 #include "qemu/ctype.h"
34 #include "qemu/cutils.h"
35 #include "qemu/log.h"
36 #include "qemu/option.h"
37 #include "qemu/units.h"
38 #include "sysemu/block-backend.h"
39 #include "sysemu/runstate.h"
40 #include "trace.h"
41 
42 static void monitor_command_cb(void *opaque, const char *cmdline,
43                                void *readline_opaque)
44 {
45     MonitorHMP *mon = opaque;
46 
47     monitor_suspend(&mon->common);
48     handle_hmp_command(mon, cmdline);
49     monitor_resume(&mon->common);
50 }
51 
52 void monitor_read_command(MonitorHMP *mon, int show_prompt)
53 {
54     if (!mon->rs) {
55         return;
56     }
57 
58     readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
59     if (show_prompt) {
60         readline_show_prompt(mon->rs);
61     }
62 }
63 
64 int monitor_read_password(MonitorHMP *mon, ReadLineFunc *readline_func,
65                           void *opaque)
66 {
67     if (mon->rs) {
68         readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
69         /* prompt is printed on return from the command handler */
70         return 0;
71     } else {
72         monitor_printf(&mon->common,
73                        "terminal does not support password prompting\n");
74         return -ENOTTY;
75     }
76 }
77 
78 static int get_str(char *buf, int buf_size, const char **pp)
79 {
80     const char *p;
81     char *q;
82     int c;
83 
84     q = buf;
85     p = *pp;
86     while (qemu_isspace(*p)) {
87         p++;
88     }
89     if (*p == '\0') {
90     fail:
91         *q = '\0';
92         *pp = p;
93         return -1;
94     }
95     if (*p == '\"') {
96         p++;
97         while (*p != '\0' && *p != '\"') {
98             if (*p == '\\') {
99                 p++;
100                 c = *p++;
101                 switch (c) {
102                 case 'n':
103                     c = '\n';
104                     break;
105                 case 'r':
106                     c = '\r';
107                     break;
108                 case '\\':
109                 case '\'':
110                 case '\"':
111                     break;
112                 default:
113                     printf("unsupported escape code: '\\%c'\n", c);
114                     goto fail;
115                 }
116                 if ((q - buf) < buf_size - 1) {
117                     *q++ = c;
118                 }
119             } else {
120                 if ((q - buf) < buf_size - 1) {
121                     *q++ = *p;
122                 }
123                 p++;
124             }
125         }
126         if (*p != '\"') {
127             printf("unterminated string\n");
128             goto fail;
129         }
130         p++;
131     } else {
132         while (*p != '\0' && !qemu_isspace(*p)) {
133             if ((q - buf) < buf_size - 1) {
134                 *q++ = *p;
135             }
136             p++;
137         }
138     }
139     *q = '\0';
140     *pp = p;
141     return 0;
142 }
143 
144 #define MAX_ARGS 16
145 
146 static void free_cmdline_args(char **args, int nb_args)
147 {
148     int i;
149 
150     assert(nb_args <= MAX_ARGS);
151 
152     for (i = 0; i < nb_args; i++) {
153         g_free(args[i]);
154     }
155 
156 }
157 
158 /*
159  * Parse the command line to get valid args.
160  * @cmdline: command line to be parsed.
161  * @pnb_args: location to store the number of args, must NOT be NULL.
162  * @args: location to store the args, which should be freed by caller, must
163  *        NOT be NULL.
164  *
165  * Returns 0 on success, negative on failure.
166  *
167  * NOTE: this parser is an approximate form of the real command parser. Number
168  *       of args have a limit of MAX_ARGS. If cmdline contains more, it will
169  *       return with failure.
170  */
171 static int parse_cmdline(const char *cmdline,
172                          int *pnb_args, char **args)
173 {
174     const char *p;
175     int nb_args, ret;
176     char buf[1024];
177 
178     p = cmdline;
179     nb_args = 0;
180     for (;;) {
181         while (qemu_isspace(*p)) {
182             p++;
183         }
184         if (*p == '\0') {
185             break;
186         }
187         if (nb_args >= MAX_ARGS) {
188             goto fail;
189         }
190         ret = get_str(buf, sizeof(buf), &p);
191         if (ret < 0) {
192             goto fail;
193         }
194         args[nb_args] = g_strdup(buf);
195         nb_args++;
196     }
197     *pnb_args = nb_args;
198     return 0;
199 
200  fail:
201     free_cmdline_args(args, nb_args);
202     return -1;
203 }
204 
205 /*
206  * Can command @cmd be executed in preconfig state?
207  */
208 static bool cmd_can_preconfig(const HMPCommand *cmd)
209 {
210     if (!cmd->flags) {
211         return false;
212     }
213 
214     return strchr(cmd->flags, 'p');
215 }
216 
217 static bool cmd_available(const HMPCommand *cmd)
218 {
219     return phase_check(PHASE_MACHINE_READY) || cmd_can_preconfig(cmd);
220 }
221 
222 static void help_cmd_dump_one(Monitor *mon,
223                               const HMPCommand *cmd,
224                               char **prefix_args,
225                               int prefix_args_nb)
226 {
227     int i;
228 
229     if (!cmd_available(cmd)) {
230         return;
231     }
232 
233     for (i = 0; i < prefix_args_nb; i++) {
234         monitor_printf(mon, "%s ", prefix_args[i]);
235     }
236     monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
237 }
238 
239 /* @args[@arg_index] is the valid command need to find in @cmds */
240 static void help_cmd_dump(Monitor *mon, const HMPCommand *cmds,
241                           char **args, int nb_args, int arg_index)
242 {
243     const HMPCommand *cmd;
244     size_t i;
245 
246     /* No valid arg need to compare with, dump all in *cmds */
247     if (arg_index >= nb_args) {
248         for (cmd = cmds; cmd->name != NULL; cmd++) {
249             help_cmd_dump_one(mon, cmd, args, arg_index);
250         }
251         return;
252     }
253 
254     /* Find one entry to dump */
255     for (cmd = cmds; cmd->name != NULL; cmd++) {
256         if (hmp_compare_cmd(args[arg_index], cmd->name) &&
257             cmd_available(cmd)) {
258             if (cmd->sub_table) {
259                 /* continue with next arg */
260                 help_cmd_dump(mon, cmd->sub_table,
261                               args, nb_args, arg_index + 1);
262             } else {
263                 help_cmd_dump_one(mon, cmd, args, arg_index);
264             }
265             return;
266         }
267     }
268 
269     /* Command not found */
270     monitor_printf(mon, "unknown command: '");
271     for (i = 0; i <= arg_index; i++) {
272         monitor_printf(mon, "%s%s", args[i], i == arg_index ? "'\n" : " ");
273     }
274 }
275 
276 void help_cmd(Monitor *mon, const char *name)
277 {
278     char *args[MAX_ARGS];
279     int nb_args = 0;
280 
281     /* 1. parse user input */
282     if (name) {
283         /* special case for log, directly dump and return */
284         if (!strcmp(name, "log")) {
285             const QEMULogItem *item;
286             monitor_printf(mon, "Log items (comma separated):\n");
287             monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
288             for (item = qemu_log_items; item->mask != 0; item++) {
289                 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
290             }
291             return;
292         }
293 
294         if (parse_cmdline(name, &nb_args, args) < 0) {
295             return;
296         }
297     }
298 
299     /* 2. dump the contents according to parsed args */
300     help_cmd_dump(mon, hmp_cmds, args, nb_args, 0);
301 
302     free_cmdline_args(args, nb_args);
303 }
304 
305 /*******************************************************************/
306 
307 static const char *pch;
308 static sigjmp_buf expr_env;
309 
310 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
311 expr_error(Monitor *mon, const char *fmt, ...)
312 {
313     va_list ap;
314     va_start(ap, fmt);
315     monitor_vprintf(mon, fmt, ap);
316     monitor_printf(mon, "\n");
317     va_end(ap);
318     siglongjmp(expr_env, 1);
319 }
320 
321 static void next(void)
322 {
323     if (*pch != '\0') {
324         pch++;
325         while (qemu_isspace(*pch)) {
326             pch++;
327         }
328     }
329 }
330 
331 static int64_t expr_sum(Monitor *mon);
332 
333 static int64_t expr_unary(Monitor *mon)
334 {
335     int64_t n;
336     char *p;
337     int ret;
338 
339     switch (*pch) {
340     case '+':
341         next();
342         n = expr_unary(mon);
343         break;
344     case '-':
345         next();
346         n = -expr_unary(mon);
347         break;
348     case '~':
349         next();
350         n = ~expr_unary(mon);
351         break;
352     case '(':
353         next();
354         n = expr_sum(mon);
355         if (*pch != ')') {
356             expr_error(mon, "')' expected");
357         }
358         next();
359         break;
360     case '\'':
361         pch++;
362         if (*pch == '\0') {
363             expr_error(mon, "character constant expected");
364         }
365         n = *pch;
366         pch++;
367         if (*pch != '\'') {
368             expr_error(mon, "missing terminating \' character");
369         }
370         next();
371         break;
372     case '$':
373         {
374             char buf[128], *q;
375             int64_t reg = 0;
376 
377             pch++;
378             q = buf;
379             while ((*pch >= 'a' && *pch <= 'z') ||
380                    (*pch >= 'A' && *pch <= 'Z') ||
381                    (*pch >= '0' && *pch <= '9') ||
382                    *pch == '_' || *pch == '.') {
383                 if ((q - buf) < sizeof(buf) - 1) {
384                     *q++ = *pch;
385                 }
386                 pch++;
387             }
388             while (qemu_isspace(*pch)) {
389                 pch++;
390             }
391             *q = 0;
392             ret = get_monitor_def(mon, &reg, buf);
393             if (ret < 0) {
394                 expr_error(mon, "unknown register");
395             }
396             n = reg;
397         }
398         break;
399     case '\0':
400         expr_error(mon, "unexpected end of expression");
401         n = 0;
402         break;
403     default:
404         errno = 0;
405         n = strtoull(pch, &p, 0);
406         if (errno == ERANGE) {
407             expr_error(mon, "number too large");
408         }
409         if (pch == p) {
410             expr_error(mon, "invalid char '%c' in expression", *p);
411         }
412         pch = p;
413         while (qemu_isspace(*pch)) {
414             pch++;
415         }
416         break;
417     }
418     return n;
419 }
420 
421 static int64_t expr_prod(Monitor *mon)
422 {
423     int64_t val, val2;
424     int op;
425 
426     val = expr_unary(mon);
427     for (;;) {
428         op = *pch;
429         if (op != '*' && op != '/' && op != '%') {
430             break;
431         }
432         next();
433         val2 = expr_unary(mon);
434         switch (op) {
435         default:
436         case '*':
437             val *= val2;
438             break;
439         case '/':
440         case '%':
441             if (val2 == 0) {
442                 expr_error(mon, "division by zero");
443             }
444             if (op == '/') {
445                 val /= val2;
446             } else {
447                 val %= val2;
448             }
449             break;
450         }
451     }
452     return val;
453 }
454 
455 static int64_t expr_logic(Monitor *mon)
456 {
457     int64_t val, val2;
458     int op;
459 
460     val = expr_prod(mon);
461     for (;;) {
462         op = *pch;
463         if (op != '&' && op != '|' && op != '^') {
464             break;
465         }
466         next();
467         val2 = expr_prod(mon);
468         switch (op) {
469         default:
470         case '&':
471             val &= val2;
472             break;
473         case '|':
474             val |= val2;
475             break;
476         case '^':
477             val ^= val2;
478             break;
479         }
480     }
481     return val;
482 }
483 
484 static int64_t expr_sum(Monitor *mon)
485 {
486     int64_t val, val2;
487     int op;
488 
489     val = expr_logic(mon);
490     for (;;) {
491         op = *pch;
492         if (op != '+' && op != '-') {
493             break;
494         }
495         next();
496         val2 = expr_logic(mon);
497         if (op == '+') {
498             val += val2;
499         } else {
500             val -= val2;
501         }
502     }
503     return val;
504 }
505 
506 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
507 {
508     pch = *pp;
509     if (sigsetjmp(expr_env, 0)) {
510         *pp = pch;
511         return -1;
512     }
513     while (qemu_isspace(*pch)) {
514         pch++;
515     }
516     *pval = expr_sum(mon);
517     *pp = pch;
518     return 0;
519 }
520 
521 static int get_double(Monitor *mon, double *pval, const char **pp)
522 {
523     const char *p = *pp;
524     char *tailp;
525     double d;
526 
527     d = strtod(p, &tailp);
528     if (tailp == p) {
529         monitor_printf(mon, "Number expected\n");
530         return -1;
531     }
532     if (d != d || d - d != 0) {
533         /* NaN or infinity */
534         monitor_printf(mon, "Bad number\n");
535         return -1;
536     }
537     *pval = d;
538     *pp = tailp;
539     return 0;
540 }
541 
542 /*
543  * Store the command-name in cmdname, and return a pointer to
544  * the remaining of the command string.
545  */
546 static const char *get_command_name(const char *cmdline,
547                                     char *cmdname, size_t nlen)
548 {
549     size_t len;
550     const char *p, *pstart;
551 
552     p = cmdline;
553     while (qemu_isspace(*p)) {
554         p++;
555     }
556     if (*p == '\0') {
557         return NULL;
558     }
559     pstart = p;
560     while (*p != '\0' && *p != '/' && !qemu_isspace(*p)) {
561         p++;
562     }
563     len = p - pstart;
564     if (len > nlen - 1) {
565         len = nlen - 1;
566     }
567     memcpy(cmdname, pstart, len);
568     cmdname[len] = '\0';
569     return p;
570 }
571 
572 /**
573  * Read key of 'type' into 'key' and return the current
574  * 'type' pointer.
575  */
576 static char *key_get_info(const char *type, char **key)
577 {
578     size_t len;
579     char *p, *str;
580 
581     if (*type == ',') {
582         type++;
583     }
584 
585     p = strchr(type, ':');
586     if (!p) {
587         *key = NULL;
588         return NULL;
589     }
590     len = p - type;
591 
592     str = g_malloc(len + 1);
593     memcpy(str, type, len);
594     str[len] = '\0';
595 
596     *key = str;
597     return ++p;
598 }
599 
600 static int default_fmt_format = 'x';
601 static int default_fmt_size = 4;
602 
603 static int is_valid_option(const char *c, const char *typestr)
604 {
605     char option[3];
606 
607     option[0] = '-';
608     option[1] = *c;
609     option[2] = '\0';
610 
611     typestr = strstr(typestr, option);
612     return (typestr != NULL);
613 }
614 
615 static const HMPCommand *search_dispatch_table(const HMPCommand *disp_table,
616                                                const char *cmdname)
617 {
618     const HMPCommand *cmd;
619 
620     for (cmd = disp_table; cmd->name != NULL; cmd++) {
621         if (hmp_compare_cmd(cmdname, cmd->name)) {
622             return cmd;
623         }
624     }
625 
626     return NULL;
627 }
628 
629 /*
630  * Parse command name from @cmdp according to command table @table.
631  * If blank, return NULL.
632  * Else, if no valid command can be found, report to @mon, and return
633  * NULL.
634  * Else, change @cmdp to point right behind the name, and return its
635  * command table entry.
636  * Do not assume the return value points into @table!  It doesn't when
637  * the command is found in a sub-command table.
638  */
639 static const HMPCommand *monitor_parse_command(MonitorHMP *hmp_mon,
640                                                const char *cmdp_start,
641                                                const char **cmdp,
642                                                HMPCommand *table)
643 {
644     Monitor *mon = &hmp_mon->common;
645     const char *p;
646     const HMPCommand *cmd;
647     char cmdname[256];
648 
649     /* extract the command name */
650     p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
651     if (!p) {
652         return NULL;
653     }
654 
655     cmd = search_dispatch_table(table, cmdname);
656     if (!cmd) {
657         monitor_printf(mon, "unknown command: '%.*s'\n",
658                        (int)(p - cmdp_start), cmdp_start);
659         return NULL;
660     }
661     if (!cmd_available(cmd)) {
662         monitor_printf(mon, "Command '%.*s' not available "
663                             "until machine initialization has completed.\n",
664                        (int)(p - cmdp_start), cmdp_start);
665         return NULL;
666     }
667 
668     /* filter out following useless space */
669     while (qemu_isspace(*p)) {
670         p++;
671     }
672 
673     *cmdp = p;
674     /* search sub command */
675     if (cmd->sub_table != NULL && *p != '\0') {
676         return monitor_parse_command(hmp_mon, cmdp_start, cmdp, cmd->sub_table);
677     }
678 
679     return cmd;
680 }
681 
682 /*
683  * Parse arguments for @cmd.
684  * If it can't be parsed, report to @mon, and return NULL.
685  * Else, insert command arguments into a QDict, and return it.
686  * Note: On success, caller has to free the QDict structure.
687  */
688 static QDict *monitor_parse_arguments(Monitor *mon,
689                                       const char **endp,
690                                       const HMPCommand *cmd)
691 {
692     const char *typestr;
693     char *key;
694     int c;
695     const char *p = *endp;
696     char buf[1024];
697     QDict *qdict = qdict_new();
698 
699     /* parse the parameters */
700     typestr = cmd->args_type;
701     for (;;) {
702         typestr = key_get_info(typestr, &key);
703         if (!typestr) {
704             break;
705         }
706         c = *typestr;
707         typestr++;
708         switch (c) {
709         case 'F':
710         case 'B':
711         case 's':
712             {
713                 int ret;
714 
715                 while (qemu_isspace(*p)) {
716                     p++;
717                 }
718                 if (*typestr == '?') {
719                     typestr++;
720                     if (*p == '\0') {
721                         /* no optional string: NULL argument */
722                         break;
723                     }
724                 }
725                 ret = get_str(buf, sizeof(buf), &p);
726                 if (ret < 0) {
727                     switch (c) {
728                     case 'F':
729                         monitor_printf(mon, "%s: filename expected\n",
730                                        cmd->name);
731                         break;
732                     case 'B':
733                         monitor_printf(mon, "%s: block device name expected\n",
734                                        cmd->name);
735                         break;
736                     default:
737                         monitor_printf(mon, "%s: string expected\n", cmd->name);
738                         break;
739                     }
740                     goto fail;
741                 }
742                 qdict_put_str(qdict, key, buf);
743             }
744             break;
745         case 'O':
746             {
747                 QemuOptsList *opts_list;
748                 QemuOpts *opts;
749 
750                 opts_list = qemu_find_opts(key);
751                 if (!opts_list || opts_list->desc->name) {
752                     goto bad_type;
753                 }
754                 while (qemu_isspace(*p)) {
755                     p++;
756                 }
757                 if (!*p) {
758                     break;
759                 }
760                 if (get_str(buf, sizeof(buf), &p) < 0) {
761                     goto fail;
762                 }
763                 opts = qemu_opts_parse_noisily(opts_list, buf, true);
764                 if (!opts) {
765                     goto fail;
766                 }
767                 qemu_opts_to_qdict(opts, qdict);
768                 qemu_opts_del(opts);
769             }
770             break;
771         case '/':
772             {
773                 int count, format, size;
774 
775                 while (qemu_isspace(*p)) {
776                     p++;
777                 }
778                 if (*p == '/') {
779                     /* format found */
780                     p++;
781                     count = 1;
782                     if (qemu_isdigit(*p)) {
783                         count = 0;
784                         while (qemu_isdigit(*p)) {
785                             count = count * 10 + (*p - '0');
786                             p++;
787                         }
788                     }
789                     size = -1;
790                     format = -1;
791                     for (;;) {
792                         switch (*p) {
793                         case 'o':
794                         case 'd':
795                         case 'u':
796                         case 'x':
797                         case 'i':
798                         case 'c':
799                             format = *p++;
800                             break;
801                         case 'b':
802                             size = 1;
803                             p++;
804                             break;
805                         case 'h':
806                             size = 2;
807                             p++;
808                             break;
809                         case 'w':
810                             size = 4;
811                             p++;
812                             break;
813                         case 'g':
814                         case 'L':
815                             size = 8;
816                             p++;
817                             break;
818                         default:
819                             goto next;
820                         }
821                     }
822                 next:
823                     if (*p != '\0' && !qemu_isspace(*p)) {
824                         monitor_printf(mon, "invalid char in format: '%c'\n",
825                                        *p);
826                         goto fail;
827                     }
828                     if (format < 0) {
829                         format = default_fmt_format;
830                     }
831                     if (format != 'i') {
832                         /* for 'i', not specifying a size gives -1 as size */
833                         if (size < 0) {
834                             size = default_fmt_size;
835                         }
836                         default_fmt_size = size;
837                     }
838                     default_fmt_format = format;
839                 } else {
840                     count = 1;
841                     format = default_fmt_format;
842                     if (format != 'i') {
843                         size = default_fmt_size;
844                     } else {
845                         size = -1;
846                     }
847                 }
848                 qdict_put_int(qdict, "count", count);
849                 qdict_put_int(qdict, "format", format);
850                 qdict_put_int(qdict, "size", size);
851             }
852             break;
853         case 'i':
854         case 'l':
855         case 'M':
856             {
857                 int64_t val;
858 
859                 while (qemu_isspace(*p)) {
860                     p++;
861                 }
862                 if (*typestr == '?' || *typestr == '.') {
863                     if (*typestr == '?') {
864                         if (*p == '\0') {
865                             typestr++;
866                             break;
867                         }
868                     } else {
869                         if (*p == '.') {
870                             p++;
871                             while (qemu_isspace(*p)) {
872                                 p++;
873                             }
874                         } else {
875                             typestr++;
876                             break;
877                         }
878                     }
879                     typestr++;
880                 }
881                 if (get_expr(mon, &val, &p)) {
882                     goto fail;
883                 }
884                 /* Check if 'i' is greater than 32-bit */
885                 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
886                     monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
887                     monitor_printf(mon, "integer is for 32-bit values\n");
888                     goto fail;
889                 } else if (c == 'M') {
890                     if (val < 0) {
891                         monitor_printf(mon, "enter a positive value\n");
892                         goto fail;
893                     }
894                     val *= MiB;
895                 }
896                 qdict_put_int(qdict, key, val);
897             }
898             break;
899         case 'o':
900             {
901                 int ret;
902                 uint64_t val;
903                 const char *end;
904 
905                 while (qemu_isspace(*p)) {
906                     p++;
907                 }
908                 if (*typestr == '?') {
909                     typestr++;
910                     if (*p == '\0') {
911                         break;
912                     }
913                 }
914                 ret = qemu_strtosz_MiB(p, &end, &val);
915                 if (ret < 0 || val > INT64_MAX) {
916                     monitor_printf(mon, "invalid size\n");
917                     goto fail;
918                 }
919                 qdict_put_int(qdict, key, val);
920                 p = end;
921             }
922             break;
923         case 'T':
924             {
925                 double val;
926 
927                 while (qemu_isspace(*p)) {
928                     p++;
929                 }
930                 if (*typestr == '?') {
931                     typestr++;
932                     if (*p == '\0') {
933                         break;
934                     }
935                 }
936                 if (get_double(mon, &val, &p) < 0) {
937                     goto fail;
938                 }
939                 if (p[0] && p[1] == 's') {
940                     switch (*p) {
941                     case 'm':
942                         val /= 1e3; p += 2; break;
943                     case 'u':
944                         val /= 1e6; p += 2; break;
945                     case 'n':
946                         val /= 1e9; p += 2; break;
947                     }
948                 }
949                 if (*p && !qemu_isspace(*p)) {
950                     monitor_printf(mon, "Unknown unit suffix\n");
951                     goto fail;
952                 }
953                 qdict_put(qdict, key, qnum_from_double(val));
954             }
955             break;
956         case 'b':
957             {
958                 const char *beg;
959                 bool val;
960 
961                 while (qemu_isspace(*p)) {
962                     p++;
963                 }
964                 beg = p;
965                 while (qemu_isgraph(*p)) {
966                     p++;
967                 }
968                 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
969                     val = true;
970                 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
971                     val = false;
972                 } else {
973                     monitor_printf(mon, "Expected 'on' or 'off'\n");
974                     goto fail;
975                 }
976                 qdict_put_bool(qdict, key, val);
977             }
978             break;
979         case '-':
980             {
981                 const char *tmp = p;
982                 int skip_key = 0;
983                 /* option */
984 
985                 c = *typestr++;
986                 if (c == '\0') {
987                     goto bad_type;
988                 }
989                 while (qemu_isspace(*p)) {
990                     p++;
991                 }
992                 if (*p == '-') {
993                     p++;
994                     if (c != *p) {
995                         if (!is_valid_option(p, typestr)) {
996                             monitor_printf(mon, "%s: unsupported option -%c\n",
997                                            cmd->name, *p);
998                             goto fail;
999                         } else {
1000                             skip_key = 1;
1001                         }
1002                     }
1003                     if (skip_key) {
1004                         p = tmp;
1005                     } else {
1006                         /* has option */
1007                         p++;
1008                         qdict_put_bool(qdict, key, true);
1009                     }
1010                 }
1011             }
1012             break;
1013         case 'S':
1014             {
1015                 /* package all remaining string */
1016                 int len;
1017 
1018                 while (qemu_isspace(*p)) {
1019                     p++;
1020                 }
1021                 if (*typestr == '?') {
1022                     typestr++;
1023                     if (*p == '\0') {
1024                         /* no remaining string: NULL argument */
1025                         break;
1026                     }
1027                 }
1028                 len = strlen(p);
1029                 if (len <= 0) {
1030                     monitor_printf(mon, "%s: string expected\n",
1031                                    cmd->name);
1032                     goto fail;
1033                 }
1034                 qdict_put_str(qdict, key, p);
1035                 p += len;
1036             }
1037             break;
1038         default:
1039         bad_type:
1040             monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
1041             goto fail;
1042         }
1043         g_free(key);
1044         key = NULL;
1045     }
1046     /* check that all arguments were parsed */
1047     while (qemu_isspace(*p)) {
1048         p++;
1049     }
1050     if (*p != '\0') {
1051         monitor_printf(mon, "%s: extraneous characters at the end of line\n",
1052                        cmd->name);
1053         goto fail;
1054     }
1055 
1056     return qdict;
1057 
1058 fail:
1059     qobject_unref(qdict);
1060     g_free(key);
1061     return NULL;
1062 }
1063 
1064 typedef struct HandleHmpCommandCo {
1065     Monitor *mon;
1066     const HMPCommand *cmd;
1067     QDict *qdict;
1068     bool done;
1069 } HandleHmpCommandCo;
1070 
1071 static void handle_hmp_command_co(void *opaque)
1072 {
1073     HandleHmpCommandCo *data = opaque;
1074     data->cmd->cmd(data->mon, data->qdict);
1075     monitor_set_cur(qemu_coroutine_self(), NULL);
1076     data->done = true;
1077 }
1078 
1079 void handle_hmp_command(MonitorHMP *mon, const char *cmdline)
1080 {
1081     QDict *qdict;
1082     const HMPCommand *cmd;
1083     const char *cmd_start = cmdline;
1084 
1085     trace_handle_hmp_command(mon, cmdline);
1086 
1087     cmd = monitor_parse_command(mon, cmdline, &cmdline, hmp_cmds);
1088     if (!cmd) {
1089         return;
1090     }
1091 
1092     if (!cmd->cmd) {
1093         /* FIXME: is it useful to try autoload modules here ??? */
1094         monitor_printf(&mon->common, "Command \"%.*s\" is not available.\n",
1095                        (int)(cmdline - cmd_start), cmd_start);
1096         return;
1097     }
1098 
1099     qdict = monitor_parse_arguments(&mon->common, &cmdline, cmd);
1100     if (!qdict) {
1101         while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
1102             cmdline--;
1103         }
1104         monitor_printf(&mon->common, "Try \"help %.*s\" for more information\n",
1105                        (int)(cmdline - cmd_start), cmd_start);
1106         return;
1107     }
1108 
1109     if (!cmd->coroutine) {
1110         /* old_mon is non-NULL when called from qmp_human_monitor_command() */
1111         Monitor *old_mon = monitor_set_cur(qemu_coroutine_self(), &mon->common);
1112         cmd->cmd(&mon->common, qdict);
1113         monitor_set_cur(qemu_coroutine_self(), old_mon);
1114     } else {
1115         HandleHmpCommandCo data = {
1116             .mon = &mon->common,
1117             .cmd = cmd,
1118             .qdict = qdict,
1119             .done = false,
1120         };
1121         Coroutine *co = qemu_coroutine_create(handle_hmp_command_co, &data);
1122         monitor_set_cur(co, &mon->common);
1123         aio_co_enter(qemu_get_aio_context(), co);
1124         AIO_WAIT_WHILE(qemu_get_aio_context(), !data.done);
1125     }
1126 
1127     qobject_unref(qdict);
1128 }
1129 
1130 static void cmd_completion(MonitorHMP *mon, const char *name, const char *list)
1131 {
1132     const char *p, *pstart;
1133     char cmd[128];
1134     int len;
1135 
1136     p = list;
1137     for (;;) {
1138         pstart = p;
1139         p = qemu_strchrnul(p, '|');
1140         len = p - pstart;
1141         if (len > sizeof(cmd) - 2) {
1142             len = sizeof(cmd) - 2;
1143         }
1144         memcpy(cmd, pstart, len);
1145         cmd[len] = '\0';
1146         if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
1147             readline_add_completion(mon->rs, cmd);
1148         }
1149         if (*p == '\0') {
1150             break;
1151         }
1152         p++;
1153     }
1154 }
1155 
1156 static void file_completion(MonitorHMP *mon, const char *input)
1157 {
1158     DIR *ffs;
1159     struct dirent *d;
1160     char path[1024];
1161     char file[1024], file_prefix[1024];
1162     int input_path_len;
1163     const char *p;
1164 
1165     p = strrchr(input, '/');
1166     if (!p) {
1167         input_path_len = 0;
1168         pstrcpy(file_prefix, sizeof(file_prefix), input);
1169         pstrcpy(path, sizeof(path), ".");
1170     } else {
1171         input_path_len = p - input + 1;
1172         memcpy(path, input, input_path_len);
1173         if (input_path_len > sizeof(path) - 1) {
1174             input_path_len = sizeof(path) - 1;
1175         }
1176         path[input_path_len] = '\0';
1177         pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
1178     }
1179 
1180     ffs = opendir(path);
1181     if (!ffs) {
1182         return;
1183     }
1184     for (;;) {
1185         struct stat sb;
1186         d = readdir(ffs);
1187         if (!d) {
1188             break;
1189         }
1190 
1191         if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
1192             continue;
1193         }
1194 
1195         if (strstart(d->d_name, file_prefix, NULL)) {
1196             memcpy(file, input, input_path_len);
1197             if (input_path_len < sizeof(file)) {
1198                 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
1199                         d->d_name);
1200             }
1201             /*
1202              * stat the file to find out if it's a directory.
1203              * In that case add a slash to speed up typing long paths
1204              */
1205             if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
1206                 pstrcat(file, sizeof(file), "/");
1207             }
1208             readline_add_completion(mon->rs, file);
1209         }
1210     }
1211     closedir(ffs);
1212 }
1213 
1214 static const char *next_arg_type(const char *typestr)
1215 {
1216     const char *p = strchr(typestr, ':');
1217     return (p != NULL ? ++p : typestr);
1218 }
1219 
1220 static void monitor_find_completion_by_table(MonitorHMP *mon,
1221                                              const HMPCommand *cmd_table,
1222                                              char **args,
1223                                              int nb_args)
1224 {
1225     const char *cmdname;
1226     int i;
1227     const char *ptype, *old_ptype, *str, *name;
1228     const HMPCommand *cmd;
1229     BlockBackend *blk = NULL;
1230 
1231     if (nb_args <= 1) {
1232         /* command completion */
1233         if (nb_args == 0) {
1234             cmdname = "";
1235         } else {
1236             cmdname = args[0];
1237         }
1238         readline_set_completion_index(mon->rs, strlen(cmdname));
1239         for (cmd = cmd_table; cmd->name != NULL; cmd++) {
1240             if (cmd_available(cmd)) {
1241                 cmd_completion(mon, cmdname, cmd->name);
1242             }
1243         }
1244     } else {
1245         /* find the command */
1246         for (cmd = cmd_table; cmd->name != NULL; cmd++) {
1247             if (hmp_compare_cmd(args[0], cmd->name) &&
1248                 cmd_available(cmd)) {
1249                 break;
1250             }
1251         }
1252         if (!cmd->name) {
1253             return;
1254         }
1255 
1256         if (cmd->sub_table) {
1257             /* do the job again */
1258             monitor_find_completion_by_table(mon, cmd->sub_table,
1259                                              &args[1], nb_args - 1);
1260             return;
1261         }
1262         if (cmd->command_completion) {
1263             cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
1264             return;
1265         }
1266 
1267         ptype = next_arg_type(cmd->args_type);
1268         for (i = 0; i < nb_args - 2; i++) {
1269             if (*ptype != '\0') {
1270                 ptype = next_arg_type(ptype);
1271                 while (*ptype == '?') {
1272                     ptype = next_arg_type(ptype);
1273                 }
1274             }
1275         }
1276         str = args[nb_args - 1];
1277         old_ptype = NULL;
1278         while (*ptype == '-' && old_ptype != ptype) {
1279             old_ptype = ptype;
1280             ptype = next_arg_type(ptype);
1281         }
1282         switch (*ptype) {
1283         case 'F':
1284             /* file completion */
1285             readline_set_completion_index(mon->rs, strlen(str));
1286             file_completion(mon, str);
1287             break;
1288         case 'B':
1289             /* block device name completion */
1290             readline_set_completion_index(mon->rs, strlen(str));
1291             while ((blk = blk_next(blk)) != NULL) {
1292                 name = blk_name(blk);
1293                 if (str[0] == '\0' ||
1294                     !strncmp(name, str, strlen(str))) {
1295                     readline_add_completion(mon->rs, name);
1296                 }
1297             }
1298             break;
1299         case 's':
1300         case 'S':
1301             if (!strcmp(cmd->name, "help|?")) {
1302                 monitor_find_completion_by_table(mon, cmd_table,
1303                                                  &args[1], nb_args - 1);
1304             }
1305             break;
1306         default:
1307             break;
1308         }
1309     }
1310 }
1311 
1312 static void monitor_find_completion(void *opaque,
1313                                     const char *cmdline)
1314 {
1315     MonitorHMP *mon = opaque;
1316     char *args[MAX_ARGS];
1317     int nb_args, len;
1318 
1319     /* 1. parse the cmdline */
1320     if (parse_cmdline(cmdline, &nb_args, args) < 0) {
1321         return;
1322     }
1323 
1324     /*
1325      * if the line ends with a space, it means we want to complete the
1326      * next arg
1327      */
1328     len = strlen(cmdline);
1329     if (len > 0 && qemu_isspace(cmdline[len - 1])) {
1330         if (nb_args >= MAX_ARGS) {
1331             goto cleanup;
1332         }
1333         args[nb_args++] = g_strdup("");
1334     }
1335 
1336     /* 2. auto complete according to args */
1337     monitor_find_completion_by_table(mon, hmp_cmds, args, nb_args);
1338 
1339 cleanup:
1340     free_cmdline_args(args, nb_args);
1341 }
1342 
1343 static void monitor_read(void *opaque, const uint8_t *buf, int size)
1344 {
1345     MonitorHMP *mon = container_of(opaque, MonitorHMP, common);
1346     int i;
1347 
1348     if (mon->rs) {
1349         for (i = 0; i < size; i++) {
1350             readline_handle_byte(mon->rs, buf[i]);
1351         }
1352     } else {
1353         if (size == 0 || buf[size - 1] != 0) {
1354             monitor_printf(&mon->common, "corrupted command\n");
1355         } else {
1356             handle_hmp_command(mon, (char *)buf);
1357         }
1358     }
1359 }
1360 
1361 static void monitor_event(void *opaque, QEMUChrEvent event)
1362 {
1363     Monitor *mon = opaque;
1364     MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
1365 
1366     switch (event) {
1367     case CHR_EVENT_MUX_IN:
1368         qemu_mutex_lock(&mon->mon_lock);
1369         mon->mux_out = 0;
1370         qemu_mutex_unlock(&mon->mon_lock);
1371         if (mon->reset_seen) {
1372             readline_restart(hmp_mon->rs);
1373             monitor_resume(mon);
1374             monitor_flush(mon);
1375         } else {
1376             qatomic_mb_set(&mon->suspend_cnt, 0);
1377         }
1378         break;
1379 
1380     case CHR_EVENT_MUX_OUT:
1381         if (mon->reset_seen) {
1382             if (qatomic_mb_read(&mon->suspend_cnt) == 0) {
1383                 monitor_printf(mon, "\n");
1384             }
1385             monitor_flush(mon);
1386             monitor_suspend(mon);
1387         } else {
1388             qatomic_inc(&mon->suspend_cnt);
1389         }
1390         qemu_mutex_lock(&mon->mon_lock);
1391         mon->mux_out = 1;
1392         qemu_mutex_unlock(&mon->mon_lock);
1393         break;
1394 
1395     case CHR_EVENT_OPENED:
1396         monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
1397                        "information\n", QEMU_VERSION);
1398         if (!mon->mux_out) {
1399             readline_restart(hmp_mon->rs);
1400             readline_show_prompt(hmp_mon->rs);
1401         }
1402         mon->reset_seen = 1;
1403         mon_refcount++;
1404         break;
1405 
1406     case CHR_EVENT_CLOSED:
1407         mon_refcount--;
1408         monitor_fdsets_cleanup();
1409         break;
1410 
1411     case CHR_EVENT_BREAK:
1412         /* Ignored */
1413         break;
1414     }
1415 }
1416 
1417 
1418 /*
1419  * These functions just adapt the readline interface in a typesafe way.  We
1420  * could cast function pointers but that discards compiler checks.
1421  */
1422 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
1423                                                        const char *fmt, ...)
1424 {
1425     MonitorHMP *mon = opaque;
1426     va_list ap;
1427     va_start(ap, fmt);
1428     monitor_vprintf(&mon->common, fmt, ap);
1429     va_end(ap);
1430 }
1431 
1432 static void monitor_readline_flush(void *opaque)
1433 {
1434     MonitorHMP *mon = opaque;
1435     monitor_flush(&mon->common);
1436 }
1437 
1438 void monitor_init_hmp(Chardev *chr, bool use_readline, Error **errp)
1439 {
1440     MonitorHMP *mon = g_new0(MonitorHMP, 1);
1441 
1442     if (!qemu_chr_fe_init(&mon->common.chr, chr, errp)) {
1443         g_free(mon);
1444         return;
1445     }
1446 
1447     monitor_data_init(&mon->common, false, false, false);
1448 
1449     mon->use_readline = use_readline;
1450     if (mon->use_readline) {
1451         mon->rs = readline_init(monitor_readline_printf,
1452                                 monitor_readline_flush,
1453                                 mon,
1454                                 monitor_find_completion);
1455         monitor_read_command(mon, 0);
1456     }
1457 
1458     qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read, monitor_read,
1459                              monitor_event, NULL, &mon->common, NULL, true);
1460     monitor_list_append(&mon->common);
1461 }
1462