Merge https://gitlab.denx.de/u-boot/custodians/u-boot-spi into next
[platform/kernel/u-boot.git] / lib / efi_loader / efi_image_loader.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  EFI image loader
4  *
5  *  based partly on wine code
6  *
7  *  Copyright (c) 2016 Alexander Graf
8  */
9
10 #include <common.h>
11 #include <cpu_func.h>
12 #include <efi_loader.h>
13 #include <malloc.h>
14 #include <pe.h>
15 #include <sort.h>
16 #include <crypto/pkcs7_parser.h>
17 #include <linux/err.h>
18
19 const efi_guid_t efi_global_variable_guid = EFI_GLOBAL_VARIABLE_GUID;
20 const efi_guid_t efi_guid_device_path = EFI_DEVICE_PATH_PROTOCOL_GUID;
21 const efi_guid_t efi_guid_loaded_image = EFI_LOADED_IMAGE_PROTOCOL_GUID;
22 const efi_guid_t efi_guid_loaded_image_device_path =
23                 EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID;
24 const efi_guid_t efi_simple_file_system_protocol_guid =
25                 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
26 const efi_guid_t efi_file_info_guid = EFI_FILE_INFO_GUID;
27
28 static int machines[] = {
29 #if defined(__aarch64__)
30         IMAGE_FILE_MACHINE_ARM64,
31 #elif defined(__arm__)
32         IMAGE_FILE_MACHINE_ARM,
33         IMAGE_FILE_MACHINE_THUMB,
34         IMAGE_FILE_MACHINE_ARMNT,
35 #endif
36
37 #if defined(__x86_64__)
38         IMAGE_FILE_MACHINE_AMD64,
39 #elif defined(__i386__)
40         IMAGE_FILE_MACHINE_I386,
41 #endif
42
43 #if defined(__riscv) && (__riscv_xlen == 32)
44         IMAGE_FILE_MACHINE_RISCV32,
45 #endif
46
47 #if defined(__riscv) && (__riscv_xlen == 64)
48         IMAGE_FILE_MACHINE_RISCV64,
49 #endif
50         0 };
51
52 /**
53  * efi_print_image_info() - print information about a loaded image
54  *
55  * If the program counter is located within the image the offset to the base
56  * address is shown.
57  *
58  * @obj:        EFI object
59  * @image:      loaded image
60  * @pc:         program counter (use NULL to suppress offset output)
61  * Return:      status code
62  */
63 static efi_status_t efi_print_image_info(struct efi_loaded_image_obj *obj,
64                                          struct efi_loaded_image *image,
65                                          void *pc)
66 {
67         printf("UEFI image");
68         printf(" [0x%p:0x%p]",
69                image->image_base, image->image_base + image->image_size - 1);
70         if (pc && pc >= image->image_base &&
71             pc < image->image_base + image->image_size)
72                 printf(" pc=0x%zx", pc - image->image_base);
73         if (image->file_path)
74                 printf(" '%pD'", image->file_path);
75         printf("\n");
76         return EFI_SUCCESS;
77 }
78
79 /**
80  * efi_print_image_infos() - print information about all loaded images
81  *
82  * @pc:         program counter (use NULL to suppress offset output)
83  */
84 void efi_print_image_infos(void *pc)
85 {
86         struct efi_object *efiobj;
87         struct efi_handler *handler;
88
89         list_for_each_entry(efiobj, &efi_obj_list, link) {
90                 list_for_each_entry(handler, &efiobj->protocols, link) {
91                         if (!guidcmp(handler->guid, &efi_guid_loaded_image)) {
92                                 efi_print_image_info(
93                                         (struct efi_loaded_image_obj *)efiobj,
94                                         handler->protocol_interface, pc);
95                         }
96                 }
97         }
98 }
99
100 /**
101  * efi_loader_relocate() - relocate UEFI binary
102  *
103  * @rel:                pointer to the relocation table
104  * @rel_size:           size of the relocation table in bytes
105  * @efi_reloc:          actual load address of the image
106  * @pref_address:       preferred load address of the image
107  * Return:              status code
108  */
109 static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
110                         unsigned long rel_size, void *efi_reloc,
111                         unsigned long pref_address)
112 {
113         unsigned long delta = (unsigned long)efi_reloc - pref_address;
114         const IMAGE_BASE_RELOCATION *end;
115         int i;
116
117         if (delta == 0)
118                 return EFI_SUCCESS;
119
120         end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + rel_size);
121         while (rel < end && rel->SizeOfBlock) {
122                 const uint16_t *relocs = (const uint16_t *)(rel + 1);
123                 i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(uint16_t);
124                 while (i--) {
125                         uint32_t offset = (uint32_t)(*relocs & 0xfff) +
126                                           rel->VirtualAddress;
127                         int type = *relocs >> EFI_PAGE_SHIFT;
128                         uint64_t *x64 = efi_reloc + offset;
129                         uint32_t *x32 = efi_reloc + offset;
130                         uint16_t *x16 = efi_reloc + offset;
131
132                         switch (type) {
133                         case IMAGE_REL_BASED_ABSOLUTE:
134                                 break;
135                         case IMAGE_REL_BASED_HIGH:
136                                 *x16 += ((uint32_t)delta) >> 16;
137                                 break;
138                         case IMAGE_REL_BASED_LOW:
139                                 *x16 += (uint16_t)delta;
140                                 break;
141                         case IMAGE_REL_BASED_HIGHLOW:
142                                 *x32 += (uint32_t)delta;
143                                 break;
144                         case IMAGE_REL_BASED_DIR64:
145                                 *x64 += (uint64_t)delta;
146                                 break;
147 #ifdef __riscv
148                         case IMAGE_REL_BASED_RISCV_HI20:
149                                 *x32 = ((*x32 & 0xfffff000) + (uint32_t)delta) |
150                                         (*x32 & 0x00000fff);
151                                 break;
152                         case IMAGE_REL_BASED_RISCV_LOW12I:
153                         case IMAGE_REL_BASED_RISCV_LOW12S:
154                                 /* We know that we're 4k aligned */
155                                 if (delta & 0xfff) {
156                                         printf("Unsupported reloc offset\n");
157                                         return EFI_LOAD_ERROR;
158                                 }
159                                 break;
160 #endif
161                         default:
162                                 printf("Unknown Relocation off %x type %x\n",
163                                        offset, type);
164                                 return EFI_LOAD_ERROR;
165                         }
166                         relocs++;
167                 }
168                 rel = (const IMAGE_BASE_RELOCATION *)relocs;
169         }
170         return EFI_SUCCESS;
171 }
172
173 void __weak invalidate_icache_all(void)
174 {
175         /* If the system doesn't support icache_all flush, cross our fingers */
176 }
177
178 /**
179  * efi_set_code_and_data_type() - determine the memory types to be used for code
180  *                                and data.
181  *
182  * @loaded_image_info:  image descriptor
183  * @image_type:         field Subsystem of the optional header for
184  *                      Windows specific field
185  */
186 static void efi_set_code_and_data_type(
187                         struct efi_loaded_image *loaded_image_info,
188                         uint16_t image_type)
189 {
190         switch (image_type) {
191         case IMAGE_SUBSYSTEM_EFI_APPLICATION:
192                 loaded_image_info->image_code_type = EFI_LOADER_CODE;
193                 loaded_image_info->image_data_type = EFI_LOADER_DATA;
194                 break;
195         case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
196                 loaded_image_info->image_code_type = EFI_BOOT_SERVICES_CODE;
197                 loaded_image_info->image_data_type = EFI_BOOT_SERVICES_DATA;
198                 break;
199         case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
200         case IMAGE_SUBSYSTEM_EFI_ROM:
201                 loaded_image_info->image_code_type = EFI_RUNTIME_SERVICES_CODE;
202                 loaded_image_info->image_data_type = EFI_RUNTIME_SERVICES_DATA;
203                 break;
204         default:
205                 printf("%s: invalid image type: %u\n", __func__, image_type);
206                 /* Let's assume it is an application */
207                 loaded_image_info->image_code_type = EFI_LOADER_CODE;
208                 loaded_image_info->image_data_type = EFI_LOADER_DATA;
209                 break;
210         }
211 }
212
213 #ifdef CONFIG_EFI_SECURE_BOOT
214 /**
215  * cmp_pe_section() - compare virtual addresses of two PE image sections
216  * @arg1:       pointer to pointer to first section header
217  * @arg2:       pointer to pointer to second section header
218  *
219  * Compare the virtual addresses of two sections of an portable executable.
220  * The arguments are defined as const void * to allow usage with qsort().
221  *
222  * Return:      -1 if the virtual address of arg1 is less than that of arg2,
223  *              0 if the virtual addresses are equal, 1 if the virtual address
224  *              of arg1 is greater than that of arg2.
225  */
226 static int cmp_pe_section(const void *arg1, const void *arg2)
227 {
228         const IMAGE_SECTION_HEADER *section1, *section2;
229
230         section1 = *((const IMAGE_SECTION_HEADER **)arg1);
231         section2 = *((const IMAGE_SECTION_HEADER **)arg2);
232
233         if (section1->VirtualAddress < section2->VirtualAddress)
234                 return -1;
235         else if (section1->VirtualAddress == section2->VirtualAddress)
236                 return 0;
237         else
238                 return 1;
239 }
240
241 /**
242  * efi_image_parse() - parse a PE image
243  * @efi:        Pointer to image
244  * @len:        Size of @efi
245  * @regp:       Pointer to a list of regions
246  * @auth:       Pointer to a pointer to authentication data in PE
247  * @auth_len:   Size of @auth
248  *
249  * Parse image binary in PE32(+) format, assuming that sanity of PE image
250  * has been checked by a caller.
251  * On success, an address of authentication data in @efi and its size will
252  * be returned in @auth and @auth_len, respectively.
253  *
254  * Return:      true on success, false on error
255  */
256 bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
257                      WIN_CERTIFICATE **auth, size_t *auth_len)
258 {
259         struct efi_image_regions *regs;
260         IMAGE_DOS_HEADER *dos;
261         IMAGE_NT_HEADERS32 *nt;
262         IMAGE_SECTION_HEADER *sections, **sorted;
263         int num_regions, num_sections, i;
264         int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY;
265         u32 align, size, authsz, authoff;
266         size_t bytes_hashed;
267
268         dos = (void *)efi;
269         nt = (void *)(efi + dos->e_lfanew);
270
271         /*
272          * Count maximum number of regions to be digested.
273          * We don't have to have an exact number here.
274          * See efi_image_region_add()'s in parsing below.
275          */
276         num_regions = 3; /* for header */
277         num_regions += nt->FileHeader.NumberOfSections;
278         num_regions++; /* for extra */
279
280         regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
281                       1);
282         if (!regs)
283                 goto err;
284         regs->max = num_regions;
285
286         /*
287          * Collect data regions for hash calculation
288          * 1. File headers
289          */
290         if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
291                 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
292                 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
293
294                 /* Skip CheckSum */
295                 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
296                 if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
297                         efi_image_region_add(regs,
298                                              &opt->Subsystem,
299                                              efi + opt->SizeOfHeaders, 0);
300                 } else {
301                         /* Skip Certificates Table */
302                         efi_image_region_add(regs,
303                                              &opt->Subsystem,
304                                              &opt->DataDirectory[ctidx], 0);
305                         efi_image_region_add(regs,
306                                              &opt->DataDirectory[ctidx] + 1,
307                                              efi + opt->SizeOfHeaders, 0);
308                 }
309
310                 bytes_hashed = opt->SizeOfHeaders;
311                 align = opt->FileAlignment;
312                 authoff = opt->DataDirectory[ctidx].VirtualAddress;
313                 authsz = opt->DataDirectory[ctidx].Size;
314         } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
315                 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
316
317                 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
318                 efi_image_region_add(regs, &opt->Subsystem,
319                                      &opt->DataDirectory[ctidx], 0);
320                 efi_image_region_add(regs, &opt->DataDirectory[ctidx] + 1,
321                                      efi + opt->SizeOfHeaders, 0);
322
323                 bytes_hashed = opt->SizeOfHeaders;
324                 align = opt->FileAlignment;
325                 authoff = opt->DataDirectory[ctidx].VirtualAddress;
326                 authsz = opt->DataDirectory[ctidx].Size;
327         } else {
328                 debug("%s: Invalid optional header magic %x\n", __func__,
329                       nt->OptionalHeader.Magic);
330                 goto err;
331         }
332
333         /* 2. Sections */
334         num_sections = nt->FileHeader.NumberOfSections;
335         sections = (void *)((uint8_t *)&nt->OptionalHeader +
336                             nt->FileHeader.SizeOfOptionalHeader);
337         sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
338         if (!sorted) {
339                 debug("%s: Out of memory\n", __func__);
340                 goto err;
341         }
342
343         /*
344          * Make sure the section list is in ascending order.
345          */
346         for (i = 0; i < num_sections; i++)
347                 sorted[i] = &sections[i];
348         qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
349
350         for (i = 0; i < num_sections; i++) {
351                 if (!sorted[i]->SizeOfRawData)
352                         continue;
353
354                 size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
355                 efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
356                                      efi + sorted[i]->PointerToRawData + size,
357                                      0);
358                 debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
359                       i, sorted[i]->Name,
360                       sorted[i]->PointerToRawData,
361                       sorted[i]->PointerToRawData + size,
362                       sorted[i]->VirtualAddress,
363                       sorted[i]->VirtualAddress
364                         + sorted[i]->Misc.VirtualSize);
365
366                 bytes_hashed += size;
367         }
368         free(sorted);
369
370         /* 3. Extra data excluding Certificates Table */
371         if (bytes_hashed + authsz < len) {
372                 debug("extra data for hash: %zu\n",
373                       len - (bytes_hashed + authsz));
374                 efi_image_region_add(regs, efi + bytes_hashed,
375                                      efi + len - authsz, 0);
376         }
377
378         /* Return Certificates Table */
379         if (authsz) {
380                 if (len < authoff + authsz) {
381                         debug("%s: Size for auth too large: %u >= %zu\n",
382                               __func__, authsz, len - authoff);
383                         goto err;
384                 }
385                 if (authsz < sizeof(*auth)) {
386                         debug("%s: Size for auth too small: %u < %zu\n",
387                               __func__, authsz, sizeof(*auth));
388                         goto err;
389                 }
390                 *auth = efi + authoff;
391                 *auth_len = authsz;
392                 debug("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff, authsz);
393         } else {
394                 *auth = NULL;
395                 *auth_len = 0;
396         }
397
398         *regp = regs;
399
400         return true;
401
402 err:
403         free(regs);
404
405         return false;
406 }
407
408 /**
409  * efi_image_unsigned_authenticate() - authenticate unsigned image with
410  * SHA256 hash
411  * @regs:       List of regions to be verified
412  *
413  * If an image is not signed, it doesn't have a signature. In this case,
414  * its message digest is calculated and it will be compared with one of
415  * hash values stored in signature databases.
416  *
417  * Return:      true if authenticated, false if not
418  */
419 static bool efi_image_unsigned_authenticate(struct efi_image_regions *regs)
420 {
421         struct efi_signature_store *db = NULL, *dbx = NULL;
422         bool ret = false;
423
424         dbx = efi_sigstore_parse_sigdb(L"dbx");
425         if (!dbx) {
426                 debug("Getting signature database(dbx) failed\n");
427                 goto out;
428         }
429
430         db = efi_sigstore_parse_sigdb(L"db");
431         if (!db) {
432                 debug("Getting signature database(db) failed\n");
433                 goto out;
434         }
435
436         /* try black-list first */
437         if (efi_signature_verify_with_sigdb(regs, NULL, dbx, NULL)) {
438                 debug("Image is not signed and rejected by \"dbx\"\n");
439                 goto out;
440         }
441
442         /* try white-list */
443         if (efi_signature_verify_with_sigdb(regs, NULL, db, NULL))
444                 ret = true;
445         else
446                 debug("Image is not signed and not found in \"db\" or \"dbx\"\n");
447
448 out:
449         efi_sigstore_free(db);
450         efi_sigstore_free(dbx);
451
452         return ret;
453 }
454
455 /**
456  * efi_image_authenticate() - verify a signature of signed image
457  * @efi:        Pointer to image
458  * @efi_size:   Size of @efi
459  *
460  * A signed image should have its signature stored in a table of its PE header.
461  * So if an image is signed and only if if its signature is verified using
462  * signature databases, an image is authenticated.
463  * If an image is not signed, its validity is checked by using
464  * efi_image_unsigned_authenticated().
465  * TODO:
466  * When AuditMode==0, if the image's signature is not found in
467  * the authorized database, or is found in the forbidden database,
468  * the image will not be started and instead, information about it
469  * will be placed in this table.
470  * When AuditMode==1, an EFI_IMAGE_EXECUTION_INFO element is created
471  * in the EFI_IMAGE_EXECUTION_INFO_TABLE for every certificate found
472  * in the certificate table of every image that is validated.
473  *
474  * Return:      true if authenticated, false if not
475  */
476 static bool efi_image_authenticate(void *efi, size_t efi_size)
477 {
478         struct efi_image_regions *regs = NULL;
479         WIN_CERTIFICATE *wincerts = NULL, *wincert;
480         size_t wincerts_len;
481         struct pkcs7_message *msg = NULL;
482         struct efi_signature_store *db = NULL, *dbx = NULL;
483         struct x509_certificate *cert = NULL;
484         void *new_efi = NULL;
485         size_t new_efi_size;
486         bool ret = false;
487
488         if (!efi_secure_boot_enabled())
489                 return true;
490
491         /*
492          * Size must be 8-byte aligned and the trailing bytes must be
493          * zero'ed. Otherwise hash value may be incorrect.
494          */
495         if (efi_size & 0x7) {
496                 new_efi_size = (efi_size + 0x7) & ~0x7ULL;
497                 new_efi = calloc(new_efi_size, 1);
498                 if (!new_efi)
499                         return false;
500                 memcpy(new_efi, efi, efi_size);
501                 efi = new_efi;
502                 efi_size = new_efi_size;
503         }
504
505         if (!efi_image_parse(efi, efi_size, &regs, &wincerts,
506                              &wincerts_len)) {
507                 debug("Parsing PE executable image failed\n");
508                 goto err;
509         }
510
511         if (!wincerts) {
512                 /* The image is not signed */
513                 ret = efi_image_unsigned_authenticate(regs);
514
515                 goto err;
516         }
517
518         /*
519          * verify signature using db and dbx
520          */
521         db = efi_sigstore_parse_sigdb(L"db");
522         if (!db) {
523                 debug("Getting signature database(db) failed\n");
524                 goto err;
525         }
526
527         dbx = efi_sigstore_parse_sigdb(L"dbx");
528         if (!dbx) {
529                 debug("Getting signature database(dbx) failed\n");
530                 goto err;
531         }
532
533         /* go through WIN_CERTIFICATE list */
534         for (wincert = wincerts;
535              (void *)wincert < (void *)wincerts + wincerts_len;
536              wincert = (void *)wincert + ALIGN(wincert->dwLength, 8)) {
537                 if (wincert->dwLength < sizeof(*wincert)) {
538                         debug("%s: dwLength too small: %u < %zu\n",
539                               __func__, wincert->dwLength, sizeof(*wincert));
540                         goto err;
541                 }
542                 msg = pkcs7_parse_message((void *)wincert + sizeof(*wincert),
543                                           wincert->dwLength - sizeof(*wincert));
544                 if (IS_ERR(msg)) {
545                         debug("Parsing image's signature failed\n");
546                         msg = NULL;
547                         goto err;
548                 }
549
550                 /* try black-list first */
551                 if (efi_signature_verify_with_sigdb(regs, msg, dbx, NULL)) {
552                         debug("Signature was rejected by \"dbx\"\n");
553                         goto err;
554                 }
555
556                 if (!efi_signature_verify_signers(msg, dbx)) {
557                         debug("Signer was rejected by \"dbx\"\n");
558                         goto err;
559                 } else {
560                         ret = true;
561                 }
562
563                 /* try white-list */
564                 if (!efi_signature_verify_with_sigdb(regs, msg, db, &cert)) {
565                         debug("Verifying signature with \"db\" failed\n");
566                         goto err;
567                 } else {
568                         ret = true;
569                 }
570
571                 if (!efi_signature_verify_cert(cert, dbx)) {
572                         debug("Certificate was rejected by \"dbx\"\n");
573                         goto err;
574                 } else {
575                         ret = true;
576                 }
577         }
578
579 err:
580         x509_free_certificate(cert);
581         efi_sigstore_free(db);
582         efi_sigstore_free(dbx);
583         pkcs7_free_message(msg);
584         free(regs);
585         free(new_efi);
586
587         return ret;
588 }
589 #else
590 static bool efi_image_authenticate(void *efi, size_t efi_size)
591 {
592         return true;
593 }
594 #endif /* CONFIG_EFI_SECURE_BOOT */
595
596 /**
597  * efi_load_pe() - relocate EFI binary
598  *
599  * This function loads all sections from a PE binary into a newly reserved
600  * piece of memory. On success the entry point is returned as handle->entry.
601  *
602  * @handle:             loaded image handle
603  * @efi:                pointer to the EFI binary
604  * @efi_size:           size of @efi binary
605  * @loaded_image_info:  loaded image protocol
606  * Return:              status code
607  */
608 efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
609                          void *efi, size_t efi_size,
610                          struct efi_loaded_image *loaded_image_info)
611 {
612         IMAGE_NT_HEADERS32 *nt;
613         IMAGE_DOS_HEADER *dos;
614         IMAGE_SECTION_HEADER *sections;
615         int num_sections;
616         void *efi_reloc;
617         int i;
618         const IMAGE_BASE_RELOCATION *rel;
619         unsigned long rel_size;
620         int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
621         uint64_t image_base;
622         unsigned long virt_size = 0;
623         int supported = 0;
624         efi_status_t ret;
625
626         /* Sanity check for a file header */
627         if (efi_size < sizeof(*dos)) {
628                 printf("%s: Truncated DOS Header\n", __func__);
629                 ret = EFI_LOAD_ERROR;
630                 goto err;
631         }
632
633         dos = efi;
634         if (dos->e_magic != IMAGE_DOS_SIGNATURE) {
635                 printf("%s: Invalid DOS Signature\n", __func__);
636                 ret = EFI_LOAD_ERROR;
637                 goto err;
638         }
639
640         /*
641          * Check if the image section header fits into the file. Knowing that at
642          * least one section header follows we only need to check for the length
643          * of the 64bit header which is longer than the 32bit header.
644          */
645         if (efi_size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS64)) {
646                 printf("%s: Invalid offset for Extended Header\n", __func__);
647                 ret = EFI_LOAD_ERROR;
648                 goto err;
649         }
650
651         nt = (void *) ((char *)efi + dos->e_lfanew);
652         if (nt->Signature != IMAGE_NT_SIGNATURE) {
653                 printf("%s: Invalid NT Signature\n", __func__);
654                 ret = EFI_LOAD_ERROR;
655                 goto err;
656         }
657
658         for (i = 0; machines[i]; i++)
659                 if (machines[i] == nt->FileHeader.Machine) {
660                         supported = 1;
661                         break;
662                 }
663
664         if (!supported) {
665                 printf("%s: Machine type 0x%04x is not supported\n",
666                        __func__, nt->FileHeader.Machine);
667                 ret = EFI_LOAD_ERROR;
668                 goto err;
669         }
670
671         num_sections = nt->FileHeader.NumberOfSections;
672         sections = (void *)&nt->OptionalHeader +
673                             nt->FileHeader.SizeOfOptionalHeader;
674
675         if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
676                         - efi)) {
677                 printf("%s: Invalid number of sections: %d\n",
678                        __func__, num_sections);
679                 ret = EFI_LOAD_ERROR;
680                 goto err;
681         }
682
683         /* Authenticate an image */
684         if (efi_image_authenticate(efi, efi_size))
685                 handle->auth_status = EFI_IMAGE_AUTH_PASSED;
686         else
687                 handle->auth_status = EFI_IMAGE_AUTH_FAILED;
688
689         /* Calculate upper virtual address boundary */
690         for (i = num_sections - 1; i >= 0; i--) {
691                 IMAGE_SECTION_HEADER *sec = &sections[i];
692                 virt_size = max_t(unsigned long, virt_size,
693                                   sec->VirtualAddress + sec->Misc.VirtualSize);
694         }
695
696         /* Read 32/64bit specific header bits */
697         if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
698                 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
699                 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
700                 image_base = opt->ImageBase;
701                 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
702                 handle->image_type = opt->Subsystem;
703                 efi_reloc = efi_alloc(virt_size,
704                                       loaded_image_info->image_code_type);
705                 if (!efi_reloc) {
706                         printf("%s: Could not allocate %lu bytes\n",
707                                __func__, virt_size);
708                         ret = EFI_OUT_OF_RESOURCES;
709                         goto err;
710                 }
711                 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
712                 rel_size = opt->DataDirectory[rel_idx].Size;
713                 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
714                 virt_size = ALIGN(virt_size, opt->SectionAlignment);
715         } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
716                 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
717                 image_base = opt->ImageBase;
718                 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
719                 handle->image_type = opt->Subsystem;
720                 efi_reloc = efi_alloc(virt_size,
721                                       loaded_image_info->image_code_type);
722                 if (!efi_reloc) {
723                         printf("%s: Could not allocate %lu bytes\n",
724                                __func__, virt_size);
725                         ret = EFI_OUT_OF_RESOURCES;
726                         goto err;
727                 }
728                 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
729                 rel_size = opt->DataDirectory[rel_idx].Size;
730                 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
731                 virt_size = ALIGN(virt_size, opt->SectionAlignment);
732         } else {
733                 printf("%s: Invalid optional header magic %x\n", __func__,
734                        nt->OptionalHeader.Magic);
735                 ret = EFI_LOAD_ERROR;
736                 goto err;
737         }
738
739         /* Copy PE headers */
740         memcpy(efi_reloc, efi,
741                sizeof(*dos)
742                  + sizeof(*nt)
743                  + nt->FileHeader.SizeOfOptionalHeader
744                  + num_sections * sizeof(IMAGE_SECTION_HEADER));
745
746         /* Load sections into RAM */
747         for (i = num_sections - 1; i >= 0; i--) {
748                 IMAGE_SECTION_HEADER *sec = &sections[i];
749                 memset(efi_reloc + sec->VirtualAddress, 0,
750                        sec->Misc.VirtualSize);
751                 memcpy(efi_reloc + sec->VirtualAddress,
752                        efi + sec->PointerToRawData,
753                        sec->SizeOfRawData);
754         }
755
756         /* Run through relocations */
757         if (efi_loader_relocate(rel, rel_size, efi_reloc,
758                                 (unsigned long)image_base) != EFI_SUCCESS) {
759                 efi_free_pages((uintptr_t) efi_reloc,
760                                (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
761                 ret = EFI_LOAD_ERROR;
762                 goto err;
763         }
764
765         /* Flush cache */
766         flush_cache((ulong)efi_reloc,
767                     ALIGN(virt_size, EFI_CACHELINE_SIZE));
768         invalidate_icache_all();
769
770         /* Populate the loaded image interface bits */
771         loaded_image_info->image_base = efi_reloc;
772         loaded_image_info->image_size = virt_size;
773
774         if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
775                 return EFI_SUCCESS;
776         else
777                 return EFI_SECURITY_VIOLATION;
778
779 err:
780         return ret;
781 }