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 2001–3000 of 3,525

                        continue;
 
                unique[i] = true;
 
                if (!config->entries[i]->version)
                        continue;
 
                _cleanup_free_ char16_t *t = config->entries[i]->title_show;
                config->entries[i]->title_show = xasprintf("%ls (%ls)", t, config->entries[i]->version);
        }
 
        if (entries_unique(config->entries, unique, config->n_entries))
                return;
 
        /* add machine-id to non-unique titles */
        for (size_t i = 0; i < config->n_entries; i++) {
                if (unique[i])
                        continue;
 
                unique[i] = true;
 
                if (!config->entries[i]->machine_id)
                        continue;
 
                _cleanup_free_ char16_t *t = config->entries[i]->title_show;
                config->entries[i]->title_show = xasprintf("%ls (%.8ls)", t, config->entries[i]->machine_id);
        }
 
        if (entries_unique(config->entries, unique, config->n_entries))
                return;
 
        /* add file name to non-unique titles */
        for (size_t i = 0; i < config->n_entries; i++) {
                if (unique[i])
                        continue;
 
                _cleanup_free_ char16_t *t = config->entries[i]->title_show;
                config->entries[i]->title_show = xasprintf("%ls (%ls)", t, config->entries[i]->id);
        }
}
 
static bool is_sd_boot(EFI_FILE *root_dir, const char16_t *loader_path) {
        static const char * const section_names[] = {
                ".sdmagic",
                NULL
        };
        _cleanup_free_ char *content = NULL;
        EFI_STATUS err;
        size_t read;
 
        assert(root_dir);
        assert(loader_path);
 
        _cleanup_file_close_ EFI_FILE *handle = NULL;
        err = root_dir->Open(root_dir, &handle, (char16_t *) loader_path, EFI_FILE_MODE_READ, 0ULL);
        if (err != EFI_SUCCESS)
                return false;
 
        _cleanup_free_ PeSectionHeader *section_table = NULL;
        size_t n_section_table, size_in_memory;
        err = pe_section_table_from_file(handle, &section_table, &n_section_table, &size_in_memory);
        if (err != EFI_SUCCESS)
                return false;
 
        PeSectionVector vector[1] = {};
        pe_locate_profile_sections(
                        section_table,
                        n_section_table,
                        section_names,
                        /* profile= */ UINT_MAX,
                        /* validate_base= */ 0,
                        size_in_memory,
                        vector);
        if (vector[0].memory_size != STRLEN(SD_MAGIC))
                return false;
 
        err = file_handle_read(handle, vector[0].file_offset, vector[0].file_size, &content, &read);
        if (err != EFI_SUCCESS || vector[0].file_size != read)
                return false;
 
        return memcmp(content, SD_MAGIC, STRLEN(SD_MAGIC)) == 0;
}
 
static BootEntry* config_add_entry_loader_auto(
                Config *config,
                EFI_HANDLE *device,
                EFI_FILE *root_dir,
                const char16_t *loaded_image_path,
                const char16_t *id,
                char16_t key,
                const char16_t *title,
                const char16_t *loader) {
 
        assert(config);
        assert(device);
        assert(root_dir);
        assert(id);
        assert(title);
 
        if (!config->auto_entries)
                return NULL;
 
        if (!loader) {
                loader = u"\\EFI\\BOOT\\BOOT" EFI_MACHINE_TYPE_NAME ".efi";
 
                /* We are trying to add the default EFI loader here,
                 * but we do not want to do that if that would be us.
                 *
                 * If the default loader is not us, it might be shim. It would
                 * chainload GRUBX64.EFI in that case, which might be us. */
                if (strcaseeq16(loader, loaded_image_path) ||
                    is_sd_boot(root_dir, loader) ||
                    is_sd_boot(root_dir, u"\\EFI\\BOOT\\GRUB" EFI_MACHINE_TYPE_NAME u".EFI"))
                        return NULL;
        }
 
        /* check existence */
        _cleanup_file_close_ EFI_FILE *handle = NULL;
        EFI_STATUS err = root_dir->Open(root_dir, &handle, (char16_t *) loader, EFI_FILE_MODE_READ, 0ULL);
        if (err != EFI_SUCCESS)
                return NULL;
 
        BootEntry *entry = xnew(BootEntry, 1);
        *entry = (BootEntry) {
                .id = xstrdup16(id),
                .type = LOADER_AUTO,
                .title = xstrdup16(title),
                .device = device,
                .loader = xstrdup16(loader),
                .key = key,
                .tries_done = -1,
                .tries_left = -1,
                .call = call_image_start,
        };
 
        config_add_entry(config, entry);
        return entry;
}
 
