2 * Commandline option parsing functions
4 * Copyright (c) 2003-2008 Fabrice Bellard
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
29 #include "qemu-common.h"
30 #include "qemu-error.h"
31 #include "qemu-objects.h"
34 #include "qemu-option-internal.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
47 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
52 while (*p != '\0' && *p != delim) {
53 if (q && (q - buf) < buf_size - 1)
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)
82 if (q && (q - buf) < buf_size - 1)
92 int get_next_param_value(char *buf, int buf_size,
93 const char *tag, const char **pstr)
100 p = get_opt_name(option, sizeof(option), p, '=');
104 if (!strcmp(tag, option)) {
105 *pstr = get_opt_value(buf, buf_size, p);
111 p = get_opt_value(NULL, 0, p);
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);
126 int check_params(char *buf, int buf_size,
127 const char * const *params, const char *str)
134 p = get_opt_name(buf, buf_size, p, '=');
139 for (i = 0; params[i] != NULL; i++) {
140 if (!strcmp(params[i], buf)) {
144 if (params[i] == NULL) {
147 p = get_opt_value(NULL, 0, p);
157 * Searches an option list for an option with the given name
159 QEMUOptionParameter *get_option_parameter(QEMUOptionParameter *list,
162 while (list && list->name) {
163 if (!strcmp(list->name, name)) {
172 static void parse_option_bool(const char *name, const char *value, bool *ret,
176 if (!strcmp(value, "on")) {
178 } else if (!strcmp(value, "off")) {
181 error_set(errp,QERR_INVALID_PARAMETER_VALUE, name, "'on' or 'off'");
188 static void parse_option_number(const char *name, const char *value,
189 uint64_t *ret, Error **errp)
195 number = strtoull(value, &postfix, 0);
196 if (*postfix != '\0') {
197 error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
202 error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
206 static void parse_option_size(const char *name, const char *value,
207 uint64_t *ret, Error **errp)
213 sizef = strtod(value, &postfix);
230 *ret = (uint64_t) sizef;
233 error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
234 error_printf_unless_qmp("You may use k, M, G or T suffixes for "
235 "kilobytes, megabytes, gigabytes and terabytes.\n");
239 error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
244 * Sets the value of a parameter in a given option list. The parsing of the
245 * value depends on the type of option:
247 * OPT_FLAG (uses value.n):
248 * If no value is given, the flag is set to 1.
249 * Otherwise the value must be "on" (set to 1) or "off" (set to 0)
251 * OPT_STRING (uses value.s):
252 * value is strdup()ed and assigned as option value
254 * OPT_SIZE (uses value.n):
255 * The value is converted to an integer. Suffixes for kilobytes etc. are
256 * allowed (powers of 1024).
258 * Returns 0 on succes, -1 in error cases
260 int set_option_parameter(QEMUOptionParameter *list, const char *name,
264 Error *local_err = NULL;
266 // Find a matching parameter
267 list = get_option_parameter(list, name);
269 fprintf(stderr, "Unknown option '%s'\n", name);
274 switch (list->type) {
276 parse_option_bool(name, value, &flag, &local_err);
277 if (!error_is_set(&local_err)) {
278 list->value.n = flag;
284 list->value.s = g_strdup(value);
286 fprintf(stderr, "Option '%s' needs a parameter\n", name);
292 parse_option_size(name, value, &list->value.n, &local_err);
296 fprintf(stderr, "Bug: Option '%s' has an unknown type\n", name);
300 if (error_is_set(&local_err)) {
301 qerror_report_err(local_err);
302 error_free(local_err);
310 * Sets the given parameter to an integer instead of a string.
311 * This function cannot be used to set string options.
313 * Returns 0 on success, -1 in error cases
315 int set_option_parameter_int(QEMUOptionParameter *list, const char *name,
318 // Find a matching parameter
319 list = get_option_parameter(list, name);
321 fprintf(stderr, "Unknown option '%s'\n", name);
326 switch (list->type) {
330 list->value.n = value;
341 * Frees a option list. If it contains strings, the strings are freed as well.
343 void free_option_parameters(QEMUOptionParameter *list)
345 QEMUOptionParameter *cur = list;
347 while (cur && cur->name) {
348 if (cur->type == OPT_STRING) {
349 g_free(cur->value.s);
358 * Count valid options in list
360 static size_t count_option_parameters(QEMUOptionParameter *list)
362 size_t num_options = 0;
364 while (list && list->name) {
373 * Append an option list (list) to an option list (dest).
375 * If dest is NULL, a new copy of list is created.
377 * Returns a pointer to the first element of dest (or the newly allocated copy)
379 QEMUOptionParameter *append_option_parameters(QEMUOptionParameter *dest,
380 QEMUOptionParameter *list)
382 size_t num_options, num_dest_options;
384 num_options = count_option_parameters(dest);
385 num_dest_options = num_options;
387 num_options += count_option_parameters(list);
389 dest = g_realloc(dest, (num_options + 1) * sizeof(QEMUOptionParameter));
390 dest[num_dest_options].name = NULL;
392 while (list && list->name) {
393 if (get_option_parameter(dest, list->name) == NULL) {
394 dest[num_dest_options++] = *list;
395 dest[num_dest_options].name = NULL;
404 * Parses a parameter string (param) into an option list (dest).
406 * list is the template option list. If dest is NULL, a new copy of list is
407 * created. If list is NULL, this function fails.
409 * A parameter string consists of one or more parameters, separated by commas.
410 * Each parameter consists of its name and possibly of a value. In the latter
411 * case, the value is delimited by an = character. To specify a value which
412 * contains commas, double each comma so it won't be recognized as the end of
415 * For more details of the parsing see above.
417 * Returns a pointer to the first element of dest (or the newly allocated copy)
418 * or NULL in error cases
420 QEMUOptionParameter *parse_option_parameters(const char *param,
421 QEMUOptionParameter *list, QEMUOptionParameter *dest)
423 QEMUOptionParameter *allocated = NULL;
426 char *param_delim, *value_delim;
434 dest = allocated = append_option_parameters(NULL, list);
439 // Find parameter name and value in the string
440 param_delim = strchr(param, ',');
441 value_delim = strchr(param, '=');
443 if (value_delim && (value_delim < param_delim || !param_delim)) {
450 param = get_opt_name(name, sizeof(name), param, next_delim);
452 param = get_opt_value(value, sizeof(value), param + 1);
454 if (*param != '\0') {
459 if (set_option_parameter(dest, name, value_delim ? value : NULL)) {
467 // Only free the list if it was newly allocated
468 free_option_parameters(allocated);
473 * Prints all options of a list that have a value to stdout
475 void print_option_parameters(QEMUOptionParameter *list)
477 while (list && list->name) {
478 switch (list->type) {
480 if (list->value.s != NULL) {
481 printf("%s='%s' ", list->name, list->value.s);
485 printf("%s=%s ", list->name, list->value.n ? "on" : "off");
489 printf("%s=%" PRId64 " ", list->name, list->value.n);
492 printf("%s=(unknown type) ", list->name);
500 * Prints an overview of all available options
502 void print_option_help(QEMUOptionParameter *list)
504 printf("Supported options:\n");
505 while (list && list->name) {
506 printf("%-16s %s\n", list->name,
507 list->help ? list->help : "No description available");
512 /* ------------------------------------------------------------------ */
514 static QemuOpt *qemu_opt_find(QemuOpts *opts, const char *name)
518 QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
519 if (strcmp(opt->name, name) != 0)
526 const char *qemu_opt_get(QemuOpts *opts, const char *name)
528 QemuOpt *opt = qemu_opt_find(opts, name);
529 return opt ? opt->str : NULL;
532 bool qemu_opt_get_bool(QemuOpts *opts, const char *name, bool defval)
534 QemuOpt *opt = qemu_opt_find(opts, name);
538 assert(opt->desc && opt->desc->type == QEMU_OPT_BOOL);
539 return opt->value.boolean;
542 uint64_t qemu_opt_get_number(QemuOpts *opts, const char *name, uint64_t defval)
544 QemuOpt *opt = qemu_opt_find(opts, name);
548 assert(opt->desc && opt->desc->type == QEMU_OPT_NUMBER);
549 return opt->value.uint;
552 uint64_t qemu_opt_get_size(QemuOpts *opts, const char *name, uint64_t defval)
554 QemuOpt *opt = qemu_opt_find(opts, name);
558 assert(opt->desc && opt->desc->type == QEMU_OPT_SIZE);
559 return opt->value.uint;
562 static void qemu_opt_parse(QemuOpt *opt, Error **errp)
564 if (opt->desc == NULL)
567 switch (opt->desc->type) {
568 case QEMU_OPT_STRING:
572 parse_option_bool(opt->name, opt->str, &opt->value.boolean, errp);
574 case QEMU_OPT_NUMBER:
575 parse_option_number(opt->name, opt->str, &opt->value.uint, errp);
578 parse_option_size(opt->name, opt->str, &opt->value.uint, errp);
585 static void qemu_opt_del(QemuOpt *opt)
587 QTAILQ_REMOVE(&opt->opts->head, opt, next);
588 g_free((/* !const */ char*)opt->name);
589 g_free((/* !const */ char*)opt->str);
593 static void opt_set(QemuOpts *opts, const char *name, const char *value,
594 bool prepend, Error **errp)
597 const QemuOptDesc *desc = opts->list->desc;
598 Error *local_err = NULL;
601 for (i = 0; desc[i].name != NULL; i++) {
602 if (strcmp(desc[i].name, name) == 0) {
606 if (desc[i].name == NULL) {
608 /* empty list -> allow any */;
610 error_set(errp, QERR_INVALID_PARAMETER, name);
615 opt = g_malloc0(sizeof(*opt));
616 opt->name = g_strdup(name);
619 QTAILQ_INSERT_HEAD(&opts->head, opt, next);
621 QTAILQ_INSERT_TAIL(&opts->head, opt, next);
623 if (desc[i].name != NULL) {
627 opt->str = g_strdup(value);
629 qemu_opt_parse(opt, &local_err);
630 if (error_is_set(&local_err)) {
631 error_propagate(errp, local_err);
636 int qemu_opt_set(QemuOpts *opts, const char *name, const char *value)
638 Error *local_err = NULL;
640 opt_set(opts, name, value, false, &local_err);
641 if (error_is_set(&local_err)) {
642 qerror_report_err(local_err);
643 error_free(local_err);
650 void qemu_opt_set_err(QemuOpts *opts, const char *name, const char *value,
653 opt_set(opts, name, value, false, errp);
656 int qemu_opt_set_bool(QemuOpts *opts, const char *name, bool val)
659 const QemuOptDesc *desc = opts->list->desc;
662 for (i = 0; desc[i].name != NULL; i++) {
663 if (strcmp(desc[i].name, name) == 0) {
667 if (desc[i].name == NULL) {
669 /* empty list -> allow any */;
671 qerror_report(QERR_INVALID_PARAMETER, name);
676 opt = g_malloc0(sizeof(*opt));
677 opt->name = g_strdup(name);
679 QTAILQ_INSERT_TAIL(&opts->head, opt, next);
680 if (desc[i].name != NULL) {
683 opt->value.boolean = !!val;
687 int qemu_opt_foreach(QemuOpts *opts, qemu_opt_loopfunc func, void *opaque,
688 int abort_on_failure)
693 QTAILQ_FOREACH(opt, &opts->head, next) {
694 rc = func(opt->name, opt->str, opaque);
695 if (abort_on_failure && rc != 0)
701 QemuOpts *qemu_opts_find(QemuOptsList *list, const char *id)
705 QTAILQ_FOREACH(opts, &list->head, next) {
712 if (strcmp(opts->id, id) != 0) {
720 static int id_wellformed(const char *id)
724 if (!qemu_isalpha(id[0])) {
727 for (i = 1; id[i]; i++) {
728 if (!qemu_isalnum(id[i]) && !strchr("-._", id[i])) {
735 QemuOpts *qemu_opts_create(QemuOptsList *list, const char *id,
736 int fail_if_exists, Error **errp)
738 QemuOpts *opts = NULL;
741 if (!id_wellformed(id)) {
742 error_set(errp,QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
743 error_printf_unless_qmp("Identifiers consist of letters, digits, '-', '.', '_', starting with a letter.\n");
746 opts = qemu_opts_find(list, id);
748 if (fail_if_exists && !list->merge_lists) {
749 error_set(errp, QERR_DUPLICATE_ID, id, list->name);
755 } else if (list->merge_lists) {
756 opts = qemu_opts_find(list, NULL);
761 opts = g_malloc0(sizeof(*opts));
763 opts->id = g_strdup(id);
766 loc_save(&opts->loc);
767 QTAILQ_INIT(&opts->head);
768 QTAILQ_INSERT_TAIL(&list->head, opts, next);
772 void qemu_opts_reset(QemuOptsList *list)
774 QemuOpts *opts, *next_opts;
776 QTAILQ_FOREACH_SAFE(opts, &list->head, next, next_opts) {
781 void qemu_opts_loc_restore(QemuOpts *opts)
783 loc_restore(&opts->loc);
786 int qemu_opts_set(QemuOptsList *list, const char *id,
787 const char *name, const char *value)
790 Error *local_err = NULL;
792 opts = qemu_opts_create(list, id, 1, &local_err);
793 if (error_is_set(&local_err)) {
794 qerror_report_err(local_err);
795 error_free(local_err);
798 return qemu_opt_set(opts, name, value);
801 const char *qemu_opts_id(QemuOpts *opts)
806 void qemu_opts_del(QemuOpts *opts)
811 opt = QTAILQ_FIRST(&opts->head);
816 QTAILQ_REMOVE(&opts->list->head, opts, next);
821 int qemu_opts_print(QemuOpts *opts, void *dummy)
825 fprintf(stderr, "%s: %s:", opts->list->name,
826 opts->id ? opts->id : "<noid>");
827 QTAILQ_FOREACH(opt, &opts->head, next) {
828 fprintf(stderr, " %s=\"%s\"", opt->name, opt->str);
830 fprintf(stderr, "\n");
834 static int opts_do_parse(QemuOpts *opts, const char *params,
835 const char *firstname, bool prepend)
837 char option[128], value[1024];
838 const char *p,*pe,*pc;
839 Error *local_err = NULL;
841 for (p = params; *p != '\0'; p++) {
844 if (!pe || (pc && pc < pe)) {
845 /* found "foo,more" */
846 if (p == params && firstname) {
847 /* implicitly named first option */
848 pstrcpy(option, sizeof(option), firstname);
849 p = get_opt_value(value, sizeof(value), p);
851 /* option without value, probably a flag */
852 p = get_opt_name(option, sizeof(option), p, ',');
853 if (strncmp(option, "no", 2) == 0) {
854 memmove(option, option+2, strlen(option+2)+1);
855 pstrcpy(value, sizeof(value), "off");
857 pstrcpy(value, sizeof(value), "on");
861 /* found "foo=bar,more" */
862 p = get_opt_name(option, sizeof(option), p, '=');
867 p = get_opt_value(value, sizeof(value), p);
869 if (strcmp(option, "id") != 0) {
870 /* store and parse */
871 opt_set(opts, option, value, prepend, &local_err);
872 if (error_is_set(&local_err)) {
873 qerror_report_err(local_err);
874 error_free(local_err);
885 int qemu_opts_do_parse(QemuOpts *opts, const char *params, const char *firstname)
887 return opts_do_parse(opts, params, firstname, false);
890 static QemuOpts *opts_parse(QemuOptsList *list, const char *params,
891 int permit_abbrev, bool defaults)
893 const char *firstname;
894 char value[1024], *id = NULL;
897 Error *local_err = NULL;
899 assert(!permit_abbrev || list->implied_opt_name);
900 firstname = permit_abbrev ? list->implied_opt_name : NULL;
902 if (strncmp(params, "id=", 3) == 0) {
903 get_opt_value(value, sizeof(value), params+3);
905 } else if ((p = strstr(params, ",id=")) != NULL) {
906 get_opt_value(value, sizeof(value), p+4);
910 if (!id && !QTAILQ_EMPTY(&list->head)) {
911 opts = qemu_opts_find(list, NULL);
913 opts = qemu_opts_create(list, id, 0, &local_err);
916 opts = qemu_opts_create(list, id, 1, &local_err);
919 if (error_is_set(&local_err)) {
920 qerror_report_err(local_err);
921 error_free(local_err);
926 if (opts_do_parse(opts, params, firstname, defaults) != 0) {
934 QemuOpts *qemu_opts_parse(QemuOptsList *list, const char *params,
937 return opts_parse(list, params, permit_abbrev, false);
940 void qemu_opts_set_defaults(QemuOptsList *list, const char *params,
945 opts = opts_parse(list, params, permit_abbrev, true);
949 typedef struct OptsFromQDictState {
952 } OptsFromQDictState;
954 static void qemu_opts_from_qdict_1(const char *key, QObject *obj, void *opaque)
956 OptsFromQDictState *state = opaque;
961 if (!strcmp(key, "id") || error_is_set(state->errp)) {
965 switch (qobject_type(obj)) {
967 value = qstring_get_str(qobject_to_qstring(obj));
970 n = snprintf(buf, sizeof(buf), "%" PRId64,
971 qint_get_int(qobject_to_qint(obj)));
972 assert(n < sizeof(buf));
976 n = snprintf(buf, sizeof(buf), "%.17g",
977 qfloat_get_double(qobject_to_qfloat(obj)));
978 assert(n < sizeof(buf));
982 pstrcpy(buf, sizeof(buf),
983 qbool_get_int(qobject_to_qbool(obj)) ? "on" : "off");
990 qemu_opt_set_err(state->opts, key, value, state->errp);
994 * Create QemuOpts from a QDict.
995 * Use value of key "id" as ID if it exists and is a QString.
996 * Only QStrings, QInts, QFloats and QBools are copied. Entries with
997 * other types are silently ignored.
999 QemuOpts *qemu_opts_from_qdict(QemuOptsList *list, const QDict *qdict,
1002 OptsFromQDictState state;
1003 Error *local_err = NULL;
1006 opts = qemu_opts_create(list, qdict_get_try_str(qdict, "id"), 1,
1008 if (error_is_set(&local_err)) {
1009 error_propagate(errp, local_err);
1013 assert(opts != NULL);
1015 state.errp = &local_err;
1017 qdict_iter(qdict, qemu_opts_from_qdict_1, &state);
1018 if (error_is_set(&local_err)) {
1019 error_propagate(errp, local_err);
1020 qemu_opts_del(opts);
1028 * Convert from QemuOpts to QDict.
1029 * The QDict values are of type QString.
1030 * TODO We'll want to use types appropriate for opt->desc->type, but
1031 * this is enough for now.
1033 QDict *qemu_opts_to_qdict(QemuOpts *opts, QDict *qdict)
1039 qdict = qdict_new();
1042 qdict_put(qdict, "id", qstring_from_str(opts->id));
1044 QTAILQ_FOREACH(opt, &opts->head, next) {
1045 val = QOBJECT(qstring_from_str(opt->str));
1046 qdict_put_obj(qdict, opt->name, val);
1051 /* Validate parsed opts against descriptions where no
1052 * descriptions were provided in the QemuOptsList.
1054 void qemu_opts_validate(QemuOpts *opts, const QemuOptDesc *desc, Error **errp)
1057 Error *local_err = NULL;
1059 assert(opts->list->desc[0].name == NULL);
1061 QTAILQ_FOREACH(opt, &opts->head, next) {
1064 for (i = 0; desc[i].name != NULL; i++) {
1065 if (strcmp(desc[i].name, opt->name) == 0) {
1069 if (desc[i].name == NULL) {
1070 error_set(errp, QERR_INVALID_PARAMETER, opt->name);
1074 opt->desc = &desc[i];
1076 qemu_opt_parse(opt, &local_err);
1077 if (error_is_set(&local_err)) {
1078 error_propagate(errp, local_err);
1084 int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func, void *opaque,
1085 int abort_on_failure)
1091 loc_push_none(&loc);
1092 QTAILQ_FOREACH(opts, &list->head, next) {
1093 loc_restore(&opts->loc);
1094 rc |= func(opts, opaque);
1095 if (abort_on_failure && rc != 0)