Skip to content

Commit dfd5a41

Browse files
committed
[pixie-uefi] using log crate
1 parent 9ef1ae9 commit dfd5a41

8 files changed

Lines changed: 78 additions & 80 deletions

File tree

pixie-uefi/Cargo.lock

Lines changed: 10 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pixie-uefi/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ test = false
1010
bench = false
1111

1212
[dependencies]
13+
anstyle = { version = "1.0.10", default-features = false }
1314
blake3 = { version = "1.5.0", default-features = false, features = ["prefer_intrinsics", "no_avx512", "pure"] }
1415
core_detect = "1.0.0"
1516
futures = { version = "0.3.29", default-features = false, features = ["alloc", "async-await"] }
1617
gpt_disk_io = "0.16.0"
18+
log = "0.4.27"
1719
lz4_flex = { version = "0.11.3", default-features = false }
1820
managed = { version = "0.8.0", default-features = false, features = ["alloc"] }
1921
postcard = { version = "1.0.8", default-features = false, features = ["alloc"] }

pixie-uefi/src/main.rs

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#![no_main]
22
#![no_std]
3-
#![feature(negative_impls)]
43
#![feature(never_type)]
54
#![deny(unused_must_use)]
65

@@ -11,13 +10,13 @@ use crate::{
1110
flash::flash,
1211
os::{
1312
error::{Error, Result},
14-
MessageKind, TcpStream, UefiOS, PACKET_SIZE,
13+
TcpStream, UefiOS, PACKET_SIZE,
1514
},
1615
reboot_to_os::reboot_to_os,
1716
register::register,
1817
store::store,
1918
};
20-
use alloc::{borrow::ToOwned, boxed::Box};
19+
use alloc::boxed::Box;
2120
use core::net::{Ipv4Addr, SocketAddrV4};
2221
use futures::future::{self, Either};
2322
use pixie_shared::{Action, TcpRequest, UdpRequest, ACTION_PORT, PING_PORT};
@@ -67,7 +66,7 @@ async fn server_discover(os: UefiOS) -> Result<SocketAddrV4> {
6766
}
6867

