]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/bootspec.c
4cced23adcbd3303f4c48a1ba537d6c0d38ddee2
[thirdparty/systemd.git] / src / shared / bootspec.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <unistd.h>
4
5 #include "bootspec-fundamental.h"
6 #include "bootspec.h"
7 #include "chase-symlinks.h"
8 #include "conf-files.h"
9 #include "devnum-util.h"
10 #include "dirent-util.h"
11 #include "efi-loader.h"
12 #include "env-file.h"
13 #include "errno-util.h"
14 #include "fd-util.h"
15 #include "fileio.h"
16 #include "find-esp.h"
17 #include "path-util.h"
18 #include "pe-header.h"
19 #include "pretty-print.h"
20 #include "recurse-dir.h"
21 #include "sort-util.h"
22 #include "stat-util.h"
23 #include "string-table.h"
24 #include "strv.h"
25 #include "terminal-util.h"
26 #include "unaligned.h"
27
28 static const char* const boot_entry_type_table[_BOOT_ENTRY_TYPE_MAX] = {
29 [BOOT_ENTRY_CONF] = "Boot Loader Specification Type #1 (.conf)",
30 [BOOT_ENTRY_UNIFIED] = "Boot Loader Specification Type #2 (.efi)",
31 [BOOT_ENTRY_LOADER] = "Reported by Boot Loader",
32 [BOOT_ENTRY_LOADER_AUTO] = "Automatic",
33 };
34
35 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(boot_entry_type, BootEntryType);
36
37 static void boot_entry_free(BootEntry *entry) {
38 assert(entry);
39
40 free(entry->id);
41 free(entry->id_old);
42 free(entry->path);
43 free(entry->root);
44 free(entry->title);
45 free(entry->show_title);
46 free(entry->sort_key);
47 free(entry->version);
48 free(entry->machine_id);
49 free(entry->architecture);
50 strv_free(entry->options);
51 free(entry->kernel);
52 free(entry->efi);
53 strv_free(entry->initrd);
54 free(entry->device_tree);
55 strv_free(entry->device_tree_overlay);
56 }
57
58 static int mangle_path(
59 const char *fname,
60 unsigned line,
61 const char *field,
62 const char *p,
63 char **ret) {
64
65 _cleanup_free_ char *c = NULL;
66
67 assert(field);
68 assert(p);
69 assert(ret);
70
71 /* Spec leaves open if prefixed with "/" or not, let's normalize that */
72 if (path_is_absolute(p))
73 c = strdup(p);
74 else
75 c = strjoin("/", p);
76 if (!c)
77 return -ENOMEM;
78
79 /* We only reference files, never directories */
80 if (endswith(c, "/")) {
81 log_syntax(NULL, LOG_WARNING, fname, line, 0, "Path in field '%s' has trailing slash, ignoring: %s", field, c);
82 *ret = NULL;
83 return 0;
84 }
85
86 /* Remove duplicate "/" */
87 path_simplify(c);
88
89 /* No ".." or "." or so */
90 if (!path_is_normalized(c)) {
91 log_syntax(NULL, LOG_WARNING, fname, line, 0, "Path in field '%s' is not normalized, ignoring: %s", field, c);
92 *ret = NULL;
93 return 0;
94 }
95
96 *ret = TAKE_PTR(c);
97 return 1;
98 }
99
100 static int parse_path_one(
101 const char *fname,
102 unsigned line,
103 const char *field,
104 char **s,
105 const char *p) {
106
107 _cleanup_free_ char *c = NULL;
108 int r;
109
110 assert(field);
111 assert(s);
112 assert(p);
113
114 r = mangle_path(fname, line, field, p, &c);
115 if (r <= 0)
116 return r;
117
118 return free_and_replace(*s, c);
119 }
120
121 static int parse_path_strv(
122 const char *fname,
123 unsigned line,
124 const char *field,
125 char ***s,
126 const char *p) {
127
128 char *c;
129 int r;
130
131 assert(field);
132 assert(s);
133 assert(p);
134
135 r = mangle_path(fname, line, field, p, &c);
136 if (r <= 0)
137 return r;
138
139 return strv_consume(s, c);
140 }
141
142 static int parse_path_many(
143 const char *fname,
144 unsigned line,
145 const char *field,
146 char ***s,
147 const char *p) {
148
149 _cleanup_strv_free_ char **l = NULL, **f = NULL;
150 int r;
151
152 l = strv_split(p, NULL);
153 if (!l)
154 return -ENOMEM;
155
156 STRV_FOREACH(i, l) {
157 char *c;
158
159 r = mangle_path(fname, line, field, *i, &c);
160 if (r < 0)
161 return r;
162 if (r == 0)
163 continue;
164
165 r = strv_consume(&f, c);
166 if (r < 0)
167 return r;
168 }
169
170 return strv_extend_strv(s, f, /* filter_duplicates= */ false);
171 }
172
173 static int parse_tries(const char *fname, const char **p, unsigned *ret) {
174 _cleanup_free_ char *d = NULL;
175 unsigned tries;
176 size_t n;
177 int r;
178
179 assert(fname);
180 assert(p);
181 assert(*p);
182 assert(ret);
183
184 n = strspn(*p, DIGITS);
185 if (n == 0) {
186 *ret = UINT_MAX;
187 return 0;
188 }
189
190 d = strndup(*p, n);
191 if (!d)
192 return log_oom();
193
194 r = safe_atou_full(d, 10, &tries);
195 if (r >= 0 && tries > INT_MAX) /* sd-boot allows INT_MAX, let's use the same limit */
196 r = -ERANGE;
197 if (r < 0)
198 return log_error_errno(r, "Failed to parse tries counter of filename '%s': %m", fname);
199
200 *p = *p + n;
201 *ret = tries;
202 return 1;
203 }
204
205 int boot_filename_extract_tries(
206 const char *fname,
207 char **ret_stripped,
208 unsigned *ret_tries_left,
209 unsigned *ret_tries_done) {
210
211 unsigned tries_left = UINT_MAX, tries_done = UINT_MAX;
212 _cleanup_free_ char *stripped = NULL;
213 const char *p, *suffix, *m;
214 int r;
215
216 assert(fname);
217 assert(ret_stripped);
218 assert(ret_tries_left);
219 assert(ret_tries_done);
220
221 /* Be liberal with suffix, only insist on a dot. After all we want to cover any capitalization here
222 * (vfat is case insensitive after all), and at least .efi and .conf as suffix. */
223 suffix = strrchr(fname, '.');
224 if (!suffix)
225 goto nothing;
226
227 p = m = memrchr(fname, '+', suffix - fname);
228 if (!p)
229 goto nothing;
230 p++;
231
232 r = parse_tries(fname, &p, &tries_left);
233 if (r < 0)
234 return r;
235 if (r == 0)
236 goto nothing;
237
238 if (*p == '-') {
239 p++;
240
241 r = parse_tries(fname, &p, &tries_done);
242 if (r < 0)
243 return r;
244 if (r == 0)
245 goto nothing;
246 }
247
248 if (p != suffix)
249 goto nothing;
250
251 stripped = strndup(fname, m - fname);
252 if (!stripped)
253 return log_oom();
254
255 if (!strextend(&stripped, suffix))
256 return log_oom();
257
258 *ret_stripped = TAKE_PTR(stripped);
259 *ret_tries_left = tries_left;
260 *ret_tries_done = tries_done;
261
262 return 0;
263
264 nothing:
265 stripped = strdup(fname);
266 if (!stripped)
267 return log_oom();
268
269 *ret_stripped = TAKE_PTR(stripped);
270 *ret_tries_left = *ret_tries_done = UINT_MAX;
271 return 0;
272 }
273
274 static int boot_entry_load_type1(
275 FILE *f,
276 const char *root,
277 const char *dir,
278 const char *fname,
279 BootEntry *entry) {
280
281 _cleanup_(boot_entry_free) BootEntry tmp = BOOT_ENTRY_INIT(BOOT_ENTRY_CONF);
282 unsigned line = 1;
283 char *c;
284 int r;
285
286 assert(f);
287 assert(root);
288 assert(dir);
289 assert(fname);
290 assert(entry);
291
292 /* Loads a Type #1 boot menu entry from the specified FILE* object */
293
294 r = boot_filename_extract_tries(fname, &tmp.id, &tmp.tries_left, &tmp.tries_done);
295 if (r < 0)
296 return r;
297
298 if (!efi_loader_entry_name_valid(tmp.id))
299 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid loader entry name: %s", fname);
300
301 c = endswith_no_case(tmp.id, ".conf");
302 if (!c)
303 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid loader entry file suffix: %s", fname);
304
305 tmp.id_old = strndup(tmp.id, c - tmp.id); /* Without .conf suffix */
306 if (!tmp.id_old)
307 return log_oom();
308
309 tmp.path = path_join(dir, fname);
310 if (!tmp.path)
311 return log_oom();
312
313 tmp.root = strdup(root);
314 if (!tmp.root)
315 return log_oom();
316
317 for (;;) {
318 _cleanup_free_ char *buf = NULL, *field = NULL;
319 const char *p;
320
321 r = read_line(f, LONG_LINE_MAX, &buf);
322 if (r == 0)
323 break;
324 if (r == -ENOBUFS)
325 return log_syntax(NULL, LOG_ERR, tmp.path, line, r, "Line too long.");
326 if (r < 0)
327 return log_syntax(NULL, LOG_ERR, tmp.path, line, r, "Error while reading: %m");
328
329 line++;
330
331 p = strstrip(buf);
332 if (IN_SET(p[0], '#', '\0'))
333 continue;
334
335 r = extract_first_word(&p, &field, NULL, 0);
336 if (r < 0) {
337 log_syntax(NULL, LOG_WARNING, tmp.path, line, r, "Failed to parse, ignoring line: %m");
338 continue;
339 }
340 if (r == 0) {
341 log_syntax(NULL, LOG_WARNING, tmp.path, line, 0, "Bad syntax, ignoring line.");
342 continue;
343 }
344
345 if (isempty(p)) {
346 /* Some fields can reasonably have an empty value. In other cases warn. */
347 if (!STR_IN_SET(field, "options", "devicetree-overlay"))
348 log_syntax(NULL, LOG_WARNING, tmp.path, line, 0, "Field '%s' without value, ignoring line.", field);
349
350 continue;
351 }
352
353 if (streq(field, "title"))
354 r = free_and_strdup(&tmp.title, p);
355 else if (streq(field, "sort-key"))
356 r = free_and_strdup(&tmp.sort_key, p);
357 else if (streq(field, "version"))
358 r = free_and_strdup(&tmp.version, p);
359 else if (streq(field, "machine-id"))
360 r = free_and_strdup(&tmp.machine_id, p);
361 else if (streq(field, "architecture"))
362 r = free_and_strdup(&tmp.architecture, p);
363 else if (streq(field, "options"))
364 r = strv_extend(&tmp.options, p);
365 else if (streq(field, "linux"))
366 r = parse_path_one(tmp.path, line, field, &tmp.kernel, p);
367 else if (streq(field, "efi"))
368 r = parse_path_one(tmp.path, line, field, &tmp.efi, p);
369 else if (streq(field, "initrd"))
370 r = parse_path_strv(tmp.path, line, field, &tmp.initrd, p);
371 else if (streq(field, "devicetree"))
372 r = parse_path_one(tmp.path, line, field, &tmp.device_tree, p);
373 else if (streq(field, "devicetree-overlay"))
374 r = parse_path_many(tmp.path, line, field, &tmp.device_tree_overlay, p);
375 else {
376 log_syntax(NULL, LOG_WARNING, tmp.path, line, 0, "Unknown line '%s', ignoring.", field);
377 continue;
378 }
379 if (r < 0)
380 return log_syntax(NULL, LOG_ERR, tmp.path, line, r, "Error while parsing: %m");
381 }
382
383 *entry = tmp;
384 tmp = (BootEntry) {};
385 return 0;
386 }
387
388 int boot_config_load_type1(
389 BootConfig *config,
390 FILE *f,
391 const char *root,
392 const char *dir,
393 const char *fname) {
394 int r;
395
396 assert(config);
397 assert(f);
398 assert(root);
399 assert(dir);
400 assert(fname);
401
402 if (!GREEDY_REALLOC0(config->entries, config->n_entries + 1))
403 return log_oom();
404
405 r = boot_entry_load_type1(f, root, dir, fname, config->entries + config->n_entries);
406 if (r < 0)
407 return r;
408
409 config->n_entries++;
410 return 0;
411 }
412
413 void boot_config_free(BootConfig *config) {
414 assert(config);
415
416 free(config->default_pattern);
417 free(config->timeout);
418 free(config->editor);
419 free(config->auto_entries);
420 free(config->auto_firmware);
421 free(config->console_mode);
422 free(config->beep);
423
424 free(config->entry_oneshot);
425 free(config->entry_default);
426 free(config->entry_selected);
427
428 for (size_t i = 0; i < config->n_entries; i++)
429 boot_entry_free(config->entries + i);
430 free(config->entries);
431
432 set_free(config->inodes_seen);
433 }
434
435 int boot_loader_read_conf(BootConfig *config, FILE *file, const char *path) {
436 unsigned line = 1;
437 int r;
438
439 assert(config);
440 assert(file);
441 assert(path);
442
443 for (;;) {
444 _cleanup_free_ char *buf = NULL, *field = NULL;
445 const char *p;
446
447 r = read_line(file, LONG_LINE_MAX, &buf);
448 if (r == 0)
449 break;
450 if (r == -ENOBUFS)
451 return log_syntax(NULL, LOG_ERR, path, line, r, "Line too long.");
452 if (r < 0)
453 return log_syntax(NULL, LOG_ERR, path, line, r, "Error while reading: %m");
454
455 line++;
456
457 p = strstrip(buf);
458 if (IN_SET(p[0], '#', '\0'))
459 continue;
460
461 r = extract_first_word(&p, &field, NULL, 0);
462 if (r < 0) {
463 log_syntax(NULL, LOG_WARNING, path, line, r, "Failed to parse, ignoring line: %m");
464 continue;
465 }
466 if (r == 0) {
467 log_syntax(NULL, LOG_WARNING, path, line, 0, "Bad syntax, ignoring line.");
468 continue;
469 }
470 if (isempty(p)) {
471 log_syntax(NULL, LOG_WARNING, path, line, 0, "Field '%s' without value, ignoring line.", field);
472 continue;
473 }
474
475 if (streq(field, "default"))
476 r = free_and_strdup(&config->default_pattern, p);
477 else if (streq(field, "timeout"))
478 r = free_and_strdup(&config->timeout, p);
479 else if (streq(field, "editor"))
480 r = free_and_strdup(&config->editor, p);
481 else if (streq(field, "auto-entries"))
482 r = free_and_strdup(&config->auto_entries, p);
483 else if (streq(field, "auto-firmware"))
484 r = free_and_strdup(&config->auto_firmware, p);
485 else if (streq(field, "console-mode"))
486 r = free_and_strdup(&config->console_mode, p);
487 else if (streq(field, "random-seed-mode"))
488 log_syntax(NULL, LOG_WARNING, path, line, 0, "'random-seed-mode' has been deprecated, ignoring.");
489 else if (streq(field, "beep"))
490 r = free_and_strdup(&config->beep, p);
491 else {
492 log_syntax(NULL, LOG_WARNING, path, line, 0, "Unknown line '%s', ignoring.", field);
493 continue;
494 }
495 if (r < 0)
496 return log_syntax(NULL, LOG_ERR, path, line, r, "Error while parsing: %m");
497 }
498
499 return 1;
500 }
501
502 static int boot_loader_read_conf_path(BootConfig *config, const char *root, const char *path) {
503 _cleanup_free_ char *full = NULL;
504 _cleanup_fclose_ FILE *f = NULL;
505 int r;
506
507 assert(config);
508 assert(path);
509
510 r = chase_symlinks_and_fopen_unlocked(path, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, "re", &full, &f);
511 if (r == -ENOENT)
512 return 0;
513 if (r < 0)
514 return log_error_errno(r, "Failed to open '%s/%s': %m", root, path);
515
516 return boot_loader_read_conf(config, f, full);
517 }
518
519 static int boot_entry_compare(const BootEntry *a, const BootEntry *b) {
520 int r;
521
522 assert(a);
523 assert(b);
524
525 r = CMP(!a->sort_key, !b->sort_key);
526 if (r != 0)
527 return r;
528
529 if (a->sort_key && b->sort_key) {
530 r = strcmp(a->sort_key, b->sort_key);
531 if (r != 0)
532 return r;
533
534 r = strcmp_ptr(a->machine_id, b->machine_id);
535 if (r != 0)
536 return r;
537
538 r = -strverscmp_improved(a->version, b->version);
539 if (r != 0)
540 return r;
541 }
542
543 return -strverscmp_improved(a->id, b->id);
544 }
545
546 static int config_check_inode_relevant_and_unseen(BootConfig *config, int fd, const char *fname) {
547 _cleanup_free_ char *d = NULL;
548 struct stat st;
549
550 assert(config);
551 assert(fd >= 0);
552 assert(fname);
553
554 /* So, here's the thing: because of the mess around /efi/ vs. /boot/ vs. /boot/efi/ it might be that
555 * people have these dirs, or subdirs of them symlinked or bind mounted, and we might end up
556 * iterating though some dirs multiple times. Let's thus rather be safe than sorry, and track the
557 * inodes we already processed: let's ignore inodes we have seen already. This should be robust
558 * against any form of symlinking or bind mounting, and effectively suppress any such duplicates. */
559
560 if (fstat(fd, &st) < 0)
561 return log_error_errno(errno, "Failed to stat('%s'): %m", fname);
562 if (!S_ISREG(st.st_mode)) {
563 log_debug("File '%s' is not a reguar file, ignoring.", fname);
564 return false;
565 }
566
567 if (set_contains(config->inodes_seen, &st)) {
568 log_debug("Inode '%s' already seen before, ignoring.", fname);
569 return false;
570 }
571 d = memdup(&st, sizeof(st));
572 if (!d)
573 return log_oom();
574 if (set_ensure_put(&config->inodes_seen, &inode_hash_ops, d) < 0)
575 return log_oom();
576
577 TAKE_PTR(d);
578 return true;
579 }
580
581 static int boot_entries_find_type1(
582 BootConfig *config,
583 const char *root,
584 const char *dir) {
585
586 _cleanup_free_ DirectoryEntries *dentries = NULL;
587 _cleanup_free_ char *full = NULL;
588 _cleanup_close_ int dir_fd = -1;
589 int r;
590
591 assert(config);
592 assert(root);
593 assert(dir);
594
595 dir_fd = chase_symlinks_and_open(dir, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, O_DIRECTORY|O_CLOEXEC, &full);
596 if (dir_fd == -ENOENT)
597 return 0;
598 if (dir_fd < 0)
599 return log_error_errno(dir_fd, "Failed to open '%s/%s': %m", root, dir);
600
601 r = readdir_all(dir_fd, RECURSE_DIR_IGNORE_DOT, &dentries);
602 if (r < 0)
603 return log_error_errno(r, "Failed to read directory '%s': %m", full);
604
605 for (size_t i = 0; i < dentries->n_entries; i++) {
606 const struct dirent *de = dentries->entries[i];
607 _cleanup_fclose_ FILE *f = NULL;
608
609 if (!dirent_is_file(de))
610 continue;
611
612 if (!endswith_no_case(de->d_name, ".conf"))
613 continue;
614
615 r = xfopenat(dir_fd, de->d_name, "re", O_NOFOLLOW|O_NOCTTY, &f);
616 if (r < 0) {
617 log_warning_errno(r, "Failed to open %s/%s, ignoring: %m", full, de->d_name);
618 continue;
619 }
620
621 r = config_check_inode_relevant_and_unseen(config, fileno(f), de->d_name);
622 if (r < 0)
623 return r;
624 if (r == 0) /* inode already seen or otherwise not relevant */
625 continue;
626
627 r = boot_config_load_type1(config, f, root, full, de->d_name);
628 if (r == -ENOMEM) /* ignore all other errors */
629 return r;
630 }
631
632 return 0;
633 }
634
635 static int boot_entry_load_unified(
636 const char *root,
637 const char *path,
638 const char *osrelease,
639 const char *cmdline,
640 BootEntry *ret) {
641
642 _cleanup_free_ char *fname = NULL, *os_pretty_name = NULL, *os_image_id = NULL, *os_name = NULL, *os_id = NULL,
643 *os_image_version = NULL, *os_version = NULL, *os_version_id = NULL, *os_build_id = NULL;
644 _cleanup_(boot_entry_free) BootEntry tmp = BOOT_ENTRY_INIT(BOOT_ENTRY_UNIFIED);
645 const char *k, *good_name, *good_version, *good_sort_key;
646 _cleanup_fclose_ FILE *f = NULL;
647 int r;
648
649 assert(root);
650 assert(path);
651 assert(osrelease);
652
653 k = path_startswith(path, root);
654 if (!k)
655 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not below root: %s", path);
656
657 f = fmemopen_unlocked((void*) osrelease, strlen(osrelease), "r");
658 if (!f)
659 return log_error_errno(errno, "Failed to open os-release buffer: %m");
660
661 r = parse_env_file(f, "os-release",
662 "PRETTY_NAME", &os_pretty_name,
663 "IMAGE_ID", &os_image_id,
664 "NAME", &os_name,
665 "ID", &os_id,
666 "IMAGE_VERSION", &os_image_version,
667 "VERSION", &os_version,
668 "VERSION_ID", &os_version_id,
669 "BUILD_ID", &os_build_id);
670 if (r < 0)
671 return log_error_errno(r, "Failed to parse os-release data from unified kernel image %s: %m", path);
672
673 if (!bootspec_pick_name_version_sort_key(
674 os_pretty_name,
675 os_image_id,
676 os_name,
677 os_id,
678 os_image_version,
679 os_version,
680 os_version_id,
681 os_build_id,
682 &good_name,
683 &good_version,
684 &good_sort_key))
685 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Missing fields in os-release data from unified kernel image %s, refusing.", path);
686
687 r = path_extract_filename(path, &fname);
688 if (r < 0)
689 return log_error_errno(r, "Failed to extract file name from '%s': %m", path);
690
691 r = boot_filename_extract_tries(fname, &tmp.id, &tmp.tries_left, &tmp.tries_done);
692 if (r < 0)
693 return r;
694
695 if (!efi_loader_entry_name_valid(tmp.id))
696 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid loader entry name: %s", tmp.id);
697
698 if (os_id && os_version_id) {
699 tmp.id_old = strjoin(os_id, "-", os_version_id);
700 if (!tmp.id_old)
701 return log_oom();
702 }
703
704 tmp.path = strdup(path);
705 if (!tmp.path)
706 return log_oom();
707
708 tmp.root = strdup(root);
709 if (!tmp.root)
710 return log_oom();
711
712 tmp.kernel = path_make_absolute(k, "/");
713 if (!tmp.kernel)
714 return log_oom();
715
716 tmp.options = strv_new(skip_leading_chars(cmdline, WHITESPACE));
717 if (!tmp.options)
718 return log_oom();
719
720 delete_trailing_chars(tmp.options[0], WHITESPACE);
721
722 tmp.title = strdup(good_name);
723 if (!tmp.title)
724 return log_oom();
725
726 tmp.sort_key = strdup(good_sort_key);
727 if (!tmp.sort_key)
728 return log_oom();
729
730 if (good_version) {
731 tmp.version = strdup(good_version);
732 if (!tmp.version)
733 return log_oom();
734 }
735
736 *ret = tmp;
737 tmp = (BootEntry) {};
738 return 0;
739 }
740
741 /* Maximum PE section we are willing to load (Note that sections we are not interested in may be larger, but
742 * the ones we do care about and we are willing to load into memory have this size limit.) */
743 #define PE_SECTION_SIZE_MAX (4U*1024U*1024U)
744
745 static int find_sections(
746 int fd,
747 const char *path,
748 char **ret_osrelease,
749 char **ret_cmdline) {
750
751 _cleanup_free_ struct PeSectionHeader *sections = NULL;
752 _cleanup_free_ char *osrelease = NULL, *cmdline = NULL;
753 ssize_t n;
754
755 struct DosFileHeader dos;
756 n = pread(fd, &dos, sizeof(dos), 0);
757 if (n < 0)
758 return log_warning_errno(errno, "%s: Failed to read DOS header, ignoring: %m", path);
759 if (n != sizeof(dos))
760 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "%s: Short read while reading DOS header, ignoring.", path);
761
762 if (dos.Magic[0] != 'M' || dos.Magic[1] != 'Z')
763 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: DOS executable magic missing, ignoring.", path);
764
765 uint64_t start = unaligned_read_le32(&dos.ExeHeader);
766
767 struct PeHeader pe;
768 n = pread(fd, &pe, sizeof(pe), start);
769 if (n < 0)
770 return log_warning_errno(errno, "%s: Failed to read PE header, ignoring: %m", path);
771 if (n != sizeof(pe))
772 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "%s: Short read while reading PE header, ignoring.", path);
773
774 if (pe.Magic[0] != 'P' || pe.Magic[1] != 'E' || pe.Magic[2] != 0 || pe.Magic[3] != 0)
775 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: PE executable magic missing, ignoring.", path);
776
777 size_t n_sections = unaligned_read_le16(&pe.FileHeader.NumberOfSections);
778 if (n_sections > 96)
779 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: PE header has too many sections, ignoring.", path);
780
781 sections = new(struct PeSectionHeader, n_sections);
782 if (!sections)
783 return log_oom();
784
785 n = pread(fd, sections,
786 n_sections * sizeof(struct PeSectionHeader),
787 start + sizeof(pe) + unaligned_read_le16(&pe.FileHeader.SizeOfOptionalHeader));
788 if (n < 0)
789 return log_warning_errno(errno, "%s: Failed to read section data, ignoring: %m", path);
790 if ((size_t) n != n_sections * sizeof(struct PeSectionHeader))
791 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "%s: Short read while reading sections, ignoring.", path);
792
793 for (size_t i = 0; i < n_sections; i++) {
794 _cleanup_free_ char *k = NULL;
795 uint32_t offset, size;
796 char **b;
797
798 if (strneq((char*) sections[i].Name, ".osrel", sizeof(sections[i].Name)))
799 b = &osrelease;
800 else if (strneq((char*) sections[i].Name, ".cmdline", sizeof(sections[i].Name)))
801 b = &cmdline;
802 else
803 continue;
804
805 if (*b)
806 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: Duplicate section %s, ignoring.", path, sections[i].Name);
807
808 offset = unaligned_read_le32(&sections[i].PointerToRawData);
809 size = unaligned_read_le32(&sections[i].VirtualSize);
810
811 if (size > PE_SECTION_SIZE_MAX)
812 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: Section %s too large, ignoring.", path, sections[i].Name);
813
814 k = new(char, size+1);
815 if (!k)
816 return log_oom();
817
818 n = pread(fd, k, size, offset);
819 if (n < 0)
820 return log_warning_errno(errno, "%s: Failed to read section payload, ignoring: %m", path);
821 if ((size_t) n != size)
822 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "%s: Short read while reading section payload, ignoring:", path);
823
824 /* Allow one trailing NUL byte, but nothing more. */
825 if (size > 0 && memchr(k, 0, size - 1))
826 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: Section contains embedded NUL byte, ignoring.", path);
827
828 k[size] = 0;
829 *b = TAKE_PTR(k);
830 }
831
832 if (!osrelease)
833 return log_warning_errno(SYNTHETIC_ERRNO(EBADMSG), "%s: Image lacks .osrel section, ignoring.", path);
834
835 if (ret_osrelease)
836 *ret_osrelease = TAKE_PTR(osrelease);
837 if (ret_cmdline)
838 *ret_cmdline = TAKE_PTR(cmdline);
839
840 return 0;
841 }
842
843 static int boot_entries_find_unified(
844 BootConfig *config,
845 const char *root,
846 const char *dir) {
847
848 _cleanup_(closedirp) DIR *d = NULL;
849 _cleanup_free_ char *full = NULL;
850 int r;
851
852 assert(config);
853 assert(dir);
854
855 r = chase_symlinks_and_opendir(dir, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &full, &d);
856 if (r == -ENOENT)
857 return 0;
858 if (r < 0)
859 return log_error_errno(r, "Failed to open '%s/%s': %m", root, dir);
860
861 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read %s: %m", full)) {
862 _cleanup_free_ char *j = NULL, *osrelease = NULL, *cmdline = NULL;
863 _cleanup_close_ int fd = -1;
864
865 if (!dirent_is_file(de))
866 continue;
867
868 if (!endswith_no_case(de->d_name, ".efi"))
869 continue;
870
871 if (!GREEDY_REALLOC0(config->entries, config->n_entries + 1))
872 return log_oom();
873
874 fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOFOLLOW|O_NOCTTY);
875 if (fd < 0) {
876 log_warning_errno(errno, "Failed to open %s/%s, ignoring: %m", full, de->d_name);
877 continue;
878 }
879
880 r = config_check_inode_relevant_and_unseen(config, fd, de->d_name);
881 if (r < 0)
882 return r;
883 if (r == 0) /* inode already seen or otherwise not relevant */
884 continue;
885
886 j = path_join(full, de->d_name);
887 if (!j)
888 return log_oom();
889
890 if (find_sections(fd, j, &osrelease, &cmdline) < 0)
891 continue;
892
893 r = boot_entry_load_unified(root, j, osrelease, cmdline, config->entries + config->n_entries);
894 if (r < 0)
895 continue;
896
897 config->n_entries++;
898 }
899
900 return 0;
901 }
902
903 static bool find_nonunique(const BootEntry *entries, size_t n_entries, bool arr[]) {
904 bool non_unique = false;
905
906 assert(entries || n_entries == 0);
907 assert(arr || n_entries == 0);
908
909 for (size_t i = 0; i < n_entries; i++)
910 arr[i] = false;
911
912 for (size_t i = 0; i < n_entries; i++)
913 for (size_t j = 0; j < n_entries; j++)
914 if (i != j && streq(boot_entry_title(entries + i),
915 boot_entry_title(entries + j)))
916 non_unique = arr[i] = arr[j] = true;
917
918 return non_unique;
919 }
920
921 static int boot_entries_uniquify(BootEntry *entries, size_t n_entries) {
922 _cleanup_free_ bool *arr = NULL;
923 char *s;
924
925 assert(entries || n_entries == 0);
926
927 if (n_entries == 0)
928 return 0;
929
930 arr = new(bool, n_entries);
931 if (!arr)
932 return -ENOMEM;
933
934 /* Find _all_ non-unique titles */
935 if (!find_nonunique(entries, n_entries, arr))
936 return 0;
937
938 /* Add version to non-unique titles */
939 for (size_t i = 0; i < n_entries; i++)
940 if (arr[i] && entries[i].version) {
941 if (asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].version) < 0)
942 return -ENOMEM;
943
944 free_and_replace(entries[i].show_title, s);
945 }
946
947 if (!find_nonunique(entries, n_entries, arr))
948 return 0;
949
950 /* Add machine-id to non-unique titles */
951 for (size_t i = 0; i < n_entries; i++)
952 if (arr[i] && entries[i].machine_id) {
953 if (asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].machine_id) < 0)
954 return -ENOMEM;
955
956 free_and_replace(entries[i].show_title, s);
957 }
958
959 if (!find_nonunique(entries, n_entries, arr))
960 return 0;
961
962 /* Add file name to non-unique titles */
963 for (size_t i = 0; i < n_entries; i++)
964 if (arr[i]) {
965 if (asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].id) < 0)
966 return -ENOMEM;
967
968 free_and_replace(entries[i].show_title, s);
969 }
970
971 return 0;
972 }
973
974 static int boot_config_find(const BootConfig *config, const char *id) {
975 assert(config);
976
977 if (!id)
978 return -1;
979
980 if (id[0] == '@') {
981 if (!strcaseeq(id, "@saved"))
982 return -1;
983 if (!config->entry_selected)
984 return -1;
985 id = config->entry_selected;
986 }
987
988 for (size_t i = 0; i < config->n_entries; i++)
989 if (fnmatch(id, config->entries[i].id, FNM_CASEFOLD) == 0)
990 return i;
991
992 return -1;
993 }
994
995 static int boot_entries_select_default(const BootConfig *config) {
996 int i;
997
998 assert(config);
999 assert(config->entries || config->n_entries == 0);
1000
1001 if (config->n_entries == 0) {
1002 log_debug("Found no default boot entry :(");
1003 return -1; /* -1 means "no default" */
1004 }
1005
1006 if (config->entry_oneshot) {
1007 i = boot_config_find(config, config->entry_oneshot);
1008 if (i >= 0) {
1009 log_debug("Found default: id \"%s\" is matched by LoaderEntryOneShot",
1010 config->entries[i].id);
1011 return i;
1012 }
1013 }
1014
1015 if (config->entry_default) {
1016 i = boot_config_find(config, config->entry_default);
1017 if (i >= 0) {
1018 log_debug("Found default: id \"%s\" is matched by LoaderEntryDefault",
1019 config->entries[i].id);
1020 return i;
1021 }
1022 }
1023
1024 if (config->default_pattern) {
1025 i = boot_config_find(config, config->default_pattern);
1026 if (i >= 0) {
1027 log_debug("Found default: id \"%s\" is matched by pattern \"%s\"",
1028 config->entries[i].id, config->default_pattern);
1029 return i;
1030 }
1031 }
1032
1033 log_debug("Found default: first entry \"%s\"", config->entries[0].id);
1034 return 0;
1035 }
1036
1037 static int boot_entries_select_selected(const BootConfig *config) {
1038 assert(config);
1039 assert(config->entries || config->n_entries == 0);
1040
1041 if (!config->entry_selected || config->n_entries == 0)
1042 return -1;
1043
1044 return boot_config_find(config, config->entry_selected);
1045 }
1046
1047 static int boot_load_efi_entry_pointers(BootConfig *config, bool skip_efivars) {
1048 int r;
1049
1050 assert(config);
1051
1052 if (skip_efivars || !is_efi_boot())
1053 return 0;
1054
1055 /* Loads the three "pointers" to boot loader entries from their EFI variables */
1056
1057 r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderEntryOneShot), &config->entry_oneshot);
1058 if (r == -ENOMEM)
1059 return log_oom();
1060 if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
1061 log_warning_errno(r, "Failed to read EFI variable \"LoaderEntryOneShot\", ignoring: %m");
1062
1063 r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderEntryDefault), &config->entry_default);
1064 if (r == -ENOMEM)
1065 return log_oom();
1066 if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
1067 log_warning_errno(r, "Failed to read EFI variable \"LoaderEntryDefault\", ignoring: %m");
1068
1069 r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderEntrySelected), &config->entry_selected);
1070 if (r == -ENOMEM)
1071 return log_oom();
1072 if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
1073 log_warning_errno(r, "Failed to read EFI variable \"LoaderEntrySelected\", ignoring: %m");
1074
1075 return 1;
1076 }
1077
1078 int boot_config_select_special_entries(BootConfig *config, bool skip_efivars) {
1079 int r;
1080
1081 assert(config);
1082
1083 r = boot_load_efi_entry_pointers(config, skip_efivars);
1084 if (r < 0)
1085 return r;
1086
1087 config->default_entry = boot_entries_select_default(config);
1088 config->selected_entry = boot_entries_select_selected(config);
1089
1090 return 0;
1091 }
1092
1093 int boot_config_finalize(BootConfig *config) {
1094 int r;
1095
1096 typesafe_qsort(config->entries, config->n_entries, boot_entry_compare);
1097
1098 r = boot_entries_uniquify(config->entries, config->n_entries);
1099 if (r < 0)
1100 return log_error_errno(r, "Failed to uniquify boot entries: %m");
1101
1102 return 0;
1103 }
1104
1105 int boot_config_load(
1106 BootConfig *config,
1107 const char *esp_path,
1108 const char *xbootldr_path) {
1109
1110 int r;
1111
1112 assert(config);
1113
1114 if (esp_path) {
1115 r = boot_loader_read_conf_path(config, esp_path, "/loader/loader.conf");
1116 if (r < 0)
1117 return r;
1118
1119 r = boot_entries_find_type1(config, esp_path, "/loader/entries");
1120 if (r < 0)
1121 return r;
1122
1123 r = boot_entries_find_unified(config, esp_path, "/EFI/Linux/");
1124 if (r < 0)
1125 return r;
1126 }
1127
1128 if (xbootldr_path) {
1129 r = boot_entries_find_type1(config, xbootldr_path, "/loader/entries");
1130 if (r < 0)
1131 return r;
1132
1133 r = boot_entries_find_unified(config, xbootldr_path, "/EFI/Linux/");
1134 if (r < 0)
1135 return r;
1136 }
1137
1138 return boot_config_finalize(config);
1139 }
1140
1141 int boot_config_load_auto(
1142 BootConfig *config,
1143 const char *override_esp_path,
1144 const char *override_xbootldr_path) {
1145
1146 _cleanup_free_ char *esp_where = NULL, *xbootldr_where = NULL;
1147 dev_t esp_devid = 0, xbootldr_devid = 0;
1148 int r;
1149
1150 assert(config);
1151
1152 /* This function is similar to boot_entries_load_config(), however we automatically search for the
1153 * ESP and the XBOOTLDR partition unless it is explicitly specified. Also, if the user did not pass
1154 * an ESP or XBOOTLDR path directly, let's see if /run/boot-loader-entries/ exists. If so, let's
1155 * read data from there, as if it was an ESP (i.e. loading both entries and loader.conf data from
1156 * it). This allows other boot loaders to pass boot loader entry information to our tools if they
1157 * want to. */
1158
1159 if (!override_esp_path && !override_xbootldr_path) {
1160 if (access("/run/boot-loader-entries/", F_OK) >= 0)
1161 return boot_config_load(config, "/run/boot-loader-entries/", NULL);
1162
1163 if (errno != ENOENT)
1164 return log_error_errno(errno,
1165 "Failed to determine whether /run/boot-loader-entries/ exists: %m");
1166 }
1167
1168 r = find_esp_and_warn(NULL, override_esp_path, /* unprivileged_mode= */ false, &esp_where, NULL, NULL, NULL, NULL, &esp_devid);
1169 if (r < 0) /* we don't log about ENOKEY here, but propagate it, leaving it to the caller to log */
1170 return r;
1171
1172 r = find_xbootldr_and_warn(NULL, override_xbootldr_path, /* unprivileged_mode= */ false, &xbootldr_where, NULL, &xbootldr_devid);
1173 if (r < 0 && r != -ENOKEY)
1174 return r; /* It's fine if the XBOOTLDR partition doesn't exist, hence we ignore ENOKEY here */
1175
1176 /* If both paths actually refer to the same inode, suppress the xbootldr path */
1177 if (esp_where && xbootldr_where && devnum_set_and_equal(esp_devid, xbootldr_devid))
1178 xbootldr_where = mfree(xbootldr_where);
1179
1180 return boot_config_load(config, esp_where, xbootldr_where);
1181 }
1182
1183 int boot_config_augment_from_loader(
1184 BootConfig *config,
1185 char **found_by_loader,
1186 bool only_auto) {
1187
1188 static const char *const title_table[] = {
1189 /* Pretty names for a few well-known automatically discovered entries. */
1190 "auto-osx", "macOS",
1191 "auto-windows", "Windows Boot Manager",
1192 "auto-efi-shell", "EFI Shell",
1193 "auto-efi-default", "EFI Default Loader",
1194 "auto-reboot-to-firmware-setup", "Reboot Into Firmware Interface",
1195 NULL,
1196 };
1197
1198 assert(config);
1199
1200 /* Let's add the entries discovered by the boot loader to the end of our list, unless they are
1201 * already included there. */
1202
1203 STRV_FOREACH(i, found_by_loader) {
1204 BootEntry *existing;
1205 _cleanup_free_ char *c = NULL, *t = NULL, *p = NULL;
1206
1207 existing = boot_config_find_entry(config, *i);
1208 if (existing) {
1209 existing->reported_by_loader = true;
1210 continue;
1211 }
1212
1213 if (only_auto && !startswith(*i, "auto-"))
1214 continue;
1215
1216 c = strdup(*i);
1217 if (!c)
1218 return log_oom();
1219
1220 STRV_FOREACH_PAIR(a, b, title_table)
1221 if (streq(*a, *i)) {
1222 t = strdup(*b);
1223 if (!t)
1224 return log_oom();
1225 break;
1226 }
1227
1228 p = strdup(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderEntries)));
1229 if (!p)
1230 return log_oom();
1231
1232 if (!GREEDY_REALLOC0(config->entries, config->n_entries + 1))
1233 return log_oom();
1234
1235 config->entries[config->n_entries++] = (BootEntry) {
1236 .type = startswith(*i, "auto-") ? BOOT_ENTRY_LOADER_AUTO : BOOT_ENTRY_LOADER,
1237 .id = TAKE_PTR(c),
1238 .title = TAKE_PTR(t),
1239 .path = TAKE_PTR(p),
1240 .reported_by_loader = true,
1241 .tries_left = UINT_MAX,
1242 .tries_done = UINT_MAX,
1243 };
1244 }
1245
1246 return 0;
1247 }
1248
1249 BootEntry* boot_config_find_entry(BootConfig *config, const char *id) {
1250 assert(config);
1251 assert(id);
1252
1253 for (size_t j = 0; j < config->n_entries; j++)
1254 if (streq_ptr(config->entries[j].id, id) ||
1255 streq_ptr(config->entries[j].id_old, id))
1256 return config->entries + j;
1257
1258 return NULL;
1259 }
1260
1261 static void boot_entry_file_list(
1262 const char *field,
1263 const char *root,
1264 const char *p,
1265 int *ret_status) {
1266
1267 assert(p);
1268 assert(ret_status);
1269
1270 int status = chase_symlinks_and_access(p, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, F_OK, NULL, NULL);
1271
1272 /* Note that this shows two '/' between the root and the file. This is intentional to highlight (in
1273 * the absence of color support) to the user that the boot loader is only interested in the second
1274 * part of the file. */
1275 printf("%13s%s %s%s/%s", strempty(field), field ? ":" : " ", ansi_grey(), root, ansi_normal());
1276
1277 if (status < 0) {
1278 errno = -status;
1279 printf("%s%s%s (%m)\n", ansi_highlight_red(), p, ansi_normal());
1280 } else
1281 printf("%s\n", p);
1282
1283 if (*ret_status == 0 && status < 0)
1284 *ret_status = status;
1285 }
1286
1287 int show_boot_entry(
1288 const BootEntry *e,
1289 bool show_as_default,
1290 bool show_as_selected,
1291 bool show_reported) {
1292
1293 int status = 0;
1294
1295 /* Returns 0 on success, negative on processing error, and positive if something is wrong with the
1296 boot entry itself. */
1297
1298 assert(e);
1299
1300 printf(" type: %s\n",
1301 boot_entry_type_to_string(e->type));
1302
1303 printf(" title: %s%s%s",
1304 ansi_highlight(), boot_entry_title(e), ansi_normal());
1305
1306 if (show_as_default)
1307 printf(" %s(default)%s",
1308 ansi_highlight_green(), ansi_normal());
1309
1310 if (show_as_selected)
1311 printf(" %s(selected)%s",
1312 ansi_highlight_magenta(), ansi_normal());
1313
1314 if (show_reported) {
1315 if (e->type == BOOT_ENTRY_LOADER)
1316 printf(" %s(reported/absent)%s",
1317 ansi_highlight_red(), ansi_normal());
1318 else if (!e->reported_by_loader && e->type != BOOT_ENTRY_LOADER_AUTO)
1319 printf(" %s(not reported/new)%s",
1320 ansi_highlight_green(), ansi_normal());
1321 }
1322
1323 putchar('\n');
1324
1325 if (e->id)
1326 printf(" id: %s\n", e->id);
1327 if (e->path) {
1328 _cleanup_free_ char *text = NULL, *link = NULL;
1329
1330 const char *p = e->root ? path_startswith(e->path, e->root) : NULL;
1331 if (p) {
1332 text = strjoin(ansi_grey(), e->root, "/", ansi_normal(), "/", p);
1333 if (!text)
1334 return log_oom();
1335 }
1336
1337 /* Let's urlify the link to make it easy to view in an editor, but only if it is a text
1338 * file. Unified images are binary ELFs, and EFI variables are not pure text either. */
1339 if (e->type == BOOT_ENTRY_CONF)
1340 (void) terminal_urlify_path(e->path, text, &link);
1341
1342 printf(" source: %s\n", link ?: text ?: e->path);
1343 }
1344 if (e->tries_left != UINT_MAX) {
1345 printf(" tries: %u left", e->tries_left);
1346
1347 if (e->tries_done != UINT_MAX)
1348 printf("; %u done\n", e->tries_done);
1349 else
1350 printf("\n");
1351 }
1352
1353 if (e->sort_key)
1354 printf(" sort-key: %s\n", e->sort_key);
1355 if (e->version)
1356 printf(" version: %s\n", e->version);
1357 if (e->machine_id)
1358 printf(" machine-id: %s\n", e->machine_id);
1359 if (e->architecture)
1360 printf(" architecture: %s\n", e->architecture);
1361 if (e->kernel)
1362 boot_entry_file_list("linux", e->root, e->kernel, &status);
1363
1364 STRV_FOREACH(s, e->initrd)
1365 boot_entry_file_list(s == e->initrd ? "initrd" : NULL,
1366 e->root,
1367 *s,
1368 &status);
1369
1370 if (!strv_isempty(e->options)) {
1371 _cleanup_free_ char *t = NULL, *t2 = NULL;
1372 _cleanup_strv_free_ char **ts = NULL;
1373
1374 t = strv_join(e->options, " ");
1375 if (!t)
1376 return log_oom();
1377
1378 ts = strv_split_newlines(t);
1379 if (!ts)
1380 return log_oom();
1381
1382 t2 = strv_join(ts, "\n ");
1383 if (!t2)
1384 return log_oom();
1385
1386 printf(" options: %s\n", t2);
1387 }
1388
1389 if (e->device_tree)
1390 boot_entry_file_list("devicetree", e->root, e->device_tree, &status);
1391
1392 STRV_FOREACH(s, e->device_tree_overlay)
1393 boot_entry_file_list(s == e->device_tree_overlay ? "devicetree-overlay" : NULL,
1394 e->root,
1395 *s,
1396 &status);
1397
1398 return -status;
1399 }
1400
1401 int show_boot_entries(const BootConfig *config, JsonFormatFlags json_format) {
1402 int r;
1403
1404 assert(config);
1405
1406 if (!FLAGS_SET(json_format, JSON_FORMAT_OFF)) {
1407 _cleanup_(json_variant_unrefp) JsonVariant *array = NULL;
1408
1409 for (size_t i = 0; i < config->n_entries; i++) {
1410 _cleanup_free_ char *opts = NULL;
1411 const BootEntry *e = config->entries + i;
1412 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
1413
1414 if (!strv_isempty(e->options)) {
1415 opts = strv_join(e->options, " ");
1416 if (!opts)
1417 return log_oom();
1418 }
1419
1420 r = json_append(&v, JSON_BUILD_OBJECT(
1421 JSON_BUILD_PAIR_CONDITION(e->id, "id", JSON_BUILD_STRING(e->id)),
1422 JSON_BUILD_PAIR_CONDITION(e->path, "path", JSON_BUILD_STRING(e->path)),
1423 JSON_BUILD_PAIR_CONDITION(e->root, "root", JSON_BUILD_STRING(e->root)),
1424 JSON_BUILD_PAIR_CONDITION(e->title, "title", JSON_BUILD_STRING(e->title)),
1425 JSON_BUILD_PAIR_CONDITION(boot_entry_title(e), "showTitle", JSON_BUILD_STRING(boot_entry_title(e))),
1426 JSON_BUILD_PAIR_CONDITION(e->sort_key, "sortKey", JSON_BUILD_STRING(e->sort_key)),
1427 JSON_BUILD_PAIR_CONDITION(e->version, "version", JSON_BUILD_STRING(e->version)),
1428 JSON_BUILD_PAIR_CONDITION(e->machine_id, "machineId", JSON_BUILD_STRING(e->machine_id)),
1429 JSON_BUILD_PAIR_CONDITION(e->architecture, "architecture", JSON_BUILD_STRING(e->architecture)),
1430 JSON_BUILD_PAIR_CONDITION(opts, "options", JSON_BUILD_STRING(opts)),
1431 JSON_BUILD_PAIR_CONDITION(e->kernel, "linux", JSON_BUILD_STRING(e->kernel)),
1432 JSON_BUILD_PAIR_CONDITION(e->efi, "efi", JSON_BUILD_STRING(e->efi)),
1433 JSON_BUILD_PAIR_CONDITION(!strv_isempty(e->initrd), "initrd", JSON_BUILD_STRV(e->initrd)),
1434 JSON_BUILD_PAIR_CONDITION(e->device_tree, "devicetree", JSON_BUILD_STRING(e->device_tree)),
1435 JSON_BUILD_PAIR_CONDITION(!strv_isempty(e->device_tree_overlay), "devicetreeOverlay", JSON_BUILD_STRV(e->device_tree_overlay))));
1436 if (r < 0)
1437 return log_oom();
1438
1439 /* Sanitizers (only memory sanitizer?) do not like function call with too many
1440 * arguments and trigger false positive warnings. Let's not add too many json objects
1441 * at once. */
1442 r = json_append(&v, JSON_BUILD_OBJECT(
1443 JSON_BUILD_PAIR_CONDITION(e->tries_left != UINT_MAX, "triesLeft", JSON_BUILD_UNSIGNED(e->tries_left)),
1444 JSON_BUILD_PAIR_CONDITION(e->tries_done != UINT_MAX, "triesDone", JSON_BUILD_UNSIGNED(e->tries_done))));
1445 if (r < 0)
1446 return log_oom();
1447
1448 r = json_variant_append_array(&array, v);
1449 if (r < 0)
1450 return log_oom();
1451 }
1452
1453 json_variant_dump(array, json_format | JSON_FORMAT_EMPTY_ARRAY, NULL, NULL);
1454
1455 } else {
1456 for (size_t n = 0; n < config->n_entries; n++) {
1457 r = show_boot_entry(
1458 config->entries + n,
1459 /* show_as_default= */ n == (size_t) config->default_entry,
1460 /* show_as_selected= */ n == (size_t) config->selected_entry,
1461 /* show_discovered= */ true);
1462 if (r < 0)
1463 return r;
1464
1465 if (n+1 < config->n_entries)
1466 putchar('\n');
1467 }
1468 }
1469
1470 return 0;
1471 }