Search code examples
delphistackdelphi-2009

how can i see how much of the stack space is currently used in my delphi app?


how can i see how much of the stack space is currently used in my delphi app? i had a very strange error that sounds like stack trouble. i'd like to add it to my app's log to get some idea how much stack space is in use/remaining. using the debugger is probably not so great because the routine can be called many times.

thank you!


Solution

  • {$IFDEF MSWINDOWS}
    function currentStackUsage: NativeUInt;
    //NB: Win32 uses FS, Win64 uses GS as base for Thread Information Block.
    asm
      {$IFDEF WIN32}
      mov eax, fs:[4]  // TIB: base of the stack
      sub eax, esp     // compute difference in EAX (=Result)
      {$ENDIF}
      {$IFDEF WIN64}
      mov rax, gs:[8]  // TIB: base of the stack
      sub rax, rsp     // compute difference in RAX (=Result)
      {$ENDIF}
    {$ENDIF}
    end;