variables.go 15.7 KB
Newer Older
1 2 3 4
package proctl

import (
	"bytes"
D
Derek Parker 已提交
5
	"debug/dwarf"
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
	"encoding/binary"
	"fmt"
	"strconv"
	"strings"
	"unsafe"

	"github.com/derekparker/delve/dwarf/op"
)

type Variable struct {
	Name  string
	Value string
	Type  string
}

21 22 23 24 25 26 27
type M struct {
	procid   int
	spinning uint8
	blocked  uint8
	curg     uintptr
}

D
Derek Parker 已提交
28 29
const ptrsize uintptr = unsafe.Sizeof(int(1))

30 31 32
// Parses and returns select info on the internal M
// data structures used by the Go scheduler.
func (thread *ThreadContext) AllM() ([]*M, error) {
D
Derek Parker 已提交
33
	reader := thread.Process.Dwarf.Reader()
34 35 36 37 38

	allmaddr, err := parseAllMPtr(thread.Process, reader)
	if err != nil {
		return nil, err
	}
D
Derek Parker 已提交
39
	mptr, err := thread.readMemory(uintptr(allmaddr), ptrsize)
40 41 42 43 44 45 46 47 48
	if err != nil {
		return nil, err
	}
	m := binary.LittleEndian.Uint64(mptr)
	if m == 0 {
		return nil, fmt.Errorf("allm contains no M pointers")
	}

	// parse addresses
49
	procidInstructions, err := instructionsFor("procid", thread.Process, reader, true)
50 51 52
	if err != nil {
		return nil, err
	}
53
	spinningInstructions, err := instructionsFor("spinning", thread.Process, reader, true)
54 55 56
	if err != nil {
		return nil, err
	}
57
	alllinkInstructions, err := instructionsFor("alllink", thread.Process, reader, true)
58 59 60
	if err != nil {
		return nil, err
	}
61
	blockedInstructions, err := instructionsFor("blocked", thread.Process, reader, true)
62 63 64
	if err != nil {
		return nil, err
	}
65
	curgInstructions, err := instructionsFor("curg", thread.Process, reader, true)
66 67 68 69 70 71 72 73 74 75 76
	if err != nil {
		return nil, err
	}

	var allm []*M
	for {
		// curg
		curgAddr, err := executeMemberStackProgram(mptr, curgInstructions)
		if err != nil {
			return nil, err
		}
D
Derek Parker 已提交
77
		curgBytes, err := thread.readMemory(uintptr(curgAddr), ptrsize)
78 79 80 81 82 83 84 85 86 87
		if err != nil {
			return nil, fmt.Errorf("could not read curg %#v %s", curgAddr, err)
		}
		curg := binary.LittleEndian.Uint64(curgBytes)

		// procid
		procidAddr, err := executeMemberStackProgram(mptr, procidInstructions)
		if err != nil {
			return nil, err
		}
D
Derek Parker 已提交
88
		procidBytes, err := thread.readMemory(uintptr(procidAddr), ptrsize)
89 90 91 92 93 94 95 96 97 98 99 100
		if err != nil {
			return nil, fmt.Errorf("could not read procid %#v %s", procidAddr, err)
		}
		procid := binary.LittleEndian.Uint64(procidBytes)

		// spinning
		spinningAddr, err := executeMemberStackProgram(mptr, spinningInstructions)
		if err != nil {
			return nil, err
		}
		spinBytes, err := thread.readMemory(uintptr(spinningAddr), 1)
		if err != nil {
D
Derek Parker 已提交
101
			return nil, fmt.Errorf("could not read spinning %#v %s", spinningAddr, err)
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
		}

		// blocked
		blockedAddr, err := executeMemberStackProgram(mptr, blockedInstructions)
		if err != nil {
			return nil, err
		}
		blockBytes, err := thread.readMemory(uintptr(blockedAddr), 1)
		if err != nil {
			return nil, fmt.Errorf("could not read blocked %#v %s", blockedAddr, err)
		}

		allm = append(allm, &M{
			procid:   int(procid),
			blocked:  blockBytes[0],
			spinning: spinBytes[0],
			curg:     uintptr(curg),
		})

		// Follow the linked list
		alllinkAddr, err := executeMemberStackProgram(mptr, alllinkInstructions)
		if err != nil {
			return nil, err
		}
D
Derek Parker 已提交
126
		mptr, err = thread.readMemory(uintptr(alllinkAddr), ptrsize)
127 128 129 130 131 132 133 134 135 136 137 138 139
		if err != nil {
			return nil, fmt.Errorf("could not read alllink %#v %s", alllinkAddr, err)
		}
		m = binary.LittleEndian.Uint64(mptr)

		if m == 0 {
			break
		}
	}

	return allm, nil
}

