bhyve_parse_command.c 25.8 KB
Newer Older
1 2 3 4 5
/*
 * bhyve_parse_command.c: Bhyve command parser
 *
 * Copyright (C) 2006-2016 Red Hat, Inc.
 * Copyright (C) 2006 Daniel P. Berrange
6
 * Copyright (c) 2011 NetApp, Inc.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * Copyright (C) 2016 Fabian Freyer
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>
25
#include <libutil.h>
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

#include "bhyve_capabilities.h"
#include "bhyve_command.h"
#include "bhyve_parse_command.h"
#include "viralloc.h"
#include "virlog.h"
#include "virstring.h"
#include "virutil.h"

#define VIR_FROM_THIS VIR_FROM_BHYVE

VIR_LOG_INIT("bhyve.bhyve_parse_command");

/*
 * This function takes a string representation of the command line and removes
 * all newline characters, if they are prefixed by a backslash. The result
 * should be a string with one command per line.
 *
 * NB: command MUST be NULL-Terminated.
 */
static char *
bhyveParseCommandLineUnescape(const char *command)
{
    size_t len = strlen(command);
    char *unescaped = NULL;
    char *curr_src = NULL;
    char *curr_dst = NULL;

    /* Since we are only removing characters, allocating a buffer of the same
     * size as command shouldn't be a problem here */
    if (VIR_ALLOC_N(unescaped, len+1) < 0)
        return NULL;

    /* Iterate over characters in the command, skipping "\\\n", "\\\r" as well
     * as "\\\r\n". */
    for (curr_src = (char*) command, curr_dst = unescaped; *curr_src != '\0';
        curr_src++, curr_dst++) {
        if (*curr_src == '\\') {
            switch (*(curr_src + 1)) {
                case '\n': /* \LF */
                    curr_src++;
                    curr_dst--;
                    break;
                case '\r': /* \CR */
                    curr_src++;
                    curr_dst--;
                    if (*curr_src == '\n') /* \CRLF */
                        curr_src++;
                    break;
                default:
                    *curr_dst = '\\';
            }
        } else {
            *curr_dst = *curr_src;
        }
    }

    return unescaped;
}

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
/*
 * This function is adapted from vm_parse_memsize in
 * /lib/libvmmapi/vmmapi.c in the FreeBSD Source tree.
 */
static int
bhyveParseMemsize(const char *arg, size_t *ret_memsize)
{
    size_t val;
    int error;

    if (virStrToLong_ul(arg, NULL, 10, &val) == 0) {
        /*
         * For the sake of backward compatibility if the memory size
         * specified on the command line is less than a megabyte then
         * it is interpreted as being in units of MB.
         */
        if (val < 1024 * 1024UL)
            val *= 1024 * 1024UL;
        *ret_memsize = val;
        error = 0;
    } else {
        error = expand_number(arg, ret_memsize);
    }

    /* use memory in KiB here */
    *ret_memsize /= 1024UL;

    return error;
}

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
/*
 * Try to extract loader and bhyve argv lists from a command line string.
 */
