[整理]Linux下实现IsBadWritePtr函数

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: [整理]Linux下实现IsBadWritePtr函数

在Linux中没有像Windows API提供的IsBadWritePtr类似的函数或者系统调用。不过你可以自己实现类似的功能,下面的代码实现了函数IsReadBadPtr, IsWriteBadPtr的实现类似。 大致原理是在linux下非法指针访问产生SIGSEGV, 并且会产生core dump, 你在测试指针之前设置自己的SIGSEGV信号处理函数就 可以不产生core dump。

参考:http://bbs.csdn.net/topics/80398644

http://zhangyafeikimi.iteye.com/blog/248822

#include <setjmp.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

/*
 ***************************
 * Global Variables 
 ***************************
*/
static volatile sig_atomic_t segv_flag;
static jmp_buf jmp_env;

/*
 ********************************************
 * Pre: none 
 * Post: restore the original process state 
 *    and return 1 to setjmp
 ********************************************
*/
static void segv_handler( int dummy )
{
segv_flag = 1;
longjmp( jmp_env , 1);
}

/*
 ********************************************
 * Pre: A pointer and it's length
 * Post: Return true is the pointer is bad
 *    or false if otherwise
 ********************************************
*/

int IsReadBadPtr(void * ptr_buffer, unsigned long buffer_size)
{
struct sigaction oldaction, newaction;
volatile char dummy;
char *ptr = (char *)ptr_buffer;

if ( !buffer_size )
return 0;

      /* storing the old signal environment and trapping SIGSEGV */
newaction.sa_handler = segv_handler;
newaction.sa_flags = 0;
sigemptyset( &newaction.sa_mask);

sigaction( SIGSEGV, &newaction, &oldaction);

segv_flag = 0;

      /* Storing the process state so if any failure happens 
         we can restore it to the original state */
if ( setjmp(jmp_env) == 0 )
{
/* testing the pointer: only the first and the end are     needed here since any failure to any of this would       indicate there would an error on the entire range */
dummy = ptr[0];
dummy = ptr[buffer_size-1];
}

      /* restoring the original signal environment */
sigaction(SIGSEGV, &oldaction, NULL);

return segv_flag;
}

int main()
{
char *testptr,c;  // testptr[10],结果将是Ok read Ptr

if ( IsReadBadPtr(testptr, 10))
printf(" Bad read Ptr\n");
else
printf(" Ok read Ptr\n");
fflush(stdout);
return 0;
}
原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: [整理]Linux下实现IsBadWritePtr函数

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: