Debian Codegraph @

src/internal/trace/event.go

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