|
12 | 12 | */ |
13 | 13 |
|
14 | 14 | import python |
15 | | -private import LegacyPointsTo |
| 15 | +private import semmle.python.dataflow.new.internal.DataFlowDispatch |
| 16 | +private import semmle.python.dataflow.new.internal.Builtins |
| 17 | +private import semmle.python.ApiGraphs |
16 | 18 |
|
17 | | -from Call call, ClassValue ex |
| 19 | +/** |
| 20 | + * Holds if `cls` is a user-defined exception class, i.e. it transitively |
| 21 | + * extends one of the builtin exception base classes. |
| 22 | + */ |
| 23 | +predicate isUserDefinedExceptionClass(Class cls) { |
| 24 | + cls.getABase() = |
| 25 | + API::builtin(["BaseException", "Exception"]).getAValueReachableFromSource().asExpr() |
| 26 | + or |
| 27 | + isUserDefinedExceptionClass(getADirectSuperclass(cls)) |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * Gets the name of a builtin exception class. |
| 32 | + */ |
| 33 | +string getBuiltinExceptionName() { |
| 34 | + result = Builtins::getBuiltinName() and |
| 35 | + ( |
| 36 | + result.matches("%Error") or |
| 37 | + result.matches("%Exception") or |
| 38 | + result.matches("%Warning") or |
| 39 | + result = |
| 40 | + ["GeneratorExit", "KeyboardInterrupt", "StopIteration", "StopAsyncIteration", "SystemExit"] |
| 41 | + ) |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Holds if `call` is an instantiation of an exception class. |
| 46 | + */ |
| 47 | +predicate isExceptionInstantiation(Call call) { |
| 48 | + exists(Class cls | |
| 49 | + classTracker(cls).asExpr() = call.getFunc() and |
| 50 | + isUserDefinedExceptionClass(cls) |
| 51 | + ) |
| 52 | + or |
| 53 | + call.getFunc() = API::builtin(getBuiltinExceptionName()).getAValueReachableFromSource().asExpr() |
| 54 | +} |
| 55 | + |
| 56 | +from Call call |
18 | 57 | where |
19 | | - call.getFunc().(ExprWithPointsTo).pointsTo(ex) and |
20 | | - ex.getASuperType() = ClassValue::exception() and |
| 58 | + isExceptionInstantiation(call) and |
21 | 59 | exists(ExprStmt s | s.getValue() = call) |
22 | 60 | select call, "Instantiating an exception, but not raising it, has no effect." |
0 commit comments