xref: /openbmc/qemu/monitor/hmp.c (revision 2296b465)
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 G_NORETURN G_GNUC_PRINTF(2, 3)
312 void 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                 int ret;
985                 /* option */
986 
987                 c = *typestr++;
988                 if (c == '\0') {
989                     goto bad_type;
990                 }
991                 while (qemu_isspace(*p)) {
992                     p++;
993                 }
994                 if (*p == '-') {
995                     p++;
996                     if (c != *p) {
997                         if (!is_valid_option(p, typestr)) {
998                             monitor_printf(mon, "%s: unsupported option -%c\n",
999                                            cmd->name, *p);
1000                             goto fail;
1001                         } else {
1002                             skip_key = 1;
1003                         }
1004                     }
1005                     if (skip_key) {
1006                         p = tmp;
1007                     } else if (*typestr == 's') {
1008                         /* has option with string value */
1009                         typestr++;
1010                         tmp = p++;
1011                         while (qemu_isspace(*p)) {
1012                             p++;
1013                         }
1014                         ret = get_str(buf, sizeof(buf), &p);
1015                         if (ret < 0) {
1016                             monitor_printf(mon, "%s: value expected for -%c\n",
1017                                            cmd->name, *tmp);
1018                             goto fail;
1019                         }
1020                         qdict_put_str(qdict, key, buf);
1021                     } else {
1022                         /* has boolean option */
1023                         p++;
1024                         qdict_put_bool(qdict, key, true);
1025                     }
1026                 } else if (*typestr == 's') {
1027                     typestr++;
1028                 }
1029             }
1030             break;
1031         case 'S':
1032             {
1033                 /* package all remaining string */
1034                 int len;
1035 
1036                 while (qemu_isspace(*p)) {
1037                     p++;
1038                 }
1039                 if (*typestr == '?') {
1040                     typestr++;
1041                     if (*p == '\0') {
1042                         /* no remaining string: NULL argument */
1043                         break;
1044                     }
1045                 }
1046                 len = strlen(p);
1047                 if (len <= 0) {
1048                     monitor_printf(mon, "%s: string expected\n",
1049                                    cmd->name);
1050                     goto fail;
1051                 }
1052                 qdict_put_str(qdict, key, p);
1053                 p += len;
1054             }
1055             break;
1056         default:
1057         bad_type:
1058             monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
1059             goto fail;
1060         }
1061         g_free(key);
1062         key = NULL;
1063     }
1064     /* check that all arguments were parsed */
1065     while (qemu_isspace(*p)) {
1066         p++;
1067     }
1068     if (*p != '\0') {
1069         monitor_printf(mon, "%s: extraneous characters at the end of line\n",
1070                        cmd->name);
1071         goto fail;
1072     }
1073 
1074     return qdict;
1075 
1076 fail:
1077     qobject_unref(qdict);
1078     g_free(key);
1079     return NULL;
1080 }
1081 
1082 static void hmp_info_human_readable_text(Monitor *mon,
1083                                          HumanReadableText *(*handler)(Error **))
1084 {
1085     Error *err = NULL;
1086     g_autoptr(HumanReadableText) info = handler(&err);
1087 
1088     if (hmp_handle_error(mon, err)) {
1089         return;
1090     }
1091 
1092     monitor_printf(mon, "%s", info->human_readable_text);
1093 }
1094 
1095 static void handle_hmp_command_exec(Monitor *mon,
1096                                     const HMPCommand *cmd,
1097                                     QDict *qdict)
1098 {
1099     if (cmd->cmd_info_hrt) {
1100         hmp_info_human_readable_text(mon,
1101                                      cmd->cmd_info_hrt);
1102     } else {
1103         cmd->cmd(mon, qdict);
1104     }
1105 }
1106 
1107 typedef struct HandleHmpCommandCo {
1108     Monitor *mon;
1109     const HMPCommand *cmd;
1110     QDict *qdict;
1111     bool done;
1112 } HandleHmpCommandCo;
1113 
1114 static void handle_hmp_command_co(void *opaque)
1115 {
1116     HandleHmpCommandCo *data = opaque;
1117     handle_hmp_command_exec(data->mon, data->cmd, data->qdict);
1118     monitor_set_cur(qemu_coroutine_self(), NULL);
1119     data->done = true;
1120 }
1121 
1122 void handle_hmp_command(MonitorHMP *mon, const char *cmdline)
1123 {
1124     QDict *qdict;
1125     const HMPCommand *cmd;
1126     const char *cmd_start = cmdline;
1127 
1128     trace_handle_hmp_command(mon, cmdline);
1129 
1130     cmd = monitor_parse_command(mon, cmdline, &cmdline, hmp_cmds);
1131     if (!cmd) {
1132         return;
1133     }
1134 
1135     if (!cmd->cmd && !cmd->cmd_info_hrt) {
1136         /* FIXME: is it useful to try autoload modules here ??? */
1137         monitor_printf(&mon->common, "Command \"%.*s\" is not available.\n",
1138                        (int)(cmdline - cmd_start), cmd_start);
1139         return;
1140     }
1141 
1142     qdict = monitor_parse_arguments(&mon->common, &cmdline, cmd);
1143     if (!qdict) {
1144         while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
1145             cmdline--;
1146         }
1147         monitor_printf(&mon->common, "Try \"help %.*s\" for more information\n",
1148                        (int)(cmdline - cmd_start), cmd_start);
1149         return;
1150     }
1151 
1152     if (!cmd->coroutine) {
1153         /* old_mon is non-NULL when called from qmp_human_monitor_command() */
1154         Monitor *old_mon = monitor_set_cur(qemu_coroutine_self(), &mon->common);
1155         handle_hmp_command_exec(&mon->common, cmd, qdict);
1156         monitor_set_cur(qemu_coroutine_self(), old_mon);
1157     } else {
1158         HandleHmpCommandCo data = {
1159             .mon = &mon->common,
1160             .cmd = cmd,
1161             .qdict = qdict,
1162             .done = false,
1163         };
1164         Coroutine *co = qemu_coroutine_create(handle_hmp_command_co, &data);
1165         monitor_set_cur(co, &mon->common);
1166         aio_co_enter(qemu_get_aio_context(), co);
1167         AIO_WAIT_WHILE(qemu_get_aio_context(), !data.done);
1168     }
1169 
1170     qobject_unref(qdict);
1171 }
1172 
1173 static void cmd_completion(MonitorHMP *mon, const char *name, const char *list)
1174 {
1175     const char *p, *pstart;
1176     char cmd[128];
1177     int len;
1178 
1179     p = list;
1180     for (;;) {
1181         pstart = p;
1182         p = qemu_strchrnul(p, '|');
1183         len = p - pstart;
1184         if (len > sizeof(cmd) - 2) {
1185             len = sizeof(cmd) - 2;
1186         }
1187         memcpy(cmd, pstart, len);
1188         cmd[len] = '\0';
1189         if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
1190             readline_add_completion(mon->rs, cmd);
1191         }
1192         if (*p == '\0') {
1193             break;
1194         }
1195         p++;
1196     }
1197 }
1198 
1199 static void file_completion(MonitorHMP *mon, const char *input)
1200 {
1201     DIR *ffs;
1202     struct dirent *d;
1203     char path[1024];
1204     char file[1024], file_prefix[1024];
1205     int input_path_len;
1206     const char *p;
1207 
1208     p = strrchr(input, '/');
1209     if (!p) {
1210         input_path_len = 0;
1211         pstrcpy(file_prefix, sizeof(file_prefix), input);
1212         pstrcpy(path, sizeof(path), ".");
1213     } else {
1214         input_path_len = p - input + 1;
1215         memcpy(path, input, input_path_len);
1216         if (input_path_len > sizeof(path) - 1) {
1217             input_path_len = sizeof(path) - 1;
1218         }
1219         path[input_path_len] = '\0';
1220         pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
1221     }
1222 
1223     ffs = opendir(path);
1224     if (!ffs) {
1225         return;
1226     }
1227     for (;;) {
1228         struct stat sb;
1229         d = readdir(ffs);
1230         if (!d) {
1231             break;
1232         }
1233 
1234         if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
1235             continue;
1236         }
1237 
1238         if (strstart(d->d_name, file_prefix, NULL)) {
1239             memcpy(file, input, input_path_len);
1240             if (input_path_len < sizeof(file)) {
1241                 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
1242                         d->d_name);
1243             }
1244             /*
1245              * stat the file to find out if it's a directory.
1246              * In that case add a slash to speed up typing long paths
1247              */
1248             if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
1249                 pstrcat(file, sizeof(file), "/");
1250             }
1251             readline_add_completion(mon->rs, file);
1252         }
1253     }
1254     closedir(ffs);
1255 }
1256 
1257 static const char *next_arg_type(const char *typestr)
1258 {
1259     const char *p = strchr(typestr, ':');
1260     return (p != NULL ? ++p : typestr);
1261 }
1262 
1263 static void monitor_find_completion_by_table(MonitorHMP *mon,
1264                                              const HMPCommand *cmd_table,
1265                                              char **args,
1266                                              int nb_args)
1267 {
1268     const char *cmdname;
1269     int i;
1270     const char *ptype, *old_ptype, *str, *name;
1271     const HMPCommand *cmd;
1272     BlockBackend *blk = NULL;
1273 
1274     if (nb_args <= 1) {
1275         /* command completion */
1276         if (nb_args == 0) {
1277             cmdname = "";
1278         } else {
1279             cmdname = args[0];
1280         }
1281         readline_set_completion_index(mon->rs, strlen(cmdname));
1282         for (cmd = cmd_table; cmd->name != NULL; cmd++) {
1283             if (cmd_available(cmd)) {
1284                 cmd_completion(mon, cmdname, cmd->name);
1285             }
1286         }
1287     } else {
1288         /* find the command */
1289         for (cmd = cmd_table; cmd->name != NULL; cmd++) {
1290             if (hmp_compare_cmd(args[0], cmd->name) &&
1291                 cmd_available(cmd)) {
1292                 break;
1293             }
1294         }
1295         if (!cmd->name) {
1296             return;
1297         }
1298 
1299         if (cmd->sub_table) {
1300             /* do the job again */
1301             monitor_find_completion_by_table(mon, cmd->sub_table,
1302                                              &args[1], nb_args - 1);
1303             return;
1304         }
1305         if (cmd->command_completion) {
1306             cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
1307             return;
1308         }
1309 
1310         ptype = next_arg_type(cmd->args_type);
1311         for (i = 0; i < nb_args - 2; i++) {
1312             if (*ptype != '\0') {
1313                 ptype = next_arg_type(ptype);
1314                 while (*ptype == '?') {
1315                     ptype = next_arg_type(ptype);
1316                 }
1317             }
1318         }
1319         str = args[nb_args - 1];
1320         old_ptype = NULL;
1321         while (*ptype == '-' && old_ptype != ptype) {
1322             old_ptype = ptype;
1323             ptype = next_arg_type(ptype);
1324         }
1325         switch (*ptype) {
1326         case 'F':
1327             /* file completion */
1328             readline_set_completion_index(mon->rs, strlen(str));
1329             file_completion(mon, str);
1330             break;
1331         case 'B':
1332             /* block device name completion */
1333             readline_set_completion_index(mon->rs, strlen(str));
1334             while ((blk = blk_next(blk)) != NULL) {
1335                 name = blk_name(blk);
1336                 if (str[0] == '\0' ||
1337                     !strncmp(name, str, strlen(str))) {
1338                     readline_add_completion(mon->rs, name);
1339                 }
1340             }
1341             break;
1342         case 's':
1343         case 'S':
1344             if (!strcmp(cmd->name, "help|?")) {
1345                 monitor_find_completion_by_table(mon, cmd_table,
1346                                                  &args[1], nb_args - 1);
1347             }
1348             break;
1349         default:
1350             break;
1351         }
1352     }
1353 }
1354 
1355 static void monitor_find_completion(void *opaque,
1356                                     const char *cmdline)
1357 {
1358     MonitorHMP *mon = opaque;
1359     char *args[MAX_ARGS];
1360     int nb_args, len;
1361 
1362     /* 1. parse the cmdline */
1363     if (parse_cmdline(cmdline, &nb_args, args) < 0) {
1364         return;
1365     }
1366 
1367     /*
1368      * if the line ends with a space, it means we want to complete the
1369      * next arg
1370      */
1371     len = strlen(cmdline);
1372     if (len > 0 && qemu_isspace(cmdline[len - 1])) {
1373         if (nb_args >= MAX_ARGS) {
1374             goto cleanup;
1375         }
1376         args[nb_args++] = g_strdup("");
1377     }
1378 
1379     /* 2. auto complete according to args */
1380     monitor_find_completion_by_table(mon, hmp_cmds, args, nb_args);
1381 
1382 cleanup:
1383     free_cmdline_args(args, nb_args);
1384 }
1385 
1386 static void monitor_read(void *opaque, const uint8_t *buf, int size)
1387 {
1388     MonitorHMP *mon = container_of(opaque, MonitorHMP, common);
1389     int i;
1390 
1391     if (mon->rs) {
1392         for (i = 0; i < size; i++) {
1393             readline_handle_byte(mon->rs, buf[i]);
1394         }
1395     } else {
1396         if (size == 0 || buf[size - 1] != 0) {
1397             monitor_printf(&mon->common, "corrupted command\n");
1398         } else {
1399             handle_hmp_command(mon, (char *)buf);
1400         }
1401     }
1402 }
1403 
1404 static void monitor_event(void *opaque, QEMUChrEvent event)
1405 {
1406     Monitor *mon = opaque;
1407     MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
1408 
1409     switch (event) {
1410     case CHR_EVENT_MUX_IN:
1411         qemu_mutex_lock(&mon->mon_lock);
1412         mon->mux_out = 0;
1413         qemu_mutex_unlock(&mon->mon_lock);
1414         if (mon->reset_seen) {
1415             readline_restart(hmp_mon->rs);
1416             monitor_resume(mon);
1417             monitor_flush(mon);
1418         } else {
1419             qatomic_mb_set(&mon->suspend_cnt, 0);
1420         }
1421         break;
1422 
1423     case CHR_EVENT_MUX_OUT:
1424         if (mon->reset_seen) {
1425             if (qatomic_mb_read(&mon->suspend_cnt) == 0) {
1426                 monitor_printf(mon, "\n");
1427             }
1428             monitor_flush(mon);
1429             monitor_suspend(mon);
1430         } else {
1431             qatomic_inc(&mon->suspend_cnt);
1432         }
1433         qemu_mutex_lock(&mon->mon_lock);
1434         mon->mux_out = 1;
1435         qemu_mutex_unlock(&mon->mon_lock);
1436         break;
1437 
1438     case CHR_EVENT_OPENED:
1439         monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
1440                        "information\n", QEMU_VERSION);
1441         if (!mon->mux_out) {
1442             readline_restart(hmp_mon->rs);
1443             readline_show_prompt(hmp_mon->rs);
1444         }
1445         mon->reset_seen = 1;
1446         mon_refcount++;
1447         break;
1448 
1449     case CHR_EVENT_CLOSED:
1450         mon_refcount--;
1451         monitor_fdsets_cleanup();
1452         break;
1453 
1454     case CHR_EVENT_BREAK:
1455         /* Ignored */
1456         break;
1457     }
1458 }
1459 
1460 
1461 /*
1462  * These functions just adapt the readline interface in a typesafe way.  We
1463  * could cast function pointers but that discards compiler checks.
1464  */
1465 static void G_GNUC_PRINTF(2, 3) monitor_readline_printf(void *opaque,
1466                                                        const char *fmt, ...)
1467 {
1468     MonitorHMP *mon = opaque;
1469     va_list ap;
1470     va_start(ap, fmt);
1471     monitor_vprintf(&mon->common, fmt, ap);
1472     va_end(ap);
1473 }
1474 
1475 static void monitor_readline_flush(void *opaque)
1476 {
1477     MonitorHMP *mon = opaque;
1478     monitor_flush(&mon->common);
1479 }
1480 
1481 void monitor_init_hmp(Chardev *chr, bool use_readline, Error **errp)
1482 {
1483     MonitorHMP *mon = g_new0(MonitorHMP, 1);
1484 
1485     if (!qemu_chr_fe_init(&mon->common.chr, chr, errp)) {
1486         g_free(mon);
1487         return;
1488     }
1489 
1490     monitor_data_init(&mon->common, false, false, false);
1491 
1492     mon->use_readline = use_readline;
1493     if (mon->use_readline) {
1494         mon->rs = readline_init(monitor_readline_printf,
1495                                 monitor_readline_flush,
1496                                 mon,
1497                                 monitor_find_completion);
1498         monitor_read_command(mon, 0);
1499     }
1500 
1501     qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read, monitor_read,
1502                              monitor_event, NULL, &mon->common, NULL, true);
1503     monitor_list_append(&mon->common);
1504 }
1505