</>EmbeddedInterview

Implement a simple shadow page table mapping in C.

HardCoding: Systems, Bitmaps & Virtualization

Short answer: A shadow page table maps guest virtual pages directly to host physical pages. The hypervisor derives the mapping from guest page tables and its own guest-physical-to-host-physical mappings. This small software model uses 4 KB pages and a fixed table.

#include <stdint.h>
#include <stdbool.h>
#define N 64
#define MASK UINT64_C(0xfff)

struct shadow {
    bool valid, writable;
    uint64_t gva, hpa;
};
static struct shadow table[N];

bool shadow_map(uint64_t gva, uint64_t hpa, bool write)
{
    if ((gva | hpa) & MASK) return false;
    struct shadow *free_slot = 0;
    for (int i = 0; i < N; i++) {
        if (table[i].valid && table[i].gva == gva) {
            table[i] = (struct shadow){true, write, gva, hpa};
            return true;
        }
        if (!table[i].valid && !free_slot) free_slot = &table[i];
    }
    if (!free_slot) return false;
    *free_slot = (struct shadow){true, write, gva, hpa};
    return true;
}

bool shadow_lookup(uint64_t va, bool write, uint64_t *pa)
{
    for (int i = 0; i < N; i++)
        if (table[i].valid && table[i].gva == (va & ~MASK)) {
            if (write && !table[i].writable) return false;
            *pa = table[i].hpa | (va & MASK);
            return true;
        }
    return false;
}

Example: GVA 0x4123 maps through page 0x4000 to host frame 0x9000, producing HPA 0x9123. Real shadow tables must combine permissions, track guest page-table changes and invalidate stale TLB entries. Hardware stage-2 translation (ARM) or EPT (Intel) normally avoids this software shadowing. Assume serialized access and one guest address space.