140
func instructionsFor(name string, dbp *DebuggedProcess, reader *dwarf.Reader, member bool) ([]byte, error) {
141
	reader.Seek(0)
142
	entry, err := findDwarfEntry(name, reader, member)
143 144 145
	if err != nil {
		return nil, err
	}
146
	instructions, ok := entry.Val(dwarf.AttrLocation).([]byte)
147
	if !ok {
148 149 150 151 152
		instructions, ok = entry.Val(dwarf.AttrDataMemberLoc).([]byte)
		if !ok {
			return nil, fmt.Errorf("type assertion failed")
		}
		return instructions, nil
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
	}
	return instructions, nil
}

func executeMemberStackProgram(base, instructions []byte) (uint64, error) {
	parentInstructions := append([]byte{op.DW_OP_addr}, base...)
	addr, err := op.ExecuteStackProgram(0, append(parentInstructions, instructions...))
	if err != nil {
		return 0, err
	}

	return uint64(addr), nil
}

func parseAllMPtr(dbp *DebuggedProcess, reader *dwarf.Reader) (uint64, error) {
	entry, err := findDwarfEntry("runtime.allm", reader, false)
	if err != nil {
		return 0, err
	}

	instructions, ok := entry.Val(dwarf.AttrLocation).([]byte)
	if !ok {
		return 0, fmt.Errorf("type assertion failed")
	}
	addr, err := op.ExecuteStackProgram(0, instructions)
	if err != nil {
		return 0, err
	}

	return uint64(addr), nil
}

185
func (dbp *DebuggedProcess) PrintGoroutinesInfo() error {
D
Derek Parker 已提交
186
	reader := dbp.Dwarf.Reader()
187

D
Derek Parker 已提交
188
	allglen, err := allglenval(dbp, reader)
189 190 191
	if err != nil {
		return err
	}
192
	reader.Seek(0)
193
	allgentryaddr, err := addressFor(dbp, "runtime.allg", reader)
194 195 196 197
	if err != nil {
		return err
	}
	fmt.Printf("[%d goroutines]\n", allglen)
D
Derek Parker 已提交
198
	faddr, err := dbp.CurrentThread.readMemory(uintptr(allgentryaddr), ptrsize)
199 200 201
	allg := binary.LittleEndian.Uint64(faddr)

	for i := uint64(0); i < allglen; i++ {
D
Derek Parker 已提交
202
		err = printGoroutineInfo(dbp, allg+(i*uint64(ptrsize)), reader)
203 204 205 206 207 208 209 210
		if err != nil {
			return err
		}
	}

	return nil
}

