bininfo.go 21.1 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 11 12 13
	"errors"
	"fmt"
	"io"
	"os"
14 15
	"sort"
	"strings"
16 17 18 19
	"sync"
	"time"

	"github.com/derekparker/delve/pkg/dwarf/frame"
20
	"github.com/derekparker/delve/pkg/dwarf/godwarf"
21
	"github.com/derekparker/delve/pkg/dwarf/line"
22
	"github.com/derekparker/delve/pkg/dwarf/op"
23 24 25 26 27 28
	"github.com/derekparker/delve/pkg/dwarf/reader"
)

type BinaryInfo struct {
	lastModified time.Time // Time the executable of this process was last modified

29
	GOOS   string
30 31 32 33 34
	closer io.Closer

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

35 36 37
	Arch          Arch
	dwarf         *dwarf.Data
	frameEntries  frame.FrameDescriptionEntries
38
	loclist       loclistReader
39
	compileUnits  []*compileUnit
40
	types         map[string]dwarf.Offset
41
	packageVars   []packageVar // packageVars is a list of all global/package variables in debug_info, sorted by address
42
	gStructOffset uint64
43

44
	// Functions is a list of all DW_TAG_subprogram entries in debug_info, sorted by entry point
45 46 47 48 49 50
	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

51 52
	typeCache map[dwarf.Offset]godwarf.Type

53 54 55
	loadModuleDataOnce sync.Once
	moduleData         []moduleData
	nameOfRuntimeType  map[uintptr]nameOfRuntimeTypeEntry
56

57 58 59
	// consts[off] lists all the constants with the type defined at offset off.
	consts constantsMap

60 61
	loadErrMu sync.Mutex
	loadErr   error
62 63

	dwarfReader *dwarf.Reader
64 65 66 67 68 69
}

var UnsupportedLinuxArchErr = errors.New("unsupported architecture - only linux/amd64 is supported")
var UnsupportedWindowsArchErr = errors.New("unsupported architecture of windows/386 - only windows/amd64 is supported")
var UnsupportedDarwinArchErr = errors.New("unsupported architecture - only darwin/amd64 is supported")

70 71 72 73 74 75 76 77
const dwarfGoLanguage = 22 // DW_LANG_Go (from DWARF v5, section 7.12, page 231)

type compileUnit struct {
	entry         *dwarf.Entry        // debug_info entry describing this compile unit
	isgo          bool                // true if this is the go compile unit
	Name          string              // univocal name for non-go compile units
	lineInfo      *line.DebugLineInfo // debug_line segment associated with this compile unit
	LowPC, HighPC uint64
78
	optimized     bool // this compile unit is optimized
79 80
}

81 82 83 84 85 86 87 88 89 90 91 92 93 94
type partialUnitConstant struct {
	name  string
	typ   dwarf.Offset
	value int64
}

type partialUnit struct {
	entry       *dwarf.Entry
	types       map[string]dwarf.Offset
	variables   []packageVar
	constants   []partialUnitConstant
	functions   []Function
}

95 96 97 98 99 100 101 102 103 104 105 106
// 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 {
107 108 109 110 111
	return packageName(fn.Name)
}

func packageName(name string) string {
	pathend := strings.LastIndex(name, "/")
112 113 114 115
	if pathend < 0 {
		pathend = 0
	}

116 117
	if i := strings.Index(name[pathend:], "."); i != -1 {
		return name[:pathend+i]
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
	}
	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
}

147 148 149 150 151
// Optimized returns true if the function was optimized by the compiler.
func (fn *Function) Optimized() bool {
	return fn.cu.optimized
}

152 153 154 155 156 157 158 159 160 161 162 163 164 165
type constantsMap map[dwarf.Offset]*constantType

type constantType struct {
	initialized bool
	values      []constantValue
}

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

166 167 168 169 170 171 172 173 174
// 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
	offset dwarf.Offset
	addr   uint64
}

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
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
}

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

234
func NewBinaryInfo(goos, goarch string) BinaryInfo {
235
	r := BinaryInfo{GOOS: goos, nameOfRuntimeType: make(map[uintptr]nameOfRuntimeTypeEntry), typeCache: make(map[dwarf.Offset]godwarf.Type)}
236 237 238 239

	// TODO: find better way to determine proc arch (perhaps use executable file info)
	switch goarch {
	case "amd64":
240
		r.Arch = AMD64Arch(goos)
241 242 243 244 245 246 247 248 249 250 251
	}

	return r
}

