feature: trace! levels

This commit is contained in:
Mark Poliakov 2021-11-25 12:02:25 +02:00
parent 47b67fa93c
commit 61a92920c2
13 changed files with 62 additions and 20 deletions

View File

@ -12,6 +12,7 @@
//! * [errorln!] //! * [errorln!]
use crate::dev::serial::SerialDevice; use crate::dev::serial::SerialDevice;
use libsys::debug::TraceLevel;
use core::fmt; use core::fmt;
/// Kernel logging levels /// Kernel logging levels
@ -27,6 +28,18 @@ pub enum Level {
Error, Error,
} }
impl From<TraceLevel> for Level {
#[inline(always)]
fn from(l: TraceLevel) -> Self {
match l {
TraceLevel::Debug => Self::Debug,
TraceLevel::Info => Self::Info,
TraceLevel::Warn => Self::Warn,
TraceLevel::Error => Self::Error,
}
}
}
struct SerialOutput<T: 'static + SerialDevice> { struct SerialOutput<T: 'static + SerialDevice> {
inner: &'static T, inner: &'static T,
} }
@ -101,7 +114,7 @@ macro_rules! errorln {
} }
#[doc(hidden)] #[doc(hidden)]
pub fn _debug(_level: Level, args: fmt::Arguments) { pub fn _debug(level: Level, args: fmt::Arguments) {
use crate::arch::machine; use crate::arch::machine;
use fmt::Write; use fmt::Write;

View File

@ -9,6 +9,7 @@ use core::ops::DerefMut;
use core::time::Duration; use core::time::Duration;
use libsys::{ use libsys::{
abi::SystemCall, abi::SystemCall,
debug::TraceLevel,
error::Errno, error::Errno,
ioctl::IoctlCmd, ioctl::IoctlCmd,
proc::{ExitCode, Pid}, proc::{ExitCode, Pid},
@ -319,10 +320,11 @@ pub fn syscall(num: SystemCall, args: &[usize]) -> Result<usize, Errno> {
// Debugging // Debugging
SystemCall::DebugTrace => { SystemCall::DebugTrace => {
let buf = arg::str_ref(args[0], args[1])?; let level = TraceLevel::from_repr(args[0]).map(Level::from).ok_or(Errno::InvalidArgument)?;
print!(Level::Debug, "[trace] "); let buf = arg::str_ref(args[1], args[2])?;
print!(Level::Debug, "{}", buf); let thread = Thread::current();
println!(Level::Debug, ""); let proc = thread.owner().unwrap();
println!(level, "[trace {:?}:{}] {}", proc.id(), thread.id(), buf);
Ok(args[1]) Ok(args[1])
} }

View File

@ -1,6 +1,7 @@
use crate::abi::SystemCall; use crate::abi::SystemCall;
use crate::{ use crate::{
error::Errno, error::Errno,
debug::TraceLevel,
ioctl::IoctlCmd, ioctl::IoctlCmd,
proc::{ExitCode, Pid}, proc::{ExitCode, Pid},
signal::{Signal, SignalDestination}, signal::{Signal, SignalDestination},
@ -104,10 +105,11 @@ pub fn sys_ex_nanosleep(ns: u64, rem: &mut [u64; 2]) -> Result<(), Errno> {
/// ///
/// System call /// System call
#[inline(always)] #[inline(always)]
pub fn sys_ex_debug_trace(msg: &[u8]) -> Result<(), Errno> { pub fn sys_ex_debug_trace(level: TraceLevel, msg: &[u8]) -> Result<(), Errno> {
Errno::from_syscall_unit(unsafe { Errno::from_syscall_unit(unsafe {
syscall!( syscall!(
SystemCall::DebugTrace, SystemCall::DebugTrace,
argn!(level.repr()),
argp!(msg.as_ptr()), argp!(msg.as_ptr()),
argn!(msg.len()) argn!(msg.len())
) )

10
libsys/src/debug.rs Normal file
View File

@ -0,0 +1,10 @@
use enum_repr::EnumRepr;
#[EnumRepr(type = "usize")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum TraceLevel {
Debug = 1,
Info = 2,
Warn = 3,
Error = 4,
}

View File

@ -5,6 +5,7 @@
extern crate bitflags; extern crate bitflags;
pub mod abi; pub mod abi;
pub mod debug;
pub mod error; pub mod error;
pub mod ioctl; pub mod ioctl;
pub mod mem; pub mod mem;

View File

@ -1,6 +1,6 @@
use core::alloc::{Layout, GlobalAlloc}; use core::alloc::{Layout, GlobalAlloc};
use core::sync::atomic::{AtomicUsize, Ordering}; use core::sync::atomic::{AtomicUsize, Ordering};
use libsys::mem::memset; use libsys::{debug::TraceLevel, mem::memset};
use crate::trace; use crate::trace;
@ -16,14 +16,14 @@ unsafe impl GlobalAlloc for Allocator {
if res > 65536 { if res > 65536 {
panic!("Out of memory"); panic!("Out of memory");
} }
trace!("alloc({:?}) = {:p}", layout, &ALLOC_DATA[res]); trace!(TraceLevel::Debug, "alloc({:?}) = {:p}", layout, &ALLOC_DATA[res]);
let res = &mut ALLOC_DATA[res] as *mut _; let res = &mut ALLOC_DATA[res] as *mut _;
memset(res, 0, layout.size()); memset(res, 0, layout.size());
res res
} }
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
trace!("free({:p}, {:?})", ptr, layout); trace!(TraceLevel::Debug, "free({:p}, {:?})", ptr, layout);
} }
} }

View File

@ -1,4 +1,4 @@
use libsys::ProgramArgs; use libsys::{debug::TraceLevel, ProgramArgs};
use alloc::vec::Vec; use alloc::vec::Vec;
use crate::trace; use crate::trace;
@ -17,5 +17,5 @@ pub(crate) unsafe fn setup_env(arg: &ProgramArgs) {
PROGRAM_ARGS.push(string); PROGRAM_ARGS.push(string);
} }
trace!("args = {:?}", PROGRAM_ARGS); trace!(TraceLevel::Debug, "args = {:?}", PROGRAM_ARGS);
} }

View File

@ -7,7 +7,7 @@ extern crate lazy_static;
extern crate alloc; extern crate alloc;
use core::panic::PanicInfo; use core::panic::PanicInfo;
use libsys::{ProgramArgs, proc::ExitCode}; use libsys::{debug::TraceLevel, ProgramArgs, proc::ExitCode};
mod allocator; mod allocator;
pub mod env; pub mod env;
@ -40,6 +40,6 @@ fn panic_handler(pi: &PanicInfo) -> ! {
// TODO unwind to send panic argument back to parent thread // TODO unwind to send panic argument back to parent thread
// TODO print to stdout/stderr (if available) // TODO print to stdout/stderr (if available)
let thread = thread::current(); let thread = thread::current();
trace!("{:?} panicked: {:?}", thread, pi); trace!(TraceLevel::Error, "{:?} panicked: {:?}", thread, pi);
sys::sys_exit(ExitCode::from(-1)); sys::sys_exit(ExitCode::from(-1));
} }

View File

@ -1,9 +1,16 @@
use libsys::debug::TraceLevel;
use crate::sys; use crate::sys;
use core::fmt; use core::fmt;
#[macro_export] #[macro_export]
macro_rules! trace { macro_rules! trace {
($($args:tt)+) => ($crate::os::_trace(format_args!($($args)+))) ($level:expr, $($args:tt)+) => ($crate::os::_trace($level, format_args!($($args)+)))
}
#[macro_export]
macro_rules! trace_debug {
($($args:tt)+) => ($crate::os::_trace($crate::sys::debug::TraceLevel::Debug, format_args!($($args)+)))
} }
struct BufferWriter<'a> { struct BufferWriter<'a> {
@ -21,7 +28,7 @@ impl fmt::Write for BufferWriter<'_> {
} }
} }
pub fn _trace(args: fmt::Arguments) { pub fn _trace(level: TraceLevel, args: fmt::Arguments) {
use core::fmt::Write; use core::fmt::Write;
static mut BUFFER: [u8; 4096] = [0; 4096]; static mut BUFFER: [u8; 4096] = [0; 4096];
let mut writer = BufferWriter { let mut writer = BufferWriter {
@ -29,5 +36,5 @@ pub fn _trace(args: fmt::Arguments) {
pos: 0, pos: 0,
}; };
writer.write_fmt(args).ok(); writer.write_fmt(args).ok();
sys::sys_ex_debug_trace(unsafe { &BUFFER[..writer.pos] }).ok(); sys::sys_ex_debug_trace(level, unsafe { &BUFFER[..writer.pos] }).ok();
} }

View File

@ -1,5 +1,6 @@
use crate::trace; use crate::trace;
use libsys::{ use libsys::{
debug::TraceLevel,
calls::{sys_ex_sigreturn, sys_exit}, calls::{sys_ex_sigreturn, sys_exit},
proc::ExitCode, proc::ExitCode,
signal::Signal, signal::Signal,
@ -26,7 +27,7 @@ pub fn set_handler(sig: Signal, handler: SignalHandler) -> SignalHandler {
#[inline(never)] #[inline(never)]
pub(crate) extern "C" fn signal_handler(arg: Signal) -> ! { pub(crate) extern "C" fn signal_handler(arg: Signal) -> ! {
// TODO tpidr_el0 is invalidated when entering signal context // TODO tpidr_el0 is invalidated when entering signal context
trace!("Entered signal handler: arg={:?}", arg); trace!(TraceLevel::Debug, "Entered signal handler: arg={:?}", arg);
let no = arg as usize; let no = arg as usize;
if no >= 32 { if no >= 32 {
panic!("Undefined signal number: {}", no); panic!("Undefined signal number: {}", no);

View File

@ -5,6 +5,7 @@ pub use libsys::abi;
pub use libsys::calls::*; pub use libsys::calls::*;
pub use libsys::stat::{self, AccessMode, FileDescriptor}; pub use libsys::stat::{self, AccessMode, FileDescriptor};
pub use libsys::error::Errno; pub use libsys::error::Errno;
pub use libsys::debug;
use core::sync::atomic::{Ordering, AtomicBool}; use core::sync::atomic::{Ordering, AtomicBool};

View File

@ -110,7 +110,7 @@ fn random_bytes(buf: &mut [u8]) {
#[no_mangle] #[no_mangle]
fn main() -> i32 { fn main() -> i32 {
let seed = libusr::sys::sys_ex_getcputime().unwrap().as_nanos() as u64 / 13; let seed = libusr::sys::sys_ex_getcputime().unwrap().as_nanos() as u64 / 13;
trace!("Using seed: {:#x}", seed); println!("Using seed: {:#x}", seed);
random_set_seed(seed); random_set_seed(seed);
let mut buf = [0; 256]; let mut buf = [0; 256];

View File

@ -10,6 +10,7 @@ use libusr::io::{self, Read};
use libusr::signal::{self, SignalHandler}; use libusr::signal::{self, SignalHandler};
use libusr::sys::{ use libusr::sys::{
proc::Pid, sys_execve, sys_setpgid, sys_exit, sys_fork, sys_getpgid, sys_waitpid, Errno, ExitCode, proc::Pid, sys_execve, sys_setpgid, sys_exit, sys_fork, sys_getpgid, sys_waitpid, Errno, ExitCode,
sys_faccessat, AccessMode,
FileDescriptor, Signal, FileDescriptor, Signal,
}; };
@ -31,6 +32,9 @@ fn execute(line: &str) -> Result<ExitCode, Errno> {
let args: Vec<&str> = line.split(' ').collect(); let args: Vec<&str> = line.split(' ').collect();
let cmd = args[0]; let cmd = args[0];
let filename = "/bin/".to_owned() + cmd;
sys_faccessat(None, &filename, AccessMode::X_OK, 0)?;
if let Some(pid) = unsafe { sys_fork()? } { if let Some(pid) = unsafe { sys_fork()? } {
let mut status = 0; let mut status = 0;
sys_waitpid(pid, &mut status)?; sys_waitpid(pid, &mut status)?;
@ -40,7 +44,6 @@ fn execute(line: &str) -> Result<ExitCode, Errno> {
} else { } else {
let pgid = sys_setpgid(unsafe { Pid::from_raw(0) }, unsafe { Pid::from_raw(0) }).unwrap(); let pgid = sys_setpgid(unsafe { Pid::from_raw(0) }, unsafe { Pid::from_raw(0) }).unwrap();
io::tcsetpgrp(FileDescriptor::STDIN, pgid).unwrap(); io::tcsetpgrp(FileDescriptor::STDIN, pgid).unwrap();
let filename = "/bin/".to_owned() + cmd;
sys_execve(&filename, &args).unwrap(); sys_execve(&filename, &args).unwrap();
sys_exit(ExitCode::from(-1)); sys_exit(ExitCode::from(-1));
} }
@ -67,7 +70,9 @@ fn main() -> i32 {
continue; continue;
} }
execute(line).ok(); if let Err(e) = execute(line) {
eprintln!("{}: {:?}", line.split(' ').next().unwrap(), e);
}
}, },
Err(_) => { Err(_) => {
println!("Interrupt!"); println!("Interrupt!");