qcow2.c: replace QEMUOptionParameter with QemuOpts
[qemu/ar7.git] / util / qemu-option.c
blob0d9d3ec889a075a51c98e805593147db786a1c94
1 /*
2 * Commandline option parsing functions
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2009 Kevin Wolf <kwolf@redhat.com>
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:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
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.
26 #include <stdio.h>
27 #include <string.h>
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"
37 * Extracts the name of an option from the parameter string (p points at the
38 * first byte of the option name)
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.
44 * The return value is the position of the delimiter/zero byte after the option
45 * name in p.
47 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
49 char *q;
51 q = buf;
52 while (*p != '\0' && *p != delim) {
53 if (q && (q - buf) < buf_size - 1)
54 *q++ = *p;
55 p++;
57 if (q)
58 *q = '\0';
60 return p;
64 * Extracts the value of an option from the parameter string p (p points at the
65 * first byte of the option value)
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.
71 const char *get_opt_value(char *buf, int buf_size, const char *p)
73 char *q;
75 q = buf;
76 while (*p != '\0') {
77 if (*p == ',') {
78 if (*(p + 1) != ',')
79 break;
80 p++;
82 if (q && (q - buf) < buf_size - 1)
83 *q++ = *p;
84 p++;
86 if (q)
87 *q = '\0';
89 return p;
92 int get_next_param_value(char *buf, int buf_size,
93 const char *tag, const char **pstr)
95 const char *p;
96 char option[128];
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)++;
109 return strlen(buf);
110 } else {
111 p = get_opt_value(NULL, 0, p);
113 if (*p != ',')
114 break;
115 p++;
117 return 0;
120 int get_param_value(char *buf, int buf_size,
121 const char *tag, const char *str)
123 return get_next_param_value(buf, buf_size, tag, &str);
127 * Searches an option list for an option with the given name
129 QEMUOptionParameter *get_option_parameter(QEMUOptionParameter *list,
130 const char *name)
132 while (list && list->name) {
133 if (!strcmp(list->name, name)) {
134 return list;
136 list++;
139 return NULL;
142 static void parse_option_bool(const char *name, const char *value, bool *ret,
143 Error **errp)
145 if (value != NULL) {
146 if (!strcmp(value, "on")) {
147 *ret = 1;
148 } else if (!strcmp(value, "off")) {
149 *ret = 0;
150 } else {
151 error_set(errp,QERR_INVALID_PARAMETER_VALUE, name, "'on' or 'off'");
153 } else {
154 *ret = 1;
158 static void parse_option_number(const char *name, const char *value,
159 uint64_t *ret, Error **errp)
161 char *postfix;
162 uint64_t number;
164 if (value != NULL) {
165 number = strtoull(value, &postfix, 0);
166 if (*postfix != '\0') {
167 error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
168 return;
170 *ret = number;
171 } else {
172 error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
176 static const QemuOptDesc *find_desc_by_name(const QemuOptDesc *desc,
177 const char *name)
179 int i;
181 for (i = 0; desc[i].name != NULL; i++) {
182 if (strcmp(desc[i].name, name) == 0) {
183 return &desc[i];
187 return NULL;
190 void parse_option_size(const char *name, const char *value,
191 uint64_t *ret, Error **errp)
193 char *postfix;
194 double sizef;
196 if (value != NULL) {
197 sizef = strtod(value, &postfix);
198 switch (*postfix) {
199 case 'T':
200 sizef *= 1024;
201 /* fall through */
202 case 'G':
203 sizef *= 1024;
204 /* fall through */
205 case 'M':
206 sizef *= 1024;
207 /* fall through */
208 case 'K':
209 case 'k':
210 sizef *= 1024;
211 /* fall through */
212 case 'b':
213 case '\0':
214 *ret = (uint64_t) sizef;
215 break;
216 default:
217 error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
218 #if 0 /* conversion from qerror_report() to error_set() broke this: */
219 error_printf_unless_qmp("You may use k, M, G or T suffixes for "
220 "kilobytes, megabytes, gigabytes and terabytes.\n");
221 #endif
222 return;
224 } else {
225 error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
230 * Sets the value of a parameter in a given option list. The parsing of the
231 * value depends on the type of option:
233 * OPT_FLAG (uses value.n):
234 * If no value is given, the flag is set to 1.
235 * Otherwise the value must be "on" (set to 1) or "off" (set to 0)
237 * OPT_STRING (uses value.s):
238 * value is strdup()ed and assigned as option value
240 * OPT_SIZE (uses value.n):
241 * The value is converted to an integer. Suffixes for kilobytes etc. are
242 * allowed (powers of 1024).
244 * Returns 0 on succes, -1 in error cases
246 int set_option_parameter(QEMUOptionParameter *list, const char *name,
247 const char *value)
249 bool flag;
250 Error *local_err = NULL;
252 // Find a matching parameter
253 list = get_option_parameter(list, name);
254 if (list == NULL) {
255 fprintf(stderr, "Unknown option '%s'\n", name);
256 return -1;
259 // Process parameter
260 switch (list->type) {
261 case OPT_FLAG:
262 parse_option_bool(name, value, &flag, &local_err);
263 if (!local_err) {
264 list->value.n = flag;
266 break;
268 case OPT_STRING:
269 if (value != NULL) {
270 list->value.s = g_strdup(value);
271 } else {
272 fprintf(stderr, "Option '%s' needs a parameter\n", name);
273 return -1;
275 break;
277 case OPT_SIZE:
278 parse_option_size(name, value, &list->value.n, &local_err);
279 break;
281 default:
282 fprintf(stderr, "Bug: Option '%s' has an unknown type\n", name);
283 return -1;
286 if (local_err) {
287 qerror_report_err(local_err);
288 error_free(local_err);
289 return -1;
292 list->assigned = true;
294 return 0;
298 * Sets the given parameter to an integer instead of a string.
299 * This function cannot be used to set string options.
301 * Returns 0 on success, -1 in error cases
303 int set_option_parameter_int(QEMUOptionParameter *list, const char *name,
304 uint64_t value)
306 // Find a matching parameter
307 list = get_option_parameter(list, name);
308 if (list == NULL) {
309 fprintf(stderr, "Unknown option '%s'\n", name);
310 return -1;
313 // Process parameter
314 switch (list->type) {
315 case OPT_FLAG:
316 case OPT_NUMBER:
317 case OPT_SIZE:
318 list->value.n = value;
319 break;
321 default:
322 return -1;
325 list->assigned = true;
327 return 0;
331 * Frees a option list. If it contains strings, the strings are freed as well.
333 void free_option_parameters(QEMUOptionParameter *list)
335 QEMUOptionParameter *cur = list;
337 while (cur && cur->name) {
338 if (cur->type == OPT_STRING) {
339 g_free(cur->value.s);
341 cur++;
344 g_free(list);
348 * Count valid options in list
350 static size_t count_option_parameters(QEMUOptionParameter *list)
352 size_t num_options = 0;
354 while (list && list->name) {
355 num_options++;
356 list++;
359 return num_options;
363 * Append an option list (list) to an option list (dest).
365 * If dest is NULL, a new copy of list is created.
367 * Returns a pointer to the first element of dest (or the newly allocated copy)
369 QEMUOptionParameter *append_option_parameters(QEMUOptionParameter *dest,
370 QEMUOptionParameter *list)
372 size_t num_options, num_dest_options;
374 num_options = count_option_parameters(dest);
375 num_dest_options = num_options;
377 num_options += count_option_parameters(list);
379 dest = g_realloc(dest, (num_options + 1) * sizeof(QEMUOptionParameter));
380 dest[num_dest_options].name = NULL;
382 while (list && list->name) {
383 if (get_option_parameter(dest, list->name) == NULL) {
384 dest[num_dest_options++] = *list;
385 dest[num_dest_options].name = NULL;
387 list++;
390 return dest;
394 * Parses a parameter string (param) into an option list (dest).
396 * list is the template option list. If dest is NULL, a new copy of list is
397 * created. If list is NULL, this function fails.
399 * A parameter string consists of one or more parameters, separated by commas.
400 * Each parameter consists of its name and possibly of a value. In the latter
401 * case, the value is delimited by an = character. To specify a value which
402 * contains commas, double each comma so it won't be recognized as the end of
403 * the parameter.
405 * For more details of the parsing see above.
407 * Returns a pointer to the first element of dest (or the newly allocated copy)
408 * or NULL in error cases
410 QEMUOptionParameter *parse_option_parameters(const char *param,
411 QEMUOptionParameter *list, QEMUOptionParameter *dest)
413 QEMUOptionParameter *allocated = NULL;
414 char name[256];
415 char value[256];
416 char *param_delim, *value_delim;
417 char next_delim;
418 int i;
420 if (list == NULL) {
421 return NULL;
424 if (dest == NULL) {
425 dest = allocated = append_option_parameters(NULL, list);
428 for (i = 0; dest[i].name; i++) {
429 dest[i].assigned = false;
432 while (*param) {
434 // Find parameter name and value in the string
435 param_delim = strchr(param, ',');
436 value_delim = strchr(param, '=');
438 if (value_delim && (value_delim < param_delim || !param_delim)) {
439 next_delim = '=';
440 } else {
441 next_delim = ',';
442 value_delim = NULL;
445 param = get_opt_name(name, sizeof(name), param, next_delim);
446 if (value_delim) {
447 param = get_opt_value(value, sizeof(value), param + 1);
449 if (*param != '\0') {
450 param++;
453 // Set the parameter
454 if (set_option_parameter(dest, name, value_delim ? value : NULL)) {
455 goto fail;
459 return dest;
461 fail:
462 // Only free the list if it was newly allocated
463 free_option_parameters(allocated);
464 return NULL;
467 bool has_help_option(const char *param)
469 size_t buflen = strlen(param) + 1;
470 char *buf = g_malloc0(buflen);
471 const char *p = param;
472 bool result = false;
474 while (*p) {
475 p = get_opt_value(buf, buflen, p);
476 if (*p) {
477 p++;
480 if (is_help_option(buf)) {
481 result = true;
482 goto out;
486 out:
487 free(buf);
488 return result;
491 bool is_valid_option_list(const char *param)
493 size_t buflen = strlen(param) + 1;
494 char *buf = g_malloc0(buflen);
495 const char *p = param;
496 bool result = true;
498 while (*p) {
499 p = get_opt_value(buf, buflen, p);
500 if (*p && !*++p) {
501 result = false;
502 goto out;
505 if (!*buf || *buf == ',') {
506 result = false;
507 goto out;
511 out:
512 free(buf);
513 return result;
517 * Prints all options of a list that have a value to stdout
519 void print_option_parameters(QEMUOptionParameter *list)
521 while (list && list->name) {
522 switch (list->type) {
523 case OPT_STRING:
524 if (list->value.s != NULL) {
525 printf("%s='%s' ", list->name, list->value.s);
527 break;
528 case OPT_FLAG:
529 printf("%s=%s ", list->name, list->value.n ? "on" : "off");
530 break;
531 case OPT_SIZE:
532 case OPT_NUMBER:
533 printf("%s=%" PRId64 " ", list->name, list->value.n);
534 break;
535 default:
536 printf("%s=(unknown type) ", list->name);
537 break;
539 list++;
544 * Prints an overview of all available options
546 void print_option_help(QEMUOptionParameter *list)
548 printf("Supported options:\n");
549 while (list && list->name) {
550 printf("%-16s %s\n", list->name,
551 list->help ? list->help : "No description available");
552 list++;
556 void qemu_opts_print_help(QemuOptsList *list)
558 QemuOptDesc *desc;
560 assert(list);
561 desc = list->desc;
562 printf("Supported options:\n");
563 while (desc && desc->name) {
564 printf("%-16s %s\n", desc->name,
565 desc->help ? desc->help : "No description available");
566 desc++;
569 /* ------------------------------------------------------------------ */
571 QemuOpt *qemu_opt_find(QemuOpts *opts, const char *name)
573 QemuOpt *opt;
575 QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
576 if (strcmp(opt->name, name) != 0)
577 continue;
578 return opt;
580 return NULL;
583 static void qemu_opt_del(QemuOpt *opt)
585 QTAILQ_REMOVE(&opt->opts->head, opt, next);
586 g_free(opt->name);
587 g_free(opt->str);
588 g_free(opt);
591 /* qemu_opt_set allows many settings for the same option.
592 * This function deletes all settings for an option.
594 static void qemu_opt_del_all(QemuOpts *opts, const char *name)
596 QemuOpt *opt, *next_opt;
598 QTAILQ_FOREACH_SAFE(opt, &opts->head, next, next_opt) {
599 if (!strcmp(opt->name, name)) {
600 qemu_opt_del(opt);
605 const char *qemu_opt_get(QemuOpts *opts, const char *name)
607 QemuOpt *opt = qemu_opt_find(opts, name);
609 if (!opt) {
610 const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
611 if (desc && desc->def_value_str) {
612 return desc->def_value_str;
615 return opt ? opt->str : NULL;
618 /* Get a known option (or its default) and remove it from the list
619 * all in one action. Return a malloced string of the option value.
620 * Result must be freed by caller with g_free().
622 char *qemu_opt_get_del(QemuOpts *opts, const char *name)
624 QemuOpt *opt;
625 const QemuOptDesc *desc;
626 char *str = NULL;
628 if (opts == NULL) {
629 return NULL;
632 opt = qemu_opt_find(opts, name);
633 if (!opt) {
634 desc = find_desc_by_name(opts->list->desc, name);
635 if (desc && desc->def_value_str) {
636 str = g_strdup(desc->def_value_str);
638 return str;
640 str = opt->str;
641 opt->str = NULL;
642 qemu_opt_del_all(opts, name);
643 return str;
646 bool qemu_opt_has_help_opt(QemuOpts *opts)
648 QemuOpt *opt;
650 QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
651 if (is_help_option(opt->name)) {
652 return true;
655 return false;
658 static bool qemu_opt_get_bool_helper(QemuOpts *opts, const char *name,
659 bool defval, bool del)
661 QemuOpt *opt = qemu_opt_find(opts, name);
662 bool ret = defval;
664 if (opt == NULL) {
665 const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
666 if (desc && desc->def_value_str) {
667 parse_option_bool(name, desc->def_value_str, &ret, &error_abort);
669 return ret;
671 assert(opt->desc && opt->desc->type == QEMU_OPT_BOOL);
672 ret = opt->value.boolean;
673 if (del) {
674 qemu_opt_del_all(opts, name);
676 return ret;
679 bool qemu_opt_get_bool(QemuOpts *opts, const char *name, bool defval)
681 return qemu_opt_get_bool_helper(opts, name, defval, false);
684 bool qemu_opt_get_bool_del(QemuOpts *opts, const char *name, bool defval)
686 return qemu_opt_get_bool_helper(opts, name, defval, true);
689 static uint64_t qemu_opt_get_number_helper(QemuOpts *opts, const char *name,
690 uint64_t defval, bool del)
692 QemuOpt *opt = qemu_opt_find(opts, name);
693 uint64_t ret = defval;
695 if (opt == NULL) {
696 const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
697 if (desc && desc->def_value_str) {
698 parse_option_number(name, desc->def_value_str, &ret, &error_abort);
700 return ret;
702 assert(opt->desc && opt->desc->type == QEMU_OPT_NUMBER);
703 ret = opt->value.uint;
704 if (del) {
705 qemu_opt_del_all(opts, name);
707 return ret;
710 uint64_t qemu_opt_get_number(QemuOpts *opts, const char *name, uint64_t defval)
712 return qemu_opt_get_number_helper(opts, name, defval, false);
715 uint64_t qemu_opt_get_number_del(QemuOpts *opts, const char *name,
716 uint64_t defval)
718 return qemu_opt_get_number_helper(opts, name, defval, true);
721 static uint64_t qemu_opt_get_size_helper(QemuOpts *opts, const char *name,
722 uint64_t defval, bool del)
724 QemuOpt *opt = qemu_opt_find(opts, name);
725 uint64_t ret = defval;
727 if (opt == NULL) {
728 const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
729 if (desc && desc->def_value_str) {
730 parse_option_size(name, desc->def_value_str, &ret, &error_abort);
732 return ret;
734 assert(opt->desc && opt->desc->type == QEMU_OPT_SIZE);
735 ret = opt->value.uint;
736 if (del) {
737 qemu_opt_del_all(opts, name);
739 return ret;
742 uint64_t qemu_opt_get_size(QemuOpts *opts, const char *name, uint64_t defval)
744 return qemu_opt_get_size_helper(opts, name, defval, false);
747 uint64_t qemu_opt_get_size_del(QemuOpts *opts, const char *name,
748 uint64_t defval)
750 return qemu_opt_get_size_helper(opts, name, defval, true);
753 static void qemu_opt_parse(QemuOpt *opt, Error **errp)
755 if (opt->desc == NULL)
756 return;
758 switch (opt->desc->type) {
759 case QEMU_OPT_STRING:
760 /* nothing */
761 return;
762 case QEMU_OPT_BOOL:
763 parse_option_bool(opt->name, opt->str, &opt->value.boolean, errp);
764 break;
765 case QEMU_OPT_NUMBER:
766 parse_option_number(opt->name, opt->str, &opt->value.uint, errp);
767 break;
768 case QEMU_OPT_SIZE:
769 parse_option_size(opt->name, opt->str, &opt->value.uint, errp);
770 break;
771 default:
772 abort();
776 static bool opts_accepts_any(const QemuOpts *opts)
778 return opts->list->desc[0].name == NULL;
781 int qemu_opt_unset(QemuOpts *opts, const char *name)
783 QemuOpt *opt = qemu_opt_find(opts, name);
785 assert(opts_accepts_any(opts));
787 if (opt == NULL) {
788 return -1;
789 } else {
790 qemu_opt_del(opt);
791 return 0;
795 static void opt_set(QemuOpts *opts, const char *name, const char *value,
796 bool prepend, Error **errp)
798 QemuOpt *opt;
799 const QemuOptDesc *desc;
800 Error *local_err = NULL;
802 desc = find_desc_by_name(opts->list->desc, name);
803 if (!desc && !opts_accepts_any(opts)) {
804 error_set(errp, QERR_INVALID_PARAMETER, name);
805 return;
808 opt = g_malloc0(sizeof(*opt));
809 opt->name = g_strdup(name);
810 opt->opts = opts;
811 if (prepend) {
812 QTAILQ_INSERT_HEAD(&opts->head, opt, next);
813 } else {
814 QTAILQ_INSERT_TAIL(&opts->head, opt, next);
816 opt->desc = desc;
817 opt->str = g_strdup(value);
818 qemu_opt_parse(opt, &local_err);
819 if (local_err) {
820 error_propagate(errp, local_err);
821 qemu_opt_del(opt);
825 int qemu_opt_set(QemuOpts *opts, const char *name, const char *value)
827 Error *local_err = NULL;
829 opt_set(opts, name, value, false, &local_err);
830 if (local_err) {
831 qerror_report_err(local_err);
832 error_free(local_err);
833 return -1;
836 return 0;
839 void qemu_opt_set_err(QemuOpts *opts, const char *name, const char *value,
840 Error **errp)
842 opt_set(opts, name, value, false, errp);
845 int qemu_opt_set_bool(QemuOpts *opts, const char *name, bool val)
847 QemuOpt *opt;
848 const QemuOptDesc *desc = opts->list->desc;
850 opt = g_malloc0(sizeof(*opt));
851 opt->desc = find_desc_by_name(desc, name);
852 if (!opt->desc && !opts_accepts_any(opts)) {
853 qerror_report(QERR_INVALID_PARAMETER, name);
854 g_free(opt);
855 return -1;
858 opt->name = g_strdup(name);
859 opt->opts = opts;
860 opt->value.boolean = !!val;
861 opt->str = g_strdup(val ? "on" : "off");
862 QTAILQ_INSERT_TAIL(&opts->head, opt, next);
864 return 0;
867 int qemu_opt_set_number(QemuOpts *opts, const char *name, int64_t val)
869 QemuOpt *opt;
870 const QemuOptDesc *desc = opts->list->desc;
872 opt = g_malloc0(sizeof(*opt));
873 opt->desc = find_desc_by_name(desc, name);
874 if (!opt->desc && !opts_accepts_any(opts)) {
875 qerror_report(QERR_INVALID_PARAMETER, name);
876 g_free(opt);
877 return -1;
880 opt->name = g_strdup(name);
881 opt->opts = opts;
882 opt->value.uint = val;
883 opt->str = g_strdup_printf("%" PRId64, val);
884 QTAILQ_INSERT_TAIL(&opts->head, opt, next);
886 return 0;
889 int qemu_opt_foreach(QemuOpts *opts, qemu_opt_loopfunc func, void *opaque,
890 int abort_on_failure)
892 QemuOpt *opt;
893 int rc = 0;
895 QTAILQ_FOREACH(opt, &opts->head, next) {
896 rc = func(opt->name, opt->str, opaque);
897 if (abort_on_failure && rc != 0)
898 break;
900 return rc;
903 QemuOpts *qemu_opts_find(QemuOptsList *list, const char *id)
905 QemuOpts *opts;
907 QTAILQ_FOREACH(opts, &list->head, next) {
908 if (!opts->id && !id) {
909 return opts;
911 if (opts->id && id && !strcmp(opts->id, id)) {
912 return opts;
915 return NULL;
918 static int id_wellformed(const char *id)
920 int i;
922 if (!qemu_isalpha(id[0])) {
923 return 0;
925 for (i = 1; id[i]; i++) {
926 if (!qemu_isalnum(id[i]) && !strchr("-._", id[i])) {
927 return 0;
930 return 1;
933 QemuOpts *qemu_opts_create(QemuOptsList *list, const char *id,
934 int fail_if_exists, Error **errp)
936 QemuOpts *opts = NULL;
938 if (id) {
939 if (!id_wellformed(id)) {
940 error_set(errp,QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
941 #if 0 /* conversion from qerror_report() to error_set() broke this: */
942 error_printf_unless_qmp("Identifiers consist of letters, digits, '-', '.', '_', starting with a letter.\n");
943 #endif
944 return NULL;
946 opts = qemu_opts_find(list, id);
947 if (opts != NULL) {
948 if (fail_if_exists && !list->merge_lists) {
949 error_setg(errp, "Duplicate ID '%s' for %s", id, list->name);
950 return NULL;
951 } else {
952 return opts;
955 } else if (list->merge_lists) {
956 opts = qemu_opts_find(list, NULL);
957 if (opts) {
958 return opts;
961 opts = g_malloc0(sizeof(*opts));
962 opts->id = g_strdup(id);
963 opts->list = list;
964 loc_save(&opts->loc);
965 QTAILQ_INIT(&opts->head);
966 QTAILQ_INSERT_TAIL(&list->head, opts, next);
967 return opts;
970 void qemu_opts_reset(QemuOptsList *list)
972 QemuOpts *opts, *next_opts;
974 QTAILQ_FOREACH_SAFE(opts, &list->head, next, next_opts) {
975 qemu_opts_del(opts);
979 void qemu_opts_loc_restore(QemuOpts *opts)
981 loc_restore(&opts->loc);
984 int qemu_opts_set(QemuOptsList *list, const char *id,
985 const char *name, const char *value)
987 QemuOpts *opts;
988 Error *local_err = NULL;
990 opts = qemu_opts_create(list, id, 1, &local_err);
991 if (local_err) {
992 qerror_report_err(local_err);
993 error_free(local_err);
994 return -1;
996 return qemu_opt_set(opts, name, value);
999 const char *qemu_opts_id(QemuOpts *opts)
1001 return opts->id;
1004 /* The id string will be g_free()d by qemu_opts_del */
1005 void qemu_opts_set_id(QemuOpts *opts, char *id)
1007 opts->id = id;
1010 void qemu_opts_del(QemuOpts *opts)
1012 QemuOpt *opt;
1014 if (opts == NULL) {
1015 return;
1018 for (;;) {
1019 opt = QTAILQ_FIRST(&opts->head);
1020 if (opt == NULL)
1021 break;
1022 qemu_opt_del(opt);
1024 QTAILQ_REMOVE(&opts->list->head, opts, next);
1025 g_free(opts->id);
1026 g_free(opts);
1029 void qemu_opts_print(QemuOpts *opts)
1031 QemuOpt *opt;
1032 QemuOptDesc *desc = opts->list->desc;
1034 if (desc[0].name == NULL) {
1035 QTAILQ_FOREACH(opt, &opts->head, next) {
1036 printf("%s=\"%s\" ", opt->name, opt->str);
1038 return;
1040 for (; desc && desc->name; desc++) {
1041 const char *value;
1042 QemuOpt *opt = qemu_opt_find(opts, desc->name);
1044 value = opt ? opt->str : desc->def_value_str;
1045 if (!value) {
1046 continue;
1048 if (desc->type == QEMU_OPT_STRING) {
1049 printf("%s='%s' ", desc->name, value);
1050 } else if ((desc->type == QEMU_OPT_SIZE ||
1051 desc->type == QEMU_OPT_NUMBER) && opt) {
1052 printf("%s=%" PRId64 " ", desc->name, opt->value.uint);
1053 } else {
1054 printf("%s=%s ", desc->name, value);
1059 static int opts_do_parse(QemuOpts *opts, const char *params,
1060 const char *firstname, bool prepend)
1062 char option[128], value[1024];
1063 const char *p,*pe,*pc;
1064 Error *local_err = NULL;
1066 for (p = params; *p != '\0'; p++) {
1067 pe = strchr(p, '=');
1068 pc = strchr(p, ',');
1069 if (!pe || (pc && pc < pe)) {
1070 /* found "foo,more" */
1071 if (p == params && firstname) {
1072 /* implicitly named first option */
1073 pstrcpy(option, sizeof(option), firstname);
1074 p = get_opt_value(value, sizeof(value), p);
1075 } else {
1076 /* option without value, probably a flag */
1077 p = get_opt_name(option, sizeof(option), p, ',');
1078 if (strncmp(option, "no", 2) == 0) {
1079 memmove(option, option+2, strlen(option+2)+1);
1080 pstrcpy(value, sizeof(value), "off");
1081 } else {
1082 pstrcpy(value, sizeof(value), "on");
1085 } else {
1086 /* found "foo=bar,more" */
1087 p = get_opt_name(option, sizeof(option), p, '=');
1088 if (*p != '=') {
1089 break;
1091 p++;
1092 p = get_opt_value(value, sizeof(value), p);
1094 if (strcmp(option, "id") != 0) {
1095 /* store and parse */
1096 opt_set(opts, option, value, prepend, &local_err);
1097 if (local_err) {
1098 qerror_report_err(local_err);
1099 error_free(local_err);
1100 return -1;
1103 if (*p != ',') {
1104 break;
1107 return 0;
1110 int qemu_opts_do_parse(QemuOpts *opts, const char *params, const char *firstname)
1112 return opts_do_parse(opts, params, firstname, false);
1115 static QemuOpts *opts_parse(QemuOptsList *list, const char *params,
1116 int permit_abbrev, bool defaults)
1118 const char *firstname;
1119 char value[1024], *id = NULL;
1120 const char *p;
1121 QemuOpts *opts;
1122 Error *local_err = NULL;
1124 assert(!permit_abbrev || list->implied_opt_name);
1125 firstname = permit_abbrev ? list->implied_opt_name : NULL;
1127 if (strncmp(params, "id=", 3) == 0) {
1128 get_opt_value(value, sizeof(value), params+3);
1129 id = value;
1130 } else if ((p = strstr(params, ",id=")) != NULL) {
1131 get_opt_value(value, sizeof(value), p+4);
1132 id = value;
1136 * This code doesn't work for defaults && !list->merge_lists: when
1137 * params has no id=, and list has an element with !opts->id, it
1138 * appends a new element instead of returning the existing opts.
1139 * However, we got no use for this case. Guard against possible
1140 * (if unlikely) future misuse:
1142 assert(!defaults || list->merge_lists);
1143 opts = qemu_opts_create(list, id, !defaults, &local_err);
1144 if (opts == NULL) {
1145 if (local_err) {
1146 qerror_report_err(local_err);
1147 error_free(local_err);
1149 return NULL;
1152 if (opts_do_parse(opts, params, firstname, defaults) != 0) {
1153 qemu_opts_del(opts);
1154 return NULL;
1157 return opts;
1160 QemuOpts *qemu_opts_parse(QemuOptsList *list, const char *params,
1161 int permit_abbrev)
1163 return opts_parse(list, params, permit_abbrev, false);
1166 void qemu_opts_set_defaults(QemuOptsList *list, const char *params,
1167 int permit_abbrev)
1169 QemuOpts *opts;
1171 opts = opts_parse(list, params, permit_abbrev, true);
1172 assert(opts);
1175 typedef struct OptsFromQDictState {
1176 QemuOpts *opts;
1177 Error **errp;
1178 } OptsFromQDictState;
1180 static void qemu_opts_from_qdict_1(const char *key, QObject *obj, void *opaque)
1182 OptsFromQDictState *state = opaque;
1183 char buf[32];
1184 const char *value;
1185 int n;
1187 if (!strcmp(key, "id") || *state->errp) {
1188 return;
1191 switch (qobject_type(obj)) {
1192 case QTYPE_QSTRING:
1193 value = qstring_get_str(qobject_to_qstring(obj));
1194 break;
1195 case QTYPE_QINT:
1196 n = snprintf(buf, sizeof(buf), "%" PRId64,
1197 qint_get_int(qobject_to_qint(obj)));
1198 assert(n < sizeof(buf));
1199 value = buf;
1200 break;
1201 case QTYPE_QFLOAT:
1202 n = snprintf(buf, sizeof(buf), "%.17g",
1203 qfloat_get_double(qobject_to_qfloat(obj)));
1204 assert(n < sizeof(buf));
1205 value = buf;
1206 break;
1207 case QTYPE_QBOOL:
1208 pstrcpy(buf, sizeof(buf),
1209 qbool_get_int(qobject_to_qbool(obj)) ? "on" : "off");
1210 value = buf;
1211 break;
1212 default:
1213 return;
1216 qemu_opt_set_err(state->opts, key, value, state->errp);
1220 * Create QemuOpts from a QDict.
1221 * Use value of key "id" as ID if it exists and is a QString.
1222 * Only QStrings, QInts, QFloats and QBools are copied. Entries with
1223 * other types are silently ignored.
1225 QemuOpts *qemu_opts_from_qdict(QemuOptsList *list, const QDict *qdict,
1226 Error **errp)
1228 OptsFromQDictState state;
1229 Error *local_err = NULL;
1230 QemuOpts *opts;
1232 opts = qemu_opts_create(list, qdict_get_try_str(qdict, "id"), 1,
1233 &local_err);
1234 if (local_err) {
1235 error_propagate(errp, local_err);
1236 return NULL;
1239 assert(opts != NULL);
1241 state.errp = &local_err;
1242 state.opts = opts;
1243 qdict_iter(qdict, qemu_opts_from_qdict_1, &state);
1244 if (local_err) {
1245 error_propagate(errp, local_err);
1246 qemu_opts_del(opts);
1247 return NULL;
1250 return opts;
1254 * Adds all QDict entries to the QemuOpts that can be added and removes them
1255 * from the QDict. When this function returns, the QDict contains only those
1256 * entries that couldn't be added to the QemuOpts.
1258 void qemu_opts_absorb_qdict(QemuOpts *opts, QDict *qdict, Error **errp)
1260 const QDictEntry *entry, *next;
1262 entry = qdict_first(qdict);
1264 while (entry != NULL) {
1265 Error *local_err = NULL;
1266 OptsFromQDictState state = {
1267 .errp = &local_err,
1268 .opts = opts,
1271 next = qdict_next(qdict, entry);
1273 if (find_desc_by_name(opts->list->desc, entry->key)) {
1274 qemu_opts_from_qdict_1(entry->key, entry->value, &state);
1275 if (local_err) {
1276 error_propagate(errp, local_err);
1277 return;
1278 } else {
1279 qdict_del(qdict, entry->key);
1283 entry = next;
1288 * Convert from QemuOpts to QDict.
1289 * The QDict values are of type QString.
1290 * TODO We'll want to use types appropriate for opt->desc->type, but
1291 * this is enough for now.
1293 QDict *qemu_opts_to_qdict(QemuOpts *opts, QDict *qdict)
1295 QemuOpt *opt;
1296 QObject *val;
1298 if (!qdict) {
1299 qdict = qdict_new();
1301 if (opts->id) {
1302 qdict_put(qdict, "id", qstring_from_str(opts->id));
1304 QTAILQ_FOREACH(opt, &opts->head, next) {
1305 val = QOBJECT(qstring_from_str(opt->str));
1306 qdict_put_obj(qdict, opt->name, val);
1308 return qdict;
1311 /* Validate parsed opts against descriptions where no
1312 * descriptions were provided in the QemuOptsList.
1314 void qemu_opts_validate(QemuOpts *opts, const QemuOptDesc *desc, Error **errp)
1316 QemuOpt *opt;
1317 Error *local_err = NULL;
1319 assert(opts_accepts_any(opts));
1321 QTAILQ_FOREACH(opt, &opts->head, next) {
1322 opt->desc = find_desc_by_name(desc, opt->name);
1323 if (!opt->desc) {
1324 error_set(errp, QERR_INVALID_PARAMETER, opt->name);
1325 return;
1328 qemu_opt_parse(opt, &local_err);
1329 if (local_err) {
1330 error_propagate(errp, local_err);
1331 return;
1336 int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func, void *opaque,
1337 int abort_on_failure)
1339 Location loc;
1340 QemuOpts *opts;
1341 int rc = 0;
1343 loc_push_none(&loc);
1344 QTAILQ_FOREACH(opts, &list->head, next) {
1345 loc_restore(&opts->loc);
1346 rc |= func(opts, opaque);
1347 if (abort_on_failure && rc != 0)
1348 break;
1350 loc_pop(&loc);
1351 return rc;
1354 static size_t count_opts_list(QemuOptsList *list)
1356 QemuOptDesc *desc = NULL;
1357 size_t num_opts = 0;
1359 if (!list) {
1360 return 0;
1363 desc = list->desc;
1364 while (desc && desc->name) {
1365 num_opts++;
1366 desc++;
1369 return num_opts;
1372 /* Convert QEMUOptionParameter to QemuOpts
1373 * FIXME: this function will be removed after all drivers
1374 * switch to QemuOpts
1376 QemuOptsList *params_to_opts(QEMUOptionParameter *list)
1378 QemuOptsList *opts = NULL;
1379 size_t num_opts, i = 0;
1381 if (!list) {
1382 return NULL;
1385 num_opts = count_option_parameters(list);
1386 opts = g_malloc0(sizeof(QemuOptsList) +
1387 (num_opts + 1) * sizeof(QemuOptDesc));
1388 QTAILQ_INIT(&opts->head);
1389 /* (const char *) members will point to malloced space and need to free */
1390 opts->allocated = true;
1392 while (list && list->name) {
1393 opts->desc[i].name = g_strdup(list->name);
1394 opts->desc[i].help = g_strdup(list->help);
1395 switch (list->type) {
1396 case OPT_FLAG:
1397 opts->desc[i].type = QEMU_OPT_BOOL;
1398 opts->desc[i].def_value_str =
1399 g_strdup(list->value.n ? "on" : "off");
1400 break;
1402 case OPT_NUMBER:
1403 opts->desc[i].type = QEMU_OPT_NUMBER;
1404 if (list->value.n) {
1405 opts->desc[i].def_value_str =
1406 g_strdup_printf("%" PRIu64, list->value.n);
1408 break;
1410 case OPT_SIZE:
1411 opts->desc[i].type = QEMU_OPT_SIZE;
1412 if (list->value.n) {
1413 opts->desc[i].def_value_str =
1414 g_strdup_printf("%" PRIu64, list->value.n);
1416 break;
1418 case OPT_STRING:
1419 opts->desc[i].type = QEMU_OPT_STRING;
1420 opts->desc[i].def_value_str = g_strdup(list->value.s);
1421 break;
1424 i++;
1425 list++;
1428 return opts;
1431 /* convert QemuOpts to QEMUOptionParameter
1432 * Note: result QEMUOptionParameter has shorter lifetime than
1433 * input QemuOpts.
1434 * FIXME: this function will be removed after all drivers
1435 * switch to QemuOpts
1437 QEMUOptionParameter *opts_to_params(QemuOpts *opts)
1439 QEMUOptionParameter *dest = NULL;
1440 QemuOptDesc *desc;
1441 size_t num_opts, i = 0;
1442 const char *tmp;
1444 if (!opts || !opts->list || !opts->list->desc) {
1445 return NULL;
1447 assert(!opts_accepts_any(opts));
1449 num_opts = count_opts_list(opts->list);
1450 dest = g_malloc0((num_opts + 1) * sizeof(QEMUOptionParameter));
1452 desc = opts->list->desc;
1453 while (desc && desc->name) {
1454 dest[i].name = desc->name;
1455 dest[i].help = desc->help;
1456 dest[i].assigned = qemu_opt_find(opts, desc->name) ? true : false;
1457 switch (desc->type) {
1458 case QEMU_OPT_STRING:
1459 dest[i].type = OPT_STRING;
1460 tmp = qemu_opt_get(opts, desc->name);
1461 dest[i].value.s = g_strdup(tmp);
1462 break;
1464 case QEMU_OPT_BOOL:
1465 dest[i].type = OPT_FLAG;
1466 dest[i].value.n = qemu_opt_get_bool(opts, desc->name, 0) ? 1 : 0;
1467 break;
1469 case QEMU_OPT_NUMBER:
1470 dest[i].type = OPT_NUMBER;
1471 dest[i].value.n = qemu_opt_get_number(opts, desc->name, 0);
1472 break;
1474 case QEMU_OPT_SIZE:
1475 dest[i].type = OPT_SIZE;
1476 dest[i].value.n = qemu_opt_get_size(opts, desc->name, 0);
1477 break;
1480 i++;
1481 desc++;
1484 return dest;
1487 void qemu_opts_free(QemuOptsList *list)
1489 /* List members point to new malloced space and need to be freed.
1490 * FIXME:
1491 * Introduced for QEMUOptionParamter->QemuOpts conversion.
1492 * Will remove after all drivers switch to QemuOpts.
1494 if (list && list->allocated) {
1495 QemuOptDesc *desc = list->desc;
1496 while (desc && desc->name) {
1497 g_free((char *)desc->name);
1498 g_free((char *)desc->help);
1499 g_free((char *)desc->def_value_str);
1500 desc++;
1504 g_free(list);
1507 /* Realloc dst option list and append options either from an option list (list)
1508 * or a QEMUOptionParameter (param) to it. dst could be NULL or a malloced list.
1509 * FIXME: will remove QEMUOptionParameter after all drivers switch to QemuOpts.
1511 QemuOptsList *qemu_opts_append(QemuOptsList *dst,
1512 QemuOptsList *list,
1513 QEMUOptionParameter *param)
1515 size_t num_opts, num_dst_opts;
1516 QemuOptDesc *desc;
1517 bool need_init = false;
1519 assert(!(list && param));
1520 if (!param && !list) {
1521 return dst;
1524 if (param) {
1525 list = params_to_opts(param);
1528 /* If dst is NULL, after realloc, some area of dst should be initialized
1529 * before adding options to it.
1531 if (!dst) {
1532 need_init = true;
1535 num_opts = count_opts_list(dst);
1536 num_dst_opts = num_opts;
1537 num_opts += count_opts_list(list);
1538 dst = g_realloc(dst, sizeof(QemuOptsList) +
1539 (num_opts + 1) * sizeof(QemuOptDesc));
1540 if (need_init) {
1541 dst->name = NULL;
1542 dst->implied_opt_name = NULL;
1543 QTAILQ_INIT(&dst->head);
1544 dst->allocated = true;
1545 dst->merge_lists = false;
1547 dst->desc[num_dst_opts].name = NULL;
1549 /* (const char *) members of result dst are malloced, need free. */
1550 assert(dst->allocated);
1551 /* append list->desc to dst->desc */
1552 if (list) {
1553 desc = list->desc;
1554 while (desc && desc->name) {
1555 if (find_desc_by_name(dst->desc, desc->name) == NULL) {
1556 dst->desc[num_dst_opts].name = g_strdup(desc->name);
1557 dst->desc[num_dst_opts].type = desc->type;
1558 dst->desc[num_dst_opts].help = g_strdup(desc->help);
1559 dst->desc[num_dst_opts].def_value_str =
1560 g_strdup(desc->def_value_str);
1561 num_dst_opts++;
1562 dst->desc[num_dst_opts].name = NULL;
1564 desc++;
1568 if (param) {
1569 qemu_opts_free(list);
1571 return dst;