-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathSizeCheck2.ql
More file actions
64 lines (59 loc) · 1.96 KB
/
SizeCheck2.ql
File metadata and controls
64 lines (59 loc) · 1.96 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
/**
* @name Not enough memory allocated for array of pointer type
* @description Calling 'malloc', 'calloc' or 'realloc' without allocating enough memory to contain
* multiple instances of the type of the pointer may result in a buffer overflow
* @kind problem
* @problem.severity warning
* @precision medium
* @id cpp/suspicious-allocation-size
* @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)
)
)
}
from Allocation alloc, Type base, int basesize, int allocated
where baseType(alloc, base)
and allocated = alloc.getSize()
// If the codebase has more than one type with the same name, check if any matches
and not exists(int size | base.getSize() = size |
size = 0
or (allocated / size) * size = allocated)
and basesize = min(base.getSize())
select alloc, "Allocated memory (" + allocated.toString() +
" bytes) is not a multiple of the size of '" +
base.getName() + "' (" + basesize.toString() + " bytes)."