Source file src/runtime/align_test.go

     1  // Copyright 2022 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 runtime_test
     6  
     7  import (
     8  	"bytes"
     9  	"go/ast"
    10  	"go/build"
    11  	"go/importer"
    12  	"go/parser"
    13  	"go/printer"
    14  	"go/token"
    15  	"go/types"
    16  	"os"
    17  	"regexp"
    18  	"runtime"
    19  	"strings"
    20  	"testing"
    21  )
    22  
    23  // Check that 64-bit fields on which we apply atomic operations
    24  // are aligned to 8 bytes. This can be a problem on 32-bit systems.
    25  func TestAtomicAlignment(t *testing.T) {
    26  	// Read the code making the tables above, to see which fields and
    27  	// variables we are currently checking.
    28  	checked := map[string]bool{}
    29  	x, err := os.ReadFile("./align_runtime_test.go")
    30  	if err != nil {
    31  		t.Fatalf("read failed: %v", err)
    32  	}
    33  	fieldDesc := map[int]string{}
    34  	r := regexp.MustCompile(`unsafe[.]Offsetof[(](\w+){}[.](\w+)[)]`)
    35  	matches := r.FindAllStringSubmatch(string(x), -1)
    36  	for i, v := range matches {
    37  		checked["field runtime."+v[1]+"."+v[2]] = true
    38  		fieldDesc[i] = v[1] + "." + v[2]
    39  	}
    40  	varDesc := map[int]string{}
    41  	r = regexp.MustCompile(`unsafe[.]Pointer[(]&(\w+)[)]`)
    42  	matches = r.FindAllStringSubmatch(string(x), -1)
    43  	for i, v := range matches {
    44  		checked["var "+v[1]] = true
    45  		varDesc[i] = v[1]
    46  	}
    47  
    48  	// Check all of our alignemnts. This is the actual core of the test.
    49  	for i, d := range runtime.AtomicFields {
    50  		if d%8 != 0 {
    51  			t.Errorf("field alignment of %s failed: offset is %d", fieldDesc[i], d)
    52  		}
    53  	}
    54  	for i, p := range runtime.AtomicVariables {
    55  		if uintptr(p)%8 != 0 {
    56  			t.Errorf("variable alignment of %s failed: address is %x", varDesc[i], p)
    57  		}
    58  	}
    59  
    60  	// The code above is the actual test. The code below attempts to check
    61  	// that the tables used by the code above are exhaustive.
    62  
    63  	// Parse the whole runtime package, checking that arguments of
    64  	// appropriate atomic operations are in the list above.
    65  	fset := token.NewFileSet()
    66  	m, err := parser.ParseDir(fset, ".", nil, 0)
    67  	if err != nil {
    68  		t.Fatalf("parsing runtime failed: %v", err)
    69  	}
    70  	pkg := m["runtime"] // Note: ignore runtime_test and main packages
    71  
    72  	// Filter files by those for the current architecture/os being tested.
    73  	fileMap := map[string]bool{}
    74  	for _, f := range buildableFiles(t, ".") {
    75  		fileMap[f] = true
    76  	}
    77  	var files []*ast.File
    78  	for fname, f := range pkg.Files {
    79  		if fileMap[fname] {
    80  			files = append(files, f)
    81  		}
    82  	}
    83  
    84  	// Call go/types to analyze the runtime package.
    85  	var info types.Info
    86  	info.Types = map[ast.Expr]types.TypeAndValue{}
    87  	conf := types.Config{Importer: importer.Default()}
    88  	_, err = conf.Check("runtime", fset, files, &info)
    89  	if err != nil {
    90  		t.Fatalf("typechecking runtime failed: %v", err)
    91  	}
    92  
    93  	// Analyze all atomic.*64 callsites.
    94  	v := Visitor{t: t, fset: fset, types: info.Types, checked: checked}
    95  	ast.Walk(&v, pkg)
    96  }
    97  
    98  type Visitor struct {
    99  	fset    *token.FileSet
   100  	types   map[ast.Expr]types.TypeAndValue
   101  	checked map[string]bool
   102  	t       *testing.T
   103  }
   104  
   105  func (v *Visitor) Visit(n ast.Node) ast.Visitor {
   106  	c, ok := n.(*ast.CallExpr)
   107  	if !ok {
   108  		return v
   109  	}
   110  	f, ok := c.Fun.(*ast.SelectorExpr)
   111  	if !ok {
   112  		return v
   113  	}
   114  	p, ok := f.X.(*ast.Ident)
   115  	if !ok {
   116  		return v
   117  	}
   118  	if p.Name != "atomic" {
   119  		return v
   120  	}
   121  	if !strings.HasSuffix(f.Sel.Name, "64") {
   122  		return v
   123  	}
   124  
   125  	a := c.Args[0]
   126  
   127  	// This is a call to atomic.XXX64(a, ...). Make sure a is aligned to 8 bytes.
   128  	// XXX = one of Load, Store, Cas, etc.
   129  	// The arg we care about the alignment of is always the first one.
   130  
   131  	if u, ok := a.(*ast.UnaryExpr); ok && u.Op == token.AND {
   132  		v.checkAddr(u.X)
   133  		return v
   134  	}
   135  
   136  	// Other cases there's nothing we can check. Assume we're ok.
   137  	v.t.Logf("unchecked atomic operation %s %v", v.fset.Position(n.Pos()), v.print(n))
   138  
   139  	return v
   140  }
   141  
   142  // checkAddr checks to make sure n is a properly aligned address for a 64-bit atomic operation.
   143  func (v *Visitor) checkAddr(n ast.Node) {
   144  	switch n := n.(type) {
   145  	case *ast.IndexExpr:
   146  		// Alignment of an array element is the same as the whole array.
   147  		v.checkAddr(n.X)
   148  		return
   149  	case *ast.Ident:
   150  		key := "var " + v.print(n)
   151  		if !v.checked[key] {
   152  			v.t.Errorf("unchecked variable %s %s", v.fset.Position(n.Pos()), key)
   153  		}
   154  		return
   155  	case *ast.SelectorExpr:
   156  		t := v.types[n.X].Type
   157  		if t == nil {
   158  			// Not sure what is happening here, go/types fails to
   159  			// type the selector arg on some platforms.
   160  			return
   161  		}
   162  		if p, ok := t.(*types.Pointer); ok {
   163  			// Note: we assume here that the pointer p in p.foo is properly
   164  			// aligned. We just check that foo is at a properly aligned offset.
   165  			t = p.Elem()
   166  		} else {
   167  			v.checkAddr(n.X)
   168  		}
   169  		if t.Underlying() == t {
   170  			v.t.Errorf("analysis can't handle unnamed type %s %v", v.fset.Position(n.Pos()), t)
   171  		}
   172  		key := "field " + t.String() + "." + n.Sel.Name
   173  		if !v.checked[key] {
   174  			v.t.Errorf("unchecked field %s %s", v.fset.Position(n.Pos()), key)
   175  		}
   176  	default:
   177  		v.t.Errorf("unchecked atomic address %s %v", v.fset.Position(n.Pos()), v.print(n))
   178  
   179  	}
   180  }
   181  
   182  func (v *Visitor) print(n ast.Node) string {
   183  	var b bytes.Buffer
   184  	printer.Fprint(&b, v.fset, n)
   185  	return b.String()
   186  }
   187  
   188  // buildableFiles returns the list of files in the given directory
   189  // that are actually used for the build, given GOOS/GOARCH restrictions.
   190  func buildableFiles(t *testing.T, dir string) []string {
   191  	ctxt := build.Default
   192  	ctxt.CgoEnabled = true
   193  	pkg, err := ctxt.ImportDir(dir, 0)
   194  	if err != nil {
   195  		t.Fatalf("can't find buildable files: %v", err)
   196  	}
   197  	return pkg.GoFiles
   198  }
   199  

View as plain text