qemu-option.c 31.5 KB
Newer Older
K
Kevin Wolf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Commandline option parsing functions
 *
 * Copyright (c) 2003-2008 Fabrice Bellard
 * Copyright (c) 2009 Kevin Wolf <kwolf@redhat.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

P
Peter Maydell 已提交
26
#include "qemu/osdep.h"
K
Kevin Wolf 已提交
27

28
#include "qapi/error.h"
K
Kevin Wolf 已提交
29
#include "qemu-common.h"
30
#include "qemu/error-report.h"
M
Markus Armbruster 已提交
31 32
#include "qapi/qmp/qbool.h"
#include "qapi/qmp/qdict.h"
33
#include "qapi/qmp/qnum.h"
M
Markus Armbruster 已提交
34
#include "qapi/qmp/qstring.h"
35
#include "qapi/qmp/qerror.h"
36
#include "qemu/option_int.h"
37 38 39
#include "qemu/cutils.h"
#include "qemu/id.h"
#include "qemu/help_option.h"
K
Kevin Wolf 已提交
40 41 42 43 44 45

/*
 * Extracts the name of an option from the parameter string (p points at the
 * first byte of the option name)
 *
 * The option name is delimited by delim (usually , or =) or the string end
46 47
 * and is copied into option. The caller is responsible for free'ing option
 * when no longer required.
K
Kevin Wolf 已提交
48 49 50 51
 *
 * The return value is the position of the delimiter/zero byte after the option
 * name in p.
 */
52
static const char *get_opt_name(const char *p, char **option, char delim)
K
Kevin Wolf 已提交
53
{
54
    char *offset = strchr(p, delim);
K
Kevin Wolf 已提交
55

56 57 58 59 60 61
    if (offset) {
        *option = g_strndup(p, offset - p);
        return offset;
    } else {
        *option = g_strdup(p);
        return p + strlen(p);
K
Kevin Wolf 已提交
62 63 64 65 66 67 68 69 70 71 72
    }
}

/*
 * Extracts the value of an option from the parameter string p (p points at the
 * first byte of the option value)
 *
 * This function is comparable to get_opt_name with the difference that the
 * delimiter is fixed to be comma which starts a new option. To specify an
 * option value that contains commas, double each comma.
 */
73
const char *get_opt_value(const char *p, char **value)
K
Kevin Wolf 已提交
74
{
75 76
    size_t capacity = 0, length;
    const char *offset;
K
Kevin Wolf 已提交
77

78 79 80
    if (value) {
        *value = NULL;
    }
81
    while (1) {
K
Keno Fischer 已提交
82
        offset = qemu_strchrnul(p, ',');
83 84 85 86 87 88 89 90
        length = offset - p;
        if (*offset != '\0' && *(offset + 1) == ',') {
            length++;
        }
        if (value) {
            *value = g_renew(char, *value, capacity + length + 1);
            strncpy(*value + capacity, p, length);
            (*value)[capacity + length] = '\0';
K
Kevin Wolf 已提交
91
        }
92 93 94 95 96 97 98
        capacity += length;
        if (*offset == '\0' ||
            *(offset + 1) != ',') {
            break;
        }

        p += (offset - p) + 2;
K
Kevin Wolf 已提交
99 100
    }

101
    return offset;
K
Kevin Wolf 已提交
102 103
}

104 105
static void parse_option_bool(const char *name, const char *value, bool *ret,
                              Error **errp)
106
{
107
    if (!strcmp(value, "on")) {
108
        *ret = 1;
109 110 111 112 113
    } else if (!strcmp(value, "off")) {
        *ret = 0;
    } else {
        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
                   name, "'on' or 'off'");
114 115 116
    }
}

117 118
static void parse_option_number(const char *name, const char *value,
                                uint64_t *ret, Error **errp)
119 120
{
    uint64_t number;
121
    int err;
122

123 124 125 126 127 128 129
    err = qemu_strtou64(value, NULL, 0, &number);
    if (err == -ERANGE) {
        error_setg(errp, "Value '%s' is too large for parameter '%s'",
                   value, name);
        return;
    }
    if (err) {
130
        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
131
        return;
132
    }
133
    *ret = number;
134 135
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149
static const QemuOptDesc *find_desc_by_name(const QemuOptDesc *desc,
                                            const char *name)
{
    int i;

    for (i = 0; desc[i].name != NULL; i++) {
        if (strcmp(desc[i].name, name) == 0) {
            return &desc[i];
        }
    }

    return NULL;
}

150 151
void parse_option_size(const char *name, const char *value,
                       uint64_t *ret, Error **errp)
152
{
153 154
    uint64_t size;
    int err;
155

156 157
    err = qemu_strtosz(value, NULL, &size);
    if (err == -ERANGE) {
158
        error_setg(errp, "Value '%s' is out of range for parameter '%s'",
159
                   value, name);
160 161
        return;
    }
162 163 164 165 166 167
    if (err) {
        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name,
                   "a non-negative number below 2^64");
        error_append_hint(errp, "Optional suffix k, M, G, T, P or E means"
                          " kilo-, mega-, giga-, tera-, peta-\n"
                          "and exabytes, respectively.\n");
168
        return;
169
    }
170
    *ret = size;
171 172
}

