在Windows上,您可以使用CaptureStackBackTrace捕获堆栈跟踪
void* frames[USHRT_MAX];
USHORT framesCount = CaptureStackBackTrace(0, USHRT_MAX, frames, NULL);
但是,在循环中通过较小的块捕获它以避免分配USHRT_MAX
缓冲区不会提供相同的结果。
这段代码
#include <Windows.h>
#include <assert.h>
#include <stdio.h>
__declspec(noinline) void CheckStack(void)
{
printf("Checking stack...\n");
void* entireStack[USHRT_MAX];
USHORT frameCount = CaptureStackBackTrace(0, USHRT_MAX, entireStack, NULL);
printf("Stack size is: %u\n", frameCount);
ULONG frameOffset = 1;
for (;;)
{
void* chunk[64];
USHORT framesFound = CaptureStackBackTrace(frameOffset, 64, chunk, NULL);
if (framesFound)
{
if (memcmp(entireStack + frameOffset, chunk, sizeof(chunk)) != 0)
{
printf("Incorrect content\n");
}
frameOffset += (ULONG)framesFound;
}
else
{
break;
}
}
if (frameCount != frameOffset)
{
printf("Incorrect count (%u != %u)\n", frameCount, frameOffset);
}
printf("Done\n");
}
__declspec(noinline) void Test(int i)
{
if (i != 500)
Test(++i);
else
CheckStack();
}
int main()
{
Test(0);
}
产生以下输出
Checking stack...
Stack size is: 507
Incorrect count (507 != 257)
Done
当建设为cl /Od main.c /link /OUT:main.exe
。
我是否错误地使用了FramesToSkip
参数或为什么计数不相等?
如果您使用的是Windows Server 2003和Windows XP,
FramesToSkip和FramesToCapture参数之和必须小于63。
这是在文件中。
另外,正如@RbMm所说,在API源代码中,有以下逻辑:
if(FramesToSkip>0xfe)
{
return 0; //There are too many stack structures skipped, returning directly to 0.
}
但是,在CaptureStackBackTrace和RtlCaptureStackBackTrace上msdn都没有提到这一点。我不打算在这里发布源代码,但在调试中证明它:
1.创建一个样本:
#include <Windows.h>
#include <assert.h>
#include <stdio.h>
__declspec(noinline) void CheckStack(void)
{
void* entireStack[USHRT_MAX];
USHORT frameCount = CaptureStackBackTrace(255, USHRT_MAX, entireStack, NULL);
}
__declspec(noinline) void Test(int i)
{
if (i != 500)
Test(++i);
else
CheckStack();
}
int main()
{
Test(0);
}
2.在反汇编中进入CaptureStackBackTrace
:你可以看到dword ptr[ebp+8]
(CaptureStackBackTrace
的第一个参数被推入堆栈)将与0feh
(254)进行比较。如果为true,则返回0。