x86/KASLR: Warn when KASLR is disabled
[cascardo/linux.git] / arch / x86 / boot / compressed / misc.c
1 /*
2  * misc.c
3  *
4  * This is a collection of several routines used to extract the kernel
5  * which includes KASLR relocation, decompression, ELF parsing, and
6  * relocation processing. Additionally included are the screen and serial
7  * output functions and related debugging support functions.
8  *
9  * malloc by Hannu Savolainen 1993 and Matthias Urlichs 1994
10  * puts by Nick Holloway 1993, better puts by Martin Mares 1995
11  * High loaded stuff by Hans Lermen & Werner Almesberger, Feb. 1996
12  */
13
14 #include "misc.h"
15 #include "../string.h"
16
17 /*
18  * WARNING!!
19  * This code is compiled with -fPIC and it is relocated dynamically at
20  * run time, but no relocation processing is performed. This means that
21  * it is not safe to place pointers in static structures.
22  */
23
24 /* Macros used by the included decompressor code below. */
25 #define STATIC          static
26
27 /*
28  * Use normal definitions of mem*() from string.c. There are already
29  * included header files which expect a definition of memset() and by
30  * the time we define memset macro, it is too late.
31  */
32 #undef memcpy
33 #undef memset
34 #define memzero(s, n)   memset((s), 0, (n))
35
36 /* Functions used by the included decompressor code below. */
37 static void error(char *m);
38
39 /*
40  * This is set up by the setup-routine at boot-time
41  */
42 struct boot_params *boot_params;
43
44 memptr free_mem_ptr;
45 memptr free_mem_end_ptr;
46
47 static char *vidmem;
48 static int vidport;
49 static int lines, cols;
50
51 #ifdef CONFIG_KERNEL_GZIP
52 #include "../../../../lib/decompress_inflate.c"
53 #endif
54
55 #ifdef CONFIG_KERNEL_BZIP2
56 #include "../../../../lib/decompress_bunzip2.c"
57 #endif
58
59 #ifdef CONFIG_KERNEL_LZMA
60 #include "../../../../lib/decompress_unlzma.c"
61 #endif
62
63 #ifdef CONFIG_KERNEL_XZ
64 #include "../../../../lib/decompress_unxz.c"
65 #endif
66
67 #ifdef CONFIG_KERNEL_LZO
68 #include "../../../../lib/decompress_unlzo.c"
69 #endif
70
71 #ifdef CONFIG_KERNEL_LZ4
72 #include "../../../../lib/decompress_unlz4.c"
73 #endif
74 /*
75  * NOTE: When adding a new decompressor, please update the analysis in
76  * ../header.S.
77  */
78
79 static void scroll(void)
80 {
81         int i;
82
83         memcpy(vidmem, vidmem + cols * 2, (lines - 1) * cols * 2);
84         for (i = (lines - 1) * cols * 2; i < lines * cols * 2; i += 2)
85                 vidmem[i] = ' ';
86 }
87
88 #define XMTRDY          0x20
89
90 #define TXR             0       /*  Transmit register (WRITE) */
91 #define LSR             5       /*  Line Status               */
92 static void serial_putchar(int ch)
93 {
94         unsigned timeout = 0xffff;
95
96         while ((inb(early_serial_base + LSR) & XMTRDY) == 0 && --timeout)
97                 cpu_relax();
98
99         outb(ch, early_serial_base + TXR);
100 }
101
102 void __putstr(const char *s)
103 {
104         int x, y, pos;
105         char c;
106
107         if (early_serial_base) {
108                 const char *str = s;
109                 while (*str) {
110                         if (*str == '\n')
111                                 serial_putchar('\r');
112                         serial_putchar(*str++);
113                 }
114         }
115
116         if (boot_params->screen_info.orig_video_mode == 0 &&
117             lines == 0 && cols == 0)
118                 return;
119
120         x = boot_params->screen_info.orig_x;
121         y = boot_params->screen_info.orig_y;
122
123         while ((c = *s++) != '\0') {
124                 if (c == '\n') {
125                         x = 0;
126                         if (++y >= lines) {
127                                 scroll();
128                                 y--;
129                         }
130                 } else {
131                         vidmem[(x + cols * y) * 2] = c;
132                         if (++x >= cols) {
133                                 x = 0;
134                                 if (++y >= lines) {
135                                         scroll();
136                                         y--;
137                                 }
138                         }
139                 }
140         }
141
142         boot_params->screen_info.orig_x = x;
143         boot_params->screen_info.orig_y = y;
144
145         pos = (x + cols * y) * 2;       /* Update cursor position */
146         outb(14, vidport);
147         outb(0xff & (pos >> 9), vidport+1);
148         outb(15, vidport);
149         outb(0xff & (pos >> 1), vidport+1);
150 }
151
152 void __puthex(unsigned long value)
153 {
154         char alpha[2] = "0";
155         int bits;
156
157         for (bits = sizeof(value) * 8 - 4; bits >= 0; bits -= 4) {
158                 unsigned long digit = (value >> bits) & 0xf;
159
160                 if (digit < 0xA)
161                         alpha[0] = '0' + digit;
162                 else
163                         alpha[0] = 'a' + (digit - 0xA);
164
165                 __putstr(alpha);
166         }
167 }
168
169 void warn(char *m)
170 {
171         error_putstr("\n\n");
172         error_putstr(m);
173         error_putstr("\n\n");
174 }
175
176 static void error(char *m)
177 {
178         warn(m);
179         error_putstr(" -- System halted");
180
181         while (1)
182                 asm("hlt");
183 }
184
185 #if CONFIG_X86_NEED_RELOCS
186 static void handle_relocations(void *output, unsigned long output_len)
187 {
188         int *reloc;
189         unsigned long delta, map, ptr;
190         unsigned long min_addr = (unsigned long)output;
191         unsigned long max_addr = min_addr + output_len;
192
193         /*
194          * Calculate the delta between where vmlinux was linked to load
195          * and where it was actually loaded.
196          */
197         delta = min_addr - LOAD_PHYSICAL_ADDR;
198         if (!delta) {
199                 debug_putstr("No relocation needed... ");
200                 return;
201         }
202         debug_putstr("Performing relocations... ");
203
204         /*
205          * The kernel contains a table of relocation addresses. Those
206          * addresses have the final load address of the kernel in virtual
207          * memory. We are currently working in the self map. So we need to
208          * create an adjustment for kernel memory addresses to the self map.
209          * This will involve subtracting out the base address of the kernel.
210          */
211         map = delta - __START_KERNEL_map;
212
213         /*
214          * Process relocations: 32 bit relocations first then 64 bit after.
215          * Three sets of binary relocations are added to the end of the kernel
216          * before compression. Each relocation table entry is the kernel
217          * address of the location which needs to be updated stored as a
218          * 32-bit value which is sign extended to 64 bits.
219          *
220          * Format is:
221          *
222          * kernel bits...
223          * 0 - zero terminator for 64 bit relocations
224          * 64 bit relocation repeated
225          * 0 - zero terminator for inverse 32 bit relocations
226          * 32 bit inverse relocation repeated
227          * 0 - zero terminator for 32 bit relocations
228          * 32 bit relocation repeated
229          *
230          * So we work backwards from the end of the decompressed image.
231          */
232         for (reloc = output + output_len - sizeof(*reloc); *reloc; reloc--) {
233                 int extended = *reloc;
234                 extended += map;
235
236                 ptr = (unsigned long)extended;
237                 if (ptr < min_addr || ptr > max_addr)
238                         error("32-bit relocation outside of kernel!\n");
239
240                 *(uint32_t *)ptr += delta;
241         }
242 #ifdef CONFIG_X86_64
243         while (*--reloc) {
244                 long extended = *reloc;
245                 extended += map;
246
247                 ptr = (unsigned long)extended;
248                 if (ptr < min_addr || ptr > max_addr)
249                         error("inverse 32-bit relocation outside of kernel!\n");
250
251                 *(int32_t *)ptr -= delta;
252         }
253         for (reloc--; *reloc; reloc--) {
254                 long extended = *reloc;
255                 extended += map;
256
257                 ptr = (unsigned long)extended;
258                 if (ptr < min_addr || ptr > max_addr)
259                         error("64-bit relocation outside of kernel!\n");
260
261                 *(uint64_t *)ptr += delta;
262         }
263 #endif
264 }
265 #else
266 static inline void handle_relocations(void *output, unsigned long output_len)
267 { }
268 #endif
269
270 static void parse_elf(void *output)
271 {
272 #ifdef CONFIG_X86_64
273         Elf64_Ehdr ehdr;
274         Elf64_Phdr *phdrs, *phdr;
275 #else
276         Elf32_Ehdr ehdr;
277         Elf32_Phdr *phdrs, *phdr;
278 #endif
279         void *dest;
280         int i;
281
282         memcpy(&ehdr, output, sizeof(ehdr));
283         if (ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
284            ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
285            ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
286            ehdr.e_ident[EI_MAG3] != ELFMAG3) {
287                 error("Kernel is not a valid ELF file");
288                 return;
289         }
290
291         debug_putstr("Parsing ELF... ");
292
293         phdrs = malloc(sizeof(*phdrs) * ehdr.e_phnum);
294         if (!phdrs)
295                 error("Failed to allocate space for phdrs");
296
297         memcpy(phdrs, output + ehdr.e_phoff, sizeof(*phdrs) * ehdr.e_phnum);
298
299         for (i = 0; i < ehdr.e_phnum; i++) {
300                 phdr = &phdrs[i];
301
302                 switch (phdr->p_type) {
303                 case PT_LOAD:
304 #ifdef CONFIG_RELOCATABLE
305                         dest = output;
306                         dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR);
307 #else
308                         dest = (void *)(phdr->p_paddr);
309 #endif
310                         memcpy(dest, output + phdr->p_offset, phdr->p_filesz);
311                         break;
312                 default: /* Ignore other PT_* */ break;
313                 }
314         }
315
316         free(phdrs);
317 }
318
319 asmlinkage __visible void *extract_kernel(void *rmode, memptr heap,
320                                   unsigned char *input_data,
321                                   unsigned long input_len,
322                                   unsigned char *output,
323                                   unsigned long output_len,
324                                   unsigned long run_size)
325 {
326         unsigned char *output_orig = output;
327
328         /* Retain x86 boot parameters pointer passed from startup_32/64. */
329         boot_params = rmode;
330
331         /* Clear flags intended for solely in-kernel use. */
332         boot_params->hdr.loadflags &= ~KASLR_FLAG;
333
334         sanitize_boot_params(boot_params);
335
336         if (boot_params->screen_info.orig_video_mode == 7) {
337                 vidmem = (char *) 0xb0000;
338                 vidport = 0x3b4;
339         } else {
340                 vidmem = (char *) 0xb8000;
341                 vidport = 0x3d4;
342         }
343
344         lines = boot_params->screen_info.orig_video_lines;
345         cols = boot_params->screen_info.orig_video_cols;
346
347         console_init();
348         debug_putstr("early console in extract_kernel\n");
349
350         free_mem_ptr     = heap;        /* Heap */
351         free_mem_end_ptr = heap + BOOT_HEAP_SIZE;
352
353         /* Report initial kernel position details. */
354         debug_putaddr(input_data);
355         debug_putaddr(input_len);
356         debug_putaddr(output);
357         debug_putaddr(output_len);
358         debug_putaddr(run_size);
359
360         /*
361          * The memory hole needed for the kernel is the larger of either
362          * the entire decompressed kernel plus relocation table, or the
363          * entire decompressed kernel plus .bss and .brk sections.
364          */
365         output = choose_random_location(input_data, input_len, output,
366                                         output_len > run_size ? output_len
367                                                               : run_size);
368
369         /* Validate memory location choices. */
370         if ((unsigned long)output & (MIN_KERNEL_ALIGN - 1))
371                 error("Destination address inappropriately aligned");
372 #ifdef CONFIG_X86_64
373         if (heap > 0x3fffffffffffUL)
374                 error("Destination address too large");
375 #else
376         if (heap > ((-__PAGE_OFFSET-(128<<20)-1) & 0x7fffffff))
377                 error("Destination address too large");
378 #endif
379 #ifndef CONFIG_RELOCATABLE
380         if ((unsigned long)output != LOAD_PHYSICAL_ADDR)
381                 error("Wrong destination address");
382 #endif
383
384         debug_putstr("\nDecompressing Linux... ");
385         __decompress(input_data, input_len, NULL, NULL, output, output_len,
386                         NULL, error);
387         parse_elf(output);
388         /*
389          * 32-bit always performs relocations. 64-bit relocations are only
390          * needed if kASLR has chosen a different load address.
391          */
392         if (!IS_ENABLED(CONFIG_X86_64) || output != output_orig)
393                 handle_relocations(output, output_len);
394         debug_putstr("done.\nBooting the kernel.\n");
395         return output;
396 }