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
/*!
A standalone, `#![no_std]`-friendly `Logger` crate.
Based on the design of the logger built into the [bootloader](https://github.com/rust-osdev/bootloader) crate and meant to be used in OS kernels.
To use this crate, specify it as a dependency in your kernel's `Cargo.toml`, then initialize it.
# Initialization
The logger needs to be initialized in order to be used. To do that, one must first create a global instance, using a crate like `conquer_once`:
```
pub static PRINTK: OnceCell<LockedPrintk> = OnceCell::uninit();
```
After this, the `log` crate needs to be attached to it. This requires the following 3 steps:
1. Use the `get_or_init` method to unwrap the `LockedPrintk` object from its outer OnceCell
2. Use `log::set_logger` to tell the `log` crate what to attach to
3. Use `log::set_max_level` to tell the `log` crate how many levels of logging you want to do
Here's an example function demonstrating how this is done in pure Rust:
```
pub fn printk_init(buffer: &'static mut [u8], info: FrameBufferInfo) {
let kernel_logger = printk::PRINTK.get_or_init(move || printk::LockedPrintk::new(buffer, info));
log::set_logger(kernel_logger).expect("logger already set");
log::set_max_level(log::LevelFilter::Trace);
log::info!("Hello, Kernel!");
}
```
# Contributing
If you have any functionality to add, feel free to [create a pull request](https://github.com/kennystrawnmusic/printk/pulls). I'll gladly test and accept it. Also, if you have any bugs to report, that is also what GitHub is for.
*/
#![no_std]
#[allow(unused_imports)]
use {
bootloader::{
boot_info::{
FrameBufferInfo,
PixelFormat,
}
},
conquer_once::{
spin::{
OnceCell,
}
},
core::{
fmt::{
self,
Write,
},
ptr,
},
noto_sans_mono_bitmap::{
get_bitmap,
get_bitmap_width,
BitmapChar,
BitmapHeight,
FontWeight,
},
spinning_top::{
Spinlock,
}
};
/// Memory safety: need to ensure that each instance is mutexed
pub struct LockedPrintk(Spinlock<Printk>);
impl LockedPrintk {
// Constructor
#[allow(dead_code)] //TODO: use this in main.rs
pub fn new(buf: &'static mut [u8], i: FrameBufferInfo) -> Self {
LockedPrintk(Spinlock::new(Printk::new(buf, i)))
}
#[allow(dead_code)] //TODO: use this in main.rs
pub unsafe fn force_unlock(&self) {
self.0.force_unlock()
}
}
impl log::Log for LockedPrintk {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}
fn log(&self, record: &log::Record) {
let mut printk = self.0.lock();
writeln!(printk, "{}: {}", record.level(), record.args()).unwrap();
printk.move_down(2);
}
fn flush(&self) {
}
}
/// Structure to render characters to the framebuffer
pub struct Printk {
buffer: &'static mut [u8],
info: FrameBufferInfo,
x: usize,
y: usize,
}
impl Printk {
/// Creates a new empty logging interface
#[allow(dead_code)]
pub fn new(buffer: &'static mut [u8], info: FrameBufferInfo) -> Self {
let mut printk = Self {
buffer,
info,
x: 0,
y: 0,
};
printk.clear();
printk
}
/// Draws black-and-white pixels on the screen
pub fn draw_grayscale(&mut self, x: usize, y: usize, intensity: u8) {
// Pixel offset
let poff = y * self.info.stride + x;
let u8_intensity = {
if intensity > 200 {
0xf
} else {
0
}
};
let color = match self.info.pixel_format {
PixelFormat::RGB => {
[intensity, intensity, intensity/2, 0]
},
PixelFormat::BGR => {
[intensity/2, intensity, intensity, 0]
},
PixelFormat::U8 => {
[u8_intensity, 0, 0, 0]
},
//TODO: use embedded-graphics to solve this problem
_ => panic!("Kernel panic -- not syncing: Unknown pixel format")
};
// Number of bytes in a pixel (4 on my machine)
let bpp = self.info.bytes_per_pixel;
// Byte offset: multiply bytes-per-pixel by pixel offset to obtain
let boff = poff*bpp;
// Copy bytes
self.buffer[boff..(boff+bpp)].copy_from_slice(&color[..bpp]);
// Raw pointer to buffer start ― that's why this is unsafe
let _ = unsafe { ptr::read_volatile(&self.buffer[boff]) };
}
/// Renders characters from the `noto-sans-mono-bitmap` crate
pub fn render(&mut self, rendered: BitmapChar) {
// Loop through lines
for (y, ln) in rendered.bitmap().iter().enumerate() {
// Loop through characters on each line
for (x, col) in ln.iter().enumerate() {
// Use above draw_grayscale method to render each character in the bitmap
self.draw_grayscale(self.x+x, self.y+y, *col)
}
}
// Increment by width of each character
self.x += rendered.width();
}
/// Moves down by `distance` number of pixels
pub fn move_down(&mut self, distance: usize) {
self.y += distance;
}
/// Moves to the beginning of a line
pub fn home(&mut self) {
self.x = 0;
}
/// Moves down one line
pub fn next_line(&mut self) {
self.move_down(14);
self.home();
}
/// Moves to the top of the page
pub fn page_up(&mut self) {
self.y = 0;
}
/// Clears the screen
pub fn clear(&mut self) {
self.home();
self.page_up();
self.buffer.fill(0);
}
/// Gets the width of the framebuffer
pub fn width(&self) -> usize {
self.info.horizontal_resolution
}
/// Gets the height of the framebuffer
pub fn height(&self) -> usize {
self.info.vertical_resolution
}
/// Prints an individual character on the screen
pub fn putch(&mut self, c: char) {
match c {
'\n' => self.next_line(),
'\r' => self.home(),
c => {
if self.x >= self.width() {
self.next_line();
}
const LETTER_WIDTH: usize = get_bitmap_width(FontWeight::Regular, BitmapHeight::Size14);
if self.y >= (self.height() - LETTER_WIDTH) {
self.clear();
}
let mapped = get_bitmap(c, FontWeight::Regular, BitmapHeight::Size14).unwrap();
self.render(mapped);
}
}
}
}
unsafe impl Send for Printk {}
unsafe impl Sync for Printk {}
impl fmt::Write for Printk {
fn write_str(&mut self, s: &str) -> fmt::Result {
for c in s.chars() {
self.putch(c)
}
Ok(())
}
}