static int
bhyveCommandLineToArgv(const char *nativeConfig,
                      int *loader_argc,
                      char ***loader_argv,
                      int *bhyve_argc,
                      char ***bhyve_argv)
{
    const char *curr = NULL;
    char *nativeConfig_unescaped = NULL;
    const char *start;
    const char *next;
    char *line;
    char **lines = NULL;
    size_t i;
    size_t line_count = 0;
    size_t lines_alloc = 0;
    char **_bhyve_argv = NULL;
    char **_loader_argv = NULL;

    nativeConfig_unescaped = bhyveParseCommandLineUnescape(nativeConfig);
    if (nativeConfig_unescaped == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to unescape command line string"));
        goto error;
    }

    curr = nativeConfig_unescaped;

    /* Iterate over string, splitting on sequences of '\n' */
    while (curr && *curr != '\0') {
        start = curr;
        next = strchr(curr, '\n');

152 153 154 155
        if (next)
            line = g_strndup(curr, next - curr);
        else
            line = g_strdup(curr);
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

        if (VIR_RESIZE_N(lines, lines_alloc, line_count, 2) < 0) {
            VIR_FREE(line);
            goto error;
        }

        if (*line)
            lines[line_count++] = line;
        lines[line_count] = NULL;

        while (next && (*next == '\n' || *next == '\r'
                        || STRPREFIX(next, "\r\n")))
            next++;

        curr = next;
    }

    for (i = 0; i < line_count; i++) {
        curr = lines[i];
        size_t j;
        char **arglist = NULL;
        size_t args_count = 0;
        size_t args_alloc = 0;

        /* iterate over each line, splitting on sequences of ' '. This code is
         * adapted from qemu/qemu_parse_command.c. */
        while (curr && *curr != '\0') {
            char *arg;
            start = curr;

            if (*start == '\'') {
                if (start == curr)
                    curr++;
                next = strchr(start + 1, '\'');
            } else if (*start == '"') {
                if (start == curr)
                    curr++;
                next = strchr(start + 1, '"');
            } else {
                next = strchr(start, ' ');
            }

198 199 200 201
            if (next)
                arg = g_strndup(curr, next - curr);
            else
                arg = g_strdup(curr);
202 203 204 205 206 207 208 209 210 211 212 213

            if (next && (*next == '\'' || *next == '"'))
                next++;

            if (VIR_RESIZE_N(arglist, args_alloc, args_count, 2) < 0) {
                VIR_FREE(arg);
                goto error;
            }

            arglist[args_count++] = arg;
            arglist[args_count] = NULL;

214
            while (next && g_ascii_isspace(*next))
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
                next++;

            curr = next;
        }

        VIR_FREE(nativeConfig_unescaped);

        /* To prevent a memory leak here, only set the argument lists when
         * the first matching command is found. This shouldn't really be a
         * problem, since usually no multiple loaders or bhyverun commands
         * are specified (this wouldn't really be valid anyways).
         * Otherwise, later argument lists may be assigned to _argv without
         * freeing the earlier ones. */
        if (!_bhyve_argv && STREQ(arglist[0], "/usr/sbin/bhyve")) {
            if ((VIR_REALLOC_N(_bhyve_argv, args_count + 1) < 0)
                || (!bhyve_argc))
                goto error;
            for (j = 0; j < args_count; j++)
                _bhyve_argv[j] = arglist[j];
            _bhyve_argv[j] = NULL;
            *bhyve_argc = args_count-1;
            VIR_FREE(arglist);
        } else if (!_loader_argv) {
            if ((VIR_REALLOC_N(_loader_argv, args_count + 1) < 0)
                || (!loader_argc))
                goto error;
            for (j = 0; j < args_count; j++)
                _loader_argv[j] = arglist[j];
            _loader_argv[j] = NULL;
            *loader_argc = args_count-1;
            VIR_FREE(arglist);
        } else {
            /* To prevent a use-after-free here, only free the argument list
             * when it is definitely not going to be used */
249
            virStringListFree(arglist);
250 251 252 253 254 255 256
        }
    }

    *loader_argv = _loader_argv;
    if (!(*bhyve_argv = _bhyve_argv))
        goto error;

257
    virStringListFree(lines);
258 259 260 261 262
    return 0;

 error:
    VIR_FREE(_loader_argv);
    VIR_FREE(_bhyve_argv);
263
    virStringListFree(lines);
264 265 266
    return -1;
}

