Debian Codegraph @

trace/event.go

raw symbols SCIP
1 // Copyright 2023 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 trace
10
11 import (
12 "errors"
13 "fmt"
14 "io"
15 "iter"
16 "math"
17 "regexp"
18 "slices"
19 "strings"
20 "time"
21
22 "golang.org/x/exp/trace/internal/tracev2"
23 "golang.org/x/exp/trace/internal/version"
24 )
25
26 // EventKind indicates the kind of event this is.
27 //
28 // Use this information to obtain a more specific event that
29 // allows access to more detailed information.
30 type EventKind uint16
31
32 const (
33 EventBad EventKind = iota
34
35 // EventKindSync is an event that indicates a global synchronization
36 // point in the trace. At the point of a sync event, the
37 // trace reader can be certain that all resources (e.g. threads,
38 // goroutines) that have existed until that point have been enumerated.
39 EventSync
40
41 // EventMetric is an event that represents the value of a metric at
42 // a particular point in time.
43 EventMetric
44
45 // EventLabel attaches a label to a resource.
46 EventLabel
47
48 // EventStackSample represents an execution sample, indicating what a
49 // thread/proc/goroutine was doing at a particular point in time via
50 // its backtrace.
51 //
52 // Note: Samples should be considered a close approximation of
53 // what a thread/proc/goroutine was executing at a given point in time.
54 // These events may slightly contradict the situation StateTransitions
55 // describe, so they should only be treated as a best-effort annotation.
56 EventStackSample
57
58 // EventRangeBegin and EventRangeEnd are a pair of generic events representing
59 // a special range of time. Ranges are named and scoped to some resource
60 // (identified via ResourceKind). A range that has begun but has not ended
61 // is considered active.
62 //
63 // EvRangeBegin and EvRangeEnd will share the same name, and an End will always
64 // follow a Begin on the same instance of the resource. The associated
65 // resource ID can be obtained from the Event. ResourceNone indicates the
66 // range is globally scoped. That is, any goroutine/proc/thread can start or
67 // stop, but only one such range may be active at any given time.
68 //
69 // EventRangeActive is like EventRangeBegin, but indicates that the range was
70 // already active. In this case, the resource referenced may not be in the current
71 // context.
72 EventRangeBegin
73 EventRangeActive
74 EventRangeEnd
75
76 // EvTaskBegin and EvTaskEnd are a pair of events representing a runtime/trace.Task.
77 EventTaskBegin
78 EventTaskEnd
79
80 // EventRegionBegin and EventRegionEnd are a pair of events represent a runtime/trace.Region.
81 EventRegionBegin
82 EventRegionEnd
83
84 // EventLog represents a runtime/trace.Log call.
85 EventLog
86
87 // EventStateTransition represents a state change for some resource.
88 EventStateTransition
89
90 // EventExperimental is an experimental event that is unvalidated and exposed in a raw form.
91 // Users are expected to understand the format and perform their own validation. These events
92 // may always be safely ignored.
93 EventExperimental
94 )
95
96 // String returns a string form of the EventKind.
97 func (e EventKind) String() string {
98 if int(e) >= len(eventKindStrings) {
99 return eventKindStrings[0]
100 }
101 return eventKindStrings[e]
102 }
103
104 var eventKindStrings = [...]string{
105 EventBad: "Bad",
106 EventSync: "Sync",
107 EventMetric: "Metric",
108 EventLabel: "Label",
109 EventStackSample: "StackSample",
110 EventRangeBegin: "RangeBegin",
111 EventRangeActive: "RangeActive",
112 EventRangeEnd: "RangeEnd",
113 EventTaskBegin: "TaskBegin",
114 EventTaskEnd: "TaskEnd",
115 EventRegionBegin: "RegionBegin",
116 EventRegionEnd: "RegionEnd",
117 EventLog: "Log",
118 EventStateTransition: "StateTransition",
119 EventExperimental: "Experimental",
120 }
121
122 const maxTime = Time(math.MaxInt64)
123
124 // Time is a timestamp in nanoseconds.
125 //
126 // It corresponds to the monotonic clock on the platform that the
127 // trace was taken, and so is possible to correlate with timestamps
128 // for other traces taken on the same machine using the same clock
129 // (i.e. no reboots in between).
130 //
131 // The actual absolute value of the timestamp is only meaningful in
132 // relation to other timestamps from the same clock.
133 //
134 // BUG: Timestamps coming from traces on Windows platforms are
135 // only comparable with timestamps from the same trace. Timestamps
136 // across traces cannot be compared, because the system clock is
137 // not used as of Go 1.22.
138 //
139 // BUG: Traces produced by Go versions 1.21 and earlier cannot be
140 // compared with timestamps from other traces taken on the same
141 // machine. This is because the system clock was not used at all
142 // to collect those timestamps.
143 type Time int64
144
145 // Sub subtracts t0 from t, returning the duration in nanoseconds.
146 func (t Time) Sub(t0 Time) time.Duration {
147 return time.Duration(int64(t) - int64(t0))
148 }
149
150 // Metric provides details about a Metric event.
151 type Metric struct {
152 // Name is the name of the sampled metric.
153 //
154 // Names follow the same convention as metric names in the
155 // runtime/metrics package, meaning they include the unit.
156 // Names that match with the runtime/metrics package represent
157 // the same quantity. Note that this corresponds to the
158 // runtime/metrics package for the Go version this trace was
159 // collected for.
160 Name string
161
162 // Value is the sampled value of the metric.
163 //
164 // The Value's Kind is tied to the name of the metric, and so is
165 // guaranteed to be the same for metric samples for the same metric.
166 Value Value
167 }
168
169 // Label provides details about a Label event.
170 type Label struct {
171 // Label is the label applied to some resource.
172 Label string
173
174 // Resource is the resource to which this label should be applied.
175 Resource ResourceID
176 }
177
178 // Range provides details about a Range event.
179 type Range struct {
180 // Name is a human-readable name for the range.
181 //
182 // This name can be used to identify the end of the range for the resource
183 // its scoped to, because only one of each type of range may be active on
184 // a particular resource. The relevant resource should be obtained from the
185 // Event that produced these details. The corresponding RangeEnd will have
186 // an identical name.
187 Name string
188
189 // Scope is the resource that the range is scoped to.
190 //
191 // For example, a ResourceGoroutine scope means that the same goroutine
192 // must have a start and end for the range, and that goroutine can only
193 // have one range of a particular name active at any given time. The
194 // ID that this range is scoped to may be obtained via Event.Goroutine.
195 //
196 // The ResourceNone scope means that the range is globally scoped. As a
197 // result, any goroutine/proc/thread may start or end the range, and only
198 // one such named range may be active globally at any given time.
199 //
200 // For RangeBegin and RangeEnd events, this will always reference some
201 // resource ID in the current execution context. For RangeActive events,
202 // this may reference a resource not in the current context. Prefer Scope
203 // over the current execution context.
204 Scope ResourceID
205 }
206
207 // RangeAttribute provides attributes about a completed Range.
208 type RangeAttribute struct {
209 // Name is the human-readable name for the range.
210 Name string
211
212 // Value is the value of the attribute.
213 Value Value
214 }
215
216 // TaskID is the internal ID of a task used to disambiguate tasks (even if they
217 // are of the same type).
218 type TaskID uint64
219
220 const (
221 // NoTask indicates the lack of a task.
222 NoTask = TaskID(^uint64(0))
223
224 // BackgroundTask is the global task that events are attached to if there was
225 // no other task in the context at the point the event was emitted.
226 BackgroundTask = TaskID(0)
227 )
228
229 // Task provides details about a Task event.
230 type Task struct {
231 // ID is a unique identifier for the task.
232 //
233 // This can be used to associate the beginning of a task with its end.
234 ID TaskID
235
236 // ParentID is the ID of the parent task.
237 Parent TaskID
238
239 // Type is the taskType that was passed to runtime/trace.NewTask.
240 //
241 // May be "" if a task's TaskBegin event isn't present in the trace.
242 Type string
243 }
244
245 // Region provides details about a Region event.
246 type Region struct {
247 // Task is the ID of the task this region is associated with.
248 Task TaskID
249
250 // Type is the regionType that was passed to runtime/trace.StartRegion or runtime/trace.WithRegion.
251 Type string
252 }
253
254 // Log provides details about a Log event.
255 type Log struct {
256 // Task is the ID of the task this region is associated with.
257 Task TaskID
258
259 // Category is the category that was passed to runtime/trace.Log or runtime/trace.Logf.
260 Category string
261
262 // Message is the message that was passed to runtime/trace.Log or runtime/trace.Logf.
263 Message string
264 }
265
266 // StackSample is used to construct StackSample events via MakeEvent. There are
267 // no details associated with it, use EventConfig.Stack instead.
268 type StackSample struct{}
269
270 // MakeStack create a stack from a list of stack frames.
271 func MakeStack(frames []StackFrame) Stack {
272 // TODO(felixge): support evTable reuse.
273 tbl := &evTable{pcs: make(map[uint64]frame)}
274 tbl.strings.compactify()
275 tbl.stacks.compactify()
276 return Stack{table: tbl, id: addStack(tbl, frames)}
277 }
278
279 // Stack represents a stack. It's really a handle to a stack and it's trivially comparable.
280 //
281 // If two Stacks are equal then their Frames are guaranteed to be identical. If they are not
282 // equal, however, their Frames may still be equal.
283 type Stack struct {
284 table *evTable
285 id stackID
286 }
287
288 // Frames is an iterator over the frames in a Stack.
289 func (s Stack) Frames() iter.Seq[StackFrame] {
290 return func(yield func(StackFrame) bool) {
291 if s.id == 0 {
292 return
293 }
294 stk := s.table.stacks.mustGet(s.id)
295 for _, pc := range stk.pcs {
296 f := s.table.pcs[pc]
297 sf := StackFrame{
298 PC: f.pc,
299 Func: s.table.strings.mustGet(f.funcID),
300 File: s.table.strings.mustGet(f.fileID),
301 Line: f.line,
302 }
303 if !yield(sf) {
304 return
305 }
306 }
307 }
308 }
309
310 // String returns the stack as a human-readable string.
311 //
312 // The format of the string is intended for debugging and is subject to change.
313 func (s Stack) String() string {
314 var sb strings.Builder
315 printStack(&sb, "", s.Frames())
316 return sb.String()
317 }
318
319 func printStack(w io.Writer, prefix string, frames iter.Seq[StackFrame]) {
320 for f := range frames {
321 fmt.Fprintf(w, "%s%s @ 0x%x\n", prefix, f.Func, f.PC)
322 fmt.Fprintf(w, "%s\t%s:%d\n", prefix, f.File, f.Line)
323 }
324 }
325
326 // NoStack is a sentinel value that can be compared against any Stack value, indicating
327 // a lack of a stack trace.
328 var NoStack = Stack{}
329
330 // StackFrame represents a single frame of a stack.
331 type StackFrame struct {
332 // PC is the program counter of the function call if this
333 // is not a leaf frame. If it's a leaf frame, it's the point
334 // at which the stack trace was taken.
335 PC uint64
336
337 // Func is the name of the function this frame maps to.
338 Func string
339
340 // File is the file which contains the source code of Func.
341 File string
342
343 // Line is the line number within File which maps to PC.
344 Line uint64
345 }
346
347 // ExperimentalEvent presents a raw view of an experimental event's arguments and their names.
348 type ExperimentalEvent struct {
349 // Name is the name of the event.
350 Name string
351
352 // Experiment is the name of the experiment this event is a part of.
353 Experiment string
354
355 // Args lists the names of the event's arguments in order.
356 Args []string
357
358 // argValues contains the raw integer arguments which are interpreted
359 // by ArgValue using table.
360 table *evTable
361 argValues []uint64
362 }
363
364 // ArgValue returns a typed Value for the i'th argument in the experimental event.
365 func (e ExperimentalEvent) ArgValue(i int) Value {
366 if i < 0 || i >= len(e.Args) {
367 panic(fmt.Sprintf("experimental event argument index %d out of bounds [0, %d)", i, len(e.Args)))
368 }
369 if strings.HasSuffix(e.Args[i], "string") {
370 s := e.table.strings.mustGet(stringID(e.argValues[i]))
371 return StringValue(s)
372 }
373 return Uint64Value(e.argValues[i])
374 }
375
376 // ExperimentalBatch represents a packet of unparsed data along with metadata about that packet.
377 type ExperimentalBatch struct {
378 // Thread is the ID of the thread that produced a packet of data.
379 Thread ThreadID
380
381 // Data is a packet of unparsed data all produced by one thread.
382 Data []byte
383 }
384
385 type EventDetails interface {
386 Metric | Label | Range | StateTransition | Sync | Task | Region | Log | StackSample
387 }
388
389 // EventConfig holds the data for constructing a trace event.
390 type EventConfig[T EventDetails] struct {
391 // Time is the timestamp of the event.
392 Time Time
393
394 // Kind is the kind of the event.
395 Kind EventKind
396
397 // Goroutine is the goroutine ID of the event.
398 Goroutine GoID
399
400 // Proc is the proc ID of the event.
401 Proc ProcID
402
403 // Thread is the thread ID of the event.
404 Thread ThreadID
405
406 // Stack is the stack of the event.
407 Stack Stack
408
409 // Details is the kind specific details of the event.
410 Details T
411 }
412
413 // MakeEvent creates a new trace event from the given configuration.
414 func MakeEvent[T EventDetails](c EventConfig[T]) (e Event, err error) {
415 // TODO(felixge): make the evTable reusable.
416 e = Event{
417 table: &evTable{pcs: make(map[uint64]frame), sync: sync{freq: 1}},
418 base: baseEvent{time: c.Time},
419 ctx: schedCtx{G: c.Goroutine, P: c.Proc, M: c.Thread},
420 }
421 defer func() {
422 // N.b. evSync is not in tracev2.Specs()
423 if err != nil || e.base.typ == evSync {
424 return
425 }
426 spec := tracev2.Specs()[e.base.typ]
427 if len(spec.StackIDs) > 0 && c.Stack != NoStack {
428 // The stack for the main execution context is always the
429 // first stack listed in StackIDs. Subtract one from this
430 // because we've peeled away the timestamp argument.
431 e.base.args[spec.StackIDs[0]-1] = uint64(addStack(e.table, slices.Collect(c.Stack.Frames())))
432 }
433
434 e.table.strings.compactify()
435 e.table.stacks.compactify()
436 }()
437 var defaultKind EventKind
438 switch c.Kind {
439 case defaultKind:
440 return Event{}, fmt.Errorf("the Kind field must be provided")
441 case EventMetric:
442 if m, ok := any(c.Details).(Metric); ok {
443 return makeMetricEvent(e, m)
444 }
445 case EventLabel:
446 if l, ok := any(c.Details).(Label); ok {
447 return makeLabelEvent(e, l)
448 }
449 case EventRangeBegin, EventRangeActive, EventRangeEnd:
450 if r, ok := any(c.Details).(Range); ok {
451 return makeRangeEvent(e, c.Kind, r)
452 }
453 case EventStateTransition:
454 if t, ok := any(c.Details).(StateTransition); ok {
455 return makeStateTransitionEvent(e, t)
456 }
457 case EventSync:
458 if s, ok := any(c.Details).(Sync); ok {
459 return makeSyncEvent(e, s)
460 }
461 case EventTaskBegin, EventTaskEnd:
462 if t, ok := any(c.Details).(Task); ok {
463 return makeTaskEvent(e, c.Kind, t)
464 }
465 case EventRegionBegin, EventRegionEnd:
466 if r, ok := any(c.Details).(Region); ok {
467 return makeRegionEvent(e, c.Kind, r)
468 }
469 case EventLog:
470 if l, ok := any(c.Details).(Log); ok {
471 return makeLogEvent(e, l)
472 }
473 case EventStackSample:
474 if _, ok := any(c.Details).(StackSample); ok {
475 return makeStackSampleEvent(e, c.Stack)
476 }
477 }
478 return Event{}, fmt.Errorf("the Kind field %s is incompatible with Details type %T", c.Kind, c.Details)
479 }
480
481 func makeMetricEvent(e Event, m Metric) (Event, error) {
482 if m.Value.Kind() != ValueUint64 {
483 return Event{}, fmt.Errorf("metric value must be a uint64, got: %s", m.Value.String())
484 }
485 switch m.Name {
486 case "/sched/gomaxprocs:threads":
487 e.base.typ = tracev2.EvProcsChange
488 case "/memory/classes/heap/objects:bytes":
489 e.base.typ = tracev2.EvHeapAlloc
490 case "/gc/heap/goal:bytes":
491 e.base.typ = tracev2.EvHeapGoal
492 default:
493 return Event{}, fmt.Errorf("unknown metric name: %s", m.Name)
494 }
495 e.base.args[0] = uint64(m.Value.Uint64())
496 return e, nil
497 }
498
499 func makeLabelEvent(e Event, l Label) (Event, error) {
500 if l.Resource.Kind != ResourceGoroutine {
501 return Event{}, fmt.Errorf("resource must be a goroutine: %s", l.Resource)
502 }
503 e.base.typ = tracev2.EvGoLabel
504 e.base.args[0] = uint64(e.table.strings.append(l.Label))
505 // TODO(felixge): check against sched ctx and return error on mismatch
506 e.ctx.G = l.Resource.Goroutine()
507 return e, nil
508 }
509
510 var stwRangeRegexp = regexp.MustCompile(`^stop-the-world \((.*)\)$`)
511
512 // TODO(felixge): should this ever manipulate the e ctx? Or just report mismatches?
513 func makeRangeEvent(e Event, kind EventKind, r Range) (Event, error) {
514 // TODO(felixge): Should we add dedicated range kinds rather than using
515 // string names?
516 switch r.Name {
517 case "GC concurrent mark phase":
518 if r.Scope.Kind != ResourceNone {
519 return Event{}, fmt.Errorf("unexpected scope: %s", r.Scope)
520 }
521 switch kind {
522 case EventRangeBegin:
523 e.base.typ = tracev2.EvGCBegin
524 case EventRangeActive:
525 e.base.typ = tracev2.EvGCActive
526 case EventRangeEnd:
527 e.base.typ = tracev2.EvGCEnd
528 default:
529 return Event{}, fmt.Errorf("unexpected range kind: %s", kind)
530 }
531 case "GC incremental sweep":
532 if r.Scope.Kind != ResourceProc {
533 return Event{}, fmt.Errorf("unexpected scope: %s", r.Scope)
534 }
535 switch kind {
536 case EventRangeBegin:
537 e.base.typ = tracev2.EvGCSweepBegin
538 e.ctx.P = r.Scope.Proc()
539 case EventRangeActive:
540 e.base.typ = tracev2.EvGCSweepActive
541 e.base.args[0] = uint64(r.Scope.Proc())
542 case EventRangeEnd:
543 e.base.typ = tracev2.EvGCSweepEnd
544 // TODO(felixge): check against sched ctx and return error on mismatch
545 e.ctx.P = r.Scope.Proc()
546 default:
547 return Event{}, fmt.Errorf("unexpected range kind: %s", kind)
548 }
549 case "GC mark assist":
550 if r.Scope.Kind != ResourceGoroutine {
551 return Event{}, fmt.Errorf("unexpected scope: %s", r.Scope)
552 }
553 switch kind {
554 case EventRangeBegin:
555 e.base.typ = tracev2.EvGCMarkAssistBegin
556 e.ctx.G = r.Scope.Goroutine()
557 case EventRangeActive:
558 e.base.typ = tracev2.EvGCMarkAssistActive
559 e.base.args[0] = uint64(r.Scope.Goroutine())
560 case EventRangeEnd:
561 e.base.typ = tracev2.EvGCMarkAssistEnd
562 // TODO(felixge): check against sched ctx and return error on mismatch
563 e.ctx.G = r.Scope.Goroutine()
564 default:
565 return Event{}, fmt.Errorf("unexpected range kind: %s", kind)
566 }
567 default:
568 match := stwRangeRegexp.FindStringSubmatch(r.Name)
569 if len(match) != 2 {
570 return Event{}, fmt.Errorf("unexpected range name: %s", r.Name)
571 }
572 if r.Scope.Kind != ResourceGoroutine {
573 return Event{}, fmt.Errorf("unexpected scope: %s", r.Scope)
574 }
575 switch kind {
576 case EventRangeBegin:
577 e.base.typ = tracev2.EvSTWBegin
578 // TODO(felixge): check against sched ctx and return error on mismatch
579 e.ctx.G = r.Scope.Goroutine()
580 case EventRangeEnd:
581 e.base.typ = tracev2.EvSTWEnd
582 // TODO(felixge): check against sched ctx and return error on mismatch
583 e.ctx.G = r.Scope.Goroutine()
584 default:
585 return Event{}, fmt.Errorf("unexpected range kind: %s", kind)
586 }
587 e.base.args[0] = uint64(e.table.strings.append(match[1]))
588 }
589 return e, nil
590 }
591
592 func makeStateTransitionEvent(e Event, t StateTransition) (Event, error) {
593 switch t.Resource.Kind {
594 case ResourceProc:
595 from, to := ProcState(t.oldState), ProcState(t.newState)
596 switch {
597 case from == ProcIdle && to == ProcIdle:
598 // TODO(felixge): Could this also be a ProcStatus event?
599 e.base.typ = tracev2.EvProcSteal
600 e.base.args[0] = uint64(t.Resource.Proc())
601 e.base.extra(version.Go122)[0] = uint64(tracev2.ProcSyscallAbandoned)
602 case from == ProcIdle && to == ProcRunning:
603 e.base.typ = tracev2.EvProcStart
604 e.base.args[0] = uint64(t.Resource.Proc())
605 case from == ProcRunning && to == ProcIdle:
606 e.base.typ = tracev2.EvProcStop
607 if t.Resource.Proc() != e.ctx.P {
608 e.base.typ = tracev2.EvProcSteal
609 e.base.args[0] = uint64(t.Resource.Proc())
610 }
611 default:
612 e.base.typ = tracev2.EvProcStatus
613 e.base.args[0] = uint64(t.Resource.Proc())
614 e.base.args[1] = uint64(procState2Tracev2ProcStatus[to])
615 e.base.extra(version.Go122)[0] = uint64(procState2Tracev2ProcStatus[from])
616 return e, nil
617 }
618 case ResourceGoroutine:
619 from, to := GoState(t.oldState), GoState(t.newState)
620 stack := slices.Collect(t.Stack.Frames())
621 goroutine := t.Resource.Goroutine()
622
623 if (from == GoUndetermined || from == to) && from != GoNotExist {
624 e.base.typ = tracev2.EvGoStatus
625 if len(stack) > 0 {
626 e.base.typ = tracev2.EvGoStatusStack
627 }
628 e.base.args[0] = uint64(goroutine)
629 e.base.args[2] = uint64(from)<<32 | uint64(goState2Tracev2GoStatus[to])
630 } else {
631 switch from {
632 case GoNotExist:
633 switch to {
634 case GoWaiting:
635 e.base.typ = tracev2.EvGoCreateBlocked
636 e.base.args[0] = uint64(goroutine)
637 e.base.args[1] = uint64(addStack(e.table, stack))
638 case GoRunnable:
639 e.base.typ = tracev2.EvGoCreate
640 e.base.args[0] = uint64(goroutine)
641 e.base.args[1] = uint64(addStack(e.table, stack))
642 case GoSyscall:
643 e.base.typ = tracev2.EvGoCreateSyscall
644 e.base.args[0] = uint64(goroutine)
645 default:
646 return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to)
647 }
648 case GoRunnable:
649 e.base.typ = tracev2.EvGoStart
650 e.base.args[0] = uint64(goroutine)
651 case GoRunning:
652 switch to {
653 case GoNotExist:
654 e.base.typ = tracev2.EvGoDestroy
655 e.ctx.G = goroutine
656 case GoRunnable:
657 e.base.typ = tracev2.EvGoStop
658 e.ctx.G = goroutine
659 e.base.args[0] = uint64(e.table.strings.append(t.Reason))
660 case GoWaiting:
661 e.base.typ = tracev2.EvGoBlock
662 e.ctx.G = goroutine
663 e.base.args[0] = uint64(e.table.strings.append(t.Reason))
664 case GoSyscall:
665 e.base.typ = tracev2.EvGoSyscallBegin
666 e.ctx.G = goroutine
667 default:
668 return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to)
669 }
670 case GoSyscall:
671 switch to {
672 case GoNotExist:
673 e.base.typ = tracev2.EvGoDestroySyscall
674 e.ctx.G = goroutine
675 case GoRunning:
676 e.base.typ = tracev2.EvGoSyscallEnd
677 e.ctx.G = goroutine
678 case GoRunnable:
679 e.base.typ = tracev2.EvGoSyscallEndBlocked
680 e.ctx.G = goroutine
681 default:
682 return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to)
683 }
684 case GoWaiting:
685 switch to {
686 case GoRunnable:
687 e.base.typ = tracev2.EvGoUnblock
688 e.base.args[0] = uint64(goroutine)
689 default:
690 return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to)
691 }
692 default:
693 return Event{}, fmt.Errorf("unexpected transition: %s -> %s", from, to)
694 }
695 }
696 default:
697 return Event{}, fmt.Errorf("unsupported state transition resource: %s", t.Resource)
698 }
699 return e, nil
700 }
701
702 func makeSyncEvent(e Event, s Sync) (Event, error) {
703 e.base.typ = evSync
704 e.base.args[0] = uint64(s.N)
705 if e.table.expBatches == nil {
706 e.table.expBatches = make(map[tracev2.Experiment][]ExperimentalBatch)
707 }
708 for name, batches := range s.ExperimentalBatches {
709 var found bool
710 for id, exp := range tracev2.Experiments() {
711 if exp == name {
712 found = true
713 e.table.expBatches[tracev2.Experiment(id)] = batches
714 break
715 }
716 }
717 if !found {
718 return Event{}, fmt.Errorf("unknown experiment: %s", name)
719 }
720 }
721 if s.ClockSnapshot != nil {
722 e.table.hasClockSnapshot = true
723 e.table.snapWall = s.ClockSnapshot.Wall
724 e.table.snapMono = s.ClockSnapshot.Mono
725 // N.b. MakeEvent sets e.table.freq to 1.
726 e.table.snapTime = timestamp(s.ClockSnapshot.Trace)
727 }
728 return e, nil
729 }
730
731 func makeTaskEvent(e Event, kind EventKind, t Task) (Event, error) {
732 if t.ID == NoTask {
733 return Event{}, errors.New("task ID cannot be NoTask")
734 }
735 e.base.args[0] = uint64(t.ID)
736 switch kind {
737 case EventTaskBegin:
738 e.base.typ = tracev2.EvUserTaskBegin
739 e.base.args[1] = uint64(t.Parent)
740 e.base.args[2] = uint64(e.table.strings.append(t.Type))
741 case EventTaskEnd:
742 e.base.typ = tracev2.EvUserTaskEnd
743 e.base.extra(version.Go122)[0] = uint64(t.Parent)
744 e.base.extra(version.Go122)[1] = uint64(e.table.addExtraString(t.Type))
745 default:
746 // TODO(felixge): also do this for ranges?
747 panic("unexpected task kind")
748 }
749 return e, nil
750 }
751
752 func makeRegionEvent(e Event, kind EventKind, r Region) (Event, error) {
753 e.base.args[0] = uint64(r.Task)
754 e.base.args[1] = uint64(e.table.strings.append(r.Type))
755 switch kind {
756 case EventRegionBegin:
757 e.base.typ = tracev2.EvUserRegionBegin
758 case EventRegionEnd:
759 e.base.typ = tracev2.EvUserRegionEnd
760 default:
761 panic("unexpected region kind")
762 }
763 return e, nil
764 }
765
766 func makeLogEvent(e Event, l Log) (Event, error) {
767 e.base.typ = tracev2.EvUserLog
768 e.base.args[0] = uint64(l.Task)
769 e.base.args[1] = uint64(e.table.strings.append(l.Category))
770 e.base.args[2] = uint64(e.table.strings.append(l.Message))
771 return e, nil
772 }
773
774 func makeStackSampleEvent(e Event, s Stack) (Event, error) {
775 e.base.typ = tracev2.EvCPUSample
776 frames := slices.Collect(s.Frames())
777 e.base.args[0] = uint64(addStack(e.table, frames))
778 return e, nil
779 }
780
781 func addStack(table *evTable, frames []StackFrame) stackID {
782 var pcs []uint64
783 for _, f := range frames {
784 table.pcs[f.PC] = frame{
785 pc: f.PC,
786 funcID: table.strings.append(f.Func),
787 fileID: table.strings.append(f.File),
788 line: f.Line,
789 }
790 pcs = append(pcs, f.PC)
791 }
792 return table.stacks.append(stack{pcs: pcs})
793 }
794
795 // Event represents a single event in the trace.
796 type Event struct {
797 table *evTable
798 ctx schedCtx
799 base baseEvent
800 }
801
802 // Kind returns the kind of event that this is.
803 func (e Event) Kind() EventKind {
804 return tracev2Type2Kind[e.base.typ]
805 }
806
807 // Time returns the timestamp of the event.
808 func (e Event) Time() Time {
809 return e.base.time
810 }
811
812 // Goroutine returns the ID of the goroutine that was executing when
813 // this event happened. It describes part of the execution context
814 // for this event.
815 //
816 // Note that for goroutine state transitions this always refers to the
817 // state before the transition. For example, if a goroutine is just
818 // starting to run on this thread and/or proc, then this will return
819 // NoGoroutine. In this case, the goroutine starting to run will be
820 // can be found at Event.StateTransition().Resource.
821 func (e Event) Goroutine() GoID {
822 return e.ctx.G
823 }
824
825 // Proc returns the ID of the proc this event event pertains to.
826 //
827 // Note that for proc state transitions this always refers to the
828 // state before the transition. For example, if a proc is just
829 // starting to run on this thread, then this will return NoProc.
830 func (e Event) Proc() ProcID {
831 return e.ctx.P
832 }
833
834 // Thread returns the ID of the thread this event pertains to.
835 //
836 // Note that for thread state transitions this always refers to the
837 // state before the transition. For example, if a thread is just
838 // starting to run, then this will return NoThread.
839 //
840 // Note: tracking thread state is not currently supported, so this
841 // will always return a valid thread ID. However thread state transitions
842 // may be tracked in the future, and callers must be robust to this
843 // possibility.
844 func (e Event) Thread() ThreadID {
845 return e.ctx.M
846 }
847
848 // Stack returns a handle to a stack associated with the event.
849 //
850 // This represents a stack trace at the current moment in time for
851 // the current execution context.
852 func (e Event) Stack() Stack {
853 if e.base.typ == evSync {
854 return NoStack
855 }
856 if e.base.typ == tracev2.EvCPUSample {
857 return Stack{table: e.table, id: stackID(e.base.args[0])}
858 }
859 spec := tracev2.Specs()[e.base.typ]
860 if len(spec.StackIDs) == 0 {
861 return NoStack
862 }
863 // The stack for the main execution context is always the
864 // first stack listed in StackIDs. Subtract one from this
865 // because we've peeled away the timestamp argument.
866 id := stackID(e.base.args[spec.StackIDs[0]-1])
867 if id == 0 {
868 return NoStack
869 }
870 return Stack{table: e.table, id: id}
871 }
872
873 // Metric returns details about a Metric event.
874 //
875 // Panics if Kind != EventMetric.
876 func (e Event) Metric() Metric {
877 if e.Kind() != EventMetric {
878 panic("Metric called on non-Metric event")
879 }
880 var m Metric
881 switch e.base.typ {
882 case tracev2.EvProcsChange:
883 m.Name = "/sched/gomaxprocs:threads"
884 m.Value = Uint64Value(e.base.args[0])
885 case tracev2.EvHeapAlloc:
886 m.Name = "/memory/classes/heap/objects:bytes"
887 m.Value = Uint64Value(e.base.args[0])
888 case tracev2.EvHeapGoal:
889 m.Name = "/gc/heap/goal:bytes"
890 m.Value = Uint64Value(e.base.args[0])
891 default:
892 panic(fmt.Sprintf("internal error: unexpected wire-format event type for Metric kind: %d", e.base.typ))
893 }
894 return m
895 }
896
897 // Label returns details about a Label event.
898 //
899 // Panics if Kind != EventLabel.
900 func (e Event) Label() Label {
901 if e.Kind() != EventLabel {
902 panic("Label called on non-Label event")
903 }
904 if e.base.typ != tracev2.EvGoLabel {
905 panic(fmt.Sprintf("internal error: unexpected wire-format event type for Label kind: %d", e.base.typ))
906 }
907 return Label{
908 Label: e.table.strings.mustGet(stringID(e.base.args[0])),
909 Resource: ResourceID{Kind: ResourceGoroutine, id: int64(e.ctx.G)},
910 }
911 }
912
913 // Range returns details about an EventRangeBegin, EventRangeActive, or EventRangeEnd event.
914 //
915 // Panics if Kind != EventRangeBegin, Kind != EventRangeActive, and Kind != EventRangeEnd.
916 func (e Event) Range() Range {
917 if kind := e.Kind(); kind != EventRangeBegin && kind != EventRangeActive && kind != EventRangeEnd {
918 panic("Range called on non-Range event")
919 }
920 var r Range
921 switch e.base.typ {
922 case tracev2.EvSTWBegin, tracev2.EvSTWEnd:
923 // N.B. ordering.advance smuggles in the STW reason as e.base.args[0]
924 // for tracev2.EvSTWEnd (it's already there for Begin).
925 r.Name = "stop-the-world (" + e.table.strings.mustGet(stringID(e.base.args[0])) + ")"
926 r.Scope = ResourceID{Kind: ResourceGoroutine, id: int64(e.Goroutine())}
927 case tracev2.EvGCBegin, tracev2.EvGCActive, tracev2.EvGCEnd:
928 r.Name = "GC concurrent mark phase"
929 r.Scope = ResourceID{Kind: ResourceNone}
930 case tracev2.EvGCSweepBegin, tracev2.EvGCSweepActive, tracev2.EvGCSweepEnd:
931 r.Name = "GC incremental sweep"
932 r.Scope = ResourceID{Kind: ResourceProc}
933 if e.base.typ == tracev2.EvGCSweepActive {
934 r.Scope.id = int64(e.base.args[0])
935 } else {
936 r.Scope.id = int64(e.Proc())
937 }
938 case tracev2.EvGCMarkAssistBegin, tracev2.EvGCMarkAssistActive, tracev2.EvGCMarkAssistEnd:
939 r.Name = "GC mark assist"
940 r.Scope = ResourceID{Kind: ResourceGoroutine}
941 if e.base.typ == tracev2.EvGCMarkAssistActive {
942 r.Scope.id = int64(e.base.args[0])
943 } else {
944 r.Scope.id = int64(e.Goroutine())
945 }
946 default:
947 panic(fmt.Sprintf("internal error: unexpected wire-event type for Range kind: %d", e.base.typ))
948 }
949 return r
950 }
951
952 // RangeAttributes returns attributes for a completed range.
953 //
954 // Panics if Kind != EventRangeEnd.
955 func (e Event) RangeAttributes() []RangeAttribute {
956 if e.Kind() != EventRangeEnd {
957 panic("Range called on non-Range event")
958 }
959 if e.base.typ != tracev2.EvGCSweepEnd {
960 return nil
961 }
962 return []RangeAttribute{
963 {
964 Name: "bytes swept",
965 Value: Uint64Value(e.base.args[0]),
966 },
967 {
968 Name: "bytes reclaimed",
969 Value: Uint64Value(e.base.args[1]),
970 },
971 }
972 }
973
974 // Task returns details about a TaskBegin or TaskEnd event.
975 //
976 // Panics if Kind != EventTaskBegin and Kind != EventTaskEnd.
977 func (e Event) Task() Task {
978 if kind := e.Kind(); kind != EventTaskBegin && kind != EventTaskEnd {
979 panic("Task called on non-Task event")
980 }
981 parentID := NoTask
982 var typ string
983 switch e.base.typ {
984 case tracev2.EvUserTaskBegin:
985 parentID = TaskID(e.base.args[1])
986 typ = e.table.strings.mustGet(stringID(e.base.args[2]))
987 case tracev2.EvUserTaskEnd:
988 parentID = TaskID(e.base.extra(version.Go122)[0])
989 typ = e.table.getExtraString(extraStringID(e.base.extra(version.Go122)[1]))
990 default:
991 panic(fmt.Sprintf("internal error: unexpected wire-format event type for Task kind: %d", e.base.typ))
992 }
993 return Task{
994 ID: TaskID(e.base.args[0]),
995 Parent: parentID,
996 Type: typ,
997 }
998 }
999
1000 // Region returns details about a RegionBegin or RegionEnd event.
1001 //
1002 // Panics if Kind != EventRegionBegin and Kind != EventRegionEnd.
1003 func (e Event) Region() Region {
1004 if kind := e.Kind(); kind != EventRegionBegin && kind != EventRegionEnd {
1005 panic("Region called on non-Region event")
1006 }
1007 if e.base.typ != tracev2.EvUserRegionBegin && e.base.typ != tracev2.EvUserRegionEnd {
1008 panic(fmt.Sprintf("internal error: unexpected wire-format event type for Region kind: %d", e.base.typ))
1009 }
1010 return Region{
1011 Task: TaskID(e.base.args[0]),
1012 Type: e.table.strings.mustGet(stringID(e.base.args[1])),
1013 }
1014 }
1015
1016 // Log returns details about a Log event.
1017 //
1018 // Panics if Kind != EventLog.
1019 func (e Event) Log() Log {
1020 if e.Kind() != EventLog {
1021 panic("Log called on non-Log event")
1022 }
1023 if e.base.typ != tracev2.EvUserLog {
1024 panic(fmt.Sprintf("internal error: unexpected wire-format event type for Log kind: %d", e.base.typ))
1025 }
1026 return Log{
1027 Task: TaskID(e.base.args[0]),
1028 Category: e.table.strings.mustGet(stringID(e.base.args[1])),
1029 Message: e.table.strings.mustGet(stringID(e.base.args[2])),
1030 }
1031 }
1032
1033 // StateTransition returns details about a StateTransition event.
1034 //
1035 // Panics if Kind != EventStateTransition.
1036 func (e Event) StateTransition() StateTransition {
1037 if e.Kind() != EventStateTransition {
1038 panic("StateTransition called on non-StateTransition event")
1039 }
1040 var s StateTransition
1041 switch e.base.typ {
1042 case tracev2.EvProcStart:
1043 s = MakeProcStateTransition(ProcID(e.base.args[0]), ProcIdle, ProcRunning)
1044 case tracev2.EvProcStop:
1045 s = MakeProcStateTransition(e.ctx.P, ProcRunning, ProcIdle)
1046 case tracev2.EvProcSteal:
1047 // N.B. ordering.advance populates e.base.extra.
1048 beforeState := ProcRunning
1049 if tracev2.ProcStatus(e.base.extra(version.Go122)[0]) == tracev2.ProcSyscallAbandoned {
1050 // We've lost information because this ProcSteal advanced on a
1051 // SyscallAbandoned state. Treat the P as idle because ProcStatus
1052 // treats SyscallAbandoned as Idle. Otherwise we'll have an invalid
1053 // transition.
1054 beforeState = ProcIdle
1055 }
1056 s = MakeProcStateTransition(ProcID(e.base.args[0]), beforeState, ProcIdle)
1057 case tracev2.EvProcStatus:
1058 // N.B. ordering.advance populates e.base.extra.
1059 s = MakeProcStateTransition(ProcID(e.base.args[0]), ProcState(e.base.extra(version.Go122)[0]), tracev2ProcStatus2ProcState[e.base.args[1]])
1060 case tracev2.EvGoCreate, tracev2.EvGoCreateBlocked:
1061 status := GoRunnable
1062 if e.base.typ == tracev2.EvGoCreateBlocked {
1063 status = GoWaiting
1064 }
1065 s = MakeGoStateTransition(GoID(e.base.args[0]), GoNotExist, status)
1066 s.Stack = Stack{table: e.table, id: stackID(e.base.args[1])}
1067 case tracev2.EvGoCreateSyscall:
1068 s = MakeGoStateTransition(GoID(e.base.args[0]), GoNotExist, GoSyscall)
1069 case tracev2.EvGoStart:
1070 s = MakeGoStateTransition(GoID(e.base.args[0]), GoRunnable, GoRunning)
1071 case tracev2.EvGoDestroy:
1072 s = MakeGoStateTransition(e.ctx.G, GoRunning, GoNotExist)
1073 case tracev2.EvGoDestroySyscall:
1074 s = MakeGoStateTransition(e.ctx.G, GoSyscall, GoNotExist)
1075 case tracev2.EvGoStop:
1076 s = MakeGoStateTransition(e.ctx.G, GoRunning, GoRunnable)
1077 s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
1078 s.Stack = e.Stack() // This event references the resource the event happened on.
1079 case tracev2.EvGoBlock:
1080 s = MakeGoStateTransition(e.ctx.G, GoRunning, GoWaiting)
1081 s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
1082 s.Stack = e.Stack() // This event references the resource the event happened on.
1083 case tracev2.EvGoUnblock, tracev2.EvGoSwitch, tracev2.EvGoSwitchDestroy:
1084 // N.B. GoSwitch and GoSwitchDestroy both emit additional events, but
1085 // the first thing they both do is unblock the goroutine they name,
1086 // identically to an unblock event (even their arguments match).
1087 s = MakeGoStateTransition(GoID(e.base.args[0]), GoWaiting, GoRunnable)
1088 case tracev2.EvGoSyscallBegin:
1089 s = MakeGoStateTransition(e.ctx.G, GoRunning, GoSyscall)
1090 s.Stack = e.Stack() // This event references the resource the event happened on.
1091 case tracev2.EvGoSyscallEnd:
1092 s = MakeGoStateTransition(e.ctx.G, GoSyscall, GoRunning)
1093 case tracev2.EvGoSyscallEndBlocked:
1094 s = MakeGoStateTransition(e.ctx.G, GoSyscall, GoRunnable)
1095 case tracev2.EvGoStatus, tracev2.EvGoStatusStack:
1096 packedStatus := e.base.args[2]
1097 from, to := packedStatus>>32, packedStatus&((1<<32)-1)
1098 s = MakeGoStateTransition(GoID(e.base.args[0]), GoState(from), tracev2GoStatus2GoState[to])
1099 s.Stack = e.Stack() // This event references the resource the event happened on.
1100 default:
1101 panic(fmt.Sprintf("internal error: unexpected wire-format event type for StateTransition kind: %d", e.base.typ))
1102 }
1103 return s
1104 }
1105
1106 // Sync returns details that are relevant for the following events, up to but excluding the
1107 // next EventSync event.
1108 func (e Event) Sync() Sync {
1109 if e.Kind() != EventSync {
1110 panic("Sync called on non-Sync event")
1111 }
1112 s := Sync{N: int(e.base.args[0])}
1113 if e.table != nil {
1114 expBatches := make(map[string][]ExperimentalBatch)
1115 for exp, batches := range e.table.expBatches {
1116 expBatches[tracev2.Experiments()[exp]] = batches
1117 }
1118 s.ExperimentalBatches = expBatches
1119 if e.table.hasClockSnapshot {
1120 s.ClockSnapshot = &ClockSnapshot{
1121 Trace: e.table.freq.mul(e.table.snapTime),
1122 Wall: e.table.snapWall,
1123 Mono: e.table.snapMono,
1124 }
1125 }
1126 }
1127 return s
1128 }
1129
1130 // Sync contains details potentially relevant to all the following events, up to but excluding
1131 // the next EventSync event.
1132 type Sync struct {
1133 // N indicates that this is the Nth sync event in the trace.
1134 N int
1135
1136 // ClockSnapshot represents a near-simultaneous clock reading of several
1137 // different system clocks. The snapshot can be used as a reference to
1138 // convert timestamps to different clocks, which is helpful for correlating
1139 // timestamps with data captured by other tools. The value is nil for traces
1140 // before go1.25.
1141 ClockSnapshot *ClockSnapshot
1142
1143 // ExperimentalBatches contain all the unparsed batches of data for a given experiment.
1144 ExperimentalBatches map[string][]ExperimentalBatch
1145 }
1146
1147 // ClockSnapshot represents a near-simultaneous clock reading of several
1148 // different system clocks. The snapshot can be used as a reference to convert
1149 // timestamps to different clocks, which is helpful for correlating timestamps
1150 // with data captured by other tools.
1151 type ClockSnapshot struct {
1152 // Trace is a snapshot of the trace clock.
1153 Trace Time
1154
1155 // Wall is a snapshot of the system's wall clock.
1156 Wall time.Time
1157
1158 // Mono is a snapshot of the system's monotonic clock.
1159 Mono uint64
1160 }
1161
1162 // Experimental returns a view of the raw event for an experimental event.
1163 //
1164 // Panics if Kind != EventExperimental.
1165 func (e Event) Experimental() ExperimentalEvent {
1166 if e.Kind() != EventExperimental {
1167 panic("Experimental called on non-Experimental event")
1168 }
1169 spec := tracev2.Specs()[e.base.typ]
1170 argNames := spec.Args[1:] // Skip timestamp; already handled.
1171 return ExperimentalEvent{
1172 Name: spec.Name,
1173 Experiment: tracev2.Experiments()[spec.Experiment],
1174 Args: argNames,
1175 table: e.table,
1176 argValues: e.base.args[:len(argNames)],
1177 }
1178 }
1179
1180 const evSync = ^tracev2.EventType(0)
1181
1182 var tracev2Type2Kind = [...]EventKind{
1183 tracev2.EvCPUSample: EventStackSample,
1184 tracev2.EvProcsChange: EventMetric,
1185 tracev2.EvProcStart: EventStateTransition,
1186 tracev2.EvProcStop: EventStateTransition,
1187 tracev2.EvProcSteal: EventStateTransition,
1188 tracev2.EvProcStatus: EventStateTransition,
1189 tracev2.EvGoCreate: EventStateTransition,
1190 tracev2.EvGoCreateSyscall: EventStateTransition,
1191 tracev2.EvGoStart: EventStateTransition,
1192 tracev2.EvGoDestroy: EventStateTransition,
1193 tracev2.EvGoDestroySyscall: EventStateTransition,
1194 tracev2.EvGoStop: EventStateTransition,
1195 tracev2.EvGoBlock: EventStateTransition,
1196 tracev2.EvGoUnblock: EventStateTransition,
1197 tracev2.EvGoSyscallBegin: EventStateTransition,
1198 tracev2.EvGoSyscallEnd: EventStateTransition,
1199 tracev2.EvGoSyscallEndBlocked: EventStateTransition,
1200 tracev2.EvGoStatus: EventStateTransition,
1201 tracev2.EvSTWBegin: EventRangeBegin,
1202 tracev2.EvSTWEnd: EventRangeEnd,
1203 tracev2.EvGCActive: EventRangeActive,
1204 tracev2.EvGCBegin: EventRangeBegin,
1205 tracev2.EvGCEnd: EventRangeEnd,
1206 tracev2.EvGCSweepActive: EventRangeActive,
1207 tracev2.EvGCSweepBegin: EventRangeBegin,
1208 tracev2.EvGCSweepEnd: EventRangeEnd,
1209 tracev2.EvGCMarkAssistActive: EventRangeActive,
1210 tracev2.EvGCMarkAssistBegin: EventRangeBegin,
1211 tracev2.EvGCMarkAssistEnd: EventRangeEnd,
1212 tracev2.EvHeapAlloc: EventMetric,
1213 tracev2.EvHeapGoal: EventMetric,
1214 tracev2.EvGoLabel: EventLabel,
1215 tracev2.EvUserTaskBegin: EventTaskBegin,
1216 tracev2.EvUserTaskEnd: EventTaskEnd,
1217 tracev2.EvUserRegionBegin: EventRegionBegin,
1218 tracev2.EvUserRegionEnd: EventRegionEnd,
1219 tracev2.EvUserLog: EventLog,
1220 tracev2.EvGoSwitch: EventStateTransition,
1221 tracev2.EvGoSwitchDestroy: EventStateTransition,
1222 tracev2.EvGoCreateBlocked: EventStateTransition,
1223 tracev2.EvGoStatusStack: EventStateTransition,
1224 tracev2.EvSpan: EventExperimental,
1225 tracev2.EvSpanAlloc: EventExperimental,
1226 tracev2.EvSpanFree: EventExperimental,
1227 tracev2.EvHeapObject: EventExperimental,
1228 tracev2.EvHeapObjectAlloc: EventExperimental,
1229 tracev2.EvHeapObjectFree: EventExperimental,
1230 tracev2.EvGoroutineStack: EventExperimental,
1231 tracev2.EvGoroutineStackAlloc: EventExperimental,
1232 tracev2.EvGoroutineStackFree: EventExperimental,
1233 evSync: EventSync,
1234 }
1235
1236 var tracev2GoStatus2GoState = [...]GoState{
1237 tracev2.GoRunnable: GoRunnable,
1238 tracev2.GoRunning: GoRunning,
1239 tracev2.GoWaiting: GoWaiting,
1240 tracev2.GoSyscall: GoSyscall,
1241 }
1242
1243 var goState2Tracev2GoStatus = [...]tracev2.GoStatus{
1244 GoRunnable: tracev2.GoRunnable,
1245 GoRunning: tracev2.GoRunning,
1246 GoWaiting: tracev2.GoWaiting,
1247 GoSyscall: tracev2.GoSyscall,
1248 }
1249
1250 var tracev2ProcStatus2ProcState = [...]ProcState{
1251 tracev2.ProcRunning: ProcRunning,
1252 tracev2.ProcIdle: ProcIdle,
1253 tracev2.ProcSyscall: ProcRunning,
1254 tracev2.ProcSyscallAbandoned: ProcIdle,
1255 }
1256
1257 var procState2Tracev2ProcStatus = [...]tracev2.ProcStatus{
1258 ProcRunning: tracev2.ProcRunning,
1259 ProcIdle: tracev2.ProcIdle,
1260 // TODO(felixge): how to map ProcSyscall and ProcSyscallAbandoned?
1261 }
1262
1263 // String returns the event as a human-readable string.
1264 //
1265 // The format of the string is intended for debugging and is subject to change.
1266 func (e Event) String() string {
1267 var sb strings.Builder
1268 fmt.Fprintf(&sb, "M=%d P=%d G=%d", e.Thread(), e.Proc(), e.Goroutine())
1269 fmt.Fprintf(&sb, " %s Time=%d", e.Kind(), e.Time())
1270 // Kind-specific fields.
1271 switch kind := e.Kind(); kind {
1272 case EventMetric:
1273 m := e.Metric()
1274 fmt.Fprintf(&sb, " Name=%q Value=%s", m.Name, m.Value)
1275 case EventLabel:
1276 l := e.Label()
1277 fmt.Fprintf(&sb, " Label=%q Resource=%s", l.Label, l.Resource)
1278 case EventRangeBegin, EventRangeActive, EventRangeEnd:
1279 r := e.Range()
1280 fmt.Fprintf(&sb, " Name=%q Scope=%s", r.Name, r.Scope)
1281 if kind == EventRangeEnd {
1282 fmt.Fprintf(&sb, " Attributes=[")
1283 for i, attr := range e.RangeAttributes() {
1284 if i != 0 {
1285 fmt.Fprintf(&sb, " ")
1286 }
1287 fmt.Fprintf(&sb, "%q=%s", attr.Name, attr.Value)
1288 }
1289 fmt.Fprintf(&sb, "]")
1290 }
1291 case EventTaskBegin, EventTaskEnd:
1292 t := e.Task()
1293 fmt.Fprintf(&sb, " ID=%d Parent=%d Type=%q", t.ID, t.Parent, t.Type)
1294 case EventRegionBegin, EventRegionEnd:
1295 r := e.Region()
1296 fmt.Fprintf(&sb, " Task=%d Type=%q", r.Task, r.Type)
1297 case EventLog:
1298 l := e.Log()
1299 fmt.Fprintf(&sb, " Task=%d Category=%q Message=%q", l.Task, l.Category, l.Message)
1300 case EventStateTransition:
1301 s := e.StateTransition()
1302 switch s.Resource.Kind {
1303 case ResourceGoroutine:
1304 id := s.Resource.Goroutine()
1305 old, new := s.Goroutine()
1306 fmt.Fprintf(&sb, " GoID=%d %s->%s", id, old, new)
1307 case ResourceProc:
1308 id := s.Resource.Proc()
1309 old, new := s.Proc()
1310 fmt.Fprintf(&sb, " ProcID=%d %s->%s", id, old, new)
1311 }
1312 fmt.Fprintf(&sb, " Reason=%q", s.Reason)
1313 if s.Stack != NoStack {
1314 fmt.Fprintln(&sb)
1315 fmt.Fprintln(&sb, "TransitionStack=")
1316 printStack(&sb, "\t", s.Stack.Frames())
1317 }
1318 case EventExperimental:
1319 r := e.Experimental()
1320 fmt.Fprintf(&sb, " Name=%s Args=[", r.Name)
1321 for i, arg := range r.Args {
1322 if i != 0 {
1323 fmt.Fprintf(&sb, ", ")
1324 }
1325 fmt.Fprintf(&sb, "%s=%s", arg, r.ArgValue(i).String())
1326 }
1327 fmt.Fprintf(&sb, "]")
1328 case EventSync:
1329 s := e.Sync()
1330 fmt.Fprintf(&sb, " N=%d", s.N)
1331 if s.ClockSnapshot != nil {
1332 fmt.Fprintf(&sb, " Trace=%d Mono=%d Wall=%s",
1333 s.ClockSnapshot.Trace,
1334 s.ClockSnapshot.Mono,
1335 s.ClockSnapshot.Wall.Format(time.RFC3339Nano),
1336 )
1337 }
1338 }
1339 if stk := e.Stack(); stk != NoStack {
1340 fmt.Fprintln(&sb)
1341 fmt.Fprintln(&sb, "Stack=")
1342 printStack(&sb, "\t", stk.Frames())
1343 }
1344 return sb.String()
1345 }
1346
1347 // validateTableIDs checks to make sure lookups in e.table
1348 // will work.
1349 func (e Event) validateTableIDs() error {
1350 if e.base.typ == evSync {
1351 return nil
1352 }
1353 spec := tracev2.Specs()[e.base.typ]
1354
1355 // Check stacks.
1356 for _, i := range spec.StackIDs {
1357 id := stackID(e.base.args[i-1])
1358 _, ok := e.table.stacks.get(id)
1359 if !ok {
1360 return fmt.Errorf("found invalid stack ID %d for event %s", id, spec.Name)
1361 }
1362 }
1363 // N.B. Strings referenced by stack frames are validated
1364 // early on, when reading the stacks in to begin with.
1365
1366 // Check strings.
1367 for _, i := range spec.StringIDs {
1368 id := stringID(e.base.args[i-1])
1369 _, ok := e.table.strings.get(id)
1370 if !ok {
1371 return fmt.Errorf("found invalid string ID %d for event %s", id, spec.Name)
1372 }
1373 }
1374 return nil
1375 }
1376
1377 func syncEvent(table *evTable, ts Time, n int) Event {
1378 ev := Event{
1379 table: table,
1380 ctx: schedCtx{
1381 G: NoGoroutine,
1382 P: NoProc,
1383 M: NoThread,
1384 },
1385 base: baseEvent{
1386 typ: evSync,
1387 time: ts,
1388 },
1389 }
1390 ev.base.args[0] = uint64(n)
1391 return ev
1392 }