func (bininfo *BinaryInfo) LoadBinaryInfo(path string, wg *sync.WaitGroup) error {
	fi, err := os.Stat(path)
	if err == nil {
		bininfo.lastModified = fi.ModTime()
	}

252
	switch bininfo.GOOS {
253 254 255 256 257 258 259 260 261 262
	case "linux":
		return bininfo.LoadBinaryInfoElf(path, wg)
	case "windows":
		return bininfo.LoadBinaryInfoPE(path, wg)
	case "darwin":
		return bininfo.LoadBinaryInfoMacho(path, wg)
	}
	return errors.New("unsupported operating system")
}

263 264 265 266 267 268
// GStructOffset returns the offset of the G
// struct in thread local storage.
func (bi *BinaryInfo) GStructOffset() uint64 {
	return bi.gStructOffset
}

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
func (bi *BinaryInfo) LastModified() time.Time {
	return bi.lastModified
}

// DwarfReader returns a reader for the dwarf data
func (bi *BinaryInfo) DwarfReader() *reader.Reader {
	return reader.New(bi.dwarf)
}

// 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.
288 289 290 291 292
func (bi *BinaryInfo) PCToLine(pc uint64) (string, int, *Function) {
	fn := bi.PCToFunc(pc)
	if fn == nil {
		return "", 0, nil
	}
A
aarzilli 已提交
293
	f, ln := fn.cu.lineInfo.PCToLine(fn.Entry, pc)
294
	return f, ln, fn
295 296
}

297
// LineToPC converts a file:line into a memory address.
298 299 300 301 302
func (bi *BinaryInfo) LineToPC(filename string, lineno int) (pc uint64, fn *Function, err error) {
	for _, cu := range bi.compileUnits {
		if cu.lineInfo.Lookup[filename] != nil {
			pc = cu.lineInfo.LineToPC(filename, lineno)
			fn = bi.PCToFunc(pc)
303 304
			if fn != nil {
				return
305 306 307 308 309
			}
		}
	}
	err = fmt.Errorf("could not find %s:%d", filename, lineno)
	return
310 311
}

A
aarzilli 已提交
312 313 314 315 316 317 318 319 320 321 322
// 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
}

323
// PCToFunc returns the function containing the given PC address
324 325 326 327 328 329 330 331 332 333 334 335
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
336 337
}

338 339 340 341
func (bi *BinaryInfo) Close() error {
	return bi.closer.Close()
}

342 343 344 345 346 347 348 349 350 351
func (bi *BinaryInfo) setLoadError(fmtstr string, args ...interface{}) {
	bi.loadErrMu.Lock()
	bi.loadErr = fmt.Errorf(fmtstr, args...)
	bi.loadErrMu.Unlock()
}

func (bi *BinaryInfo) LoadError() error {
	return bi.loadErr
}

352 353 354 355
type nilCloser struct{}

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

356 357 358
// LoadFromData creates a new BinaryInfo object using the specified data.
// This is used for debugging BinaryInfo, you should use LoadBinary instead.
func (bi *BinaryInfo) LoadFromData(dwdata *dwarf.Data, debugFrameBytes, debugLineBytes, debugLocBytes []byte) {
359 360 361 362 363 364 365
	bi.closer = (*nilCloser)(nil)
	bi.dwarf = dwdata

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

366 367 368 369 370 371 372 373 374 375 376 377 378 379
	bi.loclistInit(debugLocBytes)

	bi.loadDebugInfoMaps(debugLineBytes, nil)
}

func (bi *BinaryInfo) loclistInit(data []byte) {
	bi.loclist.data = data
	bi.loclist.ptrSz = bi.Arch.PtrSize()
}

