Statistics
| Branch: | Revision:

root / qemu-option.c @ ad718d01

History | View | Annotate | Download (27.8 kB)

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 <stdio.h>
27
#include <string.h>
28

    
29
#include "qemu-common.h"
30
#include "qemu-error.h"
31
#include "qemu-objects.h"
32
#include "error.h"
33
#include "qerror.h"
34
#include "qemu-option-internal.h"
35

    
36
/*
37
 * Extracts the name of an option from the parameter string (p points at the
38
 * first byte of the option name)
39
 *
40
 * The option name is delimited by delim (usually , or =) or the string end
41
 * and is copied into buf. If the option name is longer than buf_size, it is
42
 * truncated. buf is always zero terminated.
43
 *
44
 * The return value is the position of the delimiter/zero byte after the option
45
 * name in p.
46
 */
47
const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
48
{
49
    char *q;
50

    
51
    q = buf;
52
    while (*p != '\0' && *p != delim) {
53
        if (q && (q - buf) < buf_size - 1)
54
            *q++ = *p;
55
        p++;
56
    }
57
    if (q)
58
        *q = '\0';
59

    
60
    return p;
61
}
62

    
63
/*
64
 * Extracts the value of an option from the parameter string p (p points at the
65
 * first byte of the option value)
66
 *
67
 * This function is comparable to get_opt_name with the difference that the
68
 * delimiter is fixed to be comma which starts a new option. To specify an
69
 * option value that contains commas, double each comma.
70
 */
71
const char *get_opt_value(char *buf, int buf_size, const char *p)
72
{
73
    char *q;
74

    
75
    q = buf;
76
    while (*p != '\0') {
77
        if (*p == ',') {
78
            if (*(p + 1) != ',')
79
                break;
80
            p++;
81
        }
82
        if (q && (q - buf) < buf_size - 1)
83
            *q++ = *p;
84
        p++;
85
    }
86
    if (q)
87
        *q = '\0';
88

    
89
    return p;
90
}
91

    
92
int get_next_param_value(char *buf, int buf_size,
93
                         const char *tag, const char **pstr)
94
{
95
    const char *p;
96
    char option[128];
97

    
98
    p = *pstr;
99
    for(;;) {
100
        p = get_opt_name(option, sizeof(option), p, '=');
101
        if (*p != '=')
102
            break;
103
        p++;
104
        if (!strcmp(tag, option)) {
105
            *pstr = get_opt_value(buf, buf_size, p);
106
            if (**pstr == ',') {
107
                (*pstr)++;
108
            }
109
            return strlen(buf);
110
        } else {
111
            p = get_opt_value(NULL, 0, p);
112
        }
113
        if (*p != ',')
114
            break;
115
        p++;
116
    }
117
    return 0;
118
}
119

    
120
int get_param_value(char *buf, int buf_size,
121
                    const char *tag, const char *str)
122
{
123
    return get_next_param_value(buf, buf_size, tag, &str);
124
}
125

    
126
int check_params(char *buf, int buf_size,
127
                 const char * const *params, const char *str)
128
{
129
    const char *p;
130
    int i;
131

    
132
    p = str;
133
    while (*p != '\0') {
134
        p = get_opt_name(buf, buf_size, p, '=');
135
        if (*p != '=') {
136
            return -1;
137
        }
138
        p++;
139
        for (i = 0; params[i] != NULL; i++) {
140
            if (!strcmp(params[i], buf)) {
141
                break;
142
            }
143
        }
144
        if (params[i] == NULL) {
145
            return -1;
146
        }
147
        p = get_opt_value(NULL, 0, p);
148
        if (*p != ',') {
149
            break;
150
        }
151
        p++;
152
    }
153
    return 0;
154
}
155

    
156
/*
157
 * Searches an option list for an option with the given name
158
 */
159
QEMUOptionParameter *get_option_parameter(QEMUOptionParameter *list,
160
    const char *name)
161
{
162
    while (list && list->name) {
163
        if (!strcmp(list->name, name)) {
164
            return list;
165
        }
166
        list++;
167
    }
168

    
169
    return NULL;
170
}
171

    
172
static void parse_option_bool(const char *name, const char *value, bool *ret,
173
                              Error **errp)
