1 /*
2  *  EFI image loader
3  *
4  *  based partly on wine code
5  *
6  *  Copyright (c) 2016 Alexander Graf
7  *
8  *  SPDX-License-Identifier:     GPL-2.0+
9  */
10 
11 #include <common.h>
12 #include <efi_loader.h>
13 #include <pe.h>
14 #include <asm/global_data.h>
15 
16 DECLARE_GLOBAL_DATA_PTR;
17 
18 const efi_guid_t efi_global_variable_guid = EFI_GLOBAL_VARIABLE_GUID;
19 const efi_guid_t efi_guid_device_path = DEVICE_PATH_GUID;
20 const efi_guid_t efi_guid_loaded_image = LOADED_IMAGE_GUID;
21 const efi_guid_t efi_simple_file_system_protocol_guid =
22 		EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
23 const efi_guid_t efi_file_info_guid = EFI_FILE_INFO_GUID;
24 
25 static int machines[] = {
26 #if defined(CONFIG_ARM64)
27 	IMAGE_FILE_MACHINE_ARM64,
28 #elif defined(CONFIG_ARM)
29 	IMAGE_FILE_MACHINE_ARM,
30 	IMAGE_FILE_MACHINE_THUMB,
31 	IMAGE_FILE_MACHINE_ARMNT,
32 #endif
33 
34 #if defined(CONFIG_X86_64)
35 	IMAGE_FILE_MACHINE_AMD64,
36 #elif defined(CONFIG_X86)
37 	IMAGE_FILE_MACHINE_I386,
38 #endif
39 
40 #if defined(CONFIG_CPU_RISCV_32)
41 	IMAGE_FILE_MACHINE_RISCV32,
42 #endif
43 
44 #if defined(CONFIG_CPU_RISCV_64)
45 	IMAGE_FILE_MACHINE_RISCV64,
46 #endif
47 	0 };
48 
49 /*
50  * Print information about a loaded image.
51  *
52  * If the program counter is located within the image the offset to the base
53  * address is shown.
54  *
55  * @image:	loaded image
56  * @pc:		program counter (use NULL to suppress offset output)
57  * @return:	status code
58  */
59 efi_status_t efi_print_image_info(struct efi_loaded_image *image, void *pc)
60 {
61 	if (!image)
62 		return EFI_INVALID_PARAMETER;
63 	printf("UEFI image");
64 	printf(" [0x%p:0x%p]",
65 	       image->reloc_base, image->reloc_base + image->reloc_size - 1);
66 	if (pc && pc >= image->reloc_base &&
67 	    pc < image->reloc_base + image->reloc_size)
68 		printf(" pc=0x%zx", pc - image->reloc_base);
69 	if (image->file_path)
70 		printf(" '%pD'", image->file_path);
71 	printf("\n");
72 	return EFI_SUCCESS;
73 }
74 
75 /*
76  * Print information about all loaded images.
77  *
78  * @pc:		program counter (use NULL to suppress offset output)
79  */
80 void efi_print_image_infos(void *pc)
81 {
82 	struct efi_object *efiobj;
83 	struct efi_handler *handler;
84 
85 	list_for_each_entry(efiobj, &efi_obj_list, link) {
86 		list_for_each_entry(handler, &efiobj->protocols, link) {
87 			if (!guidcmp(handler->guid, &efi_guid_loaded_image)) {
88 				efi_print_image_info(
89 					handler->protocol_interface, pc);
90 			}
91 		}
92 	}
93 }
94 
95 static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
96 			unsigned long rel_size, void *efi_reloc)
97 {
98 	const IMAGE_BASE_RELOCATION *end;
99 	int i;
100 
101 	end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + rel_size);
102 	while (rel < end - 1 && rel->SizeOfBlock) {
103 		const uint16_t *relocs = (const uint16_t *)(rel + 1);
104 		i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(uint16_t);
105 		while (i--) {
106 			uint32_t offset = (uint32_t)(*relocs & 0xfff) +
107 					  rel->VirtualAddress;
108 			int type = *relocs >> EFI_PAGE_SHIFT;
109 			unsigned long delta = (unsigned long)efi_reloc;
110 			uint64_t *x64 = efi_reloc + offset;
111 			uint32_t *x32 = efi_reloc + offset;
112 			uint16_t *x16 = efi_reloc + offset;
113 
114 			switch (type) {
115 			case IMAGE_REL_BASED_ABSOLUTE:
116 				break;
117 			case IMAGE_REL_BASED_HIGH:
118 				*x16 += ((uint32_t)delta) >> 16;
119 				break;
120 			case IMAGE_REL_BASED_LOW:
121 				*x16 += (uint16_t)delta;
122 				break;
123 			case IMAGE_REL_BASED_HIGHLOW:
124 				*x32 += (uint32_t)delta;
125 				break;
126 			case IMAGE_REL_BASED_DIR64:
127 				*x64 += (uint64_t)delta;
128 				break;
129 			default:
130 				printf("Unknown Relocation off %x type %x\n",
131 				       offset, type);
132 				return EFI_LOAD_ERROR;
133 			}
134 			relocs++;
135 		}
136 		rel = (const IMAGE_BASE_RELOCATION *)relocs;
137 	}
138 	return EFI_SUCCESS;
139 }
140 
141 void __weak invalidate_icache_all(void)
142 {
143 	/* If the system doesn't support icache_all flush, cross our fingers */
144 }
145 
146 /*
147  * Determine the memory types to be used for code and data.
148  *
149  * @loaded_image_info	image descriptor
150  * @image_type		field Subsystem of the optional header for
151  *			Windows specific field
152  */
153 static void efi_set_code_and_data_type(
154 			struct efi_loaded_image *loaded_image_info,
155 			uint16_t image_type)
156 {
157 	switch (image_type) {
158 	case IMAGE_SUBSYSTEM_EFI_APPLICATION:
159 		loaded_image_info->image_code_type = EFI_LOADER_CODE;
160 		loaded_image_info->image_data_type = EFI_LOADER_DATA;
161 		break;
162 	case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
163 		loaded_image_info->image_code_type = EFI_BOOT_SERVICES_CODE;
164 		loaded_image_info->image_data_type = EFI_BOOT_SERVICES_DATA;
165 		break;
166 	case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
167 	case IMAGE_SUBSYSTEM_EFI_ROM:
168 		loaded_image_info->image_code_type = EFI_RUNTIME_SERVICES_CODE;
169 		loaded_image_info->image_data_type = EFI_RUNTIME_SERVICES_DATA;
170 		break;
171 	default:
172 		printf("%s: invalid image type: %u\n", __func__, image_type);
173 		/* Let's assume it is an application */
174 		loaded_image_info->image_code_type = EFI_LOADER_CODE;
175 		loaded_image_info->image_data_type = EFI_LOADER_DATA;
176 		break;
177 	}
178 }
179 
180 /*
181  * This function loads all sections from a PE binary into a newly reserved
182  * piece of memory. On successful load it then returns the entry point for
183  * the binary. Otherwise NULL.
184  */
185 void *efi_load_pe(void *efi, struct efi_loaded_image *loaded_image_info)
186 {
187 	IMAGE_NT_HEADERS32 *nt;
188 	IMAGE_DOS_HEADER *dos;
189 	IMAGE_SECTION_HEADER *sections;
190 	int num_sections;
191 	void *efi_reloc;
192 	int i;
193 	const IMAGE_BASE_RELOCATION *rel;
194 	unsigned long rel_size;
195 	int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
196 	void *entry;
197 	uint64_t image_size;
198 	unsigned long virt_size = 0;
199 	int supported = 0;
200 
201 	dos = efi;
202 	if (dos->e_magic != IMAGE_DOS_SIGNATURE) {
203 		printf("%s: Invalid DOS Signature\n", __func__);
204 		return NULL;
205 	}
206 
207 	nt = (void *) ((char *)efi + dos->e_lfanew);
208 	if (nt->Signature != IMAGE_NT_SIGNATURE) {
209 		printf("%s: Invalid NT Signature\n", __func__);
210 		return NULL;
211 	}
212 
213 	for (i = 0; machines[i]; i++)
214 		if (machines[i] == nt->FileHeader.Machine) {
215 			supported = 1;
216 			break;
217 		}
218 
219 	if (!supported) {
220 		printf("%s: Machine type 0x%04x is not supported\n",
221 		       __func__, nt->FileHeader.Machine);
222 		return NULL;
223 	}
224 
225 	/* Calculate upper virtual address boundary */
226 	num_sections = nt->FileHeader.NumberOfSections;
227 	sections = (void *)&nt->OptionalHeader +
228 			    nt->FileHeader.SizeOfOptionalHeader;
229 
230 	for (i = num_sections - 1; i >= 0; i--) {
231 		IMAGE_SECTION_HEADER *sec = &sections[i];
232 		virt_size = max_t(unsigned long, virt_size,
233 				  sec->VirtualAddress + sec->Misc.VirtualSize);
234 	}
235 
236 	/* Read 32/64bit specific header bits */
237 	if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
238 		IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
239 		IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
240 		image_size = opt->SizeOfImage;
241 		efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
242 		efi_reloc = efi_alloc(virt_size,
243 				      loaded_image_info->image_code_type);
244 		if (!efi_reloc) {
245 			printf("%s: Could not allocate %lu bytes\n",
246 			       __func__, virt_size);
247 			return NULL;
248 		}
249 		entry = efi_reloc + opt->AddressOfEntryPoint;
250 		rel_size = opt->DataDirectory[rel_idx].Size;
251 		rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
252 		virt_size = ALIGN(virt_size, opt->SectionAlignment);
253 	} else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
254 		IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
255 		image_size = opt->SizeOfImage;
256 		efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
257 		efi_reloc = efi_alloc(virt_size,
258 				      loaded_image_info->image_code_type);
259 		if (!efi_reloc) {
260 			printf("%s: Could not allocate %lu bytes\n",
261 			       __func__, virt_size);
262 			return NULL;
263 		}
264 		entry = efi_reloc + opt->AddressOfEntryPoint;
265 		rel_size = opt->DataDirectory[rel_idx].Size;
266 		rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
267 		virt_size = ALIGN(virt_size, opt->SectionAlignment);
268 	} else {
269 		printf("%s: Invalid optional header magic %x\n", __func__,
270 		       nt->OptionalHeader.Magic);
271 		return NULL;
272 	}
273 
274 	/* Load sections into RAM */
275 	for (i = num_sections - 1; i >= 0; i--) {
276 		IMAGE_SECTION_HEADER *sec = &sections[i];
277 		memset(efi_reloc + sec->VirtualAddress, 0,
278 		       sec->Misc.VirtualSize);
279 		memcpy(efi_reloc + sec->VirtualAddress,
280 		       efi + sec->PointerToRawData,
281 		       sec->SizeOfRawData);
282 	}
283 
284 	/* Run through relocations */
285 	if (efi_loader_relocate(rel, rel_size, efi_reloc) != EFI_SUCCESS) {
286 		efi_free_pages((uintptr_t) efi_reloc,
287 			       (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
288 		return NULL;
289 	}
290 
291 	/* Flush cache */
292 	flush_cache((ulong)efi_reloc,
293 		    ALIGN(virt_size, CONFIG_SYS_CACHELINE_SIZE));
294 	invalidate_icache_all();
295 
296 	/* Populate the loaded image interface bits */
297 	loaded_image_info->image_base = efi;
298 	loaded_image_info->image_size = image_size;
299 	loaded_image_info->reloc_base = efi_reloc;
300 	loaded_image_info->reloc_size = virt_size;
301 
302 	return entry;
303 }
304