• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 23672908348

27 Mar 2026 10:16PM UTC coverage: 72.401% (+0.3%) from 72.113%
23672908348

push

github

daandemeyer
boot-entry: add 'auto' keyword to parse_boot_entry_token_type

Add the auto keyword as documented in the help message and man pages of
`kernel-install`, `bootctl` and `systemd-pcrlock`.

0 of 4 new or added lines in 1 file covered. (0.0%)

2759 existing lines in 71 files now uncovered.

318227 of 439535 relevant lines covered (72.4%)

1197709.62 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

71.62
/src/shared/bootspec.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <fnmatch.h>
4
#include <unistd.h>
5

6
#include "sd-json.h"
7

8
#include "alloc-util.h"
9
#include "bootspec.h"
10
#include "bootspec-fundamental.h"
11
#include "chase.h"
12
#include "devnum-util.h"
13
#include "dirent-util.h"
14
#include "efi-loader.h"
15
#include "efivars.h"
16
#include "env-file.h"
17
#include "extract-word.h"
18
#include "fd-util.h"
19
#include "fileio.h"
20
#include "find-esp.h"
21
#include "log.h"
22
#include "parse-util.h"
23
#include "path-util.h"
24
#include "pe-binary.h"
25
#include "pretty-print.h"
26
#include "recurse-dir.h"
27
#include "set.h"
28
#include "sort-util.h"
29
#include "stat-util.h"
30
#include "string-table.h"
31
#include "string-util.h"
32
#include "strv.h"
33
#include "uki.h"
34

35
static const char* const boot_entry_type_description_table[_BOOT_ENTRY_TYPE_MAX] = {
36
        [BOOT_ENTRY_TYPE1]  = "Boot Loader Specification Type #1 (.conf)",
37
        [BOOT_ENTRY_TYPE2]  = "Boot Loader Specification Type #2 (UKI, .efi)",
38
        [BOOT_ENTRY_LOADER] = "Reported by Boot Loader",
39
        [BOOT_ENTRY_AUTO]   = "Automatic",
40
};
41

42
DEFINE_STRING_TABLE_LOOKUP_TO_STRING(boot_entry_type_description, BootEntryType);
20✔
43

44
static const char* const boot_entry_type_table[_BOOT_ENTRY_TYPE_MAX] = {
45
        [BOOT_ENTRY_TYPE1]  = "type1",
46
        [BOOT_ENTRY_TYPE2]  = "type2",
47
        [BOOT_ENTRY_LOADER] = "loader",
48
        [BOOT_ENTRY_AUTO]   = "auto",
49
};
50

51
DEFINE_STRING_TABLE_LOOKUP(boot_entry_type, BootEntryType);
22✔
52

53
static const char* const boot_entry_source_description_table[_BOOT_ENTRY_SOURCE_MAX] = {
54
        [BOOT_ENTRY_ESP]      = "EFI System Partition",
55
        [BOOT_ENTRY_XBOOTLDR] = "Extended Boot Loader Partition",
56
};
57

58
DEFINE_STRING_TABLE_LOOKUP_TO_STRING(boot_entry_source_description, BootEntrySource);
20✔
59

60
static const char* const boot_entry_source_table[_BOOT_ENTRY_SOURCE_MAX] = {
61
        [BOOT_ENTRY_ESP]      = "esp",
62
        [BOOT_ENTRY_XBOOTLDR] = "xbootldr",
63
};
64

65
DEFINE_STRING_TABLE_LOOKUP_TO_STRING(boot_entry_source, BootEntrySource);
16✔
66

67
static void boot_entry_addons_done(BootEntryAddons *addons) {
267✔
68
        assert(addons);
267✔
69

70
        FOREACH_ARRAY(addon, addons->items, addons->n_items) {
277✔
71
                free(addon->cmdline);
10✔
72
                free(addon->location);
10✔
73
        }
74
        addons->items = mfree(addons->items);
267✔
75
        addons->n_items = 0;
267✔
76
}
267✔
77

78
static void boot_entry_free(BootEntry *entry) {
124✔
79
        assert(entry);
124✔
80

81
        free(entry->id);
124✔
82
        free(entry->id_old);
124✔
83
        free(entry->id_without_profile);
124✔
84
        free(entry->path);
124✔
85
        free(entry->root);
124✔
86
        free(entry->title);
124✔
87
        free(entry->show_title);
124✔
88
        free(entry->sort_key);
124✔
89
        free(entry->version);
124✔
90
        free(entry->machine_id);
124✔
91
        free(entry->architecture);
124✔
92
        strv_free(entry->options);
124✔
93
        boot_entry_addons_done(&entry->local_addons);
124✔
94
        free(entry->kernel);
124✔
95
        free(entry->efi);
124✔
96
        free(entry->uki);
124✔
97
        free(entry->uki_url);
124✔
98
        strv_free(entry->initrd);
124✔
99
        free(entry->device_tree);
124✔
100
        strv_free(entry->device_tree_overlay);
124✔
101
}
124✔
102

103
static int mangle_path(
×
104
                const char *fname,
105
                unsigned line,
106
                const char *field,
107
                const char *p,
108
                char **ret) {
109

110
        _cleanup_free_ char *c = NULL;
×
111

112
        assert(field);
×
113
        assert(p);
×
114
        assert(ret);
×
115

116
        /* Spec leaves open if prefixed with "/" or not, let's normalize that */
117
        c = path_make_absolute(p, "/");
×
118
        if (!c)
×
119
                return -ENOMEM;
120

121
        /* We only reference files, never directories */
122
        if (endswith(c, "/")) {
×
123
                log_syntax(NULL, LOG_WARNING, fname, line, 0, "Path in field '%s' has trailing slash, ignoring: %s", field, c);
×
124
                *ret = NULL;
×
125
                return 0;
×
126
        }
127

128
        /* Remove duplicate "/" */
129
        path_simplify(c);
×
130

131
        /* No ".." or "." or so */
132
        if (!path_is_normalized(c)) {
×
133
                log_syntax(NULL, LOG_WARNING, fname, line, 0, "Path in field '%s' is not normalized, ignoring: %s", field, c);
×
134
                *ret = NULL;
×
135
                return 0;
×
136
        }
137

138
        *ret = TAKE_PTR(c);
×
139
        return 1;
×
140
}
141

142
static int parse_path_one(
×
143
                const char *fname,
144
                unsigned line,
145
                const char *field,
146
                char **s,
147
                const char *p) {
148

149
        _cleanup_free_ char *c = NULL;
×
150
        int r;
×
151

152
        assert(field);
×
153
        assert(s);
×
154
        assert(p);
×
155

156
        r = mangle_path(fname, line, field, p, &c);
×
157
        if (r <= 0)
×
158
                return r;
159

160
        return free_and_replace(*s, c);
×
161
}
162

163
static int parse_path_strv(
×
164
                const char *fname,
165
                unsigned line,
166
                const char *field,
167
                char ***s,
168
                const char *p) {
169

170
        char *c;
×
171
        int r;
×
172

173
        assert(field);
×
174
        assert(s);
×
175
        assert(p);
×
176

177
        r = mangle_path(fname, line, field, p, &c);
×
178
        if (r <= 0)
×
179
                return r;
×
180

181
        return strv_consume(s, c);
×
182
}
183

184
static int parse_path_many(
×
185
                const char *fname,
186
                unsigned line,
187
                const char *field,
188
                char ***s,
189
                const char *p) {
190

191
        _cleanup_strv_free_ char **l = NULL, **f = NULL;
×
192
        int r;
×
193

194
        l = strv_split(p, NULL);
×
195
        if (!l)
×
196
                return -ENOMEM;
197

198
        STRV_FOREACH(i, l) {
×
199
                char *c;
×
200

201
                r = mangle_path(fname, line, field, *i, &c);
×
202
                if (r < 0)
×
203
                        return r;
×
204
                if (r == 0)
×
205
                        continue;
×
206

207
                r = strv_consume(&f, c);
×
208
                if (r < 0)
×
209
                        return r;
210
        }
211

212
        return strv_extend_strv_consume(s, TAKE_PTR(f), /* filter_duplicates= */ false);
×
213
}
214

215
static int parse_tries(const char *fname, const char **p, unsigned *ret) {
36✔
216
        _cleanup_free_ char *d = NULL;
36✔
217
        unsigned tries;
36✔
218
        size_t n;
36✔
219
        int r;
36✔
220

221
        assert(fname);
36✔
222
        assert(p);
36✔
223
        assert(*p);
36✔
224
        assert(ret);
36✔
225

226
        n = strspn(*p, DIGITS);
36✔
227
        if (n == 0) {
36✔
228
                *ret = UINT_MAX;
2✔
229
                return 0;
2✔
230
        }
231

232
        d = strndup(*p, n);
34✔
233
        if (!d)
34✔
234
                return log_oom();
×
235

236
        r = safe_atou_full(d, 10, &tries);
34✔
237
        if (r >= 0 && tries > INT_MAX) /* sd-boot allows INT_MAX, let's use the same limit */
34✔
238
                r = -ERANGE;
239
        if (r < 0)
32✔
240
                return log_error_errno(r, "Failed to parse tries counter of filename '%s': %m", fname);
2✔
241

242
        *p = *p + n;
32✔
243
        *ret = tries;
32✔
244
        return 1;
32✔
245
}
246

247
int boot_filename_extract_tries(
67✔
248
                const char *fname,
249
                char **ret_stripped,
250
                unsigned *ret_tries_left,
251
                unsigned *ret_tries_done) {
252

253
        unsigned tries_left = UINT_MAX, tries_done = UINT_MAX;
67✔
254
        _cleanup_free_ char *stripped = NULL;
67✔
255
        const char *p, *suffix, *m;
67✔
256
        int r;
67✔
257

258
        assert(fname);
67✔
259
        assert(ret_stripped);
67✔
260
        assert(ret_tries_left);
67✔
261
        assert(ret_tries_done);
67✔
262

263
        /* Be liberal with suffix, only insist on a dot. After all we want to cover any capitalization here
264
         * (vfat is case insensitive after all), and at least .efi and .conf as suffix. */
265
        suffix = strrchr(fname, '.');
67✔
266
        if (!suffix)
67✔
267
                goto nothing;
1✔
268

269
        p = m = memrchr(fname, '+', suffix - fname);
66✔
270
        if (!p)
66✔
271
                goto nothing;
43✔
272
        p++;
23✔
273

274
        r = parse_tries(fname, &p, &tries_left);
23✔
275
        if (r < 0)
23✔
276
                return r;
277
        if (r == 0)
22✔
278
                goto nothing;
2✔
279

280
        if (*p == '-') {
20✔
281
                p++;
13✔
282

283
                r = parse_tries(fname, &p, &tries_done);
13✔
284
                if (r < 0)
13✔
285
                        return r;
286
                if (r == 0)
12✔
287
                        goto nothing;
×
288
        }
289

290
        if (p != suffix)
19✔
291
                goto nothing;
3✔
292

293
        stripped = strndup(fname, m - fname);
16✔
294
        if (!stripped)
16✔
295
                return log_oom();
×
296

297
        if (!strextend(&stripped, suffix))
16✔
298
                return log_oom();
×
299

300
        *ret_stripped = TAKE_PTR(stripped);
16✔
301
        *ret_tries_left = tries_left;
16✔
302
        *ret_tries_done = tries_done;
16✔
303

304
        return 0;
16✔
305

306
nothing:
49✔
307
        stripped = strdup(fname);
49✔
308
        if (!stripped)
49✔
309
                return log_oom();
×
310

311
        *ret_stripped = TAKE_PTR(stripped);
49✔
312
        *ret_tries_left = *ret_tries_done = UINT_MAX;
49✔
313
        return 0;
49✔
314
}
315

