aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


client/runtime/guest_memory.c (2094B)


      1 #define _GNU_SOURCE
      2 #include "guest_memory.h"
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 #include <stdatomic.h>
      6 
      7 unsigned char *guest_pages[65536];
      8 static _Atomic uint64_t mapped_bytes;
      9 
     10 #if defined(__linux__) && UINTPTR_MAX > UINT32_MAX
     11 #include <pthread.h>
     12 #include <sys/mman.h>
     13 
     14 unsigned char *guest_base;
     15 static pthread_once_t reservation = PTHREAD_ONCE_INIT;
     16 
     17 static void reserve_guest_memory(void)
     18 {
     19     void *memory = mmap(NULL, 0x100000000ull, PROT_NONE,
     20                         MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
     21     if (memory != MAP_FAILED) guest_base = memory;
     22 }
     23 #endif
     24 
     25 /* Kernel32 memory queries report guest mappings, not the host's 64-bit layout. */
     26 uint64_t guest_memory_mapped_bytes(void) { return atomic_load(&mapped_bytes); }
     27 
     28 void guest_memory_fault(uint32_t address)
     29 {
     30     fprintf(stderr, "Unmapped guest address: 0x%08x\n", address);
     31     abort();
     32 }
     33 
     34 uint32_t guest_map(const char *name, uint32_t base, uint32_t size)
     35 {
     36     /* Allocate each range contiguously, including accesses across page boundaries. */
     37     uint64_t end = (uint64_t)base + size;
     38     if (!size || (base & 0xffffu) || end > 0x100000000ull) {
     39         fprintf(stderr, "Invalid guest mapping: %s 0x%08x + 0x%x\n", name, base, size);
     40         abort();
     41     }
     42     uint32_t first = base >> 16;
     43     uint32_t count = (uint32_t)(((uint64_t)size + 0xffffu) >> 16);
     44     for (uint32_t i = 0; i < count; ++i) {
     45         if (guest_pages[first + i]) {
     46             fprintf(stderr, "Overlapping guest mapping: %s\n", name);
     47             abort();
     48         }
     49     }
     50 
     51 #if defined(__linux__) && UINTPTR_MAX > UINT32_MAX
     52     if (pthread_once(&reservation, reserve_guest_memory)) abort();
     53     if (!guest_base) return 0;
     54     unsigned char *memory = guest_base + base;
     55     if (mprotect(memory, (size_t)count * 0x10000u, PROT_READ | PROT_WRITE)) return 0;
     56 #else
     57     unsigned char *memory = calloc(count, 0x10000u);
     58     if (!memory) return 0;
     59 #endif
     60     for (uint32_t i = 0; i < count; ++i)
     61         guest_pages[first + i] = memory + (size_t)i * 0x10000u;
     62     atomic_fetch_add(&mapped_bytes, (uint64_t)count * 0x10000u);
     63     return size;
     64 }