Deleted Added
sdiff udiff text old ( 76224 ) new ( 91017 )
full compact
1#ifndef lint
2static const char rcsid[] =
3 "$FreeBSD: head/usr.bin/gprof/elf.c 76224 2001-05-02 23:56:21Z obrien $";
4#endif /* not lint */
5
6#include <sys/types.h>
7#include <sys/mman.h>
8#include <sys/stat.h>
9#include <machine/elf.h>
10
11#include <err.h>
12#include <fcntl.h>
13#include <string.h>
14#include <unistd.h>
15
16#include "gprof.h"
17
18static bool wantsym(const Elf_Sym *, const char *);
19
20/* Things which get -E excluded by default. */
21static char *excludes[] = { ".mcount", "_mcleanup", NULL };
22
23int
24elf_getnfile(const char *filename, char ***defaultEs)
25{
26 int fd;
27 Elf_Ehdr h;
28 struct stat s;
29 void *mapbase;
30 const char *base;
31 const Elf_Shdr *shdrs;
32 const Elf_Shdr *sh_symtab;
33 const Elf_Shdr *sh_strtab;
34 const char *strtab;
35 const Elf_Sym *symtab;
36 int symtabct;
37 int i;
38
39 if ((fd = open(filename, O_RDONLY)) == -1)
40 err(1, "%s", filename);
41 if (read(fd, &h, sizeof h) != sizeof h || !IS_ELF(h)) {
42 close(fd);
43 return -1;
44 }
45 if (fstat(fd, &s) == -1)
46 err(1, "Cannot fstat %s", filename);
47 if ((mapbase = mmap(0, s.st_size, PROT_READ, MAP_SHARED, fd, 0)) ==
48 MAP_FAILED)
49 err(1, "Cannot mmap %s", filename);
50 close(fd);
51
52 base = (const char *)mapbase;
53 shdrs = (const Elf_Shdr *)(base + h.e_shoff);
54
55 /* Find the symbol table and associated string table section. */
56 for (i = 1; i < h.e_shnum; i++)
57 if (shdrs[i].sh_type == SHT_SYMTAB)
58 break;
59 if (i == h.e_shnum)
60 errx(1, "%s has no symbol table", filename);
61 sh_symtab = &shdrs[i];
62 sh_strtab = &shdrs[sh_symtab->sh_link];
63
64 symtab = (const Elf_Sym *)(base + sh_symtab->sh_offset);
65 symtabct = sh_symtab->sh_size / sh_symtab->sh_entsize;
66 strtab = (const char *)(base + sh_strtab->sh_offset);
67
68 /* Count the symbols that we're interested in. */
69 nname = 0;
70 for (i = 1; i < symtabct; i++)
71 if (wantsym(&symtab[i], strtab))
72 nname++;
73
74 /* Allocate memory for them, plus a terminating entry. */
75 if ((nl = (nltype *)calloc(nname + 1, sizeof(nltype))) == NULL)
76 errx(1, "Insufficient memory for symbol table");
77
78 /* Read them in. */
79 npe = nl;
80 for (i = 1; i < symtabct; i++) {
81 const Elf_Sym *sym = &symtab[i];
82
83 if (wantsym(sym, strtab)) {
84 npe->value = sym->st_value;
85 npe->name = strtab + sym->st_name;
86 npe++;
87 }
88 }
89 npe->value = -1;
90
91 *defaultEs = excludes;
92 return 0;
93}
94
95static bool
96wantsym(const Elf_Sym *sym, const char *strtab)
97{
98 int type;
99 int bind;
100
101 type = ELF_ST_TYPE(sym->st_info);
102 bind = ELF_ST_BIND(sym->st_info);
103
104 if (type != STT_FUNC ||
105 (aflag && bind == STB_LOCAL) ||
106 (uflag && strchr(strtab + sym->st_name, '.') != NULL))
107 return 0;
108
109 return 1;
110}