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

import (
	"bytes"
D
Derek Parker 已提交
5
	"debug/dwarf"
6 7 8 9 10 11 12
	"encoding/binary"
	"fmt"
	"strconv"
	"strings"
	"unsafe"

	"github.com/derekparker/delve/dwarf/op"
13
	"github.com/derekparker/delve/dwarf/reader"
14 15 16 17 18 19 20 21
)

type Variable struct {
	Name  string
	Value string
	Type  string
}

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

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

31 32 33
// 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 已提交
34
	reader := thread.Process.Dwarf.Reader()
35 36 37 38 39

	allmaddr, err := parseAllMPtr(thread.Process, reader)
	if err != nil {
		return nil, err
	}
D
Derek Parker 已提交
40
	mptr, err := thread.readMemory(uintptr(allmaddr), ptrsize)
41 42 43 44 45 46 47 48 49
	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
50
	procidInstructions, err := instructionsFor("procid", thread.Process, reader, true)
51 52 53
	if err != nil {
		return nil, err
	}
54
	spinningInstructions, err := instructionsFor("spinning", thread.Process, reader, true)
55 56 57
	if err != nil {
		return nil, err
	}
58
	alllinkInstructions, err := instructionsFor("alllink", thread.Process, reader, true)
59 60 61
	if err != nil {
		return nil, err
	}
62
	blockedInstructions, err := instructionsFor("blocked", thread.Process, reader, true)
63 64 65
	if err != nil {
		return nil, err
	}
66
	curgInstructions, err := instructionsFor("curg", thread.Process, reader, true)
67 68 69 70 71 72 73 74 75 76 77
	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 已提交
78
		curgBytes, err := thread.readMemory(uintptr(curgAddr), ptrsize)
79 80 81 82 83 84 85 86 87 88
		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 已提交
89
		procidBytes, err := thread.readMemory(uintptr(procidAddr), ptrsize)
90 91 92 93 94 95 96 97 98 99 100 101
		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 已提交
102
			return nil, fmt.Errorf("could not read spinning %#v %s", spinningAddr, err)
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
		}

		// 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 已提交
127
		mptr, err = thread.readMemory(uintptr(alllinkAddr), ptrsize)
128 129 130 131 132 133 134 135 136 137 138 139 140
		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
}

141
func instructionsFor(name string, dbp *DebuggedProcess, reader *dwarf.Reader, member bool) ([]byte, error) {
142
	reader.Seek(0)
143
	entry, err := findDwarfEntry(name, reader, member)
144 145 146
	if err != nil {
		return nil, err
	}
147 148 149 150 151 152
	return instructionsForEntry(entry)
}

func instructionsForEntry(entry *dwarf.Entry) ([]byte, error) {
	if entry.Tag == dwarf.TagMember {
		instructions, ok := entry.Val(dwarf.AttrDataMemberLoc).([]byte)
153
		if !ok {
154
			return nil, fmt.Errorf("member data has no data member location attribute")
155
		}
156 157
		// clone slice to prevent stomping on the dwarf data
		return append([]byte{}, instructions...), nil
158
	}
159 160 161 162 163 164 165 166 167

	// non-member
	instructions, ok := entry.Val(dwarf.AttrLocation).([]byte)
	if !ok {
		return nil, fmt.Errorf("entry has no location attribute")
	}

	// clone slice to prevent stomping on the dwarf data
	return append([]byte{}, instructions...), nil
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
}

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
}

198
func (dbp *DebuggedProcess) PrintGoroutinesInfo() error {
D
Derek Parker 已提交
199
	reader := dbp.Dwarf.Reader()
200

D
Derek Parker 已提交
201
	allglen, err := allglenval(dbp, reader)
202 203 204
	if err != nil {
		return err
	}
205
	reader.Seek(0)
206
	allgentryaddr, err := addressFor(dbp, "runtime.allg", reader)
207 208 209 210
	if err != nil {
		return err
	}
	fmt.Printf("[%d goroutines]\n", allglen)
D
Derek Parker 已提交
211
	faddr, err := dbp.CurrentThread.readMemory(uintptr(allgentryaddr), ptrsize)
212 213 214
	allg := binary.LittleEndian.Uint64(faddr)

	for i := uint64(0); i < allglen; i++ {
D
Derek Parker 已提交
215
		err = printGoroutineInfo(dbp, allg+(i*uint64(ptrsize)), reader)
216 217 218 219 220 221 222 223
		if err != nil {
			return err
		}
	}

	return nil
}

