1 // Copyright 2020 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.
5 // Package framepointer defines an Analyzer that reports assembly code
6 // that clobbers the frame pointer before saving it.
14 "golang.org/x/tools/go/analysis"
15 "golang.org/x/tools/go/analysis/passes/internal/analysisutil"
18 const Doc = "report assembly that clobbers the frame pointer before saving it"
20 var Analyzer = &analysis.Analyzer{
27 re = regexp.MustCompile
28 asmWriteBP = re(`,\s*BP$`) // TODO: can have false positive, e.g. for TESTQ BP,BP. Seems unlikely.
29 asmMentionBP = re(`\bBP\b`)
30 asmControlFlow = re(`^(J|RET)`)
33 func run(pass *analysis.Pass) (interface{}, error) {
34 if build.Default.GOARCH != "amd64" { // TODO: arm64 also?
37 if build.Default.GOOS != "linux" && build.Default.GOOS != "darwin" {
41 // Find assembly files to work on.
43 for _, fname := range pass.OtherFiles {
44 if strings.HasSuffix(fname, ".s") {
45 sfiles = append(sfiles, fname)
49 for _, fname := range sfiles {
50 content, tf, err := analysisutil.ReadFile(pass.Fset, fname)
55 lines := strings.SplitAfter(string(content), "\n")
57 for lineno, line := range lines {
60 // Ignore comments and commented-out code.
61 if i := strings.Index(line, "//"); i >= 0 {
64 line = strings.TrimSpace(line)
66 // We start checking code at a TEXT line for a frameless function.
67 if strings.HasPrefix(line, "TEXT") && strings.Contains(line, "(SB)") && strings.Contains(line, "$0") {
75 if asmWriteBP.MatchString(line) { // clobber of BP, function is not OK
76 pass.Reportf(analysisutil.LineStart(tf, lineno), "frame pointer is clobbered before saving")
80 if asmMentionBP.MatchString(line) { // any other use of BP might be a read, so function is OK
84 if asmControlFlow.MatchString(line) { // give up after any branch instruction