-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrecord.go
More file actions
1474 lines (1292 loc) · 42.6 KB
/
Copy pathrecord.go
File metadata and controls
1474 lines (1292 loc) · 42.6 KB
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
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package perf
import (
"context"
"errors"
"fmt"
"math/bits"
"os"
"sync/atomic"
"time"
"unsafe"
"golang.org/x/sys/unix"
)
// ErrDisabled is returned from ReadRecord and ReadRawRecord if the event
// being monitored is attached to a different process, and that process
// exits. (since Linux 3.18)
var ErrDisabled = errors.New("perf: event disabled")
// ErrNoReadRecord is returned by ReadRecord when it is disabled on a
// group event, due to different configurations of the leader and follower
// events. See also (*Event).SetOutput.
var ErrNoReadRecord = errors.New("perf: ReadRecord disabled")
// ReadRecord reads and decodes a record from the ring buffer associated
// with ev.
//
// ReadRecord may be called concurrently with ReadCount or ReadGroupCount,
// but not concurrently with itself, ReadRawRecord, Close, or any other
// Event method.
//
// If another event's records were routed to ev via SetOutput, and the
// two events did not have compatible SampleFormat Options settings (see
// SetOutput documentation), ReadRecord returns ErrNoReadRecord.
func (ev *Event) ReadRecord(ctx context.Context) (Record, error) {
if err := ev.ok(); err != nil {
return nil, err
}
if ev.noReadRecord {
return nil, ErrNoReadRecord
}
var raw RawRecord
if err := ev.ReadRawRecord(ctx, &raw); err != nil {
return nil, err
}
rec, err := newRecord(ev, raw.Header.Type)
if err != nil {
return nil, err
}
rec.DecodeFrom(&raw, ev)
return rec, nil
}
// ReadRawRecord reads and decodes a raw record from the ring buffer
// associated with ev into rec. Callers must not retain rec.Data.
//
// ReadRawRecord may be called concurrently with ReadCount or ReadGroupCount,
// but not concurrently with itself, ReadRecord, Close or any other Event
// method.
func (ev *Event) ReadRawRecord(ctx context.Context, raw *RawRecord) error {
if err := ev.ok(); err != nil {
return err
}
if ev.ring == nil {
return errors.New("perf: event ring not mapped")
}
// Fast path: try reading from the ring buffer first. If there is
// a record there, we are done.
if ev.readRawRecordNonblock(raw) {
return nil
}
// If the context has a deadline, and that deadline is in the future,
// use it to compute a timeout for ppoll(2). If the context is
// expired, bail out immediately. Otherwise, the timeout is zero,
// which means no timeout.
var timeout time.Duration
deadline, ok := ctx.Deadline()
if ok {
timeout = time.Until(deadline)
if timeout <= 0 {
<-ctx.Done()
return ctx.Err()
}
}
// Start a round of polling, then await results. Only one request
// can be in flight at a time, and the whole request-response cycle
// is owned by the current invocation of ReadRawRecord.
again:
ev.pollreq <- pollreq{timeout: timeout}
select {
case <-ctx.Done():
active := false
err := ctx.Err()
if err == context.Canceled {
// Initiate active wakeup on ev.wakeupfd, and wait for
// doPoll to return. doPoll might miss this signal,
// but that's okay: see below.
val := uint64(1)
buf := (*[8]byte)(unsafe.Pointer(&val))[:]
unix.Write(ev.wakeupfd, buf)
active = true
}
<-ev.pollresp
// We don't know if doPoll woke up due to our active wakeup
// or because it timed out. It doesn't make a difference.
// The important detail here is that doPoll does not touch
// ev.wakeupfd (besides polling it for readiness). If we
// initiated active wakeup, we must restore the event file
// descriptor to quiescent state ourselves, in order to avoid
// a spurious wakeup during the next round of polling.
if active {
var buf [8]byte
unix.Read(ev.wakeupfd, buf[:])
}
return err
case resp := <-ev.pollresp:
if resp.err != nil {
// Polling failed. Nothing to do but report the error.
return resp.err
}
if resp.perfhup {
// Saw POLLHUP on ev.perffd. See also the
// documentation for ErrDisabled.
return ErrDisabled
}
if !resp.perfready {
// Here, we have not touched ev.wakeupfd, there
// was no polling error, and ev.perffd is not
// ready. Therefore, ppoll(2) must have timed out.
//
// The reason we are here is the following: doPoll
// woke up, and immediately sent us a pollresp, which
// won the race with <-ctx.Done(), such that this
// select case fired. In any case, ctx is expired,
// because we wouldn't be here otherwise.
<-ctx.Done()
return ctx.Err()
}
if !ev.readRawRecordNonblock(raw) {
// It might happen that an overflow notification was
// generated on the file descriptor, we observed it
// as POLLIN, but there is still nothing new for us
// to read in the ring buffer.
//
// This is because the notification is raised based
// on the Attr.Wakeup and Attr.Options.Watermark
// settings, rather than based on what events we've
// seen already.
//
// For example, for an event with Attr.Wakeup == 1,
// POLLIN will be indicated on the file descriptor
// after the first event, regardless of whether we
// have consumed it from the ring buffer or not.
//
// If we happen to see POLLIN with an empty ring
// buffer, the only thing to do is to wait again.
//
// See also https://github.com/acln0/perfwakeup.
goto again
}
return nil
}
}
// readRawRecordNonblock reads a raw record into rec, if one is available.
// Callers must not retain rec.Data. The boolean return value signals whether
// a record was actually found / written to rec.
func (ev *Event) readRawRecordNonblock(raw *RawRecord) bool {
head := atomic.LoadUint64(&ev.meta.Data_head)
tail := atomic.LoadUint64(&ev.meta.Data_tail)
if head == tail {
return false
}
// Head and tail values only ever grow, so we must take their value
// modulo the size of the data segment of the ring.
start := tail % uint64(len(ev.ringdata))
raw.Header = *(*RecordHeader)(unsafe.Pointer(&ev.ringdata[start]))
end := (tail + uint64(raw.Header.Size)) % uint64(len(ev.ringdata))
// If the record wraps around the ring, we must allocate storage,
// so that we can return a contiguous area of memory to the caller.
var data []byte
if end < start {
data = make([]byte, raw.Header.Size)
n := copy(data, ev.ringdata[start:])
copy(data[n:], ev.ringdata[:int(raw.Header.Size)-n])
} else {
data = ev.ringdata[start:end]
}
raw.Data = data[unsafe.Sizeof(raw.Header):]
// Notify the kernel of the last record we've seen.
atomic.AddUint64(&ev.meta.Data_tail, uint64(raw.Header.Size))
return true
}
// poll services requests from ev.pollreq and sends responses on ev.pollresp.
func (ev *Event) poll() {
defer close(ev.pollresp)
for req := range ev.pollreq {
ev.pollresp <- ev.doPoll(req)
}
}
// doPoll executes one round of polling on ev.perffd and ev.wakeupfd.
//
// A req.timeout value of zero is interpreted as "no timeout". req.timeout
// must not be negative.
func (ev *Event) doPoll(req pollreq) pollresp {
var timeout *unix.Timespec
if req.timeout > 0 {
sec := int64(req.timeout / time.Second)
nsec := int64(req.timeout) - sec*int64(time.Second)
timeout = &unix.Timespec{Sec: sec, Nsec: nsec}
}
pollfds := []unix.PollFd{
{Fd: int32(ev.perffd), Events: unix.POLLIN},
{Fd: int32(ev.wakeupfd), Events: unix.POLLIN},
}
again:
_, err := unix.Ppoll(pollfds, timeout, nil)
// TODO(acln): do we need to do this business at all? See #20400.
if err == unix.EINTR {
goto again
}
// If we are here and we have successfully woken up, it is for one
// of four reasons: we got POLLIN on ev.perffd, we got POLLHUP on
// ev.perffd (see ErrDisabled), the ppoll(2) timeout fired, or we
// got POLLIN on ev.wakeupfd.
//
// Report if the perf fd is ready, if we saw POLLHUP, and any
// errors except EINTR. The machinery is documented in more detail
// in ReadRawRecord.
return pollresp{
perfready: pollfds[0].Revents&unix.POLLIN != 0,
perfhup: pollfds[0].Revents&unix.POLLHUP != 0,
err: os.NewSyscallError("ppoll", err),
}
}
type pollreq struct {
// timeout is the timeout for ppoll(2): zero means no timeout
timeout time.Duration
}
type pollresp struct {
// perfready indicates if the perf FD (ev.perffd) is ready.
perfready bool
// perfhup indicates if POLLUP was observed on ev.perffd.
perfhup bool
// err is the *os.SyscallError from ppoll(2).
err error
}
// SampleFormat configures information requested in overflow packets.
type SampleFormat struct {
// IP records the instruction pointer.
IP bool
// Tid records process and thread IDs.
Tid bool
// Time records a hardware timestamp.
Time bool
// Addr records an address, if applicable.
Addr bool
// Count records counter values for all events in a group, not just
// the group leader.
Count bool
// Callchain records the stack backtrace.
Callchain bool
// ID records a unique ID for the opened event's group leader.
ID bool
// CPU records the CPU number.
CPU bool
// Period records the current sampling period.
Period bool
// StreamID returns a unique ID for the opened event. Unlike ID,
// the actual ID is returned, not the group ID.
StreamID bool
// Raw records additional data, if applicable. Usually returned by
// tracepoint events.
Raw bool
// BranchStack provides a record of recent branches, as provided by
// CPU branch sampling hardware. See also Attr.BranchSampleFormat.
BranchStack bool
// UserRegisters records the current user-level CPU state (the
// values in the process before the kernel was called). See also
// Attr.SampleRegistersUser.
UserRegisters bool
// UserStack records the user level stack, allowing stack unwinding.
UserStack bool
// Weight records a hardware provided weight value that expresses
// how costly the sampled event was.
Weight bool
// DataSource records the data source: where in the memory hierarchy
// the data associated with the sampled instruction came from.
DataSource bool
// Identifier places the ID value in a fixed position in the record.
Identifier bool
// Transaction records reasons for transactional memory abort events.
Transaction bool
// IntrRegisters Records a subset of the current CPU register state.
// Unlike UserRegisters, the registers will return kernel register
// state if the overflow happened while kernel code is running. See
// also Attr.SampleRegistersIntr.
IntrRegisters bool
PhysicalAddress bool
}
// TODO(acln): document SampleFormat.PhysicalAddress
// marshal packs the SampleFormat into a uint64.
func (sf SampleFormat) marshal() uint64 {
// Always keep this in sync with the type definition above.
fields := []bool{
sf.IP,
sf.Tid,
sf.Time,
sf.Addr,
sf.Count,
sf.Callchain,
sf.ID,
sf.CPU,
sf.Period,
sf.StreamID,
sf.Raw,
sf.BranchStack,
sf.UserRegisters,
sf.UserStack,
sf.Weight,
sf.DataSource,
sf.Identifier,
sf.Transaction,
sf.IntrRegisters,
sf.PhysicalAddress,
}
return marshalBitwiseUint64(fields)
}
// SampleID contains identifiers for when and where a record was collected.
//
// A SampleID is included in a Record if Options.SampleIDAll is set on the
// associated event. Fields are set according to SampleFormat options.
type SampleID struct {
Pid uint32
Tid uint32
Time uint64
ID uint64
StreamID uint64
CPU uint32
_ uint32 // reserved
Identifier uint64
}
// Record is the interface implemented by all record types.
type Record interface {
Header() RecordHeader
DecodeFrom(*RawRecord, *Event)
}
// RecordType is the type of an overflow record.
type RecordType uint32
// Known record types.
const (
RecordTypeMmap RecordType = unix.PERF_RECORD_MMAP
RecordTypeLost RecordType = unix.PERF_RECORD_LOST
RecordTypeComm RecordType = unix.PERF_RECORD_COMM
RecordTypeExit RecordType = unix.PERF_RECORD_EXIT
RecordTypeThrottle RecordType = unix.PERF_RECORD_THROTTLE
RecordTypeUnthrottle RecordType = unix.PERF_RECORD_UNTHROTTLE
RecordTypeFork RecordType = unix.PERF_RECORD_FORK
RecordTypeRead RecordType = unix.PERF_RECORD_READ
RecordTypeSample RecordType = unix.PERF_RECORD_SAMPLE
RecordTypeMmap2 RecordType = unix.PERF_RECORD_MMAP2
RecordTypeAux RecordType = unix.PERF_RECORD_AUX
RecordTypeItraceStart RecordType = unix.PERF_RECORD_ITRACE_START
RecordTypeLostSamples RecordType = unix.PERF_RECORD_LOST_SAMPLES
RecordTypeSwitch RecordType = unix.PERF_RECORD_SWITCH
RecordTypeSwitchCPUWide RecordType = unix.PERF_RECORD_SWITCH_CPU_WIDE
RecordTypeNamespaces RecordType = unix.PERF_RECORD_NAMESPACES
)
func (rt RecordType) known() bool {
return rt >= RecordTypeMmap && rt <= RecordTypeNamespaces
}
// RecordHeader is the header present in every overflow record.
type RecordHeader struct {
Type RecordType
Misc uint16
Size uint16
}
// Header returns rh itself, so that types which embed a RecordHeader
// automatically implement a part of the Record interface.
func (rh RecordHeader) Header() RecordHeader { return rh }
// CPUMode returns the CPU mode in use when the sample happened.
func (rh RecordHeader) CPUMode() CPUMode {
return CPUMode(rh.Misc & cpuModeMask)
}
// CPUMode is a CPU operation mode.
type CPUMode uint8
const cpuModeMask = 7
// Known CPU modes.
const (
UnknownMode CPUMode = iota
KernelMode
UserMode
HypervisorMode
GuestKernelMode
GuestUserMode
)
// RawRecord is a raw overflow record, read from the memory mapped ring
// buffer associated with an Event.
//
// Header is the 8 byte record header. Data contains the rest of the record.
type RawRecord struct {
Header RecordHeader
Data []byte
}
func (raw RawRecord) fields() fields { return fields(raw.Data) }
var newRecordFuncs = [...]func(ev *Event) Record{
RecordTypeMmap: func(_ *Event) Record { return &MmapRecord{} },
RecordTypeLost: func(_ *Event) Record { return &LostRecord{} },
RecordTypeComm: func(_ *Event) Record { return &CommRecord{} },
RecordTypeExit: func(_ *Event) Record { return &ExitRecord{} },
RecordTypeThrottle: func(_ *Event) Record { return &ThrottleRecord{} },
RecordTypeUnthrottle: func(_ *Event) Record { return &UnthrottleRecord{} },
RecordTypeFork: func(_ *Event) Record { return &ForkRecord{} },
RecordTypeRead: newReadRecord,
RecordTypeSample: newSampleRecord,
RecordTypeMmap2: func(_ *Event) Record { return &Mmap2Record{} },
RecordTypeAux: func(_ *Event) Record { return &AuxRecord{} },
RecordTypeItraceStart: func(_ *Event) Record { return &ItraceStartRecord{} },
RecordTypeLostSamples: func(_ *Event) Record { return &LostSamplesRecord{} },
RecordTypeSwitch: func(_ *Event) Record { return &SwitchRecord{} },
RecordTypeSwitchCPUWide: func(_ *Event) Record { return &SwitchCPUWideRecord{} },
RecordTypeNamespaces: func(_ *Event) Record { return &NamespacesRecord{} },
}
func newReadRecord(ev *Event) Record {
if ev.a.CountFormat.Group {
return &ReadGroupRecord{}
}
return &ReadRecord{}
}
func newSampleRecord(ev *Event) Record {
if ev.a.CountFormat.Group {
return &SampleGroupRecord{}
}
return &SampleRecord{}
}
// newRecord returns an empty Record of the given type, tailored for the
// specified Event.
func newRecord(ev *Event, rt RecordType) (Record, error) {
if !rt.known() {
return nil, fmt.Errorf("unknown record type %d", rt)
}
return newRecordFuncs[rt](ev), nil
}
// mmapDataBit is PERF_RECORD_MISC_MMAP_DATA
const mmapDataBit = 1 << 13
// MmapRecord (PERF_RECORD_MMAP) records PROT_EXEC mappings such that
// user-space IPs can be correlated to code.
type MmapRecord struct {
RecordHeader
Pid uint32 // process ID
Tid uint32 // thread ID
Addr uint64 // address of the allocated memory
Len uint64 // length of the allocated memory
PageOffset uint64 // page offset of the allocated memory
Filename string // describes backing of allocated memory
SampleID
}
// DecodeFrom implements the Record.DecodeFrom method.
func (mr *MmapRecord) DecodeFrom(raw *RawRecord, ev *Event) {
mr.RecordHeader = raw.Header
f := raw.fields()
f.uint32(&mr.Pid, &mr.Tid)
f.uint64(&mr.Addr)
f.uint64(&mr.Len)
f.uint64(&mr.PageOffset)
f.string(&mr.Filename)
f.idCond(ev.a.Options.SampleIDAll, &mr.SampleID, ev.a.SampleFormat)
}
// Executable returns a boolean indicating whether the mapping is executable.
func (mr *MmapRecord) Executable() bool {
// The data bit is set when the mapping is _not_ executable.
return mr.RecordHeader.Misc&mmapDataBit == 0
}
// LostRecord (PERF_RECORD_LOST) indicates when events are lost.
type LostRecord struct {
RecordHeader
ID uint64 // the unique ID for the lost events
Lost uint64 // the number of lost events
SampleID
}
// DecodeFrom implements the Record.DecodeFrom method.
func (lr *LostRecord) DecodeFrom(raw *RawRecord, ev *Event) {
lr.RecordHeader = raw.Header
f := raw.fields()
f.uint64(&lr.ID)
f.uint64(&lr.Lost)
f.idCond(ev.a.Options.SampleIDAll, &lr.SampleID, ev.a.SampleFormat)
}
// CommRecord (PERF_RECORD_COMM) indicates a change in the process name.
type CommRecord struct {
RecordHeader
Pid uint32 // process ID
Tid uint32 // threadID
NewName string // the new name of the process
SampleID
}
// DecodeFrom implements the Record.DecodeFrom method.
func (cr *CommRecord) DecodeFrom(raw *RawRecord, ev *Event) {
cr.RecordHeader = raw.Header
f := raw.fields()
f.uint32(&cr.Pid, &cr.Tid)
f.string(&cr.NewName)
f.idCond(ev.a.Options.SampleIDAll, &cr.SampleID, ev.a.SampleFormat)
}
// commExecBit is PERF_RECORD_MISC_COMM_EXEC
const commExecBit = 1 << 13
// WasExec returns a boolean indicating whether a process name change
// was caused by an exec(2) system call.
func (cr *CommRecord) WasExec() bool {
return cr.RecordHeader.Misc&(commExecBit) != 0
}
// ExitRecord (PERF_RECORD_EXIT) indicates a process exit event.
type ExitRecord struct {
RecordHeader
Pid uint32 // process ID
Ppid uint32 // parent process ID
Tid uint32 // thread ID
Ptid uint32 // parent thread ID
Time uint64 // time when the process exited
SampleID
}
// DecodeFrom implements the Record.DecodeFrom method.
func (er *ExitRecord) DecodeFrom(raw *RawRecord, ev *Event) {
er.RecordHeader = raw.Header
f := raw.fields()
f.uint32(&er.Pid, &er.Ppid)
f.uint32(&er.Tid, &er.Ptid)
f.uint64(&er.Time)
f.idCond(ev.a.Options.SampleIDAll, &er.SampleID, ev.a.SampleFormat)
}
// ThrottleRecord (PERF_RECORD_THROTTLE) indicates a throttle event.
type ThrottleRecord struct {
RecordHeader
Time uint64
ID uint64
StreamID uint64
SampleID
}
// DecodeFrom implements the Record.DecodeFrom method.
func (tr *ThrottleRecord) DecodeFrom(raw *RawRecord, ev *Event) {
tr.RecordHeader = raw.Header
f := raw.fields()
f.uint64(&tr.Time)
f.uint64(&tr.ID)
f.uint64(&tr.StreamID)
f.idCond(ev.a.Options.SampleIDAll, &tr.SampleID, ev.a.SampleFormat)
}
// UnthrottleRecord (PERF_RECORD_UNTHROTTLE) indicates an unthrottle event.
type UnthrottleRecord struct {
RecordHeader
Time uint64
ID uint64
StreamID uint64
SampleID
}
// DecodeFrom implements the Record.DecodeFrom method.
func (ur *UnthrottleRecord) DecodeFrom(raw *RawRecord, ev *Event) {
ur.RecordHeader = raw.Header
f := raw.fields()
f.uint64(&ur.Time)
f.uint64(&ur.ID)
f.uint64(&ur.StreamID)
f.idCond(ev.a.Options.SampleIDAll, &ur.SampleID, ev.a.SampleFormat)
}
// ForkRecord (PERF_RECORD_FORK) indicates a fork event.
type ForkRecord struct {
RecordHeader
Pid uint32 // process ID
Ppid uint32 // parent process ID
Tid uint32 // thread ID
Ptid uint32 // parent thread ID
Time uint64 // time when the fork occurred
SampleID
}
// DecodeFrom implements the Record.DecodeFrom method.
func (fr *ForkRecord) DecodeFrom(raw *RawRecord, ev *Event) {
fr.RecordHeader = raw.Header
f := raw.fields()
f.uint32(&fr.Pid, &fr.Ppid)
f.uint32(&fr.Tid, &fr.Ptid)
f.uint64(&fr.Time)
f.idCond(ev.a.Options.SampleIDAll, &fr.SampleID, ev.a.SampleFormat)
}
// ReadRecord (PERF_RECORD_READ) indicates a read event.
type ReadRecord struct {
RecordHeader
Pid uint32 // process ID
Tid uint32 // thread ID
Count Count // count value
SampleID
}
// DecodeFrom implements the Record.DecodeFrom method.
func (rr *ReadRecord) DecodeFrom(raw *RawRecord, ev *Event) {
rr.RecordHeader = raw.Header
f := raw.fields()
f.uint32(&rr.Pid, &rr.Tid)
f.count(&rr.Count, ev.a.CountFormat)
f.idCond(ev.a.Options.SampleIDAll, &rr.SampleID, ev.a.SampleFormat)
}
// ReadGroupRecord (PERF_RECORD_READ) indicates a read event on a group event.
type ReadGroupRecord struct {
RecordHeader
Pid uint32 // process ID
Tid uint32 // thread ID
GroupCount GroupCount // group count values
SampleID
}
// DecodeFrom implements the Record.DecodeFrom method.
func (rr *ReadGroupRecord) DecodeFrom(raw *RawRecord, ev *Event) {
rr.RecordHeader = raw.Header
f := raw.fields()
f.uint32(&rr.Pid, &rr.Tid)
f.groupCount(&rr.GroupCount, ev.a.CountFormat)
f.idCond(ev.a.Options.SampleIDAll, &rr.SampleID, ev.a.SampleFormat)
}
// SampleRecord indicates a sample.
//
// All the fields up to and including Callchain represent ABI bits. All the
// fields starting with Data are non-ABI and have no compatibility guarantees.
//
// Fields on SampleRecord are set according to the SampleFormat the event
// was configured with. A boolean flag in SampleFormat typically enables
// the homonymous field in a SampleRecord.
type SampleRecord struct {
RecordHeader
Identifier uint64
IP uint64
Pid uint32
Tid uint32
Time uint64
Addr uint64
ID uint64
StreamID uint64
CPU uint32
_ uint32 // reserved
Period uint64
Count Count
Callchain []uint64
Raw []byte
BranchStack []BranchEntry
UserRegisterABI uint64
UserRegisters []uint64
UserStack []byte
UserStackDynamicSize uint64
Weight uint64
DataSource DataSource
Transaction Transaction
IntrRegisterABI uint64
IntrRegisters []uint64
PhysicalAddress uint64
}
// DecodeFrom implements the Record.DecodeFrom method.
func (sr *SampleRecord) DecodeFrom(raw *RawRecord, ev *Event) {
sr.RecordHeader = raw.Header
f := raw.fields()
f.uint64Cond(ev.a.SampleFormat.Identifier, &sr.Identifier)
f.uint64Cond(ev.a.SampleFormat.IP, &sr.IP)
f.uint32Cond(ev.a.SampleFormat.Tid, &sr.Pid, &sr.Tid)
f.uint64Cond(ev.a.SampleFormat.Time, &sr.Time)
f.uint64Cond(ev.a.SampleFormat.Addr, &sr.Addr)
f.uint64Cond(ev.a.SampleFormat.ID, &sr.ID)
f.uint64Cond(ev.a.SampleFormat.StreamID, &sr.StreamID)
// If we have a StreamID and it is different from our
// own ID, then the output from the event we're interested
// in was redirected to ev. We must switch to that event
// in order to decode the sample.
if ev.a.SampleFormat.StreamID {
if sr.StreamID != ev.id {
ev = ev.groupByID[sr.StreamID]
}
}
var reserved uint32
f.uint32Cond(ev.a.SampleFormat.CPU, &sr.CPU, &reserved)
f.uint64Cond(ev.a.SampleFormat.Period, &sr.Period)
if ev.a.SampleFormat.Count {
f.count(&sr.Count, ev.a.CountFormat)
}
if ev.a.SampleFormat.Callchain {
var nr uint64
f.uint64(&nr)
sr.Callchain = make([]uint64, nr)
for i := 0; i < len(sr.Callchain); i++ {
f.uint64(&sr.Callchain[i])
}
}
if ev.a.SampleFormat.Raw {
f.uint32sizeBytes(&sr.Raw)
}
if ev.a.SampleFormat.BranchStack {
var nr uint64
f.uint64(&nr)
sr.BranchStack = make([]BranchEntry, nr)
for i := 0; i < len(sr.BranchStack); i++ {
var from, to, entry uint64
f.uint64(&from)
f.uint64(&to)
f.uint64(&entry)
sr.BranchStack[i].decode(from, to, entry)
}
}
if ev.a.SampleFormat.UserRegisters {
f.uint64(&sr.UserRegisterABI)
num := bits.OnesCount64(ev.a.SampleRegistersUser)
sr.UserRegisters = make([]uint64, num)
for i := 0; i < len(sr.UserRegisters); i++ {
f.uint64(&sr.UserRegisters[i])
}
}
if ev.a.SampleFormat.UserStack {
f.uint64sizeBytes(&sr.UserStack)
if len(sr.UserStack) > 0 {
f.uint64(&sr.UserStackDynamicSize)
}
}
f.uint64Cond(ev.a.SampleFormat.Weight, &sr.Weight)
if ev.a.SampleFormat.DataSource {
var ds uint64
f.uint64(&ds)
sr.DataSource = DataSource(ds)
}
if ev.a.SampleFormat.Transaction {
var tx uint64
f.uint64(&tx)
sr.Transaction = Transaction(tx)
}
if ev.a.SampleFormat.IntrRegisters {
f.uint64(&sr.IntrRegisterABI)
num := bits.OnesCount64(ev.a.SampleRegistersIntr)
sr.IntrRegisters = make([]uint64, num)
for i := 0; i < len(sr.IntrRegisters); i++ {
f.uint64(&sr.IntrRegisters[i])
}
}
f.uint64Cond(ev.a.SampleFormat.PhysicalAddress, &sr.PhysicalAddress)
}
// exactIPBit is PERF_RECORD_MISC_EXACT_IP
const exactIPBit = 1 << 14
// ExactIP indicates that sr.IP points to the actual instruction that
// triggered the event. See also Options.PreciseIP.
func (sr *SampleRecord) ExactIP() bool {
return sr.RecordHeader.Misc&exactIPBit != 0
}
// SampleGroupRecord indicates a sample from an event group.
//
// All the fields up to and including Callchain represent ABI bits. All the
// fields starting with Data are non-ABI and have no compatibility guarantees.
//
// Fields on SampleGroupRecord are set according to the RecordFormat the event
// was configured with. A boolean flag in RecordFormat typically enables the
// homonymous field in SampleGroupRecord.
type SampleGroupRecord struct {
RecordHeader
Identifier uint64
IP uint64
Pid uint32
Tid uint32
Time uint64
Addr uint64
ID uint64
StreamID uint64
CPU uint32
_ uint32
Period uint64
Count GroupCount
Callchain []uint64
Raw []byte
BranchStack []BranchEntry
UserRegisterABI uint64
UserRegisters []uint64
UserStack []byte
UserStackDynamicSize uint64
Weight uint64
DataSource DataSource
Transaction Transaction
IntrRegisterABI uint64
IntrRegisters []uint64
PhysicalAddress uint64
}
// DecodeFrom implements the Record.DecodeFrom method.
func (sr *SampleGroupRecord) DecodeFrom(raw *RawRecord, ev *Event) {
sr.RecordHeader = raw.Header
f := raw.fields()
f.uint64Cond(ev.a.SampleFormat.Identifier, &sr.Identifier)
f.uint64Cond(ev.a.SampleFormat.IP, &sr.IP)
f.uint32Cond(ev.a.SampleFormat.Tid, &sr.Pid, &sr.Tid)
f.uint64Cond(ev.a.SampleFormat.Time, &sr.Time)
f.uint64Cond(ev.a.SampleFormat.Addr, &sr.Addr)
f.uint64Cond(ev.a.SampleFormat.ID, &sr.ID)
f.uint64Cond(ev.a.SampleFormat.StreamID, &sr.StreamID)
// If we have a StreamID and it is different from our
// own ID, then the output from the event we're interested
// in was redirected to ev. We must switch to that event
// in order to decode the sample.
if ev.a.SampleFormat.StreamID {
if sr.StreamID != ev.id {
ev = ev.groupByID[sr.StreamID]
}
}
var reserved uint32
f.uint32Cond(ev.a.SampleFormat.CPU, &sr.CPU, &reserved)
f.uint64Cond(ev.a.SampleFormat.Period, &sr.Period)
if ev.a.SampleFormat.Count {
f.groupCount(&sr.Count, ev.a.CountFormat)
}
if ev.a.SampleFormat.Callchain {
var nr uint64
f.uint64(&nr)
sr.Callchain = make([]uint64, nr)
for i := 0; i < len(sr.Callchain); i++ {
f.uint64(&sr.Callchain[i])
}
}
if ev.a.SampleFormat.Raw {
f.uint32sizeBytes(&sr.Raw)
}
if ev.a.SampleFormat.BranchStack {
var nr uint64
f.uint64(&nr)
sr.BranchStack = make([]BranchEntry, nr)
for i := 0; i < len(sr.BranchStack); i++ {
var from, to, entry uint64
f.uint64(&from)
f.uint64(&to)
f.uint64(&entry)
sr.BranchStack[i].decode(from, to, entry)
}
}
if ev.a.SampleFormat.UserRegisters {
f.uint64(&sr.UserRegisterABI)
num := bits.OnesCount64(ev.a.SampleRegistersUser)
sr.UserRegisters = make([]uint64, num)
for i := 0; i < len(sr.UserRegisters); i++ {
f.uint64(&sr.UserRegisters[i])
}
}
if ev.a.SampleFormat.UserStack {
f.uint64sizeBytes(&sr.UserStack)
if len(sr.UserStack) > 0 {
f.uint64(&sr.UserStackDynamicSize)
}
}
f.uint64Cond(ev.a.SampleFormat.Weight, &sr.Weight)
if ev.a.SampleFormat.DataSource {
var ds uint64
f.uint64(&ds)
sr.DataSource = DataSource(ds)
}
if ev.a.SampleFormat.Transaction {
var tx uint64
f.uint64(&tx)
sr.Transaction = Transaction(tx)
}
if ev.a.SampleFormat.IntrRegisters {
f.uint64(&sr.IntrRegisterABI)
num := bits.OnesCount64(ev.a.SampleRegistersIntr)
sr.IntrRegisters = make([]uint64, num)
for i := 0; i < len(sr.IntrRegisters); i++ {
f.uint64(&sr.IntrRegisters[i])
}
}
f.uint64Cond(ev.a.SampleFormat.PhysicalAddress, &sr.PhysicalAddress)
}
// ExactIP indicates that sr.IP points to the actual instruction that
// triggered the event. See also Options.PreciseIP.
func (sr *SampleGroupRecord) ExactIP() bool {
return sr.RecordHeader.Misc&exactIPBit != 0
}
// BranchEntry is a sampled branch.
type BranchEntry struct {
From uint64
To uint64
Mispredicted bool
Predicted bool
InTransaction bool
TransactionAbort bool
Cycles uint16
BranchType BranchType
}
func (be *BranchEntry) decode(from, to, entry uint64) {
*be = BranchEntry{
From: from,
To: to,
Mispredicted: entry&(1<<0) != 0,
Predicted: entry&(1<<1) != 0,
InTransaction: entry&(1<<2) != 0,
TransactionAbort: entry&(1<<3) != 0,
Cycles: uint16((entry << 44) >> 48),
BranchType: BranchType((entry << 40) >> 44),
}
}
// BranchType classifies a BranchEntry.
type BranchType uint8
// Branch classifications.
const (
BranchTypeUnknown BranchType = iota
BranchTypeConditional
BranchTypeUnconditional
BranchTypeIndirect
BranchTypeCall
BranchTypeIndirectCall