</>EmbeddedInterview

Look up which guest memory region contains a guest physical address.

Medium"Coding: Systems, Bitmaps & Virtualization"
#include <stdint.h>
#include <stddef.h>

typedef struct {
    uint64_t gpa_start;      /* guest physical start */
    uint64_t size;
    uint8_t *hva;            /* host virtual address where it is mapped */
} mem_region_t;

/* regions sorted by gpa_start and non-overlapping */
uint8_t *gpa_to_hva(const mem_region_t *r, size_t n, uint64_t gpa, uint64_t len)
{
    size_t lo = 0, hi = n;
    while (lo < hi) {                                 /* binary search for the last start <= gpa */
        size_t mid = lo + (hi - lo) / 2;
        if (r[mid].gpa_start <= gpa) lo = mid + 1; else hi = mid;
    }
    if (lo == 0) return NULL;
    const mem_region_t *m = &r[lo - 1];
    uint64_t off = gpa - m->gpa_start;
    if (off >= m->size || len > m->size - off) return NULL;   /* outside, or crosses the end */
    return m->hva + off;
}

Points: this is what a VMM (QEMU, Firecracker, KVM's memslots) does to turn a guest physical address from a device or exit into a host pointer. Keep regions sorted for O(log n) lookup (KVM caches the last-used slot too); check that the whole access fits inside one region (an access crossing two regions must be split); return NULL for MMIO holes so the caller emulates a device instead. Never trust guest-supplied addresses and lengths: overflow-safe checks (len > size - off) matter here because the guest is untrusted.