174
{
175
    if (value != NULL) {
176
        if (!strcmp(value, "on")) {
177
            *ret = 1;
178
        } else if (!strcmp(value, "off")) {
179
            *ret = 0;
180
        } else {
181
            error_set(errp,QERR_INVALID_PARAMETER_VALUE, name, "'on' or 'off'");
182
        }
183
    } else {
184
        *ret = 1;
185
    }
186
}
187

    
188
static void parse_option_number(const char *name, const char *value,
189
                                uint64_t *ret, Error **errp)
190
{
191
    char *postfix;
192
    uint64_t number;
193

    
194
    if (value != NULL) {
195
        number = strtoull(value, &postfix, 0);
196
        if (*postfix != '\0') {
197
            error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
198
            return;
199
        }
200
        *ret = number;
201
    } else {
202
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a number");
203
    }
204
}
205

    
206
static void parse_option_size(const char *name, const char *value,
207
                              uint64_t *ret, Error **errp)
208
{
209
    char *postfix;
210
    double sizef;
211

    
212
    if (value != NULL) {
213
        sizef = strtod(value, &postfix);
214
        switch (*postfix) {
215
        case 'T':
216
            sizef *= 1024;
217
            /* fall through */
218
        case 'G':
219
            sizef *= 1024;
220
            /* fall through */
221
        case 'M':
222
            sizef *= 1024;
223
            /* fall through */
224
        case 'K':
225
        case 'k':
226
            sizef *= 1024;
227
            /* fall through */
228
        case 'b':
229
        case '\0':
230
            *ret = (uint64_t) sizef;
231
            break;
232
        default:
233
            error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
234
            error_printf_unless_qmp("You may use k, M, G or T suffixes for "
235
                    "kilobytes, megabytes, gigabytes and terabytes.\n");
236
            return;
237
        }
238
    } else {
239
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");
240
    }
241
}
242

    
243
/*
244
 * Sets the value of a parameter in a given option list. The parsing of the
245
 * value depends on the type of option:
246
 *
247
 * OPT_FLAG (uses value.n):
248
 *      If no value is given, the flag is set to 1.
249
 *      Otherwise the value must be "on" (set to 1) or "off" (set to 0)
250
 *
251
 * OPT_STRING (uses value.s):
252
 *      value is strdup()ed and assigned as option value
253
 *
254
 * OPT_SIZE (uses value.n):
255
 *      The value is converted to an integer. Suffixes for kilobytes etc. are
256
 *      allowed (powers of 1024).
257
 *
258
 * Returns 0 on succes, -1 in error cases
259
 */
260
int set_option_parameter(QEMUOptionParameter *list, const char *name,
261
    const char *value)
262
{
263
    bool flag;
264
    Error *local_err = NULL;
265

    
266
    // Find a matching parameter
267
    list = get_option_parameter(list, name);
268
    if (list == NULL) {
269
        fprintf(stderr, "Unknown option '%s'\n", name);
270
        return -1;
271
    }
272

    
273
    // Process parameter
274
    switch (list->type) {
275
    case OPT_FLAG:
276
        parse_option_bool(name, value, &flag, &local_err);
277
        if (!error_is_set(&local_err)) {
278
            list->value.n = flag;
279
        }
280
        break;
281

    
282
    case OPT_STRING:
283
        if (value != NULL) {
284
            list->value.s = g_strdup(value);
285
        } else {
286
            fprintf(stderr, "Option '%s' needs a parameter\n", name);
287
            return -1;
288
        }
289
        break;
290

    
291
    case OPT_SIZE:
292
        parse_option_size(name, value, &list->value.n, &local_err);
293
        break;
294

    
295
    default:
296
        fprintf(stderr, "Bug: Option '%s' has an unknown type\n", name);
297
        return -1;
298
    }
299

    
300
    if (error_is_set(&local_err)) {
301
        qerror_report_err(local_err);
302
        error_free(local_err);
303
        return -1;
304
    }
305

    
306
    return 0;
307
}
308

    
309
/*
310
 * Sets the given parameter to an integer instead of a string.
311
 * This function cannot be used to set string options.
312
 *
313
 * Returns 0 on success, -1 in error cases
314
 */
315
int set_option_parameter_int(QEMUOptionParameter *list, const char *name,
316
    uint64_t value)
