Exception Handler not called in C
Asked Answered
C

1

6

I am reading about Structured Exception Handling in C. Here is an example code which does not work as expected:

This code is taken from here:

http://msdn.microsoft.com/en-us/library/ha52ak6a.aspx

// C4733.cpp
// compile with: /W1 /c
// processor: x86
#include "stdlib.h"
#include "stdio.h"
void my_handler()
{
   printf("Hello from my_handler\n");
   exit(1);
}

int main()
{
   _asm {
      push    my_handler
      mov     eax, DWORD PTR fs:0
      push    eax
      mov     DWORD PTR fs:0, esp   // C4733
   }

   *(int*)0 = 0;
}

This code should print the message, "Hello from my_handler" when the exception is triggered by trying to write to an invalid memory address. However, it appears that the exception handler is not called at all.

I compiled this code and tried debugging it with Olly Debugger. When the exception occurs, I try passing the exception to the application defined exception handler (by pressing, Shift + F9) but it does not get called. I set a breakpoint at the exception handler (first instruction), but it never reaches that section of code.

What might be the reason for this?

Caldera answered 1/11, 2013 at 7:8 Comment(2)
Looks like it is a compiler warning, not a runtime error checking. I don't have windows so cannot check..Lucie
Have you tried to compile your code with /ZI /MTd compiler options ? In this way, I have got the expected result.Zoezoeller
M
2

I was facing the same issue. The reason that it does not work is that my_handler is blocked by the compiler at linked time. We need either tell the compiler that my_handler is safe, or totally disable safety-checking. So, there are two ways to make it work. (Tried on both MSVC 2008 and 2010)

  • Disable the safeseh table by add /safeseh:no at link time.

    cl /c C4733.cpp
    link /safeseh:no C4733.obj 
    
  • Create a masm file to add my_handler to the SEH table. But the SAFESEH example on MSN did not work on my laptop. I found this solution on stackoverflow to work instead: Custom SEH handler with /SAFESEH. But we have to create an additional MASM procedure to jump to the external C function.

Mennonite answered 3/12, 2013 at 6:19 Comment(2)
Do you absolutely need that MASM file? Can't you just add that assembly code using inline assembly?Linetta
@Linetta I doubt if inlining works. There is a -safeseh parameter passed to ml.exe, which is not supported by cl.exe. FYI, I compiled the asm using: ml.exe -Fo my.obj -c -safeseh my.asmMennonite

© 2022 - 2024 — McMap. All rights reserved.