1From ff406eff25465932b97a2857ee5a75fd0957e9b9 Mon Sep 17 00:00:00 2001
2From: Peter Jones <pjones@redhat.com>
3Date: Thu, 11 Feb 2021 17:07:33 +0100
4Subject: [PATCH] util/mkimage: Improve data_size value calculation
5
6According to "Microsoft Portable Executable and Common Object File Format
7Specification", the Optional Header SizeOfInitializedData field contains:
8
9  Size of the initialized data section, or the sum of all such sections if
10  there are multiple data sections.
11
12Make this explicit by adding the GRUB kernel data size to the sum of all
13the modules sizes. The ALIGN_UP() is not required by the PE spec but do
14it to avoid alignment issues.
15
16Signed-off-by: Peter Jones <pjones@redhat.com>
17Signed-off-by: Javier Martinez Canillas <javierm@redhat.com>
18Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
19Signed-off-by: Stefan Sørensen <stefan.sorensen@spectralink.com>
20---
21 util/mkimage.c | 6 +++++-
22 1 file changed, 5 insertions(+), 1 deletion(-)
23
24diff --git a/util/mkimage.c b/util/mkimage.c
25index deaef56..853a521 100644
26--- a/util/mkimage.c
27+++ b/util/mkimage.c
28@@ -1260,6 +1260,7 @@ grub_install_generate_image (const char *dir, const char *prefix,
29 	void *pe_img;
30 	grub_uint8_t *header;
31 	void *sections;
32+	size_t scn_size;
33 	size_t pe_size;
34 	struct grub_pe32_coff_header *c;
35 	struct grub_pe32_section_table *text_section, *data_section;
36@@ -1362,7 +1363,10 @@ grub_install_generate_image (const char *dir, const char *prefix,
37 						| GRUB_PE32_SCN_MEM_EXECUTE
38 						| GRUB_PE32_SCN_MEM_READ);
39
40-	PE_OHDR (o32, o64, data_size) = grub_host_to_target32 (reloc_addr - layout.exec_size - header_size);
41+	scn_size = ALIGN_UP (layout.kernel_size - layout.exec_size, GRUB_PE32_FILE_ALIGNMENT);
42+	PE_OHDR (o32, o64, data_size) = grub_host_to_target32 (scn_size +
43+							       ALIGN_UP (total_module_size,
44+									 GRUB_PE32_FILE_ALIGNMENT));
45
46 	data_section = text_section + 1;
47 	strcpy (data_section->name, ".data");
48--
492.14.2
50
51