]> sbz's 6dev Repos - elfdbg/.git/blame - elf.c
Rewrite ELF parsing from scratch w/o dependency of elf(3) and gelf(3)
[elfdbg/.git] / elf.c
CommitLineData
1960d10e
SB
1#include <fcntl.h>
2#include <stdio.h>
3#include <stdlib.h>
4#include <string.h>
5#include <sys/mman.h>
6#include <unistd.h>
7
8#include "elf.h"
9
10
11Elf_Obj *
12elf_init(const char *filename)
13{
14 int fd;
15 struct stat sb;
16 Elf_Obj *e;
17
18 fd = open(filename, O_RDONLY);
19 e = (Elf_Obj *)malloc(sizeof(Elf_Obj));
20 e->fd = fd;
21 fstat(fd, &sb);
22 e->sb = sb;
23
24 e->mm = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
25 e->ehdr = (Elf_Ehdr *) e->mm;
26 e->ehdr_size = e->ehdr->e_ehsize;
27
28 e->shdr = (Elf_Shdr *) (e->mm + e->ehdr->e_shoff);
29 e->shdr_size = e->ehdr->e_shnum;
30
31 e->strtab = NULL;
32 e->strtab_size = 0;
33
34 return e;
35}
36
37Elf_Shdr *
38elf_strtab(Elf_Obj *e)
39{
40 Elf_Shdr *ptr;
41
42 ptr = &e->shdr[e->ehdr->e_shstrndx];
43 e->strtab = malloc(ptr->sh_size);
44 e->strtab_size = ptr->sh_size;
45
46 memcpy(e->strtab, (e->mm + ptr->sh_offset), ptr->sh_size);
47
48 return ptr;
49}
50
51int
52elf_destroy(Elf_Obj *e)
53{
54 if (e == NULL)
55 return 1;
56
57 munmap(e->mm, e->sb.st_size);
58 close(e->fd);
59 if (e->strtab != NULL)
60 free(e->strtab);
61 free(e);
62
63 return 0;
64}
65
66int
67elf_debug(Elf_Obj *e)
68{
69 int i, has_debug = 0;
70 char *debug_prefix = ".debug_";
71 char *section_name = NULL;
72
73 for (i=0; i < e->shdr_size; i++) {
74 section_name = &e->strtab[e->shdr[i].sh_name];
75 if (strnstr(section_name, debug_prefix, strlen(debug_prefix))) {
76 //printf("%s\n", section_name);
77 has_debug++;
78 }
79
80 }
81
82 return has_debug;
83}