Windows内核实验:延迟内存分配

Windows内核实验:延迟内存分配

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
DWORD var1;
#pragma section("new_page",read,write)
__declspec(allocate("new_page")) DWORD var2 = 1;
void __declspec(naked) IdtEntry() {//裸函数不会帮我们生成栈帧,单纯一个call
__asm{
mov eax,var2
mov var1,eax
iretd
}
}
void interrupt() {
__asm {
int 0x20
}
}
int main() {
if (0x401040 != IdtEntry) {
printf("Idtentry address wrong");
system("pause");
exit(-1);
}
//eq 8003f500 0040ee00`00081040
system("pause");
interrupt();
printf("&var2:%p\n",&var2);
printf("var1:%d\n",var1);
system("pause");
}
#pragma section("new_page",read,write)
__declspec(allocate("new_page")) DWORD var2 = 1;

用来分配一个新section,并把var2变量放入该section

https://learn.microsoft.com/zh-cn/cpp/preprocessor/section?view=msvc-170

https://learn.microsoft.com/zh-cn/cpp/cpp/allocate?view=msvc-170

image-20230603011009892

主要是为了让var2在一个新页开始,即4k对齐,而且这个页里只有这个变量

请按任意键继续. . .
&var2:0041B000
var1:0
请按任意键继续. . .

没有是1的原因是mov eax,var2var2所在页第一次被访问,由于延迟绑定机制,会触发缺页异常,我们没有在中断里构造正确的环境,导致缺页处理程序不能正常执行,所以为0

但是如果我们在第一个pause停下时去用ce或者调试器访问这一段内存,会把这段虚拟内存映射到物理内存

image-20230603012716985

这种机制就可以用到反调试上面去

其实只要读了var2的地址就会把这个页面映射

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
DWORD var1;
#pragma section("new_page",read,write)
__declspec(allocate("new_page")) DWORD var2 = 1;
void __declspec(naked) IdtEntry() {//裸函数不会帮我们生成栈帧,单纯一个call
__asm{
mov eax,var2
mov var1,eax
iretd
}
}
void interrupt() {
__asm {
int 0x20
}
}
int main() {
if (0x401040 != IdtEntry) {
printf("Idtentry address wrong");
system("pause");
exit(-1);
}
//eq 8003f500 0040ee00`00081040
interrupt();
printf("&var2:%p\n",&var2);
interrupt();//读过地址后就会映射过来
printf("var1:%d\n",var1);
system("pause");
}
&var2:0041B000
var1:1
请按任意键继续. . .