xref: /openbmc/qemu/util/qemu-option.c (revision 56411125)
1 /*
2  * Commandline option parsing functions
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  * Copyright (c) 2009 Kevin Wolf <kwolf@redhat.com>
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include <stdio.h>
27 #include <string.h>
28 
29 #include "qemu-common.h"
30 #include "qemu/error-report.h"
31 #include "qapi/qmp/types.h"
32 #include "qapi/error.h"
33 #include "qapi/qmp/qerror.h"
34 #include "qemu/option_int.h"
35 
36 /*
37  * Extracts the name of an option from the parameter string (p points at the
38  * first byte of the option name)
39  *
40  * The option name is delimited by delim (usually , or =) or the string end
41  * and is copied into buf. If the option name is longer than buf_size, it is
42  * truncated. buf is always zero terminated.
43  *
44  * The return value is the position of the delimiter/zero byte after the option
45  * name in p.
46  */
47 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
48 {
49     char *q;
50 
51     q = buf;
52     while (*p != '\0' && *p != delim) {
53         if (q && (q - buf) < buf_size - 1)
54             *q++ = *p;
55         p++;
56     }
57     if (q)
58         *q = '\0';
59 
60     return p;
61 }
62 
63 /*
64  * Extracts the value of an option from the parameter string p (p points at the
65  * first byte of the option value)
66  *
67  * This function is comparable to get_opt_name with the difference that the
68  * delimiter is fixed to be comma which starts a new option. To specify an
69  * option value that contains commas, double each comma.
70  */
71 const char *get_opt_value(char *buf, int buf_size, const char *p)
72 {
73     char *q;
74 
75     q = buf;
76     while (*p != '\0') {
77         if (*p == ',') {
78             if (*(p + 1) != ',')
79                 break;
80             p++;
81         }
82         if (q && (q - buf) < buf_size - 1)
83             *q++ = *p;
84         p++;
85     }
86     if (q)
87         *q = '\0';
88 
89     return p;
90 }
91 
92 int get_next_param_value(char *buf, int buf_size,
93                          const char *tag, const char **pstr)
94 {
95     const char *p;
96     char option[128];
97 
98     p = *pstr;
99     for(;;) {
100         p = get_opt_name(option, sizeof(option), p, '=');
101         if (*p != '=')
102             break;
103         p++;
104         if (!strcmp(tag, option)) {
105             *pstr = get_opt_value(buf, buf_size, p);
106             if (**pstr == ',') {
107                 (*pstr)++;
108             }
109             return strlen(buf);
110         } else {
111             p = get_opt_value(NULL, 0, p);
112         }
113         if (*p != ',')
114             break;
115         p++;
116     }
117     return 0;
118 }
119 
120 int get_param_value(char *buf, int buf_size,
121                     const char *tag, const char *str)
122 {
123     return get_next_param_value(buf, buf_size, tag, &str);
124 }
125 
126 static void parse_option_bool(const char *name, const char *value, bool *ret,
127                               Error **errp)
128 {
129     if (value != NULL) {
130         if (!strcmp(value, "on")) {
131             *ret = 1;
132         } else if (!strcmp(value, "off")) {
133             *ret = 0;
134         } else {
135             error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
136                        name, "'on' or 'off'");
137         }
138     } else {
139         *ret = 1;
140     }
141 }
142 
143 static void parse_option_number(const char *name, const char *value,
144                                 uint64_t *ret, Error **errp)
145 {
146     char *postfix;
147     uint64_t number;
148 
149     if (value != NULL) {
150         number = strtoull(value, &postfix, 0);
151         if (*postfix != '\0') {
152             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
153             return;
154         }
155         *ret = number;
156     } else {
157         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
158     }
159 }
160 
161 static const QemuOptDesc *find_desc_by_name(const QemuOptDesc *desc,
162                                             const char *name)
163 {
164     int i;
165 
166     for (i = 0; desc[i].name != NULL; i++) {
167         if (strcmp(desc[i].name, name) == 0) {
168             return &desc[i];
169         }
170     }
171 
172     return NULL;
173 }
174 
175 void parse_option_size(const char *name, const char *value,
176                        uint64_t *ret, Error **errp)
177 {
178     char *postfix;
179     double sizef;
180 
181     if (value != NULL) {
182         sizef = strtod(value, &postfix);
183         if (sizef < 0 || sizef > UINT64_MAX) {
184             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name,
185                              "a non-negative number below 2^64");
186             return;
187         }
188         switch (*postfix) {
189         case 'T':
190             sizef *= 1024;
191             /* fall through */
192         case 'G':
193             sizef *= 1024;
194             /* fall through */
195         case 'M':
196             sizef *= 1024;
197             /* fall through */
198         case 'K':
199         case 'k':
200             sizef *= 1024;
201             /* fall through */
202         case 'b':
203         case '\0':
204             *ret = (uint64_t) sizef;
205             break;
206         default:
207             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
208             error_append_hint(errp, "You may use k, M, G or T suffixes for "
209                     "kilobytes, megabytes, gigabytes and terabytes.");
210             return;
211         }
212     } else {
213         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
214     }
215 }
216 
217 bool has_help_option(const char *param)
218 {
219     size_t buflen = strlen(param) + 1;
220     char *buf = g_malloc(buflen);
221     const char *p = param;
222     bool result = false;
223 
224     while (*p) {
225         p = get_opt_value(buf, buflen, p);
226         if (*p) {
227             p++;
228         }
229 
230         if (is_help_option(buf)) {
231             result = true;
232             goto out;
233         }
234     }
235 
236 out:
237     g_free(buf);
238     return result;
239 }
240 
241 bool is_valid_option_list(const char *param)
242 {
243     size_t buflen = strlen(param) + 1;
244     char *buf = g_malloc(buflen);
245     const char *p = param;
246     bool result = true;
247 
248     while (*p) {
249         p = get_opt_value(buf, buflen, p);
250         if (*p && !*++p) {
251             result = false;
252             goto out;
253         }
254 
255         if (!*buf || *buf == ',') {
256             result = false;
257             goto out;
258         }
259     }
260 
261 out:
262     g_free(buf);
263     return result;
264 }
265 
266 void qemu_opts_print_help(QemuOptsList *list)
267 {
268     QemuOptDesc *desc;
269 
270     assert(list);
271     desc = list->desc;
272     printf("Supported options:\n");
273     while (desc && desc->name) {
274         printf("%-16s %s\n", desc->name,
275                desc->help ? desc->help : "No description available");
276         desc++;
277     }
278 }
279 /* ------------------------------------------------------------------ */
280 
281 QemuOpt *qemu_opt_find(QemuOpts *opts, const char *name)
282 {
283     QemuOpt *opt;
284 
285     QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
286         if (strcmp(opt->name, name) != 0)
287             continue;
288         return opt;
289     }
290     return NULL;
291 }
292 
293 static void qemu_opt_del(QemuOpt *opt)
294 {
295     QTAILQ_REMOVE(&opt->opts->head, opt, next);
296     g_free(opt->name);
297     g_free(opt->str);
298     g_free(opt);
299 }
300 
301 /* qemu_opt_set allows many settings for the same option.
302  * This function deletes all settings for an option.
303  */
304 static void qemu_opt_del_all(QemuOpts *opts, const char *name)
305 {
306     QemuOpt *opt, *next_opt;
307 
308     QTAILQ_FOREACH_SAFE(opt, &opts->head, next, next_opt) {
309         if (!strcmp(opt->name, name)) {
310             qemu_opt_del(opt);
311         }
312     }
313 }
314 
315 const char *qemu_opt_get(QemuOpts *opts, const char *name)
316 {
317     QemuOpt *opt;
318 
319     if (opts == NULL) {
320         return NULL;
321     }
322 
323     opt = qemu_opt_find(opts, name);
324     if (!opt) {
325         const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
326         if (desc && desc->def_value_str) {
327             return desc->def_value_str;
328         }
329     }
330     return opt ? opt->str : NULL;
331 }
332 
333 /* Get a known option (or its default) and remove it from the list
334  * all in one action. Return a malloced string of the option value.
335  * Result must be freed by caller with g_free().
336  */
337 char *qemu_opt_get_del(QemuOpts *opts, const char *name)
338 {
339     QemuOpt *opt;
340     const QemuOptDesc *desc;
341     char *str = NULL;
342 
343     if (opts == NULL) {
344         return NULL;
345     }
346 
347     opt = qemu_opt_find(opts, name);
348     if (!opt) {
349         desc = find_desc_by_name(opts->list->desc, name);
350         if (desc && desc->def_value_str) {
351             str = g_strdup(desc->def_value_str);
352         }
353         return str;
354     }
355     str = opt->str;
356     opt->str = NULL;
357     qemu_opt_del_all(opts, name);
358     return str;
359 }
360 
361 bool qemu_opt_has_help_opt(QemuOpts *opts)
362 {
363     QemuOpt *opt;
364 
365     QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
366         if (is_help_option(opt->name)) {
367             return true;
368         }
369     }
370     return false;
371 }
372 
373 static bool qemu_opt_get_bool_helper(QemuOpts *opts, const char *name,
374                                      bool defval, bool del)
375 {
376     QemuOpt *opt;
377     bool ret = defval;
378 
379     if (opts == NULL) {
380         return ret;
381     }
382 
383     opt = qemu_opt_find(opts, name);
384     if (opt == NULL) {
385         const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
386         if (desc && desc->def_value_str) {
387             parse_option_bool(name, desc->def_value_str, &ret, &error_abort);
388         }
389         return ret;
390     }
391     assert(opt->desc && opt->desc->type == QEMU_OPT_BOOL);
392     ret = opt->value.boolean;
393     if (del) {
394         qemu_opt_del_all(opts, name);
395     }
396     return ret;
397 }
398 
399 bool qemu_opt_get_bool(QemuOpts *opts, const char *name, bool defval)
400 {
401     return qemu_opt_get_bool_helper(opts, name, defval, false);
402 }
403 
404 bool qemu_opt_get_bool_del(QemuOpts *opts, const char *name, bool defval)
405 {
406     return qemu_opt_get_bool_helper(opts, name, defval, true);
407 }
408 
409 static uint64_t qemu_opt_get_number_helper(QemuOpts *opts, const char *name,
410                                            uint64_t defval, bool del)
411 {
412     QemuOpt *opt;
413     uint64_t ret = defval;
414 
415     if (opts == NULL) {
416         return ret;
417     }
418 
419     opt = qemu_opt_find(opts, name);
420     if (opt == NULL) {
421         const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
422         if (desc && desc->def_value_str) {
423             parse_option_number(name, desc->def_value_str, &ret, &error_abort);
424         }
425         return ret;
426     }
427     assert(opt->desc && opt->desc->type == QEMU_OPT_NUMBER);
428     ret = opt->value.uint;
429     if (del) {
430         qemu_opt_del_all(opts, name);
431     }
432     return ret;
433 }
434 
435 uint64_t qemu_opt_get_number(QemuOpts *opts, const char *name, uint64_t defval)
436 {
437     return qemu_opt_get_number_helper(opts, name, defval, false);
438 }
439 
440 uint64_t qemu_opt_get_number_del(QemuOpts *opts, const char *name,
441                                  uint64_t defval)
442 {
443     return qemu_opt_get_number_helper(opts, name, defval, true);
444 }
445 
446 static uint64_t qemu_opt_get_size_helper(QemuOpts *opts, const char *name,
447                                          uint64_t defval, bool del)
448 {
449     QemuOpt *opt;
450     uint64_t ret = defval;
451 
452     if (opts == NULL) {
453         return ret;
454     }
455 
456     opt = qemu_opt_find(opts, name);
457     if (opt == NULL) {
458         const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
459         if (desc && desc->def_value_str) {
460             parse_option_size(name, desc->def_value_str, &ret, &error_abort);
461         }
462         return ret;
463     }
464     assert(opt->desc && opt->desc->type == QEMU_OPT_SIZE);
465     ret = opt->value.uint;
466     if (del) {
467         qemu_opt_del_all(opts, name);
468     }
469     return ret;
470 }
471 
472 uint64_t qemu_opt_get_size(QemuOpts *opts, const char *name, uint64_t defval)
473 {
474     return qemu_opt_get_size_helper(opts, name, defval, false);
475 }
476 
477 uint64_t qemu_opt_get_size_del(QemuOpts *opts, const char *name,
478                                uint64_t defval)
479 {
480     return qemu_opt_get_size_helper(opts, name, defval, true);
481 }
482 
483 static void qemu_opt_parse(QemuOpt *opt, Error **errp)
484 {
485     if (opt->desc == NULL)
486         return;
487 
488     switch (opt->desc->type) {
489     case QEMU_OPT_STRING:
490         /* nothing */
491         return;
492     case QEMU_OPT_BOOL:
493         parse_option_bool(opt->name, opt->str, &opt->value.boolean, errp);
494         break;
495     case QEMU_OPT_NUMBER:
496         parse_option_number(opt->name, opt->str, &opt->value.uint, errp);
497         break;
498     case QEMU_OPT_SIZE:
499         parse_option_size(opt->name, opt->str, &opt->value.uint, errp);
500         break;
501     default:
502         abort();
503     }
504 }
505 
506 static bool opts_accepts_any(const QemuOpts *opts)
507 {
508     return opts->list->desc[0].name == NULL;
509 }
510 
511 int qemu_opt_unset(QemuOpts *opts, const char *name)
512 {
513     QemuOpt *opt = qemu_opt_find(opts, name);
514 
515     assert(opts_accepts_any(opts));
516 
517     if (opt == NULL) {
518         return -1;
519     } else {
520         qemu_opt_del(opt);
521         return 0;
522     }
523 }
524 
525 static void opt_set(QemuOpts *opts, const char *name, const char *value,
526                     bool prepend, Error **errp)
527 {
528     QemuOpt *opt;
529     const QemuOptDesc *desc;
530     Error *local_err = NULL;
531 
532     desc = find_desc_by_name(opts->list->desc, name);
533     if (!desc && !opts_accepts_any(opts)) {
534         error_setg(errp, QERR_INVALID_PARAMETER, name);
535         return;
536     }
537 
538     opt = g_malloc0(sizeof(*opt));
539     opt->name = g_strdup(name);
540     opt->opts = opts;
541     if (prepend) {
542         QTAILQ_INSERT_HEAD(&opts->head, opt, next);
543     } else {
544         QTAILQ_INSERT_TAIL(&opts->head, opt, next);
545     }
546     opt->desc = desc;
547     opt->str = g_strdup(value);
548     qemu_opt_parse(opt, &local_err);
549     if (local_err) {
550         error_propagate(errp, local_err);
551         qemu_opt_del(opt);
552     }
553 }
554 
555 void qemu_opt_set(QemuOpts *opts, const char *name, const char *value,
556                   Error **errp)
557 {
558     opt_set(opts, name, value, false, errp);
559 }
560 
561 void qemu_opt_set_bool(QemuOpts *opts, const char *name, bool val,
562                        Error **errp)
563 {
564     QemuOpt *opt;
565     const QemuOptDesc *desc = opts->list->desc;
566 
567     opt = g_malloc0(sizeof(*opt));
568     opt->desc = find_desc_by_name(desc, name);
569     if (!opt->desc && !opts_accepts_any(opts)) {
570         error_setg(errp, QERR_INVALID_PARAMETER, name);
571         g_free(opt);
572         return;
573     }
574 
575     opt->name = g_strdup(name);
576     opt->opts = opts;
577     opt->value.boolean = !!val;
578     opt->str = g_strdup(val ? "on" : "off");
579     QTAILQ_INSERT_TAIL(&opts->head, opt, next);
580 }
581 
582 void qemu_opt_set_number(QemuOpts *opts, const char *name, int64_t val,
583                          Error **errp)
584 {
585     QemuOpt *opt;
586     const QemuOptDesc *desc = opts->list->desc;
587 
588     opt = g_malloc0(sizeof(*opt));
589     opt->desc = find_desc_by_name(desc, name);
590     if (!opt->desc && !opts_accepts_any(opts)) {
591         error_setg(errp, QERR_INVALID_PARAMETER, name);
592         g_free(opt);
593         return;
594     }
595 
596     opt->name = g_strdup(name);
597     opt->opts = opts;
598     opt->value.uint = val;
599     opt->str = g_strdup_printf("%" PRId64, val);
600     QTAILQ_INSERT_TAIL(&opts->head, opt, next);
601 }
602 
603 /**
604  * For each member of @opts, call @func(@opaque, name, value, @errp).
605  * @func() may store an Error through @errp, but must return non-zero then.
606  * When @func() returns non-zero, break the loop and return that value.
607  * Return zero when the loop completes.
608  */
609 int qemu_opt_foreach(QemuOpts *opts, qemu_opt_loopfunc func, void *opaque,
610                      Error **errp)
611 {
612     QemuOpt *opt;
613     int rc;
614 
615     QTAILQ_FOREACH(opt, &opts->head, next) {
616         rc = func(opaque, opt->name, opt->str, errp);
617         if (rc) {
618             return rc;
619         }
620         assert(!errp || !*errp);
621     }
622     return 0;
623 }
624 
625 QemuOpts *qemu_opts_find(QemuOptsList *list, const char *id)
626 {
627     QemuOpts *opts;
628 
629     QTAILQ_FOREACH(opts, &list->head, next) {
630         if (!opts->id && !id) {
631             return opts;
632         }
633         if (opts->id && id && !strcmp(opts->id, id)) {
634             return opts;
635         }
636     }
637     return NULL;
638 }
639 
640 QemuOpts *qemu_opts_create(QemuOptsList *list, const char *id,
641                            int fail_if_exists, Error **errp)
642 {
643     QemuOpts *opts = NULL;
644 
645     if (id) {
646         if (!id_wellformed(id)) {
647             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id",
648                        "an identifier");
649             error_append_hint(errp, "Identifiers consist of letters, digits, "
650                               "'-', '.', '_', starting with a letter.");
651             return NULL;
652         }
653         opts = qemu_opts_find(list, id);
654         if (opts != NULL) {
655             if (fail_if_exists && !list->merge_lists) {
656                 error_setg(errp, "Duplicate ID '%s' for %s", id, list->name);
657                 return NULL;
658             } else {
659                 return opts;
660             }
661         }
662     } else if (list->merge_lists) {
663         opts = qemu_opts_find(list, NULL);
664         if (opts) {
665             return opts;
666         }
667     }
668     opts = g_malloc0(sizeof(*opts));
669     opts->id = g_strdup(id);
670     opts->list = list;
671     loc_save(&opts->loc);
672     QTAILQ_INIT(&opts->head);
673     QTAILQ_INSERT_TAIL(&list->head, opts, next);
674     return opts;
675 }
676 
677 void qemu_opts_reset(QemuOptsList *list)
678 {
679     QemuOpts *opts, *next_opts;
680 
681     QTAILQ_FOREACH_SAFE(opts, &list->head, next, next_opts) {
682         qemu_opts_del(opts);
683     }
684 }
685 
686 void qemu_opts_loc_restore(QemuOpts *opts)
687 {
688     loc_restore(&opts->loc);
689 }
690 
691 void qemu_opts_set(QemuOptsList *list, const char *id,
692                    const char *name, const char *value, Error **errp)
693 {
694     QemuOpts *opts;
695     Error *local_err = NULL;
696 
697     opts = qemu_opts_create(list, id, 1, &local_err);
698     if (local_err) {
699         error_propagate(errp, local_err);
700         return;
701     }
702     qemu_opt_set(opts, name, value, errp);
703 }
704 
705 const char *qemu_opts_id(QemuOpts *opts)
706 {
707     return opts->id;
708 }
709 
710 /* The id string will be g_free()d by qemu_opts_del */
711 void qemu_opts_set_id(QemuOpts *opts, char *id)
712 {
713     opts->id = id;
714 }
715 
716 void qemu_opts_del(QemuOpts *opts)
717 {
718     QemuOpt *opt;
719 
720     if (opts == NULL) {
721         return;
722     }
723 
724     for (;;) {
725         opt = QTAILQ_FIRST(&opts->head);
726         if (opt == NULL)
727             break;
728         qemu_opt_del(opt);
729     }
730     QTAILQ_REMOVE(&opts->list->head, opts, next);
731     g_free(opts->id);
732     g_free(opts);
733 }
734 
735 /* print value, escaping any commas in value */
736 static void escaped_print(const char *value)
737 {
738     const char *ptr;
739 
740     for (ptr = value; *ptr; ++ptr) {
741         if (*ptr == ',') {
742             putchar(',');
743         }
744         putchar(*ptr);
745     }
746 }
747 
748 void qemu_opts_print(QemuOpts *opts, const char *separator)
749 {
750     QemuOpt *opt;
751     QemuOptDesc *desc = opts->list->desc;
752     const char *sep = "";
753 
754     if (opts->id) {
755         printf("id=%s", opts->id); /* passed id_wellformed -> no commas */
756         sep = separator;
757     }
758 
759     if (desc[0].name == NULL) {
760         QTAILQ_FOREACH(opt, &opts->head, next) {
761             printf("%s%s=", sep, opt->name);
762             escaped_print(opt->str);
763             sep = separator;
764         }
765         return;
766     }
767     for (; desc && desc->name; desc++) {
768         const char *value;
769         QemuOpt *opt = qemu_opt_find(opts, desc->name);
770 
771         value = opt ? opt->str : desc->def_value_str;
772         if (!value) {
773             continue;
774         }
775         if (desc->type == QEMU_OPT_STRING) {
776             printf("%s%s=", sep, desc->name);
777             escaped_print(value);
778         } else if ((desc->type == QEMU_OPT_SIZE ||
779                     desc->type == QEMU_OPT_NUMBER) && opt) {
780             printf("%s%s=%" PRId64, sep, desc->name, opt->value.uint);
781         } else {
782             printf("%s%s=%s", sep, desc->name, value);
783         }
784         sep = separator;
785     }
786 }
787 
788 static void opts_do_parse(QemuOpts *opts, const char *params,
789                           const char *firstname, bool prepend, Error **errp)
790 {
791     char option[128], value[1024];
792     const char *p,*pe,*pc;
793     Error *local_err = NULL;
794 
795     for (p = params; *p != '\0'; p++) {
796         pe = strchr(p, '=');
797         pc = strchr(p, ',');
798         if (!pe || (pc && pc < pe)) {
799             /* found "foo,more" */
800             if (p == params && firstname) {
801                 /* implicitly named first option */
802                 pstrcpy(option, sizeof(option), firstname);
803                 p = get_opt_value(value, sizeof(value), p);
804             } else {
805                 /* option without value, probably a flag */
806                 p = get_opt_name(option, sizeof(option), p, ',');
807                 if (strncmp(option, "no", 2) == 0) {
808                     memmove(option, option+2, strlen(option+2)+1);
809                     pstrcpy(value, sizeof(value), "off");
810                 } else {
811                     pstrcpy(value, sizeof(value), "on");
812                 }
813             }
814         } else {
815             /* found "foo=bar,more" */
816             p = get_opt_name(option, sizeof(option), p, '=');
817             if (*p != '=') {
818                 break;
819             }
820             p++;
821             p = get_opt_value(value, sizeof(value), p);
822         }
823         if (strcmp(option, "id") != 0) {
824             /* store and parse */
825             opt_set(opts, option, value, prepend, &local_err);
826             if (local_err) {
827                 error_propagate(errp, local_err);
828                 return;
829             }
830         }
831         if (*p != ',') {
832             break;
833         }
834     }
835 }
836 
837 /**
838  * Store options parsed from @params into @opts.
839  * If @firstname is non-null, the first key=value in @params may omit
840  * key=, and is treated as if key was @firstname.
841  * On error, store an error object through @errp if non-null.
842  */
843 void qemu_opts_do_parse(QemuOpts *opts, const char *params,
844                        const char *firstname, Error **errp)
845 {
846     opts_do_parse(opts, params, firstname, false, errp);
847 }
848 
849 static QemuOpts *opts_parse(QemuOptsList *list, const char *params,
850                             bool permit_abbrev, bool defaults, Error **errp)
851 {
852     const char *firstname;
853     char value[1024], *id = NULL;
854     const char *p;
855     QemuOpts *opts;
856     Error *local_err = NULL;
857 
858     assert(!permit_abbrev || list->implied_opt_name);
859     firstname = permit_abbrev ? list->implied_opt_name : NULL;
860 
861     if (strncmp(params, "id=", 3) == 0) {
862         get_opt_value(value, sizeof(value), params+3);
863         id = value;
864     } else if ((p = strstr(params, ",id=")) != NULL) {
865         get_opt_value(value, sizeof(value), p+4);
866         id = value;
867     }
868 
869     /*
870      * This code doesn't work for defaults && !list->merge_lists: when
871      * params has no id=, and list has an element with !opts->id, it
872      * appends a new element instead of returning the existing opts.
873      * However, we got no use for this case.  Guard against possible
874      * (if unlikely) future misuse:
875      */
876     assert(!defaults || list->merge_lists);
877     opts = qemu_opts_create(list, id, !defaults, &local_err);
878     if (opts == NULL) {
879         error_propagate(errp, local_err);
880         return NULL;
881     }
882 
883     opts_do_parse(opts, params, firstname, defaults, &local_err);
884     if (local_err) {
885         error_propagate(errp, local_err);
886         qemu_opts_del(opts);
887         return NULL;
888     }
889 
890     return opts;
891 }
892 
893 /**
894  * Create a QemuOpts in @list and with options parsed from @params.
895  * If @permit_abbrev, the first key=value in @params may omit key=,
896  * and is treated as if key was @list->implied_opt_name.
897  * On error, store an error object through @errp if non-null.
898  * Return the new QemuOpts on success, null pointer on error.
899  */
900 QemuOpts *qemu_opts_parse(QemuOptsList *list, const char *params,
901                           bool permit_abbrev, Error **errp)
902 {
903     return opts_parse(list, params, permit_abbrev, false, errp);
904 }
905 
906 /**
907  * Create a QemuOpts in @list and with options parsed from @params.
908  * If @permit_abbrev, the first key=value in @params may omit key=,
909  * and is treated as if key was @list->implied_opt_name.
910  * Report errors with error_report_err().  This is inappropriate in
911  * QMP context.  Do not use this function there!
912  * Return the new QemuOpts on success, null pointer on error.
913  */
914 QemuOpts *qemu_opts_parse_noisily(QemuOptsList *list, const char *params,
915                                   bool permit_abbrev)
916 {
917     Error *err = NULL;
918     QemuOpts *opts;
919 
920     opts = opts_parse(list, params, permit_abbrev, false, &err);
921     if (err) {
922         error_report_err(err);
923     }
924     return opts;
925 }
926 
927 void qemu_opts_set_defaults(QemuOptsList *list, const char *params,
928                             int permit_abbrev)
929 {
930     QemuOpts *opts;
931 
932     opts = opts_parse(list, params, permit_abbrev, true, NULL);
933     assert(opts);
934 }
935 
936 typedef struct OptsFromQDictState {
937     QemuOpts *opts;
938     Error **errp;
939 } OptsFromQDictState;
940 
941 static void qemu_opts_from_qdict_1(const char *key, QObject *obj, void *opaque)
942 {
943     OptsFromQDictState *state = opaque;
944     char buf[32];
945     const char *value;
946     int n;
947 
948     if (!strcmp(key, "id") || *state->errp) {
949         return;
950     }
951 
952     switch (qobject_type(obj)) {
953     case QTYPE_QSTRING:
954         value = qstring_get_str(qobject_to_qstring(obj));
955         break;
956     case QTYPE_QINT:
957         n = snprintf(buf, sizeof(buf), "%" PRId64,
958                      qint_get_int(qobject_to_qint(obj)));
959         assert(n < sizeof(buf));
960         value = buf;
961         break;
962     case QTYPE_QFLOAT:
963         n = snprintf(buf, sizeof(buf), "%.17g",
964                      qfloat_get_double(qobject_to_qfloat(obj)));
965         assert(n < sizeof(buf));
966         value = buf;
967         break;
968     case QTYPE_QBOOL:
969         pstrcpy(buf, sizeof(buf),
970                 qbool_get_bool(qobject_to_qbool(obj)) ? "on" : "off");
971         value = buf;
972         break;
973     default:
974         return;
975     }
976 
977     qemu_opt_set(state->opts, key, value, state->errp);
978 }
979 
980 /*
981  * Create QemuOpts from a QDict.
982  * Use value of key "id" as ID if it exists and is a QString.
983  * Only QStrings, QInts, QFloats and QBools are copied.  Entries with
984  * other types are silently ignored.
985  */
986 QemuOpts *qemu_opts_from_qdict(QemuOptsList *list, const QDict *qdict,
987                                Error **errp)
988 {
989     OptsFromQDictState state;
990     Error *local_err = NULL;
991     QemuOpts *opts;
992 
993     opts = qemu_opts_create(list, qdict_get_try_str(qdict, "id"), 1,
994                             &local_err);
995     if (local_err) {
996         error_propagate(errp, local_err);
997         return NULL;
998     }
999 
1000     assert(opts != NULL);
1001 
1002     state.errp = &local_err;
1003     state.opts = opts;
1004     qdict_iter(qdict, qemu_opts_from_qdict_1, &state);
1005     if (local_err) {
1006         error_propagate(errp, local_err);
1007         qemu_opts_del(opts);
1008         return NULL;
1009     }
1010 
1011     return opts;
1012 }
1013 
1014 /*
1015  * Adds all QDict entries to the QemuOpts that can be added and removes them
1016  * from the QDict. When this function returns, the QDict contains only those
1017  * entries that couldn't be added to the QemuOpts.
1018  */
1019 void qemu_opts_absorb_qdict(QemuOpts *opts, QDict *qdict, Error **errp)
1020 {
1021     const QDictEntry *entry, *next;
1022 
1023     entry = qdict_first(qdict);
1024 
1025     while (entry != NULL) {
1026         Error *local_err = NULL;
1027         OptsFromQDictState state = {
1028             .errp = &local_err,
1029             .opts = opts,
1030         };
1031 
1032         next = qdict_next(qdict, entry);
1033 
1034         if (find_desc_by_name(opts->list->desc, entry->key)) {
1035             qemu_opts_from_qdict_1(entry->key, entry->value, &state);
1036             if (local_err) {
1037                 error_propagate(errp, local_err);
1038                 return;
1039             } else {
1040                 qdict_del(qdict, entry->key);
1041             }
1042         }
1043 
1044         entry = next;
1045     }
1046 }
1047 
1048 /*
1049  * Convert from QemuOpts to QDict.
1050  * The QDict values are of type QString.
1051  * TODO We'll want to use types appropriate for opt->desc->type, but
1052  * this is enough for now.
1053  */
1054 QDict *qemu_opts_to_qdict(QemuOpts *opts, QDict *qdict)
1055 {
1056     QemuOpt *opt;
1057     QObject *val;
1058 
1059     if (!qdict) {
1060         qdict = qdict_new();
1061     }
1062     if (opts->id) {
1063         qdict_put(qdict, "id", qstring_from_str(opts->id));
1064     }
1065     QTAILQ_FOREACH(opt, &opts->head, next) {
1066         val = QOBJECT(qstring_from_str(opt->str));
1067         qdict_put_obj(qdict, opt->name, val);
1068     }
1069     return qdict;
1070 }
1071 
1072 /* Validate parsed opts against descriptions where no
1073  * descriptions were provided in the QemuOptsList.
1074  */
1075 void qemu_opts_validate(QemuOpts *opts, const QemuOptDesc *desc, Error **errp)
1076 {
1077     QemuOpt *opt;
1078     Error *local_err = NULL;
1079 
1080     assert(opts_accepts_any(opts));
1081 
1082     QTAILQ_FOREACH(opt, &opts->head, next) {
1083         opt->desc = find_desc_by_name(desc, opt->name);
1084         if (!opt->desc) {
1085             error_setg(errp, QERR_INVALID_PARAMETER, opt->name);
1086             return;
1087         }
1088 
1089         qemu_opt_parse(opt, &local_err);
1090         if (local_err) {
1091             error_propagate(errp, local_err);
1092             return;
1093         }
1094     }
1095 }
1096 
1097 /**
1098  * For each member of @list, call @func(@opaque, member, @errp).
1099  * Call it with the current location temporarily set to the member's.
1100  * @func() may store an Error through @errp, but must return non-zero then.
1101  * When @func() returns non-zero, break the loop and return that value.
1102  * Return zero when the loop completes.
1103  */
1104 int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func,
1105                       void *opaque, Error **errp)
1106 {
1107     Location loc;
1108     QemuOpts *opts;
1109     int rc;
1110 
1111     loc_push_none(&loc);
1112     QTAILQ_FOREACH(opts, &list->head, next) {
1113         loc_restore(&opts->loc);
1114         rc = func(opaque, opts, errp);
1115         if (rc) {
1116             return rc;
1117         }
1118         assert(!errp || !*errp);
1119     }
1120     loc_pop(&loc);
1121     return 0;
1122 }
1123 
1124 static size_t count_opts_list(QemuOptsList *list)
1125 {
1126     QemuOptDesc *desc = NULL;
1127     size_t num_opts = 0;
1128 
1129     if (!list) {
1130         return 0;
1131     }
1132 
1133     desc = list->desc;
1134     while (desc && desc->name) {
1135         num_opts++;
1136         desc++;
1137     }
1138 
1139     return num_opts;
1140 }
1141 
1142 void qemu_opts_free(QemuOptsList *list)
1143 {
1144     g_free(list);
1145 }
1146 
1147 /* Realloc dst option list and append options from an option list (list)
1148  * to it. dst could be NULL or a malloced list.
1149  * The lifetime of dst must be shorter than the input list because the
1150  * QemuOptDesc->name, ->help, and ->def_value_str strings are shared.
1151  */
1152 QemuOptsList *qemu_opts_append(QemuOptsList *dst,
1153                                QemuOptsList *list)
1154 {
1155     size_t num_opts, num_dst_opts;
1156     QemuOptDesc *desc;
1157     bool need_init = false;
1158     bool need_head_update;
1159 
1160     if (!list) {
1161         return dst;
1162     }
1163 
1164     /* If dst is NULL, after realloc, some area of dst should be initialized
1165      * before adding options to it.
1166      */
1167     if (!dst) {
1168         need_init = true;
1169         need_head_update = true;
1170     } else {
1171         /* Moreover, even if dst is not NULL, the realloc may move it to a
1172          * different address in which case we may get a stale tail pointer
1173          * in dst->head. */
1174         need_head_update = QTAILQ_EMPTY(&dst->head);
1175     }
1176 
1177     num_opts = count_opts_list(dst);
1178     num_dst_opts = num_opts;
1179     num_opts += count_opts_list(list);
1180     dst = g_realloc(dst, sizeof(QemuOptsList) +
1181                     (num_opts + 1) * sizeof(QemuOptDesc));
1182     if (need_init) {
1183         dst->name = NULL;
1184         dst->implied_opt_name = NULL;
1185         dst->merge_lists = false;
1186     }
1187     if (need_head_update) {
1188         QTAILQ_INIT(&dst->head);
1189     }
1190     dst->desc[num_dst_opts].name = NULL;
1191 
1192     /* append list->desc to dst->desc */
1193     if (list) {
1194         desc = list->desc;
1195         while (desc && desc->name) {
1196             if (find_desc_by_name(dst->desc, desc->name) == NULL) {
1197                 dst->desc[num_dst_opts++] = *desc;
1198                 dst->desc[num_dst_opts].name = NULL;
1199             }
1200             desc++;
1201         }
1202     }
1203 
1204     return dst;
1205 }
1206