rustduck-core 1.1.0

Safe typed TSDuck core bindings for rustduck
Documentation
//! Native bridge trampoline and panic containment.

use std::panic::{AssertUnwindSafe, catch_unwind};

use rustduck_sys::bridge::{self as sys_bridge, ffi as sys_ffi};

use crate::{Error, Result};

use crate::memory::endpoint::CallbackError;
use crate::memory::registry;

use super::protocol::{self, CallbackDirection, CallbackRequest, CallbackResponse};

const PLUGIN_NAME_VALID: u8 = 0x01;
const DATA_VALID: u8 = 0x02;
const EVENT_DATA_VALID: u8 = 0x04;

/// Installs the process-wide private dispatcher used by the sys native adapter.
pub(crate) fn install_dispatcher() -> Result<()> {
    if sys_bridge::install_memory_callback_dispatcher(native_dispatch, native_writeback_failure) {
        Ok(())
    } else {
        Err(Error::InvalidState {
            object: "MemoryEventHandler",
            operation: "install dispatcher",
            state: "already installed with a different dispatcher",
        })
    }
}

/// Validates one native callback after its adapter has copied native buffers.
/// A panic is captured, recorded on the target endpoint when available, and
/// converted into a callback failure.
fn dispatch(request: CallbackRequest<'_>) -> Option<CallbackResponse> {
    let event_code = request.event_code;
    contain_panic(event_code, || protocol::dispatch(request))
}

fn native_writeback_failure(event_code: u32) {
    if let Some(endpoint) = registry::lookup(event_code) {
        protocol::record(&endpoint, CallbackError::NativeWritebackFailure);
    }
}

fn native_dispatch(
    event_code: u32,
    plugin_name_utf16: &[u8],
    data: &[u8],
    writable_capacity: usize,
    data_read_only: bool,
    validity: u8,
) -> sys_ffi::RustDuckMemoryCallbackResult {
    let direction = if data_read_only {
        CallbackDirection::Output
    } else {
        CallbackDirection::Input
    };
    let response = dispatch(CallbackRequest {
        event_code,
        plugin_name_utf16,
        direction,
        data,
        writable_capacity: if data_read_only { 0 } else { writable_capacity },
        plugin_name_valid: validity & PLUGIN_NAME_VALID != 0,
        data_valid: validity & DATA_VALID != 0,
        event_data_valid: validity & EVENT_DATA_VALID != 0,
    });
    let (ok, data) = match response {
        Some(CallbackResponse::Input(Some(data))) => (true, data),
        Some(CallbackResponse::Input(None) | CallbackResponse::Output) => (true, Vec::new()),
        None => (false, Vec::new()),
    };
    sys_ffi::RustDuckMemoryCallbackResult { ok, data }
}