173 174 175 176 177
bool has_help_option(const char *param)
{
    const char *p = param;
    bool result = false;

178 179 180 181
    while (*p && !result) {
        char *value;

        p = get_opt_value(p, &value);
182 183 184 185
        if (*p) {
            p++;
        }

186 187
        result = is_help_option(value);
        g_free(value);
188 189 190 191 192
    }

    return result;
}

193
bool is_valid_option_list(const char *p)
194
{
195 196
    char *value = NULL;
    bool result = false;
197 198

    while (*p) {
199 200 201
        p = get_opt_value(p, &value);
        if ((*p && !*++p) ||
            (!*value || *value == ',')) {
202 203 204
            goto out;
        }

205 206
        g_free(value);
        value = NULL;
207 208
    }

209
    result = true;
210
out:
211
    g_free(value);
212 213 214
    return result;
}

215 216 217 218 219 220 221 222 223 224 225 226
void qemu_opts_print_help(QemuOptsList *list)
{
    QemuOptDesc *desc;

    assert(list);
    desc = list->desc;
    while (desc && desc->name) {
        printf("%-16s %s\n", desc->name,
               desc->help ? desc->help : "No description available");
        desc++;
    }
}
227 228
/* ------------------------------------------------------------------ */

C
Chunyan Liu 已提交
229
QemuOpt *qemu_opt_find(QemuOpts *opts, const char *name)
230 231 232
{
    QemuOpt *opt;

M
Mark McLoughlin 已提交
233
    QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
234 235 236 237 238 239 240
        if (strcmp(opt->name, name) != 0)
            continue;
        return opt;
    }
    return NULL;
}

241 242 243 244 245 246 247 248
static void qemu_opt_del(QemuOpt *opt)
{
    QTAILQ_REMOVE(&opt->opts->head, opt, next);
    g_free(opt->name);
    g_free(opt->str);
    g_free(opt);
}

249 250 251 252 253 254 255 256 257 258 259 260 261 262
/* qemu_opt_set allows many settings for the same option.
 * This function deletes all settings for an option.
 */
static void qemu_opt_del_all(QemuOpts *opts, const char *name)
{
    QemuOpt *opt, *next_opt;

    QTAILQ_FOREACH_SAFE(opt, &opts->head, next, next_opt) {
        if (!strcmp(opt->name, name)) {
            qemu_opt_del(opt);
        }
    }
}

263 264
const char *qemu_opt_get(QemuOpts *opts, const char *name)
{
265 266 267 268 269
    QemuOpt *opt;

    if (opts == NULL) {
        return NULL;
    }
270

271
    opt = qemu_opt_find(opts, name);
272 273 274 275 276 277
    if (!opt) {
        const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
        if (desc && desc->def_value_str) {
            return desc->def_value_str;
        }
    }
278 279 280
    return opt ? opt->str : NULL;
}

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
void qemu_opt_iter_init(QemuOptsIter *iter, QemuOpts *opts, const char *name)
{
    iter->opts = opts;
    iter->opt = QTAILQ_FIRST(&opts->head);
    iter->name = name;
}

const char *qemu_opt_iter_next(QemuOptsIter *iter)
{
    QemuOpt *ret = iter->opt;
    if (iter->name) {
        while (ret && !g_str_equal(iter->name, ret->name)) {
            ret = QTAILQ_NEXT(ret, next);
        }
    }
    iter->opt = ret ? QTAILQ_NEXT(ret, next) : NULL;
    return ret ? ret->str : NULL;
}

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
/* Get a known option (or its default) and remove it from the list
 * all in one action. Return a malloced string of the option value.
 * Result must be freed by caller with g_free().
 */
char *qemu_opt_get_del(QemuOpts *opts, const char *name)
{
    QemuOpt *opt;
    const QemuOptDesc *desc;
    char *str = NULL;

    if (opts == NULL) {
        return NULL;
    }

    opt = qemu_opt_find(opts, name);
    if (!opt) {
        desc = find_desc_by_name(opts->list->desc, name);
        if (desc && desc->def_value_str) {
            str = g_strdup(desc->def_value_str);
        }
        return str;
    }
    str = opt->str;
    opt->str = NULL;
    qemu_opt_del_all(opts, name);
    return str;
}

328 329 330 331 332 333 334 335 336 337 338 339
bool qemu_opt_has_help_opt(QemuOpts *opts)
{
    QemuOpt *opt;

    QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
        if (is_help_option(opt->name)) {
            return true;
        }
    }
    return false;
}

