Debian Codegraph @

trace/internal/tracev1/parser.go

raw symbols SCIP
1 // Copyright 2024 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Code generated by "gen.bash" from internal/trace; DO NOT EDIT.
6
7 //go:build go1.23
8
9 // Package tracev1 implements a parser for Go execution traces from versions
10 // 1.11–1.21.
11 //
12 // The package started as a copy of Go 1.19's golang.org/x/exp/trace, but has been
13 // optimized to be faster while using less memory and fewer allocations. It has
14 // been further modified for the specific purpose of converting traces to the
15 // new 1.22+ format.
16 package tracev1
17
18 import (
19 "bytes"
20 "cmp"
21 "encoding/binary"
22 "errors"
23 "fmt"
24 "golang.org/x/exp/trace/internal/version"
25 "io"
26 "math"
27 "slices"
28 "sort"
29 )
30
31 // Timestamp represents a count of nanoseconds since the beginning of the trace.
32 // They can only be meaningfully compared with other timestamps from the same
33 // trace.
34 type Timestamp int64
35
36 // Event describes one event in the trace.
37 type Event struct {
38 // The Event type is carefully laid out to optimize its size and to avoid
39 // pointers, the latter so that the garbage collector won't have to scan any
40 // memory of our millions of events.
41
42 Ts Timestamp // timestamp in nanoseconds
43 G uint64 // G on which the event happened
44 Args [4]uint64 // event-type-specific arguments
45 StkID uint32 // unique stack ID
46 P int32 // P on which the event happened (can be a real P or one of TimerP, NetpollP, SyscallP)
47 Type EventType // one of Ev*
48 }
49
50 // Frame is a frame in stack traces.
51 type Frame struct {
52 PC uint64
53 // string ID of the function name
54 Fn uint64
55 // string ID of the file name
56 File uint64
57 Line int
58 }
59
60 const (
61 // Special P identifiers:
62 FakeP = 1000000 + iota
63 TimerP // contains timer unblocks
64 NetpollP // contains network unblocks
65 SyscallP // contains returns from syscalls
66 GCP // contains GC state
67 ProfileP // contains recording of CPU profile samples
68 )
69
70 // Trace is the result of Parse.
71 type Trace struct {
72 Version version.Version
73
74 // Events is the sorted list of Events in the trace.
75 Events Events
76 // Stacks is the stack traces (stored as slices of PCs), keyed by stack IDs
77 // from the trace.
78 Stacks map[uint32][]uint64
79 PCs map[uint64]Frame
80 Strings map[uint64]string
81 InlineStrings []string
82 }
83
84 // batchOffset records the byte offset of, and number of events in, a batch. A
85 // batch is a sequence of events emitted by a P. Events within a single batch
86 // are sorted by time.
87 type batchOffset struct {
88 offset int
89 numEvents int
90 }
91
92 type parser struct {
93 ver version.Version
94 data []byte
95 off int
96
97 strings map[uint64]string
98 inlineStrings []string
99 inlineStringsMapping map[string]int
100 // map from Ps to their batch offsets
101 batchOffsets map[int32][]batchOffset
102 stacks map[uint32][]uint64
103 stacksData []uint64
104 ticksPerSec int64
105 pcs map[uint64]Frame
106 cpuSamples []Event
107 timerGoids map[uint64]bool
108
109 // state for readRawEvent
110 args []uint64
111
112 // state for parseEvent
113 lastTs Timestamp
114 lastG uint64
115 // map from Ps to the last Gs that ran on them
116 lastGs map[int32]uint64
117 lastP int32
118 }
119
120 func (p *parser) discard(n uint64) bool {
121 if n > math.MaxInt {
122 return false
123 }
124 if noff := p.off + int(n); noff < p.off || noff > len(p.data) {
125 return false
126 } else {
127 p.off = noff
128 }
129 return true
130 }
131
132 func newParser(r io.Reader, ver version.Version) (*parser, error) {
133 var buf []byte
134 if seeker, ok := r.(io.Seeker); ok {
135 // Determine the size of the reader so that we can allocate a buffer
136 // without having to grow it later.
137 cur, err := seeker.Seek(0, io.SeekCurrent)
138 if err != nil {
139 return nil, err
140 }
141 end, err := seeker.Seek(0, io.SeekEnd)
142 if err != nil {
143 return nil, err
144 }
145 _, err = seeker.Seek(cur, io.SeekStart)
146 if err != nil {
147 return nil, err
148 }
149
150 buf = make([]byte, end-cur)
151 _, err = io.ReadFull(r, buf)
152 if err != nil {
153 return nil, err
154 }
155 } else {
156 var err error
157 buf, err = io.ReadAll(r)
158 if err != nil {
159 return nil, err
160 }
161 }
162 return &parser{data: buf, ver: ver, timerGoids: make(map[uint64]bool)}, nil
163 }
164
165 // Parse parses Go execution traces from versions 1.11–1.21. The provided reader
166 // will be read to completion and the entire trace will be materialized in
167 // memory. That is, this function does not allow incremental parsing.
168 //
169 // The reader has to be positioned just after the trace header and vers needs to
170 // be the version of the trace. This can be achieved by using
171 // version.ReadHeader.
172 func Parse(r io.Reader, vers version.Version) (Trace, error) {
173 // We accept the version as an argument because golang.org/x/exp/trace will have
174 // already read the version to determine which parser to use.
175 p, err := newParser(r, vers)
176 if err != nil {
177 return Trace{}, err
178 }
179 return p.parse()
180 }
181
182 // parse parses, post-processes and verifies the trace.
183 func (p *parser) parse() (Trace, error) {
184 defer func() {
185 p.data = nil
186 }()
187
188 // We parse a trace by running the following steps in order:
189 //
190 // 1. In the initial pass we collect information about batches (their
191 // locations and sizes.) We also parse CPU profiling samples in this
192 // step, simply to reduce the number of full passes that we need.
193 //
194 // 2. In the second pass we parse batches and merge them into a globally
195 // ordered event stream. This uses the batch information from the first
196 // pass to quickly find batches.
197 //
198 // 3. After all events have been parsed we convert their timestamps from CPU
199 // ticks to wall time. Furthermore we move timers and syscalls to
200 // dedicated, fake Ps.
201 //
202 // 4. Finally, we validate the trace.
203
204 p.strings = make(map[uint64]string)
205 p.batchOffsets = make(map[int32][]batchOffset)
206 p.lastGs = make(map[int32]uint64)
207 p.stacks = make(map[uint32][]uint64)
208 p.pcs = make(map[uint64]Frame)
209 p.inlineStringsMapping = make(map[string]int)
210
211 if err := p.collectBatchesAndCPUSamples(); err != nil {
212 return Trace{}, err
213 }
214
215 events, err := p.parseEventBatches()
216 if err != nil {
217 return Trace{}, err
218 }
219
220 if p.ticksPerSec == 0 {
221 return Trace{}, errors.New("no EvFrequency event")
222 }
223
224 if events.Len() > 0 {
225 // Translate cpu ticks to real time.
226 minTs := events.Ptr(0).Ts
227 // Use floating point to avoid integer overflows.
228 freq := 1e9 / float64(p.ticksPerSec)
229 for i := 0; i < events.Len(); i++ {
230 ev := events.Ptr(i)
231 ev.Ts = Timestamp(float64(ev.Ts-minTs) * freq)
232 // Move timers and syscalls to separate fake Ps.
233 if p.timerGoids[ev.G] && ev.Type == EvGoUnblock {
234 ev.P = TimerP
235 }
236 if ev.Type == EvGoSysExit {
237 ev.P = SyscallP
238 }
239 }
240 }
241
242 if err := p.postProcessTrace(events); err != nil {
243 return Trace{}, err
244 }
245
246 res := Trace{
247 Version: p.ver,
248 Events: events,
249 Stacks: p.stacks,
250 Strings: p.strings,
251 InlineStrings: p.inlineStrings,
252 PCs: p.pcs,
253 }
254 return res, nil
255 }
256
257 // rawEvent is a helper type used during parsing.
258 type rawEvent struct {
259 typ EventType
260 args []uint64
261 sargs []string
262
263 // if typ == EvBatch, these fields describe the batch.
264 batchPid int32
265 batchOffset int
266 }
267
268 type proc struct {
269 pid int32
270 // the remaining events in the current batch
271 events []Event
272 // buffer for reading batches into, aliased by proc.events
273 buf []Event
274
275 // there are no more batches left
276 done bool
277 }
278
279 const eventsBucketSize = 524288 // 32 MiB of events
280
281 type Events struct {
282 // Events is a slice of slices that grows one slice of size eventsBucketSize
283 // at a time. This avoids the O(n) cost of slice growth in append, and
284 // additionally allows consumers to drop references to parts of the data,
285 // freeing memory piecewise.
286 n int
287 buckets []*[eventsBucketSize]Event
288 off int
289 }
290
291 // grow grows the slice by one and returns a pointer to the new element, without
292 // overwriting it.
293 func (l *Events) grow() *Event {
294 a, b := l.index(l.n)
295 if a >= len(l.buckets) {
296 l.buckets = append(l.buckets, new([eventsBucketSize]Event))
297 }
298 ptr := &l.buckets[a][b]
299 l.n++
300 return ptr
301 }
302
303 // append appends v to the slice and returns a pointer to the new element.
304 func (l *Events) append(v Event) *Event {
305 ptr := l.grow()
306 *ptr = v
307 return ptr
308 }
309
310 func (l *Events) Ptr(i int) *Event {
311 a, b := l.index(i + l.off)
312 return &l.buckets[a][b]
313 }
314
315 func (l *Events) index(i int) (int, int) {
316 // Doing the division on uint instead of int compiles this function to a
317 // shift and an AND (for power of 2 bucket sizes), versus a whole bunch of
318 // instructions for int.
319 return int(uint(i) / eventsBucketSize), int(uint(i) % eventsBucketSize)
320 }
321
322 func (l *Events) Len() int {
323 return l.n - l.off
324 }
325
326 func (l *Events) Less(i, j int) bool {
327 return l.Ptr(i).Ts < l.Ptr(j).Ts
328 }
329
330 func (l *Events) Swap(i, j int) {
331 *l.Ptr(i), *l.Ptr(j) = *l.Ptr(j), *l.Ptr(i)
332 }
333
334 func (l *Events) Pop() (*Event, bool) {
335 if l.off == l.n {
336 return nil, false
337 }
338 a, b := l.index(l.off)
339 ptr := &l.buckets[a][b]
340 l.off++
341 if b == eventsBucketSize-1 || l.off == l.n {
342 // We've consumed the last event from the bucket, so drop the bucket and
343 // allow GC to collect it.
344 l.buckets[a] = nil
345 }
346 return ptr, true
347 }
348
349 func (l *Events) Peek() (*Event, bool) {
350 if l.off == l.n {
351 return nil, false
352 }
353 a, b := l.index(l.off)
354 return &l.buckets[a][b], true
355 }
356
357 func (l *Events) All() func(yield func(ev *Event) bool) {
358 return func(yield func(ev *Event) bool) {
359 for i := 0; i < l.Len(); i++ {
360 a, b := l.index(i + l.off)
361 ptr := &l.buckets[a][b]
362 if !yield(ptr) {
363 return
364 }
365 }
366 }
367 }
368
369 // parseEventBatches reads per-P event batches and merges them into a single, consistent
370 // stream. The high level idea is as follows. Events within an individual batch
371 // are in correct order, because they are emitted by a single P. So we need to
372 // produce a correct interleaving of the batches. To do this we take first
373 // unmerged event from each batch (frontier). Then choose subset that is "ready"
374 // to be merged, that is, events for which all dependencies are already merged.
375 // Then we choose event with the lowest timestamp from the subset, merge it and
376 // repeat. This approach ensures that we form a consistent stream even if
377 // timestamps are incorrect (condition observed on some machines).
378 func (p *parser) parseEventBatches() (Events, error) {
379 // The ordering of CPU profile sample events in the data stream is based on
380 // when each run of the signal handler was able to acquire the spinlock,
381 // with original timestamps corresponding to when ReadTrace pulled the data
382 // off of the profBuf queue. Re-sort them by the timestamp we captured
383 // inside the signal handler.
384 slices.SortFunc(p.cpuSamples, func(a, b Event) int {
385 return cmp.Compare(a.Ts, b.Ts)
386 })
387
388 allProcs := make([]proc, 0, len(p.batchOffsets))
389 for pid := range p.batchOffsets {
390 allProcs = append(allProcs, proc{pid: pid})
391 }
392 allProcs = append(allProcs, proc{pid: ProfileP, events: p.cpuSamples})
393
394 events := Events{}
395
396 // Merge events as long as at least one P has more events
397 gs := make(map[uint64]gState)
398 // Note: technically we don't need a priority queue here. We're only ever
399 // interested in the earliest eligible event, which means we just have to
400 // track the smallest element. However, in practice, the priority queue
401 // performs better, because for each event we only have to compute its state
402 // transition once, not on each iteration. If it was eligible before, it'll
403 // already be in the queue. Furthermore, on average, we only have one P to
404 // look at in each iteration, because all other Ps are already in the queue.
405 var frontier orderEventList
406
407 availableProcs := make([]*proc, len(allProcs))
408 for i := range allProcs {
409 availableProcs[i] = &allProcs[i]
410 }
411 for {
412 pidLoop:
413 for i := 0; i < len(availableProcs); i++ {
414 proc := availableProcs[i]
415
416 for len(proc.events) == 0 {
417 // Call loadBatch in a loop because sometimes batches are empty
418 evs, err := p.loadBatch(proc.pid, proc.buf[:0])
419 proc.buf = evs[:0]
420 if err == io.EOF {
421 // This P has no more events
422 proc.done = true
423 availableProcs[i], availableProcs[len(availableProcs)-1] = availableProcs[len(availableProcs)-1], availableProcs[i]
424 availableProcs = availableProcs[:len(availableProcs)-1]
425 // We swapped the element at i with another proc, so look at
426 // the index again
427 i--
428 continue pidLoop
429 } else if err != nil {
430 return Events{}, err
431 } else {
432 proc.events = evs
433 }
434 }
435
436 ev := &proc.events[0]
437 g, init, _ := stateTransition(ev)
438
439 // TODO(dh): This implementation matches the behavior of the
440 // upstream 'go tool trace', and works in practice, but has run into
441 // the following inconsistency during fuzzing: what happens if
442 // multiple Ps have events for the same G? While building the
443 // frontier we will check all of the events against the current
444 // state of the G. However, when we process the frontier, the state
445 // of the G changes, and a transition that was valid while building
446 // the frontier may no longer be valid when processing the frontier.
447 // Is this something that can happen for real, valid traces, or is
448 // this only possible with corrupt data?
449 if !transitionReady(g, gs[g], init) {
450 continue
451 }
452 proc.events = proc.events[1:]
453 availableProcs[i], availableProcs[len(availableProcs)-1] = availableProcs[len(availableProcs)-1], availableProcs[i]
454 availableProcs = availableProcs[:len(availableProcs)-1]
455 frontier.Push(orderEvent{*ev, proc})
456
457 // We swapped the element at i with another proc, so look at the
458 // index again
459 i--
460 }
461
462 if len(frontier) == 0 {
463 for i := range allProcs {
464 if !allProcs[i].done {
465 return Events{}, fmt.Errorf("no consistent ordering of events possible")
466 }
467 }
468 break
469 }
470 f := frontier.Pop()
471
472 // We're computing the state transition twice, once when computing the
473 // frontier, and now to apply the transition. This is fine because
474 // stateTransition is a pure function. Computing it again is cheaper
475 // than storing large items in the frontier.
476 g, init, next := stateTransition(&f.ev)
477
478 // Get rid of "Local" events, they are intended merely for ordering.
479 switch f.ev.Type {
480 case EvGoStartLocal:
481 f.ev.Type = EvGoStart
482 case EvGoUnblockLocal:
483 f.ev.Type = EvGoUnblock
484 case EvGoSysExitLocal:
485 f.ev.Type = EvGoSysExit
486 }
487 events.append(f.ev)
488
489 if err := transition(gs, g, init, next); err != nil {
490 return Events{}, err
491 }
492 availableProcs = append(availableProcs, f.proc)
493 }
494
495 // At this point we have a consistent stream of events. Make sure time
496 // stamps respect the ordering. The tests will skip (not fail) the test case
497 // if they see this error.
498 if !sort.IsSorted(&events) {
499 return Events{}, ErrTimeOrder
500 }
501
502 // The last part is giving correct timestamps to EvGoSysExit events. The
503 // problem with EvGoSysExit is that actual syscall exit timestamp
504 // (ev.Args[2]) is potentially acquired long before event emission. So far
505 // we've used timestamp of event emission (ev.Ts). We could not set ev.Ts =
506 // ev.Args[2] earlier, because it would produce seemingly broken timestamps
507 // (misplaced event). We also can't simply update the timestamp and resort
508 // events, because if timestamps are broken we will misplace the event and
509 // later report logically broken trace (instead of reporting broken
510 // timestamps).
511 lastSysBlock := make(map[uint64]Timestamp)
512 for i := 0; i < events.Len(); i++ {
513 ev := events.Ptr(i)
514 switch ev.Type {
515 case EvGoSysBlock, EvGoInSyscall:
516 lastSysBlock[ev.G] = ev.Ts
517 case EvGoSysExit:
518 ts := Timestamp(ev.Args[2])
519 if ts == 0 {
520 continue
521 }
522 block := lastSysBlock[ev.G]
523 if block == 0 {
524 return Events{}, fmt.Errorf("stray syscall exit")
525 }
526 if ts < block {
527 return Events{}, ErrTimeOrder
528 }
529 ev.Ts = ts
530 }
531 }
532 sort.Stable(&events)
533
534 return events, nil
535 }
536
537 // collectBatchesAndCPUSamples records the offsets of batches and parses CPU samples.
538 func (p *parser) collectBatchesAndCPUSamples() error {
539 // Read events.
540 var raw rawEvent
541 var curP int32
542 for n := uint64(0); ; n++ {
543 err := p.readRawEvent(skipArgs|skipStrings, &raw)
544 if err == io.EOF {
545 break
546 }
547 if err != nil {
548 return err
549 }
550 if raw.typ == EvNone {
551 continue
552 }
553
554 if raw.typ == EvBatch {
555 bo := batchOffset{offset: raw.batchOffset}
556 p.batchOffsets[raw.batchPid] = append(p.batchOffsets[raw.batchPid], bo)
557 curP = raw.batchPid
558 }
559
560 batches := p.batchOffsets[curP]
561 if len(batches) == 0 {
562 return fmt.Errorf("read event %d with current P of %d, but P has no batches yet",
563 raw.typ, curP)
564 }
565 batches[len(batches)-1].numEvents++
566
567 if raw.typ == EvCPUSample {
568 e := Event{Type: raw.typ}
569
570 argOffset := 1
571 narg := raw.argNum()
572 if len(raw.args) != narg {
573 return fmt.Errorf("CPU sample has wrong number of arguments: want %d, got %d", narg, len(raw.args))
574 }
575 for i := argOffset; i < narg; i++ {
576 if i == narg-1 {
577 e.StkID = uint32(raw.args[i])
578 } else {
579 e.Args[i-argOffset] = raw.args[i]
580 }
581 }
582
583 e.Ts = Timestamp(e.Args[0])
584 e.P = int32(e.Args[1])
585 e.G = e.Args[2]
586 e.Args[0] = 0
587
588 // Most events are written out by the active P at the exact moment
589 // they describe. CPU profile samples are different because they're
590 // written to the tracing log after some delay, by a separate worker
591 // goroutine, into a separate buffer.
592 //
593 // We keep these in their own batch until all of the batches are
594 // merged in timestamp order. We also (right before the merge)
595 // re-sort these events by the timestamp captured in the profiling
596 // signal handler.
597 //
598 // Note that we're not concerned about the memory usage of storing
599 // all CPU samples during the indexing phase. There are orders of
600 // magnitude fewer CPU samples than runtime events.
601 p.cpuSamples = append(p.cpuSamples, e)
602 }
603 }
604
605 return nil
606 }
607
608 const (
609 skipArgs = 1 << iota
610 skipStrings
611 )
612
613 func (p *parser) readByte() (byte, bool) {
614 if p.off < len(p.data) && p.off >= 0 {
615 b := p.data[p.off]
616 p.off++
617 return b, true
618 } else {
619 return 0, false
620 }
621 }
622
623 func (p *parser) readFull(n int) ([]byte, error) {
624 if p.off >= len(p.data) || p.off < 0 || p.off+n > len(p.data) {
625 // p.off < 0 is impossible but makes BCE happy.
626 //
627 // We do fail outright if there's not enough data, we don't care about
628 // partial results.
629 return nil, io.ErrUnexpectedEOF
630 }
631 buf := p.data[p.off : p.off+n]
632 p.off += n
633 return buf, nil
634 }
635
636 // readRawEvent reads a raw event into ev. The slices in ev are only valid until
637 // the next call to readRawEvent, even when storing to a different location.
638 func (p *parser) readRawEvent(flags uint, ev *rawEvent) error {
639 // The number of arguments is encoded using two bits and can thus only
640 // represent the values 0–3. The value 3 (on the wire) indicates that
641 // arguments are prefixed by their byte length, to encode >=3 arguments.
642 const inlineArgs = 3
643
644 // Read event type and number of arguments (1 byte).
645 b, ok := p.readByte()
646 if !ok {
647 return io.EOF
648 }
649 typ := EventType(b << 2 >> 2)
650 // Most events have a timestamp before the actual arguments, so we add 1 and
651 // parse it like it's the first argument. EvString has a special format and
652 // the number of arguments doesn't matter. EvBatch writes '1' as the number
653 // of arguments, but actually has two: a pid and a timestamp, but here the
654 // timestamp is the second argument, not the first; adding 1 happens to come
655 // up with the correct number, but it doesn't matter, because EvBatch has
656 // custom logic for parsing.
657 //
658 // Note that because we're adding 1, inlineArgs == 3 describes the largest
659 // number of logical arguments that isn't length-prefixed, even though the
660 // value 3 on the wire indicates length-prefixing. For us, that becomes narg
661 // == 4.
662 narg := b>>6 + 1
663 if typ == EvNone || typ >= EvCount || EventDescriptions[typ].minVersion > p.ver {
664 return fmt.Errorf("unknown event type %d", typ)
665 }
666
667 switch typ {
668 case EvString:
669 if flags&skipStrings != 0 {
670 // String dictionary entry [ID, length, string].
671 if _, err := p.readVal(); err != nil {
672 return errMalformedVarint
673 }
674 ln, err := p.readVal()
675 if err != nil {
676 return err
677 }
678 if !p.discard(ln) {
679 return fmt.Errorf("failed to read trace: %w", io.EOF)
680 }
681 } else {
682 // String dictionary entry [ID, length, string].
683 id, err := p.readVal()
684 if err != nil {
685 return err
686 }
687 if id == 0 {
688 return errors.New("string has invalid id 0")
689 }
690 if p.strings[id] != "" {
691 return fmt.Errorf("string has duplicate id %d", id)
692 }
693 var ln uint64
694 ln, err = p.readVal()
695 if err != nil {
696 return err
697 }
698 if ln == 0 {
699 return errors.New("string has invalid length 0")
700 }
701 if ln > 1e6 {
702 return fmt.Errorf("string has too large length %d", ln)
703 }
704 buf, err := p.readFull(int(ln))
705 if err != nil {
706 return fmt.Errorf("failed to read trace: %w", err)
707 }
708 p.strings[id] = string(buf)
709 }
710
711 ev.typ = EvNone
712 return nil
713 case EvBatch:
714 if want := byte(2); narg != want {
715 return fmt.Errorf("EvBatch has wrong number of arguments: got %d, want %d", narg, want)
716 }
717
718 // -1 because we've already read the first byte of the batch
719 off := p.off - 1
720
721 pid, err := p.readVal()
722 if err != nil {
723 return err
724 }
725 if pid != math.MaxUint64 && pid > math.MaxInt32 {
726 return fmt.Errorf("processor ID %d is larger than maximum of %d", pid, uint64(math.MaxUint))
727 }
728
729 var pid32 int32
730 if pid == math.MaxUint64 {
731 pid32 = -1
732 } else {
733 pid32 = int32(pid)
734 }
735
736 v, err := p.readVal()
737 if err != nil {
738 return err
739 }
740
741 *ev = rawEvent{
742 typ: EvBatch,
743 args: p.args[:0],
744 batchPid: pid32,
745 batchOffset: off,
746 }
747 ev.args = append(ev.args, pid, v)
748 return nil
749 default:
750 *ev = rawEvent{typ: typ, args: p.args[:0]}
751 if narg <= inlineArgs {
752 if flags&skipArgs == 0 {
753 for i := 0; i < int(narg); i++ {
754 v, err := p.readVal()
755 if err != nil {
756 return fmt.Errorf("failed to read event %d argument: %w", typ, err)
757 }
758 ev.args = append(ev.args, v)
759 }
760 } else {
761 for i := 0; i < int(narg); i++ {
762 if _, err := p.readVal(); err != nil {
763 return fmt.Errorf("failed to read event %d argument: %w", typ, errMalformedVarint)
764 }
765 }
766 }
767 } else {
768 // More than inlineArgs args, the first value is length of the event
769 // in bytes.
770 v, err := p.readVal()
771 if err != nil {
772 return fmt.Errorf("failed to read event %d argument: %w", typ, err)
773 }
774
775 if limit := uint64(2048); v > limit {
776 // At the time of Go 1.19, v seems to be at most 128. Set 2048
777 // as a generous upper limit and guard against malformed traces.
778 return fmt.Errorf("failed to read event %d argument: length-prefixed argument too big: %d bytes, limit is %d", typ, v, limit)
779 }
780
781 if flags&skipArgs == 0 || typ == EvCPUSample {
782 buf, err := p.readFull(int(v))
783 if err != nil {
784 return fmt.Errorf("failed to read trace: %w", err)
785 }
786 for len(buf) > 0 {
787 var v uint64
788 v, buf, err = readValFrom(buf)
789 if err != nil {
790 return err
791 }
792 ev.args = append(ev.args, v)
793 }
794 } else {
795 // Skip over arguments
796 if !p.discard(v) {
797 return fmt.Errorf("failed to read trace: %w", io.EOF)
798 }
799 }
800 if typ == EvUserLog {
801 // EvUserLog records are followed by a value string
802 if flags&skipArgs == 0 {
803 // Read string
804 s, err := p.readStr()
805 if err != nil {
806 return err
807 }
808 ev.sargs = append(ev.sargs, s)
809 } else {
810 // Skip string
811 v, err := p.readVal()
812 if err != nil {
813 return err
814 }
815 if !p.discard(v) {
816 return io.EOF
817 }
818 }
819 }
820 }
821
822 p.args = ev.args[:0]
823 return nil
824 }
825 }
826
827 // loadBatch loads the next batch for pid and appends its contents to events.
828 func (p *parser) loadBatch(pid int32, events []Event) ([]Event, error) {
829 offsets := p.batchOffsets[pid]
830 if len(offsets) == 0 {
831 return nil, io.EOF
832 }
833 n := offsets[0].numEvents
834 offset := offsets[0].offset
835 offsets = offsets[1:]
836 p.batchOffsets[pid] = offsets
837
838 p.off = offset
839
840 if cap(events) < n {
841 events = make([]Event, 0, n)
842 }
843
844 gotHeader := false
845 var raw rawEvent
846 var ev Event
847 for {
848 err := p.readRawEvent(0, &raw)
849 if err == io.EOF {
850 break
851 }
852 if err != nil {
853 return nil, err
854 }
855 if raw.typ == EvNone || raw.typ == EvCPUSample {
856 continue
857 }
858 if raw.typ == EvBatch {
859 if gotHeader {
860 break
861 } else {
862 gotHeader = true
863 }
864 }
865
866 err = p.parseEvent(&raw, &ev)
867 if err != nil {
868 return nil, err
869 }
870 if ev.Type != EvNone {
871 events = append(events, ev)
872 }
873 }
874
875 return events, nil
876 }
877
878 func (p *parser) readStr() (s string, err error) {
879 sz, err := p.readVal()
880 if err != nil {
881 return "", err
882 }
883 if sz == 0 {
884 return "", nil
885 }
886 if sz > 1e6 {
887 return "", fmt.Errorf("string is too large (len=%d)", sz)
888 }
889 buf, err := p.readFull(int(sz))
890 if err != nil {
891 return "", fmt.Errorf("failed to read trace: %w", err)
892 }
893 return string(buf), nil
894 }
895
896 // parseEvent transforms raw events into events.
897 // It does analyze and verify per-event-type arguments.
898 func (p *parser) parseEvent(raw *rawEvent, ev *Event) error {
899 desc := &EventDescriptions[raw.typ]
900 if desc.Name == "" {
901 return fmt.Errorf("missing description for event type %d", raw.typ)
902 }
903 narg := raw.argNum()
904 if len(raw.args) != narg {
905 return fmt.Errorf("%s has wrong number of arguments: want %d, got %d", desc.Name, narg, len(raw.args))
906 }
907 switch raw.typ {
908 case EvBatch:
909 p.lastGs[p.lastP] = p.lastG
910 if raw.args[0] != math.MaxUint64 && raw.args[0] > math.MaxInt32 {
911 return fmt.Errorf("processor ID %d is larger than maximum of %d", raw.args[0], uint64(math.MaxInt32))
912 }
913 if raw.args[0] == math.MaxUint64 {
914 p.lastP = -1
915 } else {
916 p.lastP = int32(raw.args[0])
917 }
918 p.lastG = p.lastGs[p.lastP]
919 p.lastTs = Timestamp(raw.args[1])
920 case EvFrequency:
921 p.ticksPerSec = int64(raw.args[0])
922 if p.ticksPerSec <= 0 {
923 // The most likely cause for this is tick skew on different CPUs.
924 // For example, solaris/amd64 seems to have wildly different
925 // ticks on different CPUs.
926 return ErrTimeOrder
927 }
928 case EvTimerGoroutine:
929 p.timerGoids[raw.args[0]] = true
930 case EvStack:
931 if len(raw.args) < 2 {
932 return fmt.Errorf("EvStack has wrong number of arguments: want at least 2, got %d", len(raw.args))
933 }
934 size := raw.args[1]
935 if size > 1000 {
936 return fmt.Errorf("EvStack has bad number of frames: %d", size)
937 }
938 want := 2 + 4*size
939 if uint64(len(raw.args)) != want {
940 return fmt.Errorf("EvStack has wrong number of arguments: want %d, got %d", want, len(raw.args))
941 }
942 id := uint32(raw.args[0])
943 if id != 0 && size > 0 {
944 stk := p.allocateStack(size)
945 for i := 0; i < int(size); i++ {
946 pc := raw.args[2+i*4+0]
947 fn := raw.args[2+i*4+1]
948 file := raw.args[2+i*4+2]
949 line := raw.args[2+i*4+3]
950 stk[i] = pc
951
952 if _, ok := p.pcs[pc]; !ok {
953 p.pcs[pc] = Frame{PC: pc, Fn: fn, File: file, Line: int(line)}
954 }
955 }
956 p.stacks[id] = stk
957 }
958 case EvCPUSample:
959 // These events get parsed during the indexing step and don't strictly
960 // belong to the batch.
961 default:
962 *ev = Event{Type: raw.typ, P: p.lastP, G: p.lastG}
963 var argOffset int
964 ev.Ts = p.lastTs + Timestamp(raw.args[0])
965 argOffset = 1
966 p.lastTs = ev.Ts
967 for i := argOffset; i < narg; i++ {
968 if i == narg-1 && desc.Stack {
969 ev.StkID = uint32(raw.args[i])
970 } else {
971 ev.Args[i-argOffset] = raw.args[i]
972 }
973 }
974 switch raw.typ {
975 case EvGoStart, EvGoStartLocal, EvGoStartLabel:
976 p.lastG = ev.Args[0]
977 ev.G = p.lastG
978 case EvGoEnd, EvGoStop, EvGoSched, EvGoPreempt,
979 EvGoSleep, EvGoBlock, EvGoBlockSend, EvGoBlockRecv,
980 EvGoBlockSelect, EvGoBlockSync, EvGoBlockCond, EvGoBlockNet,
981 EvGoSysBlock, EvGoBlockGC:
982 p.lastG = 0
983 case EvGoSysExit, EvGoWaiting, EvGoInSyscall:
984 ev.G = ev.Args[0]
985 case EvUserTaskCreate:
986 // e.Args 0: taskID, 1:parentID, 2:nameID
987 case EvUserRegion:
988 // e.Args 0: taskID, 1: mode, 2:nameID
989 case EvUserLog:
990 // e.Args 0: taskID, 1:keyID, 2: stackID, 3: messageID
991 // raw.sargs 0: message
992
993 if id, ok := p.inlineStringsMapping[raw.sargs[0]]; ok {
994 ev.Args[3] = uint64(id)
995 } else {
996 id := len(p.inlineStrings)
997 p.inlineStringsMapping[raw.sargs[0]] = id
998 p.inlineStrings = append(p.inlineStrings, raw.sargs[0])
999 ev.Args[3] = uint64(id)
1000 }
1001 }
1002
1003 return nil
1004 }
1005
1006 ev.Type = EvNone
1007 return nil
1008 }
1009
1010 // ErrTimeOrder is returned by Parse when the trace contains
1011 // time stamps that do not respect actual event ordering.
1012 var ErrTimeOrder = errors.New("time stamps out of order")
1013
1014 // postProcessTrace does inter-event verification and information restoration.
1015 // The resulting trace is guaranteed to be consistent
1016 // (for example, a P does not run two Gs at the same time, or a G is indeed
1017 // blocked before an unblock event).
1018 func (p *parser) postProcessTrace(events Events) error {
1019 const (
1020 gDead = iota
1021 gRunnable
1022 gRunning
1023 gWaiting
1024 )
1025 type gdesc struct {
1026 state int
1027 ev *Event
1028 evStart *Event
1029 evCreate *Event
1030 evMarkAssist *Event
1031 }
1032 type pdesc struct {
1033 running bool
1034 g uint64
1035 evSweep *Event
1036 }
1037
1038 gs := make(map[uint64]gdesc)
1039 ps := make(map[int32]pdesc)
1040 tasks := make(map[uint64]*Event) // task id to task creation events
1041 activeRegions := make(map[uint64][]*Event) // goroutine id to stack of regions
1042 gs[0] = gdesc{state: gRunning}
1043 var evGC, evSTW *Event
1044
1045 checkRunning := func(p pdesc, g gdesc, ev *Event, allowG0 bool) error {
1046 name := EventDescriptions[ev.Type].Name
1047 if g.state != gRunning {
1048 return fmt.Errorf("g %d is not running while %s (time %d)", ev.G, name, ev.Ts)
1049 }
1050 if p.g != ev.G {
1051 return fmt.Errorf("p %d is not running g %d while %s (time %d)", ev.P, ev.G, name, ev.Ts)
1052 }
1053 if !allowG0 && ev.G == 0 {
1054 return fmt.Errorf("g 0 did %s (time %d)", name, ev.Ts)
1055 }
1056 return nil
1057 }
1058
1059 for evIdx := 0; evIdx < events.Len(); evIdx++ {
1060 ev := events.Ptr(evIdx)
1061
1062 switch ev.Type {
1063 case EvProcStart:
1064 p := ps[ev.P]
1065 if p.running {
1066 return fmt.Errorf("p %d is running before start (time %d)", ev.P, ev.Ts)
1067 }
1068 p.running = true
1069
1070 ps[ev.P] = p
1071 case EvProcStop:
1072 p := ps[ev.P]
1073 if !p.running {
1074 return fmt.Errorf("p %d is not running before stop (time %d)", ev.P, ev.Ts)
1075 }
1076 if p.g != 0 {
1077 return fmt.Errorf("p %d is running a goroutine %d during stop (time %d)", ev.P, p.g, ev.Ts)
1078 }
1079 p.running = false
1080
1081 ps[ev.P] = p
1082 case EvGCStart:
1083 if evGC != nil {
1084 return fmt.Errorf("previous GC is not ended before a new one (time %d)", ev.Ts)
1085 }
1086 evGC = ev
1087 // Attribute this to the global GC state.
1088 ev.P = GCP
1089 case EvGCDone:
1090 if evGC == nil {
1091 return fmt.Errorf("bogus GC end (time %d)", ev.Ts)
1092 }
1093 evGC = nil
1094 case EvSTWStart:
1095 evp := &evSTW
1096 if *evp != nil {
1097 return fmt.Errorf("previous STW is not ended before a new one (time %d)", ev.Ts)
1098 }
1099 *evp = ev
1100 case EvSTWDone:
1101 evp := &evSTW
1102 if *evp == nil {
1103 return fmt.Errorf("bogus STW end (time %d)", ev.Ts)
1104 }
1105 *evp = nil
1106 case EvGCSweepStart:
1107 p := ps[ev.P]
1108 if p.evSweep != nil {
1109 return fmt.Errorf("previous sweeping is not ended before a new one (time %d)", ev.Ts)
1110 }
1111 p.evSweep = ev
1112
1113 ps[ev.P] = p
1114 case EvGCMarkAssistStart:
1115 g := gs[ev.G]
1116 if g.evMarkAssist != nil {
1117 return fmt.Errorf("previous mark assist is not ended before a new one (time %d)", ev.Ts)
1118 }
1119 g.evMarkAssist = ev
1120
1121 gs[ev.G] = g
1122 case EvGCMarkAssistDone:
1123 // Unlike most events, mark assists can be in progress when a
1124 // goroutine starts tracing, so we can't report an error here.
1125 g := gs[ev.G]
1126 if g.evMarkAssist != nil {
1127 g.evMarkAssist = nil
1128 }
1129
1130 gs[ev.G] = g
1131 case EvGCSweepDone:
1132 p := ps[ev.P]
1133 if p.evSweep == nil {
1134 return fmt.Errorf("bogus sweeping end (time %d)", ev.Ts)
1135 }
1136 p.evSweep = nil
1137
1138 ps[ev.P] = p
1139 case EvGoWaiting:
1140 g := gs[ev.G]
1141 if g.state != gRunnable {
1142 return fmt.Errorf("g %d is not runnable before EvGoWaiting (time %d)", ev.G, ev.Ts)
1143 }
1144 g.state = gWaiting
1145 g.ev = ev
1146
1147 gs[ev.G] = g
1148 case EvGoInSyscall:
1149 g := gs[ev.G]
1150 if g.state != gRunnable {
1151 return fmt.Errorf("g %d is not runnable before EvGoInSyscall (time %d)", ev.G, ev.Ts)
1152 }
1153 g.state = gWaiting
1154 g.ev = ev
1155
1156 gs[ev.G] = g
1157 case EvGoCreate:
1158 g := gs[ev.G]
1159 p := ps[ev.P]
1160 if err := checkRunning(p, g, ev, true); err != nil {
1161 return err
1162 }
1163 if _, ok := gs[ev.Args[0]]; ok {
1164 return fmt.Errorf("g %d already exists (time %d)", ev.Args[0], ev.Ts)
1165 }
1166 gs[ev.Args[0]] = gdesc{state: gRunnable, ev: ev, evCreate: ev}
1167
1168 case EvGoStart, EvGoStartLabel:
1169 g := gs[ev.G]
1170 p := ps[ev.P]
1171 if g.state != gRunnable {
1172 return fmt.Errorf("g %d is not runnable before start (time %d)", ev.G, ev.Ts)
1173 }
1174 if p.g != 0 {
1175 return fmt.Errorf("p %d is already running g %d while start g %d (time %d)", ev.P, p.g, ev.G, ev.Ts)
1176 }
1177 g.state = gRunning
1178 g.evStart = ev
1179 p.g = ev.G
1180 if g.evCreate != nil {
1181 ev.StkID = uint32(g.evCreate.Args[1])
1182 g.evCreate = nil
1183 }
1184
1185 if g.ev != nil {
1186 g.ev = nil
1187 }
1188
1189 gs[ev.G] = g
1190 ps[ev.P] = p
1191 case EvGoEnd, EvGoStop:
1192 g := gs[ev.G]
1193 p := ps[ev.P]
1194 if err := checkRunning(p, g, ev, false); err != nil {
1195 return err
1196 }
1197 g.evStart = nil
1198 g.state = gDead
1199 p.g = 0
1200
1201 if ev.Type == EvGoEnd { // flush all active regions
1202 delete(activeRegions, ev.G)
1203 }
1204
1205 gs[ev.G] = g
1206 ps[ev.P] = p
1207 case EvGoSched, EvGoPreempt:
1208 g := gs[ev.G]
1209 p := ps[ev.P]
1210 if err := checkRunning(p, g, ev, false); err != nil {
1211 return err
1212 }
1213 g.state = gRunnable
1214 g.evStart = nil
1215 p.g = 0
1216 g.ev = ev
1217
1218 gs[ev.G] = g
1219 ps[ev.P] = p
1220 case EvGoUnblock:
1221 g := gs[ev.G]
1222 p := ps[ev.P]
1223 if g.state != gRunning {
1224 return fmt.Errorf("g %d is not running while unpark (time %d)", ev.G, ev.Ts)
1225 }
1226 if ev.P != TimerP && p.g != ev.G {
1227 return fmt.Errorf("p %d is not running g %d while unpark (time %d)", ev.P, ev.G, ev.Ts)
1228 }
1229 g1 := gs[ev.Args[0]]
1230 if g1.state != gWaiting {
1231 return fmt.Errorf("g %d is not waiting before unpark (time %d)", ev.Args[0], ev.Ts)
1232 }
1233 if g1.ev != nil && g1.ev.Type == EvGoBlockNet {
1234 ev.P = NetpollP
1235 }
1236 g1.state = gRunnable
1237 g1.ev = ev
1238 gs[ev.Args[0]] = g1
1239
1240 case EvGoSysCall:
1241 g := gs[ev.G]
1242 p := ps[ev.P]
1243 if err := checkRunning(p, g, ev, false); err != nil {
1244 return err
1245 }
1246 g.ev = ev
1247
1248 gs[ev.G] = g
1249 case EvGoSysBlock:
1250 g := gs[ev.G]
1251 p := ps[ev.P]
1252 if err := checkRunning(p, g, ev, false); err != nil {
1253 return err
1254 }
1255 g.state = gWaiting
1256 g.evStart = nil
1257 p.g = 0
1258
1259 gs[ev.G] = g
1260 ps[ev.P] = p
1261 case EvGoSysExit:
1262 g := gs[ev.G]
1263 if g.state != gWaiting {
1264 return fmt.Errorf("g %d is not waiting during syscall exit (time %d)", ev.G, ev.Ts)
1265 }
1266 g.state = gRunnable
1267 g.ev = ev
1268
1269 gs[ev.G] = g
1270 case EvGoSleep, EvGoBlock, EvGoBlockSend, EvGoBlockRecv,
1271 EvGoBlockSelect, EvGoBlockSync, EvGoBlockCond, EvGoBlockNet, EvGoBlockGC:
1272 g := gs[ev.G]
1273 p := ps[ev.P]
1274 if err := checkRunning(p, g, ev, false); err != nil {
1275 return err
1276 }
1277 g.state = gWaiting
1278 g.ev = ev
1279 g.evStart = nil
1280 p.g = 0
1281
1282 gs[ev.G] = g
1283 ps[ev.P] = p
1284 case EvUserTaskCreate:
1285 taskid := ev.Args[0]
1286 if prevEv, ok := tasks[taskid]; ok {
1287 return fmt.Errorf("task id conflicts (id:%d), %q vs %q", taskid, ev, prevEv)
1288 }
1289 tasks[ev.Args[0]] = ev
1290
1291 case EvUserTaskEnd:
1292 taskid := ev.Args[0]
1293 delete(tasks, taskid)
1294
1295 case EvUserRegion:
1296 mode := ev.Args[1]
1297 regions := activeRegions[ev.G]
1298 if mode == 0 { // region start
1299 activeRegions[ev.G] = append(regions, ev) // push
1300 } else if mode == 1 { // region end
1301 n := len(regions)
1302 if n > 0 { // matching region start event is in the trace.
1303 s := regions[n-1]
1304 if s.Args[0] != ev.Args[0] || s.Args[2] != ev.Args[2] { // task id, region name mismatch
1305 return fmt.Errorf("misuse of region in goroutine %d: span end %q when the inner-most active span start event is %q", ev.G, ev, s)
1306 }
1307
1308 if n > 1 {
1309 activeRegions[ev.G] = regions[:n-1]
1310 } else {
1311 delete(activeRegions, ev.G)
1312 }
1313 }
1314 } else {
1315 return fmt.Errorf("invalid user region mode: %q", ev)
1316 }
1317 }
1318
1319 if ev.StkID != 0 && len(p.stacks[ev.StkID]) == 0 {
1320 // Make sure events don't refer to stacks that don't exist or to
1321 // stacks with zero frames. Neither of these should be possible, but
1322 // better be safe than sorry.
1323
1324 ev.StkID = 0
1325 }
1326
1327 }
1328
1329 // TODO(mknyszek): restore stacks for EvGoStart events.
1330 return nil
1331 }
1332
1333 var errMalformedVarint = errors.New("malformatted base-128 varint")
1334
1335 // readVal reads unsigned base-128 value from r.
1336 func (p *parser) readVal() (uint64, error) {
1337 v, n := binary.Uvarint(p.data[p.off:])
1338 if n <= 0 {
1339 return 0, errMalformedVarint
1340 }
1341 p.off += n
1342 return v, nil
1343 }
1344
1345 func readValFrom(buf []byte) (v uint64, rem []byte, err error) {
1346 v, n := binary.Uvarint(buf)
1347 if n <= 0 {
1348 return 0, nil, errMalformedVarint
1349 }
1350 return v, buf[n:], nil
1351 }
1352
1353 func (ev *Event) String() string {
1354 desc := &EventDescriptions[ev.Type]
1355 w := new(bytes.Buffer)
1356 fmt.Fprintf(w, "%d %s p=%d g=%d stk=%d", ev.Ts, desc.Name, ev.P, ev.G, ev.StkID)
1357 for i, a := range desc.Args {
1358 fmt.Fprintf(w, " %s=%d", a, ev.Args[i])
1359 }
1360 return w.String()
1361 }
1362
1363 // argNum returns total number of args for the event accounting for timestamps,
1364 // sequence numbers and differences between trace format versions.
1365 func (raw *rawEvent) argNum() int {
1366 desc := &EventDescriptions[raw.typ]
1367 if raw.typ == EvStack {
1368 return len(raw.args)
1369 }
1370 narg := len(desc.Args)
1371 if desc.Stack {
1372 narg++
1373 }
1374 switch raw.typ {
1375 case EvBatch, EvFrequency, EvTimerGoroutine:
1376 return narg
1377 }
1378 narg++ // timestamp
1379 return narg
1380 }
1381
1382 type EventType uint8
1383
1384 // Event types in the trace.
1385 // Verbatim copy from src/runtime/trace.go with the "trace" prefix removed.
1386 const (
1387 EvNone EventType = 0 // unused
1388 EvBatch EventType = 1 // start of per-P batch of events [pid, timestamp]
1389 EvFrequency EventType = 2 // contains tracer timer frequency [frequency (ticks per second)]
1390 EvStack EventType = 3 // stack [stack id, number of PCs, array of {PC, func string ID, file string ID, line}]
1391 EvGomaxprocs EventType = 4 // current value of GOMAXPROCS [timestamp, GOMAXPROCS, stack id]
1392 EvProcStart EventType = 5 // start of P [timestamp, thread id]
1393 EvProcStop EventType = 6 // stop of P [timestamp]
1394 EvGCStart EventType = 7 // GC start [timestamp, seq, stack id]
1395 EvGCDone EventType = 8 // GC done [timestamp]
1396 EvSTWStart EventType = 9 // GC mark termination start [timestamp, kind]
1397 EvSTWDone EventType = 10 // GC mark termination done [timestamp]
1398 EvGCSweepStart EventType = 11 // GC sweep start [timestamp, stack id]
1399 EvGCSweepDone EventType = 12 // GC sweep done [timestamp, swept, reclaimed]
1400 EvGoCreate EventType = 13 // goroutine creation [timestamp, new goroutine id, new stack id, stack id]
1401 EvGoStart EventType = 14 // goroutine starts running [timestamp, goroutine id, seq]
1402 EvGoEnd EventType = 15 // goroutine ends [timestamp]
1403 EvGoStop EventType = 16 // goroutine stops (like in select{}) [timestamp, stack]
1404 EvGoSched EventType = 17 // goroutine calls Gosched [timestamp, stack]
1405 EvGoPreempt EventType = 18 // goroutine is preempted [timestamp, stack]
1406 EvGoSleep EventType = 19 // goroutine calls Sleep [timestamp, stack]
1407 EvGoBlock EventType = 20 // goroutine blocks [timestamp, stack]
1408 EvGoUnblock EventType = 21 // goroutine is unblocked [timestamp, goroutine id, seq, stack]
1409 EvGoBlockSend EventType = 22 // goroutine blocks on chan send [timestamp, stack]
1410 EvGoBlockRecv EventType = 23 // goroutine blocks on chan recv [timestamp, stack]
1411 EvGoBlockSelect EventType = 24 // goroutine blocks on select [timestamp, stack]
1412 EvGoBlockSync EventType = 25 // goroutine blocks on Mutex/RWMutex [timestamp, stack]
1413 EvGoBlockCond EventType = 26 // goroutine blocks on Cond [timestamp, stack]
1414 EvGoBlockNet EventType = 27 // goroutine blocks on network [timestamp, stack]
1415 EvGoSysCall EventType = 28 // syscall enter [timestamp, stack]
1416 EvGoSysExit EventType = 29 // syscall exit [timestamp, goroutine id, seq, real timestamp]
1417 EvGoSysBlock EventType = 30 // syscall blocks [timestamp]
1418 EvGoWaiting EventType = 31 // denotes that goroutine is blocked when tracing starts [timestamp, goroutine id]
1419 EvGoInSyscall EventType = 32 // denotes that goroutine is in syscall when tracing starts [timestamp, goroutine id]
1420 EvHeapAlloc EventType = 33 // gcController.heapLive change [timestamp, heap live bytes]
1421 EvHeapGoal EventType = 34 // gcController.heapGoal change [timestamp, heap goal bytes]
1422 EvTimerGoroutine EventType = 35 // denotes timer goroutine [timer goroutine id]
1423 EvFutileWakeup EventType = 36 // denotes that the previous wakeup of this goroutine was futile [timestamp]
1424 EvString EventType = 37 // string dictionary entry [ID, length, string]
1425 EvGoStartLocal EventType = 38 // goroutine starts running on the same P as the last event [timestamp, goroutine id]
1426 EvGoUnblockLocal EventType = 39 // goroutine is unblocked on the same P as the last event [timestamp, goroutine id, stack]
1427 EvGoSysExitLocal EventType = 40 // syscall exit on the same P as the last event [timestamp, goroutine id, real timestamp]
1428 EvGoStartLabel EventType = 41 // goroutine starts running with label [timestamp, goroutine id, seq, label string id]
1429 EvGoBlockGC EventType = 42 // goroutine blocks on GC assist [timestamp, stack]
1430 EvGCMarkAssistStart EventType = 43 // GC mark assist start [timestamp, stack]
1431 EvGCMarkAssistDone EventType = 44 // GC mark assist done [timestamp]
1432 EvUserTaskCreate EventType = 45 // trace.NewTask [timestamp, internal task id, internal parent id, stack, name string]
1433 EvUserTaskEnd EventType = 46 // end of task [timestamp, internal task id, stack]
1434 EvUserRegion EventType = 47 // trace.WithRegion [timestamp, internal task id, mode(0:start, 1:end), name string]
1435 EvUserLog EventType = 48 // trace.Log [timestamp, internal id, key string id, stack, value string]
1436 EvCPUSample EventType = 49 // CPU profiling sample [timestamp, stack, real timestamp, real P id (-1 when absent), goroutine id]
1437 EvCount EventType = 50
1438 )
1439
1440 var EventDescriptions = [256]struct {
1441 Name string
1442 minVersion version.Version
1443 Stack bool
1444 Args []string
1445 SArgs []string // string arguments
1446 }{
1447 EvNone: {"None", 5, false, []string{}, nil},
1448 EvBatch: {"Batch", 5, false, []string{"p", "ticks"}, nil}, // in 1.5 format it was {"p", "seq", "ticks"}
1449 EvFrequency: {"Frequency", 5, false, []string{"freq"}, nil}, // in 1.5 format it was {"freq", "unused"}
1450 EvStack: {"Stack", 5, false, []string{"id", "siz"}, nil},
1451 EvGomaxprocs: {"Gomaxprocs", 5, true, []string{"procs"}, nil},
1452 EvProcStart: {"ProcStart", 5, false, []string{"thread"}, nil},
1453 EvProcStop: {"ProcStop", 5, false, []string{}, nil},
1454 EvGCStart: {"GCStart", 5, true, []string{"seq"}, nil}, // in 1.5 format it was {}
1455 EvGCDone: {"GCDone", 5, false, []string{}, nil},
1456 EvSTWStart: {"GCSTWStart", 5, false, []string{"kindid"}, []string{"kind"}}, // <= 1.9, args was {} (implicitly {0})
1457 EvSTWDone: {"GCSTWDone", 5, false, []string{}, nil},
1458 EvGCSweepStart: {"GCSweepStart", 5, true, []string{}, nil},
1459 EvGCSweepDone: {"GCSweepDone", 5, false, []string{"swept", "reclaimed"}, nil}, // before 1.9, format was {}
1460 EvGoCreate: {"GoCreate", 5, true, []string{"g", "stack"}, nil},
1461 EvGoStart: {"GoStart", 5, false, []string{"g", "seq"}, nil}, // in 1.5 format it was {"g"}
1462 EvGoEnd: {"GoEnd", 5, false, []string{}, nil},
1463 EvGoStop: {"GoStop", 5, true, []string{}, nil},
1464 EvGoSched: {"GoSched", 5, true, []string{}, nil},
1465 EvGoPreempt: {"GoPreempt", 5, true, []string{}, nil},
1466 EvGoSleep: {"GoSleep", 5, true, []string{}, nil},
1467 EvGoBlock: {"GoBlock", 5, true, []string{}, nil},
1468 EvGoUnblock: {"GoUnblock", 5, true, []string{"g", "seq"}, nil}, // in 1.5 format it was {"g"}
1469 EvGoBlockSend: {"GoBlockSend", 5, true, []string{}, nil},
1470 EvGoBlockRecv: {"GoBlockRecv", 5, true, []string{}, nil},
1471 EvGoBlockSelect: {"GoBlockSelect", 5, true, []string{}, nil},
1472 EvGoBlockSync: {"GoBlockSync", 5, true, []string{}, nil},
1473 EvGoBlockCond: {"GoBlockCond", 5, true, []string{}, nil},
1474 EvGoBlockNet: {"GoBlockNet", 5, true, []string{}, nil},
1475 EvGoSysCall: {"GoSysCall", 5, true, []string{}, nil},
1476 EvGoSysExit: {"GoSysExit", 5, false, []string{"g", "seq", "ts"}, nil},
1477 EvGoSysBlock: {"GoSysBlock", 5, false, []string{}, nil},
1478 EvGoWaiting: {"GoWaiting", 5, false, []string{"g"}, nil},
1479 EvGoInSyscall: {"GoInSyscall", 5, false, []string{"g"}, nil},
1480 EvHeapAlloc: {"HeapAlloc", 5, false, []string{"mem"}, nil},
1481 EvHeapGoal: {"HeapGoal", 5, false, []string{"mem"}, nil},
1482 EvTimerGoroutine: {"TimerGoroutine", 5, false, []string{"g"}, nil}, // in 1.5 format it was {"g", "unused"}
1483 EvFutileWakeup: {"FutileWakeup", 5, false, []string{}, nil},
1484 EvString: {"String", 7, false, []string{}, nil},
1485 EvGoStartLocal: {"GoStartLocal", 7, false, []string{"g"}, nil},
1486 EvGoUnblockLocal: {"GoUnblockLocal", 7, true, []string{"g"}, nil},
1487 EvGoSysExitLocal: {"GoSysExitLocal", 7, false, []string{"g", "ts"}, nil},
1488 EvGoStartLabel: {"GoStartLabel", 8, false, []string{"g", "seq", "labelid"}, []string{"label"}},
1489 EvGoBlockGC: {"GoBlockGC", 8, true, []string{}, nil},
1490 EvGCMarkAssistStart: {"GCMarkAssistStart", 9, true, []string{}, nil},
1491 EvGCMarkAssistDone: {"GCMarkAssistDone", 9, false, []string{}, nil},
1492 EvUserTaskCreate: {"UserTaskCreate", 11, true, []string{"taskid", "pid", "typeid"}, []string{"name"}},
1493 EvUserTaskEnd: {"UserTaskEnd", 11, true, []string{"taskid"}, nil},
1494 EvUserRegion: {"UserRegion", 11, true, []string{"taskid", "mode", "typeid"}, []string{"name"}},
1495 EvUserLog: {"UserLog", 11, true, []string{"id", "keyid"}, []string{"category", "message"}},
1496 EvCPUSample: {"CPUSample", 19, true, []string{"ts", "p", "g"}, nil},
1497 }
1498
1499 //gcassert:inline
1500 func (p *parser) allocateStack(size uint64) []uint64 {
1501 if size == 0 {
1502 return nil
1503 }
1504
1505 // Stacks are plentiful but small. For our "Staticcheck on std" trace with
1506 // 11e6 events, we have roughly 500,000 stacks, using 200 MiB of memory. To
1507 // avoid making 500,000 small allocations we allocate backing arrays 1 MiB
1508 // at a time.
1509 out := p.stacksData
1510 if uint64(len(out)) < size {
1511 out = make([]uint64, 1024*128)
1512 }
1513 p.stacksData = out[size:]
1514 return out[:size:size]
1515 }
1516
1517 func (tr *Trace) STWReason(kindID uint64) STWReason {
1518 if tr.Version < 21 {
1519 if kindID == 0 || kindID == 1 {
1520 return STWReason(kindID + 1)
1521 } else {
1522 return STWUnknown
1523 }
1524 } else if tr.Version == 21 {
1525 if kindID < NumSTWReasons {
1526 return STWReason(kindID)
1527 } else {
1528 return STWUnknown
1529 }
1530 } else {
1531 return STWUnknown
1532 }
1533 }
1534
1535 type STWReason int
1536
1537 const (
1538 STWUnknown STWReason = 0
1539 STWGCMarkTermination STWReason = 1
1540 STWGCSweepTermination STWReason = 2
1541 STWWriteHeapDump STWReason = 3
1542 STWGoroutineProfile STWReason = 4
1543 STWGoroutineProfileCleanup STWReason = 5
1544 STWAllGoroutinesStackTrace STWReason = 6
1545 STWReadMemStats STWReason = 7
1546 STWAllThreadsSyscall STWReason = 8
1547 STWGOMAXPROCS STWReason = 9
1548 STWStartTrace STWReason = 10
1549 STWStopTrace STWReason = 11
1550 STWCountPagesInUse STWReason = 12
1551 STWReadMetricsSlow STWReason = 13
1552 STWReadMemStatsSlow STWReason = 14
1553 STWPageCachePagesLeaked STWReason = 15
1554 STWResetDebugLog STWReason = 16
1555
1556 NumSTWReasons = 17
1557 )