211
func printGoroutineInfo(dbp *DebuggedProcess, addr uint64, reader *dwarf.Reader) error {
D
Derek Parker 已提交
212
	gaddrbytes, err := dbp.CurrentThread.readMemory(uintptr(addr), ptrsize)
213 214 215
	if err != nil {
		return fmt.Errorf("error derefing *G %s", err)
	}
216
	initialInstructions := append([]byte{op.DW_OP_addr}, gaddrbytes...)
217

218 219
	reader.Seek(0)
	goidaddr, err := offsetFor(dbp, "goid", reader, initialInstructions)
220
	if err != nil {
221 222 223 224 225 226
		return err
	}
	reader.Seek(0)
	schedaddr, err := offsetFor(dbp, "sched", reader, initialInstructions)
	if err != nil {
		return err
227
	}
228

D
Derek Parker 已提交
229
	goidbytes, err := dbp.CurrentThread.readMemory(uintptr(goidaddr), ptrsize)
230 231 232
	if err != nil {
		return fmt.Errorf("error reading goid %s", err)
	}
D
Derek Parker 已提交
233
	schedbytes, err := dbp.CurrentThread.readMemory(uintptr(schedaddr+uint64(ptrsize)), ptrsize)
234 235 236
	if err != nil {
		return fmt.Errorf("error reading sched %s", err)
	}
237
	gopc := binary.LittleEndian.Uint64(schedbytes)
238 239 240 241 242 243
	f, l, fn := dbp.GoSymTable.PCToLine(gopc)
	fname := ""
	if fn != nil {
		fname = fn.Name
	}
	fmt.Printf("Goroutine %d - %s:%d %s\n", binary.LittleEndian.Uint64(goidbytes), f, l, fname)
244 245 246
	return nil
}

D
Derek Parker 已提交
247
func allglenval(dbp *DebuggedProcess, reader *dwarf.Reader) (uint64, error) {
248
	entry, err := findDwarfEntry("runtime.allglen", reader, false)
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	if err != nil {
		return 0, err
	}

	instructions, ok := entry.Val(dwarf.AttrLocation).([]byte)
	if !ok {
		return 0, fmt.Errorf("type assertion failed")
	}
	addr, err := op.ExecuteStackProgram(0, instructions)
	if err != nil {
		return 0, err
	}
	val, err := dbp.CurrentThread.readMemory(uintptr(addr), 8)
	if err != nil {
		return 0, err
	}
	return binary.LittleEndian.Uint64(val), nil
}

268 269
func addressFor(dbp *DebuggedProcess, name string, reader *dwarf.Reader) (uint64, error) {
	entry, err := findDwarfEntry(name, reader, false)
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
	if err != nil {
		return 0, err
	}

	instructions, ok := entry.Val(dwarf.AttrLocation).([]byte)
	if !ok {
		return 0, fmt.Errorf("type assertion failed")
	}
	addr, err := op.ExecuteStackProgram(0, instructions)
	if err != nil {
		return 0, err
	}

	return uint64(addr), nil
}

286 287
func offsetFor(dbp *DebuggedProcess, name string, reader *dwarf.Reader, parentinstr []byte) (uint64, error) {
	entry, err := findDwarfEntry(name, reader, true)
288 289 290 291 292 293 294
	if err != nil {
		return 0, err
	}
	instructions, ok := entry.Val(dwarf.AttrDataMemberLoc).([]byte)
	if !ok {
		return 0, fmt.Errorf("type assertion failed")
	}
295
	offset, err := op.ExecuteStackProgram(0, append(parentinstr, instructions...))
296 297 298 299 300 301 302
	if err != nil {
		return 0, err
	}

	return uint64(offset), nil
}