340 341
static bool qemu_opt_get_bool_helper(QemuOpts *opts, const char *name,
                                     bool defval, bool del)
342
{
343
    QemuOpt *opt;
344
    bool ret = defval;
345

346 347 348 349 350
    if (opts == NULL) {
        return ret;
    }

    opt = qemu_opt_find(opts, name);
351 352 353
    if (opt == NULL) {
        const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
        if (desc && desc->def_value_str) {
354
            parse_option_bool(name, desc->def_value_str, &ret, &error_abort);
355
        }
356
        return ret;
357
    }
358
    assert(opt->desc && opt->desc->type == QEMU_OPT_BOOL);
359 360 361 362 363
    ret = opt->value.boolean;
    if (del) {
        qemu_opt_del_all(opts, name);
    }
    return ret;
364 365
}

366 367 368 369 370 371 372 373 374 375 376 377
bool qemu_opt_get_bool(QemuOpts *opts, const char *name, bool defval)
{
    return qemu_opt_get_bool_helper(opts, name, defval, false);
}

bool qemu_opt_get_bool_del(QemuOpts *opts, const char *name, bool defval)
{
    return qemu_opt_get_bool_helper(opts, name, defval, true);
}

static uint64_t qemu_opt_get_number_helper(QemuOpts *opts, const char *name,
                                           uint64_t defval, bool del)
378
{
379
    QemuOpt *opt;
380
    uint64_t ret = defval;
381

382 383 384 385 386
    if (opts == NULL) {
        return ret;
    }

    opt = qemu_opt_find(opts, name);
387 388 389
    if (opt == NULL) {
        const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
        if (desc && desc->def_value_str) {
390
            parse_option_number(name, desc->def_value_str, &ret, &error_abort);
391
        }
392
        return ret;
393
    }
394
    assert(opt->desc && opt->desc->type == QEMU_OPT_NUMBER);
395 396 397 398 399
    ret = opt->value.uint;
    if (del) {
        qemu_opt_del_all(opts, name);
    }
    return ret;
400 401
}

402 403 404 405 406 407 408 409 410 411 412 413 414
uint64_t qemu_opt_get_number(QemuOpts *opts, const char *name, uint64_t defval)
{
    return qemu_opt_get_number_helper(opts, name, defval, false);
}

uint64_t qemu_opt_get_number_del(QemuOpts *opts, const char *name,
                                 uint64_t defval)
{
    return qemu_opt_get_number_helper(opts, name, defval, true);
}

static uint64_t qemu_opt_get_size_helper(QemuOpts *opts, const char *name,
                                         uint64_t defval, bool del)
415
{
416
    QemuOpt *opt;
417
    uint64_t ret = defval;
418

419 420 421 422 423
    if (opts == NULL) {
        return ret;
    }

    opt = qemu_opt_find(opts, name);
424 425 426
    if (opt == NULL) {
        const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);
        if (desc && desc->def_value_str) {
427
            parse_option_size(name, desc->def_value_str, &ret, &error_abort);
428
        }
429
        return ret;
430
    }
431
    assert(opt->desc && opt->desc->type == QEMU_OPT_SIZE);
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    ret = opt->value.uint;
    if (del) {
        qemu_opt_del_all(opts, name);
    }
    return ret;
}

uint64_t qemu_opt_get_size(QemuOpts *opts, const char *name, uint64_t defval)
{
    return qemu_opt_get_size_helper(opts, name, defval, false);
}

uint64_t qemu_opt_get_size_del(QemuOpts *opts, const char *name,
                               uint64_t defval)
{
    return qemu_opt_get_size_helper(opts, name, defval, true);
448 449
}

450
static void qemu_opt_parse(QemuOpt *opt, Error **errp)
451 452
{
    if (opt->desc == NULL)
453
        return;
454

455 456 457
    switch (opt->desc->type) {
    case QEMU_OPT_STRING:
        /* nothing */
458
        return;
459
    case QEMU_OPT_BOOL:
460
        parse_option_bool(opt->name, opt->str, &opt->value.boolean, errp);
461
        break;
462
    case QEMU_OPT_NUMBER:
463
        parse_option_number(opt->name, opt->str, &opt->value.uint, errp);
464
        break;
465
    case QEMU_OPT_SIZE:
466
        parse_option_size(opt->name, opt->str, &opt->value.uint, errp);
467
        break;
468 469 470 471 472
    default:
        abort();
    }
}

473 474 475 476 477
static bool opts_accepts_any(const QemuOpts *opts)
{
    return opts->list->desc[0].name == NULL;
}

K
Kevin Wolf 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491
int qemu_opt_unset(QemuOpts *opts, const char *name)
{
    QemuOpt *opt = qemu_opt_find(opts, name);

    assert(opts_accepts_any(opts));

    if (opt == NULL) {
        return -1;
    } else {
        qemu_opt_del(opt);
        return 0;
    }
}