317
{
318
    // Find a matching parameter
319
    list = get_option_parameter(list, name);
320
    if (list == NULL) {
321
        fprintf(stderr, "Unknown option '%s'\n", name);
322
        return -1;
323
    }
324

    
325
    // Process parameter
326
    switch (list->type) {
327
    case OPT_FLAG:
328
    case OPT_NUMBER:
329
    case OPT_SIZE:
330
        list->value.n = value;
331
        break;
332

    
333
    default:
334
        return -1;
335
    }
336

    
337
    return 0;
338
}
339

    
340
/*
341
 * Frees a option list. If it contains strings, the strings are freed as well.
342
 */
343
void free_option_parameters(QEMUOptionParameter *list)
344
{
345
    QEMUOptionParameter *cur = list;
346

    
347
    while (cur && cur->name) {
348
        if (cur->type == OPT_STRING) {
349
            g_free(cur->value.s);
350
        }
351
        cur++;
352
    }
353

    
354
    g_free(list);
355
}
356

    
357
/*
358
 * Count valid options in list
359
 */
360
static size_t count_option_parameters(QEMUOptionParameter *list)
361
{
362
    size_t num_options = 0;
363

    
364
    while (list && list->name) {
365
        num_options++;
366
        list++;
367
    }
368

    
369
    return num_options;
370
}
371

    
372
/*
373
 * Append an option list (list) to an option list (dest).
374
 *
375
 * If dest is NULL, a new copy of list is created.
376
 *
377
 * Returns a pointer to the first element of dest (or the newly allocated copy)
378
 */
379
QEMUOptionParameter *append_option_parameters(QEMUOptionParameter *dest,
380
    QEMUOptionParameter *list)
381
{
382
    size_t num_options, num_dest_options;
383

    
384
    num_options = count_option_parameters(dest);
385
    num_dest_options = num_options;
386

    
387
    num_options += count_option_parameters(list);
388

    
389
    dest = g_realloc(dest, (num_options + 1) * sizeof(QEMUOptionParameter));
390
    dest[num_dest_options].name = NULL;
391

    
392
    while (list && list->name) {
393
        if (get_option_parameter(dest, list->name) == NULL) {
394
            dest[num_dest_options++] = *list;
395
            dest[num_dest_options].name = NULL;
396
        }
397
        list++;
398
    }
399

    
400
    return dest;
401
}
402

    
403
/*
404
 * Parses a parameter string (param) into an option list (dest).
405
 *
406
 * list is the template option list. If dest is NULL, a new copy of list is
407
 * created. If list is NULL, this function fails.
408
 *
409
 * A parameter string consists of one or more parameters, separated by commas.
410
 * Each parameter consists of its name and possibly of a value. In the latter
411
 * case, the value is delimited by an = character. To specify a value which
412
 * contains commas, double each comma so it won't be recognized as the end of
413
 * the parameter.
414
 *
415
 * For more details of the parsing see above.
416
 *
417
 * Returns a pointer to the first element of dest (or the newly allocated copy)
418
 * or NULL in error cases
419
 */
420
QEMUOptionParameter *parse_option_parameters(const char *param,
421
    QEMUOptionParameter *list, QEMUOptionParameter *dest)
422
{
423
    QEMUOptionParameter *allocated = NULL;
424
    char name[256];
425
    char value[256];
426
    char *param_delim, *value_delim;
427
    char next_delim;
428

    
429
    if (list == NULL) {
430
        return NULL;
431
    }
432

    
433
    if (dest == NULL) {
434
        dest = allocated = append_option_parameters(NULL, list);
435
    }
436

    
437
    while (*param) {
438

    
439
        // Find parameter name and value in the string
440
        param_delim = strchr(param, ',');
441
        value_delim = strchr(param, '=');
442

    
443
        if (value_delim && (value_delim < param_delim || !param_delim)) {
444
            next_delim = '=';
445
        } else {
446
            next_delim = ',';
447
            value_delim = NULL;
448
        }
449

    
450
        param = get_opt_name(name, sizeof(name), param, next_delim);
451
        if (value_delim) {
452
            param = get_opt_value(value, sizeof(value), param + 1);
453
        }
454
        if (*param != '\0') {
455
            param++;
456
        }
457

    
458
        // Set the parameter
459
        if (set_option_parameter(dest, name, value_delim ? value : NULL)) {
460
            goto fail;
461
        }
462
    }
463

    
464
    return dest;
465

    
466
fail:
467
    // Only free the list if it was newly allocated
468
    free_option_parameters(allocated);
469
    return NULL;
470
}
471

    
472
/*
473
 * Prints all options of a list that have a value to stdout
474
 */
