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