Free Pascal: call stack and procedures names at runtime

| category: Programming | author: st
Tags:

Here is an example how to get N-2 calling procedure information.

Warning: code seeking debugging info is slow so be aware to use it in loops.

Make sure to compile with following options:

  • -gl (not requierd but show file and line numbers info)
  • -gs (show proc name after address)
var
  i: Longint;
  PrevBP: Pointer;
  CallerFrame, CallerAddr, BP: Pointer;
  CallerName: string = '';
begin
  // get N-2 caller proc name
  BP := get_frame;
  PrevBP := BP - 1;
  i := 0;
  while BP > PrevBP do
  begin
    CallerAddr := get_caller_addr(BP);
    CallerFrame := get_caller_frame(BP);
    if (CallerAddr = nil) or (CallerFrame = nil) then
      break;
    if i = 1 then
    begin
      CallerName := BackTraceStrFunc(CallerAddr);
      break;
    end;
    PrevBP := BP;
    BP := CallerFrame;
    Inc(i);
  end;
...

Finally, CallerName variable should contains something like following

$0043EF0A  TSCRIPTSTEST__TESTPARSER,  line 749 of ScriptsTest.pas