use alloc::vec::Vec;
use crate::base::channel::Channel;
use crate::base::error::Error;
use crate::base::session::Session;
use crate::shell::v2::{self as shell_v2, CommandOutput, Shell};
pub struct Logcat<'a, 'b, S> {
channel: Channel<'a, S>,
buf: &'b mut [u8],
acc_end: usize,
head: usize,
tail: usize,
}
impl<'a, 'b, S: Session> Logcat<'a, 'b, S> {
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_end: 0,
head: 0,
tail: 0,
}
}
fn compact_raw(&mut self) {
if self.acc_end < self.head {
self.buf.copy_within(self.head..self.tail, self.acc_end);
self.tail -= self.head - self.acc_end;
self.head = self.acc_end;
}
}
async fn fill_raw(&mut self, n: usize) -> Result<(), Error<S::IoError>> {
while self.tail - self.head < n {
if self.tail >= self.buf.len() {
self.compact_raw();
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(())
}
fn absorb_stdout(&mut self, payload_len: usize) {
self.compact_raw();
let payload_start = self.head + shell_v2::HEADER_SIZE;
let payload_end = payload_start + payload_len;
self.buf.copy_within(payload_start..payload_end, self.head);
self.acc_end = self.head + payload_len;
self.head = payload_end;
}
pub async fn read_entry(&mut self) -> Result<LogEntry, Error<S::IoError>> {
loop {
if let Some((entry, consumed)) =
parse_entry(&self.buf[..self.acc_end]).map_err(Error::Logcat)?
{
self.buf.copy_within(consumed..self.acc_end, 0);
self.acc_end -= consumed;
return Ok(entry);
}
loop {
match self.fill_raw(shell_v2::HEADER_SIZE).await {
Ok(()) => {}
Err(Error::ChannelClosed) => return self.drain_acc_or_close(),
Err(e) => return Err(e),
}
let hdr: [u8; shell_v2::HEADER_SIZE] = self.buf
[self.head..self.head + shell_v2::HEADER_SIZE]
.try_into()
.unwrap();
let (id, payload_len) = shell_v2::parse_header(&hdr);
let frame_size = shell_v2::HEADER_SIZE + payload_len as usize;
match self.fill_raw(frame_size).await {
Ok(()) => {}
Err(Error::ChannelClosed) => return self.drain_acc_or_close(),
Err(e) => return Err(e),
}
match id {
shell_v2::STDOUT => {
self.absorb_stdout(payload_len as usize);
break;
}
shell_v2::EXIT => return self.drain_acc_or_close(),
_ => self.head += frame_size,
}
}
}
}
fn drain_acc_or_close(&mut self) -> Result<LogEntry, Error<S::IoError>> {
if let Some((entry, consumed)) =
parse_entry(&self.buf[..self.acc_end]).map_err(Error::Logcat)?
{
self.buf.copy_within(consumed..self.acc_end, 0);
self.acc_end -= consumed;
return Ok(entry);
}
Err(Error::ChannelClosed)
}
pub async fn close(self) -> Result<(), Error<S::IoError>> {
self.channel.close().await
}
}
fn write_destination(
buf: &mut [u8],
prefix: &[u8],
args: &[&str],
) -> Result<usize, crate::base::destination::DestinationError> {
crate::base::destination::write_destination(buf, &[b"shell,v2,raw:", prefix], args)
}
async fn open_shell_channel<'a, S: Session>(
session: &'a mut S,
prefix: &[u8],
args: &[&str],
buf: &mut [u8],
) -> Result<Channel<'a, S>, Error<S::IoError>> {
session.require_feature(crate::base::protocol::features::Feature::ShellV2)?;
let dest_len = write_destination(buf, prefix, args)?;
session.open(&buf[..dest_len]).await
}
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 = open_shell_channel(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 = open_shell_channel(session, b"logcat -B -d", args, buf).await?;
let mut logcat = Logcat::new(channel, buf);
let mut entries = Vec::new();
loop {
match logcat.read_entry().await {
Ok(entry) => entries.push(entry),
Err(Error::ChannelClosed) => break,
Err(e) => return Err(e),
}
}
let _ = logcat.close().await;
Ok(entries)
}
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 = open_shell_channel(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 = open_shell_channel(session, b"logcat", args, rx).await?;
let mut shell = Shell::new(channel, rx);
shell.close_stdin().await?;
shell.collect().await
}
mod format;
pub use format::*;
#[cfg(test)]
mod tests;