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