xref: /openbmc/qemu/util/qemu-option.c (revision 3c4b89c3)
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 "qemu/osdep.h"
27 
28 #include "qapi/error.h"
29 #include "qemu/error-report.h"
30 #include "qapi/qmp/qbool.h"
31 #include "qapi/qmp/qdict.h"
32 #include "qapi/qmp/qnum.h"
33 #include "qapi/qmp/qstring.h"
34 #include "qapi/qmp/qerror.h"
35 #include "qemu/option_int.h"
36 #include "qemu/cutils.h"
37 #include "qemu/id.h"
38 #include "qemu/help_option.h"
39 
40 /*
41  * Extracts the name of an option from the parameter string (p points at the
42  * first byte of the option name)
43  *
44  * The option name is delimited by delim (usually , or =) or the string end
45  * and is copied into option. The caller is responsible for free'ing option
46  * when no longer required.
47  *
48  * The return value is the position of the delimiter/zero byte after the option
49  * name in p.
50  */
51 static const char *get_opt_name(const char *p, char **option, char delim)
52 {
53     char *offset = strchr(p, delim);
54 
55     if (offset) {
56         *option = g_strndup(p, offset - p);
57         return offset;
58     } else {
59         *option = g_strdup(p);
60         return p + strlen(p);
61     }
62 }
63 
64 /*
65  * Extracts the value of an option from the parameter string p (p points at the
66  * first byte of the option value)
67  *
68  * This function is comparable to get_opt_name with the difference that the
69  * delimiter is fixed to be comma which starts a new option. To specify an
70  * option value that contains commas, double each comma.
71  */
72 const char *get_opt_value(const char *p, char **value)
73 {
74     size_t capacity = 0, length;
75     const char *offset;
76 
77     *value = NULL;
78     while (1) {
79         offset = qemu_strchrnul(p, ',');
80         length = offset - p;
81         if (*offset != '\0' && *(offset + 1) == ',') {
82             length++;
83         }
84         *value = g_renew(char, *value, capacity + length + 1);
85         strncpy(*value + capacity, p, length);
86         (*value)[capacity + length] = '\0';
87         capacity += length;
88         if (*offset == '\0' ||
89             *(offset + 1) != ',') {
90             break;
91         }
92 
93         p += (offset - p) + 2;
94     }
95 
96     return offset;
97 }
98 
99 static bool parse_option_bool(const char *name, const char *value, bool *ret,
100                               Error **errp)
101 {
102     if (!strcmp(value, "on")) {
103         *ret = 1;
104     } else if (!strcmp(value, "off")) {
105         *ret = 0;
106     } else {
107         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
108                    name, "'on' or 'off'");
109         return false;
110     }
111     return true;
112 }
113 
114 static bool parse_option_number(const char *name, const char *value,
115                                 uint64_t *ret, Error **errp)
116 {
117     uint64_t number;
118     int err;
119 
120     err = qemu_strtou64(value, NULL, 0, &number);
121     if (err == -ERANGE) {
122         error_setg(errp, "Value '%s' is too large for parameter '%s'",
123                    value, name);
124         return false;
125     }
126     if (err) {
127         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
128         return false;
129     }
130     *ret = number;
131     return true;
132 }
133 
134 static const QemuOptDesc *find_desc_by_name(const QemuOptDesc *desc,
135                                             const char *name)
136 {
137     int i;
138 
139     for (i = 0; desc[i].name != NULL; i++) {
140         if (strcmp(desc[i].name, name) == 0) {
141             return &desc[i];
142         }
143     }
144 
145     return NULL;
146 }
147 
148 static const char *find_default_by_name(QemuOpts *opts, const char *name)
149 {
150     const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
151 
152     return desc ? desc->def_value_str : NULL;
153 }
154 
155 bool parse_option_size(const char *name, const char *value,
156                        uint64_t *ret, Error **errp)
157 {
158     uint64_t size;
159     int err;
160 
161     err = qemu_strtosz(value, NULL, &size);
162     if (err == -ERANGE) {
163         error_setg(errp, "Value '%s' is out of range for parameter '%s'",
164                    value, name);
165         return false;
166     }
167     if (err) {
168         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name,
169                    "a non-negative number below 2^64");
170         error_append_hint(errp, "Optional suffix k, M, G, T, P or E means"
171                           " kilo-, mega-, giga-, tera-, peta-\n"
172                           "and exabytes, respectively.\n");
173         return false;
174     }
175     *ret = size;
176     return true;
177 }
178 
179 static const char *opt_type_to_string(enum QemuOptType type)
180 {
181     switch (type) {
182     case QEMU_OPT_STRING:
183         return "str";
184     case QEMU_OPT_BOOL:
185         return "bool (on/off)";
186     case QEMU_OPT_NUMBER:
187         return "num";
188     case QEMU_OPT_SIZE:
189         return "size";
190     }
191 
192     g_assert_not_reached();
193 }
194 
195 /**
196  * Print the list of options available in the given list.  If
197  * @print_caption is true, a caption (including the list name, if it
198  * exists) is printed.  The options itself will be indented, so
199  * @print_caption should only be set to false if the caller prints its
200  * own custom caption (so that the indentation makes sense).
201  */
202 void qemu_opts_print_help(QemuOptsList *list, bool print_caption)
203 {
204     QemuOptDesc *desc;
205     int i;
206     GPtrArray *array = g_ptr_array_new();
207 
208     assert(list);
209     desc = list->desc;
210     while (desc && desc->name) {
211         GString *str = g_string_new(NULL);
212         g_string_append_printf(str, "  %s=<%s>", desc->name,
213                                opt_type_to_string(desc->type));
214         if (desc->help) {
215             if (str->len < 24) {
216                 g_string_append_printf(str, "%*s", 24 - (int)str->len, "");
217             }
218             g_string_append_printf(str, " - %s", desc->help);
219         }
220         g_ptr_array_add(array, g_string_free(str, false));
221         desc++;
222     }
223 
224     g_ptr_array_sort(array, (GCompareFunc)qemu_pstrcmp0);
225     if (print_caption && array->len > 0) {
226         if (list->name) {
227             printf("%s options:\n", list->name);
228         } else {
229             printf("Options:\n");
230         }
231     } else if (array->len == 0) {
232         if (list->name) {
233             printf("There are no options for %s.\n", list->name);
234         } else {
235             printf("No options available.\n");
236         }
237     }
238     for (i = 0; i < array->len; i++) {
239         printf("%s\n", (char *)array->pdata[i]);
240     }
241     g_ptr_array_set_free_func(array, g_free);
242     g_ptr_array_free(array, true);
243 
244 }
245 /* ------------------------------------------------------------------ */
246 
247 QemuOpt *qemu_opt_find(QemuOpts *opts, const char *name)
248 {
249     QemuOpt *opt;
250 
251     QTAILQ_FOREACH_REVERSE(opt, &opts->head, next) {
252         if (strcmp(opt->name, name) != 0)
253             continue;
254         return opt;
255     }
256     return NULL;
257 }
258 
259 static void qemu_opt_del(QemuOpt *opt)
260 {
261     QTAILQ_REMOVE(&opt->opts->head, opt, next);
262     g_free(opt->name);
263     g_free(opt->str);
264     g_free(opt);
265 }
266 
267 /* qemu_opt_set allows many settings for the same option.
268  * This function deletes all settings for an option.
269  */
270 static void qemu_opt_del_all(QemuOpts *opts, const char *name)
271 {
272     QemuOpt *opt, *next_opt;
273 
274     QTAILQ_FOREACH_SAFE(opt, &opts->head, next, next_opt) {
275         if (!strcmp(opt->name, name)) {
276             qemu_opt_del(opt);
277         }
278     }
279 }
280 
281 const char *qemu_opt_get(QemuOpts *opts, const char *name)
282 {
283     QemuOpt *opt;
284 
285     if (opts == NULL) {
286         return NULL;
287     }
288 
289     opt = qemu_opt_find(opts, name);
290     if (!opt) {
291         return find_default_by_name(opts, name);
292     }
293 
294     return opt->str;
295 }
296 
297 void qemu_opt_iter_init(QemuOptsIter *iter, QemuOpts *opts, const char *name)
298 {
299     iter->opts = opts;
300     iter->opt = QTAILQ_FIRST(&opts->head);
301     iter->name = name;
302 }
303 
304 const char *qemu_opt_iter_next(QemuOptsIter *iter)
305 {
306     QemuOpt *ret = iter->opt;
307     if (iter->name) {
308         while (ret && !g_str_equal(iter->name, ret->name)) {
309             ret = QTAILQ_NEXT(ret, next);
310         }
311     }
312     iter->opt = ret ? QTAILQ_NEXT(ret, next) : NULL;
313     return ret ? ret->str : NULL;
314 }
315 
316 /* Get a known option (or its default) and remove it from the list
317  * all in one action. Return a malloced string of the option value.
318  * Result must be freed by caller with g_free().
319  */
320 char *qemu_opt_get_del(QemuOpts *opts, const char *name)
321 {
322     QemuOpt *opt;
323     char *str;
324 
325     if (opts == NULL) {
326         return NULL;
327     }
328 
329     opt = qemu_opt_find(opts, name);
330     if (!opt) {
331         return g_strdup(find_default_by_name(opts, name));
332     }
333     str = opt->str;
334     opt->str = NULL;
335     qemu_opt_del_all(opts, name);
336     return str;
337 }
338 
339 bool qemu_opt_has_help_opt(QemuOpts *opts)
340 {
341     QemuOpt *opt;
342 
343     QTAILQ_FOREACH_REVERSE(opt, &opts->head, next) {
344         if (is_help_option(opt->name)) {
345             return true;
346         }
347     }
348     return false;
349 }
350 
351 static bool qemu_opt_get_bool_helper(QemuOpts *opts, const char *name,
352                                      bool defval, bool del)
353 {
354     QemuOpt *opt;
355     const char *def_val;
356     bool ret = defval;
357 
358     if (opts == NULL) {
359         return ret;
360     }
361 
362     opt = qemu_opt_find(opts, name);
363     if (opt == NULL) {
364         def_val = find_default_by_name(opts, name);
365         if (def_val) {
366             parse_option_bool(name, def_val, &ret, &error_abort);
367         }
368         return ret;
369     }
370     assert(opt->desc && opt->desc->type == QEMU_OPT_BOOL);
371     ret = opt->value.boolean;
372     if (del) {
373         qemu_opt_del_all(opts, name);
374     }
375     return ret;
376 }
377 
378 bool qemu_opt_get_bool(QemuOpts *opts, const char *name, bool defval)
379 {
380     return qemu_opt_get_bool_helper(opts, name, defval, false);
381 }
382 
383 bool qemu_opt_get_bool_del(QemuOpts *opts, const char *name, bool defval)
384 {
385     return qemu_opt_get_bool_helper(opts, name, defval, true);
386 }
387 
388 static uint64_t qemu_opt_get_number_helper(QemuOpts *opts, const char *name,
389                                            uint64_t defval, bool del)
390 {
391     QemuOpt *opt;
392     const char *def_val;
393     uint64_t ret = defval;
394 
395     if (opts == NULL) {
396         return ret;
397     }
398 
399     opt = qemu_opt_find(opts, name);
400     if (opt == NULL) {
401         def_val = find_default_by_name(opts, name);
402         if (def_val) {
403             parse_option_number(name, def_val, &ret, &error_abort);
404         }
405         return ret;
406     }
407     assert(opt->desc && opt->desc->type == QEMU_OPT_NUMBER);
408     ret = opt->value.uint;
409     if (del) {
410         qemu_opt_del_all(opts, name);
411     }
412     return ret;
413 }
414 
415 uint64_t qemu_opt_get_number(QemuOpts *opts, const char *name, uint64_t defval)
416 {
417     return qemu_opt_get_number_helper(opts, name, defval, false);
418 }
419 
420 uint64_t qemu_opt_get_number_del(QemuOpts *opts, const char *name,
421                                  uint64_t defval)
422 {
423     return qemu_opt_get_number_helper(opts, name, defval, true);
424 }
425 
426 static uint64_t qemu_opt_get_size_helper(QemuOpts *opts, const char *name,
427                                          uint64_t defval, bool del)
428 {
429     QemuOpt *opt;
430     const char *def_val;
431     uint64_t ret = defval;
432 
433     if (opts == NULL) {
434         return ret;
435     }
436 
437     opt = qemu_opt_find(opts, name);
438     if (opt == NULL) {
439         def_val = find_default_by_name(opts, name);
440         if (def_val) {
441             parse_option_size(name, def_val, &ret, &error_abort);
442         }
443         return ret;
444     }
445     assert(opt->desc && opt->desc->type == QEMU_OPT_SIZE);
446     ret = opt->value.uint;
447     if (del) {
448         qemu_opt_del_all(opts, name);
449     }
450     return ret;
451 }
452 
453 uint64_t qemu_opt_get_size(QemuOpts *opts, const char *name, uint64_t defval)
454 {
455     return qemu_opt_get_size_helper(opts, name, defval, false);
456 }
457 
458 uint64_t qemu_opt_get_size_del(QemuOpts *opts, const char *name,
459                                uint64_t defval)
460 {
461     return qemu_opt_get_size_helper(opts, name, defval, true);
462 }
463 
464 static bool qemu_opt_parse(QemuOpt *opt, Error **errp)
465 {
466     if (opt->desc == NULL)
467         return true;
468 
469     switch (opt->desc->type) {
470     case QEMU_OPT_STRING:
471         /* nothing */
472         return true;
473     case QEMU_OPT_BOOL:
474         return parse_option_bool(opt->name, opt->str, &opt->value.boolean,
475                                  errp);
476     case QEMU_OPT_NUMBER:
477         return parse_option_number(opt->name, opt->str, &opt->value.uint,
478                                    errp);
479     case QEMU_OPT_SIZE:
480         return parse_option_size(opt->name, opt->str, &opt->value.uint,
481                                  errp);
482     default:
483         abort();
484     }
485 }
486 
487 static bool opts_accepts_any(const QemuOpts *opts)
488 {
489     return opts->list->desc[0].name == NULL;
490 }
491 
492 int qemu_opt_unset(QemuOpts *opts, const char *name)
493 {
494     QemuOpt *opt = qemu_opt_find(opts, name);
495 
496     assert(opts_accepts_any(opts));
497 
498     if (opt == NULL) {
499         return -1;
500     } else {
501         qemu_opt_del(opt);
502         return 0;
503     }
504 }
505 
506 static QemuOpt *opt_create(QemuOpts *opts, const char *name, char *value,
507                            bool prepend)
508 {
509     QemuOpt *opt = g_malloc0(sizeof(*opt));
510 
511     opt->name = g_strdup(name);
512     opt->str = value;
513     opt->opts = opts;
514     if (prepend) {
515         QTAILQ_INSERT_HEAD(&opts->head, opt, next);
516     } else {
517         QTAILQ_INSERT_TAIL(&opts->head, opt, next);
518     }
519 
520     return opt;
521 }
522 
523 static bool opt_validate(QemuOpt *opt, bool *help_wanted,
524                          Error **errp)
525 {
526     const QemuOptDesc *desc;
527     Error *local_err = NULL;
528 
529     desc = find_desc_by_name(opt->opts->list->desc, opt->name);
530     if (!desc && !opts_accepts_any(opt->opts)) {
531         error_setg(errp, QERR_INVALID_PARAMETER, opt->name);
532         if (help_wanted && is_help_option(opt->name)) {
533             *help_wanted = true;
534         }
535         return false;
536     }
537 
538     opt->desc = desc;
539     if (!qemu_opt_parse(opt, &local_err)) {
540         error_propagate(errp, local_err);
541         return false;
542     }
543 
544     return true;
545 }
546 
547 bool qemu_opt_set(QemuOpts *opts, const char *name, const char *value,
548                   Error **errp)
549 {
550     QemuOpt *opt = opt_create(opts, name, g_strdup(value), false);
551 
552     if (!opt_validate(opt, NULL, errp)) {
553         qemu_opt_del(opt);
554         return false;
555     }
556     return true;
557 }
558 
559 bool qemu_opt_set_bool(QemuOpts *opts, const char *name, bool val,
560                        Error **errp)
561 {
562     QemuOpt *opt;
563     const QemuOptDesc *desc;
564 
565     desc = find_desc_by_name(opts->list->desc, name);
566     if (!desc && !opts_accepts_any(opts)) {
567         error_setg(errp, QERR_INVALID_PARAMETER, name);
568         return false;
569     }
570 
571     opt = g_malloc0(sizeof(*opt));
572     opt->name = g_strdup(name);
573     opt->opts = opts;
574     opt->desc = desc;
575     opt->value.boolean = !!val;
576     opt->str = g_strdup(val ? "on" : "off");
577     QTAILQ_INSERT_TAIL(&opts->head, opt, next);
578     return true;
579 }
580 
581 bool qemu_opt_set_number(QemuOpts *opts, const char *name, int64_t val,
582                          Error **errp)
583 {
584     QemuOpt *opt;
585     const QemuOptDesc *desc;
586 
587     desc = find_desc_by_name(opts->list->desc, name);
588     if (!desc && !opts_accepts_any(opts)) {
589         error_setg(errp, QERR_INVALID_PARAMETER, name);
590         return false;
591     }
592 
593     opt = g_malloc0(sizeof(*opt));
594     opt->name = g_strdup(name);
595     opt->opts = opts;
596     opt->desc = desc;
597     opt->value.uint = val;
598     opt->str = g_strdup_printf("%" PRId64, val);
599     QTAILQ_INSERT_TAIL(&opts->head, opt, next);
600     return true;
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.\n");
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 bool qemu_opts_set(QemuOptsList *list, const char *id,
692                    const char *name, const char *value, Error **errp)
693 {
694     QemuOpts *opts;
695 
696     opts = qemu_opts_create(list, id, 1, errp);
697     if (!opts) {
698         return false;
699     }
700     return qemu_opt_set(opts, name, value, errp);
701 }
702 
703 const char *qemu_opts_id(QemuOpts *opts)
704 {
705     return opts->id;
706 }
707 
708 /* The id string will be g_free()d by qemu_opts_del */
709 void qemu_opts_set_id(QemuOpts *opts, char *id)
710 {
711     opts->id = id;
712 }
713 
714 void qemu_opts_del(QemuOpts *opts)
715 {
716     QemuOpt *opt;
717 
718     if (opts == NULL) {
719         return;
720     }
721 
722     for (;;) {
723         opt = QTAILQ_FIRST(&opts->head);
724         if (opt == NULL)
725             break;
726         qemu_opt_del(opt);
727     }
728     QTAILQ_REMOVE(&opts->list->head, opts, next);
729     g_free(opts->id);
730     g_free(opts);
731 }
732 
733 /* print value, escaping any commas in value */
734 static void escaped_print(const char *value)
735 {
736     const char *ptr;
737 
738     for (ptr = value; *ptr; ++ptr) {
739         if (*ptr == ',') {
740             putchar(',');
741         }
742         putchar(*ptr);
743     }
744 }
745 
746 void qemu_opts_print(QemuOpts *opts, const char *separator)
747 {
748     QemuOpt *opt;
749     QemuOptDesc *desc = opts->list->desc;
750     const char *sep = "";
751 
752     if (opts->id) {
753         printf("id=%s", opts->id); /* passed id_wellformed -> no commas */
754         sep = separator;
755     }
756 
757     if (desc[0].name == NULL) {
758         QTAILQ_FOREACH(opt, &opts->head, next) {
759             printf("%s%s=", sep, opt->name);
760             escaped_print(opt->str);
761             sep = separator;
762         }
763         return;
764     }
765     for (; desc && desc->name; desc++) {
766         const char *value;
767         opt = qemu_opt_find(opts, desc->name);
768 
769         value = opt ? opt->str : desc->def_value_str;
770         if (!value) {
771             continue;
772         }
773         if (desc->type == QEMU_OPT_STRING) {
774             printf("%s%s=", sep, desc->name);
775             escaped_print(value);
776         } else if ((desc->type == QEMU_OPT_SIZE ||
777                     desc->type == QEMU_OPT_NUMBER) && opt) {
778             printf("%s%s=%" PRId64, sep, desc->name, opt->value.uint);
779         } else {
780             printf("%s%s=%s", sep, desc->name, value);
781         }
782         sep = separator;
783     }
784 }
785 
786 static const char *get_opt_name_value(const char *params,
787                                       const char *firstname,
788                                       char **name, char **value)
789 {
790     const char *p, *pe, *pc;
791 
792     pe = strchr(params, '=');
793     pc = strchr(params, ',');
794 
795     if (!pe || (pc && pc < pe)) {
796         /* found "foo,more" */
797         if (firstname) {
798             /* implicitly named first option */
799             *name = g_strdup(firstname);
800             p = get_opt_value(params, value);
801         } else {
802             /* option without value, must be a flag */
803             p = get_opt_name(params, name, ',');
804             if (strncmp(*name, "no", 2) == 0) {
805                 memmove(*name, *name + 2, strlen(*name + 2) + 1);
806                 *value = g_strdup("off");
807             } else {
808                 *value = g_strdup("on");
809             }
810         }
811     } else {
812         /* found "foo=bar,more" */
813         p = get_opt_name(params, name, '=');
814         assert(*p == '=');
815         p++;
816         p = get_opt_value(p, value);
817     }
818 
819     assert(!*p || *p == ',');
820     if (*p == ',') {
821         p++;
822     }
823     return p;
824 }
825 
826 static bool opts_do_parse(QemuOpts *opts, const char *params,
827                           const char *firstname, bool prepend,
828                           bool *help_wanted, Error **errp)
829 {
830     char *option, *value;
831     const char *p;
832     QemuOpt *opt;
833 
834     for (p = params; *p;) {
835         p = get_opt_name_value(p, firstname, &option, &value);
836         firstname = NULL;
837 
838         if (!strcmp(option, "id")) {
839             g_free(option);
840             g_free(value);
841             continue;
842         }
843 
844         opt = opt_create(opts, option, value, prepend);
845         g_free(option);
846         if (!opt_validate(opt, help_wanted, errp)) {
847             qemu_opt_del(opt);
848             return false;
849         }
850     }
851 
852     return true;
853 }
854 
855 static char *opts_parse_id(const char *params)
856 {
857     const char *p;
858     char *name, *value;
859 
860     for (p = params; *p;) {
861         p = get_opt_name_value(p, NULL, &name, &value);
862         if (!strcmp(name, "id")) {
863             g_free(name);
864             return value;
865         }
866         g_free(name);
867         g_free(value);
868     }
869 
870     return NULL;
871 }
872 
873 bool has_help_option(const char *params)
874 {
875     const char *p;
876     char *name, *value;
877     bool ret;
878 
879     for (p = params; *p;) {
880         p = get_opt_name_value(p, NULL, &name, &value);
881         ret = is_help_option(name);
882         g_free(name);
883         g_free(value);
884         if (ret) {
885             return true;
886         }
887     }
888 
889     return false;
890 }
891 
892 /**
893  * Store options parsed from @params into @opts.
894  * If @firstname is non-null, the first key=value in @params may omit
895  * key=, and is treated as if key was @firstname.
896  * On error, store an error object through @errp if non-null.
897  */
898 bool qemu_opts_do_parse(QemuOpts *opts, const char *params,
899                        const char *firstname, Error **errp)
900 {
901     return opts_do_parse(opts, params, firstname, false, NULL, errp);
902 }
903 
904 static QemuOpts *opts_parse(QemuOptsList *list, const char *params,
905                             bool permit_abbrev, bool defaults,
906                             bool *help_wanted, Error **errp)
907 {
908     const char *firstname;
909     char *id = opts_parse_id(params);
910     QemuOpts *opts;
911     Error *local_err = NULL;
912 
913     assert(!permit_abbrev || list->implied_opt_name);
914     firstname = permit_abbrev ? list->implied_opt_name : NULL;
915 
916     /*
917      * This code doesn't work for defaults && !list->merge_lists: when
918      * params has no id=, and list has an element with !opts->id, it
919      * appends a new element instead of returning the existing opts.
920      * However, we got no use for this case.  Guard against possible
921      * (if unlikely) future misuse:
922      */
923     assert(!defaults || list->merge_lists);
924     opts = qemu_opts_create(list, id, !defaults, &local_err);
925     g_free(id);
926     if (opts == NULL) {
927         error_propagate(errp, local_err);
928         return NULL;
929     }
930 
931     if (!opts_do_parse(opts, params, firstname, defaults, help_wanted,
932                        &local_err)) {
933         error_propagate(errp, local_err);
934         qemu_opts_del(opts);
935         return NULL;
936     }
937 
938     return opts;
939 }
940 
941 /**
942  * Create a QemuOpts in @list and with options parsed from @params.
943  * If @permit_abbrev, the first key=value in @params may omit key=,
944  * and is treated as if key was @list->implied_opt_name.
945  * On error, store an error object through @errp if non-null.
946  * Return the new QemuOpts on success, null pointer on error.
947  */
948 QemuOpts *qemu_opts_parse(QemuOptsList *list, const char *params,
949                           bool permit_abbrev, Error **errp)
950 {
951     return opts_parse(list, params, permit_abbrev, false, NULL, errp);
952 }
953 
954 /**
955  * Create a QemuOpts in @list and with options parsed from @params.
956  * If @permit_abbrev, the first key=value in @params may omit key=,
957  * and is treated as if key was @list->implied_opt_name.
958  * Report errors with error_report_err().  This is inappropriate in
959  * QMP context.  Do not use this function there!
960  * Return the new QemuOpts on success, null pointer on error.
961  */
962 QemuOpts *qemu_opts_parse_noisily(QemuOptsList *list, const char *params,
963                                   bool permit_abbrev)
964 {
965     Error *err = NULL;
966     QemuOpts *opts;
967     bool help_wanted = false;
968 
969     opts = opts_parse(list, params, permit_abbrev, false, &help_wanted, &err);
970     if (err) {
971         if (help_wanted) {
972             qemu_opts_print_help(list, true);
973             error_free(err);
974         } else {
975             error_report_err(err);
976         }
977     }
978     return opts;
979 }
980 
981 void qemu_opts_set_defaults(QemuOptsList *list, const char *params,
982                             int permit_abbrev)
983 {
984     QemuOpts *opts;
985 
986     opts = opts_parse(list, params, permit_abbrev, true, NULL, NULL);
987     assert(opts);
988 }
989 
990 static bool qemu_opts_from_qdict_entry(QemuOpts *opts,
991                                        const QDictEntry *entry,
992                                        Error **errp)
993 {
994     const char *key = qdict_entry_key(entry);
995     QObject *obj = qdict_entry_value(entry);
996     char buf[32];
997     g_autofree char *tmp = NULL;
998     const char *value;
999 
1000     if (!strcmp(key, "id")) {
1001         return true;
1002     }
1003 
1004     switch (qobject_type(obj)) {
1005     case QTYPE_QSTRING:
1006         value = qstring_get_str(qobject_to(QString, obj));
1007         break;
1008     case QTYPE_QNUM:
1009         tmp = qnum_to_string(qobject_to(QNum, obj));
1010         value = tmp;
1011         break;
1012     case QTYPE_QBOOL:
1013         pstrcpy(buf, sizeof(buf),
1014                 qbool_get_bool(qobject_to(QBool, obj)) ? "on" : "off");
1015         value = buf;
1016         break;
1017     default:
1018         return true;
1019     }
1020 
1021     return qemu_opt_set(opts, key, value, errp);
1022 }
1023 
1024 /*
1025  * Create QemuOpts from a QDict.
1026  * Use value of key "id" as ID if it exists and is a QString.  Only
1027  * QStrings, QNums and QBools are copied.  Entries with other types
1028  * are silently ignored.
1029  */
1030 QemuOpts *qemu_opts_from_qdict(QemuOptsList *list, const QDict *qdict,
1031                                Error **errp)
1032 {
1033     Error *local_err = NULL;
1034     QemuOpts *opts;
1035     const QDictEntry *entry;
1036 
1037     opts = qemu_opts_create(list, qdict_get_try_str(qdict, "id"), 1, errp);
1038     if (!opts) {
1039         return NULL;
1040     }
1041 
1042     assert(opts != NULL);
1043 
1044     for (entry = qdict_first(qdict);
1045          entry;
1046          entry = qdict_next(qdict, entry)) {
1047         if (!qemu_opts_from_qdict_entry(opts, entry, &local_err)) {
1048             error_propagate(errp, local_err);
1049             qemu_opts_del(opts);
1050             return NULL;
1051         }
1052     }
1053 
1054     return opts;
1055 }
1056 
1057 /*
1058  * Adds all QDict entries to the QemuOpts that can be added and removes them
1059  * from the QDict. When this function returns, the QDict contains only those
1060  * entries that couldn't be added to the QemuOpts.
1061  */
1062 bool qemu_opts_absorb_qdict(QemuOpts *opts, QDict *qdict, Error **errp)
1063 {
1064     const QDictEntry *entry, *next;
1065 
1066     entry = qdict_first(qdict);
1067 
1068     while (entry != NULL) {
1069         Error *local_err = NULL;
1070 
1071         next = qdict_next(qdict, entry);
1072 
1073         if (find_desc_by_name(opts->list->desc, entry->key)) {
1074             if (!qemu_opts_from_qdict_entry(opts, entry, &local_err)) {
1075                 error_propagate(errp, local_err);
1076                 return false;
1077             }
1078             qdict_del(qdict, entry->key);
1079         }
1080 
1081         entry = next;
1082     }
1083 
1084     return true;
1085 }
1086 
1087 /*
1088  * Convert from QemuOpts to QDict. The QDict values are of type QString.
1089  *
1090  * If @list is given, only add those options to the QDict that are contained in
1091  * the list. If @del is true, any options added to the QDict are removed from
1092  * the QemuOpts, otherwise they remain there.
1093  *
1094  * If two options in @opts have the same name, they are processed in order
1095  * so that the last one wins (consistent with the reverse iteration in
1096  * qemu_opt_find()), but all of them are deleted if @del is true.
1097  *
1098  * TODO We'll want to use types appropriate for opt->desc->type, but
1099  * this is enough for now.
1100  */
1101 QDict *qemu_opts_to_qdict_filtered(QemuOpts *opts, QDict *qdict,
1102                                    QemuOptsList *list, bool del)
1103 {
1104     QemuOpt *opt, *next;
1105 
1106     if (!qdict) {
1107         qdict = qdict_new();
1108     }
1109     if (opts->id) {
1110         qdict_put_str(qdict, "id", opts->id);
1111     }
1112     QTAILQ_FOREACH_SAFE(opt, &opts->head, next, next) {
1113         if (list) {
1114             QemuOptDesc *desc;
1115             bool found = false;
1116             for (desc = list->desc; desc->name; desc++) {
1117                 if (!strcmp(desc->name, opt->name)) {
1118                     found = true;
1119                     break;
1120                 }
1121             }
1122             if (!found) {
1123                 continue;
1124             }
1125         }
1126         qdict_put_str(qdict, opt->name, opt->str);
1127         if (del) {
1128             qemu_opt_del(opt);
1129         }
1130     }
1131     return qdict;
1132 }
1133 
1134 /* Copy all options in a QemuOpts to the given QDict. See
1135  * qemu_opts_to_qdict_filtered() for details. */
1136 QDict *qemu_opts_to_qdict(QemuOpts *opts, QDict *qdict)
1137 {
1138     return qemu_opts_to_qdict_filtered(opts, qdict, NULL, false);
1139 }
1140 
1141 /* Validate parsed opts against descriptions where no
1142  * descriptions were provided in the QemuOptsList.
1143  */
1144 bool qemu_opts_validate(QemuOpts *opts, const QemuOptDesc *desc, Error **errp)
1145 {
1146     QemuOpt *opt;
1147     Error *local_err = NULL;
1148 
1149     assert(opts_accepts_any(opts));
1150 
1151     QTAILQ_FOREACH(opt, &opts->head, next) {
1152         opt->desc = find_desc_by_name(desc, opt->name);
1153         if (!opt->desc) {
1154             error_setg(errp, QERR_INVALID_PARAMETER, opt->name);
1155             return false;
1156         }
1157 
1158         if (!qemu_opt_parse(opt, &local_err)) {
1159             error_propagate(errp, local_err);
1160             return false;
1161         }
1162     }
1163 
1164     return true;
1165 }
1166 
1167 /**
1168  * For each member of @list, call @func(@opaque, member, @errp).
1169  * Call it with the current location temporarily set to the member's.
1170  * @func() may store an Error through @errp, but must return non-zero then.
1171  * When @func() returns non-zero, break the loop and return that value.
1172  * Return zero when the loop completes.
1173  */
1174 int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func,
1175                       void *opaque, Error **errp)
1176 {
1177     Location loc;
1178     QemuOpts *opts;
1179     int rc = 0;
1180 
1181     loc_push_none(&loc);
1182     QTAILQ_FOREACH(opts, &list->head, next) {
1183         loc_restore(&opts->loc);
1184         rc = func(opaque, opts, errp);
1185         if (rc) {
1186             break;
1187         }
1188         assert(!errp || !*errp);
1189     }
1190     loc_pop(&loc);
1191     return rc;
1192 }
1193 
1194 static size_t count_opts_list(QemuOptsList *list)
1195 {
1196     QemuOptDesc *desc = NULL;
1197     size_t num_opts = 0;
1198 
1199     if (!list) {
1200         return 0;
1201     }
1202 
1203     desc = list->desc;
1204     while (desc && desc->name) {
1205         num_opts++;
1206         desc++;
1207     }
1208 
1209     return num_opts;
1210 }
1211 
1212 void qemu_opts_free(QemuOptsList *list)
1213 {
1214     g_free(list);
1215 }
1216 
1217 /* Realloc dst option list and append options from an option list (list)
1218  * to it. dst could be NULL or a malloced list.
1219  * The lifetime of dst must be shorter than the input list because the
1220  * QemuOptDesc->name, ->help, and ->def_value_str strings are shared.
1221  */
1222 QemuOptsList *qemu_opts_append(QemuOptsList *dst,
1223                                QemuOptsList *list)
1224 {
1225     size_t num_opts, num_dst_opts;
1226     QemuOptDesc *desc;
1227     bool need_init = false;
1228     bool need_head_update;
1229 
1230     if (!list) {
1231         return dst;
1232     }
1233 
1234     /* If dst is NULL, after realloc, some area of dst should be initialized
1235      * before adding options to it.
1236      */
1237     if (!dst) {
1238         need_init = true;
1239         need_head_update = true;
1240     } else {
1241         /* Moreover, even if dst is not NULL, the realloc may move it to a
1242          * different address in which case we may get a stale tail pointer
1243          * in dst->head. */
1244         need_head_update = QTAILQ_EMPTY(&dst->head);
1245     }
1246 
1247     num_opts = count_opts_list(dst);
1248     num_dst_opts = num_opts;
1249     num_opts += count_opts_list(list);
1250     dst = g_realloc(dst, sizeof(QemuOptsList) +
1251                     (num_opts + 1) * sizeof(QemuOptDesc));
1252     if (need_init) {
1253         dst->name = NULL;
1254         dst->implied_opt_name = NULL;
1255         dst->merge_lists = false;
1256     }
1257     if (need_head_update) {
1258         QTAILQ_INIT(&dst->head);
1259     }
1260     dst->desc[num_dst_opts].name = NULL;
1261 
1262     /* append list->desc to dst->desc */
1263     if (list) {
1264         desc = list->desc;
1265         while (desc && desc->name) {
1266             if (find_desc_by_name(dst->desc, desc->name) == NULL) {
1267                 dst->desc[num_dst_opts++] = *desc;
1268                 dst->desc[num_dst_opts].name = NULL;
1269             }
1270             desc++;
1271         }
1272     }
1273 
1274     return dst;
1275 }
1276