1 #define _POSIX_C_SOURCE 200112L
16 void *libelf_map(char *path, size_t *fsize);
17 int libelf_iself(void *elf);
18 char *libelf_soname(void *elf);
19 int libelf_type(void *elf);
21 Elf64_Ehdr *libelf_header(void *elf) {
25 Elf64_Shdr *libelf_shdr(void *elf, int n) {
29 Elf64_Shdr *libelf_sht_strtab(void *elf) {
34 hdr = libelf_header(elf);
36 for (i = 0; i < hdr->e_shnum; i++) {
37 shdr = (Elf64_Shdr *)((char *)elf + hdr->e_shoff + i * hdr->e_shentsize);
38 if (shdr->sh_type == SHT_STRTAB && i == hdr->e_shstrndx) {
45 char *libelf_sectionname(Elf64_Shdr *section, Elf64_Shdr *strtab) {
46 return (char *)strtab + section->sh_name;
49 Elf64_Shdr *libelf_section_n(void *elf, int n) {
52 hdr = libelf_header(elf);
54 if (n > hdr->e_shnum) {
58 return (Elf64_Shdr *)((char *)elf + hdr->e_shoff + n * hdr->e_shentsize);
61 Elf64_Shdr *libelf_section(void *elf, int type) {
66 hdr = libelf_header(elf);
68 for (i = 0; i < hdr->e_shnum; i++) {
69 shdr = (Elf64_Shdr *)((char *)elf + hdr->e_shoff + i * hdr->e_shentsize);
70 if (shdr->sh_type == type) {
77 int libelf_type(void *elf) {
78 return ((Elf64_Ehdr *)elf)->e_type;
81 int libelf_iself(void *elf) {
84 if (hdr->e_ident[EI_MAG0] != ELFMAG0
85 || hdr->e_ident[EI_MAG1] != ELFMAG1
86 || hdr->e_ident[EI_MAG2] != ELFMAG2
87 || hdr->e_ident[EI_MAG3] != ELFMAG3
94 void *libelf_map(char *path, size_t *fsize) {
101 elffd = open(path, O_RDONLY);
106 if (fstat(elffd, &sbuf) == -1) {
110 /* not a regular file? */
111 if (!S_ISREG(sbuf.st_mode)) {
115 /* not at least the size of the elf header? */
116 if (sbuf.st_size < sizeof(Elf64_Ehdr)) {
121 elfbase = mmap(0, sbuf.st_size, PROT_READ,MAP_PRIVATE, elffd, 0);
127 if (!libelf_iself(elfbase)) {
128 munmap(elfbase, sbuf.st_size);
132 *fsize = sbuf.st_size;