bininfo.go 44.9 KB
Newer Older
1 2 3
package proc

import (
4
	"bytes"
5 6 7
	"debug/dwarf"
	"debug/elf"
	"debug/macho"
8
	"debug/pe"
9
	"encoding/binary"
10
	"encoding/hex"
11 12
	"errors"
	"fmt"
13 14
	"go/ast"
	"go/token"
15 16
	"io"
	"os"
17
	"path/filepath"
18
	"reflect"
19
	"sort"
20
	"strconv"
21
	"strings"
22 23 24
	"sync"
	"time"

25 26 27 28 29 30
	"github.com/go-delve/delve/pkg/dwarf/frame"
	"github.com/go-delve/delve/pkg/dwarf/godwarf"
	"github.com/go-delve/delve/pkg/dwarf/line"
	"github.com/go-delve/delve/pkg/dwarf/op"
	"github.com/go-delve/delve/pkg/dwarf/reader"
	"github.com/go-delve/delve/pkg/goversion"
31 32
	"github.com/go-delve/delve/pkg/logflags"
	"github.com/sirupsen/logrus"
33 34
)

35 36
// BinaryInfo holds information on the binaries being executed (this
// includes both the executable and also any loaded libraries).
37
type BinaryInfo struct {
D
Derek Parker 已提交
38 39 40 41 42 43
	// Architecture of this binary.
	Arch Arch

	// GOOS operating system this binary is executing on.
	GOOS string

44 45
	debugInfoDirectories []string

D
Derek Parker 已提交
46 47 48 49 50 51 52
	// Functions is a list of all DW_TAG_subprogram entries in debug_info, sorted by entry point
	Functions []Function
	// Sources is a list of all source files found in debug_line.
	Sources []string
	// LookupFunc maps function names to a description of the function.
	LookupFunc map[string]*Function

53
	// Images is a list of loaded shared libraries (also known as
J
Justin Clift 已提交
54
	// shared objects on linux or DLLs on windows).
55 56 57 58
	Images []*Image

	ElfDynamicSection ElfDynamicSection

59 60
	lastModified time.Time // Time the executable of this process was last modified

61 62
	closer         io.Closer
	sepDebugCloser io.Closer
63 64 65 66

	// Maps package names to package paths, needed to lookup types inside DWARF info
	packageMap map[string]string

D
Derek Parker 已提交
67
	frameEntries frame.FrameDescriptionEntries
68 69 70 71 72

	compileUnits []*compileUnit // compileUnits is sorted by increasing DWARF offset

	types       map[string]dwarfRef
	packageVars []packageVar // packageVars is a list of all global/package variables in debug_info, sorted by address
73

D
Derek Parker 已提交
74
	gStructOffset uint64
75

76 77 78 79
	// nameOfRuntimeType maps an address of a runtime._type struct to its
	// decoded name. Used with versions of Go <= 1.10 to figure out the DIE of
	// the concrete type of interfaces.
	nameOfRuntimeType map[uintptr]nameOfRuntimeTypeEntry
80

81 82
	// consts[off] lists all the constants with the type defined at offset off.
	consts constantsMap
83 84
}

85 86 87 88 89 90 91 92
// ErrUnsupportedLinuxArch is returned when attempting to debug a binary compiled for an unsupported architecture.
var ErrUnsupportedLinuxArch = errors.New("unsupported architecture - only linux/amd64 is supported")

// ErrUnsupportedWindowsArch is returned when attempting to debug a binary compiled for an unsupported architecture.
var ErrUnsupportedWindowsArch = errors.New("unsupported architecture of windows/386 - only windows/amd64 is supported")

// ErrUnsupportedDarwinArch is returned when attempting to debug a binary compiled for an unsupported architecture.
var ErrUnsupportedDarwinArch = errors.New("unsupported architecture - only darwin/amd64 is supported")
93

94 95
// ErrCouldNotDetermineRelocation is an error returned when Delve could not determine the base address of a
// position independant executable.
96 97
var ErrCouldNotDetermineRelocation = errors.New("could not determine the base address of a PIE")

98 99 100
// ErrNoDebugInfoFound is returned when Delve cannot open the debug_info
// section or find an external debug info file.
var ErrNoDebugInfoFound = errors.New("could not open debug info")
101

102 103 104
const dwarfGoLanguage = 22 // DW_LANG_Go (from DWARF v5, section 7.12, page 231)

type compileUnit struct {
105 106 107
	name   string // univocal name for non-go compile units
	lowPC  uint64
	ranges [][2]uint64
108 109 110 111 112 113 114

	entry              *dwarf.Entry        // debug_info entry describing this compile unit
	isgo               bool                // true if this is the go compile unit
	lineInfo           *line.DebugLineInfo // debug_line segment associated with this compile unit
	concreteInlinedFns []inlinedFn         // list of concrete inlined functions within this compile unit
	optimized          bool                // this compile unit is optimized
	producer           string              // producer attribute
115

116
	offset dwarf.Offset // offset of the entry describing the compile unit
117 118 119 120 121 122 123 124

	image *Image // parent image of this compilation unit.
}

// dwarfRef is a reference to a Debug Info Entry inside a shared object.
type dwarfRef struct {
	imageIndex int
	offset     dwarf.Offset
125 126
}

127 128 129 130 131 132 133 134 135 136
// inlinedFn represents a concrete inlined function, e.g.
// an entry for the generated code of an inlined function.
type inlinedFn struct {
	Name          string    // Name of the function that was inlined
	LowPC, HighPC uint64    // Address range of the generated inlined instructions
	CallFile      string    // File of the call site of the inlined function
	CallLine      int64     // Line of the call site of the inlined function
	Parent        *Function // The function that contains this inlined function
}

137 138 139 140 141 142 143 144 145 146 147 148
// Function describes a function in the target program.
type Function struct {
	Name       string
	Entry, End uint64 // same as DW_AT_lowpc and DW_AT_highpc
	offset     dwarf.Offset
	cu         *compileUnit
}

// PackageName returns the package part of the symbol name,
// or the empty string if there is none.
// Borrowed from $GOROOT/debug/gosym/symtab.go
func (fn *Function) PackageName() string {
149 150 151 152 153
	return packageName(fn.Name)
}

func packageName(name string) string {
	pathend := strings.LastIndex(name, "/")
154 155 156 157
	if pathend < 0 {
		pathend = 0
	}

158 159
	if i := strings.Index(name[pathend:], "."); i != -1 {
		return name[:pathend+i]
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 185 186 187 188
	}
	return ""
}

// ReceiverName returns the receiver type name of this symbol,
// or the empty string if there is none.
// Borrowed from $GOROOT/debug/gosym/symtab.go
func (fn *Function) ReceiverName() string {
	pathend := strings.LastIndex(fn.Name, "/")
	if pathend < 0 {
		pathend = 0
	}
	l := strings.Index(fn.Name[pathend:], ".")
	r := strings.LastIndex(fn.Name[pathend:], ".")
	if l == -1 || r == -1 || l == r {
		return ""
	}
	return fn.Name[pathend+l+1 : pathend+r]
}

// BaseName returns the symbol name without the package or receiver name.
// Borrowed from $GOROOT/debug/gosym/symtab.go
func (fn *Function) BaseName() string {
	if i := strings.LastIndex(fn.Name, "."); i != -1 {
		return fn.Name[i+1:]
	}
	return fn.Name
}