// 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).
380
func (bi *BinaryInfo) Location(entry reader.Entry, attr dwarf.Attr, pc uint64, regs op.DwarfRegisters) (int64, []op.Piece, string, error) {
381 382
	a := entry.Val(attr)
	if a == nil {
383
		return 0, nil, "", fmt.Errorf("no location attribute %s", attr)
384 385
	}
	if instr, ok := a.([]byte); ok {
386 387 388 389 390
		var descr bytes.Buffer
		fmt.Fprintf(&descr, "[block] ")
		op.PrettyPrint(&descr, instr)
		addr, pieces, err := op.ExecuteStackProgram(regs, instr)
		return addr, pieces, descr.String(), err
391 392 393
	}
	off, ok := a.(int64)
	if !ok {
394
		return 0, nil, "", fmt.Errorf("could not interpret location attribute %s", attr)
395 396
	}
	if bi.loclist.data == nil {
397
		return 0, nil, "", fmt.Errorf("could not find loclist entry at %#x for address %#x (no debug_loc section found)", off, pc)
398 399 400
	}
	instr := bi.loclistEntry(off, pc)
	if instr == nil {
401
		return 0, nil, "", fmt.Errorf("could not find loclist entry at %#x for address %#x", off, pc)
402
	}
403 404 405 406 407
	var descr bytes.Buffer
	fmt.Fprintf(&descr, "[%#x:%#x] ", off, pc)
	op.PrettyPrint(&descr, instr)
	addr, pieces, err := op.ExecuteStackProgram(regs, instr)
	return addr, pieces, descr.String(), err
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 433 434 435 436 437 438 439 440
}

// 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
	if cu := bi.findCompileUnit(pc); cu != nil {
		base = cu.LowPC
	}

	bi.loclist.Seek(int(off))
	var e loclistEntry
	for bi.loclist.Next(&e) {
		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 {
		if pc >= cu.LowPC && pc < cu.HighPC {
			return cu
		}
	}
	return nil
441 442
}

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
// ELF ///////////////////////////////////////////////////////////////

func (bi *BinaryInfo) LoadBinaryInfoElf(path string, wg *sync.WaitGroup) error {
	exe, err := os.OpenFile(path, 0, os.ModePerm)
	if err != nil {
		return err
	}
	bi.closer = exe
	elfFile, err := elf.NewFile(exe)
	if err != nil {
		return err
	}
	if elfFile.Machine != elf.EM_X86_64 {
		return UnsupportedLinuxArchErr
	}
	bi.dwarf, err = elfFile.DWARF()
	if err != nil {
		return err
	}

463 464
	bi.dwarfReader = bi.dwarf.Reader()

465 466 467 468
	debugLineBytes, err := getDebugLineInfoElf(elfFile)
	if err != nil {
		return err
	}
469
	bi.loclistInit(getDebugLocElf(elfFile))
470 471

	wg.Add(3)
472
	go bi.parseDebugFrameElf(elfFile, wg)
473
	go bi.loadDebugInfoMaps(debugLineBytes, wg)
474
	go bi.setGStructOffsetElf(elfFile, wg)
475 476 477 478 479 480 481 482 483 484 485 486
	return nil
}

func (bi *BinaryInfo) parseDebugFrameElf(exe *elf.File, wg *sync.WaitGroup) {
	defer wg.Done()

	debugFrameSec := exe.Section(".debug_frame")
	debugInfoSec := exe.Section(".debug_info")

	if debugFrameSec != nil && debugInfoSec != nil {
		debugFrame, err := exe.Section(".debug_frame").Data()
		if err != nil {
487 488
			bi.setLoadError("could not get .debug_frame section: %v", err)
			return
489 490 491
		}
		dat, err := debugInfoSec.Data()
		if err != nil {
492 493
			bi.setLoadError("could not get .debug_frame section: %v", err)
			return
494 495 496
		}
		bi.frameEntries = frame.Parse(debugFrame, frame.DwarfEndian(dat))
	} else {
497 498
		bi.setLoadError("could not find .debug_frame section in binary")
		return
499 500 501
	}
}

502
func getDebugLineInfoElf(exe *elf.File) ([]byte, error) {
503 504 505
	if sec := exe.Section(".debug_line"); sec != nil {
		debugLine, err := exe.Section(".debug_line").Data()
		if err != nil {
506
			return nil, fmt.Errorf("could not get .debug_line section: %v", err)
507
		}
508
		return debugLine, nil
509
	}
510
	return nil, errors.New("could not find .debug_line section in binary")
511 512
}

513 514 515 516 517 518 519 520
func getDebugLocElf(exe *elf.File) []byte {
	if sec := exe.Section(".debug_loc"); sec != nil {
		debugLoc, _ := exe.Section(".debug_loc").Data()
		return debugLoc
	}
	return nil
}

