Tidying up after constructor failure lazarus / 62-General ---------------------------------------------------------------------- MarkMLl · 2022-01-30 12:12 If a (class instance) constructor is intentionally aborted using fail, is a finally block run if present (the documentation says "exit at once", please can somebody confirm) and if so can the finalisation code determine that nil is being returned? I've got a scenario where a constructor is doing some basic hardware tests, e.g. opening a GPIO chip (via the gpiod library) and requesting that the line be reserved as output. If this isn't properly released then a second attempt won't work (and there might be resources lost due to unclosed handles of various kinds). MarkMLl ---------------------------------------------------------------------- Thaddy · 2022-01-30 12:19 You are talking about just the constructor? The behavior is documented. https://www.freepascal.org/docs-html/current/ref/refse32.html ---------------------------------------------------------------------- MarkMLl · 2022-01-30 13:04 Quote from: Thaddy on January 30, 2022, 01:19:43 pmYou are talking about just the constructor? The behavior is documented. https://www.freepascal.org/docs-html/current/ref/refse32.html I'm referring to (creation of) instances of classes, and I see no reference to fail on that page. I think https://www.freepascal.org/docs- html/current/ref/refse38.html#x75-990006.4 is the relevant page, together with https://www.freepascal.org/docs- html/current/rtl/system/fail.html which is what I quoted from. MarkMLl ---------------------------------------------------------------------- engkin · 2022-01-30 13:21 Yes, finally block will run with and without Fail. ---------------------------------------------------------------------- Bart · 2022-01-30 13:22 If you call Fail in the constructor the constructor will exit immediately, and teh reference to the class instance will be nil. No cleaning up done, so if you allocate resources in the constructor and then Fail, resources will leak. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$ifdef fpc}{$mode objfpc}{$H+}{$endif}{$apptype console} {$R+}{$Q+} uses  sysutils, classes;type   { TA }   TA = class  private    F: TObject;  P: Pointer;  public    constructor create;    destructor destroy; override;  end; var  A: TA; { TA } constructor TA.create;begin  writeln('TA.Create');  F := TObject.Create;  GetMem(P,1024);  if paramstr(1)='---' then Fail;end; destructor TA.destroy;begin  writeln('TA.Destroy');  F.Free;  FreeMem(P);  inherited destroy;end;  begin  A := TA.Create;  writeln('PtrInt(A)=',PtrInt(A));  if Assigned(A) then A.Free; end.Code: [Select]C:\Users\Bart\LazarusProjecten\ConsoleProjecten>test TA.Create PtrInt(A)=22489224 TA.Destroy Heap dump by heaptrc unit of C:\Users\Bart\LazarusProjecten\ConsoleProjecten\test.exe 114 memory blocks allocated : 3681/3968 114 memory blocks freed     : 3681/3968 0 unfreed memory blocks : 0 True heap size : 458752 (112 used in System startup) True free heap : 458640 C:\Users\Bart\LazarusProjecten\ConsoleProjecten>test --- TA.Create PtrInt(A)=0 Heap dump by heaptrc unit of C:\Users\Bart\LazarusProjecten\ConsoleProjecten\test.exe 115 memory blocks allocated : 3697/3984 113 memory blocks freed     : 2669/2952 2 unfreed memory blocks : 1028 True heap size : 524288 (128 used in System startup) True free heap : 522912 Should be : 522936 Call trace for block $016391F0 size 1024   $00401988  main,  line 47 of test.pas Call trace for block $01631248 size 4   $004017CD  TA__CREATE,  line 32 of test.pas   $00401988  main,  line 47 of test.pas Bart ---------------------------------------------------------------------- engkin · 2022-01-30 13:27 Quote from: Bart on January 30, 2022, 02:22:41 pmIf you call Fail in the constructor the constructor will exit immediately Not if there is a try/finally. ---------------------------------------------------------------------- Thaddy · 2022-01-30 13:28 https://www.freepascal.org/docs-html/rtl/system/fail.html ---------------------------------------------------------------------- engkin · 2022-01-30 13:36 In the case of a class constructor, Fail is merely a call to FreeInstance if Self is assigned, and an Exit. ---------------------------------------------------------------------- MarkMLl · 2022-01-30 13:38 Quote from: engkin on January 30, 2022, 02:27:27 pmQuote from: Bart on January 30, 2022, 02:22:41 pmIf you call Fail in the constructor the constructor will exit immediately Not if there is a try/finally. I confirm that behaviour, and also note that the instance becomes inaccessible before rather than after the finally block. Hence any handles etc. also need to be stored as local variables in the scope of the constructor. MarkMLl ---------------------------------------------------------------------- BrunoK · 2022-01-30 13:51 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Unit1; {$mode objfpc}{$H+} uses  Classes; type   { TGPIOPin }   TGPIOPin = class    FCreating : boolean;    FPinAllocated : boolean;  procedure AllocatePin;    procedure ReleasePin;    constructor Create;    procedure FreeInstance; override;  end; { TGPIOPin } procedure TGPIOPin.AllocatePin;begin  { Do allocate pin ... }  FPinAllocated := True;end; procedure TGPIOPin.ReleasePin;begin  { Deallocate pin ... }  FPinAllocated := False;end; constructor TGPIOPin.Create;begin  FCreating := True;  AllocatePin;  // Oups something was wrong ..  Fail;  // everytheing went well ...  FCreating := False;end; procedure TGPIOPin.FreeInstance;begin  if FCreating and FPinAllocated then    ReleasePin;  inherited FreeInstance;end; var  vGPIOPin : TGPIOPin; begin  vGPIOPin := TGPIOPin.Create;  if not Assigned(vGPIOPin) then    WriteLn('TGPIOPin.Create failed')  else    WriteLn('TGPIOPin.Create : success');  ReadLn;end. ---------------------------------------------------------------------- MarkMLl · 2022-01-30 14:13 Bart, BrunoK: I know what a constructor looks like, and thanks for the reminder but I know how to spell "Fail" >:-) The issue is that I've got a complex sequence of operations, summarised as Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   powerDownChipHandle := Gpiod.gpiod_chip_open(PChar(gpioDevice));  powerDownLineHandle := Gpiod.gpiod_chip_get_line(fPowerDownChipHandle, gpioPowerDownPin);  if Gpiod.gpiod_line_is_used(fPowerDownLineHandle) then begin  if Gpiod.gpiod_line_request_output(fPowerDownLineHandle, Pchar('RC522'), 0) <> 0 then begin  if Gpiod.gpiod_line_set_value(fPowerDownLineHandle, Ord(false xor x)) <> 0 then begin  if Gpiod.gpiod_line_set_value(fPowerDownLineHandle, Ord(true xor x)) <> 0 then begin  i2cHandle := fpOpen(i2cDevice, O_RDWR);  if fpIoctl(fI2cHandle, I2C_SLAVE, Pointer(ptruint(i2cSlave))) <> 0 then begin  Note that that is a SUMMARY, don't kick me for omitting error checking code which is there ad nauseam. Now any stage there might fail independently of the others... and at present is, since I'm not entirely confident of the reliability of the Linux kernel module that's supporting the I2C/SPI/GPIO board (it's probably broken, since I've modified it...). And details like closing a GPIO line can't be omitted, since simply closing the chip leaves the line in use (I've commented about that library in the past). So it really is necessary to have a finally block, and it's expedient for this to handle all cleaning up since dealing with all possible preceding failures at every stage individually "gets old fast" :-) MarkMLl ---------------------------------------------------------------------- engkin · 2022-01-30 15:10 Here is the relevant part of the compiler's ngenutil.pas: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i class function tnodeutils.call_fail_node:tnode;...    if is_class(current_structdef) then...            { if self<>0 and vmt<>0 then freeinstance }            addstatement(newstatement,cifnode.create(                caddnode.create(andn,                    caddnode.create(unequaln,                      load_self_pointer_node,                        cnilnode.create),                    caddnode.create(unequaln,                      load_vmt_pointer_node,                        cnilnode.create)),                ccallnode.create(nil,tprocsym(srsym) ,srsym.owner,load_self_node,[],nil),                nil));          end...    { self:=nil }    addstatement(newstatement,cassignmentnode.create(        load_self_pointer_node,        cnilnode.create));    { exit }    addstatement(newstatement,cexitnode.create(nil));  end; Or: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   if (self<>0) and (vmt<>0) then    freeinstance;  self:=nil;  exit; ---------------------------------------------------------------------- BrunoK · 2022-01-30 15:15 Something like that ?Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Unit1; {$mode objfpc}{$H+} uses  Classes, unit1; type  TGpioOpStage = (osNone,                  osGetline,                  oslineisused,                  osRequestOutput,                  osLineSetF,                  osLineSetT,                  osI2CHandle,                  osI2CSlave,                  osConnected);   { TGPIOPin }   TGPIOPin = class    FCreateing : boolean;    FGpioOpStage : TGpioOpStage;    procedure AllocatePin;    procedure ReleasePin;    constructor Create;    procedure FreeInstance; override;  end;    function InitGpio(aGpiod: TGPIOPin): boolean;  begin    powerDownLineHandle := aGpiod.aGpiod_chip_get_line(fPowerDownChipHandle,      gpioPowerDownPin);    if powerDownLineHandle <> 0 then begin      Inc(aGpiod.FGpioOpStage);      if aGpiod.aGpiod_line_is_used(fPowerDownLineHandle) then begin        Inc(aGpiod.FGpioOpStage);        if aGpiod.aGpiod_line_request_output(fPowerDownLineHandle, PChar('RC522'), 0) <>          0 then begin          Inc(aGpiod.FGpioOpStage);          if aGpiod.aGpiod_line_set_value(fPowerDownLineHandle, Ord(False xor x)) <> 0 then          begin            Inc(aGpiod.FGpioOpStage);          if aGpiod.aGpiod_line_set_value(fPowerDownLineHandle,              Ord(True xor x)) <> 0 then begin              Inc(aGpiod.FGpioOpStage);              if aGpiod.FGpioOpStage = osLineSetT then begin // Olk up to here ?                i2cHandle := fpOpen(i2cDevice, O_RDWR);                if i2cHandle <> 0 then begin                  Inc(aGpiod.FGpioOpStage);                  if fpIoctl(fI2cHandle, I2C_SLAVE, Pointer(ptruint(i2cSlave))) <> 0 then                begin                    Inc(aGpiod.FGpioOpStage);                end;                end;              end;            end;          end;        end;      end;    end;  end;   function ReleaseGpio(aGpiod: TGPIOPin): boolean;  var    lTGpioOpStage : TGpioOpStage;  begin    for lTGpioOpStage := aGpiod.FGpioOpStage downto osNone do begin      case lTGpioOpStage of        osGetline:     DoUnGetline;        oslineisused:    DoUnlineisused;        osRequestOutput: DoUnRequestOutput;        osLineSetF:      DoUnLineSetF;        osLineSetT:      DoUnLineSetT;        osLineSetT:      DoUnLineSetT;        osI2CHandle:     DoUnI2CHandle;        osI2CSlave:      DoUnI2CSlave;      end;      aGpiod.FGpioOpStage := lTGpioOpStage;    end;    // If every thing cleared OK, FGpioOpStage should be osNone  end; { TGPIOPin } procedure TGPIOPin.AllocatePin;begin  InitGpio(Self);end; procedure TGPIOPin.ReleasePin;begin  ReleaseGpio(Self);end; constructor TGPIOPin.Create;begin  FCreateing := True;  AllocatePin;  if FGpioOpStage <> osConnected then    Fail;  FCreateing := False;end; procedure TGPIOPin.FreeInstance;begin  if FCreating then  ReleasePin;  inherited FreeInstance;end; var  vGPIOPin : TGPIOPin; begin  vGPIOPin := TGPIOPin.Create;  if not Assigned(vGPIOPin) then    WriteLn('TGPIOPin.Create failed')  else    WriteLn('TGPIOPin.Create : success');  ReadLn;end.   Uncompiled + untested at all ! ---------------------------------------------------------------------- Bart · 2022-01-30 15:22 Quote from: MarkMLl on January 30, 2022, 03:13:50 pmBart, BrunoK: I know what a constructor looks like, and thanks for the reminder but I know how to spell "Fail" >:-) I understood your question as: are resources allocated in the constructor being released upon fail? Hence my example. Bart ---------------------------------------------------------------------- MarkMLl · 2022-01-30 15:38 Quote from: Bart on January 30, 2022, 04:22:35 pmI understood your question as: are resources allocated in the constructor being released upon fail? Hence my example. It explicitly asked about a finally block, and that handles etc. were involved. Hence my clarification above :-) MarkMLl ---------------------------------------------------------------------- MarkMLl · 2022-01-30 19:32 Quote from: BrunoK on January 30, 2022, 04:15:32 pmSomething like that ?Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Unit1;[/quote] Something like this appears adequate: [code=pascal]...  finally    if not Assigned(self) then begin    (* Got here because of fail             *) (* Fail deallocated the instance, so we have to rely on local variables for     *)(* handles etc.                                                               *)       if i2cHandle <> -1 then        fpClose(i2CHandle);      if powerDownLineHandle <> nil then        Gpiod.gpiod_line_release(powerDownLineHandle);      if powerDownChipHandle <> nil then        Gpiod.gpiod_chip_close(powerDownChipHandle)    end  endend { TMFRC522_I2C.Create } ;  There's various things which tidy themselves up automatically, e.g. the state of the physical GPIO signal once it's released. There's also various "gotchas" in the library, e.g. an active_low routine that isn't implemented in early versions which is why I usually prefer to access this sort of thing using dynamic linkage (in the code above, Gpiod can either be a unit encapsulating load-time linkage or an object encapsulating explicit dynamic linkage). So my question was fairly well focussed, and really boiled down to "can I trust this bit of documentation?" :-) MarkMLl ---------------------------------------------------------------------- Bart · 2022-01-30 21:08 Quote from: MarkMLl on January 30, 2022, 04:38:57 pmIt explicitly asked about a finally block, and that handles etc. were involved. Hence my clarification above :-) You did not specify where the finilization was (inside the constructor or outside). My examples shows (implicitely) that it can be detected reliably in a finally outside the constructor. Bart