* Parse an ELF file. */
| 883 | * Parse an ELF file. |
| 884 | */ |
| 885 | ELF *e9tool::parseELF(const char *filename, intptr_t base) |
| 886 | { |
| 887 | int fd = open(filename, O_RDONLY, 0); |
| 888 | if (fd < 0) |
| 889 | error("failed to open file \"%s\" for reading: %s", filename, |
| 890 | strerror(errno)); |
| 891 | |
| 892 | struct stat stat; |
| 893 | if (fstat(fd, &stat) != 0) |
| 894 | error("failed to get statistics for file \"%s\": %s", filename, |
| 895 | strerror(errno)); |
| 896 | |
| 897 | size_t size = (size_t)stat.st_size; |
| 898 | void *ptr = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); |
| 899 | if (ptr == MAP_FAILED) |
| 900 | error("failed to map file \"%s\" into memory: %s", filename, |
| 901 | strerror(errno)); |
| 902 | close(fd); |
| 903 | const uint8_t *data = (const uint8_t *)ptr; |
| 904 | |
| 905 | /* |
| 906 | * Basic ELF file parsing. |
| 907 | */ |
| 908 | if (size < sizeof(Elf64_Ehdr)) |
| 909 | error("failed to parse ELF EHDR from file \"%s\"; file is too small", |
| 910 | filename); |
| 911 | const Elf64_Ehdr *ehdr = (const Elf64_Ehdr *)data; |
| 912 | if (ehdr->e_ident[EI_MAG0] != ELFMAG0 || |
| 913 | ehdr->e_ident[EI_MAG1] != ELFMAG1 || |
| 914 | ehdr->e_ident[EI_MAG2] != ELFMAG2 || |
| 915 | ehdr->e_ident[EI_MAG3] != ELFMAG3) |
| 916 | error("failed to parse ELF file \"%s\"; invalid magic number", |
| 917 | filename); |
| 918 | if (ehdr->e_ident[EI_CLASS] != ELFCLASS64) |
| 919 | error("failed to parse ELF file \"%s\"; file is not 64bit", |
| 920 | filename); |
| 921 | if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB) |
| 922 | error("failed to parse ELF file \"%s\"; file is not little endian", |
| 923 | filename); |
| 924 | if (ehdr->e_ident[EI_VERSION] != EV_CURRENT) |
| 925 | error("failed to parse ELF file \"%s\"; invalid version", |
| 926 | filename); |
| 927 | if (ehdr->e_machine != EM_X86_64) |
| 928 | error("failed to parse ELF file \"%s\"; file is not x86_64", |
| 929 | filename); |
| 930 | if (ehdr->e_phoff < sizeof(Elf64_Ehdr) || ehdr->e_phoff >= size) |
| 931 | error("failed to parse ELF file \"%s\"; invalid program header " |
| 932 | "offset", filename); |
| 933 | if (ehdr->e_phnum > PN_XNUM) |
| 934 | error("failed to parse ELF file \"%s\"; too many program headers", |
| 935 | filename); |
| 936 | if (ehdr->e_phoff < sizeof(Elf64_Ehdr) || |
| 937 | ehdr->e_phoff + ehdr->e_phnum * sizeof(Elf64_Phdr) > size) |
| 938 | error("failed to parse ELF file \"%s\"; invalid program headers", |
| 939 | filename); |
| 940 | if (ehdr->e_shnum > SHN_LORESERVE) |
| 941 | error("failed to parse ELF file \"%s\"; too many section headers", |
| 942 | filename); |
nothing calls this directly
no test coverage detected