{$R-,S-,I-}

unit StakDump;
  {-Exit handler with stack dump for Turbo 4}

interface

  {==========================================================================}

implementation

var
  ExitSave : Pointer;
  InitSP : Word;

  {$L STAKDUMP}        {Good stuff's in here}
  procedure Trace;
    {-Dump stack of return addresses}
  external;

  {$F+}
  procedure ErrorProc;
    {-Gains control when errors occur}
  begin
    {Restore previous handler}
    ExitProc := ExitSave;
    if (ErrorAddr <> nil) and (Mem[PrefixSeg:5] <> $C3) then begin
      {Error not previously handled, and not in user-interface Turbo}
      {Reset standard output}
      if IoResult = 0 then ;
      Assign(Output, '');
      Rewrite(Output);
      {Write runtime error}
      WriteLn('Runtime error ', ExitCode, '. Stack dump:');
      {Trace from error address to top of stack}
      Trace;
      {Stop remaining handlers from reporting error}
      ErrorAddr := nil;
    end;
  end;
  {$F-}

begin
  {Save initial stack pointer}
  InitSP := SPtr+4;
  {Set up ExitProc}
  ExitSave := ExitProc;
  ExitProc := @ErrorProc;
end.
