结构化异常处理(SEH)在MSVC和MinGW上的使用

结构化异常处理(SEH)在MSVC和MinGW上的使用

SEH 即 Structured Exception Handling,结构化异常处理。是 M$ 在 Windows 下实现的一套异常处理机制,用于支持软件和硬件异常处理。SEH 作为 Windows 特有的机制,同时也是 Windows 溢出攻击中常见的利用的途径之一。

关于SEH的详细分析,请看Matt Pietrek的文章(原文是发布在MSDN上的,但似乎已经被删除了,这是别处转载的链接):

英语原文:A Crash Course on the Depths of Win32 Structured Exception Handling
英语转载:A Crash Course on the Depths of Win32 Structured Exception Handling
译文:深入解析结构化异常处理(SEH)

在MSVC上使用

#include <windows.h>
#include <Dbghelp.h>

//崩溃函数
int crashFunc()
{
    printf("crashFunc\n");
    int *p = NULL;
    *p = 1;
    return *p;
}

LONG WINAPI UnhandledExceptionFilterEx(struct _EXCEPTION_POINTERS *pException)
{
    printf("UnhandledExceptionFilterEx call\n");

    return EXCEPTION_CONTINUE_SEARCH;
    //return EXCEPTION_EXECUTE_HANDLER;
}

int main(int argc, char** argv)
{

    //方式1 调用winapi,把崩溃处理函数挂载在顶层异常处理中
    SetUnhandledExceptionFilter(UnhandledExceptionFilterEx);
    crashFunc();


    //方式2 使用__try/__except拦截异常
    __try
    {
        crashFunc();
    }
    __except(UnhandledExceptionFilterEx(GetExceptionInformation()))
    {
        printf("crash __except\n");
    }
}

在mingw上使用

#include <windows.h>
#include <Dbghelp.h>

//崩溃函数
int crashFunc()
{
    printf("crashFunc\n");
    int *p = NULL;
    *p = 1;
    return *p;
}

LONG WINAPI UnhandledExceptionFilterEx(struct _EXCEPTION_POINTERS *pException)
{
    printf("UnhandledExceptionFilterEx call\n");

    return EXCEPTION_CONTINUE_SEARCH;
    //return EXCEPTION_EXECUTE_HANDLER;
}

int exceptEx(_In_ EXCEPTION_POINTERS *lpEP)
{
    return UnhandledExceptionFilterEx(lpEP);
}


int main(int argc, char** argv)
{

    //方式1 和msvc一样,都是调用winapi
    SetUnhandledExceptionFilter(UnhandledExceptionFilterEx);
    crashFunc();


    //方式2 __try1/__except1拦截异常
    __try1(exceptEx)
    {
        crashFunc();
    }
    __except1
    {
        printf("crash __except1\n");
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值