interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi / src / helpers / logger.rs

269 lines · 8921 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! This optional feature adds support for the `log` crate, providing
4//! a custom logger implementation which writes to a UEFI text output protocol.
5//!
6//! The main export of this module is the `Logger` structure,
7//! which implements the `log` crate's trait `Log`.
8//!
9//! # Implementation Details
10//!
11//! The implementation is not the most efficient, since there is no buffering done,
12//! and the messages have to be converted from UTF-8 to UEFI's UCS-2.
13//!
14//! The last part also means that some Unicode characters might not be
15//! supported by the UEFI console. Don't expect emoji output support.
16
17use crate::proto::console::text::Output;
18use crate::system;
19use core::fmt::{self, Write};
20use core::ptr;
21use core::sync::atomic::{AtomicPtr, Ordering};
22
23/// Global logger object
24static LOGGER: Logger = Logger::new();
25
26/// Set up logging
27///
28/// This is unsafe because you must arrange for the logger to be reset with
29/// disable() on exit from UEFI boot services.
30pub unsafe fn init() {
31 // Connect the logger to stdout.
32 system::with_stdout(|stdout| {
33 // SAFETY: `with_stdout` hands out a live stdout handle for this call.
34 unsafe {
35 LOGGER.set_output(stdout);
36 }
37 });
38
39 // Set the logger.
40 log::set_logger(&LOGGER).unwrap(); // Can only fail if already initialized.
41
42 // Set logger max level to level specified by log features
43 log::set_max_level(log::STATIC_MAX_LEVEL);
44}
45
46pub fn disable() {
47 LOGGER.disable();
48}
49
50/// Writer to the QEMU debugcon device and the debug-console of
51/// cloud-hypervisor.
52///
53/// More info: <https://phip1611.de/blog/how-to-use-qemus-debugcon-feature/>
54#[cfg(all(
55 any(target_arch = "x86", target_arch = "x86_64"),
56 feature = "log-debugcon"
57))]
58#[derive(Copy, Clone, Debug)]
59struct DebugconWriter;
60
61#[cfg(all(
62 any(target_arch = "x86", target_arch = "x86_64"),
63 feature = "log-debugcon"
64))]
65impl DebugconWriter {
66 const IO_PORT: u16 = 0xe9;
67}
68
69#[cfg(all(
70 any(target_arch = "x86", target_arch = "x86_64"),
71 feature = "log-debugcon"
72))]
73impl Write for DebugconWriter {
74 fn write_str(&mut self, s: &str) -> fmt::Result {
75 for &byte in s.as_bytes() {
76 // SAFETY: Port 0xe9 is a fixed debug output sink, and writing a byte
77 // has no aliasing or lifetime requirements.
78 unsafe {
79 core::arch::asm!("outb %al, %dx", in("al") byte, in("dx") Self::IO_PORT, options(att_syntax))
80 };
81 }
82 Ok(())
83 }
84}
85
86/// Logging implementation which writes to a UEFI output stream.
87///
88/// If this logger is used as a global logger, you must disable it using the
89/// `disable` method before exiting UEFI boot services in order to prevent
90/// undefined behaviour from inadvertent logging.
91#[derive(Debug)]
92pub struct Logger {
93 writer: AtomicPtr<Output>,
94}
95
96impl Logger {
97 /// Creates a new logger.
98 ///
99 /// The logger is initially disabled. Call [`set_output`] to enable it.
100 ///
101 /// [`set_output`]: Self::set_output
102 #[must_use]
103 pub const fn new() -> Self {
104 Self {
105 writer: AtomicPtr::new(ptr::null_mut()),
106 }
107 }
108
109 /// Get the output pointer (may be null).
110 #[must_use]
111 fn output(&self) -> *mut Output {
112 self.writer.load(Ordering::Acquire)
113 }
114
115 /// Set the [`Output`] to which the logger will write.
116 ///
117 /// If a null pointer is passed for `output`, this method is equivalent to
118 /// calling [`disable`].
119 ///
120 /// # Safety
121 ///
122 /// The `output` pointer must either be null or point to a valid [`Output`]
123 /// object. That object must remain valid until the logger is either
124 /// disabled, or `set_output` is called with a different `output`.
125 ///
126 /// You must arrange for the [`disable`] method to be called or for this
127 /// logger to be otherwise discarded before boot services are exited.
128 ///
129 /// [`disable`]: Self::disable
130 pub unsafe fn set_output(&self, output: *mut Output) {
131 self.writer.store(output, Ordering::Release);
132 }
133
134 /// Disable the logger.
135 pub fn disable(&self) {
136 // SAFETY: Passing a null pointer disables output without dereferencing it.
137 unsafe { self.set_output(ptr::null_mut()) }
138 }
139}
140
141impl log::Log for Logger {
142 fn enabled(&self, _metadata: &log::Metadata) -> bool {
143 // We decide in `log` already if something is printed. We do not
144 // need micro optimizations here.
145 true
146 }
147
148 fn log(&self, record: &log::Record) {
149 // SAFETY: `output()` returns either null or the live output pointer set
150 // by `set_output`.
151 if let Some(writer) = unsafe { self.output().as_mut() } {
152 // Ignore all errors. Since we're in the logger implementation we
153 // can't log the error. We also don't want to panic, since logging
154 // is generally not critical functionality.
155 let _ = DecoratedLog::write(
156 writer,
157 record.level(),
158 record.args(),
159 record.file().unwrap_or("<unknown file>"),
160 record.line().unwrap_or(0),
161 );
162 }
163
164 #[cfg(all(
165 any(target_arch = "x86", target_arch = "x86_64"),
166 feature = "log-debugcon"
167 ))]
168 {
169 // Ignore all errors. Since we're in the logger implementation we
170 // can't log the error. We also don't want to panic, since logging
171 // is generally not critical functionality.
172 let _ = DecoratedLog::write(
173 &mut DebugconWriter,
174 record.level(),
175 record.args(),
176 record.file().unwrap_or("<unknown file>"),
177 record.line().unwrap_or(0),
178 );
179 }
180 }
181
182 fn flush(&self) {
183 // This simple logger does not buffer output.
184 }
185}
186
187// The logger is not thread-safe, but the UEFI boot environment only uses one processor.
188// SAFETY: The only shared state is an atomic raw pointer, and UEFI boot services
189// run on a single processor here.
190unsafe impl Sync for Logger {}
191// SAFETY: The atomic pointer makes sharing and sending the logger itself sound
192// under the same single-processor assumption.
193unsafe impl Send for Logger {}
194
195/// Writer wrapper which prints a log level in front of every line of text
196///
197/// This is less easy than it sounds because...
198///
199/// 1. The fmt::Arguments is a rather opaque type, the ~only thing you can do
200/// with it is to hand it to an fmt::Write implementation.
201/// 2. Without using memory allocation, the easy cop-out of writing everything
202/// to a String then post-processing is not available.
203///
204/// Therefore, we need to inject ourselves in the middle of the fmt::Write
205/// machinery and intercept the strings that it sends to the Writer.
206struct DecoratedLog<'writer, 'a, W: fmt::Write> {
207 writer: &'writer mut W,
208 log_level: log::Level,
209 at_line_start: bool,
210 file: &'a str,
211 line: u32,
212}
213
214impl<'writer, 'a, W: fmt::Write> DecoratedLog<'writer, 'a, W> {
215 // Call this method to print a level-annotated log
216 fn write(
217 writer: &'writer mut W,
218 log_level: log::Level,
219 args: &fmt::Arguments,
220 file: &'a str,
221 line: u32,
222 ) -> fmt::Result {
223 let mut decorated_writer = Self {
224 writer,
225 log_level,
226 at_line_start: true,
227 file,
228 line,
229 };
230 writeln!(decorated_writer, "{}", *args)
231 }
232}
233
234impl<W: fmt::Write> fmt::Write for DecoratedLog<'_, '_, W> {
235 fn write_str(&mut self, s: &str) -> fmt::Result {
236 // Split the input string into lines
237 let mut lines = s.lines();
238
239 // The beginning of the input string may actually fall in the middle of
240 // a line of output. We only print the log level if it truly is at the
241 // beginning of a line of output.
242 let first = lines.next().unwrap_or("");
243 if self.at_line_start {
244 write!(
245 self.writer,
246 "[{:>5}]: {:>12}@{:03}: ",
247 self.log_level, self.file, self.line
248 )?;
249 self.at_line_start = false;
250 }
251 write!(self.writer, "{first}")?;
252
253 // For the remainder of the line iterator (if any), we know that we are
254 // truly at the beginning of lines of output.
255 for line in lines {
256 let level = self.log_level;
257 write!(self.writer, "\n{level}: {line}")?;
258 }
259
260 // If the string ends with a newline character, we must 1/propagate it
261 // to the output (it was swallowed by the iteration) and 2/prepare to
262 // write the log level of the beginning of the next line (if any).
263 if s.ends_with('\n') {
264 writeln!(self.writer)?;
265 self.at_line_start = true;
266 }
267 Ok(())
268 }
269}