forked from randall77/hprof
/
parser.go
1630 lines (1528 loc) · 39.7 KB
/
parser.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 read
import (
"bufio"
"debug/dwarf"
"debug/elf"
"debug/macho"
"debug/pe"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"regexp"
"runtime"
"sort"
)
type FieldKind int
type TypeKind int
const (
FieldKindEol FieldKind = 0
FieldKindPtr = 1
FieldKindString = 2
FieldKindSlice = 3
FieldKindIface = 4
FieldKindEface = 5
FieldKindBool FieldKind = 6
FieldKindUInt8 = 7
FieldKindSInt8 = 8
FieldKindUInt16 = 9
FieldKindSInt16 = 10
FieldKindUInt32 FieldKind = 11
FieldKindSInt32 = 12
FieldKindUInt64 FieldKind = 13
FieldKindSInt64 = 14
FieldKindFloat32 = 15
FieldKindFloat64 = 16
FieldKindComplex64 = 17
FieldKindComplex128 = 18
FieldKindBytes8 = 19
FieldKindBytes16 = 20
FieldKindBytesElided = 21
TypeKindObject TypeKind = 0
TypeKindArray = 1
TypeKindChan = 2
TypeKindConservative = 127
tagEOF = 0
tagObject = 1
tagOtherRoot = 2
tagType = 3
tagGoRoutine = 4
tagStackFrame = 5
tagParams = 6
tagFinalizer = 7
tagItab = 8
tagOSThread = 9
tagMemStats = 10
tagQFinal = 11
tagData = 12
tagBss = 13
tagDefer = 14
tagPanic = 15
tagMemProf = 16
tagAllocSample = 17
// DWARF constants
dw_op_call_frame_cfa = 156
dw_op_consts = 17
dw_op_plus = 34
dw_op_addr = 3
dw_ate_boolean = 2
dw_ate_complex_float = 3 // complex64/complex128
dw_ate_float = 4 // float32/float64
dw_ate_signed = 5 // int8/int16/int32/int64/int
dw_ate_unsigned = 7 // uint8/uint16/uint32/uint64/uint/uintptr
// Size of buckets for FindObj. Bigger buckets use less memory
// but make FindObj take longer. 512 byte buckets use about 1.5%
// of the total heap size and require us to look at at most
// 64 objects.
bucketSize = 512
)
type Dump struct {
Order binary.ByteOrder
PtrSize uint64 // in bytes
HChanSize uint64 // channel header size in bytes
HeapStart uint64
HeapEnd uint64
TheChar byte
Experiment string
Ncpu uint64
Types []*Type
objects []object
Frames []*StackFrame
Goroutines []*GoRoutine
Otherroots []*OtherRoot
Finalizers []*Finalizer // pending finalizers, object still live
QFinal []*QFinalizer // finalizers which are ready to run
Osthreads []*OSThread
Memstats *runtime.MemStats
Data *Data
Bss *Data
Defers []*Defer
Panics []*Panic
MemProf []*MemProfEntry
AllocSamples []*AllocSample
// handle to dump file
r io.ReaderAt
buf []byte // temporary space for Contents calls
edges []Edge // temporary space for Edges calls
// list of full types, indexed by ID
FTList []*FullType
// map from type address to type
TypeMap map[uint64]*Type
// map from itab address whether the data field of an iface
// with that itab contains a pointer.
ItabMap map[uint64]bool
// Data structure for fast lookup of objects. Divides the heap
// into chunks of bucketSize bytes. For each bucket, we keep
// track of the lowest address object that has any of its
// bytes in that bucket.
bucketSize uint64
idx []ObjId
}
type Type struct {
Name string // not necessarily unique
Size uint64
efaceptr bool // Efaces with this type have a data field which is a pointer
Fields []Field // ordered in increasing offset order
Addr uint64
}
type FullType struct {
Id int
Typ *Type
Kind TypeKind
Size uint64
Name string
Fields []Field
}
// An edge is a directed connection between two objects. The source
// object is implicit. An edge includes information about where it
// leaves the source object and where it lands in the destination obj.
type Edge struct {
To ObjId // index of target object in array
FromOffset uint64 // offset in source object where ptr was found
ToOffset uint64 // offset in destination object where ptr lands
// name of field in the source object, if known
FieldName string
}
// object represents an object in the heap.
// There will be a lot of these. They need to be small.
type object struct {
Ft *FullType
offset int64 // position of object contents in dump file
Addr uint64
}
type ObjId int
const (
ObjNil ObjId = -1
)
// NumObjects returns the number of objects in the heap. Valid
// ObjIds for other calls are from 0 to NumObjects()-1.
func (d *Dump) NumObjects() int {
return len(d.objects)
}
func (d *Dump) Contents(i ObjId) []byte {
x := d.objects[i]
b := d.buf
if uint64(cap(b)) < x.Ft.Size {
b = make([]byte, x.Ft.Size)
d.buf = b
}
b = b[:x.Ft.Size]
n, err := d.r.ReadAt(b, x.offset)
if err != nil && !(n == len(b) && err == io.EOF) {
// TODO: propagate to caller
log.Fatal(err)
}
return b
}
func (d *Dump) Addr(x ObjId) uint64 {
return d.objects[x].Addr
}
func (d *Dump) Size(x ObjId) uint64 {
return d.objects[x].Ft.Size
}
func (d *Dump) Ft(x ObjId) *FullType {
return d.objects[x].Ft
}
// FindObj returns the object id containing the address addr, or -1 if no object contains addr.
func (d *Dump) FindObj(addr uint64) ObjId {
if addr < d.HeapStart || addr >= d.HeapEnd { // quick exit. Includes nil.
return ObjNil
}
// linear search among all the objects that map to the same bucketSize-byte bucket.
for i := d.idx[(addr-d.HeapStart)/bucketSize]; i < ObjId(len(d.objects)); i++ {
x := &d.objects[i]
if addr < x.Addr {
return ObjNil
}
if addr < x.Addr+x.Ft.Size {
return ObjId(i)
}
}
return ObjNil
}
func (d *Dump) Edges(i ObjId) []Edge {
x := &d.objects[i]
e := d.edges[:0]
b := d.Contents(i)
for _, f := range x.Ft.Fields {
switch f.Kind {
case FieldKindPtr, FieldKindString, FieldKindSlice:
p := readPtr(d, b[f.Offset:])
y := d.FindObj(p)
if y != ObjNil {
e = append(e, Edge{y, f.Offset, p - d.objects[y].Addr, f.Name})
}
case FieldKindEface:
taddr := readPtr(d, b[f.Offset:])
if taddr != 0 {
t := d.TypeMap[taddr]
if t == nil {
log.Fatal("can't find eface type", taddr)
}
if t.efaceptr {
p := readPtr(d, b[f.Offset+d.PtrSize:])
y := d.FindObj(p)
if y != ObjNil {
e = append(e, Edge{y, f.Offset + d.PtrSize, p - d.objects[y].Addr, f.Name})
}
}
}
case FieldKindIface:
itabaddr := readPtr(d, b[f.Offset:])
if itabaddr != 0 {
ptr, ok := d.ItabMap[itabaddr]
if !ok {
log.Fatal("can't find itab", itabaddr)
}
if ptr {
p := readPtr(d, b[f.Offset+d.PtrSize:])
y := d.FindObj(p)
if y != ObjNil {
e = append(e, Edge{y, f.Offset + d.PtrSize, p - d.objects[y].Addr, f.Name})
}
}
}
default:
continue
}
}
d.edges = e
return e
}
type OtherRoot struct {
Description string
Edges []Edge
toaddr uint64
}
// Object obj has a finalizer.
type Finalizer struct {
obj uint64
fn uint64 // function to be run (a FuncVal*)
code uint64 // code ptr (fn->fn)
fint uint64 // type of function argument
ot uint64 // type of object
}
// Finalizer that's ready to run
type QFinalizer struct {
obj uint64
fn uint64 // function to be run (a FuncVal*)
code uint64 // code ptr (fn->fn)
fint uint64 // type of function argument
ot uint64 // type of object
Edges []Edge
}
type Defer struct {
addr uint64
gp uint64
argp uint64
pc uint64
fn uint64
code uint64
link uint64
}
type Panic struct {
addr uint64
gp uint64
typ uint64
data uint64
defr uint64
link uint64
}
type MemProfFrame struct {
Func string
File string
Line uint64
}
type MemProfEntry struct {
addr uint64
size uint64
stack []MemProfFrame
allocs uint64
frees uint64
}
type AllocSample struct {
Addr uint64 // address of object
Prof *MemProfEntry // record of allocation site
}
type Data struct {
Addr uint64
Data []byte
Fields []Field
Edges []Edge
}
type OSThread struct {
addr uint64
id uint64
procid uint64
}
// A Field is a location in an object where there
// might be a pointer.
type Field struct {
Kind FieldKind
Offset uint64
Name string
BaseType string // base type for Ptr, Slice, Iface ("" if not known)
}
type GoRoutine struct {
Bos *StackFrame // frame at the top of the stack (i.e. currently running)
Ctxt ObjId
Addr uint64
bosaddr uint64
Goid uint64
Gopc uint64
Status uint64
IsSystem bool
IsBackground bool
WaitSince uint64
WaitReason string
ctxtaddr uint64
maddr uint64
deferaddr uint64
panicaddr uint64
}
type StackFrame struct {
Name string
Parent *StackFrame
Goroutine *GoRoutine
Depth uint64
Data []byte
Edges []Edge
Addr uint64
childaddr uint64
entry uint64
pc uint64
Fields []Field
}
// both an io.Reader and an io.ByteReader
type Reader interface {
Read(p []byte) (n int, err error)
ReadByte() (c byte, err error)
}
func readUint64(r Reader) uint64 {
x, err := binary.ReadUvarint(r)
if err != nil {
log.Fatal(err)
}
return x
}
func readNBytes(r Reader, n uint64) []byte {
s := make([]byte, n)
_, err := io.ReadFull(r, s)
if err != nil {
log.Fatal(err)
}
return s
}
func readBytes(r Reader) []byte {
n := readUint64(r)
return readNBytes(r, n)
}
func readString(r Reader) string {
return string(readBytes(r))
}
func readBool(r Reader) bool {
b, err := r.ReadByte()
if err != nil {
log.Fatal(err)
}
return b != 0
}
func readFields(r Reader) []Field {
var x []Field
for {
kind := FieldKind(readUint64(r))
if kind == FieldKindEol {
// TODO: sort by offset, or check that it is sorted
return x
}
x = append(x, Field{Kind: kind, Offset: readUint64(r)})
}
}
// A Reader that can tell you its current offset in the file.
type myReader struct {
r *bufio.Reader
cnt int64
}
func (r *myReader) Read(p []byte) (n int, err error) {
n, err = r.r.Read(p)
r.cnt += int64(n)
return
}
func (r *myReader) ReadByte() (c byte, err error) {
c, err = r.r.ReadByte()
if err != nil {
return
}
r.cnt++
return
}
func (r *myReader) ReadLine() (line []byte, isPrefix bool, err error) {
line, isPrefix, err = r.r.ReadLine()
r.cnt += int64(len(line)) + 1
return
}
func (r *myReader) Skip(n int64) error {
k, err := io.CopyN(ioutil.Discard, r.r, n)
r.cnt += k
return err
}
func (r *myReader) Count() int64 {
return r.cnt
}
type tkey struct {
typaddr uint64
kind TypeKind
size uint64
}
func (d *Dump) makeFullType(typaddr uint64, kind TypeKind, size uint64) *FullType {
t := d.TypeMap[typaddr]
if typaddr != 0 && t == nil {
log.Fatal("types appear before use of that type")
}
var name string
switch kind {
case TypeKindObject:
if t != nil {
name = t.Name
} else {
name = fmt.Sprintf("noptr%d", size)
}
case TypeKindArray:
name = fmt.Sprintf("{%d}%s", size/t.Size, t.Name)
case TypeKindChan:
if d.HChanSize == 0 {
log.Fatal("hchansize must be before objects")
}
if t.Size > 0 {
name = fmt.Sprintf("chan{%d}%s", (size-d.HChanSize)/t.Size, t.Name)
} else {
name = fmt.Sprintf("chan{inf}%s", t.Name)
}
case TypeKindConservative:
name = fmt.Sprintf("conservative%d", size)
}
ft := &FullType{len(d.FTList), t, kind, size, name, nil}
d.FTList = append(d.FTList, ft)
return ft
}
// Reads heap dump into memory.
func rawRead(filename string) *Dump {
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
r := &myReader{r: bufio.NewReader(file)}
// check for header
hdr, prefix, err := r.ReadLine()
if err != nil {
log.Fatal(err)
}
if prefix || string(hdr) != "go1.3 heap dump" {
log.Fatal("not a go1.3 heap dump file")
}
var d Dump
d.r = file
d.ItabMap = map[uint64]bool{}
d.TypeMap = map[uint64]*Type{}
ftmap := map[tkey]*FullType{} // full type dedup
memprof := map[uint64]*MemProfEntry{}
for {
kind := readUint64(r)
switch kind {
case tagObject:
obj := object{}
obj.Addr = readUint64(r)
typaddr := readUint64(r)
kind := TypeKind(readUint64(r))
size := readUint64(r)
k := tkey{typaddr, kind, size}
ft := ftmap[k]
if ft == nil {
ft = d.makeFullType(typaddr, kind, size)
ftmap[k] = ft
}
obj.Ft = ft
obj.offset = r.Count()
r.Skip(int64(ft.Size))
d.objects = append(d.objects, obj)
case tagEOF:
return &d
case tagOtherRoot:
t := &OtherRoot{}
t.Description = readString(r)
t.toaddr = readUint64(r)
d.Otherroots = append(d.Otherroots, t)
case tagType:
typ := &Type{}
typ.Addr = readUint64(r)
typ.Size = readUint64(r)
typ.Name = readString(r)
typ.efaceptr = readBool(r)
typ.Fields = readFields(r)
// Note: there may be duplicate type records in a dump.
// The duplicates get thrown away here.
if _, ok := d.TypeMap[typ.Addr]; !ok {
d.TypeMap[typ.Addr] = typ
d.Types = append(d.Types, typ)
}
case tagGoRoutine:
g := &GoRoutine{}
g.Addr = readUint64(r)
g.bosaddr = readUint64(r)
g.Goid = readUint64(r)
g.Gopc = readUint64(r)
g.Status = readUint64(r)
g.IsSystem = readBool(r)
g.IsBackground = readBool(r)
g.WaitSince = readUint64(r)
g.WaitReason = readString(r)
g.ctxtaddr = readUint64(r)
g.maddr = readUint64(r)
g.deferaddr = readUint64(r)
g.panicaddr = readUint64(r)
d.Goroutines = append(d.Goroutines, g)
case tagStackFrame:
t := &StackFrame{}
t.Addr = readUint64(r)
t.Depth = readUint64(r)
t.childaddr = readUint64(r)
t.Data = readBytes(r)
t.entry = readUint64(r)
t.pc = readUint64(r)
readUint64(r) // continpc
t.Name = readString(r)
t.Fields = readFields(r)
d.Frames = append(d.Frames, t)
case tagParams:
if readUint64(r) == 0 {
d.Order = binary.LittleEndian
} else {
d.Order = binary.BigEndian
}
d.PtrSize = readUint64(r)
d.HChanSize = readUint64(r)
d.HeapStart = readUint64(r)
d.HeapEnd = readUint64(r)
d.TheChar = byte(readUint64(r))
d.Experiment = readString(r)
d.Ncpu = readUint64(r)
case tagFinalizer:
t := &Finalizer{}
t.obj = readUint64(r)
t.fn = readUint64(r)
t.code = readUint64(r)
t.fint = readUint64(r)
t.ot = readUint64(r)
d.Finalizers = append(d.Finalizers, t)
case tagQFinal:
t := &QFinalizer{}
t.obj = readUint64(r)
t.fn = readUint64(r)
t.code = readUint64(r)
t.fint = readUint64(r)
t.ot = readUint64(r)
d.QFinal = append(d.QFinal, t)
case tagData:
t := &Data{}
t.Addr = readUint64(r)
t.Data = readBytes(r)
t.Fields = readFields(r)
d.Data = t
case tagBss:
t := &Data{}
t.Addr = readUint64(r)
t.Data = readBytes(r)
t.Fields = readFields(r)
d.Bss = t
case tagItab:
addr := readUint64(r)
ptr := readBool(r)
d.ItabMap[addr] = ptr
case tagOSThread:
t := &OSThread{}
t.addr = readUint64(r)
t.id = readUint64(r)
t.procid = readUint64(r)
d.Osthreads = append(d.Osthreads, t)
case tagMemStats:
t := &runtime.MemStats{}
t.Alloc = readUint64(r)
t.TotalAlloc = readUint64(r)
t.Sys = readUint64(r)
t.Lookups = readUint64(r)
t.Mallocs = readUint64(r)
t.Frees = readUint64(r)
t.HeapAlloc = readUint64(r)
t.HeapSys = readUint64(r)
t.HeapIdle = readUint64(r)
t.HeapInuse = readUint64(r)
t.HeapReleased = readUint64(r)
t.HeapObjects = readUint64(r)
t.StackInuse = readUint64(r)
t.StackSys = readUint64(r)
t.MSpanInuse = readUint64(r)
t.MSpanSys = readUint64(r)
t.MCacheInuse = readUint64(r)
t.MCacheSys = readUint64(r)
t.BuckHashSys = readUint64(r)
t.GCSys = readUint64(r)
t.OtherSys = readUint64(r)
t.NextGC = readUint64(r)
t.LastGC = readUint64(r)
t.PauseTotalNs = readUint64(r)
for i := 0; i < 256; i++ {
t.PauseNs[i] = readUint64(r)
}
t.NumGC = uint32(readUint64(r))
d.Memstats = t
case tagDefer:
t := &Defer{}
t.addr = readUint64(r)
t.gp = readUint64(r)
t.argp = readUint64(r)
t.pc = readUint64(r)
t.fn = readUint64(r)
t.code = readUint64(r)
t.link = readUint64(r)
d.Defers = append(d.Defers, t)
case tagPanic:
t := &Panic{}
t.addr = readUint64(r)
t.gp = readUint64(r)
t.typ = readUint64(r)
t.data = readUint64(r)
t.defr = readUint64(r)
t.link = readUint64(r)
d.Panics = append(d.Panics, t)
case tagMemProf:
t := &MemProfEntry{}
key := readUint64(r)
t.size = readUint64(r)
nstk := readUint64(r)
for i := uint64(0); i < nstk; i++ {
fn := readString(r)
file := readString(r)
line := readUint64(r)
// TODO: intern fn, file. They will repeat a lot.
t.stack = append(t.stack, MemProfFrame{fn, file, line})
}
t.allocs = readUint64(r)
t.frees = readUint64(r)
d.MemProf = append(d.MemProf, t)
memprof[key] = t
case tagAllocSample:
t := &AllocSample{}
t.Addr = readUint64(r)
t.Prof = memprof[readUint64(r)]
d.AllocSamples = append(d.AllocSamples, t)
default:
log.Fatal("unknown record kind ", kind)
}
}
// TODO: any easy way to truncate the objects array? We could
// reclaim the fraction that append() added but we didn't need.
}
func getDwarf(execname string) *dwarf.Data {
e, err := elf.Open(execname)
if err == nil {
defer e.Close()
d, err := e.DWARF()
if err == nil {
return d
}
}
m, err := macho.Open(execname)
if err == nil {
defer m.Close()
d, err := m.DWARF()
if err == nil {
return d
}
}
p, err := pe.Open(execname)
if err == nil {
defer p.Close()
d, err := p.DWARF()
if err == nil {
return d
}
}
log.Fatal("can't get dwarf info from executable", err)
return nil
}
func readUleb(b []byte) ([]byte, uint64) {
r := uint64(0)
s := uint(0)
for {
x := b[0]
b = b[1:]
r |= uint64(x&127) << s
if x&128 == 0 {
break
}
s += 7
}
return b, r
}
func readSleb(b []byte) ([]byte, int64) {
c, v := readUleb(b)
// sign extend
k := (len(b) - len(c)) * 7
return c, int64(v) << uint(64-k) >> uint(64-k)
}
func joinNames(a, b string) string {
if a == "" {
return b
}
if b == "" {
return a
}
return fmt.Sprintf("%s.%s", a, b)
}
type dwarfType interface {
// Name returns the name of this type
Name() string
// Size returns the size of this type in bytes
Size() uint64
// Fields returns a list of fields within the object, in increasing offset order.
Fields() []Field
}
type dwarfTypeImpl struct {
name string
size uint64
fields []Field
}
type dwarfBaseType struct {
dwarfTypeImpl
encoding int64
}
type dwarfTypedef struct {
dwarfTypeImpl
type_ dwarfType
}
type dwarfStructType struct {
dwarfTypeImpl
members []dwarfTypeMember
}
type dwarfTypeMember struct {
name string
offset uint64
type_ dwarfType
}
type dwarfPtrType struct {
dwarfTypeImpl
elem dwarfType
}
type dwarfArrayType struct {
dwarfTypeImpl
elem dwarfType
}
type dwarfFuncType struct {
dwarfTypeImpl
}
func (t *dwarfTypeImpl) Name() string {
return t.name
}
func (t *dwarfTypeImpl) Size() uint64 {
return t.size
}
func (t *dwarfBaseType) Fields() []Field {
if t.fields != nil {
return t.fields
}
switch {
case t.encoding == dw_ate_boolean:
t.fields = append(t.fields, Field{FieldKindBool, 0, "", ""})
case t.encoding == dw_ate_signed && t.size == 1:
t.fields = append(t.fields, Field{FieldKindSInt8, 0, "", ""})
case t.encoding == dw_ate_unsigned && t.size == 1:
t.fields = append(t.fields, Field{FieldKindUInt8, 0, "", ""})
case t.encoding == dw_ate_signed && t.size == 2:
t.fields = append(t.fields, Field{FieldKindSInt16, 0, "", ""})
case t.encoding == dw_ate_unsigned && t.size == 2:
t.fields = append(t.fields, Field{FieldKindUInt16, 0, "", ""})
case t.encoding == dw_ate_signed && t.size == 4:
t.fields = append(t.fields, Field{FieldKindSInt32, 0, "", ""})
case t.encoding == dw_ate_unsigned && t.size == 4:
t.fields = append(t.fields, Field{FieldKindUInt32, 0, "", ""})
case t.encoding == dw_ate_signed && t.size == 8:
t.fields = append(t.fields, Field{FieldKindSInt64, 0, "", ""})
case t.encoding == dw_ate_unsigned && t.size == 8:
t.fields = append(t.fields, Field{FieldKindUInt64, 0, "", ""})
case t.encoding == dw_ate_float && t.size == 4:
t.fields = append(t.fields, Field{FieldKindFloat32, 0, "", ""})
case t.encoding == dw_ate_float && t.size == 8:
t.fields = append(t.fields, Field{FieldKindFloat64, 0, "", ""})
case t.encoding == dw_ate_complex_float && t.size == 8:
t.fields = append(t.fields, Field{FieldKindComplex64, 0, "", ""})
case t.encoding == dw_ate_complex_float && t.size == 16:
t.fields = append(t.fields, Field{FieldKindComplex128, 0, "", ""})
default:
log.Fatalf("unknown encoding type encoding=%d size=%d", t.encoding, t.size)
}
return t.fields
}
func (t *dwarfTypedef) Fields() []Field {
return t.type_.Fields()
}
func (t *dwarfTypedef) Size() uint64 {
return t.type_.Size()
}
var unkBase = "unkBase"
func (t *dwarfPtrType) Fields() []Field {
if t.fields == nil {
if t.Name()[0] == '*' {
t.fields = append(t.fields, Field{FieldKindPtr, 0, "", t.Name()[1:]})
} else {
t.fields = append(t.fields, Field{FieldKindPtr, 0, "", unkBase})
}
}
return t.fields
}
func (t *dwarfFuncType) Fields() []Field {
if t.fields == nil {
t.fields = append(t.fields, Field{FieldKindPtr, 0, "", unkBase})
}
return t.fields
}
func (t *dwarfStructType) Fields() []Field {
if t.fields != nil {
return t.fields
}
// Iterate over members, flatten fields.
// Don't look inside strings, interfaces, slices.
switch {
case t.name == "string":
t.fields = append(t.fields, Field{FieldKindString, 0, "", ""})
case t.name == "runtime.iface":
t.fields = append(t.fields, Field{FieldKindIface, 0, "", unkBase})
case t.name == "runtime.eface":
t.fields = append(t.fields, Field{FieldKindEface, 0, "", ""})
default:
// Detect slices. TODO: This could be fooled by the right user
// code, so find a better way.
if len(t.members) == 3 &&
t.members[0].name == "array" &&
t.members[1].name == "len" &&
t.members[2].name == "cap" &&
t.members[0].offset == 0 &&
t.members[1].offset == t.members[0].type_.Size() &&
t.members[2].offset == 2*t.members[0].type_.Size() {
_, aok := t.members[0].type_.(*dwarfPtrType)
l, lok := t.members[1].type_.(*dwarfBaseType)
c, cok := t.members[2].type_.(*dwarfBaseType)
if aok && lok && cok && l.encoding == dw_ate_unsigned && c.encoding == dw_ate_unsigned {
t.fields = append(t.fields, Field{FieldKindSlice, 0, "", t.members[0].type_.Name()[1:]})
break
}
}
for _, m := range t.members {
for _, f := range m.type_.Fields() {
t.fields = append(t.fields, Field{f.Kind, m.offset + f.Offset, joinNames(m.name, f.Name), f.BaseType})
}
}
}
return t.fields
}
func (t *dwarfArrayType) Fields() []Field {
if t.fields != nil {
return t.fields
}
s := t.elem.Size()
if s == 0 {
return t.fields
}
n := t.Size() / s
fields := t.elem.Fields()
for i := uint64(0); i < n; i++ {
for _, f := range fields {
t.fields = append(t.fields, Field{f.Kind, i*s + f.Offset, joinNames(fmt.Sprintf("%d", i), f.Name), f.BaseType})
}
}
return t.fields
}
// Some type names in the dwarf info don't match the corresponding
// type names in the binary. We'll use the rewrites here to map
// between the two.
// TODO: just map names for now. Rename this? Do this conversion in the dwarf dumper?
type adjTypeName struct {
matcher *regexp.Regexp
formatter string
}
var adjTypeNames = []adjTypeName{
{regexp.MustCompile(`hash<(.*),(.*)>`), "map.hdr[%s]%s"},
{regexp.MustCompile(`bucket<(.*),(.*)>`), "map.bucket[%s]%s"},
}
// load a map of all of the dwarf types
func typeMap(d *Dump, w *dwarf.Data) map[dwarf.Offset]dwarfType {
t := make(map[dwarf.Offset]dwarfType)
// pass 1: make a dwarfType for all of the types in the file
r := w.Reader()
for {
e, err := r.Next()
if err != nil {
log.Fatal(err)
}
if e == nil {