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