use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Priority {
Unknown,
Default,
Verbose,
Debug,
Info,
Warn,
Error,
Fatal,
Silent,
Other(OtherPriority),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OtherPriority(u8);
impl Priority {
pub fn as_char(self) -> char {
match self {
Self::Unknown | Self::Default | Self::Other(_) => '?',
Self::Verbose => 'V',
Self::Debug => 'D',
Self::Info => 'I',
Self::Warn => 'W',
Self::Error => 'E',
Self::Fatal => 'F',
Self::Silent => 'S',
}
}
}
impl From<u8> for Priority {
fn from(byte: u8) -> Self {
match byte {
0 => Self::Unknown,
1 => Self::Default,
2 => Self::Verbose,
3 => Self::Debug,
4 => Self::Info,
5 => Self::Warn,
6 => Self::Error,
7 => Self::Fatal,
8 => Self::Silent,
9..=u8::MAX => Self::Other(OtherPriority(byte)),
}
}
}
impl From<Priority> for u8 {
fn from(priority: Priority) -> Self {
match priority {
Priority::Unknown => 0,
Priority::Default => 1,
Priority::Verbose => 2,
Priority::Debug => 3,
Priority::Info => 4,
Priority::Warn => 5,
Priority::Error => 6,
Priority::Fatal => 7,
Priority::Silent => 8,
Priority::Other(OtherPriority(byte)) => byte,
}
}
}
impl fmt::Display for Priority {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Unknown => "UNKNOWN",
Self::Default => "DEFAULT",
Self::Verbose => "VERBOSE",
Self::Debug => "DEBUG",
Self::Info => "INFO",
Self::Warn => "WARN",
Self::Error => "ERROR",
Self::Fatal => "FATAL",
Self::Silent => "SILENT",
Self::Other(OtherPriority(byte)) => return write!(f, "OTHER({byte})"),
})
}
}
macro_rules! log_ids {
(@text text) => { true };
(@text binary) => { false };
(
$(#[$attr:meta])*
pub enum LogId {
$($variant:ident = $number:literal, $name:literal, $format:ident;)*
$(#[$unknown_attr:meta])*
Unknown(UnknownLogId),
}
) => {
$(#[$attr])*
pub enum LogId {
$(
#[doc = concat!("Buffer ", stringify!($number), ", `", $name, "`.")]
$variant,
)*
$(#[$unknown_attr])*
Unknown(UnknownLogId),
}
impl LogId {
pub const fn number(self) -> u32 {
match self {
$(Self::$variant => $number,)*
Self::Unknown(UnknownLogId(number)) => number,
}
}
pub const fn is_text(self) -> bool {
match self {
$(Self::$variant => log_ids!(@text $format),)*
Self::Unknown(_) => false,
}
}
}
impl From<u32> for LogId {
fn from(number: u32) -> Self {
match number {
$($number => Self::$variant,)*
_ => Self::Unknown(UnknownLogId(number)),
}
}
}
impl fmt::Display for LogId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
$(Self::$variant => f.write_str($name),)*
Self::Unknown(UnknownLogId(other)) => write!(f, "unknown({other})"),
}
}
}
};
}
log_ids! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LogId {
Main = 0, "main", text;
Radio = 1, "radio", text;
Events = 2, "events", binary;
System = 3, "system", text;
Crash = 4, "crash", text;
Stats = 5, "stats", binary;
Security = 6, "security", binary;
Kernel = 7, "kernel", text;
Unknown(UnknownLogId),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UnknownLogId(u32);
impl From<LogId> for u32 {
fn from(id: LogId) -> Self {
id.number()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogEntry {
pub pid: u32,
pub tid: u32,
pub sec: u32,
pub nsec: u32,
pub uid: u32,
pub log_id: LogId,
pub priority: Priority,
pub tag: Vec<u8>,
pub message: Vec<u8>,
}
impl LogEntry {
pub fn tag_lossy(&self) -> alloc::borrow::Cow<'_, str> {
String::from_utf8_lossy(&self.tag)
}
pub fn message_lossy(&self) -> alloc::borrow::Cow<'_, str> {
String::from_utf8_lossy(&self.message)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LogcatError {
InvalidHeader,
Exited {
code: u8,
stderr: Vec<u8>,
},
ClosedWithoutExit,
TruncatedEntry,
}
impl fmt::Display for LogcatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidHeader => f.write_str("logcat: invalid logger_entry header"),
Self::Exited { code, stderr } => {
write!(f, "logcat exited with status {code}")?;
let said = String::from_utf8_lossy(stderr);
let reason = said
.lines()
.map(str::trim)
.find(|line| !line.is_empty() && !line.starts_with("WARNING:"));
match reason {
Some(reason) => write!(f, ": {reason}"),
None => Ok(()),
}
}
Self::ClosedWithoutExit => {
f.write_str("logcat's channel closed before its exit status arrived")
}
Self::TruncatedEntry => f.write_str("logcat's output ended in the middle of an entry"),
}
}
}
impl core::error::Error for LogcatError {}
pub(super) const HEADER_V3_SIZE: usize = 24;
pub(super) const HEADER_V4_SIZE: usize = 28;
pub(super) const LOGGER_ENTRY_MAX_LEN: usize = 5 * 1024;
pub(super) fn parse_entry(buf: &[u8]) -> Result<Option<(LogEntry, usize)>, LogcatError> {
const HEADER_PREFIX: usize = 4;
if buf.len() < HEADER_PREFIX {
return Ok(None);
}
let payload_len = u16::from_le_bytes([buf[0], buf[1]]) as usize;
let hdr_size = u16::from_le_bytes([buf[2], buf[3]]) as usize;
let total = hdr_size + payload_len;
if hdr_size < HEADER_V3_SIZE || total > LOGGER_ENTRY_MAX_LEN {
return Err(LogcatError::InvalidHeader);
}
if buf.len() < total {
return Ok(None);
}
let pid = i32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as u32;
let tid = u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]);
let sec = i32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]) as u32;
let nsec = i32::from_le_bytes([buf[16], buf[17], buf[18], buf[19]]) as u32;
let lid = u32::from_le_bytes([buf[20], buf[21], buf[22], buf[23]]);
let uid = if hdr_size >= HEADER_V4_SIZE {
u32::from_le_bytes([buf[24], buf[25], buf[26], buf[27]])
} else {
0
};
let payload = &buf[hdr_size..total];
let log_id = LogId::from(lid);
let (priority, tag, message) = if payload.is_empty() {
(Priority::Unknown, Vec::new(), Vec::new())
} else if !log_id.is_text() {
(Priority::Unknown, Vec::new(), payload.to_vec())
} else {
let priority = Priority::from(payload[0]);
let rest = &payload[1..];
let tag_end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len());
let tag = rest[..tag_end].to_vec();
let msg_start = (tag_end + 1).min(rest.len());
let mut message = rest[msg_start..].to_vec();
if message.last() == Some(&0) {
message.pop();
}
(priority, tag, message)
};
Ok(Some((
LogEntry {
pid,
tid,
sec,
nsec,
uid,
log_id,
priority,
tag,
message,
},
total,
)))
}