github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/tools/go/pointer/pointer14_test.go (about)

     1  // Copyright 2013 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  // +build !go1.5
     6  
     7  // No testdata on Android.
     8  
     9  // +build !android
    10  
    11  package pointer_test
    12  
    13  // This test uses 'expectation' comments embedded within testdata/*.go
    14  // files to specify the expected pointer analysis behaviour.
    15  // See below for grammar.
    16  
    17  import (
    18  	"bytes"
    19  	"errors"
    20  	"fmt"
    21  	"go/token"
    22  	"io/ioutil"
    23  	"os"
    24  	"regexp"
    25  	"strconv"
    26  	"strings"
    27  	"testing"
    28  
    29  	"golang.org/x/tools/go/callgraph"
    30  	"golang.org/x/tools/go/loader"
    31  	"golang.org/x/tools/go/pointer"
    32  	"golang.org/x/tools/go/ssa"
    33  	"golang.org/x/tools/go/ssa/ssautil"
    34  	"golang.org/x/tools/go/types"
    35  	"golang.org/x/tools/go/types/typeutil"
    36  )
    37  
    38  var inputs = []string{
    39  	"testdata/a_test.go",
    40  	"testdata/another.go",
    41  	"testdata/arrayreflect.go",
    42  	"testdata/arrays.go",
    43  	"testdata/channels.go",
    44  	"testdata/chanreflect.go",
    45  	"testdata/context.go",
    46  	"testdata/conv.go",
    47  	"testdata/finalizer.go",
    48  	"testdata/flow.go",
    49  	"testdata/fmtexcerpt.go",
    50  	"testdata/func.go",
    51  	"testdata/funcreflect.go",
    52  	"testdata/hello.go", // NB: causes spurious failure of HVN cross-check
    53  	"testdata/interfaces.go",
    54  	"testdata/issue9002.go",
    55  	"testdata/mapreflect.go",
    56  	"testdata/maps.go",
    57  	"testdata/panic.go",
    58  	"testdata/recur.go",
    59  	"testdata/reflect.go",
    60  	"testdata/rtti.go",
    61  	"testdata/structreflect.go",
    62  	"testdata/structs.go",
    63  	"testdata/timer.go",
    64  }
    65  
    66  // Expectation grammar:
    67  //
    68  // @calls f -> g
    69  //
    70  //   A 'calls' expectation asserts that edge (f, g) appears in the
    71  //   callgraph.  f and g are notated as per Function.String(), which
    72  //   may contain spaces (e.g. promoted method in anon struct).
    73  //
    74  // @pointsto a | b | c
    75  //
    76  //   A 'pointsto' expectation asserts that the points-to set of its
    77  //   operand contains exactly the set of labels {a,b,c} notated as per
    78  //   labelString.
    79  //
    80  //   A 'pointsto' expectation must appear on the same line as a
    81  //   print(x) statement; the expectation's operand is x.
    82  //
    83  //   If one of the strings is "...", the expectation asserts that the
    84  //   points-to set at least the other labels.
    85  //
    86  //   We use '|' because label names may contain spaces, e.g.  methods
    87  //   of anonymous structs.
    88  //
    89  //   From a theoretical perspective, concrete types in interfaces are
    90  //   labels too, but they are represented differently and so have a
    91  //   different expectation, @types, below.
    92  //
    93  // @types t | u | v
    94  //
    95  //   A 'types' expectation asserts that the set of possible dynamic
    96  //   types of its interface operand is exactly {t,u,v}, notated per
    97  //   go/types.Type.String(). In other words, it asserts that the type
    98  //   component of the interface may point to that set of concrete type
    99  //   literals.  It also works for reflect.Value, though the types
   100  //   needn't be concrete in that case.
   101  //
   102  //   A 'types' expectation must appear on the same line as a
   103  //   print(x) statement; the expectation's operand is x.
   104  //
   105  //   If one of the strings is "...", the expectation asserts that the
   106  //   interface's type may point to at least the other types.
   107  //
   108  //   We use '|' because type names may contain spaces.
   109  //
   110  // @warning "regexp"
   111  //
   112  //   A 'warning' expectation asserts that the analysis issues a
   113  //   warning that matches the regular expression within the string
   114  //   literal.
   115  //
   116  // @line id
   117  //
   118  //   A line directive associates the name "id" with the current
   119  //   file:line.  The string form of labels will use this id instead of
   120  //   a file:line, making @pointsto expectations more robust against
   121  //   perturbations in the source file.
   122  //   (NB, anon functions still include line numbers.)
   123  //
   124  type expectation struct {
   125  	kind     string // "pointsto" | "types" | "calls" | "warning"
   126  	filename string
   127  	linenum  int // source line number, 1-based
   128  	args     []string
   129  	types    []types.Type // for types
   130  }
   131  
   132  func (e *expectation) String() string {
   133  	return fmt.Sprintf("@%s[%s]", e.kind, strings.Join(e.args, " | "))
   134  }
   135  
   136  func (e *expectation) errorf(format string, args ...interface{}) {
   137  	fmt.Printf("%s:%d: ", e.filename, e.linenum)
   138  	fmt.Printf(format, args...)
   139  	fmt.Println()
   140  }
   141  
   142  func (e *expectation) needsProbe() bool {
   143  	return e.kind == "pointsto" || e.kind == "types"
   144  }
   145  
   146  // Find probe (call to print(x)) of same source file/line as expectation.
   147  func findProbe(prog *ssa.Program, probes map[*ssa.CallCommon]bool, queries map[ssa.Value]pointer.Pointer, e *expectation) (site *ssa.CallCommon, pts pointer.PointsToSet) {
   148  	for call := range probes {
   149  		pos := prog.Fset.Position(call.Pos())
   150  		if pos.Line == e.linenum && pos.Filename == e.filename {
   151  			// TODO(adonovan): send this to test log (display only on failure).
   152  			// fmt.Printf("%s:%d: info: found probe for %s: %s\n",
   153  			// 	e.filename, e.linenum, e, p.arg0) // debugging
   154  			return call, queries[call.Args[0]].PointsTo()
   155  		}
   156  	}
   157  	return // e.g. analysis didn't reach this call
   158  }
   159  
   160  func doOneInput(input, filename string) bool {
   161  	var conf loader.Config
   162  
   163  	// Parsing.
   164  	f, err := conf.ParseFile(filename, input)
   165  	if err != nil {
   166  		fmt.Println(err)
   167  		return false
   168  	}
   169  
   170  	// Create single-file main package and import its dependencies.
   171  	conf.CreateFromFiles("main", f)
   172  	iprog, err := conf.Load()
   173  	if err != nil {
   174  		fmt.Println(err)
   175  		return false
   176  	}
   177  	mainPkgInfo := iprog.Created[0].Pkg
   178  
   179  	// SSA creation + building.
   180  	prog := ssautil.CreateProgram(iprog, ssa.SanityCheckFunctions)
   181  	prog.Build()
   182  
   183  	mainpkg := prog.Package(mainPkgInfo)
   184  	ptrmain := mainpkg // main package for the pointer analysis
   185  	if mainpkg.Func("main") == nil {
   186  		// No main function; assume it's a test.
   187  		ptrmain = prog.CreateTestMainPackage(mainpkg)
   188  	}
   189  
   190  	// Find all calls to the built-in print(x).  Analytically,
   191  	// print is a no-op, but it's a convenient hook for testing
   192  	// the PTS of an expression, so our tests use it.
   193  	probes := make(map[*ssa.CallCommon]bool)
   194  	for fn := range ssautil.AllFunctions(prog) {
   195  		if fn.Pkg == mainpkg {
   196  			for _, b := range fn.Blocks {
   197  				for _, instr := range b.Instrs {
   198  					if instr, ok := instr.(ssa.CallInstruction); ok {
   199  						call := instr.Common()
   200  						if b, ok := call.Value.(*ssa.Builtin); ok && b.Name() == "print" && len(call.Args) == 1 {
   201  							probes[instr.Common()] = true
   202  						}
   203  					}
   204  				}
   205  			}
   206  		}
   207  	}
   208  
   209  	ok := true
   210  
   211  	lineMapping := make(map[string]string) // maps "file:line" to @line tag
   212  
   213  	// Parse expectations in this input.
   214  	var exps []*expectation
   215  	re := regexp.MustCompile("// *@([a-z]*) *(.*)$")
   216  	lines := strings.Split(input, "\n")
   217  	for linenum, line := range lines {
   218  		linenum++ // make it 1-based
   219  		if matches := re.FindAllStringSubmatch(line, -1); matches != nil {
   220  			match := matches[0]
   221  			kind, rest := match[1], match[2]
   222  			e := &expectation{kind: kind, filename: filename, linenum: linenum}
   223  
   224  			if kind == "line" {
   225  				if rest == "" {
   226  					ok = false
   227  					e.errorf("@%s expectation requires identifier", kind)
   228  				} else {
   229  					lineMapping[fmt.Sprintf("%s:%d", filename, linenum)] = rest
   230  				}
   231  				continue
   232  			}
   233  
   234  			if e.needsProbe() && !strings.Contains(line, "print(") {
   235  				ok = false
   236  				e.errorf("@%s expectation must follow call to print(x)", kind)
   237  				continue
   238  			}
   239  
   240  			switch kind {
   241  			case "pointsto":
   242  				e.args = split(rest, "|")
   243  
   244  			case "types":
   245  				for _, typstr := range split(rest, "|") {
   246  					var t types.Type = types.Typ[types.Invalid] // means "..."
   247  					if typstr != "..." {
   248  						tv, err := types.Eval(prog.Fset, mainpkg.Pkg, f.Pos(), typstr)
   249  						if err != nil {
   250  							ok = false
   251  							// Don't print err since its location is bad.
   252  							e.errorf("'%s' is not a valid type: %s", typstr, err)
   253  							continue
   254  						}
   255  						t = tv.Type
   256  					}
   257  					e.types = append(e.types, t)
   258  				}
   259  
   260  			case "calls":
   261  				e.args = split(rest, "->")
   262  				// TODO(adonovan): eagerly reject the
   263  				// expectation if fn doesn't denote
   264  				// existing function, rather than fail
   265  				// the expectation after analysis.
   266  				if len(e.args) != 2 {
   267  					ok = false
   268  					e.errorf("@calls expectation wants 'caller -> callee' arguments")
   269  					continue
   270  				}
   271  
   272  			case "warning":
   273  				lit, err := strconv.Unquote(strings.TrimSpace(rest))
   274  				if err != nil {
   275  					ok = false
   276  					e.errorf("couldn't parse @warning operand: %s", err.Error())
   277  					continue
   278  				}
   279  				e.args = append(e.args, lit)
   280  
   281  			default:
   282  				ok = false
   283  				e.errorf("unknown expectation kind: %s", e)
   284  				continue
   285  			}
   286  			exps = append(exps, e)
   287  		}
   288  	}
   289  
   290  	var log bytes.Buffer
   291  	fmt.Fprintf(&log, "Input: %s\n", filename)
   292  
   293  	// Run the analysis.
   294  	config := &pointer.Config{
   295  		Reflection:     true,
   296  		BuildCallGraph: true,
   297  		Mains:          []*ssa.Package{ptrmain},
   298  		Log:            &log,
   299  	}
   300  	for probe := range probes {
   301  		v := probe.Args[0]
   302  		if pointer.CanPoint(v.Type()) {
   303  			config.AddQuery(v)
   304  		}
   305  	}
   306  
   307  	// Print the log is there was an error or a panic.
   308  	complete := false
   309  	defer func() {
   310  		if !complete || !ok {
   311  			log.WriteTo(os.Stderr)
   312  		}
   313  	}()
   314  
   315  	result, err := pointer.Analyze(config)
   316  	if err != nil {
   317  		panic(err) // internal error in pointer analysis
   318  	}
   319  
   320  	// Check the expectations.
   321  	for _, e := range exps {
   322  		var call *ssa.CallCommon
   323  		var pts pointer.PointsToSet
   324  		var tProbe types.Type
   325  		if e.needsProbe() {
   326  			if call, pts = findProbe(prog, probes, result.Queries, e); call == nil {
   327  				ok = false
   328  				e.errorf("unreachable print() statement has expectation %s", e)
   329  				continue
   330  			}
   331  			tProbe = call.Args[0].Type()
   332  			if !pointer.CanPoint(tProbe) {
   333  				ok = false
   334  				e.errorf("expectation on non-pointerlike operand: %s", tProbe)
   335  				continue
   336  			}
   337  		}
   338  
   339  		switch e.kind {
   340  		case "pointsto":
   341  			if !checkPointsToExpectation(e, pts, lineMapping, prog) {
   342  				ok = false
   343  			}
   344  
   345  		case "types":
   346  			if !checkTypesExpectation(e, pts, tProbe) {
   347  				ok = false
   348  			}
   349  
   350  		case "calls":
   351  			if !checkCallsExpectation(prog, e, result.CallGraph) {
   352  				ok = false
   353  			}
   354  
   355  		case "warning":
   356  			if !checkWarningExpectation(prog, e, result.Warnings) {
   357  				ok = false
   358  			}
   359  		}
   360  	}
   361  
   362  	complete = true
   363  
   364  	// ok = false // debugging: uncomment to always see log
   365  
   366  	return ok
   367  }
   368  
   369  func labelString(l *pointer.Label, lineMapping map[string]string, prog *ssa.Program) string {
   370  	// Functions and Globals need no pos suffix,
   371  	// nor do allocations in intrinsic operations
   372  	// (for which we'll print the function name).
   373  	switch l.Value().(type) {
   374  	case nil, *ssa.Function, *ssa.Global:
   375  		return l.String()
   376  	}
   377  
   378  	str := l.String()
   379  	if pos := l.Pos(); pos != token.NoPos {
   380  		// Append the position, using a @line tag instead of a line number, if defined.
   381  		posn := prog.Fset.Position(pos)
   382  		s := fmt.Sprintf("%s:%d", posn.Filename, posn.Line)
   383  		if tag, ok := lineMapping[s]; ok {
   384  			return fmt.Sprintf("%s@%s:%d", str, tag, posn.Column)
   385  		}
   386  		str = fmt.Sprintf("%s@%s", str, posn)
   387  	}
   388  	return str
   389  }
   390  
   391  func checkPointsToExpectation(e *expectation, pts pointer.PointsToSet, lineMapping map[string]string, prog *ssa.Program) bool {
   392  	expected := make(map[string]int)
   393  	surplus := make(map[string]int)
   394  	exact := true
   395  	for _, g := range e.args {
   396  		if g == "..." {
   397  			exact = false
   398  			continue
   399  		}
   400  		expected[g]++
   401  	}
   402  	// Find the set of labels that the probe's
   403  	// argument (x in print(x)) may point to.
   404  	for _, label := range pts.Labels() {
   405  		name := labelString(label, lineMapping, prog)
   406  		if expected[name] > 0 {
   407  			expected[name]--
   408  		} else if exact {
   409  			surplus[name]++
   410  		}
   411  	}
   412  	// Report multiset difference:
   413  	ok := true
   414  	for _, count := range expected {
   415  		if count > 0 {
   416  			ok = false
   417  			e.errorf("value does not alias these expected labels: %s", join(expected))
   418  			break
   419  		}
   420  	}
   421  	for _, count := range surplus {
   422  		if count > 0 {
   423  			ok = false
   424  			e.errorf("value may additionally alias these labels: %s", join(surplus))
   425  			break
   426  		}
   427  	}
   428  	return ok
   429  }
   430  
   431  func checkTypesExpectation(e *expectation, pts pointer.PointsToSet, typ types.Type) bool {
   432  	var expected typeutil.Map
   433  	var surplus typeutil.Map
   434  	exact := true
   435  	for _, g := range e.types {
   436  		if g == types.Typ[types.Invalid] {
   437  			exact = false
   438  			continue
   439  		}
   440  		expected.Set(g, struct{}{})
   441  	}
   442  
   443  	if !pointer.CanHaveDynamicTypes(typ) {
   444  		e.errorf("@types expectation requires an interface- or reflect.Value-typed operand, got %s", typ)
   445  		return false
   446  	}
   447  
   448  	// Find the set of types that the probe's
   449  	// argument (x in print(x)) may contain.
   450  	for _, T := range pts.DynamicTypes().Keys() {
   451  		if expected.At(T) != nil {
   452  			expected.Delete(T)
   453  		} else if exact {
   454  			surplus.Set(T, struct{}{})
   455  		}
   456  	}
   457  	// Report set difference:
   458  	ok := true
   459  	if expected.Len() > 0 {
   460  		ok = false
   461  		e.errorf("interface cannot contain these types: %s", expected.KeysString())
   462  	}
   463  	if surplus.Len() > 0 {
   464  		ok = false
   465  		e.errorf("interface may additionally contain these types: %s", surplus.KeysString())
   466  	}
   467  	return ok
   468  }
   469  
   470  var errOK = errors.New("OK")
   471  
   472  func checkCallsExpectation(prog *ssa.Program, e *expectation, cg *callgraph.Graph) bool {
   473  	found := make(map[string]int)
   474  	err := callgraph.GraphVisitEdges(cg, func(edge *callgraph.Edge) error {
   475  		// Name-based matching is inefficient but it allows us to
   476  		// match functions whose names that would not appear in an
   477  		// index ("<root>") or which are not unique ("func@1.2").
   478  		if edge.Caller.Func.String() == e.args[0] {
   479  			calleeStr := edge.Callee.Func.String()
   480  			if calleeStr == e.args[1] {
   481  				return errOK // expectation satisified; stop the search
   482  			}
   483  			found[calleeStr]++
   484  		}
   485  		return nil
   486  	})
   487  	if err == errOK {
   488  		return true
   489  	}
   490  	if len(found) == 0 {
   491  		e.errorf("didn't find any calls from %s", e.args[0])
   492  	}
   493  	e.errorf("found no call from %s to %s, but only to %s",
   494  		e.args[0], e.args[1], join(found))
   495  	return false
   496  }
   497  
   498  func checkWarningExpectation(prog *ssa.Program, e *expectation, warnings []pointer.Warning) bool {
   499  	// TODO(adonovan): check the position part of the warning too?
   500  	re, err := regexp.Compile(e.args[0])
   501  	if err != nil {
   502  		e.errorf("invalid regular expression in @warning expectation: %s", err.Error())
   503  		return false
   504  	}
   505  
   506  	if len(warnings) == 0 {
   507  		e.errorf("@warning %s expectation, but no warnings", strconv.Quote(e.args[0]))
   508  		return false
   509  	}
   510  
   511  	for _, w := range warnings {
   512  		if re.MatchString(w.Message) {
   513  			return true
   514  		}
   515  	}
   516  
   517  	e.errorf("@warning %s expectation not satised; found these warnings though:", strconv.Quote(e.args[0]))
   518  	for _, w := range warnings {
   519  		fmt.Printf("%s: warning: %s\n", prog.Fset.Position(w.Pos), w.Message)
   520  	}
   521  	return false
   522  }
   523  
   524  func TestInput(t *testing.T) {
   525  	ok := true
   526  
   527  	wd, err := os.Getwd()
   528  	if err != nil {
   529  		t.Errorf("os.Getwd: %s", err)
   530  		return
   531  	}
   532  
   533  	// 'go test' does a chdir so that relative paths in
   534  	// diagnostics no longer make sense relative to the invoking
   535  	// shell's cwd.  We print a special marker so that Emacs can
   536  	// make sense of them.
   537  	fmt.Fprintf(os.Stderr, "Entering directory `%s'\n", wd)
   538  
   539  	for _, filename := range inputs {
   540  		content, err := ioutil.ReadFile(filename)
   541  		if err != nil {
   542  			t.Errorf("couldn't read file '%s': %s", filename, err)
   543  			continue
   544  		}
   545  
   546  		if !doOneInput(string(content), filename) {
   547  			ok = false
   548  		}
   549  	}
   550  	if !ok {
   551  		t.Fail()
   552  	}
   553  }
   554  
   555  // join joins the elements of multiset with " | "s.
   556  func join(set map[string]int) string {
   557  	var buf bytes.Buffer
   558  	sep := ""
   559  	for name, count := range set {
   560  		for i := 0; i < count; i++ {
   561  			buf.WriteString(sep)
   562  			sep = " | "
   563  			buf.WriteString(name)
   564  		}
   565  	}
   566  	return buf.String()
   567  }
   568  
   569  // split returns the list of sep-delimited non-empty strings in s.
   570  func split(s, sep string) (r []string) {
   571  	for _, elem := range strings.Split(s, sep) {
   572  		elem = strings.TrimSpace(elem)
   573  		if elem != "" {
   574  			r = append(r, elem)
   575  		}
   576  	}
   577  	return
   578  }