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

View as plain text