Source file src/internal/trace/event.go

     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  	"fmt"
     9  	"iter"
    10  	"math"
    11  	"strings"
    12  	"time"
    13  
    14  	"internal/trace/tracev2"
    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.
    22  type EventKind uint16
    23  
    24  const (
    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.
    89  func (e EventKind) String() string {
    90  	if int(e) >= len(eventKindStrings) {
    91  		return eventKindStrings[0]
    92  	}
    93  	return eventKindStrings[e]
    94  }
    95  
    96  var 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  
   114  const 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.
   135  type Time int64
   136  
   137  // Sub subtracts t0 from t, returning the duration in nanoseconds.
   138  func (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.
   143  type 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.
   162  type 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.
   171  type 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.
   200  type 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).
   210  type TaskID uint64
   211  
   212  const (
   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.
   222  type 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.
   238  type 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.
   247  type 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.
   262  type Stack struct {
   263  	table *evTable
   264  	id    stackID
   265  }
   266  
   267  // Frames is an iterator over the frames in a Stack.
   268  func (s Stack) Frames() iter.Seq[StackFrame] {
   269  	return func(yield func(StackFrame) bool) {
   270  		if s.id == 0 {
   271  			return
   272  		}
   273  		stk := s.table.stacks.mustGet(s.id)
   274  		for _, pc := range stk.pcs {
   275  			f := s.table.pcs[pc]
   276  			sf := StackFrame{
   277  				PC:   f.pc,
   278  				Func: s.table.strings.mustGet(f.funcID),
   279  				File: s.table.strings.mustGet(f.fileID),
   280  				Line: f.line,
   281  			}
   282  			if !yield(sf) {
   283  				return
   284  			}
   285  		}
   286  	}
   287  }
   288  
   289  // NoStack is a sentinel value that can be compared against any Stack value, indicating
   290  // a lack of a stack trace.
   291  var NoStack = Stack{}
   292  
   293  // StackFrame represents a single frame of a stack.
   294  type StackFrame struct {
   295  	// PC is the program counter of the function call if this
   296  	// is not a leaf frame. If it's a leaf frame, it's the point
   297  	// at which the stack trace was taken.
   298  	PC uint64
   299  
   300  	// Func is the name of the function this frame maps to.
   301  	Func string
   302  
   303  	// File is the file which contains the source code of Func.
   304  	File string
   305  
   306  	// Line is the line number within File which maps to PC.
   307  	Line uint64
   308  }
   309  
   310  // ExperimentalEvent presents a raw view of an experimental event's arguments and their names.
   311  type ExperimentalEvent struct {
   312  	// Name is the name of the event.
   313  	Name string
   314  
   315  	// Experiment is the name of the experiment this event is a part of.
   316  	Experiment string
   317  
   318  	// Args lists the names of the event's arguments in order.
   319  	Args []string
   320  
   321  	// argValues contains the raw integer arguments which are interpreted
   322  	// by ArgValue using table.
   323  	table     *evTable
   324  	argValues []uint64
   325  }
   326  
   327  // ArgValue returns a typed Value for the i'th argument in the experimental event.
   328  func (e ExperimentalEvent) ArgValue(i int) Value {
   329  	if i < 0 || i >= len(e.Args) {
   330  		panic(fmt.Sprintf("experimental event argument index %d out of bounds [0, %d)", i, len(e.Args)))
   331  	}
   332  	if strings.HasSuffix(e.Args[i], "string") {
   333  		s := e.table.strings.mustGet(stringID(e.argValues[i]))
   334  		return stringValue(s)
   335  	}
   336  	return uint64Value(e.argValues[i])
   337  }
   338  
   339  // ExperimentalBatch represents a packet of unparsed data along with metadata about that packet.
   340  type ExperimentalBatch struct {
   341  	// Thread is the ID of the thread that produced a packet of data.
   342  	Thread ThreadID
   343  
   344  	// Data is a packet of unparsed data all produced by one thread.
   345  	Data []byte
   346  }
   347  
   348  // Event represents a single event in the trace.
   349  type Event struct {
   350  	table *evTable
   351  	ctx   schedCtx
   352  	base  baseEvent
   353  }
   354  
   355  // Kind returns the kind of event that this is.
   356  func (e Event) Kind() EventKind {
   357  	return tracev2Type2Kind[e.base.typ]
   358  }
   359  
   360  // Time returns the timestamp of the event.
   361  func (e Event) Time() Time {
   362  	return e.base.time
   363  }
   364  
   365  // Goroutine returns the ID of the goroutine that was executing when
   366  // this event happened. It describes part of the execution context
   367  // for this event.
   368  //
   369  // Note that for goroutine state transitions this always refers to the
   370  // state before the transition. For example, if a goroutine is just
   371  // starting to run on this thread and/or proc, then this will return
   372  // NoGoroutine. In this case, the goroutine starting to run will be
   373  // can be found at Event.StateTransition().Resource.
   374  func (e Event) Goroutine() GoID {
   375  	return e.ctx.G
   376  }
   377  
   378  // Proc returns the ID of the proc this event event pertains to.
   379  //
   380  // Note that for proc state transitions this always refers to the
   381  // state before the transition. For example, if a proc is just
   382  // starting to run on this thread, then this will return NoProc.
   383  func (e Event) Proc() ProcID {
   384  	return e.ctx.P
   385  }
   386  
   387  // Thread returns the ID of the thread this event pertains to.
   388  //
   389  // Note that for thread state transitions this always refers to the
   390  // state before the transition. For example, if a thread is just
   391  // starting to run, then this will return NoThread.
   392  //
   393  // Note: tracking thread state is not currently supported, so this
   394  // will always return a valid thread ID. However thread state transitions
   395  // may be tracked in the future, and callers must be robust to this
   396  // possibility.
   397  func (e Event) Thread() ThreadID {
   398  	return e.ctx.M
   399  }
   400  
   401  // Stack returns a handle to a stack associated with the event.
   402  //
   403  // This represents a stack trace at the current moment in time for
   404  // the current execution context.
   405  func (e Event) Stack() Stack {
   406  	if e.base.typ == evSync {
   407  		return NoStack
   408  	}
   409  	if e.base.typ == tracev2.EvCPUSample {
   410  		return Stack{table: e.table, id: stackID(e.base.args[0])}
   411  	}
   412  	spec := tracev2.Specs()[e.base.typ]
   413  	if len(spec.StackIDs) == 0 {
   414  		return NoStack
   415  	}
   416  	// The stack for the main execution context is always the
   417  	// first stack listed in StackIDs. Subtract one from this
   418  	// because we've peeled away the timestamp argument.
   419  	id := stackID(e.base.args[spec.StackIDs[0]-1])
   420  	if id == 0 {
   421  		return NoStack
   422  	}
   423  	return Stack{table: e.table, id: id}
   424  }
   425  
   426  // Metric returns details about a Metric event.
   427  //
   428  // Panics if Kind != EventMetric.
   429  func (e Event) Metric() Metric {
   430  	if e.Kind() != EventMetric {
   431  		panic("Metric called on non-Metric event")
   432  	}
   433  	var m Metric
   434  	switch e.base.typ {
   435  	case tracev2.EvProcsChange:
   436  		m.Name = "/sched/gomaxprocs:threads"
   437  		m.Value = uint64Value(e.base.args[0])
   438  	case tracev2.EvHeapAlloc:
   439  		m.Name = "/memory/classes/heap/objects:bytes"
   440  		m.Value = uint64Value(e.base.args[0])
   441  	case tracev2.EvHeapGoal:
   442  		m.Name = "/gc/heap/goal:bytes"
   443  		m.Value = uint64Value(e.base.args[0])
   444  	default:
   445  		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Metric kind: %d", e.base.typ))
   446  	}
   447  	return m
   448  }
   449  
   450  // Label returns details about a Label event.
   451  //
   452  // Panics if Kind != EventLabel.
   453  func (e Event) Label() Label {
   454  	if e.Kind() != EventLabel {
   455  		panic("Label called on non-Label event")
   456  	}
   457  	if e.base.typ != tracev2.EvGoLabel {
   458  		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Label kind: %d", e.base.typ))
   459  	}
   460  	return Label{
   461  		Label:    e.table.strings.mustGet(stringID(e.base.args[0])),
   462  		Resource: ResourceID{Kind: ResourceGoroutine, id: int64(e.ctx.G)},
   463  	}
   464  }
   465  
   466  // Range returns details about an EventRangeBegin, EventRangeActive, or EventRangeEnd event.
   467  //
   468  // Panics if Kind != EventRangeBegin, Kind != EventRangeActive, and Kind != EventRangeEnd.
   469  func (e Event) Range() Range {
   470  	if kind := e.Kind(); kind != EventRangeBegin && kind != EventRangeActive && kind != EventRangeEnd {
   471  		panic("Range called on non-Range event")
   472  	}
   473  	var r Range
   474  	switch e.base.typ {
   475  	case tracev2.EvSTWBegin, tracev2.EvSTWEnd:
   476  		// N.B. ordering.advance smuggles in the STW reason as e.base.args[0]
   477  		// for tracev2.EvSTWEnd (it's already there for Begin).
   478  		r.Name = "stop-the-world (" + e.table.strings.mustGet(stringID(e.base.args[0])) + ")"
   479  		r.Scope = ResourceID{Kind: ResourceGoroutine, id: int64(e.Goroutine())}
   480  	case tracev2.EvGCBegin, tracev2.EvGCActive, tracev2.EvGCEnd:
   481  		r.Name = "GC concurrent mark phase"
   482  		r.Scope = ResourceID{Kind: ResourceNone}
   483  	case tracev2.EvGCSweepBegin, tracev2.EvGCSweepActive, tracev2.EvGCSweepEnd:
   484  		r.Name = "GC incremental sweep"
   485  		r.Scope = ResourceID{Kind: ResourceProc}
   486  		if e.base.typ == tracev2.EvGCSweepActive {
   487  			r.Scope.id = int64(e.base.args[0])
   488  		} else {
   489  			r.Scope.id = int64(e.Proc())
   490  		}
   491  		r.Scope.id = int64(e.Proc())
   492  	case tracev2.EvGCMarkAssistBegin, tracev2.EvGCMarkAssistActive, tracev2.EvGCMarkAssistEnd:
   493  		r.Name = "GC mark assist"
   494  		r.Scope = ResourceID{Kind: ResourceGoroutine}
   495  		if e.base.typ == tracev2.EvGCMarkAssistActive {
   496  			r.Scope.id = int64(e.base.args[0])
   497  		} else {
   498  			r.Scope.id = int64(e.Goroutine())
   499  		}
   500  	default:
   501  		panic(fmt.Sprintf("internal error: unexpected wire-event type for Range kind: %d", e.base.typ))
   502  	}
   503  	return r
   504  }
   505  
   506  // RangeAttributes returns attributes for a completed range.
   507  //
   508  // Panics if Kind != EventRangeEnd.
   509  func (e Event) RangeAttributes() []RangeAttribute {
   510  	if e.Kind() != EventRangeEnd {
   511  		panic("Range called on non-Range event")
   512  	}
   513  	if e.base.typ != tracev2.EvGCSweepEnd {
   514  		return nil
   515  	}
   516  	return []RangeAttribute{
   517  		{
   518  			Name:  "bytes swept",
   519  			Value: uint64Value(e.base.args[0]),
   520  		},
   521  		{
   522  			Name:  "bytes reclaimed",
   523  			Value: uint64Value(e.base.args[1]),
   524  		},
   525  	}
   526  }
   527  
   528  // Task returns details about a TaskBegin or TaskEnd event.
   529  //
   530  // Panics if Kind != EventTaskBegin and Kind != EventTaskEnd.
   531  func (e Event) Task() Task {
   532  	if kind := e.Kind(); kind != EventTaskBegin && kind != EventTaskEnd {
   533  		panic("Task called on non-Task event")
   534  	}
   535  	parentID := NoTask
   536  	var typ string
   537  	switch e.base.typ {
   538  	case tracev2.EvUserTaskBegin:
   539  		parentID = TaskID(e.base.args[1])
   540  		typ = e.table.strings.mustGet(stringID(e.base.args[2]))
   541  	case tracev2.EvUserTaskEnd:
   542  		parentID = TaskID(e.base.extra(version.Go122)[0])
   543  		typ = e.table.getExtraString(extraStringID(e.base.extra(version.Go122)[1]))
   544  	default:
   545  		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Task kind: %d", e.base.typ))
   546  	}
   547  	return Task{
   548  		ID:     TaskID(e.base.args[0]),
   549  		Parent: parentID,
   550  		Type:   typ,
   551  	}
   552  }
   553  
   554  // Region returns details about a RegionBegin or RegionEnd event.
   555  //
   556  // Panics if Kind != EventRegionBegin and Kind != EventRegionEnd.
   557  func (e Event) Region() Region {
   558  	if kind := e.Kind(); kind != EventRegionBegin && kind != EventRegionEnd {
   559  		panic("Region called on non-Region event")
   560  	}
   561  	if e.base.typ != tracev2.EvUserRegionBegin && e.base.typ != tracev2.EvUserRegionEnd {
   562  		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Region kind: %d", e.base.typ))
   563  	}
   564  	return Region{
   565  		Task: TaskID(e.base.args[0]),
   566  		Type: e.table.strings.mustGet(stringID(e.base.args[1])),
   567  	}
   568  }
   569  
   570  // Log returns details about a Log event.
   571  //
   572  // Panics if Kind != EventLog.
   573  func (e Event) Log() Log {
   574  	if e.Kind() != EventLog {
   575  		panic("Log called on non-Log event")
   576  	}
   577  	if e.base.typ != tracev2.EvUserLog {
   578  		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Log kind: %d", e.base.typ))
   579  	}
   580  	return Log{
   581  		Task:     TaskID(e.base.args[0]),
   582  		Category: e.table.strings.mustGet(stringID(e.base.args[1])),
   583  		Message:  e.table.strings.mustGet(stringID(e.base.args[2])),
   584  	}
   585  }
   586  
   587  // StateTransition returns details about a StateTransition event.
   588  //
   589  // Panics if Kind != EventStateTransition.
   590  func (e Event) StateTransition() StateTransition {
   591  	if e.Kind() != EventStateTransition {
   592  		panic("StateTransition called on non-StateTransition event")
   593  	}
   594  	var s StateTransition
   595  	switch e.base.typ {
   596  	case tracev2.EvProcStart:
   597  		s = procStateTransition(ProcID(e.base.args[0]), ProcIdle, ProcRunning)
   598  	case tracev2.EvProcStop:
   599  		s = procStateTransition(e.ctx.P, ProcRunning, ProcIdle)
   600  	case tracev2.EvProcSteal:
   601  		// N.B. ordering.advance populates e.base.extra.
   602  		beforeState := ProcRunning
   603  		if tracev2.ProcStatus(e.base.extra(version.Go122)[0]) == tracev2.ProcSyscallAbandoned {
   604  			// We've lost information because this ProcSteal advanced on a
   605  			// SyscallAbandoned state. Treat the P as idle because ProcStatus
   606  			// treats SyscallAbandoned as Idle. Otherwise we'll have an invalid
   607  			// transition.
   608  			beforeState = ProcIdle
   609  		}
   610  		s = procStateTransition(ProcID(e.base.args[0]), beforeState, ProcIdle)
   611  	case tracev2.EvProcStatus:
   612  		// N.B. ordering.advance populates e.base.extra.
   613  		s = procStateTransition(ProcID(e.base.args[0]), ProcState(e.base.extra(version.Go122)[0]), tracev2ProcStatus2ProcState[e.base.args[1]])
   614  	case tracev2.EvGoCreate, tracev2.EvGoCreateBlocked:
   615  		status := GoRunnable
   616  		if e.base.typ == tracev2.EvGoCreateBlocked {
   617  			status = GoWaiting
   618  		}
   619  		s = goStateTransition(GoID(e.base.args[0]), GoNotExist, status)
   620  		s.Stack = Stack{table: e.table, id: stackID(e.base.args[1])}
   621  	case tracev2.EvGoCreateSyscall:
   622  		s = goStateTransition(GoID(e.base.args[0]), GoNotExist, GoSyscall)
   623  	case tracev2.EvGoStart:
   624  		s = goStateTransition(GoID(e.base.args[0]), GoRunnable, GoRunning)
   625  	case tracev2.EvGoDestroy:
   626  		s = goStateTransition(e.ctx.G, GoRunning, GoNotExist)
   627  		s.Stack = e.Stack() // This event references the resource the event happened on.
   628  	case tracev2.EvGoDestroySyscall:
   629  		s = goStateTransition(e.ctx.G, GoSyscall, GoNotExist)
   630  	case tracev2.EvGoStop:
   631  		s = goStateTransition(e.ctx.G, GoRunning, GoRunnable)
   632  		s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
   633  		s.Stack = e.Stack() // This event references the resource the event happened on.
   634  	case tracev2.EvGoBlock:
   635  		s = goStateTransition(e.ctx.G, GoRunning, GoWaiting)
   636  		s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
   637  		s.Stack = e.Stack() // This event references the resource the event happened on.
   638  	case tracev2.EvGoUnblock, tracev2.EvGoSwitch, tracev2.EvGoSwitchDestroy:
   639  		// N.B. GoSwitch and GoSwitchDestroy both emit additional events, but
   640  		// the first thing they both do is unblock the goroutine they name,
   641  		// identically to an unblock event (even their arguments match).
   642  		s = goStateTransition(GoID(e.base.args[0]), GoWaiting, GoRunnable)
   643  	case tracev2.EvGoSyscallBegin:
   644  		s = goStateTransition(e.ctx.G, GoRunning, GoSyscall)
   645  		s.Stack = e.Stack() // This event references the resource the event happened on.
   646  	case tracev2.EvGoSyscallEnd:
   647  		s = goStateTransition(e.ctx.G, GoSyscall, GoRunning)
   648  		s.Stack = e.Stack() // This event references the resource the event happened on.
   649  	case tracev2.EvGoSyscallEndBlocked:
   650  		s = goStateTransition(e.ctx.G, GoSyscall, GoRunnable)
   651  		s.Stack = e.Stack() // This event references the resource the event happened on.
   652  	case tracev2.EvGoStatus, tracev2.EvGoStatusStack:
   653  		packedStatus := e.base.args[2]
   654  		from, to := packedStatus>>32, packedStatus&((1<<32)-1)
   655  		s = goStateTransition(GoID(e.base.args[0]), GoState(from), tracev2GoStatus2GoState[to])
   656  	default:
   657  		panic(fmt.Sprintf("internal error: unexpected wire-format event type for StateTransition kind: %d", e.base.typ))
   658  	}
   659  	return s
   660  }
   661  
   662  // Sync returns details that are relevant for the following events, up to but excluding the
   663  // next EventSync event.
   664  func (e Event) Sync() Sync {
   665  	if e.Kind() != EventSync {
   666  		panic("Sync called on non-Sync event")
   667  	}
   668  	var expBatches map[string][]ExperimentalBatch
   669  	if e.table != nil {
   670  		expBatches = make(map[string][]ExperimentalBatch)
   671  		for exp, batches := range e.table.expBatches {
   672  			expBatches[tracev2.Experiments()[exp]] = batches
   673  		}
   674  	}
   675  	return Sync{
   676  		N:                   int(e.base.args[0]),
   677  		ExperimentalBatches: expBatches,
   678  	}
   679  }
   680  
   681  // Sync contains details potentially relevant to all the following events, up to but excluding
   682  // the next EventSync event.
   683  type Sync struct {
   684  	// N indicates that this is the Nth sync event in the trace.
   685  	N int
   686  
   687  	// ExperimentalBatches contain all the unparsed batches of data for a given experiment.
   688  	ExperimentalBatches map[string][]ExperimentalBatch
   689  }
   690  
   691  // Experimental returns a view of the raw event for an experimental event.
   692  //
   693  // Panics if Kind != EventExperimental.
   694  func (e Event) Experimental() ExperimentalEvent {
   695  	if e.Kind() != EventExperimental {
   696  		panic("Experimental called on non-Experimental event")
   697  	}
   698  	spec := tracev2.Specs()[e.base.typ]
   699  	argNames := spec.Args[1:] // Skip timestamp; already handled.
   700  	return ExperimentalEvent{
   701  		Name:       spec.Name,
   702  		Experiment: tracev2.Experiments()[spec.Experiment],
   703  		Args:       argNames,
   704  		table:      e.table,
   705  		argValues:  e.base.args[:len(argNames)],
   706  	}
   707  }
   708  
   709  const evSync = ^tracev2.EventType(0)
   710  
   711  var tracev2Type2Kind = [...]EventKind{
   712  	tracev2.EvCPUSample:           EventStackSample,
   713  	tracev2.EvProcsChange:         EventMetric,
   714  	tracev2.EvProcStart:           EventStateTransition,
   715  	tracev2.EvProcStop:            EventStateTransition,
   716  	tracev2.EvProcSteal:           EventStateTransition,
   717  	tracev2.EvProcStatus:          EventStateTransition,
   718  	tracev2.EvGoCreate:            EventStateTransition,
   719  	tracev2.EvGoCreateSyscall:     EventStateTransition,
   720  	tracev2.EvGoStart:             EventStateTransition,
   721  	tracev2.EvGoDestroy:           EventStateTransition,
   722  	tracev2.EvGoDestroySyscall:    EventStateTransition,
   723  	tracev2.EvGoStop:              EventStateTransition,
   724  	tracev2.EvGoBlock:             EventStateTransition,
   725  	tracev2.EvGoUnblock:           EventStateTransition,
   726  	tracev2.EvGoSyscallBegin:      EventStateTransition,
   727  	tracev2.EvGoSyscallEnd:        EventStateTransition,
   728  	tracev2.EvGoSyscallEndBlocked: EventStateTransition,
   729  	tracev2.EvGoStatus:            EventStateTransition,
   730  	tracev2.EvSTWBegin:            EventRangeBegin,
   731  	tracev2.EvSTWEnd:              EventRangeEnd,
   732  	tracev2.EvGCActive:            EventRangeActive,
   733  	tracev2.EvGCBegin:             EventRangeBegin,
   734  	tracev2.EvGCEnd:               EventRangeEnd,
   735  	tracev2.EvGCSweepActive:       EventRangeActive,
   736  	tracev2.EvGCSweepBegin:        EventRangeBegin,
   737  	tracev2.EvGCSweepEnd:          EventRangeEnd,
   738  	tracev2.EvGCMarkAssistActive:  EventRangeActive,
   739  	tracev2.EvGCMarkAssistBegin:   EventRangeBegin,
   740  	tracev2.EvGCMarkAssistEnd:     EventRangeEnd,
   741  	tracev2.EvHeapAlloc:           EventMetric,
   742  	tracev2.EvHeapGoal:            EventMetric,
   743  	tracev2.EvGoLabel:             EventLabel,
   744  	tracev2.EvUserTaskBegin:       EventTaskBegin,
   745  	tracev2.EvUserTaskEnd:         EventTaskEnd,
   746  	tracev2.EvUserRegionBegin:     EventRegionBegin,
   747  	tracev2.EvUserRegionEnd:       EventRegionEnd,
   748  	tracev2.EvUserLog:             EventLog,
   749  	tracev2.EvGoSwitch:            EventStateTransition,
   750  	tracev2.EvGoSwitchDestroy:     EventStateTransition,
   751  	tracev2.EvGoCreateBlocked:     EventStateTransition,
   752  	tracev2.EvGoStatusStack:       EventStateTransition,
   753  	tracev2.EvSpan:                EventExperimental,
   754  	tracev2.EvSpanAlloc:           EventExperimental,
   755  	tracev2.EvSpanFree:            EventExperimental,
   756  	tracev2.EvHeapObject:          EventExperimental,
   757  	tracev2.EvHeapObjectAlloc:     EventExperimental,
   758  	tracev2.EvHeapObjectFree:      EventExperimental,
   759  	tracev2.EvGoroutineStack:      EventExperimental,
   760  	tracev2.EvGoroutineStackAlloc: EventExperimental,
   761  	tracev2.EvGoroutineStackFree:  EventExperimental,
   762  	evSync:                        EventSync,
   763  }
   764  
   765  var tracev2GoStatus2GoState = [...]GoState{
   766  	tracev2.GoRunnable: GoRunnable,
   767  	tracev2.GoRunning:  GoRunning,
   768  	tracev2.GoWaiting:  GoWaiting,
   769  	tracev2.GoSyscall:  GoSyscall,
   770  }
   771  
   772  var tracev2ProcStatus2ProcState = [...]ProcState{
   773  	tracev2.ProcRunning:          ProcRunning,
   774  	tracev2.ProcIdle:             ProcIdle,
   775  	tracev2.ProcSyscall:          ProcRunning,
   776  	tracev2.ProcSyscallAbandoned: ProcIdle,
   777  }
   778  
   779  // String returns the event as a human-readable string.
   780  //
   781  // The format of the string is intended for debugging and is subject to change.
   782  func (e Event) String() string {
   783  	var sb strings.Builder
   784  	fmt.Fprintf(&sb, "M=%d P=%d G=%d", e.Thread(), e.Proc(), e.Goroutine())
   785  	fmt.Fprintf(&sb, " %s Time=%d", e.Kind(), e.Time())
   786  	// Kind-specific fields.
   787  	switch kind := e.Kind(); kind {
   788  	case EventMetric:
   789  		m := e.Metric()
   790  		fmt.Fprintf(&sb, " Name=%q Value=%s", m.Name, m.Value)
   791  	case EventLabel:
   792  		l := e.Label()
   793  		fmt.Fprintf(&sb, " Label=%q Resource=%s", l.Label, l.Resource)
   794  	case EventRangeBegin, EventRangeActive, EventRangeEnd:
   795  		r := e.Range()
   796  		fmt.Fprintf(&sb, " Name=%q Scope=%s", r.Name, r.Scope)
   797  		if kind == EventRangeEnd {
   798  			fmt.Fprintf(&sb, " Attributes=[")
   799  			for i, attr := range e.RangeAttributes() {
   800  				if i != 0 {
   801  					fmt.Fprintf(&sb, " ")
   802  				}
   803  				fmt.Fprintf(&sb, "%q=%s", attr.Name, attr.Value)
   804  			}
   805  			fmt.Fprintf(&sb, "]")
   806  		}
   807  	case EventTaskBegin, EventTaskEnd:
   808  		t := e.Task()
   809  		fmt.Fprintf(&sb, " ID=%d Parent=%d Type=%q", t.ID, t.Parent, t.Type)
   810  	case EventRegionBegin, EventRegionEnd:
   811  		r := e.Region()
   812  		fmt.Fprintf(&sb, " Task=%d Type=%q", r.Task, r.Type)
   813  	case EventLog:
   814  		l := e.Log()
   815  		fmt.Fprintf(&sb, " Task=%d Category=%q Message=%q", l.Task, l.Category, l.Message)
   816  	case EventStateTransition:
   817  		s := e.StateTransition()
   818  		fmt.Fprintf(&sb, " Resource=%s Reason=%q", s.Resource, s.Reason)
   819  		switch s.Resource.Kind {
   820  		case ResourceGoroutine:
   821  			id := s.Resource.Goroutine()
   822  			old, new := s.Goroutine()
   823  			fmt.Fprintf(&sb, " GoID=%d %s->%s", id, old, new)
   824  		case ResourceProc:
   825  			id := s.Resource.Proc()
   826  			old, new := s.Proc()
   827  			fmt.Fprintf(&sb, " ProcID=%d %s->%s", id, old, new)
   828  		}
   829  		if s.Stack != NoStack {
   830  			fmt.Fprintln(&sb)
   831  			fmt.Fprintln(&sb, "TransitionStack=")
   832  			for f := range s.Stack.Frames() {
   833  				fmt.Fprintf(&sb, "\t%s @ 0x%x\n", f.Func, f.PC)
   834  				fmt.Fprintf(&sb, "\t\t%s:%d\n", f.File, f.Line)
   835  			}
   836  		}
   837  	case EventExperimental:
   838  		r := e.Experimental()
   839  		fmt.Fprintf(&sb, " Name=%s Args=[", r.Name)
   840  		for i, arg := range r.Args {
   841  			if i != 0 {
   842  				fmt.Fprintf(&sb, ", ")
   843  			}
   844  			fmt.Fprintf(&sb, "%s=%s", arg, r.ArgValue(i).String())
   845  		}
   846  		fmt.Fprintf(&sb, "]")
   847  	}
   848  	if stk := e.Stack(); stk != NoStack {
   849  		fmt.Fprintln(&sb)
   850  		fmt.Fprintln(&sb, "Stack=")
   851  		for f := range stk.Frames() {
   852  			fmt.Fprintf(&sb, "\t%s @ 0x%x\n", f.Func, f.PC)
   853  			fmt.Fprintf(&sb, "\t\t%s:%d\n", f.File, f.Line)
   854  		}
   855  	}
   856  	return sb.String()
   857  }
   858  
   859  // validateTableIDs checks to make sure lookups in e.table
   860  // will work.
   861  func (e Event) validateTableIDs() error {
   862  	if e.base.typ == evSync {
   863  		return nil
   864  	}
   865  	spec := tracev2.Specs()[e.base.typ]
   866  
   867  	// Check stacks.
   868  	for _, i := range spec.StackIDs {
   869  		id := stackID(e.base.args[i-1])
   870  		_, ok := e.table.stacks.get(id)
   871  		if !ok {
   872  			return fmt.Errorf("found invalid stack ID %d for event %s", id, spec.Name)
   873  		}
   874  	}
   875  	// N.B. Strings referenced by stack frames are validated
   876  	// early on, when reading the stacks in to begin with.
   877  
   878  	// Check strings.
   879  	for _, i := range spec.StringIDs {
   880  		id := stringID(e.base.args[i-1])
   881  		_, ok := e.table.strings.get(id)
   882  		if !ok {
   883  			return fmt.Errorf("found invalid string ID %d for event %s", id, spec.Name)
   884  		}
   885  	}
   886  	return nil
   887  }
   888  
   889  func syncEvent(table *evTable, ts Time, n int) Event {
   890  	ev := Event{
   891  		table: table,
   892  		ctx: schedCtx{
   893  			G: NoGoroutine,
   894  			P: NoProc,
   895  			M: NoThread,
   896  		},
   897  		base: baseEvent{
   898  			typ:  evSync,
   899  			time: ts,
   900  		},
   901  	}
   902  	ev.base.args[0] = uint64(n)
   903  	return ev
   904  }
   905  

View as plain text