misc.c 11 KB

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