libadb-ffi 0.9.0

C ABI for libadb
Documentation
#![allow(clippy::await_holding_lock)]

use alloc::boxed::Box;
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
use core::ffi::{c_char, CStr};
use core::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;

use libadb::base::channel::ChannelId;
use libadb::base::error::{Error, ProtocolError};
use libadb::shell::v2::{destination, FrameDecoder, FrameId, ShellMode, WindowSize};

use crate::block_on;
use crate::connection::{lock_poisoned, FfiReader, FfiWriter};
use crate::error::{self, AdbStatus};
use crate::slice::copy_out;
use crate::transport::FfiTransportError;

const SHELL_V2_RX_BUF: usize = 64 * 1024;

struct ParseState {
    rx: Vec<u8>,
    decoder: FrameDecoder,
}

impl ParseState {
    fn new() -> Self {
        Self {
            rx: vec![0u8; SHELL_V2_RX_BUF],
            decoder: FrameDecoder::new(),
        }
    }

    fn try_next_frame(&mut self) -> Result<Option<(u8, Vec<u8>)>, Error<FfiTransportError>> {
        let frame = self
            .decoder
            .try_next_raw(&self.rx)
            .map_err(Error::Protocol)?;
        Ok(frame.map(|(id, payload)| (FrameId::byte_of(id), payload)))
    }

    fn ensure_writable(&mut self) -> Result<(), Error<FfiTransportError>> {
        if self.decoder.tail() < self.rx.len() {
            return Ok(());
        }
        self.decoder.compact(&mut self.rx);
        if self.decoder.tail() == self.rx.len() {
            return Err(Error::ReceiveBufferFull);
        }
        Ok(())
    }
}

/// Opaque shell_v2 session handle.
///
/// No outer mutex: each field guards its own mutable state, so reader
/// and writer paths can run concurrently without contending on a single
/// session-wide lock.
#[allow(non_camel_case_types)]
pub struct adb_shell_t {
    reader: Arc<Mutex<FfiReader>>,
    writer: FfiWriter,
    channel_id: ChannelId,
    parse_state: Mutex<ParseState>,
    send_lock: Mutex<()>,
    closed: AtomicBool,
}

const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<adb_shell_t>();
};

fn read_frame(sh: &adb_shell_t) -> Result<(u8, Vec<u8>), Error<FfiTransportError>> {
    let mut p = lock_poisoned(&sh.parse_state);
    loop {
        if let Some(frame) = p.try_next_frame()? {
            return Ok(frame);
        }
        p.ensure_writable()?;
        let tail = p.decoder.tail();
        let dst = &mut p.rx[tail..];
        let n = block_on::block_on_read(&sh.reader, &sh.writer, sh.channel_id, dst)?;
        p.decoder.commit(n);
    }
}

async fn send_frame_async(
    writer: &FfiWriter,
    send_lock: &Mutex<()>,
    channel_id: ChannelId,
    id: FrameId,
    payload: &[u8],
) -> Result<(), Error<FfiTransportError>> {
    let len = u32::try_from(payload.len())
        .map_err(|_| Error::Protocol(ProtocolError::PayloadTooLarge))?;
    let b = len.to_le_bytes();
    let hdr = [id.into(), b[0], b[1], b[2], b[3]];
    let _turn = lock_poisoned(send_lock);
    writer.write_channel(channel_id, &hdr).await?;
    if !payload.is_empty() {
        writer.write_channel(channel_id, payload).await?;
    }
    Ok(())
}