316
static int boot_entry_load_type1(
8✔
317
                FILE *f,
318
                const char *root,
319
                const BootEntrySource source,
320
                const char *dir,
321
                const char *fname,
322
                BootEntry *ret) {
323

324
        _cleanup_(boot_entry_free) BootEntry tmp = BOOT_ENTRY_INIT(BOOT_ENTRY_TYPE1, source);
8✔
325
        char *c;
8✔
326
        int r;
8✔
327

328
        assert(f);
8✔
329
        assert(root);
8✔
330
        assert(dir);
8✔
331
        assert(fname);
8✔
332
        assert(ret);
8✔
333

334
        /* Loads a Type #1 boot menu entry from the specified FILE* object */
335

336
        r = boot_filename_extract_tries(fname, &tmp.id, &tmp.tries_left, &tmp.tries_done);
8✔
337
        if (r < 0)
8✔
338
                return r;
339

340
        if (!efi_loader_entry_name_valid(tmp.id))
8✔
341
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid loader entry name: %s", fname);
×
342

343
        c = endswith_no_case(tmp.id, ".conf");
8✔
344
        if (!c)
8✔
345
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid loader entry file suffix: %s", fname);
×
346

347
        tmp.id_old = strndup(tmp.id, c - tmp.id); /* Without .conf suffix */
8✔
348
        if (!tmp.id_old)
8✔
349
                return log_oom();
×
350

351
        tmp.path = path_join(dir, fname);
8✔
352
        if (!tmp.path)
8✔
353
                return log_oom();
×
354

355
        tmp.root = strdup(root);
8✔
356
        if (!tmp.root)
8✔
357
                return log_oom();
×
358

359
        for (unsigned line = 1;; line++) {
27✔
360
                _cleanup_free_ char *buf = NULL, *field = NULL;
27✔
361

362
                r = read_stripped_line(f, LONG_LINE_MAX, &buf);
35✔
363
                if (r == -ENOBUFS)
35✔
364
                        return log_syntax(NULL, LOG_ERR, tmp.path, line, r, "Line too long.");
×
365
                if (r < 0)
35✔
366
                        return log_syntax(NULL, LOG_ERR, tmp.path, line, r, "Error while reading: %m");
×
367
                if (r == 0)
35✔
368
                        break;
369

370
                if (IN_SET(buf[0], '#', '\0'))
27✔
371
                        continue;
×
372

373
                const char *p = buf;
27✔
374
                r = extract_first_word(&p, &field, NULL, 0);
27✔
375
                if (r < 0) {
27✔
376
                        log_syntax(NULL, LOG_WARNING, tmp.path, line, r, "Failed to parse, ignoring line: %m");
×
377
                        continue;
×
378
                }
379
                if (r == 0) {
27✔
380
                        log_syntax(NULL, LOG_WARNING, tmp.path, line, 0, "Bad syntax, ignoring line.");
×
381
                        continue;
×
382
                }
383

384
                if (isempty(p)) {
27✔
385
                        /* Some fields can reasonably have an empty value. In other cases warn. */
386
                        if (!STR_IN_SET(field, "options", "devicetree-overlay"))
×
387
                                log_syntax(NULL, LOG_WARNING, tmp.path, line, 0, "Field '%s' without value, ignoring line.", field);
×
388

389
                        continue;
×
390
                }
391

392
                if (streq(field, "title"))
27✔
393
                        r = free_and_strdup(&tmp.title, p);
8✔
394
                else if (streq(field, "sort-key"))
19✔
395
                        r = free_and_strdup(&tmp.sort_key, p);
3✔
396
                else if (streq(field, "version"))
16✔
397
                        r = free_and_strdup(&tmp.version, p);
8✔
398
                else if (streq(field, "machine-id"))
8✔
399
                        r = free_and_strdup(&tmp.machine_id, p);
8✔
400
                else if (streq(field, "architecture"))
×
401
                        r = free_and_strdup(&tmp.architecture, p);
×
402
                else if (streq(field, "options"))
×
403
                        r = strv_extend(&tmp.options, p);
×
404
                else if (streq(field, "linux"))
×
405
                        r = parse_path_one(tmp.path, line, field, &tmp.kernel, p);
×
406
                else if (streq(field, "efi"))
×
407
                        r = parse_path_one(tmp.path, line, field, &tmp.efi, p);
×
408
                else if (streq(field, "uki"))
×
409
                        r = parse_path_one(tmp.path, line, field, &tmp.uki, p);
×
410
                else if (streq(field, "uki-url"))
×
411
                        r = free_and_strdup(&tmp.uki_url, p);
×
412
                else if (streq(field, "profile"))
×
413
                        r = safe_atou_full(p, 10, &tmp.profile);
×
414
                else if (streq(field, "initrd"))
×
415
                        r = parse_path_strv(tmp.path, line, field, &tmp.initrd, p);
×
416
                else if (streq(field, "devicetree"))
×
417
                        r = parse_path_one(tmp.path, line, field, &tmp.device_tree, p);
×
418
                else if (streq(field, "devicetree-overlay"))
×
419
                        r = parse_path_many(tmp.path, line, field, &tmp.device_tree_overlay, p);
×
420
                else {
421
                        log_syntax(NULL, LOG_WARNING, tmp.path, line, 0, "Unknown line '%s', ignoring.", field);
×
422
                        continue;
×
423
                }
424
                if (r < 0)
27✔
425
                        return log_syntax(NULL, LOG_ERR, tmp.path, line, r, "Error while parsing: %m");
×
426
        }
427

428
        *ret = TAKE_STRUCT(tmp);
8✔
429
        return 0;
8✔
430
}
431

432
int boot_config_load_type1(
8✔
433
                BootConfig *config,
434
                FILE *f,
435
                const char *root,
436
                const BootEntrySource source,
437
                const char *dir,
438
                const char *filename) {
439
        int r;
8✔
440

441
        assert(config);
8✔
442
        assert(f);
8✔
443
        assert(root);
8✔
444
        assert(dir);
8✔
445
        assert(filename);
8✔
446

447
        if (!GREEDY_REALLOC(config->entries, config->n_entries + 1))
8✔
448
                return log_oom();
×
449

450
        BootEntry *entry = config->entries + config->n_entries;
8✔
451

452
        r = boot_entry_load_type1(f, root, source, dir, filename, entry);
8✔
453
        if (r < 0)
8✔
454
                return r;
455
        config->n_entries++;
8✔
456

457
        entry->global_addons = &config->global_addons[source];
8✔
458

459
        return 0;
8✔
460
}
461

462
void boot_config_free(BootConfig *config) {
33✔
463
        assert(config);
33✔
464

465
        free(config->preferred_pattern);
33✔
466
        free(config->default_pattern);
33✔
467

468
        free(config->entry_oneshot);
33✔
469
        free(config->entry_preferred);
33✔
470
        free(config->entry_default);
33✔
471
        free(config->entry_selected);
33✔
472
        free(config->entry_sysfail);
33✔
473

474
        FOREACH_ARRAY(i, config->entries, config->n_entries)
119✔
475
                boot_entry_free(i);
86✔
476
        free(config->entries);
33✔
477

478
        FOREACH_ELEMENT(i, config->global_addons)
99✔
479
                boot_entry_addons_done(i);
66✔
480

481
        set_free(config->inodes_seen);
33✔
482
}
33✔
483

484
int boot_loader_read_conf(BootConfig *config, FILE *file, const char *path) {
31✔
485
        int r;
31✔
486

487
        assert(config);
31✔
488
        assert(file);
31✔
489
        assert(path);
31✔
490

491
        for (unsigned line = 1;; line++) {
62✔
492
                _cleanup_free_ char *buf = NULL, *field = NULL;
62✔
493

494
                r = read_stripped_line(file, LONG_LINE_MAX, &buf);
93✔
495
                if (r == -ENOBUFS)
93✔
496
                        return log_syntax(NULL, LOG_ERR, path, line, r, "Line too long.");
×
497
                if (r < 0)
93✔
498
                        return log_syntax(NULL, LOG_ERR, path, line, r, "Error while reading: %m");
×
499
                if (r == 0)
93✔
500
                        break;
501

502
                if (IN_SET(buf[0], '#', '\0'))
62✔
503
                        continue;
62✔
504

505
                const char *p = buf;
×
506
                r = extract_first_word(&p, &field, NULL, 0);
×
507
                if (r < 0) {
×
508
                        log_syntax(NULL, LOG_WARNING, path, line, r, "Failed to parse, ignoring line: %m");
×
509
                        continue;
×
510
                }
511
                if (r == 0) {
×
512
                        log_syntax(NULL, LOG_WARNING, path, line, 0, "Bad syntax, ignoring line.");
×
513
                        continue;
×
514
                }
515
                if (isempty(p)) {
×
516
                        log_syntax(NULL, LOG_WARNING, path, line, 0, "Field '%s' without value, ignoring line.", field);
×
517
                        continue;
×
518
                }
519

520
                if (streq(field, "preferred"))
×
521
                        r = free_and_strdup(&config->preferred_pattern, p);
×
522
                else if (streq(field, "default"))
×
523
                        r = free_and_strdup(&config->default_pattern, p);
×
524
                else if (STR_IN_SET(field, "timeout", "editor", "auto-entries", "auto-firmware",
×
525
                                    "auto-poweroff", "auto-reboot", "beep", "reboot-for-bitlocker",
526
                                    "reboot-on-error", "secure-boot-enroll", "secure-boot-enroll-action",
527
                                    "secure-boot-enroll-timeout-sec", "console-mode", "log-level"))
528
                        r = 0; /* we don't parse these in userspace, but they are OK */
×
529
                else {
530
                        log_syntax(NULL, LOG_WARNING, path, line, 0, "Unknown line '%s', ignoring.", field);
×
531
                        continue;
×
532
                }
533
                if (r < 0)
×
534
                        return log_syntax(NULL, LOG_ERR, path, line, r, "Error while parsing: %m");
×
535
        }
536

537
        return 1;
31✔
538
}
539

540
static int boot_loader_read_conf_path(BootConfig *config, const char *root, const char *path) {
33✔
541
        _cleanup_free_ char *full = NULL;
33✔
542
        _cleanup_fclose_ FILE *f = NULL;
33✔
543
        int r;
33✔
544

545
        assert(config);
33✔
546
        assert(path);
33✔
547

548
        r = chase_and_fopen_unlocked(path, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, "re", &full, &f);
33✔
549
        config->loader_conf_status = r < 0 ? r : true;
33✔
550
        if (r == -ENOENT)
33✔
551
                return 0;
552
        if (r < 0)
31✔
553
                return log_error_errno(r, "Failed to open '%s/%s': %m", root, skip_leading_slash(path));
×
554

555
        return boot_loader_read_conf(config, f, full);
31✔
556
}
557

558
static unsigned boot_entry_profile(const BootEntry *a) {
40✔
559
        assert(a);
40✔
560

561
        return a->profile == UINT_MAX ? 0 : a->profile;
40✔
562
}
563

