|
12 | 12 |
|
13 | 13 | import cpp |
14 | 14 | import codingstandards.c.misra |
| 15 | +import semmle.code.cpp.dataflow.DataFlow |
15 | 16 |
|
16 | | -from |
| 17 | +/** |
| 18 | + * Models a function parameter of type array with specified size |
| 19 | + * ``` |
| 20 | + * void f1(int ar[3]); |
| 21 | + * ``` |
| 22 | + */ |
| 23 | +class ArrayParameter extends Parameter { |
| 24 | + ArrayParameter() { this.getType().(ArrayType).hasArraySize() } |
| 25 | + |
| 26 | + Expr getAMatchingArgument() { |
| 27 | + exists(FunctionCall fc | |
| 28 | + this.getFunction() = fc.getTarget() and |
| 29 | + result = fc.getArgument(this.getIndex()) |
| 30 | + ) |
| 31 | + } |
| 32 | + |
| 33 | + int getArraySize() { result = this.getType().(ArrayType).getArraySize() } |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * The number of initialized elements in an ArrayAggregateLiteral. |
| 38 | + * In the following examples the result=2 |
| 39 | + * ``` |
| 40 | + * int arr3[3] = {1, 2}; |
| 41 | + * int arr2[2] = {1, 2, 3}; |
| 42 | + * ``` |
| 43 | + */ |
| 44 | +int countElements(ArrayAggregateLiteral l) { result = count(l.getElementExpr(_)) } |
| 45 | + |
| 46 | +class SmallArrayConfig extends DataFlow::Configuration { |
| 47 | + SmallArrayConfig() { this = "SmallArrayConfig" } |
| 48 | + |
| 49 | + override predicate isSource(DataFlow::Node src) { src.asExpr() instanceof ArrayAggregateLiteral } |
| 50 | + |
| 51 | + override predicate isSink(DataFlow::Node sink) { |
| 52 | + sink.asExpr() = any(ArrayParameter p).getAMatchingArgument() |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +from Expr arg, ArrayParameter p |
17 | 57 | where |
18 | | - not isExcluded(x, Contracts6Package::arrayFunctionArgumentNumberOfElementsQuery()) and |
19 | | -select |
| 58 | + not isExcluded(arg, Contracts6Package::arrayFunctionArgumentNumberOfElementsQuery()) and |
| 59 | + exists(SmallArrayConfig config | arg = p.getAMatchingArgument() | |
| 60 | + // the argument is a value and not an arrey |
| 61 | + not arg.getType() instanceof DerivedType |
| 62 | + or |
| 63 | + // the argument is an array too small |
| 64 | + arg.getType().(ArrayType).getArraySize() < p.getArraySize() |
| 65 | + or |
| 66 | + // the argument is a pointer and its value does not come from a literal of the correct |
| 67 | + arg.getType() instanceof PointerType and |
| 68 | + not exists(ArrayAggregateLiteral l | |
| 69 | + config.hasFlow(DataFlow::exprNode(l), DataFlow::exprNode(arg)) and |
| 70 | + countElements(l) >= p.getArraySize() |
| 71 | + ) |
| 72 | + ) |
| 73 | +select arg, |
| 74 | + "The function argument does not have a sufficient number or elements declared in the $@.", p, |
| 75 | + "parameter" |
0 commit comments