14 int AllocateMemory(uintptr_t VirtAddr, size_t ByteCount);
15 uintptr_t FindFreeRange(size_t ByteCount, int MaxBits);
18 int AllocateMemory(uintptr_t VirtAddr, size_t ByteCount)
20 uintptr_t base = (VirtAddr >> 12) << 12;
21 size_t size = (VirtAddr & 0xFFF) + ByteCount;
26 MEMORY_BASIC_INFORMATION info;
27 VirtualQuery( (void*)base, &info, sizeof(info) );
28 if( info.State != MEM_FREE ) {
29 printf("ERROR: Unable to allocate memory %p+0x%x, already allocated\n",
38 } while( size >= 0x1000 );
39 tmp = VirtualAlloc((void*)base, size, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE);
41 printf("ERROR: Unable to allocate memory %p+%x (0x%x)\n",
47 // printf("AllocateMemory: mmap(%p, 0x%lx, ...)\n", (void*)base, ByteCount);
48 tmp = mmap((void*)base, size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
49 if( tmp == MAP_FAILED ) {
50 printf("ERROR: Unable to allocate memory\n");
51 perror("AllocateMemory");
54 // printf("AllocateMemory: RETURN 0\n");
59 uintptr_t FindFreeRange(size_t ByteCount, int MaxBits)
61 uintptr_t base, ofs, size;
63 static const int PAGE_SIZE = 0x1000;
65 size = (ByteCount + PAGE_SIZE - 1) / PAGE_SIZE;
68 end <<= (sizeof(intptr_t)*8-MaxBits);
69 end >>= (sizeof(intptr_t)*8-MaxBits);
70 // printf("end = %p\n", (void*)end);
72 // for( base = 0; base < end - size; base -= PAGE_SIZE )
73 for( base = end - size + 1; base > 0; base -= PAGE_SIZE )
75 for( ofs = 0; ofs < size; ofs += PAGE_SIZE ) {
77 MEMORY_BASIC_INFORMATION info;
78 VirtualQuery( (void*)(base + ofs), &info, sizeof(info) );
79 if( info.State != MEM_FREE )
82 if( msync( (void*)(base+ofs), 1, 0) == 0 )
85 perror("FindFreeRange, msync");