如何确定'malloc'符号是来自源还是来自编译器?

How to determine if a 'malloc' symbol came from the source or from the compiler?

本文关键字:编译器 符号 何确定 malloc      更新时间:2023-10-16

使用 Dll 注入,我能够从msvcrt.dll挂住malloc符号,并打印从注入的过程中malloc的所有调用的日志。问题是在日志中,我可以找到对目标 exe 中没有的malloc调用,请参阅进一步的示例。

我相信有一种方法可以解决这个问题,基于我在钩子过程中发现的malloc调用的返回地址。下面是使用 tcc 编译的目标 PE 的日志文件:

0 malloc(18)    memory allocated at: 10229112    the return adress is 74ab770a.
1 malloc(4096)  memory allocated at: 10232824    the return adress is 74ab770a.
2 malloc(15)    memory allocated at: 10229144    the return adress is 401022.
3 malloc(15)    memory allocated at: 10229168    the return adress is 401041.
4 malloc(15)    memory allocated at: 10229192    the return adress is 401060.

在 exe 文件中,只有最后三个调用存在,很明显另一个来自完全不同的 PE。

打印日志时,如何检测来自exe文件的哪些调用以及来自不同 PE 的哪些调用?感谢您的任何帮助。

当我们从 DLL 挂钩函数时,假设msvcrt!malloc调用可以来自不同的 PE 模块。 我们可以从带有GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS标志的 returnAddress 调用GetModuleHandleExW获取调用模块的基址。 如果我们需要检测调用是否来自 EXE,我们可以将此地址与 EXE 的基址进行比较,我们可以通过GetModuleHandleW

代码可能看起来像

HMODULE hmod;
if (GetModuleHandleEx(
    GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|
    GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (PCWSTR)_ReturnAddress(), &hmod))
{
    static HMODULE hmodEXE = 0;
    if (!hmodEXE)
    {
        hmodEXE = GetModuleHandleW(0);
    }
    DbgPrint("%p: call %sfrom exen", _ReturnAddress(), hmodEXE == hmod ? "" : "not ");
}
else
{
    DbgPrint("%p: call not from any PEn", _ReturnAddress());
}