From 133df784a963a93b4d849f40200d6d71854e3efc Mon Sep 17 00:00:00 2001 From: Xavier Pinho Date: Fri, 24 Jan 2025 17:11:55 +0000 Subject: [PATCH] [c#] laxer extension method matching (#5253) --- .../datastructures/CSharpScope.scala | 5 ++++- .../querying/ast/ExtensionMethodTests.scala | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/joern-cli/frontends/csharpsrc2cpg/src/main/scala/io/joern/csharpsrc2cpg/datastructures/CSharpScope.scala b/joern-cli/frontends/csharpsrc2cpg/src/main/scala/io/joern/csharpsrc2cpg/datastructures/CSharpScope.scala index 88175c9275a6..bd1045876901 100644 --- a/joern-cli/frontends/csharpsrc2cpg/src/main/scala/io/joern/csharpsrc2cpg/datastructures/CSharpScope.scala +++ b/joern-cli/frontends/csharpsrc2cpg/src/main/scala/io/joern/csharpsrc2cpg/datastructures/CSharpScope.scala @@ -140,7 +140,10 @@ class CSharpScope(summary: CSharpProgramSummary) name: String, argTypes: List[String] ): CSharpMethod => Boolean = { m => - m.isStatic && m.name == name && m.parameterTypes.map(_._2) == thisType :: argTypes + // TODO: we should also compare argTypes, however we first need to account for: + // a) default valued parameters in CSharpMethod, to account for different arities + // b) compatible/sub types, i.e. System.String should unify with System.Object. + m.isStatic && m.name == name && m.parameterTypes.map(_._2).headOption.contains(thisType) } /** Tries to find an extension method for [[baseTypeFullName]] with the given [[callName]] and [[argTypes]] in the diff --git a/joern-cli/frontends/csharpsrc2cpg/src/test/scala/io/joern/csharpsrc2cpg/querying/ast/ExtensionMethodTests.scala b/joern-cli/frontends/csharpsrc2cpg/src/test/scala/io/joern/csharpsrc2cpg/querying/ast/ExtensionMethodTests.scala index 13f031fef575..a336ec5fc0fa 100644 --- a/joern-cli/frontends/csharpsrc2cpg/src/test/scala/io/joern/csharpsrc2cpg/querying/ast/ExtensionMethodTests.scala +++ b/joern-cli/frontends/csharpsrc2cpg/src/test/scala/io/joern/csharpsrc2cpg/querying/ast/ExtensionMethodTests.scala @@ -195,6 +195,22 @@ class ExtensionMethodTests extends CSharpCode2CpgFixture { cpg.call.nameExact("DoStuff").callee.l shouldBe cpg.literal("2").method.l } + + "resolve correctly if the extra argument is type-compatible with the extension method's extra parameter" in { + val cpg = code(""" + |using System.Collections.Generic; + | + |var x = new List(); + |x.DoStuff(null); + | + |static class Extensions + |{ + | public static int DoStuff(this List myList, object x) { return 2; } + |} + |""".stripMargin) + + cpg.call.nameExact("DoStuff").callee.l shouldBe cpg.literal("2").method.l + } } "consecutive unary extension method calls" should {