From a11eb28e2fc572c2494813730205376d33d2d051 Mon Sep 17 00:00:00 2001 From: Cosmin Cojocar Date: Thu, 12 Oct 2023 10:01:41 +0200 Subject: [PATCH] Handle new function when getting the call info in case is overriden Signed-off-by: Cosmin Cojocar --- helpers.go | 2 +- helpers_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/helpers.go b/helpers.go index c7bcd51d12..15b2b5f3a3 100644 --- a/helpers.go +++ b/helpers.go @@ -183,7 +183,7 @@ func GetCallInfo(n ast.Node, ctx *Context) (string, string, error) { case *ast.CallExpr: switch call := expr.Fun.(type) { case *ast.Ident: - if call.Name == "new" { + if call.Name == "new" && len(expr.Args) > 0 { t := ctx.Info.TypeOf(expr.Args[0]) if t != nil { return t.String(), fn.Sel.Name, nil diff --git a/helpers_test.go b/helpers_test.go index 7c7c71fe40..cd01216596 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -251,6 +251,38 @@ var _ = Describe("Helpers", func() { Expect(result).Should(HaveKeyWithValue("fmt", "Println")) }) + + It("should return the type and call name when built-in new function is overriden", func() { + pkg := testutils.NewTestPackage() + defer pkg.Close() + pkg.AddFile("main.go", ` + package main + + type S struct{ F int } + + func (f S) Fun() {} + + func new() S { return S{} } + + func main() { + new().Fun() + } + `) + ctx := pkg.CreateContext("main.go") + result := map[string]string{} + visitor := testutils.NewMockVisitor() + visitor.Context = ctx + visitor.Callback = func(n ast.Node, ctx *gosec.Context) bool { + typeName, call, err := gosec.GetCallInfo(n, ctx) + if err == nil { + result[typeName] = call + } + return true + } + ast.Walk(visitor, ctx.Root) + + Expect(result).Should(HaveKeyWithValue("main", "new")) + }) }) Context("when getting binary expression operands", func() { It("should return all operands of a binary expression", func() {