...
Run Format

Source file src/debug/gosym/pclntab.go

Documentation: debug/gosym

     1  // Copyright 2009 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  /*
     6   * Line tables
     7   */
     8  
     9  package gosym
    10  
    11  import (
    12  	"bytes"
    13  	"encoding/binary"
    14  	"sync"
    15  )
    16  
    17  // A LineTable is a data structure mapping program counters to line numbers.
    18  //
    19  // In Go 1.1 and earlier, each function (represented by a Func) had its own LineTable,
    20  // and the line number corresponded to a numbering of all source lines in the
    21  // program, across all files. That absolute line number would then have to be
    22  // converted separately to a file name and line number within the file.
    23  //
    24  // In Go 1.2, the format of the data changed so that there is a single LineTable
    25  // for the entire program, shared by all Funcs, and there are no absolute line
    26  // numbers, just line numbers within specific files.
    27  //
    28  // For the most part, LineTable's methods should be treated as an internal
    29  // detail of the package; callers should use the methods on Table instead.
    30  type LineTable struct {
    31  	Data []byte
    32  	PC   uint64
    33  	Line int
    34  
    35  	// Go 1.2 state
    36  	mu       sync.Mutex
    37  	go12     int // is this in Go 1.2 format? -1 no, 0 unknown, 1 yes
    38  	binary   binary.ByteOrder
    39  	quantum  uint32
    40  	ptrsize  uint32
    41  	functab  []byte
    42  	nfunctab uint32
    43  	filetab  []byte
    44  	nfiletab uint32
    45  	fileMap  map[string]uint32
    46  	strings  map[uint32]string // interned substrings of Data, keyed by offset
    47  }
    48  
    49  // NOTE(rsc): This is wrong for GOARCH=arm, which uses a quantum of 4,
    50  // but we have no idea whether we're using arm or not. This only
    51  // matters in the old (pre-Go 1.2) symbol table format, so it's not worth
    52  // fixing.
    53  const oldQuantum = 1
    54  
    55  func (t *LineTable) parse(targetPC uint64, targetLine int) (b []byte, pc uint64, line int) {
    56  	// The PC/line table can be thought of as a sequence of
    57  	//  <pc update>* <line update>
    58  	// batches. Each update batch results in a (pc, line) pair,
    59  	// where line applies to every PC from pc up to but not
    60  	// including the pc of the next pair.
    61  	//
    62  	// Here we process each update individually, which simplifies
    63  	// the code, but makes the corner cases more confusing.
    64  	b, pc, line = t.Data, t.PC, t.Line
    65  	for pc <= targetPC && line != targetLine && len(b) > 0 {
    66  		code := b[0]
    67  		b = b[1:]
    68  		switch {
    69  		case code == 0:
    70  			if len(b) < 4 {
    71  				b = b[0:0]
    72  				break
    73  			}
    74  			val := binary.BigEndian.Uint32(b)
    75  			b = b[4:]
    76  			line += int(val)
    77  		case code <= 64:
    78  			line += int(code)
    79  		case code <= 128:
    80  			line -= int(code - 64)
    81  		default:
    82  			pc += oldQuantum * uint64(code-128)
    83  			continue
    84  		}
    85  		pc += oldQuantum
    86  	}
    87  	return b, pc, line
    88  }
    89  
    90  func (t *LineTable) slice(pc uint64) *LineTable {
    91  	data, pc, line := t.parse(pc, -1)
    92  	return &LineTable{Data: data, PC: pc, Line: line}
    93  }
    94  
    95  // PCToLine returns the line number for the given program counter.
    96  // Callers should use Table's PCToLine method instead.
    97  func (t *LineTable) PCToLine(pc uint64) int {
    98  	if t.isGo12() {
    99  		return t.go12PCToLine(pc)
   100  	}
   101  	_, _, line := t.parse(pc, -1)
   102  	return line
   103  }
   104  
   105  // LineToPC returns the program counter for the given line number,
   106  // considering only program counters before maxpc.
   107  // Callers should use Table's LineToPC method instead.
   108  func (t *LineTable) LineToPC(line int, maxpc uint64) uint64 {
   109  	if t.isGo12() {
   110  		return 0
   111  	}
   112  	_, pc, line1 := t.parse(maxpc, line)
   113  	if line1 != line {
   114  		return 0
   115  	}
   116  	// Subtract quantum from PC to account for post-line increment
   117  	return pc - oldQuantum
   118  }
   119  
   120  // NewLineTable returns a new PC/line table
   121  // corresponding to the encoded data.
   122  // Text must be the start address of the
   123  // corresponding text segment.
   124  func NewLineTable(data []byte, text uint64) *LineTable {
   125  	return &LineTable{Data: data, PC: text, Line: 0, strings: make(map[uint32]string)}
   126  }
   127  
   128  // Go 1.2 symbol table format.
   129  // See golang.org/s/go12symtab.
   130  //
   131  // A general note about the methods here: rather than try to avoid
   132  // index out of bounds errors, we trust Go to detect them, and then
   133  // we recover from the panics and treat them as indicative of a malformed
   134  // or incomplete table.
   135  //
   136  // The methods called by symtab.go, which begin with "go12" prefixes,
   137  // are expected to have that recovery logic.
   138  
   139  // isGo12 reports whether this is a Go 1.2 (or later) symbol table.
   140  func (t *LineTable) isGo12() bool {
   141  	t.go12Init()
   142  	return t.go12 == 1
   143  }
   144  
   145  const go12magic = 0xfffffffb
   146  
   147  // uintptr returns the pointer-sized value encoded at b.
   148  // The pointer size is dictated by the table being read.
   149  func (t *LineTable) uintptr(b []byte) uint64 {
   150  	if t.ptrsize == 4 {
   151  		return uint64(t.binary.Uint32(b))
   152  	}
   153  	return t.binary.Uint64(b)
   154  }
   155  
   156  // go12init initializes the Go 1.2 metadata if t is a Go 1.2 symbol table.
   157  func (t *LineTable) go12Init() {
   158  	t.mu.Lock()
   159  	defer t.mu.Unlock()
   160  	if t.go12 != 0 {
   161  		return
   162  	}
   163  
   164  	defer func() {
   165  		// If we panic parsing, assume it's not a Go 1.2 symbol table.
   166  		recover()
   167  	}()
   168  
   169  	// Check header: 4-byte magic, two zeros, pc quantum, pointer size.
   170  	t.go12 = -1 // not Go 1.2 until proven otherwise
   171  	if len(t.Data) < 16 || t.Data[4] != 0 || t.Data[5] != 0 ||
   172  		(t.Data[6] != 1 && t.Data[6] != 2 && t.Data[6] != 4) || // pc quantum
   173  		(t.Data[7] != 4 && t.Data[7] != 8) { // pointer size
   174  		return
   175  	}
   176  
   177  	switch uint32(go12magic) {
   178  	case binary.LittleEndian.Uint32(t.Data):
   179  		t.binary = binary.LittleEndian
   180  	case binary.BigEndian.Uint32(t.Data):
   181  		t.binary = binary.BigEndian
   182  	default:
   183  		return
   184  	}
   185  
   186  	t.quantum = uint32(t.Data[6])
   187  	t.ptrsize = uint32(t.Data[7])
   188  
   189  	t.nfunctab = uint32(t.uintptr(t.Data[8:]))
   190  	t.functab = t.Data[8+t.ptrsize:]
   191  	functabsize := t.nfunctab*2*t.ptrsize + t.ptrsize
   192  	fileoff := t.binary.Uint32(t.functab[functabsize:])
   193  	t.functab = t.functab[:functabsize]
   194  	t.filetab = t.Data[fileoff:]
   195  	t.nfiletab = t.binary.Uint32(t.filetab)
   196  	t.filetab = t.filetab[:t.nfiletab*4]
   197  
   198  	t.go12 = 1 // so far so good
   199  }
   200  
   201  // go12Funcs returns a slice of Funcs derived from the Go 1.2 pcln table.
   202  func (t *LineTable) go12Funcs() []Func {
   203  	// Assume it is malformed and return nil on error.
   204  	defer func() {
   205  		recover()
   206  	}()
   207  
   208  	n := len(t.functab) / int(t.ptrsize) / 2
   209  	funcs := make([]Func, n)
   210  	for i := range funcs {
   211  		f := &funcs[i]
   212  		f.Entry = t.uintptr(t.functab[2*i*int(t.ptrsize):])
   213  		f.End = t.uintptr(t.functab[(2*i+2)*int(t.ptrsize):])
   214  		info := t.Data[t.uintptr(t.functab[(2*i+1)*int(t.ptrsize):]):]
   215  		f.LineTable = t
   216  		f.FrameSize = int(t.binary.Uint32(info[t.ptrsize+2*4:]))
   217  		f.Sym = &Sym{
   218  			Value:  f.Entry,
   219  			Type:   'T',
   220  			Name:   t.string(t.binary.Uint32(info[t.ptrsize:])),
   221  			GoType: 0,
   222  			Func:   f,
   223  		}
   224  	}
   225  	return funcs
   226  }
   227  
   228  // findFunc returns the func corresponding to the given program counter.
   229  func (t *LineTable) findFunc(pc uint64) []byte {
   230  	if pc < t.uintptr(t.functab) || pc >= t.uintptr(t.functab[len(t.functab)-int(t.ptrsize):]) {
   231  		return nil
   232  	}
   233  
   234  	// The function table is a list of 2*nfunctab+1 uintptrs,
   235  	// alternating program counters and offsets to func structures.
   236  	f := t.functab
   237  	nf := t.nfunctab
   238  	for nf > 0 {
   239  		m := nf / 2
   240  		fm := f[2*t.ptrsize*m:]
   241  		if t.uintptr(fm) <= pc && pc < t.uintptr(fm[2*t.ptrsize:]) {
   242  			return t.Data[t.uintptr(fm[t.ptrsize:]):]
   243  		} else if pc < t.uintptr(fm) {
   244  			nf = m
   245  		} else {
   246  			f = f[(m+1)*2*t.ptrsize:]
   247  			nf -= m + 1
   248  		}
   249  	}
   250  	return nil
   251  }
   252  
   253  // readvarint reads, removes, and returns a varint from *pp.
   254  func (t *LineTable) readvarint(pp *[]byte) uint32 {
   255  	var v, shift uint32
   256  	p := *pp
   257  	for shift = 0; ; shift += 7 {
   258  		b := p[0]
   259  		p = p[1:]
   260  		v |= (uint32(b) & 0x7F) << shift
   261  		if b&0x80 == 0 {
   262  			break
   263  		}
   264  	}
   265  	*pp = p
   266  	return v
   267  }
   268  
   269  // string returns a Go string found at off.
   270  func (t *LineTable) string(off uint32) string {
   271  	if s, ok := t.strings[off]; ok {
   272  		return s
   273  	}
   274  	i := bytes.IndexByte(t.Data[off:], 0)
   275  	s := string(t.Data[off : off+uint32(i)])
   276  	t.strings[off] = s
   277  	return s
   278  }
   279  
   280  // step advances to the next pc, value pair in the encoded table.
   281  func (t *LineTable) step(p *[]byte, pc *uint64, val *int32, first bool) bool {
   282  	uvdelta := t.readvarint(p)
   283  	if uvdelta == 0 && !first {
   284  		return false
   285  	}
   286  	if uvdelta&1 != 0 {
   287  		uvdelta = ^(uvdelta >> 1)
   288  	} else {
   289  		uvdelta >>= 1
   290  	}
   291  	vdelta := int32(uvdelta)
   292  	pcdelta := t.readvarint(p) * t.quantum
   293  	*pc += uint64(pcdelta)
   294  	*val += vdelta
   295  	return true
   296  }
   297  
   298  // pcvalue reports the value associated with the target pc.
   299  // off is the offset to the beginning of the pc-value table,
   300  // and entry is the start PC for the corresponding function.
   301  func (t *LineTable) pcvalue(off uint32, entry, targetpc uint64) int32 {
   302  	p := t.Data[off:]
   303  
   304  	val := int32(-1)
   305  	pc := entry
   306  	for t.step(&p, &pc, &val, pc == entry) {
   307  		if targetpc < pc {
   308  			return val
   309  		}
   310  	}
   311  	return -1
   312  }
   313  
   314  // findFileLine scans one function in the binary looking for a
   315  // program counter in the given file on the given line.
   316  // It does so by running the pc-value tables mapping program counter
   317  // to file number. Since most functions come from a single file, these
   318  // are usually short and quick to scan. If a file match is found, then the
   319  // code goes to the expense of looking for a simultaneous line number match.
   320  func (t *LineTable) findFileLine(entry uint64, filetab, linetab uint32, filenum, line int32) uint64 {
   321  	if filetab == 0 || linetab == 0 {
   322  		return 0
   323  	}
   324  
   325  	fp := t.Data[filetab:]
   326  	fl := t.Data[linetab:]
   327  	fileVal := int32(-1)
   328  	filePC := entry
   329  	lineVal := int32(-1)
   330  	linePC := entry
   331  	fileStartPC := filePC
   332  	for t.step(&fp, &filePC, &fileVal, filePC == entry) {
   333  		if fileVal == filenum && fileStartPC < filePC {
   334  			// fileVal is in effect starting at fileStartPC up to
   335  			// but not including filePC, and it's the file we want.
   336  			// Run the PC table looking for a matching line number
   337  			// or until we reach filePC.
   338  			lineStartPC := linePC
   339  			for linePC < filePC && t.step(&fl, &linePC, &lineVal, linePC == entry) {
   340  				// lineVal is in effect until linePC, and lineStartPC < filePC.
   341  				if lineVal == line {
   342  					if fileStartPC <= lineStartPC {
   343  						return lineStartPC
   344  					}
   345  					if fileStartPC < linePC {
   346  						return fileStartPC
   347  					}
   348  				}
   349  				lineStartPC = linePC
   350  			}
   351  		}
   352  		fileStartPC = filePC
   353  	}
   354  	return 0
   355  }
   356  
   357  // go12PCToLine maps program counter to line number for the Go 1.2 pcln table.
   358  func (t *LineTable) go12PCToLine(pc uint64) (line int) {
   359  	defer func() {
   360  		if recover() != nil {
   361  			line = -1
   362  		}
   363  	}()
   364  
   365  	f := t.findFunc(pc)
   366  	if f == nil {
   367  		return -1
   368  	}
   369  	entry := t.uintptr(f)
   370  	linetab := t.binary.Uint32(f[t.ptrsize+5*4:])
   371  	return int(t.pcvalue(linetab, entry, pc))
   372  }
   373  
   374  // go12PCToFile maps program counter to file name for the Go 1.2 pcln table.
   375  func (t *LineTable) go12PCToFile(pc uint64) (file string) {
   376  	defer func() {
   377  		if recover() != nil {
   378  			file = ""
   379  		}
   380  	}()
   381  
   382  	f := t.findFunc(pc)
   383  	if f == nil {
   384  		return ""
   385  	}
   386  	entry := t.uintptr(f)
   387  	filetab := t.binary.Uint32(f[t.ptrsize+4*4:])
   388  	fno := t.pcvalue(filetab, entry, pc)
   389  	if fno <= 0 {
   390  		return ""
   391  	}
   392  	return t.string(t.binary.Uint32(t.filetab[4*fno:]))
   393  }
   394  
   395  // go12LineToPC maps a (file, line) pair to a program counter for the Go 1.2 pcln table.
   396  func (t *LineTable) go12LineToPC(file string, line int) (pc uint64) {
   397  	defer func() {
   398  		if recover() != nil {
   399  			pc = 0
   400  		}
   401  	}()
   402  
   403  	t.initFileMap()
   404  	filenum := t.fileMap[file]
   405  	if filenum == 0 {
   406  		return 0
   407  	}
   408  
   409  	// Scan all functions.
   410  	// If this turns out to be a bottleneck, we could build a map[int32][]int32
   411  	// mapping file number to a list of functions with code from that file.
   412  	for i := uint32(0); i < t.nfunctab; i++ {
   413  		f := t.Data[t.uintptr(t.functab[2*t.ptrsize*i+t.ptrsize:]):]
   414  		entry := t.uintptr(f)
   415  		filetab := t.binary.Uint32(f[t.ptrsize+4*4:])
   416  		linetab := t.binary.Uint32(f[t.ptrsize+5*4:])
   417  		pc := t.findFileLine(entry, filetab, linetab, int32(filenum), int32(line))
   418  		if pc != 0 {
   419  			return pc
   420  		}
   421  	}
   422  	return 0
   423  }
   424  
   425  // initFileMap initializes the map from file name to file number.
   426  func (t *LineTable) initFileMap() {
   427  	t.mu.Lock()
   428  	defer t.mu.Unlock()
   429  
   430  	if t.fileMap != nil {
   431  		return
   432  	}
   433  	m := make(map[string]uint32)
   434  
   435  	for i := uint32(1); i < t.nfiletab; i++ {
   436  		s := t.string(t.binary.Uint32(t.filetab[4*i:]))
   437  		m[s] = i
   438  	}
   439  	t.fileMap = m
   440  }
   441  
   442  // go12MapFiles adds to m a key for every file in the Go 1.2 LineTable.
   443  // Every key maps to obj. That's not a very interesting map, but it provides
   444  // a way for callers to obtain the list of files in the program.
   445  func (t *LineTable) go12MapFiles(m map[string]*Obj, obj *Obj) {
   446  	defer func() {
   447  		recover()
   448  	}()
   449  
   450  	t.initFileMap()
   451  	for file := range t.fileMap {
   452  		m[file] = obj
   453  	}
   454  }
   455  

View as plain text