]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/efibootmgr/efibootmgr.c
MFC 363241:
[FreeBSD/FreeBSD.git] / usr.sbin / efibootmgr / efibootmgr.c
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
70 typedef struct _bmgr_opts {
71         char    *env;
72         char    *loader;
73         char    *label;
74         char    *kernel;
75         char    *name;
76         char    *order;
77         int     bootnum;
78         bool    copy;
79         bool    create;
80         bool    delete;
81         bool    delete_bootnext;
82         bool    del_timeout;
83         bool    dry_run;
84         bool    has_bootnum;
85         bool    once;
86         int     cp_src;
87         bool    set_active;
88         bool    set_bootnext;
89         bool    set_inactive;
90         bool    set_timeout;
91         int     timeout;
92         bool    verbose;
93 } bmgr_opts_t;
94
95 static struct option lopts[] = {
96         {"activate", 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 */
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] [-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
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.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
279 static void
280 read_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
316 static void
317 set_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
350 static void
351 handle_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  */
387 static void
388 add_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
425 static void
426 remove_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
453 static void
454 delete_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
482 static void
483 del_bootnext(void)
484 {
485
486         if (efi_del_variable(EFI_GLOBAL_GUID, "BootNext") < 0)
487                 err(1, "efi_del_variable");
488 }
489
490 static void
491 handle_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
501 static int
502 compare(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
517 static char *
518 make_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
559 static char *
560 make_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
576 static size_t
577 create_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
622 static int
623 make_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         if (efivar_unix_path_to_device_path(loader, &loaderdp) != 0)
645                 err(1, "Cannot translate unix loader path '%s' to UEFI", loader);
646         if (kernel != NULL) {
647                 if (efivar_unix_path_to_device_path(kernel, &kerneldp) != 0)
648                         err(1, "Cannot translate unix kernel path '%s' to UEFI", kernel);
649         } else {
650                 kerneldp = NULL;
651         }
652         llen = efidp_size(loaderdp);
653         if (llen > MAX_DP_LEN)
654                 errx(1, "Loader path too long.");
655         klen = efidp_size(kerneldp);
656         if (klen > MAX_DP_LEN)
657                 errx(1, "Kernel path too long.");
658         dp = malloc(llen + klen);
659         if (dp == NULL)
660                 errx(1, "Can't allocate memory for new device paths");
661         memcpy(dp, loaderdp, llen);
662         if (kerneldp != NULL)
663                 memcpy((char *)dp + llen, kerneldp, klen);
664
665         /* don't make the new bootvar active by default, use the -a option later */
666         load_attrs = LOAD_OPTION_CATEGORY_BOOT;
667         if (activate)
668                 load_attrs |= LOAD_OPTION_ACTIVE;
669         load_opt_buf = malloc(MAX_LOADOPT_LEN);
670         if (load_opt_buf == NULL)
671                 err(1, "malloc");
672
673         lopt_size = create_loadopt(load_opt_buf, MAX_LOADOPT_LEN, load_attrs,
674             dp, llen + klen, label, env, env ? strlen(env) + 1 : 0);
675         if (lopt_size == BAD_LENGTH)
676                 errx(1, "Can't create loadopt");
677
678         ret = 0;
679         if (!dry_run) {
680                 ret = efi_set_variable(EFI_GLOBAL_GUID, bootvar,
681                     (uint8_t*)load_opt_buf, lopt_size, COMMON_ATTRS);
682         }
683
684         if (ret)
685                 err(1, "efi_set_variable");
686
687         if (!dry_run)
688                 add_to_boot_order(bootvar); /* first, still not active */
689         new_ent = malloc(sizeof(struct entry));
690         if (new_ent == NULL)
691                 err(1, "malloc");
692         memset(new_ent, 0, sizeof(struct entry));
693         new_ent->name = bootvar;
694         new_ent->guid = EFI_GLOBAL_GUID;
695         LIST_INSERT_HEAD(&efivars, new_ent, entries);
696         free(load_opt_buf);
697         free(dp);
698
699         return 0;
700 }
701
702
703 static void
704 print_loadopt_str(uint8_t *data, size_t datalen)
705 {
706         char *dev, *relpath, *abspath;
707         uint32_t attr;
708         uint16_t fplen;
709         efi_char *descr;
710         uint8_t *ep = data + datalen;
711         uint8_t *walker = data;
712         efidp dp, edp;
713         char buf[1024];
714         int len;
715         int rv;
716         int indent;
717
718         if (datalen < sizeof(attr) + sizeof(fplen) + sizeof(efi_char))
719                 return;
720         // First 4 bytes are attribute flags
721         attr = le32dec(walker);
722         walker += sizeof(attr);
723         // Next two bytes are length of the file paths
724         fplen = le16dec(walker);
725         walker += sizeof(fplen);
726         // Next we have a 0 terminated UCS2 string that we know to be aligned
727         descr = (efi_char *)(intptr_t)(void *)walker;
728         len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
729         walker += (len + 1) * sizeof(efi_char);
730         if (walker > ep)
731                 return;
732         // Now we have fplen bytes worth of file path stuff
733         dp = (efidp)walker;
734         walker += fplen;
735         if (walker > ep)
736                 return;
737         edp = (efidp)walker;
738         /*
739          * Everything left is the binary option args
740          * opt = walker;
741          * optlen = ep - walker;
742          */
743         indent = 1;
744         while (dp < edp) {
745                 efidp_format_device_path(buf, sizeof(buf), dp,
746                     (intptr_t)(void *)edp - (intptr_t)(void *)dp);
747                 printf("%*s%s\n", indent, "", buf);
748                 indent = 10 + len + 1;
749                 rv = efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath);
750                 if (rv == 0) {
751                         printf("%*s%s:%s %s\n", indent + 4, "", dev, relpath, abspath);
752                         free(dev);
753                         free(relpath);
754                         free(abspath);
755                 }
756                 dp = (efidp)((char *)dp + efidp_size(dp));
757         }
758 }
759
760 static char *
761 get_descr(uint8_t *data)
762 {
763         uint8_t *pos = data;
764         efi_char *desc;
765         int  len;
766         char *buf;
767         int i = 0;
768
769         pos += sizeof(uint32_t) + sizeof(uint16_t);
770         desc = (efi_char*)(intptr_t)(void *)pos;
771         len = ucs2len(desc);
772         buf = malloc(len + 1);
773         memset(buf, 0, len + 1);
774         while (desc[i]) {
775                 buf[i] = desc[i];
776                 i++;
777         }
778         return (char*)buf;
779 }
780
781
782 static bool
783 print_boot_var(const char *name, bool verbose, bool curboot)
784 {
785         size_t size;
786         uint32_t load_attrs;
787         uint8_t *data;
788         int ret;
789         char *d;
790
791         ret = efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL);
792         if (ret < 0)
793                 return false;
794         load_attrs = le32dec(data);
795         d = get_descr(data);
796         printf("%c%s%c %s", curboot ? '+' : ' ', name,
797             ((load_attrs & LOAD_OPTION_ACTIVE) ? '*': ' '), d);
798         free(d);
799         if (verbose)
800                 print_loadopt_str(data, size);
801         else
802                 printf("\n");
803         return true;
804 }
805
806
807 /* Cmd epilogue, or just the default with no args.
808  * The order is [bootnext] bootcurrent, timeout, order, and the bootvars [-v]
809  */
810 static int
811 print_boot_vars(bool verbose)
812 {
813         /*
814          * just read and print the current values
815          * as a command epilogue
816          */
817         struct entry *v;
818         uint8_t *data;
819         size_t size;
820         uint32_t attrs;
821         int ret, bolen;
822         uint16_t *boot_order = NULL, current;
823
824         ret = efi_get_variable(EFI_GLOBAL_GUID, "BootNext", &data, &size, &attrs);
825         if (ret > 0) {
826                 printf("BootNext : %04x\n", le16dec(data));
827         }
828
829         ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
830         current = le16dec(data);
831         printf("BootCurrent: %04x\n", current);
832
833         ret = efi_get_variable(EFI_GLOBAL_GUID, "Timeout", &data, &size, &attrs);
834         if (ret > 0) {
835                 printf("Timeout    : %d seconds\n", le16dec(data));
836         }
837
838         if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) > 0) {
839                 if (size % 2 == 1)
840                         warn("Bad BootOrder variable: odd length %d", (int)size);
841                 boot_order = malloc(size);
842                 bolen = size / 2;
843                 printf("BootOrder  : ");
844                 for (size_t i = 0; i < size; i += 2) {
845                         boot_order[i / 2] = le16dec(data + i);
846                         printf("%04X%s", boot_order[i / 2], i == size - 2 ? "\n" : ", ");
847                 }
848         }
849
850         if (boot_order == NULL) {
851                 /*
852                  * now we want to fetch 'em all fresh again
853                  * which possibly includes a newly created bootvar
854                  */
855                 LIST_FOREACH(v, &efivars, entries) {
856                         print_boot_var(v->name, verbose, v->idx == current);
857                 }
858         } else {
859                 LIST_FOREACH(v, &efivars, entries) {
860                         v->flags = 0;
861                 }
862                 for (int i = 0; i < bolen; i++) {
863                         char buffer[10];
864
865                         snprintf(buffer, sizeof(buffer), "Boot%04X", boot_order[i]);
866                         if (!print_boot_var(buffer, verbose, boot_order[i] == current))
867                                 printf("%s: MISSING!\n", buffer);
868                         LIST_FOREACH(v, &efivars, entries) {
869                                 if (v->idx == boot_order[i]) {
870                                         v->flags |= SEEN;
871                                         break;
872                                 }
873                         }
874                 }
875                 if (verbose) {
876                         printf("\n\nUnreferenced Variables:\n");
877                         LIST_FOREACH(v, &efivars, entries) {
878                                 if (v->flags == 0)
879                                         print_boot_var(v->name, verbose, v->idx == current);
880                         }
881                 }
882         }
883         return 0;
884 }
885
886 static void
887 delete_timeout(void)
888 {
889
890         efi_del_variable(EFI_GLOBAL_GUID,"Timeout");
891 }
892
893 static void
894 handle_timeout(int to)
895 {
896         uint16_t timeout;
897
898         le16enc(&timeout, to);
899         if (set_bootvar("Timeout", (uint8_t *)&timeout, sizeof(timeout)) < 0)
900                 errx(1, "Can't set Timeout for booting.");
901 }
902
903 int
904 main(int argc, char *argv[])
905 {
906
907         if (!efi_variables_supported())
908                 errx(1, "efi variables not supported on this system. root? kldload efirt?");
909
910         memset(&opts, 0, sizeof (bmgr_opts_t));
911         parse_args(argc, argv);
912         read_vars();
913
914         if (opts.create)
915                 /*
916                  * side effect, adds to boot order, but not yet active.
917                  */
918                 make_boot_var(opts.label ? opts.label : "",
919                     opts.loader, opts.kernel, opts.env, opts.dry_run,
920                     opts.has_bootnum ? opts.bootnum : -1, opts.set_active);
921         else if (opts.set_active || opts.set_inactive )
922                 handle_activity(opts.bootnum, opts.set_active);
923         else if (opts.order != NULL)
924                 set_boot_order(opts.order); /* create a new bootorder with opts.order */
925         else if (opts.set_bootnext)
926                 handle_bootnext(opts.bootnum);
927         else if (opts.delete_bootnext)
928                 del_bootnext();
929         else if (opts.delete)
930                 delete_bootvar(opts.bootnum);
931         else if (opts.del_timeout)
932                 delete_timeout();
933         else if (opts.set_timeout)
934                 handle_timeout(opts.timeout);
935
936         print_boot_vars(opts.verbose);
937 }