189 190 191 192 193
// Optimized returns true if the function was optimized by the compiler.
func (fn *Function) Optimized() bool {
	return fn.cu.optimized
}

194
type constantsMap map[dwarfRef]*constantType
195 196 197 198 199 200 201 202 203 204 205 206 207

type constantType struct {
	initialized bool
	values      []constantValue
}

type constantValue struct {
	name      string
	fullName  string
	value     int64
	singleBit bool
}

208 209 210 211 212
// packageVar represents a package-level variable (or a C global variable).
// If a global variable does not have an address (for example it's stored in
// a register, or non-contiguously) addr will be 0.
type packageVar struct {
	name   string
213
	cu     *compileUnit
214 215 216 217
	offset dwarf.Offset
	addr   uint64
}

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
type loclistReader struct {
	data  []byte
	cur   int
	ptrSz int
}

func (rdr *loclistReader) Seek(off int) {
	rdr.cur = off
}

func (rdr *loclistReader) read(sz int) []byte {
	r := rdr.data[rdr.cur : rdr.cur+sz]
	rdr.cur += sz
	return r
}

func (rdr *loclistReader) oneAddr() uint64 {
	switch rdr.ptrSz {
	case 4:
		addr := binary.LittleEndian.Uint32(rdr.read(rdr.ptrSz))
		if addr == ^uint32(0) {
			return ^uint64(0)
		}
		return uint64(addr)
	case 8:
		addr := uint64(binary.LittleEndian.Uint64(rdr.read(rdr.ptrSz)))
		return addr
	default:
		panic("bad address size")
	}
}

func (rdr *loclistReader) Next(e *loclistEntry) bool {
	e.lowpc = rdr.oneAddr()
	e.highpc = rdr.oneAddr()

	if e.lowpc == 0 && e.highpc == 0 {
		return false
	}

	if e.BaseAddressSelection() {
		e.instr = nil
		return true
	}

	instrlen := binary.LittleEndian.Uint16(rdr.read(2))
	e.instr = rdr.read(int(instrlen))
	return true
}

type loclistEntry struct {
	lowpc, highpc uint64
	instr         []byte
}

273 274 275 276 277
type runtimeTypeDIE struct {
	offset dwarf.Offset
	kind   int64
}

278 279 280 281
func (e *loclistEntry) BaseAddressSelection() bool {
	return e.lowpc == ^uint64(0)
}

282
type buildIDHeader struct {
283 284 285 286 287
	Namesz uint32
	Descsz uint32
	Type   uint32
}

288 289 290 291 292 293
// ElfDynamicSection describes the .dynamic section of an ELF executable.
type ElfDynamicSection struct {
	Addr uint64 // relocated address of where the .dynamic section is mapped in memory
	Size uint64 // size of the .dynamic section of the executable
}

294 295
// NewBinaryInfo returns an initialized but unloaded BinaryInfo struct.
func NewBinaryInfo(goos, goarch string) *BinaryInfo {
296
	r := &BinaryInfo{GOOS: goos, nameOfRuntimeType: make(map[uintptr]nameOfRuntimeTypeEntry)}
297

298
	// TODO: find better way to determine proc arch (perhaps use executable file info).
299 300
	switch goarch {
	case "amd64":
301
		r.Arch = AMD64Arch(goos)
302 303 304 305 306
	}

	return r
}

307
// LoadBinaryInfo will load and store the information from the binary at 'path'.
308
func (bi *BinaryInfo) LoadBinaryInfo(path string, entryPoint uint64, debugInfoDirs []string) error {
309 310
	fi, err := os.Stat(path)
	if err == nil {
311
		bi.lastModified = fi.ModTime()
312 313
	}

314 315 316 317 318 319
	bi.debugInfoDirectories = debugInfoDirs

	return bi.AddImage(path, entryPoint)
}

func loadBinaryInfo(bi *BinaryInfo, image *Image, path string, entryPoint uint64) error {
320 321
	var wg sync.WaitGroup
	defer wg.Wait()
322

323
	switch bi.GOOS {
324
	case "linux", "freebsd":
325
		return loadBinaryInfoElf(bi, image, path, entryPoint, &wg)
326
	case "windows":
327
		return loadBinaryInfoPE(bi, image, path, entryPoint, &wg)
328
	case "darwin":
329
		return loadBinaryInfoMacho(bi, image, path, entryPoint, &wg)
330 331 332 333
	}
	return errors.New("unsupported operating system")
}

334 335 336 337 338 339
// GStructOffset returns the offset of the G
// struct in thread local storage.
func (bi *BinaryInfo) GStructOffset() uint64 {
	return bi.gStructOffset
}

340
// LastModified returns the last modified time of the binary.
341 342 343 344 345
func (bi *BinaryInfo) LastModified() time.Time {
	return bi.lastModified
}

// DwarfReader returns a reader for the dwarf data
346 347
func (so *Image) DwarfReader() *reader.Reader {
	return reader.New(so.dwarf)
348 349 350 351 352 353 354 355 356 357 358 359
}

// Types returns list of types present in the debugged program.
func (bi *BinaryInfo) Types() ([]string, error) {
	types := make([]string, 0, len(bi.types))
	for k := range bi.types {
		types = append(types, k)
	}
	return types, nil
}

// PCToLine converts an instruction address to a file/line/function.
360 361 362 363 364
func (bi *BinaryInfo) PCToLine(pc uint64) (string, int, *Function) {
	fn := bi.PCToFunc(pc)
	if fn == nil {
		return "", 0, nil
	}
A
aarzilli 已提交
365
	f, ln := fn.cu.lineInfo.PCToLine(fn.Entry, pc)
366
	return f, ln, fn
367 368
}

369
// LineToPC converts a file:line into a memory address.
370
func (bi *BinaryInfo) LineToPC(filename string, lineno int) (pc uint64, fn *Function, err error) {
371
	fileFound := false
372 373
	for _, cu := range bi.compileUnits {
		if cu.lineInfo.Lookup[filename] != nil {
374 375
			fileFound = true
			pc := cu.lineInfo.LineToPC(filename, lineno)
376 377 378 379 380
			if pc == 0 {
				// Check to see if this file:line belongs to the call site
				// of an inlined function.
				for _, ifn := range cu.concreteInlinedFns {
					if strings.Contains(ifn.CallFile, filename) && ifn.CallLine == int64(lineno) {
381
						return ifn.LowPC, ifn.Parent, nil
382 383 384
					}
				}
			}
385 386
			if fn := bi.PCToFunc(pc); fn != nil {
				return pc, fn, nil
387 388 389
			}
		}
	}
390 391 392 393 394
	if fileFound {
		return 0, nil, fmt.Errorf("could not find statement at %s:%d, please use a line with a statement", filename, lineno)
	} else {
		return 0, nil, fmt.Errorf("could not find file %s", filename)
	}
395 396
}

A
aarzilli 已提交
397 398 399 400 401 402 403 404 405 406 407
// AllPCsForFileLine returns all PC addresses for the given filename:lineno.
func (bi *BinaryInfo) AllPCsForFileLine(filename string, lineno int) []uint64 {
	r := make([]uint64, 0, 1)
	for _, cu := range bi.compileUnits {
		if cu.lineInfo.Lookup[filename] != nil {
			r = append(r, cu.lineInfo.AllPCsForFileLine(filename, lineno)...)
		}
	}
	return r
}