475
void print_option_parameters(QEMUOptionParameter *list)
476
{
477
    while (list && list->name) {
478
        switch (list->type) {
479
            case OPT_STRING:
480
                 if (list->value.s != NULL) {
481
                     printf("%s='%s' ", list->name, list->value.s);
482
                 }
483
                break;
484
            case OPT_FLAG:
485
                printf("%s=%s ", list->name, list->value.n ? "on" : "off");
486
                break;
487
            case OPT_SIZE:
488
            case OPT_NUMBER:
489
                printf("%s=%" PRId64 " ", list->name, list->value.n);
490
                break;
491
            default:
492
                printf("%s=(unknown type) ", list->name);
493
                break;
494
        }
495
        list++;
496
    }
497
}
498

    
499
/*
500
 * Prints an overview of all available options
501
 */
502
void print_option_help(QEMUOptionParameter *list)
503
{
504
    printf("Supported options:\n");
505
    while (list && list->name) {
506
        printf("%-16s %s\n", list->name,
507
            list->help ? list->help : "No description available");
508
        list++;
509
    }
510
}
511

    
512
/* ------------------------------------------------------------------ */
513

    
514
static QemuOpt *qemu_opt_find(QemuOpts *opts, const char *name)
515
{
516
    QemuOpt *opt;
517

    
518
    QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
519
        if (strcmp(opt->name, name) != 0)
520
            continue;
521
        return opt;
522
    }
523
    return NULL;
524
}
525

    
526
const char *qemu_opt_get(QemuOpts *opts, const char *name)
527
{
528
    QemuOpt *opt = qemu_opt_find(opts, name);
529
    return opt ? opt->str : NULL;
530
}
531

    
532
bool qemu_opt_has_help_opt(QemuOpts *opts)
533
{
534
    QemuOpt *opt;
535

    
536
    QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
537
        if (is_help_option(opt->name)) {
538
            return true;
539
        }
540
    }
541
    return false;
542
}
543

    
544
bool qemu_opt_get_bool(QemuOpts *opts, const char *name, bool defval)
545
{
546
    QemuOpt *opt = qemu_opt_find(opts, name);
547

    
548
    if (opt == NULL)
549
        return defval;
550
    assert(opt->desc && opt->desc->type == QEMU_OPT_BOOL);
551
    return opt->value.boolean;
552
}
553

    
554
uint64_t qemu_opt_get_number(QemuOpts *opts, const char *name, uint64_t defval)
555
{
556
    QemuOpt *opt = qemu_opt_find(opts, name);
557

    
558
    if (opt == NULL)
559
        return defval;
560
    assert(opt->desc && opt->desc->type == QEMU_OPT_NUMBER);
561
    return opt->value.uint;
562
}
563

    
564
uint64_t qemu_opt_get_size(QemuOpts *opts, const char *name, uint64_t defval)
565
{
566
    QemuOpt *opt = qemu_opt_find(opts, name);
567

    
568
    if (opt == NULL)
569
        return defval;
570
    assert(opt->desc && opt->desc->type == QEMU_OPT_SIZE);
571
    return opt->value.uint;
572
}
573

    
574
static void qemu_opt_parse(QemuOpt *opt, Error **errp)
575
{
576
    if (opt->desc == NULL)
577
        return;
578

    
579
    switch (opt->desc->type) {
580
    case QEMU_OPT_STRING:
581
        /* nothing */
582
        return;
583
    case QEMU_OPT_BOOL:
584
        parse_option_bool(opt->name, opt->str, &opt->value.boolean, errp);
585
        break;
586
    case QEMU_OPT_NUMBER:
587
        parse_option_number(opt->name, opt->str, &opt->value.uint, errp);
588
        break;
589
    case QEMU_OPT_SIZE:
590
        parse_option_size(opt->name, opt->str, &opt->value.uint, errp);
591
        break;
592
    default:
593
        abort();
594
    }
595
}
596

    
597
static void qemu_opt_del(QemuOpt *opt)
598
{
599
    QTAILQ_REMOVE(&opt->opts->head, opt, next);
600
    g_free((/* !const */ char*)opt->name);
601
    g_free((/* !const */ char*)opt->str);
602
    g_free(opt);
603
}
604

    
605
static bool opts_accepts_any(const QemuOpts *opts)
606
{
607
    return opts->list->desc[0].name == NULL;
608
}
609

    
610
static const QemuOptDesc *find_desc_by_name(const QemuOptDesc *desc,
611
                                            const char *name)
