aboutsummaryrefslogtreecommitdiff
path: root/src/libmach/symelf.c
blob: dd1752eb2699bea065eede1eaf77556063567ef6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <u.h>
#include <libc.h>
#include <mach.h>
#include "elf.h"

static int
elfsyminit(Fhdr *fp)
{
	int i, onlyundef;
	Elf *elf;
	Symbol sym;
	ElfSym esym;
	ElfProg *p;

	elf = fp->elf;

	onlyundef = fp->nsym > 0;
	for(i=0; elfsym(elf, i, &esym) >= 0; i++){
		if(esym.name == nil)
			continue;
		if(onlyundef && esym.shndx != ElfSymShnNone)
			continue;
		if(esym.type != ElfSymTypeObject && esym.type != ElfSymTypeFunc)
			continue;
		if(strchr(esym.name, '@'))
			continue;
		memset(&sym, 0, sizeof sym);
		sym.name = esym.name;
		sym.loc.type = LADDR;
		sym.loc.addr = esym.value;
		if(esym.size){
			sym.hiloc.type = LADDR;
			sym.hiloc.addr = esym.value+esym.size;
		}
		sym.fhdr = fp;
		if(esym.type==ElfSymTypeObject){
			sym.class = CDATA;
			sym.type = 'D';
			if(&elf->sect[esym.shndx] == elf->bss)
				sym.type = 'B';
		}else if(esym.type==ElfSymTypeFunc){
			sym.class = CTEXT;
			sym.type = 'T';
		}
		if(esym.shndx == ElfSymShnNone)
			sym.type = 'U';
		if(esym.bind==ElfSymBindLocal)
			sym.type += 'a' - 'A';
		_addsym(fp, &sym);
	}

	for(i=0; i<elf->nprog; i++){
		p = &elf->prog[i];
		if(p->type != ElfProgDynamic)
			continue;
		elf->dynamic = p->vaddr;
		memset(&sym, 0, sizeof sym);
		sym.name = "_DYNAMIC";
		sym.loc = locaddr(p->vaddr);
		sym.hiloc = locaddr(p->vaddr+p->filesz);
		sym.type = 'D';
		sym.class = CDATA;
		_addsym(fp, &sym);
	}
	return 0;
}

int
elfsymlookup(Elf *elf, char *name, ulong *addr)
{
	int i;
	ElfSym esym;

	for(i=0; elfsym(elf, i, &esym) >= 0; i++){
		if(esym.name == nil)
			continue;
		if(strcmp(esym.name, name) == 0){
			*addr = esym.value;
			return 0;
		}
	}
	return -1;
}

int
symelf(Fhdr *fhdr)
{
	int ret;

	ret = -1;

	/* try dwarf */
	if(fhdr->dwarf){
		if(machdebug)
			fprint(2, "dwarf symbols...\n");
		if(symdwarf(fhdr) < 0)
			fprint(2, "initializing dwarf: %r");
		else
			ret = 0;
	}

	/* try stabs */
	if(fhdr->stabs.stabbase){
		if(machdebug)
			fprint(2, "stabs symbols...\n");
		if(symstabs(fhdr) < 0)
			fprint(2, "initializing stabs: %r");
		else
			ret = 0;
	}

	if(machdebug)
		fprint(2, "elf symbols...\n");

	if(elfsyminit(fhdr) < 0)
		fprint(2, "initializing elf: %r");
	else
		ret = 0;
	return ret;
}