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