492
static void opt_set(QemuOpts *opts, const char *name, char *value,
493 494 495 496 497 498 499 500
                    bool prepend, Error **errp)
{
    QemuOpt *opt;
    const QemuOptDesc *desc;
    Error *local_err = NULL;

    desc = find_desc_by_name(opts->list->desc, name);
    if (!desc && !opts_accepts_any(opts)) {
501
        g_free(value);
502
        error_setg(errp, QERR_INVALID_PARAMETER, name);
503
        return;
504
    }
M
Mark McLoughlin 已提交
505

506 507
    opt = g_malloc0(sizeof(*opt));
    opt->name = g_strdup(name);
M
Mark McLoughlin 已提交
508
    opt->opts = opts;
509 510 511 512 513
    if (prepend) {
        QTAILQ_INSERT_HEAD(&opts->head, opt, next);
    } else {
        QTAILQ_INSERT_TAIL(&opts->head, opt, next);
    }
514
    opt->desc = desc;
515
    opt->str = value;
516
    qemu_opt_parse(opt, &local_err);
517
    if (local_err) {
518
        error_propagate(errp, local_err);
519 520 521 522
        qemu_opt_del(opt);
    }
}

523 524
void qemu_opt_set(QemuOpts *opts, const char *name, const char *value,
                  Error **errp)
525
{
526
    opt_set(opts, name, g_strdup(value), false, errp);
527 528
}

529 530
void qemu_opt_set_bool(QemuOpts *opts, const char *name, bool val,
                       Error **errp)
531 532 533 534
{
    QemuOpt *opt;
    const QemuOptDesc *desc = opts->list->desc;

535 536 537
    opt = g_malloc0(sizeof(*opt));
    opt->desc = find_desc_by_name(desc, name);
    if (!opt->desc && !opts_accepts_any(opts)) {
538
        error_setg(errp, QERR_INVALID_PARAMETER, name);
539
        g_free(opt);
540
        return;
541 542 543 544 545
    }

    opt->name = g_strdup(name);
    opt->opts = opts;
    opt->value.boolean = !!val;
546 547
    opt->str = g_strdup(val ? "on" : "off");
    QTAILQ_INSERT_TAIL(&opts->head, opt, next);
548 549
}

550 551
void qemu_opt_set_number(QemuOpts *opts, const char *name, int64_t val,
                         Error **errp)
552 553 554 555 556 557 558
{
    QemuOpt *opt;
    const QemuOptDesc *desc = opts->list->desc;

    opt = g_malloc0(sizeof(*opt));
    opt->desc = find_desc_by_name(desc, name);
    if (!opt->desc && !opts_accepts_any(opts)) {
559
        error_setg(errp, QERR_INVALID_PARAMETER, name);
560
        g_free(opt);
561
        return;
562 563 564 565 566 567 568 569 570
    }

    opt->name = g_strdup(name);
    opt->opts = opts;
    opt->value.uint = val;
    opt->str = g_strdup_printf("%" PRId64, val);
    QTAILQ_INSERT_TAIL(&opts->head, opt, next);
}

571
/**
572 573
 * For each member of @opts, call @func(@opaque, name, value, @errp).
 * @func() may store an Error through @errp, but must return non-zero then.
574 575 576
 * When @func() returns non-zero, break the loop and return that value.
 * Return zero when the loop completes.
 */
577 578
int qemu_opt_foreach(QemuOpts *opts, qemu_opt_loopfunc func, void *opaque,
                     Error **errp)
G
Gerd Hoffmann 已提交
579 580
{
    QemuOpt *opt;
581
    int rc;
G
Gerd Hoffmann 已提交
582

B
Blue Swirl 已提交
583
    QTAILQ_FOREACH(opt, &opts->head, next) {
584
        rc = func(opaque, opt->name, opt->str, errp);
585 586 587
        if (rc) {
            return rc;
        }
588
        assert(!errp || !*errp);
G
Gerd Hoffmann 已提交
589
    }
590
    return 0;
G
Gerd Hoffmann 已提交
591 592
}

593 594 595 596
QemuOpts *qemu_opts_find(QemuOptsList *list, const char *id)
{
    QemuOpts *opts;

B
Blue Swirl 已提交
597
    QTAILQ_FOREACH(opts, &list->head, next) {
598 599
        if (!opts->id && !id) {
            return opts;
600
        }
601 602
        if (opts->id && id && !strcmp(opts->id, id)) {
            return opts;
603 604 605 606 607
        }
    }
    return NULL;
}

608 609
QemuOpts *qemu_opts_create(QemuOptsList *list, const char *id,
                           int fail_if_exists, Error **errp)