224
func printGoroutineInfo(dbp *DebuggedProcess, addr uint64, reader *dwarf.Reader) error {
D
Derek Parker 已提交
225
	gaddrbytes, err := dbp.CurrentThread.readMemory(uintptr(addr), ptrsize)
226 227 228
	if err != nil {
		return fmt.Errorf("error derefing *G %s", err)
	}
229
	initialInstructions := append([]byte{op.DW_OP_addr}, gaddrbytes...)
230

231 232
	reader.Seek(0)
	goidaddr, err := offsetFor(dbp, "goid", reader, initialInstructions)
233
	if err != nil {
234 235 236 237 238 239
		return err
	}
	reader.Seek(0)
	schedaddr, err := offsetFor(dbp, "sched", reader, initialInstructions)
	if err != nil {
		return err
240
	}
241

D
Derek Parker 已提交
242
	goidbytes, err := dbp.CurrentThread.readMemory(uintptr(goidaddr), ptrsize)
243 244 245
	if err != nil {
		return fmt.Errorf("error reading goid %s", err)
	}
D
Derek Parker 已提交
246
	schedbytes, err := dbp.CurrentThread.readMemory(uintptr(schedaddr+uint64(ptrsize)), ptrsize)
247 248 249
	if err != nil {
		return fmt.Errorf("error reading sched %s", err)
	}
250
	gopc := binary.LittleEndian.Uint64(schedbytes)
251 252 253 254 255 256
	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)
257 258 259
	return nil
}

D
Derek Parker 已提交
260
func allglenval(dbp *DebuggedProcess, reader *dwarf.Reader) (uint64, error) {
261
	entry, err := findDwarfEntry("runtime.allglen", reader, false)
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
	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
}

281 282
func addressFor(dbp *DebuggedProcess, name string, reader *dwarf.Reader) (uint64, error) {
	entry, err := findDwarfEntry(name, reader, false)
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	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
}

299 300
func offsetFor(dbp *DebuggedProcess, name string, reader *dwarf.Reader, parentinstr []byte) (uint64, error) {
	entry, err := findDwarfEntry(name, reader, true)
301 302 303 304 305 306 307
	if err != nil {
		return 0, err
	}
	instructions, ok := entry.Val(dwarf.AttrDataMemberLoc).([]byte)
	if !ok {
		return 0, fmt.Errorf("type assertion failed")
	}
308
	offset, err := op.ExecuteStackProgram(0, append(parentinstr, instructions...))
309 310 311 312 313 314 315
	if err != nil {
		return 0, err
	}

	return uint64(offset), nil
}

316 317
// Returns the value of the named symbol.
func (thread *ThreadContext) EvalSymbol(name string) (*Variable, error) {
D
Derek Parker 已提交
318 319 320 321
	pc, err := thread.CurrentPC()
	if err != nil {
		return nil, err
	}
322

323
	reader := thread.Process.DwarfReader()
324

325 326
	_, err = reader.SeekToFunction(pc)
	if err != nil {
D
Derek Parker 已提交
327 328
		return nil, err
	}
D
Derek Parker 已提交
329

330 331
	varName := name
	memberName := ""
332 333
	if strings.Contains(name, ".") {
		idx := strings.Index(name, ".")
334 335
		varName = name[:idx]
		memberName = name[idx+1:]
336 337
	}

338
	for entry, err := reader.NextScopeVariable(); entry != nil; entry, err = reader.NextScopeVariable() {
D
Derek Parker 已提交
339
		if err != nil {
340
			return nil, err
D
Derek Parker 已提交
341 342 343 344 345 346 347
		}

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

348 349 350 351 352
		if n == varName {
			if len(memberName) == 0 {
				return thread.extractVariableFromEntry(entry)
			}
			return thread.evaluateStructMember(entry, reader, memberName)
D
Derek Parker 已提交
353 354 355
		}
	}

356
	return nil, fmt.Errorf("could not find symbol value for %s", name)
D
Derek Parker 已提交
357
}
358

