integrated-application-development / sonar-delphi

Delphi language plugin for SonarQube
GNU Lesser General Public License v3.0
104 stars 16 forks source link

New rule: Class instance variables should not be passed as an interface parameter #99

Open fourls opened 11 months ago

fourls commented 11 months ago

Prerequisites

Suggested rule title

Class instance variables should not be passed as an interface parameter

Rule description

This rule picks up cases where a variable containing an object instance (e.g. TObject) is passed to a routine that expects an interface (e.g. IInterface). The interface reference causes the object to be reference counted and freed at the end of the routine, meaning that the variable is pointing to freed memory when control is returned to the calling code.

type
  IFooIntf = interface
  end;

  TFooImpl = class(TInterfacedObject, IFooIntf)
  end;

procedure DoThing(Foo: IFooIntf);
begin
  // ...
end;

procedure Run;
var
  FooImpl: TFooImpl;
begin
  FooImpl := TFooImpl.Create;
  DoThing(FooImpl); // Noncompliant - performs reference counting and destroys object before returning control
  FooImpl.Free; // This will cause a double free
end;

Rationale

This is a common "gotcha" as it is a frequent pattern in other languages. It is also a statically verifiable case in which access violations are likely.

Cirras commented 11 months ago

This is an unintuitive "gotcha" that I agree should be covered by a rule. 👍