|
| 1 | +/** |
| 2 | + * @name Prefix or suffix predicate calls when comparing with literal |
| 3 | + * @description Using 'myString.prefix(n) = "..."' instead of 'myString.matches("...%")' |
| 4 | + * @kind problem |
| 5 | + * @problem.severity error |
| 6 | + * @id ql/prefix-or-suffix-equality-check |
| 7 | + * @tags performance |
| 8 | + * @precision high |
| 9 | + */ |
| 10 | + |
| 11 | +import ql |
| 12 | +import codeql_ql.ast.internal.Predicate |
| 13 | + |
| 14 | +class StringClass extends PrimitiveType { |
| 15 | + StringClass() { this.getName() = "string" } |
| 16 | +} |
| 17 | + |
| 18 | +class PrefixPredicate extends BuiltinPredicate { |
| 19 | + PrefixPredicate() { this = any(StringClass sc).getClassPredicate("prefix", 1) } |
| 20 | +} |
| 21 | + |
| 22 | +class SuffixPredicate extends BuiltinPredicate { |
| 23 | + SuffixPredicate() { this = any(StringClass sc).getClassPredicate("suffix", 1) } |
| 24 | +} |
| 25 | + |
| 26 | +class PrefixPredicateCall extends Call { |
| 27 | + PrefixPredicateCall() { this.getTarget() instanceof PrefixPredicate } |
| 28 | +} |
| 29 | + |
| 30 | +class SuffixPredicateCall extends Call { |
| 31 | + SuffixPredicateCall() { this.getTarget() instanceof SuffixPredicate } |
| 32 | +} |
| 33 | + |
| 34 | +class EqFormula extends ComparisonFormula { |
| 35 | + EqFormula() { this.getSymbol() = "=" } |
| 36 | +} |
| 37 | + |
| 38 | +pragma[inline] |
| 39 | +string getMessage(Call call, String literal) { |
| 40 | + call instanceof PrefixPredicateCall and result = ".matches(\"" + literal.getValue() + "%\")" |
| 41 | + or |
| 42 | + call instanceof SuffixPredicateCall and result = ".matches(\"%" + literal.getValue() + "\")" |
| 43 | +} |
| 44 | + |
| 45 | +from EqFormula eq, PrefixPredicateCall call, String literal |
| 46 | +where eq.getAnOperand() = call and eq.getAnOperand() = literal |
| 47 | +select eq, |
| 48 | + "Use " + getMessage(call, literal) + " instead (but be sure to escape " + literal.getValue() + |
| 49 | + ")." |
0 commit comments