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