612
{
613
    int i;
614

    
615
    for (i = 0; desc[i].name != NULL; i++) {
616
        if (strcmp(desc[i].name, name) == 0) {
617
            return &desc[i];
618
        }
619
    }
620

    
621
    return NULL;
622
}
623

    
624
static void opt_set(QemuOpts *opts, const char *name, const char *value,
625
                    bool prepend, Error **errp)
626
{
627
    QemuOpt *opt;
628
    const QemuOptDesc *desc;
629
    Error *local_err = NULL;
630

    
631
    desc = find_desc_by_name(opts->list->desc, name);
632
    if (!desc && !opts_accepts_any(opts)) {
633
        error_set(errp, QERR_INVALID_PARAMETER, name);
634
        return;
635
    }
636

    
637
    opt = g_malloc0(sizeof(*opt));
638
    opt->name = g_strdup(name);
639
    opt->opts = opts;
640
    if (prepend) {
641
        QTAILQ_INSERT_HEAD(&opts->head, opt, next);
642
    } else {
643
        QTAILQ_INSERT_TAIL(&opts->head, opt, next);
644
    }
645
    opt->desc = desc;
646
    if (value) {
647
        opt->str = g_strdup(value);
648
    }
649
    qemu_opt_parse(opt, &local_err);
650
    if (error_is_set(&local_err)) {
651
        error_propagate(errp, local_err);
652
        qemu_opt_del(opt);
653
    }
654
}
655

    
656
int qemu_opt_set(QemuOpts *opts, const char *name, const char *value)
657
{
658
    Error *local_err = NULL;
659

    
660
    opt_set(opts, name, value, false, &local_err);
661
    if (error_is_set(&local_err)) {
662
        qerror_report_err(local_err);
663
        error_free(local_err);
664
        return -1;
665
    }
666

    
667
    return 0;
668
}
669

    
670
void qemu_opt_set_err(QemuOpts *opts, const char *name, const char *value,
671
                      Error **errp)
672
{
673
    opt_set(opts, name, value, false, errp);
674
}
675

    
676
int qemu_opt_set_bool(QemuOpts *opts, const char *name, bool val)
677
{
678
    QemuOpt *opt;
679
    const QemuOptDesc *desc = opts->list->desc;
680

    
681
    opt = g_malloc0(sizeof(*opt));
682
    opt->desc = find_desc_by_name(desc, name);
683
    if (!opt->desc && !opts_accepts_any(opts)) {
684
        qerror_report(QERR_INVALID_PARAMETER, name);
685
        g_free(opt);
686
        return -1;
687
    }
688

    
689
    opt->name = g_strdup(name);
690
    opt->opts = opts;
691
    opt->value.boolean = !!val;
692
    opt->str = g_strdup(val ? "on" : "off");
693
    QTAILQ_INSERT_TAIL(&opts->head, opt, next);
694

    
695
    return 0;
696
}
697

    
698
int qemu_opt_foreach(QemuOpts *opts, qemu_opt_loopfunc func, void *opaque,
699
                     int abort_on_failure)
700
{
701
    QemuOpt *opt;
702
    int rc = 0;
703

    
704
    QTAILQ_FOREACH(opt, &opts->head, next) {
705
        rc = func(opt->name, opt->str, opaque);
706
        if (abort_on_failure  &&  rc != 0)
707
            break;
708
    }
709
    return rc;
710
}
711

    
712
QemuOpts *qemu_opts_find(QemuOptsList *list, const char *id)
713
{
714
    QemuOpts *opts;
715

    
716
    QTAILQ_FOREACH(opts, &list->head, next) {
717
        if (!opts->id) {
718
            if (!id) {
719
                return opts;
720
            }
721
            continue;
722
        }
723
        if (strcmp(opts->id, id) != 0) {
724
            continue;
725
        }
726
        return opts;
727
    }
728
    return NULL;
729
}
730

    
731
static int id_wellformed(const char *id)
732
{
733
    int i;
734

    
735
    if (!qemu_isalpha(id[0])) {
736
        return 0;
737
    }
738
    for (i = 1; id[i]; i++) {
739
        if (!qemu_isalnum(id[i]) && !strchr("-._", id[i])) {
740
            return 0;
741
        }
742
    }
743
    return 1;
744
}
745

    
746
QemuOpts *qemu_opts_create(QemuOptsList *list, const char *id,
747
                           int fail_if_exists, Error **errp)
