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