https://codeql.github.com/docs/codeql-language-guides/types-in-java/
CodeQL中提供了Type类以及子类,来表示Java中的各种类型
PrimitiveType类用来表示Java中所有的主数据类型,例如boolean、int
RefType类用来表示Java中所有的引用类型,例如Array、字符串
RefType类提供了两个成员谓词getASupertype和getASubtype来查找该引用类型对应的超类和子类。
class A {}
interface I {}
class B extends A implements I {}
如上所示:A的超类是java.lang.Object,子类是B;B的超类有A和I,没有子类。
代码示例
获取B类所有的超类
import java
from Class B
where B.hasName("B")
select B.getASupertype+()
类型转换
import java
from CastExpr ce, Array source, Array target
where source = ce.getExpr().getType() and
target = ce.getType() and
target.getElementType().(RefType).getASupertype+() = source.getElementType()
select ce, "Potentially problematic array downcast."
Array类的成员谓词getElementType可以获得该数组中元素的数据类型,result是Type类型的
Type Array::getElementType()
在第6行中,将Type类型向下转换为RefType类型,然后调用RefType类的成员谓词getASupertype
target.getElementType().(RefType).getASupertype+()
标识方法
Java支持重载,可以通过限制形参的数据类型来标识固定的某个方法
代码示例
标识java.util.Collection.contains(Object)方法
class JavaUtilCollection extends GenericInterface {
JavaUtilCollection() {
this.hasQualifiedName("java.util", "Collection")
}
}
class JavaUtilCollectionContains extends Method {
JavaUtilCollectionContains() {
this.getDeclaringType() instanceof JavaUtilCollection and
this.hasStringSignature("contains(Object)")
}
}
如上所示的hasStringSignature谓词有如下作用:
1、限制方法名为contains,可以使用谓词hasName来替代
2、限制参数为1个,可以使用谓词getNumberOfParameters来替代
3、限制参数的类型是Object类型,可以使用如下方式来替代
getParameter(0).getType() instanceof TypeObject.
常用类型标识
TypeString 用来表示数据类型是 java.lang.String
代码示例
import java
from Parameter p
where p.getType() instanceof TypeString
select p
BoxedType