/
variables.go
2535 lines (2251 loc) · 70.2 KB
/
variables.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"
"encoding/binary"
"errors"
"fmt"
"go/constant"
"go/token"
"math"
"reflect"
"sort"
"strconv"
"strings"
"time"
"unsafe"
"github.com/undoio/delve/pkg/dwarf/godwarf"
"github.com/undoio/delve/pkg/dwarf/op"
"github.com/undoio/delve/pkg/goversion"
"github.com/undoio/delve/pkg/logflags"
)
const (
maxErrCount = 3 // Max number of read errors to accept while evaluating slices, arrays and structs
maxArrayStridePrefetch = 1024 // Maximum size of array stride for which we will prefetch the array contents
// hashTophashEmptyZero is used by map reading code, indicates an empty cell
hashTophashEmptyZero = 0 // +rtype emptyRest
// hashTophashEmptyOne is used by map reading code, indicates an empty cell in Go 1.12 and later
hashTophashEmptyOne = 1 // +rtype emptyOne
// hashMinTopHashGo111 used by map reading code, indicates minimum value of tophash that isn't empty or evacuated, in Go1.11
hashMinTopHashGo111 = 4 // +rtype minTopHash
// hashMinTopHashGo112 is used by map reading code, indicates minimum value of tophash that isn't empty or evacuated, in Go1.12
hashMinTopHashGo112 = 5 // +rtype minTopHash
maxFramePrefetchSize = 1 * 1024 * 1024 // Maximum prefetch size for a stack frame
maxMapBucketsFactor = 100 // Maximum numbers of map buckets to read for every requested map entry when loading variables through (*EvalScope).LocalVariables and (*EvalScope).FunctionArguments.
maxGoroutineUserCurrentDepth = 30 // Maximum depth used by (*G).UserCurrent to search its location
)
type floatSpecial uint8
const (
// FloatIsNormal means the value is a normal float.
FloatIsNormal floatSpecial = iota
// FloatIsNaN means the float is a special NaN value.
FloatIsNaN
// FloatIsPosInf means the float is a special positive inifitiy value.
FloatIsPosInf
// FloatIsNegInf means the float is a special negative infinity value.
FloatIsNegInf
)
type variableFlags uint16
const (
// VariableEscaped is set for local variables that escaped to the heap
//
// The compiler performs escape analysis on local variables, the variables
// that may outlive the stack frame are allocated on the heap instead and
// only the address is recorded on the stack. These variables will be
// marked with this flag.
VariableEscaped variableFlags = (1 << iota)
// VariableShadowed is set for local variables that are shadowed by a
// variable with the same name in another scope
VariableShadowed
// VariableConstant means this variable is a constant value
VariableConstant
// VariableArgument means this variable is a function argument
VariableArgument
// VariableReturnArgument means this variable is a function return value
VariableReturnArgument
// VariableFakeAddress means the address of this variable is either fake
// (i.e. the variable is partially or completely stored in a CPU register
// and doesn't have a real address) or possibly no longer available (because
// the variable is the return value of a function call and allocated on a
// frame that no longer exists)
VariableFakeAddress
// VariableCPrt means the variable is a C pointer
VariableCPtr
// VariableCPURegister means this variable is a CPU register.
VariableCPURegister
)
// Variable represents a variable. It contains the address, name,
// type and other information parsed from both the Dwarf information
// and the memory of the debugged process.
// If OnlyAddr is true, the variables value has not been loaded.
type Variable struct {
Addr uint64
OnlyAddr bool
Name string
DwarfType godwarf.Type
RealType godwarf.Type
Kind reflect.Kind
mem MemoryReadWriter
bi *BinaryInfo
Value constant.Value
FloatSpecial floatSpecial
reg *op.DwarfRegister // contains the value of this variable if VariableCPURegister flag is set and loaded is false
Len int64
Cap int64
Flags variableFlags
// Base address of arrays, Base address of the backing array for slices (0 for nil slices)
// Base address of the backing byte array for strings
// address of the struct backing chan and map variables
// address of the function entry point for function variables (0 for nil function pointers)
Base uint64
stride int64
fieldType godwarf.Type
// closureAddr is the closure address for function variables (0 for non-closures)
closureAddr uint64
// number of elements to skip when loading a map
mapSkip int
Children []Variable
loaded bool
Unreadable error
LocationExpr *locationExpr // location expression
DeclLine int64 // line number of this variable's declaration
}
// LoadConfig controls how variables are loaded from the targets memory.
type LoadConfig struct {
// FollowPointers requests pointers to be automatically dereferenced.
FollowPointers bool
// MaxVariableRecurse is how far to recurse when evaluating nested types.
MaxVariableRecurse int
// MaxStringLen is the maximum number of bytes read from a string
MaxStringLen int
// MaxArrayValues is the maximum number of elements read from an array, a slice or a map.
MaxArrayValues int
// MaxStructFields is the maximum number of fields read from a struct, -1 will read all fields.
MaxStructFields int
// MaxMapBuckets is the maximum number of map buckets to read before giving up.
// A value of 0 will read as many buckets as necessary until the entire map
// is read or MaxArrayValues is reached.
//
// Loading a map is an operation that issues O(num_buckets) operations.
// Normally the number of buckets is proportional to the number of elements
// in the map, since the runtime tries to keep the load factor of maps
// between 40% and 80%.
//
// It is possible, however, to create very sparse maps either by:
// a) adding lots of entries to a map and then deleting most of them, or
// b) using the make(mapType, N) expression with a very large N
//
// When this happens delve will have to scan many empty buckets to find the
// few entries in the map.
// MaxMapBuckets can be set to avoid annoying slowdowns␣while reading
// very sparse maps.
//
// Since there is no good way for a user of delve to specify the value of
// MaxMapBuckets, this field is not actually exposed through the API.
// Instead (*EvalScope).LocalVariables and (*EvalScope).FunctionArguments
// set this field automatically to MaxArrayValues * maxMapBucketsFactor.
// Every other invocation uses the default value of 0, obtaining the old behavior.
// In practice this means that debuggers using the ListLocalVars or
// ListFunctionArgs API will not experience a massive slowdown when a very
// sparse map is in scope, but evaluating a single variable will still work
// correctly, even if the variable in question is a very sparse map.
MaxMapBuckets int
}
var loadSingleValue = LoadConfig{false, 0, 64, 0, 0, 0}
var loadFullValue = LoadConfig{true, 1, 64, 64, -1, 0}
var loadFullValueLongerStrings = LoadConfig{true, 1, 1024 * 1024, 64, -1, 0}
// G status, from: src/runtime/runtime2.go
const (
Gidle uint64 = iota // 0
Grunnable // 1 runnable and on a run queue
Grunning // 2
Gsyscall // 3
Gwaiting // 4
GmoribundUnused // 5 currently unused, but hardcoded in gdb scripts
Gdead // 6
Genqueue // 7 Only the Gscanenqueue is used.
Gcopystack // 8 in this state when newstack is moving the stack
)
// G represents a runtime G (goroutine) structure (at least the
// fields that Delve is interested in).
type G struct {
ID int // Goroutine ID
PC uint64 // PC of goroutine when it was parked.
SP uint64 // SP of goroutine when it was parked.
BP uint64 // BP of goroutine when it was parked (go >= 1.7).
LR uint64 // LR of goroutine when it was parked.
GoPC uint64 // PC of 'go' statement that created this goroutine.
StartPC uint64 // PC of the first function run on this goroutine.
Status uint64
stack stack // value of stack
WaitSince int64
WaitReason int64
SystemStack bool // SystemStack is true if this goroutine is currently executing on a system stack.
// Information on goroutine location
CurrentLoc Location
// Thread that this goroutine is currently allocated to
Thread Thread
variable *Variable
Unreadable error // could not read the G struct
labels *map[string]string // G's pprof labels, computed on demand in Labels() method
}
// stack represents a stack span in the target process.
type stack struct {
hi, lo uint64
}
// GetG returns information on the G (goroutine) that is executing on this thread.
//
// The G structure for a thread is stored in thread local storage. Here we simply
// calculate the address and read and parse the G struct.
//
// We cannot simply use the allg linked list in order to find the M that represents
// the given OS thread and follow its G pointer because on Darwin mach ports are not
// universal, so our port for this thread would not map to the `id` attribute of the M
// structure. Also, when linked against libc, Go prefers the libc version of clone as
// opposed to the runtime version. This has the consequence of not setting M.id for
// any thread, regardless of OS.
//
// In order to get around all this craziness, we read the address of the G structure for
// the current thread from the thread local storage area.
func GetG(thread Thread) (*G, error) {
if thread.Common().g != nil {
return thread.Common().g, nil
}
if loc, _ := thread.Location(); loc != nil && loc.Fn != nil && loc.Fn.Name == "runtime.clone" {
// When threads are executing runtime.clone the value of TLS is unreliable.
return nil, nil
}
gaddr, err := getGVariable(thread)
if err != nil {
return nil, err
}
g, err := gaddr.parseG()
if err != nil {
return nil, err
}
if g.ID == 0 {
// The runtime uses a special goroutine with ID == 0 to mark that the
// current goroutine is executing on the system stack (sometimes also
// referred to as the g0 stack or scheduler stack, I'm not sure if there's
// actually any difference between those).
// For our purposes it's better if we always return the real goroutine
// since the rest of the code assumes the goroutine ID is univocal.
// The real 'current goroutine' is stored in g0.m.curg
mvar, err := g.variable.structMember("m")
if err != nil {
return nil, err
}
curgvar, err := mvar.structMember("curg")
if err != nil {
return nil, err
}
g, err = curgvar.parseG()
if err != nil {
if _, ok := err.(ErrNoGoroutine); ok {
err = ErrNoGoroutine{thread.ThreadID()}
}
return nil, err
}
g.SystemStack = true
}
g.Thread = thread
if loc, err := thread.Location(); err == nil {
g.CurrentLoc = *loc
}
thread.Common().g = g
return g, nil
}
// GoroutinesInfo searches for goroutines starting at index 'start', and
// returns an array of up to 'count' (or all found elements, if 'count' is 0)
// G structures representing the information Delve care about from the internal
// runtime G structure.
// GoroutinesInfo also returns the next index to be used as 'start' argument
// while scanning for all available goroutines, or -1 if there was an error
// or if the index already reached the last possible value.
func GoroutinesInfo(dbp *Target, start, count int) ([]*G, int, error) {
if _, err := dbp.Valid(); err != nil {
return nil, -1, err
}
if dbp.gcache.allGCache != nil {
// We can't use the cached array to fulfill a subrange request
if start == 0 && (count == 0 || count >= len(dbp.gcache.allGCache)) {
return dbp.gcache.allGCache, -1, nil
}
}
var (
threadg = map[int]*G{}
allg []*G
)
threads := dbp.ThreadList()
for _, th := range threads {
g, _ := GetG(th)
if g != nil {
threadg[g.ID] = g
}
}
allgptr, allglen, err := dbp.gcache.getRuntimeAllg(dbp.BinInfo(), dbp.Memory())
if err != nil {
return nil, -1, err
}
for i := uint64(start); i < allglen; i++ {
if count != 0 && len(allg) >= count {
return allg, int(i), nil
}
gvar, err := newGVariable(dbp.CurrentThread(), allgptr+(i*uint64(dbp.BinInfo().Arch.PtrSize())), true)
if err != nil {
allg = append(allg, &G{Unreadable: err})
continue
}
g, err := gvar.parseG()
if err != nil {
allg = append(allg, &G{Unreadable: err})
continue
}
if thg, allocated := threadg[g.ID]; allocated {
loc, err := thg.Thread.Location()
if err != nil {
return nil, -1, err
}
g.Thread = thg.Thread
// Prefer actual thread location information.
g.CurrentLoc = *loc
g.SystemStack = thg.SystemStack
}
if g.Status != Gdead {
allg = append(allg, g)
}
dbp.gcache.addGoroutine(g)
}
if start == 0 {
dbp.gcache.allGCache = allg
}
return allg, -1, nil
}
// FindGoroutine returns a G struct representing the goroutine
// specified by `gid`.
func FindGoroutine(dbp *Target, gid int) (*G, error) {
if selg := dbp.SelectedGoroutine(); (gid == -1) || (selg != nil && selg.ID == gid) || (selg == nil && gid == 0) {
// Return the currently selected goroutine in the following circumstances:
//
// 1. if the caller asks for gid == -1 (because that's what a goroutine ID of -1 means in our API).
// 2. if gid == selg.ID.
// this serves two purposes: (a) it's an optimizations that allows us
// to avoid reading any other goroutine and, more importantly, (b) we
// could be reading an incorrect value for the goroutine ID of a thread.
// This condition usually happens when a goroutine calls runtime.clone
// and for a short period of time two threads will appear to be running
// the same goroutine.
// 3. if the caller asks for gid == 0 and the selected goroutine is
// either 0 or nil.
// Goroutine 0 is special, it either means we have no current goroutine
// (for example, running C code), or that we are running on a special
// stack (system stack, signal handling stack) and we didn't properly
// detect it.
// Since there could be multiple goroutines '0' running simultaneously
// if the user requests it return the one that's already selected or
// nil if there isn't a selected goroutine.
return selg, nil
}
if gid == 0 {
return nil, fmt.Errorf("unknown goroutine %d", gid)
}
if g := dbp.gcache.partialGCache[gid]; g != nil {
return g, nil
}
// Calling GoroutinesInfo could be slow if there are many goroutines
// running, check if a running goroutine has been requested first.
for _, thread := range dbp.ThreadList() {
g, _ := GetG(thread)
if g != nil && g.ID == gid {
return g, nil
}
}
const goroutinesInfoLimit = 10
nextg := 0
for nextg >= 0 {
var gs []*G
var err error
gs, nextg, err = GoroutinesInfo(dbp, nextg, goroutinesInfoLimit)
if err != nil {
return nil, err
}
for i := range gs {
if gs[i].ID == gid {
if gs[i].Unreadable != nil {
return nil, gs[i].Unreadable
}
return gs[i], nil
}
}
}
return nil, fmt.Errorf("unknown goroutine %d", gid)
}
func getGVariable(thread Thread) (*Variable, error) {
regs, err := thread.Registers()
if err != nil {
return nil, err
}
gaddr, hasgaddr := regs.GAddr()
if !hasgaddr {
var err error
gaddr, err = readUintRaw(thread.ProcessMemory(), regs.TLS()+thread.BinInfo().GStructOffset(), int64(thread.BinInfo().Arch.PtrSize()))
if err != nil {
return nil, err
}
}
return newGVariable(thread, gaddr, thread.BinInfo().Arch.DerefTLS())
}
func newGVariable(thread Thread, gaddr uint64, deref bool) (*Variable, error) {
typ, err := thread.BinInfo().findType("runtime.g")
if err != nil {
return nil, err
}
if deref {
typ = &godwarf.PtrType{
CommonType: godwarf.CommonType{
ByteSize: int64(thread.BinInfo().Arch.PtrSize()),
Name: "",
ReflectKind: reflect.Ptr,
Offset: 0,
},
Type: typ,
}
}
return newVariableFromThread(thread, "", gaddr, typ), nil
}
// Defer returns the top-most defer of the goroutine.
func (g *G) Defer() *Defer {
if g.variable.Unreadable != nil {
return nil
}
dvar, _ := g.variable.structMember("_defer")
if dvar == nil {
return nil
}
dvar = dvar.maybeDereference()
if dvar.Addr == 0 {
return nil
}
d := &Defer{variable: dvar}
d.load()
return d
}
// UserCurrent returns the location the users code is at,
// or was at before entering a runtime function.
func (g *G) UserCurrent() Location {
it, err := g.stackIterator(0)
if err != nil {
return g.CurrentLoc
}
for count := 0; it.Next() && count < maxGoroutineUserCurrentDepth; count++ {
frame := it.Frame()
if frame.Call.Fn != nil {
name := frame.Call.Fn.Name
if strings.Contains(name, ".") && (!strings.HasPrefix(name, "runtime.") || frame.Call.Fn.exportedRuntime()) && !strings.HasPrefix(name, "internal/") && !strings.HasPrefix(name, "runtime/internal") {
return frame.Call
}
}
}
return g.CurrentLoc
}
// Go returns the location of the 'go' statement
// that spawned this goroutine.
func (g *G) Go() Location {
pc := g.GoPC
if fn := g.variable.bi.PCToFunc(pc); fn != nil {
// Backup to CALL instruction.
// Mimics runtime/traceback.go:677.
if g.GoPC > fn.Entry {
pc--
}
}
f, l, fn := g.variable.bi.PCToLine(pc)
return Location{PC: g.GoPC, File: f, Line: l, Fn: fn}
}
// StartLoc returns the starting location of the goroutine.
func (g *G) StartLoc(tgt *Target) Location {
fn := g.variable.bi.PCToFunc(g.StartPC)
fn = tgt.dwrapUnwrap(fn)
if fn == nil {
return Location{PC: g.StartPC}
}
f, l := fn.cu.lineInfo.PCToLine(fn.Entry, fn.Entry)
return Location{PC: fn.Entry, File: f, Line: l, Fn: fn}
}
// System returns true if g is a system goroutine. See isSystemGoroutine in
// $GOROOT/src/runtime/traceback.go.
func (g *G) System(tgt *Target) bool {
loc := g.StartLoc(tgt)
if loc.Fn == nil {
return false
}
switch loc.Fn.Name {
case "runtime.main", "runtime.handleAsyncEvent":
return false
}
return strings.HasPrefix(loc.Fn.Name, "runtime.")
}
func (g *G) Labels() map[string]string {
if g.labels != nil {
return *g.labels
}
var labels map[string]string
if labelsVar := g.variable.loadFieldNamed("labels"); labelsVar != nil && len(labelsVar.Children) == 1 {
if address := labelsVar.Children[0]; address.Addr != 0 {
labelMapType, _ := g.variable.bi.findType("runtime/pprof.labelMap")
if labelMapType != nil {
labelMap := newVariable("", address.Addr, labelMapType, g.variable.bi, g.variable.mem)
labelMap.loadValue(loadFullValue)
labels = map[string]string{}
for i := range labelMap.Children {
if i%2 == 0 {
k := labelMap.Children[i]
v := labelMap.Children[i+1]
labels[constant.StringVal(k.Value)] = constant.StringVal(v.Value)
}
}
}
}
}
g.labels = &labels
return *g.labels
}
type Ancestor struct {
ID int64 // Goroutine ID
Unreadable error
pcsVar *Variable
}
// IsNilErr is returned when a variable is nil.
type IsNilErr struct {
name string
}
func (err *IsNilErr) Error() string {
return fmt.Sprintf("%s is nil", err.name)
}
func globalScope(tgt *Target, bi *BinaryInfo, image *Image, mem MemoryReadWriter) *EvalScope {
return &EvalScope{Location: Location{}, Regs: op.DwarfRegisters{StaticBase: image.StaticBase}, Mem: mem, g: nil, BinInfo: bi, target: tgt, frameOffset: 0}
}
func newVariableFromThread(t Thread, name string, addr uint64, dwarfType godwarf.Type) *Variable {
return newVariable(name, addr, dwarfType, t.BinInfo(), t.ProcessMemory())
}
func (v *Variable) newVariable(name string, addr uint64, dwarfType godwarf.Type, mem MemoryReadWriter) *Variable {
return newVariable(name, addr, dwarfType, v.bi, mem)
}
func newVariable(name string, addr uint64, dwarfType godwarf.Type, bi *BinaryInfo, mem MemoryReadWriter) *Variable {
if styp, isstruct := dwarfType.(*godwarf.StructType); isstruct && !strings.Contains(styp.Name, "<") && !strings.Contains(styp.Name, "{") {
// For named structs the compiler will emit a DW_TAG_structure_type entry
// and a DW_TAG_typedef entry.
//
// Normally variables refer to the typedef entry but sometimes global
// variables will refer to the struct entry incorrectly.
// Also the runtime type offset resolution (runtimeTypeToDIE) will return
// the struct entry directly.
//
// In both cases we prefer to have a typedef type for consistency's sake.
//
// So we wrap all struct types into a fake typedef type except for:
// a. types not defined by go
// b. anonymous struct types (they contain the '{' character)
// c. Go internal struct types used to describe maps (they contain the '<'
// character).
cu := bi.Images[dwarfType.Common().Index].findCompileUnitForOffset(dwarfType.Common().Offset)
if cu != nil && cu.isgo {
dwarfType = &godwarf.TypedefType{
CommonType: *(dwarfType.Common()),
Type: dwarfType,
}
}
}
v := &Variable{
Name: name,
Addr: addr,
DwarfType: dwarfType,
mem: mem,
bi: bi,
}
v.RealType = resolveTypedef(v.DwarfType)
switch t := v.RealType.(type) {
case *godwarf.PtrType:
v.Kind = reflect.Ptr
if _, isvoid := t.Type.(*godwarf.VoidType); isvoid {
v.Kind = reflect.UnsafePointer
} else if isCgoType(bi, t) {
v.Flags |= VariableCPtr
v.fieldType = t.Type
v.stride = alignAddr(v.fieldType.Size(), v.fieldType.Align())
v.Len = 0
if isCgoCharPtr(bi, t) {
v.Kind = reflect.String
}
if v.Addr != 0 {
v.Base, v.Unreadable = readUintRaw(v.mem, v.Addr, int64(v.bi.Arch.PtrSize()))
}
}
case *godwarf.ChanType:
v.Kind = reflect.Chan
if v.Addr != 0 {
v.loadChanInfo()
}
case *godwarf.MapType:
v.Kind = reflect.Map
case *godwarf.StringType:
v.Kind = reflect.String
v.stride = 1
v.fieldType = &godwarf.UintType{BasicType: godwarf.BasicType{CommonType: godwarf.CommonType{ByteSize: 1, Name: "byte"}, BitSize: 8, BitOffset: 0}}
if v.Addr != 0 {
v.Base, v.Len, v.Unreadable = readStringInfo(v.mem, v.bi.Arch, v.Addr)
}
case *godwarf.SliceType:
v.Kind = reflect.Slice
if v.Addr != 0 {
v.loadSliceInfo(t)
}
case *godwarf.InterfaceType:
v.Kind = reflect.Interface
case *godwarf.StructType:
v.Kind = reflect.Struct
case *godwarf.ArrayType:
v.Kind = reflect.Array
v.Base = v.Addr
v.Len = t.Count
v.Cap = -1
v.fieldType = t.Type
v.stride = 0
if t.Count > 0 {
v.stride = t.ByteSize / t.Count
}
case *godwarf.ComplexType:
switch t.ByteSize {
case 8:
v.Kind = reflect.Complex64
case 16:
v.Kind = reflect.Complex128
}
case *godwarf.IntType:
v.Kind = reflect.Int
case *godwarf.CharType:
// Rest of the code assumes that Kind == reflect.Int implies RealType ==
// godwarf.IntType.
v.RealType = &godwarf.IntType{BasicType: t.BasicType}
v.Kind = reflect.Int
case *godwarf.UcharType:
v.RealType = &godwarf.IntType{BasicType: t.BasicType}
v.Kind = reflect.Int
case *godwarf.UintType:
v.Kind = reflect.Uint
case *godwarf.FloatType:
switch t.ByteSize {
case 4:
v.Kind = reflect.Float32
case 8:
v.Kind = reflect.Float64
}
case *godwarf.BoolType:
v.Kind = reflect.Bool
case *godwarf.FuncType:
v.Kind = reflect.Func
case *godwarf.VoidType:
v.Kind = reflect.Invalid
case *godwarf.UnspecifiedType:
v.Kind = reflect.Invalid
default:
v.Unreadable = fmt.Errorf("unknown type: %T", t)
}
return v
}
func resolveTypedef(typ godwarf.Type) godwarf.Type {
for {
switch tt := typ.(type) {
case *godwarf.TypedefType:
typ = tt.Type
case *godwarf.QualType:
typ = tt.Type
default:
return typ
}
}
}
var constantMaxInt64 = constant.MakeInt64(1<<63 - 1)
func newConstant(val constant.Value, mem MemoryReadWriter) *Variable {
v := &Variable{Value: val, mem: mem, loaded: true}
switch val.Kind() {
case constant.Int:
v.Kind = reflect.Int
if constant.Sign(val) >= 0 && constant.Compare(val, token.GTR, constantMaxInt64) {
v.Kind = reflect.Uint64
}
case constant.Float:
v.Kind = reflect.Float64
case constant.Bool:
v.Kind = reflect.Bool
case constant.Complex:
v.Kind = reflect.Complex128
case constant.String:
v.Kind = reflect.String
v.Len = int64(len(constant.StringVal(val)))
}
v.Flags |= VariableConstant
return v
}
var nilVariable = &Variable{
Name: "nil",
Addr: 0,
Base: 0,
Kind: reflect.Ptr,
Children: []Variable{{Addr: 0, OnlyAddr: true}},
}
func (v *Variable) clone() *Variable {
r := *v
return &r
}
// TypeString returns the string representation
// of the type of this variable.
func (v *Variable) TypeString() string {
if v == nilVariable {
return "nil"
}
if v.DwarfType == nil {
return v.Kind.String()
}
if v.DwarfType.Common().Name != "" {
return v.DwarfType.Common().Name
}
r := v.DwarfType.String()
if r == "*void" {
cu := v.bi.Images[v.DwarfType.Common().Index].findCompileUnitForOffset(v.DwarfType.Common().Offset)
if cu != nil && cu.isgo {
r = "unsafe.Pointer"
}
}
return r
}
func (v *Variable) toField(field *godwarf.StructField) (*Variable, error) {
if v.Unreadable != nil {
return v.clone(), nil
}
if v.Addr == 0 {
return nil, &IsNilErr{v.Name}
}
name := ""
if v.Name != "" {
parts := strings.Split(field.Name, ".")
if len(parts) > 1 {
name = fmt.Sprintf("%s.%s", v.Name, parts[1])
} else {
name = fmt.Sprintf("%s.%s", v.Name, field.Name)
}
}
return v.newVariable(name, uint64(int64(v.Addr)+field.ByteOffset), field.Type, v.mem), nil
}
// ErrNoGoroutine returned when a G could not be found
// for a specific thread.
type ErrNoGoroutine struct {
tid int
}
func (ng ErrNoGoroutine) Error() string {
return fmt.Sprintf("no G executing on thread %d", ng.tid)
}
var ErrUnreadableG = errors.New("could not read G struct")
func (v *Variable) parseG() (*G, error) {
mem := v.mem
gaddr := uint64(v.Addr)
_, deref := v.RealType.(*godwarf.PtrType)
if deref {
var err error
gaddr, err = readUintRaw(mem, gaddr, int64(v.bi.Arch.PtrSize()))
if err != nil {
return nil, fmt.Errorf("error derefing *G %s", err)
}
}
if gaddr == 0 {
id := 0
if thread, ok := mem.(Thread); ok {
id = thread.ThreadID()
}
return nil, ErrNoGoroutine{tid: id}
}
isptr := func(t godwarf.Type) bool {
_, ok := t.(*godwarf.PtrType)
return ok
}
for isptr(v.RealType) {
v = v.maybeDereference() // +rtype g
}
v.mem = cacheMemory(v.mem, v.Addr, int(v.RealType.Size()))
schedVar := v.loadFieldNamed("sched") // +rtype gobuf
if schedVar == nil {
return nil, ErrUnreadableG
}
pc, _ := constant.Int64Val(schedVar.fieldVariable("pc").Value) // +rtype uintptr
sp, _ := constant.Int64Val(schedVar.fieldVariable("sp").Value) // +rtype uintptr
var bp, lr int64
if bpvar := schedVar.fieldVariable("bp"); /* +rtype -opt uintptr */ bpvar != nil && bpvar.Value != nil {
bp, _ = constant.Int64Val(bpvar.Value)
}
if bpvar := schedVar.fieldVariable("lr"); /* +rtype -opt uintptr */ bpvar != nil && bpvar.Value != nil {
lr, _ = constant.Int64Val(bpvar.Value)
}
unreadable := false
loadInt64Maybe := func(name string) int64 {
vv := v.loadFieldNamed(name)
if vv == nil {
unreadable = true
return 0
}
n, _ := constant.Int64Val(vv.Value)
return n
}
id := loadInt64Maybe("goid") // +rtype int64
gopc := loadInt64Maybe("gopc") // +rtype uintptr
startpc := loadInt64Maybe("startpc") // +rtype uintptr
waitSince := loadInt64Maybe("waitsince") // +rtype int64
waitReason := int64(0)
if producer := v.bi.Producer(); producer != "" && goversion.ProducerAfterOrEqual(producer, 1, 11) {
waitReason = loadInt64Maybe("waitreason") // +rtype -opt waitReason
}
var stackhi, stacklo uint64
if stackVar := v.loadFieldNamed("stack"); /* +rtype stack */ stackVar != nil {
if stackhiVar := stackVar.fieldVariable("hi"); /* +rtype uintptr */ stackhiVar != nil {
stackhi, _ = constant.Uint64Val(stackhiVar.Value)
}
if stackloVar := stackVar.fieldVariable("lo"); /* +rtype uintptr */ stackloVar != nil {
stacklo, _ = constant.Uint64Val(stackloVar.Value)
}
}
status := loadInt64Maybe("atomicstatus") // +rtype uint32
if unreadable {
return nil, ErrUnreadableG
}
f, l, fn := v.bi.PCToLine(uint64(pc))
v.Name = "runtime.curg"
g := &G{
ID: int(id),
GoPC: uint64(gopc),
StartPC: uint64(startpc),
PC: uint64(pc),
SP: uint64(sp),
BP: uint64(bp),
LR: uint64(lr),
Status: uint64(status),
WaitSince: waitSince,
WaitReason: waitReason,
CurrentLoc: Location{PC: uint64(pc), File: f, Line: l, Fn: fn},
variable: v,
stack: stack{hi: stackhi, lo: stacklo},
}
return g, nil
}
func (v *Variable) loadFieldNamed(name string) *Variable {
v, err := v.structMember(name)
if err != nil {
return nil
}
v.loadValue(loadFullValue)
if v.Unreadable != nil {
return nil
}
return v
}
func (v *Variable) fieldVariable(name string) *Variable {
if !v.loaded {
panic("fieldVariable called on a variable that wasn't loaded")
}
for i := range v.Children {
if child := &v.Children[i]; child.Name == name {
return child
}
}
return nil
}
var errTracebackAncestorsDisabled = errors.New("tracebackancestors is disabled")
// Ancestors returns the list of ancestors for g.
func Ancestors(p *Target, g *G, n int) ([]Ancestor, error) {
scope := globalScope(p, p.BinInfo(), p.BinInfo().Images[0], p.Memory())
tbav, err := scope.EvalExpression("runtime.debug.tracebackancestors", loadSingleValue)
if err == nil && tbav.Unreadable == nil && tbav.Kind == reflect.Int {
tba, _ := constant.Int64Val(tbav.Value)
if tba == 0 {
return nil, errTracebackAncestorsDisabled
}
}
av, err := g.variable.structMember("ancestors")
if err != nil {
return nil, err
}
av = av.maybeDereference()
av.loadValue(LoadConfig{MaxArrayValues: n, MaxVariableRecurse: 1, MaxStructFields: -1})
if av.Unreadable != nil {
return nil, err
}
if av.Addr == 0 {
// no ancestors
return nil, nil
}
r := make([]Ancestor, len(av.Children))
for i := range av.Children {
if av.Children[i].Unreadable != nil {
r[i].Unreadable = av.Children[i].Unreadable
continue
}
goidv := av.Children[i].fieldVariable("goid")
if goidv.Unreadable != nil {
r[i].Unreadable = goidv.Unreadable
continue
}
r[i].ID, _ = constant.Int64Val(goidv.Value)
pcsVar := av.Children[i].fieldVariable("pcs")
if pcsVar.Unreadable != nil {