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