misc.c 12 KB

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