2 * Copyright (c) 2017 Netflix, Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
52 #include <geom/geom.h>
53 #include <geom/geom_ctl.h>
54 #include <geom/geom_int.h>
59 #include <efivar-dp.h>
61 #ifndef LOAD_OPTION_ACTIVE
62 #define LOAD_OPTION_ACTIVE 0x00000001
65 #ifndef LOAD_OPTION_CATEGORY_BOOT
66 #define LOAD_OPTION_CATEGORY_BOOT 0x00000000
69 #define BAD_LENGTH ((size_t)-1)
71 typedef struct _bmgr_opts {
95 static struct option lopts[] = {
96 {"activate", required_argument, NULL, 'a'},
97 {"bootnext", required_argument, NULL, 'n'}, /* set bootnext */
98 {"bootorder", required_argument, NULL, 'o'}, /* set order */
99 {"copy", required_argument, NULL, 'C'}, /* Copy boot method */
100 {"create", no_argument, NULL, 'c'},
101 {"deactivate", required_argument, NULL, 'A'},
102 {"del-timout", no_argument, NULL, 'T'},
103 {"delete", required_argument, NULL, 'B'},
104 {"delete-bootnext", required_argument, NULL, 'N'},
105 {"device", required_argument, NULL, 'd'},
106 {"dry-run", no_argument, NULL, 'D'},
107 {"env", required_argument, NULL, 'e'},
108 {"help", no_argument, NULL, 'h'},
109 {"kernel", required_argument, NULL, 'k'},
110 {"label", required_argument, NULL, 'L'},
111 {"loader", required_argument, NULL, 'l'},
112 {"once", no_argument, NULL, 'O'},
113 {"partition", required_argument, NULL, 'p'},
114 {"set-timeout", required_argument, NULL, 't'},
115 {"verbose", no_argument, NULL, 'v'},
119 /* global efibootmgr opts */
120 static bmgr_opts_t opts;
122 static LIST_HEAD(efivars_head, entry) efivars =
123 LIST_HEAD_INITIALIZER(efivars);
136 LIST_ENTRY(entry) entries;
139 #define MAX_DP_LEN 4096
140 #define MAX_LOADOPT_LEN 8192
144 mangle_loader(char *loader)
148 for (c = loader; *c; c++)
156 #define COMMON_ATTRS EFI_VARIABLE_NON_VOLATILE | \
157 EFI_VARIABLE_BOOTSERVICE_ACCESS | \
158 EFI_VARIABLE_RUNTIME_ACCESS
161 * We use global guid, and common var attrs and
162 * find it better to just delete and re-create a var.
165 set_bootvar(const char *name, uint8_t *data, size_t size)
168 return efi_set_variable(EFI_GLOBAL_GUID, name, data, size,
174 " [-aAnNB Bootvar] [-t timeout] [-T] [-o bootorder] [-O] [--verbose] [--help] \n\
175 [-c -l loader [-k kernel ] [-L label] [--dry-run]]"
177 #define CREATE_USAGE \
178 " efibootmgr -c -l loader [-k kernel] [-L label] [--dry-run]"
179 #define ORDER_USAGE \
180 " efibootmgr -o bootvarnum1,bootvarnum2,..."
181 #define TIMEOUT_USAGE \
182 " efibootmgr -t seconds"
183 #define DELETE_USAGE \
184 " efibootmgr -B bootvarnum"
185 #define ACTIVE_USAGE \
186 " efibootmgr [-a | -A] bootvarnum"
187 #define BOOTNEXT_USAGE \
188 " efibootmgr [-n | -N] bootvarnum"
191 parse_args(int argc, char *argv[])
195 while ((ch = getopt_long(argc, argv, "A:a:B:C:cDe:hk:L:l:Nn:Oo:Tt:v",
196 lopts, NULL)) != -1) {
199 opts.set_inactive = true;
200 opts.bootnum = strtoul(optarg, NULL, 16);
203 opts.set_active = true;
204 opts.bootnum = strtoul(optarg, NULL, 16);
208 opts.bootnum = strtoul(optarg, NULL, 16);
212 opts.cp_src = strtoul(optarg, NULL, 16);
216 case 'D': /* should be remove dups XXX */
221 opts.env = strdup(optarg);
225 errx(1, "%s", USAGE);
229 opts.kernel = strdup(optarg);
233 opts.label = strdup(optarg);
237 opts.loader = strdup(optarg);
238 opts.loader = mangle_loader(opts.loader);
241 opts.delete_bootnext = true;
244 opts.set_bootnext = true;
245 opts.bootnum = strtoul(optarg, NULL, 16);
252 opts.order = strdup(optarg);
255 opts.del_timeout = true;
258 opts.set_timeout = true;
259 opts.timeout = strtoul(optarg, NULL, 10);
268 errx(1, "%s",CREATE_USAGE);
271 if (opts.set_bootnext && !(opts.bootnum))
272 errx(1, "%s", BOOTNEXT_USAGE);
274 if ((opts.set_active || opts.set_inactive) && !(opts.bootnum))
275 errx(1, "%s", ACTIVE_USAGE);
277 if (opts.order && !(opts.order))
278 errx(1, "%s", ORDER_USAGE);
287 char *next_name = NULL;
293 while ((ret = efi_get_next_variable_name(&guid, &next_name)) > 0) {
295 * Only pay attention to EFI:BootXXXX variables to get the list.
297 if (efi_guid_cmp(guid, &EFI_GLOBAL_GUID) != 0 ||
298 strlen(next_name) != 8 ||
299 strncmp(next_name, "Boot", 4) != 0 ||
300 !isxdigit(next_name[4]) ||
301 !isxdigit(next_name[5]) ||
302 !isxdigit(next_name[6]) ||
303 !isxdigit(next_name[7]))
305 nent = malloc(sizeof(struct entry));
306 nent->name = strdup(next_name);
308 ret = efi_get_variable(*guid, next_name, &nent->data,
309 &nent->size, &nent->attrs);
311 err(1, "efi_get_variable");
313 nent->idx = strtoul(&next_name[4], NULL, 16);
314 LIST_INSERT_HEAD(&efivars, nent, entries);
320 set_boot_order(char *order)
334 size = sizeof(uint16_t) * cnt;
335 new_data = malloc(size);
339 while ((next = strsep(&cp, ",")) != NULL) {
340 new_data[i] = strtoul(next, NULL, 16);
341 if (new_data[i] == 0 && errno == EINVAL) {
342 warnx("can't parse %s as a numb", next);
343 errx(1, "%s", ORDER_USAGE);
348 if (set_bootvar("BootOrder", (uint8_t*)new_data, size) < 0)
349 err(1, "Unabke to set BootOrder to %s", order);
354 handle_activity(int bootnum, bool active)
356 uint32_t attrs, load_attrs;
361 asprintf(&name, "%s%04X", "Boot", bootnum);
364 if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, &attrs) < 0)
365 err(1, "No such bootvar %s\n", name);
367 load_attrs = le32dec(data);
370 load_attrs |= LOAD_OPTION_ACTIVE;
372 load_attrs &= ~LOAD_OPTION_ACTIVE;
374 le32enc(data, load_attrs);
376 if (set_bootvar(name, data, size) < 0)
377 err(1, "handle activity efi_set_variable");
382 * add boot var to boot order.
383 * called by create boot var. There is no option
384 * to add one independent of create.
386 * Note: we currently don't support where it goes
387 * so it goes on the front, inactive.
388 * use -o 2,3,7 etc to affect order, -a to activate.
391 add_to_boot_order(char *bootvar)
398 val = strtoul(&bootvar[4], NULL, 16);
400 if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0) {
401 if (errno == ENOENT) { /* create it and set this bootvar to active */
405 err(1, "efi_get_variable BootOrder");
409 * We have BootOrder with the current order
410 * so grow the array by one, add the value
411 * and write the new variable value.
413 size += sizeof(uint16_t);
419 if (size > sizeof(uint16_t))
420 memcpy(new + sizeof(uint16_t), data, size - sizeof(uint16_t));
422 if (set_bootvar("BootOrder", new, size) < 0)
423 err(1, "set_bootvar");
429 remove_from_order(uint16_t bootnum)
435 if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0)
442 for (j = i = 0; i < size; i += sizeof(uint16_t)) {
443 if (le16dec(data + i) == bootnum)
445 memcpy(new + j, data + i, sizeof(uint16_t));
446 j += sizeof(uint16_t);
449 warnx("Boot variable %04x not in BootOrder", bootnum);
450 else if (set_bootvar("BootOrder", new, j) < 0)
451 err(1, "Unable to update BootOrder with new value");
457 delete_bootvar(int bootnum)
463 * Try to delete the boot variable and remocve it
464 * from the boot order. We always do both actions
465 * to make it easy to clean up from oopses.
467 if (bootnum < 0 || bootnum > 0xffff)
468 errx(1, "Bad boot variable %#x", bootnum);
469 asprintf(&name, "%s%04X", "Boot", bootnum);
472 printf("Removing boot variable '%s'\n", name);
473 if (efi_del_variable(EFI_GLOBAL_GUID, name) < 0) {
475 warn("cannot delete variable %s", name);
477 printf("Removing 0x%x from BootOrder\n", bootnum);
478 remove_from_order(bootnum);
489 if (efi_del_variable(EFI_GLOBAL_GUID, "BootNext") < 0)
490 err(1, "efi_del_variable");
494 handle_bootnext(uint16_t bootnum)
498 le16enc(&num, bootnum);
499 if (set_bootvar("BootNext", (uint8_t*)&bootnum, sizeof(uint16_t)) < 0)
500 err(1, "set_bootvar");
505 compare(const void *a, const void *b)
510 memcpy(&c, a, sizeof(uint16_t));
511 memcpy(&d, b, sizeof(uint16_t));
521 make_next_boot_var_name(void)
524 uint16_t *vals, next_free = 0;
529 LIST_FOREACH(v, &efivars, entries) {
533 vals = malloc(sizeof(uint16_t) * cnt);
538 LIST_FOREACH(v, &efivars, entries) {
541 qsort(vals, cnt, sizeof(uint16_t), compare);
542 /* if the hole is at the beginning, just return zero */
546 /* now just run the list looking for the first hole */
547 for (i = 0; i < cnt - 1 && next_free == 0; i++)
548 if (vals[i] + 1 != vals[i + 1])
549 next_free = vals[i] + 1;
551 next_free = vals[cnt - 1] + 1;
552 /* In theory we could have used all 65k slots -- what to do? */
556 asprintf(&name, "%s%04X", "Boot", next_free);
564 create_loadopt(uint8_t *buf, size_t bufmax, uint32_t attributes, efidp dp, size_t dp_size,
565 const char *description, const uint8_t *optional_data, size_t optional_data_size)
567 efi_char *bbuf = NULL;
572 if (optional_data == NULL && optional_data_size != 0)
574 if (dp == NULL && dp_size != 0)
578 * Compute the length to make sure the passed in buffer is long enough.
580 utf8_to_ucs2(description, &bbuf, &desc_len);
581 len = sizeof(uint32_t) + sizeof(uint16_t) + desc_len + dp_size + optional_data_size;
587 le32enc(pos, attributes);
588 pos += sizeof (attributes);
590 le16enc(pos, dp_size);
591 pos += sizeof (uint16_t);
593 memcpy(pos, bbuf, desc_len); /* NB:desc_len includes strailing NUL */
597 memcpy(pos, dp, dp_size);
600 if (optional_data && optional_data_size > 0) {
601 memcpy(pos, optional_data, optional_data_size);
602 pos += optional_data_size;
610 make_boot_var(const char *label, const char *loader, const char *kernel, const char *env, bool dry_run)
612 struct entry *new_ent;
613 uint32_t load_attrs = 0;
614 uint8_t *load_opt_buf;
615 size_t lopt_size, llen, klen;
616 efidp dp, loaderdp, kerneldp;
617 char *bootvar = NULL;
620 assert(label != NULL);
622 bootvar = make_next_boot_var_name();
624 err(1, "bootvar creation");
626 errx(1, "Must specify boot loader");
627 if (efivar_unix_path_to_device_path(loader, &loaderdp) != 0)
628 err(1, "Cannot translate unix loader path '%s' to UEFI", loader);
629 if (kernel != NULL) {
630 if (efivar_unix_path_to_device_path(kernel, &kerneldp) != 0)
631 err(1, "Cannot translate unix kernel path '%s' to UEFI", kernel);
635 llen = efidp_size(loaderdp);
636 if (llen > MAX_DP_LEN)
637 errx(1, "Loader path too long.");
638 klen = efidp_size(kerneldp);
639 if (klen > MAX_DP_LEN)
640 errx(1, "Kernel path too long.");
641 dp = malloc(llen + klen);
643 errx(1, "Can't allocate memory for new device paths");
644 memcpy(dp, loaderdp, llen);
645 if (kerneldp != NULL)
646 memcpy((char *)dp + llen, kerneldp, klen);
648 /* don't make the new bootvar active by default, use the -a option later */
649 load_attrs = LOAD_OPTION_CATEGORY_BOOT;
650 load_opt_buf = malloc(MAX_LOADOPT_LEN);
651 if (load_opt_buf == NULL)
654 lopt_size = create_loadopt(load_opt_buf, MAX_LOADOPT_LEN, load_attrs,
655 dp, llen + klen, label, env, env ? strlen(env) + 1 : 0);
656 if (lopt_size == BAD_LENGTH)
657 errx(1, "Can't crate loadopt");
661 ret = efi_set_variable(EFI_GLOBAL_GUID, bootvar,
662 (uint8_t*)load_opt_buf, lopt_size, COMMON_ATTRS);
666 err(1, "efi_set_variable");
668 add_to_boot_order(bootvar); /* first, still not active */
669 new_ent = malloc(sizeof(struct entry));
672 memset(new_ent, 0, sizeof(struct entry));
673 new_ent->name = bootvar;
674 new_ent->guid = EFI_GLOBAL_GUID;
675 LIST_INSERT_HEAD(&efivars, new_ent, entries);
684 print_loadopt_str(uint8_t *data, size_t datalen)
686 char *dev, *relpath, *abspath;
690 uint8_t *ep = data + datalen;
691 uint8_t *walker = data;
698 if (datalen < sizeof(attr) + sizeof(fplen) + sizeof(efi_char))
700 // First 4 bytes are attribute flags
701 attr = le32dec(walker);
702 walker += sizeof(attr);
703 // Next two bytes are length of the file paths
704 fplen = le16dec(walker);
705 walker += sizeof(fplen);
706 // Next we have a 0 terminated UCS2 string that we know to be aligned
707 descr = (efi_char *)(intptr_t)(void *)walker;
708 len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
709 walker += (len + 1) * sizeof(efi_char);
712 // Now we have fplen bytes worth of file path stuff
719 * Everything left is the binary option args
721 * optlen = ep - walker;
725 efidp_format_device_path(buf, sizeof(buf), dp,
726 (intptr_t)(void *)edp - (intptr_t)(void *)dp);
727 printf("%*s%s\n", indent, "", buf);
728 indent = 10 + len + 1;
729 rv = efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath);
731 printf("%*s%s:%s %s\n", indent + 4, "", dev, relpath, abspath);
736 dp = (efidp)((char *)dp + efidp_size(dp));
741 get_descr(uint8_t *data)
749 pos += sizeof(uint32_t) + sizeof(uint16_t);
750 desc = (efi_char*)(intptr_t)(void *)pos;
752 buf = malloc(len + 1);
753 memset(buf, 0, len + 1);
763 print_boot_var(const char *name, bool verbose, bool curboot)
771 ret = efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL);
774 load_attrs = le32dec(data);
776 printf("%c%s%c %s", curboot ? '+' : ' ', name,
777 ((load_attrs & LOAD_OPTION_ACTIVE) ? '*': ' '), d);
780 print_loadopt_str(data, size);
787 /* Cmd epilogue, or just the default with no args.
788 * The order is [bootnext] bootcurrent, timeout, order, and the bootvars [-v]
791 print_boot_vars(bool verbose)
794 * just read and print the current values
795 * as a command epilogue
802 uint16_t *boot_order = NULL, current;
804 ret = efi_get_variable(EFI_GLOBAL_GUID, "BootNext", &data, &size, &attrs);
806 printf("BootNext : %04x\n", le16dec(data));
809 ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
810 current = le16dec(data);
811 printf("BootCurrent: %04x\n", current);
813 ret = efi_get_variable(EFI_GLOBAL_GUID, "Timeout", &data, &size, &attrs);
815 printf("Timeout : %d seconds\n", le16dec(data));
818 if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) > 0) {
820 warn("Bad BootOrder variable: odd length %d", (int)size);
821 boot_order = malloc(size);
823 printf("BootOrder : ");
824 for (size_t i = 0; i < size; i += 2) {
825 boot_order[i / 2] = le16dec(data + i);
826 printf("%04X%s", boot_order[i / 2], i == size - 2 ? "\n" : ", ");
830 if (boot_order == NULL) {
832 * now we want to fetch 'em all fresh again
833 * which possibly includes a newly created bootvar
835 LIST_FOREACH(v, &efivars, entries) {
836 print_boot_var(v->name, verbose, v->idx == current);
839 LIST_FOREACH(v, &efivars, entries) {
842 for (int i = 0; i < bolen; i++) {
845 snprintf(buffer, sizeof(buffer), "Boot%04X", boot_order[i]);
846 if (!print_boot_var(buffer, verbose, boot_order[i] == current))
847 printf("%s: MISSING!\n", buffer);
848 LIST_FOREACH(v, &efivars, entries) {
849 if (v->idx == boot_order[i]) {
856 printf("\n\nUnreferenced Variables:\n");
857 LIST_FOREACH(v, &efivars, entries) {
859 print_boot_var(v->name, verbose, v->idx == current);
870 efi_del_variable(EFI_GLOBAL_GUID,"Timeout");
874 handle_timeout(int to)
878 le16enc(&timeout, to);
879 if (set_bootvar("Timeout", (uint8_t *)&timeout, sizeof(timeout)) < 0)
880 errx(1, "Can't set Timeout for booting.");
884 main(int argc, char *argv[])
887 if (!efi_variables_supported())
888 errx(1, "efi variables not supported on this system. root? kldload efirt?");
890 memset(&opts, 0, sizeof (bmgr_opts_t));
891 parse_args(argc, argv);
896 * side effect, adds to boot order, but not yet active.
898 make_boot_var(opts.label ? opts.label : "",
899 opts.loader, opts.kernel, opts.env, opts.dry_run);
900 else if (opts.set_active || opts.set_inactive )
901 handle_activity(opts.bootnum, opts.set_active);
902 else if (opts.order != NULL)
903 set_boot_order(opts.order); /* create a new bootorder with opts.order */
904 else if (opts.set_bootnext)
905 handle_bootnext(opts.bootnum);
906 else if (opts.delete_bootnext)
908 else if (opts.delete)
909 delete_bootvar(opts.bootnum);
910 else if (opts.del_timeout)
912 else if (opts.set_timeout)
913 handle_timeout(opts.timeout);
915 print_boot_vars(opts.verbose);