HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/boot/boot.c

153,971 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 91c82b3536d2e6cb8dcb6498d9825975a409d28a

Lines 1001–2000 of 3,525

                        break;
                default:
                        assert(config->timeout_sec_efivar < UINT32_MAX);
                        efivar_set_uint64_str16(MAKE_GUID_PTR(LOADER), u"LoaderConfigTimeout",
                                                config->timeout_sec_efivar, EFI_VARIABLE_NON_VOLATILE);
                }
        }
 
        switch (action) {
        case ACTION_CONTINUE:
                assert_not_reached();
        case ACTION_POWEROFF:
                (void) call_poweroff_system(/* entry= */ NULL, /* root_dir= */ NULL, /* parent_image= */ NULL);
        case ACTION_REBOOT:
        case ACTION_FIRMWARE_SETUP:
                (void) call_reboot_system(/* entry= */ NULL, /* root_dir= */ NULL, /* parent_image= */ NULL);
        case ACTION_RUN:
        case ACTION_QUIT:
                break;
        }
 
        *chosen_entry = config->entries[idx_highlight];
        clear_screen(COLOR_NORMAL);
        return action == ACTION_RUN;
}
 
static void config_add_entry(Config *config, BootEntry *entry) {
        assert(config);
        assert(entry);
 
        /* This is just for paranoia. */
        assert(config->n_entries < IDX_MAX);
 
        if ((config->n_entries & 15) == 0)
                config->entries = xrealloc(
                                config->entries,
                                sizeof(void *) * config->n_entries,
                                sizeof(void *) * (config->n_entries + 16));
        config->entries[config->n_entries++] = entry;
}
 
