xref: /titanic_41/usr/src/cmd/mdb/tools/findfp/common/findsym.c (revision 9e86db79b7d1bbc5f2f04e99954cbd5eae0e22bb)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <stdio.h>
30 #include <string.h>
31 #include <libelf.h>
32 #include <gelf.h>
33 
34 #include <findfp.h>
35 #include <util.h>
36 
37 int
38 findelfsym(Elf *elf, uintptr_t addr, char **symnamep, offset_t *offp)
39 {
40 	Elf_Data *symtab;
41 	GElf_Shdr shdr;
42 	Elf_Scn *scn;
43 	int symtabidx, nent, i;
44 
45 	if ((symtabidx = findelfsecidx(elf, ".symtab")) < 0)
46 		elfdie("failed to find .symtab\n");
47 
48 	if ((scn = elf_getscn(elf, symtabidx)) == NULL ||
49 	    gelf_getshdr(scn, &shdr) == NULL ||
50 	    (symtab = elf_getdata(scn, NULL)) == NULL)
51 		elfdie("failed to read .symtab");
52 
53 	nent = shdr.sh_size / shdr.sh_entsize;
54 
55 	for (i = 0; i < nent; i++) {
56 		GElf_Sym sym;
57 
58 		if (gelf_getsym(symtab, i, &sym) == NULL)
59 			elfdie("failed to get symbol at idx %d", i);
60 
61 		if ((GELF_ST_TYPE(sym.st_info) != STT_FUNC &&
62 		    GELF_ST_TYPE(sym.st_info) != STT_OBJECT) ||
63 		    sym.st_shndx == SHN_UNDEF)
64 			continue;
65 
66 		if (addr - sym.st_value < sym.st_size) {
67 			/* matched */
68 			if ((*symnamep = elf_strptr(elf, shdr.sh_link,
69 			    sym.st_name)) == NULL)
70 				elfdie("failed to get name for sym %d", i);
71 			*offp = addr - sym.st_value;
72 			return (1);
73 		}
74 	}
75 
76 	return (0);
77 }
78