1 // SPDX-License-Identifier: GPL-2.0
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.
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
18 #include "../string.h"
19 #include "../voffset.h"
20 #include <asm/bootparam_utils.h>
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.
29 /* Macros used by the included decompressor code below. */
33 * Use normal definitions of mem*() from string.c. There are already
34 * included header files which expect a definition of memset() and by
35 * the time we define memset macro, it is too late.
39 #define memzero(s, n) memset((s), 0, (n))
40 #define memmove memmove
42 /* Functions used by the included decompressor code below. */
43 void *memmove(void *dest, const void *src, size_t n);
46 * This is set up by the setup-routine at boot-time
48 struct boot_params *boot_params;
51 memptr free_mem_end_ptr;
55 static int lines, cols;
57 #ifdef CONFIG_KERNEL_GZIP
58 #include "../../../../lib/decompress_inflate.c"
61 #ifdef CONFIG_KERNEL_BZIP2
62 #include "../../../../lib/decompress_bunzip2.c"
65 #ifdef CONFIG_KERNEL_LZMA
66 #include "../../../../lib/decompress_unlzma.c"
69 #ifdef CONFIG_KERNEL_XZ
70 #include "../../../../lib/decompress_unxz.c"
73 #ifdef CONFIG_KERNEL_LZO
74 #include "../../../../lib/decompress_unlzo.c"
77 #ifdef CONFIG_KERNEL_LZ4
78 #include "../../../../lib/decompress_unlz4.c"
81 #ifdef CONFIG_KERNEL_ZSTD
82 #include "../../../../lib/decompress_unzstd.c"
85 * NOTE: When adding a new decompressor, please update the analysis in
89 static void scroll(void)
93 memmove(vidmem, vidmem + cols * 2, (lines - 1) * cols * 2);
94 for (i = (lines - 1) * cols * 2; i < lines * cols * 2; i += 2)
100 #define TXR 0 /* Transmit register (WRITE) */
101 #define LSR 5 /* Line Status */
102 static void serial_putchar(int ch)
104 unsigned timeout = 0xffff;
106 while ((inb(early_serial_base + LSR) & XMTRDY) == 0 && --timeout)
109 outb(ch, early_serial_base + TXR);
112 void __putstr(const char *s)
117 if (early_serial_base) {
121 serial_putchar('\r');
122 serial_putchar(*str++);
126 if (lines == 0 || cols == 0)
129 x = boot_params->screen_info.orig_x;
130 y = boot_params->screen_info.orig_y;
132 while ((c = *s++) != '\0') {
140 vidmem[(x + cols * y) * 2] = c;
151 boot_params->screen_info.orig_x = x;
152 boot_params->screen_info.orig_y = y;
154 pos = (x + cols * y) * 2; /* Update cursor position */
156 outb(0xff & (pos >> 9), vidport+1);
158 outb(0xff & (pos >> 1), vidport+1);
161 void __puthex(unsigned long value)
166 for (bits = sizeof(value) * 8 - 4; bits >= 0; bits -= 4) {
167 unsigned long digit = (value >> bits) & 0xf;
170 alpha[0] = '0' + digit;
172 alpha[0] = 'a' + (digit - 0xA);
178 #if CONFIG_X86_NEED_RELOCS
179 static void handle_relocations(void *output, unsigned long output_len,
180 unsigned long virt_addr)
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);
188 * Calculate the delta between where vmlinux was linked to load
189 * and where it was actually loaded.
191 delta = min_addr - LOAD_PHYSICAL_ADDR;
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.
200 map = delta - __START_KERNEL_map;
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.
207 if (IS_ENABLED(CONFIG_X86_64))
208 delta = virt_addr - LOAD_PHYSICAL_ADDR;
211 debug_putstr("No relocation needed... ");
214 debug_putstr("Performing relocations... ");
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.
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
233 * So we work backwards from the end of the decompressed image.
235 for (reloc = output + output_len - sizeof(*reloc); *reloc; reloc--) {
236 long extended = *reloc;
239 ptr = (unsigned long)extended;
240 if (ptr < min_addr || ptr > max_addr)
241 error("32-bit relocation outside of kernel!\n");
243 *(uint32_t *)ptr += delta;
247 long extended = *reloc;
250 ptr = (unsigned long)extended;
251 if (ptr < min_addr || ptr > max_addr)
252 error("inverse 32-bit relocation outside of kernel!\n");
254 *(int32_t *)ptr -= delta;
256 for (reloc--; *reloc; reloc--) {
257 long extended = *reloc;
260 ptr = (unsigned long)extended;
261 if (ptr < min_addr || ptr > max_addr)
262 error("64-bit relocation outside of kernel!\n");
264 *(uint64_t *)ptr += delta;
269 static inline void handle_relocations(void *output, unsigned long output_len,
270 unsigned long virt_addr)
274 static void parse_elf(void *output)
278 Elf64_Phdr *phdrs, *phdr;
281 Elf32_Phdr *phdrs, *phdr;
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");
295 debug_putstr("Parsing ELF... ");
297 phdrs = malloc(sizeof(*phdrs) * ehdr.e_phnum);
299 error("Failed to allocate space for phdrs");
301 memcpy(phdrs, output + ehdr.e_phoff, sizeof(*phdrs) * ehdr.e_phnum);
303 for (i = 0; i < ehdr.e_phnum; i++) {
306 switch (phdr->p_type) {
309 if ((phdr->p_align % 0x200000) != 0)
310 error("Alignment of LOAD segment isn't multiple of 2MB");
312 #ifdef CONFIG_RELOCATABLE
314 dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR);
316 dest = (void *)(phdr->p_paddr);
318 memmove(dest, output + phdr->p_offset, phdr->p_filesz);
320 default: /* Ignore other PT_* */ break;
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
334 * |-----compressed kernel image------|
336 * 0 extract_offset +INIT_SIZE
337 * |-----------|---------------|-------------------------|--------|
339 * VO__text startup_32 of ZO VO__end ZO__end
341 * |-------uncompressed kernel image---------|
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)
350 const unsigned long kernel_total_size = VO__end - VO__text;
351 unsigned long virt_addr = LOAD_PHYSICAL_ADDR;
352 unsigned long needed_size;
354 /* Retain x86 boot parameters pointer passed from startup_32/64. */
357 /* Clear flags intended for solely in-kernel use. */
358 boot_params->hdr.loadflags &= ~KASLR_FLAG;
360 sanitize_boot_params(boot_params);
362 if (boot_params->screen_info.orig_video_mode == 7) {
363 vidmem = (char *) 0xb0000;
366 vidmem = (char *) 0xb8000;
370 lines = boot_params->screen_info.orig_video_lines;
371 cols = boot_params->screen_info.orig_video_cols;
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
380 boot_params->acpi_rsdp_addr = get_rsdp_addr();
382 debug_putstr("early console in extract_kernel\n");
384 free_mem_ptr = heap; /* Heap */
385 free_mem_end_ptr = heap + BOOT_HEAP_SIZE;
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.
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.
398 needed_size = max(output_len, kernel_total_size);
400 needed_size = ALIGN(needed_size, MIN_KERNEL_ALIGN);
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);
412 /* Report address of 32-bit trampoline */
413 debug_putaddr(trampoline_32bit);
416 choose_random_location((unsigned long)input_data, input_len,
417 (unsigned long *)&output,
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");
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");
432 if (heap > ((-__PAGE_OFFSET-(128<<20)-1) & 0x7fffffff))
433 error("Destination address too large");
435 #ifndef CONFIG_RELOCATABLE
436 if ((unsigned long)output != LOAD_PHYSICAL_ADDR)
437 error("Destination address does not match LOAD_PHYSICAL_ADDR");
438 if (virt_addr != LOAD_PHYSICAL_ADDR)
439 error("Destination virtual address changed when not relocatable");
442 debug_putstr("\nDecompressing Linux... ");
443 __decompress(input_data, input_len, NULL, NULL, output, output_len,
446 handle_relocations(output, output_len, virt_addr);
447 debug_putstr("done.\nBooting the kernel.\n");
451 void fortify_panic(const char *name)
453 error("detected buffer overflow");