408 409 410 411 412 413 414 415 416 417 418 419 420 421
// AllPCsForFileLines returns a map providing all PC addresses for filename and each line in linenos
func (bi *BinaryInfo) AllPCsForFileLines(filename string, linenos []int) map[int][]uint64 {
	r := make(map[int][]uint64)
	for _, line := range linenos {
		r[line] = make([]uint64, 0, 1)
	}
	for _, cu := range bi.compileUnits {
		if cu.lineInfo.Lookup[filename] != nil {
			cu.lineInfo.AllPCsForFileLines(filename, r)
		}
	}
	return r
}

422
// PCToFunc returns the function containing the given PC address
423 424 425 426 427 428 429 430 431 432 433 434
func (bi *BinaryInfo) PCToFunc(pc uint64) *Function {
	i := sort.Search(len(bi.Functions), func(i int) bool {
		fn := bi.Functions[i]
		return pc <= fn.Entry || (fn.Entry <= pc && pc < fn.End)
	})
	if i != len(bi.Functions) {
		fn := &bi.Functions[i]
		if fn.Entry <= pc && pc < fn.End {
			return fn
		}
	}
	return nil
435 436
}

437 438
// PCToImage returns the image containing the given PC address.
func (bi *BinaryInfo) PCToImage(pc uint64) *Image {
439 440 441 442
	fn := bi.PCToFunc(pc)
	return bi.funcToImage(fn)
}

443 444
// Image represents a loaded library file (shared object on linux, DLL on windows).
type Image struct {
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
	Path       string
	StaticBase uint64
	addr       uint64

	index int // index of this object in BinaryInfo.SharedObjects

	closer         io.Closer
	sepDebugCloser io.Closer

	dwarf       *dwarf.Data
	dwarfReader *dwarf.Reader
	loclist     loclistReader

	typeCache map[dwarf.Offset]godwarf.Type

	// runtimeTypeToDIE maps between the offset of a runtime._type in
	// runtime.moduledata.types and the offset of the DIE in debug_info. This
	// map is filled by using the extended attribute godwarf.AttrGoRuntimeType
	// which was added in go 1.11.
	runtimeTypeToDIE map[uint64]runtimeTypeDIE

	loadErrMu sync.Mutex
	loadErr   error
468 469
}

470 471 472 473 474 475 476 477
func (image *Image) registerRuntimeTypeToDIE(entry *dwarf.Entry, ardr *reader.Reader) {
	if off, ok := entry.Val(godwarf.AttrGoRuntimeType).(uint64); ok {
		if _, ok := image.runtimeTypeToDIE[off]; !ok {
			image.runtimeTypeToDIE[off+image.StaticBase] = runtimeTypeDIE{entry.Offset, -1}
		}
	}
}

478 479 480 481 482 483 484 485
// AddImage adds the specified image to bi, loading data asynchronously.
// Addr is the relocated entry point for the executable and staticBase (i.e.
// the relocation offset) for all other images.
// The first image added must be the executable file.
func (bi *BinaryInfo) AddImage(path string, addr uint64) error {
	// Check if the image is already present.
	if len(bi.Images) > 0 && !strings.HasPrefix(path, "/") {
		return nil
486 487 488
	}
	for _, image := range bi.Images {
		if image.Path == path && image.addr == addr {
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
			return nil
		}
	}

	// Actually add the image.
	image := &Image{Path: path, addr: addr, typeCache: make(map[dwarf.Offset]godwarf.Type)}
	// add Image regardless of error so that we don't attempt to re-add it every time we stop
	image.index = len(bi.Images)
	bi.Images = append(bi.Images, image)
	err := loadBinaryInfo(bi, image, path, addr)
	if err != nil {
		bi.Images[len(bi.Images)-1].loadErr = err
	}
	return err
}

// moduleDataToImage finds the image corresponding to the given module data object.
func (bi *BinaryInfo) moduleDataToImage(md *moduleData) *Image {
	return bi.funcToImage(bi.PCToFunc(uint64(md.text)))
}

// imageToModuleData finds the module data in mds corresponding to the given image.
func (bi *BinaryInfo) imageToModuleData(image *Image, mds []moduleData) *moduleData {
	for _, md := range mds {
		im2 := bi.moduleDataToImage(&md)
		if im2.index == image.index {
			return &md
516 517
		}
	}
518
	return nil
519 520
}

521 522 523 524 525 526 527
// typeToImage returns the image containing the give type.
func (bi *BinaryInfo) typeToImage(typ godwarf.Type) *Image {
	return bi.Images[typ.Common().Index]
}

var errBinaryInfoClose = errors.New("multiple errors closing executable files")

528
// Close closes all internal readers.
529
func (bi *BinaryInfo) Close() error {
530 531 532 533 534
	var errs []error
	for _, image := range bi.Images {
		if err := image.Close(); err != nil {
			errs = append(errs, err)
		}
535
	}
536 537 538 539 540 541 542
	switch len(errs) {
	case 0:
		return nil
	case 1:
		return errs[0]
	default:
		return errBinaryInfoClose
543
	}
544 545
}

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
func (image *Image) Close() error {
	var err1, err2 error
	if image.sepDebugCloser != nil {
		err := image.sepDebugCloser.Close()
		if err != nil {
			err1 = fmt.Errorf("closing shared object %q (split dwarf): %v", image.Path, err)
		}
	}
	if image.closer != nil {
		err := image.closer.Close()
		if err != nil {
			err2 = fmt.Errorf("closing shared object %q: %v", image.Path, err)
		}
	}
	if err1 != nil && err2 != nil {
		return errBinaryInfoClose
	}
	if err1 != nil {
		return err1
	}
	return err2
567 568
}

569 570 571 572 573 574 575 576 577
func (image *Image) setLoadError(fmtstr string, args ...interface{}) {
	image.loadErrMu.Lock()
	image.loadErr = fmt.Errorf(fmtstr, args...)
	image.loadErrMu.Unlock()
}

// LoadError returns any error incurred while loading this image.
func (image *Image) LoadError() error {
	return image.loadErr
578 579
}

580 581 582 583
type nilCloser struct{}

func (c *nilCloser) Close() error { return nil }

584
// LoadImageFromData creates a new Image, using the specified data, and adds it to bi.
585
// This is used for debugging BinaryInfo, you should use LoadBinary instead.
586 587 588 589 590 591
func (bi *BinaryInfo) LoadImageFromData(dwdata *dwarf.Data, debugFrameBytes, debugLineBytes, debugLocBytes []byte) {
	image := &Image{}
	image.closer = (*nilCloser)(nil)
	image.sepDebugCloser = (*nilCloser)(nil)
	image.dwarf = dwdata
	image.typeCache = make(map[dwarf.Offset]godwarf.Type)
592 593

	if debugFrameBytes != nil {
594
		bi.frameEntries = frame.Parse(debugFrameBytes, frame.DwarfEndian(debugFrameBytes), 0)
595 596
	}

597 598 599
	image.loclistInit(debugLocBytes, bi.Arch.PtrSize())

	bi.loadDebugInfoMaps(image, debugLineBytes, nil, nil)
600

601
	bi.Images = append(bi.Images, image)
602 603
}

604 605 606
func (image *Image) loclistInit(data []byte, ptrSz int) {
	image.loclist.data = data
	image.loclist.ptrSz = ptrSz
607 608
}

