2 * Copyright (c) 2017-2018 Netflix, Inc.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer
9 * in this position and unchanged.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
31 #include <sys/param.h>
51 #include <geom/geom.h>
52 #include <geom/geom_ctl.h>
53 #include <geom/geom_int.h>
58 #include <efivar-dp.h>
60 #ifndef LOAD_OPTION_ACTIVE
61 #define LOAD_OPTION_ACTIVE 0x00000001
64 #ifndef LOAD_OPTION_CATEGORY_BOOT
65 #define LOAD_OPTION_CATEGORY_BOOT 0x00000000
68 #define BAD_LENGTH ((size_t)-1)
70 typedef struct _bmgr_opts {
98 static struct option lopts[] = {
99 {"activate", no_argument, NULL, 'a'},
100 {"bootnext", no_argument, NULL, 'n'}, /* set bootnext */
101 {"bootnum", required_argument, NULL, 'b'},
102 {"bootorder", required_argument, NULL, 'o'}, /* set order */
103 {"copy", required_argument, NULL, 'C'}, /* Copy boot method */
104 {"create", no_argument, NULL, 'c'},
105 {"deactivate", no_argument, NULL, 'A'},
106 {"del-timout", no_argument, NULL, 'T'},
107 {"delete", no_argument, NULL, 'B'},
108 {"delete-bootnext", no_argument, NULL, 'N'},
109 {"device-path", no_argument, NULL, 'd'},
110 {"dry-run", no_argument, NULL, 'D'},
111 {"env", required_argument, NULL, 'e'},
112 {"esp", no_argument, NULL, 'E'},
113 {"help", no_argument, NULL, 'h'},
114 {"kernel", required_argument, NULL, 'k'},
115 {"label", required_argument, NULL, 'L'},
116 {"loader", required_argument, NULL, 'l'},
117 {"once", no_argument, NULL, 'O'},
118 {"set-timeout", required_argument, NULL, 't'},
119 {"unix-path", no_argument, NULL, 'p'},
120 {"verbose", no_argument, NULL, 'v'},
124 /* global efibootmgr opts */
125 static bmgr_opts_t opts;
127 static LIST_HEAD(efivars_head, entry) efivars =
128 LIST_HEAD_INITIALIZER(efivars);
141 LIST_ENTRY(entry) entries;
144 #define MAX_DP_LEN 4096
145 #define MAX_LOADOPT_LEN 8192
149 mangle_loader(char *loader)
153 for (c = loader; *c; c++)
161 #define COMMON_ATTRS EFI_VARIABLE_NON_VOLATILE | \
162 EFI_VARIABLE_BOOTSERVICE_ACCESS | \
163 EFI_VARIABLE_RUNTIME_ACCESS
166 * We use global guid, and common var attrs and
167 * find it better to just delete and re-create a var.
170 set_bootvar(const char *name, uint8_t *data, size_t size)
173 return efi_set_variable(EFI_GLOBAL_GUID, name, data, size,
179 " [-aAnB -b bootnum] [-N] [-t timeout] [-T] [-o bootorder] [-O] [--verbose] [--help]\n\
180 [-c -l loader [-k kernel] [-L label] [--dry-run] [-b bootnum]]"
182 #define CREATE_USAGE \
183 " efibootmgr -c -l loader [-k kernel] [-L label] [--dry-run] [-b bootnum] [-a]"
184 #define ORDER_USAGE \
185 " efibootmgr -o bootvarnum1,bootvarnum2,..."
186 #define TIMEOUT_USAGE \
187 " efibootmgr -t seconds"
188 #define DELETE_USAGE \
189 " efibootmgr -B -b bootnum"
190 #define ACTIVE_USAGE \
191 " efibootmgr [-a | -A] -b bootnum"
192 #define BOOTNEXT_USAGE \
193 " efibootmgr [-n | -N] -b bootnum"
196 parse_args(int argc, char *argv[])
200 while ((ch = getopt_long(argc, argv, "AaBb:C:cdDe:Ehk:L:l:NnOo:pTt:v",
201 lopts, NULL)) != -1) {
204 opts.set_inactive = true;
207 opts.set_active = true;
210 opts.has_bootnum = true;
211 opts.bootnum = strtoul(optarg, NULL, 16);
218 opts.cp_src = strtoul(optarg, NULL, 16);
222 case 'D': /* should be remove dups XXX */
226 opts.device_path = true;
230 opts.env = strdup(optarg);
233 opts.esp_device = true;
237 errx(1, "%s", USAGE);
241 opts.kernel = strdup(optarg);
245 opts.label = strdup(optarg);
249 opts.loader = strdup(optarg);
250 opts.loader = mangle_loader(opts.loader);
253 opts.delete_bootnext = true;
256 opts.set_bootnext = true;
263 opts.order = strdup(optarg);
266 opts.unix_path = true;
269 opts.del_timeout = true;
272 opts.set_timeout = true;
273 opts.timeout = strtoul(optarg, NULL, 10);
282 errx(1, "%s",CREATE_USAGE);
286 if (opts.order && !(opts.order))
287 errx(1, "%s", ORDER_USAGE);
289 if ((opts.set_inactive || opts.set_active) && !opts.has_bootnum)
290 errx(1, "%s", ACTIVE_USAGE);
292 if (opts.delete && !opts.has_bootnum)
293 errx(1, "%s", DELETE_USAGE);
295 if (opts.set_bootnext && !opts.has_bootnum)
296 errx(1, "%s", BOOTNEXT_USAGE);
305 char *next_name = NULL;
311 while ((ret = efi_get_next_variable_name(&guid, &next_name)) > 0) {
313 * Only pay attention to EFI:BootXXXX variables to get the list.
315 if (efi_guid_cmp(guid, &EFI_GLOBAL_GUID) != 0 ||
316 strlen(next_name) != 8 ||
317 strncmp(next_name, "Boot", 4) != 0 ||
318 !isxdigit(next_name[4]) ||
319 !isxdigit(next_name[5]) ||
320 !isxdigit(next_name[6]) ||
321 !isxdigit(next_name[7]))
323 nent = malloc(sizeof(struct entry));
324 nent->name = strdup(next_name);
326 ret = efi_get_variable(*guid, next_name, &nent->data,
327 &nent->size, &nent->attrs);
329 err(1, "efi_get_variable");
331 nent->idx = strtoul(&next_name[4], NULL, 16);
332 LIST_INSERT_HEAD(&efivars, nent, entries);
338 set_boot_order(char *order)
352 size = sizeof(uint16_t) * cnt;
353 new_data = malloc(size);
357 while ((next = strsep(&cp, ",")) != NULL) {
358 new_data[i] = strtoul(next, NULL, 16);
359 if (new_data[i] == 0 && errno == EINVAL) {
360 warnx("can't parse %s as a numb", next);
361 errx(1, "%s", ORDER_USAGE);
366 if (set_bootvar("BootOrder", (uint8_t*)new_data, size) < 0)
367 err(1, "Unabke to set BootOrder to %s", order);
372 handle_activity(int bootnum, bool active)
374 uint32_t attrs, load_attrs;
379 asprintf(&name, "%s%04X", "Boot", bootnum);
382 if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, &attrs) < 0)
383 err(1, "No such bootvar %s\n", name);
385 load_attrs = le32dec(data);
388 load_attrs |= LOAD_OPTION_ACTIVE;
390 load_attrs &= ~LOAD_OPTION_ACTIVE;
392 le32enc(data, load_attrs);
394 if (set_bootvar(name, data, size) < 0)
395 err(1, "handle activity efi_set_variable");
400 * add boot var to boot order.
401 * called by create boot var. There is no option
402 * to add one independent of create.
404 * Note: we currently don't support where it goes
405 * so it goes on the front, inactive.
406 * use -o 2,3,7 etc to affect order, -a to activate.
409 add_to_boot_order(char *bootvar)
416 val = strtoul(&bootvar[4], NULL, 16);
418 if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0) {
419 if (errno == ENOENT) { /* create it and set this bootvar to active */
423 err(1, "efi_get_variable BootOrder");
427 * We have BootOrder with the current order
428 * so grow the array by one, add the value
429 * and write the new variable value.
431 size += sizeof(uint16_t);
437 if (size > sizeof(uint16_t))
438 memcpy(new + sizeof(uint16_t), data, size - sizeof(uint16_t));
440 if (set_bootvar("BootOrder", new, size) < 0)
441 err(1, "set_bootvar");
447 remove_from_order(uint16_t bootnum)
453 if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0)
460 for (j = i = 0; i < size; i += sizeof(uint16_t)) {
461 if (le16dec(data + i) == bootnum)
463 memcpy(new + j, data + i, sizeof(uint16_t));
464 j += sizeof(uint16_t);
467 warnx("Boot variable %04x not in BootOrder", bootnum);
468 else if (set_bootvar("BootOrder", new, j) < 0)
469 err(1, "Unable to update BootOrder with new value");
475 delete_bootvar(int bootnum)
481 * Try to delete the boot variable and remocve it
482 * from the boot order. We always do both actions
483 * to make it easy to clean up from oopses.
485 if (bootnum < 0 || bootnum > 0xffff)
486 errx(1, "Bad boot variable %#x", bootnum);
487 asprintf(&name, "%s%04X", "Boot", bootnum);
490 printf("Removing boot variable '%s'\n", name);
491 if (efi_del_variable(EFI_GLOBAL_GUID, name) < 0) {
493 warn("cannot delete variable %s", name);
495 printf("Removing 0x%x from BootOrder\n", bootnum);
496 remove_from_order(bootnum);
507 if (efi_del_variable(EFI_GLOBAL_GUID, "BootNext") < 0)
508 err(1, "efi_del_variable");
512 handle_bootnext(uint16_t bootnum)
516 le16enc(&num, bootnum);
517 if (set_bootvar("BootNext", (uint8_t*)&bootnum, sizeof(uint16_t)) < 0)
518 err(1, "set_bootvar");
523 compare(const void *a, const void *b)
528 memcpy(&c, a, sizeof(uint16_t));
529 memcpy(&d, b, sizeof(uint16_t));
539 make_next_boot_var_name(void)
542 uint16_t *vals, next_free = 0;
547 LIST_FOREACH(v, &efivars, entries) {
551 vals = malloc(sizeof(uint16_t) * cnt);
556 LIST_FOREACH(v, &efivars, entries) {
559 qsort(vals, cnt, sizeof(uint16_t), compare);
560 /* if the hole is at the beginning, just return zero */
564 /* now just run the list looking for the first hole */
565 for (i = 0; i < cnt - 1 && next_free == 0; i++)
566 if (vals[i] + 1 != vals[i + 1])
567 next_free = vals[i] + 1;
569 next_free = vals[cnt - 1] + 1;
570 /* In theory we could have used all 65k slots -- what to do? */
574 asprintf(&name, "%s%04X", "Boot", next_free);
581 make_boot_var_name(uint16_t bootnum)
586 LIST_FOREACH(v, &efivars, entries) {
587 if (v->idx == bootnum)
591 asprintf(&name, "%s%04X", "Boot", bootnum);
598 create_loadopt(uint8_t *buf, size_t bufmax, uint32_t attributes, efidp dp, size_t dp_size,
599 const char *description, const uint8_t *optional_data, size_t optional_data_size)
601 efi_char *bbuf = NULL;
606 if (optional_data == NULL && optional_data_size != 0)
608 if (dp == NULL && dp_size != 0)
612 * Compute the length to make sure the passed in buffer is long enough.
614 utf8_to_ucs2(description, &bbuf, &desc_len);
615 len = sizeof(uint32_t) + sizeof(uint16_t) + desc_len + dp_size + optional_data_size;
621 le32enc(pos, attributes);
622 pos += sizeof (attributes);
624 le16enc(pos, dp_size);
625 pos += sizeof (uint16_t);
627 memcpy(pos, bbuf, desc_len); /* NB:desc_len includes strailing NUL */
631 memcpy(pos, dp, dp_size);
634 if (optional_data && optional_data_size > 0) {
635 memcpy(pos, optional_data, optional_data_size);
636 pos += optional_data_size;
644 make_boot_var(const char *label, const char *loader, const char *kernel, const char *env, bool dry_run,
645 int bootnum, bool activate)
647 struct entry *new_ent;
648 uint32_t load_attrs = 0;
649 uint8_t *load_opt_buf;
650 size_t lopt_size, llen, klen;
651 efidp dp, loaderdp, kerneldp;
652 char *bootvar = NULL;
655 assert(label != NULL);
658 bootvar = make_next_boot_var_name();
660 bootvar = make_boot_var_name((uint16_t)bootnum);
662 err(1, "bootvar creation");
664 errx(1, "Must specify boot loader");
665 if (efivar_unix_path_to_device_path(loader, &loaderdp) != 0)
666 err(1, "Cannot translate unix loader path '%s' to UEFI", loader);
667 if (kernel != NULL) {
668 if (efivar_unix_path_to_device_path(kernel, &kerneldp) != 0)
669 err(1, "Cannot translate unix kernel path '%s' to UEFI", kernel);
673 llen = efidp_size(loaderdp);
674 if (llen > MAX_DP_LEN)
675 errx(1, "Loader path too long.");
676 klen = efidp_size(kerneldp);
677 if (klen > MAX_DP_LEN)
678 errx(1, "Kernel path too long.");
679 dp = malloc(llen + klen);
681 errx(1, "Can't allocate memory for new device paths");
682 memcpy(dp, loaderdp, llen);
683 if (kerneldp != NULL)
684 memcpy((char *)dp + llen, kerneldp, klen);
686 /* don't make the new bootvar active by default, use the -a option later */
687 load_attrs = LOAD_OPTION_CATEGORY_BOOT;
689 load_attrs |= LOAD_OPTION_ACTIVE;
690 load_opt_buf = malloc(MAX_LOADOPT_LEN);
691 if (load_opt_buf == NULL)
694 lopt_size = create_loadopt(load_opt_buf, MAX_LOADOPT_LEN, load_attrs,
695 dp, llen + klen, label, env, env ? strlen(env) + 1 : 0);
696 if (lopt_size == BAD_LENGTH)
697 errx(1, "Can't create loadopt");
701 ret = efi_set_variable(EFI_GLOBAL_GUID, bootvar,
702 (uint8_t*)load_opt_buf, lopt_size, COMMON_ATTRS);
706 err(1, "efi_set_variable");
709 add_to_boot_order(bootvar); /* first, still not active */
710 new_ent = malloc(sizeof(struct entry));
713 memset(new_ent, 0, sizeof(struct entry));
714 new_ent->name = bootvar;
715 new_ent->guid = EFI_GLOBAL_GUID;
716 LIST_INSERT_HEAD(&efivars, new_ent, entries);
725 print_loadopt_str(uint8_t *data, size_t datalen)
727 char *dev, *relpath, *abspath;
731 uint8_t *ep = data + datalen;
732 uint8_t *walker = data;
739 if (datalen < sizeof(attr) + sizeof(fplen) + sizeof(efi_char))
741 // First 4 bytes are attribute flags
742 attr = le32dec(walker);
743 walker += sizeof(attr);
744 // Next two bytes are length of the file paths
745 fplen = le16dec(walker);
746 walker += sizeof(fplen);
747 // Next we have a 0 terminated UCS2 string that we know to be aligned
748 descr = (efi_char *)(intptr_t)(void *)walker;
749 len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
750 walker += (len + 1) * sizeof(efi_char);
753 // Now we have fplen bytes worth of file path stuff
760 * Everything left is the binary option args
762 * optlen = ep - walker;
766 efidp_format_device_path(buf, sizeof(buf), dp,
767 (intptr_t)(void *)edp - (intptr_t)(void *)dp);
768 printf("%*s%s\n", indent, "", buf);
769 indent = 10 + len + 1;
770 rv = efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath);
772 printf("%*s%s:%s %s\n", indent + 4, "", dev, relpath, abspath);
777 dp = (efidp)((char *)dp + efidp_size(dp));
782 get_descr(uint8_t *data)
790 pos += sizeof(uint32_t) + sizeof(uint16_t);
791 desc = (efi_char*)(intptr_t)(void *)pos;
793 buf = malloc(len + 1);
794 memset(buf, 0, len + 1);
804 print_boot_var(const char *name, bool verbose, bool curboot)
812 ret = efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL);
815 load_attrs = le32dec(data);
817 printf("%c%s%c %s", curboot ? '+' : ' ', name,
818 ((load_attrs & LOAD_OPTION_ACTIVE) ? '*': ' '), d);
821 print_loadopt_str(data, size);
828 /* Cmd epilogue, or just the default with no args.
829 * The order is [bootnext] bootcurrent, timeout, order, and the bootvars [-v]
832 print_boot_vars(bool verbose)
835 * just read and print the current values
836 * as a command epilogue
843 uint16_t *boot_order = NULL, current;
845 ret = efi_get_variable(EFI_GLOBAL_GUID, "BootNext", &data, &size, &attrs);
847 printf("BootNext : %04x\n", le16dec(data));
850 ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
851 current = le16dec(data);
852 printf("BootCurrent: %04x\n", current);
854 ret = efi_get_variable(EFI_GLOBAL_GUID, "Timeout", &data, &size, &attrs);
856 printf("Timeout : %d seconds\n", le16dec(data));
859 if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) > 0) {
861 warn("Bad BootOrder variable: odd length %d", (int)size);
862 boot_order = malloc(size);
864 printf("BootOrder : ");
865 for (size_t i = 0; i < size; i += 2) {
866 boot_order[i / 2] = le16dec(data + i);
867 printf("%04X%s", boot_order[i / 2], i == size - 2 ? "\n" : ", ");
871 if (boot_order == NULL) {
873 * now we want to fetch 'em all fresh again
874 * which possibly includes a newly created bootvar
876 LIST_FOREACH(v, &efivars, entries) {
877 print_boot_var(v->name, verbose, v->idx == current);
880 LIST_FOREACH(v, &efivars, entries) {
883 for (int i = 0; i < bolen; i++) {
886 snprintf(buffer, sizeof(buffer), "Boot%04X", boot_order[i]);
887 if (!print_boot_var(buffer, verbose, boot_order[i] == current))
888 printf("%s: MISSING!\n", buffer);
889 LIST_FOREACH(v, &efivars, entries) {
890 if (v->idx == boot_order[i]) {
897 printf("\n\nUnreferenced Variables:\n");
898 LIST_FOREACH(v, &efivars, entries) {
900 print_boot_var(v->name, verbose, v->idx == current);
911 efi_del_variable(EFI_GLOBAL_GUID,"Timeout");
915 handle_timeout(int to)
919 le16enc(&timeout, to);
920 if (set_bootvar("Timeout", (uint8_t *)&timeout, sizeof(timeout)) < 0)
921 errx(1, "Can't set Timeout for booting.");
925 report_esp_device(bool do_dp, bool do_unix)
931 uint16_t current, fplen;
932 char *name, *dev, *relpath, *abspath;
933 uint8_t *walker, *ep;
938 if (do_dp && do_unix)
939 errx(1, "Can't report both UEFI device-path and Unix path together");
941 ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
943 err(1, "Can't get BootCurrent");
944 current = le16dec(data);
945 if (asprintf(&name, "Boot%04X", current) < 0)
946 err(1, "Can't format boot var\n");
947 if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL) < 0)
948 err(1, "Can't retrieve EFI var %s", name);
949 // First 4 bytes are attribute flags
952 walker += sizeof(uint32_t);
953 // Next two bytes are length of the file paths
954 fplen = le16dec(walker);
955 walker += sizeof(fplen);
956 // Next we have a 0 terminated UCS2 string that we know to be aligned
957 descr = (efi_char *)(intptr_t)(void *)walker;
958 len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
959 walker += (len + 1) * sizeof(efi_char);
961 errx(1, "malformed boot variable %s", name);
962 // Now we have fplen bytes worth of file path stuff
967 errx(1, "malformed boot variable %s", name);
969 efidp_format_device_path_node(buf, sizeof(buf), dp);
973 if (efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath) < 0)
974 errx(1, "Can't convert to unix path");
977 errx(1, "Can't find where %s:%s is mounted",
979 abspath[strlen(abspath) - strlen(relpath) - 1] = '\0';
980 printf("%s\n", abspath);
991 main(int argc, char *argv[])
994 if (!efi_variables_supported())
995 errx(1, "efi variables not supported on this system. root? kldload efirt?");
997 memset(&opts, 0, sizeof (bmgr_opts_t));
998 parse_args(argc, argv);
1003 * side effect, adds to boot order, but not yet active.
1005 make_boot_var(opts.label ? opts.label : "",
1006 opts.loader, opts.kernel, opts.env, opts.dry_run,
1007 opts.has_bootnum ? opts.bootnum : -1, opts.set_active);
1008 else if (opts.set_active || opts.set_inactive )
1009 handle_activity(opts.bootnum, opts.set_active);
1010 else if (opts.order != NULL)
1011 set_boot_order(opts.order); /* create a new bootorder with opts.order */
1012 else if (opts.set_bootnext)
1013 handle_bootnext(opts.bootnum);
1014 else if (opts.delete_bootnext)
1016 else if (opts.delete)
1017 delete_bootvar(opts.bootnum);
1018 else if (opts.del_timeout)
1020 else if (opts.set_timeout)
1021 handle_timeout(opts.timeout);
1022 else if (opts.esp_device)
1023 report_esp_device(opts.device_path, opts.unix_path);
1025 print_boot_vars(opts.verbose);