static void config_add_entry_osx(Config *config) {
        EFI_STATUS err;
        size_t n_handles = 0;
        _cleanup_free_ EFI_HANDLE *handles = NULL;
 
        assert(config);
 
        if (!config->auto_entries)
                return;
 
        err = BS->LocateHandleBuffer(
                        ByProtocol, MAKE_GUID_PTR(EFI_SIMPLE_FILE_SYSTEM_PROTOCOL), NULL, &n_handles, &handles);
        if (err != EFI_SUCCESS)
                return;
 
        for (size_t i = 0; i < n_handles; i++) {
                _cleanup_file_close_ EFI_FILE *root = NULL;
 
                if (open_volume(handles[i], &root) != EFI_SUCCESS)
                        continue;
 
                if (config_add_entry_loader_auto(
                                config,
                                handles[i],
                                root,
                                /* loaded_image_path= */ NULL,
                                u"auto-osx",
                                'a',
                                u"macOS",
                                u"\\System\\Library\\CoreServices\\boot.efi"))
                        break;
        }
}
 
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
static EFI_STATUS call_boot_windows_bitlocker(const BootEntry *entry, EFI_FILE *root_dir, EFI_HANDLE parent_image) {
        _cleanup_free_ EFI_HANDLE *handles = NULL;
        size_t n_handles;
        EFI_STATUS err;
 
        assert(entry);
 
        // FIXME: Experimental for now. Should be generalized, and become a per-entry option that can be
        // enabled independently of BitLocker, and without a BootXXXX entry pre-existing.
 
        /* BitLocker key cannot be sealed without a TPM present. */
        if (!tpm_present())
                return EFI_NOT_FOUND;
 
        err = BS->LocateHandleBuffer(
                        ByProtocol, MAKE_GUID_PTR(EFI_BLOCK_IO_PROTOCOL), NULL, &n_handles, &handles);
        if (err != EFI_SUCCESS)
                return err;
 
        /* Look for BitLocker magic string on all block drives. */
        bool found = false;
        for (size_t i = 0; i < n_handles; i++) {
                EFI_BLOCK_IO_PROTOCOL *block_io;
                err = BS->HandleProtocol(handles[i], MAKE_GUID_PTR(EFI_BLOCK_IO_PROTOCOL), (void **) &block_io);
                if (err != EFI_SUCCESS || block_io->Media->BlockSize < 512 || block_io->Media->BlockSize > 4096)
                        continue;
 
                EFI_DISK_IO_PROTOCOL *disk_io;
                err = BS->HandleProtocol(handles[i], MAKE_GUID_PTR(EFI_DISK_IO_PROTOCOL), (void **) &disk_io);
                if (err != EFI_SUCCESS) {
                        log_debug_status(err, "Failed to get disk I/O protocol: %m");
                        continue;
                }
 
                char buf[STRLEN("-FVE-FS-")];
                err = disk_io->ReadDisk(disk_io, block_io->Media->MediaId, /* Offset= */ 3, sizeof(buf), buf);
                if (err != EFI_SUCCESS)
                        continue;
 
                if (memcmp(buf, "-FVE-FS-", STRLEN("-FVE-FS-")) == 0) {
                        found = true;
                        break;
                }
        }
 
        /* If no BitLocker drive was found, we can just chainload bootmgfw.efi directly. */
        if (!found)
                return EFI_NOT_FOUND;
 
        _cleanup_free_ uint16_t *boot_order = NULL;
        size_t boot_order_size;
 
        /* There can be gaps in Boot#### entries. Instead of iterating over the full
         * EFI var list or uint16_t namespace, just look for "Windows Boot Manager" in BootOrder. */
        err = efivar_get_raw(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"BootOrder", (void**) &boot_order, &boot_order_size);
        if (err != EFI_SUCCESS || boot_order_size % sizeof(uint16_t) != 0)
                return err;
 
        for (size_t i = 0; i < boot_order_size / sizeof(uint16_t); i++) {
                _cleanup_free_ char *buf = NULL;
                size_t buf_size;
 
                _cleanup_free_ char16_t *name = xasprintf("Boot%04x", boot_order[i]);
                err = efivar_get_raw(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), name, (void**) &buf, &buf_size);
                if (err != EFI_SUCCESS)
                        continue;
 
                /* Boot#### are EFI_LOAD_OPTION. But we really are only interested
                 * for the description, which is at this offset. */
                size_t offset = sizeof(uint32_t) + sizeof(uint16_t);
                if (buf_size < offset + sizeof(char16_t))
                        continue;
 
                if (streq16((char16_t *) (buf + offset), u"Windows Boot Manager")) {
                        err = efivar_set_raw(
                                MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE),
                                u"BootNext",
                                boot_order + i,
                                sizeof(boot_order[i]),
                                EFI_VARIABLE_NON_VOLATILE);
                        if (err != EFI_SUCCESS)
                                return err;
                        RT->ResetSystem(EfiResetWarm, EFI_SUCCESS, 0, NULL);
                        assert_not_reached();
                }
        }
 
        return EFI_NOT_FOUND;
}
#endif
 
