11

I'm trying to figure out how to obtain a stack trace after an exception is thrown in Delphi. However, when I try to read the stack in the Application.OnException event using the function below, the stack already seems to be flushed and replaced by the throwing procedures.

function GetStackReport: AnsiString;
var
    retaddr, walker: ^pointer;
begin

    // ...

    // History of stack, ignore esp frame
    asm
        mov walker, ebp
    end;

    // assume return address is present above ebp
    while Cardinal(walker^) <> 0 do begin
        retaddr := walker;
        Inc(retaddr);
        result := result + AddressInfo(Cardinal(retaddr^));
        walker := walker^;
    end;
end;

Here's what kind of results I'm getting:

001A63E3: TApplication.HandleException (Forms)
00129072: StdWndProc (Classes)
001A60B0: TApplication.ProcessMessage (Forms)

That's obviously not what I'm looking for, although it's correct. I'd like to retrieve the stack as it was just before the exception was thrown, or in other words the contents before (after would do too) the OnException call.

Is there any way to do that?

I am aware that I'm reinventing the wheel, because the folks over at madExcept/Eurekalog/jclDebug have already done this, but I'd like to know how it's done.

Orwell
  • 1,468
  • 1
  • 13
  • 28
  • How good are you at reading assembler? ;-) – Warren P Apr 08 '13 at 23:58
  • 10
    I never understood why the RTL doesn't have this built in... – Wouter van Nifterick Apr 09 '13 at 00:16
  • @WarrenP: reasonably good, or at least good enough to be able to fix this I thought, but I'm out of luck it seems. :( – Orwell Apr 09 '13 at 06:59
  • 1
    "I'd like to know how it's done." - read the sources. JCL sources are open, same for mORMot and some free loggers and profilers. There are a number of FLOSS products incorporating unwinding stack. You just can read their code and learn from it. – Arioch 'The Apr 09 '13 at 10:38
  • And if you need to do something and don't have time to hash it out yourself, you could contact madshi (author of MadExcept) and ask him to engineer a solution. That's what I would do. This stuff is HARD. – Warren P Apr 09 '13 at 18:58

2 Answers2

22

It is not possible to manually obtain a viable stack trace from inside the OnException event. As you have already noticed, the stack at the time of the error is already gone by the time that event is triggered. What you are looking for requires obtaining the stack trace at the time the exception is raised. Third-party exception loggers, like MadExcept, EurekaLog, etc handle those details for you by hooking into key functions and core exception handlers inside of the RTL itself.

In recent Delphi versions, the SysUtils.Exception class does have public StackTrace and StackInfo properties now, which would be useful in the OnException event except for the fact that Embarcadero has chosen NOT to implement those properties natively for unknown reasons. It requires third-party exception loggers to assign handlers to various callbacks exposed by the Exception class to generate stack trace data for the properties. But if you have JclDebug installed, for instance, then you could provide your own callback handlers in your own code that use JCL's stack tracing functions to generate the stack data for the properties.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • The reasons are not unknown at all. The fields were added as a service to help the third party tools. The fields provide a common place for them to place their information. Emba didn't populate them because that's the job of the third party libraries. – David Heffernan Apr 09 '13 at 07:28
  • The reason might be known to those following the newsgroups or other sources. But the online help does not mention it: http://docwiki.embarcadero.com/Libraries/XE3/en/System.SysUtils.Exception.StackTrace – dummzeuch Apr 09 '13 at 14:07
  • 21
    Embacadero is best suited to implement stack tracing since it is the one making the compiler in the first place. Prior to exposing the callbacks, third party hooking was the only option. With the callbacks in place, not providing a native solution is a cop-out IMHO. Embarcadero could and should, but they seem to have chosen not to. – Remy Lebeau Apr 09 '13 at 15:25
  • 4
    At the very least, I would like to see Embarcadero add a new unit to the RTL that users could optionally add to their `uses` clause if desired and it would assign its own handlers to the callbacks and generate basic call stack information. For those users who don't want to buy/install third party loggers. – Remy Lebeau Apr 09 '13 at 15:37
  • 2
    I think they should just give a pile of cash to Madshi and build in MadExcept. (Of course that would tick off the loyal fans of EurekaLog, but as in all holy wars, it seems I am right, and you EurekaLog fans are just wrong.) ;-) – Warren P Apr 09 '13 at 19:00
  • 4
    @WarrenP I would not like to see that. Because then Emba would be in charge of developing it. And I think it's better off with Mathias at the helm. – David Heffernan Apr 09 '13 at 21:19
  • 3
    @David Heffernan : 'that's the job of the third party libraries'. Is that the same approach they took with the Delphi Help? It's the job of the users? 'Embarcadero has no further information about this topic...' If Embarcadero doesn't, who is supposed to have the information? Inexcusable. Same here - as Remy said "They have chosen not to" - that is, they have chosen to cut corners and leave us without information - as usual.. – Vector Apr 10 '13 at 03:25
  • 6
    Only in the world of Embarcadero could providing an exception stack trace be considered the job of third party libraries. – Stephen Drew Nov 04 '13 at 07:08
  • @WarrenP latest madexcept was pretty bad at discerning which code is part of the stack trace. We could not use it in production as it added little to no business value, littering stack trace with vcl, sysutils, etc while ignoring our own functions and procedures. – nurettin May 11 '18 at 07:01
  • @Remy: if you want EMBT to provide an own unit with a basic implementation of these callbacks then please create a QP request and add the number here. I'd vote for it. – Markus May 25 '18 at 14:27
  • 1
    @Markus a QP already exists (from 2 years ago): [RSP-13347](https://quality.embarcadero.com/browse/RSP-13347) – Remy Lebeau May 25 '18 at 15:05
  • @Remy: thanks for pointing me to it, I voted for it and commented it. – Markus May 25 '18 at 19:26
10

I'd like to retrieve the stack as it was just before the exception was thrown, or in other words the contents before (after would do too) the OnException call.

Actually, you don't want the stack before the OnException call. That's what you've already got. You want the stack at the point at which the exception was raised. And that requires the stack tracing to happen ASAP after the raise. It's too late in the OnException call because the exception has propagated all the way to the top-level handler.

madExcept works by hooking all the RTL functions that handle exceptions. And it hooks the lowest level functions. This takes some serious effort to bring about. With these routines hooked the code can capture stack traces and so on. Note that the hooking is version specific and requires reverse engineering of the RTL.

What's more the stack walking is very much more advanced than your basic code. I don't mean that in a derogatory way, it's just that stack walking on x86 is a tricky business and the madExcept code is very well honed.

That's the basic idea. If you want to learn more then you can obtain the source code of JclDebug for free. Or buy madExcept and get its source.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490