https://codeql.github.com/docs/codeql-language-guides/types-in-java/

CodeQL中提供了Type类以及子类,来表示Java中的各种类型

PrimitiveType类用来表示Java中所有的主数据类型,例如boolean、int
RefType类用来表示Java中所有的引用类型,例如Array、字符串

RefType类提供了两个成员谓词getASupertype和getASubtype来查找该引用类型对应的超类和子类。

  1. class A {}
  2. interface I {}
  3. class B extends A implements I {}

如上所示:A的超类是java.lang.Object,子类是B;B的超类有A和I,没有子类。
代码示例
获取B类所有的超类

  1. import java
  2. from Class B
  3. where B.hasName("B")
  4. select B.getASupertype+()

点击查看【processon】

类型转换

  1. import java
  2. from CastExpr ce, Array source, Array target
  3. where source = ce.getExpr().getType() and
  4. target = ce.getType() and
  5. target.getElementType().(RefType).getASupertype+() = source.getElementType()
  6. select ce, "Potentially problematic array downcast."

Array类的成员谓词getElementType可以获得该数组中元素的数据类型,result是Type类型的

  1. Type Array::getElementType()

在第6行中,将Type类型向下转换为RefType类型,然后调用RefType类的成员谓词getASupertype

  1. target.getElementType().(RefType).getASupertype+()

标识方法

Java支持重载,可以通过限制形参的数据类型来标识固定的某个方法
代码示例
标识java.util.Collection.contains(Object)方法

  1. class JavaUtilCollection extends GenericInterface {
  2. JavaUtilCollection() {
  3. this.hasQualifiedName("java.util", "Collection")
  4. }
  5. }
  1. class JavaUtilCollectionContains extends Method {
  2. JavaUtilCollectionContains() {
  3. this.getDeclaringType() instanceof JavaUtilCollection and
  4. this.hasStringSignature("contains(Object)")
  5. }
  6. }

如上所示的hasStringSignature谓词有如下作用:
1、限制方法名为contains,可以使用谓词hasName来替代
2、限制参数为1个,可以使用谓词getNumberOfParameters来替代
3、限制参数的类型是Object类型,可以使用如下方式来替代

  1. getParameter(0).getType() instanceof TypeObject.

常用类型标识

TypeString 用来表示数据类型是 java.lang.String

代码示例

  1. import java
  2. from Parameter p
  3. where p.getType() instanceof TypeString
  4. select p

BoxedType

image.png