267 268
static int
bhyveParseBhyveLPCArg(virDomainDefPtr def,
J
Ján Tomko 已提交
269
                      unsigned caps G_GNUC_UNUSED,
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
                      const char *arg)
{
    /* -l emulation[,config] */
    const char *separator = NULL;
    const char *param = NULL;
    size_t last = 0;
    virDomainChrDefPtr chr = NULL;
    char *type = NULL;

    separator = strchr(arg, ',');
    param = separator + 1;

    if (!separator)
        goto error;

285
    type = g_strndup(arg, separator - arg);
286 287 288

    /* Only support com%d */
    if (STRPREFIX(type, "com") && type[4] == 0) {
289
        if (!(chr = virDomainChrDefNew(NULL)))
290 291
            goto error;

292 293 294
        chr->source->type = VIR_DOMAIN_CHR_TYPE_NMDM;
        chr->source->data.nmdm.master = NULL;
        chr->source->data.nmdm.slave = NULL;
295 296 297 298 299 300 301 302 303
        chr->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL;

        if (!STRPREFIX(param, "/dev/nmdm")) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("Failed to set com port %s: does not start with "
                             "'/dev/nmdm'."), type);
                goto error;
        }

304 305
        chr->source->data.nmdm.master = g_strdup(param);
        chr->source->data.nmdm.slave = g_strdup(chr->source->data.file.path);
306 307 308

        /* If the last character of the master is 'A', the slave will be 'B'
         * and vice versa */
309 310
        last = strlen(chr->source->data.nmdm.master) - 1;
        switch (chr->source->data.file.path[last]) {
311
            case 'A':
312
                chr->source->data.nmdm.slave[last] = 'B';
313 314
                break;
            case 'B':
315
                chr->source->data.nmdm.slave[last] = 'A';
316 317 318 319 320
                break;
            default:
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("Failed to set slave for %s: last letter not "
                                 "'A' or 'B'"),
321
                               NULLSTR(chr->source->data.nmdm.master));
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
                goto error;
        }

        switch (type[3]-'0') {
        case 1:
        case 2:
            chr->target.port = type[3] - '1';
            break;
        default:
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("Failed to parse %s: only com1 and com2"
                             " supported."), type);
            goto error;
            break;
        }

        if (VIR_APPEND_ELEMENT(def->serials, def->nserials, chr) < 0) {
            virDomainChrDefFree(chr);
            goto error;
        }
    }

    VIR_FREE(type);
    return 0;

 error:
    virDomainChrDefFree(chr);
    VIR_FREE(type);
    return -1;
}

static int
bhyveParsePCISlot(const char *slotdef,
                  unsigned *pcislot,
                  unsigned *bus,
                  unsigned *function)
{
    /* slot[:function] | bus:slot:function */
    const char *curr = NULL;
    const char *next = NULL;
    unsigned values[3];
    size_t i;

    curr = slotdef;
    for (i = 0; i < 3; i++) {
       char *val = NULL;

       next = strchr(curr, ':');

371 372 373 374
       if (next)
           val = g_strndup(curr, next - curr);
       else
           val = g_strdup(curr);
375 376

       if (virStrToLong_ui(val, NULL, 10, &values[i]) < 0)
377
           return -1;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

       VIR_FREE(val);

       if (!next)
           break;

       curr = next +1;
    }

    *bus = 0;
    *pcislot = 0;
    *function = 0;

    switch (i + 1) {
    case 2:
        /* pcislot[:function] */
        *function = values[1];
    case 1:
        *pcislot = values[0];
        break;
    case 3:
        /* bus:pcislot:function */
        *bus = values[0];
        *pcislot = values[1];
        *function = values[2];
        break;
    }

    return 0;
}

