xref: /openbmc/qemu/util/qemu-option.c (revision 07a32d6b)
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_set(errp,QERR_INVALID_PARAMETER_VALUE, name, "'on' or 'off'");
136         }
137     } else {
138         *ret = 1;
139     }
140 }
141 
142 static void parse_option_number(const char *name, const char *value,
143                                 uint64_t *ret, Error **errp)
144 {
145     char *postfix;
146     uint64_t number;
147 
148     if (value != NULL) {
149         number = strtoull(value, &postfix, 0);
150         if (*postfix != '\0') {
151             error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
152             return;
153         }
154         *ret = number;
155     } else {
156         error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
157     }
158 }
159 
160 static const QemuOptDesc *find_desc_by_name(const QemuOptDesc *desc,
161                                             const char *name)
162 {
163     int i;
164 
165     for (i = 0; desc[i].name != NULL; i++) {
166         if (strcmp(desc[i].name, name) == 0) {
167             return &desc[i];
168         }
169     }
170 
171     return NULL;
172 }
173 
174 void parse_option_size(const char *name, const char *value,
175                        uint64_t *ret, Error **errp)
176 {
177     char *postfix;
178     double sizef;
179 
180     if (value != NULL) {
181         sizef = strtod(value, &postfix);
182         switch (*postfix) {
183         case 'T':
184             sizef *= 1024;
185             /* fall through */
186         case 'G':
187             sizef *= 1024;
188             /* fall through */
189         case 'M':
190             sizef *= 1024;
191             /* fall through */
192         case 'K':
193         case 'k':
194             sizef *= 1024;
195             /* fall through */
196         case 'b':
197         case '\0':
198             *ret = (uint64_t) sizef;
199             break;
200         default:
201             error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
202 #if 0 /* conversion from qerror_report() to error_set() broke this: */
203             error_printf_unless_qmp("You may use k, M, G or T suffixes for "
204                     "kilobytes, megabytes, gigabytes and terabytes.\n");
205 #endif
206             return;
207         }
208     } else {
209         error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
210     }
211 }
212 
213 bool has_help_option(const char *param)
214 {
215     size_t buflen = strlen(param) + 1;
216     char *buf = g_malloc0(buflen);
217     const char *p = param;
218     bool result = false;
219 
220     while (*p) {
221         p = get_opt_value(buf, buflen, p);
222         if (*p) {
223             p++;
224         }
225 
226         if (is_help_option(buf)) {
227             result = true;
228             goto out;
229         }
230     }
231 
232 out:
233     free(buf);
234     return result;
235 }
236 
237 bool is_valid_option_list(const char *param)
238 {
239     size_t buflen = strlen(param) + 1;
240     char *buf = g_malloc0(buflen);
241     const char *p = param;
242     bool result = true;
243 
244     while (*p) {
245         p = get_opt_value(buf, buflen, p);
246         if (*p && !*++p) {
247             result = false;
248             goto out;
249         }
250 
251         if (!*buf || *buf == ',') {
252             result = false;
253             goto out;
254         }
255     }
256 
257 out:
258     free(buf);
259     return result;
260 }
261 
262 void qemu_opts_print_help(QemuOptsList *list)
263 {
264     QemuOptDesc *desc;
265 
266     assert(list);
267     desc = list->desc;
268     printf("Supported options:\n");
269     while (desc && desc->name) {
270         printf("%-16s %s\n", desc->name,
271                desc->help ? desc->help : "No description available");
272         desc++;
273     }
274 }
275 /* ------------------------------------------------------------------ */
276 
277 QemuOpt *qemu_opt_find(QemuOpts *opts, const char *name)
278 {
279     QemuOpt *opt;
280 
281     QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
282         if (strcmp(opt->name, name) != 0)
283             continue;
284         return opt;
285     }
286     return NULL;
287 }
288 
289 static void qemu_opt_del(QemuOpt *opt)
290 {
291     QTAILQ_REMOVE(&opt->opts->head, opt, next);
292     g_free(opt->name);
293     g_free(opt->str);
294     g_free(opt);
295 }
296 
297 /* qemu_opt_set allows many settings for the same option.
298  * This function deletes all settings for an option.
299  */
300 static void qemu_opt_del_all(QemuOpts *opts, const char *name)
301 {
302     QemuOpt *opt, *next_opt;
303 
304     QTAILQ_FOREACH_SAFE(opt, &opts->head, next, next_opt) {
305         if (!strcmp(opt->name, name)) {
306             qemu_opt_del(opt);
307         }
308     }
309 }
310 
311 const char *qemu_opt_get(QemuOpts *opts, const char *name)
312 {
313     QemuOpt *opt = qemu_opt_find(opts, name);
314 
315     if (!opt) {
316         const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
317         if (desc && desc->def_value_str) {
318             return desc->def_value_str;
319         }
320     }
321     return opt ? opt->str : NULL;
322 }
323 
324 /* Get a known option (or its default) and remove it from the list
325  * all in one action. Return a malloced string of the option value.
326  * Result must be freed by caller with g_free().
327  */
328 char *qemu_opt_get_del(QemuOpts *opts, const char *name)
329 {
330     QemuOpt *opt;
331     const QemuOptDesc *desc;
332     char *str = NULL;
333 
334     if (opts == NULL) {
335         return NULL;
336     }
337 
338     opt = qemu_opt_find(opts, name);
339     if (!opt) {
340         desc = find_desc_by_name(opts->list->desc, name);
341         if (desc && desc->def_value_str) {
342             str = g_strdup(desc->def_value_str);
343         }
344         return str;
345     }
346     str = opt->str;
347     opt->str = NULL;
348     qemu_opt_del_all(opts, name);
349     return str;
350 }
351 
352 bool qemu_opt_has_help_opt(QemuOpts *opts)
353 {
354     QemuOpt *opt;
355 
356     QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
357         if (is_help_option(opt->name)) {
358             return true;
359         }
360     }
361     return false;
362 }
363 
364 static bool qemu_opt_get_bool_helper(QemuOpts *opts, const char *name,
365                                      bool defval, bool del)
366 {
367     QemuOpt *opt = qemu_opt_find(opts, name);
368     bool ret = defval;
369 
370     if (opt == NULL) {
371         const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
372         if (desc && desc->def_value_str) {
373             parse_option_bool(name, desc->def_value_str, &ret, &error_abort);
374         }
375         return ret;
376     }
377     assert(opt->desc && opt->desc->type == QEMU_OPT_BOOL);
378     ret = opt->value.boolean;
379     if (del) {
380         qemu_opt_del_all(opts, name);
381     }
382     return ret;
383 }
384 
385 bool qemu_opt_get_bool(QemuOpts *opts, const char *name, bool defval)
386 {
387     return qemu_opt_get_bool_helper(opts, name, defval, false);
388 }
389 
390 bool qemu_opt_get_bool_del(QemuOpts *opts, const char *name, bool defval)
391 {
392     return qemu_opt_get_bool_helper(opts, name, defval, true);
393 }
394 
395 static uint64_t qemu_opt_get_number_helper(QemuOpts *opts, const char *name,
396                                            uint64_t defval, bool del)
397 {
398     QemuOpt *opt = qemu_opt_find(opts, name);
399     uint64_t ret = defval;
400 
401     if (opt == NULL) {
402         const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
403         if (desc && desc->def_value_str) {
404             parse_option_number(name, desc->def_value_str, &ret, &error_abort);
405         }
406         return ret;
407     }
408     assert(opt->desc && opt->desc->type == QEMU_OPT_NUMBER);
409     ret = opt->value.uint;
410     if (del) {
411         qemu_opt_del_all(opts, name);
412     }
413     return ret;
414 }
415 
416 uint64_t qemu_opt_get_number(QemuOpts *opts, const char *name, uint64_t defval)
417 {
418     return qemu_opt_get_number_helper(opts, name, defval, false);
419 }
420 
421 uint64_t qemu_opt_get_number_del(QemuOpts *opts, const char *name,
422                                  uint64_t defval)
423 {
424     return qemu_opt_get_number_helper(opts, name, defval, true);
425 }
426 
427 static uint64_t qemu_opt_get_size_helper(QemuOpts *opts, const char *name,
428                                          uint64_t defval, bool del)
429 {
430     QemuOpt *opt = qemu_opt_find(opts, name);
431     uint64_t ret = defval;
432 
433     if (opt == NULL) {
434         const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
435         if (desc && desc->def_value_str) {
436             parse_option_size(name, desc->def_value_str, &ret, &error_abort);
437         }
438         return ret;
439     }
440     assert(opt->desc && opt->desc->type == QEMU_OPT_SIZE);
441     ret = opt->value.uint;
442     if (del) {
443         qemu_opt_del_all(opts, name);
444     }
445     return ret;
446 }
447 
448 uint64_t qemu_opt_get_size(QemuOpts *opts, const char *name, uint64_t defval)
449 {
450     return qemu_opt_get_size_helper(opts, name, defval, false);
451 }
452 
453 uint64_t qemu_opt_get_size_del(QemuOpts *opts, const char *name,
454                                uint64_t defval)
455 {
456     return qemu_opt_get_size_helper(opts, name, defval, true);
457 }
458 
459 static void qemu_opt_parse(QemuOpt *opt, Error **errp)
460 {
461     if (opt->desc == NULL)
462         return;
463 
464     switch (opt->desc->type) {
465     case QEMU_OPT_STRING:
466         /* nothing */
467         return;
468     case QEMU_OPT_BOOL:
469         parse_option_bool(opt->name, opt->str, &opt->value.boolean, errp);
470         break;
471     case QEMU_OPT_NUMBER:
472         parse_option_number(opt->name, opt->str, &opt->value.uint, errp);
473         break;
474     case QEMU_OPT_SIZE:
475         parse_option_size(opt->name, opt->str, &opt->value.uint, errp);
476         break;
477     default:
478         abort();
479     }
480 }
481 
482 static bool opts_accepts_any(const QemuOpts *opts)
483 {
484     return opts->list->desc[0].name == NULL;
485 }
486 
487 int qemu_opt_unset(QemuOpts *opts, const char *name)
488 {
489     QemuOpt *opt = qemu_opt_find(opts, name);
490 
491     assert(opts_accepts_any(opts));
492 
493     if (opt == NULL) {
494         return -1;
495     } else {
496         qemu_opt_del(opt);
497         return 0;
498     }
499 }
500 
501 static void opt_set(QemuOpts *opts, const char *name, const char *value,
502                     bool prepend, Error **errp)
503 {
504     QemuOpt *opt;
505     const QemuOptDesc *desc;
506     Error *local_err = NULL;
507 
508     desc = find_desc_by_name(opts->list->desc, name);
509     if (!desc && !opts_accepts_any(opts)) {
510         error_set(errp, QERR_INVALID_PARAMETER, name);
511         return;
512     }
513 
514     opt = g_malloc0(sizeof(*opt));
515     opt->name = g_strdup(name);
516     opt->opts = opts;
517     if (prepend) {
518         QTAILQ_INSERT_HEAD(&opts->head, opt, next);
519     } else {
520         QTAILQ_INSERT_TAIL(&opts->head, opt, next);
521     }
522     opt->desc = desc;
523     opt->str = g_strdup(value);
524     qemu_opt_parse(opt, &local_err);
525     if (local_err) {
526         error_propagate(errp, local_err);
527         qemu_opt_del(opt);
528     }
529 }
530 
531 int qemu_opt_set(QemuOpts *opts, const char *name, const char *value)
532 {
533     Error *local_err = NULL;
534 
535     opt_set(opts, name, value, false, &local_err);
536     if (local_err) {
537         qerror_report_err(local_err);
538         error_free(local_err);
539         return -1;
540     }
541 
542     return 0;
543 }
544 
545 void qemu_opt_set_err(QemuOpts *opts, const char *name, const char *value,
546                       Error **errp)
547 {
548     opt_set(opts, name, value, false, errp);
549 }
550 
551 int qemu_opt_set_bool(QemuOpts *opts, const char *name, bool val)
552 {
553     QemuOpt *opt;
554     const QemuOptDesc *desc = opts->list->desc;
555 
556     opt = g_malloc0(sizeof(*opt));
557     opt->desc = find_desc_by_name(desc, name);
558     if (!opt->desc && !opts_accepts_any(opts)) {
559         qerror_report(QERR_INVALID_PARAMETER, name);
560         g_free(opt);
561         return -1;
562     }
563 
564     opt->name = g_strdup(name);
565     opt->opts = opts;
566     opt->value.boolean = !!val;
567     opt->str = g_strdup(val ? "on" : "off");
568     QTAILQ_INSERT_TAIL(&opts->head, opt, next);
569 
570     return 0;
571 }
572 
573 int qemu_opt_set_number(QemuOpts *opts, const char *name, int64_t val)
574 {
575     QemuOpt *opt;
576     const QemuOptDesc *desc = opts->list->desc;
577 
578     opt = g_malloc0(sizeof(*opt));
579     opt->desc = find_desc_by_name(desc, name);
580     if (!opt->desc && !opts_accepts_any(opts)) {
581         qerror_report(QERR_INVALID_PARAMETER, name);
582         g_free(opt);
583         return -1;
584     }
585 
586     opt->name = g_strdup(name);
587     opt->opts = opts;
588     opt->value.uint = val;
589     opt->str = g_strdup_printf("%" PRId64, val);
590     QTAILQ_INSERT_TAIL(&opts->head, opt, next);
591 
592     return 0;
593 }
594 
595 int qemu_opt_foreach(QemuOpts *opts, qemu_opt_loopfunc func, void *opaque,
596                      int abort_on_failure)
597 {
598     QemuOpt *opt;
599     int rc = 0;
600 
601     QTAILQ_FOREACH(opt, &opts->head, next) {
602         rc = func(opt->name, opt->str, opaque);
603         if (abort_on_failure  &&  rc != 0)
604             break;
605     }
606     return rc;
607 }
608 
609 QemuOpts *qemu_opts_find(QemuOptsList *list, const char *id)
610 {
611     QemuOpts *opts;
612 
613     QTAILQ_FOREACH(opts, &list->head, next) {
614         if (!opts->id && !id) {
615             return opts;
616         }
617         if (opts->id && id && !strcmp(opts->id, id)) {
618             return opts;
619         }
620     }
621     return NULL;
622 }
623 
624 static int id_wellformed(const char *id)
625 {
626     int i;
627 
628     if (!qemu_isalpha(id[0])) {
629         return 0;
630     }
631     for (i = 1; id[i]; i++) {
632         if (!qemu_isalnum(id[i]) && !strchr("-._", id[i])) {
633             return 0;
634         }
635     }
636     return 1;
637 }
638 
639 QemuOpts *qemu_opts_create(QemuOptsList *list, const char *id,
640                            int fail_if_exists, Error **errp)
641 {
642     QemuOpts *opts = NULL;
643 
644     if (id) {
645         if (!id_wellformed(id)) {
646             error_set(errp,QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
647 #if 0 /* conversion from qerror_report() to error_set() broke this: */
648             error_printf_unless_qmp("Identifiers consist of letters, digits, '-', '.', '_', starting with a letter.\n");
649 #endif
650             return NULL;
651         }
652         opts = qemu_opts_find(list, id);
653         if (opts != NULL) {
654             if (fail_if_exists && !list->merge_lists) {
655                 error_setg(errp, "Duplicate ID '%s' for %s", id, list->name);
656                 return NULL;
657             } else {
658                 return opts;
659             }
660         }
661     } else if (list->merge_lists) {
662         opts = qemu_opts_find(list, NULL);
663         if (opts) {
664             return opts;
665         }
666     }
667     opts = g_malloc0(sizeof(*opts));
668     opts->id = g_strdup(id);
669     opts->list = list;
670     loc_save(&opts->loc);
671     QTAILQ_INIT(&opts->head);
672     QTAILQ_INSERT_TAIL(&list->head, opts, next);
673     return opts;
674 }
675 
676 void qemu_opts_reset(QemuOptsList *list)
677 {
678     QemuOpts *opts, *next_opts;
679 
680     QTAILQ_FOREACH_SAFE(opts, &list->head, next, next_opts) {
681         qemu_opts_del(opts);
682     }
683 }
684 
685 void qemu_opts_loc_restore(QemuOpts *opts)
686 {
687     loc_restore(&opts->loc);
688 }
689 
690 int qemu_opts_set(QemuOptsList *list, const char *id,
691                   const char *name, const char *value)
692 {
693     QemuOpts *opts;
694     Error *local_err = NULL;
695 
696     opts = qemu_opts_create(list, id, 1, &local_err);
697     if (local_err) {
698         qerror_report_err(local_err);
699         error_free(local_err);
700         return -1;
701     }
702     return qemu_opt_set(opts, name, value);
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 void qemu_opts_print(QemuOpts *opts)
736 {
737     QemuOpt *opt;
738     QemuOptDesc *desc = opts->list->desc;
739 
740     if (desc[0].name == NULL) {
741         QTAILQ_FOREACH(opt, &opts->head, next) {
742             printf("%s=\"%s\" ", opt->name, opt->str);
743         }
744         return;
745     }
746     for (; desc && desc->name; desc++) {
747         const char *value;
748         QemuOpt *opt = qemu_opt_find(opts, desc->name);
749 
750         value = opt ? opt->str : desc->def_value_str;
751         if (!value) {
752             continue;
753         }
754         if (desc->type == QEMU_OPT_STRING) {
755             printf("%s='%s' ", desc->name, value);
756         } else if ((desc->type == QEMU_OPT_SIZE ||
757                     desc->type == QEMU_OPT_NUMBER) && opt) {
758             printf("%s=%" PRId64 " ", desc->name, opt->value.uint);
759         } else {
760             printf("%s=%s ", desc->name, value);
761         }
762     }
763 }
764 
765 static int opts_do_parse(QemuOpts *opts, const char *params,
766                          const char *firstname, bool prepend)
767 {
768     char option[128], value[1024];
769     const char *p,*pe,*pc;
770     Error *local_err = NULL;
771 
772     for (p = params; *p != '\0'; p++) {
773         pe = strchr(p, '=');
774         pc = strchr(p, ',');
775         if (!pe || (pc && pc < pe)) {
776             /* found "foo,more" */
777             if (p == params && firstname) {
778                 /* implicitly named first option */
779                 pstrcpy(option, sizeof(option), firstname);
780                 p = get_opt_value(value, sizeof(value), p);
781             } else {
782                 /* option without value, probably a flag */
783                 p = get_opt_name(option, sizeof(option), p, ',');
784                 if (strncmp(option, "no", 2) == 0) {
785                     memmove(option, option+2, strlen(option+2)+1);
786                     pstrcpy(value, sizeof(value), "off");
787                 } else {
788                     pstrcpy(value, sizeof(value), "on");
789                 }
790             }
791         } else {
792             /* found "foo=bar,more" */
793             p = get_opt_name(option, sizeof(option), p, '=');
794             if (*p != '=') {
795                 break;
796             }
797             p++;
798             p = get_opt_value(value, sizeof(value), p);
799         }
800         if (strcmp(option, "id") != 0) {
801             /* store and parse */
802             opt_set(opts, option, value, prepend, &local_err);
803             if (local_err) {
804                 qerror_report_err(local_err);
805                 error_free(local_err);
806                 return -1;
807             }
808         }
809         if (*p != ',') {
810             break;
811         }
812     }
813     return 0;
814 }
815 
816 int qemu_opts_do_parse(QemuOpts *opts, const char *params, const char *firstname)
817 {
818     return opts_do_parse(opts, params, firstname, false);
819 }
820 
821 static QemuOpts *opts_parse(QemuOptsList *list, const char *params,
822                             int permit_abbrev, bool defaults)
823 {
824     const char *firstname;
825     char value[1024], *id = NULL;
826     const char *p;
827     QemuOpts *opts;
828     Error *local_err = NULL;
829 
830     assert(!permit_abbrev || list->implied_opt_name);
831     firstname = permit_abbrev ? list->implied_opt_name : NULL;
832 
833     if (strncmp(params, "id=", 3) == 0) {
834         get_opt_value(value, sizeof(value), params+3);
835         id = value;
836     } else if ((p = strstr(params, ",id=")) != NULL) {
837         get_opt_value(value, sizeof(value), p+4);
838         id = value;
839     }
840 
841     /*
842      * This code doesn't work for defaults && !list->merge_lists: when
843      * params has no id=, and list has an element with !opts->id, it
844      * appends a new element instead of returning the existing opts.
845      * However, we got no use for this case.  Guard against possible
846      * (if unlikely) future misuse:
847      */
848     assert(!defaults || list->merge_lists);
849     opts = qemu_opts_create(list, id, !defaults, &local_err);
850     if (opts == NULL) {
851         if (local_err) {
852             qerror_report_err(local_err);
853             error_free(local_err);
854         }
855         return NULL;
856     }
857 
858     if (opts_do_parse(opts, params, firstname, defaults) != 0) {
859         qemu_opts_del(opts);
860         return NULL;
861     }
862 
863     return opts;
864 }
865 
866 QemuOpts *qemu_opts_parse(QemuOptsList *list, const char *params,
867                           int permit_abbrev)
868 {
869     return opts_parse(list, params, permit_abbrev, false);
870 }
871 
872 void qemu_opts_set_defaults(QemuOptsList *list, const char *params,
873                             int permit_abbrev)
874 {
875     QemuOpts *opts;
876 
877     opts = opts_parse(list, params, permit_abbrev, true);
878     assert(opts);
879 }
880 
881 typedef struct OptsFromQDictState {
882     QemuOpts *opts;
883     Error **errp;
884 } OptsFromQDictState;
885 
886 static void qemu_opts_from_qdict_1(const char *key, QObject *obj, void *opaque)
887 {
888     OptsFromQDictState *state = opaque;
889     char buf[32];
890     const char *value;
891     int n;
892 
893     if (!strcmp(key, "id") || *state->errp) {
894         return;
895     }
896 
897     switch (qobject_type(obj)) {
898     case QTYPE_QSTRING:
899         value = qstring_get_str(qobject_to_qstring(obj));
900         break;
901     case QTYPE_QINT:
902         n = snprintf(buf, sizeof(buf), "%" PRId64,
903                      qint_get_int(qobject_to_qint(obj)));
904         assert(n < sizeof(buf));
905         value = buf;
906         break;
907     case QTYPE_QFLOAT:
908         n = snprintf(buf, sizeof(buf), "%.17g",
909                      qfloat_get_double(qobject_to_qfloat(obj)));
910         assert(n < sizeof(buf));
911         value = buf;
912         break;
913     case QTYPE_QBOOL:
914         pstrcpy(buf, sizeof(buf),
915                 qbool_get_int(qobject_to_qbool(obj)) ? "on" : "off");
916         value = buf;
917         break;
918     default:
919         return;
920     }
921 
922     qemu_opt_set_err(state->opts, key, value, state->errp);
923 }
924 
925 /*
926  * Create QemuOpts from a QDict.
927  * Use value of key "id" as ID if it exists and is a QString.
928  * Only QStrings, QInts, QFloats and QBools are copied.  Entries with
929  * other types are silently ignored.
930  */
931 QemuOpts *qemu_opts_from_qdict(QemuOptsList *list, const QDict *qdict,
932                                Error **errp)
933 {
934     OptsFromQDictState state;
935     Error *local_err = NULL;
936     QemuOpts *opts;
937 
938     opts = qemu_opts_create(list, qdict_get_try_str(qdict, "id"), 1,
939                             &local_err);
940     if (local_err) {
941         error_propagate(errp, local_err);
942         return NULL;
943     }
944 
945     assert(opts != NULL);
946 
947     state.errp = &local_err;
948     state.opts = opts;
949     qdict_iter(qdict, qemu_opts_from_qdict_1, &state);
950     if (local_err) {
951         error_propagate(errp, local_err);
952         qemu_opts_del(opts);
953         return NULL;
954     }
955 
956     return opts;
957 }
958 
959 /*
960  * Adds all QDict entries to the QemuOpts that can be added and removes them
961  * from the QDict. When this function returns, the QDict contains only those
962  * entries that couldn't be added to the QemuOpts.
963  */
964 void qemu_opts_absorb_qdict(QemuOpts *opts, QDict *qdict, Error **errp)
965 {
966     const QDictEntry *entry, *next;
967 
968     entry = qdict_first(qdict);
969 
970     while (entry != NULL) {
971         Error *local_err = NULL;
972         OptsFromQDictState state = {
973             .errp = &local_err,
974             .opts = opts,
975         };
976 
977         next = qdict_next(qdict, entry);
978 
979         if (find_desc_by_name(opts->list->desc, entry->key)) {
980             qemu_opts_from_qdict_1(entry->key, entry->value, &state);
981             if (local_err) {
982                 error_propagate(errp, local_err);
983                 return;
984             } else {
985                 qdict_del(qdict, entry->key);
986             }
987         }
988 
989         entry = next;
990     }
991 }
992 
993 /*
994  * Convert from QemuOpts to QDict.
995  * The QDict values are of type QString.
996  * TODO We'll want to use types appropriate for opt->desc->type, but
997  * this is enough for now.
998  */
999 QDict *qemu_opts_to_qdict(QemuOpts *opts, QDict *qdict)
1000 {
1001     QemuOpt *opt;
1002     QObject *val;
1003 
1004     if (!qdict) {
1005         qdict = qdict_new();
1006     }
1007     if (opts->id) {
1008         qdict_put(qdict, "id", qstring_from_str(opts->id));
1009     }
1010     QTAILQ_FOREACH(opt, &opts->head, next) {
1011         val = QOBJECT(qstring_from_str(opt->str));
1012         qdict_put_obj(qdict, opt->name, val);
1013     }
1014     return qdict;
1015 }
1016 
1017 /* Validate parsed opts against descriptions where no
1018  * descriptions were provided in the QemuOptsList.
1019  */
1020 void qemu_opts_validate(QemuOpts *opts, const QemuOptDesc *desc, Error **errp)
1021 {
1022     QemuOpt *opt;
1023     Error *local_err = NULL;
1024 
1025     assert(opts_accepts_any(opts));
1026 
1027     QTAILQ_FOREACH(opt, &opts->head, next) {
1028         opt->desc = find_desc_by_name(desc, opt->name);
1029         if (!opt->desc) {
1030             error_set(errp, QERR_INVALID_PARAMETER, opt->name);
1031             return;
1032         }
1033 
1034         qemu_opt_parse(opt, &local_err);
1035         if (local_err) {
1036             error_propagate(errp, local_err);
1037             return;
1038         }
1039     }
1040 }
1041 
1042 int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func, void *opaque,
1043                       int abort_on_failure)
1044 {
1045     Location loc;
1046     QemuOpts *opts;
1047     int rc = 0;
1048 
1049     loc_push_none(&loc);
1050     QTAILQ_FOREACH(opts, &list->head, next) {
1051         loc_restore(&opts->loc);
1052         rc |= func(opts, opaque);
1053         if (abort_on_failure  &&  rc != 0)
1054             break;
1055     }
1056     loc_pop(&loc);
1057     return rc;
1058 }
1059 
1060 static size_t count_opts_list(QemuOptsList *list)
1061 {
1062     QemuOptDesc *desc = NULL;
1063     size_t num_opts = 0;
1064 
1065     if (!list) {
1066         return 0;
1067     }
1068 
1069     desc = list->desc;
1070     while (desc && desc->name) {
1071         num_opts++;
1072         desc++;
1073     }
1074 
1075     return num_opts;
1076 }
1077 
1078 void qemu_opts_free(QemuOptsList *list)
1079 {
1080     g_free(list);
1081 }
1082 
1083 /* Realloc dst option list and append options from an option list (list)
1084  * to it. dst could be NULL or a malloced list.
1085  * The lifetime of dst must be shorter than the input list because the
1086  * QemuOptDesc->name, ->help, and ->def_value_str strings are shared.
1087  */
1088 QemuOptsList *qemu_opts_append(QemuOptsList *dst,
1089                                QemuOptsList *list)
1090 {
1091     size_t num_opts, num_dst_opts;
1092     QemuOptDesc *desc;
1093     bool need_init = false;
1094 
1095     if (!list) {
1096         return dst;
1097     }
1098 
1099     /* If dst is NULL, after realloc, some area of dst should be initialized
1100      * before adding options to it.
1101      */
1102     if (!dst) {
1103         need_init = true;
1104     }
1105 
1106     num_opts = count_opts_list(dst);
1107     num_dst_opts = num_opts;
1108     num_opts += count_opts_list(list);
1109     dst = g_realloc(dst, sizeof(QemuOptsList) +
1110                     (num_opts + 1) * sizeof(QemuOptDesc));
1111     if (need_init) {
1112         dst->name = NULL;
1113         dst->implied_opt_name = NULL;
1114         QTAILQ_INIT(&dst->head);
1115         dst->merge_lists = false;
1116     }
1117     dst->desc[num_dst_opts].name = NULL;
1118 
1119     /* append list->desc to dst->desc */
1120     if (list) {
1121         desc = list->desc;
1122         while (desc && desc->name) {
1123             if (find_desc_by_name(dst->desc, desc->name) == NULL) {
1124                 dst->desc[num_dst_opts++] = *desc;
1125                 dst->desc[num_dst_opts].name = NULL;
1126             }
1127             desc++;
1128         }
1129     }
1130 
1131     return dst;
1132 }
1133