libc, libutil: remove compat hacks
[minix.git] / commands / swifi / read_nlist.c
blob9c0335dc3883f77502d65215e2007e7e156bf2c4
1 /* ELF functions-only symbol table extractor by David van Moolenbroek.
2 * Replaces generic a.out version by Philip Homburg.
3 * Temporary solution until libc's nlist(3) becomes usable.
4 */
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <fcntl.h>
10 #include <errno.h>
11 #include <libelf.h>
12 #include <nlist.h>
14 static int get_syms(Elf *elf, Elf_Scn *scn, Elf32_Shdr *shdr,
15 struct nlist **nlistp)
17 Elf_Data *data;
18 Elf32_Sym *sym;
19 unsigned long nsyms;
20 struct nlist *nlp;
21 char *name;
22 size_t size;
23 int i;
25 if ((data = elf_getdata(scn, NULL)) == NULL) {
26 errno = ENOEXEC;
27 return -1;
30 nsyms = data->d_size / sizeof(Elf32_Sym);
32 size = sizeof(struct nlist) * nsyms;
33 if ((*nlistp = nlp = malloc(size)) == NULL)
34 return -1;
35 memset(nlp, 0, size);
37 sym = (Elf32_Sym *) data->d_buf;
38 for (i = 0; i < nsyms; i++, sym++, nlp++) {
39 nlp->n_value = sym->st_value;
41 /* The caller only cares about N_TEXT. Properly setting other
42 * types would involve crosschecking with section types.
44 switch (ELF32_ST_TYPE(sym->st_info)) {
45 case STT_FUNC: nlp->n_type = N_TEXT; break;
46 default: nlp->n_type = N_UNDF; break;
49 name = elf_strptr(elf, shdr->sh_link, (size_t) sym->st_name);
50 if ((nlp->n_name = strdup(name ? name : "")) == NULL) {
51 free(*nlistp);
52 return -1;
56 return nsyms;
59 int read_nlist(const char *filename, struct nlist **nlist_table)
61 /* Read in the symbol table of 'filename'. Return the resulting symbols
62 * as an array, with 'nlist_table' set to point to it, and the number
63 * of elements as the return value. The caller has no way to free the
64 * results. Return 0 if the executable contains no symbols. Upon error,
65 * return -1 and set errno to an appropriate value.
67 Elf *elf;
68 Elf_Scn *scn;
69 Elf32_Shdr *shdr;
70 int res, fd;
72 if (elf_version(EV_CURRENT) == EV_NONE) {
73 errno = EINVAL;
74 return -1;
77 if ((fd = open(filename, O_RDONLY)) < 0)
78 return -1;
80 elf = elf_begin(fd, ELF_C_READ, NULL);
81 if (elf == NULL) {
82 errno = ENOEXEC;
83 close(fd);
84 return -1;
87 scn = NULL;
88 res = 0;
89 while ((scn = elf_nextscn(elf, scn)) != NULL) {
90 if ((shdr = elf32_getshdr(scn)) == NULL)
91 continue;
93 if (shdr->sh_type != SHT_SYMTAB)
94 continue;
96 res = get_syms(elf, scn, shdr, nlist_table);
97 break;
100 elf_end(elf);
101 close(fd);
103 return res;