Debian Codegraph @

src/boot/pe.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "chid.h"
4 #include "devicetree.h"
5 #include "efi-firmware.h"
6 #include "efi-log.h"
7 #include "pe.h"
8 #include "util.h"
9
10 #define DOS_FILE_MAGIC "MZ"
11 #define PE_FILE_MAGIC "PE\0\0"
12 #define IMAGE_DLLCHARACTERISTICS_NX_COMPAT 0x0100U
13
14 #if defined(__i386__)
15 # define TARGET_MACHINE_TYPE 0x014CU
16 # define TARGET_MACHINE_TYPE_COMPATIBILITY 0x8664U
17 #elif defined(__x86_64__)
18 # define TARGET_MACHINE_TYPE 0x8664U
19 #elif defined(__aarch64__)
20 # define TARGET_MACHINE_TYPE 0xAA64U
21 #elif defined(__arm__)
22 # define TARGET_MACHINE_TYPE 0x01C2U
23 #elif defined(__riscv) && __riscv_xlen == 32
24 # define TARGET_MACHINE_TYPE 0x5032U
25 #elif defined(__riscv) && __riscv_xlen == 64
26 # define TARGET_MACHINE_TYPE 0x5064U
27 #elif defined(__loongarch__) && __loongarch_grlen == 32
28 # define TARGET_MACHINE_TYPE 0x6232U
29 #elif defined(__loongarch__) && __loongarch_grlen == 64
30 # define TARGET_MACHINE_TYPE 0x6264U
31 #else
32 # error Unknown EFI arch
33 #endif
34
35 #ifndef TARGET_MACHINE_TYPE_COMPATIBILITY
36 # define TARGET_MACHINE_TYPE_COMPATIBILITY 0
37 #endif
38
39 typedef struct DosFileHeader {
40 uint8_t Magic[2];
41 uint16_t LastSize;
42 uint16_t nBlocks;
43 uint16_t nReloc;
44 uint16_t HdrSize;
45 uint16_t MinAlloc;
46 uint16_t MaxAlloc;
47 uint16_t ss;
48 uint16_t sp;
49 uint16_t Checksum;
50 uint16_t ip;
51 uint16_t cs;
52 uint16_t RelocPos;
53 uint16_t nOverlay;
54 uint16_t reserved[4];
55 uint16_t OEMId;
56 uint16_t OEMInfo;
57 uint16_t reserved2[10];
58 uint32_t ExeHeader;
59 } _packed_ DosFileHeader;
60
61 typedef struct CoffFileHeader {
62 uint16_t Machine;
63 uint16_t NumberOfSections;
64 uint32_t TimeDateStamp;
65 uint32_t PointerToSymbolTable;
66 uint32_t NumberOfSymbols;
67 uint16_t SizeOfOptionalHeader;
68 uint16_t Characteristics;
69 } _packed_ CoffFileHeader;
70
71 #define OPTHDR32_MAGIC 0x10B /* PE32 OptionalHeader */
72 #define OPTHDR64_MAGIC 0x20B /* PE32+ OptionalHeader */
73
74 typedef struct PeImageDataDirectory {
75 uint32_t VirtualAddress;
76 uint32_t Size;
77 } _packed_ PeImageDataDirectory;
78
79 #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
80
81 typedef struct PeOptionalHeader {
82 uint16_t Magic;
83 uint8_t LinkerMajor;
84 uint8_t LinkerMinor;
85 uint32_t SizeOfCode;
86 uint32_t SizeOfInitializedData;
87 uint32_t SizeOfUninitializeData;
88 uint32_t AddressOfEntryPoint;
89 uint32_t BaseOfCode;
90 union {
91 struct { /* PE32 */
92 uint32_t BaseOfData;
93 uint32_t ImageBase32;
94 };
95 uint64_t ImageBase64; /* PE32+ */
96 };
97 uint32_t SectionAlignment;
98 uint32_t FileAlignment;
99 uint16_t MajorOperatingSystemVersion;
100 uint16_t MinorOperatingSystemVersion;
101 uint16_t MajorImageVersion;
102 uint16_t MinorImageVersion;
103 uint16_t MajorSubsystemVersion;
104 uint16_t MinorSubsystemVersion;
105 uint32_t Win32VersionValue;
106 uint32_t SizeOfImage;
107 uint32_t SizeOfHeaders;
108 uint32_t CheckSum;
109 uint16_t Subsystem;
110 uint16_t DllCharacteristics;
111 union {
112 struct {
113 uint64_t SizeOfStackReserve64;
114 uint64_t SizeOfStackCommit64;
115 uint64_t SizeOfHeapReserve64;
116 uint64_t SizeOfHeapCommit64;
117 uint32_t LoaderFlags64;
118 uint32_t NumberOfRvaAndSizes64;
119
120 PeImageDataDirectory DataDirectory64[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
121 };
122 struct {
123 uint32_t SizeOfStackReserve32;
124 uint32_t SizeOfStackCommit32;
125 uint32_t SizeOfHeapReserve32;
126 uint32_t SizeOfHeapCommit32;
127 uint32_t LoaderFlags32;
128 uint32_t NumberOfRvaAndSizes32;
129
130 PeImageDataDirectory DataDirectory32[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
131 };
132 };
133 } _packed_ PeOptionalHeader;
134
135 typedef struct PeFileHeader {
136 uint8_t Magic[4];
137 CoffFileHeader FileHeader;
138 PeOptionalHeader OptionalHeader;
139 } _packed_ PeFileHeader;
140
141 #define SECTION_TABLE_BYTES_MAX (16U * 1024U * 1024U)
142
143 static bool verify_dos(const DosFileHeader *dos) {
144 assert(dos);
145
146 DISABLE_WARNING_TYPE_LIMITS;
147 return memcmp(dos->Magic, DOS_FILE_MAGIC, STRLEN(DOS_FILE_MAGIC)) == 0 &&
148 dos->ExeHeader >= sizeof(DosFileHeader) &&
149 (size_t) dos->ExeHeader <= SIZE_MAX - sizeof(PeFileHeader);
150 REENABLE_WARNING;
151 }
152
153 static bool verify_pe(
154 const DosFileHeader *dos,
155 const PeFileHeader *pe,
156 bool allow_compatibility) {
157
158 assert(dos);
159 assert(pe);
160
161 return memcmp(pe->Magic, PE_FILE_MAGIC, STRLEN(PE_FILE_MAGIC)) == 0 &&
162 (pe->FileHeader.Machine == TARGET_MACHINE_TYPE ||
163 (allow_compatibility && pe->FileHeader.Machine == TARGET_MACHINE_TYPE_COMPATIBILITY)) &&
164 pe->FileHeader.NumberOfSections > 0 &&
165 IN_SET(pe->OptionalHeader.Magic, OPTHDR32_MAGIC, OPTHDR64_MAGIC) &&
166 pe->FileHeader.SizeOfOptionalHeader < SIZE_MAX - (dos->ExeHeader + offsetof(PeFileHeader, OptionalHeader));
167 }
168
169 static size_t section_table_offset(const DosFileHeader *dos, const PeFileHeader *pe) {
170 assert(dos);
171 assert(pe);
172
173 return dos->ExeHeader + offsetof(PeFileHeader, OptionalHeader) + pe->FileHeader.SizeOfOptionalHeader;
174 }
175
176 static bool pe_section_name_equal(const char *a, const char *b) {
177
178 if (a == b)
179 return true;
180 if (!a != !b)
181 return false;
182
183 /* Compares up to 8 characters of a and b i.e. the name size limit in the PE section header */
184
185 for (size_t i = 0; i < sizeof_field(PeSectionHeader, Name); i++) {
186 if (a[i] != b[i])
187 return false;
188
189 if (a[i] == 0) /* Name is shorter than 8 */
190 return true;
191 }
192
193 return true;
194 }
195
196 static bool pe_use_this_dtb(
197 const void *dtb,
198 size_t dtb_size,
199 const void *base,
200 const Device *device,
201 size_t section_nb) {
202
203 assert(dtb);
204
205 EFI_STATUS err;
206
207 err = devicetree_match(dtb, dtb_size);
208 if (err == EFI_SUCCESS)
209 return true;
210 if (err != EFI_UNSUPPORTED)
211 return false;
212
213 /* There's nothing to match against if firmware does not provide DTB and there is no .hwids section */
214 if (!device || !base)
215 return false;
216
217 const char *compatible = device_get_compatible(base, device);
218 if (!compatible)
219 return false;
220
221 err = devicetree_match_by_compatible(dtb, dtb_size, compatible);
222 if (err == EFI_SUCCESS)
223 return true;
224 if (err == EFI_INVALID_PARAMETER)
225 log_error_status(err, "Found bad DT blob in PE section %zu", section_nb);
226 return false;
227 }
228
229 static bool pe_use_this_firmware(
230 const void *efifw,
231 size_t efifw_size,
232 const void *base,
233 const Device *device,
234 size_t section_nb) {
235
236 assert(efifw);
237
238 EFI_STATUS err;
239
240 /* if there is no hwids section, there is nothing much we can do */
241 if (!device || !base)
242 return false;
243
244 const char *fwid = device_get_fwid(base, device);
245 if (!fwid)
246 return false;
247
248 err = efi_firmware_match_by_fwid(efifw, efifw_size, fwid);
249 if (err == EFI_SUCCESS)
250 return true;
251 if (err == EFI_INVALID_PARAMETER)
252 log_error_status(err, "Found bad efifw blob in PE section %zu", section_nb);
253 return false;
254 }
255
256 static void pe_locate_sections_internal(
257 const PeSectionHeader section_table[],
258 size_t n_section_table,
259 const char *const section_names[],
260 size_t validate_base,
261 const void *device_table,
262 const Device *device,
263 PeSectionVector sections[]) {
264
265 assert(section_table || n_section_table == 0);
266 assert(section_names);
267 assert(sections);
268
269 /* Searches for the sections listed in 'sections[]' within the section table. Validates the resulted
270 * data. If 'validate_base' is non-zero also takes base offset when loaded into memory into account for
271 * checking for overflows. */
272
273 for (size_t i = 0; section_names[i]; i++)
274 FOREACH_ARRAY(j, section_table, n_section_table) {
275
276 if (!pe_section_name_equal((const char*) j->Name, section_names[i]))
277 continue;
278
279 /* Overflow check: ignore sections that are impossibly large, relative to the file
280 * address for the section. */
281 size_t size_max = SIZE_MAX - j->PointerToRawData;
282 if ((size_t) j->SizeOfRawData > size_max)
283 continue;
284
285 /* Overflow check: ignore sections that are impossibly large, given the virtual
286 * address for the section */
287 size_max = SIZE_MAX - j->VirtualAddress;
288 if ((size_t) j->VirtualSize > size_max)
289 continue;
290
291 /* 2nd overflow check: ignore sections that are impossibly large also taking the
292 * loaded base into account. */
293 if (validate_base != 0) {
294 if (validate_base > size_max)
295 continue;
296 size_max -= validate_base;
297
298 if (j->VirtualAddress > size_max)
299 continue;
300 }
301
302 /* Special handling for .dtbauto sections compared to plain .dtb */
303 if (pe_section_name_equal(section_names[i], ".dtbauto")) {
304 /* .dtbauto sections require validate_base for matching */
305 if (!validate_base)
306 break;
307 if (!pe_use_this_dtb(
308 (const uint8_t *) SIZE_TO_PTR(validate_base) + j->VirtualAddress,
309 j->VirtualSize,
310 device_table,
311 device,
312 (PTR_TO_SIZE(j) - PTR_TO_SIZE(section_table)) / sizeof(*j)))
313 continue;
314 }
315
316 /* handle efifw section which works very much like .dtbauto */
317 if (pe_section_name_equal(section_names[i], ".efifw")) {
318 /* can't match without validate_base */
319 if (!validate_base)
320 break;
321 if (!pe_use_this_firmware(
322 (const uint8_t *) SIZE_TO_PTR(validate_base) + j->VirtualAddress,
323 j->VirtualSize,
324 device_table,
325 device,
326 (PTR_TO_SIZE(j) - PTR_TO_SIZE(section_table)) / sizeof(*j)))
327 continue;
328 }
329
330 /* At this time, the sizes and offsets have been validated. Store them away */
331 sections[i] = (PeSectionVector) {
332 .memory_size = j->VirtualSize,
333 .memory_offset = j->VirtualAddress,
334 /* VirtualSize can be bigger than SizeOfRawData when the section requires
335 * uninitialized data. It can also be smaller than SizeOfRawData when there's
336 * no need for uninitialized data as SizeOfRawData is aligned to
337 * FileAlignment and VirtualSize isn't. The actual data that's read from disk
338 * is the minimum of these two fields. */
339 .file_size = MIN(j->SizeOfRawData, j->VirtualSize),
340 .file_offset = j->PointerToRawData,
341 };
342
343 /* First matching section wins, ignore the rest */
344 break;
345 }
346 }
347
348 static bool looking_for_dtbauto(const char *const section_names[]) {
349 assert(section_names);
350
351 for (size_t i = 0; section_names[i]; i++)
352 if (pe_section_name_equal(section_names[i], ".dtbauto"))
353 return true;
354 return false;
355 }
356
357 static void pe_locate_sections(
358 const PeSectionHeader section_table[],
359 size_t n_section_table,
360 const char *const section_names[],
361 size_t validate_base,
362 PeSectionVector sections[]) {
363
364 if (!looking_for_dtbauto(section_names))
365 return pe_locate_sections_internal(
366 section_table,
367 n_section_table,
368 section_names,
369 validate_base,
370 /* device_table= */ NULL,
371 /* device= */ NULL,
372 sections);
373
374 /* It doesn't make sense not to provide validate_base here */
375 assert(validate_base != 0);
376
377 const void *hwids = NULL;
378 const Device *device = NULL;
379
380 if (!firmware_devicetree_exists()) {
381 /* Find HWIDs table and search for the current device */
382 static const char *const hwid_section_names[] = { ".hwids", NULL };
383 PeSectionVector hwids_section[1] = {};
384
385 pe_locate_sections_internal(
386 section_table,
387 n_section_table,
388 hwid_section_names,
389 validate_base,
390 /* device_table= */ NULL,
391 /* device= */ NULL,
392 hwids_section);
393
394 if (PE_SECTION_VECTOR_IS_SET(hwids_section)) {
395 hwids = (const uint8_t *) SIZE_TO_PTR(validate_base) + hwids_section[0].memory_offset;
396
397 EFI_STATUS err = chid_match(hwids, hwids_section[0].memory_size, DEVICE_TYPE_DEVICETREE, &device);
398 if (err != EFI_SUCCESS) {
399 log_full(err, err == EFI_NOT_FOUND ? LOG_DEBUG : LOG_ERR,
400 "HWID matching failed, no DT blob will be selected: %m");
401 hwids = NULL;
402 }
403 }
404 }
405
406 return pe_locate_sections_internal(
407 section_table,
408 n_section_table,
409 section_names,
410 validate_base,
411 hwids,
412 device,
413 sections);
414 }
415
416 static uint32_t get_compatibility_entry_address(const DosFileHeader *dos, const PeFileHeader *pe) {
417 /* The kernel may provide alternative PE entry points for different PE architectures. This allows
418 * booting a 64-bit kernel on 32-bit EFI that is otherwise running on a 64-bit CPU. The locations of any
419 * such compat entry points are located in a special PE section. */
420
421 assert(dos);
422 assert(pe);
423
424 static const char *const section_names[] = { ".compat", NULL };
425 PeSectionVector vector[1] = {};
426 pe_locate_sections(
427 (const PeSectionHeader *) ((const uint8_t *) dos + section_table_offset(dos, pe)),
428 pe->FileHeader.NumberOfSections,
429 section_names,
430 PTR_TO_SIZE(dos),
431 vector);
432
433 if (!PE_SECTION_VECTOR_IS_SET(vector)) /* not found */
434 return 0;
435
436 typedef struct {
437 uint8_t type;
438 uint8_t size;
439 uint16_t machine_type;
440 uint32_t entry_point;
441 } _packed_ LinuxPeCompat1;
442
443 size_t addr = vector[0].memory_offset, size = vector[0].memory_size;
444
445 while (size >= sizeof(LinuxPeCompat1) && addr % alignof(LinuxPeCompat1) == 0) {
446 const LinuxPeCompat1 *compat = (const LinuxPeCompat1 *) ((const uint8_t *) dos + addr);
447
448 if (compat->type == 0 || compat->size == 0 || compat->size > size)
449 break;
450
451 if (compat->type == 1 &&
452 compat->size >= sizeof(LinuxPeCompat1) &&
453 compat->machine_type == TARGET_MACHINE_TYPE)
454 return compat->entry_point;
455
456 addr += compat->size;
457 size -= compat->size;
458 }
459
460 return 0;
461 }
462
463 EFI_STATUS pe_kernel_info(const void *base, uint32_t *ret_entry_point, uint32_t *ret_compat_entry_point, size_t *ret_size_in_memory) {
464 assert(base);
465
466 const DosFileHeader *dos = (const DosFileHeader *) base;
467 if (!verify_dos(dos))
468 return EFI_LOAD_ERROR;
469
470 const PeFileHeader *pe = (const PeFileHeader *) ((const uint8_t *) base + dos->ExeHeader);
471 if (!verify_pe(dos, pe, /* allow_compatibility= */ true))
472 return EFI_LOAD_ERROR;
473
474 /* When allocating we need to also consider the virtual/uninitialized data sections, so parse it out
475 * of the SizeOfImage field in the PE header and return it */
476 size_t size_in_memory = pe->OptionalHeader.SizeOfImage;
477
478 /* Support for LINUX_INITRD_MEDIA_GUID was added in kernel stub 1.0. */
479 if (pe->OptionalHeader.MajorImageVersion < 1)
480 return EFI_UNSUPPORTED;
481
482 if (pe->FileHeader.Machine == TARGET_MACHINE_TYPE) {
483 if (ret_entry_point)
484 *ret_entry_point = pe->OptionalHeader.AddressOfEntryPoint;
485 if (ret_compat_entry_point)
486 *ret_compat_entry_point = 0;
487 if (ret_size_in_memory)
488 *ret_size_in_memory = size_in_memory;
489 return EFI_SUCCESS;
490 }
491
492 uint32_t compat_entry_point = get_compatibility_entry_address(dos, pe);
493 if (compat_entry_point == 0)
494 /* Image type not supported and no compat entry found. */
495 return EFI_UNSUPPORTED;
496
497 if (ret_entry_point)
498 *ret_entry_point = 0;
499 if (ret_compat_entry_point)
500 *ret_compat_entry_point = compat_entry_point;
501 if (ret_size_in_memory)
502 *ret_size_in_memory = size_in_memory;
503
504 return EFI_SUCCESS;
505 }
506
507 /* https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#optional-header-data-directories-image-only */
508 #define BASE_RELOCATION_TABLE_DATA_DIRECTORY_ENTRY 5
509
510 /* We do not expect PE inner kernels to have any relocations. However that might be wrong for some
511 * architectures, or it might change in the future. If the case of relocation arise, we should transform this
512 * function in a function applying the relocations. However for now, since it would not be exercised and
513 * would bitrot, we leave it as a check that relocations are never expected.
514 */
515 EFI_STATUS pe_kernel_check_no_relocation(const void *base) {
516 assert(base);
517
518 const DosFileHeader *dos = base;
519 if (!verify_dos(dos))
520 return EFI_LOAD_ERROR;
521
522 const PeFileHeader *pe = (const PeFileHeader *) ((const uint8_t *) base + dos->ExeHeader);
523 if (!verify_pe(dos, pe, /* allow_compatibility= */ true))
524 return EFI_LOAD_ERROR;
525
526 const PeImageDataDirectory *data_directory;
527 switch (pe->OptionalHeader.Magic) {
528 case OPTHDR32_MAGIC:
529 data_directory = pe->OptionalHeader.DataDirectory32;
530 break;
531 case OPTHDR64_MAGIC:
532 data_directory = pe->OptionalHeader.DataDirectory64;
533 break;
534 default:
535 assert_not_reached();
536 }
537
538 if (data_directory[BASE_RELOCATION_TABLE_DATA_DIRECTORY_ENTRY].Size != 0)
539 return log_error_status(EFI_LOAD_ERROR, "Inner kernel image contains base relocations, which we do not support.");
540
541 return EFI_SUCCESS;
542 }
543
544 bool pe_kernel_check_nx_compat(const void *base) {
545 const DosFileHeader *dos = ASSERT_PTR(base);
546 if (!verify_dos(dos))
547 return false;
548
549 const PeFileHeader *pe = (const PeFileHeader *) ((const uint8_t *) base + dos->ExeHeader);
550 if (!verify_pe(dos, pe, /* allow_compatibility= */ true))
551 return false;
552
553 return pe->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
554 }
555
556 EFI_STATUS pe_section_table_from_base(
557 const void *base,
558 const PeSectionHeader **ret_section_table,
559 size_t *ret_n_section_table) {
560
561 assert(base);
562 assert(ret_section_table);
563 assert(ret_n_section_table);
564
565 const DosFileHeader *dos = (const DosFileHeader*) base;
566 if (!verify_dos(dos))
567 return EFI_LOAD_ERROR;
568
569 const PeFileHeader *pe = (const PeFileHeader*) ((const uint8_t*) base + dos->ExeHeader);
570 if (!verify_pe(dos, pe, /* allow_compatibility= */ false))
571 return EFI_LOAD_ERROR;
572
573 assert_cc(sizeof(pe->FileHeader.NumberOfSections) == sizeof(uint16_t)); /* multiplication below cannot overflow */
574
575 size_t n_section_table = pe->FileHeader.NumberOfSections;
576 if (n_section_table * sizeof(PeSectionHeader) > SECTION_TABLE_BYTES_MAX)
577 return EFI_OUT_OF_RESOURCES;
578
579 *ret_section_table = (const PeSectionHeader*) ((const uint8_t*) base + section_table_offset(dos, pe));
580 *ret_n_section_table = n_section_table;
581
582 return EFI_SUCCESS;
583 }
584
585 EFI_STATUS pe_memory_locate_sections(
586 const void *base,
587 const char *const section_names[],
588 PeSectionVector sections[]) {
589
590 EFI_STATUS err;
591
592 assert(base);
593 assert(section_names);
594 assert(sections);
595
596 const PeSectionHeader *section_table;
597 size_t n_section_table;
598 err = pe_section_table_from_base(base, &section_table, &n_section_table);
599 if (err != EFI_SUCCESS)
600 return err;
601
602 pe_locate_sections(
603 section_table,
604 n_section_table,
605 section_names,
606 PTR_TO_SIZE(base),
607 sections);
608
609 return EFI_SUCCESS;
610 }
611
612 EFI_STATUS pe_section_table_from_file(
613 EFI_FILE *handle,
614 PeSectionHeader **ret_section_table,
615 size_t *ret_n_section_table) {
616
617 EFI_STATUS err;
618 size_t len;
619
620 assert(handle);
621 assert(ret_section_table);
622 assert(ret_n_section_table);
623
624 DosFileHeader dos;
625 len = sizeof(dos);
626 err = handle->Read(handle, &len, &dos);
627 if (err != EFI_SUCCESS)
628 return err;
629 if (len != sizeof(dos) || !verify_dos(&dos))
630 return EFI_LOAD_ERROR;
631
632 err = handle->SetPosition(handle, dos.ExeHeader);
633 if (err != EFI_SUCCESS)
634 return err;
635
636 PeFileHeader pe;
637 len = sizeof(pe);
638 err = handle->Read(handle, &len, &pe);
639 if (err != EFI_SUCCESS)
640 return err;
641 if (len != sizeof(pe) || !verify_pe(&dos, &pe, /* allow_compatibility= */ false))
642 return EFI_LOAD_ERROR;
643
644 DISABLE_WARNING_TYPE_LIMITS;
645 if ((size_t) pe.FileHeader.NumberOfSections > SIZE_MAX / sizeof(PeSectionHeader))
646 return EFI_OUT_OF_RESOURCES;
647 REENABLE_WARNING;
648 size_t n_section_table = (size_t) pe.FileHeader.NumberOfSections;
649 if (n_section_table * sizeof(PeSectionHeader) > SECTION_TABLE_BYTES_MAX)
650 return EFI_OUT_OF_RESOURCES;
651
652 _cleanup_free_ PeSectionHeader *section_table = xnew(PeSectionHeader, n_section_table);
653 if (!section_table)
654 return EFI_OUT_OF_RESOURCES;
655
656 err = handle->SetPosition(handle, section_table_offset(&dos, &pe));
657 if (err != EFI_SUCCESS)
658 return err;
659
660 len = n_section_table * sizeof(PeSectionHeader);
661 err = handle->Read(handle, &len, section_table);
662 if (err != EFI_SUCCESS)
663 return err;
664 if (len != n_section_table * sizeof(PeSectionHeader))
665 return EFI_LOAD_ERROR;
666
667 *ret_section_table = TAKE_PTR(section_table);
668 *ret_n_section_table = n_section_table;
669 return EFI_SUCCESS;
670 }
671
672 static const PeSectionHeader* pe_section_table_find_profile_start(
673 const PeSectionHeader *section_table,
674 size_t n_section_table,
675 unsigned profile) {
676
677 assert(section_table || n_section_table == 0);
678
679 if (profile == UINT_MAX) /* base profile? that starts at the beginning */
680 return section_table;
681
682 unsigned current_profile = UINT_MAX;
683 FOREACH_ARRAY(p, section_table, n_section_table) {
684
685 if (!pe_section_name_equal((const char*) p->Name, ".profile"))
686 continue;
687
688 if (current_profile == UINT_MAX)
689 current_profile = 0;
690 else
691 current_profile++;
692
693 if (current_profile == profile) /* Found our profile! */
694 return p;
695 }
696
697 /* We reached the end of the table? Then this section does not exist */
698 return NULL;
699 }
700
701 static size_t pe_section_table_find_profile_length(
702 const PeSectionHeader *section_table,
703 size_t n_section_table,
704 const PeSectionHeader *start,
705 unsigned profile) {
706
707 assert(section_table);
708 assert(n_section_table > 0);
709 assert(start >= section_table);
710 assert(start < section_table + n_section_table);
711
712 /* Look for the next .profile (or the end of the table), this is where the sections for this
713 * profile end. The base profile does not start with a .profile, the others do, hence conditionally
714 * skip over the first entry. */
715 const PeSectionHeader *e;
716 if (profile == UINT_MAX) /* Base profile */
717 e = start;
718 else {
719 assert(pe_section_name_equal((const char *) start->Name, ".profile"));
720 e = start + 1;
721 }
722
723 for (; e < section_table + n_section_table; e++)
724 if (pe_section_name_equal((const char*) e->Name, ".profile"))
725 return e - start;
726
727 return (section_table + n_section_table) - start;
728 }
729
730 EFI_STATUS pe_locate_profile_sections(
731 const PeSectionHeader section_table[],
732 size_t n_section_table,
733 const char* const section_names[],
734 unsigned profile,
735 size_t validate_base,
736 PeSectionVector sections[]) {
737
738 assert(section_table || n_section_table == 0);
739 assert(section_names);
740 assert(sections);
741
742 /* Now scan through the section table until we skipped over the right number of .profile sections */
743 const PeSectionHeader *p = pe_section_table_find_profile_start(section_table, n_section_table, profile);
744 if (!p)
745 return EFI_NOT_FOUND;
746
747 /* Look for the next .profile (or the end of the table), this is where the sections for this
748 * profile end. */
749 size_t n = pe_section_table_find_profile_length(section_table, n_section_table, p, profile);
750
751 /* And now parse everything between the start and end of our profile */
752 pe_locate_sections(
753 p,
754 n,
755 section_names,
756 validate_base,
757 sections);
758
759 return EFI_SUCCESS;
760 }