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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With