@@ -33,9 +33,50 @@ class ArrayDeclaration extends VariableDeclarationEntry {
3333 Expr getInitExpr ( ) { result = this .getVariable ( ) .getInitializer ( ) .getExpr ( ) }
3434}
3535
36+ class HeapAllocationFunctionCall extends FunctionCall {
37+ AllocationFunction heapAllocFunction ;
38+
39+ HeapAllocationFunctionCall ( ) { this .getTarget ( ) = heapAllocFunction }
40+
41+ predicate isMallocCall ( ) { heapAllocFunction .getName ( ) = "malloc" }
42+
43+ predicate isCallocCall ( ) { heapAllocFunction .getName ( ) = "calloc" }
44+
45+ predicate isReallocCall ( ) { heapAllocFunction .getName ( ) = "realloc" }
46+
47+ abstract Expr getByteArgument ( ) ;
48+
49+ int getByteLowerBound ( ) { result = lowerBound ( this .getByteArgument ( ) ) }
50+ }
51+
52+ class MallocFunctionCall extends HeapAllocationFunctionCall {
53+ MallocFunctionCall ( ) { this .isMallocCall ( ) }
54+
55+ override Expr getByteArgument ( ) { result = this .getArgument ( 0 ) }
56+ }
57+
58+ class CallocReallocFunctionCall extends HeapAllocationFunctionCall {
59+ CallocReallocFunctionCall ( ) { this .isCallocCall ( ) or this .isReallocCall ( ) }
60+
61+ override Expr getByteArgument ( ) { result = this .getArgument ( 1 ) }
62+ }
63+
64+ class NarrowedHeapAllocationFunctionCall extends Cast {
65+ HeapAllocationFunctionCall alloc ;
66+
67+ NarrowedHeapAllocationFunctionCall ( ) { alloc = this .getExpr ( ) }
68+
69+ int getMinNumElements ( ) {
70+ result =
71+ alloc .getByteLowerBound ( ) / this .getUnderlyingType ( ) .( PointerType ) .getBaseType ( ) .getSize ( )
72+ }
73+
74+ HeapAllocationFunctionCall getAllocFunctionCall ( ) { result = alloc }
75+ }
76+
3677newtype TArrayAllocation =
3778 TStackAllocation ( ArrayDeclaration arrayDecl ) or
38- TDynamicAllocation ( AllocationFunction alloc )
79+ TDynamicAllocation ( NarrowedHeapAllocationFunctionCall narrowedAlloc )
3980
4081newtype TPointerFormation =
4182 TArrayExpr ( ArrayExprBA arrayExpr ) or
@@ -44,16 +85,20 @@ newtype TPointerFormation =
4485class ArrayAllocation extends TArrayAllocation {
4586 ArrayDeclaration asStackAllocation ( ) { this = TStackAllocation ( result ) }
4687
47- AllocationFunction asDynamicAllocation ( ) { this = TDynamicAllocation ( result ) }
88+ NarrowedHeapAllocationFunctionCall asDynamicAllocation ( ) { this = TDynamicAllocation ( result ) }
4889
4990 string toString ( ) {
5091 result = this .asStackAllocation ( ) .toString ( ) or
5192 result = this .asDynamicAllocation ( ) .toString ( )
5293 }
5394
95+ /**
96+ * Gets the number of the object that the array holds. This number is exact for a stack-allocated
97+ * array, and the minimum estimated value for a heap-allocated one.
98+ */
5499 int getLength ( ) {
55100 result = this .asStackAllocation ( ) .getLength ( ) or
56- none ( ) // TODO: this.asDynamicAllocation()
101+ result = this .asDynamicAllocation ( ) . getMinNumElements ( )
57102 }
58103
59104 Location getLocation ( ) {
0 commit comments