564
static int boot_entry_compare(const BootEntry *a, const BootEntry *b) {
28✔
565
        int r;
28✔
566

567
        assert(a);
28✔
568
        assert(b);
28✔
569

570
        /* This mimics a function of the same name in src/boot/efi/sd-boot.c */
571

572
        r = CMP(a->tries_left == 0, b->tries_left == 0);
28✔
573
        if (r != 0)
28✔
UNCOV
574
                return r;
×
575

576
        r = CMP(!a->sort_key, !b->sort_key);
28✔
577
        if (r != 0)
25✔
578
                return r;
3✔
579

580
        if (a->sort_key && b->sort_key) {
25✔
581
                r = strcmp(a->sort_key, b->sort_key);
22✔
582
                if (r != 0)
22✔
583
                        return r;
584

585
                r = strcmp_ptr(a->machine_id, b->machine_id);
21✔
586
                if (r != 0)
21✔
587
                        return r;
588

589
                r = -strverscmp_improved(a->version, b->version);
21✔
590
                if (r != 0)
21✔
591
                        return r;
592

593
                r = CMP(boot_entry_profile(a), boot_entry_profile(b));
20✔
UNCOV
594
                if (r != 0)
×
595
                        return r;
20✔
596
        }
597

598
        r = -strverscmp_improved(a->id_without_profile ?: a->id, b->id_without_profile ?: b->id);
3✔
599
        if (r != 0)
3✔
600
                return r;
601

UNCOV
602
        if (a->id_without_profile && b->id_without_profile) {
×
603
                /* The strverscmp_improved() call above already established that we are talking about the
604
                 * same image here, hence order by profile, if there is one */
605
                r = CMP(boot_entry_profile(a), boot_entry_profile(b));
×
UNCOV
606
                if (r != 0)
×
607
                        return r;
×
608
        }
609

UNCOV
610
        if (a->tries_left != UINT_MAX || b->tries_left != UINT_MAX)
×
611
                return 0;
612

UNCOV
613
        r = -CMP(a->tries_left, b->tries_left);
×
UNCOV
614
        if (r != 0)
×
UNCOV
615
                return r;
×
616

UNCOV
617
        return CMP(a->tries_done, b->tries_done);
×
618
}
619

620
static int config_check_inode_relevant_and_unseen(BootConfig *config, int fd, const char *fname) {
28✔
621
        _cleanup_free_ char *d = NULL;
28✔
622
        struct stat st;
28✔
623

624
        assert(config);
28✔
625
        assert(fd >= 0);
28✔
626
        assert(fname);
28✔
627

628
        /* So, here's the thing: because of the mess around /efi/ vs. /boot/ vs. /boot/efi/ it might be that
629
         * people have these dirs, or subdirs of them symlinked or bind mounted, and we might end up
630
         * iterating though some dirs multiple times. Let's thus rather be safe than sorry, and track the
631
         * inodes we already processed: let's ignore inodes we have seen already. This should be robust
632
         * against any form of symlinking or bind mounting, and effectively suppress any such duplicates. */
633

634
        if (fstat(fd, &st) < 0)
28✔
UNCOV
635
                return log_error_errno(errno, "Failed to stat('%s'): %m", fname);
×
636
        if (!S_ISREG(st.st_mode)) {
28✔
UNCOV
637
                log_debug("File '%s' is not a regular file, ignoring.", fname);
×
638
                return false;
×
639
        }
640

641
        if (set_contains(config->inodes_seen, &st)) {
28✔
UNCOV
642
                log_debug("Inode '%s' already seen before, ignoring.", fname);
×
UNCOV
643
                return false;
×
644
        }
645

646
        d = memdup(&st, sizeof(st));
28✔
647
        if (!d)
28✔
UNCOV
648
                return log_oom();
×
649

650
        if (set_ensure_consume(&config->inodes_seen, &inode_hash_ops, TAKE_PTR(d)) < 0)
28✔
UNCOV
651
                return log_oom();
×
652

653
        return true;
654
}
655

656
static int boot_entries_find_type1(
47✔
657
                BootConfig *config,
658
                const char *root,
659
                const BootEntrySource source,
660
                const char *dir) {
661

662
        _cleanup_free_ DirectoryEntries *dentries = NULL;
94✔
663
        _cleanup_free_ char *full = NULL;
47✔
664
        _cleanup_close_ int dir_fd = -EBADF;
47✔
665
        int r;
47✔
666

667
        assert(config);
47✔
668
        assert(root);
47✔
669
        assert(dir);
47✔
670

671
        dir_fd = chase_and_open(dir, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, O_DIRECTORY|O_CLOEXEC, &full);
47✔
672
        if (dir_fd == -ENOENT)
47✔
673
                return 0;
674
        if (dir_fd < 0)
33✔
UNCOV
675
                return log_error_errno(dir_fd, "Failed to open '%s/%s': %m", root, skip_leading_slash(dir));
×
676

677
        r = readdir_all(dir_fd, RECURSE_DIR_IGNORE_DOT, &dentries);
33✔
678
        if (r < 0)
33✔
679
                return log_error_errno(r, "Failed to read directory '%s': %m", full);
×
680

681
        FOREACH_ARRAY(i, dentries->entries, dentries->n_entries) {
41✔
682
                const struct dirent *de = *i;
8✔
683
                _cleanup_fclose_ FILE *f = NULL;
8✔
684

685
                if (!dirent_is_file(de))
8✔
UNCOV
686
                        continue;
×
687

688
                if (!endswith_no_case(de->d_name, ".conf"))
8✔
UNCOV
689
                        continue;
×
690

691
                r = xfopenat(dir_fd, de->d_name, "re", O_NOFOLLOW|O_NOCTTY, &f);
8✔
692
                if (r < 0) {
8✔
UNCOV
693
                        log_warning_errno(r, "Failed to open %s/%s, ignoring: %m", full, de->d_name);
×
UNCOV
694
                        continue;
×
695
                }
696

697
                r = config_check_inode_relevant_and_unseen(config, fileno(f), de->d_name);
8✔
698
                if (r < 0)
8✔
699
                        return r;
700
                if (r == 0) /* inode already seen or otherwise not relevant */
8✔
UNCOV
701
                        continue;
×
702

703
                r = boot_config_load_type1(config, f, root, source, full, de->d_name);
8✔
704
                if (r == -ENOMEM) /* ignore all other errors */
8✔
UNCOV
705
                        return log_oom();
×
706
        }
707

708
        return 0;
709
}
710

711
static int boot_entry_load_unified(
30✔
712
                const char *root,
713
                const BootEntrySource source,
714
                const char *path,
715
                unsigned profile,
716
                const char *osrelease_text,
717
                const char *profile_text,
718
                const char *cmdline_text,
719
                BootEntry *ret) {
720

UNCOV
721
        _cleanup_free_ char *fname = NULL, *os_pretty_name = NULL, *os_image_id = NULL, *os_name = NULL, *os_id = NULL,
×
722
                *os_image_version = NULL, *os_version = NULL, *os_version_id = NULL, *os_build_id = NULL;
30✔
723
        const char *k, *good_name, *good_version, *good_sort_key;
30✔
724
        int r;
30✔
725

726
        assert(root);
30✔
727
        assert(path);
30✔
728
        assert(osrelease_text);
30✔
729
        assert(ret);
30✔
730

731
        k = path_startswith(path, root);
30✔
732
        if (!k)
30✔
UNCOV
733
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not below root: %s", path);
×
734

735
        r = parse_env_data(osrelease_text, /* size= */ SIZE_MAX,
30✔
736
                           ".osrel",
737
                           "PRETTY_NAME", &os_pretty_name,
738
                           "IMAGE_ID", &os_image_id,
739
                           "NAME", &os_name,
740
                           "ID", &os_id,
741
                           "IMAGE_VERSION", &os_image_version,
742
                           "VERSION", &os_version,
743
                           "VERSION_ID", &os_version_id,
744
                           "BUILD_ID", &os_build_id);
745
        if (r < 0)
30✔
UNCOV
746
                return log_error_errno(r, "Failed to parse os-release data from unified kernel image %s: %m", path);
×
747

748
        if (!bootspec_pick_name_version_sort_key(
30✔
749
                            os_pretty_name,
750
                            os_image_id,
751
                            os_name,
752
                            os_id,
753
                            os_image_version,
754
                            os_version,
755
                            os_version_id,
756
                            os_build_id,
757
                            &good_name,
758
                            &good_version,
759
                            &good_sort_key))
760
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Missing fields in os-release data from unified kernel image %s, refusing.", path);
×
761

762
        _cleanup_free_ char *profile_id = NULL, *profile_title = NULL;
30✔
763
        if (profile_text) {
30✔
764
                r = parse_env_data(
30✔
765
                                profile_text, /* size= */ SIZE_MAX,
766
                                ".profile",
767
                                "ID", &profile_id,
768
                                "TITLE", &profile_title);
769
                if (r < 0)
30✔
UNCOV
770
                        return log_error_errno(r, "Failed to parse profile data from unified kernel image '%s': %m", path);
×
771
        }
772

773
        r = path_extract_filename(path, &fname);
30✔
774
        if (r < 0)
30✔
UNCOV
775
                return log_error_errno(r, "Failed to extract file name from '%s': %m", path);
×
776

777
        _cleanup_(boot_entry_free) BootEntry tmp = BOOT_ENTRY_INIT(BOOT_ENTRY_TYPE2, source);
30✔
778

779
        r = boot_filename_extract_tries(fname, &tmp.id, &tmp.tries_left, &tmp.tries_done);
30✔
780
        if (r < 0)
30✔
781
                return r;
782

783
        if (!efi_loader_entry_name_valid(tmp.id))
30✔
784
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid loader entry name: %s", tmp.id);
×
785

786
        tmp.profile = profile;
30✔
787

788
        if (profile_id || profile > 0) {
30✔
789
                tmp.id_without_profile = TAKE_PTR(tmp.id);
30✔
790

791
                if (profile_id)
30✔
792
                        tmp.id = strjoin(tmp.id_without_profile, "@", profile_id);
30✔
793
                else
UNCOV
794
                        (void) asprintf(&tmp.id, "%s@%u", tmp.id_without_profile, profile);
×
795
                if (!tmp.id)
30✔
UNCOV
796
                        return log_oom();
×
797
        }
798

799
        if (os_id && os_version_id) {
30✔
UNCOV
800
                tmp.id_old = strjoin(os_id, "-", os_version_id);
×
801
                if (!tmp.id_old)
×
UNCOV
802
                        return log_oom();
×
803
        }
804

805
        tmp.path = strdup(path);
30✔
806
        if (!tmp.path)
30✔
UNCOV
807
                return log_oom();
×
808

809
        tmp.root = strdup(root);
30✔
810
        if (!tmp.root)
30✔
UNCOV
811
                return log_oom();
×
812

813
        tmp.kernel = path_make_absolute(k, "/");
30✔
814
        if (!tmp.kernel)
30✔
815
                return log_oom();
×
816

817
        tmp.options = strv_new(cmdline_text);
30✔
818
        if (!tmp.options)
30✔
UNCOV
819
                return log_oom();
×
820

821
        if (profile_title)
30✔
822
                tmp.title = strjoin(good_name, " (", profile_title, ")");
20✔
823
        else if (profile_id)
10✔
824
                tmp.title = strjoin(good_name, " (", profile_id, ")");
10✔
825
        else if (profile > 0)
×
UNCOV
826
                (void) asprintf(&tmp.title, "%s (@%u)", good_name, profile);
×
827
        else
UNCOV
828
                tmp.title = strdup(good_name);
×
829
        if (!tmp.title)
30✔
UNCOV
830
                return log_oom();
×
831

832
        if (good_sort_key) {
30✔
833
                tmp.sort_key = strdup(good_sort_key);
30✔
834
                if (!tmp.sort_key)
30✔
UNCOV
835
                        return log_oom();
×
836
        }
837

838
        if (good_version) {
30✔
839
                tmp.version = strdup(good_version);
30✔
840
                if (!tmp.version)
30✔
UNCOV
841
                        return log_oom();
×
842
        }
843

844
        *ret = TAKE_STRUCT(tmp);
30✔
845
        return 0;
30✔
846
}
847

