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