QEMU Memory Allocation Issue

Viewed 387

I seem to have encountered an issue with qemu memory allocation.

static void *
x64_syscall_mmap(void *base_addr, u64 size, u32 memory_protection, 
                u32 mapping_visibility, s32 fd, u64 fd_offset)
{
  s64 result = 0;
  __asm__ __volatile__("mov r10, %5\n"
             "mov r8, %6\n"
             "mov r9, %7\n"
             "syscall"
              : "=a" (result)
              : "a" (9), 
                "D" ((u64)base_addr),
                "S" (size),
                "d" ((u64)memory_protection),
                "r" ((u64)mapping_visibility),
                "r" ((u64)fd),
                "r" (fd_offset)
              : "r10", "r8", "r9", "r11", "rcx", "memory");

  void *sys_result = (void *)((u64)result);
  if ((u64)result >= (u64)(-MAX_ERRNO)) {
    breakpoint();
    sys_result = NULL;
  }

  return sys_result;
}


typedef struct {
  void* base;
  u64 size;
  u64 used;
} X64MemArena;

static X64MemArena platform_mem_arena = {0};

static s32
x64_mem_arena_init(X64MemArena *mem_arena, u64 size)
{
  mem_arena->base = x64_syscall_mmap(NULL, size, PROT_READ | PROT_WRITE,
          MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (mem_arena->base == NULL) {
    breakpoint();
  }
  // I tried without this call, gives same result
  if (x64_syscall_mlock(mem_arena->base, mem_arena->size) < 0) {
    breakpoint();
  }

  mem_arena->used = 0;
  mem_arena->size = size;

  return 0;
}
// ...
// used here 
if (x64_mem_arena_init(&platform_mem_arena, 1024 * 1024 * 200) == -1) {
  breakpoint();
}

Run with qemu-system-x86_64 -enable-kvm -m 512M -s -S -drive format=raw,file=ker.img -kernel /boot/vmlinuz-5.8.0-50-generic -append "root=/dev/sda init=/sbin/x64-ker nokaslr"

When I inspect the contents of (u8 *)platform_mem_arena.base in debugger I get 0xd6ad000 <error: Cannot access memory at address 0xd6ad000> In the qemu window I get a line: x86/mm: Checked W+X mappings: passed, no W+X pages found. Could this be something to do with it?

Running on my Ubuntu host it works fine. Memory is valid and zeroed. So, it seems to be an issue with qemu.

0 Answers
Related