static BootEntry* boot_entry_free(BootEntry *entry) {
        if (!entry)
                return NULL;
 
        free(entry->id);
        free(entry->id_without_profile);
        free(entry->title_show);
        free(entry->title);
        free(entry->sort_key);
        free(entry->version);
        free(entry->machine_id);
        free(entry->loader);
        free(entry->url);
        free(entry->devicetree);
        free(entry->options);
        strv_free(entry->initrd);
        strv_free(entry->extras);
        free(entry->directory);
        free(entry->current_name);
        free(entry->next_name);
 
        return mfree(entry);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(BootEntry *, boot_entry_free);
 
static EFI_STATUS config_timeout_sec_from_string(const char *value, uint64_t *dst) {
        assert(dst);
 
        if (streq8(value, "menu-disabled"))
                *dst = TIMEOUT_MENU_DISABLED;
        else if (streq8(value, "menu-force"))
                *dst = TIMEOUT_MENU_FORCE;
        else if (streq8(value, "menu-hidden"))
                *dst = TIMEOUT_MENU_HIDDEN;
        else {
                uint64_t u;
                if (!parse_number8(value, &u, NULL) || u > TIMEOUT_TYPE_MAX)
                        return EFI_INVALID_PARAMETER;
                *dst = u;
        }
        return EFI_SUCCESS;
}
 
static void config_timeout_load_from_smbios(Config *config) {
        EFI_STATUS err;
 
        if (is_confidential_vm())
                return; /* Don't consume SMBIOS in Confidential Computing contexts */
 
        const char *value = smbios_find_oem_string("io.systemd.boot.timeout=", /* after= */ NULL);
        if (!value)
                return;
 
        err = config_timeout_sec_from_string(value, &config->timeout_sec_smbios);
        if (err != EFI_SUCCESS) {
                log_warning_status(err, "Error parsing 'timeout' smbios option, ignoring: %s",
                                   value);
                return;
        }
        config->timeout_sec = config->timeout_sec_smbios;
}
 
static void config_defaults_load_from_file(Config *config, char *content) {
        char *line;
        size_t pos = 0;
        char *key, *value;
 
        assert(config);
        assert(content);
 
        /* If you add, remove, or change an option name here, please also update
         * shared/bootspec.c@boot_loader_read_conf() to make parsing by bootctl/logind/etc. work. */
        while ((line = line_get_key_value(content, " \t", &pos, &key, &value)))
                if (streq8(key, "timeout")) {
                        EFI_STATUS err = config_timeout_sec_from_string(value, &config->timeout_sec_config);
                        if (err != EFI_SUCCESS) {
                                log_warning_status(err, "Error parsing 'timeout' config option, ignoring: %s",
                                                   value);
                                continue;
                        }
                        config->timeout_sec = config->timeout_sec_config;
 
                } else if (streq8(key, "default")) {
                        if (value[0] == '@' && !strcaseeq8(value, "@saved")) {
                                log_warning("Unsupported special entry identifier, ignoring: %s", value);
                                continue;
                        }
                        free(config->entry_default_config);
                        config->entry_default_config = xstr8_to_16(value);
 
                } else if (streq8(key, "preferred")) {
                        if (value[0] == '@' && !strcaseeq8(value, "@saved")) {
                                log_warning("Unsupported special entry identifier, ignoring: %s", value);
                                continue;
                        }
                        free(config->entry_preferred_config);
                        config->entry_preferred_config = xstr8_to_16(value);
 
                } else if (streq8(key, "editor")) {
                        if (!parse_boolean(value, &config->editor))
                                log_warning("Error parsing 'editor' config option, ignoring: %s", value);
 
                } else if (streq8(key, "auto-entries")) {
                        if (!parse_boolean(value, &config->auto_entries))
                                log_warning("Error parsing 'auto-entries' config option, ignoring: %s", value);
 
                } else if (streq8(key, "auto-firmware")) {
                        if (!parse_boolean(value, &config->auto_firmware))
                                log_warning("Error parsing 'auto-firmware' config option, ignoring: %s", value);
 
                } else if (streq8(key, "auto-poweroff")) {
                        if (!parse_boolean(value, &config->auto_poweroff))
                                log_warning("Error parsing 'auto-poweroff' config option, ignoring: %s", value);
 
                } else if (streq8(key, "auto-reboot")) {
                        if (!parse_boolean(value, &config->auto_reboot))
                                log_warning("Error parsing 'auto-reboot' config option, ignoring: %s", value);
 
                } else if (streq8(key, "beep")) {
                        if (!parse_boolean(value, &config->beep))
                                log_warning("Error parsing 'beep' config option, ignoring: %s", value);
 
                } else if (streq8(key, "reboot-for-bitlocker")) {
                        if (!parse_boolean(value, &config->reboot_for_bitlocker))
                                log_warning("Error parsing 'reboot-for-bitlocker' config option, ignoring: %s",
                                          value);
 
                } else if (streq8(key, "reboot-on-error")) {
                        if (streq8(value, "auto"))
                                config->reboot_on_error = REBOOT_AUTO;
                        else {
                                bool reboot_yes_no;
                                if (!parse_boolean(value, &reboot_yes_no))
                                        log_warning("Error parsing 'reboot-on-error' config option, ignoring: %s", value);
                                else
                                        config->reboot_on_error = reboot_yes_no ? REBOOT_YES : REBOOT_NO;
                        }
 
                } else if (streq8(key, "secure-boot-enroll")) {
                        if (streq8(value, "manual"))
                                config->secure_boot_enroll = ENROLL_MANUAL;
                        else if (streq8(value, "force"))
                                config->secure_boot_enroll = ENROLL_FORCE;
                        else if (streq8(value, "if-safe"))
                                config->secure_boot_enroll = ENROLL_IF_SAFE;
                        else if (streq8(value, "off"))
                                config->secure_boot_enroll = ENROLL_OFF;
                        else
                                log_warning("Error parsing 'secure-boot-enroll' config option, ignoring: %s",
                                          value);
                } else if (streq8(key, "secure-boot-enroll-action")) {
                        if (streq8(value, "reboot"))
                                config->secure_boot_enroll_action = ENROLL_ACTION_REBOOT;
                        else if (streq8(value, "shutdown"))
                                config->secure_boot_enroll_action = ENROLL_ACTION_SHUTDOWN;
                        else
                                log_warning("Error parsing 'secure-boot-enroll-action' config option, ignoring: %s",
                                          value);
                } else if (streq8(key, "secure-boot-enroll-timeout-sec")) {
                        if (streq8(value, "hidden"))
                                config->secure_boot_enroll_timeout_sec = ENROLL_TIMEOUT_HIDDEN;
                        else {
                                uint64_t u;
                                if (!parse_number8(value, &u, NULL) || u > ENROLL_TIMEOUT_MAX) {
                                        log_warning("Error parsing 'secure-boot-enroll-timeout-sec' config option, ignoring: %s",
                                                  value);
                                        continue;
                                }
                                config->secure_boot_enroll_timeout_sec = u;
                        }
                } else if (streq8(key, "console-mode")) {
                        if (streq8(value, "auto"))
                                config->console_mode = CONSOLE_MODE_AUTO;
                        else if (streq8(value, "max"))
                                config->console_mode = CONSOLE_MODE_FIRMWARE_MAX;
                        else if (streq8(value, "keep"))
                                config->console_mode = CONSOLE_MODE_KEEP;
                        else {
                                uint64_t u;
                                if (!parse_number8(value, &u, NULL) || u > CONSOLE_MODE_RANGE_MAX) {
                                        log_warning("Error parsing 'console-mode' config option, ignoring: %s",
                                                  value);
                                        continue;
                                }
                                config->console_mode = u;
                        }
                } else if (streq8(key, "log-level")) {
                        if (log_set_max_level_from_string(value) < 0)
                                log_warning("Error parsing 'log-level' config option, ignoring: %s", value);
                }
}
 
static void boot_entry_parse_tries(
                BootEntry *entry,
                const char16_t *directory,
                const char16_t *file,
                const char16_t *suffix) {
 
        assert(entry);
        assert(directory);
        assert(file);
        assert(suffix);
 
        /*
         * Parses a suffix of two counters (one going down, one going up) in the form "+LEFT-DONE" from the end of the
         * filename (but before the .efi/.conf suffix), where the "-DONE" part is optional and may be left out (in
         * which case that counter as assumed to be zero, i.e. the missing part is synonymous to "-0").
         *
         * Names we grok, and the series they result in:
         *
         * foobar+3.efi   → foobar+2-1.efi → foobar+1-2.efi → foobar+0-3.efi → STOP!
         * foobar+4-0.efi → foobar+3-1.efi → foobar+2-2.efi → foobar+1-3.efi → foobar+0-4.efi → STOP!
         */
 
        const char16_t *counter = NULL;
        for (;;) {
                char16_t *plus = strchr16(counter ?: file, '+');
                if (plus) {
                        /* We want the last "+". */
                        counter = plus + 1;
                        continue;
                }
                if (counter)
                        break;
 
                /* No boot counter found. */
                return;
        }
 
        uint64_t tries_left, tries_done = 0;
        size_t prefix_len = counter - file;
 
        if (!parse_number16(counter, &tries_left, &counter) || tries_left > INT_MAX)
                return;
 
        /* Parse done counter only if present. */
        if (*counter == '-' && (!parse_number16(counter + 1, &tries_done, &counter) || tries_done > INT_MAX))
                return;
 
        /* Boot counter in the middle of the name? */
        if (!strcaseeq16(counter, suffix))
                return;
 
        entry->id = xasprintf("%.*ls%ls",
                        (int) prefix_len - 1,
                        file,
                        suffix);
        entry->tries_left = tries_left;
        entry->tries_done = tries_done;
        entry->directory = xstrdup16(directory);
        entry->current_name = xstrdup16(file);
        entry->next_name = xasprintf(
                        "%.*ls%" PRIu64 "-%" PRIu64 "%ls",
                        (int) prefix_len,
                        file,
                        LESS_BY(tries_left, 1u),
                        MIN(tries_done + 1, (uint64_t) INT_MAX),
                        suffix);
}
 
static EFI_STATUS boot_entry_bump_counters(BootEntry *entry) {
        _cleanup_free_ char16_t* old_path = NULL, *new_path = NULL;
        _cleanup_file_close_ EFI_FILE *handle = NULL;
        _cleanup_free_ EFI_FILE_INFO *file_info = NULL;
        size_t file_info_size;
        EFI_STATUS err;
 
        assert(entry);
 
        if (!LOADER_TYPE_BUMP_COUNTERS(entry->type))
                return EFI_SUCCESS;
 
        if (entry->tries_left < 0)
                return EFI_SUCCESS;
 
        if (!entry->directory || !entry->current_name || !entry->next_name)
                return EFI_SUCCESS;
 
        _cleanup_file_close_ EFI_FILE *root = NULL;
        err = open_volume(entry->device, &root);
        if (err != EFI_SUCCESS)
                return log_error_status(err, "Error opening entry root path: %m");
 
        old_path = xasprintf("%ls\\%ls", entry->directory, entry->current_name);
 
        err = root->Open(root, &handle, old_path, EFI_FILE_MODE_READ|EFI_FILE_MODE_WRITE, 0ULL);
        if (EFI_STATUS_IS_WRITE_REFUSED(err))
                goto read_only;
        if (err != EFI_SUCCESS)
                return log_error_status(err, "Error opening boot entry '%ls': %m", old_path);
 
        err = get_file_info(handle, &file_info, &file_info_size);
        if (err != EFI_SUCCESS)
                return log_error_status(err, "Error getting boot entry file info: %m");
 
        /* If the boot entry file is marked read-only take this as a hint that the boot counter logic shall
         * not be applied to it, and skip it. */
        if (FLAGS_SET(file_info->Attribute, EFI_FILE_READ_ONLY))
                goto read_only;
 
        /* And rename the file */
        strcpy16(file_info->FileName, entry->next_name);
        err = handle->SetInfo(handle, MAKE_GUID_PTR(EFI_FILE_INFO), file_info_size, file_info);
        if (err != EFI_SUCCESS)
                return log_error_status(
                                err, "Failed to rename '%ls' to '%ls', ignoring: %m", old_path, entry->next_name);
 
        /* Flush everything to disk, just in case… */
        err = handle->Flush(handle);
        if (err != EFI_SUCCESS)
                return log_error_status(err, "Error flushing boot entry file info: %m");
 
        /* Let's tell the OS that we renamed this file, so that it knows what to rename to the counter-less name on
         * success */
        new_path = xasprintf("%ls\\%ls", entry->directory, entry->next_name);
        efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderBootCountPath", new_path, 0);
 
        /* If the file we just renamed is the loader path, then let's update that. */
        if (streq16(entry->loader, old_path)) {
                free(entry->loader);
                entry->loader = TAKE_PTR(new_path);
        }
 
        return EFI_SUCCESS;
 
read_only:
        log_debug("Boot entry '%ls' is read-only, skipping boot counter logic.", old_path);
        return EFI_SUCCESS;
}
 
static EFI_STATUS call_image_start(const BootEntry *entry, EFI_FILE *root_dir, EFI_HANDLE parent_image);
 
static void boot_entry_add_type1(
                Config *config,
                EFI_HANDLE *device,
                EFI_FILE *root_dir,
                const char16_t *path,
                const char16_t *file,
                char *content,
                const char16_t *loaded_image_path) {
 
        _cleanup_(boot_entry_freep) BootEntry *entry = NULL;
        char *line;
        size_t pos = 0, n_initrd = 0, n_extras = 0;
        char *key, *value;
        EFI_STATUS err;
 
        assert(config);
        assert(device);
        assert(root_dir);
        assert(file);
        assert(content);
 
        entry = xnew(BootEntry, 1);
        *entry = (BootEntry) {
                .tries_done = -1,
                .tries_left = -1,
                .call = call_image_start,
        };
 
        /* If you add, remove, or change an option name here, please also update shared/bootspec.c and
         * shared/varlink-io.systemd.BootControl to make parsing by bootctl/logind/etc. work. */
        while ((line = line_get_key_value(content, " \t", &pos, &key, &value)))
                if (streq8(key, "title")) {
                        free(entry->title);
                        entry->title = xstr8_to_16(value);
 
                } else if (streq8(key, "sort-key")) {
                        free(entry->sort_key);
                        entry->sort_key = xstr8_to_16(value);
 
                } else if (streq8(key, "profile")) {
                        uint64_t u;
                        if (parse_number8(value, &u, NULL) && u <= UINT_MAX)
                                entry->profile = (unsigned)u;
                        else
                                log_warning("Error parsing 'profile' entry option, ignoring: %s", value);
 
                } else if (streq8(key, "version")) {
                        free(entry->version);
                        entry->version = xstr8_to_16(value);
 
                } else if (streq8(key, "machine-id")) {
                        free(entry->machine_id);
                        entry->machine_id = xstr8_to_16(value);
 
                } else if (streq8(key, "linux")) {
 
                        if (!IN_SET(entry->type, LOADER_UNDEFINED, LOADER_LINUX)) {
                                entry->type = LOADER_BAD;
                                break;
                        }
 
                        free(entry->loader);
                        entry->type = LOADER_LINUX;
                        entry->loader = xstr8_to_path(value);
                        entry->key = 'l';
 
                } else if (streq8(key, "uki")) {
 
                        if (!IN_SET(entry->type, LOADER_UNDEFINED, LOADER_UKI)) {
                                entry->type = LOADER_BAD;
                                break;
                        }
 
                        free(entry->loader);
                        entry->type = LOADER_UKI;
                        entry->loader = xstr8_to_path(value);
                        entry->key = 'l';
 
                } else if (streq8(key, "uki-url")) {
 
                        if (!IN_SET(entry->type, LOADER_UNDEFINED, LOADER_UKI_URL)) {
                                entry->type = LOADER_BAD;
                                break;
                        }
 
                        _cleanup_free_ char16_t *p = xstr8_to_16(value);
 
                        const char16_t *e = startswith(p, u":");
                        if (e) {
                                _cleanup_free_ char16_t *origin = disk_get_url(device);
 
                                if (!origin) {
                                        /* Automatically hide entries that require an original URL but where none is available. */
                                        entry->type = LOADER_IGNORE;
                                        break;
                                }
 
                                entry->url = url_replace_last_component(origin, p);
                        } else
                                entry->url = TAKE_PTR(p);
 
                        entry->type = LOADER_UKI_URL;
                        entry->key = 'l';
 
                } else if (streq8(key, "efi")) {
 
                        if (!IN_SET(entry->type, LOADER_UNDEFINED, LOADER_EFI)) {
                                entry->type = LOADER_BAD;
                                break;
                        }
 
                        entry->type = LOADER_EFI;
                        free(entry->loader);
                        entry->loader = xstr8_to_path(value);
 
                        /* do not add an entry for ourselves */
                        if (strcaseeq16(entry->loader, loaded_image_path)) {
                                entry->type = LOADER_IGNORE;
                                break;
                        }
 
                } else if (streq8(key, "architecture")) {
                        /* do not add an entry for an EFI image of architecture not matching with that of the image */
                        if (!strcaseeq8(value, EFI_MACHINE_TYPE_NAME)) {
                                entry->type = LOADER_IGNORE;
                                break;
                        }
 
                } else if (streq8(key, "devicetree")) {
                        free(entry->devicetree);
                        entry->devicetree = xstr8_to_path(value);
 
                } else if (streq8(key, "initrd")) {
                        entry->initrd = xrealloc(
                                entry->initrd,
                                n_initrd == 0 ? 0 : (n_initrd + 1) * sizeof(uint16_t *),
                                (n_initrd + 2) * sizeof(uint16_t *));
                        entry->initrd[n_initrd++] = xstr8_to_path(value);
                        entry->initrd[n_initrd] = NULL;
 
                } else if (streq8(key, "extra")) {
                        entry->extras = xrealloc(
                                entry->extras,
                                n_extras == 0 ? 0 : (n_extras + 1) * sizeof(uint16_t *),
                                (n_extras + 2) * sizeof(uint16_t *));
                        entry->extras[n_extras++] = xstr8_to_path(value);
                        entry->extras[n_extras] = NULL;
 
                } else if (streq8(key, "options")) {
                        _cleanup_free_ char16_t *new = NULL;
 
                        new = xstr8_to_16(value);
                        if (entry->options) {
                                char16_t *s = xasprintf("%ls %ls", entry->options, new);
                                free(entry->options);
                                entry->options = s;
                        } else
                                entry->options = TAKE_PTR(new);
                }
 
        /* Filter all entries that are badly defined or don't apply to the local system. */
        if (IN_SET(entry->type, LOADER_UNDEFINED, LOADER_BAD, LOADER_IGNORE))
                return;
 
        /* Check existence of loader file */
        if (entry->loader) {
                _cleanup_file_close_ EFI_FILE *handle = NULL;
                err = root_dir->Open(root_dir, &handle, entry->loader, EFI_FILE_MODE_READ, 0ULL);
                if (err != EFI_SUCCESS)
                        return;
        }
 
        entry->device = device;
 
        if (path)
                boot_entry_parse_tries(entry, path, file, u".conf");
 
        if (!entry->id)
                entry->id = xstrdup16(file);
 
        strtolower16(entry->id);
 
        config_add_entry(config, entry);
        TAKE_PTR(entry);
}
 
static EFI_STATUS efivar_get_timeout(const char16_t *var, uint64_t *ret_value) {
        _cleanup_free_ char16_t *value = NULL;
        EFI_STATUS err;
 
        assert(var);
        assert(ret_value);
 
        err = efivar_get_str16(MAKE_GUID_PTR(LOADER), var, &value);
        if (err != EFI_SUCCESS)
                return err;
 
        if (streq16(value, u"menu-disabled")) {
                *ret_value = TIMEOUT_MENU_DISABLED;
                return EFI_SUCCESS;
        }
        if (streq16(value, u"menu-force")) {
                *ret_value = TIMEOUT_MENU_FORCE;
                return EFI_SUCCESS;
        }
        if (streq16(value, u"menu-hidden")) {
                *ret_value = TIMEOUT_MENU_HIDDEN;
                return EFI_SUCCESS;
        }
 
        uint64_t timeout;
        if (!parse_number16(value, &timeout, NULL))
                return EFI_INVALID_PARAMETER;
 
        *ret_value = MIN(timeout, TIMEOUT_TYPE_MAX);
        return EFI_SUCCESS;
}
 
static void config_load_defaults(Config *config, EFI_FILE *root_dir) {
        _cleanup_free_ char *content = NULL;
        size_t content_size;
        EFI_STATUS err;
 
        assert(root_dir);
        assert(config);
 
        *config = (Config) {
                .editor = true,
                .auto_entries = true,
                .auto_firmware = true,
                .reboot_on_error = REBOOT_AUTO,
                .secure_boot_enroll = ENROLL_IF_SAFE,
                .secure_boot_enroll_action = ENROLL_ACTION_REBOOT,
                .secure_boot_enroll_timeout_sec = ENROLL_TIMEOUT_DEFAULT,
                .idx_default_efivar = IDX_INVALID,
                .console_mode = CONSOLE_MODE_KEEP,
                .console_mode_efivar = CONSOLE_MODE_KEEP,
                .timeout_sec_config = TIMEOUT_UNSET,
                .timeout_sec_efivar = TIMEOUT_UNSET,
                .timeout_sec_smbios = TIMEOUT_UNSET,
        };
 
        err = file_read(root_dir, u"\\loader\\loader.conf", 0, 0, &content, &content_size);
        if (err == EFI_SUCCESS) {
                /* First, measure. */
                err = tpm_log_tagged_event(
                                TPM2_PCR_BOOT_LOADER_CONFIG,
                                POINTER_TO_PHYSICAL_ADDRESS(content),
                                content_size,
                                LOADER_CONF_EVENT_TAG_ID,
                                u"loader.conf",
                                /* ret_measured= */ NULL);
                if (err != EFI_SUCCESS)
                        log_error_status(err, "Error measuring loader.conf into TPM: %m");
 
                /* Then: parse */
                config_defaults_load_from_file(config, content);
        }
 
        err = efivar_get_timeout(u"LoaderConfigTimeout", &config->timeout_sec_efivar);
        if (err == EFI_SUCCESS)
                config->timeout_sec = config->timeout_sec_efivar;
        else if (err != EFI_NOT_FOUND)
                log_warning_status(err, "Error reading LoaderConfigTimeout EFI variable, ignoring: %m");
        config_timeout_load_from_smbios(config);
 
        err = efivar_get_timeout(u"LoaderConfigTimeoutOneShot", &config->timeout_sec);
        if (err == EFI_SUCCESS) {
                /* Unset variable now, after all it's "one shot". */
                (void) efivar_unset(MAKE_GUID_PTR(LOADER), u"LoaderConfigTimeoutOneShot", EFI_VARIABLE_NON_VOLATILE);
 
                config->force_menu = true; /* force the menu when this is set */
        } else if (err != EFI_NOT_FOUND)
                log_warning_status(err, "Error reading LoaderConfigTimeoutOneShot EFI variable, ignoring: %m");
 
        uint64_t value;
        err = efivar_get_uint64_str16(MAKE_GUID_PTR(LOADER), u"LoaderConfigConsoleMode", &value);
        if (err == EFI_SUCCESS && value <= INT64_MAX)
                config->console_mode_efivar = value;
 
        err = efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryOneShot", &config->entry_oneshot);
        if (err == EFI_SUCCESS)
                /* Unset variable now, after all it's "one shot". */
                (void) efivar_unset(MAKE_GUID_PTR(LOADER), u"LoaderEntryOneShot", EFI_VARIABLE_NON_VOLATILE);
 
        (void) efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryDefault", &config->entry_default_efivar);
        (void) efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryPreferred", &config->entry_preferred_efivar);
        (void) efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntrySysFail", &config->entry_sysfail);
 
        strtolower16(config->entry_default_config);
        strtolower16(config->entry_default_efivar);
        strtolower16(config->entry_preferred_config);
        strtolower16(config->entry_preferred_efivar);
        strtolower16(config->entry_oneshot);
        strtolower16(config->entry_saved);
        strtolower16(config->entry_sysfail);
 
        config->use_saved_entry = streq16(config->entry_default_config, u"@saved");
        config->use_saved_entry_efivar = streq16(config->entry_default_efivar, u"@saved");
        config->use_saved_entry_preferred = streq16(config->entry_preferred_config, u"@saved");
        config->use_saved_entry_preferred_efivar = streq16(config->entry_preferred_efivar, u"@saved");
        if (config->use_saved_entry || config->use_saved_entry_efivar || config->use_saved_entry_preferred || config->use_saved_entry_preferred_efivar)
                (void) efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryLastBooted", &config->entry_saved);
 
}
 
static bool valid_type1_filename(const char16_t *fname) {
        assert(fname);
 
        if (IN_SET(fname[0], u'.', u'\0'))
                return false;
        if (!endswith_no_case(fname, u".conf"))
                return false;
        if (startswith_no_case(fname, u"auto-"))
                return false;
 
        return true;
}
 
static void config_load_type1_entries(
                Config *config,
                EFI_HANDLE *device,
                EFI_FILE *root_dir,
                const char16_t *loaded_image_path) {
 
        _cleanup_file_close_ EFI_FILE *entries_dir = NULL;
        _cleanup_free_ EFI_FILE_INFO *f = NULL;
        size_t f_size = 0;
        EFI_STATUS err;
 
        assert(config);
        assert(device);
        assert(root_dir);
 
        /* Adds Boot Loader Type #1 entries (i.e. /loader/entries/….conf) */
 
        const uint16_t dropin_path[] = u"\\loader\\entries";
 
        err = open_directory(root_dir, dropin_path, &entries_dir);
        if (err != EFI_SUCCESS)
                return;
 
        for (;;) {
                _cleanup_free_ char *content = NULL;
 
                err = readdir(entries_dir, &f, &f_size);
                if (err != EFI_SUCCESS || !f)
                        break;
 
                if (FLAGS_SET(f->Attribute, EFI_FILE_DIRECTORY))
                        continue;
                if (!valid_type1_filename(f->FileName))
                        continue;
 
                err = file_read(entries_dir,
                                f->FileName,
                                /* offset= */ 0,
                                /* size= */ 0,
                                &content,
                                /* ret_size= */ NULL);
                if (err != EFI_SUCCESS)
                        continue;
 
                boot_entry_add_type1(config, device, root_dir, dropin_path, f->FileName, content, loaded_image_path);
        }
}
 
static void config_load_smbios_entries(
                Config *config,
                EFI_HANDLE *device,
                EFI_FILE *root_dir,
                const char16_t *loaded_image_path) {
 
        assert(config);
        assert(device);
        assert(root_dir);
 
        /* Loads Boot Loader Type #1 entries from SMBIOS 11 */
 
        if (is_confidential_vm())
                return; /* Don't consume SMBIOS in CoCo contexts */
 
        for (const char *after = NULL, *extra;; after = extra) {
                extra = smbios_find_oem_string("io.systemd.boot.entries-extra:", after);
                if (!extra)
                        break;
 
                const char *eq = strchr8(extra, '=');
                if (!eq)
                        continue;
 
                _cleanup_free_ char16_t *fname = xstrn8_to_16(extra, eq - extra);
                if (!valid_type1_filename(fname))
                        continue;
 
                /* Make a copy,  since boot_entry_add_type1() wants to modify it */
                _cleanup_free_ char *contents = xstrdup8(eq + 1);
 
                boot_entry_add_type1(config, device, root_dir, /* path= */ NULL, fname, contents, loaded_image_path);
        }
}
 
static unsigned boot_entry_profile(const BootEntry *a) {
        assert(a);
 
        return a->profile == UINT_MAX ? 0 : a->profile;
}
 
static int boot_entry_compare(const BootEntry *a, const BootEntry *b) {
        int r;
 
        assert(a);
        assert(b);
 
        /* Order entries that have no tries left to the end of the list */
        r = CMP(a->tries_left == 0, b->tries_left == 0);
        if (r != 0)
                return r;
 
        /* If there's a sort key defined for *both* entries, then we do new-style ordering, i.e. by
         * sort-key/machine-id/version, with a final fallback to id. If there's no sort key for either, we do
         * old-style ordering, i.e. by id only. If one has sort key and the other does not, we put new-style
         * before old-style. */
        r = CMP(!a->sort_key, !b->sort_key);
        if (r != 0) /* one is old-style, one new-style */
                return r;
 
        if (a->sort_key && b->sort_key) {
                r = strcmp16(a->sort_key, b->sort_key);
                if (r != 0)
                        return r;
 
                /* If multiple installations of the same OS are around, group by machine ID */
                r = strcmp16(a->machine_id, b->machine_id);
                if (r != 0)
                        return r;
 
                /* If the sort key was defined, then order by version now (downwards, putting the newest first) */
                r = -strverscmp_improved(a->version, b->version);
                if (r != 0)
                        return r;
 
                r = CMP(boot_entry_profile(a), boot_entry_profile(b));
                if (r != 0)
                        return r;
        }
 
        /* Now order by ID. The version is likely part of the ID, thus note that this will generatelly put
         * the newer versions earlier. Specifying a sort key explicitly is preferable, because it gives an
         * explicit sort order. */
        r = -strverscmp_improved(a->id_without_profile ?: a->id, b->id_without_profile ?: b->id);
        if (r != 0)
                return r;
 
        /* Let's sort profiles by their profile */
        if (a->id_without_profile && b->id_without_profile) {
                /* Note: the strverscmp_improved() call above checked for us that we are looking at the very
                 * same id, hence at this point we only need to compare profile numbers, since we know they
                 * belong to the same UKI. */
                r = CMP(boot_entry_profile(a), boot_entry_profile(b));
                if (r != 0)
                        return r;
        }
 
        if (a->tries_left < 0 || b->tries_left < 0)
                return 0;
 
        /* If both items have boot counting, and otherwise are identical, put the entry with more tries left first */
        r = -CMP(a->tries_left, b->tries_left);
        if (r != 0)
                return r;
 
        /* If they have the same number of tries left, then let the one win which was tried fewer times so far */
        return CMP(a->tries_done, b->tries_done);
}
 
static size_t config_find_entry(Config *config, const char16_t *pattern, const bool check_assessment) {
        assert(config);
 
        /* We expect pattern and entry IDs to be already case folded. */
 
        if (!pattern)
                return IDX_INVALID;
 
        for (size_t i = 0; i < config->n_entries; i++)
                if (efi_fnmatch(pattern, config->entries[i]->id) && (!check_assessment || config->entries[i]->tries_left != 0))
                        return i;
 
        return IDX_INVALID;
}
 
static bool sysfail_process(Config *config) {
        SysFailType sysfail_type;
 
        assert(config);
 
        sysfail_type = sysfail_check();
        if (sysfail_type == SYSFAIL_NO_FAILURE)
                return false;
 
        /* Store reason string in LoaderSysFailReason EFI variable */
        const char16_t *reason_str = sysfail_get_error_str(sysfail_type);
        if (reason_str)
                (void) efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderSysFailReason", reason_str, 0);
 
        config->sysfail_occurred = true;
 
        return true;
}
 
static void config_select_default_entry(Config *config) {
        size_t i;
 
        assert(config);
 
        if (config->sysfail_occurred) {
                i = config_find_entry(config, config->entry_sysfail, /* check_assessment= */ false);
                if (i != IDX_INVALID) {
                        config->idx_default = i;
                        return;
                }
        }
 
        i = config_find_entry(config, config->entry_oneshot, /* check_assessment= */ false);
        if (i != IDX_INVALID) {
                config->idx_default = i;
                return;
        }
 
        /* Try to match the preferred entry pattern */
 
        i = config_find_entry(config, config->use_saved_entry_preferred_efivar ? config->entry_saved : config->entry_preferred_efivar, /* check_assessment= */ true);
        if (i != IDX_INVALID) {
                config->idx_default = i;
                config->idx_default_efivar = i;
                return;
        }
 
        i = config_find_entry(config, config->entry_preferred_config, /* check_assessment= */ true);
        if (i != IDX_INVALID) {
                config->idx_default = i;
                return;
        }
 
        if (config->use_saved_entry_preferred)
                /* No need to do the same thing twice. */
                i = config->use_saved_entry_preferred_efivar ? IDX_INVALID : config_find_entry(config, config->entry_saved, /* check_assessment= */ true);
        else
                i = config_find_entry(config, config->entry_preferred_config, /* check_assessment= */ true);
        if (i != IDX_INVALID) {
                config->idx_default = i;
                return;
        }
 
        /* Try to match the default pattern */
 
        i = config_find_entry(config, config->use_saved_entry_efivar ? config->entry_saved : config->entry_default_efivar, /* check_assessment= */ false);
        if (i != IDX_INVALID) {
                config->idx_default = i;
                config->idx_default_efivar = i;
                return;
        }
 
        if (config->use_saved_entry)
                /* No need to do the same thing twice. */
                i = config->use_saved_entry_efivar ? IDX_INVALID : config_find_entry(config, config->entry_saved, /* check_assessment= */ false);
        else
                i = config_find_entry(config, config->entry_default_config, /* check_assessment= */ false);
        if (i != IDX_INVALID) {
                config->idx_default = i;
                return;
        }
 
        /* select the first suitable entry */
        for (i = 0; i < config->n_entries; i++) {
                if (config->entries[i]->profile > 0)
                        continue; /* For now, never select any non-default profile */
 
                if (LOADER_TYPE_MAY_AUTO_SELECT(config->entries[i]->type)) {
                        config->idx_default = i;
                        return;
                }
        }
 
        /* If no configured entry to select from was found, enable the menu. */
        config->idx_default = 0;
        if (config->timeout_sec == 0)
                config->timeout_sec = 10;
}
 
static bool entries_unique(BootEntry **entries, bool *unique, size_t n_entries) {
        bool is_unique = true;
 
        assert(entries);
        assert(unique);
 
        for (size_t i = 0; i < n_entries; i++)
                for (size_t k = i + 1; k < n_entries; k++) {
                        if (!streq16(entries[i]->title_show, entries[k]->title_show))
                                continue;
 
                        is_unique = unique[i] = unique[k] = false;
                }
 
        return is_unique;
}
 
/* generate unique titles, avoiding non-distinguishable menu entries */
static void generate_boot_entry_titles(Config *config) {
        assert(config);
 
        bool unique[config->n_entries];
 
        /* set title */
        for (size_t i = 0; i < config->n_entries; i++) {
                assert(!config->entries[i]->title_show);
                unique[i] = true;
                config->entries[i]->title_show = xstrdup16(config->entries[i]->title ?: config->entries[i]->id);
        }
 
        if (entries_unique(config->entries, unique, config->n_entries))
                return;
 
        /* add version to non-unique titles */
        for (size_t i = 0; i < config->n_entries; i++) {
                if (unique[i])