1// Copyright 2012 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5//go:build linux && (386 || amd64 || arm || arm64 || loong64 || mips64 || mips64le || ppc64 || ppc64le || riscv64 || s390x)
6
7package runtime
8
9import "unsafe"
10
11// Look up symbols in the Linux vDSO.
12
13// This code was originally based on the sample Linux vDSO parser at
14// https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/vDSO/parse_vdso.c
15
16// This implements the ELF dynamic linking spec at
17// http://sco.com/developers/gabi/latest/ch5.dynamic.html
18
19// The version section is documented at
20// https://refspecs.linuxfoundation.org/LSB_3.2.0/LSB-Core-generic/LSB-Core-generic/symversion.html
21
22const (
23	_AT_SYSINFO_EHDR = 33
24
25	_PT_LOAD    = 1 /* Loadable program segment */
26	_PT_DYNAMIC = 2 /* Dynamic linking information */
27
28	_DT_NULL     = 0          /* Marks end of dynamic section */
29	_DT_HASH     = 4          /* Dynamic symbol hash table */
30	_DT_STRTAB   = 5          /* Address of string table */
31	_DT_SYMTAB   = 6          /* Address of symbol table */
32	_DT_GNU_HASH = 0x6ffffef5 /* GNU-style dynamic symbol hash table */
33	_DT_VERSYM   = 0x6ffffff0
34	_DT_VERDEF   = 0x6ffffffc
35
36	_VER_FLG_BASE = 0x1 /* Version definition of file itself */
37
38	_SHN_UNDEF = 0 /* Undefined section */
39
40	_SHT_DYNSYM = 11 /* Dynamic linker symbol table */
41
42	_STT_FUNC = 2 /* Symbol is a code object */
43
44	_STT_NOTYPE = 0 /* Symbol type is not specified */
45
46	_STB_GLOBAL = 1 /* Global symbol */
47	_STB_WEAK   = 2 /* Weak symbol */
48
49	_EI_NIDENT = 16
50
51	// Maximum indices for the array types used when traversing the vDSO ELF structures.
52	// Computed from architecture-specific max provided by vdso_linux_*.go
53	vdsoSymTabSize     = vdsoArrayMax / unsafe.Sizeof(elfSym{})
54	vdsoDynSize        = vdsoArrayMax / unsafe.Sizeof(elfDyn{})
55	vdsoSymStringsSize = vdsoArrayMax     // byte
56	vdsoVerSymSize     = vdsoArrayMax / 2 // uint16
57	vdsoHashSize       = vdsoArrayMax / 4 // uint32
58
59	// vdsoBloomSizeScale is a scaling factor for gnuhash tables which are uint32 indexed,
60	// but contain uintptrs
61	vdsoBloomSizeScale = unsafe.Sizeof(uintptr(0)) / 4 // uint32
62)
63
64/* How to extract and insert information held in the st_info field.  */
65func _ELF_ST_BIND(val byte) byte { return val >> 4 }
66func _ELF_ST_TYPE(val byte) byte { return val & 0xf }
67
68type vdsoSymbolKey struct {
69	name    string
70	symHash uint32
71	gnuHash uint32
72	ptr     *uintptr
73}
74
75type vdsoVersionKey struct {
76	version string
77	verHash uint32
78}
79
80type vdsoInfo struct {
81	valid bool
82
83	/* Load information */
84	loadAddr   uintptr
85	loadOffset uintptr /* loadAddr - recorded vaddr */
86
87	/* Symbol table */
88	symtab     *[vdsoSymTabSize]elfSym
89	symstrings *[vdsoSymStringsSize]byte
90	chain      []uint32
91	bucket     []uint32
92	symOff     uint32
93	isGNUHash  bool
94
95	/* Version table */
96	versym *[vdsoVerSymSize]uint16
97	verdef *elfVerdef
98}
99
100// see vdso_linux_*.go for vdsoSymbolKeys[] and vdso*Sym vars
101
102func vdsoInitFromSysinfoEhdr(info *vdsoInfo, hdr *elfEhdr) {
103	info.valid = false
104	info.loadAddr = uintptr(unsafe.Pointer(hdr))
105
106	pt := unsafe.Pointer(info.loadAddr + uintptr(hdr.e_phoff))
107
108	// We need two things from the segment table: the load offset
109	// and the dynamic table.
110	var foundVaddr bool
111	var dyn *[vdsoDynSize]elfDyn
112	for i := uint16(0); i < hdr.e_phnum; i++ {
113		pt := (*elfPhdr)(add(pt, uintptr(i)*unsafe.Sizeof(elfPhdr{})))
114		switch pt.p_type {
115		case _PT_LOAD:
116			if !foundVaddr {
117				foundVaddr = true
118				info.loadOffset = info.loadAddr + uintptr(pt.p_offset-pt.p_vaddr)
119			}
120
121		case _PT_DYNAMIC:
122			dyn = (*[vdsoDynSize]elfDyn)(unsafe.Pointer(info.loadAddr + uintptr(pt.p_offset)))
123		}
124	}
125
126	if !foundVaddr || dyn == nil {
127		return // Failed
128	}
129
130	// Fish out the useful bits of the dynamic table.
131
132	var hash, gnuhash *[vdsoHashSize]uint32
133	info.symstrings = nil
134	info.symtab = nil
135	info.versym = nil
136	info.verdef = nil
137	for i := 0; dyn[i].d_tag != _DT_NULL; i++ {
138		dt := &dyn[i]
139		p := info.loadOffset + uintptr(dt.d_val)
140		switch dt.d_tag {
141		case _DT_STRTAB:
142			info.symstrings = (*[vdsoSymStringsSize]byte)(unsafe.Pointer(p))
143		case _DT_SYMTAB:
144			info.symtab = (*[vdsoSymTabSize]elfSym)(unsafe.Pointer(p))
145		case _DT_HASH:
146			hash = (*[vdsoHashSize]uint32)(unsafe.Pointer(p))
147		case _DT_GNU_HASH:
148			gnuhash = (*[vdsoHashSize]uint32)(unsafe.Pointer(p))
149		case _DT_VERSYM:
150			info.versym = (*[vdsoVerSymSize]uint16)(unsafe.Pointer(p))
151		case _DT_VERDEF:
152			info.verdef = (*elfVerdef)(unsafe.Pointer(p))
153		}
154	}
155
156	if info.symstrings == nil || info.symtab == nil || (hash == nil && gnuhash == nil) {
157		return // Failed
158	}
159
160	if info.verdef == nil {
161		info.versym = nil
162	}
163
164	if gnuhash != nil {
165		// Parse the GNU hash table header.
166		nbucket := gnuhash[0]
167		info.symOff = gnuhash[1]
168		bloomSize := gnuhash[2]
169		info.bucket = gnuhash[4+bloomSize*uint32(vdsoBloomSizeScale):][:nbucket]
170		info.chain = gnuhash[4+bloomSize*uint32(vdsoBloomSizeScale)+nbucket:]
171		info.isGNUHash = true
172	} else {
173		// Parse the hash table header.
174		nbucket := hash[0]
175		nchain := hash[1]
176		info.bucket = hash[2 : 2+nbucket]
177		info.chain = hash[2+nbucket : 2+nbucket+nchain]
178	}
179
180	// That's all we need.
181	info.valid = true
182}
183
184func vdsoFindVersion(info *vdsoInfo, ver *vdsoVersionKey) int32 {
185	if !info.valid {
186		return 0
187	}
188
189	def := info.verdef
190	for {
191		if def.vd_flags&_VER_FLG_BASE == 0 {
192			aux := (*elfVerdaux)(add(unsafe.Pointer(def), uintptr(def.vd_aux)))
193			if def.vd_hash == ver.verHash && ver.version == gostringnocopy(&info.symstrings[aux.vda_name]) {
194				return int32(def.vd_ndx & 0x7fff)
195			}
196		}
197
198		if def.vd_next == 0 {
199			break
200		}
201		def = (*elfVerdef)(add(unsafe.Pointer(def), uintptr(def.vd_next)))
202	}
203
204	return -1 // cannot match any version
205}
206
207func vdsoParseSymbols(info *vdsoInfo, version int32) {
208	if !info.valid {
209		return
210	}
211
212	apply := func(symIndex uint32, k vdsoSymbolKey) bool {
213		sym := &info.symtab[symIndex]
214		typ := _ELF_ST_TYPE(sym.st_info)
215		bind := _ELF_ST_BIND(sym.st_info)
216		// On ppc64x, VDSO functions are of type _STT_NOTYPE.
217		if typ != _STT_FUNC && typ != _STT_NOTYPE || bind != _STB_GLOBAL && bind != _STB_WEAK || sym.st_shndx == _SHN_UNDEF {
218			return false
219		}
220		if k.name != gostringnocopy(&info.symstrings[sym.st_name]) {
221			return false
222		}
223		// Check symbol version.
224		if info.versym != nil && version != 0 && int32(info.versym[symIndex]&0x7fff) != version {
225			return false
226		}
227
228		*k.ptr = info.loadOffset + uintptr(sym.st_value)
229		return true
230	}
231
232	if !info.isGNUHash {
233		// Old-style DT_HASH table.
234		for _, k := range vdsoSymbolKeys {
235			if len(info.bucket) > 0 {
236				for chain := info.bucket[k.symHash%uint32(len(info.bucket))]; chain != 0; chain = info.chain[chain] {
237					if apply(chain, k) {
238						break
239					}
240				}
241			}
242		}
243		return
244	}
245
246	// New-style DT_GNU_HASH table.
247	for _, k := range vdsoSymbolKeys {
248		symIndex := info.bucket[k.gnuHash%uint32(len(info.bucket))]
249		if symIndex < info.symOff {
250			continue
251		}
252		for ; ; symIndex++ {
253			hash := info.chain[symIndex-info.symOff]
254			if hash|1 == k.gnuHash|1 {
255				// Found a hash match.
256				if apply(symIndex, k) {
257					break
258				}
259			}
260			if hash&1 != 0 {
261				// End of chain.
262				break
263			}
264		}
265	}
266}
267
268func vdsoauxv(tag, val uintptr) {
269	switch tag {
270	case _AT_SYSINFO_EHDR:
271		if val == 0 {
272			// Something went wrong
273			return
274		}
275		var info vdsoInfo
276		// TODO(rsc): I don't understand why the compiler thinks info escapes
277		// when passed to the three functions below.
278		info1 := (*vdsoInfo)(noescape(unsafe.Pointer(&info)))
279		vdsoInitFromSysinfoEhdr(info1, (*elfEhdr)(unsafe.Pointer(val)))
280		vdsoParseSymbols(info1, vdsoFindVersion(info1, &vdsoLinuxVersion))
281	}
282}
283
284// vdsoMarker reports whether PC is on the VDSO page.
285//
286//go:nosplit
287func inVDSOPage(pc uintptr) bool {
288	for _, k := range vdsoSymbolKeys {
289		if *k.ptr != 0 {
290			page := *k.ptr &^ (physPageSize - 1)
291			return pc >= page && pc < page+physPageSize
292		}
293	}
294	return false
295}
296