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
5package buildinfo_test
6
7import (
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
25var 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.
31func 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	goVersionRe := regexp.MustCompile("(?m)^go\t.*\n")
138	buildRe := regexp.MustCompile("(?m)^build\t.*\n")
139	cleanOutputForComparison := func(got string) string {
140		// Remove or replace anything that might depend on the test's environment
141		// so we can check the output afterward with a string comparison.
142		// We'll remove all build lines except the compiler, just to make sure
143		// build lines are included.
144		got = goVersionRe.ReplaceAllString(got, "go\tGOVERSION\n")
145		got = buildRe.ReplaceAllStringFunc(got, func(match string) string {
146			if strings.HasPrefix(match, "build\t-compiler=") {
147				return match
148			}
149			return ""
150		})
151		return got
152	}
153
154	cases := []struct {
155		name    string
156		build   func(t *testing.T, goos, goarch, buildmode string) string
157		want    string
158		wantErr string
159	}{
160		{
161			name: "doesnotexist",
162			build: func(t *testing.T, goos, goarch, buildmode string) string {
163				return "doesnotexist.txt"
164			},
165			wantErr: "doesnotexist",
166		},
167		{
168			name: "empty",
169			build: func(t *testing.T, _, _, _ string) string {
170				dir := t.TempDir()
171				name := filepath.Join(dir, "empty")
172				if err := os.WriteFile(name, nil, 0666); err != nil {
173					t.Fatal(err)
174				}
175				return name
176			},
177			wantErr: "unrecognized file format",
178		},
179		{
180			name:  "valid_modules",
181			build: buildWithModules,
182			want: "go\tGOVERSION\n" +
183				"path\texample.com/m\n" +
184				"mod\texample.com/m\t(devel)\t\n" +
185				"build\t-compiler=gc\n",
186		},
187		{
188			name: "invalid_modules",
189			build: func(t *testing.T, goos, goarch, buildmode string) string {
190				name := buildWithModules(t, goos, goarch, buildmode)
191				damageBuildInfo(t, name)
192				return name
193			},
194			wantErr: "not a Go executable",
195		},
196		{
197			name:  "valid_gopath",
198			build: buildWithGOPATH,
199			want: "go\tGOVERSION\n" +
200				"path\texample.com/m\n" +
201				"build\t-compiler=gc\n",
202		},
203		{
204			name: "invalid_gopath",
205			build: func(t *testing.T, goos, goarch, buildmode string) string {
206				name := buildWithGOPATH(t, goos, goarch, buildmode)
207				damageBuildInfo(t, name)
208				return name
209			},
210			wantErr: "not a Go executable",
211		},
212	}
213
214	for _, p := range platforms {
215		p := p
216		t.Run(p.goos+"_"+p.goarch, func(t *testing.T) {
217			if p != runtimePlatform && !*flagAll {
218				t.Skipf("skipping platforms other than %s_%s because -all was not set", runtimePlatform.goos, runtimePlatform.goarch)
219			}
220			for _, mode := range buildModes {
221				mode := mode
222				t.Run(mode, func(t *testing.T) {
223					for _, tc := range cases {
224						tc := tc
225						t.Run(tc.name, func(t *testing.T) {
226							t.Parallel()
227							name := tc.build(t, p.goos, p.goarch, mode)
228							if info, err := buildinfo.ReadFile(name); err != nil {
229								if tc.wantErr == "" {
230									t.Fatalf("unexpected error: %v", err)
231								} else if errMsg := err.Error(); !strings.Contains(errMsg, tc.wantErr) {
232									t.Fatalf("got error %q; want error containing %q", errMsg, tc.wantErr)
233								}
234							} else {
235								if tc.wantErr != "" {
236									t.Fatalf("unexpected success; want error containing %q", tc.wantErr)
237								}
238								got := info.String()
239								if clean := cleanOutputForComparison(got); got != tc.want && clean != tc.want {
240									t.Fatalf("got:\n%s\nwant:\n%s", got, tc.want)
241								}
242							}
243						})
244					}
245				})
246			}
247		})
248	}
249}
250
251// FuzzIssue57002 is a regression test for golang.org/issue/57002.
252//
253// The cause of issue 57002 is when pointerSize is not being checked,
254// the read can panic with slice bounds out of range
255func FuzzIssue57002(f *testing.F) {
256	// input from issue
257	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})
258	f.Fuzz(func(t *testing.T, input []byte) {
259		buildinfo.Read(bytes.NewReader(input))
260	})
261}
262
263// TestIssue54968 is a regression test for golang.org/issue/54968.
264//
265// The cause of issue 54968 is when the first buildInfoMagic is invalid, it
266// enters an infinite loop.
267func TestIssue54968(t *testing.T) {
268	t.Parallel()
269
270	const (
271		paddingSize    = 200
272		buildInfoAlign = 16
273	)
274	buildInfoMagic := []byte("\xff Go buildinf:")
275
276	// Construct a valid PE header.
277	var buf bytes.Buffer
278
279	buf.Write([]byte{'M', 'Z'})
280	buf.Write(bytes.Repeat([]byte{0}, 0x3c-2))
281	// At location 0x3c, the stub has the file offset to the PE signature.
282	binary.Write(&buf, binary.LittleEndian, int32(0x3c+4))
283
284	buf.Write([]byte{'P', 'E', 0, 0})
285
286	binary.Write(&buf, binary.LittleEndian, pe.FileHeader{NumberOfSections: 1})
287
288	sh := pe.SectionHeader32{
289		Name:             [8]uint8{'t', 0},
290		SizeOfRawData:    uint32(paddingSize + len(buildInfoMagic)),
291		PointerToRawData: uint32(buf.Len()),
292	}
293	sh.PointerToRawData = uint32(buf.Len() + binary.Size(sh))
294
295	binary.Write(&buf, binary.LittleEndian, sh)
296
297	start := buf.Len()
298	buf.Write(bytes.Repeat([]byte{0}, paddingSize+len(buildInfoMagic)))
299	data := buf.Bytes()
300
301	if _, err := pe.NewFile(bytes.NewReader(data)); err != nil {
302		t.Fatalf("need a valid PE header for the misaligned buildInfoMagic test: %s", err)
303	}
304
305	// Place buildInfoMagic after the header.
306	for i := 1; i < paddingSize-len(buildInfoMagic); i++ {
307		// Test only misaligned buildInfoMagic.
308		if i%buildInfoAlign == 0 {
309			continue
310		}
311
312		t.Run(fmt.Sprintf("start_at_%d", i), func(t *testing.T) {
313			d := data[:start]
314			// Construct intentionally-misaligned buildInfoMagic.
315			d = append(d, bytes.Repeat([]byte{0}, i)...)
316			d = append(d, buildInfoMagic...)
317			d = append(d, bytes.Repeat([]byte{0}, paddingSize-i)...)
318
319			_, err := buildinfo.Read(bytes.NewReader(d))
320
321			wantErr := "not a Go executable"
322			if err == nil {
323				t.Errorf("got error nil; want error containing %q", wantErr)
324			} else if errMsg := err.Error(); !strings.Contains(errMsg, wantErr) {
325				t.Errorf("got error %q; want error containing %q", errMsg, wantErr)
326			}
327		})
328	}
329}
330