848
static int pe_load_headers_and_sections(
50✔
849
                int fd,
850
                const char *path,
851
                IMAGE_SECTION_HEADER **ret_sections,
852
                PeHeader **ret_pe_header) {
853

854
        _cleanup_free_ IMAGE_SECTION_HEADER *sections = NULL;
100✔
UNCOV
855
        _cleanup_free_ IMAGE_DOS_HEADER *dos_header = NULL;
×
856
        _cleanup_free_ PeHeader *pe_header = NULL;
50✔
857
        int r;
50✔
858

859
        assert(fd >= 0);
50✔
860
        assert(path);
50✔
861

862
        r = pe_load_headers(fd, &dos_header, &pe_header);
50✔
863
        if (r < 0)
50✔
UNCOV
864
                return log_error_errno(r, "Failed to parse PE file '%s': %m", path);
×
865

866
        r = pe_load_sections(fd, dos_header, pe_header, &sections);
50✔
867
        if (r < 0)
50✔
UNCOV
868
                return log_error_errno(r, "Failed to parse PE sections of '%s': %m", path);
×
869

870
        if (ret_pe_header)
50✔
871
                *ret_pe_header = TAKE_PTR(pe_header);
50✔
872
        if (ret_sections)
50✔
873
                *ret_sections = TAKE_PTR(sections);
50✔
874

875
        return 0;
876
}
877

878
static const IMAGE_SECTION_HEADER* pe_find_profile_section_table(
70✔
879
                const PeHeader *pe_header,
880
                const IMAGE_SECTION_HEADER *sections,
881
                unsigned profile,
882
                size_t *ret_n_sections) {
883

884
        assert(pe_header);
70✔
885

886
        /* Looks for the part of the section table that defines the specified profile. If 'profile' is
887
         * specified as UINT_MAX this will look for the base profile. */
888

889
        if (le16toh(pe_header->pe.NumberOfSections) == 0)
70✔
890
                return NULL;
891

892
        assert(sections);
70✔
893

894
        const IMAGE_SECTION_HEADER
70✔
895
                *p = sections,
70✔
896
                *e = sections + le16toh(pe_header->pe.NumberOfSections),
70✔
897
                *start = profile == UINT_MAX ? sections : NULL,
70✔
898
                *end;
899
        unsigned current_profile = UINT_MAX;
900

901
        for (;;) {
250✔
902
                p = pe_section_table_find(p, e - p, ".profile");
160✔
903
                if (!p) {
160✔
904
                        end = e;
905
                        break;
906
                }
907
                if (current_profile == profile) {
140✔
908
                        end = p;
909
                        break;
910
                }
911

912
                if (current_profile == UINT_MAX)
90✔
913
                        current_profile = 0;
914
                else
915
                        current_profile++;
50✔
916

917
                if (current_profile == profile)
90✔
918
                        start = p;
30✔
919

920
                p++; /* Continue scanning after the .profile entry we just found */
90✔
921
        }
922

923
        if (!start)
70✔
924
                return NULL;
925

926
        if (ret_n_sections)
60✔
927
                *ret_n_sections = end - start;
60✔
928

929
        return start;
930
}
931

932
static int trim_cmdline(char **cmdline) {
40✔
933
        assert(cmdline);
40✔
934

935
        /* Strips leading and trailing whitespace from command line */
936

937
        if (!*cmdline)
40✔
938
                return 0;
939

940
        const char *skipped = skip_leading_chars(*cmdline, WHITESPACE);
40✔
941

942
        if (isempty(skipped)) {
40✔
UNCOV
943
                *cmdline = mfree(*cmdline);
×
UNCOV
944
                return 0;
×
945
        }
946

947
        if (skipped != *cmdline) {
40✔
UNCOV
948
                _cleanup_free_ char *c = strdup(skipped);
×
UNCOV
949
                if (!c)
×
UNCOV
950
                        return -ENOMEM;
×
951

UNCOV
952
                free_and_replace(*cmdline, c);
×
953
        }
954

955
        delete_trailing_chars(*cmdline, WHITESPACE);
40✔
956
        return 1;
40✔
957
}
958

959
/* Maximum PE section we are willing to load (Note that sections we are not interested in may be larger, but
960
 * the ones we do care about and we are willing to load into memory have this size limit.) */
961
#define PE_SECTION_SIZE_MAX (4U*1024U*1024U)
962

963
static int pe_find_uki_sections(
40✔
964
                int fd,
965
                const char *path,
966
                unsigned profile,
967
                char **ret_osrelease,
968
                char **ret_profile,
969
                char **ret_cmdline) {
970

UNCOV
971
        _cleanup_free_ char *osrelease_text = NULL, *profile_text = NULL, *cmdline_text = NULL;
×
UNCOV
972
        _cleanup_free_ IMAGE_SECTION_HEADER *sections = NULL;
×
973
        _cleanup_free_ PeHeader *pe_header = NULL;
40✔
974
        int r;
40✔
975

976
        assert(fd >= 0);
40✔
977
        assert(path);
40✔
978
        assert(profile != UINT_MAX);
40✔
979
        assert(ret_osrelease);
40✔
980
        assert(ret_profile);
40✔
981
        assert(ret_cmdline);
40✔
982

983
        r = pe_load_headers_and_sections(fd, path, &sections, &pe_header);
40✔
984
        if (r < 0)
40✔
985
                return r;
986

987
        if (!pe_is_uki(pe_header, sections))
40✔
UNCOV
988
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Parsed PE file '%s' is not a UKI.", path);
×
989

990
        if (!pe_is_native(pe_header)) /* Don't process non-native UKIs */
40✔
UNCOV
991
                goto nothing;
×
992

993
        /* Find part of the section table for this profile */
994
        size_t n_psections = 0;
40✔
995
        const IMAGE_SECTION_HEADER *psections = pe_find_profile_section_table(pe_header, sections, profile, &n_psections);
40✔
996
        if (!psections && profile != 0) /* Profile not found? (Profile @0 needs no explicit .profile!) */
40✔
997
                goto nothing;
10✔
998

999
        /* Find base profile part of section table */
1000
        size_t n_bsections;
30✔
1001
        const IMAGE_SECTION_HEADER *bsections = ASSERT_PTR(pe_find_profile_section_table(pe_header, sections, UINT_MAX, &n_bsections));
30✔
1002

1003
        struct {
30✔
1004
                const char *name;
1005
                char **data;
1006
        } table[] = {
30✔
1007
                { ".osrel",   &osrelease_text },
1008
                { ".profile", &profile_text   },
1009
                { ".cmdline", &cmdline_text   },
1010
        };
1011

1012
        FOREACH_ELEMENT(t, table) {
120✔
1013
                const IMAGE_SECTION_HEADER *found;
90✔
1014

1015
                /* First look in the profile part of the section table, and if we don't find anything there, look into the base part */
1016
                found = pe_section_table_find(psections, n_psections, t->name);
90✔
1017
                if (!found) {
90✔
1018
                        found = pe_section_table_find(bsections, n_bsections, t->name);
40✔
1019
                        if (!found)
40✔
UNCOV
1020
                                continue;
×
1021
                }
1022

1023
                /* Permit "masking" of sections in the base profile */
1024
                if (le32toh(found->VirtualSize) == 0)
90✔
UNCOV
1025
                        continue;
×
1026

1027
                r = pe_read_section_data(fd, found, PE_SECTION_SIZE_MAX, (void**) t->data, /* ret_size= */ NULL);
90✔
1028
                if (r < 0)
90✔
UNCOV
1029
                        return log_error_errno(r, "Failed to load contents of section '%s': %m", t->name);
×
1030
        }
1031

1032
        if (!osrelease_text)
30✔
UNCOV
1033
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unified kernel image lacks .osrel data for profile @%u, refusing.", profile);
×
1034

1035
        if (trim_cmdline(&cmdline_text) < 0)
30✔
UNCOV
1036
                return log_oom();
×
1037

1038
        *ret_osrelease = TAKE_PTR(osrelease_text);
30✔
1039
        *ret_profile = TAKE_PTR(profile_text);
30✔
1040
        *ret_cmdline = TAKE_PTR(cmdline_text);
30✔
1041
        return 1;
30✔
1042

1043
nothing:
10✔
1044
        *ret_osrelease = *ret_profile = *ret_cmdline = NULL;
10✔
1045
        return 0;
10✔
1046
}
1047

1048
static int pe_find_addon_sections(
10✔
1049
                int fd,
1050
                const char *path,
1051
                char **ret_cmdline) {
1052

1053
        _cleanup_free_ IMAGE_SECTION_HEADER *sections = NULL;
20✔
1054
        _cleanup_free_ PeHeader *pe_header = NULL;
10✔
1055
        int r;
10✔
1056

1057
        assert(fd >= 0);
10✔
1058
        assert(path);
10✔
1059

1060
        r = pe_load_headers_and_sections(fd, path, &sections, &pe_header);
10✔
1061
        if (r < 0)
10✔
1062
                return r;
1063

1064
        if (!pe_is_addon(pe_header, sections))
10✔
1065
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Parse PE file '%s' is not an add-on.", path);
×
1066

1067
        /* Define early, before the gotos below */
1068
        _cleanup_free_ char *cmdline_text = NULL;
10✔
1069

1070
        if (!pe_is_native(pe_header))
10✔
UNCOV
1071
                goto nothing;
×
1072

1073
        const IMAGE_SECTION_HEADER *found = pe_section_table_find(sections, le16toh(pe_header->pe.NumberOfSections), ".cmdline");
10✔
1074
        if (!found)
10✔
UNCOV
1075
                goto nothing;
×
1076

1077
        r = pe_read_section_data(fd, found, PE_SECTION_SIZE_MAX, (void**) &cmdline_text, /* ret_size= */ NULL);
10✔
1078
        if (r < 0)
10✔
1079
                return log_error_errno(r, "Failed to load contents of section '.cmdline': %m");
×
1080

1081
        if (trim_cmdline(&cmdline_text) < 0)
10✔
UNCOV
1082
                return log_oom();
×
1083

1084
        *ret_cmdline = TAKE_PTR(cmdline_text);
10✔
1085
        return 1;
10✔
1086

UNCOV
1087
nothing:
×
UNCOV
1088
        *ret_cmdline = NULL;
×
UNCOV
1089
        return 0;
×
1090
}
1091