609
func (bi *BinaryInfo) locationExpr(entry reader.Entry, attr dwarf.Attr, pc uint64) ([]byte, string, error) {
610 611
	a := entry.Val(attr)
	if a == nil {
612
		return nil, "", fmt.Errorf("no location attribute %s", attr)
613 614
	}
	if instr, ok := a.([]byte); ok {
615 616 617
		var descr bytes.Buffer
		fmt.Fprintf(&descr, "[block] ")
		op.PrettyPrint(&descr, instr)
618
		return instr, descr.String(), nil
619 620 621
	}
	off, ok := a.(int64)
	if !ok {
622
		return nil, "", fmt.Errorf("could not interpret location attribute %s", attr)
623 624 625
	}
	instr := bi.loclistEntry(off, pc)
	if instr == nil {
626
		return nil, "", fmt.Errorf("could not find loclist entry at %#x for address %#x", off, pc)
627
	}
628 629 630
	var descr bytes.Buffer
	fmt.Fprintf(&descr, "[%#x:%#x] ", off, pc)
	op.PrettyPrint(&descr, instr)
631 632 633
	return instr, descr.String(), nil
}

634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
// LocationCovers returns the list of PC addresses that is covered by the
// location attribute 'attr' of entry 'entry'.
func (bi *BinaryInfo) LocationCovers(entry *dwarf.Entry, attr dwarf.Attr) ([][2]uint64, error) {
	a := entry.Val(attr)
	if a == nil {
		return nil, fmt.Errorf("attribute %s not found", attr)
	}
	if _, isblock := a.([]byte); isblock {
		return [][2]uint64{[2]uint64{0, ^uint64(0)}}, nil
	}

	off, ok := a.(int64)
	if !ok {
		return nil, fmt.Errorf("attribute %s of unsupported type %T", attr, a)
	}
	cu := bi.findCompileUnitForOffset(entry.Offset)
	if cu == nil {
		return nil, errors.New("could not find compile unit")
	}

	image := cu.image
	base := cu.lowPC
	if image == nil || image.loclist.data == nil {
		return nil, errors.New("malformed executable")
	}

	r := [][2]uint64{}
	image.loclist.Seek(int(off))
	var e loclistEntry
	for image.loclist.Next(&e) {
		if e.BaseAddressSelection() {
			base = e.highpc
			continue
		}
		r = append(r, [2]uint64{e.lowpc + base, e.highpc + base})
	}
	return r, nil
}

673 674 675 676 677 678 679 680 681
// Location returns the location described by attribute attr of entry.
// This will either be an int64 address or a slice of Pieces for locations
// that don't correspond to a single memory address (registers, composite
// locations).
func (bi *BinaryInfo) Location(entry reader.Entry, attr dwarf.Attr, pc uint64, regs op.DwarfRegisters) (int64, []op.Piece, string, error) {
	instr, descr, err := bi.locationExpr(entry, attr, pc)
	if err != nil {
		return 0, nil, "", err
	}
682
	addr, pieces, err := op.ExecuteStackProgram(regs, instr)
683
	return addr, pieces, descr, err
684 685 686 687 688 689
}

// loclistEntry returns the loclist entry in the loclist starting at off,
// for address pc.
func (bi *BinaryInfo) loclistEntry(off int64, pc uint64) []byte {
	var base uint64
690
	image := bi.Images[0]
691
	if cu := bi.findCompileUnit(pc); cu != nil {
692
		base = cu.lowPC
693 694 695 696
		image = cu.image
	}
	if image == nil || image.loclist.data == nil {
		return nil
697 698
	}

699
	image.loclist.Seek(int(off))
700
	var e loclistEntry
701
	for image.loclist.Next(&e) {
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
		if e.BaseAddressSelection() {
			base = e.highpc
			continue
		}
		if pc >= e.lowpc+base && pc < e.highpc+base {
			return e.instr
		}
	}

	return nil
}

// findCompileUnit returns the compile unit containing address pc.
func (bi *BinaryInfo) findCompileUnit(pc uint64) *compileUnit {
	for _, cu := range bi.compileUnits {
717
		for _, rng := range cu.ranges {
718 719 720
			if pc >= rng[0] && pc < rng[1] {
				return cu
			}
721 722 723 724 725 726
		}
	}
	return nil
}

func (bi *BinaryInfo) findCompileUnitForOffset(off dwarf.Offset) *compileUnit {
727 728 729 730 731
	i := sort.Search(len(bi.compileUnits), func(i int) bool {
		return bi.compileUnits[i].offset >= off
	})
	if i > 0 {
		i--
732
	}
733
	return bi.compileUnits[i]
734 735
}

736
// Producer returns the value of DW_AT_producer.
737 738 739 740 741 742 743 744 745
func (bi *BinaryInfo) Producer() string {
	for _, cu := range bi.compileUnits {
		if cu.isgo && cu.producer != "" {
			return cu.producer
		}
	}
	return ""
}

746
// Type returns the Dwarf type entry at `offset`.
747 748 749 750 751 752 753 754 755 756 757
func (image *Image) Type(offset dwarf.Offset) (godwarf.Type, error) {
	return godwarf.ReadType(image.dwarf, image.index, offset, image.typeCache)
}

// funcToImage returns the Image containing function fn, or the
// executable file as a fallback.
func (bi *BinaryInfo) funcToImage(fn *Function) *Image {
	if fn == nil {
		return bi.Images[0]
	}
	return fn.cu.image
758 759
}

760 761
// ELF ///////////////////////////////////////////////////////////////

762
// ErrNoBuildIDNote is used in openSeparateDebugInfo to signal there's no
763 764
// build-id note on the binary, so LoadBinaryInfoElf will return
// the error message coming from elfFile.DWARF() instead.
765
type ErrNoBuildIDNote struct{}
766

767
func (e *ErrNoBuildIDNote) Error() string {
768 769 770 771 772 773 774 775
	return "can't find build-id note on binary"
}

// openSeparateDebugInfo searches for a file containing the separate
// debug info for the binary using the "build ID" method as described
// in GDB's documentation [1], and if found returns two handles, one
// for the bare file, and another for its corresponding elf.File.
// [1] https://sourceware.org/gdb/onlinedocs/gdb/Separate-Debug-Files.html
776 777 778
//
// Alternatively, if the debug file cannot be found be the build-id, Delve
// will look in directories specified by the debug-info-directories config value.
779
func (bi *BinaryInfo) openSeparateDebugInfo(image *Image, exe *elf.File, debugInfoDirectories []string) (*os.File, *elf.File, error) {
780 781 782 783 784 785 786 787 788 789
	var debugFilePath string
	for _, dir := range debugInfoDirectories {
		var potentialDebugFilePath string
		if strings.Contains(dir, "build-id") {
			desc1, desc2, err := parseBuildID(exe)
			if err != nil {
				continue
			}
			potentialDebugFilePath = fmt.Sprintf("%s/%s/%s.debug", dir, desc1, desc2)
		} else {
790
			potentialDebugFilePath = fmt.Sprintf("%s/%s.debug", dir, filepath.Base(image.Path))
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
		}
		_, err := os.Stat(potentialDebugFilePath)
		if err == nil {
			debugFilePath = potentialDebugFilePath
			break
		}
	}
	if debugFilePath == "" {
		return nil, nil, ErrNoDebugInfoFound
	}
	sepFile, err := os.OpenFile(debugFilePath, 0, os.ModePerm)
	if err != nil {
		return nil, nil, errors.New("can't open separate debug file: " + err.Error())
	}

	elfFile, err := elf.NewFile(sepFile)
	if err != nil {
		sepFile.Close()
		return nil, nil, fmt.Errorf("can't open separate debug file %q: %v", debugFilePath, err.Error())
	}

	if elfFile.Machine != elf.EM_X86_64 {
		sepFile.Close()
		return nil, nil, fmt.Errorf("can't open separate debug file %q: %v", debugFilePath, ErrUnsupportedLinuxArch.Error())
	}

	return sepFile, elfFile, nil
}

