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