Skip to content

x/tools/go/analysis: request some form of static thread safety analysis for Go #46788

Open
@g-talbot

Description

@g-talbot

In issue #24889 there's a short paragraph about static thread safety analysis that clang does for C++ programs:

clang supports thread safety analysis for C++ (https://clang.llvm.org/docs/ThreadSafetyAnalysis.html) based on annotations in the source code. This would clearly be applicable to Go code.

I'm pretty agnostic as to how some form of static thread safety analysis enters the Go ecosystem, but I would like to have it. I've used this at a previous employer (Google) to great effect, and IMO it would be of great benefit to Go programs as well.

Here's a strawman proposal, more to spur discussion than be a "real" solution. What if a struct is defined with a lock in it like so:

type MyStruct struct {
  sync.Mutex

  field1 int
  field2 string
  field3 []string
}

Let's annotate MyStruct to require locking on all of its members:

//go: guarded
type MyStruct struct {
  sync.RWMutex

  // by having //go: guarded above this implies that MyStruct must be locked
  // to access the members.  Reads of any of the fields would require RLock() and
  // writes would require Lock().
  field1 int
  field2 string
  field3 []string
}

So if I defined a function that accessed the members and didn't lock, compilation would fail:

func (m *MyStruct) GetField1() int {
  return m.field1 // does not compile
}

But this would work:

func (m *MyStruct) GetField1() int {
  m.RLock()
  defer m.RUnlock()
  return m.field1
}

And this too:

func (m *MyStruct) GetField1() int {
  m.RLock()
  defer m.RUnlock()
  return m.GetField1WithLock()
}

//go: with-rlock: m
func (m *MyStruct) GetField1WithRLock() int {
  return m.field1
}

I know folks don't love the comment pragmas, but I didn't have a better idea. Perhaps the basic gist of tying the lock to a specific struct that there could be some way that's "neater" and "more go like" than the complex clang annotations? With anonymous struct fields making for clean composition?

Metadata

Metadata

Assignees

No one assigned

    Labels

    AnalysisIssues related to static analysis (vet, x/tools/go/analysis)FeatureRequestIssues asking for a new feature that does not need a proposal.NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.ToolsThis label describes issues relating to any tools in the x/tools repository.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions