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

View as plain text