|
14 | 14 | import python |
15 | 15 | import semmle.python.dataflow.new.DataFlow |
16 | 16 | private import semmle.python.dataflow.new.internal.DataFlowDispatch |
| 17 | +private import semmle.python.ApiGraphs |
17 | 18 |
|
18 | 19 | predicate rhs_in_expr(Expr rhs, Compare cmp) { |
19 | 20 | exists(Cmpop op, int i | cmp.getOp(i) = op and cmp.getComparator(i) = rhs | |
@@ -42,6 +43,35 @@ predicate hasDynamicMethods(Class cls) { |
42 | 43 | ) |
43 | 44 | } |
44 | 45 |
|
| 46 | +/** |
| 47 | + * Holds if `cls_arg` references a known container builtin type, either directly |
| 48 | + * or as an element of a tuple. |
| 49 | + */ |
| 50 | +private predicate isContainerTypeArg(DataFlow::Node cls_arg) { |
| 51 | + cls_arg = |
| 52 | + API::builtin(["list", "tuple", "set", "frozenset", "dict", "str", "bytes", "bytearray"]) |
| 53 | + .getAValueReachableFromSource() |
| 54 | + or |
| 55 | + isContainerTypeArg(DataFlow::exprNode(cls_arg.asExpr().(Tuple).getAnElt())) |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Holds if `rhs` is guarded by an `isinstance` check that tests for |
| 60 | + * a container type. |
| 61 | + */ |
| 62 | +predicate guardedByIsinstanceContainer(DataFlow::Node rhs) { |
| 63 | + exists( |
| 64 | + DataFlow::GuardNode guard, DataFlow::CallCfgNode isinstance_call, DataFlow::LocalSourceNode src |
| 65 | + | |
| 66 | + isinstance_call = API::builtin("isinstance").getACall() and |
| 67 | + src.flowsTo(isinstance_call.getArg(0)) and |
| 68 | + src.flowsTo(rhs) and |
| 69 | + isContainerTypeArg(isinstance_call.getArg(1)) and |
| 70 | + guard = isinstance_call.asCfgNode() and |
| 71 | + guard.controlsBlock(rhs.asCfgNode().getBasicBlock(), true) |
| 72 | + ) |
| 73 | +} |
| 74 | + |
45 | 75 | from Compare cmp, DataFlow::LocalSourceNode origin, DataFlow::Node rhs, Class cls |
46 | 76 | where |
47 | 77 | origin = classInstanceTracker(cls) and |
|
50 | 80 | not DuckTyping::hasUnresolvedBase(getADirectSuperclass*(cls)) and |
51 | 81 | not isDecoratorApplication(origin) and |
52 | 82 | not hasDynamicMethods(cls) and |
| 83 | + not guardedByIsinstanceContainer(rhs) and |
53 | 84 | rhs_in_expr(rhs.asExpr(), cmp) |
54 | 85 | select cmp, "This test may raise an Exception as the $@ may be of non-container class $@.", origin, |
55 | 86 | "target", cls, cls.getName() |
0 commit comments