static int
bhyveParsePCIDisk(virDomainDefPtr def,
J
Ján Tomko 已提交
411
                  unsigned caps G_GNUC_UNUSED,
412 413 414 415 416 417 418 419 420 421 422 423 424 425
                  unsigned pcislot,
                  unsigned pcibus,
                  unsigned function,
                  int bus,
                  int device,
                  unsigned *nvirtiodisk,
                  unsigned *nahcidisk,
                  char *config)
{
    /* -s slot,virtio-blk|ahci-cd|ahci-hd,/path/to/file */
    const char *separator = NULL;
    int idx = -1;
    virDomainDiskDefPtr disk = NULL;

426
    if (!(disk = virDomainDiskDefNew(NULL)))
427
        return 0;
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

    disk->bus = bus;
    disk->device = device;

    disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
    disk->info.addr.pci.slot = pcislot;
    disk->info.addr.pci.bus = pcibus;
    disk->info.addr.pci.function = function;

    if (STRPREFIX(config, "/dev/"))
        disk->src->type = VIR_STORAGE_TYPE_BLOCK;
    else
        disk->src->type = VIR_STORAGE_TYPE_FILE;

    if (!config)
        goto error;

    separator = strchr(config, ',');
446 447 448 449
    if (separator)
        disk->src->path = g_strndup(config, separator - config);
    else
        disk->src->path = g_strdup(config);
450 451 452 453

    if (bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
        idx = *nvirtiodisk;
        *nvirtiodisk += 1;
454
        disk->dst = g_strdup("vda");
455 456 457
    } else if (bus == VIR_DOMAIN_DISK_BUS_SATA) {
        idx = *nahcidisk;
        *nahcidisk += 1;
458
        disk->dst = g_strdup("sda");
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    }

    if (idx > 'z' - 'a') {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("too many disks"));
        goto error;
    }

    disk->dst[2] = 'a' + idx;

    if (VIR_APPEND_ELEMENT(def->disks, def->ndisks, disk) < 0)
        goto error;

    return 0;

 error:
    virDomainDiskDefFree(disk);
    return -1;
}

static int
bhyveParsePCINet(virDomainDefPtr def,
                 virDomainXMLOptionPtr xmlopt,
J
Ján Tomko 已提交
482
                 unsigned caps G_GNUC_UNUSED,
483 484 485
                 unsigned pcislot,
                 unsigned pcibus,
                 unsigned function,
C
Cole Robinson 已提交
486
                 int model,
487 488 489 490 491 492 493 494
                 const char *config)
{
    /* -s slot,virtio-net,tapN[,mac=xx:xx:xx:xx:xx:xx] */

    virDomainNetDefPtr net = NULL;
    const char *separator = NULL;
    const char *mac = NULL;

495
    if (!(net = virDomainNetDefNew(xmlopt)))
496 497
        goto cleanup;

498 499 500 501
    /* As we only support interface type='bridge' and cannot
     * guess the actual bridge name from the command line,
     * try to come up with some reasonable defaults */
    net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;
502
    net->data.bridge.brname = g_strdup("virbr0");
503

C
Cole Robinson 已提交
504
    net->model = model;
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
    net->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
    net->info.addr.pci.slot = pcislot;
    net->info.addr.pci.bus = pcibus;
    net->info.addr.pci.function = function;

    if (!config)
        goto error;

    if (!STRPREFIX(config, "tap")) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Only tap devices supported"));
        goto error;
    }

    separator = strchr(config, ',');
520 521 522 523
    if (separator)
        net->ifname = g_strndup(config, separator - config);
    else
        net->ifname = g_strdup(config);
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576

    if (!separator)
        goto cleanup;

    if (!STRPREFIX(++separator, "mac=")) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Only mac option can be specified for virt-net"));
        goto error;
    }
    mac = separator + 4;

    if (virMacAddrParse(mac, &net->mac) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to parse mac address '%s'"),
                       mac);
        goto cleanup;
     }

 cleanup:
    if (!mac)
        virDomainNetGenerateMAC(xmlopt, &net->mac);

    if (VIR_APPEND_ELEMENT(def->nets, def->nnets, net) < 0)
        goto error;
    return 0;

 error:
    virDomainNetDefFree(net);
    return -1;
}