521 522 523 524 525 526 527 528 529 530 531
func (bi *BinaryInfo) setGStructOffsetElf(exe *elf.File, wg *sync.WaitGroup) {
	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 {
532 533
		bi.setLoadError("could not parse ELF symbols: %v", err)
		return
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
	}
	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
		}
	}
	// 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.
	bi.gStructOffset = ^(tls.Memsz) + 1 + tlsg.Value // -tls.Memsz + tlsg.Value
}

559 560 561 562 563 564 565 566 567 568 569
// PE ////////////////////////////////////////////////////////////////

func (bi *BinaryInfo) LoadBinaryInfoPE(path string, wg *sync.WaitGroup) error {
	peFile, closer, err := openExecutablePathPE(path)
	if err != nil {
		return err
	}
	bi.closer = closer
	if peFile.Machine != pe.IMAGE_FILE_MACHINE_AMD64 {
		return UnsupportedWindowsArchErr
	}
570
	bi.dwarf, err = peFile.DWARF()
571 572 573 574
	if err != nil {
		return err
	}

575 576
	bi.dwarfReader = bi.dwarf.Reader()

577 578 579 580
	debugLineBytes, err := getDebugLineInfoPE(peFile)
	if err != nil {
		return err
	}
581
	bi.loclistInit(getDebugLocPE(peFile))
582 583

	wg.Add(2)
584
	go bi.parseDebugFramePE(peFile, wg)
585
	go bi.loadDebugInfoMaps(debugLineBytes, wg)
586 587 588 589 590 591

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

	bi.gStructOffset = 0x28
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
	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
}

func (bi *BinaryInfo) parseDebugFramePE(exe *pe.File, wg *sync.WaitGroup) {
	defer wg.Done()

	debugFrameSec := exe.Section(".debug_frame")
	debugInfoSec := exe.Section(".debug_info")

	if debugFrameSec != nil && debugInfoSec != nil {
		debugFrame, err := debugFrameSec.Data()
		if err != nil && uint32(len(debugFrame)) < debugFrameSec.Size {
617 618
			bi.setLoadError("could not get .debug_frame section: %v", err)
			return
619 620 621 622 623 624
		}
		if 0 < debugFrameSec.VirtualSize && debugFrameSec.VirtualSize < debugFrameSec.Size {
			debugFrame = debugFrame[:debugFrameSec.VirtualSize]
		}
		dat, err := debugInfoSec.Data()
		if err != nil {
625 626
			bi.setLoadError("could not get .debug_info section: %v", err)
			return
627 628 629
		}
		bi.frameEntries = frame.Parse(debugFrame, frame.DwarfEndian(dat))
	} else {
630 631
		bi.setLoadError("could not find .debug_frame section in binary")
		return
632 633 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 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
	}
}

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

// Borrowed from https://golang.org/src/cmd/internal/objfile/pe.go
func loadPETable(f *pe.File, sname, ename string) ([]byte, error) {
	ssym, err := findPESymbol(f, sname)
	if err != nil {
		return nil, err
	}
	esym, err := findPESymbol(f, ename)
	if err != nil {
		return nil, err
	}
	if ssym.SectionNumber != esym.SectionNumber {
		return nil, fmt.Errorf("%s and %s symbols must be in the same section", sname, ename)
	}
	sect := f.Sections[ssym.SectionNumber-1]
	data, err := sect.Data()
	if err != nil {
		return nil, err
	}
	return data[ssym.Value:esym.Value], nil
}

