eacc855ae08e7c8df1b460844b9f78a271ac9461
[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 static void error(char *x)
170 {
171         error_putstr("\n\n");
172         error_putstr(x);
173         error_putstr("\n\n -- System halted");
174
175         while (1)
176                 asm("hlt");
177 }
178
179 #if CONFIG_X86_NEED_RELOCS
180 static void handle_relocations(void *output, unsigned long output_len)
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 + output_len;
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         if (!delta) {
193                 debug_putstr("No relocation needed... ");
194                 return;
195         }
196         debug_putstr("Performing relocations... ");
197
198         /*
199          * The kernel contains a table of relocation addresses. Those
200          * addresses have the final load address of the kernel in virtual
201          * memory. We are currently working in the self map. So we need to
202          * create an adjustment for kernel memory addresses to the self map.
203          * This will involve subtracting out the base address of the kernel.
204          */
205         map = delta - __START_KERNEL_map;
206
207         /*
208          * Process relocations: 32 bit relocations first then 64 bit after.
209          * Three sets of binary relocations are added to the end of the kernel
210          * before compression. Each relocation table entry is the kernel
211          * address of the location which needs to be updated stored as a
212          * 32-bit value which is sign extended to 64 bits.
213          *
214          * Format is:
215          *
216          * kernel bits...
217          * 0 - zero terminator for 64 bit relocations
218          * 64 bit relocation repeated
219          * 0 - zero terminator for inverse 32 bit relocations
220          * 32 bit inverse relocation repeated
221          * 0 - zero terminator for 32 bit relocations
222          * 32 bit relocation repeated
223          *
224          * So we work backwards from the end of the decompressed image.
225          */
226         for (reloc = output + output_len - sizeof(*reloc); *reloc; reloc--) {
227                 int extended = *reloc;
228                 extended += map;
229
230                 ptr = (unsigned long)extended;
231                 if (ptr < min_addr || ptr > max_addr)
232                         error("32-bit relocation outside of kernel!\n");
233
234                 *(uint32_t *)ptr += delta;
235         }
236 #ifdef CONFIG_X86_64
237         while (*--reloc) {
238                 long extended = *reloc;
239                 extended += map;
240
241                 ptr = (unsigned long)extended;
242                 if (ptr < min_addr || ptr > max_addr)
243                         error("inverse 32-bit relocation outside of kernel!\n");
244
245                 *(int32_t *)ptr -= delta;
246         }
247         for (reloc--; *reloc; reloc--) {
248                 long extended = *reloc;
249                 extended += map;
250
251                 ptr = (unsigned long)extended;
252                 if (ptr < min_addr || ptr > max_addr)
253                         error("64-bit relocation outside of kernel!\n");
254
255                 *(uint64_t *)ptr += delta;
256         }
257 #endif
258 }
259 #else
260 static inline void handle_relocations(void *output, unsigned long output_len)
261 { }
262 #endif
263
264 static void parse_elf(void *output)
265 {
266 #ifdef CONFIG_X86_64
267         Elf64_Ehdr ehdr;
268         Elf64_Phdr *phdrs, *phdr;
269 #else
270         Elf32_Ehdr ehdr;
271         Elf32_Phdr *phdrs, *phdr;
272 #endif
273         void *dest;
274         int i;
275
276         memcpy(&ehdr, output, sizeof(ehdr));
277         if (ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
278            ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
279            ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
280            ehdr.e_ident[EI_MAG3] != ELFMAG3) {
281                 error("Kernel is not a valid ELF file");
282                 return;
283         }
284
285         debug_putstr("Parsing ELF... ");
286
287         phdrs = malloc(sizeof(*phdrs) * ehdr.e_phnum);
288         if (!phdrs)
289                 error("Failed to allocate space for phdrs");
290
291         memcpy(phdrs, output + ehdr.e_phoff, sizeof(*phdrs) * ehdr.e_phnum);
292
293         for (i = 0; i < ehdr.e_phnum; i++) {
294                 phdr = &phdrs[i];
295
296                 switch (phdr->p_type) {
297                 case PT_LOAD:
298 #ifdef CONFIG_RELOCATABLE
299                         dest = output;
300                         dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR);
301 #else
302                         dest = (void *)(phdr->p_paddr);
303 #endif
304                         memcpy(dest, output + phdr->p_offset, phdr->p_filesz);
305                         break;
306                 default: /* Ignore other PT_* */ break;
307                 }
308         }
309
310         free(phdrs);
311 }
312
313 asmlinkage __visible void *extract_kernel(void *rmode, memptr heap,
314                                   unsigned char *input_data,
315                                   unsigned long input_len,
316                                   unsigned char *output,
317                                   unsigned long output_len,
318                                   unsigned long run_size)
319 {
320         unsigned char *output_orig = output;
321
322         /* Retain x86 boot parameters pointer passed from startup_32/64. */
323         boot_params = rmode;
324
325         /* Clear flags intended for solely in-kernel use. */
326         boot_params->hdr.loadflags &= ~KASLR_FLAG;
327
328         sanitize_boot_params(boot_params);
329
330         if (boot_params->screen_info.orig_video_mode == 7) {
331                 vidmem = (char *) 0xb0000;
332                 vidport = 0x3b4;
333         } else {
334                 vidmem = (char *) 0xb8000;
335                 vidport = 0x3d4;
336         }
337
338         lines = boot_params->screen_info.orig_video_lines;
339         cols = boot_params->screen_info.orig_video_cols;
340
341         console_init();
342         debug_putstr("early console in extract_kernel\n");
343
344         free_mem_ptr     = heap;        /* Heap */
345         free_mem_end_ptr = heap + BOOT_HEAP_SIZE;
346
347         /* Report initial kernel position details. */
348         debug_putaddr(input_data);
349         debug_putaddr(input_len);
350         debug_putaddr(output);
351         debug_putaddr(output_len);
352         debug_putaddr(run_size);
353
354         /*
355          * The memory hole needed for the kernel is the larger of either
356          * the entire decompressed kernel plus relocation table, or the
357          * entire decompressed kernel plus .bss and .brk sections.
358          */
359         output = choose_random_location(input_data, input_len, output,
360                                         output_len > run_size ? output_len
361                                                               : run_size);
362
363         /* Validate memory location choices. */
364         if ((unsigned long)output & (MIN_KERNEL_ALIGN - 1))
365                 error("Destination address inappropriately aligned");
366 #ifdef CONFIG_X86_64
367         if (heap > 0x3fffffffffffUL)
368                 error("Destination address too large");
369 #else
370         if (heap > ((-__PAGE_OFFSET-(128<<20)-1) & 0x7fffffff))
371                 error("Destination address too large");
372 #endif
373 #ifndef CONFIG_RELOCATABLE
374         if ((unsigned long)output != LOAD_PHYSICAL_ADDR)
375                 error("Wrong destination address");
376 #endif
377
378         debug_putstr("\nDecompressing Linux... ");
379         __decompress(input_data, input_len, NULL, NULL, output, output_len,
380                         NULL, error);
381         parse_elf(output);
382         /*
383          * 32-bit always performs relocations. 64-bit relocations are only
384          * needed if kASLR has chosen a different load address.
385          */
386         if (!IS_ENABLED(CONFIG_X86_64) || output != output_orig)
387                 handle_relocations(output, output_len);
388         debug_putstr("done.\nBooting the kernel.\n");
389         return output;
390 }