610 611 612 613
{
    QemuOpts *opts = NULL;

    if (id) {
614
        if (!id_wellformed(id)) {
615 616
            error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id",
                       "an identifier");
617
            error_append_hint(errp, "Identifiers consist of letters, digits, "
618
                              "'-', '.', '_', starting with a letter.\n");
619 620
            return NULL;
        }
621 622
        opts = qemu_opts_find(list, id);
        if (opts != NULL) {
623
            if (fail_if_exists && !list->merge_lists) {
624
                error_setg(errp, "Duplicate ID '%s' for %s", id, list->name);
625 626 627 628 629
                return NULL;
            } else {
                return opts;
            }
        }
630 631 632 633 634
    } else if (list->merge_lists) {
        opts = qemu_opts_find(list, NULL);
        if (opts) {
            return opts;
        }
635
    }
636
    opts = g_malloc0(sizeof(*opts));
637
    opts->id = g_strdup(id);
638
    opts->list = list;
639
    loc_save(&opts->loc);
B
Blue Swirl 已提交
640 641
    QTAILQ_INIT(&opts->head);
    QTAILQ_INSERT_TAIL(&list->head, opts, next);
642 643 644
    return opts;
}

645 646 647 648 649 650 651 652 653
void qemu_opts_reset(QemuOptsList *list)
{
    QemuOpts *opts, *next_opts;

    QTAILQ_FOREACH_SAFE(opts, &list->head, next, next_opts) {
        qemu_opts_del(opts);
    }
}

654 655 656 657 658
void qemu_opts_loc_restore(QemuOpts *opts)
{
    loc_restore(&opts->loc);
}

659 660
void qemu_opts_set(QemuOptsList *list, const char *id,
                   const char *name, const char *value, Error **errp)
661 662
{
    QemuOpts *opts;
663
    Error *local_err = NULL;
664

665
    opts = qemu_opts_create(list, id, 1, &local_err);
666
    if (local_err) {
667 668
        error_propagate(errp, local_err);
        return;
669
    }
670
    qemu_opt_set(opts, name, value, errp);
671 672
}

G
Gerd Hoffmann 已提交
673 674 675 676 677
const char *qemu_opts_id(QemuOpts *opts)
{
    return opts->id;
}

678 679 680 681 682 683
/* The id string will be g_free()d by qemu_opts_del */
void qemu_opts_set_id(QemuOpts *opts, char *id)
{
    opts->id = id;
}

684 685 686 687
void qemu_opts_del(QemuOpts *opts)
{
    QemuOpt *opt;

688 689 690 691
    if (opts == NULL) {
        return;
    }

692
    for (;;) {
B
Blue Swirl 已提交
693
        opt = QTAILQ_FIRST(&opts->head);
694 695 696 697
        if (opt == NULL)
            break;
        qemu_opt_del(opt);
    }
B
Blue Swirl 已提交
698
    QTAILQ_REMOVE(&opts->list->head, opts, next);
699 700
    g_free(opts->id);
    g_free(opts);
701 702
}

703 704 705 706 707 708 709 710 711 712 713 714 715 716
/* print value, escaping any commas in value */
static void escaped_print(const char *value)
{
    const char *ptr;

    for (ptr = value; *ptr; ++ptr) {
        if (*ptr == ',') {
            putchar(',');
        }
        putchar(*ptr);
    }
}

void qemu_opts_print(QemuOpts *opts, const char *separator)
717 718
{
    QemuOpt *opt;
719
    QemuOptDesc *desc = opts->list->desc;
720 721 722 723 724 725
    const char *sep = "";

    if (opts->id) {
        printf("id=%s", opts->id); /* passed id_wellformed -> no commas */
        sep = separator;
    }
726

727 728
    if (desc[0].name == NULL) {
        QTAILQ_FOREACH(opt, &opts->head, next) {
729 730 731
            printf("%s%s=", sep, opt->name);
            escaped_print(opt->str);
            sep = separator;
732 733 734 735 736
        }
        return;
    }
    for (; desc && desc->name; desc++) {
        const char *value;
737
        opt = qemu_opt_find(opts, desc->name);
738 739 740 741 742 743

        value = opt ? opt->str : desc->def_value_str;
        if (!value) {
            continue;
        }
        if (desc->type == QEMU_OPT_STRING) {
744 745
            printf("%s%s=", sep, desc->name);
            escaped_print(value);
746 747
        } else if ((desc->type == QEMU_OPT_SIZE ||
                    desc->type == QEMU_OPT_NUMBER) && opt) {
748
            printf("%s%s=%" PRId64, sep, desc->name, opt->value.uint);
749
        } else {
750
            printf("%s%s=%s", sep, desc->name, value);
751
        }
752
        sep = separator;
753 754 755
    }
}

756 757
static void opts_do_parse(QemuOpts *opts, const char *params,
                          const char *firstname, bool prepend, Error **errp)
