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
    *value = NULL;
    while (1) {
K
Keno Fischer 已提交
80
        offset = qemu_strchrnul(p, ',');
81 82 83 84 85 86 87 88
        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 已提交
89
        }
90 91 92 93 94 95 96
        capacity += length;
        if (*offset == '\0' ||
            *(offset + 1) != ',') {
            break;
        }

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

99
    return offset;
K
Kevin Wolf 已提交
100 101
}

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

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

121 122 123 124 125 126 127
    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) {
128
        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
129
        return;
130
    }
131
    *ret = number;
132 133
}

134 135 136 137 138 139 140 141 142 143 144 145 146 147
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;
}

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

154 155
    err = qemu_strtosz(value, NULL, &size);
    if (err == -ERANGE) {
156
        error_setg(errp, "Value '%s' is out of range for parameter '%s'",
157
                   value, name);
158 159
        return;
    }
160 161 162 163 164 165
    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");
166
        return;
167
    }
168
    *ret = size;
169 170
}

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

176 177 178 179
    while (*p && !result) {
        char *value;

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

184 185
        result = is_help_option(value);
        g_free(value);
186 187 188 189 190
    }

    return result;
}

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

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

203 204
        g_free(value);
        value = NULL;
205 206
    }

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

213 214 215 216 217 218 219 220 221 222 223 224
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++;
    }
}
225 226
/* ------------------------------------------------------------------ */

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

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

239 240 241 242 243 244 245 246
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);
}

247 248 249 250 251 252 253 254 255 256 257 258 259 260
/* 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);
        }
    }
}

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

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

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

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
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;
}

298 299 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
/* 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;
}

326 327 328 329 330 331 332 333 334 335 336 337
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;
}

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

344 345 346 347 348
    if (opts == NULL) {
        return ret;
    }

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

364 365 366 367 368 369 370 371 372 373 374 375
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)
376
{
377
    QemuOpt *opt;
378
    uint64_t ret = defval;
379

380 381 382 383 384
    if (opts == NULL) {
        return ret;
    }

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

400 401 402 403 404 405 406 407 408 409 410 411 412
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)
413
{
414
    QemuOpt *opt;
415
    uint64_t ret = defval;
416

417 418 419 420 421
    if (opts == NULL) {
        return ret;
    }

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

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

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

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

K
Kevin Wolf 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489
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;
    }
}

490
static void opt_set(QemuOpts *opts, const char *name, char *value,
491 492 493 494 495 496 497 498
                    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)) {
499
        g_free(value);
500
        error_setg(errp, QERR_INVALID_PARAMETER, name);
501
        return;
502
    }
M
Mark McLoughlin 已提交
503

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

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

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

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

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

548 549
void qemu_opt_set_number(QemuOpts *opts, const char *name, int64_t val,
                         Error **errp)
550 551 552 553 554 555 556
{
    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)) {
557
        error_setg(errp, QERR_INVALID_PARAMETER, name);
558
        g_free(opt);
559
        return;
560 561 562 563 564 565 566 567 568
    }

    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);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

682 683 684 685
void qemu_opts_del(QemuOpts *opts)
{
    QemuOpt *opt;

686 687 688 689
    if (opts == NULL) {
        return;
    }

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

701 702 703 704 705 706 707 708 709 710 711 712 713 714
/* 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)
715 716
{
    QemuOpt *opt;
717
    QemuOptDesc *desc = opts->list->desc;
718 719 720 721 722 723
    const char *sep = "";

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

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

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

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

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

 cleanup:
    g_free(option);
807
    g_free(value);
808 809
}

810 811 812 813 814 815 816 817
/**
 * 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)
818
{
819
    opts_do_parse(opts, params, firstname, false, errp);
820 821 822
}

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

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

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

    /*
     * 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);
848
    opts = qemu_opts_create(list, id, !defaults, &local_err);
849
    g_free(id);
850
    if (opts == NULL) {
851
        error_propagate(errp, local_err);
852
        return NULL;
853
    }
854

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

862 863 864
    return opts;
}

865 866 867 868
/**
 * 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.
869
 * On error, store an error object through @errp if non-null.
870 871
 * Return the new QemuOpts on success, null pointer on error.
 */
872
QemuOpts *qemu_opts_parse(QemuOptsList *list, const char *params,
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
                          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)
888
{
889 890 891 892
    Error *err = NULL;
    QemuOpts *opts;

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

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

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

908 909 910 911 912
typedef struct OptsFromQDictState {
    QemuOpts *opts;
    Error **errp;
} OptsFromQDictState;

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

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

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

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

/*
 * Create QemuOpts from a QDict.
946 947 948
 * 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.
949
 */
950 951
QemuOpts *qemu_opts_from_qdict(QemuOptsList *list, const QDict *qdict,
                               Error **errp)
952
{
953
    OptsFromQDictState state;
954
    Error *local_err = NULL;
955
    QemuOpts *opts;
956

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

964
    assert(opts != NULL);
965 966 967 968

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

975 976 977
    return opts;
}

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
/*
 * 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);
1000
            if (local_err) {
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
                error_propagate(errp, local_err);
                return;
            } else {
                qdict_del(qdict, entry->key);
            }
        }

        entry = next;
    }
}

1012
/*
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
 * 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.
 *
1023 1024 1025
 * TODO We'll want to use types appropriate for opt->desc->type, but
 * this is enough for now.
 */
1026 1027
QDict *qemu_opts_to_qdict_filtered(QemuOpts *opts, QDict *qdict,
                                   QemuOptsList *list, bool del)
1028
{
1029
    QemuOpt *opt, *next;
1030 1031 1032 1033 1034

    if (!qdict) {
        qdict = qdict_new();
    }
    if (opts->id) {
1035
        qdict_put_str(qdict, "id", opts->id);
1036
    }
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    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;
            }
        }
1051
        qdict_put_str(qdict, opt->name, opt->str);
1052 1053 1054
        if (del) {
            qemu_opt_del(opt);
        }
1055 1056 1057 1058
    }
    return qdict;
}

1059 1060 1061 1062 1063 1064 1065
/* 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);
}

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

1074
    assert(opts_accepts_any(opts));
1075 1076

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

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

1091
/**
1092
 * For each member of @list, call @func(@opaque, member, @errp).
1093
 * Call it with the current location temporarily set to the member's.
1094
 * @func() may store an Error through @errp, but must return non-zero then.
1095 1096 1097 1098
 * 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,
1099
                      void *opaque, Error **errp)
1100
{
1101
    Location loc;
1102
    QemuOpts *opts;
1103
    int rc = 0;
1104

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

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);
}
1140

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

C
Chunyan Liu 已提交
1154
    if (!list) {
1155 1156 1157 1158 1159 1160 1161 1162
        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;
1163 1164 1165 1166 1167 1168
        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);
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    }

    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;
    }
1181 1182 1183
    if (need_head_update) {
        QTAILQ_INIT(&dst->head);
    }
1184 1185 1186 1187 1188 1189 1190
    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) {
1191
                dst->desc[num_dst_opts++] = *desc;
1192 1193 1194 1195 1196 1197 1198 1199
                dst->desc[num_dst_opts].name = NULL;
            }
            desc++;
        }
    }

    return dst;
}