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