xref: /openbmc/linux/arch/x86/boot/compressed/misc.c (revision ce656528)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * misc.c
4  *
5  * This is a collection of several routines used to extract the kernel
6  * which includes KASLR relocation, decompression, ELF parsing, and
7  * relocation processing. Additionally included are the screen and serial
8  * output functions and related debugging support functions.
9  *
10  * malloc by Hannu Savolainen 1993 and Matthias Urlichs 1994
11  * puts by Nick Holloway 1993, better puts by Martin Mares 1995
12  * High loaded stuff by Hans Lermen & Werner Almesberger, Feb. 1996
13  */
14 
15 #include "misc.h"
16 #include "error.h"
17 #include "pgtable.h"
18 #include "../string.h"
19 #include "../voffset.h"
20 #include <asm/bootparam_utils.h>
21 
22 /*
23  * WARNING!!
24  * This code is compiled with -fPIC and it is relocated dynamically at
25  * run time, but no relocation processing is performed. This means that
26  * it is not safe to place pointers in static structures.
27  */
28 
29 /* Macros used by the included decompressor code below. */
30 #define STATIC		static
31 /* Define an externally visible malloc()/free(). */
32 #define MALLOC_VISIBLE
33 #include <linux/decompress/mm.h>
34 
35 /*
36  * Provide definitions of memzero and memmove as some of the decompressors will
37  * try to define their own functions if these are not defined as macros.
38  */
39 #define memzero(s, n)	memset((s), 0, (n))
40 #ifndef memmove
41 #define memmove		memmove
42 /* Functions used by the included decompressor code below. */
43 void *memmove(void *dest, const void *src, size_t n);
44 #endif
45 
46 /*
47  * This is set up by the setup-routine at boot-time
48  */
49 struct boot_params *boot_params;
50 
51 memptr free_mem_ptr;
52 memptr free_mem_end_ptr;
53 
54 static char *vidmem;
55 static int vidport;
56 
57 /* These might be accessed before .bss is cleared, so use .data instead. */
58 static int lines __section(".data");
59 static int cols __section(".data");
60 
61 #ifdef CONFIG_KERNEL_GZIP
62 #include "../../../../lib/decompress_inflate.c"
63 #endif
64 
65 #ifdef CONFIG_KERNEL_BZIP2
66 #include "../../../../lib/decompress_bunzip2.c"
67 #endif
68 
69 #ifdef CONFIG_KERNEL_LZMA
70 #include "../../../../lib/decompress_unlzma.c"
71 #endif
72 
73 #ifdef CONFIG_KERNEL_XZ
74 #include "../../../../lib/decompress_unxz.c"
75 #endif
76 
77 #ifdef CONFIG_KERNEL_LZO
78 #include "../../../../lib/decompress_unlzo.c"
79 #endif
80 
81 #ifdef CONFIG_KERNEL_LZ4
82 #include "../../../../lib/decompress_unlz4.c"
83 #endif
84 
85 #ifdef CONFIG_KERNEL_ZSTD
86 #include "../../../../lib/decompress_unzstd.c"
87 #endif
88 /*
89  * NOTE: When adding a new decompressor, please update the analysis in
90  * ../header.S.
91  */
92 
93 static void scroll(void)
94 {
95 	int i;
96 
97 	memmove(vidmem, vidmem + cols * 2, (lines - 1) * cols * 2);
98 	for (i = (lines - 1) * cols * 2; i < lines * cols * 2; i += 2)
99 		vidmem[i] = ' ';
100 }
101 
102 #define XMTRDY          0x20
103 
104 #define TXR             0       /*  Transmit register (WRITE) */
105 #define LSR             5       /*  Line Status               */
106 static void serial_putchar(int ch)
107 {
108 	unsigned timeout = 0xffff;
109 
110 	while ((inb(early_serial_base + LSR) & XMTRDY) == 0 && --timeout)
111 		cpu_relax();
112 
113 	outb(ch, early_serial_base + TXR);
114 }
115 
116 void __putstr(const char *s)
117 {
118 	int x, y, pos;
119 	char c;
120 
121 	if (early_serial_base) {
122 		const char *str = s;
123 		while (*str) {
124 			if (*str == '\n')
125 				serial_putchar('\r');
126 			serial_putchar(*str++);
127 		}
128 	}
129 
130 	if (lines == 0 || cols == 0)
131 		return;
132 
133 	x = boot_params->screen_info.orig_x;
134 	y = boot_params->screen_info.orig_y;
135 
136 	while ((c = *s++) != '\0') {
137 		if (c == '\n') {
138 			x = 0;
139 			if (++y >= lines) {
140 				scroll();
141 				y--;
142 			}
143 		} else {
144 			vidmem[(x + cols * y) * 2] = c;
145 			if (++x >= cols) {
146 				x = 0;
147 				if (++y >= lines) {
148 					scroll();
149 					y--;
150 				}
151 			}
152 		}
153 	}
154 
155 	boot_params->screen_info.orig_x = x;
156 	boot_params->screen_info.orig_y = y;
157 
158 	pos = (x + cols * y) * 2;	/* Update cursor position */
159 	outb(14, vidport);
160 	outb(0xff & (pos >> 9), vidport+1);
161 	outb(15, vidport);
162 	outb(0xff & (pos >> 1), vidport+1);
163 }
164 
165 void __puthex(unsigned long value)
166 {
167 	char alpha[2] = "0";
168 	int bits;
169 
170 	for (bits = sizeof(value) * 8 - 4; bits >= 0; bits -= 4) {
171 		unsigned long digit = (value >> bits) & 0xf;
172 
173 		if (digit < 0xA)
174 			alpha[0] = '0' + digit;
175 		else
176 			alpha[0] = 'a' + (digit - 0xA);
177 
178 		__putstr(alpha);
179 	}
180 }
181 
182 #ifdef CONFIG_X86_NEED_RELOCS
183 static void handle_relocations(void *output, unsigned long output_len,
184 			       unsigned long virt_addr)
185 {
186 	int *reloc;
187 	unsigned long delta, map, ptr;
188 	unsigned long min_addr = (unsigned long)output;
189 	unsigned long max_addr = min_addr + (VO___bss_start - VO__text);
190 
191 	/*
192 	 * Calculate the delta between where vmlinux was linked to load
193 	 * and where it was actually loaded.
194 	 */
195 	delta = min_addr - LOAD_PHYSICAL_ADDR;
196 
197 	/*
198 	 * The kernel contains a table of relocation addresses. Those
199 	 * addresses have the final load address of the kernel in virtual
200 	 * memory. We are currently working in the self map. So we need to
201 	 * create an adjustment for kernel memory addresses to the self map.
202 	 * This will involve subtracting out the base address of the kernel.
203 	 */
204 	map = delta - __START_KERNEL_map;
205 
206 	/*
207 	 * 32-bit always performs relocations. 64-bit relocations are only
208 	 * needed if KASLR has chosen a different starting address offset
209 	 * from __START_KERNEL_map.
210 	 */
211 	if (IS_ENABLED(CONFIG_X86_64))
212 		delta = virt_addr - LOAD_PHYSICAL_ADDR;
213 
214 	if (!delta) {
215 		debug_putstr("No relocation needed... ");
216 		return;
217 	}
218 	debug_putstr("Performing relocations... ");
219 
220 	/*
221 	 * Process relocations: 32 bit relocations first then 64 bit after.
222 	 * Three sets of binary relocations are added to the end of the kernel
223 	 * before compression. Each relocation table entry is the kernel
224 	 * address of the location which needs to be updated stored as a
225 	 * 32-bit value which is sign extended to 64 bits.
226 	 *
227 	 * Format is:
228 	 *
229 	 * kernel bits...
230 	 * 0 - zero terminator for 64 bit relocations
231 	 * 64 bit relocation repeated
232 	 * 0 - zero terminator for inverse 32 bit relocations
233 	 * 32 bit inverse relocation repeated
234 	 * 0 - zero terminator for 32 bit relocations
235 	 * 32 bit relocation repeated
236 	 *
237 	 * So we work backwards from the end of the decompressed image.
238 	 */
239 	for (reloc = output + output_len - sizeof(*reloc); *reloc; reloc--) {
240 		long extended = *reloc;
241 		extended += map;
242 
243 		ptr = (unsigned long)extended;
244 		if (ptr < min_addr || ptr > max_addr)
245 			error("32-bit relocation outside of kernel!\n");
246 
247 		*(uint32_t *)ptr += delta;
248 	}
249 #ifdef CONFIG_X86_64
250 	while (*--reloc) {
251 		long extended = *reloc;
252 		extended += map;
253 
254 		ptr = (unsigned long)extended;
255 		if (ptr < min_addr || ptr > max_addr)
256 			error("inverse 32-bit relocation outside of kernel!\n");
257 
258 		*(int32_t *)ptr -= delta;
259 	}
260 	for (reloc--; *reloc; reloc--) {
261 		long extended = *reloc;
262 		extended += map;
263 
264 		ptr = (unsigned long)extended;
265 		if (ptr < min_addr || ptr > max_addr)
266 			error("64-bit relocation outside of kernel!\n");
267 
268 		*(uint64_t *)ptr += delta;
269 	}
270 #endif
271 }
272 #else
273 static inline void handle_relocations(void *output, unsigned long output_len,
274 				      unsigned long virt_addr)
275 { }
276 #endif
277 
278 static void parse_elf(void *output)
279 {
280 #ifdef CONFIG_X86_64
281 	Elf64_Ehdr ehdr;
282 	Elf64_Phdr *phdrs, *phdr;
283 #else
284 	Elf32_Ehdr ehdr;
285 	Elf32_Phdr *phdrs, *phdr;
286 #endif
287 	void *dest;
288 	int i;
289 
290 	memcpy(&ehdr, output, sizeof(ehdr));
291 	if (ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
292 	   ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
293 	   ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
294 	   ehdr.e_ident[EI_MAG3] != ELFMAG3) {
295 		error("Kernel is not a valid ELF file");
296 		return;
297 	}
298 
299 	debug_putstr("Parsing ELF... ");
300 
301 	phdrs = malloc(sizeof(*phdrs) * ehdr.e_phnum);
302 	if (!phdrs)
303 		error("Failed to allocate space for phdrs");
304 
305 	memcpy(phdrs, output + ehdr.e_phoff, sizeof(*phdrs) * ehdr.e_phnum);
306 
307 	for (i = 0; i < ehdr.e_phnum; i++) {
308 		phdr = &phdrs[i];
309 
310 		switch (phdr->p_type) {
311 		case PT_LOAD:
312 #ifdef CONFIG_X86_64
313 			if ((phdr->p_align % 0x200000) != 0)
314 				error("Alignment of LOAD segment isn't multiple of 2MB");
315 #endif
316 #ifdef CONFIG_RELOCATABLE
317 			dest = output;
318 			dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR);
319 #else
320 			dest = (void *)(phdr->p_paddr);
321 #endif
322 			memmove(dest, output + phdr->p_offset, phdr->p_filesz);
323 			break;
324 		default: /* Ignore other PT_* */ break;
325 		}
326 	}
327 
328 	free(phdrs);
329 }
330 
331 /*
332  * The compressed kernel image (ZO), has been moved so that its position
333  * is against the end of the buffer used to hold the uncompressed kernel
334  * image (VO) and the execution environment (.bss, .brk), which makes sure
335  * there is room to do the in-place decompression. (See header.S for the
336  * calculations.)
337  *
338  *                             |-----compressed kernel image------|
339  *                             V                                  V
340  * 0                       extract_offset                      +INIT_SIZE
341  * |-----------|---------------|-------------------------|--------|
342  *             |               |                         |        |
343  *           VO__text      startup_32 of ZO          VO__end    ZO__end
344  *             ^                                         ^
345  *             |-------uncompressed kernel image---------|
346  *
347  */
348 asmlinkage __visible void *extract_kernel(void *rmode, memptr heap,
349 				  unsigned char *input_data,
350 				  unsigned long input_len,
351 				  unsigned char *output,
352 				  unsigned long output_len)
353 {
354 	const unsigned long kernel_total_size = VO__end - VO__text;
355 	unsigned long virt_addr = LOAD_PHYSICAL_ADDR;
356 	unsigned long needed_size;
357 
358 	/* Retain x86 boot parameters pointer passed from startup_32/64. */
359 	boot_params = rmode;
360 
361 	/* Clear flags intended for solely in-kernel use. */
362 	boot_params->hdr.loadflags &= ~KASLR_FLAG;
363 
364 	sanitize_boot_params(boot_params);
365 
366 	if (boot_params->screen_info.orig_video_mode == 7) {
367 		vidmem = (char *) 0xb0000;
368 		vidport = 0x3b4;
369 	} else {
370 		vidmem = (char *) 0xb8000;
371 		vidport = 0x3d4;
372 	}
373 
374 	lines = boot_params->screen_info.orig_video_lines;
375 	cols = boot_params->screen_info.orig_video_cols;
376 
377 	console_init();
378 
379 	/*
380 	 * Save RSDP address for later use. Have this after console_init()
381 	 * so that early debugging output from the RSDP parsing code can be
382 	 * collected.
383 	 */
384 	boot_params->acpi_rsdp_addr = get_rsdp_addr();
385 
386 	debug_putstr("early console in extract_kernel\n");
387 
388 	free_mem_ptr     = heap;	/* Heap */
389 	free_mem_end_ptr = heap + BOOT_HEAP_SIZE;
390 
391 	/*
392 	 * The memory hole needed for the kernel is the larger of either
393 	 * the entire decompressed kernel plus relocation table, or the
394 	 * entire decompressed kernel plus .bss and .brk sections.
395 	 *
396 	 * On X86_64, the memory is mapped with PMD pages. Round the
397 	 * size up so that the full extent of PMD pages mapped is
398 	 * included in the check against the valid memory table
399 	 * entries. This ensures the full mapped area is usable RAM
400 	 * and doesn't include any reserved areas.
401 	 */
402 	needed_size = max(output_len, kernel_total_size);
403 #ifdef CONFIG_X86_64
404 	needed_size = ALIGN(needed_size, MIN_KERNEL_ALIGN);
405 #endif
406 
407 	/* Report initial kernel position details. */
408 	debug_putaddr(input_data);
409 	debug_putaddr(input_len);
410 	debug_putaddr(output);
411 	debug_putaddr(output_len);
412 	debug_putaddr(kernel_total_size);
413 	debug_putaddr(needed_size);
414 
415 #ifdef CONFIG_X86_64
416 	/* Report address of 32-bit trampoline */
417 	debug_putaddr(trampoline_32bit);
418 #endif
419 
420 	choose_random_location((unsigned long)input_data, input_len,
421 				(unsigned long *)&output,
422 				needed_size,
423 				&virt_addr);
424 
425 	/* Validate memory location choices. */
426 	if ((unsigned long)output & (MIN_KERNEL_ALIGN - 1))
427 		error("Destination physical address inappropriately aligned");
428 	if (virt_addr & (MIN_KERNEL_ALIGN - 1))
429 		error("Destination virtual address inappropriately aligned");
430 #ifdef CONFIG_X86_64
431 	if (heap > 0x3fffffffffffUL)
432 		error("Destination address too large");
433 	if (virt_addr + max(output_len, kernel_total_size) > KERNEL_IMAGE_SIZE)
434 		error("Destination virtual address is beyond the kernel mapping area");
435 #else
436 	if (heap > ((-__PAGE_OFFSET-(128<<20)-1) & 0x7fffffff))
437 		error("Destination address too large");
438 #endif
439 #ifndef CONFIG_RELOCATABLE
440 	if (virt_addr != LOAD_PHYSICAL_ADDR)
441 		error("Destination virtual address changed when not relocatable");
442 #endif
443 
444 	debug_putstr("\nDecompressing Linux... ");
445 	__decompress(input_data, input_len, NULL, NULL, output, output_len,
446 			NULL, error);
447 	parse_elf(output);
448 	handle_relocations(output, output_len, virt_addr);
449 	debug_putstr("done.\nBooting the kernel.\n");
450 
451 	/* Disable exception handling before booting the kernel */
452 	cleanup_exception_handling();
453 
454 	return output;
455 }
456 
457 void fortify_panic(const char *name)
458 {
459 	error("detected buffer overflow");
460 }
461