/
bininfo.go
2435 lines (2130 loc) · 72.2 KB
/
bininfo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
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
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package proc
import (
"bytes"
"debug/dwarf"
"debug/elf"
"debug/macho"
"debug/pe"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"go/ast"
"go/token"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/undoio/delve/pkg/dwarf/frame"
"github.com/undoio/delve/pkg/dwarf/godwarf"
"github.com/undoio/delve/pkg/dwarf/line"
"github.com/undoio/delve/pkg/dwarf/loclist"
"github.com/undoio/delve/pkg/dwarf/op"
"github.com/undoio/delve/pkg/dwarf/reader"
"github.com/undoio/delve/pkg/dwarf/util"
"github.com/undoio/delve/pkg/goversion"
"github.com/undoio/delve/pkg/logflags"
"github.com/undoio/delve/pkg/proc/debuginfod"
"github.com/hashicorp/golang-lru/simplelru"
"github.com/sirupsen/logrus"
)
const (
dwarfGoLanguage = 22 // DW_LANG_Go (from DWARF v5, section 7.12, page 231)
dwarfAttrAddrBase = 0x74 // debug/dwarf.AttrAddrBase in Go 1.14, defined here for compatibility with Go < 1.14
dwarfTreeCacheSize = 512 // size of the dwarfTree cache of each image
)
// BinaryInfo holds information on the binaries being executed (this
// includes both the executable and also any loaded libraries).
type BinaryInfo struct {
// Architecture of this binary.
Arch *Arch
// GOOS operating system this binary is executing on.
GOOS string
debugInfoDirectories []string
// BuildID of this binary.
BuildID string
// 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
// lookupGenericFunc maps function names, with their type parameters removed, to functions.
// Functions that are not generic are not added to this map.
lookupGenericFunc map[string][]*Function
// SymNames maps addr to a description *elf.Symbol of this addr.
SymNames map[uint64]*elf.Symbol
// Images is a list of loaded shared libraries (also known as
// shared objects on linux or DLLs on windows).
Images []*Image
ElfDynamicSection ElfDynamicSection
lastModified time.Time // Time the executable of this process was last modified
// PackageMap maps package names to package paths, needed to lookup types inside DWARF info.
// On Go1.12 this mapping is determined by using the last element of a package path, for example:
// github.com/undoio/delve
// will map to 'delve' because it ends in '/delve'.
// Starting with Go1.13 debug_info will contain a special attribute
// (godwarf.AttrGoPackageName) containing the canonical package name for
// each package.
// If multiple packages have the same name the map entry will have more
// than one item in the slice.
PackageMap map[string][]string
frameEntries frame.FrameDescriptionEntries
types map[string]dwarfRef
packageVars []packageVar // packageVars is a list of all global/package variables in debug_info, sorted by address
gStructOffset uint64
// 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[uint64]nameOfRuntimeTypeEntry
// consts[off] lists all the constants with the type defined at offset off.
consts constantsMap
// inlinedCallLines maps a file:line pair, corresponding to the header line
// of a function to a list of PC addresses where an inlined call to that
// function starts.
inlinedCallLines map[fileLine][]uint64
// dwrapUnwrapCache caches unwrapping of defer wrapper functions (dwrap)
dwrapUnwrapCache map[uint64]*Function
// Go 1.17 register ABI is enabled.
regabi bool
logger *logrus.Entry
}
var (
// ErrCouldNotDetermineRelocation is an error returned when Delve could not determine the base address of a
// position independent executable.
ErrCouldNotDetermineRelocation = errors.New("could not determine the base address of a PIE")
// ErrNoDebugInfoFound is returned when Delve cannot open the debug_info
// section or find an external debug info file.
ErrNoDebugInfoFound = errors.New("could not open debug info")
)
var (
supportedLinuxArch = map[elf.Machine]bool{
elf.EM_X86_64: true,
elf.EM_AARCH64: true,
elf.EM_386: true,
}
supportedWindowsArch = map[_PEMachine]bool{
_IMAGE_FILE_MACHINE_AMD64: true,
}
supportedDarwinArch = map[macho.Cpu]bool{
macho.CpuAmd64: true,
macho.CpuArm64: true,
}
)
// ErrFunctionNotFound is returned when failing to find the
// function named 'FuncName' within the binary.
type ErrFunctionNotFound struct {
FuncName string
}
func (err *ErrFunctionNotFound) Error() string {
return fmt.Sprintf("could not find function %s\n", err.FuncName)
}
// FindFileLocation returns the PC for a given file:line.
// Assumes that `file` is normalized to lower case and '/' on Windows.
func FindFileLocation(p Process, filename string, lineno int) ([]uint64, error) {
// A single file:line can appear in multiple concrete functions, because of
// generics instantiation as well as multiple inlined calls into other
// concrete functions.
// 1. Find all instructions assigned in debug_line to filename:lineno.
bi := p.BinInfo()
fileFound := false
pcs := []line.PCStmt{}
for _, image := range bi.Images {
for _, cu := range image.compileUnits {
if cu.lineInfo == nil || cu.lineInfo.Lookup[filename] == nil {
continue
}
fileFound = true
pcs = append(pcs, cu.lineInfo.LineToPCs(filename, lineno)...)
}
}
if len(pcs) == 0 {
// Check if the line contained a call to a function that was inlined, in
// that case it's possible for the line itself to not appear in debug_line
// at all, but it will still be in debug_info as the call site for an
// inlined subroutine entry.
for _, pc := range bi.inlinedCallLines[fileLine{filename, lineno}] {
pcs = append(pcs, line.PCStmt{PC: pc, Stmt: true})
}
}
if len(pcs) == 0 {
return nil, &ErrCouldNotFindLine{fileFound, filename, lineno}
}
// 2. assign all occurrences of filename:lineno to their containing function
pcByFunc := map[*Function][]line.PCStmt{}
sort.Slice(pcs, func(i, j int) bool { return pcs[i].PC < pcs[j].PC })
var fn *Function
for _, pcstmt := range pcs {
if fn == nil || (pcstmt.PC < fn.Entry) || (pcstmt.PC >= fn.End) {
fn = p.BinInfo().PCToFunc(pcstmt.PC)
}
if fn != nil {
pcByFunc[fn] = append(pcByFunc[fn], pcstmt)
}
}
selectedPCs := []uint64{}
for fn, pcs := range pcByFunc {
// 3. for each concrete function split instruction between the inlined functions it contains
if strings.Contains(fn.Name, "·dwrap·") || fn.trampoline {
// skip autogenerated functions
continue
}
dwtree, err := fn.cu.image.getDwarfTree(fn.offset)
if err != nil {
return nil, fmt.Errorf("loading DWARF for %s@%#x: %v", fn.Name, fn.offset, err)
}
inlrngs := allInlineCallRanges(dwtree)
// findInlRng returns the DWARF offset of the inlined call containing pc.
// If multiple nested inlined calls contain pc the deepest one is returned
// (since allInlineCallRanges returns inlined call by decreasing depth
// this is the first matching entry of the slice).
findInlRng := func(pc uint64) dwarf.Offset {
for _, inlrng := range inlrngs {
if inlrng.rng[0] <= pc && pc < inlrng.rng[1] {
return inlrng.off
}
}
return fn.offset
}
pcsByOff := map[dwarf.Offset][]line.PCStmt{}
for _, pc := range pcs {
off := findInlRng(pc.PC)
pcsByOff[off] = append(pcsByOff[off], pc)
}
// 4. pick the first instruction with stmt set for each inlined call as
// well as the main body of the concrete function. If nothing has
// is_stmt set pick the first instruction instead.
for off, pcs := range pcsByOff {
sort.Slice(pcs, func(i, j int) bool { return pcs[i].PC < pcs[j].PC })
var selectedPC uint64
for _, pc := range pcs {
if pc.Stmt {
selectedPC = pc.PC
break
}
}
if selectedPC == 0 && len(pcs) > 0 {
selectedPC = pcs[0].PC
}
if selectedPC == 0 {
continue
}
// 5. if we picked the entry point of the function, skip it
if off == fn.offset && fn.Entry == selectedPC {
selectedPC, _ = FirstPCAfterPrologue(p, fn, true)
}
selectedPCs = append(selectedPCs, selectedPC)
}
}
sort.Slice(selectedPCs, func(i, j int) bool { return selectedPCs[i] < selectedPCs[j] })
return selectedPCs, nil
}
// inlRnage is the range of an inlined call
type inlRange struct {
off dwarf.Offset
depth uint32
rng [2]uint64
}
// allInlineCallRanges returns all inlined calls contained inside 'tree' in
// reverse nesting order (i.e. the most nested calls are returned first).
// Note that a single inlined call might not have a continuous range of
// addresses and therefore appear multiple times in the returned slice.
func allInlineCallRanges(tree *godwarf.Tree) []inlRange {
r := []inlRange{}
var visit func(*godwarf.Tree, uint32)
visit = func(n *godwarf.Tree, depth uint32) {
if n.Tag == dwarf.TagInlinedSubroutine {
for _, rng := range n.Ranges {
r = append(r, inlRange{off: n.Offset, depth: depth, rng: rng})
}
}
for _, child := range n.Children {
visit(child, depth+1)
}
}
visit(tree, 0)
sort.SliceStable(r, func(i, j int) bool { return r[i].depth > r[j].depth })
return r
}
// FindFunction returns the functions with name funcName.
func (bi *BinaryInfo) FindFunction(funcName string) ([]*Function, error) {
if fn := bi.LookupFunc[funcName]; fn != nil {
return []*Function{fn}, nil
}
fns := bi.LookupGenericFunc()[funcName]
if len(fns) == 0 {
return nil, &ErrFunctionNotFound{funcName}
}
return fns, nil
}
// FindFunctionLocation finds address of a function's line
// If lineOffset is passed FindFunctionLocation will return the address of that line
func FindFunctionLocation(p Process, funcName string, lineOffset int) ([]uint64, error) {
bi := p.BinInfo()
origfns, err := bi.FindFunction(funcName)
if err != nil {
return nil, err
}
if lineOffset > 0 {
fn := origfns[0]
filename, lineno := fn.cu.lineInfo.PCToLine(fn.Entry, fn.Entry)
return FindFileLocation(p, filename, lineno+lineOffset)
}
r := make([]uint64, 0, len(origfns[0].InlinedCalls)+len(origfns))
for _, origfn := range origfns {
if origfn.Entry > 0 {
// add concrete implementation of the function
pc, err := FirstPCAfterPrologue(p, origfn, false)
if err != nil {
return nil, err
}
r = append(r, pc)
}
// add inlined calls to the function
for _, call := range origfn.InlinedCalls {
r = append(r, call.LowPC)
}
if len(r) == 0 {
return nil, &ErrFunctionNotFound{funcName}
}
}
sort.Slice(r, func(i, j int) bool { return r[i] < r[j] })
return r, nil
}
// FirstPCAfterPrologue returns the address of the first
// instruction after the prologue for function fn.
// If sameline is set FirstPCAfterPrologue will always return an
// address associated with the same line as fn.Entry.
func FirstPCAfterPrologue(p Process, fn *Function, sameline bool) (uint64, error) {
pc, _, line, ok := fn.cu.lineInfo.PrologueEndPC(fn.Entry, fn.End)
if ok {
if !sameline {
return pc, nil
}
_, entryLine := fn.cu.lineInfo.PCToLine(fn.Entry, fn.Entry)
if entryLine == line {
return pc, nil
}
}
pc, err := firstPCAfterPrologueDisassembly(p, fn, sameline)
if err != nil {
return fn.Entry, err
}
if pc == fn.Entry {
// Look for the first instruction with the stmt flag set, so that setting a
// breakpoint with file:line and with the function name always result on
// the same instruction being selected.
if pc2, _, _, ok := fn.cu.lineInfo.FirstStmtForLine(fn.Entry, fn.End); ok {
return pc2, nil
}
}
return pc, nil
}
// cpuArch is a stringer interface representing CPU architectures.
type cpuArch interface {
String() string
}
// ErrUnsupportedArch is returned when attempting to debug a binary compiled for an unsupported architecture.
type ErrUnsupportedArch struct {
os string
cpuArch cpuArch
}
func (e *ErrUnsupportedArch) Error() string {
var supportArchs []cpuArch
switch e.os {
case "linux":
for linuxArch := range supportedLinuxArch {
supportArchs = append(supportArchs, linuxArch)
}
case "windows":
for windowArch := range supportedWindowsArch {
supportArchs = append(supportArchs, windowArch)
}
case "darwin":
for darwinArch := range supportedDarwinArch {
supportArchs = append(supportArchs, darwinArch)
}
}
errStr := "unsupported architecture of " + e.os + "/" + e.cpuArch.String()
errStr += " - only"
for _, arch := range supportArchs {
errStr += " " + e.os + "/" + arch.String() + " "
}
if len(supportArchs) == 1 {
errStr += "is supported"
} else {
errStr += "are supported"
}
return errStr
}
type compileUnit struct {
name string // univocal name for non-go compile units
Version uint8 // DWARF version of this compile unit
lowPC uint64
ranges [][2]uint64
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
optimized bool // this compile unit is optimized
producer string // producer attribute
offset dwarf.Offset // offset of the entry describing the compile unit
image *Image // parent image of this compilation unit.
}
type fileLine struct {
file string
line int
}
// dwarfRef is a reference to a Debug Info Entry inside a shared object.
type dwarfRef struct {
imageIndex int
offset dwarf.Offset
}
// InlinedCall represents a concrete inlined call to a function.
type InlinedCall struct {
cu *compileUnit
LowPC, HighPC uint64 // Address range of the generated inlined instructions
}
// 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
trampoline bool // DW_AT_trampoline attribute set to true
// InlinedCalls lists all inlined calls to this function
InlinedCalls []InlinedCall
}
// instRange returns the indexes in fn.Name of the type parameter
// instantiation, which is the position of the outermost '[' and ']'.
// If fn is not an instantiated function both returned values will be len(fn.Name)
func (fn *Function) instRange() [2]int {
d := len(fn.Name)
inst := [2]int{d, d}
if strings.HasPrefix(fn.Name, "type..") {
return inst
}
inst[0] = strings.Index(fn.Name, "[")
if inst[0] < 0 {
inst[0] = d
return inst
}
inst[1] = strings.LastIndex(fn.Name, "]")
if inst[1] < 0 {
inst[0] = d
inst[1] = d
return inst
}
return inst
}
// 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 {
inst := fn.instRange()
return packageName(fn.Name[:inst[0]])
}
func packageName(name string) string {
pathend := strings.LastIndex(name, "/")
if pathend < 0 {
pathend = 0
}
if i := strings.Index(name[pathend:], "."); i != -1 {
return name[:pathend+i]
}
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 {
inst := fn.instRange()
pathend := strings.LastIndex(fn.Name[:inst[0]], "/")
if pathend < 0 {
pathend = 0
}
l := strings.Index(fn.Name[pathend:], ".")
if l == -1 {
return ""
}
if r := strings.LastIndex(fn.Name[inst[1]:], "."); r != -1 && pathend+l != inst[1]+r {
return fn.Name[pathend+l+1 : inst[1]+r]
} else if r := strings.LastIndex(fn.Name[pathend:inst[0]], "."); r != -1 && l != r {
return fn.Name[pathend+l+1 : pathend+r]
}
return ""
}
// BaseName returns the symbol name without the package or receiver name.
// Borrowed from $GOROOT/debug/gosym/symtab.go
func (fn *Function) BaseName() string {
inst := fn.instRange()
if i := strings.LastIndex(fn.Name[inst[1]:], "."); i != -1 {
return fn.Name[inst[1]+i+1:]
} else if i := strings.LastIndex(fn.Name[:inst[0]], "."); i != -1 {
return fn.Name[i+1:]
}
return fn.Name
}
// NameWithoutTypeParams returns the function name without instantiation parameters
func (fn *Function) NameWithoutTypeParams() string {
inst := fn.instRange()
if inst[0] == inst[1] {
return fn.Name
}
return fn.Name[:inst[0]] + fn.Name[inst[1]+1:]
}
// Optimized returns true if the function was optimized by the compiler.
func (fn *Function) Optimized() bool {
return fn.cu.optimized
}
// PrologueEndPC returns the PC just after the function prologue
func (fn *Function) PrologueEndPC() uint64 {
pc, _, _, ok := fn.cu.lineInfo.PrologueEndPC(fn.Entry, fn.End)
if !ok {
return fn.Entry
}
return pc
}
// From $GOROOT/src/runtime/traceback.go:597
// exportedRuntime reports whether the function is an exported runtime function.
// It is only for runtime functions, so ASCII A-Z is fine.
func (fn *Function) exportedRuntime() bool {
name := fn.Name
const n = len("runtime.")
return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
}
// unexportedRuntime reports whether the function is a private runtime function.
func (fn *Function) privateRuntime() bool {
name := fn.Name
const n = len("runtime.")
return len(name) > n && name[:n] == "runtime." && !('A' <= name[n] && name[n] <= 'Z')
}
type constantsMap map[dwarfRef]*constantType
type constantType struct {
initialized bool
values []constantValue
}
type constantValue struct {
name string
fullName string
value int64
singleBit bool
}
// 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
cu *compileUnit
offset dwarf.Offset
addr uint64
}
type buildIDHeader struct {
Namesz uint32
Descsz uint32
Type uint32
}
// 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
}
// NewBinaryInfo returns an initialized but unloaded BinaryInfo struct.
func NewBinaryInfo(goos, goarch string) *BinaryInfo {
r := &BinaryInfo{GOOS: goos, nameOfRuntimeType: make(map[uint64]nameOfRuntimeTypeEntry), logger: logflags.DebuggerLogger()}
// TODO: find better way to determine proc arch (perhaps use executable file info).
switch goarch {
case "386":
r.Arch = I386Arch(goos)
case "amd64":
r.Arch = AMD64Arch(goos)
case "arm64":
r.Arch = ARM64Arch(goos)
}
return r
}
// LoadBinaryInfo will load and store the information from the binary at 'path'.
func (bi *BinaryInfo) LoadBinaryInfo(path string, entryPoint uint64, debugInfoDirs []string) error {
fi, err := os.Stat(path)
if err == nil {
bi.lastModified = fi.ModTime()
}
bi.debugInfoDirectories = debugInfoDirs
return bi.AddImage(path, entryPoint)
}
func loadBinaryInfo(bi *BinaryInfo, image *Image, path string, entryPoint uint64) error {
var wg sync.WaitGroup
defer wg.Wait()
switch bi.GOOS {
case "linux", "freebsd":
return loadBinaryInfoElf(bi, image, path, entryPoint, &wg)
case "windows":
return loadBinaryInfoPE(bi, image, path, entryPoint, &wg)
case "darwin":
return loadBinaryInfoMacho(bi, image, path, entryPoint, &wg)
}
return errors.New("unsupported operating system")
}
// GStructOffset returns the offset of the G
// struct in thread local storage.
func (bi *BinaryInfo) GStructOffset() uint64 {
return bi.gStructOffset
}
// LastModified returns the last modified time of the binary.
func (bi *BinaryInfo) LastModified() time.Time {
return bi.lastModified
}
// DwarfReader returns a reader for the dwarf data
func (so *Image) DwarfReader() *reader.Reader {
return reader.New(so.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.
func (bi *BinaryInfo) PCToLine(pc uint64) (string, int, *Function) {
fn := bi.PCToFunc(pc)
if fn == nil {
return "", 0, nil
}
f, ln := fn.cu.lineInfo.PCToLine(fn.Entry, pc)
return f, ln, fn
}
type ErrCouldNotFindLine struct {
fileFound bool
filename string
lineno int
}
func (err *ErrCouldNotFindLine) Error() string {
if err.fileFound {
return fmt.Sprintf("could not find statement at %s:%d, please use a line with a statement", err.filename, err.lineno)
}
return fmt.Sprintf("could not find file %s", err.filename)
}
// 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 _, image := range bi.Images {
for _, cu := range image.compileUnits {
if cu.lineInfo != nil && cu.lineInfo.Lookup[filename] != nil {
cu.lineInfo.AllPCsForFileLines(filename, r)
}
}
}
return r
}
// PCToFunc returns the concrete function containing the given PC address.
// If the PC address belongs to an inlined call it will return the containing function.
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
}
// PCToImage returns the image containing the given PC address.
func (bi *BinaryInfo) PCToImage(pc uint64) *Image {
fn := bi.PCToFunc(pc)
return bi.funcToImage(fn)
}
// Image represents a loaded library file (shared object on linux, DLL on windows).
type Image struct {
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
loclist2 *loclist.Dwarf2Reader
loclist5 *loclist.Dwarf5Reader
debugAddr *godwarf.DebugAddrSection
debugLineStr []byte
typeCache map[dwarf.Offset]godwarf.Type
compileUnits []*compileUnit // compileUnits is sorted by increasing DWARF offset
dwarfTreeCache *simplelru.LRU
runtimeMallocgcTree *godwarf.Tree // patched version of runtime.mallocgc's DIE
// 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
}
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] = runtimeTypeDIE{entry.Offset, -1}
}
}
}
// 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
}
for _, image := range bi.Images {
if image.Path == path && image.addr == addr {
return nil
}
}
// Actually add the image.
image := &Image{Path: path, addr: addr, typeCache: make(map[dwarf.Offset]godwarf.Type)}
image.dwarfTreeCache, _ = simplelru.NewLRU(dwarfTreeCacheSize, nil)
// 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
}
bi.macOSDebugFrameBugWorkaround()
return err
}
// moduleDataToImage finds the image corresponding to the given module data object.
func (bi *BinaryInfo) moduleDataToImage(md *moduleData) *Image {
fn := bi.PCToFunc(uint64(md.text))
if fn != nil {
return bi.funcToImage(fn)
}
// Try searching for the image with the closest address preceding md.text
var so *Image
for i := range bi.Images {
if int64(bi.Images[i].StaticBase) > int64(md.text) {
continue
}
if so == nil || int64(bi.Images[i].StaticBase) > int64(so.StaticBase) {
so = bi.Images[i]
}
}
return so
}
// 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 != nil && im2.index == image.index {
return &md
}
}
return nil
}
// 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")
// Close closes all internal readers.
func (bi *BinaryInfo) Close() error {
var errs []error
for _, image := range bi.Images {
if err := image.Close(); err != nil {
errs = append(errs, err)
}
}
switch len(errs) {
case 0:
return nil
case 1:
return errs[0]
default:
return errBinaryInfoClose
}
}
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
}
func (image *Image) setLoadError(logger *logrus.Entry, fmtstr string, args ...interface{}) {
image.loadErrMu.Lock()
image.loadErr = fmt.Errorf(fmtstr, args...)
image.loadErrMu.Unlock()
if logger != nil {
logger.Errorf("error loading binary %q: %v", image.Path, image.loadErr)
}
}
// LoadError returns any error incurred while loading this image.
func (image *Image) LoadError() error {
return image.loadErr
}
func (image *Image) getDwarfTree(off dwarf.Offset) (*godwarf.Tree, error) {
if image.runtimeMallocgcTree != nil && off == image.runtimeMallocgcTree.Offset {
return image.runtimeMallocgcTree, nil
}
if r, ok := image.dwarfTreeCache.Get(off); ok {
return r.(*godwarf.Tree), nil
}
r, err := godwarf.LoadTree(off, image.dwarf, image.StaticBase)
if err != nil {
return nil, err
}
image.dwarfTreeCache.Add(off, r)
return r, nil
}
type nilCloser struct{}
func (c *nilCloser) Close() error { return nil }
// LoadImageFromData creates a new Image, using the specified data, and adds it to bi.
// This is used for debugging BinaryInfo, you should use LoadBinary instead.
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)
image.dwarfTreeCache, _ = simplelru.NewLRU(dwarfTreeCacheSize, nil)
if debugFrameBytes != nil {
bi.frameEntries, _ = frame.Parse(debugFrameBytes, frame.DwarfEndian(debugFrameBytes), 0, bi.Arch.PtrSize(), 0)
}
image.loclist2 = loclist.NewDwarf2Reader(debugLocBytes, bi.Arch.PtrSize())
bi.loadDebugInfoMaps(image, nil, debugLineBytes, nil, nil)
bi.Images = append(bi.Images, image)
}
func (bi *BinaryInfo) locationExpr(entry godwarf.Entry, attr dwarf.Attr, pc uint64) ([]byte, *locationExpr, error) {
//TODO(aarzilli): handle DW_FORM_loclistx attribute form new in DWARFv5
a := entry.Val(attr)
if a == nil {
return nil, nil, fmt.Errorf("no location attribute %s", attr)
}
if instr, ok := a.([]byte); ok {
return instr, &locationExpr{isBlock: true, instr: instr}, nil
}
off, ok := a.(int64)
if !ok {
return nil, nil, fmt.Errorf("could not interpret location attribute %s", attr)
}
instr := bi.loclistEntry(off, pc)
if instr == nil {
return nil, nil, fmt.Errorf("could not find loclist entry at %#x for address %#x", off, pc)
}
return instr, &locationExpr{pc: pc, off: off, instr: instr}, nil
}
type locationExpr struct {
isBlock bool
isEscaped bool
off int64
pc uint64
instr []byte
}
func (le *locationExpr) String() string {
if le == nil {