359
func findDwarfEntry(name string, reader *dwarf.Reader, member bool) (*dwarf.Entry, error) {
E
epipho 已提交
360
	depth := 1
361 362 363 364 365
	for entry, err := reader.Next(); entry != nil; entry, err = reader.Next() {
		if err != nil {
			return nil, err
		}

E
epipho 已提交
366 367 368 369 370 371 372 373 374 375 376
		if entry.Children {
			depth++
		}

		if entry.Tag == 0 {
			depth--
			if depth <= 0 {
				return nil, fmt.Errorf("could not find symbol value for %s", name)
			}
		}

377 378 379 380 381
		if member {
			if entry.Tag != dwarf.TagMember {
				continue
			}
		} else {
382
			if entry.Tag != dwarf.TagVariable && entry.Tag != dwarf.TagFormalParameter && entry.Tag != dwarf.TagStructType {
383 384
				continue
			}
385 386 387 388 389 390
		}

		n, ok := entry.Val(dwarf.AttrName).(string)
		if !ok || n != name {
			continue
		}
391
		return entry, nil
392 393 394 395
	}
	return nil, fmt.Errorf("could not find symbol value for %s", name)
}

396
func (thread *ThreadContext) evaluateStructMember(parentEntry *dwarf.Entry, reader *reader.Reader, memberName string) (*Variable, error) {
397
	parentAddr, err := thread.extractVariableDataAddress(parentEntry, reader)
398 399 400
	if err != nil {
		return nil, err
	}
401

D
Derek Parker 已提交
402
	// Get parent variable name
403
	parentName, ok := parentEntry.Val(dwarf.AttrName).(string)
404
	if !ok {
405
		return nil, fmt.Errorf("unable to retrive variable name")
406
	}
407 408

	// Seek reader to the type information so members can be iterated
409
	_, err = reader.SeekToType(parentEntry, true, true)
410 411 412
	if err != nil {
		return nil, err
	}
413 414 415 416 417 418 419 420 421 422 423 424 425

	// Iterate to find member by name
	for memberEntry, err := reader.NextMemberVariable(); memberEntry != nil; memberEntry, err = reader.NextMemberVariable() {
		if err != nil {
			return nil, err
		}

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

		if name == memberName {
D
Derek Parker 已提交
426
			// Nil ptr, wait until here to throw a nil pointer error to prioritize no such member error
427 428 429 430
			if parentAddr == 0 {
				return nil, fmt.Errorf("%s is nil", parentName)
			}

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
			memberInstr, err := instructionsForEntry(memberEntry)
			if err != nil {
				return nil, err
			}

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

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

447 448 449 450 451
			baseAddr := make([]byte, 8)
			binary.LittleEndian.PutUint64(baseAddr, uint64(parentAddr))

			parentInstructions := append([]byte{op.DW_OP_addr}, baseAddr...)
			val, err := thread.extractValue(append(parentInstructions, memberInstr...), 0, t)
452 453 454 455 456 457 458
			if err != nil {
				return nil, err
			}
			return &Variable{Name: strings.Join([]string{parentName, memberName}, "."), Type: t.String(), Value: val}, nil
		}
	}

459
	return nil, fmt.Errorf("%s has no member %s", parentName, memberName)
460 461
}

E
epipho 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
// Extracts the name, type, and value of a variable from a dwarf entry
func (thread *ThreadContext) extractVariableFromEntry(entry *dwarf.Entry) (*Variable, error) {
	if entry == nil {
		return nil, fmt.Errorf("invalid entry")
	}

	if entry.Tag != dwarf.TagFormalParameter && entry.Tag != dwarf.TagVariable {
		return nil, fmt.Errorf("invalid entry tag, only supports FormalParameter and Variable, got %s", entry.Tag.String())
	}

	n, ok := entry.Val(dwarf.AttrName).(string)
	if !ok {
		return nil, fmt.Errorf("type assertion failed")
	}

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

	data := thread.Process.Dwarf
	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: n, Type: t.String(), Value: val}, nil
}

