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  		p := p
   242  		t.Run(p.goos+"_"+p.goarch, func(t *testing.T) {
   243  			if p != runtimePlatform && !*flagAll {
   244  				t.Skipf("skipping platforms other than %s_%s because -all was not set", runtimePlatform.goos, runtimePlatform.goarch)
   245  			}
   246  			for _, mode := range buildModes {
   247  				mode := mode
   248  				t.Run(mode, func(t *testing.T) {
   249  					for _, tc := range cases {
   250  						tc := tc
   251  						t.Run(tc.name, func(t *testing.T) {
   252  							t.Parallel()
   253  							name := tc.build(t, p.goos, p.goarch, mode)
   254  							if info, err := buildinfo.ReadFile(name); err != nil {
   255  								if tc.wantErr == "" {
   256  									t.Fatalf("unexpected error: %v", err)
   257  								} else if errMsg := err.Error(); !strings.Contains(errMsg, tc.wantErr) {
   258  									t.Fatalf("got error %q; want error containing %q", errMsg, tc.wantErr)
   259  								}
   260  							} else {
   261  								if tc.wantErr != "" {
   262  									t.Fatalf("unexpected success; want error containing %q", tc.wantErr)
   263  								}
   264  								got := info.String()
   265  								if clean := cleanOutputForComparison(got); got != tc.want && clean != tc.want {
   266  									t.Fatalf("got:\n%s\nwant:\n%s", got, tc.want)
   267  								}
   268  							}
   269  						})
   270  					}
   271  				})
   272  			}
   273  		})
   274  	}
   275  }
   276  
   277  // Test117 verifies that parsing of the old, pre-1.18 format works.
   278  func Test117(t *testing.T) {
   279  	b, err := obscuretestdata.ReadFile("testdata/go117/go117.base64")
   280  	if err != nil {
   281  		t.Fatalf("ReadFile got err %v, want nil", err)
   282  	}
   283  
   284  	info, err := buildinfo.Read(bytes.NewReader(b))
   285  	if err != nil {
   286  		t.Fatalf("Read got err %v, want nil", err)
   287  	}
   288  
   289  	if info.GoVersion != "go1.17" {
   290  		t.Errorf("GoVersion got %s want go1.17", info.GoVersion)
   291  	}
   292  	if info.Path != "example.com/go117" {
   293  		t.Errorf("Path got %s want example.com/go117", info.Path)
   294  	}
   295  	if info.Main.Path != "example.com/go117" {
   296  		t.Errorf("Main.Path got %s want example.com/go117", info.Main.Path)
   297  	}
   298  }
   299  
   300  // TestNotGo verifies that parsing of a non-Go binary returns the proper error.
   301  func TestNotGo(t *testing.T) {
   302  	b, err := obscuretestdata.ReadFile("testdata/notgo/notgo.base64")
   303  	if err != nil {
   304  		t.Fatalf("ReadFile got err %v, want nil", err)
   305  	}
   306  
   307  	_, err = buildinfo.Read(bytes.NewReader(b))
   308  	if err == nil {
   309  		t.Fatalf("Read got nil err, want non-nil")
   310  	}
   311  
   312  	// The precise error text here isn't critical, but we want something
   313  	// like errNotGoExe rather than e.g., a file read error.
   314  	if !strings.Contains(err.Error(), "not a Go executable") {
   315  		t.Errorf("ReadFile got err %v want not a Go executable", err)
   316  	}
   317  }
   318  
   319  // FuzzIssue57002 is a regression test for golang.org/issue/57002.
   320  //
   321  // The cause of issue 57002 is when pointerSize is not being checked,
   322  // the read can panic with slice bounds out of range
   323  func FuzzIssue57002(f *testing.F) {
   324  	// input from issue
   325  	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})
   326  	f.Fuzz(func(t *testing.T, input []byte) {
   327  		buildinfo.Read(bytes.NewReader(input))
   328  	})
   329  }
   330  
   331  // TestIssue54968 is a regression test for golang.org/issue/54968.
   332  //
   333  // The cause of issue 54968 is when the first buildInfoMagic is invalid, it
   334  // enters an infinite loop.
   335  func TestIssue54968(t *testing.T) {
   336  	t.Parallel()
   337  
   338  	const (
   339  		paddingSize    = 200
   340  		buildInfoAlign = 16
   341  	)
   342  	buildInfoMagic := []byte("\xff Go buildinf:")
   343  
   344  	// Construct a valid PE header.
   345  	var buf bytes.Buffer
   346  
   347  	buf.Write([]byte{'M', 'Z'})
   348  	buf.Write(bytes.Repeat([]byte{0}, 0x3c-2))
   349  	// At location 0x3c, the stub has the file offset to the PE signature.
   350  	binary.Write(&buf, binary.LittleEndian, int32(0x3c+4))
   351  
   352  	buf.Write([]byte{'P', 'E', 0, 0})
   353  
   354  	binary.Write(&buf, binary.LittleEndian, pe.FileHeader{NumberOfSections: 1})
   355  
   356  	sh := pe.SectionHeader32{
   357  		Name:             [8]uint8{'t', 0},
   358  		SizeOfRawData:    uint32(paddingSize + len(buildInfoMagic)),
   359  		PointerToRawData: uint32(buf.Len()),
   360  	}
   361  	sh.PointerToRawData = uint32(buf.Len() + binary.Size(sh))
   362  
   363  	binary.Write(&buf, binary.LittleEndian, sh)
   364  
   365  	start := buf.Len()
   366  	buf.Write(bytes.Repeat([]byte{0}, paddingSize+len(buildInfoMagic)))
   367  	data := buf.Bytes()
   368  
   369  	if _, err := pe.NewFile(bytes.NewReader(data)); err != nil {
   370  		t.Fatalf("need a valid PE header for the misaligned buildInfoMagic test: %s", err)
   371  	}
   372  
   373  	// Place buildInfoMagic after the header.
   374  	for i := 1; i < paddingSize-len(buildInfoMagic); i++ {
   375  		// Test only misaligned buildInfoMagic.
   376  		if i%buildInfoAlign == 0 {
   377  			continue
   378  		}
   379  
   380  		t.Run(fmt.Sprintf("start_at_%d", i), func(t *testing.T) {
   381  			d := data[:start]
   382  			// Construct intentionally-misaligned buildInfoMagic.
   383  			d = append(d, bytes.Repeat([]byte{0}, i)...)
   384  			d = append(d, buildInfoMagic...)
   385  			d = append(d, bytes.Repeat([]byte{0}, paddingSize-i)...)
   386  
   387  			_, err := buildinfo.Read(bytes.NewReader(d))
   388  
   389  			wantErr := "not a Go executable"
   390  			if err == nil {
   391  				t.Errorf("got error nil; want error containing %q", wantErr)
   392  			} else if errMsg := err.Error(); !strings.Contains(errMsg, wantErr) {
   393  				t.Errorf("got error %q; want error containing %q", errMsg, wantErr)
   394  			}
   395  		})
   396  	}
   397  }
   398  
   399  func FuzzRead(f *testing.F) {
   400  	go117, err := obscuretestdata.ReadFile("testdata/go117/go117.base64")
   401  	if err != nil {
   402  		f.Errorf("Error reading go117: %v", err)
   403  	}
   404  	f.Add(go117)
   405  
   406  	notgo, err := obscuretestdata.ReadFile("testdata/notgo/notgo.base64")
   407  	if err != nil {
   408  		f.Errorf("Error reading notgo: %v", err)
   409  	}
   410  	f.Add(notgo)
   411  
   412  	f.Fuzz(func(t *testing.T, in []byte) {
   413  		buildinfo.Read(bytes.NewReader(in))
   414  	})
   415  }
   416  

View as plain text