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