static int
bhyveParseBhyvePCIArg(virDomainDefPtr def,
                      virDomainXMLOptionPtr xmlopt,
                      unsigned caps,
                      unsigned *nvirtiodisk,
                      unsigned *nahcidisk,
                      const char *arg)
{
    /* -s slot,emulation[,conf] */
    const char *separator = NULL;
    char *slotdef = NULL;
    char *emulation = NULL;
    char *conf = NULL;
    unsigned pcislot, bus, function;

    separator = strchr(arg, ',');

    if (!separator)
        goto error;
    else
        separator++; /* Skip comma */

577
    slotdef = g_strndup(arg, separator - arg - 1);
578 579

    conf = strchr(separator+1, ',');
580
    if (conf) {
581
        conf++; /* Skip initial comma */
582 583 584 585
        emulation = g_strndup(separator, conf - separator - 1);
    } else {
        emulation = g_strdup(separator);
    }
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

    if (bhyveParsePCISlot(slotdef, &pcislot, &bus, &function) < 0)
        goto error;

    if (STREQ(emulation, "ahci-cd"))
        bhyveParsePCIDisk(def, caps, pcislot, bus, function,
                          VIR_DOMAIN_DISK_BUS_SATA,
                          VIR_DOMAIN_DISK_DEVICE_CDROM,
                          nvirtiodisk,
                          nahcidisk,
                          conf);
    else if (STREQ(emulation, "ahci-hd"))
        bhyveParsePCIDisk(def, caps, pcislot, bus, function,
                          VIR_DOMAIN_DISK_BUS_SATA,
                          VIR_DOMAIN_DISK_DEVICE_DISK,
                          nvirtiodisk,
                          nahcidisk,
                          conf);
    else if (STREQ(emulation, "virtio-blk"))
        bhyveParsePCIDisk(def, caps, pcislot, bus, function,
                          VIR_DOMAIN_DISK_BUS_VIRTIO,
                          VIR_DOMAIN_DISK_DEVICE_DISK,
                          nvirtiodisk,
                          nahcidisk,
                          conf);
    else if (STREQ(emulation, "virtio-net"))
R
Roman Bogorodskiy 已提交
612
        bhyveParsePCINet(def, xmlopt, caps, pcislot, bus, function,
C
Cole Robinson 已提交
613
                         VIR_DOMAIN_NET_MODEL_VIRTIO, conf);
R
Roman Bogorodskiy 已提交
614 615
    else if (STREQ(emulation, "e1000"))
        bhyveParsePCINet(def, xmlopt, caps, pcislot, bus, function,
C
Cole Robinson 已提交
616
                         VIR_DOMAIN_NET_MODEL_E1000, conf);
617 618 619 620 621 622 623 624 625 626

    VIR_FREE(emulation);
    VIR_FREE(slotdef);
    return 0;
 error:
    VIR_FREE(emulation);
    VIR_FREE(slotdef);
    return -1;
}

627 628 629 630
#define CONSUME_ARG(var) \
    if ((opti + 1) == argc) { \
        virReportError(VIR_ERR_INVALID_ARG, _("Missing argument for '%s'"), \
                       argv[opti]); \
631
        return -1; \
632 633 634
    } \
    var = argv[++opti]

635 636 637 638 639 640 641 642 643 644 645 646 647
/*
 * Parse the /usr/sbin/bhyve command line.
 */
