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
5package trace
6
7import (
8	"fmt"
9	"math"
10	"strings"
11	"time"
12
13	"internal/trace/event"
14	"internal/trace/event/go122"
15	"internal/trace/version"
16)
17
18// EventKind indicates the kind of event this is.
19//
20// Use this information to obtain a more specific event that
21// allows access to more detailed information.
22type EventKind uint16
23
24const (
25	EventBad EventKind = iota
26
27	// EventKindSync is an event that indicates a global synchronization
28	// point in the trace. At the point of a sync event, the
29	// trace reader can be certain that all resources (e.g. threads,
30	// goroutines) that have existed until that point have been enumerated.
31	EventSync
32
33	// EventMetric is an event that represents the value of a metric at
34	// a particular point in time.
35	EventMetric
36
37	// EventLabel attaches a label to a resource.
38	EventLabel
39
40	// EventStackSample represents an execution sample, indicating what a
41	// thread/proc/goroutine was doing at a particular point in time via
42	// its backtrace.
43	//
44	// Note: Samples should be considered a close approximation of
45	// what a thread/proc/goroutine was executing at a given point in time.
46	// These events may slightly contradict the situation StateTransitions
47	// describe, so they should only be treated as a best-effort annotation.
48	EventStackSample
49
50	// EventRangeBegin and EventRangeEnd are a pair of generic events representing
51	// a special range of time. Ranges are named and scoped to some resource
52	// (identified via ResourceKind). A range that has begun but has not ended
53	// is considered active.
54	//
55	// EvRangeBegin and EvRangeEnd will share the same name, and an End will always
56	// follow a Begin on the same instance of the resource. The associated
57	// resource ID can be obtained from the Event. ResourceNone indicates the
58	// range is globally scoped. That is, any goroutine/proc/thread can start or
59	// stop, but only one such range may be active at any given time.
60	//
61	// EventRangeActive is like EventRangeBegin, but indicates that the range was
62	// already active. In this case, the resource referenced may not be in the current
63	// context.
64	EventRangeBegin
65	EventRangeActive
66	EventRangeEnd
67
68	// EvTaskBegin and EvTaskEnd are a pair of events representing a runtime/trace.Task.
69	EventTaskBegin
70	EventTaskEnd
71
72	// EventRegionBegin and EventRegionEnd are a pair of events represent a runtime/trace.Region.
73	EventRegionBegin
74	EventRegionEnd
75
76	// EventLog represents a runtime/trace.Log call.
77	EventLog
78
79	// EventStateTransition represents a state change for some resource.
80	EventStateTransition
81
82	// EventExperimental is an experimental event that is unvalidated and exposed in a raw form.
83	// Users are expected to understand the format and perform their own validation. These events
84	// may always be safely ignored.
85	EventExperimental
86)
87
88// String returns a string form of the EventKind.
89func (e EventKind) String() string {
90	if int(e) >= len(eventKindStrings) {
91		return eventKindStrings[0]
92	}
93	return eventKindStrings[e]
94}
95
96var eventKindStrings = [...]string{
97	EventBad:             "Bad",
98	EventSync:            "Sync",
99	EventMetric:          "Metric",
100	EventLabel:           "Label",
101	EventStackSample:     "StackSample",
102	EventRangeBegin:      "RangeBegin",
103	EventRangeActive:     "RangeActive",
104	EventRangeEnd:        "RangeEnd",
105	EventTaskBegin:       "TaskBegin",
106	EventTaskEnd:         "TaskEnd",
107	EventRegionBegin:     "RegionBegin",
108	EventRegionEnd:       "RegionEnd",
109	EventLog:             "Log",
110	EventStateTransition: "StateTransition",
111	EventExperimental:    "Experimental",
112}
113
114const maxTime = Time(math.MaxInt64)
115
116// Time is a timestamp in nanoseconds.
117//
118// It corresponds to the monotonic clock on the platform that the
119// trace was taken, and so is possible to correlate with timestamps
120// for other traces taken on the same machine using the same clock
121// (i.e. no reboots in between).
122//
123// The actual absolute value of the timestamp is only meaningful in
124// relation to other timestamps from the same clock.
125//
126// BUG: Timestamps coming from traces on Windows platforms are
127// only comparable with timestamps from the same trace. Timestamps
128// across traces cannot be compared, because the system clock is
129// not used as of Go 1.22.
130//
131// BUG: Traces produced by Go versions 1.21 and earlier cannot be
132// compared with timestamps from other traces taken on the same
133// machine. This is because the system clock was not used at all
134// to collect those timestamps.
135type Time int64
136
137// Sub subtracts t0 from t, returning the duration in nanoseconds.
138func (t Time) Sub(t0 Time) time.Duration {
139	return time.Duration(int64(t) - int64(t0))
140}
141
142// Metric provides details about a Metric event.
143type Metric struct {
144	// Name is the name of the sampled metric.
145	//
146	// Names follow the same convention as metric names in the
147	// runtime/metrics package, meaning they include the unit.
148	// Names that match with the runtime/metrics package represent
149	// the same quantity. Note that this corresponds to the
150	// runtime/metrics package for the Go version this trace was
151	// collected for.
152	Name string
153
154	// Value is the sampled value of the metric.
155	//
156	// The Value's Kind is tied to the name of the metric, and so is
157	// guaranteed to be the same for metric samples for the same metric.
158	Value Value
159}
160
161// Label provides details about a Label event.
162type Label struct {
163	// Label is the label applied to some resource.
164	Label string
165
166	// Resource is the resource to which this label should be applied.
167	Resource ResourceID
168}
169
170// Range provides details about a Range event.
171type Range struct {
172	// Name is a human-readable name for the range.
173	//
174	// This name can be used to identify the end of the range for the resource
175	// its scoped to, because only one of each type of range may be active on
176	// a particular resource. The relevant resource should be obtained from the
177	// Event that produced these details. The corresponding RangeEnd will have
178	// an identical name.
179	Name string
180
181	// Scope is the resource that the range is scoped to.
182	//
183	// For example, a ResourceGoroutine scope means that the same goroutine
184	// must have a start and end for the range, and that goroutine can only
185	// have one range of a particular name active at any given time. The
186	// ID that this range is scoped to may be obtained via Event.Goroutine.
187	//
188	// The ResourceNone scope means that the range is globally scoped. As a
189	// result, any goroutine/proc/thread may start or end the range, and only
190	// one such named range may be active globally at any given time.
191	//
192	// For RangeBegin and RangeEnd events, this will always reference some
193	// resource ID in the current execution context. For RangeActive events,
194	// this may reference a resource not in the current context. Prefer Scope
195	// over the current execution context.
196	Scope ResourceID
197}
198
199// RangeAttributes provides attributes about a completed Range.
200type RangeAttribute struct {
201	// Name is the human-readable name for the range.
202	Name string
203
204	// Value is the value of the attribute.
205	Value Value
206}
207
208// TaskID is the internal ID of a task used to disambiguate tasks (even if they
209// are of the same type).
210type TaskID uint64
211
212const (
213	// NoTask indicates the lack of a task.
214	NoTask = TaskID(^uint64(0))
215
216	// BackgroundTask is the global task that events are attached to if there was
217	// no other task in the context at the point the event was emitted.
218	BackgroundTask = TaskID(0)
219)
220
221// Task provides details about a Task event.
222type Task struct {
223	// ID is a unique identifier for the task.
224	//
225	// This can be used to associate the beginning of a task with its end.
226	ID TaskID
227
228	// ParentID is the ID of the parent task.
229	Parent TaskID
230
231	// Type is the taskType that was passed to runtime/trace.NewTask.
232	//
233	// May be "" if a task's TaskBegin event isn't present in the trace.
234	Type string
235}
236
237// Region provides details about a Region event.
238type Region struct {
239	// Task is the ID of the task this region is associated with.
240	Task TaskID
241
242	// Type is the regionType that was passed to runtime/trace.StartRegion or runtime/trace.WithRegion.
243	Type string
244}
245
246// Log provides details about a Log event.
247type Log struct {
248	// Task is the ID of the task this region is associated with.
249	Task TaskID
250
251	// Category is the category that was passed to runtime/trace.Log or runtime/trace.Logf.
252	Category string
253
254	// Message is the message that was passed to runtime/trace.Log or runtime/trace.Logf.
255	Message string
256}
257
258// Stack represents a stack. It's really a handle to a stack and it's trivially comparable.
259//
260// If two Stacks are equal then their Frames are guaranteed to be identical. If they are not
261// equal, however, their Frames may still be equal.
262type Stack struct {
263	table *evTable
264	id    stackID
265}
266
267// Frames is an iterator over the frames in a Stack.
268func (s Stack) Frames(yield func(f StackFrame) bool) bool {
269	if s.id == 0 {
270		return true
271	}
272	stk := s.table.stacks.mustGet(s.id)
273	for _, pc := range stk.pcs {
274		f := s.table.pcs[pc]
275		sf := StackFrame{
276			PC:   f.pc,
277			Func: s.table.strings.mustGet(f.funcID),
278			File: s.table.strings.mustGet(f.fileID),
279			Line: f.line,
280		}
281		if !yield(sf) {
282			return false
283		}
284	}
285	return true
286}
287
288// NoStack is a sentinel value that can be compared against any Stack value, indicating
289// a lack of a stack trace.
290var NoStack = Stack{}
291
292// StackFrame represents a single frame of a stack.
293type StackFrame struct {
294	// PC is the program counter of the function call if this
295	// is not a leaf frame. If it's a leaf frame, it's the point
296	// at which the stack trace was taken.
297	PC uint64
298
299	// Func is the name of the function this frame maps to.
300	Func string
301
302	// File is the file which contains the source code of Func.
303	File string
304
305	// Line is the line number within File which maps to PC.
306	Line uint64
307}
308
309// ExperimentalEvent presents a raw view of an experimental event's arguments and thier names.
310type ExperimentalEvent struct {
311	// Name is the name of the event.
312	Name string
313
314	// ArgNames is the names of the event's arguments in order.
315	// This may refer to a globally shared slice. Copy before mutating.
316	ArgNames []string
317
318	// Args contains the event's arguments.
319	Args []uint64
320
321	// Data is additional unparsed data that is associated with the experimental event.
322	// Data is likely to be shared across many ExperimentalEvents, so callers that parse
323	// Data are encouraged to cache the parse result and look it up by the value of Data.
324	Data *ExperimentalData
325}
326
327// ExperimentalData represents some raw and unparsed sidecar data present in the trace that is
328// associated with certain kinds of experimental events. For example, this data may contain
329// tables needed to interpret ExperimentalEvent arguments, or the ExperimentEvent could just be
330// a placeholder for a differently encoded event that's actually present in the experimental data.
331type ExperimentalData struct {
332	// Batches contain the actual experimental data, along with metadata about each batch.
333	Batches []ExperimentalBatch
334}
335
336// ExperimentalBatch represents a packet of unparsed data along with metadata about that packet.
337type ExperimentalBatch struct {
338	// Thread is the ID of the thread that produced a packet of data.
339	Thread ThreadID
340
341	// Data is a packet of unparsed data all produced by one thread.
342	Data []byte
343}
344
345// Event represents a single event in the trace.
346type Event struct {
347	table *evTable
348	ctx   schedCtx
349	base  baseEvent
350}
351
352// Kind returns the kind of event that this is.
353func (e Event) Kind() EventKind {
354	return go122Type2Kind[e.base.typ]
355}
356
357// Time returns the timestamp of the event.
358func (e Event) Time() Time {
359	return e.base.time
360}
361
362// Goroutine returns the ID of the goroutine that was executing when
363// this event happened. It describes part of the execution context
364// for this event.
365//
366// Note that for goroutine state transitions this always refers to the
367// state before the transition. For example, if a goroutine is just
368// starting to run on this thread and/or proc, then this will return
369// NoGoroutine. In this case, the goroutine starting to run will be
370// can be found at Event.StateTransition().Resource.
371func (e Event) Goroutine() GoID {
372	return e.ctx.G
373}
374
375// Proc returns the ID of the proc this event event pertains to.
376//
377// Note that for proc state transitions this always refers to the
378// state before the transition. For example, if a proc is just
379// starting to run on this thread, then this will return NoProc.
380func (e Event) Proc() ProcID {
381	return e.ctx.P
382}
383
384// Thread returns the ID of the thread this event pertains to.
385//
386// Note that for thread state transitions this always refers to the
387// state before the transition. For example, if a thread is just
388// starting to run, then this will return NoThread.
389//
390// Note: tracking thread state is not currently supported, so this
391// will always return a valid thread ID. However thread state transitions
392// may be tracked in the future, and callers must be robust to this
393// possibility.
394func (e Event) Thread() ThreadID {
395	return e.ctx.M
396}
397
398// Stack returns a handle to a stack associated with the event.
399//
400// This represents a stack trace at the current moment in time for
401// the current execution context.
402func (e Event) Stack() Stack {
403	if e.base.typ == evSync {
404		return NoStack
405	}
406	if e.base.typ == go122.EvCPUSample {
407		return Stack{table: e.table, id: stackID(e.base.args[0])}
408	}
409	spec := go122.Specs()[e.base.typ]
410	if len(spec.StackIDs) == 0 {
411		return NoStack
412	}
413	// The stack for the main execution context is always the
414	// first stack listed in StackIDs. Subtract one from this
415	// because we've peeled away the timestamp argument.
416	id := stackID(e.base.args[spec.StackIDs[0]-1])
417	if id == 0 {
418		return NoStack
419	}
420	return Stack{table: e.table, id: id}
421}
422
423// Metric returns details about a Metric event.
424//
425// Panics if Kind != EventMetric.
426func (e Event) Metric() Metric {
427	if e.Kind() != EventMetric {
428		panic("Metric called on non-Metric event")
429	}
430	var m Metric
431	switch e.base.typ {
432	case go122.EvProcsChange:
433		m.Name = "/sched/gomaxprocs:threads"
434		m.Value = Value{kind: ValueUint64, scalar: e.base.args[0]}
435	case go122.EvHeapAlloc:
436		m.Name = "/memory/classes/heap/objects:bytes"
437		m.Value = Value{kind: ValueUint64, scalar: e.base.args[0]}
438	case go122.EvHeapGoal:
439		m.Name = "/gc/heap/goal:bytes"
440		m.Value = Value{kind: ValueUint64, scalar: e.base.args[0]}
441	default:
442		panic(fmt.Sprintf("internal error: unexpected event type for Metric kind: %s", go122.EventString(e.base.typ)))
443	}
444	return m
445}
446
447// Label returns details about a Label event.
448//
449// Panics if Kind != EventLabel.
450func (e Event) Label() Label {
451	if e.Kind() != EventLabel {
452		panic("Label called on non-Label event")
453	}
454	if e.base.typ != go122.EvGoLabel {
455		panic(fmt.Sprintf("internal error: unexpected event type for Label kind: %s", go122.EventString(e.base.typ)))
456	}
457	return Label{
458		Label:    e.table.strings.mustGet(stringID(e.base.args[0])),
459		Resource: ResourceID{Kind: ResourceGoroutine, id: int64(e.ctx.G)},
460	}
461}
462
463// Range returns details about an EventRangeBegin, EventRangeActive, or EventRangeEnd event.
464//
465// Panics if Kind != EventRangeBegin, Kind != EventRangeActive, and Kind != EventRangeEnd.
466func (e Event) Range() Range {
467	if kind := e.Kind(); kind != EventRangeBegin && kind != EventRangeActive && kind != EventRangeEnd {
468		panic("Range called on non-Range event")
469	}
470	var r Range
471	switch e.base.typ {
472	case go122.EvSTWBegin, go122.EvSTWEnd:
473		// N.B. ordering.advance smuggles in the STW reason as e.base.args[0]
474		// for go122.EvSTWEnd (it's already there for Begin).
475		r.Name = "stop-the-world (" + e.table.strings.mustGet(stringID(e.base.args[0])) + ")"
476		r.Scope = ResourceID{Kind: ResourceGoroutine, id: int64(e.Goroutine())}
477	case go122.EvGCBegin, go122.EvGCActive, go122.EvGCEnd:
478		r.Name = "GC concurrent mark phase"
479		r.Scope = ResourceID{Kind: ResourceNone}
480	case go122.EvGCSweepBegin, go122.EvGCSweepActive, go122.EvGCSweepEnd:
481		r.Name = "GC incremental sweep"
482		r.Scope = ResourceID{Kind: ResourceProc}
483		if e.base.typ == go122.EvGCSweepActive {
484			r.Scope.id = int64(e.base.args[0])
485		} else {
486			r.Scope.id = int64(e.Proc())
487		}
488		r.Scope.id = int64(e.Proc())
489	case go122.EvGCMarkAssistBegin, go122.EvGCMarkAssistActive, go122.EvGCMarkAssistEnd:
490		r.Name = "GC mark assist"
491		r.Scope = ResourceID{Kind: ResourceGoroutine}
492		if e.base.typ == go122.EvGCMarkAssistActive {
493			r.Scope.id = int64(e.base.args[0])
494		} else {
495			r.Scope.id = int64(e.Goroutine())
496		}
497	default:
498		panic(fmt.Sprintf("internal error: unexpected event type for Range kind: %s", go122.EventString(e.base.typ)))
499	}
500	return r
501}
502
503// RangeAttributes returns attributes for a completed range.
504//
505// Panics if Kind != EventRangeEnd.
506func (e Event) RangeAttributes() []RangeAttribute {
507	if e.Kind() != EventRangeEnd {
508		panic("Range called on non-Range event")
509	}
510	if e.base.typ != go122.EvGCSweepEnd {
511		return nil
512	}
513	return []RangeAttribute{
514		{
515			Name:  "bytes swept",
516			Value: Value{kind: ValueUint64, scalar: e.base.args[0]},
517		},
518		{
519			Name:  "bytes reclaimed",
520			Value: Value{kind: ValueUint64, scalar: e.base.args[1]},
521		},
522	}
523}
524
525// Task returns details about a TaskBegin or TaskEnd event.
526//
527// Panics if Kind != EventTaskBegin and Kind != EventTaskEnd.
528func (e Event) Task() Task {
529	if kind := e.Kind(); kind != EventTaskBegin && kind != EventTaskEnd {
530		panic("Task called on non-Task event")
531	}
532	parentID := NoTask
533	var typ string
534	switch e.base.typ {
535	case go122.EvUserTaskBegin:
536		parentID = TaskID(e.base.args[1])
537		typ = e.table.strings.mustGet(stringID(e.base.args[2]))
538	case go122.EvUserTaskEnd:
539		parentID = TaskID(e.base.extra(version.Go122)[0])
540		typ = e.table.getExtraString(extraStringID(e.base.extra(version.Go122)[1]))
541	default:
542		panic(fmt.Sprintf("internal error: unexpected event type for Task kind: %s", go122.EventString(e.base.typ)))
543	}
544	return Task{
545		ID:     TaskID(e.base.args[0]),
546		Parent: parentID,
547		Type:   typ,
548	}
549}
550
551// Region returns details about a RegionBegin or RegionEnd event.
552//
553// Panics if Kind != EventRegionBegin and Kind != EventRegionEnd.
554func (e Event) Region() Region {
555	if kind := e.Kind(); kind != EventRegionBegin && kind != EventRegionEnd {
556		panic("Region called on non-Region event")
557	}
558	if e.base.typ != go122.EvUserRegionBegin && e.base.typ != go122.EvUserRegionEnd {
559		panic(fmt.Sprintf("internal error: unexpected event type for Region kind: %s", go122.EventString(e.base.typ)))
560	}
561	return Region{
562		Task: TaskID(e.base.args[0]),
563		Type: e.table.strings.mustGet(stringID(e.base.args[1])),
564	}
565}
566
567// Log returns details about a Log event.
568//
569// Panics if Kind != EventLog.
570func (e Event) Log() Log {
571	if e.Kind() != EventLog {
572		panic("Log called on non-Log event")
573	}
574	if e.base.typ != go122.EvUserLog {
575		panic(fmt.Sprintf("internal error: unexpected event type for Log kind: %s", go122.EventString(e.base.typ)))
576	}
577	return Log{
578		Task:     TaskID(e.base.args[0]),
579		Category: e.table.strings.mustGet(stringID(e.base.args[1])),
580		Message:  e.table.strings.mustGet(stringID(e.base.args[2])),
581	}
582}
583
584// StateTransition returns details about a StateTransition event.
585//
586// Panics if Kind != EventStateTransition.
587func (e Event) StateTransition() StateTransition {
588	if e.Kind() != EventStateTransition {
589		panic("StateTransition called on non-StateTransition event")
590	}
591	var s StateTransition
592	switch e.base.typ {
593	case go122.EvProcStart:
594		s = procStateTransition(ProcID(e.base.args[0]), ProcIdle, ProcRunning)
595	case go122.EvProcStop:
596		s = procStateTransition(e.ctx.P, ProcRunning, ProcIdle)
597	case go122.EvProcSteal:
598		// N.B. ordering.advance populates e.base.extra.
599		beforeState := ProcRunning
600		if go122.ProcStatus(e.base.extra(version.Go122)[0]) == go122.ProcSyscallAbandoned {
601			// We've lost information because this ProcSteal advanced on a
602			// SyscallAbandoned state. Treat the P as idle because ProcStatus
603			// treats SyscallAbandoned as Idle. Otherwise we'll have an invalid
604			// transition.
605			beforeState = ProcIdle
606		}
607		s = procStateTransition(ProcID(e.base.args[0]), beforeState, ProcIdle)
608	case go122.EvProcStatus:
609		// N.B. ordering.advance populates e.base.extra.
610		s = procStateTransition(ProcID(e.base.args[0]), ProcState(e.base.extra(version.Go122)[0]), go122ProcStatus2ProcState[e.base.args[1]])
611	case go122.EvGoCreate, go122.EvGoCreateBlocked:
612		status := GoRunnable
613		if e.base.typ == go122.EvGoCreateBlocked {
614			status = GoWaiting
615		}
616		s = goStateTransition(GoID(e.base.args[0]), GoNotExist, status)
617		s.Stack = Stack{table: e.table, id: stackID(e.base.args[1])}
618	case go122.EvGoCreateSyscall:
619		s = goStateTransition(GoID(e.base.args[0]), GoNotExist, GoSyscall)
620	case go122.EvGoStart:
621		s = goStateTransition(GoID(e.base.args[0]), GoRunnable, GoRunning)
622	case go122.EvGoDestroy:
623		s = goStateTransition(e.ctx.G, GoRunning, GoNotExist)
624		s.Stack = e.Stack() // This event references the resource the event happened on.
625	case go122.EvGoDestroySyscall:
626		s = goStateTransition(e.ctx.G, GoSyscall, GoNotExist)
627	case go122.EvGoStop:
628		s = goStateTransition(e.ctx.G, GoRunning, GoRunnable)
629		s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
630		s.Stack = e.Stack() // This event references the resource the event happened on.
631	case go122.EvGoBlock:
632		s = goStateTransition(e.ctx.G, GoRunning, GoWaiting)
633		s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
634		s.Stack = e.Stack() // This event references the resource the event happened on.
635	case go122.EvGoUnblock, go122.EvGoSwitch, go122.EvGoSwitchDestroy:
636		// N.B. GoSwitch and GoSwitchDestroy both emit additional events, but
637		// the first thing they both do is unblock the goroutine they name,
638		// identically to an unblock event (even their arguments match).
639		s = goStateTransition(GoID(e.base.args[0]), GoWaiting, GoRunnable)
640	case go122.EvGoSyscallBegin:
641		s = goStateTransition(e.ctx.G, GoRunning, GoSyscall)
642		s.Stack = e.Stack() // This event references the resource the event happened on.
643	case go122.EvGoSyscallEnd:
644		s = goStateTransition(e.ctx.G, GoSyscall, GoRunning)
645		s.Stack = e.Stack() // This event references the resource the event happened on.
646	case go122.EvGoSyscallEndBlocked:
647		s = goStateTransition(e.ctx.G, GoSyscall, GoRunnable)
648		s.Stack = e.Stack() // This event references the resource the event happened on.
649	case go122.EvGoStatus, go122.EvGoStatusStack:
650		// N.B. ordering.advance populates e.base.extra.
651		s = goStateTransition(GoID(e.base.args[0]), GoState(e.base.extra(version.Go122)[0]), go122GoStatus2GoState[e.base.args[2]])
652	default:
653		panic(fmt.Sprintf("internal error: unexpected event type for StateTransition kind: %s", go122.EventString(e.base.typ)))
654	}
655	return s
656}
657
658// Experimental returns a view of the raw event for an experimental event.
659//
660// Panics if Kind != EventExperimental.
661func (e Event) Experimental() ExperimentalEvent {
662	if e.Kind() != EventExperimental {
663		panic("Experimental called on non-Experimental event")
664	}
665	spec := go122.Specs()[e.base.typ]
666	argNames := spec.Args[1:] // Skip timestamp; already handled.
667	return ExperimentalEvent{
668		Name:     spec.Name,
669		ArgNames: argNames,
670		Args:     e.base.args[:len(argNames)],
671		Data:     e.table.expData[spec.Experiment],
672	}
673}
674
675const evSync = ^event.Type(0)
676
677var go122Type2Kind = [...]EventKind{
678	go122.EvCPUSample:           EventStackSample,
679	go122.EvProcsChange:         EventMetric,
680	go122.EvProcStart:           EventStateTransition,
681	go122.EvProcStop:            EventStateTransition,
682	go122.EvProcSteal:           EventStateTransition,
683	go122.EvProcStatus:          EventStateTransition,
684	go122.EvGoCreate:            EventStateTransition,
685	go122.EvGoCreateSyscall:     EventStateTransition,
686	go122.EvGoStart:             EventStateTransition,
687	go122.EvGoDestroy:           EventStateTransition,
688	go122.EvGoDestroySyscall:    EventStateTransition,
689	go122.EvGoStop:              EventStateTransition,
690	go122.EvGoBlock:             EventStateTransition,
691	go122.EvGoUnblock:           EventStateTransition,
692	go122.EvGoSyscallBegin:      EventStateTransition,
693	go122.EvGoSyscallEnd:        EventStateTransition,
694	go122.EvGoSyscallEndBlocked: EventStateTransition,
695	go122.EvGoStatus:            EventStateTransition,
696	go122.EvSTWBegin:            EventRangeBegin,
697	go122.EvSTWEnd:              EventRangeEnd,
698	go122.EvGCActive:            EventRangeActive,
699	go122.EvGCBegin:             EventRangeBegin,
700	go122.EvGCEnd:               EventRangeEnd,
701	go122.EvGCSweepActive:       EventRangeActive,
702	go122.EvGCSweepBegin:        EventRangeBegin,
703	go122.EvGCSweepEnd:          EventRangeEnd,
704	go122.EvGCMarkAssistActive:  EventRangeActive,
705	go122.EvGCMarkAssistBegin:   EventRangeBegin,
706	go122.EvGCMarkAssistEnd:     EventRangeEnd,
707	go122.EvHeapAlloc:           EventMetric,
708	go122.EvHeapGoal:            EventMetric,
709	go122.EvGoLabel:             EventLabel,
710	go122.EvUserTaskBegin:       EventTaskBegin,
711	go122.EvUserTaskEnd:         EventTaskEnd,
712	go122.EvUserRegionBegin:     EventRegionBegin,
713	go122.EvUserRegionEnd:       EventRegionEnd,
714	go122.EvUserLog:             EventLog,
715	go122.EvGoSwitch:            EventStateTransition,
716	go122.EvGoSwitchDestroy:     EventStateTransition,
717	go122.EvGoCreateBlocked:     EventStateTransition,
718	go122.EvGoStatusStack:       EventStateTransition,
719	go122.EvSpan:                EventExperimental,
720	go122.EvSpanAlloc:           EventExperimental,
721	go122.EvSpanFree:            EventExperimental,
722	go122.EvHeapObject:          EventExperimental,
723	go122.EvHeapObjectAlloc:     EventExperimental,
724	go122.EvHeapObjectFree:      EventExperimental,
725	go122.EvGoroutineStack:      EventExperimental,
726	go122.EvGoroutineStackAlloc: EventExperimental,
727	go122.EvGoroutineStackFree:  EventExperimental,
728	evSync:                      EventSync,
729}
730
731var go122GoStatus2GoState = [...]GoState{
732	go122.GoRunnable: GoRunnable,
733	go122.GoRunning:  GoRunning,
734	go122.GoWaiting:  GoWaiting,
735	go122.GoSyscall:  GoSyscall,
736}
737
738var go122ProcStatus2ProcState = [...]ProcState{
739	go122.ProcRunning:          ProcRunning,
740	go122.ProcIdle:             ProcIdle,
741	go122.ProcSyscall:          ProcRunning,
742	go122.ProcSyscallAbandoned: ProcIdle,
743}
744
745// String returns the event as a human-readable string.
746//
747// The format of the string is intended for debugging and is subject to change.
748func (e Event) String() string {
749	var sb strings.Builder
750	fmt.Fprintf(&sb, "M=%d P=%d G=%d", e.Thread(), e.Proc(), e.Goroutine())
751	fmt.Fprintf(&sb, " %s Time=%d", e.Kind(), e.Time())
752	// Kind-specific fields.
753	switch kind := e.Kind(); kind {
754	case EventMetric:
755		m := e.Metric()
756		fmt.Fprintf(&sb, " Name=%q Value=%s", m.Name, valueAsString(m.Value))
757	case EventLabel:
758		l := e.Label()
759		fmt.Fprintf(&sb, " Label=%q Resource=%s", l.Label, l.Resource)
760	case EventRangeBegin, EventRangeActive, EventRangeEnd:
761		r := e.Range()
762		fmt.Fprintf(&sb, " Name=%q Scope=%s", r.Name, r.Scope)
763		if kind == EventRangeEnd {
764			fmt.Fprintf(&sb, " Attributes=[")
765			for i, attr := range e.RangeAttributes() {
766				if i != 0 {
767					fmt.Fprintf(&sb, " ")
768				}
769				fmt.Fprintf(&sb, "%q=%s", attr.Name, valueAsString(attr.Value))
770			}
771			fmt.Fprintf(&sb, "]")
772		}
773	case EventTaskBegin, EventTaskEnd:
774		t := e.Task()
775		fmt.Fprintf(&sb, " ID=%d Parent=%d Type=%q", t.ID, t.Parent, t.Type)
776	case EventRegionBegin, EventRegionEnd:
777		r := e.Region()
778		fmt.Fprintf(&sb, " Task=%d Type=%q", r.Task, r.Type)
779	case EventLog:
780		l := e.Log()
781		fmt.Fprintf(&sb, " Task=%d Category=%q Message=%q", l.Task, l.Category, l.Message)
782	case EventStateTransition:
783		s := e.StateTransition()
784		fmt.Fprintf(&sb, " Resource=%s Reason=%q", s.Resource, s.Reason)
785		switch s.Resource.Kind {
786		case ResourceGoroutine:
787			id := s.Resource.Goroutine()
788			old, new := s.Goroutine()
789			fmt.Fprintf(&sb, " GoID=%d %s->%s", id, old, new)
790		case ResourceProc:
791			id := s.Resource.Proc()
792			old, new := s.Proc()
793			fmt.Fprintf(&sb, " ProcID=%d %s->%s", id, old, new)
794		}
795		if s.Stack != NoStack {
796			fmt.Fprintln(&sb)
797			fmt.Fprintln(&sb, "TransitionStack=")
798			s.Stack.Frames(func(f StackFrame) bool {
799				fmt.Fprintf(&sb, "\t%s @ 0x%x\n", f.Func, f.PC)
800				fmt.Fprintf(&sb, "\t\t%s:%d\n", f.File, f.Line)
801				return true
802			})
803		}
804	case EventExperimental:
805		r := e.Experimental()
806		fmt.Fprintf(&sb, " Name=%s ArgNames=%v Args=%v", r.Name, r.ArgNames, r.Args)
807	}
808	if stk := e.Stack(); stk != NoStack {
809		fmt.Fprintln(&sb)
810		fmt.Fprintln(&sb, "Stack=")
811		stk.Frames(func(f StackFrame) bool {
812			fmt.Fprintf(&sb, "\t%s @ 0x%x\n", f.Func, f.PC)
813			fmt.Fprintf(&sb, "\t\t%s:%d\n", f.File, f.Line)
814			return true
815		})
816	}
817	return sb.String()
818}
819
820// validateTableIDs checks to make sure lookups in e.table
821// will work.
822func (e Event) validateTableIDs() error {
823	if e.base.typ == evSync {
824		return nil
825	}
826	spec := go122.Specs()[e.base.typ]
827
828	// Check stacks.
829	for _, i := range spec.StackIDs {
830		id := stackID(e.base.args[i-1])
831		_, ok := e.table.stacks.get(id)
832		if !ok {
833			return fmt.Errorf("found invalid stack ID %d for event %s", id, spec.Name)
834		}
835	}
836	// N.B. Strings referenced by stack frames are validated
837	// early on, when reading the stacks in to begin with.
838
839	// Check strings.
840	for _, i := range spec.StringIDs {
841		id := stringID(e.base.args[i-1])
842		_, ok := e.table.strings.get(id)
843		if !ok {
844			return fmt.Errorf("found invalid string ID %d for event %s", id, spec.Name)
845		}
846	}
847	return nil
848}
849
850func syncEvent(table *evTable, ts Time) Event {
851	return Event{
852		table: table,
853		ctx: schedCtx{
854			G: NoGoroutine,
855			P: NoProc,
856			M: NoThread,
857		},
858		base: baseEvent{
859			typ:  evSync,
860			time: ts,
861		},
862	}
863}
864