|
| 1 | +/** |
| 2 | + * @name `__init__` method calls overridden method |
| 3 | + * @description Calling a method from `__init__` that is overridden by a subclass may result in a partially |
| 4 | + * initialized instance being observed. |
| 5 | + * @kind problem |
| 6 | + * @tags reliability |
| 7 | + * correctness |
| 8 | + * quality |
| 9 | + * @problem.severity warning |
| 10 | + * @sub-severity low |
| 11 | + * @precision high |
| 12 | + * @id py/init-calls-subclass |
| 13 | + */ |
| 14 | + |
| 15 | +import python |
| 16 | +import semmle.python.dataflow.new.DataFlow |
| 17 | +import semmle.python.dataflow.new.internal.DataFlowDispatch |
| 18 | + |
| 19 | +predicate initSelfCallOverridden( |
| 20 | + Function init, DataFlow::Node self, DataFlow::MethodCallNode call, Function target, |
| 21 | + Function override |
| 22 | +) { |
| 23 | + init.isInitMethod() and |
| 24 | + call.getScope() = init and |
| 25 | + exists(Class superclass, Class subclass, DataFlow::ParameterNode selfArg | |
| 26 | + superclass = init.getScope() and |
| 27 | + subclass = override.getScope() and |
| 28 | + subclass = getADirectSubclass+(superclass) and |
| 29 | + selfArg.getParameter() = init.getArg(0) and |
| 30 | + DataFlow::localFlow(selfArg, self) and |
| 31 | + call.calls(self, override.getName()) and |
| 32 | + target = superclass.getAMethod() and |
| 33 | + target.getName() = override.getName() |
| 34 | + ) |
| 35 | +} |
| 36 | + |
| 37 | +predicate readsFromSelf(Function method) { |
| 38 | + exists(DataFlow::ParameterNode self, DataFlow::Node sink | |
| 39 | + self.getParameter() = method.getArg(0) and |
| 40 | + DataFlow::localFlow(self, sink) |
| 41 | + | |
| 42 | + sink instanceof DataFlow::ArgumentNode |
| 43 | + or |
| 44 | + sink = any(DataFlow::AttrRead a).getObject() |
| 45 | + ) |
| 46 | +} |
| 47 | + |
| 48 | +from |
| 49 | + Function init, DataFlow::Node self, DataFlow::MethodCallNode call, Function target, |
| 50 | + Function override |
| 51 | +where |
| 52 | + initSelfCallOverridden(init, self, call, target, override) and |
| 53 | + readsFromSelf(override) and |
| 54 | + not isClassmethod(override) and |
| 55 | + not isStaticmethod(override) and |
| 56 | + not target.getName().matches("\\_%") |
| 57 | +select call, "This call to $@ in an initialization method is overridden by $@.", target, |
| 58 | + target.getQualifiedName(), override, override.getQualifiedName() |
0 commit comments