VS2019对于两个函数名不同,但是函数代码实现相同的情况,在链接时会将两个函数合并为同一个代码段,导致两个函数的地址相等。代码如下:
#include <wdm.h>
static void InnerFunc(int i, const char* name)
{
DbgPrint("i=%d, name=%s\n", i, name);
}
typedef void* (*FuncIndexType)(int, const char*);
#define FUNC_NAME(x) ((PVOID)FuncIndex_##x)
#define DEFINE_FUNC(x)\
static void FuncIndex_##x(int i, const char *name)\
{\
InnerFunc(i, name);\
}
DEFINE_FUNC(1);
DEFINE_FUNC(2);
static PVOID g_funcArray[] = { (PVOID)FUNC_NAME(1), (PVOID)FUNC_NAME(2) };
void DriverUnload(IN PDRIVER_OBJECT DriverObject)
{
UNREFERENCED_PARAMETER(DriverObject);
}
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
{
UNREFERENCED_PARAMETER(DriverObject);
UNREFERENCED_PARAMETER(RegistryPath);
DriverObject->DriverUnload = DriverUnload;
DbgPrint("[DrvSample] DriverEntry...\n");
for (int i = 0; i < sizeof(g_funcArray) / sizeof(void*); i++)
{
DbgPrint("Address:0x%p\n", g_funcArray[i]);
((FuncIndexType)g_funcArray[i])(i, "test");
}
return STATUS_SUCCESS;
}
?上面驱动执行的结果如下图:
可以看出使用DEFINE_FUNC宏生成的FuncIndex_1和FuncIndex_2两个函数地址相等
那么要如何让两个函数地址不同呢?有两种方式:
1.禁用链接选项:启用COMPAT折叠
2.让两个函数有不同代码
#include <wdm.h>
static void InnerFunc(int index, int i, const char* name)
{
DbgPrint("index=%d i=%d, name=%s\n", index, i, name);
}
typedef void* (*FuncIndexType)(int, const char*);
#define FUNC_NAME(x) ((PVOID)FuncIndex_##x)
#define DEFINE_FUNC(x)\
static void FuncIndex_##x(int i, const char *name)\
{\
InnerFunc(x, i, name);\
}
DEFINE_FUNC(1);
DEFINE_FUNC(2);
static PVOID g_funcArray[] = { (PVOID)FUNC_NAME(1), (PVOID)FUNC_NAME(2) };
void DriverUnload(IN PDRIVER_OBJECT DriverObject)
{
UNREFERENCED_PARAMETER(DriverObject);
}
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
{
UNREFERENCED_PARAMETER(DriverObject);
UNREFERENCED_PARAMETER(RegistryPath);
DriverObject->DriverUnload = DriverUnload;
DbgPrint("[DrvSample] DriverEntry...\n");
for (int i = 0; i < sizeof(g_funcArray) / sizeof(void*); i++)
{
DbgPrint("Address:0x%p\n", g_funcArray[i]);
((FuncIndexType)g_funcArray[i])(i, "test");
}
return STATUS_SUCCESS;
}
上面两种方式的执行结果如下图:
注意:上面的实现方式,index必须要使用,否则仍然可能被链接优化为相同地址