xref: /freebsd/usr.sbin/efibootmgr/efibootmgr.c (revision b37f6c9805edb4b89f0a8c2b78f78a3dcfc0647b)
1 /*-
2  * Copyright (c) 2017 Netflix, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/stat.h>
31 #include <sys/vtoc.h>
32 #include <sys/param.h>
33 #include <assert.h>
34 #include <ctype.h>
35 #include <err.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <libgeom.h>
39 #include <paths.h>
40 #include <signal.h>
41 #include <stdint.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <getopt.h>
45 #include <limits.h>
46 #include <inttypes.h>
47 #include <stdbool.h>
48 #include <string.h>
49 #include <strings.h>
50 #include <unistd.h>
51 #include <libgeom.h>
52 #include <geom/geom.h>
53 #include <geom/geom_ctl.h>
54 #include <geom/geom_int.h>
55 
56 #include <efivar.h>
57 #include <efiutil.h>
58 #include <efichar.h>
59 #include <efivar-dp.h>
60 
61 #ifndef LOAD_OPTION_ACTIVE
62 #define LOAD_OPTION_ACTIVE 0x00000001
63 #endif
64 
65 #ifndef LOAD_OPTION_CATEGORY_BOOT
66 #define LOAD_OPTION_CATEGORY_BOOT 0x00000000
67 #endif
68 
69 #define BAD_LENGTH	((size_t)-1)
70 
71 typedef struct _bmgr_opts {
72 	char	*env;
73 	char	*loader;
74 	char	*label;
75 	char	*kernel;
76 	char	*name;
77 	char	*order;
78 	int     bootnum;
79 	bool	copy;
80 	bool    create;
81 	bool    delete;
82 	bool    delete_bootnext;
83 	bool    del_timeout;
84 	bool    dry_run;
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", required_argument, NULL, 'a'},
97 	{"bootnext", required_argument, NULL, 'n'}, /* set bootnext */
98 	{"bootorder", required_argument, NULL, 'o'}, /* set order */
99 	{"copy", required_argument, NULL, 'C'},		/* Copy boot method */
100 	{"create", no_argument, NULL, 'c'},
101 	{"deactivate", required_argument, NULL, 'A'},
102 	{"del-timout", no_argument, NULL, 'T'},
103 	{"delete", required_argument, NULL, 'B'},
104 	{"delete-bootnext", required_argument, NULL, 'N'},
105 	{"device", required_argument, NULL, 'd'},
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 	{"partition", required_argument, NULL, 'p'},
114 	{"set-timeout", required_argument, NULL, 't'},
115 	{"verbose", no_argument, NULL, 'v'},
116 	{ NULL, 0, NULL, 0}
117 };
118 
119 /* global efibootmgr opts */
120 static bmgr_opts_t opts;
121 
122 static LIST_HEAD(efivars_head, entry) efivars =
123 	LIST_HEAD_INITIALIZER(efivars);
124 
125 struct entry {
126 	efi_guid_t	guid;
127 	uint32_t	attrs;
128 	uint8_t		*data;
129 	size_t		size;
130 	char		*name;
131 	char		*label;
132 	int		idx;
133 	int		part;
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 	"   [-aAnNB Bootvar] [-t timeout] [-T] [-o bootorder] [-O] [--verbose] [--help] \n\
174   [-c -l loader [-k kernel ] [-L label] [--dry-run]]"
175 
176 #define CREATE_USAGE \
177 	"       efibootmgr -c -l loader [-k kernel] [-L label] [--dry-run]"
178 #define ORDER_USAGE \
179 	"       efibootmgr -o bootvarnum1,bootvarnum2,..."
180 #define TIMEOUT_USAGE \
181 	"       efibootmgr -t seconds"
182 #define DELETE_USAGE \
183 	"       efibootmgr -B bootvarnum"
184 #define ACTIVE_USAGE \
185 	"       efibootmgr [-a | -A] bootvarnum"
186 #define BOOTNEXT_USAGE \
187 	"       efibootmgr [-n | -N] bootvarnum"
188 
189 static void
190 parse_args(int argc, char *argv[])
191 {
192 	int ch;
193 
194 	while ((ch = getopt_long(argc, argv, "A:a:B:C:cDe:hk:L:l:Nn:Oo:Tt:v",
195 		    lopts, NULL)) != -1) {
196 		switch (ch) {
197 		case 'A':
198 			opts.set_inactive = true;
199 			opts.bootnum = strtoul(optarg, NULL, 16);
200 			break;
201 		case 'a':
202 			opts.set_active = true;
203 			opts.bootnum = strtoul(optarg, NULL, 16);
204 			break;
205 		case 'B':
206 			opts.delete = true;
207 			opts.bootnum = strtoul(optarg, NULL, 16);
208 			break;
209 		case 'C':
210 			opts.copy = true;
211 			opts.cp_src = strtoul(optarg, NULL, 16);
212 		case 'c':
213 			opts.create = true;
214 			break;
215 		case 'D': /* should be remove dups XXX */
216 			opts.dry_run = true;
217 			break;
218 		case 'e':
219 			free(opts.env);
220 			opts.env = strdup(optarg);
221 			break;
222 		case 'h':
223 		default:
224 			errx(1, "%s", USAGE);
225 			break;
226 		case 'k':
227 			free(opts.kernel);
228 			opts.kernel = strdup(optarg);
229 			break;
230 		case 'L':
231 			free(opts.label);
232 			opts.label = strdup(optarg);
233 			break;
234 		case 'l':
235 			free(opts.loader);
236 			opts.loader = strdup(optarg);
237 			opts.loader = mangle_loader(opts.loader);
238 			break;
239 		case 'N':
240 			opts.delete_bootnext = true;
241 			break;
242 		case 'n':
243 			opts.set_bootnext = true;
244 			opts.bootnum = strtoul(optarg, NULL, 16);
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 	if (opts.set_bootnext && !(opts.bootnum))
271 		errx(1, "%s", BOOTNEXT_USAGE);
272 
273 	if ((opts.set_active ||  opts.set_inactive) && !(opts.bootnum))
274 		errx(1, "%s", ACTIVE_USAGE);
275 
276 	if (opts.order && !(opts.order))
277 		errx(1, "%s", ORDER_USAGE);
278 }
279 
280 
281 static void
282 print_order(void)
283 {
284 	uint32_t attrs;
285 	uint8_t *data;
286 	size_t size, i;
287 
288 	if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0)
289 		errx(1, "Couldn't get value for BootOrder\n");
290 
291 	if (size % 2 == 1)
292 		errx(1, "Bad BootOrder variable: odd length");
293 
294 	printf("BootOrder : ");
295 	for (i = 0; i < size; i += 2)
296 		printf("%04x%s", le16dec(data + i), i == size - 2 ? "\n" : ", ");
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 
581 static size_t
582 create_loadopt(uint8_t *buf, size_t bufmax, uint32_t attributes, efidp dp, size_t dp_size,
583     const char *description, const uint8_t *optional_data, size_t optional_data_size)
584 {
585 	efi_char *bbuf = NULL;
586 	uint8_t *pos = buf;
587 	size_t desc_len = 0;
588 	size_t len;
589 
590 	if (optional_data == NULL && optional_data_size != 0)
591 		return BAD_LENGTH;
592 	if (dp == NULL && dp_size != 0)
593 		return BAD_LENGTH;
594 
595 	/*
596 	 * Compute the length to make sure the passed in buffer is long enough.
597 	 */
598 	utf8_to_ucs2(description, &bbuf, &desc_len);
599 	len = sizeof(uint32_t) + sizeof(uint16_t) + desc_len + dp_size + optional_data_size;
600 	if (len > bufmax) {
601 		free(bbuf);
602 		return BAD_LENGTH;
603 	}
604 
605 	le32enc(pos, attributes);
606 	pos += sizeof (attributes);
607 
608 	le16enc(pos, dp_size);
609 	pos += sizeof (uint16_t);
610 
611 	memcpy(pos, bbuf, desc_len);	/* NB:desc_len includes strailing NUL */
612 	pos += desc_len;
613 	free(bbuf);
614 
615 	memcpy(pos, dp, dp_size);
616 	pos += dp_size;
617 
618 	if (optional_data && optional_data_size > 0) {
619 		memcpy(pos, optional_data, optional_data_size);
620 		pos += optional_data_size;
621 	}
622 
623 	return pos - buf;
624 }
625 
626 
627 static int
628 make_boot_var(const char *label, const char *loader, const char *kernel, const char *env, bool dry_run)
629 {
630 	struct entry *new_ent;
631 	uint32_t load_attrs = 0;
632 	uint8_t *load_opt_buf;
633 	size_t lopt_size, llen, klen;
634 	efidp dp, loaderdp, kerneldp;
635 	char *bootvar = NULL;
636 	int ret;
637 
638 	assert(label != NULL);
639 
640 	bootvar = make_next_boot_var_name();
641 	if (bootvar == NULL)
642 		err(1, "bootvar creation");
643 	if (loader == NULL)
644 		errx(1, "Must specify boot loader");
645 	if (efivar_unix_path_to_device_path(loader, &loaderdp) != 0)
646 		err(1, "Cannot translate unix loader path '%s' to UEFI", loader);
647 	if (kernel != NULL) {
648 		if (efivar_unix_path_to_device_path(kernel, &kerneldp) != 0)
649 			err(1, "Cannot translate unix kernel path '%s' to UEFI", kernel);
650 	} else {
651 		kerneldp = NULL;
652 	}
653 	llen = efidp_size(loaderdp);
654 	if (llen > MAX_DP_LEN)
655 		errx(1, "Loader path too long.");
656 	klen = efidp_size(kerneldp);
657 	if (klen > MAX_DP_LEN)
658 		errx(1, "Kernel path too long.");
659 	dp = malloc(llen + klen);
660 	if (dp == NULL)
661 		errx(1, "Can't allocate memory for new device paths");
662 	memcpy(dp, loaderdp, llen);
663 	if (kerneldp != NULL)
664 		memcpy((char *)dp + llen, kerneldp, klen);
665 
666 	/* don't make the new bootvar active by default, use the -a option later */
667 	load_attrs = LOAD_OPTION_CATEGORY_BOOT;
668 	load_opt_buf = malloc(MAX_LOADOPT_LEN);
669 	if (load_opt_buf == NULL)
670 		err(1, "malloc");
671 
672 	lopt_size = create_loadopt(load_opt_buf, MAX_LOADOPT_LEN, load_attrs,
673 	    dp, llen + klen, label, env, env ? strlen(env) + 1 : 0);
674 	if (lopt_size == BAD_LENGTH)
675 		errx(1, "Can't crate loadopt");
676 
677 	ret = 0;
678 	if (!dry_run) {
679 		ret = efi_set_variable(EFI_GLOBAL_GUID, bootvar,
680 		    (uint8_t*)load_opt_buf, lopt_size, COMMON_ATTRS);
681 	}
682 
683 	if (ret)
684 		err(1, "efi_set_variable");
685 
686 	add_to_boot_order(bootvar); /* first, still not active */
687 	new_ent = malloc(sizeof(struct entry));
688 	if (new_ent == NULL)
689 		err(1, "malloc");
690 	memset(new_ent, 0, sizeof(struct entry));
691 	new_ent->name = bootvar;
692 	new_ent->guid = EFI_GLOBAL_GUID;
693 	LIST_INSERT_HEAD(&efivars, new_ent, entries);
694 	free(load_opt_buf);
695 	free(dp);
696 
697 	return 0;
698 }
699 
700 
701 static void
702 print_loadopt_str(uint8_t *data, size_t datalen)
703 {
704 	char *dev, *relpath, *abspath;
705 	uint32_t attr;
706 	uint16_t fplen;
707 	efi_char *descr;
708 	uint8_t *ep = data + datalen;
709 	uint8_t *walker = data;
710 	efidp dp, edp;
711 	char buf[1024];
712 	int len;
713 	int rv;
714 	int indent;
715 
716 	if (datalen < sizeof(attr) + sizeof(fplen) + sizeof(efi_char))
717 		return;
718 	// First 4 bytes are attribute flags
719 	attr = le32dec(walker);
720 	walker += sizeof(attr);
721 	// Next two bytes are length of the file paths
722 	fplen = le16dec(walker);
723 	walker += sizeof(fplen);
724 	// Next we have a 0 terminated UCS2 string that we know to be aligned
725 	descr = (efi_char *)(intptr_t)(void *)walker;
726 	len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
727 	walker += (len + 1) * sizeof(efi_char);
728 	if (walker > ep)
729 		return;
730 	// Now we have fplen bytes worth of file path stuff
731 	dp = (efidp)walker;
732 	walker += fplen;
733 	if (walker > ep)
734 		return;
735 	edp = (efidp)walker;
736 	/*
737 	 * Everything left is the binary option args
738 	 * opt = walker;
739 	 * optlen = ep - walker;
740 	 */
741 	indent = 1;
742 	while (dp < edp) {
743 		efidp_format_device_path(buf, sizeof(buf), dp,
744 		    (intptr_t)(void *)edp - (intptr_t)(void *)dp);
745 		printf("%*s%s\n", indent, "", buf);
746 		indent = 10 + len + 1;
747 		rv = efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath);
748 		if (rv == 0) {
749 			printf("%*s%s:%s %s\n", indent + 4, "", dev, relpath, abspath);
750 			free(dev);
751 			free(relpath);
752 			free(abspath);
753 		}
754 		dp = (efidp)((char *)dp + efidp_size(dp));
755 	}
756 }
757 
758 static char *
759 get_descr(uint8_t *data)
760 {
761 	uint8_t *pos = data;
762 	efi_char *desc;
763 	int  len;
764 	char *buf;
765 	int i = 0;
766 
767 	pos += sizeof(uint32_t) + sizeof(uint16_t);
768 	desc = (efi_char*)(intptr_t)(void *)pos;
769 	len = ucs2len(desc);
770 	buf = malloc(len + 1);
771 	memset(buf, 0, len + 1);
772 	while (desc[i]) {
773 		buf[i] = desc[i];
774 		i++;
775 	}
776 	return (char*)buf;
777 }
778 
779 
780 /* Cmd epilogue, or just the default with no args.
781  * The order is [bootnext] bootcurrent, timeout, order, and the bootvars [-v]
782  */
783 static int
784 print_boot_vars(bool verbose)
785 {
786 	/*
787 	 * just read and print the current values
788 	 * as a command epilogue
789 	 */
790 	struct entry *v;
791 	uint8_t *data;
792 	char *d;
793 	size_t size;
794 	uint32_t attrs, load_attrs;
795 	int ret;
796 
797 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootNext", &data, &size, &attrs);
798 	if (ret > 0) {
799 		printf("BootNext : %04x\n", le16dec(data));
800 	}
801 
802 	ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
803 	printf("BootCurrent: %04x\n", le16dec(data));
804 
805 	ret = efi_get_variable(EFI_GLOBAL_GUID, "Timeout", &data, &size, &attrs);
806 	if (ret > 0) {
807 		printf("Timeout : %d seconds\n", le16dec(data));
808 	}
809 	print_order();
810 
811 	/* now we want to fetch 'em all fresh again
812 	 * which possibly includes a newly created bootvar
813 	 */
814 	LIST_FOREACH(v, &efivars, entries) {
815 		attrs = 0;
816 		ret = efi_get_variable(EFI_GLOBAL_GUID, v->name, &data,
817 		    &size, &attrs);
818 		if (ret < 0)
819 			continue; /* we must have deleted it */
820 		load_attrs = le32dec(data);
821 		d = get_descr(data);
822 		printf("%s%c %s", v->name,
823 		    ((load_attrs & LOAD_OPTION_ACTIVE) ? '*': ' '), d);
824 		free(d);
825 		if (verbose)
826 			print_loadopt_str(data, size);
827 		else
828 			printf("\n");
829 	}
830 	return 0;
831 }
832 
833 static void
834 delete_timeout(void)
835 {
836 
837 	efi_del_variable(EFI_GLOBAL_GUID,"Timeout");
838 }
839 
840 static void
841 handle_timeout(int to)
842 {
843 	uint16_t timeout;
844 
845 	le16enc(&timeout, to);
846 	if (set_bootvar("Timeout", (uint8_t *)&timeout, sizeof(timeout)) < 0)
847 		errx(1, "Can't set Timeout for booting.");
848 }
849 
850 int
851 main(int argc, char *argv[])
852 {
853 
854 	if (!efi_variables_supported())
855 		errx(1, "efi variables not supported on this system. root? kldload efirt?");
856 
857 	memset(&opts, 0, sizeof (bmgr_opts_t));
858 	parse_args(argc, argv);
859 	read_vars();
860 
861 	if (opts.create)
862 		/*
863 		 * side effect, adds to boot order, but not yet active.
864 		 */
865 		make_boot_var(opts.label ? opts.label : "",
866 		    opts.loader, opts.kernel, opts.env, opts.dry_run);
867 	else if (opts.set_active || opts.set_inactive )
868 		handle_activity(opts.bootnum, opts.set_active);
869 	else if (opts.order != NULL)
870 		set_boot_order(opts.order); /* create a new bootorder with opts.order */
871 	else if (opts.set_bootnext)
872 		handle_bootnext(opts.bootnum);
873 	else if (opts.delete_bootnext)
874 		del_bootnext();
875 	else if (opts.delete)
876 		delete_bootvar(opts.bootnum);
877 	else if (opts.del_timeout)
878 		delete_timeout();
879 	else if (opts.set_timeout)
880 		handle_timeout(opts.timeout);
881 
882 	print_boot_vars(opts.verbose);
883 }
884