303 304
// Returns the value of the named symbol.
func (thread *ThreadContext) EvalSymbol(name string) (*Variable, error) {
D
Derek Parker 已提交
305
	data := thread.Process.Dwarf
306

D
Derek Parker 已提交
307 308 309 310
	pc, err := thread.CurrentPC()
	if err != nil {
		return nil, err
	}
311

D
Derek Parker 已提交
312 313 314 315
	fn := thread.Process.GoSymTable.PCToFunc(pc)
	if fn == nil {
		return nil, fmt.Errorf("could not func function scope")
	}
316

D
Derek Parker 已提交
317
	reader := data.Reader()
D
Derek Parker 已提交
318
	if err = seekToFunctionEntry(fn.Name, reader); err != nil {
D
Derek Parker 已提交
319 320
		return nil, err
	}
D
Derek Parker 已提交
321

322 323 324 325 326
	if strings.Contains(name, ".") {
		idx := strings.Index(name, ".")
		return evaluateStructMember(thread, data, reader, name[:idx], name[idx+1:])
	}

327
	entry, err := findDwarfEntry(name, reader, false)
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
	if err != nil {
		return nil, err
	}

	offset, ok := entry.Val(dwarf.AttrType).(dwarf.Offset)
	if !ok {
		return nil, fmt.Errorf("type assertion failed")
	}

	t, err := data.Type(offset)
	if err != nil {
		return nil, err
	}

	instructions, ok := entry.Val(dwarf.AttrLocation).([]byte)
	if !ok {
		return nil, fmt.Errorf("type assertion failed")
	}

	val, err := thread.extractValue(instructions, 0, t)
	if err != nil {
		return nil, err
	}

	return &Variable{Name: name, Type: t.String(), Value: val}, nil
}

D
Derek Parker 已提交
355
// seekToFunctionEntry is basically used to seek the dwarf.Reader to
D
Derek Parker 已提交
356 357 358
// the function entry that represents our current scope. From there
// we can find the first child entry that matches the var name and
// use it to determine the value of the variable.
D
Derek Parker 已提交
359
func seekToFunctionEntry(name string, reader *dwarf.Reader) error {
D
Derek Parker 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
	for entry, err := reader.Next(); entry != nil; entry, err = reader.Next() {
		if err != nil {
			return err
		}

		if entry.Tag != dwarf.TagSubprogram {
			continue
		}

		n, ok := entry.Val(dwarf.AttrName).(string)
		if !ok {
			continue
		}

		if n == name {
			break
		}
	}

	return nil
}
381