758
{
759
    char *option = NULL;
760
    char *value = NULL;
761
    const char *p,*pe,*pc;
762
    Error *local_err = NULL;
763

764
    for (p = params; *p != '\0'; p++) {
765 766 767 768 769 770
        pe = strchr(p, '=');
        pc = strchr(p, ',');
        if (!pe || (pc && pc < pe)) {
            /* found "foo,more" */
            if (p == params && firstname) {
                /* implicitly named first option */
771
                option = g_strdup(firstname);
772
                p = get_opt_value(p, &value);
773 774
            } else {
                /* option without value, probably a flag */
775
                p = get_opt_name(p, &option, ',');
776
                if (strncmp(option, "no", 2) == 0) {
777
                    memmove(option, option+2, strlen(option+2)+1);
778
                    value = g_strdup("off");
779
                } else {
780
                    value = g_strdup("on");
781 782 783 784
                }
            }
        } else {
            /* found "foo=bar,more" */
785 786
            p = get_opt_name(p, &option, '=');
            assert(*p == '=');
787
            p++;
788
            p = get_opt_value(p, &value);
789 790 791
        }
        if (strcmp(option, "id") != 0) {
            /* store and parse */
792
            opt_set(opts, option, value, prepend, &local_err);
793
            value = NULL;
794
            if (local_err) {
795
                error_propagate(errp, local_err);
796
                goto cleanup;
797 798 799 800 801
            }
        }
        if (*p != ',') {
            break;
        }
802
        g_free(option);
803 804
        g_free(value);
        option = value = NULL;
805
    }
806 807 808

 cleanup:
    g_free(option);
809
    g_free(value);
810 811
}

812 813 814 815 816 817 818 819
/**
 * Store options parsed from @params into @opts.
 * If @firstname is non-null, the first key=value in @params may omit
 * key=, and is treated as if key was @firstname.
 * On error, store an error object through @errp if non-null.
 */
void qemu_opts_do_parse(QemuOpts *opts, const char *params,
                       const char *firstname, Error **errp)
820
{
821
    opts_do_parse(opts, params, firstname, false, errp);
822 823 824
}

static QemuOpts *opts_parse(QemuOptsList *list, const char *params,
825
                            bool permit_abbrev, bool defaults, Error **errp)
826
{
827
    const char *firstname;
828
    char *id = NULL;
829 830
    const char *p;
    QemuOpts *opts;
831
    Error *local_err = NULL;
832

833 834 835
    assert(!permit_abbrev || list->implied_opt_name);
    firstname = permit_abbrev ? list->implied_opt_name : NULL;

836
    if (strncmp(params, "id=", 3) == 0) {
837
        get_opt_value(params + 3, &id);
838
    } else if ((p = strstr(params, ",id=")) != NULL) {
839
        get_opt_value(p + 4, &id);
840
    }
841 842 843 844 845 846 847 848 849

    /*
     * This code doesn't work for defaults && !list->merge_lists: when
     * params has no id=, and list has an element with !opts->id, it
     * appends a new element instead of returning the existing opts.
     * However, we got no use for this case.  Guard against possible
     * (if unlikely) future misuse:
     */
    assert(!defaults || list->merge_lists);
850
    opts = qemu_opts_create(list, id, !defaults, &local_err);
851
    g_free(id);
852
    if (opts == NULL) {
853
        error_propagate(errp, local_err);
854
        return NULL;
855
    }
856

857 858
    opts_do_parse(opts, params, firstname, defaults, &local_err);
    if (local_err) {
859
        error_propagate(errp, local_err);
860 861 862 863
        qemu_opts_del(opts);
        return NULL;
    }

864 865 866
    return opts;
}

867 868 869 870
/**
 * Create a QemuOpts in @list and with options parsed from @params.
 * If @permit_abbrev, the first key=value in @params may omit key=,
 * and is treated as if key was @list->implied_opt_name.
871
 * On error, store an error object through @errp if non-null.
872 873
 * Return the new QemuOpts on success, null pointer on error.
 */
874
QemuOpts *qemu_opts_parse(QemuOptsList *list, const char *params,
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
                          bool permit_abbrev, Error **errp)
{
    return opts_parse(list, params, permit_abbrev, false, errp);
}

/**
 * Create a QemuOpts in @list and with options parsed from @params.
 * If @permit_abbrev, the first key=value in @params may omit key=,
 * and is treated as if key was @list->implied_opt_name.
 * Report errors with error_report_err().  This is inappropriate in
 * QMP context.  Do not use this function there!
 * Return the new QemuOpts on success, null pointer on error.
 */
QemuOpts *qemu_opts_parse_noisily(QemuOptsList *list, const char *params,
                                  bool permit_abbrev)
890
{
891 892 893 894
    Error *err = NULL;
    QemuOpts *opts;

    opts = opts_parse(list, params, permit_abbrev, false, &err);
895 896
    if (err) {
        error_report_err(err);
897 898
    }
    return opts;
899 900 901 902 903 904 905
}

void qemu_opts_set_defaults(QemuOptsList *list, const char *params,
                            int permit_abbrev)
{
    QemuOpts *opts;

906
    opts = opts_parse(list, params, permit_abbrev, true, NULL);
907 908 909
    assert(opts);
}

