Source file src/debug/buildinfo/buildinfo_test.go

     1  // Copyright 2021 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 buildinfo_test
     6  
     7  import (
     8  	"bytes"
     9  	"debug/buildinfo"
    10  	"debug/pe"
    11  	"encoding/binary"
    12  	"flag"
    13  	"fmt"
    14  	"internal/testenv"
    15  	"os"
    16  	"os/exec"
    17  	"path"
    18  	"path/filepath"
    19  	"regexp"
    20  	"runtime"
    21  	"strings"
    22  	"testing"
    23  )
    24  
    25  var flagAll = flag.Bool("all", false, "test all supported GOOS/GOARCH platforms, instead of only the current platform")
    26  
    27  // TestReadFile confirms that ReadFile can read build information from binaries
    28  // on supported target platforms. It builds a trivial binary on the current
    29  // platforms (or all platforms if -all is set) in various configurations and
    30  // checks that build information can or cannot be read.
    31  func TestReadFile(t *testing.T) {
    32  	if testing.Short() {
    33  		t.Skip("test requires compiling and linking, which may be slow")
    34  	}
    35  	testenv.MustHaveGoBuild(t)
    36  
    37  	type platform struct{ goos, goarch string }
    38  	platforms := []platform{
    39  		{"aix", "ppc64"},
    40  		{"darwin", "amd64"},
    41  		{"darwin", "arm64"},
    42  		{"linux", "386"},
    43  		{"linux", "amd64"},
    44  		{"windows", "386"},
    45  		{"windows", "amd64"},
    46  	}
    47  	runtimePlatform := platform{runtime.GOOS, runtime.GOARCH}
    48  	haveRuntimePlatform := false
    49  	for _, p := range platforms {
    50  		if p == runtimePlatform {
    51  			haveRuntimePlatform = true
    52  			break
    53  		}
    54  	}
    55  	if !haveRuntimePlatform {
    56  		platforms = append(platforms, runtimePlatform)
    57  	}
    58  
    59  	buildModes := []string{"pie", "exe"}
    60  	if testenv.HasCGO() {
    61  		buildModes = append(buildModes, "c-shared")
    62  	}
    63  
    64  	// Keep in sync with src/cmd/go/internal/work/init.go:buildModeInit.
    65  	badmode := func(goos, goarch, buildmode string) string {
    66  		return fmt.Sprintf("-buildmode=%s not supported on %s/%s", buildmode, goos, goarch)
    67  	}
    68  
    69  	buildWithModules := func(t *testing.T, goos, goarch, buildmode string) string {
    70  		dir := t.TempDir()
    71  		gomodPath := filepath.Join(dir, "go.mod")
    72  		gomodData := []byte("module example.com/m\ngo 1.18\n")
    73  		if err := os.WriteFile(gomodPath, gomodData, 0666); err != nil {
    74  			t.Fatal(err)
    75  		}
    76  		helloPath := filepath.Join(dir, "hello.go")
    77  		helloData := []byte("package main\nfunc main() {}\n")
    78  		if err := os.WriteFile(helloPath, helloData, 0666); err != nil {
    79  			t.Fatal(err)
    80  		}
    81  		outPath := filepath.Join(dir, path.Base(t.Name()))
    82  		cmd := exec.Command(testenv.GoToolPath(t), "build", "-o="+outPath, "-buildmode="+buildmode)
    83  		cmd.Dir = dir
    84  		cmd.Env = append(os.Environ(), "GO111MODULE=on", "GOOS="+goos, "GOARCH="+goarch)
    85  		stderr := &strings.Builder{}
    86  		cmd.Stderr = stderr
    87  		if err := cmd.Run(); err != nil {
    88  			if badmodeMsg := badmode(goos, goarch, buildmode); strings.Contains(stderr.String(), badmodeMsg) {
    89  				t.Skip(badmodeMsg)
    90  			}
    91  			t.Fatalf("failed building test file: %v\n%s", err, stderr.String())
    92  		}
    93  		return outPath
    94  	}
    95  
    96  	buildWithGOPATH := func(t *testing.T, goos, goarch, buildmode string) string {
    97  		gopathDir := t.TempDir()
    98  		pkgDir := filepath.Join(gopathDir, "src/example.com/m")
    99  		if err := os.MkdirAll(pkgDir, 0777); err != nil {
   100  			t.Fatal(err)
   101  		}
   102  		helloPath := filepath.Join(pkgDir, "hello.go")
   103  		helloData := []byte("package main\nfunc main() {}\n")
   104  		if err := os.WriteFile(helloPath, helloData, 0666); err != nil {
   105  			t.Fatal(err)
   106  		}
   107  		outPath := filepath.Join(gopathDir, path.Base(t.Name()))
   108  		cmd := exec.Command(testenv.GoToolPath(t), "build", "-o="+outPath, "-buildmode="+buildmode)
   109  		cmd.Dir = pkgDir
   110  		cmd.Env = append(os.Environ(), "GO111MODULE=off", "GOPATH="+gopathDir, "GOOS="+goos, "GOARCH="+goarch)
   111  		stderr := &strings.Builder{}
   112  		cmd.Stderr = stderr
   113  		if err := cmd.Run(); err != nil {
   114  			if badmodeMsg := badmode(goos, goarch, buildmode); strings.Contains(stderr.String(), badmodeMsg) {
   115  				t.Skip(badmodeMsg)
   116  			}
   117  			t.Fatalf("failed building test file: %v\n%s", err, stderr.String())
   118  		}
   119  		return outPath
   120  	}
   121  
   122  	damageBuildInfo := func(t *testing.T, name string) {
   123  		data, err := os.ReadFile(name)
   124  		if err != nil {
   125  			t.Fatal(err)
   126  		}
   127  		i := bytes.Index(data, []byte("\xff Go buildinf:"))
   128  		if i < 0 {
   129  			t.Fatal("Go buildinf not found")
   130  		}
   131  		data[i+2] = 'N'
   132  		if err := os.WriteFile(name, data, 0666); err != nil {
   133  			t.Fatal(err)
   134  		}
   135  	}
   136  
   137  	damageStringLen := func(t *testing.T, name string) {
   138  		data, err := os.ReadFile(name)
   139  		if err != nil {
   140  			t.Fatal(err)
   141  		}
   142  		i := bytes.Index(data, []byte("\xff Go buildinf:"))
   143  		if i < 0 {
   144  			t.Fatal("Go buildinf not found")
   145  		}
   146  		verLen := data[i+32:]
   147  		binary.PutUvarint(verLen, 16<<40) // 16TB ought to be enough for anyone.
   148  		if err := os.WriteFile(name, data, 0666); err != nil {
   149  			t.Fatal(err)
   150  		}
   151  	}
   152  
   153  	goVersionRe := regexp.MustCompile("(?m)^go\t.*\n")
   154  	buildRe := regexp.MustCompile("(?m)^build\t.*\n")
   155  	cleanOutputForComparison := func(got string) string {
   156  		// Remove or replace anything that might depend on the test's environment
   157  		// so we can check the output afterward with a string comparison.
   158  		// We'll remove all build lines except the compiler, just to make sure
   159  		// build lines are included.
   160  		got = goVersionRe.ReplaceAllString(got, "go\tGOVERSION\n")
   161  		got = buildRe.ReplaceAllStringFunc(got, func(match string) string {
   162  			if strings.HasPrefix(match, "build\t-compiler=") {
   163  				return match
   164  			}
   165  			return ""
   166  		})
   167  		return got
   168  	}
   169  
   170  	cases := []struct {
   171  		name    string
   172  		build   func(t *testing.T, goos, goarch, buildmode string) string
   173  		want    string
   174  		wantErr string
   175  	}{
   176  		{
   177  			name: "doesnotexist",
   178  			build: func(t *testing.T, goos, goarch, buildmode string) string {
   179  				return "doesnotexist.txt"
   180  			},
   181  			wantErr: "doesnotexist",
   182  		},
   183  		{
   184  			name: "empty",
   185  			build: func(t *testing.T, _, _, _ string) string {
   186  				dir := t.TempDir()
   187  				name := filepath.Join(dir, "empty")
   188  				if err := os.WriteFile(name, nil, 0666); err != nil {
   189  					t.Fatal(err)
   190  				}
   191  				return name
   192  			},
   193  			wantErr: "unrecognized file format",
   194  		},
   195  		{
   196  			name:  "valid_modules",
   197  			build: buildWithModules,
   198  			want: "go\tGOVERSION\n" +
   199  				"path\texample.com/m\n" +
   200  				"mod\texample.com/m\t(devel)\t\n" +
   201  				"build\t-compiler=gc\n",
   202  		},
   203  		{
   204  			name: "invalid_modules",
   205  			build: func(t *testing.T, goos, goarch, buildmode string) string {
   206  				name := buildWithModules(t, goos, goarch, buildmode)
   207  				damageBuildInfo(t, name)
   208  				return name
   209  			},
   210  			wantErr: "not a Go executable",
   211  		},
   212  		{
   213  			name: "invalid_str_len",
   214  			build: func(t *testing.T, goos, goarch, buildmode string) string {
   215  				name := buildWithModules(t, goos, goarch, buildmode)
   216  				damageStringLen(t, name)
   217  				return name
   218  			},
   219  			wantErr: "not a Go executable",
   220  		},
   221  		{
   222  			name:  "valid_gopath",
   223  			build: buildWithGOPATH,
   224  			want: "go\tGOVERSION\n" +
   225  				"path\texample.com/m\n" +
   226  				"build\t-compiler=gc\n",
   227  		},
   228  		{
   229  			name: "invalid_gopath",
   230  			build: func(t *testing.T, goos, goarch, buildmode string) string {
   231  				name := buildWithGOPATH(t, goos, goarch, buildmode)
   232  				damageBuildInfo(t, name)
   233  				return name
   234  			},
   235  			wantErr: "not a Go executable",
   236  		},
   237  	}
   238  
   239  	for _, p := range platforms {
   240  		p := p
   241  		t.Run(p.goos+"_"+p.goarch, func(t *testing.T) {
   242  			if p != runtimePlatform && !*flagAll {
   243  				t.Skipf("skipping platforms other than %s_%s because -all was not set", runtimePlatform.goos, runtimePlatform.goarch)
   244  			}
   245  			for _, mode := range buildModes {
   246  				mode := mode
   247  				t.Run(mode, func(t *testing.T) {
   248  					for _, tc := range cases {
   249  						tc := tc
   250  						t.Run(tc.name, func(t *testing.T) {
   251  							t.Parallel()
   252  							name := tc.build(t, p.goos, p.goarch, mode)
   253  							if info, err := buildinfo.ReadFile(name); err != nil {
   254  								if tc.wantErr == "" {
   255  									t.Fatalf("unexpected error: %v", err)
   256  								} else if errMsg := err.Error(); !strings.Contains(errMsg, tc.wantErr) {
   257  									t.Fatalf("got error %q; want error containing %q", errMsg, tc.wantErr)
   258  								}
   259  							} else {
   260  								if tc.wantErr != "" {
   261  									t.Fatalf("unexpected success; want error containing %q", tc.wantErr)
   262  								}
   263  								got := info.String()
   264  								if clean := cleanOutputForComparison(got); got != tc.want && clean != tc.want {
   265  									t.Fatalf("got:\n%s\nwant:\n%s", got, tc.want)
   266  								}
   267  							}
   268  						})
   269  					}
   270  				})
   271  			}
   272  		})
   273  	}
   274  }
   275  
   276  // Test117 verifies that parsing of the old, pre-1.18 format works.
   277  func Test117(t *testing.T) {
   278  	// go117 was generated for linux-amd64 with:
   279  	//
   280  	// main.go:
   281  	//
   282  	// package main
   283  	// func main() {}
   284  	//
   285  	// GOTOOLCHAIN=go1.17 go mod init example.com/go117
   286  	// GOTOOLCHAIN=go1.17 go build
   287  	//
   288  	// TODO(prattmic): Ideally this would be built on the fly to better
   289  	// cover all executable formats, but then we need a network connection
   290  	// to download an old Go toolchain.
   291  	info, err := buildinfo.ReadFile("testdata/go117")
   292  	if err != nil {
   293  		t.Fatalf("ReadFile got err %v, want nil", err)
   294  	}
   295  
   296  	if info.GoVersion != "go1.17" {
   297  		t.Errorf("GoVersion got %s want go1.17", info.GoVersion)
   298  	}
   299  	if info.Path != "example.com/go117" {
   300  		t.Errorf("Path got %s want example.com/go117", info.Path)
   301  	}
   302  	if info.Main.Path != "example.com/go117" {
   303  		t.Errorf("Main.Path got %s want example.com/go117", info.Main.Path)
   304  	}
   305  }
   306  
   307  // TestNotGo verifies that parsing of a non-Go binary returns the proper error.
   308  func TestNotGo(t *testing.T) {
   309  	// notgo was generated for linux-amd64 with:
   310  	//
   311  	// main.c:
   312  	//
   313  	// int main(void) { return 0; }
   314  	//
   315  	// cc -o notgo main.c
   316  	//
   317  	// TODO(prattmic): Ideally this would be built on the fly to better
   318  	// cover all executable formats, but then we need to encode the
   319  	// intricacies of calling each platform's C compiler.
   320  	_, err := buildinfo.ReadFile("testdata/notgo")
   321  	if err == nil {
   322  		t.Fatalf("ReadFile got nil err, want non-nil")
   323  	}
   324  
   325  	// The precise error text here isn't critical, but we want something
   326  	// like errNotGoExe rather than e.g., a file read error.
   327  	if !strings.Contains(err.Error(), "not a Go executable") {
   328  		t.Errorf("ReadFile got err %v want not a Go executable", err)
   329  	}
   330  }
   331  
   332  // FuzzIssue57002 is a regression test for golang.org/issue/57002.
   333  //
   334  // The cause of issue 57002 is when pointerSize is not being checked,
   335  // the read can panic with slice bounds out of range
   336  func FuzzIssue57002(f *testing.F) {
   337  	// input from issue
   338  	f.Add([]byte{0x4d, 0x5a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x50, 0x45, 0x0, 0x0, 0x0, 0x0, 0x5, 0x0, 0x20, 0x20, 0x20, 0x20, 0x0, 0x0, 0x0, 0x0, 0x20, 0x3f, 0x0, 0x20, 0x0, 0x0, 0x20, 0x20, 0x20, 0x20, 0x20, 0xff, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb, 0x20, 0x20, 0x20, 0xfc, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x9, 0x0, 0x0, 0x0, 0x20, 0x0, 0x0, 0x0, 0x20, 0x20, 0x20, 0x20, 0x20, 0xef, 0x20, 0xff, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf, 0x0, 0x2, 0x0, 0x20, 0x0, 0x0, 0x9, 0x0, 0x4, 0x0, 0x20, 0xf6, 0x0, 0xd3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x1, 0x0, 0x0, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xa, 0x20, 0xa, 0x20, 0x20, 0x20, 0xff, 0x20, 0x20, 0xff, 0x20, 0x47, 0x6f, 0x20, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x69, 0x6e, 0x66, 0x3a, 0xde, 0xb5, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x7f, 0x7f, 0x7f, 0x20, 0xf4, 0xb2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0xb, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x20, 0x0, 0x0, 0x0, 0x0, 0x5, 0x0, 0x20, 0x20, 0x20, 0x20, 0x0, 0x0, 0x0, 0x0, 0x20, 0x3f, 0x27, 0x20, 0x0, 0xd, 0x0, 0xa, 0x20, 0x20, 0x20, 0x20, 0x20, 0xff, 0x20, 0x20, 0xff, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0, 0x20, 0x20, 0x0, 0x0, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5c, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20})
   339  	f.Fuzz(func(t *testing.T, input []byte) {
   340  		buildinfo.Read(bytes.NewReader(input))
   341  	})
   342  }
   343  
   344  // TestIssue54968 is a regression test for golang.org/issue/54968.
   345  //
   346  // The cause of issue 54968 is when the first buildInfoMagic is invalid, it
   347  // enters an infinite loop.
   348  func TestIssue54968(t *testing.T) {
   349  	t.Parallel()
   350  
   351  	const (
   352  		paddingSize    = 200
   353  		buildInfoAlign = 16
   354  	)
   355  	buildInfoMagic := []byte("\xff Go buildinf:")
   356  
   357  	// Construct a valid PE header.
   358  	var buf bytes.Buffer
   359  
   360  	buf.Write([]byte{'M', 'Z'})
   361  	buf.Write(bytes.Repeat([]byte{0}, 0x3c-2))
   362  	// At location 0x3c, the stub has the file offset to the PE signature.
   363  	binary.Write(&buf, binary.LittleEndian, int32(0x3c+4))
   364  
   365  	buf.Write([]byte{'P', 'E', 0, 0})
   366  
   367  	binary.Write(&buf, binary.LittleEndian, pe.FileHeader{NumberOfSections: 1})
   368  
   369  	sh := pe.SectionHeader32{
   370  		Name:             [8]uint8{'t', 0},
   371  		SizeOfRawData:    uint32(paddingSize + len(buildInfoMagic)),
   372  		PointerToRawData: uint32(buf.Len()),
   373  	}
   374  	sh.PointerToRawData = uint32(buf.Len() + binary.Size(sh))
   375  
   376  	binary.Write(&buf, binary.LittleEndian, sh)
   377  
   378  	start := buf.Len()
   379  	buf.Write(bytes.Repeat([]byte{0}, paddingSize+len(buildInfoMagic)))
   380  	data := buf.Bytes()
   381  
   382  	if _, err := pe.NewFile(bytes.NewReader(data)); err != nil {
   383  		t.Fatalf("need a valid PE header for the misaligned buildInfoMagic test: %s", err)
   384  	}
   385  
   386  	// Place buildInfoMagic after the header.
   387  	for i := 1; i < paddingSize-len(buildInfoMagic); i++ {
   388  		// Test only misaligned buildInfoMagic.
   389  		if i%buildInfoAlign == 0 {
   390  			continue
   391  		}
   392  
   393  		t.Run(fmt.Sprintf("start_at_%d", i), func(t *testing.T) {
   394  			d := data[:start]
   395  			// Construct intentionally-misaligned buildInfoMagic.
   396  			d = append(d, bytes.Repeat([]byte{0}, i)...)
   397  			d = append(d, buildInfoMagic...)
   398  			d = append(d, bytes.Repeat([]byte{0}, paddingSize-i)...)
   399  
   400  			_, err := buildinfo.Read(bytes.NewReader(d))
   401  
   402  			wantErr := "not a Go executable"
   403  			if err == nil {
   404  				t.Errorf("got error nil; want error containing %q", wantErr)
   405  			} else if errMsg := err.Error(); !strings.Contains(errMsg, wantErr) {
   406  				t.Errorf("got error %q; want error containing %q", errMsg, wantErr)
   407  			}
   408  		})
   409  	}
   410  }
   411  
   412  func FuzzRead(f *testing.F) {
   413  	go117, err := os.ReadFile("testdata/go117")
   414  	if err != nil {
   415  		f.Errorf("Error reading go117: %v", err)
   416  	}
   417  	f.Add(go117)
   418  
   419  	notgo, err := os.ReadFile("testdata/notgo")
   420  	if err != nil {
   421  		f.Errorf("Error reading notgo: %v", err)
   422  	}
   423  	f.Add(notgo)
   424  
   425  	f.Fuzz(func(t *testing.T, in []byte) {
   426  		buildinfo.Read(bytes.NewReader(in))
   427  	})
   428  }
   429  

View as plain text