func parseBuildID(exe *elf.File) (string, string, error) {
821 822
	buildid := exe.Section(".note.gnu.build-id")
	if buildid == nil {
823
		return "", "", &ErrNoBuildIDNote{}
824 825 826
	}

	br := buildid.Open()
827
	bh := new(buildIDHeader)
828
	if err := binary.Read(br, binary.LittleEndian, bh); err != nil {
829
		return "", "", errors.New("can't read build-id header: " + err.Error())
830 831 832 833
	}

	name := make([]byte, bh.Namesz)
	if err := binary.Read(br, binary.LittleEndian, name); err != nil {
834
		return "", "", errors.New("can't read build-id name: " + err.Error())
835 836 837
	}

	if strings.TrimSpace(string(name)) != "GNU\x00" {
838
		return "", "", errors.New("invalid build-id signature")
839 840 841 842
	}

	descBinary := make([]byte, bh.Descsz)
	if err := binary.Read(br, binary.LittleEndian, descBinary); err != nil {
843
		return "", "", errors.New("can't read build-id desc: " + err.Error())
844 845
	}
	desc := hex.EncodeToString(descBinary)
846
	return desc[:2], desc[2:], nil
847 848
}

849 850
// loadBinaryInfoElf specifically loads information from an ELF binary.
func loadBinaryInfoElf(bi *BinaryInfo, image *Image, path string, addr uint64, wg *sync.WaitGroup) error {
851 852 853 854
	exe, err := os.OpenFile(path, 0, os.ModePerm)
	if err != nil {
		return err
	}
855
	image.closer = exe
856 857 858 859 860
	elfFile, err := elf.NewFile(exe)
	if err != nil {
		return err
	}
	if elfFile.Machine != elf.EM_X86_64 {
861
		return ErrUnsupportedLinuxArch
862
	}
863

864 865 866 867 868 869 870 871 872
	if image.index == 0 {
		// adding executable file:
		// - addr is entryPoint therefore staticBase needs to be calculated by
		//   subtracting the entry point specified in the executable file from addr.
		// - memory address of the .dynamic section needs to be recorded in
		//   BinaryInfo so that we can find loaded libraries.
		if addr != 0 {
			image.StaticBase = addr - elfFile.Entry
		} else if elfFile.Type == elf.ET_DYN {
873 874
			return ErrCouldNotDetermineRelocation
		}
875 876 877 878 879 880
		if dynsec := elfFile.Section(".dynamic"); dynsec != nil {
			bi.ElfDynamicSection.Addr = dynsec.Addr + image.StaticBase
			bi.ElfDynamicSection.Size = dynsec.Size
		}
	} else {
		image.StaticBase = addr
881 882
	}

883
	dwarfFile := elfFile
884

885
	image.dwarf, err = elfFile.DWARF()
886
	if err != nil {
887 888
		var sepFile *os.File
		var serr error
889
		sepFile, dwarfFile, serr = bi.openSeparateDebugInfo(image, elfFile, bi.debugInfoDirectories)
890 891 892
		if serr != nil {
			return serr
		}
893 894
		image.sepDebugCloser = sepFile
		image.dwarf, err = dwarfFile.DWARF()
895 896 897
		if err != nil {
			return err
		}
898 899
	}

900
	image.dwarfReader = image.dwarf.Reader()
901

902
	debugLineBytes, err := godwarf.GetDebugSectionElf(dwarfFile, "line")
903 904 905
	if err != nil {
		return err
	}
906
	debugLocBytes, _ := godwarf.GetDebugSectionElf(dwarfFile, "loc")
907
	image.loclistInit(debugLocBytes, bi.Arch.PtrSize())
908

909 910 911 912 913 914 915 916
	wg.Add(2)
	go bi.parseDebugFrameElf(image, dwarfFile, wg)
	go bi.loadDebugInfoMaps(image, debugLineBytes, wg, nil)
	if image.index == 0 {
		// determine g struct offset only when loading the executable file
		wg.Add(1)
		go bi.setGStructOffsetElf(image, dwarfFile, wg)
	}
917 918 919
	return nil
}

920
func (bi *BinaryInfo) parseDebugFrameElf(image *Image, exe *elf.File, wg *sync.WaitGroup) {
921 922
	defer wg.Done()

923 924
	debugFrameData, err := godwarf.GetDebugSectionElf(exe, "frame")
	if err != nil {
925
		image.setLoadError("could not get .debug_frame section: %v", err)
926
		return
927
	}
928 929
	debugInfoData, err := godwarf.GetDebugSectionElf(exe, "info")
	if err != nil {
930
		image.setLoadError("could not get .debug_info section: %v", err)
931
		return
932 933
	}

934
	bi.frameEntries = bi.frameEntries.Append(frame.Parse(debugFrameData, frame.DwarfEndian(debugInfoData), image.StaticBase))
935 936
}

937
func (bi *BinaryInfo) setGStructOffsetElf(image *Image, exe *elf.File, wg *sync.WaitGroup) {
938 939 940 941 942 943 944 945 946 947
	defer wg.Done()

	// This is a bit arcane. Essentially:
	// - If the program is pure Go, it can do whatever it wants, and puts the G
	//   pointer at %fs-8.
	// - Otherwise, Go asks the external linker to place the G pointer by
	//   emitting runtime.tlsg, a TLS symbol, which is relocated to the chosen
	//   offset in libc's TLS block.
	symbols, err := exe.Symbols()
	if err != nil {
948
		image.setLoadError("could not parse ELF symbols: %v", err)
949
		return
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
	}
	var tlsg *elf.Symbol
	for _, symbol := range symbols {
		if symbol.Name == "runtime.tlsg" {
			s := symbol
			tlsg = &s
			break
		}
	}
	if tlsg == nil {
		bi.gStructOffset = ^uint64(8) + 1 // -8
		return
	}
	var tls *elf.Prog
	for _, prog := range exe.Progs {
		if prog.Type == elf.PT_TLS {
			tls = prog
			break
		}
	}
970 971 972 973
	if tls == nil {
		bi.gStructOffset = ^uint64(8) + 1 // -8
		return
	}
974 975 976
	memsz := tls.Memsz

	memsz = (memsz + uint64(bi.Arch.PtrSize()) - 1) & ^uint64(bi.Arch.PtrSize()-1) // align to pointer-sized-boundary
977 978
	// The TLS register points to the end of the TLS block, which is
	// tls.Memsz long. runtime.tlsg is an offset from the beginning of that block.
979
	bi.gStructOffset = ^(memsz) + 1 + tlsg.Value // -tls.Memsz + tlsg.Value
980 981
}

982 983
// PE ////////////////////////////////////////////////////////////////

984 985
const _IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040

