VS2019 驱动两个函数地址相同?

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必须要使用,否则仍然可能被链接优化为相同地址

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值