github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/trace/v2/version/version.go (about)

     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  	"github.com/go-asm/go/trace/v2/event"
    12  	"github.com/go-asm/go/trace/v2/event/go122"
    13  )
    14  
    15  // Version represents the version of a trace file.
    16  type Version uint32
    17  
    18  const (
    19  	Go122   Version = 22
    20  	Current         = Go122
    21  )
    22  
    23  var versions = map[Version][]event.Spec{
    24  	Go122: go122.Specs(),
    25  }
    26  
    27  // Specs returns the set of event.Specs for this version.
    28  func (v Version) Specs() []event.Spec {
    29  	return versions[v]
    30  }
    31  
    32  func (v Version) Valid() bool {
    33  	_, ok := versions[v]
    34  	return ok
    35  }
    36  
    37  // headerFmt is the format of the header of all Go execution traces.
    38  const headerFmt = "go 1.%d trace\x00\x00\x00"
    39  
    40  // ReadHeader reads the version of the trace out of the trace file's
    41  // header, whose prefix must be present in v.
    42  func ReadHeader(r io.Reader) (Version, error) {
    43  	var v Version
    44  	_, err := fmt.Fscanf(r, headerFmt, &v)
    45  	if err != nil {
    46  		return v, fmt.Errorf("bad file format: not a Go execution trace?")
    47  	}
    48  	if !v.Valid() {
    49  		return v, fmt.Errorf("unknown or unsupported trace version go 1.%d", v)
    50  	}
    51  	return v, nil
    52  }
    53  
    54  // WriteHeader writes a header for a trace version v to w.
    55  func WriteHeader(w io.Writer, v Version) (int, error) {
    56  	return fmt.Fprintf(w, headerFmt, v)
    57  }