1092
static int insert_boot_entry_addon(
10✔
1093
                BootEntryAddons *addons,
1094
                char *location,
1095
                char *cmdline) {
1096

1097
        assert(addons);
10✔
1098

1099
        if (!GREEDY_REALLOC(addons->items, addons->n_items + 1))
10✔
UNCOV
1100
                return log_oom();
×
1101

1102
        addons->items[addons->n_items++] = (BootEntryAddon) {
10✔
1103
                .location = location,
1104
                .cmdline = cmdline,
1105
        };
1106

1107
        return 0;
10✔
1108
}
1109

1110
static int boot_entries_find_unified_addons(
77✔
1111
                BootConfig *config,
1112
                int d_fd,
1113
                const char *addon_dir,
1114
                const char *root,
1115
                BootEntryAddons *ret_addons) {
1116

1117
        _cleanup_closedir_ DIR *d = NULL;
77✔
1118
        _cleanup_free_ char *full = NULL;
77✔
1119
        _cleanup_(boot_entry_addons_done) BootEntryAddons addons = {};
77✔
1120
        int r;
77✔
1121

1122
        assert(ret_addons);
77✔
1123
        assert(config);
77✔
1124

1125
        r = chase_and_opendirat(d_fd, addon_dir, CHASE_AT_RESOLVE_IN_ROOT, &full, &d);
77✔
1126
        if (r == -ENOENT)
77✔
1127
                return 0;
1128
        if (r < 0)
10✔
1129
                return log_error_errno(r, "Failed to open '%s/%s': %m", root, skip_leading_slash(addon_dir));
×
1130

1131
        FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read %s: %m", full)) {
40✔
1132
                _cleanup_free_ char *j = NULL, *cmdline = NULL, *location = NULL;
10✔
1133
                _cleanup_close_ int fd = -EBADF;
10✔
1134

1135
                if (!dirent_is_file(de))
10✔
UNCOV
1136
                        continue;
×
1137

1138
                if (!endswith_no_case(de->d_name, ".addon.efi"))
10✔
UNCOV
1139
                        continue;
×
1140

1141
                fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOFOLLOW|O_NOCTTY);
10✔
1142
                if (fd < 0) {
10✔
UNCOV
1143
                        log_warning_errno(errno, "Failed to open %s/%s, ignoring: %m", full, de->d_name);
×
UNCOV
1144
                        continue;
×
1145
                }
1146

1147
                r = config_check_inode_relevant_and_unseen(config, fd, de->d_name);
10✔
1148
                if (r < 0)
10✔
1149
                        return r;
1150
                if (r == 0) /* inode already seen or otherwise not relevant */
10✔
UNCOV
1151
                        continue;
×
1152

1153
                j = path_join(full, de->d_name);
10✔
1154
                if (!j)
10✔
UNCOV
1155
                        return log_oom();
×
1156

1157
                if (pe_find_addon_sections(fd, j, &cmdline) <= 0)
10✔
UNCOV
1158
                        continue;
×
1159

1160
                location = strdup(j);
10✔
1161
                if (!location)
10✔
UNCOV
1162
                        return log_oom();
×
1163

1164
                r = insert_boot_entry_addon(&addons, location, cmdline);
10✔
1165
                if (r < 0)
10✔
1166
                        return r;
1167

1168
                TAKE_PTR(location);
10✔
1169
                TAKE_PTR(cmdline);
10✔
1170
        }
1171

1172
        *ret_addons = TAKE_STRUCT(addons);
10✔
1173
        return 0;
10✔
1174
}
1175

1176
static int boot_entries_find_unified_global_addons(
47✔
1177
                BootConfig *config,
1178
                const char *root,
1179
                const char *d_name,
1180
                BootEntryAddons *ret_addons) {
1181

1182
        int r;
47✔
1183
        _cleanup_closedir_ DIR *d = NULL;
47✔
1184

1185
        assert(ret_addons);
47✔
1186

1187
        r = chase_and_opendir(root, NULL, CHASE_PROHIBIT_SYMLINKS, NULL, &d);
47✔
1188
        if (r == -ENOENT)
47✔
1189
                return 0;
1190
        if (r < 0)
47✔
UNCOV
1191
                return log_error_errno(r, "Failed to open '%s/%s': %m", root, skip_leading_slash(d_name));
×
1192

1193
        return boot_entries_find_unified_addons(config, dirfd(d), d_name, root, ret_addons);
47✔
1194
}
1195

1196
static int boot_entries_find_unified_local_addons(
30✔
1197
                BootConfig *config,
1198
                int d_fd,
1199
                const char *d_name,
1200
                const char *root,
1201
                BootEntry *ret) {
1202

1203
        _cleanup_free_ char *addon_dir = NULL;
30✔
1204

1205
        assert(ret);
30✔
1206

1207
        addon_dir = strjoin(d_name, ".extra.d");
30✔
1208
        if (!addon_dir)
30✔
UNCOV
1209
                return log_oom();
×
1210

1211
        return boot_entries_find_unified_addons(config, d_fd, addon_dir, root, &ret->local_addons);
30✔
1212
}
1213

1214
static int boot_entries_find_unified(
47✔
1215
                BootConfig *config,
1216
                const char *root,
1217
                BootEntrySource source,
1218
                const char *dir) {
1219

1220
        _cleanup_closedir_ DIR *d = NULL;
47✔
1221
        _cleanup_free_ char *full = NULL;
47✔
1222
        int r;
47✔
1223

1224
        assert(config);
47✔
1225
        assert(dir);
47✔
1226

1227
        r = chase_and_opendir(dir, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &full, &d);
47✔
1228
        if (r == -ENOENT)
47✔
1229
                return 0;
1230
        if (r < 0)
31✔
UNCOV
1231
                return log_error_errno(r, "Failed to open '%s/%s': %m", root, skip_leading_slash(dir));
×
1232

1233
        FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read %s: %m", full)) {
103✔
1234
                if (!dirent_is_file(de))
10✔
UNCOV
1235
                        continue;
×
1236

1237
                if (!endswith_no_case(de->d_name, ".efi"))
10✔
UNCOV
1238
                        continue;
×
1239

1240
                _cleanup_close_ int fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOFOLLOW|O_NOCTTY);
129✔
1241
                if (fd < 0) {
10✔
UNCOV
1242
                        log_warning_errno(errno, "Failed to open %s/%s, ignoring: %m", full, de->d_name);
×
UNCOV
1243
                        continue;
×
1244
                }
1245

1246
                r = config_check_inode_relevant_and_unseen(config, fd, de->d_name);
10✔
1247
                if (r < 0)
10✔
1248
                        return r;
1249
                if (r == 0) /* inode already seen or otherwise not relevant */
10✔
UNCOV
1250
                        continue;
×
1251

1252
                _cleanup_free_ char *j = path_join(full, de->d_name);
20✔
1253
                if (!j)
10✔
UNCOV
1254
                        return log_oom();
×
1255

1256
                for (unsigned p = 0; p < UNIFIED_PROFILES_MAX; p++) {
40✔
1257
                        _cleanup_free_ char *osrelease = NULL, *profile = NULL, *cmdline = NULL;
40✔
1258

1259
                        r = pe_find_uki_sections(fd, j, p, &osrelease, &profile, &cmdline);
40✔
1260
                        if (r == 0) /* this profile does not exist, we are done */
40✔
1261
                                break;
1262
                        if (r < 0)
30✔
UNCOV
1263
                                continue;
×
1264

1265
                        if (!GREEDY_REALLOC(config->entries, config->n_entries + 1))
30✔
UNCOV
1266
                                return log_oom();
×
1267

1268
                        BootEntry *entry = config->entries + config->n_entries;
30✔
1269

1270
                        if (boot_entry_load_unified(root, source, j, p, osrelease, profile, cmdline, entry) < 0)
30✔
UNCOV
1271
                                continue;
×
1272

1273
                        /* look for .efi.extra.d */
1274
                        (void) boot_entries_find_unified_local_addons(config, dirfd(d), de->d_name, full, entry);
30✔
1275

1276
                        /* Set up the backpointer, so that we can find the global addons */
1277
                        entry->global_addons = &config->global_addons[source];
30✔
1278

1279
                        config->n_entries++;
30✔
1280
                }
1281
        }
1282

1283
        return 0;
1284
}
1285

1286
static bool find_nonunique(const BootEntry *entries, size_t n_entries, bool arr[]) {
15✔
1287
        bool non_unique = false;
15✔
1288

1289
        assert(entries || n_entries == 0);
15✔
1290
        assert(arr || n_entries == 0);
15✔
1291

1292
        for (size_t i = 0; i < n_entries; i++)
63✔
1293
                arr[i] = false;
48✔
1294

1295
        for (size_t i = 0; i < n_entries; i++)
63✔
1296
                for (size_t j = 0; j < n_entries; j++)
222✔
1297
                        if (i != j && streq(boot_entry_title(entries + i),
174✔
1298
                                            boot_entry_title(entries + j)))
1299
                                non_unique = arr[i] = arr[j] = true;
10✔
1300

1301
        return non_unique;
15✔
1302
}
1303

1304
static int boot_entries_uniquify(BootEntry *entries, size_t n_entries) {
33✔
1305
        _cleanup_free_ bool *arr = NULL;
33✔
1306
        char *s;
33✔
1307

1308
        assert(entries || n_entries == 0);
33✔
1309

1310
        if (n_entries == 0)
33✔
1311
                return 0;
1312

1313
        arr = new(bool, n_entries);
12✔
1314
        if (!arr)
12✔
1315
                return -ENOMEM;
1316

1317
        /* Find _all_ non-unique titles */
1318
        if (!find_nonunique(entries, n_entries, arr))
12✔
1319
                return 0;
1320

1321
        /* Add version to non-unique titles */
1322
        for (size_t i = 0; i < n_entries; i++)
10✔
1323
                if (arr[i] && entries[i].version) {
8✔
1324
                        if (asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].version) < 0)
6✔
1325
                                return -ENOMEM;
1326

1327
                        free_and_replace(entries[i].show_title, s);
6✔
1328
                }
1329

1330
        if (!find_nonunique(entries, n_entries, arr))
2✔
1331
                return 0;
1332

1333
        /* Add machine-id to non-unique titles */
1334
        for (size_t i = 0; i < n_entries; i++)
3✔
1335
                if (arr[i] && entries[i].machine_id) {
2✔
1336
                        if (asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].machine_id) < 0)
2✔
1337
                                return -ENOMEM;
1338

1339
                        free_and_replace(entries[i].show_title, s);
2✔
1340
                }
1341

1342
        if (!find_nonunique(entries, n_entries, arr))
1✔
1343
                return 0;
1344

1345
        /* Add file name to non-unique titles */
1346
        for (size_t i = 0; i < n_entries; i++)
3✔
1347
                if (arr[i]) {
2✔
1348
                        if (asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].id) < 0)
2✔
1349
                                return -ENOMEM;
1350

1351
                        free_and_replace(entries[i].show_title, s);
2✔
1352
                }
1353

1354
        return 0;
1355
}
1356

