CodeQL学习记录(一)
记录官方教学语法题的答案
1 Find the thief
根据下述问题描述找出小偷
难点在于9、10、11的聚合
语句
Question | Answer | |
---|---|---|
1 | Is the thief taller than 150 cm? | yes |
2 | Does the thief have blond hair? | no |
3 | Is the thief bald? | no |
4 | Is the thief younger than 30? | no |
5 | Does the thief live east of the castle? | yes |
6 | Does the thief have black or brown hair? | yes |
7 | Is the thief taller than 180cm and shorter than 190cm? | no |
8 | Is the thief the oldest person in the village? | no |
9 | Is the thief the tallest person in the village? | no |
10 | Is the thief shorter than the average villager? | yes |
11 | Is the thief the oldest person in the eastern part of the village? | yes |
import java
import tutorial
from Person t
where t.getHeight() > 150 and
not t.getHairColor() = "blond" and
exists(string c | t.getHairColor() =c) and
t.getAge() > 30 and
t.getLocation() = "east" and
(t.getHairColor() = "black" or t.getHairColor() = "brown") and
not (t.getHeight() > 180 and t.getHeight() < 190) and
exists(Person p | p.getAge() > t.getAge()) and
not t = max(Person p||p order by p.getHeight()) and
t.getHeight() < avg(Person p||p.getHeight()) and
t = max(Person p|p.getLocation()="east"|p order by p.getAge())
select t
2.catch the fire starter
筛选的条件不太复杂:肇事者是南方人,光头,而且能够去北方旅行(不是十岁以下的儿童)
官方教程通过这个例子展现CodeQL中predicate
谓词(有点像函数)和定义class
的用法
类的用法和通常的面向对象编程有相当大的区别
import java
import tutorial
predicate isSouth(Person p){
p.getLocation() = "south"
}
predicate isBald(Person p){
not exists (string c|p.getHairColor() = c)
}
class Southerner extends Person{
Southerner(){isSouth(this)}
}
class Child extends Person{
Child(){this.getAge()<10}
override predicate isAllowedIn(string region){ region = this.getLocation()}
}
from Southerner s
where s.isAllowedIn("north") and isBald(s)
select s
3.Crown the rightful heir
这一章节的内容也是难点:谓词predicate
、递归、传递闭包
import tutorial
Person relativeOf(Person p) { parentOf*(result) = parentOf*(p) }
predicate hasCriminalRecord(Person p) {
p = "Hester" or
p = "Hugh" or
p = "Charlie"
}
from Person p
where
not p.isDeceased() and
p = relativeOf("King Basil") and
not hasCriminalRecord(p)
select p
课后习题
https://www.jianshu.com/p/f141c6c85c1d%20