static int
bhyveParseBhyveCommandLine(virDomainDefPtr def,
                           virDomainXMLOptionPtr xmlopt,
                           unsigned caps,
                           int argc, char **argv)
{
    int vcpus = 1;
    size_t memory = 0;
    unsigned nahcidisks = 0;
    unsigned nvirtiodisks = 0;
648 649
    size_t opti;
    const char *arg;
650

651 652 653
    for (opti = 1; opti < argc; opti++) {
        if (argv[opti][0] != '-')
            break;
654

655
        switch (argv[opti][1]) {
656 657 658 659
        case 'A':
            def->features[VIR_DOMAIN_FEATURE_ACPI] = VIR_TRISTATE_SWITCH_ON;
            break;
        case 'c':
660 661
            CONSUME_ARG(arg);
            if (virStrToLong_i(arg, NULL, 10, &vcpus) < 0) {
662 663
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("Failed to parse number of vCPUs"));
664
                return -1;
665
            }
666
            if (virDomainDefSetVcpusMax(def, vcpus, xmlopt) < 0)
667
                return -1;
668
            if (virDomainDefSetVcpus(def, vcpus) < 0)
669
                return -1;
670 671
            break;
        case 'l':
672 673
            CONSUME_ARG(arg);
            if (bhyveParseBhyveLPCArg(def, caps, arg))
674
                return -1;
675 676
            break;
        case 's':
677
            CONSUME_ARG(arg);
678 679 680 681 682
            if (bhyveParseBhyvePCIArg(def,
                                      xmlopt,
                                      caps,
                                      &nahcidisks,
                                      &nvirtiodisks,
683
                                      arg))
684
                return -1;
685 686
            break;
        case 'm':
687 688
            CONSUME_ARG(arg);
            if (bhyveParseMemsize(arg, &memory)) {
689 690
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("Failed to parse memory"));
691
                return -1;
692 693 694 695
            }
            if (def->mem.cur_balloon != 0 && def->mem.cur_balloon != memory) {
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("Failed to parse memory: size mismatch"));
696
                return -1;
697 698 699 700 701 702 703 704 705 706 707 708 709
            }
            def->mem.cur_balloon = memory;
            virDomainDefSetMemoryTotal(def, memory);
            break;
        case 'I':
            /* While this flag was deprecated in FreeBSD r257423, keep checking
             * for it for backwards compatibility. */
            def->features[VIR_DOMAIN_FEATURE_APIC] = VIR_TRISTATE_SWITCH_ON;
            break;
        case 'u':
            def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_UTC;
            break;
        case 'U':
710 711
            CONSUME_ARG(arg);
            if (virUUIDParse(arg, def->uuid) < 0) {
712
                virReportError(VIR_ERR_INTERNAL_ERROR,
713
                               _("Cannot parse UUID '%s'"), arg);
714
                return -1;
715 716
            }
            break;
717 718 719
        case 'S':
            def->mem.locked = true;
            break;
720 721 722
        case 'p':
        case 'g':
            CONSUME_ARG(arg);
723 724 725
        }
    }

726
    if (argc != opti) {
727 728
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to parse arguments for bhyve command"));
729
        return -1;
730 731 732
    }

    if (def->name == NULL) {
733
        def->name = g_strdup(argv[argc]);
734 735 736 737 738
    } else if (STRNEQ(def->name, argv[argc])) {
        /* the vm name of the loader and the bhyverun command differ, throw an
         * error here */
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to parse arguments: VM name mismatch"));
739
        return -1;
740 741 742 743 744
    }

    return 0;
}

745 746 747 748 749 750 751 752 753 754 755 756 757
/*
 * Parse the /usr/sbin/bhyveload command line.
 */
static int
bhyveParseBhyveLoadCommandLine(virDomainDefPtr def,
                               int argc, char **argv)
{
    /* bhyveload called with default arguments when only -m and -d are given.
     * Store this in a bit field and check if only those two options are given
     * later */
    unsigned arguments = 0;
    size_t memory = 0;
    size_t i = 0;
758 759
    size_t opti;
    const char *arg;
760

761 762 763
    for (opti = 1; opti < argc; opti++) {
        if (argv[opti][0] != '-')
            break;
764

765
        switch (argv[opti][1]) {
766
        case 'd':
767
            CONSUME_ARG(arg);
768 769 770 771 772
            arguments |= 1;
            /* Iterate over the disks of the domain trying to match up the
             * source */
            for (i = 0; i < def->ndisks; i++) {
                if (STREQ(virDomainDiskGetSource(def->disks[i]),
773
                          arg)) {
774 775 776 777 778 779
                    def->disks[i]->info.bootIndex = i;
                    break;
                }
            }
            break;
        case 'm':
780
            CONSUME_ARG(arg);
781
            arguments |= 2;
782
            if (bhyveParseMemsize(arg, &memory)) {
783 784
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("Failed to parse memory"));
785
                return -1;
786 787 788 789
            }
            if (def->mem.cur_balloon != 0 && def->mem.cur_balloon != memory) {
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("Failed to parse memory: size mismatch"));
790
                return -1;
791 792 793 794 795 796 797 798 799
            }
            def->mem.cur_balloon = memory;
            virDomainDefSetMemoryTotal(def, memory);
            break;
        default:
            arguments |= 4;
        }
    }