1357
static int boot_config_find(const BootConfig *config, const char *id) {
20✔
1358
        assert(config);
20✔
1359

1360
        if (!id)
20✔
1361
                return -1;
1362

1363
        if (id[0] == '@') {
20✔
UNCOV
1364
                if (!strcaseeq(id, "@saved"))
×
1365
                        return -1;
UNCOV
1366
                if (!config->entry_selected)
×
1367
                        return -1;
1368
                id = config->entry_selected;
1369
        }
1370

1371
        for (size_t i = 0; i < config->n_entries; i++)
49✔
1372
                if (fnmatch(id, config->entries[i].id, FNM_CASEFOLD) == 0)
49✔
1373
                        return i;
20✔
1374

1375
        return -1;
1376
}
1377

1378
static int boot_entries_select_default(const BootConfig *config) {
31✔
1379
        int i;
31✔
1380

1381
        assert(config);
31✔
1382
        assert(config->entries || config->n_entries == 0);
31✔
1383

1384
        if (config->n_entries == 0) {
31✔
1385
                log_debug("Found no default boot entry :(");
14✔
1386
                return -1; /* -1 means "no default" */
14✔
1387
        }
1388

1389
        if (config->entry_oneshot) {
17✔
1390
                i = boot_config_find(config, config->entry_oneshot);
×
1391
                if (i >= 0) {
×
UNCOV
1392
                        log_debug("Found default: id \"%s\" is matched by LoaderEntryOneShot",
×
1393
                                  config->entries[i].id);
UNCOV
1394
                        return i;
×
1395
                }
1396
        }
1397

1398
        if (config->entry_preferred) {
17✔
UNCOV
1399
                i = boot_config_find(config, config->entry_preferred);
×
UNCOV
1400
                if (i >= 0) {
×
UNCOV
1401
                        log_debug("Found default: id \"%s\" is matched by LoaderEntryPreferred",
×
1402
                                  config->entries[i].id);
UNCOV
1403
                        return i;
×
1404
                }
1405
        }
1406

1407
        if (config->entry_default) {
17✔
1408
                i = boot_config_find(config, config->entry_default);
3✔
1409
                if (i >= 0) {
3✔
1410
                        log_debug("Found default: id \"%s\" is matched by LoaderEntryDefault",
3✔
1411
                                  config->entries[i].id);
1412
                        return i;
3✔
1413
                }
1414
        }
1415

1416
        if (config->preferred_pattern) {
14✔
1417
                i = boot_config_find(config, config->preferred_pattern);
×
1418
                if (i >= 0) {
×
UNCOV
1419
                        log_debug("Found preferred: id \"%s\" is matched by pattern \"%s\"",
×
1420
                                  config->entries[i].id, config->preferred_pattern);
UNCOV
1421
                        return i;
×
1422
                }
1423
        }
1424

1425
        if (config->default_pattern) {
14✔
UNCOV
1426
                i = boot_config_find(config, config->default_pattern);
×
UNCOV
1427
                if (i >= 0) {
×
UNCOV
1428
                        log_debug("Found default: id \"%s\" is matched by pattern \"%s\"",
×
1429
                                  config->entries[i].id, config->default_pattern);
UNCOV
1430
                        return i;
×
1431
                }
1432
        }
1433

1434
        log_debug("Found default: first entry \"%s\"", config->entries[0].id);
14✔
1435
        return 0;
1436
}
1437

1438
static int boot_entries_select_selected(const BootConfig *config) {
31✔
1439
        assert(config);
31✔
1440
        assert(config->entries || config->n_entries == 0);
31✔
1441

1442
        if (!config->entry_selected || config->n_entries == 0)
31✔
1443
                return -1;
1444

1445
        return boot_config_find(config, config->entry_selected);
17✔
1446
}
1447

1448
static int boot_load_efi_entry_pointers(BootConfig *config, bool skip_efivars) {
31✔
1449
        int r;
31✔
1450

1451
        assert(config);
31✔
1452

1453
        if (skip_efivars || !is_efi_boot())
31✔
1454
                return 0;
14✔
1455

1456
        /* Loads the three "pointers" to boot loader entries from their EFI variables */
1457

1458
        r = efi_get_variable_string(EFI_LOADER_VARIABLE_STR("LoaderEntryOneShot"), &config->entry_oneshot);
17✔
1459
        if (r == -ENOMEM)
17✔
UNCOV
1460
                return log_oom();
×
1461
        if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
17✔
1462
                log_warning_errno(r, "Failed to read EFI variable \"LoaderEntryOneShot\", ignoring: %m");
×
1463

1464
        r = efi_get_variable_string(EFI_LOADER_VARIABLE_STR("LoaderEntryPreferred"), &config->entry_preferred);
17✔
1465
        if (r == -ENOMEM)
17✔
UNCOV
1466
                return log_oom();
×
1467
        if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
17✔
1468
                log_warning_errno(r, "Failed to read EFI variable \"LoaderEntryPreferred\", ignoring: %m");
×
1469

1470
        r = efi_get_variable_string(EFI_LOADER_VARIABLE_STR("LoaderEntryDefault"), &config->entry_default);
17✔
1471
        if (r == -ENOMEM)
17✔
UNCOV
1472
                return log_oom();
×
1473
        if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
17✔
1474
                log_warning_errno(r, "Failed to read EFI variable \"LoaderEntryDefault\", ignoring: %m");
×
1475

1476
        r = efi_get_variable_string(EFI_LOADER_VARIABLE_STR("LoaderEntrySelected"), &config->entry_selected);
17✔
1477
        if (r == -ENOMEM)
17✔
UNCOV
1478
                return log_oom();
×
1479
        if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
17✔
UNCOV
1480
                log_warning_errno(r, "Failed to read EFI variable \"LoaderEntrySelected\", ignoring: %m");
×
1481

1482
        r = efi_get_variable_string(EFI_LOADER_VARIABLE_STR("LoaderEntrySysFail"), &config->entry_sysfail);
17✔
1483
        if (r == -ENOMEM)
17✔
UNCOV
1484
                return log_oom();
×
1485
        if (r < 0 && !IN_SET(r, -ENOENT, -ENODATA))
17✔
UNCOV
1486
                log_warning_errno(r, "Failed to read EFI variable \"LoaderEntrySysFail\", ignoring: %m");
×
1487

1488
        return 1;
1489
}
1490

1491
int boot_config_select_special_entries(BootConfig *config, bool skip_efivars) {
31✔
1492
        int r;
31✔
1493

1494
        assert(config);
31✔
1495

1496
        r = boot_load_efi_entry_pointers(config, skip_efivars);
31✔
1497
        if (r < 0)
31✔
1498
                return r;
1499

1500
        config->default_entry = boot_entries_select_default(config);
31✔
1501
        config->selected_entry = boot_entries_select_selected(config);
31✔
1502

1503
        return 0;
31✔
1504
}
1505

1506
int boot_config_finalize(BootConfig *config) {
33✔
1507
        int r;
33✔
1508

1509
        typesafe_qsort(config->entries, config->n_entries, boot_entry_compare);
33✔
1510

1511
        r = boot_entries_uniquify(config->entries, config->n_entries);
33✔
1512
        if (r < 0)
33✔
UNCOV
1513
                return log_error_errno(r, "Failed to uniquify boot entries: %m");
×
1514

1515
        return 0;
1516
}
1517

1518
int boot_config_load(
33✔
1519
                BootConfig *config,
1520
                const char *esp_path,
1521
                const char *xbootldr_path) {
1522

1523
        int r;
33✔
1524

1525
        assert(config);
33✔
1526

1527
        if (esp_path) {
33✔
1528
                r = boot_loader_read_conf_path(config, esp_path, "/loader/loader.conf");
33✔
1529
                if (r < 0)
33✔
1530
                        return r;
1531

1532
                r = boot_entries_find_type1(config, esp_path, BOOT_ENTRY_ESP, "/loader/entries");
33✔
1533
                if (r < 0)
33✔
1534
                        return r;
1535

1536
                r = boot_entries_find_unified(config, esp_path, BOOT_ENTRY_ESP, "/EFI/Linux/");
33✔
1537
                if (r < 0)
33✔
1538
                        return r;
1539

1540
                r = boot_entries_find_unified_global_addons(config, esp_path, "/loader/addons/",
33✔
1541
                                                            &config->global_addons[BOOT_ENTRY_ESP]);
1542
                if (r < 0)
33✔
1543
                        return r;
1544
        }
1545

1546
        if (xbootldr_path) {
33✔
1547
                r = boot_entries_find_type1(config, xbootldr_path, BOOT_ENTRY_XBOOTLDR, "/loader/entries");
14✔
1548
                if (r < 0)
14✔
1549
                        return r;
1550

1551
                r = boot_entries_find_unified(config, xbootldr_path, BOOT_ENTRY_XBOOTLDR, "/EFI/Linux/");
14✔
1552
                if (r < 0)
14✔
1553
                        return r;
1554

1555
                r = boot_entries_find_unified_global_addons(config, xbootldr_path, "/loader/addons/",
14✔
1556
                                                            &config->global_addons[BOOT_ENTRY_XBOOTLDR]);
1557
                if (r < 0)
14✔
1558
                        return r;
1559
        }
1560

1561
        return boot_config_finalize(config);
33✔
1562
}
1563

UNCOV
1564
int boot_config_load_auto(
×
1565
                BootConfig *config,
1566
                const char *override_esp_path,
1567
                const char *override_xbootldr_path) {
1568

UNCOV
1569
        _cleanup_free_ char *esp_where = NULL, *xbootldr_where = NULL;
×
UNCOV
1570
        dev_t esp_devid = 0, xbootldr_devid = 0;
×
UNCOV
1571
        int r;
×
1572

1573
        assert(config);
×
1574

1575
        /* This function is similar to boot_entries_load_config(), however we automatically search for the
1576
         * ESP and the XBOOTLDR partition unless it is explicitly specified. Also, if the user did not pass
1577
         * an ESP or XBOOTLDR path directly, let's see if /run/boot-loader-entries/ exists. If so, let's
1578
         * read data from there, as if it was an ESP (i.e. loading both entries and loader.conf data from
1579
         * it). This allows other boot loaders to pass boot loader entry information to our tools if they
1580
         * want to. */
1581

UNCOV
1582
        if (!override_esp_path && !override_xbootldr_path) {
×
UNCOV
1583
                if (access("/run/boot-loader-entries/", F_OK) >= 0)
×
UNCOV
1584
                        return boot_config_load(config, "/run/boot-loader-entries/", NULL);
×
1585

UNCOV
1586
                if (errno != ENOENT)
×
UNCOV
1587
                        return log_error_errno(errno,
×
1588
                                               "Failed to determine whether /run/boot-loader-entries/ exists: %m");
1589
        }
1590

1591
        r = find_esp_and_warn_full(
×
1592
                        /* root= */ NULL,
1593
                        override_esp_path,
1594
                        /* unprivileged_mode= */ false,
1595
                        &esp_where,
1596
                        /* ret_part= */ NULL,
1597
                        /* ret_pstart= */ NULL,
1598
                        /* ret_psize= */ NULL,
1599
                        /* ret_uuid= */ NULL,
1600
                        &esp_devid);
1601
        if (r < 0) /* we don't log about ENOKEY here, but propagate it, leaving it to the caller to log */
×
1602
                return r;
1603

UNCOV
1604
        r = find_xbootldr_and_warn_full(
×
1605
                        /* root= */ NULL,
1606
                        override_xbootldr_path,
1607
                        /* unprivileged_mode= */ false,
1608
                        &xbootldr_where,
1609
                        /* ret_uuid= */ NULL,
1610
                        &xbootldr_devid);
UNCOV
1611
        if (r < 0 && r != -ENOKEY)
×
1612
                return r; /* It's fine if the XBOOTLDR partition doesn't exist, hence we ignore ENOKEY here */
1613

1614
        /* If both paths actually refer to the same inode, suppress the xbootldr path */
UNCOV
1615
        if (esp_where && xbootldr_where && devnum_set_and_equal(esp_devid, xbootldr_devid))
×
UNCOV
1616
                xbootldr_where = mfree(xbootldr_where);
×
1617

UNCOV
1618
        return boot_config_load(config, esp_where, xbootldr_where);
×
1619
}
1620