static void config_add_entry_windows(Config *config, EFI_HANDLE *device, EFI_FILE *root) {
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
        _cleanup_free_ char *bcd = NULL;
        char16_t *title = NULL;
        EFI_STATUS err;
        size_t len;
 
        assert(config);
        assert(device);
        assert(root);
 
        if (!config->auto_entries)
                return;
 
        /* Try to find a better title. */
        err = file_read(root, u"\\EFI\\Microsoft\\Boot\\BCD", 0, 100*1024, &bcd, &len);
        if (err == EFI_SUCCESS)
                title = get_bcd_title((uint8_t *) bcd, len);
 
        BootEntry *e = config_add_entry_loader_auto(
                        config,
                        device,
                        root,
                        NULL,
                        u"auto-windows",
                        'w',
                        title ?: u"Windows Boot Manager",
                        u"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
 
        if (e && config->reboot_for_bitlocker)
                e->call = call_boot_windows_bitlocker;
#endif
}
 
static void boot_entry_add_type2(
                Config *config,
                EFI_HANDLE *device,
                EFI_FILE *dir,
                const uint16_t *path,
                const uint16_t *filename) {
 
        enum {
                SECTION_CMDLINE,
                SECTION_OSREL,
                SECTION_PROFILE,
                _SECTION_MAX,
        };
        static const char * const section_names[_SECTION_MAX + 1] = {
                [SECTION_CMDLINE] = ".cmdline",
                [SECTION_OSREL]   = ".osrel",
                [SECTION_PROFILE] = ".profile",
                NULL,
        };
 
        EFI_STATUS err;
 
        assert(config);
        assert(device);
        assert(dir);
        assert(path);
        assert(filename);
 
        _cleanup_file_close_ EFI_FILE *handle = NULL;
        err = dir->Open(dir, &handle, (char16_t *) filename, EFI_FILE_MODE_READ, 0ULL);
        if (err != EFI_SUCCESS)
                return;
 
        /* Load section table once */
        _cleanup_free_ PeSectionHeader *section_table = NULL;
        size_t n_section_table, size_in_memory;
        err = pe_section_table_from_file(handle, &section_table, &n_section_table, &size_in_memory);
        if (err != EFI_SUCCESS)
                return;
 
        /* Find base profile */
        PeSectionVector base_sections[_SECTION_MAX] = {};
        pe_locate_profile_sections(
                        section_table,
                        n_section_table,
                        section_names,
                        /* profile= */ UINT_MAX,
                        /* validate_base= */ 0,
                        size_in_memory,
                        base_sections);
 
        /* and now iterate through possible profiles, and create a menu item for each profile we find */
        for (unsigned profile = 0; profile < UNIFIED_PROFILES_MAX; profile ++) {
                PeSectionVector sections[_SECTION_MAX] = {};
 
                /* Start out with the base sections */
                memcpy(sections, base_sections, sizeof(sections));
 
                err = pe_locate_profile_sections(
                                section_table,
                                n_section_table,
                                section_names,
                                profile,
                                /* validate_base= */ 0,
                                size_in_memory,
                                sections);
                if (err != EFI_SUCCESS && profile > 0) /* It's fine if there's no .profile for the first
                                                          profile */
                        break;
 
                if (!PE_SECTION_VECTOR_IS_SET(sections + SECTION_OSREL))
                        continue;
 
                _cleanup_free_ char *content = NULL;
                err = file_handle_read(
                                handle,
                                sections[SECTION_OSREL].file_offset,
                                sections[SECTION_OSREL].file_size,
                                &content,
                                /* ret_size= */ NULL);
                if (err != EFI_SUCCESS)
                        continue;
 
                _cleanup_free_ char16_t *os_pretty_name = NULL, *os_image_id = NULL, *os_name = NULL, *os_id = NULL,
                        *os_image_version = NULL, *os_version = NULL, *os_version_id = NULL, *os_build_id = NULL;
                char *line, *key, *value;
                size_t pos = 0;
 
                /* read properties from the embedded os-release file */
                while ((line = line_get_key_value(content, "=", &pos, &key, &value)))
                        if (streq8(key, "PRETTY_NAME")) {
                                free(os_pretty_name);
                                os_pretty_name = xstr8_to_16(value);
 
                        } else if (streq8(key, "IMAGE_ID")) {
                                free(os_image_id);
                                os_image_id = xstr8_to_16(value);
 
                        } else if (streq8(key, "NAME")) {
                                free(os_name);
                                os_name = xstr8_to_16(value);
 
                        } else if (streq8(key, "ID")) {
                                free(os_id);
                                os_id = xstr8_to_16(value);
 
                        } else if (streq8(key, "IMAGE_VERSION")) {
                                free(os_image_version);
                                os_image_version = xstr8_to_16(value);
 
                        } else if (streq8(key, "VERSION")) {
                                free(os_version);
                                os_version = xstr8_to_16(value);
 
                        } else if (streq8(key, "VERSION_ID")) {
                                free(os_version_id);
                                os_version_id = xstr8_to_16(value);
 
                        } else if (streq8(key, "BUILD_ID")) {
                                free(os_build_id);
                                os_build_id = xstr8_to_16(value);
                        }
 
                const char16_t *good_name, *good_version, *good_sort_key;
                if (!bootspec_pick_name_version_sort_key(
                                    os_pretty_name,
                                    os_image_id,
                                    os_name,
                                    os_id,
                                    os_image_version,
                                    os_version,
                                    os_version_id,
                                    os_build_id,
                                    &good_name,
                                    &good_version,
                                    &good_sort_key))
                        continue;
 
                _cleanup_free_ char16_t *profile_id = NULL, *profile_title = NULL;
 
                if (PE_SECTION_VECTOR_IS_SET(sections + SECTION_PROFILE)) {
                        content = mfree(content);
 
                        /* Read any .profile data from the file, if we have it */
 
                        err = file_handle_read(
                                        handle,
                                        sections[SECTION_PROFILE].file_offset,
                                        sections[SECTION_PROFILE].file_size,
                                        &content,
                                        /* ret_size= */ NULL);
                        if (err != EFI_SUCCESS)
                                continue;
 
                        /* read properties from the embedded os-release file */
                        pos = 0;
                        while ((line = line_get_key_value(content, "=", &pos, &key, &value)))
                                if (streq8(key, "ID")) {
                                        free(profile_id);
                                        profile_id = xstr8_to_16(value);
                                } else if (streq8(key, "TITLE")) {
                                        free(profile_title);
                                        profile_title = xstr8_to_16(value);
                                }
                }
 
                _cleanup_free_ char16_t *title = NULL;
                if (profile_title)
                        title = xasprintf("%ls (%ls)", good_name, profile_title);
                else if (profile > 0) {
                        if (profile_id)
                                title = xasprintf("%ls (%ls)", good_name, profile_id);
                        else
                                title = xasprintf("%ls (Profile #%u)", good_name, profile + 1);
                } else
                        title = xstrdup16(good_name);
 
                BootEntry *entry = xnew(BootEntry, 1);
                *entry = (BootEntry) {
                        .type = LOADER_TYPE2_UKI,
                        .title = TAKE_PTR(title),
                        .version = xstrdup16(good_version),
                        .device = device,
                        .loader = xasprintf("%ls\\%ls", path, filename),
                        .sort_key = xstrdup16(good_sort_key),
                        .key = 'l',
                        .tries_done = -1,
                        .tries_left = -1,
                        .profile = profile,
                        .call = call_image_start,
                };
 
                boot_entry_parse_tries(entry, path, filename, u".efi");
 
                /* If the filename had no tries suffixes then the id won't be set by the above call, do it now */
                if (!entry->id)
                        entry->id = xstrdup16(filename);
 
                /* Patterns are case folded before matching, hence IDs must be too. */
                strtolower16(entry->id);
 
                /* Ensure the secondary profiles IDs also have the tries suffix stripped, to match the primary */
                if (profile > 0) {
                        entry->id_without_profile = TAKE_PTR(entry->id);
 
                        if (profile_id)
                                entry->id = strtolower16(xasprintf("%ls@%ls", entry->id_without_profile, profile_id));
                        else
                                entry->id = xasprintf("%ls@%u", entry->id_without_profile, profile);
 
                }
 
                config_add_entry(config, entry);
 
                if (!PE_SECTION_VECTOR_IS_SET(sections + SECTION_CMDLINE))
                        continue;
 
                content = mfree(content);
 
                /* Read the embedded cmdline file for display purposes */
                size_t cmdline_len;
                err = file_handle_read(
                                handle,
                                sections[SECTION_CMDLINE].file_offset,
                                sections[SECTION_CMDLINE].file_size,
                                &content,
                                &cmdline_len);
                if (err == EFI_SUCCESS) {
                        entry->options = mangle_stub_cmdline(xstrn8_to_16(content, cmdline_len));
                        entry->options_implied = true;
                }
        }
}
 
static void config_load_type2_entries(
                Config *config,
                EFI_HANDLE *device,
                EFI_FILE *root_dir) {
 
        _cleanup_file_close_ EFI_FILE *linux_dir = NULL;
        _cleanup_free_ EFI_FILE_INFO *f = NULL;
        size_t f_size = 0;
        EFI_STATUS err;
 
        /* Adds Boot Loader Type #2 entries (i.e. /EFI/Linux/….efi) */
 
        assert(config);
        assert(device);
        assert(root_dir);
 
        const uint16_t dropin_path[] = u"\\EFI\\Linux";
 
        err = open_directory(root_dir, dropin_path, &linux_dir);
        if (err != EFI_SUCCESS)
                return;
 
        for (;;) {
                err = readdir(linux_dir, &f, &f_size);
                if (err != EFI_SUCCESS || !f)
                        break;
 
                if (f->FileName[0] == '.')
                        continue;
                if (FLAGS_SET(f->Attribute, EFI_FILE_DIRECTORY))
                        continue;
                if (!endswith_no_case(f->FileName, u".efi"))
                        continue;
                if (startswith_no_case(f->FileName, u"auto-"))
                        continue;
 
                boot_entry_add_type2(config, device, linux_dir, dropin_path, f->FileName);
        }
}
 
static void config_load_xbootldr(
                Config *config,
                EFI_HANDLE *device) {
 
        _cleanup_file_close_ EFI_FILE *root_dir = NULL;
        EFI_HANDLE new_device = NULL;  /* avoid false maybe-uninitialized warning */
        EFI_STATUS err;
 
        assert(config);
        assert(device);
 
        err = partition_open(MAKE_GUID_PTR(XBOOTLDR), device, &new_device, &root_dir);
        if (err != EFI_SUCCESS)
                return;
 
        config_load_type2_entries(config, new_device, root_dir);
        config_load_type1_entries(config, new_device, root_dir, NULL);
}
 
static EFI_STATUS initrd_prepare(
                EFI_FILE *root,
                const BootEntry *entry,
                char16_t **ret_options,
                Pages *ret_initrd_pages,
                size_t *ret_initrd_size) {
 
        assert(root);
        assert(entry);
        assert(ret_options);
        assert(ret_initrd_pages);
        assert(ret_initrd_size);
 
        assert(entry->type == LOADER_LINUX);
 
        if (strv_isempty(entry->initrd)) {
                *ret_options = NULL;
                *ret_initrd_pages = (Pages) {};
                *ret_initrd_size = 0;
                return EFI_SUCCESS;
        }
 
        /* Note that order of initrds matters. The kernel will only look for microcode updates in the very
         * first one it sees. */
 
        /* Add initrd= to options for older kernels that do not support LINUX_INITRD_MEDIA. Should be dropped
         * if linux_x86.c is dropped. */
        _cleanup_free_ char16_t *options = NULL;
 
        EFI_STATUS err;
        size_t size = 0, padded_size = 0;
 
        STRV_FOREACH(i, entry->initrd) {
                _cleanup_file_close_ EFI_FILE *handle = NULL;
                err = root->Open(root, &handle, *i, EFI_FILE_MODE_READ, 0);
                if (err != EFI_SUCCESS)
                        return err;
 
                _cleanup_free_ EFI_FILE_INFO *info = NULL;
                err = get_file_info(handle, &info, NULL);
                if (err != EFI_SUCCESS)
                        return err;
 
                if (info->FileSize == 0) /* Automatically skip over empty files */
                        continue;
 
                _cleanup_free_ char16_t *o = options;
                if (o)
                        options = xasprintf("%ls initrd=%ls", o, *i);
                else
                        options = xasprintf("initrd=%ls", *i);
 
                size_t inc = info->FileSize;
 
                if (!INC_SAFE(&padded_size, ALIGN4(inc)))
                        return EFI_OUT_OF_RESOURCES;
                assert_se(INC_SAFE(&size, *(i + 1) ? ALIGN4(inc) : inc));
        }
 
        /* Skip if no valid initrd files */
        if (padded_size == 0) {
                *ret_options = NULL;
                *ret_initrd_pages = (Pages) {};
                *ret_initrd_size = 0;
                return EFI_SUCCESS;
        }
 
        _cleanup_pages_ Pages pages = xmalloc_initrd_pages(padded_size);
        uint8_t *p = PHYSICAL_ADDRESS_TO_POINTER(pages.addr);
 
        STRV_FOREACH(i, entry->initrd) {
                _cleanup_file_close_ EFI_FILE *handle = NULL;
                err = root->Open(root, &handle, *i, EFI_FILE_MODE_READ, 0);
                if (err != EFI_SUCCESS)
                        return err;
 
                _cleanup_free_ EFI_FILE_INFO *info = NULL;
                err = get_file_info(handle, &info, NULL);
                if (err != EFI_SUCCESS)
                        return err;
 
                if (info->FileSize == 0) /* Automatically skip over empty files */
                        continue;
 
                size_t read_size = info->FileSize;
                err = chunked_read(handle, &read_size, p);
                if (err != EFI_SUCCESS)
                        return err;
 
                /* Make sure the actual read size is what we expected. */
                assert(read_size == info->FileSize);
                p += read_size;
 
                size_t pad;
                pad = ALIGN4(read_size) - read_size;
                if (pad == 0)
                        continue;
 
                memzero(p, pad);
                /* Exclude the trailing pad from size calculations. This would change the
                 * calculated hash, see https://github.com/systemd/systemd/issues/35439
                 * and https://bugzilla.suse.com/show_bug.cgi?id=1233752. */
                if (*(i + 1))
                        p += pad;
        }
 
        assert(PHYSICAL_ADDRESS_TO_POINTER(pages.addr + size) == p);
 
        if (entry->options) {
                _cleanup_free_ char16_t *o = options;
                options = xasprintf("%ls %ls", o, entry->options);
        }
 
        *ret_options = TAKE_PTR(options);
        *ret_initrd_pages = TAKE_STRUCT(pages);
        *ret_initrd_size = size;
        return EFI_SUCCESS;
}
 
static EFI_STATUS load_extras(
                EFI_FILE *root,
                const BootEntry *entry,
                Pages *ret_initrd_pages,
                size_t *ret_initrd_size) {
 
        EFI_STATUS err;
 
        assert(root);
        assert(entry);
        assert(ret_initrd_pages);
        assert(ret_initrd_size);
 
        assert(IN_SET(entry->type, LOADER_UKI, LOADER_UKI_URL));
 
        _cleanup_(iovec_done) struct iovec previous_initrd = {}, confext_initrd = {}, sysext_initrd = {}, credential_initrd = {};
 
        const struct ExtraResourceInfo {
                const char16_t *suffix;
                const CpioTarget *target;
                struct iovec *iovec;
                const char16_t *tpm_description;
        } table[] = {
                { u".cred",        &cpio_target_credentials, &credential_initrd, u"Entry credentials initrd"             },
                { u".sysext.raw",  &cpio_target_sysext,      &sysext_initrd,     u"Entry system extension initrd"        },
                { u".confext.raw", &cpio_target_confext,     &confext_initrd,    u"Entry configuration extension initrd" },
        };
 
        if (strv_isempty(entry->extras))
                goto nothing;
 
        uint32_t inode = 1; /* inode counter, so that each item gets a new inode */
        unsigned n = 0;
 
        STRV_FOREACH(i, entry->extras) {
                _cleanup_file_close_ EFI_FILE *handle = NULL;
                err = root->Open(root, &handle, *i, EFI_FILE_MODE_READ, /* Attributes= */ 0);
                if (err != EFI_SUCCESS) {
                        log_warning_status(err, "Failed to open extra file '%ls', ignoring: %m", *i);
                        continue;
                }
 
                _cleanup_free_ EFI_FILE_INFO *info = NULL;
                err = get_file_info(handle, &info, /* ret_size= */ NULL);
                if (err != EFI_SUCCESS) {
                        log_warning_status(err, "Failed to get information about file '%ls', ignoring: %m", *i);
                        continue;
                }
 
                if (FLAGS_SET(info->Attribute, EFI_FILE_DIRECTORY)) {
                        log_warning("Extra file '%ls' is a directory, ignoring.", *i);
                        continue;
                }
 
                if (info->FileSize == 0) {
                        log_warning("Extra file '%ls' is empty, ignoring.", *i);
                        continue;
                }
                if (info->FileSize > EXTRA_SIZE_MAX) {
                        log_warning("Extra file '%ls' is larger than allowed extra file size, ignoring.", *i);
                        continue;
                }
 
                if (!is_ascii(info->FileName)) {
                        log_warning("Extra file name '%ls' is not valid ASCII, ignoring.", *i);
                        continue;
                }
                if (strlen16(info->FileName) > 255) { /* Max filename size on Linux */
                        log_warning("Filename '%ls' too long, ignoring.", *i);
                        continue;
                }
 
                const struct ExtraResourceInfo *x = NULL;
                FOREACH_ELEMENT(j, table)
                        if (endswith_no_case(info->FileName, j->suffix)) {
                                x = j;
                                break;
                        }
                if (!x) {
                        log_warning("Unrecognized type of extra file '%ls', ignoring.", info->FileName);
                        continue;
                }
 
                _cleanup_free_ char *content = NULL;
                size_t contentsize = 0;  /* avoid false maybe-uninitialized warning */
                err = file_handle_read(handle, /* offset= */ 0, info->FileSize, &content, &contentsize);
                if (err != EFI_SUCCESS) {
                        log_warning_status(err, "Failed to read '%ls', ignoring: %m", *i);
                        continue;
                }
 
                /* Generate the leading directory inodes right before adding the first files to the
                 * archive. Otherwise the cpio archive cannot be unpacked, since the leading dirs won't
                 * exist. Note that we potentially do redundant work here: a prior iteration might already
                 * have created the prefix for us, but to simplify this we regenerate it anyway. It's very
                 * little data, and simplifies the implementation here a lot. */
                err = pack_cpio_prefix(x->target, &inode, &x->iovec->iov_base, &x->iovec->iov_len);
                if (err != EFI_SUCCESS)
                        return log_error_status(err, "Failed to pack cpio prefix '%s': %m", x->target->directory);
 
                err = pack_cpio_one(
                                info->FileName,
                                content, contentsize,
                                x->target,
                                &inode,
                                &x->iovec->iov_base, &x->iovec->iov_len);
                if (err != EFI_SUCCESS)
                        return log_error_status(err, "Failed to pack cpio file '%ls': %m", info->FileName);
 
                n++;
        }
 
        if (n == 0) /* Nothing actually loaded */
                goto nothing;
 
        FOREACH_ELEMENT(x, table) {
                if (x->iovec->iov_len <= 0)
                        continue;
 
                err = pack_cpio_trailer(&x->iovec->iov_base, &x->iovec->iov_len);
                if (err != EFI_SUCCESS)
                        return log_error_status(err, "Failed to pack cpio trailer: %m");
 
                err = tpm_log_ipl_event(
                                x->target->tpm_pcr,
                                POINTER_TO_PHYSICAL_ADDRESS(x->iovec->iov_base),
                                x->iovec->iov_len,
                                x->tpm_description,
                                /* ret_measured= */ NULL);
                if (err != EFI_SUCCESS)
                        return log_error_status(
                                        err,
                                        "Unable to add cpio TPM measurement for PCR %u (%ls): %m",
                                        x->target->tpm_pcr,
                                        x->tpm_description);
        }
 
        /* Be nice: pick up any previously registered initrds and prepend them to what we are generating here */
        err = initrd_read_previous(&previous_initrd);
        if (err == EFI_NOT_FOUND)
                log_debug_status(err, "No previous initrd installed.");
        else if (err != EFI_SUCCESS)
                log_warning_status(err, "Failed to read previously registered initrd, ignoring.");
        else
                log_debug("Successfully loaded previously installed initrd (%zu bytes).", previous_initrd.iov_len);
 
        err = combine_initrds(
                        (const struct iovec[]) {
                                previous_initrd,
                                credential_initrd,
                                sysext_initrd,
                                confext_initrd,
                        },
                        /* n_initrds= */ 4,
                        ret_initrd_pages,
                        ret_initrd_size);
        if (err != EFI_SUCCESS)
                return log_error_status(err, "Failed to combine previous with extra initrds: %m");
 
        return EFI_SUCCESS;
 
nothing:
        *ret_initrd_pages = (Pages) {};
        *ret_initrd_size = 0;
        return EFI_SUCCESS;
}
 
static EFI_STATUS expand_path(
                EFI_HANDLE parent_image,
                EFI_DEVICE_PATH *path,
                EFI_DEVICE_PATH **ret_expanded_path) {
 
        EFI_STATUS err;
 
        assert(parent_image);
        assert(path);
        assert(ret_expanded_path);
 
        _cleanup_free_ EFI_HANDLE *handles = NULL;
        size_t n_handles = 0;
        err = BS->LocateHandleBuffer(
                        ByProtocol,
                        MAKE_GUID_PTR(EFI_LOAD_FILE_PROTOCOL),
                        /* SearchKey= */ NULL,
                        &n_handles,
                        &handles);
        if (!IN_SET(err, EFI_SUCCESS, EFI_NOT_FOUND))
                return log_error_status(err, "Failed to get list of LoadFile protocol handles: %m");
 
        FOREACH_ARRAY(h, handles, n_handles) {
                EFI_LOAD_FILE_PROTOCOL *load_file = NULL;
                err = BS->OpenProtocol(
                                *h,
                                MAKE_GUID_PTR(EFI_LOAD_FILE_PROTOCOL),
                                (void**) &load_file,
                                parent_image,
                                /* ControllerHandler= */ NULL,
                                EFI_OPEN_PROTOCOL_GET_PROTOCOL);
                if (IN_SET(err, EFI_NOT_FOUND, EFI_INVALID_PARAMETER))
                        continue; /* Skip over LoadFile() handles that are not suitable for this kind of device path */
                if (err != EFI_SUCCESS) {
                        log_warning_status(err, "Failed to get LoadFile() protocol, ignoring: %m");
                        continue;
                }
 
                /* Issue a LoadFile() request without interest in the actual data (i.e. size is zero and
                 * buffer pointer is NULL), but with BootPolicy set to true, this has the effect of
                 * downloading the URL and establishing a handle for it. */
                size_t size = 0;
                err = load_file->LoadFile(load_file, path, /* BootPolicy= */ true, &size, /* Buffer= */ NULL);
                if (IN_SET(err, EFI_NOT_FOUND, EFI_INVALID_PARAMETER))
                        continue; /* Skip over LoadFile() handles that after all don't consider themselves
                                   * appropriate for this kind of path */
                if (!IN_SET(err, EFI_SUCCESS, EFI_BUFFER_TOO_SMALL)) {
                        /* NB: firmwares are supposed to return EFI_BUFFER_TOO_SMALL whenever we pass a NULL
                         * buffer. But for compatibility with quirky firmwares let's be lenient for the
                         * special case of a zero sized file: the firmware might return EFI_SUCCESS here and
                         * initialize the size to zero, as a buffer is not actually necessary for that
                         * case. */
                        log_warning_status(err, "Failed to get file via LoadFile() protocol, ignoring: %m");
                        continue;
                }
 
                /* Now read the updated file path */
                EFI_DEVICE_PATH *load_file_path = NULL;
                err = BS->HandleProtocol(*h, MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), (void **) &load_file_path);
                if (err != EFI_SUCCESS)
                        return log_error_status(err, "Failed to get LoadFile() device path: %m");
 
                /* And return a copy */
                *ret_expanded_path = device_path_dup(load_file_path);
                return EFI_SUCCESS;
        }
 
        return EFI_NOT_FOUND;
}
 
