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
/*
 * Copyright (C) 2020-2021 Nicolas Fouquet
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see https://www.gnu.org/licenses.
 */
//! ObsidianOS is a multitasking, POSIX compliant and written in Rust Operating System (OS)
//! under GPL license.
//! It means that this operating system is entirely compatible with GNU/Linux operating systems
//! and that this OS is under the same license than GNU/Linux.
//! However, this operating system is not written in C but in Rust which is more
//! safer, faster, memory-efficient and which has a great documentation.
#![no_std]
#![feature(abi_x86_interrupt)]
#![feature(llvm_asm)]
#![feature(alloc_error_handler)]
#![feature(naked_functions)]
#![feature(try_trait)]
#![feature(asm)]
#![warn(deprecated_in_future)]
#![warn(missing_docs)]

#[macro_use]
extern crate alloc;

#[macro_use]
pub mod serial;
pub mod boot_info;
pub mod common;
pub mod elf;
pub mod gdt;
pub mod irq;
pub mod memory;
pub mod sse;
pub mod syscall;
pub mod tasking;
pub mod fs;

use alloc::alloc::Layout;
use core::panic::PanicInfo;

use memory::{KERNEL_START_PHYS, KERNEL_START_VIRT};

/// An initialization function which runs initializations of all components
pub fn init() {
    // Init GDT
    print!("Init GDT");
    unsafe {
        gdt::init();
    }
    println!(" [ OK ]");

    // Enable SSE
    print!("Enable SSE");
    sse::enable_sse();
    println!(" [ OK ]");

    // Init IDT
    print!("Init IDT");
    irq::idt::init();
    println!(" [ OK ]");

    // Init syscalls
    print!("Init syscalls");
    unsafe {
        syscall::init();
    }
    println!(" [ OK ]");

    // Init PICs
    print!("Init PICs");
    unsafe { irq::idt::PICS.lock().initialize() };
    println!(" [ OK ]");

    print!("Init heap");
    memory::heap::init();
    println!(" [ OK ]");

    print!("Initialize virtual memory mapper");
    enable_nxe_bit();
    enable_write_protect_bit();

    memory::init();
    println!(" [ OK ]");

    println!("Areas detected:");
    let areas = boot_info::BOOT_INFO
        .get()
        .unwrap()
        .get()
        .memory_map_tag()
        .expect("Memory map tag required")
        .all_memory_areas();
    let mut total_size = 0;

    for area in areas {
        println!(
            "    - From {:#x} to {:#x}. Type: {:?}",
            area.start_address(),
            area.end_address(),
            area.typ()
        );
        total_size += area.size();
    }
    println!("Total size: | {} MiB |", total_size / (1024 * 1024));
}

#[no_mangle]
#[cfg(not(feature = "test"))]
/// The entry point of the kernel
pub extern "C" fn kmain(info_addr: usize) {
    let boot_info = unsafe {
        multiboot2::load((info_addr as u64 + (KERNEL_START_VIRT - KERNEL_START_PHYS)) as usize)
    };

    boot_info::BOOT_INFO.call_once(|| boot_info::BootInfo(boot_info));

    println!("Initialize components...");
    init();

    // Launch the drivers
    let envs = vec!["PATH=/bin".into()];
    let args = vec!["/bin/pci-driver".into()];
    elf::load("/bin/pci-driver", args, envs).expect("Cannot launch the shell");

    // Launch the shell
    let envs = vec!["PATH=/bin".into()];
    let args = vec!["/bin/osh".into()];
    elf::load("/bin/osh", args, envs).expect("Cannot launch the shell");

    println!("ObsidianOS is ready!");
    x86_64::instructions::interrupts::enable();
    unreachable!();
}

#[no_mangle]
#[cfg(feature = "test")]
/// The test entry point which will run all tests
pub extern "C" fn kmain(info_addr: usize) {
    let boot_info = unsafe {
        multiboot2::load((info_addr as u64 + (KERNEL_START_VIRT - KERNEL_START_PHYS)) as usize)
    };

    boot_info::BOOT_INFO.call_once(|| boot_info::BootInfo(boot_info));

    println!("Initialize components...");
    init();

    println!("Sorry. There is not any tests for now.");

    println!("Tests passed!");
    exit_qemu(QemuExitCode::Success);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
/// The different exit codes used by Qemu
pub enum QemuExitCode {
    /// An exit code when the tests have passed
    Success = 0x10,

    /// An exit code when the tests have failed
    Failed = 0x11,
}

/// Exit Qemu with an exit code at the end of the tests
pub fn exit_qemu(exit_code: QemuExitCode) {
    use x86_64::instructions::port::Port;

    unsafe {
        let mut port = Port::new(0xf4);
        port.write(exit_code as u32);
    }
}

#[panic_handler]
#[no_mangle]
#[cfg(not(feature = "test"))]
/// A custom panic handler
fn panic(info: &PanicInfo) -> ! {
    println!("{:#?}", info);
    irq::handlers::stop();
}

#[panic_handler]
#[no_mangle]
#[cfg(feature = "test")]
/// A custom panic handler during tests
fn panic(info: &PanicInfo) -> ! {
    println!("{:#?}", info);
    exit_qemu(QemuExitCode::Failed);
    irq::handlers::stop();
}

#[alloc_error_handler]
#[cfg(not(feature = "test"))]
/// A custom allocation error handler
fn handle_alloc_error(layout: Layout) -> ! {
    println!(
        "Heap->Out of memory! The size {:#x} bytes is too big",
        layout.size()
    );
    irq::handlers::stop();
}

#[alloc_error_handler]
#[cfg(feature = "test")]
/// A custom allocation error handler during tests
fn handle_alloc_error(layout: Layout) -> ! {
    println!(
        "Heap->Out of memory! The size {:#x} bytes is too big",
        layout.size()
    );
    exit_qemu(QemuExitCode::Failed);
    irq::handlers::stop();
}

#[cfg(not(test))]
/// Allow us to set the non executable flag in pages
fn enable_nxe_bit() {
    use x86_64::registers::model_specific::{Efer, EferFlags};

    unsafe {
        Efer::write(Efer::read() | EferFlags::NO_EXECUTE_ENABLE);
    }
}

#[cfg(not(test))]
/// Allow us to set the write protection flag in pages
fn enable_write_protect_bit() {
    use x86_64::registers::control::{Cr0, Cr0Flags};

    unsafe {
        Cr0::write(Cr0::read() | Cr0Flags::WRITE_PROTECT);
    }
}