501 502 503 504 505 506
// Execute the stack program taking into account the current stack frame
func (thread *ThreadContext) executeStackProgram(instructions []byte) (int64, error) {
	regs, err := thread.Registers()
	if err != nil {
		return 0, err
	}
507

508 509 510 511 512 513
	fde, err := thread.Process.FrameEntries.FDEForPC(regs.PC())
	if err != nil {
		return 0, err
	}

	fctx := fde.EstablishFrame(regs.PC())
D
Derek Parker 已提交
514 515
	cfa := fctx.CFAOffset() + int64(regs.SP())
	address, err := op.ExecuteStackProgram(cfa, instructions)
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
	if err != nil {
		return 0, err
	}
	return address, nil
}

// Extracts the address of a variable, dereferencing any pointers
func (thread *ThreadContext) extractVariableDataAddress(entry *dwarf.Entry, reader *reader.Reader) (int64, error) {
	instructions, err := instructionsForEntry(entry)
	if err != nil {
		return 0, err
	}

	address, err := thread.executeStackProgram(instructions)
	if err != nil {
		return 0, err
	}

D
Derek Parker 已提交
534
	// Dereference pointers to get down the concrete type
535
	for typeEntry, err := reader.SeekToType(entry, true, false); typeEntry != nil; typeEntry, err = reader.SeekToType(typeEntry, true, false) {
536
		if err != nil {
537
			return 0, err
538 539
		}

540 541 542 543 544 545 546
		if typeEntry.Tag != dwarf.TagPointerType {
			break
		}

		ptraddress := uintptr(address)

		ptr, err := thread.readMemory(ptraddress, ptrsize)
547
		if err != nil {
548
			return 0, err
549
		}
550 551
		address = int64(binary.LittleEndian.Uint64(ptr))
	}
552

553 554
	return address, nil
}
555

556 557 558 559 560 561 562 563
// 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, addr int64, typ interface{}) (string, error) {
	var err error

	if addr == 0 {
		addr, err = thread.executeStackProgram(instructions)
564 565 566 567 568 569 570 571 572 573 574
		if err != nil {
			return "", err
		}
	}

	// 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
	}

575
	ptraddress := uintptr(addr)
576 577
	switch t := typ.(type) {
	case *dwarf.PtrType:
578
		ptr, err := thread.readMemory(ptraddress, ptrsize)
579 580 581
		if err != nil {
			return "", err
		}
582 583 584 585 586 587 588

		intaddr := int64(binary.LittleEndian.Uint64(ptr))
		if intaddr == 0 {
			return fmt.Sprintf("%s nil", t.String()), nil
		}

		val, err := thread.extractValue(nil, intaddr, t.Type)
589 590 591 592
		if err != nil {
			return "", err
		}

593
		return fmt.Sprintf("*%s", val), nil
594 595 596
	case *dwarf.StructType:
		switch t.StructName {
		case "string":
597
			return thread.readString(ptraddress)
598
		case "[]int":
599
			return thread.readIntSlice(ptraddress, t)
600
		default:
D
Derek Parker 已提交
601
			// Recursively call extractValue to grab
602 603 604
			// the value of all the members of the struct.
			fields := make([]string, 0, len(t.Field))
			for _, field := range t.Field {
605
				val, err := thread.extractValue(nil, field.ByteOffset+addr, field.Type)
606 607 608 609 610 611 612 613 614 615
				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:
616
		return thread.readIntArray(ptraddress, t)
617
	case *dwarf.IntType:
618
		return thread.readInt(ptraddress, t.ByteSize)
619
	case *dwarf.FloatType:
620
		return thread.readFloat(ptraddress, t.ByteSize)
621 622 623 624 625
	}

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

626 627 628 629 630 631 632 633 634 635 636 637 638
func (thread *ThreadContext) readString(addr uintptr) (string, error) {
	// string data structure is always two ptrs in size. Addr, followed by len
	// http://research.swtch.com/godata

	// read len
	val, err := thread.readMemory(addr+ptrsize, ptrsize)
	if err != nil {
		return "", err
	}
	strlen := uintptr(binary.LittleEndian.Uint64(val))

	// read addr
	val, err = thread.readMemory(addr, ptrsize)
639 640 641 642
	if err != nil {
		return "", err
	}
	addr = uintptr(binary.LittleEndian.Uint64(val))
D
Derek Parker 已提交
643

644
	val, err = thread.readMemory(addr, strlen)
645 646 647 648
	if err != nil {
		return "", err
	}

D
Derek Parker 已提交
649
	return *(*string)(unsafe.Pointer(&val)), nil
650 651
}

D
Derek Parker 已提交
652
func (thread *ThreadContext) readIntSlice(addr uintptr, t *dwarf.StructType) (string, error) {
653 654 655 656 657 658 659 660 661
	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 已提交
662
	val, err = thread.readMemory(uintptr(a), uintptr(uint64(ptrsize)*l))
663 664 665 666
	if err != nil {
		return "", err
	}

D
Derek Parker 已提交
667 668 669
	switch t.StructName {
	case "[]int":
		members := *(*[]int)(unsafe.Pointer(&val))
D
Derek Parker 已提交
670
		setSliceLength(unsafe.Pointer(&members), int(l))
D
Derek Parker 已提交
671
		return fmt.Sprintf("len: %d cap: %d %d", l, c, members), nil
672
	}
D
Derek Parker 已提交
673
	return "", fmt.Errorf("Could not read slice")
674 675 676 677 678 679 680 681
}

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 已提交
682 683 684
	switch t.Type.Size() {
	case 4:
		members := *(*[]uint32)(unsafe.Pointer(&val))
D
Derek Parker 已提交
685
		setSliceLength(unsafe.Pointer(&members), int(t.Count))
D
Derek Parker 已提交
686
		return fmt.Sprintf("%s %d", t, members), nil
D
Derek Parker 已提交
687 688
	case 8:
		members := *(*[]uint64)(unsafe.Pointer(&val))
D
Derek Parker 已提交
689
		setSliceLength(unsafe.Pointer(&members), int(t.Count))
D
Derek Parker 已提交
690
		return fmt.Sprintf("%s %d", t, members), nil
691
	}
D
Derek Parker 已提交
692
	return "", fmt.Errorf("Could not read array")
693 694
}

695 696 697 698
func (thread *ThreadContext) readInt(addr uintptr, size int64) (string, error) {
	var n int

	val, err := thread.readMemory(addr, uintptr(size))
699 700 701 702
	if err != nil {
		return "", err
	}

703 704 705 706 707 708 709 710 711 712
	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))
	}