986 987
// loadBinaryInfoPE specifically loads information from a PE binary.
func loadBinaryInfoPE(bi *BinaryInfo, image *Image, path string, entryPoint uint64, wg *sync.WaitGroup) error {
988 989 990 991
	peFile, closer, err := openExecutablePathPE(path)
	if err != nil {
		return err
	}
992
	image.closer = closer
993
	if peFile.Machine != pe.IMAGE_FILE_MACHINE_AMD64 {
994
		return ErrUnsupportedWindowsArch
995
	}
996
	image.dwarf, err = peFile.DWARF()
997 998 999 1000
	if err != nil {
		return err
	}

1001 1002 1003
	//TODO(aarzilli): actually test this when Go supports PIE buildmode on Windows.
	opth := peFile.OptionalHeader.(*pe.OptionalHeader64)
	if entryPoint != 0 {
1004
		image.StaticBase = entryPoint - opth.ImageBase
1005 1006 1007 1008 1009 1010
	} else {
		if opth.DllCharacteristics&_IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE != 0 {
			return ErrCouldNotDetermineRelocation
		}
	}

1011
	image.dwarfReader = image.dwarf.Reader()
1012

1013
	debugLineBytes, err := godwarf.GetDebugSectionPE(peFile, "line")
1014 1015 1016
	if err != nil {
		return err
	}
1017
	debugLocBytes, _ := godwarf.GetDebugSectionPE(peFile, "loc")
1018
	image.loclistInit(debugLocBytes, bi.Arch.PtrSize())
1019 1020

	wg.Add(2)
1021 1022
	go bi.parseDebugFramePE(image, peFile, wg)
	go bi.loadDebugInfoMaps(image, debugLineBytes, wg, nil)
1023 1024 1025 1026 1027 1028

	// Use ArbitraryUserPointer (0x28) as pointer to pointer
	// to G struct per:
	// https://golang.org/src/runtime/cgo/gcc_windows_amd64.c

	bi.gStructOffset = 0x28
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
	return nil
}

func openExecutablePathPE(path string) (*pe.File, io.Closer, error) {
	f, err := os.OpenFile(path, 0, os.ModePerm)
	if err != nil {
		return nil, nil, err
	}
	peFile, err := pe.NewFile(f)
	if err != nil {
		f.Close()
		return nil, nil, err
	}
	return peFile, f, nil
}

1045
func (bi *BinaryInfo) parseDebugFramePE(image *Image, exe *pe.File, wg *sync.WaitGroup) {
1046 1047
	defer wg.Done()

1048 1049
	debugFrameBytes, err := godwarf.GetDebugSectionPE(exe, "frame")
	if err != nil {
1050
		image.setLoadError("could not get .debug_frame section: %v", err)
1051
		return
1052
	}
1053 1054
	debugInfoBytes, err := godwarf.GetDebugSectionPE(exe, "info")
	if err != nil {
1055
		image.setLoadError("could not get .debug_info section: %v", err)
1056 1057 1058
		return
	}

1059
	bi.frameEntries = bi.frameEntries.Append(frame.Parse(debugFrameBytes, frame.DwarfEndian(debugInfoBytes), image.StaticBase))
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
}

// Borrowed from https://golang.org/src/cmd/internal/objfile/pe.go
func findPESymbol(f *pe.File, name string) (*pe.Symbol, error) {
	for _, s := range f.Symbols {
		if s.Name != name {
			continue
		}
		if s.SectionNumber <= 0 {
			return nil, fmt.Errorf("symbol %s: invalid section number %d", name, s.SectionNumber)
		}
		if len(f.Sections) < int(s.SectionNumber) {
			return nil, fmt.Errorf("symbol %s: section number %d is larger than max %d", name, s.SectionNumber, len(f.Sections))
		}
		return s, nil
	}
	return nil, fmt.Errorf("no %s symbol found", name)
}

// MACH-O ////////////////////////////////////////////////////////////

1081 1082
// loadBinaryInfoMacho specifically loads information from a Mach-O binary.
func loadBinaryInfoMacho(bi *BinaryInfo, image *Image, path string, entryPoint uint64, wg *sync.WaitGroup) error {
1083 1084 1085 1086
	exe, err := macho.Open(path)
	if err != nil {
		return err
	}
1087
	image.closer = exe
1088
	if exe.Cpu != macho.CpuAmd64 {
1089
		return ErrUnsupportedDarwinArch
1090
	}
1091
	image.dwarf, err = exe.DWARF()
1092 1093 1094 1095
	if err != nil {
		return err
	}

1096
	image.dwarfReader = image.dwarf.Reader()
1097

1098
	debugLineBytes, err := godwarf.GetDebugSectionMacho(exe, "line")
1099 1100 1101
	if err != nil {
		return err
	}
1102
	debugLocBytes, _ := godwarf.GetDebugSectionMacho(exe, "loc")
1103
	image.loclistInit(debugLocBytes, bi.Arch.PtrSize())
1104 1105

	wg.Add(2)
1106 1107
	go bi.parseDebugFrameMacho(image, exe, wg)
	go bi.loadDebugInfoMaps(image, debugLineBytes, wg, bi.setGStructOffsetMacho)
1108 1109 1110
	return nil
}

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
func (bi *BinaryInfo) setGStructOffsetMacho() {
	// In go1.11 it's 0x30, before 0x8a0, see:
	// https://github.com/golang/go/issues/23617
	// and go commit b3a854c733257c5249c3435ffcee194f8439676a
	producer := bi.Producer()
	if producer != "" && goversion.ProducerAfterOrEqual(producer, 1, 11) {
		bi.gStructOffset = 0x30
		return
	}
	bi.gStructOffset = 0x8a0
}

1123
func (bi *BinaryInfo) parseDebugFrameMacho(image *Image, exe *macho.File, wg *sync.WaitGroup) {
1124 1125
	defer wg.Done()

1126 1127
	debugFrameBytes, err := godwarf.GetDebugSectionMacho(exe, "frame")
	if err != nil {
1128
		image.setLoadError("could not get __debug_frame section: %v", err)
1129
		return
1130
	}
1131 1132
	debugInfoBytes, err := godwarf.GetDebugSectionMacho(exe, "info")
	if err != nil {
1133
		image.setLoadError("could not get .debug_info section: %v", err)
1134
		return
1135
	}
1136

1137
	bi.frameEntries = bi.frameEntries.Append(frame.Parse(debugFrameBytes, frame.DwarfEndian(debugInfoBytes), image.StaticBase))
1138
}
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236

// Do not call this function directly it isn't able to deal correctly with package paths
func (bi *BinaryInfo) findType(name string) (godwarf.Type, error) {
	ref, found := bi.types[name]
	if !found {
		return nil, reader.TypeNotFoundErr
	}
	image := bi.Images[ref.imageIndex]
	return godwarf.ReadType(image.dwarf, ref.imageIndex, ref.offset, image.typeCache)
}

