C++获取寄存器eip的值

程序中需要打印当前代码段位置 如下

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <math.h>
 4 #ifdef WIN32
 5 #include <windows.h>
 6 #endif
 7 typedef void (*pFunGetip)(int n);
 8 void getip(int n);
 9 void __declspec(naked) fun()
10 {
11 __asm {
12   mov eax,[esp];
13   ret;
14 }
15 }
16 int main()
17 {
18     printf("main=0x%p\n",main);
19     void* p=0;
20     __asm {
21         lea edi,p
22         call fun
23         mov [edi],eax
24     }
25     printf("p=0x%x\n",p);
26 #ifdef WIN32
27     system("pause");
28 #endif
29     return 0;
30 }

 来个纯C++的函数

 1 static unsigned char* getEIP()
 2 {
 3   unsigned int n=0;
 4   unsigned int* p=&n;
 5   unsigned int* p2=(unsigned int*)getEIP;
 6   unsigned int m=(((unsigned int)p2)&0xfff00000);
 7   unsigned int m2=m+0xfffff;
 8   for(int i=0;i<0xff;++i)
 9   {
10       if(m&p[i])
11       {
12           if(p[i]<m2)
13           {
14               return (unsigned char*)p[i];
15           }
16       }
17   }
18   return 0;
19 }

 

posted on 2018-08-29 13:47  弘道者  阅读(2443)  评论(0编辑  收藏  举报