/// Open a shell_v2 session running `command`, which must be UTF-8 and
/// need not be null-terminated. With `pty` the session gets a PTY, with
/// `term` for its `TERM` and `rows` and `cols` for its window size.
///
/// On success, `*out_sh` receives a handle that must be released with
/// [`adb_shell_free`]. Call [`adb_shell_close`] beforehand to tear down
/// the channel gracefully. See `libadb.h`.
///
/// # Safety
/// `conn` must be a valid handle and must outlive the returned session.
/// `command` must be NULL or readable for `command_len` bytes, `term`
/// NULL or a valid null-terminated C string, and `out_sh` must point to
/// a writable `adb_shell_t*`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn adb_shell_open(
    conn: *mut super::adb_connection_t,
    command: *const u8,
    command_len: usize,
    pty: bool,
    term: *const c_char,
    rows: u16,
    cols: u16,
    out_sh: *mut *mut adb_shell_t,
) -> AdbStatus {
    error::clear_last_error();
    if conn.is_null() || out_sh.is_null() || (command.is_null() && command_len > 0) {
        return error::fail_invalid_arg("null pointer");
    }

    // SAFETY: non-null, and a valid handle per `# Safety`.
    let conn = unsafe { &*conn };
    // SAFETY: readable for `command_len` bytes when non-null, per `# Safety`.
    let cmd_bytes = unsafe { super::slice::from_ptr(command, command_len) };
    let cmd_str = match core::str::from_utf8(cmd_bytes) {
        Ok(s) => s,
        Err(e) => return error::fail_invalid_arg(e),
    };
    let term_str = if term.is_null() {
        None
    } else {
        // SAFETY: non-null, and a C string per `# Safety`.
        match unsafe { CStr::from_ptr(term) }.to_str() {
            Ok(s) => Some(s),
            Err(e) => return error::fail_invalid_arg(e),
        }
    };
    let mode = if pty {
        ShellMode::Pty { term: term_str }
    } else {
        ShellMode::Raw
    };

    let dest = match destination(mode, cmd_str) {
        Ok(d) => d,
        Err(e) => return error::fail_error::<FfiTransportError>(Error::Protocol(e)),
    };

    let reader_arc = Arc::clone(&conn.reader);
    let writer = conn.writer.clone();

    let channel_id = {
        let mut r = lock_poisoned(&reader_arc);
        ffi_try!(r.open_channel(dest.as_bytes()))
    };
    let send_lock = Mutex::new(());

    if pty && (rows != 0 || cols != 0) {
        let payload = WindowSize { rows, cols }.encode();
        let send = send_frame_async(
            &writer,
            &send_lock,
            channel_id,
            FrameId::WindowSizeChange,
            payload.as_bytes(),
        );
        if let Err(e) = block_on::block_on_write(&reader_arc, &writer, channel_id, send) {
            let _ = block_on::block_on(writer.close_channel(channel_id));
            return error::fail_error(e);
        }
    }

    let boxed = Box::new(adb_shell_t {
        reader: reader_arc,
        writer,
        channel_id,
        parse_state: Mutex::new(ParseState::new()),
        send_lock,
        closed: AtomicBool::new(false),
    });
    // SAFETY: non-null, and writable per `# Safety`.
    unsafe { *out_sh = Box::into_raw(boxed) };
    AdbStatus::Ok
}

/// Release a handle previously returned by [`adb_shell_open`]. NULL is
/// a no-op. The channel is not closed automatically: call
/// [`adb_shell_close`] first to avoid leaking it on the device.
///
/// # Safety
/// `sh` must be NULL or a handle returned by [`adb_shell_open`] that has
/// not yet been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn adb_shell_free(sh: *mut adb_shell_t) {
    if sh.is_null() {
        return;
    }
    // SAFETY: a live handle from `adb_shell_open`, which boxed it, per `# Safety`.
    drop(unsafe { Box::from_raw(sh) });
}

/// Read one decoded shell_v2 frame: `*out_id` receives the frame id,
/// `buf` up to `buf_cap` bytes of payload and `*out_len` the full
/// payload length. Channel closure is [`AdbStatus::ChannelClosed`]. See
/// `libadb.h`.
///
/// # Safety
/// `sh` must be a valid handle. `out_id` must point to a writable `u8`.
/// `buf` must be NULL or point to at least `buf_cap` writable bytes.
/// `out_len` must be NULL or point to a writable `usize`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn adb_shell_read_frame(
    sh: *mut adb_shell_t,
    out_id: *mut u8,
    buf: *mut u8,
    buf_cap: usize,
    out_len: *mut usize,
) -> AdbStatus {
    error::clear_last_error();
    if sh.is_null() || out_id.is_null() || (buf.is_null() && buf_cap > 0) {
        return error::fail_invalid_arg("null pointer");
    }
    // SAFETY: non-null, and a valid handle per `# Safety`.
    let sh = unsafe { &*sh };
    if sh.closed.load(Ordering::Acquire) {
        return error::fail_error::<FfiTransportError>(Error::ChannelClosed);
    }
    let (id, payload) = match read_frame(sh) {
        Ok(frame) => frame,
        Err(e) => return error::fail_error(e),
    };
    // SAFETY: non-null, and writable per `# Safety`.
    unsafe { *out_id = id };
    // SAFETY: `buf` and `out_len` are NULL or writable as sized, per
    // `# Safety`, and `buf` cannot overlap the freshly built `payload`.
    unsafe { copy_out(&payload, buf, buf_cap, out_len) };
    AdbStatus::Ok
}

