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
    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
    49  
    50  	// Main describes the module that contains the main package for the binary.
    51  	Main Module
    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
    56  
    57  	// Settings describes the build settings used to build the binary.
    58  	Settings []BuildSetting
    59  }
    60  
    61  // A Module describes a single module included in a build.
    62  type Module struct {
    63  	Path    string  // module path
    64  	Version string  // module version
    65  	Sum     string  // checksum
    66  	Replace *Module // 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  	// Value must not contain newlines ('\n').
    93  	Key, Value string
    94  }
    95  
    96  // quoteKey reports whether key is required to be quoted.
    97  func quoteKey(key string) bool {
    98  	return len(key) == 0 || strings.ContainsAny(key, "= \t\r\n\"`")
    99  }
   100  
   101  // quoteValue reports whether value is required to be quoted.
   102  func quoteValue(value string) bool {
   103  	return strings.ContainsAny(value, " \t\r\n\"`")
   104  }
   105  
   106  // String returns a string representation of a [BuildInfo].
   107  func (bi *BuildInfo) String() string {
   108  	buf := new(strings.Builder)
   109  	if bi.GoVersion != "" {
   110  		fmt.Fprintf(buf, "go\t%s\n", bi.GoVersion)
   111  	}
   112  	if bi.Path != "" {
   113  		fmt.Fprintf(buf, "path\t%s\n", bi.Path)
   114  	}
   115  	var formatMod func(string, Module)
   116  	formatMod = func(word string, m Module) {
   117  		buf.WriteString(word)
   118  		buf.WriteByte('\t')
   119  		buf.WriteString(m.Path)
   120  		buf.WriteByte('\t')
   121  		buf.WriteString(m.Version)
   122  		if m.Replace == nil {
   123  			buf.WriteByte('\t')
   124  			buf.WriteString(m.Sum)
   125  		} else {
   126  			buf.WriteByte('\n')
   127  			formatMod("=>", *m.Replace)
   128  		}
   129  		buf.WriteByte('\n')
   130  	}
   131  	if bi.Main != (Module{}) {
   132  		formatMod("mod", bi.Main)
   133  	}
   134  	for _, dep := range bi.Deps {
   135  		formatMod("dep", *dep)
   136  	}
   137  	for _, s := range bi.Settings {
   138  		key := s.Key
   139  		if quoteKey(key) {
   140  			key = strconv.Quote(key)
   141  		}
   142  		value := s.Value
   143  		if quoteValue(value) {
   144  			value = strconv.Quote(value)
   145  		}
   146  		fmt.Fprintf(buf, "build\t%s=%s\n", key, value)
   147  	}
   148  
   149  	return buf.String()
   150  }
   151  
   152  // ParseBuildInfo parses the string returned by [*BuildInfo.String],
   153  // restoring the original BuildInfo,
   154  // except that the GoVersion field is not set.
   155  // Programs should normally not call this function,
   156  // but instead call [ReadBuildInfo], [debug/buildinfo.ReadFile],
   157  // or [debug/buildinfo.Read].
   158  func ParseBuildInfo(data string) (bi *BuildInfo, err error) {
   159  	lineNum := 1
   160  	defer func() {
   161  		if err != nil {
   162  			err = fmt.Errorf("could not parse Go build info: line %d: %w", lineNum, err)
   163  		}
   164  	}()
   165  
   166  	const (
   167  		pathLine  = "path\t"
   168  		modLine   = "mod\t"
   169  		depLine   = "dep\t"
   170  		repLine   = "=>\t"
   171  		buildLine = "build\t"
   172  		newline   = "\n"
   173  		tab       = "\t"
   174  	)
   175  
   176  	readModuleLine := func(elem []string) (Module, error) {
   177  		if len(elem) != 2 && len(elem) != 3 {
   178  			return Module{}, fmt.Errorf("expected 2 or 3 columns; got %d", len(elem))
   179  		}
   180  		version := elem[1]
   181  		sum := ""
   182  		if len(elem) == 3 {
   183  			sum = elem[2]
   184  		}
   185  		return Module{
   186  			Path:    elem[0],
   187  			Version: version,
   188  			Sum:     sum,
   189  		}, nil
   190  	}
   191  
   192  	bi = new(BuildInfo)
   193  	var (
   194  		last *Module
   195  		line string
   196  		ok   bool
   197  	)
   198  	// Reverse of BuildInfo.String(), except for go version.
   199  	for len(data) > 0 {
   200  		line, data, ok = strings.Cut(data, newline)
   201  		if !ok {
   202  			break
   203  		}
   204  		switch {
   205  		case strings.HasPrefix(line, pathLine):
   206  			elem := line[len(pathLine):]
   207  			bi.Path = elem
   208  		case strings.HasPrefix(line, modLine):
   209  			elem := strings.Split(line[len(modLine):], tab)
   210  			last = &bi.Main
   211  			*last, err = readModuleLine(elem)
   212  			if err != nil {
   213  				return nil, err
   214  			}
   215  		case strings.HasPrefix(line, depLine):
   216  			elem := strings.Split(line[len(depLine):], tab)
   217  			last = new(Module)
   218  			bi.Deps = append(bi.Deps, last)
   219  			*last, err = readModuleLine(elem)
   220  			if err != nil {
   221  				return nil, err
   222  			}
   223  		case strings.HasPrefix(line, repLine):
   224  			elem := strings.Split(line[len(repLine):], tab)
   225  			if len(elem) != 3 {
   226  				return nil, fmt.Errorf("expected 3 columns for replacement; got %d", len(elem))
   227  			}
   228  			if last == nil {
   229  				return nil, fmt.Errorf("replacement with no module on previous line")
   230  			}
   231  			last.Replace = &Module{
   232  				Path:    elem[0],
   233  				Version: elem[1],
   234  				Sum:     elem[2],
   235  			}
   236  			last = nil
   237  		case strings.HasPrefix(line, buildLine):
   238  			kv := line[len(buildLine):]
   239  			if len(kv) < 1 {
   240  				return nil, fmt.Errorf("build line missing '='")
   241  			}
   242  
   243  			var key, rawValue string
   244  			switch kv[0] {
   245  			case '=':
   246  				return nil, fmt.Errorf("build line with missing key")
   247  
   248  			case '`', '"':
   249  				rawKey, err := strconv.QuotedPrefix(kv)
   250  				if err != nil {
   251  					return nil, fmt.Errorf("invalid quoted key in build line")
   252  				}
   253  				if len(kv) == len(rawKey) {
   254  					return nil, fmt.Errorf("build line missing '=' after quoted key")
   255  				}
   256  				if c := kv[len(rawKey)]; c != '=' {
   257  					return nil, fmt.Errorf("unexpected character after quoted key: %q", c)
   258  				}
   259  				key, _ = strconv.Unquote(rawKey)
   260  				rawValue = kv[len(rawKey)+1:]
   261  
   262  			default:
   263  				var ok bool
   264  				key, rawValue, ok = strings.Cut(kv, "=")
   265  				if !ok {
   266  					return nil, fmt.Errorf("build line missing '=' after key")
   267  				}
   268  				if quoteKey(key) {
   269  					return nil, fmt.Errorf("unquoted key %q must be quoted", key)
   270  				}
   271  			}
   272  
   273  			var value string
   274  			if len(rawValue) > 0 {
   275  				switch rawValue[0] {
   276  				case '`', '"':
   277  					var err error
   278  					value, err = strconv.Unquote(rawValue)
   279  					if err != nil {
   280  						return nil, fmt.Errorf("invalid quoted value in build line")
   281  					}
   282  
   283  				default:
   284  					value = rawValue
   285  					if quoteValue(value) {
   286  						return nil, fmt.Errorf("unquoted value %q must be quoted", value)
   287  					}
   288  				}
   289  			}
   290  
   291  			bi.Settings = append(bi.Settings, BuildSetting{Key: key, Value: value})
   292  		}
   293  		lineNum++
   294  	}
   295  	return bi, nil
   296  }
   297  

View as plain text