910 911 912 913 914
typedef struct OptsFromQDictState {
    QemuOpts *opts;
    Error **errp;
} OptsFromQDictState;

915 916
static void qemu_opts_from_qdict_1(const char *key, QObject *obj, void *opaque)
{
917
    OptsFromQDictState *state = opaque;
918
    char buf[32], *tmp = NULL;
919 920
    const char *value;

921
    if (!strcmp(key, "id") || *state->errp) {
922 923 924 925 926
        return;
    }

    switch (qobject_type(obj)) {
    case QTYPE_QSTRING:
927
        value = qstring_get_str(qobject_to(QString, obj));
928
        break;
929
    case QTYPE_QNUM:
930
        tmp = qnum_to_string(qobject_to(QNum, obj));
931
        value = tmp;
932 933
        break;
    case QTYPE_QBOOL:
B
Blue Swirl 已提交
934
        pstrcpy(buf, sizeof(buf),
935
                qbool_get_bool(qobject_to(QBool, obj)) ? "on" : "off");
936 937 938 939 940
        value = buf;
        break;
    default:
        return;
    }
941

942
    qemu_opt_set(state->opts, key, value, state->errp);
943
    g_free(tmp);
944 945 946 947
}

/*
 * Create QemuOpts from a QDict.
948 949 950
 * Use value of key "id" as ID if it exists and is a QString.  Only
 * QStrings, QNums and QBools are copied.  Entries with other types
 * are silently ignored.
951
 */
952 953
QemuOpts *qemu_opts_from_qdict(QemuOptsList *list, const QDict *qdict,
                               Error **errp)
954
{
955
    OptsFromQDictState state;
956
    Error *local_err = NULL;
957
    QemuOpts *opts;
958

959 960
    opts = qemu_opts_create(list, qdict_get_try_str(qdict, "id"), 1,
                            &local_err);
961
    if (local_err) {
962
        error_propagate(errp, local_err);
963
        return NULL;
964
    }
965

966
    assert(opts != NULL);
967 968 969 970

    state.errp = &local_err;
    state.opts = opts;
    qdict_iter(qdict, qemu_opts_from_qdict_1, &state);
971
    if (local_err) {
972 973 974 975 976
        error_propagate(errp, local_err);
        qemu_opts_del(opts);
        return NULL;
    }

977 978 979
    return opts;
}

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
/*
 * Adds all QDict entries to the QemuOpts that can be added and removes them
 * from the QDict. When this function returns, the QDict contains only those
 * entries that couldn't be added to the QemuOpts.
 */
void qemu_opts_absorb_qdict(QemuOpts *opts, QDict *qdict, Error **errp)
{
    const QDictEntry *entry, *next;

    entry = qdict_first(qdict);

    while (entry != NULL) {
        Error *local_err = NULL;
        OptsFromQDictState state = {
            .errp = &local_err,
            .opts = opts,
        };

        next = qdict_next(qdict, entry);

        if (find_desc_by_name(opts->list->desc, entry->key)) {
            qemu_opts_from_qdict_1(entry->key, entry->value, &state);
1002
            if (local_err) {
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
                error_propagate(errp, local_err);
                return;
            } else {
                qdict_del(qdict, entry->key);
            }
        }

        entry = next;
    }
}

1014
/*
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
 * Convert from QemuOpts to QDict. The QDict values are of type QString.
 *
 * If @list is given, only add those options to the QDict that are contained in
 * the list. If @del is true, any options added to the QDict are removed from
 * the QemuOpts, otherwise they remain there.
 *
 * If two options in @opts have the same name, they are processed in order
 * so that the last one wins (consistent with the reverse iteration in
 * qemu_opt_find()), but all of them are deleted if @del is true.
 *
1025 1026 1027
 * TODO We'll want to use types appropriate for opt->desc->type, but
 * this is enough for now.
 */
1028 1029
QDict *qemu_opts_to_qdict_filtered(QemuOpts *opts, QDict *qdict,
                                   QemuOptsList *list, bool del)
