C++: Use the AllocationExpr model.

This commit is contained in:
Geoffrey White
2020-10-20 17:54:49 +01:00
parent 17ff34267a
commit 6d91d55669
2 changed files with 10 additions and 40 deletions

View File

@@ -13,25 +13,9 @@
*/
import cpp
import semmle.code.cpp.models.Models
class Allocation extends FunctionCall {
Allocation() { this.getTarget().hasGlobalOrStdName(["malloc", "calloc", "realloc"]) }
private string getName() { this.getTarget().hasGlobalOrStdName(result) }
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) {
predicate baseType(AllocationExpr alloc, Type base) {
exists(PointerType pointer |
pointer.getBaseType() = base and
(
@@ -49,11 +33,12 @@ predicate decideOnSize(Type t, int size) {
size = min(t.getSize())
}
from Allocation alloc, Type base, int basesize, int allocated
from AllocationExpr alloc, Type base, int basesize, int allocated
where
baseType(alloc, base) and
allocated = alloc.getSize() and
allocated = alloc.getSizeBytes() and
decideOnSize(base, basesize) and
alloc.(FunctionCall).getTarget() instanceof AllocationFunction and // exclude `new` and similar
basesize > allocated
select alloc,
"Type '" + base.getName() + "' is " + basesize.toString() + " bytes, but only " +

View File

@@ -13,25 +13,9 @@
*/
import cpp
import semmle.code.cpp.models.Models
class Allocation extends FunctionCall {
Allocation() { this.getTarget().hasGlobalOrStdName(["malloc", "calloc", "realloc"]) }
private string getName() { this.getTarget().hasGlobalOrStdName(result) }
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) {
predicate baseType(AllocationExpr alloc, Type base) {
exists(PointerType pointer |
pointer.getBaseType() = base and
(
@@ -49,11 +33,12 @@ predicate decideOnSize(Type t, int size) {
size = min(t.getSize())
}
from Allocation alloc, Type base, int basesize, int allocated
from AllocationExpr alloc, Type base, int basesize, int allocated
where
baseType(alloc, base) and
allocated = alloc.getSize() and
allocated = alloc.getSizeBytes() and
decideOnSize(base, basesize) and
alloc.(FunctionCall).getTarget() instanceof AllocationFunction and // exclude `new` and similar
// If the codebase has more than one type with the same name, check if any matches
not exists(int size | base.getSize() = size |
size = 0 or