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 string         // Version of Go that produced this binary.
    43  	Path      string         // The main package path
    44  	Main      Module         // The module containing the main package
    45  	Deps      []*Module      // Module dependencies
    46  	Settings  []BuildSetting // Other information about the build.
    47  }
    48  
    49  // Module represents a module.
    50  type Module struct {
    51  	Path    string  // module path
    52  	Version string  // module version
    53  	Sum     string  // checksum
    54  	Replace *Module // replaced by this module
    55  }
    56  
    57  // BuildSetting describes a setting that may be used to understand how the
    58  // binary was built. For example, VCS commit and dirty status is stored here.
    59  type BuildSetting struct {
    60  	// Key and Value describe the build setting.
    61  	// Key must not contain an equals sign, space, tab, or newline.
    62  	// Value must not contain newlines ('\n').
    63  	Key, Value string
    64  }
    65  
    66  // quoteKey reports whether key is required to be quoted.
    67  func quoteKey(key string) bool {
    68  	return len(key) == 0 || strings.ContainsAny(key, "= \t\r\n\"`")
    69  }
    70  
    71  // quoteValue reports whether value is required to be quoted.
    72  func quoteValue(value string) bool {
    73  	return strings.ContainsAny(value, " \t\r\n\"`")
    74  }
    75  
    76  func (bi *BuildInfo) String() string {
    77  	buf := new(strings.Builder)
    78  	if bi.GoVersion != "" {
    79  		fmt.Fprintf(buf, "go\t%s\n", bi.GoVersion)
    80  	}
    81  	if bi.Path != "" {
    82  		fmt.Fprintf(buf, "path\t%s\n", bi.Path)
    83  	}
    84  	var formatMod func(string, Module)
    85  	formatMod = func(word string, m Module) {
    86  		buf.WriteString(word)
    87  		buf.WriteByte('\t')
    88  		buf.WriteString(m.Path)
    89  		buf.WriteByte('\t')
    90  		buf.WriteString(m.Version)
    91  		if m.Replace == nil {
    92  			buf.WriteByte('\t')
    93  			buf.WriteString(m.Sum)
    94  		} else {
    95  			buf.WriteByte('\n')
    96  			formatMod("=>", *m.Replace)
    97  		}
    98  		buf.WriteByte('\n')
    99  	}
   100  	if bi.Main != (Module{}) {
   101  		formatMod("mod", bi.Main)
   102  	}
   103  	for _, dep := range bi.Deps {
   104  		formatMod("dep", *dep)
   105  	}
   106  	for _, s := range bi.Settings {
   107  		key := s.Key
   108  		if quoteKey(key) {
   109  			key = strconv.Quote(key)
   110  		}
   111  		value := s.Value
   112  		if quoteValue(value) {
   113  			value = strconv.Quote(value)
   114  		}
   115  		fmt.Fprintf(buf, "build\t%s=%s\n", key, value)
   116  	}
   117  
   118  	return buf.String()
   119  }
   120  
   121  func ParseBuildInfo(data string) (bi *BuildInfo, err error) {
   122  	lineNum := 1
   123  	defer func() {
   124  		if err != nil {
   125  			err = fmt.Errorf("could not parse Go build info: line %d: %w", lineNum, err)
   126  		}
   127  	}()
   128  
   129  	var (
   130  		pathLine  = "path\t"
   131  		modLine   = "mod\t"
   132  		depLine   = "dep\t"
   133  		repLine   = "=>\t"
   134  		buildLine = "build\t"
   135  		newline   = "\n"
   136  		tab       = "\t"
   137  	)
   138  
   139  	readModuleLine := func(elem []string) (Module, error) {
   140  		if len(elem) != 2 && len(elem) != 3 {
   141  			return Module{}, fmt.Errorf("expected 2 or 3 columns; got %d", len(elem))
   142  		}
   143  		version := elem[1]
   144  		sum := ""
   145  		if len(elem) == 3 {
   146  			sum = elem[2]
   147  		}
   148  		return Module{
   149  			Path:    elem[0],
   150  			Version: version,
   151  			Sum:     sum,
   152  		}, nil
   153  	}
   154  
   155  	bi = new(BuildInfo)
   156  	var (
   157  		last *Module
   158  		line string
   159  		ok   bool
   160  	)
   161  	// Reverse of BuildInfo.String(), except for go version.
   162  	for len(data) > 0 {
   163  		line, data, ok = strings.Cut(data, newline)
   164  		if !ok {
   165  			break
   166  		}
   167  		switch {
   168  		case strings.HasPrefix(line, pathLine):
   169  			elem := line[len(pathLine):]
   170  			bi.Path = string(elem)
   171  		case strings.HasPrefix(line, modLine):
   172  			elem := strings.Split(line[len(modLine):], tab)
   173  			last = &bi.Main
   174  			*last, err = readModuleLine(elem)
   175  			if err != nil {
   176  				return nil, err
   177  			}
   178  		case strings.HasPrefix(line, depLine):
   179  			elem := strings.Split(line[len(depLine):], tab)
   180  			last = new(Module)
   181  			bi.Deps = append(bi.Deps, last)
   182  			*last, err = readModuleLine(elem)
   183  			if err != nil {
   184  				return nil, err
   185  			}
   186  		case strings.HasPrefix(line, repLine):
   187  			elem := strings.Split(line[len(repLine):], tab)
   188  			if len(elem) != 3 {
   189  				return nil, fmt.Errorf("expected 3 columns for replacement; got %d", len(elem))
   190  			}
   191  			if last == nil {
   192  				return nil, fmt.Errorf("replacement with no module on previous line")
   193  			}
   194  			last.Replace = &Module{
   195  				Path:    string(elem[0]),
   196  				Version: string(elem[1]),
   197  				Sum:     string(elem[2]),
   198  			}
   199  			last = nil
   200  		case strings.HasPrefix(line, buildLine):
   201  			kv := line[len(buildLine):]
   202  			if len(kv) < 1 {
   203  				return nil, fmt.Errorf("build line missing '='")
   204  			}
   205  
   206  			var key, rawValue string
   207  			switch kv[0] {
   208  			case '=':
   209  				return nil, fmt.Errorf("build line with missing key")
   210  
   211  			case '`', '"':
   212  				rawKey, err := strconv.QuotedPrefix(kv)
   213  				if err != nil {
   214  					return nil, fmt.Errorf("invalid quoted key in build line")
   215  				}
   216  				if len(kv) == len(rawKey) {
   217  					return nil, fmt.Errorf("build line missing '=' after quoted key")
   218  				}
   219  				if c := kv[len(rawKey)]; c != '=' {
   220  					return nil, fmt.Errorf("unexpected character after quoted key: %q", c)
   221  				}
   222  				key, _ = strconv.Unquote(rawKey)
   223  				rawValue = kv[len(rawKey)+1:]
   224  
   225  			default:
   226  				var ok bool
   227  				key, rawValue, ok = strings.Cut(kv, "=")
   228  				if !ok {
   229  					return nil, fmt.Errorf("build line missing '=' after key")
   230  				}
   231  				if quoteKey(key) {
   232  					return nil, fmt.Errorf("unquoted key %q must be quoted", key)
   233  				}
   234  			}
   235  
   236  			var value string
   237  			if len(rawValue) > 0 {
   238  				switch rawValue[0] {
   239  				case '`', '"':
   240  					var err error
   241  					value, err = strconv.Unquote(rawValue)
   242  					if err != nil {
   243  						return nil, fmt.Errorf("invalid quoted value in build line")
   244  					}
   245  
   246  				default:
   247  					value = rawValue
   248  					if quoteValue(value) {
   249  						return nil, fmt.Errorf("unquoted value %q must be quoted", value)
   250  					}
   251  				}
   252  			}
   253  
   254  			bi.Settings = append(bi.Settings, BuildSetting{Key: key, Value: value})
   255  		}
   256  		lineNum++
   257  	}
   258  	return bi, nil
   259  }
   260  

View as plain text