-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathbetteralign_fuzz_test.go
More file actions
292 lines (275 loc) · 9.8 KB
/
Copy pathbetteralign_fuzz_test.go
File metadata and controls
292 lines (275 loc) · 9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright (c) 2026 Dinko Korunic <dinko.korunic@gmail.com>
//
// SPDX-FileCopyrightText: Copyright (c) 2026 Dinko Korunic <dinko.korunic@gmail.com>
// SPDX-License-Identifier: BSD-3-Clause
package betteralign
import (
"go/ast"
"go/parser"
"go/token"
"go/types"
"io/fs"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"testing"
"unicode/utf8"
)
// dumpInflight writes src to a per-worker file under $FUZZ_INFLIGHT_DIR before
// each fuzz exec. When a worker is SIGKILL'd silently by the coordinator (a
// failure mode that emits no panic, no stack trace, just "EOF" from the
// framework), the file is the only record of the input the worker was
// processing. No-op when the env var is unset, so production test runs are
// unaffected.
func dumpInflight(src string) {
dir := os.Getenv("FUZZ_INFLIGHT_DIR")
if dir == "" {
return
}
_ = os.WriteFile(filepath.Join(dir, "worker-"+strconv.Itoa(os.Getpid())+".txt"), []byte(src), 0o600)
}
// markPhase writes a short phase tag to a per-worker file. Combined with
// dumpInflight's source capture, this lets us reconstruct after a silent
// worker death exactly what input was being processed AND which stage of
// the pipeline died on it: typecheck, walk, or check.
func markPhase(p string) {
dir := os.Getenv("FUZZ_INFLIGHT_DIR")
if dir == "" {
return
}
_ = os.WriteFile(filepath.Join(dir, "phase-"+strconv.Itoa(os.Getpid())+".txt"), []byte(p), 0o600)
}
// addFuzzCorpus walks every .go and .go.golden file under root and adds its
// bytes as a fuzz seed. Errors are silent; missing corpus just means fewer
// seeds, never a test failure.
func addFuzzCorpus(f *testing.F, root string) {
f.Helper()
_ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
if !strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, ".go.golden") {
return nil
}
data, readErr := os.ReadFile(path)
if readErr != nil {
return nil
}
f.Add(string(data))
return nil
})
}
// typeCheckFuzzInput parses and type-checks src. The Importer is nil so any
// imports resolve to errors-but-non-nil packages; the resulting *types.Package
// is still usable for struct introspection. Returns nil on parser failure
// (uninteresting input). Bytes are fed to parser.ParseFile directly via its
// src parameter — no temp file is created per exec, which matters at fuzz
// throughput where 56k tempdir create/cleanup cycles/sec would otherwise
// hammer the disk. Panics from go/types itself (malformed generics, recursive
// alias chains — known upstream defects) are recovered and reported as Skip
// so the fuzzer keeps hunting for real betteralign bugs.
//
// IgnoreFuncBodies: true bypasses constant folding inside function bodies
// (BUG-44). Adversarial inputs like `134291756e439044200-4-5-…` produce
// multi-million-digit rationals through go/constant's exact arithmetic;
// without the flag, one such 119-byte input pushed type-checking to 8.5 s
// and tripped a fuzzing watchdog. The fuzz invariants only look at
// package-scope named types via pkg.Scope().Names(), so skipping bodies
// is invisible to every assertion the harness makes.
func typeCheckFuzzInput(t *testing.T, src string) (pkg *types.Package) {
t.Helper()
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "input.go", src, parser.ParseComments|parser.SkipObjectResolution)
if err != nil {
t.Skip("input not valid Go")
}
conf := types.Config{
Error: func(error) {}, // swallow type errors; partial info is enough
Importer: nil, // imports resolve to errors; struct internals still type-check
IgnoreFuncBodies: true, // BUG-44: skip constant folding inside function bodies — saw 8.5s hang on huge float exponent
}
defer func() {
if r := recover(); r != nil {
t.Skipf("go/types panic (upstream): %v", r)
}
}()
pkg, _ = conf.Check("fuzz", fset, []*ast.File{file}, nil)
return pkg
}
// FuzzOptimalOrder exercises optimalOrder on every named-struct type in
// arbitrary parser-accepted Go source. Invariants checked per struct:
//
// - optimalOrder does not panic
// - returned indexes are a valid permutation of [0, NumFields)
// - returned optSize never exceeds the struct's original Sizeof
// - returned optPtrdata never exceeds the struct's original ptrdata
//
// Skip conditions (treated as "uninteresting input"): parser failure,
// type-checker producing nil package, struct with zero fields.
func FuzzOptimalOrder(f *testing.F) {
addFuzzCorpus(f, "testdata")
f.Add("package p\n\ntype S struct { a int; b byte; c int64 }\n")
f.Add("package p\n\ntype S struct {}\n")
f.Add("package p\n\ntype S struct { _ [0]func() }\n")
f.Add("package p\n\ntype S[T any] struct { x T; y int }\n")
f.Fuzz(func(t *testing.T, src string) {
dumpInflight(src)
markPhase("typecheck")
pkg := typeCheckFuzzInput(t, src)
if pkg == nil {
t.Skip("type-check produced nil package")
}
markPhase("walk")
sizes := newGCSizes(8, 8)
for _, name := range pkg.Scope().Names() {
tn, ok := pkg.Scope().Lookup(name).(*types.TypeName)
if !ok {
continue
}
named, ok := tn.Type().(*types.Named)
if !ok {
continue
}
st, ok := named.Origin().Underlying().(*types.Struct)
if !ok {
continue
}
if st.NumFields() == 0 {
continue
}
markPhase("check")
checkOptimalOrderInvariants(t, name, st, sizes)
}
markPhase("done")
})
}
func checkOptimalOrderInvariants(t *testing.T, name string, st *types.Struct, sizes *gcSizes) {
t.Helper()
nf := st.NumFields()
indexes, optSize, optPtrdata := optimalOrder(st, sizes)
if len(indexes) != nf {
t.Errorf("%s: len(indexes)=%d, want %d", name, len(indexes), nf)
return
}
seen := make([]bool, nf)
for _, idx := range indexes {
if idx < 0 || idx >= nf {
t.Errorf("%s: idx %d out of range [0,%d)", name, idx, nf)
return
}
if seen[idx] {
t.Errorf("%s: idx %d appears twice", name, idx)
return
}
seen[idx] = true
}
// Non-negativity guard. Without this the upper-bound checks below are
// trivially satisfied when origSize / origPtrdata saturate to MaxInt64,
// hiding bugs where the optimalOrder accumulator wraps to a negative.
if optSize < 0 {
t.Errorf("%s: optSize=%d (negative; integer overflow in accumulator)", name, optSize)
}
if optPtrdata < 0 {
t.Errorf("%s: optPtrdata=%d (negative; integer overflow in accumulator)", name, optPtrdata)
}
origSize := sizes.Sizeof(st)
if optSize > origSize {
t.Errorf("%s: optSize=%d > origSize=%d", name, optSize, origSize)
}
origPtrdata := sizes.ptrdata(st)
if optPtrdata > origPtrdata {
t.Errorf("%s: optPtrdata=%d > origPtrdata=%d", name, optPtrdata, origPtrdata)
}
}
// FuzzGCSizes exercises Sizeof / Alignof / ptrdata on every named type in
// arbitrary parser-accepted Go source. Invariants:
//
// - none of the three operations panics (this is what protected us against
// the upstream "ptrdata panic on *types.TypeParam" bug)
// - Sizeof >= ptrdata for any type (a pointer-bearing prefix can't exceed
// the total size)
// - Alignof >= 1 for any type (per the language spec)
//
// Skip conditions: parser failure, nil package.
func FuzzGCSizes(f *testing.F) {
addFuzzCorpus(f, "testdata")
f.Add("package p\n\ntype S struct { a int; b byte }\n")
f.Add("package p\n\ntype I interface{ M() }\n")
f.Add("package p\n\ntype G[T any] struct { x T }\n")
f.Add("package p\n\ntype F func() error\n")
f.Add("package p\n\ntype A [3]uint8\n")
f.Fuzz(func(t *testing.T, src string) {
dumpInflight(src)
markPhase("typecheck")
pkg := typeCheckFuzzInput(t, src)
if pkg == nil {
t.Skip("type-check produced nil package")
}
markPhase("walk")
sizes := newGCSizes(8, 8)
for _, name := range pkg.Scope().Names() {
tn, ok := pkg.Scope().Lookup(name).(*types.TypeName)
if !ok {
continue
}
typ := tn.Type()
markPhase("check")
checkGCSizesInvariants(t, name, typ, sizes)
}
markPhase("done")
})
}
func checkGCSizesInvariants(t *testing.T, name string, typ types.Type, sizes *gcSizes) {
t.Helper()
sz := sizes.Sizeof(typ)
al := sizes.Alignof(typ)
pd := sizes.ptrdata(typ)
if sz < 0 {
t.Errorf("%s: Sizeof=%d (negative; integer overflow)", name, sz)
}
if pd < 0 {
t.Errorf("%s: ptrdata=%d (negative; integer overflow)", name, pd)
}
if al < 1 {
t.Errorf("%s: Alignof=%d, want >=1", name, al)
}
if pd > sz {
t.Errorf("%s: ptrdata=%d > Sizeof=%d", name, pd, sz)
}
}
// FuzzGeneratedByMatcher differential-tests the generated reGeneratedBy DFA
// against Go's regexp engine on the exact pattern it was generated from. The
// matcher in match_generated.go is emitted by the rec tool (see the `generate`
// Taskfile target), so any disagreement with the reference regex is a
// code-generation bug that would mis-classify generated files. Inputs are
// confined to the matcher's real domain — a single, valid-UTF-8 comment line —
// because hasGeneratedComment never feeds it anything else, and multiline ^/$
// or invalid UTF-8 would surface differences that aren't generation bugs.
func FuzzGeneratedByMatcher(f *testing.F) {
ref := regexp.MustCompile(`^//\s*Code generated by .* DO NOT EDIT\.$`)
for _, s := range []string{
"// Code generated by foo. DO NOT EDIT.",
"// Code generated by protoc-gen-go. DO NOT EDIT.",
"//\tCode generated by sqlc. DO NOT EDIT.",
"//Code generated by x. DO NOT EDIT.",
"// Code generated by x. DO NOT EDIT",
"// code generated by x. DO NOT EDIT.",
"// Code generated by x. DO NOT EDIT. ",
"// Code generated. DO NOT EDIT.",
"// Code generated by x. do not edit.",
"package main",
"",
} {
f.Add(s)
}
f.Fuzz(func(t *testing.T, s string) {
if strings.ContainsAny(s, "\n\r") || !utf8.ValidString(s) {
t.Skip("outside the matcher's single-valid-comment-line domain")
}
if got, want := reGeneratedBy(s), ref.MatchString(s); got != want {
t.Errorf("reGeneratedBy(%q) = %v, regexp = %v", s, got, want)
}
})
}