xref: /freebsd/usr.sbin/efibootmgr/efibootmgr.c (revision 4d3fc8b0)
1 /*-
2  * Copyright (c) 2017-2018 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
13  *
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.
24  */
25 
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28 
29 #include <sys/stat.h>
30 #include <sys/vtoc.h>
31 #include <sys/param.h>
32 #include <assert.h>
33 #include <ctype.h>
34 #include <err.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <libgeom.h>
38 #include <paths.h>
39 #include <signal.h>
40 #include <stdint.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <getopt.h>
44 #include <limits.h>
45 #include <inttypes.h>
46 #include <stdbool.h>
47 #include <string.h>
48 #include <strings.h>
49 #include <unistd.h>
50 #include <libgeom.h>
51 #include <geom/geom.h>
52 #include <geom/geom_ctl.h>
53 #include <geom/geom_int.h>
54 
55 #include <efivar.h>
56 #include <efiutil.h>
57 #include <efichar.h>
58 #include <efivar-dp.h>
59 
60 #ifndef LOAD_OPTION_ACTIVE
61 #define LOAD_OPTION_ACTIVE 0x00000001
62 #endif
63 
64 #ifndef LOAD_OPTION_CATEGORY_BOOT
65 #define LOAD_OPTION_CATEGORY_BOOT 0x00000000
66 #endif
67 
68 #define BAD_LENGTH	((size_t)-1)
69 
70 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001
71 
72 typedef struct _bmgr_opts {
73 	char	*dev;
74 	char	*env;
75 	char	*loader;
76 	char	*label;
77 	char	*kernel;
78 	char	*name;
79 	char	*order;
80 	int     bootnum;
81 	bool	copy;
82 	bool    create;
83 	bool    delete;
84 	bool    delete_bootnext;
85 	bool    del_timeout;
86 	bool    dry_run;
87 	bool	device_path;
88 	bool	esp_device;
89 	bool	find_dev;
90 	bool    fw_ui;
91 	bool    no_fw_ui;
92 	bool	has_bootnum;
93 	bool    once;
94 	int	cp_src;
95 	bool    set_active;
96 	bool    set_bootnext;
97 	bool    set_inactive;
98 	bool    set_timeout;
99 	int     timeout;
100 	bool	unix_path;
101 	bool    verbose;
102 } bmgr_opts_t;
103 
104 static struct option lopts[] = {
105 	{"activate", no_argument, NULL, 'a'},
106 	{"bootnext", no_argument, NULL, 'n'}, /* set bootnext */
107 	{"bootnum", required_argument, NULL, 'b'},
108 	{"bootorder", required_argument, NULL, 'o'}, /* set order */
109 	{"copy", required_argument, NULL, 'C'},		/* Copy boot method */
110 	{"create", no_argument, NULL, 'c'},
111 	{"deactivate", no_argument, NULL, 'A'},
112 	{"del-timeout", no_argument, NULL, 'T'},
113 	{"delete", no_argument, NULL, 'B'},
114 	{"delete-bootnext", no_argument, NULL, 'N'},
115 	{"device-path", no_argument, NULL, 'd'},
116 	{"dry-run", no_argument, NULL, 'D'},
117 	{"env", required_argument, NULL, 'e'},
118 	{"esp", no_argument, NULL, 'E'},
119 	{"efidev", required_argument, NULL, 'u'},
120 	{"fw-ui", no_argument, NULL, 'f'},
121 	{"no-fw-ui", no_argument, NULL, 'F'},
122 	{"help", no_argument, NULL, 'h'},
123 	{"kernel", required_argument, NULL, 'k'},
124 	{"label", required_argument, NULL, 'L'},
125 	{"loader", required_argument, NULL, 'l'},
126 	{"once", no_argument, NULL, 'O'},
127 	{"set-timeout", required_argument, NULL, 't'},
128 	{"unix-path", no_argument, NULL, 'p'},
129 	{"verbose", no_argument, NULL, 'v'},
130 	{ NULL, 0, NULL, 0}
131 };
132 
133 /* global efibootmgr opts */
134 static bmgr_opts_t opts;
135 
136 static LIST_HEAD(efivars_head, entry) efivars =
137 	LIST_HEAD_INITIALIZER(efivars);
138 
139 struct entry {
140 	efi_guid_t	guid;
141 	uint32_t	attrs;
142 	uint8_t		*data;
143 	size_t		size;
144 	char		*name;
145 	char		*label;
146 	int		idx;
147 	int		flags;
148 #define SEEN	1
149 
150 	LIST_ENTRY(entry) entries;
151 };
152 
153 #define MAX_DP_LEN	4096
154 #define MAX_LOADOPT_LEN	8192
155 
156 
157 static char *
158 mangle_loader(char *loader)
159 {
160 	char *c;
161 
162 	for (c = loader; *c; c++)
163 		if (*c == '/')
164 			*c = '\\';
165 
166 	return loader;
167 }
168 
169 
170 #define COMMON_ATTRS EFI_VARIABLE_NON_VOLATILE | \
171 	EFI_VARIABLE_BOOTSERVICE_ACCESS | \
172 	EFI_VARIABLE_RUNTIME_ACCESS
173 
174 /*
175  * We use global guid, and common var attrs and
176  * find it better to just delete and re-create a var.
177  */
178 static int
179 set_bootvar(const char *name, uint8_t *data, size_t size)
180 {
181 
182 	return efi_set_variable(EFI_GLOBAL_GUID, name, data, size,
183 	    COMMON_ATTRS);
184 }
185 
186 
187 #define USAGE \
188 	"   [-aAnB -b bootnum] [-N] [-t timeout] [-T] [-o bootorder] [-O] [--verbose] [--help]\n\
189   [-c -l loader [-k kernel] [-L label] [--dry-run] [-b bootnum]]"
190 
191 #define CREATE_USAGE \
192 	"       efibootmgr -c -l loader [-k kernel] [-L label] [--dry-run] [-b bootnum] [-a]"
193 #define ORDER_USAGE \
194 	"       efibootmgr -o bootvarnum1,bootvarnum2,..."
195 #define TIMEOUT_USAGE \
196 	"       efibootmgr -t seconds"
197 #define DELETE_USAGE \
198 	"       efibootmgr -B -b bootnum"
199 #define ACTIVE_USAGE \
200 	"       efibootmgr [-a | -A] -b bootnum"
201 #define BOOTNEXT_USAGE \
202 	"       efibootmgr [-n | -N] -b bootnum"
203 
204 static void
205 parse_args(int argc, char *argv[])
206 {
207 	int ch;
208 
209 	while ((ch = getopt_long(argc, argv, "AaBb:C:cdDe:EFfhk:L:l:NnOo:pTt:v",
210 		    lopts, NULL)) != -1) {
211 		switch (ch) {
212 		case 'A':
213 			opts.set_inactive = true;
214 			break;
215 		case 'a':
216 			opts.set_active = true;
217 			break;
218 		case 'b':
219 			opts.has_bootnum = true;
220 			opts.bootnum = strtoul(optarg, NULL, 16);
221 			break;
222 		case 'B':
223 			opts.delete = true;
224 			break;
225 		case 'C':
226 			opts.copy = true;
227 			opts.cp_src = strtoul(optarg, NULL, 16);
228 		case 'c':
229 			opts.create = true;
230 			break;
231 		case 'D': /* should be remove dups XXX */
232 			opts.dry_run = true;
233 			break;
234 		case 'd':
235 			opts.device_path = true;
236 			break;
237 		case 'e':
238 			free(opts.env);
239 			opts.env = strdup(optarg);
240 			break;
241 		case 'E':
242 			opts.esp_device = true;
243 			break;
244 		case 'F':
245 			opts.no_fw_ui = true;
246 			break;
247 		case 'f':
248 			opts.fw_ui = true;
249 			break;
250 		case 'h':
251 		default:
252 			errx(1, "%s", USAGE);
253 			break;
254 		case 'k':
255 			free(opts.kernel);
256 			opts.kernel = strdup(optarg);
257 			break;
258 		case 'L':
259 			free(opts.label);
260 			opts.label = strdup(optarg);
261 			break;
262 		case 'l':
263 			free(opts.loader);
264 			opts.loader = strdup(optarg);
265 			opts.loader = mangle_loader(opts.loader);
266 			break;
267 		case 'N':
268 			opts.delete_bootnext = true;
269 			break;
270 		case 'n':
271 			opts.set_bootnext = true;
272 			break;
273 		case 'O':
274 			opts.once = true;
275 			break;
276 		case 'o':
277 			free(opts.order);
278 			opts.order = strdup(optarg);
279 			break;
280 		case 'p':
281 			opts.unix_path = true;
282 			break;
283 		case 'T':
284 			opts.del_timeout = true;
285 			break;
286 		case 't':
287 			opts.set_timeout = true;
288 			opts.timeout = strtoul(optarg, NULL, 10);
289 			break;
290 		case 'u':
291 			opts.find_dev = true;
292 			opts.dev = strdup(optarg);
293 			break;
294 		case 'v':
295 			opts.verbose = true;
296 			break;
297 		}
298 	}
299 	if (opts.create) {
300 		if (!opts.loader)
301 			errx(1, "%s",CREATE_USAGE);
302 		return;
303 	}
304 
305 	if (opts.order != NULL && *opts.order == '\0')
306 		errx(1, "%s", ORDER_USAGE);
307 
308 	if ((opts.set_inactive || opts.set_active) && !opts.has_bootnum)
309 		errx(1, "%s", ACTIVE_USAGE);
310 
311 	if (opts.delete && !opts.has_bootnum)
312 		errx(1, "%s", DELETE_USAGE);
313 
314 	if (opts.set_bootnext && !opts.has_bootnum)
315 		errx(1, "%s", BOOTNEXT_USAGE);
316 }
317 
318 
319 static void
320 read_vars(void)
321 {
322 
323 	efi_guid_t *guid;
324 	char *next_name = NULL;
325 	int ret = 0;
326 
327 	struct entry *nent;
328 
329 	LIST_INIT(&efivars);
330 	while ((ret = efi_get_next_variable_name(&guid, &next_name)) > 0) {
331 		/*
332 		 * Only pay attention to EFI:BootXXXX variables to get the list.
333 		 */
334 		if (efi_guid_cmp(guid, &EFI_GLOBAL_GUID) != 0 ||
335 		    strlen(next_name) != 8 ||
336 		    strncmp(next_name, "Boot", 4) != 0 ||
337 		    !isxdigit(next_name[4]) ||
338 		    !isxdigit(next_name[5]) ||
339 		    !isxdigit(next_name[6]) ||
340 		    !isxdigit(next_name[7]))
341 			continue;
342 		nent = malloc(sizeof(struct entry));
343 		nent->name = strdup(next_name);
344 
345 		ret = efi_get_variable(*guid, next_name, &nent->data,
346 		    &nent->size, &nent->attrs);
347 		if (ret < 0)
348 			err(1, "efi_get_variable");
349 		nent->guid = *guid;
350 		nent->idx = strtoul(&next_name[4], NULL, 16);
351 		LIST_INSERT_HEAD(&efivars, nent, entries);
352 	}
353 }
354 
355 
356 static void
357 set_boot_order(char *order)
358 {
359 	uint16_t *new_data;
360 	size_t size;
361 	char *next, *cp;
362 	int cnt;
363 	int i;
364 
365 	cp = order;
366 	cnt = 1;
367 	while (*cp) {
368 		if (*cp++ == ',')
369 			cnt++;
370 	}
371 	size = sizeof(uint16_t) * cnt;
372 	new_data = malloc(size);
373 
374 	i = 0;
375 	cp = strdup(order);
376 	while ((next = strsep(&cp, ",")) != NULL) {
377 		new_data[i] = strtoul(next, NULL, 16);
378 		if (new_data[i] == 0 && errno == EINVAL) {
379 			warnx("can't parse %s as a numb", next);
380 			errx(1, "%s", ORDER_USAGE);
381 		}
382 		i++;
383 	}
384 	free(cp);
385 	if (set_bootvar("BootOrder", (uint8_t*)new_data, size) < 0)
386 		err(1, "Unabke to set BootOrder to %s", order);
387 	free(new_data);
388 }
389 
390 static void
391 handle_activity(int bootnum, bool active)
392 {
393 	uint32_t attrs, load_attrs;
394 	uint8_t *data;
395 	size_t size;
396 	char *name;
397 
398 	asprintf(&name, "%s%04X", "Boot", bootnum);
399 	if (name == NULL)
400 		err(1, "asprintf");
401 	if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, &attrs) < 0)
402 		err(1, "No such bootvar %s\n", name);
403 
404 	load_attrs = le32dec(data);
405 
406 	if (active)
407 		load_attrs |= LOAD_OPTION_ACTIVE;
408 	else
409 		load_attrs &= ~LOAD_OPTION_ACTIVE;
410 
411 	le32enc(data, load_attrs);
412 
413 	if (set_bootvar(name, data, size) < 0)
414 		err(1, "handle activity efi_set_variable");
415 }
416 
417 
418 /*
419  * add boot var to boot order.
420  * called by create boot var. There is no option
421  * to add one independent of create.
422  *
423  * Note: we currently don't support where it goes
424  * so it goes on the front, inactive.
425  * use -o 2,3,7 etc to affect order, -a to activate.
426  */
427 static void
428 add_to_boot_order(char *bootvar)
429 {
430 	size_t size;
431 	uint32_t attrs;
432 	uint16_t val;
433 	uint8_t *data, *new;
434 
435 	val = strtoul(&bootvar[4], NULL, 16);
436 
437 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0) {
438 		if (errno == ENOENT) { /* create it and set this bootvar to active */
439 			size = 0;
440 			data = NULL;
441 		} else
442 			err(1, "efi_get_variable BootOrder");
443 	}
444 
445 	/*
446 	 * We have BootOrder with the current order
447 	 * so grow the array by one, add the value
448 	 * and write the new variable value.
449 	 */
450 	size += sizeof(uint16_t);
451 	new = malloc(size);
452 	if (!new)
453 		err(1, "malloc");
454 
455 	le16enc(new, val);
456 	if (size > sizeof(uint16_t))
457 		memcpy(new + sizeof(uint16_t), data, size - sizeof(uint16_t));
458 
459 	if (set_bootvar("BootOrder", new, size) < 0)
460 		err(1, "set_bootvar");
461 	free(new);
462 }
463 
464 
465 static void
466 remove_from_order(uint16_t bootnum)
467 {
468 	uint32_t attrs;
469 	size_t size, i, j;
470 	uint8_t *new, *data;
471 
472 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0)
473 		return;
474 
475 	new = malloc(size);
476 	if (new == NULL)
477 		err(1, "malloc");
478 
479 	for (j = i = 0; i < size; i += sizeof(uint16_t)) {
480 		if (le16dec(data + i) == bootnum)
481 			continue;
482 		memcpy(new + j, data + i, sizeof(uint16_t));
483 		j += sizeof(uint16_t);
484 	}
485 	if (i == j)
486 		warnx("Boot variable %04x not in BootOrder", bootnum);
487 	else if (set_bootvar("BootOrder", new, j) < 0)
488 		err(1, "Unable to update BootOrder with new value");
489 	free(new);
490 }
491 
492 
493 static void
494 delete_bootvar(int bootnum)
495 {
496 	char *name;
497 	int defer = 0;
498 
499 	/*
500 	 * Try to delete the boot variable and remocve it
501 	 * from the boot order. We always do both actions
502 	 * to make it easy to clean up from oopses.
503 	 */
504 	if (bootnum < 0 || bootnum > 0xffff)
505 		errx(1, "Bad boot variable %#x", bootnum);
506 	asprintf(&name, "%s%04X", "Boot", bootnum);
507 	if (name == NULL)
508 		err(1, "asprintf");
509 	printf("Removing boot variable '%s'\n", name);
510 	if (efi_del_variable(EFI_GLOBAL_GUID, name) < 0) {
511 		defer = 1;
512 		warn("cannot delete variable %s", name);
513 	}
514 	printf("Removing 0x%x from BootOrder\n", bootnum);
515 	remove_from_order(bootnum);
516 	free(name);
517 	if (defer)
518 		exit(defer);
519 }
520 
521 
522 static void
523 del_bootnext(void)
524 {
525 
526 	if (efi_del_variable(EFI_GLOBAL_GUID, "BootNext") < 0)
527 		err(1, "efi_del_variable");
528 }
529 
530 static void
531 handle_bootnext(uint16_t bootnum)
532 {
533 	uint16_t num;
534 
535 	le16enc(&num, bootnum);
536 	if (set_bootvar("BootNext", (uint8_t*)&bootnum, sizeof(uint16_t)) < 0)
537 		err(1, "set_bootvar");
538 }
539 
540 
541 static int
542 compare(const void *a, const void *b)
543 {
544 	uint16_t c;
545 	uint16_t d;
546 
547 	memcpy(&c, a, sizeof(uint16_t));
548 	memcpy(&d, b, sizeof(uint16_t));
549 
550 	if (c < d)
551 		return -1;
552 	if (c == d)
553 		return  0;
554 	return  1;
555 }
556 
557 static char *
558 make_next_boot_var_name(void)
559 {
560 	struct entry *v;
561 	uint16_t *vals, next_free = 0;
562 	char *name;
563 	int cnt = 0;
564 	int i;
565 
566 	LIST_FOREACH(v, &efivars, entries) {
567 		cnt++;
568 	}
569 
570 	vals = malloc(sizeof(uint16_t) * cnt);
571 	if (!vals)
572 		return NULL;
573 
574 	i = 0;
575 	LIST_FOREACH(v, &efivars, entries) {
576 		vals[i++] = v->idx;
577 	}
578 	qsort(vals, cnt, sizeof(uint16_t), compare);
579 	/* if the hole is at the beginning, just return zero */
580 	if (vals[0] > 0) {
581 		next_free = 0;
582 	} else {
583 		/* now just run the list looking for the first hole */
584 		for (i = 0; i < cnt - 1 && next_free == 0; i++)
585 			if (vals[i] + 1 != vals[i + 1])
586 				next_free = vals[i] + 1;
587 		if (next_free == 0)
588 			next_free = vals[cnt - 1] + 1;
589 		/* In theory we could have used all 65k slots -- what to do? */
590 	}
591 	free(vals);
592 
593 	asprintf(&name, "%s%04X", "Boot", next_free);
594 	if (name == NULL)
595 		err(1, "asprintf");
596 	return name;
597 }
598 
599 static char *
600 make_boot_var_name(uint16_t bootnum)
601 {
602 	struct entry *v;
603 	char *name;
604 
605 	LIST_FOREACH(v, &efivars, entries) {
606 		if (v->idx == bootnum)
607 			return NULL;
608 	}
609 
610 	asprintf(&name, "%s%04X", "Boot", bootnum);
611 	if (name == NULL)
612 		err(1, "asprintf");
613 	return name;
614 }
615 
616 static size_t
617 create_loadopt(uint8_t *buf, size_t bufmax, uint32_t attributes, efidp dp, size_t dp_size,
618     const char *description, const uint8_t *optional_data, size_t optional_data_size)
619 {
620 	efi_char *bbuf = NULL;
621 	uint8_t *pos = buf;
622 	size_t desc_len = 0;
623 	size_t len;
624 
625 	if (optional_data == NULL && optional_data_size != 0)
626 		return BAD_LENGTH;
627 	if (dp == NULL && dp_size != 0)
628 		return BAD_LENGTH;
629 
630 	/*
631 	 * Compute the length to make sure the passed in buffer is long enough.
632 	 */
633 	utf8_to_ucs2(description, &bbuf, &desc_len);
634 	len = sizeof(uint32_t) + sizeof(uint16_t) + desc_len + dp_size + optional_data_size;
635 	if (len > bufmax) {
636 		free(bbuf);
637 		return BAD_LENGTH;
638 	}
639 
640 	le32enc(pos, attributes);
641 	pos += sizeof (attributes);
642 
643 	le16enc(pos, dp_size);
644 	pos += sizeof (uint16_t);
645 
646 	memcpy(pos, bbuf, desc_len);	/* NB:desc_len includes strailing NUL */
647 	pos += desc_len;
648 	free(bbuf);
649 
650 	memcpy(pos, dp, dp_size);
651 	pos += dp_size;
652 
653 	if (optional_data && optional_data_size > 0) {
654 		memcpy(pos, optional_data, optional_data_size);
655 		pos += optional_data_size;
656 	}
657 
658 	return pos - buf;
659 }
660 
661 
662 static int
663 make_boot_var(const char *label, const char *loader, const char *kernel, const char *env, bool dry_run,
664     int bootnum, bool activate)
665 {
666 	struct entry *new_ent;
667 	uint32_t load_attrs = 0;
668 	uint8_t *load_opt_buf;
669 	size_t lopt_size, llen, klen;
670 	efidp dp, loaderdp, kerneldp;
671 	char *bootvar = NULL;
672 	int ret;
673 
674 	assert(label != NULL);
675 
676 	if (bootnum == -1)
677 		bootvar = make_next_boot_var_name();
678 	else
679 		bootvar = make_boot_var_name((uint16_t)bootnum);
680 	if (bootvar == NULL)
681 		err(1, "bootvar creation");
682 	if (loader == NULL)
683 		errx(1, "Must specify boot loader");
684 	ret = efivar_unix_path_to_device_path(loader, &loaderdp);
685 	if (ret != 0)
686 		errc(1, ret, "Cannot translate unix loader path '%s' to UEFI",
687 		    loader);
688 	if (kernel != NULL) {
689 		ret = efivar_unix_path_to_device_path(kernel, &kerneldp);
690 		if (ret != 0)
691 			errc(1, ret,
692 			    "Cannot translate unix kernel path '%s' to UEFI",
693 			    kernel);
694 	} else {
695 		kerneldp = NULL;
696 	}
697 	llen = efidp_size(loaderdp);
698 	if (llen > MAX_DP_LEN)
699 		errx(1, "Loader path too long.");
700 	klen = efidp_size(kerneldp);
701 	if (klen > MAX_DP_LEN)
702 		errx(1, "Kernel path too long.");
703 	dp = malloc(llen + klen);
704 	if (dp == NULL)
705 		errx(1, "Can't allocate memory for new device paths");
706 	memcpy(dp, loaderdp, llen);
707 	if (kerneldp != NULL)
708 		memcpy((char *)dp + llen, kerneldp, klen);
709 
710 	/* don't make the new bootvar active by default, use the -a option later */
711 	load_attrs = LOAD_OPTION_CATEGORY_BOOT;
712 	if (activate)
713 		load_attrs |= LOAD_OPTION_ACTIVE;
714 	load_opt_buf = malloc(MAX_LOADOPT_LEN);
715 	if (load_opt_buf == NULL)
716 		err(1, "malloc");
717 
718 	lopt_size = create_loadopt(load_opt_buf, MAX_LOADOPT_LEN, load_attrs,
719 	    dp, llen + klen, label, env, env ? strlen(env) + 1 : 0);
720 	if (lopt_size == BAD_LENGTH)
721 		errx(1, "Can't create loadopt");
722 
723 	ret = 0;
724 	if (!dry_run) {
725 		ret = efi_set_variable(EFI_GLOBAL_GUID, bootvar,
726 		    (uint8_t*)load_opt_buf, lopt_size, COMMON_ATTRS);
727 	}
728 
729 	if (ret)
730 		err(1, "efi_set_variable");
731 
732 	if (!dry_run)
733 		add_to_boot_order(bootvar); /* first, still not active */
734 	new_ent = malloc(sizeof(struct entry));
735 	if (new_ent == NULL)
736 		err(1, "malloc");
737 	memset(new_ent, 0, sizeof(struct entry));
738 	new_ent->name = bootvar;
739 	new_ent->guid = EFI_GLOBAL_GUID;
740 	LIST_INSERT_HEAD(&efivars, new_ent, entries);
741 	free(load_opt_buf);
742 	free(dp);
743 
744 	return 0;
745 }
746 
747 
748 static void
749 print_loadopt_str(uint8_t *data, size_t datalen)
750 {
751 	char *dev, *relpath, *abspath;
752 	uint32_t attr;
753 	uint16_t fplen;
754 	efi_char *descr;
755 	uint8_t *ep = data + datalen;
756 	uint8_t *walker = data;
757 	efidp dp, edp;
758 	char buf[1024];
759 	int len;
760 	int rv;
761 	int indent;
762 
763 	if (datalen < sizeof(attr) + sizeof(fplen) + sizeof(efi_char))
764 		return;
765 	// First 4 bytes are attribute flags
766 	attr = le32dec(walker);
767 	walker += sizeof(attr);
768 	// Next two bytes are length of the file paths
769 	fplen = le16dec(walker);
770 	walker += sizeof(fplen);
771 	// Next we have a 0 terminated UCS2 string that we know to be aligned
772 	descr = (efi_char *)(intptr_t)(void *)walker;
773 	len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
774 	walker += (len + 1) * sizeof(efi_char);
775 	if (walker > ep)
776 		return;
777 	// Now we have fplen bytes worth of file path stuff
778 	dp = (efidp)walker;
779 	walker += fplen;
780 	if (walker > ep)
781 		return;
782 	edp = (efidp)walker;
783 	/*
784 	 * Everything left is the binary option args
785 	 * opt = walker;
786 	 * optlen = ep - walker;
787 	 */
788 	indent = 1;
789 	while (dp < edp) {
790 		efidp_format_device_path(buf, sizeof(buf), dp,
791 		    (intptr_t)(void *)edp - (intptr_t)(void *)dp);
792 		printf("%*s%s\n", indent, "", buf);
793 		indent = 10 + len + 1;
794 		rv = efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath);
795 		if (rv == 0) {
796 			printf("%*s%s:%s %s\n", indent + 4, "", dev, relpath, abspath);
797 			free(dev);
798 			free(relpath);
799 			free(abspath);
800 		}
801 		dp = (efidp)((char *)dp + efidp_size(dp));
802 	}
803 }
804 
805 static char *
806 get_descr(uint8_t *data)
807 {
808 	uint8_t *pos = data;
809 	efi_char *desc;
810 	int  len;
811 	char *buf;
812 	int i = 0;
813 
814 	pos += sizeof(uint32_t) + sizeof(uint16_t);
815 	desc = (efi_char*)(intptr_t)(void *)pos;
816 	len = ucs2len(desc);
817 	buf = malloc(len + 1);
818 	memset(buf, 0, len + 1);
819 	while (desc[i]) {
820 		buf[i] = desc[i];
821 		i++;
822 	}
823 	return (char*)buf;
824 }
825 
826 
827 static bool
828 print_boot_var(const char *name, bool verbose, bool curboot)
829 {
830 	size_t size;
831 	uint32_t load_attrs;
832 	uint8_t *data;
833 	int ret;
834 	char *d;
835 
836 	ret = efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL);
837 	if (ret < 0)
838 		return false;
839 	load_attrs = le32dec(data);
840 	d = get_descr(data);
841 	printf("%c%s%c %s", curboot ? '+' : ' ', name,
842 	    ((load_attrs & LOAD_OPTION_ACTIVE) ? '*': ' '), d);
843 	free(d);
844 	if (verbose)
845 		print_loadopt_str(data, size);
846 	else
847 		printf("\n");
848 	return true;
849 }
850 
851 
852 static bool
853 os_indication_supported(uint64_t indication)
854 {
855 	uint8_t *data;
856 	size_t size;
857 	uint32_t attrs;
858 	int ret;
859 
860 	ret = efi_get_variable(EFI_GLOBAL_GUID, "OsIndicationsSupported", &data,
861 	    &size, &attrs);
862 	if (ret < 0)
863 		return false;
864 	return (le64dec(data) & indication) == indication;
865 }
866 
867 static uint64_t
868 os_indications(void)
869 {
870 	uint8_t *data;
871 	size_t size;
872 	uint32_t attrs;
873 	int ret;
874 
875 	ret = efi_get_variable(EFI_GLOBAL_GUID, "OsIndications", &data, &size,
876 	    &attrs);
877 	if (ret < 0)
878 		return 0;
879 	return le64dec(data);
880 }
881 
882 static int
883 os_indications_set(uint64_t mask, uint64_t val)
884 {
885 	uint8_t new[sizeof(uint64_t)];
886 
887 	le64enc(&new, (os_indications() & ~mask) | (val & mask));
888 	return set_bootvar("OsIndications", new, sizeof(new));
889 }
890 
891 /* Cmd epilogue, or just the default with no args.
892  * The order is [bootnext] bootcurrent, timeout, order, and the bootvars [-v]
893  */
894 static int
895 print_boot_vars(bool verbose)
896 {
897 	/*
898 	 * just read and print the current values
899 	 * as a command epilogue
900 	 */
901 	struct entry *v;
902 	uint8_t *data;
903 	size_t size;
904 	uint32_t attrs;
905 	int ret, bolen;
906 	uint16_t *boot_order = NULL, current;
907 	bool boot_to_fw_ui;
908 
909 	if (os_indication_supported(EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
910 		boot_to_fw_ui =
911 		    (os_indications() & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) != 0;
912 		printf("Boot to FW : %s\n", boot_to_fw_ui != 0 ?
913 		    "true" : "false");
914 	}
915 
916 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootNext", &data, &size, &attrs);
917 	if (ret > 0) {
918 		printf("BootNext : %04x\n", le16dec(data));
919 	}
920 
921 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
922 	current = le16dec(data);
923 	printf("BootCurrent: %04x\n", current);
924 
925 	ret = efi_get_variable(EFI_GLOBAL_GUID, "Timeout", &data, &size, &attrs);
926 	if (ret > 0) {
927 		printf("Timeout    : %d seconds\n", le16dec(data));
928 	}
929 
930 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) > 0) {
931 		if (size % 2 == 1)
932 			warn("Bad BootOrder variable: odd length %d", (int)size);
933 		boot_order = malloc(size);
934 		bolen = size / 2;
935 		printf("BootOrder  : ");
936 		for (size_t i = 0; i < size; i += 2) {
937 			boot_order[i / 2] = le16dec(data + i);
938 			printf("%04X%s", boot_order[i / 2], i == size - 2 ? "\n" : ", ");
939 		}
940 	}
941 
942 	if (boot_order == NULL) {
943 		/*
944 		 * now we want to fetch 'em all fresh again
945 		 * which possibly includes a newly created bootvar
946 		 */
947 		LIST_FOREACH(v, &efivars, entries) {
948 			print_boot_var(v->name, verbose, v->idx == current);
949 		}
950 	} else {
951 		LIST_FOREACH(v, &efivars, entries) {
952 			v->flags = 0;
953 		}
954 		for (int i = 0; i < bolen; i++) {
955 			char buffer[10];
956 
957 			snprintf(buffer, sizeof(buffer), "Boot%04X", boot_order[i]);
958 			if (!print_boot_var(buffer, verbose, boot_order[i] == current))
959 				printf("%s: MISSING!\n", buffer);
960 			LIST_FOREACH(v, &efivars, entries) {
961 				if (v->idx == boot_order[i]) {
962 					v->flags |= SEEN;
963 					break;
964 				}
965 			}
966 		}
967 		if (verbose) {
968 			printf("\n\nUnreferenced Variables:\n");
969 			LIST_FOREACH(v, &efivars, entries) {
970 				if (v->flags == 0)
971 					print_boot_var(v->name, verbose, v->idx == current);
972 			}
973 		}
974 	}
975 	return 0;
976 }
977 
978 static void
979 delete_timeout(void)
980 {
981 
982 	efi_del_variable(EFI_GLOBAL_GUID,"Timeout");
983 }
984 
985 static void
986 handle_timeout(int to)
987 {
988 	uint16_t timeout;
989 
990 	le16enc(&timeout, to);
991 	if (set_bootvar("Timeout", (uint8_t *)&timeout, sizeof(timeout)) < 0)
992 		errx(1, "Can't set Timeout for booting.");
993 }
994 
995 static void
996 report_esp_device(bool do_dp, bool do_unix)
997 {
998 	uint8_t *data;
999 	size_t size, len;
1000 	uint32_t attrs;
1001 	int ret;
1002 	uint16_t current, fplen;
1003 	char *name, *dev, *relpath, *abspath;
1004 	uint8_t *walker, *ep;
1005 	efi_char *descr;
1006 	efidp dp;
1007 	char buf[PATH_MAX];
1008 
1009 	if (do_dp && do_unix)
1010 		errx(1, "Can't report both UEFI device-path and Unix path together");
1011 
1012 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
1013 	if (ret < 0)
1014 		err(1, "Can't get BootCurrent");
1015 	current = le16dec(data);
1016 	if (asprintf(&name, "Boot%04X", current) < 0)
1017 		err(1, "Can't format boot var\n");
1018 	if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL) < 0)
1019 		err(1, "Can't retrieve EFI var %s", name);
1020 	// First 4 bytes are attribute flags
1021 	walker = data;
1022 	ep = walker + size;
1023 	walker += sizeof(uint32_t);
1024 	// Next two bytes are length of the file paths
1025 	fplen = le16dec(walker);
1026 	walker += sizeof(fplen);
1027 	// Next we have a 0 terminated UCS2 string that we know to be aligned
1028 	descr = (efi_char *)(intptr_t)(void *)walker;
1029 	len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
1030 	walker += (len + 1) * sizeof(efi_char);
1031 	if (walker > ep)
1032 		errx(1, "malformed boot variable %s", name);
1033 	// Now we have fplen bytes worth of file path stuff
1034 	dp = (efidp)walker;
1035 	walker += fplen;
1036 	if (walker > ep)
1037 		errx(1, "malformed boot variable %s", name);
1038 	if (do_dp) {
1039 		efidp_format_device_path_node(buf, sizeof(buf), dp);
1040 		printf("%s\n", buf);
1041 		exit(0);
1042 	}
1043 	if (efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath) != 0)
1044 		errx(1, "Can't convert to unix path");
1045 	if (do_unix) {
1046 		if (abspath == NULL)
1047 			errx(1, "Can't find where %s:%s is mounted",
1048 			    dev, relpath);
1049 		abspath[strlen(abspath) - strlen(relpath) - 1] = '\0';
1050 		printf("%s\n", abspath);
1051 	} else {
1052 		printf("%s\n", dev);
1053 	}
1054 	free(dev);
1055 	free(relpath);
1056 	free(abspath);
1057 	exit(0);
1058 }
1059 
1060 static void
1061 set_boot_to_fw_ui(bool to_fw)
1062 {
1063 	int ret;
1064 
1065 	if (!os_indication_supported(EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
1066 		if (to_fw)
1067 			errx(1, "boot to fw ui not supported");
1068 		else
1069 			return;
1070 	}
1071 	ret = os_indications_set(EFI_OS_INDICATIONS_BOOT_TO_FW_UI,
1072 	    to_fw ? ~0 : 0);
1073 	if (ret < 0)
1074 		errx(1, "failed to set boot to fw ui");
1075 }
1076 
1077 static void
1078 find_efi_device(const char *path)
1079 {
1080 	efidp dp = NULL;
1081 	size_t len;
1082 	int ret;
1083 	char buf[1024];
1084 
1085 	ret = efivar_unix_path_to_device_path(path, &dp);
1086 	if (ret != 0)
1087 		errc(1, ret,
1088 		    "Cannot translate path '%s' to UEFI", path);
1089 	len = efidp_size(dp);
1090 	if (len > MAX_DP_LEN)
1091 		errx(1, "Resulting device path too long.");
1092 	efidp_format_device_path(buf, sizeof(buf), dp, len);
1093 	printf("%s -> %s\n", path, buf);
1094 	exit (0);
1095 }
1096 
1097 int
1098 main(int argc, char *argv[])
1099 {
1100 
1101 	memset(&opts, 0, sizeof (bmgr_opts_t));
1102 	parse_args(argc, argv);
1103 
1104 	/*
1105 	 * find_dev can operate without any efi variables
1106 	 */
1107 	if (!efi_variables_supported() && !opts.find_dev)
1108 		errx(1, "efi variables not supported on this system. root? kldload efirt?");
1109 
1110 	read_vars();
1111 
1112 	if (opts.create)
1113 		/*
1114 		 * side effect, adds to boot order, but not yet active.
1115 		 */
1116 		make_boot_var(opts.label ? opts.label : "",
1117 		    opts.loader, opts.kernel, opts.env, opts.dry_run,
1118 		    opts.has_bootnum ? opts.bootnum : -1, opts.set_active);
1119 	else if (opts.set_active || opts.set_inactive )
1120 		handle_activity(opts.bootnum, opts.set_active);
1121 	else if (opts.order != NULL)
1122 		set_boot_order(opts.order); /* create a new bootorder with opts.order */
1123 	else if (opts.set_bootnext)
1124 		handle_bootnext(opts.bootnum);
1125 	else if (opts.delete_bootnext)
1126 		del_bootnext();
1127 	else if (opts.delete)
1128 		delete_bootvar(opts.bootnum);
1129 	else if (opts.del_timeout)
1130 		delete_timeout();
1131 	else if (opts.set_timeout)
1132 		handle_timeout(opts.timeout);
1133 	else if (opts.esp_device)
1134 		report_esp_device(opts.device_path, opts.unix_path);
1135 	else if (opts.fw_ui)
1136 		set_boot_to_fw_ui(true);
1137 	else if (opts.no_fw_ui)
1138 		set_boot_to_fw_ui(false);
1139 	else if (opts.find_dev)
1140 		find_efi_device(opts.dev);
1141 
1142 	print_boot_vars(opts.verbose);
1143 }
1144