forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSizeCheck.ql
More file actions
66 lines (60 loc) · 1.91 KB
/
SizeCheck.ql
File metadata and controls
66 lines (60 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @name Not enough memory allocated for pointer type
* @description Calling 'malloc', 'calloc' or 'realloc' without allocating enough memory to contain
* an instance of the type of the pointer may result in a buffer overflow
* @kind problem
* @problem.severity warning
* @precision medium
* @id cpp/allocation-too-small
* @tags reliability
* security
* external/cwe/cwe-131
* external/cwe/cwe-122
*/
import cpp
class Allocation extends FunctionCall
{
Allocation() {
exists(string name |
this.getTarget().hasQualifiedName(name) and
(name = "malloc" or name = "calloc" or name = "realloc"))
}
string getName() { result = this.getTarget().getQualifiedName() }
int getSize() {
(this.getName() = "malloc" and
this.getArgument(0).getValue().toInt() = result)
or
(this.getName() = "realloc" and
this.getArgument(1).getValue().toInt() = result)
or
(this.getName() = "calloc" and
result =
this.getArgument(0).getValue().toInt() *
this.getArgument(1).getValue().toInt())
}
}
predicate baseType(Allocation alloc, Type base)
{
exists(PointerType pointer |
pointer.getBaseType() = base and
(
exists(AssignExpr assign |
assign.getRValue() = alloc and assign.getLValue().getType() = pointer)
or
exists(Variable v |
v.getInitializer().getExpr() = alloc and v.getType() = pointer)
)
)
}
predicate decideOnSize(Type t, int size)
{
// If the codebase has more than one type with the same name, it can have more than one size.
size = min(t.getSize())
}
from Allocation alloc, Type base, int basesize, int allocated
where baseType(alloc, base)
and allocated = alloc.getSize()
and decideOnSize(base, basesize)
and basesize > allocated
select alloc, "Type '" + base.getName() + "' is " + basesize.toString() +
" bytes, but only " + allocated.toString() + " bytes are allocated."