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