func (bi *BinaryInfo) findTypeExpr(expr ast.Expr) (godwarf.Type, error) {
	if lit, islit := expr.(*ast.BasicLit); islit && lit.Kind == token.STRING {
		// Allow users to specify type names verbatim as quoted
		// string. Useful as a catch-all workaround for cases where we don't
		// parse/serialize types correctly or can not resolve package paths.
		typn, _ := strconv.Unquote(lit.Value)
		return bi.findType(typn)
	}
	bi.expandPackagesInType(expr)
	if snode, ok := expr.(*ast.StarExpr); ok {
		// Pointer types only appear in the dwarf informations when
		// a pointer to the type is used in the target program, here
		// we create a pointer type on the fly so that the user can
		// specify a pointer to any variable used in the target program
		ptyp, err := bi.findTypeExpr(snode.X)
		if err != nil {
			return nil, err
		}
		return pointerTo(ptyp, bi.Arch), nil
	}
	if anode, ok := expr.(*ast.ArrayType); ok {
		// Byte array types (i.e. [N]byte) are only present in DWARF if they are
		// used by the program, but it's convenient to make all of them available
		// to the user so that they can be used to read arbitrary memory, byte by
		// byte.

		alen, litlen := anode.Len.(*ast.BasicLit)
		if litlen && alen.Kind == token.INT {
			n, _ := strconv.Atoi(alen.Value)
			switch exprToString(anode.Elt) {
			case "byte", "uint8":
				btyp, err := bi.findType("uint8")
				if err != nil {
					return nil, err
				}
				return &godwarf.ArrayType{
					CommonType: godwarf.CommonType{
						ReflectKind: reflect.Array,
						ByteSize:    int64(n),
						Name:        fmt.Sprintf("[%d]uint8", n)},
					Type:          btyp,
					StrideBitSize: 8,
					Count:         int64(n)}, nil
			}
		}
	}
	return bi.findType(exprToString(expr))
}

func complexType(typename string) bool {
	for _, ch := range typename {
		switch ch {
		case '*', '[', '<', '{', '(', ' ':
			return true
		}
	}
	return false
}

func (bi *BinaryInfo) registerTypeToPackageMap(entry *dwarf.Entry) {
	if entry.Tag != dwarf.TagTypedef && entry.Tag != dwarf.TagBaseType && entry.Tag != dwarf.TagClassType && entry.Tag != dwarf.TagStructType {
		return
	}

	typename, ok := entry.Val(dwarf.AttrName).(string)
	if !ok || complexType(typename) {
		return
	}

	dot := strings.LastIndex(typename, ".")
	if dot < 0 {
		return
	}
	path := typename[:dot]
	slash := strings.LastIndex(path, "/")
	if slash < 0 || slash+1 >= len(path) {
		return
	}
	name := path[slash+1:]
	bi.packageMap[name] = path
}

func (bi *BinaryInfo) loadDebugInfoMaps(image *Image, debugLineBytes []byte, wg *sync.WaitGroup, cont func()) {
	if wg != nil {
		defer wg.Done()
	}

1237
	if bi.types == nil {
1238
		bi.types = make(map[string]dwarfRef)
1239 1240
	}
	if bi.consts == nil {
1241
		bi.consts = make(map[dwarfRef]*constantType)
1242 1243
	}
	if bi.packageMap == nil {
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
		bi.packageMap = make(map[string]string)
	}
	image.runtimeTypeToDIE = make(map[uint64]runtimeTypeDIE)

	ctxt := newLoadDebugInfoMapsContext(bi, image)

	reader := image.DwarfReader()

	for entry, err := reader.Next(); entry != nil; entry, err = reader.Next() {
		if err != nil {
			image.setLoadError("error reading debug_info: %v", err)
			break
		}
		switch entry.Tag {
		case dwarf.TagCompileUnit:
			cu := &compileUnit{}
			cu.image = image
			cu.entry = entry
			cu.offset = entry.Offset
			if lang, _ := entry.Val(dwarf.AttrLanguage).(int64); lang == dwarfGoLanguage {
				cu.isgo = true
			}
			cu.name, _ = entry.Val(dwarf.AttrName).(string)
			compdir, _ := entry.Val(dwarf.AttrCompDir).(string)
			if compdir != "" {
				cu.name = filepath.Join(compdir, cu.name)
			}
			cu.ranges, _ = image.dwarf.Ranges(entry)
			for i := range cu.ranges {
				cu.ranges[i][0] += image.StaticBase
				cu.ranges[i][1] += image.StaticBase
			}
			if len(cu.ranges) >= 1 {
				cu.lowPC = cu.ranges[0][0]
			}
			lineInfoOffset, _ := entry.Val(dwarf.AttrStmtList).(int64)
			if lineInfoOffset >= 0 && lineInfoOffset < int64(len(debugLineBytes)) {
				var logfn func(string, ...interface{})
				if logflags.DebugLineErrors() {
					logger := logrus.New().WithFields(logrus.Fields{"layer": "dwarf-line"})
					logger.Logger.Level = logrus.DebugLevel
					logfn = func(fmt string, args ...interface{}) {
						logger.Printf(fmt, args)
					}
				}
				cu.lineInfo = line.Parse(compdir, bytes.NewBuffer(debugLineBytes[lineInfoOffset:]), logfn, image.StaticBase)
			}
			cu.producer, _ = entry.Val(dwarf.AttrProducer).(string)
			if cu.isgo && cu.producer != "" {
				semicolon := strings.Index(cu.producer, ";")
				if semicolon < 0 {
					cu.optimized = goversion.ProducerAfterOrEqual(cu.producer, 1, 10)
				} else {
					cu.optimized = !strings.Contains(cu.producer[semicolon:], "-N") || !strings.Contains(cu.producer[semicolon:], "-l")
					cu.producer = cu.producer[:semicolon]
				}
			}
			bi.compileUnits = append(bi.compileUnits, cu)
			if entry.Children {
				bi.loadDebugInfoMapsCompileUnit(ctxt, image, reader, cu)
			}

		case dwarf.TagPartialUnit:
			reader.SkipChildren()

		default:
			// ignore unknown tags
			reader.SkipChildren()
		}
	}

	sort.Sort(compileUnitsByOffset(bi.compileUnits))
	sort.Sort(functionsDebugInfoByEntry(bi.Functions))
	sort.Sort(packageVarsByAddr(bi.packageVars))

	bi.LookupFunc = make(map[string]*Function)
	for i := range bi.Functions {
		bi.LookupFunc[bi.Functions[i].Name] = &bi.Functions[i]
	}

	bi.Sources = []string{}
	for _, cu := range bi.compileUnits {
		if cu.lineInfo != nil {
			for _, fileEntry := range cu.lineInfo.FileNames {
				bi.Sources = append(bi.Sources, fileEntry.Path)
			}
		}
	}
	sort.Strings(bi.Sources)
	bi.Sources = uniq(bi.Sources)

	if cont != nil {
		cont()
	}
}

