Snippets

Scoopta paging.c

Created by Scoopta
/*
 *  Copyright (C) 2019 Scoopta
 *  This file is part of NekOS
 *  NekOS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    NekOS is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NekOS.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <paging.h>

struct _cr3 {
	uint64_t padding1:3;
	uint64_t writethrough:1;
	uint64_t cache_disable:1;
	uint64_t padding2:7;
	uint64_t base_addr:40;
	uint64_t padding3:12;
} __attribute__((packed));

struct _pml4 {
	uint64_t present:1;
	uint64_t read_write:1;
	uint64_t user:1;
	uint64_t writethrough:1;
	uint64_t cache_disable:1;
	uint64_t accessed:1;
	uint64_t padding1:6;
	uint64_t base_addr:40;
	uint64_t padding2:11;
	uint64_t no_exec:1;
} __attribute__((packed));

struct _pt {
	uint64_t present:1;
	uint64_t read_write:1;
	uint64_t user:1;
	uint64_t writethrough:1;
	uint64_t cache_disable:1;
	uint64_t accessed:1;
	uint64_t dirty:1;
	uint64_t attribute_table:1;
	uint64_t global:1;
	uint64_t padding1:3;
	uint64_t base_addr:40;
	uint64_t padding2:11;
	uint64_t no_exec:1;
} __attribute__((packed));

uint64_t get_cr3() {
	struct _cr3 cr3;
	__asm__ __volatile__("movq %%cr3, %0"
			: "=r" (cr3));
	return cr3.base_addr << 12;
}

void get_pdp() {
	struct _pml4* pml4 = (struct _pml4*) get_cr3();
	kprintf("PML4: 0x%X\n", pml4);
	struct _pml4* pdp = (struct _pml4*) (uint64_t) (pml4->base_addr << 12);
	kprintf("PDP: 0x%X\n", pdp);
	struct _pml4* pd = (struct _pml4*) (uint64_t) (pdp->base_addr << 12);
	kprintf("PD: 0x%X\n", pd);
	uint16_t index = 504;
	kprintf("Present: %u\n", pd[index].present);
	kprintf("Base Addr: 0x%X\n", pd[index].base_addr);
	struct _pt* pt = (struct _pt*) (uint64_t) (pd[index].base_addr << 12);
	kprintf("PT: 0x%X\n", pt);
	kprintf("Present: %u\n", pt->present);
	kprintf("Addr: 0x%X\n", pt->base_addr << 12);
	kprintf("Read/Write: %u\n", pt->read_write);
}

Comments (0)