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