// Borrowed from https://golang.org/src/cmd/internal/objfile/pe.go
func pclnPE(exe *pe.File) (textStart uint64, symtab, pclntab []byte, err error) {
	var imageBase uint64
	switch oh := exe.OptionalHeader.(type) {
	case *pe.OptionalHeader32:
		imageBase = uint64(oh.ImageBase)
	case *pe.OptionalHeader64:
		imageBase = oh.ImageBase
	default:
		return 0, nil, nil, fmt.Errorf("pe file format not recognized")
	}
	if sect := exe.Section(".text"); sect != nil {
		textStart = imageBase + uint64(sect.VirtualAddress)
	}
	if pclntab, err = loadPETable(exe, "runtime.pclntab", "runtime.epclntab"); err != nil {
		// We didn't find the symbols, so look for the names used in 1.3 and earlier.
		// TODO: Remove code looking for the old symbols when we no longer care about 1.3.
		var err2 error
		if pclntab, err2 = loadPETable(exe, "pclntab", "epclntab"); err2 != nil {
			return 0, nil, nil, err
		}
	}
	if symtab, err = loadPETable(exe, "runtime.symtab", "runtime.esymtab"); err != nil {
		// Same as above.
		var err2 error
		if symtab, err2 = loadPETable(exe, "symtab", "esymtab"); err2 != nil {
			return 0, nil, nil, err
		}
	}
	return textStart, symtab, pclntab, nil
}

705
func getDebugLineInfoPE(exe *pe.File) ([]byte, error) {
706 707 708
	if sec := exe.Section(".debug_line"); sec != nil {
		debugLine, err := sec.Data()
		if err != nil && uint32(len(debugLine)) < sec.Size {
709
			return nil, fmt.Errorf("could not get .debug_line section: %v", err)
710 711 712 713
		}
		if 0 < sec.VirtualSize && sec.VirtualSize < sec.Size {
			debugLine = debugLine[:sec.VirtualSize]
		}
714
		return debugLine, nil
715
	}
716
	return nil, errors.New("could not find .debug_line section in binary")
717 718
}

719 720 721 722 723 724 725 726
func getDebugLocPE(exe *pe.File) []byte {
	if sec := exe.Section(".debug_loc"); sec != nil {
		debugLoc, _ := sec.Data()
		return debugLoc
	}
	return nil
}

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
// MACH-O ////////////////////////////////////////////////////////////

func (bi *BinaryInfo) LoadBinaryInfoMacho(path string, wg *sync.WaitGroup) error {
	exe, err := macho.Open(path)
	if err != nil {
		return err
	}
	bi.closer = exe
	if exe.Cpu != macho.CpuAmd64 {
		return UnsupportedDarwinArchErr
	}
	bi.dwarf, err = exe.DWARF()
	if err != nil {
		return err
	}

743 744
	bi.dwarfReader = bi.dwarf.Reader()

745 746 747 748
	debugLineBytes, err := getDebugLineInfoMacho(exe)
	if err != nil {
		return err
	}
749
	bi.loclistInit(getDebugLocMacho(exe))
750 751

	wg.Add(2)
752
	go bi.parseDebugFrameMacho(exe, wg)
753
	go bi.loadDebugInfoMaps(debugLineBytes, wg)
754
	bi.gStructOffset = 0x8a0
755 756 757 758 759 760 761 762 763 764 765 766
	return nil
}

func (bi *BinaryInfo) parseDebugFrameMacho(exe *macho.File, wg *sync.WaitGroup) {
	defer wg.Done()

	debugFrameSec := exe.Section("__debug_frame")
	debugInfoSec := exe.Section("__debug_info")

	if debugFrameSec != nil && debugInfoSec != nil {
		debugFrame, err := exe.Section("__debug_frame").Data()
		if err != nil {
767 768
			bi.setLoadError("could not get __debug_frame section: %v", err)
			return
769 770 771
		}
		dat, err := debugInfoSec.Data()
		if err != nil {
772 773
			bi.setLoadError("could not get .debug_info section: %v", err)
			return
774 775 776
		}
		bi.frameEntries = frame.Parse(debugFrame, frame.DwarfEndian(dat))
	} else {
777 778
		bi.setLoadError("could not find __debug_frame section in binary")
		return
779 780 781
	}
}

782
func getDebugLineInfoMacho(exe *macho.File) ([]byte, error) {
783 784 785
	if sec := exe.Section("__debug_line"); sec != nil {
		debugLine, err := exe.Section("__debug_line").Data()
		if err != nil {
786
			return nil, fmt.Errorf("could not get __debug_line section: %v", err)
787
		}
788
		return debugLine, nil
789
	}
790
	return nil, errors.New("could not find __debug_line section in binary")
791
}
792 793 794 795 796 797 798 799

func getDebugLocMacho(exe *macho.File) []byte {
	if sec := exe.Section("__debug_loc"); sec != nil {
		debugLoc, _ := sec.Data()
		return debugLoc
	}
	return nil
}