382
func findDwarfEntry(name string, reader *dwarf.Reader, member bool) (*dwarf.Entry, error) {
383 384 385 386 387
	for entry, err := reader.Next(); entry != nil; entry, err = reader.Next() {
		if err != nil {
			return nil, err
		}

388 389 390 391 392
		if member {
			if entry.Tag != dwarf.TagMember {
				continue
			}
		} else {
393
			if entry.Tag != dwarf.TagVariable && entry.Tag != dwarf.TagFormalParameter && entry.Tag != dwarf.TagStructType {
394 395
				continue
			}
396 397 398 399 400 401
		}

		n, ok := entry.Val(dwarf.AttrName).(string)
		if !ok || n != name {
			continue
		}
402
		return entry, nil
403 404 405 406
	}
	return nil, fmt.Errorf("could not find symbol value for %s", name)
}

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
func evaluateStructMember(thread *ThreadContext, data *dwarf.Data, reader *dwarf.Reader, parent, member string) (*Variable, error) {
	parentInstr, err := instructionsFor(parent, thread.Process, reader, false)
	if err != nil {
		return nil, err
	}
	memberInstr, err := instructionsFor(member, thread.Process, reader, true)
	if err != nil {
		return nil, err
	}
	reader.Seek(0)
	entry, err := findDwarfEntry(member, reader, true)
	if err != nil {
		return nil, err
	}
	offset, ok := entry.Val(dwarf.AttrType).(dwarf.Offset)
	if !ok {
		return nil, fmt.Errorf("type assertion failed")
	}
	t, err := data.Type(offset)
	if err != nil {
		return nil, err
	}
	val, err := thread.extractValue(append(parentInstr, memberInstr...), 0, t)
	return &Variable{Name: strings.Join([]string{parent, member}, "."), Type: t.String(), Value: val}, nil
}

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
// Extracts the value from the instructions given in the DW_AT_location entry.
// We execute the stack program described in the DW_OP_* instruction stream, and
// then grab the value from the other processes memory.
func (thread *ThreadContext) extractValue(instructions []byte, off int64, typ interface{}) (string, error) {
	regs, err := thread.Registers()
	if err != nil {
		return "", err
	}

	fde, err := thread.Process.FrameEntries.FDEForPC(regs.PC())
	if err != nil {
		return "", err
	}

	fctx := fde.EstablishFrame(regs.PC())
	cfaOffset := fctx.CFAOffset()

	offset := off
	if off == 0 {
		offset, err = op.ExecuteStackProgram(cfaOffset, instructions)
		if err != nil {
			return "", err
		}
456
		offset = int64(regs.SP()) + offset
457 458 459 460 461 462 463 464 465 466 467
	}

	// If we have a user defined type, find the
	// underlying concrete type and use that.
	if tt, ok := typ.(*dwarf.TypedefType); ok {
		typ = tt.Type
	}

	offaddr := uintptr(offset)
	switch t := typ.(type) {
	case *dwarf.PtrType:
D
Derek Parker 已提交
468
		addr, err := thread.readMemory(offaddr, ptrsize)
469 470 471 472 473 474 475 476 477 478 479 480 481 482
		if err != nil {
			return "", err
		}
		adr := binary.LittleEndian.Uint64(addr)
		val, err := thread.extractValue(nil, int64(adr), t.Type)
		if err != nil {
			return "", err
		}

		retstr := fmt.Sprintf("*%s", val)
		return retstr, nil
	case *dwarf.StructType:
		switch t.StructName {
		case "string":
483
			return thread.readString(offaddr, t.ByteSize)
484
		case "[]int":
D
Derek Parker 已提交
485
			return thread.readIntSlice(offaddr, t)
486
		default:
D
Derek Parker 已提交
487
			// Recursively call extractValue to grab
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
			// the value of all the members of the struct.
			fields := make([]string, 0, len(t.Field))
			for _, field := range t.Field {
				val, err := thread.extractValue(nil, field.ByteOffset+offset, field.Type)
				if err != nil {
					return "", err
				}

				fields = append(fields, fmt.Sprintf("%s: %s", field.Name, val))
			}
			retstr := fmt.Sprintf("%s {%s}", t.StructName, strings.Join(fields, ", "))
			return retstr, nil
		}
	case *dwarf.ArrayType:
		return thread.readIntArray(offaddr, t)
	case *dwarf.IntType:
504
		return thread.readInt(offaddr, t.ByteSize)
505
	case *dwarf.FloatType:
D
Derek Parker 已提交
506
		return thread.readFloat(offaddr, t.ByteSize)
507 508 509 510 511
	}

	return "", fmt.Errorf("could not find value for type %s", typ)
}

512 513
func (thread *ThreadContext) readString(addr uintptr, size int64) (string, error) {
	val, err := thread.readMemory(addr, uintptr(size))
514 515 516 517 518 519 520 521 522 523 524 525 526
	if err != nil {
		return "", err
	}

	// deref the pointer to the string
	addr = uintptr(binary.LittleEndian.Uint64(val))
	val, err = thread.readMemory(addr, 16)
	if err != nil {
		return "", err
	}

	i := bytes.IndexByte(val, 0x0)
	val = val[:i]
D
Derek Parker 已提交
527
	return *(*string)(unsafe.Pointer(&val)), nil
528 529
}

