forked from rust-osdev/bootloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.rs
694 lines (628 loc) · 23.5 KB
/
config.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
use crate::{concat::*, version_info};
/// Allows configuring the bootloader behavior.
///
/// TODO: describe use together with `entry_point` macro
/// TODO: example
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[non_exhaustive]
pub struct BootloaderConfig {
/// The version of the bootloader API.
///
/// Automatically generated from the crate version. Checked on deserialization to
/// ensure that the kernel and bootloader use the same API version, i.e. the same config
/// and boot info format.
pub(crate) version: ApiVersion,
/// Configuration for (optional) page table mappings created by the bootloader.
pub mappings: Mappings,
/// The size of the stack that the bootloader should allocate for the kernel (in bytes).
///
/// The bootloader starts the kernel with a valid stack pointer. This setting defines
/// the stack size that the bootloader should allocate and map. The stack is created
/// with a guard page, so a stack overflow will lead to a page fault.
pub kernel_stack_size: u64,
/// Configuration for the frame buffer that can be used by the kernel to display pixels
/// on the screen.
pub frame_buffer: FrameBuffer,
/// Configuration for changing the level of the filter of the messages that are shown in the
/// screen when booting. The default is 'Trace'.
pub log_level: LevelFilter,
/// Whether the bootloader should print log messages to the framebuffer when booting.
///
/// Enabled by default.
pub frame_buffer_logger_status: LoggerStatus,
/// Whether the bootloader should print log messages to the serial port when booting.
///
/// Enabled by default.
pub serial_logger_status: LoggerStatus,
}
impl BootloaderConfig {
pub(crate) const UUID: [u8; 16] = [
0x74, 0x3C, 0xA9, 0x61, 0x09, 0x36, 0x46, 0xA0, 0xBB, 0x55, 0x5C, 0x15, 0x89, 0x15, 0x25,
0x3D,
];
#[doc(hidden)]
pub const SERIALIZED_LEN: usize = 127;
/// Creates a new default configuration with the following values:
///
/// - `kernel_stack_size`: 80kiB
/// - `mappings`: See [`Mappings::new_default()`]
/// - `frame_buffer`: See [`FrameBuffer::new_default()`]
pub const fn new_default() -> Self {
Self {
kernel_stack_size: 80 * 1024,
version: ApiVersion::new_default(),
mappings: Mappings::new_default(),
frame_buffer: FrameBuffer::new_default(),
log_level: LevelFilter::Trace,
frame_buffer_logger_status: LoggerStatus::Enable,
serial_logger_status: LoggerStatus::Enable,
}
}
/// Serializes the configuration to a byte array.
///
/// This is used by the [`crate::entry_point`] macro to store the configuration in a
/// dedicated section in the resulting ELF file.
pub const fn serialize(&self) -> [u8; Self::SERIALIZED_LEN] {
let Self {
version,
mappings,
kernel_stack_size,
frame_buffer,
log_level,
frame_buffer_logger_status,
serial_logger_status,
} = self;
let ApiVersion {
version_major,
version_minor,
version_patch,
pre_release,
} = version;
let Mappings {
kernel_stack,
boot_info,
framebuffer,
physical_memory,
page_table_recursive,
aslr,
dynamic_range_start,
dynamic_range_end,
ramdisk_memory,
} = mappings;
let FrameBuffer {
minimum_framebuffer_height,
minimum_framebuffer_width,
} = frame_buffer;
let version = {
let one = concat_2_2(version_major.to_le_bytes(), version_minor.to_le_bytes());
let two = concat_2_1(version_patch.to_le_bytes(), [*pre_release as u8]);
concat_4_3(one, two)
};
let buf = concat_16_7(Self::UUID, version);
let buf = concat_23_8(buf, kernel_stack_size.to_le_bytes());
let buf = concat_31_9(buf, kernel_stack.serialize());
let buf = concat_40_9(buf, boot_info.serialize());
let buf = concat_49_9(buf, framebuffer.serialize());
let buf = concat_58_10(
buf,
match physical_memory {
Option::None => [0; 10],
Option::Some(m) => concat_1_9([1], m.serialize()),
},
);
let buf = concat_68_10(
buf,
match page_table_recursive {
Option::None => [0; 10],
Option::Some(m) => concat_1_9([1], m.serialize()),
},
);
let buf = concat_78_1(buf, [(*aslr) as u8]);
let buf = concat_79_9(
buf,
match dynamic_range_start {
Option::None => [0; 9],
Option::Some(addr) => concat_1_8([1], addr.to_le_bytes()),
},
);
let buf = concat_88_9(
buf,
match dynamic_range_end {
Option::None => [0; 9],
Option::Some(addr) => concat_1_8([1], addr.to_le_bytes()),
},
);
let buf = concat_97_9(buf, ramdisk_memory.serialize());
let buf = concat_106_9(
buf,
match minimum_framebuffer_height {
Option::None => [0; 9],
Option::Some(addr) => concat_1_8([1], addr.to_le_bytes()),
},
);
let buf = concat_115_9(
buf,
match minimum_framebuffer_width {
Option::None => [0; 9],
Option::Some(addr) => concat_1_8([1], addr.to_le_bytes()),
},
);
let log_level = concat_124_1(buf, (*log_level as u8).to_le_bytes());
let frame_buffer_logger_status =
concat_125_1(log_level, (*frame_buffer_logger_status as u8).to_le_bytes());
concat_126_1(
frame_buffer_logger_status,
(*serial_logger_status as u8).to_le_bytes(),
)
}
/// Tries to deserialize a config byte array that was created using [`Self::serialize`].
///
/// This is used by the bootloader to deserialize the configuration given in the kernel's
/// ELF file.
///
/// TODO: return error enum
pub fn deserialize(serialized: &[u8]) -> Result<Self, &'static str> {
if serialized.len() != Self::SERIALIZED_LEN {
return Err("invalid len");
}
let s = serialized;
let (uuid, s) = split_array_ref(s);
if uuid != &Self::UUID {
return Err("invalid UUID");
}
let (version, s) = {
let (&major, s) = split_array_ref(s);
let (&minor, s) = split_array_ref(s);
let (&patch, s) = split_array_ref(s);
let (&pre, s) = split_array_ref(s);
let pre = match pre {
[0] => false,
[1] => true,
_ => return Err("invalid pre version"),
};
let version = ApiVersion {
version_major: u16::from_le_bytes(major),
version_minor: u16::from_le_bytes(minor),
version_patch: u16::from_le_bytes(patch),
pre_release: pre,
};
(version, s)
};
// TODO check version against this crate version -> error if they're different
let (&kernel_stack_size, s) = split_array_ref(s);
let (mappings, s) = {
let (&kernel_stack, s) = split_array_ref(s);
let (&boot_info, s) = split_array_ref(s);
let (&framebuffer, s) = split_array_ref(s);
let (&physical_memory_some, s) = split_array_ref(s);
let (&physical_memory, s) = split_array_ref(s);
let (&page_table_recursive_some, s) = split_array_ref(s);
let (&page_table_recursive, s) = split_array_ref(s);
let (&[alsr], s) = split_array_ref(s);
let (&dynamic_range_start_some, s) = split_array_ref(s);
let (&dynamic_range_start, s) = split_array_ref(s);
let (&dynamic_range_end_some, s) = split_array_ref(s);
let (&dynamic_range_end, s) = split_array_ref(s);
let (&ramdisk_memory, s) = split_array_ref(s);
let mappings = Mappings {
kernel_stack: Mapping::deserialize(&kernel_stack)?,
boot_info: Mapping::deserialize(&boot_info)?,
framebuffer: Mapping::deserialize(&framebuffer)?,
physical_memory: match physical_memory_some {
[0] if physical_memory == [0; 9] => Option::None,
[1] => Option::Some(Mapping::deserialize(&physical_memory)?),
_ => return Err("invalid phys memory value"),
},
page_table_recursive: match page_table_recursive_some {
[0] if page_table_recursive == [0; 9] => Option::None,
[1] => Option::Some(Mapping::deserialize(&page_table_recursive)?),
_ => return Err("invalid page table recursive value"),
},
aslr: match alsr {
1 => true,
0 => false,
_ => return Err("invalid aslr value"),
},
dynamic_range_start: match dynamic_range_start_some {
[0] if dynamic_range_start == [0; 8] => Option::None,
[1] => Option::Some(u64::from_le_bytes(dynamic_range_start)),
_ => return Err("invalid dynamic range start value"),
},
dynamic_range_end: match dynamic_range_end_some {
[0] if dynamic_range_end == [0; 8] => Option::None,
[1] => Option::Some(u64::from_le_bytes(dynamic_range_end)),
_ => return Err("invalid dynamic range end value"),
},
ramdisk_memory: Mapping::deserialize(&ramdisk_memory)?,
};
(mappings, s)
};
let (frame_buffer, s) = {
let (&min_framebuffer_height_some, s) = split_array_ref(s);
let (&min_framebuffer_height, s) = split_array_ref(s);
let (&min_framebuffer_width_some, s) = split_array_ref(s);
let (&min_framebuffer_width, s) = split_array_ref(s);
let frame_buffer = FrameBuffer {
minimum_framebuffer_height: match min_framebuffer_height_some {
[0] if min_framebuffer_height == [0; 8] => Option::None,
[1] => Option::Some(u64::from_le_bytes(min_framebuffer_height)),
_ => return Err("minimum_framebuffer_height invalid"),
},
minimum_framebuffer_width: match min_framebuffer_width_some {
[0] if min_framebuffer_width == [0; 8] => Option::None,
[1] => Option::Some(u64::from_le_bytes(min_framebuffer_width)),
_ => return Err("minimum_framebuffer_width invalid"),
},
};
(frame_buffer, s)
};
let (&log_level, s) = split_array_ref(s);
let log_level = LevelFilter::from_u8(u8::from_le_bytes(log_level));
let log_level = match log_level {
Option::Some(level) => level,
Option::None => return Err("log_level invalid"),
};
let (&frame_buffer_logger_status, s) = split_array_ref(s);
let frame_buffer_logger_status =
LoggerStatus::from_u8(u8::from_le_bytes(frame_buffer_logger_status));
let frame_buffer_logger_status = match frame_buffer_logger_status {
Option::Some(status) => status,
Option::None => return Err("frame_buffer_logger_status invalid"),
};
let (&serial_logger_status, s) = split_array_ref(s);
let serial_logger_status = LoggerStatus::from_u8(u8::from_le_bytes(serial_logger_status));
let serial_logger_status = match serial_logger_status {
Option::Some(status) => status,
Option::None => return Err("serial_logger_status invalid"),
};
if !s.is_empty() {
return Err("unexpected rest");
}
Ok(Self {
version,
kernel_stack_size: u64::from_le_bytes(kernel_stack_size),
mappings,
frame_buffer,
log_level,
frame_buffer_logger_status,
serial_logger_status,
})
}
#[cfg(test)]
fn random() -> Self {
Self {
version: ApiVersion::random(),
mappings: Mappings::random(),
kernel_stack_size: rand::random(),
frame_buffer: FrameBuffer::random(),
log_level: LevelFilter::Trace,
frame_buffer_logger_status: LoggerStatus::Enable,
serial_logger_status: LoggerStatus::Enable,
}
}
}
impl Default for BootloaderConfig {
fn default() -> Self {
Self::new_default()
}
}
/// A semver-compatible version.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(C)]
pub struct ApiVersion {
/// Bootloader version (major).
version_major: u16,
/// Bootloader version (minor).
version_minor: u16,
/// Bootloader version (patch).
version_patch: u16,
/// Whether the bootloader API version is a pre-release.
///
/// We can't store the full prerelease string of the version number since it could be
/// arbitrarily long.
pre_release: bool,
}
impl ApiVersion {
pub(crate) const fn new_default() -> Self {
Self {
version_major: version_info::VERSION_MAJOR,
version_minor: version_info::VERSION_MINOR,
version_patch: version_info::VERSION_PATCH,
pre_release: version_info::VERSION_PRE,
}
}
#[cfg(test)]
fn random() -> ApiVersion {
Self {
version_major: rand::random(),
version_minor: rand::random(),
version_patch: rand::random(),
pre_release: rand::random(),
}
}
/// Returns the major version number.
pub fn version_major(&self) -> u16 {
self.version_major
}
/// Returns the minor version number.
pub fn version_minor(&self) -> u16 {
self.version_minor
}
/// Returns the patch version number.
pub fn version_patch(&self) -> u16 {
self.version_patch
}
/// Returns whether this version is a pre-release, e.g., an alpha version.
pub fn pre_release(&self) -> bool {
self.pre_release
}
}
impl Default for ApiVersion {
fn default() -> Self {
Self::new_default()
}
}
/// Allows to configure the virtual memory mappings created by the bootloader.
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
#[non_exhaustive]
pub struct Mappings {
/// Configures how the kernel stack should be mapped.
pub kernel_stack: Mapping,
/// Specifies where the [`crate::BootInfo`] struct should be placed in virtual memory.
pub boot_info: Mapping,
/// Specifies the mapping of the frame buffer memory region.
pub framebuffer: Mapping,
/// The bootloader supports to map the whole physical memory into the virtual address
/// space at some offset. This is useful for accessing and modifying the page tables set
/// up by the bootloader.
///
/// Defaults to `None`, i.e. no mapping of the physical memory.
pub physical_memory: Option<Mapping>,
/// As an alternative to mapping the whole physical memory (see [`Self::physical_memory`]),
/// the bootloader also has support for setting up a
/// [recursive level 4 page table](https://os.phil-opp.com/paging-implementation/#recursive-page-tables).
///
/// Defaults to `None`, i.e. no recursive mapping.
pub page_table_recursive: Option<Mapping>,
/// Whether to randomize non-statically configured addresses.
/// The kernel base address will be randomized when it's compiled as
/// a position independent executable.
///
/// Defaults to `false`.
pub aslr: bool,
/// The lowest virtual address for dynamic addresses.
///
/// Defaults to `0`.
pub dynamic_range_start: Option<u64>,
/// The highest virtual address for dynamic addresses.
///
/// Defaults to `0xffff_ffff_ffff_f000`.
pub dynamic_range_end: Option<u64>,
/// Virtual address to map ramdisk image, if present on disk
/// Defaults to dynamic
pub ramdisk_memory: Mapping,
}
impl Mappings {
/// Creates a new mapping configuration with dynamic mapping for kernel, boot info and
/// frame buffer. Neither physical memory mapping nor recursive page table creation are
/// enabled.
pub const fn new_default() -> Self {
Self {
kernel_stack: Mapping::new_default(),
boot_info: Mapping::new_default(),
framebuffer: Mapping::new_default(),
physical_memory: Option::None,
page_table_recursive: Option::None,
aslr: false,
dynamic_range_start: None,
dynamic_range_end: None,
ramdisk_memory: Mapping::new_default(),
}
}
#[cfg(test)]
fn random() -> Mappings {
let phys = rand::random();
let recursive = rand::random();
Self {
kernel_stack: Mapping::random(),
boot_info: Mapping::random(),
framebuffer: Mapping::random(),
physical_memory: if phys {
Option::Some(Mapping::random())
} else {
Option::None
},
page_table_recursive: if recursive {
Option::Some(Mapping::random())
} else {
Option::None
},
aslr: rand::random(),
dynamic_range_start: if rand::random() {
Option::Some(rand::random())
} else {
Option::None
},
dynamic_range_end: if rand::random() {
Option::Some(rand::random())
} else {
Option::None
},
ramdisk_memory: Mapping::random(),
}
}
}
/// Configuration for the frame buffer used for graphical output.
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
#[non_exhaustive]
pub struct FrameBuffer {
/// Instructs the bootloader to set up a framebuffer format that has at least the given height.
///
/// If this is not possible, the bootloader will fall back to a smaller format.
pub minimum_framebuffer_height: Option<u64>,
/// Instructs the bootloader to set up a framebuffer format that has at least the given width.
///
/// If this is not possible, the bootloader will fall back to a smaller format.
pub minimum_framebuffer_width: Option<u64>,
}
impl FrameBuffer {
/// Creates a default configuration without any requirements.
pub const fn new_default() -> Self {
Self {
minimum_framebuffer_height: Option::None,
minimum_framebuffer_width: Option::None,
}
}
#[cfg(test)]
fn random() -> FrameBuffer {
Self {
minimum_framebuffer_height: if rand::random() {
Option::Some(rand::random())
} else {
Option::None
},
minimum_framebuffer_width: if rand::random() {
Option::Some(rand::random())
} else {
Option::None
},
}
}
}
/// Specifies how the bootloader should map a memory region into the virtual address space.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Mapping {
/// Look for an unused virtual memory region at runtime.
Dynamic,
/// Try to map the region at the given virtual address.
///
/// The given virtual address must be page-aligned.
///
/// This setting can lead to runtime boot errors if the given address is not aligned,
/// already in use, or invalid for other reasons.
FixedAddress(u64),
}
impl Mapping {
/// Creates a new [`Mapping::Dynamic`].
///
/// This function has identical results as [`Default::default`], the only difference is
/// that this is a `const` function.
pub const fn new_default() -> Self {
Self::Dynamic
}
#[cfg(test)]
fn random() -> Mapping {
let fixed = rand::random();
if fixed {
Self::Dynamic
} else {
Self::FixedAddress(rand::random())
}
}
const fn serialize(&self) -> [u8; 9] {
match self {
Mapping::Dynamic => [0; 9],
Mapping::FixedAddress(addr) => concat_1_8([1], addr.to_le_bytes()),
}
}
fn deserialize(serialized: &[u8; 9]) -> Result<Self, &'static str> {
let (&variant, s) = split_array_ref(serialized);
let (&addr, s) = split_array_ref(s);
if !s.is_empty() {
return Err("invalid mapping format");
}
match variant {
[0] if addr == [0; 8] => Ok(Mapping::Dynamic),
[1] => Ok(Mapping::FixedAddress(u64::from_le_bytes(addr))),
_ => Err("invalid mapping value"),
}
}
}
impl Default for Mapping {
fn default() -> Self {
Self::new_default()
}
}
/// An enum representing the available verbosity level filters of the logger.
///
/// Based on
/// https://github.com/rust-lang/log/blob/dc32ab999f52805d5ce579b526bd9d9684c38d1a/src/lib.rs#L552-565
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LevelFilter {
/// A level lower than all log levels.
Off,
/// Corresponds to the `Error` log level.
Error,
/// Corresponds to the `Warn` log level.
Warn,
/// Corresponds to the `Info` log level.
Info,
/// Corresponds to the `Debug` log level.
Debug,
/// Corresponds to the `Trace` log level.
Trace,
}
impl LevelFilter {
/// Converts a u8 into a Option<LevelFilter>
pub fn from_u8(value: u8) -> Option<LevelFilter> {
match value {
0 => Some(Self::Off),
1 => Some(Self::Error),
2 => Some(Self::Warn),
3 => Some(Self::Info),
4 => Some(Self::Debug),
5 => Some(Self::Trace),
_ => None,
}
}
}
/// An enum for enabling or disabling the different methods for logging.
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LoggerStatus {
/// This method of logging is disabled
Disable,
/// This method of logging is enabled
Enable,
}
impl LoggerStatus {
/// Converts an u8 into a Option<LoggerStatus>
pub fn from_u8(value: u8) -> Option<LoggerStatus> {
match value {
0 => Some(Self::Disable),
1 => Some(Self::Enable),
_ => None,
}
}
}
/// Taken from https://github.com/rust-lang/rust/blob/e100ec5bc7cd768ec17d75448b29c9ab4a39272b/library/core/src/slice/mod.rs#L1673-L1677
///
/// TODO replace with `split_array` feature in stdlib as soon as it's stabilized,
/// see https://github.com/rust-lang/rust/issues/90091
fn split_array_ref<const N: usize, T>(slice: &[T]) -> (&[T; N], &[T]) {
let (a, b) = slice.split_at(N);
// SAFETY: a points to [T; N]? Yes it's [T] of length N (checked by split_at)
unsafe { (&*(a.as_ptr() as *const [T; N]), b) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mapping_serde() {
for _ in 0..10000 {
let config = Mapping::random();
assert_eq!(Mapping::deserialize(&config.serialize()), Ok(config));
}
}
#[test]
fn config_serde() {
for _ in 0..10000 {
let config = BootloaderConfig::random();
assert_eq!(
BootloaderConfig::deserialize(&config.serialize()),
Ok(config)
);
}
}
}