github.com/reiver/go@v0.0.0-20150109200633-1d0c7792f172/src/runtime/symtab.go (about)

     1  // Copyright 2014 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  package runtime
     6  
     7  import "unsafe"
     8  
     9  // NOTE: Func does not expose the actual unexported fields, because we return *Func
    10  // values to users, and we want to keep them from being able to overwrite the data
    11  // with (say) *f = Func{}.
    12  // All code operating on a *Func must call raw to get the *_func instead.
    13  
    14  // A Func represents a Go function in the running binary.
    15  type Func struct {
    16  	opaque struct{} // unexported field to disallow conversions
    17  }
    18  
    19  func (f *Func) raw() *_func {
    20  	return (*_func)(unsafe.Pointer(f))
    21  }
    22  
    23  // funcdata.h
    24  const (
    25  	_PCDATA_StackMapIndex       = 0
    26  	_FUNCDATA_ArgsPointerMaps   = 0
    27  	_FUNCDATA_LocalsPointerMaps = 1
    28  	_FUNCDATA_DeadValueMaps     = 2
    29  	_ArgsSizeUnknown            = -0x80000000
    30  )
    31  
    32  var (
    33  	pclntable []byte
    34  	ftab      []functab
    35  	filetab   []uint32
    36  
    37  	pclntab, epclntab, findfunctab struct{} // linker symbols
    38  
    39  	minpc, maxpc uintptr
    40  )
    41  
    42  type functab struct {
    43  	entry   uintptr
    44  	funcoff uintptr
    45  }
    46  
    47  const minfunc = 16 // minimum function size
    48  const pcbucketsize = 256*minfunc // size of bucket in the pc->func lookup table
    49  
    50  // findfunctab is an array of these structures.
    51  // Each bucket represents 4096 bytes of the text segment.
    52  // Each subbucket represents 256 bytes of the text segment.
    53  // To find a function given a pc, locate the bucket and subbucket for
    54  // that pc.  Add together the idx and subbucket value to obtain a
    55  // function index.  Then scan the functab array starting at that
    56  // index to find the target function.
    57  // This table uses 20 bytes for every 4096 bytes of code, or ~0.5% overhead.
    58  type findfuncbucket struct {
    59  	idx uint32
    60  	subbuckets [16]byte
    61  }
    62  
    63  func symtabinit() {
    64  	// See golang.org/s/go12symtab for header: 0xfffffffb,
    65  	// two zero bytes, a byte giving the PC quantum,
    66  	// and a byte giving the pointer width in bytes.
    67  	pcln := (*[8]byte)(unsafe.Pointer(&pclntab))
    68  	pcln32 := (*[2]uint32)(unsafe.Pointer(&pclntab))
    69  	if pcln32[0] != 0xfffffffb || pcln[4] != 0 || pcln[5] != 0 || pcln[6] != _PCQuantum || pcln[7] != ptrSize {
    70  		println("runtime: function symbol table header:", hex(pcln32[0]), hex(pcln[4]), hex(pcln[5]), hex(pcln[6]), hex(pcln[7]))
    71  		throw("invalid function symbol table\n")
    72  	}
    73  
    74  	// pclntable is all bytes of pclntab symbol.
    75  	sp := (*sliceStruct)(unsafe.Pointer(&pclntable))
    76  	sp.array = unsafe.Pointer(&pclntab)
    77  	sp.len = int(uintptr(unsafe.Pointer(&epclntab)) - uintptr(unsafe.Pointer(&pclntab)))
    78  	sp.cap = sp.len
    79  
    80  	// ftab is lookup table for function by program counter.
    81  	nftab := int(*(*uintptr)(add(unsafe.Pointer(pcln), 8)))
    82  	p := add(unsafe.Pointer(pcln), 8+ptrSize)
    83  	sp = (*sliceStruct)(unsafe.Pointer(&ftab))
    84  	sp.array = p
    85  	sp.len = nftab + 1
    86  	sp.cap = sp.len
    87  	for i := 0; i < nftab; i++ {
    88  		// NOTE: ftab[nftab].entry is legal; it is the address beyond the final function.
    89  		if ftab[i].entry > ftab[i+1].entry {
    90  			f1 := (*_func)(unsafe.Pointer(&pclntable[ftab[i].funcoff]))
    91  			f2 := (*_func)(unsafe.Pointer(&pclntable[ftab[i+1].funcoff]))
    92  			f2name := "end"
    93  			if i+1 < nftab {
    94  				f2name = funcname(f2)
    95  			}
    96  			println("function symbol table not sorted by program counter:", hex(ftab[i].entry), funcname(f1), ">", hex(ftab[i+1].entry), f2name)
    97  			for j := 0; j <= i; j++ {
    98  				print("\t", hex(ftab[j].entry), " ", funcname((*_func)(unsafe.Pointer(&pclntable[ftab[j].funcoff]))), "\n")
    99  			}
   100  			throw("invalid runtime symbol table")
   101  		}
   102  	}
   103  
   104  	// The ftab ends with a half functab consisting only of
   105  	// 'entry', followed by a uint32 giving the pcln-relative
   106  	// offset of the file table.
   107  	sp = (*sliceStruct)(unsafe.Pointer(&filetab))
   108  	end := unsafe.Pointer(&ftab[nftab].funcoff) // just beyond ftab
   109  	fileoffset := *(*uint32)(end)
   110  	sp.array = unsafe.Pointer(&pclntable[fileoffset])
   111  	// length is in first element of array.
   112  	// set len to 1 so we can get first element.
   113  	sp.len = 1
   114  	sp.cap = 1
   115  	sp.len = int(filetab[0])
   116  	sp.cap = sp.len
   117  
   118  	minpc = ftab[0].entry
   119  	maxpc = ftab[nftab].entry
   120  }
   121  
   122  // FuncForPC returns a *Func describing the function that contains the
   123  // given program counter address, or else nil.
   124  func FuncForPC(pc uintptr) *Func {
   125  	return (*Func)(unsafe.Pointer(findfunc(pc)))
   126  }
   127  
   128  // Name returns the name of the function.
   129  func (f *Func) Name() string {
   130  	return funcname(f.raw())
   131  }
   132  
   133  // Entry returns the entry address of the function.
   134  func (f *Func) Entry() uintptr {
   135  	return f.raw().entry
   136  }
   137  
   138  // FileLine returns the file name and line number of the
   139  // source code corresponding to the program counter pc.
   140  // The result will not be accurate if pc is not a program
   141  // counter within f.
   142  func (f *Func) FileLine(pc uintptr) (file string, line int) {
   143  	// Pass strict=false here, because anyone can call this function,
   144  	// and they might just be wrong about targetpc belonging to f.
   145  	file, line32 := funcline1(f.raw(), pc, false)
   146  	return file, int(line32)
   147  }
   148  
   149  func findfunc(pc uintptr) *_func {
   150  	if pc < minpc || pc >= maxpc {
   151  		return nil
   152  	}
   153  	const nsub = uintptr(len(findfuncbucket{}.subbuckets))
   154  
   155  	x := pc - minpc
   156  	b := x / pcbucketsize
   157  	i := x % pcbucketsize / (pcbucketsize/nsub)
   158  
   159  	ffb := (*findfuncbucket)(add(unsafe.Pointer(&findfunctab), b * unsafe.Sizeof(findfuncbucket{})))
   160  	idx := ffb.idx + uint32(ffb.subbuckets[i])
   161  	if pc < ftab[idx].entry {
   162  		throw("findfunc: bad findfunctab entry")
   163  	}
   164  
   165  	// linear search to find func with pc >= entry.
   166  	for ftab[idx+1].entry <= pc {
   167  		idx++
   168  	}
   169  	return (*_func)(unsafe.Pointer(&pclntable[ftab[idx].funcoff]))
   170  }
   171  
   172  func pcvalue(f *_func, off int32, targetpc uintptr, strict bool) int32 {
   173  	if off == 0 {
   174  		return -1
   175  	}
   176  	p := pclntable[off:]
   177  	pc := f.entry
   178  	val := int32(-1)
   179  	for {
   180  		var ok bool
   181  		p, ok = step(p, &pc, &val, pc == f.entry)
   182  		if !ok {
   183  			break
   184  		}
   185  		if targetpc < pc {
   186  			return val
   187  		}
   188  	}
   189  
   190  	// If there was a table, it should have covered all program counters.
   191  	// If not, something is wrong.
   192  	if panicking != 0 || !strict {
   193  		return -1
   194  	}
   195  
   196  	print("runtime: invalid pc-encoded table f=", funcname(f), " pc=", hex(pc), " targetpc=", hex(targetpc), " tab=", p, "\n")
   197  
   198  	p = pclntable[off:]
   199  	pc = f.entry
   200  	val = -1
   201  	for {
   202  		var ok bool
   203  		p, ok = step(p, &pc, &val, pc == f.entry)
   204  		if !ok {
   205  			break
   206  		}
   207  		print("\tvalue=", val, " until pc=", hex(pc), "\n")
   208  	}
   209  
   210  	throw("invalid runtime symbol table")
   211  	return -1
   212  }
   213  
   214  func cfuncname(f *_func) *byte {
   215  	if f == nil || f.nameoff == 0 {
   216  		return nil
   217  	}
   218  	return (*byte)(unsafe.Pointer(&pclntable[f.nameoff]))
   219  }
   220  
   221  func funcname(f *_func) string {
   222  	return gostringnocopy(cfuncname(f))
   223  }
   224  
   225  func funcline1(f *_func, targetpc uintptr, strict bool) (file string, line int32) {
   226  	fileno := int(pcvalue(f, f.pcfile, targetpc, strict))
   227  	line = pcvalue(f, f.pcln, targetpc, strict)
   228  	if fileno == -1 || line == -1 || fileno >= len(filetab) {
   229  		// print("looking for ", hex(targetpc), " in ", funcname(f), " got file=", fileno, " line=", lineno, "\n")
   230  		return "?", 0
   231  	}
   232  	file = gostringnocopy(&pclntable[filetab[fileno]])
   233  	return
   234  }
   235  
   236  func funcline(f *_func, targetpc uintptr) (file string, line int32) {
   237  	return funcline1(f, targetpc, true)
   238  }
   239  
   240  func funcspdelta(f *_func, targetpc uintptr) int32 {
   241  	x := pcvalue(f, f.pcsp, targetpc, true)
   242  	if x&(ptrSize-1) != 0 {
   243  		print("invalid spdelta ", hex(f.entry), " ", hex(targetpc), " ", hex(f.pcsp), " ", x, "\n")
   244  	}
   245  	return x
   246  }
   247  
   248  func pcdatavalue(f *_func, table int32, targetpc uintptr) int32 {
   249  	if table < 0 || table >= f.npcdata {
   250  		return -1
   251  	}
   252  	off := *(*int32)(add(unsafe.Pointer(&f.nfuncdata), unsafe.Sizeof(f.nfuncdata)+uintptr(table)*4))
   253  	return pcvalue(f, off, targetpc, true)
   254  }
   255  
   256  func funcdata(f *_func, i int32) unsafe.Pointer {
   257  	if i < 0 || i >= f.nfuncdata {
   258  		return nil
   259  	}
   260  	p := add(unsafe.Pointer(&f.nfuncdata), unsafe.Sizeof(f.nfuncdata)+uintptr(f.npcdata)*4)
   261  	if ptrSize == 8 && uintptr(p)&4 != 0 {
   262  		if uintptr(unsafe.Pointer(f))&4 != 0 {
   263  			println("runtime: misaligned func", f)
   264  		}
   265  		p = add(p, 4)
   266  	}
   267  	return *(*unsafe.Pointer)(add(p, uintptr(i)*ptrSize))
   268  }
   269  
   270  // step advances to the next pc, value pair in the encoded table.
   271  func step(p []byte, pc *uintptr, val *int32, first bool) (newp []byte, ok bool) {
   272  	p, uvdelta := readvarint(p)
   273  	if uvdelta == 0 && !first {
   274  		return nil, false
   275  	}
   276  	if uvdelta&1 != 0 {
   277  		uvdelta = ^(uvdelta >> 1)
   278  	} else {
   279  		uvdelta >>= 1
   280  	}
   281  	vdelta := int32(uvdelta)
   282  	p, pcdelta := readvarint(p)
   283  	*pc += uintptr(pcdelta * _PCQuantum)
   284  	*val += vdelta
   285  	return p, true
   286  }
   287  
   288  // readvarint reads a varint from p.
   289  func readvarint(p []byte) (newp []byte, val uint32) {
   290  	var v, shift uint32
   291  	for {
   292  		b := p[0]
   293  		p = p[1:]
   294  		v |= (uint32(b) & 0x7F) << shift
   295  		if b&0x80 == 0 {
   296  			break
   297  		}
   298  		shift += 7
   299  	}
   300  	return p, v
   301  }