Skip to content

Commit

Permalink
internal/symbols: compute db symbol name from ast.FuncDecl
Browse files Browse the repository at this point in the history
This is part of a series of CLs implementing automatic symbol extraction.

Change-Id: I4028ef7d1938644684a06a0971a05a7acbbb93b2
Reviewed-on: https://go-review.googlesource.com/c/vulndb/+/535295
Run-TryBot: Zvonimir Pavlinovic <[email protected]>
TryBot-Result: Gopher Robot <[email protected]>
Reviewed-by: Tatiana Bradley <[email protected]>
  • Loading branch information
zpavlinovic committed Oct 13, 2023
1 parent 923d873 commit b64e791
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
32 changes: 32 additions & 0 deletions internal/symbols/patched_functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ package main

import (
"errors"
"fmt"
"go/ast"
"io/fs"
"os"
"path"
"path/filepath"
"reflect"
"strings"

"golang.org/x/mod/modfile"
Expand Down Expand Up @@ -162,3 +165,32 @@ func packageImportPath(module, moduleRoot, pkgPath string) string {
rel = filepath.ToSlash(rel) // cross platform
return path.Join(module, rel)
}

// symbolName returns the name of f as a symbol in
// a vulnerability database.
func symbolName(f *ast.FuncDecl) string {
name := f.Name.Name
if f.Recv == nil || len(f.Recv.List) == 0 {
return name
}
field := f.Recv.List[0]
if len(field.Names) == 0 {
return "" // sanity
}

t := ""
switch xv := field.Type.(type) {
case *ast.StarExpr:
if si, ok := xv.X.(*ast.Ident); ok {
t = si.Name
}
case *ast.Ident:
t = xv.Name
case *ast.IndexExpr:
// TODO(#63535): cover index instructions stemming from generics
return ""
default:
panic(fmt.Sprintf("symbolName: unexpected receiver type: %v\n", reflect.TypeOf(field.Type)))
}
return t + "." + name
}
34 changes: 34 additions & 0 deletions internal/symbols/patched_functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
package main

import (
"go/ast"
"go/parser"
"go/token"
"path/filepath"
"sort"
"testing"
Expand Down Expand Up @@ -80,3 +83,34 @@ func TestPackageImportPath(t *testing.T) {
}
}
}

func TestSymbolName(t *testing.T) {
src := `
package p
func Foo() {}
type A struct {}
func (a A) Do() {}
type B struct {}
func (b *B) Do() {}
`
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, 0)
if err != nil {
t.Error(err)
}

var got []string
for _, decl := range f.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok {
got = append(got, symbolName(fn))
}
}
sort.Strings(got)
want := []string{"A.Do", "B.Do", "Foo"}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("(-got, want+):\n%s", diff)
}
}

0 comments on commit b64e791

Please sign in to comment.