# build the 4 level page tables for one user page # everything here only writes small entries we construct, so its f64 safe const PTE_ADDR = 0x000FFFFFFFFFF000 fn pte_index(virtual_address, level) -> num do return (virtual_address shr (12 + 9 * level)) band 0x1ff end fn next_table(table, index) -> num do const slot = table + index * 8 const entry = mem_read(slot, 8) if (entry band 1) != 0 do return entry band PTE_ADDR end const frame = frame_alloc() mem_zero(frame, 4096) mem_write(slot, frame bor 7, 8) # present | write | user return frame end fn as_map(pml4, virtual_address, physical_address, flags) do const pdpt = next_table(pml4, pte_index(virtual_address, 3)) const pd = next_table(pdpt, pte_index(virtual_address, 2)) const pt = next_table(pd, pte_index(virtual_address, 1)) mem_write(pt + pte_index(virtual_address, 0) * 8, (physical_address band PTE_ADDR) bor flags bor 1, 8) invlpg(virtual_address) end