1030
{
1031
    QemuOpt *opt, *next;
1032 1033 1034 1035 1036

    if (!qdict) {
        qdict = qdict_new();
    }
    if (opts->id) {
1037
        qdict_put_str(qdict, "id", opts->id);
1038
    }
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    QTAILQ_FOREACH_SAFE(opt, &opts->head, next, next) {
        if (list) {
            QemuOptDesc *desc;
            bool found = false;
            for (desc = list->desc; desc->name; desc++) {
                if (!strcmp(desc->name, opt->name)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                continue;
            }
        }
1053
        qdict_put_str(qdict, opt->name, opt->str);
1054 1055 1056
        if (del) {
            qemu_opt_del(opt);
        }
1057 1058 1059 1060
    }
    return qdict;
}

1061 1062 1063 1064 1065 1066 1067
/* Copy all options in a QemuOpts to the given QDict. See
 * qemu_opts_to_qdict_filtered() for details. */
QDict *qemu_opts_to_qdict(QemuOpts *opts, QDict *qdict)
{
    return qemu_opts_to_qdict_filtered(opts, qdict, NULL, false);
}

1068 1069 1070
/* Validate parsed opts against descriptions where no
 * descriptions were provided in the QemuOptsList.
 */
1071
void qemu_opts_validate(QemuOpts *opts, const QemuOptDesc *desc, Error **errp)
1072 1073
{
    QemuOpt *opt;
1074
    Error *local_err = NULL;
1075

1076
    assert(opts_accepts_any(opts));
1077 1078

    QTAILQ_FOREACH(opt, &opts->head, next) {
1079 1080
        opt->desc = find_desc_by_name(desc, opt->name);
        if (!opt->desc) {
1081
            error_setg(errp, QERR_INVALID_PARAMETER, opt->name);
1082
            return;
1083 1084
        }

1085
        qemu_opt_parse(opt, &local_err);
1086
        if (local_err) {
1087 1088
            error_propagate(errp, local_err);
            return;
1089 1090 1091 1092
        }
    }
}

1093
/**
1094
 * For each member of @list, call @func(@opaque, member, @errp).
1095
 * Call it with the current location temporarily set to the member's.
1096
 * @func() may store an Error through @errp, but must return non-zero then.
1097 1098 1099 1100
 * When @func() returns non-zero, break the loop and return that value.
 * Return zero when the loop completes.
 */
int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func,
1101
                      void *opaque, Error **errp)
1102
{
1103
    Location loc;
1104
    QemuOpts *opts;
1105
    int rc = 0;
1106

1107
    loc_push_none(&loc);
B
Blue Swirl 已提交
1108
    QTAILQ_FOREACH(opts, &list->head, next) {
1109
        loc_restore(&opts->loc);
1110
        rc = func(opaque, opts, errp);
1111
        if (rc) {
1112
            break;
1113
        }
1114
        assert(!errp || !*errp);
1115
    }
1116
    loc_pop(&loc);
1117
    return rc;
1118
}
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141

static size_t count_opts_list(QemuOptsList *list)
{
    QemuOptDesc *desc = NULL;
    size_t num_opts = 0;

    if (!list) {
        return 0;
    }

    desc = list->desc;
    while (desc && desc->name) {
        num_opts++;
        desc++;
    }

    return num_opts;
}

void qemu_opts_free(QemuOptsList *list)
{
    g_free(list);
}
1142

C
Chunyan Liu 已提交
1143 1144
/* Realloc dst option list and append options from an option list (list)
 * to it. dst could be NULL or a malloced list.
1145 1146
 * The lifetime of dst must be shorter than the input list because the
 * QemuOptDesc->name, ->help, and ->def_value_str strings are shared.
1147 1148
 */
QemuOptsList *qemu_opts_append(QemuOptsList *dst,
C
Chunyan Liu 已提交
1149
                               QemuOptsList *list)
1150 1151 1152 1153
{
    size_t num_opts, num_dst_opts;
    QemuOptDesc *desc;
    bool need_init = false;
1154
    bool need_head_update;
1155

C
Chunyan Liu 已提交
1156
    if (!list) {
1157 1158 1159 1160 1161 1162 1163 1164
        return dst;
    }

    /* If dst is NULL, after realloc, some area of dst should be initialized
     * before adding options to it.
     */
    if (!dst) {
        need_init = true;
1165 1166 1167 1168 1169 1170
        need_head_update = true;
    } else {
        /* Moreover, even if dst is not NULL, the realloc may move it to a
         * different address in which case we may get a stale tail pointer
         * in dst->head. */
        need_head_update = QTAILQ_EMPTY(&dst->head);
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    }

    num_opts = count_opts_list(dst);
    num_dst_opts = num_opts;
    num_opts += count_opts_list(list);
    dst = g_realloc(dst, sizeof(QemuOptsList) +
                    (num_opts + 1) * sizeof(QemuOptDesc));
    if (need_init) {
        dst->name = NULL;
        dst->implied_opt_name = NULL;
        dst->merge_lists = false;
    }
1183 1184 1185
    if (need_head_update) {
        QTAILQ_INIT(&dst->head);
    }
1186 1187 1188 1189 1190 1191 1192
    dst->desc[num_dst_opts].name = NULL;

    /* append list->desc to dst->desc */
    if (list) {
        desc = list->desc;
        while (desc && desc->name) {
            if (find_desc_by_name(dst->desc, desc->name) == NULL) {
1193
                dst->desc[num_dst_opts++] = *desc;
1194 1195 1196 1197 1198 1199 1200 1201
                dst->desc[num_dst_opts].name = NULL;
            }
            desc++;
        }
    }

    return dst;
}