/// Send a `STDIN` frame. Safe to call from several threads on one
/// session: frames arrive whole. After a failure the session's frame
/// stream cannot be trusted: close it. See `libadb.h`.
///
/// # Safety
/// `sh` must be a valid handle. `data` must be NULL or point to at least
/// `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn adb_shell_write_stdin(
    sh: *mut adb_shell_t,
    data: *const u8,
    len: usize,
) -> AdbStatus {
    error::clear_last_error();
    if sh.is_null() || (data.is_null() && len > 0) {
        return error::fail_invalid_arg("null pointer");
    }
    // SAFETY: readable for `len` bytes when non-null, per `# Safety`.
    let payload = unsafe { super::slice::from_ptr(data, len) };
    // SAFETY: non-null, and a valid handle per `# Safety`.
    unsafe { send_frame_payload(sh, FrameId::Stdin, payload) }
}

/// Send a `CLOSE_STDIN` frame — no more stdin will follow. A channel
/// the device has already closed is not a failure. See `libadb.h`.
///
/// # Safety
/// `sh` must be a valid handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn adb_shell_close_stdin(sh: *mut adb_shell_t) -> AdbStatus {
    error::clear_last_error();
    if sh.is_null() {
        return error::fail_invalid_arg("null handle");
    }
    // SAFETY: non-null, and a valid handle per `# Safety`.
    let sh = unsafe { &*sh };
    match send_frame(sh, FrameId::CloseStdin, &[]) {
        Ok(()) => AdbStatus::Ok,
        Err(Error::ChannelClosed) if !sh.closed.load(Ordering::Acquire) => AdbStatus::Ok,
        Err(e) => error::fail_error(e),
    }
}

/// Send a `WINDOW_SIZE_CHANGE` frame.
///
/// # Safety
/// `sh` must be a valid handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn adb_shell_set_window_size(
    sh: *mut adb_shell_t,
    rows: u16,
    cols: u16,
) -> AdbStatus {
    error::clear_last_error();
    if sh.is_null() {
        return error::fail_invalid_arg("null handle");
    }
    let payload = WindowSize { rows, cols }.encode();
    // SAFETY: non-null, and a valid handle per `# Safety`.
    unsafe { send_frame_payload(sh, FrameId::WindowSizeChange, payload.as_bytes()) }
}

/// Close the underlying channel. Subsequent read/write ops on this
/// handle return [`AdbStatus::ChannelClosed`]. Idempotent.
///
/// # Safety
/// `sh` must be a valid handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn adb_shell_close(sh: *mut adb_shell_t) -> AdbStatus {
    error::clear_last_error();
    if sh.is_null() {
        return error::fail_invalid_arg("null handle");
    }
    // SAFETY: non-null, and a valid handle per `# Safety`.
    let sh = unsafe { &*sh };
    if sh
        .closed
        .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
        .is_err()
    {
        return AdbStatus::Ok;
    }
    let ch = sh.channel_id;
    ffi_try!(sh.writer.close_channel(ch));
    AdbStatus::Ok
}

/// # Safety
/// `sh` must be a valid handle.
unsafe fn send_frame_payload(sh: *mut adb_shell_t, id: FrameId, payload: &[u8]) -> AdbStatus {
    // SAFETY: a valid handle, per `# Safety`.
    match send_frame(unsafe { &*sh }, id, payload) {
        Ok(()) => AdbStatus::Ok,
        Err(e) => error::fail_error(e),
    }
}

fn send_frame(
    sh: &adb_shell_t,
    id: FrameId,
    payload: &[u8],
) -> Result<(), Error<FfiTransportError>> {
    if sh.closed.load(Ordering::Acquire) {
        return Err(Error::ChannelClosed);
    }
    let ch = sh.channel_id;
    let send = send_frame_async(&sh.writer, &sh.send_lock, ch, id, payload);
    block_on::block_on_write(&sh.reader, &sh.writer, ch, send)
}