Source file src/internal/trace/version/version.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 version
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  
    11  	"internal/trace/tracev2"
    12  )
    13  
    14  // Version represents the version of a trace file.
    15  type Version uint32
    16  
    17  const (
    18  	Go111   Version = 11 // v1
    19  	Go119   Version = 19 // v1
    20  	Go121   Version = 21 // v1
    21  	Go122   Version = 22 // v2
    22  	Go123   Version = 23 // v2
    23  	Current         = Go123
    24  )
    25  
    26  var versions = map[Version][]tracev2.EventSpec{
    27  	// Go 1.11–1.21 use a different parser and are only set here for the sake of
    28  	// Version.Valid.
    29  	Go111: nil,
    30  	Go119: nil,
    31  	Go121: nil,
    32  
    33  	Go122: tracev2.Specs()[:tracev2.EvUserLog+1], // All events after are Go 1.23+.
    34  	Go123: tracev2.Specs(),
    35  }
    36  
    37  // Specs returns the set of event.Specs for this version.
    38  func (v Version) Specs() []tracev2.EventSpec {
    39  	return versions[v]
    40  }
    41  
    42  // EventName returns a string name of a wire format event
    43  // for a particular trace version.
    44  func (v Version) EventName(typ tracev2.EventType) string {
    45  	if !v.Valid() {
    46  		return "<invalid trace version>"
    47  	}
    48  	s := v.Specs()
    49  	if len(s) == 0 {
    50  		return "<v1 trace event type>"
    51  	}
    52  	if int(typ) < len(s) && s[typ].Name != "" {
    53  		return s[typ].Name
    54  	}
    55  	return fmt.Sprintf("Invalid(%d)", typ)
    56  }
    57  
    58  func (v Version) Valid() bool {
    59  	_, ok := versions[v]
    60  	return ok
    61  }
    62  
    63  // headerFmt is the format of the header of all Go execution traces.
    64  const headerFmt = "go 1.%d trace\x00\x00\x00"
    65  
    66  // ReadHeader reads the version of the trace out of the trace file's
    67  // header, whose prefix must be present in v.
    68  func ReadHeader(r io.Reader) (Version, error) {
    69  	var v Version
    70  	_, err := fmt.Fscanf(r, headerFmt, &v)
    71  	if err != nil {
    72  		return v, fmt.Errorf("bad file format: not a Go execution trace?")
    73  	}
    74  	if !v.Valid() {
    75  		return v, fmt.Errorf("unknown or unsupported trace version go 1.%d", v)
    76  	}
    77  	return v, nil
    78  }
    79  
    80  // WriteHeader writes a header for a trace version v to w.
    81  func WriteHeader(w io.Writer, v Version) (int, error) {
    82  	return fmt.Fprintf(w, headerFmt, v)
    83  }
    84  

View as plain text