forked from go-delve/delve
-
Notifications
You must be signed in to change notification settings - Fork 0
/
variables.go
1572 lines (1357 loc) · 39.4 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"
"encoding/binary"
"errors"
"fmt"
"go/constant"
"go/parser"
"go/token"
"reflect"
"strings"
"unsafe"
"github.com/derekparker/delve/dwarf/op"
"github.com/derekparker/delve/dwarf/reader"
"golang.org/x/debug/dwarf"
)
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
chanRecv = "chan receive"
chanSend = "chan send"
hashTophashEmpty = 0 // used by map reading code, indicates an empty bucket
hashMinTopHash = 4 // used by map reading code, indicates minimum value of tophash that isn't empty or evacuated
)
// 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 uintptr
OnlyAddr bool
Name string
DwarfType dwarf.Type
RealType dwarf.Type
Kind reflect.Kind
mem memoryReadWriter
dbp *Process
Value constant.Value
Len int64
Cap int64
// 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 uintptr
stride int64
fieldType dwarf.Type
// number of elements to skip when loading a map
mapSkip int
Children []Variable
loaded bool
Unreadable error
}
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
}
var loadSingleValue = LoadConfig{false, 0, 64, 0, 0}
var loadFullValue = LoadConfig{true, 1, 64, 64, -1}
// M represents a runtime M (OS thread) structure.
type M struct {
procid int // Thread ID or port.
spinning uint8 // Busy looping.
blocked uint8 // Waiting on futex / semaphore.
curg uintptr // Current G running on this thread.
}
// 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.
GoPC uint64 // PC of 'go' statement that created this goroutine.
WaitReason string // Reason for goroutine being parked.
Status uint64
// Information on goroutine location
CurrentLoc Location
// PC of entry to top-most deferred function.
DeferPC uint64
// Thread that this goroutine is currently allocated to
thread *Thread
dbp *Process
}
// EvalScope is the scope for variable evaluation. Contains the thread,
// current location (PC), and canonical frame address.
type EvalScope struct {
Thread *Thread
PC uint64
CFA int64
}
// 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 (scope *EvalScope) newVariable(name string, addr uintptr, dwarfType dwarf.Type) *Variable {
return newVariable(name, addr, dwarfType, scope.Thread.dbp, scope.Thread)
}
func (t *Thread) newVariable(name string, addr uintptr, dwarfType dwarf.Type) *Variable {
return newVariable(name, addr, dwarfType, t.dbp, t)
}
func (v *Variable) newVariable(name string, addr uintptr, dwarfType dwarf.Type) *Variable {
return newVariable(name, addr, dwarfType, v.dbp, v.mem)
}
func newVariable(name string, addr uintptr, dwarfType dwarf.Type, dbp *Process, mem memoryReadWriter) *Variable {
v := &Variable{
Name: name,
Addr: addr,
DwarfType: dwarfType,
mem: mem,
dbp: dbp,
}
v.RealType = resolveTypedef(v.DwarfType)
switch t := v.RealType.(type) {
case *dwarf.PtrType:
v.Kind = reflect.Ptr
if _, isvoid := t.Type.(*dwarf.VoidType); isvoid {
v.Kind = reflect.UnsafePointer
}
case *dwarf.ChanType:
v.Kind = reflect.Chan
case *dwarf.MapType:
v.Kind = reflect.Map
case *dwarf.StringType:
v.Kind = reflect.String
v.stride = 1
v.fieldType = &dwarf.UintType{BasicType: dwarf.BasicType{CommonType: dwarf.CommonType{ByteSize: 1, Name: "byte"}, BitSize: 8, BitOffset: 0}}
if v.Addr != 0 {
v.Base, v.Len, v.Unreadable = readStringInfo(v.mem, v.dbp.arch, v.Addr)
}
case *dwarf.SliceType:
v.Kind = reflect.Slice
if v.Addr != 0 {
v.loadSliceInfo(t)
}
case *dwarf.InterfaceType:
v.Kind = reflect.Interface
case *dwarf.StructType:
v.Kind = reflect.Struct
case *dwarf.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 *dwarf.ComplexType:
switch t.ByteSize {
case 8:
v.Kind = reflect.Complex64
case 16:
v.Kind = reflect.Complex128
}
case *dwarf.IntType:
v.Kind = reflect.Int
case *dwarf.UintType:
v.Kind = reflect.Uint
case *dwarf.FloatType:
switch t.ByteSize {
case 4:
v.Kind = reflect.Float32
case 8:
v.Kind = reflect.Float64
}
case *dwarf.BoolType:
v.Kind = reflect.Bool
case *dwarf.FuncType:
v.Kind = reflect.Func
case *dwarf.VoidType:
v.Kind = reflect.Invalid
case *dwarf.UnspecifiedType:
v.Kind = reflect.Invalid
default:
v.Unreadable = fmt.Errorf("Unknown type: %T", t)
}
return v
}
func resolveTypedef(typ dwarf.Type) dwarf.Type {
for {
if tt, ok := typ.(*dwarf.TypedefType); ok {
typ = tt.Type
} else {
return typ
}
}
}
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
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)))
}
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.DwarfType.Common().Name
}
return v.Kind.String()
}
func (v *Variable) toField(field *dwarf.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, uintptr(int64(v.Addr)+field.ByteOffset), field.Type), nil
}
// DwarfReader returns the DwarfReader containing the
// Dwarf information for the target process.
func (scope *EvalScope) DwarfReader() *reader.Reader {
return scope.Thread.dbp.DwarfReader()
}
// Type returns the Dwarf type entry at `offset`.
func (scope *EvalScope) Type(offset dwarf.Offset) (dwarf.Type, error) {
return scope.Thread.dbp.dwarf.Type(offset)
}
// PtrSize returns the size of a pointer.
func (scope *EvalScope) PtrSize() int {
return scope.Thread.dbp.arch.PtrSize()
}
// ChanRecvBlocked returns whether the goroutine is blocked on
// a channel read operation.
func (g *G) ChanRecvBlocked() bool {
return (g.thread == nil) && (g.WaitReason == chanRecv)
}
// chanRecvReturnAddr returns the address of the return from a channel read.
func (g *G) chanRecvReturnAddr(dbp *Process) (uint64, error) {
locs, err := g.Stacktrace(4)
if err != nil {
return 0, err
}
topLoc := locs[len(locs)-1]
return topLoc.Current.PC, nil
}
// NoGError returned when a G could not be found
// for a specific thread.
type NoGError struct {
tid int
}
func (ng NoGError) Error() string {
return fmt.Sprintf("no G executing on thread %d", ng.tid)
}
func (gvar *Variable) parseG() (*G, error) {
mem := gvar.mem
dbp := gvar.dbp
gaddr := uint64(gvar.Addr)
_, deref := gvar.RealType.(*dwarf.PtrType)
if deref {
gaddrbytes, err := mem.readMemory(uintptr(gaddr), dbp.arch.PtrSize())
if err != nil {
return nil, fmt.Errorf("error derefing *G %s", err)
}
gaddr = binary.LittleEndian.Uint64(gaddrbytes)
}
if gaddr == 0 {
id := 0
if thread, ok := mem.(*Thread); ok {
id = thread.ID
}
return nil, NoGError{tid: id}
}
gvar.loadValue(loadFullValue)
if gvar.Unreadable != nil {
return nil, gvar.Unreadable
}
schedVar := gvar.toFieldNamed("sched")
pc, _ := constant.Int64Val(schedVar.toFieldNamed("pc").Value)
sp, _ := constant.Int64Val(schedVar.toFieldNamed("sp").Value)
id, _ := constant.Int64Val(gvar.toFieldNamed("goid").Value)
gopc, _ := constant.Int64Val(gvar.toFieldNamed("gopc").Value)
waitReason := constant.StringVal(gvar.toFieldNamed("waitreason").Value)
d := gvar.toFieldNamed("_defer")
deferPC := int64(0)
fnvar := d.toFieldNamed("fn")
if fnvar != nil {
fnvalvar := fnvar.toFieldNamed("fn")
deferPC, _ = constant.Int64Val(fnvalvar.Value)
}
status, _ := constant.Int64Val(gvar.toFieldNamed("atomicstatus").Value)
f, l, fn := gvar.dbp.goSymTable.PCToLine(uint64(pc))
g := &G{
ID: int(id),
GoPC: uint64(gopc),
PC: uint64(pc),
SP: uint64(sp),
WaitReason: waitReason,
DeferPC: uint64(deferPC),
Status: uint64(status),
CurrentLoc: Location{PC: uint64(pc), File: f, Line: l, Fn: fn},
dbp: gvar.dbp,
}
return g, nil
}
func (v *Variable) toFieldNamed(name string) *Variable {
v, err := v.structMember(name)
if err != nil {
return nil
}
v.loadValue(loadFullValue)
if v.Unreadable != nil {
return nil
}
return v
}
// From $GOROOT/src/runtime/traceback.go:597
// isExportedRuntime reports whether name is an exported runtime function.
// It is only for runtime functions, so ASCII A-Z is fine.
func isExportedRuntime(name string) bool {
const n = len("runtime.")
return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
}
// 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()
if err != nil {
return g.CurrentLoc
}
for it.Next() {
frame := it.Frame()
if frame.Call.Fn != nil {
name := frame.Call.Fn.Name
if (strings.Index(name, ".") >= 0) && (!strings.HasPrefix(name, "runtime.") || isExportedRuntime(name)) {
return frame.Call
}
}
}
return g.CurrentLoc
}
// Go returns the location of the 'go' statement
// that spawned this goroutine.
func (g *G) Go() Location {
f, l, fn := g.dbp.goSymTable.PCToLine(g.GoPC)
return Location{PC: g.GoPC, File: f, Line: l, Fn: fn}
}
// EvalVariable returns the value of the given expression (backwards compatibility).
func (scope *EvalScope) EvalVariable(name string, cfg LoadConfig) (*Variable, error) {
return scope.EvalExpression(name, cfg)
}
// SetVariable sets the value of the named variable
func (scope *EvalScope) SetVariable(name, value string) error {
t, err := parser.ParseExpr(name)
if err != nil {
return err
}
xv, err := scope.evalAST(t)
if err != nil {
return err
}
if xv.Addr == 0 {
return fmt.Errorf("Can not assign to \"%s\"", name)
}
if xv.Unreadable != nil {
return fmt.Errorf("Expression \"%s\" is unreadable: %v", name, xv.Unreadable)
}
t, err = parser.ParseExpr(value)
if err != nil {
return err
}
yv, err := scope.evalAST(t)
if err != nil {
return err
}
yv.loadValue(loadSingleValue)
if err := yv.isType(xv.RealType, xv.Kind); err != nil {
return err
}
if yv.Unreadable != nil {
return fmt.Errorf("Expression \"%s\" is unreadable: %v", value, yv.Unreadable)
}
return xv.setValue(yv)
}
func (scope *EvalScope) extractVariableFromEntry(entry *dwarf.Entry, cfg LoadConfig) (*Variable, error) {
rdr := scope.DwarfReader()
v, err := scope.extractVarInfoFromEntry(entry, rdr)
if err != nil {
return nil, err
}
v.loadValue(cfg)
return v, nil
}
func (scope *EvalScope) extractVarInfo(varName string) (*Variable, error) {
reader := scope.DwarfReader()
_, err := reader.SeekToFunction(scope.PC)
if err != nil {
return nil, err
}
for entry, err := reader.NextScopeVariable(); entry != nil; entry, err = reader.NextScopeVariable() {
if err != nil {
return nil, err
}
n, ok := entry.Val(dwarf.AttrName).(string)
if !ok {
continue
}
if n == varName {
return scope.extractVarInfoFromEntry(entry, reader)
}
}
return nil, fmt.Errorf("could not find symbol value for %s", varName)
}
// LocalVariables returns all local variables from the current function scope.
func (scope *EvalScope) LocalVariables(cfg LoadConfig) ([]*Variable, error) {
return scope.variablesByTag(dwarf.TagVariable, cfg)
}
// FunctionArguments returns the name, value, and type of all current function arguments.
func (scope *EvalScope) FunctionArguments(cfg LoadConfig) ([]*Variable, error) {
return scope.variablesByTag(dwarf.TagFormalParameter, cfg)
}
// PackageVariables returns the name, value, and type of all package variables in the application.
func (scope *EvalScope) PackageVariables(cfg LoadConfig) ([]*Variable, error) {
var vars []*Variable
reader := scope.DwarfReader()
var utypoff dwarf.Offset
utypentry, err := reader.SeekToTypeNamed("<unspecified>")
if err == nil {
utypoff = utypentry.Offset
}
for entry, err := reader.NextPackageVariable(); entry != nil; entry, err = reader.NextPackageVariable() {
if err != nil {
return nil, err
}
if typoff, ok := entry.Val(dwarf.AttrType).(dwarf.Offset); !ok || typoff == utypoff {
continue
}
// Ignore errors trying to extract values
val, err := scope.extractVariableFromEntry(entry, cfg)
if err != nil {
continue
}
vars = append(vars, val)
}
return vars, nil
}
// EvalPackageVariable will evaluate the package level variable
// specified by 'name'.
func (dbp *Process) EvalPackageVariable(name string, cfg LoadConfig) (*Variable, error) {
scope := &EvalScope{Thread: dbp.CurrentThread, PC: 0, CFA: 0}
v, err := scope.packageVarAddr(name)
if err != nil {
return nil, err
}
v.loadValue(cfg)
return v, nil
}
func (scope *EvalScope) packageVarAddr(name string) (*Variable, error) {
reader := scope.DwarfReader()
for entry, err := reader.NextPackageVariable(); entry != nil; entry, err = reader.NextPackageVariable() {
if err != nil {
return nil, err
}
n, ok := entry.Val(dwarf.AttrName).(string)
if !ok {
continue
}
if n == name {
return scope.extractVarInfoFromEntry(entry, reader)
}
}
return nil, fmt.Errorf("could not find symbol value for %s", name)
}
func (v *Variable) structMember(memberName string) (*Variable, error) {
if v.Unreadable != nil {
return v.clone(), nil
}
structVar := v.maybeDereference()
structVar.Name = v.Name
if structVar.Unreadable != nil {
return structVar, nil
}
switch t := structVar.RealType.(type) {
case *dwarf.StructType:
for _, field := range t.Field {
if field.Name != memberName {
continue
}
return structVar.toField(field)
}
// Check for embedded field only if field was
// not a regular struct member
for _, field := range t.Field {
isEmbeddedStructMember :=
(field.Type.Common().Name == field.Name) ||
(len(field.Name) > 1 &&
field.Name[0] == '*' &&
field.Type.Common().Name[1:] == field.Name[1:])
if !isEmbeddedStructMember {
continue
}
// Check for embedded field referenced by type name
parts := strings.Split(field.Name, ".")
if len(parts) > 1 && parts[1] == memberName {
embeddedVar, err := structVar.toField(field)
if err != nil {
return nil, err
}
return embeddedVar, nil
}
// Recursively check for promoted fields on the embedded field
embeddedVar, err := structVar.toField(field)
if err != nil {
return nil, err
}
embeddedVar.Name = structVar.Name
embeddedField, err := embeddedVar.structMember(memberName)
if embeddedField != nil {
return embeddedField, nil
}
}
return nil, fmt.Errorf("%s has no member %s", v.Name, memberName)
default:
if v.Name == "" {
return nil, fmt.Errorf("type %s is not a struct", structVar.TypeString())
}
return nil, fmt.Errorf("%s (type %s) is not a struct", v.Name, structVar.TypeString())
}
}
// Extracts the name and type of a variable from a dwarf entry
// then executes the instructions given in the DW_AT_location attribute to grab the variable's address
func (scope *EvalScope) extractVarInfoFromEntry(entry *dwarf.Entry, rdr *reader.Reader) (*Variable, error) {
if entry == nil {
return nil, fmt.Errorf("invalid entry")
}
if entry.Tag != dwarf.TagFormalParameter && entry.Tag != dwarf.TagVariable {
return nil, fmt.Errorf("invalid entry tag, only supports FormalParameter and Variable, got %s", entry.Tag.String())
}
n, ok := entry.Val(dwarf.AttrName).(string)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
offset, ok := entry.Val(dwarf.AttrType).(dwarf.Offset)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
t, err := scope.Type(offset)
if err != nil {
return nil, err
}
instructions, ok := entry.Val(dwarf.AttrLocation).([]byte)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
addr, err := op.ExecuteStackProgram(scope.CFA, instructions)
if err != nil {
return nil, err
}
return scope.newVariable(n, uintptr(addr), t), nil
}
// If v is a pointer a new variable is returned containing the value pointed by v.
func (v *Variable) maybeDereference() *Variable {
if v.Unreadable != nil {
return v
}
switch t := v.RealType.(type) {
case *dwarf.PtrType:
ptrval, err := readUintRaw(v.mem, uintptr(v.Addr), t.ByteSize)
r := v.newVariable("", uintptr(ptrval), t.Type)
if err != nil {
r.Unreadable = err
}
return r
default:
return v
}
}
// Extracts the value of the variable at the given address.
func (v *Variable) loadValue(cfg LoadConfig) {
v.loadValueInternal(0, cfg)
}
func (v *Variable) loadValueInternal(recurseLevel int, cfg LoadConfig) {
if v.Unreadable != nil || v.loaded || (v.Addr == 0 && v.Base == 0) {
return
}
v.loaded = true
switch v.Kind {
case reflect.Ptr, reflect.UnsafePointer:
v.Len = 1
v.Children = []Variable{*v.maybeDereference()}
if cfg.FollowPointers {
// Don't increase the recursion level when dereferencing pointers
v.Children[0].loadValueInternal(recurseLevel, cfg)
} else {
v.Children[0].OnlyAddr = true
}
case reflect.Chan:
sv := v.clone()
sv.RealType = resolveTypedef(&(sv.RealType.(*dwarf.ChanType).TypedefType))
sv = sv.maybeDereference()
sv.loadValueInternal(0, loadFullValue)
v.Children = sv.Children
v.Len = sv.Len
v.Base = sv.Addr
case reflect.Map:
if recurseLevel <= cfg.MaxVariableRecurse {
v.loadMap(recurseLevel, cfg)
}
case reflect.String:
var val string
val, v.Unreadable = readStringValue(v.mem, v.Base, v.Len, cfg)
v.Value = constant.MakeString(val)
case reflect.Slice, reflect.Array:
v.loadArrayValues(recurseLevel, cfg)
case reflect.Struct:
v.mem = cacheMemory(v.mem, v.Addr, int(v.RealType.Size()))
t := v.RealType.(*dwarf.StructType)
v.Len = int64(len(t.Field))
// Recursively call extractValue to grab
// the value of all the members of the struct.
if recurseLevel <= cfg.MaxVariableRecurse {
v.Children = make([]Variable, 0, len(t.Field))
for i, field := range t.Field {
if cfg.MaxStructFields >= 0 && len(v.Children) >= cfg.MaxStructFields {
break
}
f, _ := v.toField(field)
v.Children = append(v.Children, *f)
v.Children[i].Name = field.Name
v.Children[i].loadValueInternal(recurseLevel+1, cfg)
}
}
case reflect.Interface:
v.loadInterface(recurseLevel, true, cfg)
case reflect.Complex64, reflect.Complex128:
v.readComplex(v.RealType.(*dwarf.ComplexType).ByteSize)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var val int64
val, v.Unreadable = readIntRaw(v.mem, v.Addr, v.RealType.(*dwarf.IntType).ByteSize)
v.Value = constant.MakeInt64(val)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
var val uint64
val, v.Unreadable = readUintRaw(v.mem, v.Addr, v.RealType.(*dwarf.UintType).ByteSize)
v.Value = constant.MakeUint64(val)
case reflect.Bool:
val, err := v.mem.readMemory(v.Addr, 1)
v.Unreadable = err
if err == nil {
v.Value = constant.MakeBool(val[0] != 0)
}
case reflect.Float32, reflect.Float64:
var val float64
val, v.Unreadable = v.readFloatRaw(v.RealType.(*dwarf.FloatType).ByteSize)
v.Value = constant.MakeFloat64(val)
case reflect.Func:
v.readFunctionPtr()
default:
v.Unreadable = fmt.Errorf("unknown or unsupported kind: \"%s\"", v.Kind.String())
}
}
func (v *Variable) setValue(y *Variable) error {
var err error
switch v.Kind {
case reflect.Float32, reflect.Float64:
f, _ := constant.Float64Val(y.Value)
err = v.writeFloatRaw(f, v.RealType.Size())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, _ := constant.Int64Val(y.Value)
err = v.writeUint(uint64(n), v.RealType.Size())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n, _ := constant.Uint64Val(y.Value)
err = v.writeUint(n, v.RealType.Size())
case reflect.Bool:
err = v.writeBool(constant.BoolVal(y.Value))
case reflect.Complex64, reflect.Complex128:
real, _ := constant.Float64Val(constant.Real(y.Value))
imag, _ := constant.Float64Val(constant.Imag(y.Value))
err = v.writeComplex(real, imag, v.RealType.Size())
default:
if t, isptr := v.RealType.(*dwarf.PtrType); isptr {
err = v.writeUint(uint64(y.Children[0].Addr), int64(t.ByteSize))
} else {
return fmt.Errorf("can not set variables of type %s (not implemented)", v.Kind.String())
}
}
return err
}
func readStringInfo(mem memoryReadWriter, arch Arch, addr uintptr) (uintptr, int64, error) {
// string data structure is always two ptrs in size. Addr, followed by len
// http://research.swtch.com/godata
mem = cacheMemory(mem, addr, arch.PtrSize()*2)
// read len
val, err := mem.readMemory(addr+uintptr(arch.PtrSize()), arch.PtrSize())
if err != nil {
return 0, 0, fmt.Errorf("could not read string len %s", err)
}
strlen := int64(binary.LittleEndian.Uint64(val))
if strlen < 0 {
return 0, 0, fmt.Errorf("invalid length: %d", strlen)
}
// read addr
val, err = mem.readMemory(addr, arch.PtrSize())
if err != nil {
return 0, 0, fmt.Errorf("could not read string pointer %s", err)
}
addr = uintptr(binary.LittleEndian.Uint64(val))
if addr == 0 {
return 0, 0, nil
}
return addr, strlen, nil
}
func readStringValue(mem memoryReadWriter, addr uintptr, strlen int64, cfg LoadConfig) (string, error) {
count := strlen
if count > int64(cfg.MaxStringLen) {
count = int64(cfg.MaxStringLen)
}
val, err := mem.readMemory(addr, int(count))
if err != nil {
return "", fmt.Errorf("could not read string at %#v due to %s", addr, err)
}
retstr := *(*string)(unsafe.Pointer(&val))
return retstr, nil
}
func (v *Variable) loadSliceInfo(t *dwarf.SliceType) {
v.mem = cacheMemory(v.mem, v.Addr, int(t.Size()))
var err error
for _, f := range t.Field {
switch f.Name {
case "array":
var base uint64
base, err = readUintRaw(v.mem, uintptr(int64(v.Addr)+f.ByteOffset), f.Type.Size())
if err == nil {
v.Base = uintptr(base)
// Dereference array type to get value type
ptrType, ok := f.Type.(*dwarf.PtrType)
if !ok {
v.Unreadable = fmt.Errorf("Invalid type %s in slice array", f.Type)
return
}
v.fieldType = ptrType.Type
}
case "len":
lstrAddr, _ := v.toField(f)
lstrAddr.loadValue(loadSingleValue)
err = lstrAddr.Unreadable
if err == nil {
v.Len, _ = constant.Int64Val(lstrAddr.Value)
}
case "cap":
cstrAddr, _ := v.toField(f)
cstrAddr.loadValue(loadSingleValue)
err = cstrAddr.Unreadable
if err == nil {
v.Cap, _ = constant.Int64Val(cstrAddr.Value)
}
}
if err != nil {
v.Unreadable = err
return
}
}
v.stride = v.fieldType.Size()
if t, ok := v.fieldType.(*dwarf.PtrType); ok {
v.stride = t.ByteSize
}
return
}
func (v *Variable) loadArrayValues(recurseLevel int, cfg LoadConfig) {
if v.Unreadable != nil {
return
}
if v.Len < 0 {
v.Unreadable = errors.New("Negative array length")
return
}
count := v.Len
// Cap number of elements
if count > int64(cfg.MaxArrayValues) {
count = int64(cfg.MaxArrayValues)
}
if v.stride < maxArrayStridePrefetch {
v.mem = cacheMemory(v.mem, v.Base, int(v.stride*count))
}
errcount := 0
for i := int64(0); i < count; i++ {
fieldvar := v.newVariable("", uintptr(int64(v.Base)+(i*v.stride)), v.fieldType)
fieldvar.loadValueInternal(recurseLevel+1, cfg)
if fieldvar.Unreadable != nil {
errcount++
}
v.Children = append(v.Children, *fieldvar)
if errcount > maxErrCount {
break
}
}
}
func (v *Variable) readComplex(size int64) {
var fs int64
switch size {
case 8:
fs = 4
case 16:
fs = 8
default:
v.Unreadable = fmt.Errorf("invalid size (%d) for complex type", size)
return
}
ftyp := &dwarf.FloatType{BasicType: dwarf.BasicType{CommonType: dwarf.CommonType{ByteSize: fs, Name: fmt.Sprintf("float%d", fs)}, BitSize: fs * 8, BitOffset: 0}}
realvar := v.newVariable("real", v.Addr, ftyp)
imagvar := v.newVariable("imaginary", v.Addr+uintptr(fs), ftyp)
realvar.loadValue(loadSingleValue)
imagvar.loadValue(loadSingleValue)
v.Value = constant.BinaryOp(realvar.Value, token.ADD, constant.MakeImag(imagvar.Value))
}
func (v *Variable) writeComplex(real, imag float64, size int64) error {
err := v.writeFloatRaw(real, int64(size/2))
if err != nil {
return err