1621
int boot_config_augment_from_loader(
17✔
1622
                BootConfig *config,
1623
                char **found_by_loader,
1624
                bool auto_only) {
1625

1626
        static const BootEntryAddons no_addons = (BootEntryAddons) {};
17✔
1627
        static const char *const title_table[] = {
17✔
1628
                /* Pretty names for a few well-known automatically discovered entries. */
1629
                "auto-osx",                      "macOS",
1630
                "auto-windows",                  "Windows Boot Manager",
1631
                "auto-efi-shell",                "EFI Shell",
1632
                "auto-efi-default",              "EFI Default Loader",
1633
                "auto-poweroff",                 "Power Off The System",
1634
                "auto-reboot",                   "Reboot The System",
1635
                "auto-reboot-to-firmware-setup", "Reboot Into Firmware Interface",
1636
                NULL,
1637
        };
1638

1639
        assert(config);
17✔
1640

1641
        /* Let's add the entries discovered by the boot loader to the end of our list, unless they are
1642
         * already included there. */
1643

1644
        STRV_FOREACH(i, found_by_loader) {
85✔
1645
                BootEntry *existing;
68✔
1646
                _cleanup_free_ char *c = NULL, *t = NULL, *p = NULL;
48✔
1647

1648
                existing = boot_config_find_entry(config, *i);
68✔
1649
                if (existing) {
68✔
1650
                        existing->reported_by_loader = true;
20✔
1651
                        continue;
20✔
1652
                }
1653

1654
                if (auto_only && !startswith(*i, "auto-"))
48✔
1655
                        continue;
×
1656

1657
                c = strdup(*i);
48✔
1658
                if (!c)
48✔
UNCOV
1659
                        return log_oom();
×
1660

1661
                STRV_FOREACH_PAIR(a, b, title_table)
367✔
1662
                        if (streq(*a, *i)) {
336✔
1663
                                t = strdup(*b);
17✔
1664
                                if (!t)
17✔
UNCOV
1665
                                        return log_oom();
×
1666
                                break;
1667
                        }
1668

1669
                p = strdup(EFIVAR_PATH(EFI_LOADER_VARIABLE_STR("LoaderEntries")));
48✔
1670
                if (!p)
48✔
UNCOV
1671
                        return log_oom();
×
1672

1673
                if (!GREEDY_REALLOC0(config->entries, config->n_entries + 1))
48✔
UNCOV
1674
                        return log_oom();
×
1675

1676
                config->entries[config->n_entries++] = (BootEntry) {
96✔
1677
                        .type = startswith(*i, "auto-") ? BOOT_ENTRY_AUTO : BOOT_ENTRY_LOADER,
48✔
1678
                        .id = TAKE_PTR(c),
48✔
1679
                        .title = TAKE_PTR(t),
48✔
1680
                        .path = TAKE_PTR(p),
48✔
1681
                        .reported_by_loader = true,
1682
                        .tries_left = UINT_MAX,
1683
                        .tries_done = UINT_MAX,
1684
                        .profile = UINT_MAX,
1685
                        .global_addons = &no_addons,
1686
                };
1687
        }
1688

1689
        return 0;
1690
}
1691

1692
BootEntry* boot_config_find_entry(BootConfig *config, const char *id) {
72✔
1693
        assert(config);
72✔
1694
        assert(id);
72✔
1695

1696
        for (size_t j = 0; j < config->n_entries; j++)
217✔
1697
                if (strcaseeq_ptr(config->entries[j].id, id) ||
168✔
1698
                    strcaseeq_ptr(config->entries[j].id_old, id))
145✔
1699
                        return config->entries + j;
1700

1701
        return NULL;
1702
}
1703

1704
static void boot_entry_file_list(
9✔
1705
                const char *field,
1706
                const char *root,
1707
                const char *p,
1708
                int *ret_status) {
1709

1710
        assert(p);
9✔
1711
        assert(ret_status);
9✔
1712

1713
        int status = chase_and_access(p, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, F_OK, NULL);
9✔
1714

1715
        /* Note that this shows two '/' between the root and the file. This is intentional to highlight (in
1716
         * the absence of color support) to the user that the boot loader is only interested in the second
1717
         * part of the file. */
1718
        printf("%13s%s %s%s/%s", strempty(field), field ? ":" : " ", ansi_grey(), root, ansi_normal());
18✔
1719

1720
        if (status < 0) {
9✔
UNCOV
1721
                errno = -status;
×
UNCOV
1722
                printf("%s%s%s (%m)\n", ansi_highlight_red(), p, ansi_normal());
×
1723
        } else
1724
                printf("%s\n", p);
9✔
1725

1726
        if (*ret_status == 0 && status < 0)
9✔
UNCOV
1727
                *ret_status = status;
×
1728
}
9✔
1729

1730
static void print_addon(
9✔
1731
                BootEntryAddon *addon,
1732
                const char *addon_str) {
1733

1734
        printf("  %s: %s\n", addon_str, addon->location);
9✔
1735
        printf("      options: %s%s\n", glyph(GLYPH_TREE_RIGHT), addon->cmdline);
9✔
1736
}
9✔
1737

1738
static int indent_embedded_newlines(char *cmdline, char **ret_cmdline) {
18✔
1739
        _cleanup_free_ char *t = NULL;
18✔
1740
        _cleanup_strv_free_ char **ts = NULL;
18✔
1741

1742
        assert(ret_cmdline);
18✔
1743

1744
        ts = strv_split_newlines(cmdline);
18✔
1745
        if (!ts)
18✔
1746
                return -ENOMEM;
1747

1748
        t = strv_join(ts, "\n              ");
18✔
1749
        if (!t)
18✔
1750
                return -ENOMEM;
1751

1752
        *ret_cmdline = TAKE_PTR(t);
18✔
1753

1754
        return 0;
18✔
1755
}
1756

1757
static int print_cmdline(const BootEntry *e) {
20✔
1758

1759
        _cleanup_free_ char *options = NULL, *combined_cmdline = NULL, *t2 = NULL;
20✔
1760

1761
        assert(e);
20✔
1762

1763
        if (!strv_isempty(e->options)) {
20✔
1764
                _cleanup_free_ char *t = NULL;
9✔
1765

1766
                options = strv_join(e->options, " ");
9✔
1767
                if (!options)
9✔
UNCOV
1768
                        return log_oom();
×
1769

1770
                if (indent_embedded_newlines(options, &t) < 0)
9✔
UNCOV
1771
                        return log_oom();
×
1772

1773
                printf("      options: %s\n", t);
9✔
1774
                t2 = strdup(options);
9✔
1775
                if (!t2)
9✔
UNCOV
1776
                        return log_oom();
×
1777
        }
1778

1779
        FOREACH_ARRAY(addon, e->global_addons->items, e->global_addons->n_items) {
29✔
1780
                print_addon(addon, "global-addon");
9✔
1781
                if (!strextend(&t2, " ", addon->cmdline))
9✔
UNCOV
1782
                        return log_oom();
×
1783
        }
1784

1785
        FOREACH_ARRAY(addon, e->local_addons.items, e->local_addons.n_items) {
20✔
1786
                /* Add space at the beginning of addon_str to align it correctly */
1787
                print_addon(addon, " local-addon");
×
UNCOV
1788
                if (!strextend(&t2, " ", addon->cmdline))
×
UNCOV
1789
                        return log_oom();
×
1790
        }
1791

1792
        /* Don't print the combined cmdline if it's same as options. */
1793
        if (streq_ptr(t2, options))
20✔
1794
                return 0;
1795

1796
        if (indent_embedded_newlines(t2, &combined_cmdline) < 0)
9✔
UNCOV
1797
                return log_oom();
×
1798

1799
        if (combined_cmdline)
9✔
1800
                printf("      cmdline: %s\n", combined_cmdline);
9✔
1801

1802
        return 0;
1803
}
1804

1805
static int json_addon(
3✔
1806
                BootEntryAddon *addon,
1807
                const char *addon_str,
1808
                sd_json_variant **array) {
1809

1810
        int r;
3✔
1811

1812
        assert(addon);
3✔
1813
        assert(addon_str);
3✔
1814

1815
        r = sd_json_variant_append_arraybo(
3✔
1816
                        array,
1817
                        SD_JSON_BUILD_PAIR_STRING(addon_str, addon->location),
1818
                        SD_JSON_BUILD_PAIR_STRING("options", addon->cmdline));
1819
        if (r < 0)
3✔
UNCOV
1820
                return log_oom();
×
1821

1822
        return 0;
1823
}
1824

1825
static int json_cmdline(
13✔
1826
                const BootEntry *e,
1827
                const char *def_cmdline,
1828
                sd_json_variant **v) {
1829

1830
        _cleanup_free_ char *combined_cmdline = NULL;
13✔
1831
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *addons_array = NULL;
13✔
1832
        int r;
13✔
1833

1834
        assert(e);
13✔
1835

1836
        if (def_cmdline) {
13✔
1837
                combined_cmdline = strdup(def_cmdline);
3✔
1838
                if (!combined_cmdline)
3✔
UNCOV
1839
                        return log_oom();
×
1840
        }
1841

1842
        FOREACH_ARRAY(addon, e->global_addons->items, e->global_addons->n_items) {
16✔
1843
                r = json_addon(addon, "globalAddon", &addons_array);
3✔
1844
                if (r < 0)
3✔
1845
                        return r;
1846
                if (!strextend(&combined_cmdline, " ", addon->cmdline))
3✔
UNCOV
1847
                        return log_oom();
×
1848
        }
1849

1850
        FOREACH_ARRAY(addon, e->local_addons.items, e->local_addons.n_items) {
13✔
UNCOV
1851
                r = json_addon(addon, "localAddon", &addons_array);
×
UNCOV
1852
                if (r < 0)
×
1853
                        return r;
UNCOV
1854
                if (!strextend(&combined_cmdline, " ", addon->cmdline))
×
UNCOV
1855
                        return log_oom();
×
1856
        }
1857

1858
        r = sd_json_variant_merge_objectbo(
13✔
1859
                        v,
1860
                        SD_JSON_BUILD_PAIR_VARIANT("addons", addons_array),
1861
                        SD_JSON_BUILD_PAIR_CONDITION(!!combined_cmdline, "cmdline", SD_JSON_BUILD_STRING(combined_cmdline)));
1862
        if (r < 0)
13✔
UNCOV
1863
                return log_oom();
×
1864
        return 0;
1865
}
1866

