xref: /freebsd/usr.sbin/efibootmgr/efibootmgr.c (revision 9a791529)
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 		case 'v':
294 			opts.verbose = true;
295 			break;
296 		}
297 	}
298 	if (opts.create) {
299 		if (!opts.loader)
300 			errx(1, "%s",CREATE_USAGE);
301 		return;
302 	}
303 
304 	if (opts.order != NULL && *opts.order == '\0')
305 		errx(1, "%s", ORDER_USAGE);
306 
307 	if ((opts.set_inactive || opts.set_active) && !opts.has_bootnum)
308 		errx(1, "%s", ACTIVE_USAGE);
309 
310 	if (opts.delete && !opts.has_bootnum)
311 		errx(1, "%s", DELETE_USAGE);
312 
313 	if (opts.set_bootnext && !opts.has_bootnum)
314 		errx(1, "%s", BOOTNEXT_USAGE);
315 }
316 
317 
318 static void
319 read_vars(void)
320 {
321 
322 	efi_guid_t *guid;
323 	char *next_name = NULL;
324 	int ret = 0;
325 
326 	struct entry *nent;
327 
328 	LIST_INIT(&efivars);
329 	while ((ret = efi_get_next_variable_name(&guid, &next_name)) > 0) {
330 		/*
331 		 * Only pay attention to EFI:BootXXXX variables to get the list.
332 		 */
333 		if (efi_guid_cmp(guid, &EFI_GLOBAL_GUID) != 0 ||
334 		    strlen(next_name) != 8 ||
335 		    strncmp(next_name, "Boot", 4) != 0 ||
336 		    !isxdigit(next_name[4]) ||
337 		    !isxdigit(next_name[5]) ||
338 		    !isxdigit(next_name[6]) ||
339 		    !isxdigit(next_name[7]))
340 			continue;
341 		nent = malloc(sizeof(struct entry));
342 		nent->name = strdup(next_name);
343 
344 		ret = efi_get_variable(*guid, next_name, &nent->data,
345 		    &nent->size, &nent->attrs);
346 		if (ret < 0)
347 			err(1, "efi_get_variable");
348 		nent->guid = *guid;
349 		nent->idx = strtoul(&next_name[4], NULL, 16);
350 		LIST_INSERT_HEAD(&efivars, nent, entries);
351 	}
352 }
353 
354 
355 static void
356 set_boot_order(char *order)
357 {
358 	uint16_t *new_data;
359 	size_t size;
360 	char *next, *cp;
361 	int cnt;
362 	int i;
363 
364 	cp = order;
365 	cnt = 1;
366 	while (*cp) {
367 		if (*cp++ == ',')
368 			cnt++;
369 	}
370 	size = sizeof(uint16_t) * cnt;
371 	new_data = malloc(size);
372 
373 	i = 0;
374 	cp = strdup(order);
375 	while ((next = strsep(&cp, ",")) != NULL) {
376 		new_data[i] = strtoul(next, NULL, 16);
377 		if (new_data[i] == 0 && errno == EINVAL) {
378 			warnx("can't parse %s as a numb", next);
379 			errx(1, "%s", ORDER_USAGE);
380 		}
381 		i++;
382 	}
383 	free(cp);
384 	if (set_bootvar("BootOrder", (uint8_t*)new_data, size) < 0)
385 		err(1, "Unabke to set BootOrder to %s", order);
386 	free(new_data);
387 }
388 
389 static void
390 handle_activity(int bootnum, bool active)
391 {
392 	uint32_t attrs, load_attrs;
393 	uint8_t *data;
394 	size_t size;
395 	char *name;
396 
397 	asprintf(&name, "%s%04X", "Boot", bootnum);
398 	if (name == NULL)
399 		err(1, "asprintf");
400 	if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, &attrs) < 0)
401 		err(1, "No such bootvar %s\n", name);
402 
403 	load_attrs = le32dec(data);
404 
405 	if (active)
406 		load_attrs |= LOAD_OPTION_ACTIVE;
407 	else
408 		load_attrs &= ~LOAD_OPTION_ACTIVE;
409 
410 	le32enc(data, load_attrs);
411 
412 	if (set_bootvar(name, data, size) < 0)
413 		err(1, "handle activity efi_set_variable");
414 }
415 
416 
417 /*
418  * add boot var to boot order.
419  * called by create boot var. There is no option
420  * to add one independent of create.
421  *
422  * Note: we currently don't support where it goes
423  * so it goes on the front, inactive.
424  * use -o 2,3,7 etc to affect order, -a to activate.
425  */
426 static void
427 add_to_boot_order(char *bootvar)
428 {
429 	size_t size;
430 	uint32_t attrs;
431 	uint16_t val;
432 	uint8_t *data, *new;
433 
434 	val = strtoul(&bootvar[4], NULL, 16);
435 
436 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0) {
437 		if (errno == ENOENT) { /* create it and set this bootvar to active */
438 			size = 0;
439 			data = NULL;
440 		} else
441 			err(1, "efi_get_variable BootOrder");
442 	}
443 
444 	/*
445 	 * We have BootOrder with the current order
446 	 * so grow the array by one, add the value
447 	 * and write the new variable value.
448 	 */
449 	size += sizeof(uint16_t);
450 	new = malloc(size);
451 	if (!new)
452 		err(1, "malloc");
453 
454 	le16enc(new, val);
455 	if (size > sizeof(uint16_t))
456 		memcpy(new + sizeof(uint16_t), data, size - sizeof(uint16_t));
457 
458 	if (set_bootvar("BootOrder", new, size) < 0)
459 		err(1, "set_bootvar");
460 	free(new);
461 }
462 
463 
464 static void
465 remove_from_order(uint16_t bootnum)
466 {
467 	uint32_t attrs;
468 	size_t size, i, j;
469 	uint8_t *new, *data;
470 
471 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0)
472 		return;
473 
474 	new = malloc(size);
475 	if (new == NULL)
476 		err(1, "malloc");
477 
478 	for (j = i = 0; i < size; i += sizeof(uint16_t)) {
479 		if (le16dec(data + i) == bootnum)
480 			continue;
481 		memcpy(new + j, data + i, sizeof(uint16_t));
482 		j += sizeof(uint16_t);
483 	}
484 	if (i == j)
485 		warnx("Boot variable %04x not in BootOrder", bootnum);
486 	else if (set_bootvar("BootOrder", new, j) < 0)
487 		err(1, "Unable to update BootOrder with new value");
488 	free(new);
489 }
490 
491 
492 static void
493 delete_bootvar(int bootnum)
494 {
495 	char *name;
496 	int defer = 0;
497 
498 	/*
499 	 * Try to delete the boot variable and remocve it
500 	 * from the boot order. We always do both actions
501 	 * to make it easy to clean up from oopses.
502 	 */
503 	if (bootnum < 0 || bootnum > 0xffff)
504 		errx(1, "Bad boot variable %#x", bootnum);
505 	asprintf(&name, "%s%04X", "Boot", bootnum);
506 	if (name == NULL)
507 		err(1, "asprintf");
508 	printf("Removing boot variable '%s'\n", name);
509 	if (efi_del_variable(EFI_GLOBAL_GUID, name) < 0) {
510 		defer = 1;
511 		warn("cannot delete variable %s", name);
512 	}
513 	printf("Removing 0x%x from BootOrder\n", bootnum);
514 	remove_from_order(bootnum);
515 	free(name);
516 	if (defer)
517 		exit(defer);
518 }
519 
520 
521 static void
522 del_bootnext(void)
523 {
524 
525 	if (efi_del_variable(EFI_GLOBAL_GUID, "BootNext") < 0)
526 		err(1, "efi_del_variable");
527 }
528 
529 static void
530 handle_bootnext(uint16_t bootnum)
531 {
532 	uint16_t num;
533 
534 	le16enc(&num, bootnum);
535 	if (set_bootvar("BootNext", (uint8_t*)&bootnum, sizeof(uint16_t)) < 0)
536 		err(1, "set_bootvar");
537 }
538 
539 
540 static int
541 compare(const void *a, const void *b)
542 {
543 	uint16_t c;
544 	uint16_t d;
545 
546 	memcpy(&c, a, sizeof(uint16_t));
547 	memcpy(&d, b, sizeof(uint16_t));
548 
549 	if (c < d)
550 		return -1;
551 	if (c == d)
552 		return  0;
553 	return  1;
554 }
555 
556 static char *
557 make_next_boot_var_name(void)
558 {
559 	struct entry *v;
560 	uint16_t *vals, next_free = 0;
561 	char *name;
562 	int cnt = 0;
563 	int i;
564 
565 	LIST_FOREACH(v, &efivars, entries) {
566 		cnt++;
567 	}
568 
569 	vals = malloc(sizeof(uint16_t) * cnt);
570 	if (!vals)
571 		return NULL;
572 
573 	i = 0;
574 	LIST_FOREACH(v, &efivars, entries) {
575 		vals[i++] = v->idx;
576 	}
577 	qsort(vals, cnt, sizeof(uint16_t), compare);
578 	/* if the hole is at the beginning, just return zero */
579 	if (vals[0] > 0) {
580 		next_free = 0;
581 	} else {
582 		/* now just run the list looking for the first hole */
583 		for (i = 0; i < cnt - 1 && next_free == 0; i++)
584 			if (vals[i] + 1 != vals[i + 1])
585 				next_free = vals[i] + 1;
586 		if (next_free == 0)
587 			next_free = vals[cnt - 1] + 1;
588 		/* In theory we could have used all 65k slots -- what to do? */
589 	}
590 	free(vals);
591 
592 	asprintf(&name, "%s%04X", "Boot", next_free);
593 	if (name == NULL)
594 		err(1, "asprintf");
595 	return name;
596 }
597 
598 static char *
599 make_boot_var_name(uint16_t bootnum)
600 {
601 	struct entry *v;
602 	char *name;
603 
604 	LIST_FOREACH(v, &efivars, entries) {
605 		if (v->idx == bootnum)
606 			return NULL;
607 	}
608 
609 	asprintf(&name, "%s%04X", "Boot", bootnum);
610 	if (name == NULL)
611 		err(1, "asprintf");
612 	return name;
613 }
614 
615 static size_t
616 create_loadopt(uint8_t *buf, size_t bufmax, uint32_t attributes, efidp dp, size_t dp_size,
617     const char *description, const uint8_t *optional_data, size_t optional_data_size)
618 {
619 	efi_char *bbuf = NULL;
620 	uint8_t *pos = buf;
621 	size_t desc_len = 0;
622 	size_t len;
623 
624 	if (optional_data == NULL && optional_data_size != 0)
625 		return BAD_LENGTH;
626 	if (dp == NULL && dp_size != 0)
627 		return BAD_LENGTH;
628 
629 	/*
630 	 * Compute the length to make sure the passed in buffer is long enough.
631 	 */
632 	utf8_to_ucs2(description, &bbuf, &desc_len);
633 	len = sizeof(uint32_t) + sizeof(uint16_t) + desc_len + dp_size + optional_data_size;
634 	if (len > bufmax) {
635 		free(bbuf);
636 		return BAD_LENGTH;
637 	}
638 
639 	le32enc(pos, attributes);
640 	pos += sizeof (attributes);
641 
642 	le16enc(pos, dp_size);
643 	pos += sizeof (uint16_t);
644 
645 	memcpy(pos, bbuf, desc_len);	/* NB:desc_len includes strailing NUL */
646 	pos += desc_len;
647 	free(bbuf);
648 
649 	memcpy(pos, dp, dp_size);
650 	pos += dp_size;
651 
652 	if (optional_data && optional_data_size > 0) {
653 		memcpy(pos, optional_data, optional_data_size);
654 		pos += optional_data_size;
655 	}
656 
657 	return pos - buf;
658 }
659 
660 
661 static int
662 make_boot_var(const char *label, const char *loader, const char *kernel, const char *env, bool dry_run,
663     int bootnum, bool activate)
664 {
665 	struct entry *new_ent;
666 	uint32_t load_attrs = 0;
667 	uint8_t *load_opt_buf;
668 	size_t lopt_size, llen, klen;
669 	efidp dp, loaderdp, kerneldp;
670 	char *bootvar = NULL;
671 	int ret;
672 
673 	assert(label != NULL);
674 
675 	if (bootnum == -1)
676 		bootvar = make_next_boot_var_name();
677 	else
678 		bootvar = make_boot_var_name((uint16_t)bootnum);
679 	if (bootvar == NULL)
680 		err(1, "bootvar creation");
681 	if (loader == NULL)
682 		errx(1, "Must specify boot loader");
683 	ret = efivar_unix_path_to_device_path(loader, &loaderdp);
684 	if (ret != 0)
685 		errc(1, ret, "Cannot translate unix loader path '%s' to UEFI",
686 		    loader);
687 	if (kernel != NULL) {
688 		ret = efivar_unix_path_to_device_path(kernel, &kerneldp);
689 		if (ret != 0)
690 			errc(1, ret,
691 			    "Cannot translate unix kernel path '%s' to UEFI",
692 			    kernel);
693 	} else {
694 		kerneldp = NULL;
695 	}
696 	llen = efidp_size(loaderdp);
697 	if (llen > MAX_DP_LEN)
698 		errx(1, "Loader path too long.");
699 	klen = efidp_size(kerneldp);
700 	if (klen > MAX_DP_LEN)
701 		errx(1, "Kernel path too long.");
702 	dp = malloc(llen + klen);
703 	if (dp == NULL)
704 		errx(1, "Can't allocate memory for new device paths");
705 	memcpy(dp, loaderdp, llen);
706 	if (kerneldp != NULL)
707 		memcpy((char *)dp + llen, kerneldp, klen);
708 
709 	/* don't make the new bootvar active by default, use the -a option later */
710 	load_attrs = LOAD_OPTION_CATEGORY_BOOT;
711 	if (activate)
712 		load_attrs |= LOAD_OPTION_ACTIVE;
713 	load_opt_buf = malloc(MAX_LOADOPT_LEN);
714 	if (load_opt_buf == NULL)
715 		err(1, "malloc");
716 
717 	lopt_size = create_loadopt(load_opt_buf, MAX_LOADOPT_LEN, load_attrs,
718 	    dp, llen + klen, label, env, env ? strlen(env) + 1 : 0);
719 	if (lopt_size == BAD_LENGTH)
720 		errx(1, "Can't create loadopt");
721 
722 	ret = 0;
723 	if (!dry_run) {
724 		ret = efi_set_variable(EFI_GLOBAL_GUID, bootvar,
725 		    (uint8_t*)load_opt_buf, lopt_size, COMMON_ATTRS);
726 	}
727 
728 	if (ret)
729 		err(1, "efi_set_variable");
730 
731 	if (!dry_run)
732 		add_to_boot_order(bootvar); /* first, still not active */
733 	new_ent = malloc(sizeof(struct entry));
734 	if (new_ent == NULL)
735 		err(1, "malloc");
736 	memset(new_ent, 0, sizeof(struct entry));
737 	new_ent->name = bootvar;
738 	new_ent->guid = EFI_GLOBAL_GUID;
739 	LIST_INSERT_HEAD(&efivars, new_ent, entries);
740 	free(load_opt_buf);
741 	free(dp);
742 
743 	return 0;
744 }
745 
746 
747 static void
748 print_loadopt_str(uint8_t *data, size_t datalen)
749 {
750 	char *dev, *relpath, *abspath;
751 	uint32_t attr;
752 	uint16_t fplen;
753 	efi_char *descr;
754 	uint8_t *ep = data + datalen;
755 	uint8_t *walker = data;
756 	efidp dp, edp;
757 	char buf[1024];
758 	int len;
759 	int rv;
760 	int indent;
761 
762 	if (datalen < sizeof(attr) + sizeof(fplen) + sizeof(efi_char))
763 		return;
764 	// First 4 bytes are attribute flags
765 	attr = le32dec(walker);
766 	walker += sizeof(attr);
767 	// Next two bytes are length of the file paths
768 	fplen = le16dec(walker);
769 	walker += sizeof(fplen);
770 	// Next we have a 0 terminated UCS2 string that we know to be aligned
771 	descr = (efi_char *)(intptr_t)(void *)walker;
772 	len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
773 	walker += (len + 1) * sizeof(efi_char);
774 	if (walker > ep)
775 		return;
776 	// Now we have fplen bytes worth of file path stuff
777 	dp = (efidp)walker;
778 	walker += fplen;
779 	if (walker > ep)
780 		return;
781 	edp = (efidp)walker;
782 	/*
783 	 * Everything left is the binary option args
784 	 * opt = walker;
785 	 * optlen = ep - walker;
786 	 */
787 	indent = 1;
788 	while (dp < edp) {
789 		efidp_format_device_path(buf, sizeof(buf), dp,
790 		    (intptr_t)(void *)edp - (intptr_t)(void *)dp);
791 		printf("%*s%s\n", indent, "", buf);
792 		indent = 10 + len + 1;
793 		rv = efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath);
794 		if (rv == 0) {
795 			printf("%*s%s:%s %s\n", indent + 4, "", dev, relpath, abspath);
796 			free(dev);
797 			free(relpath);
798 			free(abspath);
799 		}
800 		dp = (efidp)((char *)dp + efidp_size(dp));
801 	}
802 }
803 
804 static char *
805 get_descr(uint8_t *data)
806 {
807 	uint8_t *pos = data;
808 	efi_char *desc;
809 	int  len;
810 	char *buf;
811 	int i = 0;
812 
813 	pos += sizeof(uint32_t) + sizeof(uint16_t);
814 	desc = (efi_char*)(intptr_t)(void *)pos;
815 	len = ucs2len(desc);
816 	buf = malloc(len + 1);
817 	memset(buf, 0, len + 1);
818 	while (desc[i]) {
819 		buf[i] = desc[i];
820 		i++;
821 	}
822 	return (char*)buf;
823 }
824 
825 
826 static bool
827 print_boot_var(const char *name, bool verbose, bool curboot)
828 {
829 	size_t size;
830 	uint32_t load_attrs;
831 	uint8_t *data;
832 	int ret;
833 	char *d;
834 
835 	ret = efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL);
836 	if (ret < 0)
837 		return false;
838 	load_attrs = le32dec(data);
839 	d = get_descr(data);
840 	printf("%c%s%c %s", curboot ? '+' : ' ', name,
841 	    ((load_attrs & LOAD_OPTION_ACTIVE) ? '*': ' '), d);
842 	free(d);
843 	if (verbose)
844 		print_loadopt_str(data, size);
845 	else
846 		printf("\n");
847 	return true;
848 }
849 
850 
851 static bool
852 os_indication_supported(uint64_t indication)
853 {
854 	uint8_t *data;
855 	size_t size;
856 	uint32_t attrs;
857 	int ret;
858 
859 	ret = efi_get_variable(EFI_GLOBAL_GUID, "OsIndicationsSupported", &data,
860 	    &size, &attrs);
861 	if (ret < 0)
862 		return false;
863 	return (le64dec(data) & indication) == indication;
864 }
865 
866 static uint64_t
867 os_indications(void)
868 {
869 	uint8_t *data;
870 	size_t size;
871 	uint32_t attrs;
872 	int ret;
873 
874 	ret = efi_get_variable(EFI_GLOBAL_GUID, "OsIndications", &data, &size,
875 	    &attrs);
876 	if (ret < 0)
877 		return 0;
878 	return le64dec(data);
879 }
880 
881 static int
882 os_indications_set(uint64_t mask, uint64_t val)
883 {
884 	uint8_t new[sizeof(uint64_t)];
885 
886 	le64enc(&new, (os_indications() & ~mask) | (val & mask));
887 	return set_bootvar("OsIndications", new, sizeof(new));
888 }
889 
890 /* Cmd epilogue, or just the default with no args.
891  * The order is [bootnext] bootcurrent, timeout, order, and the bootvars [-v]
892  */
893 static int
894 print_boot_vars(bool verbose)
895 {
896 	/*
897 	 * just read and print the current values
898 	 * as a command epilogue
899 	 */
900 	struct entry *v;
901 	uint8_t *data;
902 	size_t size;
903 	uint32_t attrs;
904 	int ret, bolen;
905 	uint16_t *boot_order = NULL, current;
906 	bool boot_to_fw_ui;
907 
908 	if (os_indication_supported(EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
909 		boot_to_fw_ui =
910 		    (os_indications() & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) != 0;
911 		printf("Boot to FW : %s\n", boot_to_fw_ui != 0 ?
912 		    "true" : "false");
913 	}
914 
915 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootNext", &data, &size, &attrs);
916 	if (ret > 0) {
917 		printf("BootNext : %04x\n", le16dec(data));
918 	}
919 
920 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
921 	current = le16dec(data);
922 	printf("BootCurrent: %04x\n", current);
923 
924 	ret = efi_get_variable(EFI_GLOBAL_GUID, "Timeout", &data, &size, &attrs);
925 	if (ret > 0) {
926 		printf("Timeout    : %d seconds\n", le16dec(data));
927 	}
928 
929 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) > 0) {
930 		if (size % 2 == 1)
931 			warn("Bad BootOrder variable: odd length %d", (int)size);
932 		boot_order = malloc(size);
933 		bolen = size / 2;
934 		printf("BootOrder  : ");
935 		for (size_t i = 0; i < size; i += 2) {
936 			boot_order[i / 2] = le16dec(data + i);
937 			printf("%04X%s", boot_order[i / 2], i == size - 2 ? "\n" : ", ");
938 		}
939 	}
940 
941 	if (boot_order == NULL) {
942 		/*
943 		 * now we want to fetch 'em all fresh again
944 		 * which possibly includes a newly created bootvar
945 		 */
946 		LIST_FOREACH(v, &efivars, entries) {
947 			print_boot_var(v->name, verbose, v->idx == current);
948 		}
949 	} else {
950 		LIST_FOREACH(v, &efivars, entries) {
951 			v->flags = 0;
952 		}
953 		for (int i = 0; i < bolen; i++) {
954 			char buffer[10];
955 
956 			snprintf(buffer, sizeof(buffer), "Boot%04X", boot_order[i]);
957 			if (!print_boot_var(buffer, verbose, boot_order[i] == current))
958 				printf("%s: MISSING!\n", buffer);
959 			LIST_FOREACH(v, &efivars, entries) {
960 				if (v->idx == boot_order[i]) {
961 					v->flags |= SEEN;
962 					break;
963 				}
964 			}
965 		}
966 		if (verbose) {
967 			printf("\n\nUnreferenced Variables:\n");
968 			LIST_FOREACH(v, &efivars, entries) {
969 				if (v->flags == 0)
970 					print_boot_var(v->name, verbose, v->idx == current);
971 			}
972 		}
973 	}
974 	return 0;
975 }
976 
977 static void
978 delete_timeout(void)
979 {
980 
981 	efi_del_variable(EFI_GLOBAL_GUID,"Timeout");
982 }
983 
984 static void
985 handle_timeout(int to)
986 {
987 	uint16_t timeout;
988 
989 	le16enc(&timeout, to);
990 	if (set_bootvar("Timeout", (uint8_t *)&timeout, sizeof(timeout)) < 0)
991 		errx(1, "Can't set Timeout for booting.");
992 }
993 
994 static void
995 report_esp_device(bool do_dp, bool do_unix)
996 {
997 	uint8_t *data;
998 	size_t size, len;
999 	uint32_t attrs;
1000 	int ret;
1001 	uint16_t current, fplen;
1002 	char *name, *dev, *relpath, *abspath;
1003 	uint8_t *walker, *ep;
1004 	efi_char *descr;
1005 	efidp dp;
1006 	char buf[PATH_MAX];
1007 
1008 	if (do_dp && do_unix)
1009 		errx(1, "Can't report both UEFI device-path and Unix path together");
1010 
1011 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
1012 	if (ret < 0)
1013 		err(1, "Can't get BootCurrent");
1014 	current = le16dec(data);
1015 	if (asprintf(&name, "Boot%04X", current) < 0)
1016 		err(1, "Can't format boot var\n");
1017 	if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL) < 0)
1018 		err(1, "Can't retrieve EFI var %s", name);
1019 	// First 4 bytes are attribute flags
1020 	walker = data;
1021 	ep = walker + size;
1022 	walker += sizeof(uint32_t);
1023 	// Next two bytes are length of the file paths
1024 	fplen = le16dec(walker);
1025 	walker += sizeof(fplen);
1026 	// Next we have a 0 terminated UCS2 string that we know to be aligned
1027 	descr = (efi_char *)(intptr_t)(void *)walker;
1028 	len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
1029 	walker += (len + 1) * sizeof(efi_char);
1030 	if (walker > ep)
1031 		errx(1, "malformed boot variable %s", name);
1032 	// Now we have fplen bytes worth of file path stuff
1033 	dp = (efidp)walker;
1034 	walker += fplen;
1035 	if (walker > ep)
1036 		errx(1, "malformed boot variable %s", name);
1037 	if (do_dp) {
1038 		efidp_format_device_path_node(buf, sizeof(buf), dp);
1039 		printf("%s\n", buf);
1040 		exit(0);
1041 	}
1042 	if (efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath) != 0)
1043 		errx(1, "Can't convert to unix path");
1044 	if (do_unix) {
1045 		if (abspath == NULL)
1046 			errx(1, "Can't find where %s:%s is mounted",
1047 			    dev, relpath);
1048 		abspath[strlen(abspath) - strlen(relpath) - 1] = '\0';
1049 		printf("%s\n", abspath);
1050 	} else {
1051 		printf("%s\n", dev);
1052 	}
1053 	free(dev);
1054 	free(relpath);
1055 	free(abspath);
1056 	exit(0);
1057 }
1058 
1059 static void
1060 set_boot_to_fw_ui(bool to_fw)
1061 {
1062 	int ret;
1063 
1064 	if (!os_indication_supported(EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
1065 		if (to_fw)
1066 			errx(1, "boot to fw ui not supported");
1067 		else
1068 			return;
1069 	}
1070 	ret = os_indications_set(EFI_OS_INDICATIONS_BOOT_TO_FW_UI,
1071 	    to_fw ? ~0 : 0);
1072 	if (ret < 0)
1073 		errx(1, "failed to set boot to fw ui");
1074 }
1075 
1076 static void
1077 find_efi_device(const char *path)
1078 {
1079 	efidp dp = NULL;
1080 	size_t len;
1081 	int ret;
1082 	char buf[1024];
1083 
1084 	ret = efivar_unix_path_to_device_path(path, &dp);
1085 	if (ret != 0)
1086 		errc(1, ret,
1087 		    "Cannot translate path '%s' to UEFI", path);
1088 	len = efidp_size(dp);
1089 	if (len > MAX_DP_LEN)
1090 		errx(1, "Resulting device path too long.");
1091 	efidp_format_device_path(buf, sizeof(buf), dp, len);
1092 	printf("%s -> %s\n", path, buf);
1093 	exit (0);
1094 }
1095 
1096 int
1097 main(int argc, char *argv[])
1098 {
1099 
1100 	memset(&opts, 0, sizeof (bmgr_opts_t));
1101 	parse_args(argc, argv);
1102 
1103 	/*
1104 	 * find_dev can operate without any efi variables
1105 	 */
1106 	if (!efi_variables_supported() && !opts.find_dev)
1107 		errx(1, "efi variables not supported on this system. root? kldload efirt?");
1108 
1109 	read_vars();
1110 
1111 	if (opts.create)
1112 		/*
1113 		 * side effect, adds to boot order, but not yet active.
1114 		 */
1115 		make_boot_var(opts.label ? opts.label : "",
1116 		    opts.loader, opts.kernel, opts.env, opts.dry_run,
1117 		    opts.has_bootnum ? opts.bootnum : -1, opts.set_active);
1118 	else if (opts.set_active || opts.set_inactive )
1119 		handle_activity(opts.bootnum, opts.set_active);
1120 	else if (opts.order != NULL)
1121 		set_boot_order(opts.order); /* create a new bootorder with opts.order */
1122 	else if (opts.set_bootnext)
1123 		handle_bootnext(opts.bootnum);
1124 	else if (opts.delete_bootnext)
1125 		del_bootnext();
1126 	else if (opts.delete)
1127 		delete_bootvar(opts.bootnum);
1128 	else if (opts.del_timeout)
1129 		delete_timeout();
1130 	else if (opts.set_timeout)
1131 		handle_timeout(opts.timeout);
1132 	else if (opts.esp_device)
1133 		report_esp_device(opts.device_path, opts.unix_path);
1134 	else if (opts.fw_ui)
1135 		set_boot_to_fw_ui(true);
1136 	else if (opts.no_fw_ui)
1137 		set_boot_to_fw_ui(false);
1138 	else if (opts.find_dev)
1139 		find_efi_device(opts.dev);
1140 
1141 	print_boot_vars(opts.verbose);
1142 }
1143