#include "libelf.h"
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <nlist.h>
#include "syms.h"
#include "gelf.h"
#undef n_name
#define SPACE 100
#define ISELF (strncmp(magic_buf, ELFMAG, SELFMAG) == 0)
int
end_elf_job(int fd, Elf * elfdes)
{
(void) elf_end(elfdes);
(void) close(fd);
return (-1);
}
int
_elf_nlist(int fd, struct nlist * list)
{
Elf *elfdes;
GElf_Ehdr ehdr;
GElf_Shdr s_buf;
Elf_Data *symdata;
Elf_Scn *secidx = 0;
GElf_Sym sym;
unsigned strtab;
long count;
long ii;
if (elf_version(EV_CURRENT) == EV_NONE) {
(void) close(fd);
return (-1);
}
elfdes = elf_begin(fd, ELF_C_READ, (Elf *)0);
if (gelf_getehdr(elfdes, &ehdr) == 0)
return (end_elf_job(fd, elfdes));
while ((secidx = elf_nextscn(elfdes, secidx)) != 0) {
if ((gelf_getshdr(secidx, &s_buf)) == 0)
return (end_elf_job(fd, elfdes));
if (s_buf.sh_type != SHT_SYMTAB)
continue;
symdata = elf_getdata(secidx, (Elf_Data *)0);
if (symdata == 0)
return (end_elf_job(fd, elfdes));
if (symdata->d_size == 0)
break;
strtab = s_buf.sh_link;
count = symdata->d_size / s_buf.sh_entsize;
for (ii = 1; ii < count; ++ii) {
struct nlist *p;
register char *name;
(void) gelf_getsym(symdata, (int)ii, &sym);
name = elf_strptr(elfdes, strtab, (size_t)sym.st_name);
if (name == 0)
continue;
for (p = list; p->n_name && p->n_name[0]; ++p) {
if (strcmp(p->n_name, name))
continue;
p->n_value = (long)sym.st_value;
p->n_type = GELF_ST_TYPE(sym.st_info);
p->n_scnum = sym.st_shndx;
break;
}
}
break;
}
(void) elf_end(elfdes);
(void) close(fd);
return (0);
}
int
nlist(const char * name, struct nlist * list)
{
register struct nlist *p;
char magic_buf[EI_NIDENT];
int fd;
for (p = list; p->n_name && p->n_name[0]; p++) {
p->n_type = 0;
p->n_value = 0L;
p->n_scnum = 0;
p->n_sclass = 0;
p->n_numaux = 0;
}
if ((fd = open(name, 0)) < 0)
return (-1);
if (read(fd, magic_buf, EI_NIDENT) == -1) {
(void) close(fd);
return (-1);
}
if (lseek(fd, 0L, 0) == -1L) {
(void) close(fd);
return (-1);
}
#ifndef _LP64
if (ISELF && (magic_buf[EI_CLASS] == ELFCLASS32))
#else
if (ISELF)
#endif
return (_elf_nlist(fd, list));
else {
(void) close(fd);
return (-1);
}
}