mod format;
#[cfg(test)]
mod tests;
pub use format::*;
use alloc::vec::Vec;
use crate::base::channel::Channel;
use crate::base::session::Session;
use crate::error::{Error, ProtocolError};
use crate::shell::v2::{self as shell_v2, CommandOutput, FrameId, Shell};
pub struct Logcat<'a, 'b, S> {
channel: Channel<'a, S>,
buf: &'b mut [u8],
acc_start: usize,
acc_end: usize,
head: usize,
tail: usize,
frame_id: FrameId,
frame_left: usize,
end: End,
stderr: Vec<u8>,
}
enum End {
NotYet,
Exited(u8),
ClosedWithoutExit,
}
const STDERR_KEPT: usize = 1024;
impl<'a, 'b, S: Session> Logcat<'a, 'b, S> {
pub fn new(channel: Channel<'a, S>, buf: &'b mut [u8]) -> Self {
assert!(
buf.len() >= shell_v2::HEADER_SIZE,
"Logcat buffer must be at least {} bytes",
shell_v2::HEADER_SIZE,
);
Self {
channel,
buf,
acc_start: 0,
acc_end: 0,
head: 0,
tail: 0,
frame_id: FrameId::Stdout,
frame_left: 0,
end: End::NotYet,
stderr: Vec::new(),
}
}
fn compact(&mut self) {
if self.acc_start > 0 {
shift(self.buf, self.acc_start..self.acc_end, 0);
self.acc_end -= self.acc_start;
self.acc_start = 0;
}
if self.acc_end < self.head {
shift(self.buf, self.head..self.tail, self.acc_end);
self.tail -= self.head - self.acc_end;
self.head = self.acc_end;
}
}
async fn fill(&mut self) -> Result<(), Error<S::IoError>> {
if self.tail == self.buf.len() {
self.compact();
if self.tail == self.buf.len() {
return Err(Error::ReceiveBufferFull);
}
}
let read = self.channel.read(&mut self.buf[self.tail..]).await?;
self.tail += read;
Ok(())
}
pub async fn read_entry(&mut self) -> Result<LogEntry, Error<S::IoError>> {
loop {
if let Some(entry) = self.take_entry()? {
return Ok(entry);
}
match self.end {
End::NotYet => {}
End::Exited(0) if self.acc_start < self.acc_end => {
return Err(LogcatError::TruncatedEntry.into())
}
End::Exited(0) => return Err(Error::ChannelClosed),
End::Exited(code) => {
let stderr = self.stderr.clone();
return Err(LogcatError::Exited { code, stderr }.into());
}
End::ClosedWithoutExit => return Err(LogcatError::ClosedWithoutExit.into()),
}
if self.frame_left > 0 && self.head < self.tail {
if self.frame_id == FrameId::Exit {
self.end = End::Exited(self.buf[self.head]);
continue;
}
let n = self.frame_left.min(self.tail - self.head);
if self.frame_id == FrameId::Stdout {
if self.acc_start == self.acc_end {
self.acc_start = self.head;
self.acc_end = self.head;
} else if self.acc_end < self.head {
shift(self.buf, self.head..self.head + n, self.acc_end);
}
self.acc_end += n;
} else {
let kept = n.min(STDERR_KEPT - self.stderr.len());
self.stderr
.extend_from_slice(&self.buf[self.head..self.head + kept]);
}
self.head += n;
self.frame_left -= n;
continue;
}
if self.frame_left == 0 && self.tail - self.head >= shell_v2::HEADER_SIZE {
let hdr: [u8; shell_v2::HEADER_SIZE] = self.buf
[self.head..self.head + shell_v2::HEADER_SIZE]
.try_into()
.unwrap();
let (id, len) = shell_v2::parse_header(&hdr);
let id = match id {
Ok(FrameId::Exit) if len == 0 => {
return Err(ProtocolError::ShortExitPayload.into())
}
Ok(id @ (FrameId::Stdout | FrameId::Stderr | FrameId::Exit)) => id,
other => {
let id = FrameId::byte_of(other);
return Err(ProtocolError::UnexpectedShellFrame(id).into());
}
};
self.head += shell_v2::HEADER_SIZE;
self.frame_id = id;
self.frame_left = len as usize;
continue;
}
match self.fill().await {
Ok(()) => {}
Err(Error::ChannelClosed) => self.end = End::ClosedWithoutExit,
Err(e) => return Err(e),
}
}
}
fn take_entry(&mut self) -> Result<Option<LogEntry>, Error<S::IoError>> {
let Some((entry, consumed)) =
parse_entry(&self.buf[self.acc_start..self.acc_end]).map_err(Error::Logcat)?
else {
return Ok(None);
};
self.acc_start += consumed;
Ok(Some(entry))
}
pub async fn close(self) -> Result<(), Error<S::IoError>> {
self.channel.close().await
}
}
fn shift(buf: &mut [u8], from: core::ops::Range<usize>, to: usize) {
#[cfg(test)]
tests::MOVED.with(|moved| moved.set(moved.get() + from.len()));
buf.copy_within(from, to);
}
pub async fn open<'a, 'b, S: Session>(
session: &'a mut S,
args: &[&str],
buf: &'b mut [u8],
) -> Result<Logcat<'a, 'b, S>, Error<S::IoError>> {
let channel = shell_v2::open_argv(session, b"logcat -B", args, buf).await?;
Ok(Logcat::new(channel, buf))
}
pub async fn dump<S: Session>(
session: &mut S,
args: &[&str],
buf: &mut [u8],
) -> Result<Vec<LogEntry>, Error<S::IoError>> {
let channel = shell_v2::open_argv(session, b"logcat -B -d", args, buf).await?;
let mut logcat = Logcat::new(channel, buf);
let mut entries = Vec::new();
let end = loop {
match logcat.read_entry().await {
Ok(entry) => entries.push(entry),
Err(Error::ChannelClosed) => break Ok(entries),
Err(e) => break Err(e),
}
};
let _ = logcat.close().await;
end
}
pub async fn open_text<'a, 'b, S: Session>(
session: &'a mut S,
args: &[&str],
rx: &'b mut [u8],
) -> Result<Shell<'a, 'b, S>, Error<S::IoError>> {
let channel = shell_v2::open_argv(session, b"logcat", args, rx).await?;
Ok(Shell::new(channel, rx))
}
pub async fn exec_text<S: Session>(
session: &mut S,
args: &[&str],
rx: &mut [u8],
) -> Result<CommandOutput, Error<S::IoError>> {
let channel = shell_v2::open_argv(session, b"logcat", args, rx).await?;
Shell::new(channel, rx).run_to_exit().await
}