800 801 802
    if (argc != opti) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to parse arguments for bhyve command"));
803
        return -1;
804 805
    }

806 807 808
    if (arguments != 3) {
        /* Set os.bootloader since virDomainDefFormatInternal will only format
         * the bootloader arguments if os->bootloader is set. */
809
        def->os.bootloader = g_strdup(argv[0]);
810
        def->os.bootloaderArgs = virStringListJoin((const char**) &argv[1], " ");
811 812 813
    }

    if (def->name == NULL) {
814
        def->name = g_strdup(argv[argc]);
815 816 817 818 819
    } else if (STRNEQ(def->name, argv[argc])) {
        /* the vm name of the loader and the bhyverun command differ, throw an
         * error here */
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to parse arguments: VM name mismatch"));
820
        return -1;
821 822
    }

823
    return 0;
824 825 826 827
}

static int
bhyveParseCustomLoaderCommandLine(virDomainDefPtr def,
J
Ján Tomko 已提交
828
                                  int argc G_GNUC_UNUSED,
829 830 831
                                  char **argv)
{
    if (!argv)
832
        return -1;
833

834
    def->os.bootloader = g_strdup(argv[0]);
835
    def->os.bootloaderArgs = virStringListJoin((const char**) &argv[1], " ");
836 837 838 839

    return 0;
}

840 841
virDomainDefPtr
bhyveParseCommandLineString(const char* nativeConfig,
842 843
                            unsigned caps,
                            virDomainXMLOptionPtr xmlopt)
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
{
    virDomainDefPtr def = NULL;
    int bhyve_argc = 0;
    char **bhyve_argv = NULL;
    int loader_argc = 0;
    char **loader_argv = NULL;

    if (!(def = virDomainDefNew()))
        goto cleanup;

    /* Initialize defaults. */
    def->virtType = VIR_DOMAIN_VIRT_BHYVE;
    if (virUUIDGenerate(def->uuid) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to generate uuid"));
        virDomainDefFree(def);
        def = NULL;
        goto cleanup;
    }
    def->id = -1;
    def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME;

    if (bhyveCommandLineToArgv(nativeConfig,
                               &loader_argc, &loader_argv,
                               &bhyve_argc, &bhyve_argv)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to convert the command string to argv-lists"));
        goto error;
    }

874 875
    if (bhyveParseBhyveCommandLine(def, xmlopt, caps, bhyve_argc, bhyve_argv))
        goto error;
876 877 878 879 880 881 882
    if (loader_argv && STREQ(loader_argv[0], "/usr/sbin/bhyveload")) {
        if (bhyveParseBhyveLoadCommandLine(def, loader_argc, loader_argv))
            goto error;
    } else if (loader_argv) {
        if (bhyveParseCustomLoaderCommandLine(def, loader_argc, loader_argv))
            goto error;
    }
883

884
 cleanup:
885 886
    virStringListFree(loader_argv);
    virStringListFree(bhyve_argv);
887 888 889 890 891 892
    return def;
 error:
    virDomainDefFree(def);
    def = NULL;
    goto cleanup;
}