要得到一段代码的长度最根本的是要得到开始位置的EIP和结尾处的EIP。可惜我的VS2010不能保存利用汇编语言将EIP压入堆栈不然就简单了。不过既然直接走走不通,换一种思维也可以的。
#include
int n,m;
void func()
{
start: _asm push start
_asm pop m
printf("In The Stub!!\n");
label: _asm push label
_asm pop n
}
int _tmain(int argc, _TCHAR* argv[])
{
func();
printf("%u\n",(unsigned)n-(unsigned)m);
system("pause");
return 0;
}
代码很简单,在func开头将标志start压入堆栈,并出栈保存到m当中,然后在函数结尾同样处理,在输出的时候进行计算就行了,这样可以得到这个函数的代码长度。
In The Stub!!
25
请按任意键继续. . .
上面是输出结果,对代码进行调试反汇编跟进去,验证一下结果。
00991000 push ebp
00991001 mov ebp,esp
start: _asm push start
00991003 push offset start (991003h)
_asm pop m
00991008 pop dword ptr [m (993370h)]
printf("In The Stub!!\n");
0099100E push offset string "In The Stub!!\n" (9920F4h)
00991013 call dword ptr [__imp__printf (9920A4h)]
00991019 add esp,4
label:_asm push label
0099101C push offset label (99101Ch)
_asm pop n
00991021 pop dword ptr [n (993374h)]
从这里可以看出,输出的结果值为0x0099101c-0x00991003,刚好就等于25.
上面的方法比较简单,但是需要在计算长度之前调用函数,显得不够智能化。接下来看另一种方法,利用编译器给我们计算代码短的长度。源代码如下:
#include
#pragma code_seg("test")
void func()
{
start: _asm push start
_asm pop m
printf("In The Stub!!\n");
label: _asm push label
_asm pop n
}
void func1(){}
#pragma code_seg()
typedef void(*ptr)();
int _tmain(int argc, _TCHAR* argv[])
{
ptr funcptr=func;
ptr pointer=func1;
printf("%u\n",(unsigned)pointer-(unsigned)funcptr);
system("pause");
return 0;
}
输出结果为
48
反汇编结果如下,很明显中间加入了一下比较多余的代码。
00E72000 push ebp
00E72001 mov ebp,esp
start: _asm push start
00E72003 push offset start (0E72003h)
_asm pop m
00E72008 pop dword ptr [m (0E74370h)]
printf("In The Stub!!\n");
00E7200E push offset string "In The Stub!!\n" (0E730F4h)
00E72013 call dword ptr [__imp__printf (0E730A4h)]
00E72019 add esp,4
label:_asm push label
00E7201C push offset label (0E7201Ch)
_asm pop n
00E72021 pop dword ptr [n (0E74374h)]
}
00E72027 pop ebp
00E72028 ret
--- 无T源′文?件t -----------------------------------------------------------------------
00E72029 int 3
00E7202A int 3
00E7202B int 3
00E7202C int 3
00E7202D int 3
00E7202E int 3
00E7202F int 3
--- c:\users\administrator\desktop\test1\test1\test1.cpp -----------------------
void func1(){}