-
Notifications
You must be signed in to change notification settings - Fork 0
/
gopointer_test.go
377 lines (320 loc) · 9.28 KB
/
gopointer_test.go
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package pointer_test
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
"os"
"os/exec"
"path"
"regexp"
"strings"
"testing"
"github.com/BarrensZeppelin/pointer"
"github.com/BarrensZeppelin/pointer/internal/slices"
"github.com/BarrensZeppelin/pointer/pkgutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/tools/go/expect"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/ssa"
"golang.org/x/tools/go/ssa/ssautil"
"golang.org/x/tools/go/types/typeutil"
)
func TestGoPointerTests(t *testing.T) {
cmd := exec.Command("go", "list", "-f", "{{.Dir}}", "golang.org/x/tools/go/pointer/testdata")
var out strings.Builder
cmd.Stdout = &out
err := cmd.Run()
require.NoError(t, err)
testdataPath := strings.TrimRight(out.String(), "\n")
testfiles, err := os.ReadDir(testdataPath)
require.NoError(t, err)
qre := regexp.MustCompile(`(?m)// @(\w+)(?: ([^\n"]+))?$`)
callre := regexp.MustCompile(`^main\.`)
knownOverapproximations := map[string][]int{
"arrays_go117.go": {
57, // assignment is bidirectional
65,
72, // same with copy
111, // creating a copy of an array through dereference is bidirectional
112,
},
"arrays.go": {
54,
62,
69,
},
"channels.go": {
41, 44, // assignment is bidirectional
},
"context.go": {
20, 21, // no context sensitivity
29, 30,
39, 42,
},
"finalizer.go": {
6, // runtime.SetFinalizer is not handled context-sensitively
11,
61,
},
"fmtexcerpt.go": {
32, // known (fixable) imprecision in TypeAssert with interfaces
},
"func.go": {
28, // return bidirectional
},
"maps.go": {
45, 46, // assignment to slice contents is bidirectional
},
"interfaces.go": {
39, 42, // assignment to k is bidirectional
97, 101, 105, // known (fixable) imprecision in TypeAssert with interfaces
},
}
for _, entry := range testfiles {
overapproximations := knownOverapproximations[entry.Name()]
fullpath := path.Join(testdataPath, entry.Name())
config := &packages.Config{
Mode: pkgutil.LoadMode,
Tests: true,
ParseFile: func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) {
if filename == fullpath {
src = qre.ReplaceAll(src, []byte("//@ $1(\"$2\")"))
// t.Log(filename, string(src))
}
return parser.ParseFile(fset, filename, src, parser.AllErrors|parser.ParseComments)
},
}
entry := entry
t.Run(entry.Name(), func(t *testing.T) {
t.Parallel()
pkgs, err := pkgutil.LoadPackagesWithConfig(config, fullpath)
require.NoError(t, err)
mainPkgIndex := 0
if entry.Name() == "a_test.go" {
require.Len(t, pkgs, 2)
for i, pkg := range pkgs {
if pkg.Name == "a" {
mainPkgIndex = i
}
}
} else {
require.Len(t, pkgs, 1)
}
mainPkg := pkgs[mainPkgIndex]
if _, found := mainPkg.Imports["reflect"]; found {
t.Skipf("%s uses reflection", entry.Name())
}
prog, spkgs := ssautil.AllPackages(pkgs, ssa.InstantiateGenerics)
require.Condition(t, func() bool {
for _, spkg := range spkgs {
if spkg.Func("main") != nil {
return true
}
}
return false
}, "No main function")
prog.Build()
ptres := pointer.Analyze(pointer.AnalysisConfig{
Program: prog,
EntryPackages: spkgs,
})
if entry.Name() == "issue9002.go" {
// no notes
return
}
require.Len(t, mainPkg.Syntax, 1)
notes, err := expect.ExtractGo(prog.Fset, mainPkg.Syntax[0])
require.NoError(t, err)
require.NotEmpty(t, notes)
mainFile := prog.Fset.File(mainPkg.Syntax[0].Pos())
printArgs := map[int][]ssa.Value{}
// for fn := range ptres.Reachable {
for fn := range ssautil.AllFunctions(prog) {
if isGenericBody(fn) {
continue // skip generic bodies
}
if fn.Pkg == spkgs[mainPkgIndex] ||
(fn.Pkg == nil && prog.Fset.File(fn.Pos()) == mainFile) {
for _, block := range fn.Blocks {
for _, insn := range block.Instrs {
call, ok := insn.(ssa.CallInstruction)
if !ok {
continue
}
common := call.Common()
if v, isBuiltin := common.Value.(*ssa.Builtin); isBuiltin &&
!common.IsInvoke() && v.Name() == "print" &&
len(common.Args) == 1 {
pos := prog.Fset.Position(insn.Pos())
printArgs[pos.Line] = append(printArgs[pos.Line], common.Args[0])
}
}
}
}
}
lineMapping := map[string]string{}
for _, note := range notes {
pos := prog.Fset.Position(note.Pos)
arg := note.Args[0].(string)
if note.Name == "line" {
lineMapping[fmt.Sprintf("%s:%d", pos.Filename, pos.Line)] = arg
}
}
cgEdges := map[string][]string{}
for _, node := range ptres.CallGraph().Nodes {
eds := []string{}
for _, edge := range node.Out {
callee := edge.Callee.Func.String()
eds = append(eds, callee)
}
cgEdges[node.Func.String()] = eds
}
for _, note := range notes {
pos := prog.Fset.Position(note.Pos)
pos.Filename = strings.TrimPrefix(pos.Filename,
testdataPath+string(os.PathSeparator))
arg := note.Args[0].(string)
exact := !slices.Contains(overapproximations, pos.Line)
switch note.Name {
case "pointsto":
var expected, actual []string
if arg != "" {
for _, g := range strings.Split(arg, " | ") {
if g == "..." {
exact = false
continue
}
expected = append(expected, g)
}
}
pa := printArgs[pos.Line]
require.NotNil(t, pa)
for _, v := range pa {
for _, label := range ptres.Pointer(v).PointsTo() {
name := labelString(label, lineMapping, prog)
actual = append(actual, name)
}
}
if exact {
assert.ElementsMatchf(t, actual, expected, "At %v", pos)
} else {
assert.Subsetf(t, actual, expected, "At %v", pos)
if !slices.Contains(expected, "<command-line args>") {
assert.NotSubsetf(t, expected, actual,
"Assertion at %v should be exact", pos)
}
}
case "types":
var expected typeutil.Map
if arg != "" {
for _, typstr := range strings.Split(arg, " | ") {
if typstr == "..." {
exact = false
} else {
tv, err := types.Eval(prog.Fset, spkgs[0].Pkg, mainPkg.Syntax[0].Pos(), typstr)
if assert.NoError(t, err, "'%s' is not a valid type", typstr) {
expected.Set(tv.Type, nil)
}
}
}
}
pa := printArgs[pos.Line]
require.NotNil(t, pa)
var actual typeutil.Map
for _, v := range pa {
if types.IsInterface(v.Type()) {
ptres.DynamicTypes(v).Iterate(func(k types.Type, _ any) {
actual.Set(k, nil)
})
} else {
actual.Set(v.Type(), nil)
}
}
var extra []types.Type
actual.Iterate(func(t types.Type, _ any) {
if !expected.Delete(t) {
extra = append(extra, t)
}
})
assert.Emptyf(t, expected.Keys(), "Actual types: %v\nAt %v",
actual.KeysString(), pos)
if exact {
assert.Emptyf(t, extra, "Additional types %v at %v", extra, pos)
} else {
assert.NotEmptyf(t, extra, "Assertion at %v should be exact", pos)
}
case "calls":
parts := slices.Map(strings.Split(arg, "->"), func(s string) string {
return callre.ReplaceAllString(strings.TrimSpace(s),
"command-line-arguments.")
})
if eds, found := cgEdges[parts[0]]; found {
assert.Containsf(t, eds, parts[1], "At %v", pos)
}
}
}
})
}
}
// isGenericBody returns true if fn is the body of a generic function.
func isGenericBody(fn *ssa.Function) bool {
sig := fn.Signature
if sig.TypeParams().Len() > 0 || sig.RecvTypeParams().Len() > 0 {
return fn.Synthetic == ""
}
return false
}
func labelString(l pointer.Label, lineMapping map[string]string, prog *ssa.Program) string {
if s, ok := l.(pointer.Synthetic); ok {
return s.Label
}
s := l.Site()
str := func() string {
switch v := s.(type) {
case *ssa.Function, *ssa.Global:
return v.String()
case *ssa.Const:
return v.Name()
case *ssa.Alloc:
if v.Comment != "" {
return v.Comment
}
return "alloc"
case *ssa.Call:
// Currently only calls to append can allocate objects.
if v.Call.Value.(*ssa.Builtin).Object().Name() != "append" {
panic("unhandled *ssa.Call label: " + v.Name())
}
return "append"
case *ssa.MakeMap, *ssa.MakeChan, *ssa.MakeSlice, *ssa.Convert:
return strings.ToLower(strings.TrimPrefix(fmt.Sprintf("%T", v), "*ssa."))
case *ssa.MakeInterface:
// MakeInterface is usually implicit in Go source (so
// Pos()==0), and tagged objects may be allocated
// synthetically (so no *MakeInterface data).
return "makeinterface:" + v.X.Type().String()
default:
panic(fmt.Sprintf("unhandled object data type: %T", v))
}
}() + l.Path()
// Functions and Globals need no pos suffix,
// nor do allocations in intrinsic operations
// (for which we'll print the function name).
switch s.(type) {
case *ssa.Function, *ssa.Global:
return str
}
if pos := s.Pos(); pos != token.NoPos {
// Append the position, using a @line tag instead of a line number, if defined.
posn := prog.Fset.Position(pos)
s := fmt.Sprintf("%s:%d", posn.Filename, posn.Line)
if tag, ok := lineMapping[s]; ok {
return fmt.Sprintf("%s@%s:%d", str, tag, posn.Column)
}
str = fmt.Sprintf("%s@%s", str, posn)
}
return str
}