D
Derek Parker 已提交
530
func (thread *ThreadContext) readIntSlice(addr uintptr, t *dwarf.StructType) (string, error) {
531 532 533 534 535 536 537 538 539
	val, err := thread.readMemory(addr, uintptr(24))
	if err != nil {
		return "", err
	}

	a := binary.LittleEndian.Uint64(val[:8])
	l := binary.LittleEndian.Uint64(val[8:16])
	c := binary.LittleEndian.Uint64(val[16:24])

D
Derek Parker 已提交
540
	val, err = thread.readMemory(uintptr(a), uintptr(uint64(ptrsize)*l))
541 542 543 544
	if err != nil {
		return "", err
	}

D
Derek Parker 已提交
545 546 547
	switch t.StructName {
	case "[]int":
		members := *(*[]int)(unsafe.Pointer(&val))
D
Derek Parker 已提交
548
		setSliceLength(unsafe.Pointer(&members), int(l))
D
Derek Parker 已提交
549
		return fmt.Sprintf("len: %d cap: %d %d", l, c, members), nil
550
	}
D
Derek Parker 已提交
551
	return "", fmt.Errorf("Could not read slice")
552 553 554 555 556 557 558 559
}

func (thread *ThreadContext) readIntArray(addr uintptr, t *dwarf.ArrayType) (string, error) {
	val, err := thread.readMemory(addr, uintptr(t.ByteSize))
	if err != nil {
		return "", err
	}

D
Derek Parker 已提交
560 561 562
	switch t.Type.Size() {
	case 4:
		members := *(*[]uint32)(unsafe.Pointer(&val))
D
Derek Parker 已提交
563
		setSliceLength(unsafe.Pointer(&members), int(t.Count))
D
Derek Parker 已提交
564
		return fmt.Sprintf("%s %d", t, members), nil
D
Derek Parker 已提交
565 566
	case 8:
		members := *(*[]uint64)(unsafe.Pointer(&val))
D
Derek Parker 已提交
567
		setSliceLength(unsafe.Pointer(&members), int(t.Count))
D
Derek Parker 已提交
568
		return fmt.Sprintf("%s %d", t, members), nil
569
	}
D
Derek Parker 已提交
570
	return "", fmt.Errorf("Could not read array")
571 572
}

573 574 575 576
func (thread *ThreadContext) readInt(addr uintptr, size int64) (string, error) {
	var n int

	val, err := thread.readMemory(addr, uintptr(size))
577 578 579 580
	if err != nil {
		return "", err
	}

581 582 583 584 585 586 587 588 589 590
	switch size {
	case 1:
		n = int(val[0])
	case 2:
		n = int(binary.LittleEndian.Uint16(val))
	case 4:
		n = int(binary.LittleEndian.Uint32(val))
	case 8:
		n = int(binary.LittleEndian.Uint64(val))
	}
591

592
	return strconv.Itoa(n), nil
593 594
}

D
Derek Parker 已提交
595 596
func (thread *ThreadContext) readFloat(addr uintptr, size int64) (string, error) {
	val, err := thread.readMemory(addr, uintptr(size))
597 598 599 600 601
	if err != nil {
		return "", err
	}
	buf := bytes.NewBuffer(val)

D
Derek Parker 已提交
602 603 604 605 606 607 608 609 610 611 612 613
	switch size {
	case 4:
		n := float32(0)
		binary.Read(buf, binary.LittleEndian, &n)
		return strconv.FormatFloat(float64(n), 'f', -1, int(size)*8), nil
	case 8:
		n := float64(0)
		binary.Read(buf, binary.LittleEndian, &n)
		return strconv.FormatFloat(n, 'f', -1, int(size)*8), nil
	}

	return "", fmt.Errorf("could not read float")
614 615 616 617 618
}

func (thread *ThreadContext) readMemory(addr uintptr, size uintptr) ([]byte, error) {
	buf := make([]byte, size)

619
	_, err := readMemory(thread.Id, addr, buf)
620 621 622 623 624 625
	if err != nil {
		return nil, err
	}

	return buf, nil
}
D
Derek Parker 已提交
626 627 628 629

// Sets the length of a slice.
func setSliceLength(ptr unsafe.Pointer, l int) {
	lptr := (*int)(unsafe.Pointer(uintptr(ptr) + ptrsize))
D
Derek Parker 已提交
630
	*lptr = l
D
Derek Parker 已提交
631
}