Windows 与 Linux 下的 PAGE_ALIGN 页面对齐宏引发的 BUG

今天遇到了一个BUG,找了半天才定位到是 PAGE_ALIGN 宏导致的。

这个宏在 Windows 上和 Linux 上的定义不同,才得以引发了这次BUG的发生。

PAGE_ALIGN 的用处是对齐一个页面地址。

先来看看定义:

// Windows
#define PAGE_ALIGN(Va)      ((PVOID)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1)))

// Linux
#define PAGE_MASK           (~(PAGE_SIZE - 1))
#define PAGE_ALIGN(addr)    (((addr) + PAGE_SIZE - 1) & PAGE_MASK)

写个例子测试:

#define PAGE_ALIGN(Va)      ((PVOID)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1)))
	printf("Windows: 0x%llx\n", PAGE_ALIGN(0x1234));
#undef PAGE_ALIGN

#define PAGE_MASK           (~(PAGE_SIZE - 1))
#define PAGE_ALIGN(addr)    (((addr) + PAGE_SIZE - 1) & PAGE_MASK)
	printf("Linux  : 0x%llx\n", PAGE_ALIGN(0x1234));
#undef PAGE_ALIGN

得到结果:

Windows: 0x1000
Linux  : 0x2000

解决方法:

1、在 Windows 下,需要对齐的值在微软的 API 中是会被自动向高对齐的。所以一般不需要手动对齐。

2、如果实在要手动向高对齐,直接复制一下 Linux 中的 PAGE_ALIGN 定义,然后 Rename 一下就行了。

猜你喜欢

转载自blog.csdn.net/u012088909/article/details/100945806