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