1 // SPDX-License-Identifier: GPL-2.0+
5 * based partly on wine code
7 * Copyright (c) 2016 Alexander Graf
10 #define LOG_CATEGORY LOGC_EFI
14 #include <efi_loader.h>
19 #include <crypto/mscode.h>
20 #include <crypto/pkcs7_parser.h>
21 #include <linux/err.h>
23 const efi_guid_t efi_global_variable_guid = EFI_GLOBAL_VARIABLE_GUID;
24 const efi_guid_t efi_guid_device_path = EFI_DEVICE_PATH_PROTOCOL_GUID;
25 const efi_guid_t efi_guid_loaded_image = EFI_LOADED_IMAGE_PROTOCOL_GUID;
26 const efi_guid_t efi_guid_loaded_image_device_path =
27 EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID;
28 const efi_guid_t efi_simple_file_system_protocol_guid =
29 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
30 const efi_guid_t efi_file_info_guid = EFI_FILE_INFO_GUID;
32 static int machines[] = {
33 #if defined(__aarch64__)
34 IMAGE_FILE_MACHINE_ARM64,
35 #elif defined(__arm__)
36 IMAGE_FILE_MACHINE_ARM,
37 IMAGE_FILE_MACHINE_THUMB,
38 IMAGE_FILE_MACHINE_ARMNT,
41 #if defined(__x86_64__)
42 IMAGE_FILE_MACHINE_AMD64,
43 #elif defined(__i386__)
44 IMAGE_FILE_MACHINE_I386,
47 #if defined(__riscv) && (__riscv_xlen == 32)
48 IMAGE_FILE_MACHINE_RISCV32,
51 #if defined(__riscv) && (__riscv_xlen == 64)
52 IMAGE_FILE_MACHINE_RISCV64,
57 * efi_print_image_info() - print information about a loaded image
59 * If the program counter is located within the image the offset to the base
63 * @image: loaded image
64 * @pc: program counter (use NULL to suppress offset output)
67 static efi_status_t efi_print_image_info(struct efi_loaded_image_obj *obj,
68 struct efi_loaded_image *image,
72 printf(" [0x%p:0x%p]",
73 image->image_base, image->image_base + image->image_size - 1);
74 if (pc && pc >= image->image_base &&
75 pc < image->image_base + image->image_size)
76 printf(" pc=0x%zx", pc - image->image_base);
78 printf(" '%pD'", image->file_path);
84 * efi_print_image_infos() - print information about all loaded images
86 * @pc: program counter (use NULL to suppress offset output)
88 void efi_print_image_infos(void *pc)
90 struct efi_object *efiobj;
91 struct efi_handler *handler;
93 list_for_each_entry(efiobj, &efi_obj_list, link) {
94 list_for_each_entry(handler, &efiobj->protocols, link) {
95 if (!guidcmp(&handler->guid, &efi_guid_loaded_image)) {
97 (struct efi_loaded_image_obj *)efiobj,
98 handler->protocol_interface, pc);
105 * efi_loader_relocate() - relocate UEFI binary
107 * @rel: pointer to the relocation table
108 * @rel_size: size of the relocation table in bytes
109 * @efi_reloc: actual load address of the image
110 * @pref_address: preferred load address of the image
111 * Return: status code
113 static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
114 unsigned long rel_size, void *efi_reloc,
115 unsigned long pref_address)
117 unsigned long delta = (unsigned long)efi_reloc - pref_address;
118 const IMAGE_BASE_RELOCATION *end;
124 end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + rel_size);
125 while (rel < end && rel->SizeOfBlock) {
126 const uint16_t *relocs = (const uint16_t *)(rel + 1);
127 i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(uint16_t);
129 uint32_t offset = (uint32_t)(*relocs & 0xfff) +
131 int type = *relocs >> EFI_PAGE_SHIFT;
132 uint64_t *x64 = efi_reloc + offset;
133 uint32_t *x32 = efi_reloc + offset;
134 uint16_t *x16 = efi_reloc + offset;
137 case IMAGE_REL_BASED_ABSOLUTE:
139 case IMAGE_REL_BASED_HIGH:
140 *x16 += ((uint32_t)delta) >> 16;
142 case IMAGE_REL_BASED_LOW:
143 *x16 += (uint16_t)delta;
145 case IMAGE_REL_BASED_HIGHLOW:
146 *x32 += (uint32_t)delta;
148 case IMAGE_REL_BASED_DIR64:
149 *x64 += (uint64_t)delta;
152 case IMAGE_REL_BASED_RISCV_HI20:
153 *x32 = ((*x32 & 0xfffff000) + (uint32_t)delta) |
156 case IMAGE_REL_BASED_RISCV_LOW12I:
157 case IMAGE_REL_BASED_RISCV_LOW12S:
158 /* We know that we're 4k aligned */
160 log_err("Unsupported reloc offset\n");
161 return EFI_LOAD_ERROR;
166 log_err("Unknown Relocation off %x type %x\n",
168 return EFI_LOAD_ERROR;
172 rel = (const IMAGE_BASE_RELOCATION *)relocs;
177 void __weak invalidate_icache_all(void)
179 /* If the system doesn't support icache_all flush, cross our fingers */
183 * efi_set_code_and_data_type() - determine the memory types to be used for code
186 * @loaded_image_info: image descriptor
187 * @image_type: field Subsystem of the optional header for
188 * Windows specific field
190 static void efi_set_code_and_data_type(
191 struct efi_loaded_image *loaded_image_info,
194 switch (image_type) {
195 case IMAGE_SUBSYSTEM_EFI_APPLICATION:
196 loaded_image_info->image_code_type = EFI_LOADER_CODE;
197 loaded_image_info->image_data_type = EFI_LOADER_DATA;
199 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
200 loaded_image_info->image_code_type = EFI_BOOT_SERVICES_CODE;
201 loaded_image_info->image_data_type = EFI_BOOT_SERVICES_DATA;
203 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
204 case IMAGE_SUBSYSTEM_EFI_ROM:
205 loaded_image_info->image_code_type = EFI_RUNTIME_SERVICES_CODE;
206 loaded_image_info->image_data_type = EFI_RUNTIME_SERVICES_DATA;
209 log_err("invalid image type: %u\n", image_type);
210 /* Let's assume it is an application */
211 loaded_image_info->image_code_type = EFI_LOADER_CODE;
212 loaded_image_info->image_data_type = EFI_LOADER_DATA;
218 * efi_image_region_add() - add an entry of region
219 * @regs: Pointer to array of regions
220 * @start: Start address of region (included)
221 * @end: End address of region (excluded)
222 * @nocheck: flag against overlapped regions
224 * Take one entry of region \[@start, @end\[ and insert it into the list.
226 * * If @nocheck is false, the list will be sorted ascending by address.
227 * Overlapping entries will not be allowed.
229 * * If @nocheck is true, the list will be sorted ascending by sequence
230 * of adding the entries. Overlapping is allowed.
232 * Return: status code
234 efi_status_t efi_image_region_add(struct efi_image_regions *regs,
235 const void *start, const void *end,
238 struct image_region *reg;
241 if (regs->num >= regs->max) {
242 log_err("%s: no more room for regions\n", __func__);
243 return EFI_OUT_OF_RESOURCES;
247 return EFI_INVALID_PARAMETER;
249 for (i = 0; i < regs->num; i++) {
254 /* new data after registered region */
255 if (start >= reg->data + reg->size)
258 /* new data preceding registered region */
259 if (end <= reg->data) {
260 for (j = regs->num - 1; j >= i; j--)
261 memcpy(®s->reg[j + 1], ®s->reg[j],
266 /* new data overlapping registered region */
267 log_err("%s: new region already part of another\n", __func__);
268 return EFI_INVALID_PARAMETER;
273 reg->size = end - start;
280 * cmp_pe_section() - compare virtual addresses of two PE image sections
281 * @arg1: pointer to pointer to first section header
282 * @arg2: pointer to pointer to second section header
284 * Compare the virtual addresses of two sections of an portable executable.
285 * The arguments are defined as const void * to allow usage with qsort().
287 * Return: -1 if the virtual address of arg1 is less than that of arg2,
288 * 0 if the virtual addresses are equal, 1 if the virtual address
289 * of arg1 is greater than that of arg2.
291 static int cmp_pe_section(const void *arg1, const void *arg2)
293 const IMAGE_SECTION_HEADER *section1, *section2;
295 section1 = *((const IMAGE_SECTION_HEADER **)arg1);
296 section2 = *((const IMAGE_SECTION_HEADER **)arg2);
298 if (section1->VirtualAddress < section2->VirtualAddress)
300 else if (section1->VirtualAddress == section2->VirtualAddress)
307 * efi_prepare_aligned_image() - prepare 8-byte aligned image
308 * @efi: pointer to the EFI binary
309 * @efi_size: size of @efi binary
311 * If @efi is not 8-byte aligned, this function newly allocates
314 * Return: valid pointer to a image, return NULL if allocation fails.
316 void *efi_prepare_aligned_image(void *efi, u64 *efi_size)
322 * Size must be 8-byte aligned and the trailing bytes must be
323 * zero'ed. Otherwise hash value may be incorrect.
325 if (!IS_ALIGNED(*efi_size, 8)) {
326 new_efi_size = ALIGN(*efi_size, 8);
327 new_efi = calloc(new_efi_size, 1);
330 memcpy(new_efi, efi, *efi_size);
331 *efi_size = new_efi_size;
339 * efi_image_parse() - parse a PE image
340 * @efi: Pointer to image
342 * @regp: Pointer to a list of regions
343 * @auth: Pointer to a pointer to authentication data in PE
344 * @auth_len: Size of @auth
346 * Parse image binary in PE32(+) format, assuming that sanity of PE image
347 * has been checked by a caller.
348 * On success, an address of authentication data in @efi and its size will
349 * be returned in @auth and @auth_len, respectively.
351 * Return: true on success, false on error
353 bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
354 WIN_CERTIFICATE **auth, size_t *auth_len)
356 struct efi_image_regions *regs;
357 IMAGE_DOS_HEADER *dos;
358 IMAGE_NT_HEADERS32 *nt;
359 IMAGE_SECTION_HEADER *sections, **sorted;
360 int num_regions, num_sections, i;
361 int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY;
362 u32 align, size, authsz, authoff;
366 nt = (void *)(efi + dos->e_lfanew);
371 * Count maximum number of regions to be digested.
372 * We don't have to have an exact number here.
373 * See efi_image_region_add()'s in parsing below.
375 num_regions = 3; /* for header */
376 num_regions += nt->FileHeader.NumberOfSections;
377 num_regions++; /* for extra */
379 regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
383 regs->max = num_regions;
386 * Collect data regions for hash calculation
389 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
390 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
391 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
394 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
395 if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
396 efi_image_region_add(regs,
398 efi + opt->SizeOfHeaders, 0);
400 /* Skip Certificates Table */
401 efi_image_region_add(regs,
403 &opt->DataDirectory[ctidx], 0);
404 efi_image_region_add(regs,
405 &opt->DataDirectory[ctidx] + 1,
406 efi + opt->SizeOfHeaders, 0);
408 authoff = opt->DataDirectory[ctidx].VirtualAddress;
409 authsz = opt->DataDirectory[ctidx].Size;
412 bytes_hashed = opt->SizeOfHeaders;
413 align = opt->FileAlignment;
414 } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
415 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
418 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
419 if (nt->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
420 efi_image_region_add(regs,
422 efi + opt->SizeOfHeaders, 0);
424 /* Skip Certificates Table */
425 efi_image_region_add(regs, &opt->Subsystem,
426 &opt->DataDirectory[ctidx], 0);
427 efi_image_region_add(regs,
428 &opt->DataDirectory[ctidx] + 1,
429 efi + opt->SizeOfHeaders, 0);
431 authoff = opt->DataDirectory[ctidx].VirtualAddress;
432 authsz = opt->DataDirectory[ctidx].Size;
435 bytes_hashed = opt->SizeOfHeaders;
436 align = opt->FileAlignment;
438 log_err("%s: Invalid optional header magic %x\n", __func__,
439 nt->OptionalHeader.Magic);
444 num_sections = nt->FileHeader.NumberOfSections;
445 sections = (void *)((uint8_t *)&nt->OptionalHeader +
446 nt->FileHeader.SizeOfOptionalHeader);
447 sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
449 log_err("%s: Out of memory\n", __func__);
454 * Make sure the section list is in ascending order.
456 for (i = 0; i < num_sections; i++)
457 sorted[i] = §ions[i];
458 qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
460 for (i = 0; i < num_sections; i++) {
461 if (!sorted[i]->SizeOfRawData)
464 size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
465 efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
466 efi + sorted[i]->PointerToRawData + size,
468 log_debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
470 sorted[i]->PointerToRawData,
471 sorted[i]->PointerToRawData + size,
472 sorted[i]->VirtualAddress,
473 sorted[i]->VirtualAddress
474 + sorted[i]->Misc.VirtualSize);
476 bytes_hashed += size;
480 /* 3. Extra data excluding Certificates Table */
481 if (bytes_hashed + authsz < len) {
482 log_debug("extra data for hash: %zu\n",
483 len - (bytes_hashed + authsz));
484 efi_image_region_add(regs, efi + bytes_hashed,
485 efi + len - authsz, 0);
488 /* Return Certificates Table */
490 if (len < authoff + authsz) {
491 log_err("%s: Size for auth too large: %u >= %zu\n",
492 __func__, authsz, len - authoff);
495 if (authsz < sizeof(*auth)) {
496 log_err("%s: Size for auth too small: %u < %zu\n",
497 __func__, authsz, sizeof(*auth));
500 *auth = efi + authoff;
502 log_debug("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff,
519 #ifdef CONFIG_EFI_SECURE_BOOT
521 * efi_image_verify_digest - verify image's message digest
522 * @regs: Array of memory regions to digest
523 * @msg: Signature in pkcs7 structure
525 * @regs contains all the data in a PE image to digest. Calculate
526 * a hash value based on @regs and compare it with a messaged digest
527 * in the content (SpcPeImageData) of @msg's contentInfo.
529 * Return: true if verified, false if not
531 static bool efi_image_verify_digest(struct efi_image_regions *regs,
532 struct pkcs7_message *msg)
534 struct pefile_context ctx;
542 /* get pkcs7's contentInfo */
543 ret = pkcs7_get_content_data(msg, &data, &data_len, &asn1hdrlen);
544 if (ret < 0 || !data)
547 /* parse data and retrieve a message digest into ctx */
548 ret = mscode_parse(&ctx, data, data_len, asn1hdrlen);
552 /* calculate a hash value of PE image */
554 if (!efi_hash_regions(regs->reg, regs->num, &hash, ctx.digest_algo,
558 /* match the digest */
559 if (ctx.digest_len != hash_len || memcmp(ctx.digest, hash, hash_len))
566 * efi_image_authenticate() - verify a signature of signed image
567 * @efi: Pointer to image
568 * @efi_size: Size of @efi
570 * A signed image should have its signature stored in a table of its PE header.
571 * So if an image is signed and only if if its signature is verified using
572 * signature databases, an image is authenticated.
573 * If an image is not signed, its validity is checked by using
574 * efi_image_unsigned_authenticated().
576 * When AuditMode==0, if the image's signature is not found in
577 * the authorized database, or is found in the forbidden database,
578 * the image will not be started and instead, information about it
579 * will be placed in this table.
580 * When AuditMode==1, an EFI_IMAGE_EXECUTION_INFO element is created
581 * in the EFI_IMAGE_EXECUTION_INFO_TABLE for every certificate found
582 * in the certificate table of every image that is validated.
584 * Return: true if authenticated, false if not
586 static bool efi_image_authenticate(void *efi, size_t efi_size)
588 struct efi_image_regions *regs = NULL;
589 WIN_CERTIFICATE *wincerts = NULL, *wincert;
591 struct pkcs7_message *msg = NULL;
592 struct efi_signature_store *db = NULL, *dbx = NULL;
593 void *new_efi = NULL;
594 u8 *auth, *wincerts_end;
598 log_debug("%s: Enter, %d\n", __func__, ret);
600 if (!efi_secure_boot_enabled())
603 new_efi = efi_prepare_aligned_image(efi, (u64 *)&efi_size);
607 if (!efi_image_parse(new_efi, efi_size, ®s, &wincerts,
609 log_err("Parsing PE executable image failed\n");
614 * verify signature using db and dbx
616 db = efi_sigstore_parse_sigdb(u"db");
618 log_err("Getting signature database(db) failed\n");
622 dbx = efi_sigstore_parse_sigdb(u"dbx");
624 log_err("Getting signature database(dbx) failed\n");
628 if (efi_signature_lookup_digest(regs, dbx, true)) {
629 log_debug("Image's digest was found in \"dbx\"\n");
634 * go through WIN_CERTIFICATE list
636 * We may have multiple signatures either as WIN_CERTIFICATE's
637 * in PE header, or as pkcs7 SignerInfo's in SignedData.
638 * So the verification policy here is:
639 * - Success if, at least, one of signatures is verified
640 * - unless signature is rejected explicitly with its digest.
643 for (wincert = wincerts, wincerts_end = (u8 *)wincerts + wincerts_len;
644 (u8 *)wincert < wincerts_end;
645 wincert = (WIN_CERTIFICATE *)
646 ((u8 *)wincert + ALIGN(wincert->dwLength, 8))) {
647 if ((u8 *)wincert + sizeof(*wincert) >= wincerts_end)
650 if (wincert->dwLength <= sizeof(*wincert)) {
651 log_debug("dwLength too small: %u < %zu\n",
652 wincert->dwLength, sizeof(*wincert));
656 log_debug("WIN_CERTIFICATE_TYPE: 0x%x\n",
657 wincert->wCertificateType);
659 auth = (u8 *)wincert + sizeof(*wincert);
660 auth_size = wincert->dwLength - sizeof(*wincert);
661 if (wincert->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
662 if (auth + sizeof(efi_guid_t) >= wincerts_end)
665 if (auth_size <= sizeof(efi_guid_t)) {
666 log_debug("dwLength too small: %u < %zu\n",
667 wincert->dwLength, sizeof(*wincert));
670 if (guidcmp(auth, &efi_guid_cert_type_pkcs7)) {
671 log_debug("Certificate type not supported: %pUs\n",
677 auth += sizeof(efi_guid_t);
678 auth_size -= sizeof(efi_guid_t);
679 } else if (wincert->wCertificateType
680 != WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
681 log_debug("Certificate type not supported\n");
686 msg = pkcs7_parse_message(auth, auth_size);
688 log_err("Parsing image's signature failed\n");
694 * verify signatures in pkcs7's signedInfos which are
695 * to authenticate the integrity of pkcs7's contentInfo.
698 * UEFI specification defines two signature types possible
699 * in signature database:
700 * a. x509 certificate, where a signature in image is
701 * a message digest encrypted by RSA public key
702 * (EFI_CERT_X509_GUID)
703 * b. bare hash value of message digest
704 * (EFI_CERT_SHAxxx_GUID)
706 * efi_signature_verify() handles case (a), while
707 * efi_signature_lookup_digest() handles case (b).
709 * There is a third type:
710 * c. message digest of a certificate
711 * (EFI_CERT_X509_SHAAxxx_GUID)
712 * This type of signature is used only in revocation list
713 * (dbx) and handled as part of efi_signatgure_verify().
715 /* try black-list first */
716 if (efi_signature_verify_one(regs, msg, dbx)) {
718 log_debug("Signature was rejected by \"dbx\"\n");
722 if (!efi_signature_check_signers(msg, dbx)) {
724 log_debug("Signer(s) in \"dbx\"\n");
729 if (!efi_signature_verify(regs, msg, db, dbx)) {
730 log_debug("Signature was not verified by \"db\"\n");
735 * now calculate an image's hash value and compare it with
736 * a messaged digest embedded in pkcs7's contentInfo
738 if (efi_image_verify_digest(regs, msg)) {
743 log_debug("Message digest doesn't match\n");
747 /* last resort try the image sha256 hash in db */
748 if (!ret && efi_signature_lookup_digest(regs, db, false))
752 efi_sigstore_free(db);
753 efi_sigstore_free(dbx);
754 pkcs7_free_message(msg);
759 log_debug("%s: Exit, %d\n", __func__, ret);
763 static bool efi_image_authenticate(void *efi, size_t efi_size)
767 #endif /* CONFIG_EFI_SECURE_BOOT */
771 * efi_check_pe() - check if a memory buffer contains a PE-COFF image
773 * @buffer: buffer to check
774 * @size: size of buffer
775 * @nt_header: on return pointer to NT header of PE-COFF image
776 * Return: EFI_SUCCESS if the buffer contains a PE-COFF image
778 efi_status_t efi_check_pe(void *buffer, size_t size, void **nt_header)
780 IMAGE_DOS_HEADER *dos = buffer;
781 IMAGE_NT_HEADERS32 *nt;
783 if (size < sizeof(*dos))
784 return EFI_INVALID_PARAMETER;
786 /* Check for DOS magix */
787 if (dos->e_magic != IMAGE_DOS_SIGNATURE)
788 return EFI_INVALID_PARAMETER;
791 * Check if the image section header fits into the file. Knowing that at
792 * least one section header follows we only need to check for the length
793 * of the 64bit header which is longer than the 32bit header.
795 if (size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32))
796 return EFI_INVALID_PARAMETER;
797 nt = (IMAGE_NT_HEADERS32 *)((u8 *)buffer + dos->e_lfanew);
799 /* Check for PE-COFF magic */
800 if (nt->Signature != IMAGE_NT_SIGNATURE)
801 return EFI_INVALID_PARAMETER;
810 * section_size() - determine size of section
812 * The size of a section in memory if normally given by VirtualSize.
813 * If VirtualSize is not provided, use SizeOfRawData.
815 * @sec: section header
816 * Return: size of section in memory
818 static u32 section_size(IMAGE_SECTION_HEADER *sec)
820 if (sec->Misc.VirtualSize)
821 return sec->Misc.VirtualSize;
823 return sec->SizeOfRawData;
827 * efi_load_pe() - relocate EFI binary
829 * This function loads all sections from a PE binary into a newly reserved
830 * piece of memory. On success the entry point is returned as handle->entry.
832 * @handle: loaded image handle
833 * @efi: pointer to the EFI binary
834 * @efi_size: size of @efi binary
835 * @loaded_image_info: loaded image protocol
836 * Return: status code
838 efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
839 void *efi, size_t efi_size,
840 struct efi_loaded_image *loaded_image_info)
842 IMAGE_NT_HEADERS32 *nt;
843 IMAGE_DOS_HEADER *dos;
844 IMAGE_SECTION_HEADER *sections;
848 const IMAGE_BASE_RELOCATION *rel;
849 unsigned long rel_size;
850 int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
852 unsigned long virt_size = 0;
856 ret = efi_check_pe(efi, efi_size, (void **)&nt);
857 if (ret != EFI_SUCCESS) {
858 log_err("Not a PE-COFF file\n");
859 return EFI_LOAD_ERROR;
862 for (i = 0; machines[i]; i++)
863 if (machines[i] == nt->FileHeader.Machine) {
869 log_err("Machine type 0x%04x is not supported\n",
870 nt->FileHeader.Machine);
871 return EFI_LOAD_ERROR;
874 num_sections = nt->FileHeader.NumberOfSections;
875 sections = (void *)&nt->OptionalHeader +
876 nt->FileHeader.SizeOfOptionalHeader;
878 if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
880 log_err("Invalid number of sections: %d\n", num_sections);
881 return EFI_LOAD_ERROR;
884 /* Authenticate an image */
885 if (efi_image_authenticate(efi, efi_size)) {
886 handle->auth_status = EFI_IMAGE_AUTH_PASSED;
888 handle->auth_status = EFI_IMAGE_AUTH_FAILED;
889 log_err("Image not authenticated\n");
892 /* Calculate upper virtual address boundary */
893 for (i = num_sections - 1; i >= 0; i--) {
894 IMAGE_SECTION_HEADER *sec = §ions[i];
896 virt_size = max_t(unsigned long, virt_size,
897 sec->VirtualAddress + section_size(sec));
900 /* Read 32/64bit specific header bits */
901 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
902 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
903 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
904 image_base = opt->ImageBase;
905 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
906 handle->image_type = opt->Subsystem;
907 efi_reloc = efi_alloc_aligned_pages(virt_size,
908 loaded_image_info->image_code_type,
909 opt->SectionAlignment);
911 log_err("Out of memory\n");
912 ret = EFI_OUT_OF_RESOURCES;
915 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
916 rel_size = opt->DataDirectory[rel_idx].Size;
917 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
918 } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
919 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
920 image_base = opt->ImageBase;
921 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
922 handle->image_type = opt->Subsystem;
923 efi_reloc = efi_alloc_aligned_pages(virt_size,
924 loaded_image_info->image_code_type,
925 opt->SectionAlignment);
927 log_err("Out of memory\n");
928 ret = EFI_OUT_OF_RESOURCES;
931 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
932 rel_size = opt->DataDirectory[rel_idx].Size;
933 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
935 log_err("Invalid optional header magic %x\n",
936 nt->OptionalHeader.Magic);
937 ret = EFI_LOAD_ERROR;
941 #if IS_ENABLED(CONFIG_EFI_TCG2_PROTOCOL)
942 /* Measure an PE/COFF image */
943 ret = tcg2_measure_pe_image(efi, efi_size, handle, loaded_image_info);
944 if (ret == EFI_SECURITY_VIOLATION) {
946 * TCG2 Protocol is installed but no TPM device found,
947 * this is not expected.
949 log_err("PE image measurement failed, no tpm device found\n");
955 /* Copy PE headers */
956 memcpy(efi_reloc, efi,
959 + nt->FileHeader.SizeOfOptionalHeader
960 + num_sections * sizeof(IMAGE_SECTION_HEADER));
962 /* Load sections into RAM */
963 for (i = num_sections - 1; i >= 0; i--) {
964 IMAGE_SECTION_HEADER *sec = §ions[i];
965 u32 copy_size = section_size(sec);
967 if (copy_size > sec->SizeOfRawData) {
968 copy_size = sec->SizeOfRawData;
969 memset(efi_reloc + sec->VirtualAddress, 0,
970 sec->Misc.VirtualSize);
972 memcpy(efi_reloc + sec->VirtualAddress,
973 efi + sec->PointerToRawData,
977 /* Run through relocations */
978 if (efi_loader_relocate(rel, rel_size, efi_reloc,
979 (unsigned long)image_base) != EFI_SUCCESS) {
980 efi_free_pages((uintptr_t) efi_reloc,
981 (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
982 ret = EFI_LOAD_ERROR;
987 flush_cache((ulong)efi_reloc,
988 ALIGN(virt_size, EFI_CACHELINE_SIZE));
989 invalidate_icache_all();
991 /* Populate the loaded image interface bits */
992 loaded_image_info->image_base = efi_reloc;
993 loaded_image_info->image_size = virt_size;
995 if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
998 return EFI_SECURITY_VIOLATION;