siftgl 0.1.0

Memory-safe, ergonomic, zero-dependency, security-hardened OpenGL 3.3-4.6 Core frontend for Rust
Documentation
//! Panic-safe OpenGL 4.3 / `KHR_debug` callback registration with RAII cleanup.

use std::ffi::{c_void, CStr};
use std::fmt;
use std::panic::{self, AssertUnwindSafe};
use std::ptr;
use std::rc::Rc;

use crate::context::{GlContext, GlInner};
use crate::error::{GlError, Result};
use crate::sys;
use crate::types::{DebugSeverity, DebugSource, DebugType};

/// Structured OpenGL debug message delivered to a [`DebugGuard`] callback.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DebugMessage {
    /// Origin of the message.
    pub source: DebugSource,
    /// Category of the message.
    pub message_type: DebugType,
    /// Driver-specific numeric message identifier.
    pub id: u32,
    /// Severity level.
    pub severity: DebugSeverity,
    /// Human-readable driver diagnostic text.
    pub message: String,
}

type BoxedCallback = Box<dyn FnMut(DebugMessage) + 'static>;

/// RAII guard for an active OpenGL `KHR_debug` / GL 4.3 debug message callback.
///
/// Unregisters the callback with the driver (`glDebugMessageCallback(NULL, NULL)`)
/// BEFORE dropping the boxed Rust closure, guaranteeing no use-after-free can occur.
pub struct DebugGuard {
    ctx: Rc<GlInner>,
    user_data: *mut BoxedCallback,
}

impl fmt::Debug for DebugGuard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DebugGuard")
            .field("active", &(!self.user_data.is_null()))
            .finish()
    }
}

impl Drop for DebugGuard {
    fn drop(&mut self) {
        if let Some(set_cb) = self.ctx.fns.debug_message_callback {
            // SAFETY: Unregister callback FIRST so the driver can never invoke it again.
            unsafe {
                set_cb(None, ptr::null());
                (self.ctx.fns.disable)(sys::GL_DEBUG_OUTPUT);
            }
        }
        if !self.user_data.is_null() {
            // SAFETY: `self.user_data` was created via `Box::into_raw` in `DebugGuard::new`
            // and the driver callback has already been unregistered above.
            let _ = unsafe { Box::from_raw(self.user_data) };
            self.user_data = ptr::null_mut();
        }
    }
}

impl DebugGuard {
    /// Installs a panic-safe OpenGL debug message callback (`glDebugMessageCallback`).
    ///
    /// When `synchronous` is `true`, enables `GL_DEBUG_OUTPUT_SYNCHRONOUS` so messages
    /// are delivered immediately on the calling thread during the offending GL call.
    pub fn new<F>(ctx: &GlContext, synchronous: bool, callback: F) -> Result<Self>
    where
        F: FnMut(DebugMessage) + 'static,
    {
        let Some(set_cb) = ctx.inner.fns.debug_message_callback else {
            return Err(GlError::MissingFunction {
                name: "glDebugMessageCallback",
            });
        };

        let boxed: Box<BoxedCallback> = Box::new(Box::new(callback));
        let user_data = Box::into_raw(boxed);

        // SAFETY: `debug_trampoline` has the exact `GLDEBUGPROC` ABI, catches all panics
        // across FFI boundaries, and `user_data` remains valid until `DebugGuard::drop`
        // unregisters the callback.
        unsafe {
            (ctx.inner.fns.enable)(sys::GL_DEBUG_OUTPUT);
            if synchronous {
                (ctx.inner.fns.enable)(sys::GL_DEBUG_OUTPUT_SYNCHRONOUS);
            } else {
                (ctx.inner.fns.disable)(sys::GL_DEBUG_OUTPUT_SYNCHRONOUS);
            }
            set_cb(Some(debug_trampoline), user_data.cast::<c_void>());
            if let Some(control) = ctx.inner.fns.debug_message_control {
                control(
                    sys::GL_DONT_CARE,
                    sys::GL_DONT_CARE,
                    sys::GL_DONT_CARE,
                    0,
                    ptr::null(),
                    sys::GL_TRUE,
                );
            }
        }

        Ok(Self {
            ctx: Rc::clone(&ctx.inner),
            user_data,
        })
    }
}

/// Panic-safe C FFI trampoline for `GLDEBUGPROC`.
unsafe extern "system" fn debug_trampoline(
    source: sys::GLenum,
    gltype: sys::GLenum,
    id: sys::GLuint,
    severity: sys::GLenum,
    length: sys::GLsizei,
    message: *const sys::GLchar,
    user_param: *mut c_void,
) {
    if user_param.is_null() {
        return;
    }

    let text = if message.is_null() {
        String::new()
    } else if length > 0 {
        // SAFETY: Driver guarantees `message` has at least `length` readable bytes.
        let bytes = unsafe { std::slice::from_raw_parts(message.cast::<u8>(), length as usize) };
        String::from_utf8_lossy(bytes).into_owned()
    } else {
        // SAFETY: When `length <= 0`, driver guarantees `message` is NUL-terminated.
        let cstr = unsafe { CStr::from_ptr(message) };
        cstr.to_string_lossy().into_owned()
    };

    let msg = DebugMessage {
        source: DebugSource::from_raw(source),
        message_type: DebugType::from_raw(gltype),
        id,
        severity: DebugSeverity::from_raw(severity),
        message: text,
    };

    // SAFETY: `user_param` points to the live `BoxedCallback` owned by `DebugGuard`.
    let cb = unsafe { &mut *user_param.cast::<BoxedCallback>() };
    // Never unwind across a C/driver FFI boundary.
    let _ = panic::catch_unwind(AssertUnwindSafe(|| {
        cb(msg);
    }));
}