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