Max OS 0.3
Loading...
Searching...
No Matches
gdt.cpp
Go to the documentation of this file.
1
9#include <system/gdt.h>
10#include <common/logger.h>
11
12using namespace MaxOS;
13using namespace MaxOS::system;
14
19{
20
21 // Null descriptor
22 table[0] = 0;
23
24 // Kernel Code Segment descriptor
25 uint64_t kernel_cs = 0;
26 kernel_cs |= (uint64_t) DescriptorFlags::Write;
27 kernel_cs |= (uint64_t) DescriptorFlags::Execute;
28 kernel_cs |= (uint64_t) DescriptorFlags::CodeOrDataSegment;
29 kernel_cs |= (uint64_t) DescriptorFlags::Present;
30 kernel_cs |= (uint64_t) DescriptorFlags::LongMode;
31 table[1] = kernel_cs;
32
33 // Kernel Data Segment descriptor
34 uint64_t kernel_ds = 0;
35 kernel_ds |= (uint64_t) DescriptorFlags::Write;
36 kernel_ds |= (uint64_t) DescriptorFlags::CodeOrDataSegment;
37 kernel_ds |= (uint64_t) DescriptorFlags::Present;
38 table[2] = kernel_ds;
39
40 // User code segment descriptor (Change the privilege level to 3)
41 uint64_t user_cs = 0;
42 user_cs |= (uint64_t) DescriptorFlags::Write;
43 user_cs |= (uint64_t) DescriptorFlags::Execute;
44 user_cs |= (uint64_t) DescriptorFlags::CodeOrDataSegment;
45 user_cs |= (uint64_t) DescriptorFlags::Present;
46 user_cs |= (uint64_t) DescriptorFlags::LongMode;
47 user_cs |= (3ULL << 45);
48 table[3] = user_cs;
49
50 // User data segment descriptor (Change the privilege level to 3)
51 uint64_t user_ds = 0;
52 user_ds |= (uint64_t) DescriptorFlags::Write;
53 user_ds |= (uint64_t) DescriptorFlags::CodeOrDataSegment;
54 user_ds |= (uint64_t) DescriptorFlags::Present;
55 user_ds |= (3ULL << 45);
56 table[4] = user_ds;
57
58 // Reserve space for the TSS
59 table[5] = 0;
60 table[6] = 0;
61
62 // Load the GDT
63 load();
64
65 // Reload the segment registers
66 asm volatile("mov %0, %%ds" : : "r"(0x10));
67 asm volatile("mov %0, %%es" : : "r"(0x10));
68 asm volatile("mov %0, %%fs" : : "r"(0x10));
69 asm volatile("mov %0, %%gs" : : "r"(0x10));
70 asm volatile("mov %0, %%ss" : : "r"(0x10));
71 Logger::DEBUG() << "Reloaded segment registers\n";
72}
73
78 gdtr = {
79 .size = sizeof(table) - 1,
80 .address = (uint64_t) table,
81 };
82 asm volatile("lgdt %0" : : "m"(gdtr));
83 Logger::DEBUG() << "Loaded GDT of limit 0x" << (uint64_t) gdtr.size << " and address 0x" << (uint64_t) gdtr.address << "\n";
84
85}
86
87GlobalDescriptorTable::~GlobalDescriptorTable() = default;
static Logger DEBUG()
Gets active logger set to DEBUG level.
Definition logger.cpp:193
void load()
Loads the GDT into the CPU.
Definition gdt.cpp:77
gdtr_t gdtr
The GDTR structure.
Definition gdt.h:61
uint64_t table[7]
The GDT entries.
Definition gdt.h:59
GlobalDescriptorTable()
Construct a new Global Descriptor Table object and set up the GDT entries and load it into the CPU,...
Definition gdt.cpp:18
Defines a Global Descriptor Table (GDT) for setting up memory segments in protected mode.
Defines a Logger class for logging messages with different severity levels to multiple output streams...