-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathgdt.rs
445 lines (377 loc) · 14 KB
/
gdt.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! GDT Handler
//!
//! The Global Descriptor Table is responsible for segmentation of memory. In
//! our case though, we don't really care about that.
#![allow(dead_code)]
use sync::{SpinLock, Once};
use bit_field::BitField;
use core::mem::{self, size_of};
use core::ops::{Deref, DerefMut};
use core::slice;
use core::fmt;
use i386::{PrivilegeLevel, TssStruct};
use i386::structures::gdt::SegmentSelector;
use i386::instructions::tables::{lgdt, sgdt, DescriptorTablePointer};
use i386::instructions::segmentation::*;
use paging::PAGE_SIZE;
use paging::{MappingFlags, kernel_memory::get_kernel_memory};
use frame_allocator::{FrameAllocator, FrameAllocatorTrait};
use mem::VirtualAddress;
use alloc::vec::Vec;
use utils::align_up;
static GDT: Once<SpinLock<GdtManager>> = Once::new();
/// The global LDT used by all the processes.
static GLOBAL_LDT: Once<DescriptorTable> = Once::new();
/// Initializes the GDT.
///
/// Creates a GDT with a flat memory segmentation model. It will create 3 kernel
/// segments (code, data, stack), three user segments (code, data, stack), an
/// LDT, and a TSS for the main task.
///
/// This function should only be called once. Further calls will be silently
/// ignored.
pub fn init_gdt() {
use i386::instructions::tables::{lldt, ltr};
let ldt = GLOBAL_LDT.call_once(|| DescriptorTable::new());
GDT.call_once(|| {
let mut gdt = DescriptorTable::new();
// Push the null descriptor
gdt.push(DescriptorTableEntry::null_descriptor());
// Push a kernel code segment
gdt.push(DescriptorTableEntry::new(
0,
0xffffffff,
true,
PrivilegeLevel::Ring0,
));
// Push a kernel data segment
gdt.push(DescriptorTableEntry::new(
0,
0xffffffff,
false,
PrivilegeLevel::Ring0,
));
// Push a kernel stack segment
gdt.push(DescriptorTableEntry::new(
0,
0xffffffff,
false,
PrivilegeLevel::Ring0,
));
// Push a userland code segment
gdt.push(DescriptorTableEntry::new(
0,
0xffffffff,
true,
PrivilegeLevel::Ring3,
));
// Push a userland data segment
gdt.push(DescriptorTableEntry::new(
0,
0xffffffff,
false,
PrivilegeLevel::Ring3,
));
// Push a userland stack segment
gdt.push(DescriptorTableEntry::new(
0,
0xffffffff,
false,
PrivilegeLevel::Ring3,
));
// Global LDT
gdt.push(DescriptorTableEntry::new_ldt(ldt, PrivilegeLevel::Ring0));
let main_task = unsafe {
(MAIN_TASK.addr() as *mut TssStruct).as_ref().unwrap()
};
// Main task
gdt.push(DescriptorTableEntry::new_tss(main_task, PrivilegeLevel::Ring0, 0x2001));
info!("Loading GDT");
let gdt = SpinLock::new(GdtManager::load(gdt, 0x8, 0x10, 0x18));
unsafe {
info!("Loading LDT");
lldt(SegmentSelector(7 << 3));
info!("Loading Task");
ltr(SegmentSelector(8 << 3));
}
gdt
});
}
struct GdtManager {
unloaded_table: Option<DescriptorTable>,
}
impl GdtManager {
pub fn load(cur_loaded: DescriptorTable, new_cs: u16, new_ds: u16, new_ss: u16) -> GdtManager {
let clone = cur_loaded.clone();
info!("{:#?}", cur_loaded);
cur_loaded.load_global(new_cs, new_ds, new_ss);
GdtManager {
unloaded_table: Some(clone)
}
}
pub fn commit(&mut self, new_cs: u16, new_ds: u16, new_ss: u16) {
let old_table = self.unloaded_table.take()
.expect("Commit to not be called recursively")
.load_global(new_cs, new_ds, new_ss);
unsafe {
self.unloaded_table = Some(DescriptorTable {
table: Vec::from_raw_parts(
old_table.base as *mut DescriptorTableEntry,
old_table.limit as usize / size_of::<DescriptorTableEntry>(),
old_table.limit as usize / size_of::<DescriptorTableEntry>())
});
}
self.set_from_loaded()
}
}
impl Deref for GdtManager {
type Target = DescriptorTable;
fn deref(&self) -> &DescriptorTable {
self.unloaded_table.as_ref().expect("Deref should not be called during commit")
}
}
impl DerefMut for GdtManager {
fn deref_mut(&mut self) -> &mut DescriptorTable {
self.unloaded_table.as_mut().expect("DerefMut should not be called during commit")
}
}
/// Push a task segment.
pub fn push_task_segment(task: &'static TssStruct) -> u16 {
info!("Pushing TSS: {:#?}", task);
let mut gdt = GDT.try().unwrap().lock();
let idx = gdt.push(DescriptorTableEntry::new_tss(task, PrivilegeLevel::Ring0, 0));
gdt.commit(0x8, 0x10, 0x18);
idx
}
lazy_static! {
/// VirtualAddress of the TSS structure of the main task. Has 0x2001 bytes
/// available after the TssStruct to encode the IOPB of the current process.
pub static ref MAIN_TASK: VirtualAddress = {
// We need TssStruct + 0x2001 bytes of IOPB.
let pregion = FrameAllocator::allocate_region(align_up(size_of::<TssStruct>() + 0x2001, PAGE_SIZE))
.expect("Failed to allocate physical region for tss MAIN_TASK");
let vaddr = get_kernel_memory().map_phys_region(pregion, MappingFlags::WRITABLE);
let tss = vaddr.addr() as *mut TssStruct;
unsafe {
*tss = TssStruct::new();
// Now, set the IOPB to 0xFF to prevent all userland accesses
slice::from_raw_parts_mut(tss.offset(1) as *mut u8, 0x2001).iter_mut().for_each(|v| *v = 0xFF);
}
vaddr
};
}
// TODO: gdt::get_main_iopb does not prevent creation of multiple mut ref.
// BODY: There's currently no guarantee that we don't create multiple &mut
// BODY: pointer to the IOPB region, which would cause undefined behavior. In
// BODY: practice, it should only be used by `i386::process_switch`, and as such,
// BODY: there is never actually two main_iopb active at the same time. Still,
// BODY: it'd be nicer to have safe functions to access the IOPB.
/// Get the IOPB of the Main Task.
///
/// # Safety
///
/// This function can be used to create multiple mut references to the same
/// region, which is very UB. Care should be taken to make sure any old mut slice
/// acquired through this method is dropped before it is called again.
pub unsafe fn get_main_iopb() -> &'static mut [u8] {
slice::from_raw_parts_mut((MAIN_TASK.addr() as *mut TssStruct).offset(1) as *mut u8, 0x2001)
}
/// A structure containing our GDT.
#[derive(Debug, Clone)]
struct DescriptorTable {
table: Vec<DescriptorTableEntry>,
}
impl DescriptorTable {
/// Create an empty GDT. This will **not** include the null entry, so make
/// sure you add it!
pub fn new() -> DescriptorTable {
DescriptorTable {
table: Vec::new()
}
}
/// Fill the current DescriptorTable with a copy of the currently loaded entries.
pub fn set_from_loaded(&mut self) {
use core::slice;
let loaded_ptr = sgdt();
let loaded_table = unsafe {
slice::from_raw_parts(loaded_ptr.base as *mut DescriptorTableEntry, loaded_ptr.limit as usize / size_of::<DescriptorTableEntry>())
};
self.table.clear();
self.table.extend_from_slice(loaded_table);
}
/// Push a new entry to the table, returning a segment selector to it.
pub fn push(&mut self, entry: DescriptorTableEntry) -> u16 {
let ret = self.table.len() << 3;
self.table.push(entry);
ret as u16
}
fn load_global(mut self, new_cs: u16, new_ds: u16, new_ss: u16) -> DescriptorTablePointer {
self.table.shrink_to_fit();
assert_eq!(self.table.len(), self.table.capacity());
let ptr = DescriptorTablePointer {
base: self.table.as_ptr() as u32,
limit: (self.table.len() * size_of::<DescriptorTableEntry>() - 1) as u16,
};
let oldptr = sgdt();
// TODO: Figure out how to chose CS.
unsafe {
lgdt(&ptr);
// Reload segment selectors
set_cs(SegmentSelector(new_cs));
load_ds(SegmentSelector(new_ds));
load_es(SegmentSelector(new_ds));
load_fs(SegmentSelector(new_ds));
load_gs(SegmentSelector(new_ds));
load_ss(SegmentSelector(new_ss));
}
mem::forget(self.table);
oldptr
}
}
#[derive(Debug, Clone, Copy)]
enum SystemDescriptorTypes {
AvailableTss16 = 1,
Ldt = 2,
BusyTss16 = 3,
CallGate16 = 4,
TaskGate = 5,
InterruptGate16 = 6,
TrapGate16 = 7,
AvailableTss32 = 9,
BusyTss32 = 11,
CallGate32 = 12,
InterruptGate32 = 14,
TrapGate32 = 15
}
#[repr(transparent)]
#[derive(Clone, Copy)]
struct DescriptorTableEntry(u64);
impl fmt::Debug for DescriptorTableEntry {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
//ES =0010 00000000 ffffffff 00c09300 DPL=0 DS [-WA]
if self.0 == 0 {
write!(f, "DescriptorTableEntry(NULLDESC)")
} else {
let ty = if self.0.get_bit(44) && self.0.get_bit(43) {
"CS"
} else if self.0.get_bit(44) {
"DS"
} else {
match self.0.get_bits(40..44) {
1 => "TSS16-avl",
2 => "LDT",
3 => "TSS16-busy",
4 => "CALL16",
5 => "TASK",
6 => "INT16",
7 => "TRAP16",
9 => "TSS32-avl",
11 => "TSS32-busy",
12 => "CALL32",
14 => "INT32",
15 => "TRAP32",
_ => "UNKN"
}
};
write!(f, "DescriptorTableEntry(base={:#010x}, limit={:#010x}, flags={:#010x}, DPL={:?}, type={})",
self.get_base(), self.get_limit(), self.0, self.get_ring_level(), ty)
}
}
}
impl DescriptorTableEntry {
pub fn null_descriptor() -> DescriptorTableEntry {
DescriptorTableEntry(0)
}
/// Creates an empty GDT descriptor, but with some flags set correctly
pub fn new(base: u32, limit: u32, is_code: bool, priv_level: PrivilegeLevel) -> DescriptorTableEntry {
let mut gdt = Self::null_descriptor();
// First, the constant values.
// We always allow read access for code, and write access for data.
gdt.0.set_bit(41, true);
// Make extra sure we don't touch is_conformant by a million miles pole.
gdt.0.set_bit(42, false);
// This bit is set to 1 for segment descriptors, 0 for system descriptors.
gdt.0.set_bit(44, true);
// The segment is present.
gdt.0.set_bit(47, true);
// The size is always 32-bit protected mode.
gdt.0.set_bit(54, true);
gdt.0.set_bit(43, is_code);
gdt.0.set_bits(45..47, priv_level as u64);
gdt.set_base(base);
gdt.set_limit(limit);
gdt
}
/// Creates an empty GDT descriptor, but with some flags set correctly
pub fn new_system(ty: SystemDescriptorTypes, base: u32, limit: u32, priv_level: PrivilegeLevel) -> DescriptorTableEntry {
let mut gdt = Self::null_descriptor();
// Set the system descriptor type
gdt.0.set_bits(40..44, ty as u64);
// Set the privilege level.
gdt.0.set_bits(45..47, priv_level as u64);
// The segment is present.
gdt.0.set_bit(47, true);
gdt.set_base(base);
gdt.set_limit(limit);
gdt
}
/// Creates a new LDT descriptor.
pub fn new_ldt(base: &'static DescriptorTable, priv_level: PrivilegeLevel) -> DescriptorTableEntry {
let limit = if base.table.len() == 0 { 0 } else { base.table.len() * size_of::<DescriptorTableEntry>() - 1 };
Self::new_system(SystemDescriptorTypes::Ldt, base as *const _ as u32, limit as u32, priv_level)
}
/// Creates a GDT descriptor pointing to a TSS segment
pub fn new_tss(base: &'static TssStruct, priv_level: PrivilegeLevel, iobp_size: usize) -> DescriptorTableEntry {
Self::new_system(SystemDescriptorTypes::AvailableTss32, base as *const _ as u32, (size_of::<TssStruct>() + iobp_size - 1) as u32, priv_level)
}
fn get_limit(&self) -> u32 {
(self.0.get_bits(0..16) as u32) | ((self.0.get_bits(48..52) << 16) as u32)
}
fn set_limit(&mut self, mut newlimit: u32) {
if newlimit > 65536 && (newlimit & 0xFFF) != 0xFFF {
panic!("Limit {} is invalid", newlimit);
}
if newlimit > 65536 {
newlimit = newlimit >> 12;
self.set_4k_granularity(true);
}
self.0.set_bits(0..16, newlimit.get_bits(0..16) as u64);
self.0.set_bits(48..52, newlimit.get_bits(16..20) as u64);
}
fn get_base(&self) -> u32 {
(self.0.get_bits(16..40) as u32) | ((self.0.get_bits(56..64) << 24) as u32)
}
fn set_base(&mut self, newbase: u32) {
self.0.set_bits(16..40, newbase.get_bits(0..24) as u64);
self.0.set_bits(56..64, newbase.get_bits(24..32) as u64);
}
pub fn get_accessed(&self) -> bool {
self.0.get_bit(40)
}
pub fn is_readwrite_allowed(&self) -> bool {
self.0.get_bit(41)
}
// TODO: also gets direction
pub fn is_comformant(&self) -> bool {
self.0.get_bit(42)
}
pub fn is_executable(&self) -> bool {
self.0.get_bit(43)
}
// bit 44 is unused
pub fn get_ring_level(&self) -> PrivilegeLevel {
PrivilegeLevel::from_u16(self.0.get_bits(45..47) as u16)
}
pub fn get_present(&self) -> bool {
self.0.get_bit(47)
}
pub fn is_4k_granularity(&self) -> bool {
self.0.get_bit(55)
}
fn set_4k_granularity(&mut self, is: bool) {
self.0.set_bit(55, is);
}
pub fn is_32bit(&self) -> bool {
self.0.get_bit(54)
}
}