6968
async fn shutdown(os: UefiOS) -> ! {
70-
os.append_message("Shutting down...".to_owned(), MessageKind::Info);
69+
log::info!("Shutting down...");
7170
os.sleep_us(1_000_000).await;
7271
os.shutdown()
7372
}
@@ -115,7 +114,7 @@ async fn run(os: UefiOS) -> Result<!> {
115114
os.set_ui_drawer(|_| {});
116115

117116
if !last_was_wait {
118-
os.append_message("Sending request for command".into(), MessageKind::Debug);
117+
log::debug!("Sending request for command");
119118
}
120119

121120
let tcp = os.connect(server).await?;
@@ -124,18 +123,12 @@ async fn run(os: UefiOS) -> Result<!> {
124123
tcp.force_close().await;
125124

126125
if let Err(e) = command {
127-
os.append_message(format!("Error receiving action: {e}"), MessageKind::Warn);
126+
log::warn!("Error receiving action: {e}");
128127
} else {
129128
let command = command.unwrap();
130129
if matches!(command, Action::Wait) {
131130
if !last_was_wait {
132-
os.append_message(
133-
format!(
134-
"Started waiting for another command at {:.1}s...",
135-
os.timer().micros() as f32 * 0.000_001
136-
),
137-
MessageKind::Warn,
138-
);
131+
log::warn!("Started waiting for another command...");
139132
}
140133
last_was_wait = true;
141134
const WAIT_10MSECS: u64 = 50;
@@ -145,7 +138,7 @@ async fn run(os: UefiOS) -> Result<!> {
145138
}
146139
} else {
147140
last_was_wait = false;
148-
os.append_message(format!("Command: {:?}", command), MessageKind::Info);
141+
log::info!("Command: {:?}", command);
149142
match command {
150143
Action::Wait => unreachable!(),
151144
Action::Reboot => reboot_to_os(os).await,

pixie-uefi/src/os/mod.rs

Lines changed: 45 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ struct UefiOSImpl {
7878
vga: ScopedProtocol<Output>,
7979
serial: ScopedProtocol<Serial>,
8080
net: Option<NetworkInterface>,
81-
messages: VecDeque<(String, MessageKind)>,
81+
messages: VecDeque<(f64, log::Level, String, String)>,
8282
ui_buf: Vec<(String, Color, Color)>,
8383
ui_pos: usize,
8484
ui_drawer: Option<Box<dyn Fn(UefiOS) + 'static>>,
@@ -149,9 +149,6 @@ pub struct UefiOS {
149149
cant_build: (),
150150
}
151151

152-
impl !Send for UefiOS {}
153-
impl !Sync for UefiOS {}
154-
155152
unsafe extern "efiapi" fn exit_boot_services(_e: Event, _ctx: Option<NonNull<c_void>>) {
156153
panic!("You must never exit boot services");
157154
}
@@ -210,13 +207,16 @@ impl UefiOS {
210207

211208
let os = UefiOS { cant_build: () };
212209

210+
log::set_logger(&UefiOS { cant_build: () }).unwrap();
211+
log::set_max_level(log::LevelFilter::Trace);
212+
213213
let net = NetworkInterface::new(os);
214214
os.borrow_mut().net = Some(net);
215215

216216
os.spawn("init", async move {
217217
loop {
218218
let err = f(os).await.unwrap_err();
219-
os.append_message(format!("Error: {:?}", err), MessageKind::Error);
219+
log::error!("Error: {:?}", err);
220220
}
221221
});
222222

@@ -226,10 +226,7 @@ impl UefiOS {
226226

227227
if let Err(err) = err {
228228
if err.status() != Status::UNSUPPORTED {
229-
os.append_message(
230-
format!("Error disabling watchdog: {:?}", err),
231-
MessageKind::Error,
232-
);
229+
log::error!("Error disabling watchdog: {:?}", err);
233230
}
234231

235232
break;
@@ -503,10 +500,17 @@ impl UefiOS {
503500
// TODO(veluca): find a better solution.
504501
let messages: Vec<_> = os.messages.iter().cloned().collect();
505502

506-
for (line, kind) in messages {
507-
let fg_color = kind.color();
508-
os.write_with_color(&line, fg_color, Color::Black);
509-
os.write_with_color("\n", Color::Black, Color::Black);
503+
for (time, level, target, msg) in messages {
504+
let fg_color = match level {
505+
log::Level::Trace => Color::Cyan,
506+
log::Level::Debug => Color::Blue,
507+
log::Level::Info => Color::Green,
508+
log::Level::Warn => Color::Yellow,
509+
log::Level::Error => Color::Red,
510+
};
511+
os.write_with_color(&format!("[{time:.1}s "), Color::White, Color::Black);
512+
os.write_with_color(&format!("{level:5}"), fg_color, Color::Black);
513+
os.write_with_color(&format!(" {target}] {msg}\n"), Color::White, Color::Black);
510514
}
511515
os.write_with_color("\n", Color::Black, Color::Black);
512516
}
@@ -533,13 +537,24 @@ impl UefiOS {
533537
self.borrow_mut().ui_drawer = Some(Box::new(f));
534538
}
535539

536-
pub fn append_message(&self, msg: String, kind: MessageKind) {
540+
fn append_message(&self, time: f64, level: log::Level, target: &str, msg: String) {
537541
{
538542
let mut os = self.borrow_mut();
539543

540-
write!(os.serial, "{:5} {}\r\n", kind.as_str(), msg).unwrap();
544+
let style = match level {
545+
log::Level::Trace => anstyle::AnsiColor::Cyan.on_default(),
546+
log::Level::Debug => anstyle::AnsiColor::Blue.on_default(),
547+
log::Level::Info => anstyle::AnsiColor::Green.on_default(),
548+
log::Level::Warn => anstyle::AnsiColor::Yellow.on_default(),
549+
log::Level::Error => anstyle::AnsiColor::Red.on_default().bold(),
550+
};
551+
write!(
552+
os.serial,
553+
"[{time:.1}s {style}{level:5}{style:#} {target}] {msg}\r\n"
554+
)
555+
.unwrap();
541556

542-
os.messages.push_back((msg, kind));
557+
os.messages.push_back((time, level, target.into(), msg));
543558
const MAX_MESSAGES: usize = 5;
544559
if os.messages.len() > MAX_MESSAGES {
545560
os.messages.pop_front();
@@ -567,30 +582,22 @@ impl UefiOS {
567582
}
568583
}
569584

570-
#[derive(Clone, Copy)]
571-
pub enum MessageKind {
572-
Debug,
573-
Info,
574-
Warn,
575-
Error,
576-
}
585+
impl log::Log for UefiOS {
586+
fn enabled(&self, _metadata: &log::Metadata) -> bool {
587+
true
588+
}
577589

578-
impl MessageKind {
579-
fn color(self) -> Color {
580-
match self {
581-
MessageKind::Debug => Color::LightGray,
582-
MessageKind::Info => Color::White,
583-
MessageKind::Warn => Color::Yellow,
584-
MessageKind::Error => Color::Red,
585-
}
590+
fn log(&self, record: &log::Record) {
591+
let now = self.timer().micros() as f64 * 0.000_001;
592+
self.append_message(
593+
now,
594+
record.level(),
595+
record.target(),
596+
format!("{}", record.args()),
597+
);
586598
}
587599

588-
fn as_str(self) -> &'static str {
589-
match self {
590-
MessageKind::Debug => "DEBUG",
591-
MessageKind::Info => "INFO",
592-
MessageKind::Warn => "WARN",
593-
MessageKind::Error => "ERROR",
594-
}
600+
fn flush(&self) {
601+
// no-op
595602
}
596603
}

pixie-uefi/src/os/net.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use super::{
22
error::{Error, Result},
33
timer::Timer,
4-
MessageKind, UefiOS,
4+
UefiOS,
55
};
66
use alloc::boxed::Box;
77
use core::{
@@ -161,13 +161,10 @@ impl NetworkInterface {
161161
let bo = os.boot_options();
162162
let curopt = bo.get(bo.current());
163163
let (descr, device) = bo.boot_entry_info(&curopt[..]);
164-
os.append_message(
165-
format!(
166-
"Configuring network on interface used for booting ({} -- {})",
167-
descr,
168-
os.device_path_to_string(device),
169-
),
170-
MessageKind::Info,
164+
log::info!(
165+
"Configuring network on interface used for booting ({} -- {})",
166+
descr,
167+
os.device_path_to_string(device)
171168
);
172169
let mut device = SnpDevice::new(Box::leak(Box::new(
173170
os.open_protocol_on_device::<SimpleNetwork>(device).unwrap(),

pixie-uefi/src/reboot_to_os.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::os::{MessageKind, UefiOS};
1+
use crate::os::UefiOS;
22

33
pub async fn reboot_to_os(os: UefiOS) -> ! {
44
let bo = os.boot_options();
@@ -7,14 +7,11 @@ pub async fn reboot_to_os(os: UefiOS) -> ! {
77
// Reboot to next boot option.
88
bo.set_next(next);
99
} else {
10-
os.append_message(
11-
format!(
12-
"Did not find a valid boot order entry! current: {}",
13-
bo.current()
14-
),
15-
MessageKind::Warn,
10+
log::warn!(
11+
"Did not find a valid boot order entry! current: {}",
12+
bo.current()
1613
);
17-
os.append_message(format!("{:?}", bo.order()), MessageKind::Warn);
14+
log::warn!("{:?}", bo.order());
1815
os.sleep_us(100_000_000).await;
1916
}
2017
os.reset();

pixie-uefi/src/register.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::os::{
22
error::{Error, Result},
3-
MessageKind, UefiOS, PACKET_SIZE,
3+
UefiOS, PACKET_SIZE,
44
};
55
use alloc::{boxed::Box, rc::Rc, vec::Vec};
66
use core::{cell::RefCell, net::SocketAddrV4};
@@ -167,10 +167,7 @@ pub async fn register(os: UefiOS, server_addr: SocketAddrV4) -> Result<()> {
167167
// TODO(virv): this could be better
168168
stream.force_close().await;
169169

170-
os.append_message(
171-
format!("Registration successful! {:?}", data.borrow().station),
172-
MessageKind::Info,
173-
);
170+
log::info!("Registration successful! {:?}", data.borrow().station);
174171

175172
Ok(())
176173
}

pixie-uefi/src/store.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::{
22
os::{
33
error::{Error, Result},
4-
mpsc, MessageKind, TcpStream, UefiOS,
4+
mpsc, TcpStream, UefiOS,
55
},
66
parse_disk,
77
};
@@ -216,10 +216,7 @@ pub async fn store(os: UefiOS, server_address: SocketAddrV4) -> Result<()> {
216216
// TODO(virv): this could be better
217217
stream_upload_chunk.force_close().await;
218218

219-
os.append_message(
220-
format!("image saved. Total size {total_size}, total csize {total_csize}",),
221-
MessageKind::Info,
222-
);
219+
log::info!("image saved. Total size {total_size}, total csize {total_csize}");
223220

224221
Ok(())
225222
}

0 commit comments

Comments
 (0)