Source file src/runtime/debug/mod.go

     1  // Copyright 2018 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 debug
     6  
     7  import (
     8  	"fmt"
     9  	"runtime"
    10  	"strconv"
    11  	"strings"
    12  )
    13  
    14  // exported from runtime.
    15  func modinfo() string
    16  
    17  // ReadBuildInfo returns the build information embedded
    18  // in the running binary. The information is available only
    19  // in binaries built with module support.
    20  func ReadBuildInfo() (info *BuildInfo, ok bool) {
    21  	data := modinfo()
    22  	if len(data) < 32 {
    23  		return nil, false
    24  	}
    25  	data = data[16 : len(data)-16]
    26  	bi, err := ParseBuildInfo(data)
    27  	if err != nil {
    28  		return nil, false
    29  	}
    30  
    31  	// The go version is stored separately from other build info, mostly for
    32  	// historical reasons. It is not part of the modinfo() string, and
    33  	// ParseBuildInfo does not recognize it. We inject it here to hide this
    34  	// awkwardness from the user.
    35  	bi.GoVersion = runtime.Version()
    36  
    37  	return bi, true
    38  }
    39  
    40  // BuildInfo represents the build information read from a Go binary.
    41  type BuildInfo struct {
    42  	// GoVersion is the version of the Go toolchain that built the binary
    43  	// (for example, "go1.19.2").
    44  	GoVersion string `json:",omitempty"`
    45  
    46  	// Path is the package path of the main package for the binary
    47  	// (for example, "golang.org/x/tools/cmd/stringer").
    48  	Path string `json:",omitempty"`
    49  
    50  	// Main describes the module that contains the main package for the binary.
    51  	Main Module `json:""`
    52  
    53  	// Deps describes all the dependency modules, both direct and indirect,
    54  	// that contributed packages to the build of this binary.
    55  	Deps []*Module `json:",omitempty"`
    56  
    57  	// Settings describes the build settings used to build the binary.
    58  	Settings []BuildSetting `json:",omitempty"`
    59  }
    60  
    61  // A Module describes a single module included in a build.
    62  type Module struct {
    63  	Path    string  `json:",omitempty"` // module path
    64  	Version string  `json:",omitempty"` // module version
    65  	Sum     string  `json:",omitempty"` // checksum
    66  	Replace *Module `json:",omitempty"` // replaced by this module
    67  }
    68  
    69  // A BuildSetting is a key-value pair describing one setting that influenced a build.
    70  //
    71  // Defined keys include:
    72  //
    73  //   - -buildmode: the buildmode flag used (typically "exe")
    74  //   - -compiler: the compiler toolchain flag used (typically "gc")
    75  //   - CGO_ENABLED: the effective CGO_ENABLED environment variable
    76  //   - CGO_CFLAGS: the effective CGO_CFLAGS environment variable
    77  //   - CGO_CPPFLAGS: the effective CGO_CPPFLAGS environment variable
    78  //   - CGO_CXXFLAGS:  the effective CGO_CXXFLAGS environment variable
    79  //   - CGO_LDFLAGS: the effective CGO_LDFLAGS environment variable
    80  //   - DefaultGODEBUG: the effective GODEBUG settings
    81  //   - GOARCH: the architecture target
    82  //   - GOAMD64/GOARM/GO386/etc: the architecture feature level for GOARCH
    83  //   - GOOS: the operating system target
    84  //   - GOFIPS140: the frozen FIPS 140-3 module version, if any
    85  //   - vcs: the version control system for the source tree where the build ran
    86  //   - vcs.revision: the revision identifier for the current commit or checkout
    87  //   - vcs.time: the modification time associated with vcs.revision, in RFC3339 format
    88  //   - vcs.modified: true or false indicating whether the source tree had local modifications
    89  type BuildSetting struct {
    90  	// Key and Value describe the build setting.
    91  	// Key must not contain an equals sign, space, tab, or newline.
    92  	Key string `json:",omitempty"`
    93  	// Value must not contain newlines ('\n').
    94  	Value string `json:",omitempty"`
    95  }
    96  
    97  // quoteKey reports whether key is required to be quoted.
    98  func quoteKey(key string) bool {
    99  	return len(key) == 0 || strings.ContainsAny(key, "= \t\r\n\"`")
   100  }
   101  
   102  // quoteValue reports whether value is required to be quoted.
   103  func quoteValue(value string) bool {
   104  	return strings.ContainsAny(value, " \t\r\n\"`")
   105  }
   106  
   107  // String returns a string representation of a [BuildInfo].
   108  func (bi *BuildInfo) String() string {
   109  	buf := new(strings.Builder)
   110  	if bi.GoVersion != "" {
   111  		fmt.Fprintf(buf, "go\t%s\n", bi.GoVersion)
   112  	}
   113  	if bi.Path != "" {
   114  		fmt.Fprintf(buf, "path\t%s\n", bi.Path)
   115  	}
   116  	var formatMod func(string, Module)
   117  	formatMod = func(word string, m Module) {
   118  		buf.WriteString(word)
   119  		buf.WriteByte('\t')
   120  		buf.WriteString(m.Path)
   121  		buf.WriteByte('\t')
   122  		buf.WriteString(m.Version)
   123  		if m.Replace == nil {
   124  			buf.WriteByte('\t')
   125  			buf.WriteString(m.Sum)
   126  		} else {
   127  			buf.WriteByte('\n')
   128  			formatMod("=>", *m.Replace)
   129  		}
   130  		buf.WriteByte('\n')
   131  	}
   132  	if bi.Main != (Module{}) {
   133  		formatMod("mod", bi.Main)
   134  	}
   135  	for _, dep := range bi.Deps {
   136  		formatMod("dep", *dep)
   137  	}
   138  	for _, s := range bi.Settings {
   139  		key := s.Key
   140  		if quoteKey(key) {
   141  			key = strconv.Quote(key)
   142  		}
   143  		value := s.Value
   144  		if quoteValue(value) {
   145  			value = strconv.Quote(value)
   146  		}
   147  		fmt.Fprintf(buf, "build\t%s=%s\n", key, value)
   148  	}
   149  
   150  	return buf.String()
   151  }
   152  
   153  // ParseBuildInfo parses the string returned by [*BuildInfo.String],
   154  // restoring the original BuildInfo,
   155  // except that the GoVersion field is not set.
   156  // Programs should normally not call this function,
   157  // but instead call [ReadBuildInfo], [debug/buildinfo.ReadFile],
   158  // or [debug/buildinfo.Read].
   159  func ParseBuildInfo(data string) (bi *BuildInfo, err error) {
   160  	lineNum := 1
   161  	defer func() {
   162  		if err != nil {
   163  			err = fmt.Errorf("could not parse Go build info: line %d: %w", lineNum, err)
   164  		}
   165  	}()
   166  
   167  	const (
   168  		pathLine  = "path\t"
   169  		modLine   = "mod\t"
   170  		depLine   = "dep\t"
   171  		repLine   = "=>\t"
   172  		buildLine = "build\t"
   173  		newline   = "\n"
   174  		tab       = "\t"
   175  	)
   176  
   177  	readModuleLine := func(elem []string) (Module, error) {
   178  		if len(elem) != 2 && len(elem) != 3 {
   179  			return Module{}, fmt.Errorf("expected 2 or 3 columns; got %d", len(elem))
   180  		}
   181  		version := elem[1]
   182  		sum := ""
   183  		if len(elem) == 3 {
   184  			sum = elem[2]
   185  		}
   186  		return Module{
   187  			Path:    elem[0],
   188  			Version: version,
   189  			Sum:     sum,
   190  		}, nil
   191  	}
   192  
   193  	bi = new(BuildInfo)
   194  	var (
   195  		last *Module
   196  		line string
   197  		ok   bool
   198  	)
   199  	// Reverse of BuildInfo.String(), except for go version.
   200  	for len(data) > 0 {
   201  		line, data, ok = strings.Cut(data, newline)
   202  		if !ok {
   203  			break
   204  		}
   205  		switch {
   206  		case strings.HasPrefix(line, pathLine):
   207  			elem := line[len(pathLine):]
   208  			bi.Path = elem
   209  		case strings.HasPrefix(line, modLine):
   210  			elem := strings.Split(line[len(modLine):], tab)
   211  			last = &bi.Main
   212  			*last, err = readModuleLine(elem)
   213  			if err != nil {
   214  				return nil, err
   215  			}
   216  		case strings.HasPrefix(line, depLine):
   217  			elem := strings.Split(line[len(depLine):], tab)
   218  			last = new(Module)
   219  			bi.Deps = append(bi.Deps, last)
   220  			*last, err = readModuleLine(elem)
   221  			if err != nil {
   222  				return nil, err
   223  			}
   224  		case strings.HasPrefix(line, repLine):
   225  			elem := strings.Split(line[len(repLine):], tab)
   226  			if len(elem) != 3 {
   227  				return nil, fmt.Errorf("expected 3 columns for replacement; got %d", len(elem))
   228  			}
   229  			if last == nil {
   230  				return nil, fmt.Errorf("replacement with no module on previous line")
   231  			}
   232  			last.Replace = &Module{
   233  				Path:    elem[0],
   234  				Version: elem[1],
   235  				Sum:     elem[2],
   236  			}
   237  			last = nil
   238  		case strings.HasPrefix(line, buildLine):
   239  			kv := line[len(buildLine):]
   240  			if len(kv) < 1 {
   241  				return nil, fmt.Errorf("build line missing '='")
   242  			}
   243  
   244  			var key, rawValue string
   245  			switch kv[0] {
   246  			case '=':
   247  				return nil, fmt.Errorf("build line with missing key")
   248  
   249  			case '`', '"':
   250  				rawKey, err := strconv.QuotedPrefix(kv)
   251  				if err != nil {
   252  					return nil, fmt.Errorf("invalid quoted key in build line")
   253  				}
   254  				if len(kv) == len(rawKey) {
   255  					return nil, fmt.Errorf("build line missing '=' after quoted key")
   256  				}
   257  				if c := kv[len(rawKey)]; c != '=' {
   258  					return nil, fmt.Errorf("unexpected character after quoted key: %q", c)
   259  				}
   260  				key, _ = strconv.Unquote(rawKey)
   261  				rawValue = kv[len(rawKey)+1:]
   262  
   263  			default:
   264  				var ok bool
   265  				key, rawValue, ok = strings.Cut(kv, "=")
   266  				if !ok {
   267  					return nil, fmt.Errorf("build line missing '=' after key")
   268  				}
   269  				if quoteKey(key) {
   270  					return nil, fmt.Errorf("unquoted key %q must be quoted", key)
   271  				}
   272  			}
   273  
   274  			var value string
   275  			if len(rawValue) > 0 {
   276  				switch rawValue[0] {
   277  				case '`', '"':
   278  					var err error
   279  					value, err = strconv.Unquote(rawValue)
   280  					if err != nil {
   281  						return nil, fmt.Errorf("invalid quoted value in build line")
   282  					}
   283  
   284  				default:
   285  					value = rawValue
   286  					if quoteValue(value) {
   287  						return nil, fmt.Errorf("unquoted value %q must be quoted", value)
   288  					}
   289  				}
   290  			}
   291  
   292  			bi.Settings = append(bi.Settings, BuildSetting{Key: key, Value: value})
   293  		}
   294  		lineNum++
   295  	}
   296  	return bi, nil
   297  }
   298  

View as plain text