713

714
	return strconv.Itoa(n), nil
715 716
}

D
Derek Parker 已提交
717 718
func (thread *ThreadContext) readFloat(addr uintptr, size int64) (string, error) {
	val, err := thread.readMemory(addr, uintptr(size))
719 720 721 722 723
	if err != nil {
		return "", err
	}
	buf := bytes.NewBuffer(val)

D
Derek Parker 已提交
724 725 726 727 728 729 730 731 732 733 734 735
	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")
736 737 738 739 740
}

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

741
	_, err := readMemory(thread.Id, addr, buf)
742 743 744 745 746 747
	if err != nil {
		return nil, err
	}

	return buf, nil
}
D
Derek Parker 已提交
748

E
epipho 已提交
749 750 751 752 753 754 755
// Fetches all variables of a specific type in the current function scope
func (thread *ThreadContext) variablesByTag(tag dwarf.Tag) ([]*Variable, error) {
	pc, err := thread.CurrentPC()
	if err != nil {
		return nil, err
	}

756
	reader := thread.Process.DwarfReader()
E
epipho 已提交
757

758 759
	_, err = reader.SeekToFunction(pc)
	if err != nil {
E
epipho 已提交
760 761 762 763 764
		return nil, err
	}

	vars := make([]*Variable, 0)

765
	for entry, err := reader.NextScopeVariable(); entry != nil; entry, err = reader.NextScopeVariable() {
E
epipho 已提交
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
		if err != nil {
			return nil, err
		}

		if entry.Tag == tag {
			val, err := thread.extractVariableFromEntry(entry)
			if err != nil {
				return nil, err
			}

			vars = append(vars, val)
		}
	}

	return vars, nil
}

// LocalVariables returns all local variables from the current function scope
func (thread *ThreadContext) LocalVariables() ([]*Variable, error) {
	return thread.variablesByTag(dwarf.TagVariable)
}

// FunctionArguments returns the name, value, and type of all current function arguments
func (thread *ThreadContext) FunctionArguments() ([]*Variable, error) {
	return thread.variablesByTag(dwarf.TagFormalParameter)
}

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