748
{
749
    QemuOpts *opts = NULL;
750

    
751
    if (id) {
752
        if (!id_wellformed(id)) {
753
            error_set(errp,QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
754
            error_printf_unless_qmp("Identifiers consist of letters, digits, '-', '.', '_', starting with a letter.\n");
755
            return NULL;
756
        }
757
        opts = qemu_opts_find(list, id);
758
        if (opts != NULL) {
759
            if (fail_if_exists && !list->merge_lists) {
760
                error_set(errp, QERR_DUPLICATE_ID, id, list->name);
761
                return NULL;
762
            } else {
763
                return opts;
764
            }
765
        }
766
    } else if (list->merge_lists) {
767
        opts = qemu_opts_find(list, NULL);
768
        if (opts) {
769
            return opts;
770
        }
771
    }
772
    opts = g_malloc0(sizeof(*opts));
773
    if (id) {
774
        opts->id = g_strdup(id);
775
    }
776
    opts->list = list;
777
    loc_save(&opts->loc);
778
    QTAILQ_INIT(&opts->head);
779
    QTAILQ_INSERT_TAIL(&list->head, opts, next);
780
    return opts;
781
}
782

    
783
void qemu_opts_reset(QemuOptsList *list)
784
{
785
    QemuOpts *opts, *next_opts;
786

    
787
    QTAILQ_FOREACH_SAFE(opts, &list->head, next, next_opts) {
788
        qemu_opts_del(opts);
789
    }
790
}
791

    
792
void qemu_opts_loc_restore(QemuOpts *opts)
793
{
794
    loc_restore(&opts->loc);
795
}
796

    
797
int qemu_opts_set(QemuOptsList *list, const char *id,
798
                  const char *name, const char *value)
799
{
800
    QemuOpts *opts;
801
    Error *local_err = NULL;
802

    
803
    opts = qemu_opts_create(list, id, 1, &local_err);
804
    if (error_is_set(&local_err)) {
805
        qerror_report_err(local_err);
806
        error_free(local_err);
807
        return -1;
808
    }
809
    return qemu_opt_set(opts, name, value);
810
}
811

    
812
const char *qemu_opts_id(QemuOpts *opts)
813
{
814
    return opts->id;
815
}
816

    
817
void qemu_opts_del(QemuOpts *opts)
818
{
819
    QemuOpt *opt;
820

    
821
    for (;;) {
822
        opt = QTAILQ_FIRST(&opts->head);
823
        if (opt == NULL)
824
            break;
825
        qemu_opt_del(opt);
826
    }
827
    QTAILQ_REMOVE(&opts->list->head, opts, next);
828
    g_free(opts->id);
829
    g_free(opts);
830
}
831

    
832
int qemu_opts_print(QemuOpts *opts, void *dummy)
833
{
834
    QemuOpt *opt;
835

    
836
    fprintf(stderr, "%s: %s:", opts->list->name,
837
            opts->id ? opts->id : "<noid>");
838
    QTAILQ_FOREACH(opt, &opts->head, next) {
839
        fprintf(stderr, " %s=\"%s\"", opt->name, opt->str);
840
    }
841
    fprintf(stderr, "\n");
842
    return 0;
843
}
844

    
845
static int opts_do_parse(QemuOpts *opts, const char *params,
846
                         const char *firstname, bool prepend)
847
{
848
    char option[128], value[1024];
849
    const char *p,*pe,*pc;
850
    Error *local_err = NULL;
851

    
852
    for (p = params; *p != '\0'; p++) {
853
        pe = strchr(p, '=');
854
        pc = strchr(p, ',');
855
        if (!pe || (pc && pc < pe)) {
856
            /* found "foo,more" */
857
            if (p == params && firstname) {
858
                /* implicitly named first option */
859
                pstrcpy(option, sizeof(option), firstname);
860
                p = get_opt_value(value, sizeof(value), p);
861
            } else {
862
                /* option without value, probably a flag */
863
                p = get_opt_name(option, sizeof(option), p, ',');
864
                if (strncmp(option, "no", 2) == 0) {
865
                    memmove(option, option+2, strlen(option+2)+1);
866
                    pstrcpy(value, sizeof(value), "off");
867
                } else {
868
                    pstrcpy(value, sizeof(value), "on");
869
                }
870
            }
871
        } else {
872
            /* found "foo=bar,more" */
873
            p = get_opt_name(option, sizeof(option), p, '=');
874
            if (*p != '=') {
875
                break;
876
            }
877
            p++;
878
            p = get_opt_value(value, sizeof(value), p);
879
        }
880
        if (strcmp(option, "id") != 0) {
881
            /* store and parse */
882
            opt_set(opts, option, value, prepend, &local_err);
883
            if (error_is_set(&local_err)) {
884
                qerror_report_err(local_err);
885
                error_free(local_err);
886
                return -1;
887
            }
888
        }
889
        if (*p != ',') {
890
            break;
891
        }
892
    }
893
    return 0;
894
}
895

    
896
int qemu_opts_do_parse(QemuOpts *opts, const char *params, const char *firstname)
897
{
898
    return opts_do_parse(opts, params, firstname, false);
899
}
900

    
901
static QemuOpts *opts_parse(QemuOptsList *list, const char *params,
902
                            int permit_abbrev, bool defaults)
903
{
904
    const char *firstname;
905
    char value[1024], *id = NULL;
906
    const char *p;
907
    QemuOpts *opts;
908
    Error *local_err = NULL;
909

    
910
    assert(!permit_abbrev || list->implied_opt_name);
911
    firstname = permit_abbrev ? list->implied_opt_name : NULL;
912

    
913
    if (strncmp(params, "id=", 3) == 0) {
914
        get_opt_value(value, sizeof(value), params+3);
915
        id = value;
916
    } else if ((p = strstr(params, ",id=")) != NULL) {
917
        get_opt_value(value, sizeof(value), p+4);
918
        id = value;
919
    }
920
    if (defaults) {
921
        if (!id && !QTAILQ_EMPTY(&list->head)) {
922
            opts = qemu_opts_find(list, NULL);
923
        } else {
924
            opts = qemu_opts_create(list, id, 0, &local_err);
925
        }
926
    } else {
927
        opts = qemu_opts_create(list, id, 1, &local_err);
928
    }
929
    if (opts == NULL) {
930
        if (error_is_set(&local_err)) {
931
            qerror_report_err(local_err);
932
            error_free(local_err);
933
        }
934
        return NULL;
935
    }
936

    
937
    if (opts_do_parse(opts, params, firstname, defaults) != 0) {
938
        qemu_opts_del(opts);
939
        return NULL;
940
    }
941

    
942
    return opts;
943
}
944

    
945
QemuOpts *qemu_opts_parse(QemuOptsList *list, const char *params,
946
                          int permit_abbrev)
947
{
948
    return opts_parse(list, params, permit_abbrev, false);
949
}
950

    
951
void qemu_opts_set_defaults(QemuOptsList *list, const char *params,
952
                            int permit_abbrev)
953
{
954
    QemuOpts *opts;
955

    
956
    opts = opts_parse(list, params, permit_abbrev, true);
957
    assert(opts);
958
}
959

    
960
typedef struct OptsFromQDictState {
961
    QemuOpts *opts;
962
    Error **errp;
963
} OptsFromQDictState;
964

    
965
static void qemu_opts_from_qdict_1(const char *key, QObject *obj, void *opaque)
966
{
967
    OptsFromQDictState *state = opaque;
968
    char buf[32];
969
    const char *value;
970
    int n;
971

    
972
    if (!strcmp(key, "id") || error_is_set(state->errp)) {
973
        return;
974
    }
975

    
976
    switch (qobject_type(obj)) {
977
    case QTYPE_QSTRING:
978
        value = qstring_get_str(qobject_to_qstring(obj));
979
        break;
980
    case QTYPE_QINT:
981
        n = snprintf(buf, sizeof(buf), "%" PRId64,
982
                     qint_get_int(qobject_to_qint(obj)));
983
        assert(n < sizeof(buf));
984
        value = buf;
985
        break;
986
    case QTYPE_QFLOAT:
987
        n = snprintf(buf, sizeof(buf), "%.17g",
988
                     qfloat_get_double(qobject_to_qfloat(obj)));
989
        assert(n < sizeof(buf));
990
        value = buf;
991
        break;
992
    case QTYPE_QBOOL:
993
        pstrcpy(buf, sizeof(buf),
994
                qbool_get_int(qobject_to_qbool(obj)) ? "on" : "off");
995
        value = buf;
996
        break;
997
    default:
998
        return;
999
    }
1000

    
1001
    qemu_opt_set_err(state->opts, key, value, state->errp);
1002
}
1003

    
1004
/*
1005
 * Create QemuOpts from a QDict.
1006
 * Use value of key "id" as ID if it exists and is a QString.
1007
 * Only QStrings, QInts, QFloats and QBools are copied.  Entries with
1008
 * other types are silently ignored.
1009
 */
1010
QemuOpts *qemu_opts_from_qdict(QemuOptsList *list, const QDict *qdict,
1011
                               Error **errp)
1012
{
1013
    OptsFromQDictState state;
1014
    Error *local_err = NULL;
1015
    QemuOpts *opts;
1016

    
1017
    opts = qemu_opts_create(list, qdict_get_try_str(qdict, "id"), 1,
1018
                            &local_err);
1019
    if (error_is_set(&local_err)) {
1020
        error_propagate(errp, local_err);
1021
        return NULL;
1022
    }
1023

    
1024
    assert(opts != NULL);
1025

    
1026
    state.errp = &local_err;
1027
    state.opts = opts;
1028
    qdict_iter(qdict, qemu_opts_from_qdict_1, &state);
1029
    if (error_is_set(&local_err)) {
1030
        error_propagate(errp, local_err);
1031
        qemu_opts_del(opts);
1032
        return NULL;
1033
    }
1034

    
1035
    return opts;
1036
}
1037

    
1038
/*
1039
 * Convert from QemuOpts to QDict.
1040
 * The QDict values are of type QString.
1041
 * TODO We'll want to use types appropriate for opt->desc->type, but
1042
 * this is enough for now.
1043
 */
1044
QDict *qemu_opts_to_qdict(QemuOpts *opts, QDict *qdict)
1045
{
1046
    QemuOpt *opt;
1047
    QObject *val;
1048

    
1049
    if (!qdict) {
1050
        qdict = qdict_new();
1051
    }
1052
    if (opts->id) {
1053
        qdict_put(qdict, "id", qstring_from_str(opts->id));
1054
    }
1055
    QTAILQ_FOREACH(opt, &opts->head, next) {
1056
        val = QOBJECT(qstring_from_str(opt->str));
1057
        qdict_put_obj(qdict, opt->name, val);
1058
    }
1059
    return qdict;
1060
}
1061

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

    
1070
    assert(opts_accepts_any(opts));
1071

    
1072
    QTAILQ_FOREACH(opt, &opts->head, next) {
1073
        opt->desc = find_desc_by_name(desc, opt->name);
1074
        if (!opt->desc) {
1075
            error_set(errp, QERR_INVALID_PARAMETER, opt->name);
1076
            return;
1077
        }
1078

    
1079
        qemu_opt_parse(opt, &local_err);
1080
        if (error_is_set(&local_err)) {
1081
            error_propagate(errp, local_err);
1082
            return;
1083
        }
1084
    }
1085
}
1086

    
1087
int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func, void *opaque,
1088
                      int abort_on_failure)
1089
{
1090
    Location loc;
1091
    QemuOpts *opts;
1092
    int rc = 0;
1093

    
1094
    loc_push_none(&loc);
1095
    QTAILQ_FOREACH(opts, &list->head, next) {
1096
        loc_restore(&opts->loc);
1097
        rc |= func(opts, opaque);
1098
        if (abort_on_failure  &&  rc != 0)
1099
            break;
1100
    }
1101
    loc_pop(&loc);
1102
    return rc;
1103
}