1867
int show_boot_entry(
20✔
1868
                const BootEntry *e,
1869
                bool show_as_default,
1870
                bool show_as_selected,
1871
                bool show_reported) {
1872

1873
        int status = 0, r = 0;
20✔
1874

1875
        /* Returns 0 on success, negative on processing error, and positive if something is wrong with the
1876
           boot entry itself. */
1877

1878
        assert(e);
20✔
1879

1880
        printf("         type: %s\n",
20✔
1881
               boot_entry_type_description_to_string(e->type));
20✔
1882

1883
        printf("        title: %s%s%s",
60✔
1884
               ansi_highlight(), boot_entry_title(e), ansi_normal());
1885

1886
        if (show_as_default)
20✔
1887
                printf(" %s(default)%s",
4✔
1888
                       ansi_highlight_green(), ansi_normal());
1889

1890
        if (show_as_selected)
20✔
1891
                printf(" %s(selected)%s",
4✔
1892
                       ansi_highlight_magenta(), ansi_normal());
1893

1894
        if (show_reported) {
20✔
1895
                if (e->type == BOOT_ENTRY_LOADER)
8✔
1896
                        printf(" %s(reported/absent)%s",
12✔
1897
                               ansi_highlight_red(), ansi_normal());
1898
                else if (!e->reported_by_loader && e->type != BOOT_ENTRY_AUTO)
2✔
UNCOV
1899
                        printf(" %s(not reported/new)%s",
×
1900
                               ansi_highlight_green(), ansi_normal());
1901
        }
1902

1903
        putchar('\n');
20✔
1904

1905
        if (e->id) {
20✔
1906
                printf("           id: %s", e->id);
20✔
1907

1908
                if (e->id_without_profile && !streq_ptr(e->id, e->id_without_profile))
20✔
1909
                        printf(" (without profile: %s)\n", e->id_without_profile);
9✔
1910
                else
1911
                        putchar('\n');
11✔
1912
        }
1913
        if (e->path) {
20✔
1914
                _cleanup_free_ char *text = NULL, *link = NULL;
20✔
1915

1916
                const char *p = e->root ? path_startswith(e->path, e->root) : NULL;
20✔
1917
                if (p) {
9✔
1918
                        text = strjoin(ansi_grey(), e->root, "/", ansi_normal(), "/", p);
18✔
1919
                        if (!text)
9✔
UNCOV
1920
                                return log_oom();
×
1921
                }
1922

1923
                /* Let's urlify the link to make it easy to view in an editor, but only if it is a text
1924
                 * file. Unified images are binary ELFs, and EFI variables are not pure text either. */
1925
                if (e->type == BOOT_ENTRY_TYPE1)
20✔
1926
                        (void) terminal_urlify_path(e->path, text, &link);
×
1927

1928
                printf("       source: %s (on the %s)\n",
20✔
1929
                       link ?: text ?: e->path,
20✔
1930
                       boot_entry_source_description_to_string(e->source));
20✔
1931
        }
1932
        if (e->tries_left != UINT_MAX) {
20✔
UNCOV
1933
                printf("        tries: %u left", e->tries_left);
×
1934

UNCOV
1935
                if (e->tries_done != UINT_MAX)
×
1936
                        printf("; %u done\n", e->tries_done);
×
1937
                else
1938
                        putchar('\n');
×
1939
        }
1940

1941
        if (e->sort_key)
20✔
1942
                printf("     sort-key: %s\n", e->sort_key);
9✔
1943
        if (e->version)
20✔
1944
                printf("      version: %s\n", e->version);
9✔
1945
        if (e->machine_id)
20✔
1946
                printf("   machine-id: %s\n", e->machine_id);
×
1947
        if (e->architecture)
20✔
UNCOV
1948
                printf(" architecture: %s\n", e->architecture);
×
1949
        if (e->kernel)
20✔
1950
                boot_entry_file_list("linux", e->root, e->kernel, &status);
9✔
1951
        if (e->efi)
20✔
1952
                boot_entry_file_list("efi", e->root, e->efi, &status);
×
1953
        if (e->uki)
20✔
UNCOV
1954
                boot_entry_file_list("uki", e->root, e->uki, &status);
×
1955
        if (e->uki_url)
20✔
UNCOV
1956
                printf("      uki-url: %s\n", e->uki_url);
×
1957
        if (e->profile != UINT_MAX)
20✔
1958
                printf("      profile: %u\n", e->profile);
9✔
1959

1960
        STRV_FOREACH(s, e->initrd)
20✔
1961
                boot_entry_file_list(s == e->initrd ? "initrd" : NULL,
×
UNCOV
1962
                                     e->root,
×
1963
                                     *s,
1964
                                     &status);
1965

1966
        r = print_cmdline(e);
20✔
1967
        if (r < 0)
20✔
1968
                return r;
1969

1970
        if (e->device_tree)
20✔
UNCOV
1971
                boot_entry_file_list("devicetree", e->root, e->device_tree, &status);
×
1972

1973
        STRV_FOREACH(s, e->device_tree_overlay)
20✔
UNCOV
1974
                boot_entry_file_list(s == e->device_tree_overlay ? "devicetree-overlay" : NULL,
×
UNCOV
1975
                                     e->root,
×
1976
                                     *s,
1977
                                     &status);
1978

1979
        return -status;
20✔
1980
}
1981

1982
int boot_entry_to_json(const BootConfig *c, size_t i, sd_json_variant **ret) {
13✔
1983
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
13✔
1984
        _cleanup_free_ char *opts = NULL;
13✔
1985
        const BootEntry *e;
13✔
1986
        int r;
13✔
1987

1988
        assert(c);
13✔
1989
        assert(ret);
13✔
1990

1991
        if (i >= c->n_entries) {
13✔
UNCOV
1992
                *ret = NULL;
×
UNCOV
1993
                return 0;
×
1994
        }
1995

1996
        e = c->entries + i;
13✔
1997

1998
        if (!strv_isempty(e->options)) {
13✔
1999
                opts = strv_join(e->options, " ");
3✔
2000
                if (!opts)
3✔
UNCOV
2001
                        return log_oom();
×
2002
        }
2003

2004
        r = sd_json_variant_merge_objectbo(
13✔
2005
                        &v,
2006
                        SD_JSON_BUILD_PAIR_STRING("type", boot_entry_type_to_string(e->type)),
2007
                        SD_JSON_BUILD_PAIR_STRING("source", boot_entry_source_to_string(e->source)),
2008
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->id, "id", SD_JSON_BUILD_STRING(e->id)),
2009
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->path, "path", SD_JSON_BUILD_STRING(e->path)),
2010
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->root, "root", SD_JSON_BUILD_STRING(e->root)),
2011
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->title, "title", SD_JSON_BUILD_STRING(e->title)),
2012
                        SD_JSON_BUILD_PAIR_CONDITION(!!boot_entry_title(e), "showTitle", SD_JSON_BUILD_STRING(boot_entry_title(e))),
2013
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->sort_key, "sortKey", SD_JSON_BUILD_STRING(e->sort_key)),
2014
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->version, "version", SD_JSON_BUILD_STRING(e->version)),
2015
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->machine_id, "machineId", SD_JSON_BUILD_STRING(e->machine_id)),
2016
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->architecture, "architecture", SD_JSON_BUILD_STRING(e->architecture)),
2017
                        SD_JSON_BUILD_PAIR_CONDITION(!!opts, "options", SD_JSON_BUILD_STRING(opts)),
2018
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->kernel, "linux", SD_JSON_BUILD_STRING(e->kernel)),
2019
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->efi, "efi", SD_JSON_BUILD_STRING(e->efi)),
2020
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->uki, "uki", SD_JSON_BUILD_STRING(e->uki)),
2021
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->uki_url, "ukiUrl", SD_JSON_BUILD_STRING(e->uki_url)),
2022
                        SD_JSON_BUILD_PAIR_CONDITION(e->profile != UINT_MAX, "profile", SD_JSON_BUILD_UNSIGNED(e->profile)),
2023
                        SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(e->initrd), "initrd", SD_JSON_BUILD_STRV(e->initrd)));
2024
        if (r < 0)
13✔
UNCOV
2025
                return log_oom();
×
2026

2027
        /* Sanitizers (only memory sanitizer?) do not like function call with too many
2028
         * arguments and trigger false positive warnings. Let's not add too many json objects
2029
         * at once. */
2030
        r = sd_json_variant_merge_objectbo(
13✔
2031
                        &v,
2032
                        SD_JSON_BUILD_PAIR_CONDITION(!!e->device_tree, "devicetree", SD_JSON_BUILD_STRING(e->device_tree)),
2033
                        SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(e->device_tree_overlay), "devicetreeOverlay", SD_JSON_BUILD_STRV(e->device_tree_overlay)),
2034
                        SD_JSON_BUILD_PAIR_BOOLEAN("isReported", e->reported_by_loader),
2035
                        SD_JSON_BUILD_PAIR_CONDITION(e->tries_left != UINT_MAX, "triesLeft", SD_JSON_BUILD_UNSIGNED(e->tries_left)),
2036
                        SD_JSON_BUILD_PAIR_CONDITION(e->tries_done != UINT_MAX, "triesDone", SD_JSON_BUILD_UNSIGNED(e->tries_done)),
2037
                        SD_JSON_BUILD_PAIR_CONDITION(c->default_entry >= 0, "isDefault", SD_JSON_BUILD_BOOLEAN(i == (size_t) c->default_entry)),
2038
                        SD_JSON_BUILD_PAIR_CONDITION(c->selected_entry >= 0, "isSelected", SD_JSON_BUILD_BOOLEAN(i == (size_t) c->selected_entry)));
2039
        if (r < 0)
13✔
UNCOV
2040
                return log_oom();
×
2041

2042
        r = json_cmdline(e, opts, &v);
13✔
2043
        if (r < 0)
13✔
UNCOV
2044
                return log_oom();
×
2045

2046
        *ret = TAKE_PTR(v);
13✔
2047
        return 1;
13✔
2048
}
2049

2050
int show_boot_entries(const BootConfig *config, sd_json_format_flags_t json_format) {
8✔
2051
        int r;
8✔
2052

2053
        assert(config);
8✔
2054

2055
        if (sd_json_format_enabled(json_format)) {
8✔
2056
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *array = NULL;
6✔
2057

2058
                for (size_t i = 0; i < config->n_entries; i++) {
14✔
2059
                        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
8✔
2060

2061
                        r = boot_entry_to_json(config, i, &v);
8✔
2062
                        if (r < 0)
8✔
UNCOV
2063
                                return log_oom();
×
2064

2065
                        r = sd_json_variant_append_array(&array, v);
8✔
2066
                        if (r < 0)
8✔
UNCOV
2067
                                return log_oom();
×
2068
                }
2069

2070
                return sd_json_variant_dump(array, json_format | SD_JSON_FORMAT_EMPTY_ARRAY, NULL, NULL);
6✔
2071
        } else
2072
                for (size_t n = 0; n < config->n_entries; n++) {
10✔
2073
                        r = show_boot_entry(
16✔
2074
                                        config->entries + n,
8✔
2075
                                        /* show_as_default= */  n == (size_t) config->default_entry,
8✔
2076
                                        /* show_as_selected= */ n == (size_t) config->selected_entry,
8✔
2077
                                        /* show_reported= */  true);
2078
                        if (r < 0)
8✔
2079
                                return r;
2080

2081
                        if (n+1 < config->n_entries)
8✔
2082
                                putchar('\n');
6✔
2083
                }
2084

2085
        return 0;
2086
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc