1 /* 2 * Copyright 2002-2008, Axel Dörfler, axeld@pinc-software.de. All rights reserved. 3 * Copyright 2012, Alex Smith, alex@alex-smith.me.uk. 4 * Distributed under the terms of the MIT License. 5 */ 6 7 8 #include "elf.h" 9 10 #include <boot/arch.h> 11 #include <boot/platform.h> 12 #include <boot/stage2.h> 13 #include <driver_settings.h> 14 #include <elf_private.h> 15 #include <kernel.h> 16 #include <SupportDefs.h> 17 18 #include <errno.h> 19 #include <unistd.h> 20 #include <string.h> 21 #include <stdlib.h> 22 23 //#define TRACE_ELF 24 #ifdef TRACE_ELF 25 # define TRACE(x) dprintf x 26 #else 27 # define TRACE(x) ; 28 #endif 29 30 31 static bool sLoadElfSymbols = true; 32 33 34 // #pragma mark - Generic ELF loader 35 36 37 template<typename Class> 38 class ELFLoader { 39 private: 40 typedef typename Class::ImageType ImageType; 41 typedef typename Class::RegionType RegionType; 42 typedef typename Class::AddrType AddrType; 43 typedef typename Class::EhdrType EhdrType; 44 typedef typename Class::PhdrType PhdrType; 45 typedef typename Class::ShdrType ShdrType; 46 typedef typename Class::DynType DynType; 47 typedef typename Class::SymType SymType; 48 typedef typename Class::RelType RelType; 49 typedef typename Class::RelaType RelaType; 50 51 public: 52 static status_t Create(int fd, preloaded_image** _image); 53 static status_t Load(int fd, preloaded_image* image); 54 static status_t Relocate(preloaded_image* image); 55 static status_t Resolve(ImageType* image, SymType* symbol, 56 AddrType* symbolAddress); 57 58 private: 59 static status_t _LoadSymbolTable(int fd, ImageType* image); 60 static status_t _ParseDynamicSection(ImageType* image); 61 }; 62 63 64 #ifdef BOOT_SUPPORT_ELF32 65 struct ELF32Class { 66 static const uint8 kIdentClass = ELFCLASS32; 67 68 typedef preloaded_elf32_image ImageType; 69 typedef elf32_region RegionType; 70 typedef Elf32_Addr AddrType; 71 typedef Elf32_Ehdr EhdrType; 72 typedef Elf32_Phdr PhdrType; 73 typedef Elf32_Shdr ShdrType; 74 typedef Elf32_Dyn DynType; 75 typedef Elf32_Sym SymType; 76 typedef Elf32_Rel RelType; 77 typedef Elf32_Rela RelaType; 78 79 static inline status_t 80 AllocateRegion(AddrType* _address, AddrType size, uint8 protection, 81 void** _mappedAddress) 82 { 83 status_t status = platform_allocate_region((void**)_address, size, 84 protection, false); 85 if (status != B_OK) 86 return status; 87 88 *_mappedAddress = (void*)*_address; 89 return B_OK; 90 } 91 92 static inline void* 93 Map(AddrType address) 94 { 95 return (void*)address; 96 } 97 }; 98 99 typedef ELFLoader<ELF32Class> ELF32Loader; 100 #endif 101 102 103 #ifdef BOOT_SUPPORT_ELF64 104 struct ELF64Class { 105 static const uint8 kIdentClass = ELFCLASS64; 106 107 typedef preloaded_elf64_image ImageType; 108 typedef elf64_region RegionType; 109 typedef Elf64_Addr AddrType; 110 typedef Elf64_Ehdr EhdrType; 111 typedef Elf64_Phdr PhdrType; 112 typedef Elf64_Shdr ShdrType; 113 typedef Elf64_Dyn DynType; 114 typedef Elf64_Sym SymType; 115 typedef Elf64_Rel RelType; 116 typedef Elf64_Rela RelaType; 117 118 static inline status_t 119 AllocateRegion(AddrType* _address, AddrType size, uint8 protection, 120 void **_mappedAddress) 121 { 122 #if defined(_BOOT_PLATFORM_BIOS) 123 // Assume the real 64-bit base address is KERNEL_LOAD_BASE_64_BIT and 124 // the mappings in the loader address space are at KERNEL_LOAD_BASE. 125 126 void* address = (void*)(addr_t)(*_address & 0xffffffff); 127 #else 128 void* address = (void*)*_address; 129 #endif 130 131 status_t status = platform_allocate_region(&address, size, protection, 132 false); 133 if (status != B_OK) 134 return status; 135 136 *_mappedAddress = address; 137 #if defined(_BOOT_PLATFORM_BIOS) 138 *_address = (AddrType)(addr_t)address + KERNEL_LOAD_BASE_64_BIT 139 - KERNEL_LOAD_BASE; 140 #else 141 platform_bootloader_address_to_kernel_address(address, _address); 142 #endif 143 return B_OK; 144 } 145 146 static inline void* 147 Map(AddrType address) 148 { 149 #ifdef _BOOT_PLATFORM_BIOS 150 return (void*)(addr_t)(address - KERNEL_LOAD_BASE_64_BIT 151 + KERNEL_LOAD_BASE); 152 #else 153 void *result; 154 if (platform_kernel_address_to_bootloader_address(address, &result) != B_OK) { 155 panic("Couldn't convert address %#" PRIx64, address); 156 } 157 return result; 158 #endif 159 } 160 }; 161 162 typedef ELFLoader<ELF64Class> ELF64Loader; 163 #endif 164 165 166 template<typename Class> 167 /*static*/ status_t 168 ELFLoader<Class>::Create(int fd, preloaded_image** _image) 169 { 170 ImageType* image = (ImageType*)kernel_args_malloc(sizeof(ImageType)); 171 if (image == NULL) 172 return B_NO_MEMORY; 173 174 ssize_t length = read_pos(fd, 0, &image->elf_header, sizeof(EhdrType)); 175 if (length < (ssize_t)sizeof(EhdrType)) { 176 kernel_args_free(image); 177 return B_BAD_TYPE; 178 } 179 180 const EhdrType& elfHeader = image->elf_header; 181 182 if (memcmp(elfHeader.e_ident, ELFMAG, 4) != 0 183 || elfHeader.e_ident[4] != Class::kIdentClass 184 || elfHeader.e_phoff == 0 185 || !elfHeader.IsHostEndian() 186 || elfHeader.e_phentsize != sizeof(PhdrType)) { 187 kernel_args_free(image); 188 return B_BAD_TYPE; 189 } 190 191 image->elf_class = elfHeader.e_ident[EI_CLASS]; 192 193 *_image = image; 194 return B_OK; 195 } 196 197 198 template<typename Class> 199 /*static*/ status_t 200 ELFLoader<Class>::Load(int fd, preloaded_image* _image) 201 { 202 size_t totalSize; 203 ssize_t length; 204 status_t status; 205 void* mappedRegion = NULL; 206 207 ImageType* image = static_cast<ImageType*>(_image); 208 const EhdrType& elfHeader = image->elf_header; 209 210 ssize_t size = elfHeader.e_phnum * elfHeader.e_phentsize; 211 PhdrType* programHeaders = (PhdrType*)malloc(size); 212 if (programHeaders == NULL) { 213 dprintf("error allocating space for program headers\n"); 214 status = B_NO_MEMORY; 215 goto error1; 216 } 217 218 length = read_pos(fd, elfHeader.e_phoff, programHeaders, size); 219 if (length < size) { 220 TRACE(("error reading in program headers\n")); 221 status = B_ERROR; 222 goto error1; 223 } 224 225 // create an area large enough to hold the image 226 227 image->data_region.size = 0; 228 image->text_region.size = 0; 229 230 for (int32 i = 0; i < elfHeader.e_phnum; i++) { 231 PhdrType& header = programHeaders[i]; 232 233 switch (header.p_type) { 234 case PT_LOAD: 235 break; 236 case PT_DYNAMIC: 237 image->dynamic_section.start = header.p_vaddr; 238 image->dynamic_section.size = header.p_memsz; 239 continue; 240 case PT_INTERP: 241 case PT_PHDR: 242 case PT_ARM_UNWIND: 243 // known but unused type 244 continue; 245 default: 246 dprintf("unhandled pheader type 0x%" B_PRIx32 "\n", header.p_type); 247 continue; 248 } 249 250 RegionType* region; 251 if (header.IsReadWrite()) { 252 if (image->data_region.size != 0) { 253 dprintf("elf: rw already handled!\n"); 254 continue; 255 } 256 region = &image->data_region; 257 } else if (header.IsExecutable()) { 258 if (image->text_region.size != 0) { 259 dprintf("elf: ro already handled!\n"); 260 continue; 261 } 262 region = &image->text_region; 263 } else 264 continue; 265 266 region->start = ROUNDDOWN(header.p_vaddr, B_PAGE_SIZE); 267 region->size = ROUNDUP(header.p_memsz + (header.p_vaddr % B_PAGE_SIZE), 268 B_PAGE_SIZE); 269 region->delta = -region->start; 270 271 TRACE(("segment %" B_PRId32 ": start = 0x%" B_PRIx64 ", size = %" 272 B_PRIu64 ", delta = %" B_PRIx64 "\n", i, (uint64)region->start, 273 (uint64)region->size, (int64)(AddrType)region->delta)); 274 } 275 276 277 // found both, text and data? 278 if (image->data_region.size == 0 || image->text_region.size == 0) { 279 dprintf("Couldn't find both text and data segment!\n"); 280 status = B_BAD_DATA; 281 goto error1; 282 } 283 284 // get the segment order 285 RegionType* firstRegion; 286 RegionType* secondRegion; 287 if (image->text_region.start < image->data_region.start) { 288 firstRegion = &image->text_region; 289 secondRegion = &image->data_region; 290 } else { 291 firstRegion = &image->data_region; 292 secondRegion = &image->text_region; 293 } 294 295 // The kernel and the modules are relocatable, thus AllocateRegion() 296 // can automatically allocate an address, but shall prefer the specified 297 // base address. 298 totalSize = secondRegion->start + secondRegion->size - firstRegion->start; 299 { 300 AddrType address = firstRegion->start; 301 if (Class::AllocateRegion(&address, totalSize, 302 B_READ_AREA | B_WRITE_AREA, &mappedRegion) != B_OK) { 303 status = B_NO_MEMORY; 304 goto error1; 305 } 306 firstRegion->start = address; 307 } 308 309 // initialize the region pointers to the allocated region 310 secondRegion->start += firstRegion->start + firstRegion->delta; 311 312 image->data_region.delta += image->data_region.start; 313 image->text_region.delta += image->text_region.start; 314 315 TRACE(("text: start 0x%" B_PRIx64 ", size 0x%" B_PRIx64 ", delta 0x%" 316 B_PRIx64 "\n", (uint64)image->text_region.start, 317 (uint64)image->text_region.size, 318 (int64)(AddrType)image->text_region.delta)); 319 TRACE(("data: start 0x%" B_PRIx64 ", size 0x%" B_PRIx64 ", delta 0x%" 320 B_PRIx64 "\n", (uint64)image->data_region.start, 321 (uint64)image->data_region.size, 322 (int64)(AddrType)image->data_region.delta)); 323 324 // load program data 325 326 for (int32 i = 0; i < elfHeader.e_phnum; i++) { 327 PhdrType& header = programHeaders[i]; 328 329 if (header.p_type != PT_LOAD) 330 continue; 331 332 RegionType* region; 333 if (header.IsReadWrite()) 334 region = &image->data_region; 335 else if (header.IsExecutable()) 336 region = &image->text_region; 337 else 338 continue; 339 340 TRACE(("load segment %" PRId32 " (%" PRIu64 " bytes) mapped at %p...\n", 341 i, (uint64)header.p_filesz, Class::Map(region->start))); 342 343 length = read_pos(fd, header.p_offset, 344 Class::Map(region->start + (header.p_vaddr % B_PAGE_SIZE)), 345 header.p_filesz); 346 if (length < (ssize_t)header.p_filesz) { 347 status = B_BAD_DATA; 348 dprintf("error reading in seg %" B_PRId32 "\n", i); 349 goto error2; 350 } 351 352 // Clear anything above the file size (that may also contain the BSS 353 // area) 354 355 uint32 offset = (header.p_vaddr % B_PAGE_SIZE) + header.p_filesz; 356 if (offset < region->size) 357 memset(Class::Map(region->start + offset), 0, region->size - offset); 358 } 359 360 // offset dynamic section, and program entry addresses by the delta of the 361 // regions 362 image->dynamic_section.start += image->text_region.delta; 363 image->elf_header.e_entry += image->text_region.delta; 364 365 image->num_debug_symbols = 0; 366 image->debug_symbols = NULL; 367 image->debug_string_table = NULL; 368 369 if (sLoadElfSymbols) 370 _LoadSymbolTable(fd, image); 371 372 free(programHeaders); 373 374 return B_OK; 375 376 error2: 377 if (mappedRegion != NULL) 378 platform_free_region(mappedRegion, totalSize); 379 error1: 380 free(programHeaders); 381 kernel_args_free(image); 382 383 return status; 384 } 385 386 387 template<typename Class> 388 /*static*/ status_t 389 ELFLoader<Class>::Relocate(preloaded_image* _image) 390 { 391 ImageType* image = static_cast<ImageType*>(_image); 392 393 status_t status = _ParseDynamicSection(image); 394 if (status != B_OK) 395 return status; 396 397 // deal with the rels first 398 if (image->rel) { 399 TRACE(("total %i relocs\n", 400 (int)image->rel_len / (int)sizeof(RelType))); 401 402 status = boot_arch_elf_relocate_rel(image, image->rel, image->rel_len); 403 if (status != B_OK) 404 return status; 405 } 406 407 if (image->pltrel) { 408 RelType* pltrel = image->pltrel; 409 if (image->pltrel_type == DT_REL) { 410 TRACE(("total %i plt-relocs\n", 411 (int)image->pltrel_len / (int)sizeof(RelType))); 412 413 status = boot_arch_elf_relocate_rel(image, pltrel, 414 image->pltrel_len); 415 } else { 416 TRACE(("total %i plt-relocs\n", 417 (int)image->pltrel_len / (int)sizeof(RelaType))); 418 419 status = boot_arch_elf_relocate_rela(image, (RelaType*)pltrel, 420 image->pltrel_len); 421 } 422 if (status != B_OK) 423 return status; 424 } 425 426 if (image->rela) { 427 TRACE(("total %i rela relocs\n", 428 (int)image->rela_len / (int)sizeof(RelaType))); 429 status = boot_arch_elf_relocate_rela(image, image->rela, 430 image->rela_len); 431 if (status != B_OK) 432 return status; 433 } 434 435 return B_OK; 436 } 437 438 template<typename Class> 439 /*static*/ status_t 440 ELFLoader<Class>::Resolve(ImageType* image, SymType* symbol, 441 AddrType* symbolAddress) 442 { 443 switch (symbol->st_shndx) { 444 case SHN_UNDEF: 445 // Since we do that only for the kernel, there shouldn't be 446 // undefined symbols. 447 TRACE(("elf_resolve_symbol: undefined symbol\n")); 448 return B_MISSING_SYMBOL; 449 case SHN_ABS: 450 *symbolAddress = symbol->st_value; 451 return B_NO_ERROR; 452 case SHN_COMMON: 453 // ToDo: finish this 454 TRACE(("elf_resolve_symbol: COMMON symbol, finish me!\n")); 455 return B_ERROR; 456 default: 457 // standard symbol 458 *symbolAddress = symbol->st_value + image->text_region.delta; 459 return B_OK; 460 } 461 } 462 463 464 template<typename Class> 465 /*static*/ status_t 466 ELFLoader<Class>::_LoadSymbolTable(int fd, ImageType* image) 467 { 468 const EhdrType& elfHeader = image->elf_header; 469 SymType* symbolTable = NULL; 470 ShdrType* stringHeader = NULL; 471 uint32 numSymbols = 0; 472 char* stringTable; 473 status_t status; 474 475 // get section headers 476 477 ssize_t size = elfHeader.e_shnum * elfHeader.e_shentsize; 478 ShdrType* sectionHeaders = (ShdrType*)malloc(size); 479 if (sectionHeaders == NULL) { 480 dprintf("error allocating space for section headers\n"); 481 return B_NO_MEMORY; 482 } 483 484 ssize_t length = read_pos(fd, elfHeader.e_shoff, sectionHeaders, size); 485 if (length < size) { 486 TRACE(("error reading in program headers\n")); 487 status = B_ERROR; 488 goto error1; 489 } 490 491 // find symbol table in section headers 492 493 for (int32 i = 0; i < elfHeader.e_shnum; i++) { 494 if (sectionHeaders[i].sh_type == SHT_SYMTAB) { 495 stringHeader = §ionHeaders[sectionHeaders[i].sh_link]; 496 497 if (stringHeader->sh_type != SHT_STRTAB) { 498 TRACE(("doesn't link to string table\n")); 499 status = B_BAD_DATA; 500 goto error1; 501 } 502 503 // read in symbol table 504 size = sectionHeaders[i].sh_size; 505 symbolTable = (SymType*)kernel_args_malloc(size); 506 if (symbolTable == NULL) { 507 status = B_NO_MEMORY; 508 goto error1; 509 } 510 511 length = read_pos(fd, sectionHeaders[i].sh_offset, symbolTable, 512 size); 513 if (length < size) { 514 TRACE(("error reading in symbol table\n")); 515 status = B_ERROR; 516 goto error1; 517 } 518 519 numSymbols = size / sizeof(SymType); 520 break; 521 } 522 } 523 524 if (symbolTable == NULL) { 525 TRACE(("no symbol table\n")); 526 status = B_BAD_VALUE; 527 goto error1; 528 } 529 530 // read in string table 531 532 size = stringHeader->sh_size; 533 stringTable = (char*)kernel_args_malloc(size); 534 if (stringTable == NULL) { 535 status = B_NO_MEMORY; 536 goto error2; 537 } 538 539 length = read_pos(fd, stringHeader->sh_offset, stringTable, size); 540 if (length < size) { 541 TRACE(("error reading in string table\n")); 542 status = B_ERROR; 543 goto error3; 544 } 545 546 TRACE(("loaded %" B_PRIu32 " debug symbols\n", numSymbols)); 547 548 // insert tables into image 549 image->debug_symbols = symbolTable; 550 image->num_debug_symbols = numSymbols; 551 image->debug_string_table = stringTable; 552 image->debug_string_table_size = size; 553 554 free(sectionHeaders); 555 return B_OK; 556 557 error3: 558 kernel_args_free(stringTable); 559 error2: 560 kernel_args_free(symbolTable); 561 error1: 562 free(sectionHeaders); 563 564 return status; 565 } 566 567 568 template<typename Class> 569 /*static*/ status_t 570 ELFLoader<Class>::_ParseDynamicSection(ImageType* image) 571 { 572 image->syms = 0; 573 image->rel = 0; 574 image->rel_len = 0; 575 image->rela = 0; 576 image->rela_len = 0; 577 image->pltrel = 0; 578 image->pltrel_len = 0; 579 image->pltrel_type = 0; 580 581 if(image->dynamic_section.start == 0) 582 return B_ERROR; 583 584 DynType* d = (DynType*)Class::Map(image->dynamic_section.start); 585 586 for (int i = 0; d[i].d_tag != DT_NULL; i++) { 587 switch (d[i].d_tag) { 588 case DT_HASH: 589 case DT_STRTAB: 590 break; 591 case DT_SYMTAB: 592 image->syms = (SymType*)Class::Map(d[i].d_un.d_ptr 593 + image->text_region.delta); 594 break; 595 case DT_REL: 596 image->rel = (RelType*)Class::Map(d[i].d_un.d_ptr 597 + image->text_region.delta); 598 break; 599 case DT_RELSZ: 600 image->rel_len = d[i].d_un.d_val; 601 break; 602 case DT_RELA: 603 image->rela = (RelaType*)Class::Map(d[i].d_un.d_ptr 604 + image->text_region.delta); 605 break; 606 case DT_RELASZ: 607 image->rela_len = d[i].d_un.d_val; 608 break; 609 case DT_JMPREL: 610 image->pltrel = (RelType*)Class::Map(d[i].d_un.d_ptr 611 + image->text_region.delta); 612 break; 613 case DT_PLTRELSZ: 614 image->pltrel_len = d[i].d_un.d_val; 615 break; 616 case DT_PLTREL: 617 image->pltrel_type = d[i].d_un.d_val; 618 break; 619 620 default: 621 continue; 622 } 623 } 624 625 // lets make sure we found all the required sections 626 if (image->syms == NULL) 627 return B_ERROR; 628 629 return B_OK; 630 } 631 632 633 // #pragma mark - 634 635 636 void 637 elf_init() 638 { 639 void* settings = load_driver_settings("kernel"); 640 if (settings == NULL) 641 return; 642 643 sLoadElfSymbols = get_driver_boolean_parameter(settings, "load_symbols", 644 false, false); 645 646 unload_driver_settings(settings); 647 } 648 649 650 status_t 651 elf_load_image(int fd, preloaded_image** _image) 652 { 653 status_t status = B_ERROR; 654 655 TRACE(("elf_load_image(fd = %d, _image = %p)\n", fd, _image)); 656 657 #if BOOT_SUPPORT_ELF64 658 if (gKernelArgs.kernel_image == NULL 659 || gKernelArgs.kernel_image->elf_class == ELFCLASS64) { 660 status = ELF64Loader::Create(fd, _image); 661 if (status == B_OK) 662 return ELF64Loader::Load(fd, *_image); 663 else if (status != B_BAD_TYPE) 664 return status; 665 } 666 #endif 667 #if BOOT_SUPPORT_ELF32 668 if (gKernelArgs.kernel_image == NULL 669 || gKernelArgs.kernel_image->elf_class == ELFCLASS32) { 670 status = ELF32Loader::Create(fd, _image); 671 if (status == B_OK) 672 return ELF32Loader::Load(fd, *_image); 673 } 674 #endif 675 676 return status; 677 } 678 679 680 status_t 681 elf_load_image(Directory* directory, const char* path) 682 { 683 preloaded_image* image; 684 685 TRACE(("elf_load_image(directory = %p, \"%s\")\n", directory, path)); 686 687 int fd = open_from(directory, path, O_RDONLY); 688 if (fd < 0) 689 return fd; 690 691 // check if this file has already been loaded 692 693 struct stat stat; 694 if (fstat(fd, &stat) < 0) 695 return errno; 696 697 image = gKernelArgs.preloaded_images; 698 for (; image != NULL; image = image->next) { 699 if (image->inode == stat.st_ino) { 700 // file has already been loaded, no need to load it twice! 701 close(fd); 702 return B_OK; 703 } 704 } 705 706 // we still need to load it, so do it 707 708 status_t status = elf_load_image(fd, &image); 709 if (status == B_OK) { 710 image->name = kernel_args_strdup(path); 711 image->inode = stat.st_ino; 712 713 // insert to kernel args 714 image->next = gKernelArgs.preloaded_images; 715 gKernelArgs.preloaded_images = image; 716 } else 717 kernel_args_free(image); 718 719 close(fd); 720 return status; 721 } 722 723 724 status_t 725 elf_relocate_image(preloaded_image* image) 726 { 727 #ifdef BOOT_SUPPORT_ELF64 728 if (image->elf_class == ELFCLASS64) 729 return ELF64Loader::Relocate(image); 730 else 731 #endif 732 #ifdef BOOT_SUPPORT_ELF32 733 return ELF32Loader::Relocate(image); 734 #else 735 return B_ERROR; 736 #endif 737 } 738 739 740 #ifdef BOOT_SUPPORT_ELF32 741 status_t 742 boot_elf_resolve_symbol(preloaded_elf32_image* image, Elf32_Sym* symbol, 743 Elf32_Addr* symbolAddress) 744 { 745 return ELF32Loader::Resolve(image, symbol, symbolAddress); 746 } 747 #endif 748 749 750 #ifdef BOOT_SUPPORT_ELF64 751 status_t 752 boot_elf_resolve_symbol(preloaded_elf64_image* image, Elf64_Sym* symbol, 753 Elf64_Addr* symbolAddress) 754 { 755 return ELF64Loader::Resolve(image, symbol, symbolAddress); 756 } 757 758 void 759 boot_elf64_set_relocation(Elf64_Addr resolveAddress, Elf64_Addr finalAddress) 760 { 761 Elf64_Addr* dest = (Elf64_Addr*)ELF64Class::Map(resolveAddress); 762 *dest = finalAddress; 763 } 764 #endif 765