fn contain_panic(
    event_code: u32,
    operation: impl FnOnce() -> Option<CallbackResponse>,
) -> Option<CallbackResponse> {
    match catch_unwind(AssertUnwindSafe(operation)) {
        Ok(result) => result,
        Err(_) => {
            if let Some(endpoint) = registry::lookup(event_code) {
                protocol::record(&endpoint, CallbackError::Panic);
            }
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroUsize;

    use super::*;
    use crate::memory::{MemoryInput, MemoryOutput, MemoryQueuePolicy};
    use crate::transport_stream::TS_PACKET_SIZE;

    fn plugin_name(name: &str) -> Vec<u8> {
        name.encode_utf16().flat_map(u16::to_ne_bytes).collect()
    }

    fn request<'a>(
        event_code: u32,
        plugin_name_utf16: &'a [u8],
        direction: CallbackDirection,
        data: &'a [u8],
        writable_capacity: usize,
    ) -> CallbackRequest<'a> {
        CallbackRequest {
            event_code,
            plugin_name_utf16,
            direction,
            data,
            writable_capacity,
            plugin_name_valid: true,
            data_valid: true,
            event_data_valid: true,
        }
    }

    #[test]
    fn rejects_wrong_plugin_before_routing() {
        let output = MemoryOutput::new(
            NonZeroUsize::new(TS_PACKET_SIZE).expect("nonzero"),
            MemoryQueuePolicy::Drop,
        )
        .expect("endpoint");
        assert!(
            dispatch(request(
                output.inner.event_code(),
                &plugin_name("other"),
                CallbackDirection::Output,
                &[0x47; TS_PACKET_SIZE],
                0,
            ))
            .is_none()
        );
        assert_eq!(
            output.take_callback_error(),
            Some(CallbackError::WrongPlugin)
        );
    }

    #[test]
    fn output_callback_routes_packets_and_contains_protocol_errors() {
        let output = MemoryOutput::new(
            NonZeroUsize::new(TS_PACKET_SIZE).expect("nonzero"),
            MemoryQueuePolicy::Drop,
        )
        .expect("endpoint");
        let name = plugin_name("memory");
        let packets = [0x47; TS_PACKET_SIZE];
        assert!(matches!(
            dispatch(request(
                output.inner.event_code(),
                &name,
                CallbackDirection::Output,
                &packets,
                0,
            )),
            Some(CallbackResponse::Output)
        ));
        assert_eq!(output.recv().expect("receive"), Some(packets.to_vec()));

        assert!(
            dispatch(request(
                output.inner.event_code(),
                &name,
                CallbackDirection::Output,
                &packets[..TS_PACKET_SIZE - 1],
                0,
            ))
            .is_none()
        );
        assert_eq!(
            output.take_callback_error(),
            Some(CallbackError::InvalidPacketAlignment)
        );
        assert!(matches!(
            output.try_recv_shared(),
            Err(crate::Error::QueueAborted { .. })
        ));
    }

    #[test]
    fn callback_queue_abort_is_owner_visible() {
        let output = MemoryOutput::new(
            NonZeroUsize::new(TS_PACKET_SIZE).expect("nonzero"),
            MemoryQueuePolicy::Drop,
        )
        .expect("endpoint");
        output.abort();
        assert!(
            dispatch(request(
                output.inner.event_code(),
                &plugin_name("memory"),
                CallbackDirection::Output,
                &[0x47; TS_PACKET_SIZE],
                0,
            ))
            .is_none()
        );
        assert_eq!(
            output.take_callback_error(),
            Some(CallbackError::QueueAborted)
        );
    }

    #[test]
    fn input_callback_drains_and_then_reports_eof() {
        let input = MemoryInput::new(
            NonZeroUsize::new(TS_PACKET_SIZE).expect("nonzero"),
            MemoryQueuePolicy::Drop,
        )
        .expect("endpoint");
        input.push(&[0x47; TS_PACKET_SIZE]).expect("push");
        input.close();
        let name = plugin_name("memory");
        let first = dispatch(request(
            input.inner.event_code(),
            &name,
            CallbackDirection::Input,
            &[],
            TS_PACKET_SIZE,
        ));
        assert!(
            matches!(first, Some(CallbackResponse::Input(Some(data))) if data == [0x47; TS_PACKET_SIZE])
        );
        assert!(matches!(
            dispatch(request(
                input.inner.event_code(),
                &name,
                CallbackDirection::Input,
                &[],
                TS_PACKET_SIZE,
            )),
            Some(CallbackResponse::Input(None))
        ));
    }

    #[test]
    fn panic_is_contained_and_aborts_the_target_endpoint() {
        let input = MemoryInput::new(
            NonZeroUsize::new(TS_PACKET_SIZE).expect("nonzero"),
            MemoryQueuePolicy::Drop,
        )
        .expect("endpoint");
        assert!(contain_panic(input.inner.event_code(), || panic!("test panic")).is_none());
        assert_eq!(input.take_callback_error(), Some(CallbackError::Panic));
        assert!(matches!(
            input.push(&[]),
            Err(crate::Error::QueueAborted { .. })
        ));
    }
}