// loadDebugInfoMapsCompileUnit loads entry from a single compile unit.
func (bi *BinaryInfo) loadDebugInfoMapsCompileUnit(ctxt *loadDebugInfoMapsContext, image *Image, reader *reader.Reader, cu *compileUnit) {
	for entry, err := reader.Next(); entry != nil; entry, err = reader.Next() {
		if err != nil {
			image.setLoadError("error reading debug_info: %v", err)
			return
		}
		switch entry.Tag {
		case 0:
			return
		case dwarf.TagImportedUnit:
			bi.loadDebugInfoMapsImportedUnit(entry, ctxt, image, cu)
			reader.SkipChildren()

		case dwarf.TagArrayType, dwarf.TagBaseType, dwarf.TagClassType, dwarf.TagStructType, dwarf.TagUnionType, dwarf.TagConstType, dwarf.TagVolatileType, dwarf.TagRestrictType, dwarf.TagEnumerationType, dwarf.TagPointerType, dwarf.TagSubroutineType, dwarf.TagTypedef, dwarf.TagUnspecifiedType:
			if name, ok := entry.Val(dwarf.AttrName).(string); ok {
				if !cu.isgo {
					name = "C." + name
				}
				if _, exists := bi.types[name]; !exists {
					bi.types[name] = dwarfRef{image.index, entry.Offset}
				}
			}
			if cu != nil && cu.isgo {
				bi.registerTypeToPackageMap(entry)
			}
			image.registerRuntimeTypeToDIE(entry, ctxt.ardr)
			reader.SkipChildren()

		case dwarf.TagVariable:
			if n, ok := entry.Val(dwarf.AttrName).(string); ok {
				var addr uint64
				if loc, ok := entry.Val(dwarf.AttrLocation).([]byte); ok {
					if len(loc) == bi.Arch.PtrSize()+1 && op.Opcode(loc[0]) == op.DW_OP_addr {
						addr = binary.LittleEndian.Uint64(loc[1:])
					}
				}
				if !cu.isgo {
					n = "C." + n
				}
				if _, known := ctxt.knownPackageVars[n]; !known {
					bi.packageVars = append(bi.packageVars, packageVar{n, cu, entry.Offset, addr + image.StaticBase})
				}
			}
			reader.SkipChildren()

		case dwarf.TagConstant:
			name, okName := entry.Val(dwarf.AttrName).(string)
			typ, okType := entry.Val(dwarf.AttrType).(dwarf.Offset)
			val, okVal := entry.Val(dwarf.AttrConstValue).(int64)
			if okName && okType && okVal {
				if !cu.isgo {
					name = "C." + name
				}
				ct := bi.consts[dwarfRef{image.index, typ}]
				if ct == nil {
					ct = &constantType{}
					bi.consts[dwarfRef{image.index, typ}] = ct
				}
				ct.values = append(ct.values, constantValue{name: name, fullName: name, value: val})
			}
			reader.SkipChildren()

		case dwarf.TagSubprogram:
			ok1 := false
			inlined := false
			var lowpc, highpc uint64
			if inval, ok := entry.Val(dwarf.AttrInline).(int64); ok {
				inlined = inval == 1
			}
			if ranges, _ := image.dwarf.Ranges(entry); len(ranges) == 1 {
				ok1 = true
				lowpc = ranges[0][0] + image.StaticBase
				highpc = ranges[0][1] + image.StaticBase
			}
			name, ok2 := entry.Val(dwarf.AttrName).(string)
			if !ok2 {
				originOffset, hasAbstractOrigin := entry.Val(dwarf.AttrAbstractOrigin).(dwarf.Offset)
				if hasAbstractOrigin {
					name, ok2 = ctxt.abstractOriginNameTable[originOffset]
				}
			}

			var fn Function
			if (ok1 == !inlined) && ok2 {
				if inlined {
					ctxt.abstractOriginNameTable[entry.Offset] = name
				}
				if !cu.isgo {
					name = "C." + name
				}
				fn = Function{
					Name:  name,
					Entry: lowpc, End: highpc,
					offset: entry.Offset,
					cu:     cu,
				}
				bi.Functions = append(bi.Functions, fn)
			}
			if entry.Children {
				for {
					entry, err = reader.Next()
					if err != nil {
						image.setLoadError("error reading debug_info: %v", err)
						return
					}
					if entry.Tag == 0 {
						break
					}
					if entry.Tag == dwarf.TagInlinedSubroutine && entry.Val(dwarf.AttrAbstractOrigin) != nil {
						originOffset := entry.Val(dwarf.AttrAbstractOrigin).(dwarf.Offset)
						name := ctxt.abstractOriginNameTable[originOffset]
						if ranges, _ := image.dwarf.Ranges(entry); len(ranges) == 1 {
							ok1 = true
							lowpc = ranges[0][0]
							highpc = ranges[0][1]
						}
						callfileidx, ok1 := entry.Val(dwarf.AttrCallFile).(int64)
						callline, ok2 := entry.Val(dwarf.AttrCallLine).(int64)
						if ok1 && ok2 {
							callfile := cu.lineInfo.FileNames[callfileidx-1].Path
							cu.concreteInlinedFns = append(cu.concreteInlinedFns, inlinedFn{
								Name:     name,
								LowPC:    lowpc + image.StaticBase,
								HighPC:   highpc + image.StaticBase,
								CallFile: callfile,
								CallLine: callline,
								Parent:   &fn,
							})
						}
					}
					reader.SkipChildren()
				}
			}
		}
	}
}

// loadDebugInfoMapsImportedUnit loads entries into cu from the partial unit
// referenced in a DW_TAG_imported_unit entry.
func (bi *BinaryInfo) loadDebugInfoMapsImportedUnit(entry *dwarf.Entry, ctxt *loadDebugInfoMapsContext, image *Image, cu *compileUnit) {
	off, ok := entry.Val(dwarf.AttrImport).(dwarf.Offset)
	if !ok {
		return
	}
	reader := image.DwarfReader()
	reader.Seek(off)
	imentry, err := reader.Next()
	if err != nil {
		return
	}
	if imentry.Tag != dwarf.TagPartialUnit {
		return
	}
	bi.loadDebugInfoMapsCompileUnit(ctxt, image, reader, cu)
}

func uniq(s []string) []string {
	if len(s) <= 0 {
		return s
	}
	src, dst := 1, 1
	for src < len(s) {
		if s[src] != s[dst-1] {
			s[dst] = s[src]
			dst++
		}
		src++
	}
	return s[:dst]
}

func (bi *BinaryInfo) expandPackagesInType(expr ast.Expr) {
	switch e := expr.(type) {
	case *ast.ArrayType:
		bi.expandPackagesInType(e.Elt)
	case *ast.ChanType:
		bi.expandPackagesInType(e.Value)
	case *ast.FuncType:
		for i := range e.Params.List {
			bi.expandPackagesInType(e.Params.List[i].Type)
		}
		if e.Results != nil {
			for i := range e.Results.List {
				bi.expandPackagesInType(e.Results.List[i].Type)
			}
		}
	case *ast.MapType:
		bi.expandPackagesInType(e.Key)
		bi.expandPackagesInType(e.Value)
	case *ast.ParenExpr:
		bi.expandPackagesInType(e.X)
	case *ast.SelectorExpr:
		switch x := e.X.(type) {
		case *ast.Ident:
			if path, ok := bi.packageMap[x.Name]; ok {
				x.Name = path
			}
		default:
			bi.expandPackagesInType(e.X)
		}
	case *ast.StarExpr:
		bi.expandPackagesInType(e.X)
	default:
		// nothing to do
	}
}

// Looks up symbol (either functions or global variables) at address addr.
// Used by disassembly formatter.
func (bi *BinaryInfo) symLookup(addr uint64) (string, uint64) {
	fn := bi.PCToFunc(addr)
	if fn != nil {
		if fn.Entry == addr {
			// only report the function name if it's the exact address because it's
			// easier to read the absolute address than function_name+offset.
			return fn.Name, fn.Entry
		}
		return "", 0
	}
	i := sort.Search(len(bi.packageVars), func(i int) bool {
		return bi.packageVars[i].addr >= addr
	})
	if i >= len(bi.packageVars) {
		return "", 0
	}
	if bi.packageVars[i].addr > addr {
		// report previous variable + offset if i-th variable starts after addr
		i--
	}
	if i > 0 {
		return bi.packageVars[i].name, bi.packageVars[i].addr
	}
	return "", 0
}