static EFI_STATUS call_image_start(
                const BootEntry *entry,
                EFI_FILE *root_dir,
                EFI_HANDLE parent_image) {
 
        _cleanup_(devicetree_cleanup) struct devicetree_state dtstate = {};
        _cleanup_(unload_imagep) EFI_HANDLE image = NULL;
        EFI_STATUS err;
 
        assert(entry);
 
        _cleanup_file_close_ EFI_FILE *image_root = NULL;
        _cleanup_free_ EFI_DEVICE_PATH *path = NULL;
        bool boot_policy;
        if (entry->url) {
                /* Generate a device path that only contains the URL */
                err = make_url_device_path(entry->url, &path);
                if (err != EFI_SUCCESS)
                        return log_error_status(err, "Error making URL device path: %m");
 
                /* Try to expand this path on all available NICs and IP protocols */
                _cleanup_free_ EFI_DEVICE_PATH *expanded_path = NULL;
                for (unsigned n_attempt = 0;; n_attempt++) {
                        err = expand_path(parent_image, path, &expanded_path);
                        if (err == EFI_SUCCESS) {
                                /* If this worked then let's try to boot with the expanded path. */
                                free(path);
                                path = TAKE_PTR(expanded_path);
                                break;
                        }
                        if (err != EFI_NOT_FOUND || n_attempt > 5) {
                                log_warning_status(err, "Failed to expand device path, ignoring: %m");
                                break;
                        }
 
                        /* Maybe the network devices have been configured for this yet (because we are the
                         * first piece of code trying to do networking)? Then let's connect them, and try
                         * again. */
                        reconnect_all_drivers();
                }
 
                /* Note: if the path expansion doesn't work, we'll continue with the unexpanded path. Which
                 * will probably fail on many (most?) firmwares, but it's worth a try. */
 
                boot_policy = true; /* Set BootPolicy parameter to LoadImage() to true, which ultimately
                                     * controls whether the LoadFile (and thus HTTP boot) or LoadFile2 (which
                                     * does not set up HTTP boot) protocol shall be used. */
        } else {
                assert(entry->device);
                assert(entry->loader);
 
                err = open_volume(entry->device, &image_root);