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

View as plain text