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;
137 int main(int ac, char **av) {
147 while ((opt = getopt(ac, av, "e")) != -1) {
151 elf = libelf_map(av[optind], &fsize);
156 /* only dynamic files will have an soname */
157 if (libelf_type(elf) != ET_DYN && libelf_type(elf) != ET_EXEC) {
161 hdr = libelf_header(elf);
163 switch (hdr->e_ident[EI_CLASS]) {
172 /* check endian ness */
173 switch (hdr->e_ident[EI_DATA]) {
174 case ELFDATA2LSB: break;
175 case ELFDATA2MSB: break;
181 /* find program header table */
182 for (i = 0; i < hdr->e_phnum; i++) {
183 phdr = (Elf64_Phdr *)((char *)elf + hdr->e_phoff + i * hdr->e_phentsize);
184 if (phdr->p_type == PT_DYNAMIC) {
185 dsect = (Elf64_Shdr *)((char *)elf + phdr->p_offset);
188 dyn = (Elf64_Dyn *)((char *)elf + dsect->sh_offset);
192 dyn = (Elf64_Dyn *)dsect;
194 dsect = libelf_section(elf, SHT_DYNAMIC);
197 strsect = libelf_section_n(elf, dsect->sh_link);
198 strtab = (char *)elf + strsect->sh_offset;
200 while (dyn->d_tag != DT_NULL) {
201 if (dyn->d_tag == DT_NEEDED) {
203 printf("%s ", av[optind]);
205 printf("%s\n", strtab + dyn->d_un.d_val);