Files

50 lines
1.9 KiB
C

#include "../includes/gdt.h"
/* Code taken from http://www.osdever.net/bkerndev/Docs/gdt.htm with some minor tweaks. */
struct gdt_entry gdt_entries[3];
struct gdt gdt_ptr;
/* Should be called by main. This will setup the special GDT
* pointer, set up the first 3 entries in our GDT, and then
* finally call load_gdt() in our assembler file in order
* to tell the processor where the new GDT is and update the
* new segment registers */
void gdt_install()
{
/* Setup the GDT pointer and the size of the table */
gdt_ptr.size = sizeof(struct gdt_entry) * 3 - 1;
gdt_ptr.address = (unsigned int) &gdt_entries;
/* Our NULL descriptor */
gdt_set_gate(0, 0, 0, 0, &gdt_entries[0]);
/* The second entry is our Code Segment. The base address
* is 0, the limit is 4GBytes, it uses 4KByte granularity,
* uses 32-bit opcodes, and is a Code Segment descriptor.
* Please check the table above in the tutorial in order
* to see exactly what each value means */
gdt_set_gate(0, 0xFFFFFFFF, 0x9A, 0xCF, &gdt_entries[1]);
/* The third entry is our Data Segment. It's EXACTLY the
* same as our code segment, but the descriptor type in
* this entry's access byte says it's a Data Segment */
gdt_set_gate(0, 0xFFFFFFFF, 0x92, 0xCF, &gdt_entries[2]);
/* Flush out the old GDT and install the new changes! */
load_gdt(&gdt_ptr);
}
void gdt_set_gate(unsigned long base, unsigned long limit, unsigned char access, unsigned char gran, struct gdt_entry* gdt_entry)
{
/* Setup the descriptor base address */
gdt_entry->base_low = (base & 0xFFFF);
gdt_entry->base_middle = (base >> 16) & 0xFF;
gdt_entry->base_high = (base >> 24) & 0xFF;
/* Setup the descriptor limits */
gdt_entry->limit_low = (limit & 0xFFFF);
gdt_entry->granularity = ((limit >> 16) & 0x0F);
/* Finally, set up the granularity and access flags */
gdt_entry->granularity |= (gran & 0xF0);
gdt_entry->access = access;
}