diff --git a/Cargo.lock b/Cargo.lock index 3fdba68..c374a81 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,6 +18,12 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + [[package]] name = "shlex" version = "2.0.1" @@ -29,4 +35,5 @@ name = "vulkan-memory-allocator-sys" version = "0.1.0" dependencies = [ "cc", + "log", ] diff --git a/Cargo.toml b/Cargo.toml index 2d150e4..a420565 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,5 +19,8 @@ include = [ "/THIRD_PARTY_LICENSES.md", ] +[dependencies] +log = "0.4.14" + [build-dependencies] cc = "1.2" diff --git a/README.md b/README.md index 30465b0..f31bce1 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ Raw Rust bindings to AMD's [Vulkan Memory Allocator](https://github.com/GPUOpen- VMA and the Vulkan headers are included, so building needs only a C++17 compiler. The crate doesn't depend on ash or any other Vulkan bindings. There is no safe wrapper, and everything is named as in VMA's C API. +Failed checks go to stderr and the [`log`](https://crates.io/crates/log) crate. Leak reports go to `log`, or to stderr if no logger takes them. The crate docs have the details. + ## License MIT. See [THIRD_PARTY_LICENSES.md](THIRD_PARTY_LICENSES.md) for VMA and the Vulkan headers. diff --git a/src/bindings.rs b/src/bindings.rs index 7fbc29d..83c76ee 100644 --- a/src/bindings.rs +++ b/src/bindings.rs @@ -3699,19 +3699,3 @@ unsafe extern "C" { pStatsString: *mut ::core::ffi::c_char, ); } -pub type VmaSysCheckFailedHandler = ::core::option::Option< - unsafe extern "C" fn( - expr: *const ::core::ffi::c_char, - file: *const ::core::ffi::c_char, - line: ::core::ffi::c_int, - ), ->; -pub type VmaSysLeakHandler = ::core::option::Option< - unsafe extern "C" fn(expr: *const ::core::ffi::c_char), ->; -unsafe extern "C" { - pub fn vmaSysSetHandlers( - check_failed: VmaSysCheckFailedHandler, - leak: VmaSysLeakHandler, - ); -} diff --git a/src/lib.rs b/src/lib.rs index 4f98c13..d6734ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,12 +10,39 @@ //! //! Virtual blocks ([`vmaCreateVirtualBlock`]) need no Vulkan device. //! -//! See [`vmaSysSetHandlers`] to route failed checks and leak reports somewhere other than stderr. -//! Checks are compiled in when this crate is built with debug assertions. Leak reports are always -//! on. A pool still alive when its allocator is destroyed is a check, not a leak report. -//! //! The library is built for Vulkan 1.4 with `VMA_EXTERNAL_MEMORY` on and //! `VMA_EXTERNAL_MEMORY_WIN32` off, and for 64-bit targets only. +//! +//! # Failed checks and leaks +//! +//! VMA reports through macros with no allocator to hand, so this crate sends its reports to +//! [`log`] at error level with the target [`LOG_TARGET`]. +//! +//! Checks are compiled in when this crate is built with debug assertions. A failed check goes to +//! stderr, then to `log`, then the logger is flushed and the process aborts. +//! +//! Leak reports are always on. Each one goes to `log`, or to stderr if `log_enabled!` is false for +//! [`LOG_TARGET`]. `log` can't tell a missing logger from a filter, so filtering out the target +//! moves leak reports to stderr rather than silencing them. A logger that accepts a report and +//! then drops it loses it. +//! +//! Each leak report is one line starting `VMA leak: `, cut off at 1023 bytes. They say: +//! +//! - For each allocation left in a memory block when it's destroyed: offset in the block, size, +//! user data, name, type and usage. The name is the one set with [`vmaSetAllocationName`]. +//! - For each allocation left in a virtual block: offset, size and user data. +//! - For each memory or virtual block destroyed with allocations left: one more line saying so. +//! - For dedicated allocations: only that some were left. They aren't listed. +//! - For memory still mapped when it's freed: only that it was mapped. +//! +//! No line says which allocator, pool or block it came from. A pool still alive when its allocator +//! is destroyed is a failed check, not a leak report. +//! +//! To act on a leak in code, call [`vmaIsVirtualBlockEmpty`] or [`vmaCalculateStatistics`] before +//! destroying, or match [`LOG_TARGET`] in a logger. +//! +//! The logger runs inside VMA's calls, sometimes with VMA's locks held, so it must not call VMA. +//! It must not panic either: a panic can't unwind through VMA, so it aborts the process. #![no_std] #![allow( @@ -32,4 +59,9 @@ #[cfg(not(target_pointer_width = "64"))] compile_error!("vulkan-memory-allocator-sys supports only 64-bit targets"); +mod report; + +/// The `log` target of VMA's failed checks and leak reports. +pub const LOG_TARGET: &str = "vulkan_memory_allocator_sys"; + include!("bindings.rs"); diff --git a/src/report.rs b/src/report.rs new file mode 100644 index 0000000..c518461 --- /dev/null +++ b/src/report.rs @@ -0,0 +1,43 @@ +//! The side of `src/vma.cpp`'s reports that needs `log`. + +use core::ffi::{CStr, c_char, c_int}; +use core::fmt; + +use log::Level; + +use crate::LOG_TARGET; + +/// Shows bytes as UTF-8. VMA names can hold any bytes, and truncation can split a character. +struct Lossy<'a>(&'a [u8]); + +impl fmt::Display for Lossy<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for chunk in self.0.utf8_chunks() { + f.write_str(chunk.valid())?; + if !chunk.invalid().is_empty() { + f.write_str("\u{FFFD}")?; + } + } + Ok(()) + } +} + +/// Logs `message`, and flushes the logger if `fatal` isn't 0. Returns 0 if the logger doesn't +/// want it. +/// +/// # Safety +/// +/// `message` is NUL-terminated. +#[unsafe(no_mangle)] +unsafe extern "C" fn vma_sys_log(message: *const c_char, fatal: c_int) -> c_int { + if !log::log_enabled!(target: LOG_TARGET, Level::Error) { + return 0; + } + // SAFETY: the caller passes a NUL-terminated string. + let message = unsafe { CStr::from_ptr(message) }.to_bytes(); + log::error!(target: LOG_TARGET, "{}", Lossy(message)); + if fatal != 0 { + log::logger().flush(); + } + 1 +} diff --git a/src/vma.cpp b/src/vma.cpp index 0f26249..c67ba6a 100644 --- a/src/vma.cpp +++ b/src/vma.cpp @@ -1,45 +1,49 @@ -// VMA's implementation. Failed checks and leaks go to replaceable handlers, so no C runtime -// dialog opens. +// VMA's implementation. Failed checks and leaks go to `log` and stderr, so no C runtime dialog +// opens. static void vma_sys_check_failed(const char* expr, const char* file, int line); -static void vma_sys_leak(const char* expr); +static void vma_sys_leak(const char* format, ...); #ifdef VMA_SYS_CHECKS #define VMA_ASSERT(expr) ((expr) ? (void)0 : vma_sys_check_failed(#expr, __FILE__, __LINE__)) #else #define VMA_ASSERT(expr) #endif -#define VMA_ASSERT_LEAK(expr) ((expr) ? (void)0 : vma_sys_leak(#expr)) +#define VMA_ASSERT_LEAK(expr) ((expr) ? (void)0 : vma_sys_leak("VMA leak: %s", #expr)) +#define VMA_LEAK_LOG_FORMAT(format, ...) vma_sys_leak("VMA leak: " format, __VA_ARGS__) #define VMA_IMPLEMENTATION #include "vma.h" -#include +#include #include #include static_assert(VMA_VERSION == VK_MAKE_VERSION(3, 5, 0), "src/bindings.rs is generated from VMA 3.5.0"); -static std::atomic check_failed_handler{nullptr}; -static std::atomic leak_handler{nullptr}; +// Defined in src/report.rs. Hidden so that a Rust cdylib doesn't export it on ELF. +extern "C" +#ifdef __GNUC__ +__attribute__((visibility("hidden"))) +#endif +int vma_sys_log(const char* message, int fatal); +// A logger can drop or hold a message, so stderr comes first. static void vma_sys_check_failed(const char* expr, const char* file, int line) { - if (VmaSysCheckFailedHandler handler = check_failed_handler.load()) { - handler(expr, file, line); - } else { - std::fprintf(stderr, "VMA check failed at %s:%d: %s\n", file, line, expr); - } + char message[1024]; + std::snprintf(message, sizeof message, "VMA check failed at %s:%d: %s", file, line, expr); + std::fprintf(stderr, "%s\n", message); + std::fflush(stderr); + vma_sys_log(message, 1); std::abort(); } -static void vma_sys_leak(const char* expr) { - if (VmaSysLeakHandler handler = leak_handler.load()) { - handler(expr); - } else { - std::fprintf(stderr, "VMA leak: %s\n", expr); +static void vma_sys_leak(const char* format, ...) { + char message[1024]; + std::va_list args; + va_start(args, format); + std::vsnprintf(message, sizeof message, format, args); + va_end(args); + if (!vma_sys_log(message, 0)) { + std::fprintf(stderr, "%s\n", message); } } - -extern "C" void vmaSysSetHandlers(VmaSysCheckFailedHandler check_failed, VmaSysLeakHandler leak) { - check_failed_handler.store(check_failed); - leak_handler.store(leak); -} diff --git a/src/vma.h b/src/vma.h index e1f8b45..3d1ea27 100644 --- a/src/vma.h +++ b/src/vma.h @@ -11,23 +11,4 @@ #define VMA_EXTERNAL_MEMORY_WIN32 0 #include "vk_mem_alloc.h" -#ifdef __cplusplus -extern "C" { -#endif - -// Called when one of VMA's internal checks fails. The process aborts when it returns. -typedef void (*VmaSysCheckFailedHandler)(const char* expr, const char* file, int line); -// Called when an allocator, pool or virtual block is destroyed with allocations left, or memory is -// freed while still mapped. -typedef void (*VmaSysLeakHandler)(const char* expr); - -// Replaces the handlers, which print to stderr by default. Null restores a default. Safe to call -// from any thread. Internal checks are compiled only when the crate is built with debug -// assertions; the leak handler is always active. -void vmaSysSetHandlers(VmaSysCheckFailedHandler check_failed, VmaSysLeakHandler leak); - -#ifdef __cplusplus -} -#endif - #endif diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..b52009b --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,26 @@ +use std::ptr; + +use vulkan_memory_allocator_sys::*; + +/// Destroys a virtual block with a 64-byte allocation left at offset 0. +pub fn leak() { + let block_info = VmaVirtualBlockCreateInfo { + size: 1024, + ..Default::default() + }; + let allocation_info = VmaVirtualAllocationCreateInfo { + size: 64, + alignment: 1, + ..Default::default() + }; + let mut block = ptr::null_mut(); + let mut allocation = ptr::null_mut(); + let mut offset = 0; + // SAFETY: the arguments outlive each call, and `block` is live until destroyed. + unsafe { + assert_eq!(vmaCreateVirtualBlock(&block_info, &mut block), VK_SUCCESS); + let result = vmaVirtualAllocate(block, &allocation_info, &mut allocation, &mut offset); + assert_eq!(result, VK_SUCCESS); + vmaDestroyVirtualBlock(block); + } +} diff --git a/tests/fallback.rs b/tests/fallback.rs new file mode 100644 index 0000000..b2e0667 --- /dev/null +++ b/tests/fallback.rs @@ -0,0 +1,74 @@ +//! Each test runs again as a child process, which has no logger yet, puts VMA's stderr where the +//! parent can read it, and can abort. + +use std::env; +use std::process::{Command, Output}; + +mod common; + +const CHILD: &str = "VMA_SYS_TEST_CHILD"; + +/// Runs `body` if this is the child. Otherwise runs `test` in a child and returns its output. +fn in_child(test: &str, body: fn()) -> Option { + if env::var_os(CHILD).is_some() { + body(); + return None; + } + let output = Command::new(env::current_exe().unwrap()) + .args(["--exact", test]) + .env(CHILD, "1") + .output() + .unwrap(); + Some(output) +} + +#[test] +fn a_leak_with_no_logger_reaches_stderr() { + let Some(output) = in_child("a_leak_with_no_logger_reaches_stderr", common::leak) else { + return; + }; + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stderr}"); + assert!( + stderr.contains("VMA leak: UNFREED VIRTUAL ALLOCATION; Offset: 0; Size: 64;"), + "{stderr}" + ); +} + +// Checks are compiled in only with debug assertions. +#[cfg(debug_assertions)] +#[test] +fn a_failed_check_reaches_stderr_past_a_logger_that_drops_it_and_aborts() { + use std::ptr; + + use vulkan_memory_allocator_sys::*; + + struct Drops; + + impl log::Log for Drops { + fn enabled(&self, _: &log::Metadata<'_>) -> bool { + true + } + + fn log(&self, _: &log::Record<'_>) {} + + fn flush(&self) {} + } + + fn fail_a_check() { + log::set_logger(&Drops).unwrap(); + log::set_max_level(log::LevelFilter::Error); + let info = VmaVirtualBlockCreateInfo::default(); + let mut block = ptr::null_mut(); + // SAFETY: the size of 0 fails a check, which aborts before anything else happens. + unsafe { vmaCreateVirtualBlock(&info, &mut block) }; + } + + let test = "a_failed_check_reaches_stderr_past_a_logger_that_drops_it_and_aborts"; + let Some(output) = in_child(test, fail_a_check) else { + return; + }; + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!output.status.success(), "{stderr}"); + assert!(stderr.contains("VMA check failed at "), "{stderr}"); +} diff --git a/tests/to_logger.rs b/tests/to_logger.rs new file mode 100644 index 0000000..200caba --- /dev/null +++ b/tests/to_logger.rs @@ -0,0 +1,40 @@ +//! The logger is set once per process, so this file holds the one test that sets it. + +use std::sync::Mutex; + +use log::{LevelFilter, Log, Metadata, Record}; +use vulkan_memory_allocator_sys::LOG_TARGET; + +mod common; + +static LINES: Mutex> = Mutex::new(Vec::new()); + +struct Capture; + +impl Log for Capture { + fn enabled(&self, metadata: &Metadata<'_>) -> bool { + metadata.target() == LOG_TARGET + } + + fn log(&self, record: &Record<'_>) { + LINES.lock().unwrap().push(record.args().to_string()); + } + + fn flush(&self) {} +} + +#[test] +fn a_leak_reaches_the_logger_with_its_offset_and_size() { + log::set_logger(&Capture).unwrap(); + log::set_max_level(LevelFilter::Error); + + common::leak(); + + let lines = LINES.lock().unwrap(); + assert_eq!(lines.len(), 2, "{lines:?}"); + assert!( + lines[0].starts_with("VMA leak: UNFREED VIRTUAL ALLOCATION; Offset: 0; Size: 64;"), + "{lines:?}" + ); + assert!(lines[1].starts_with("VMA leak: "), "{lines:?}"); +} diff --git a/tests/virtual_block.rs b/tests/virtual_block.rs index c53c3d3..a98bb63 100644 --- a/tests/virtual_block.rs +++ b/tests/virtual_block.rs @@ -1,7 +1,6 @@ //! Virtual blocks run the compiled library with no Vulkan device. use std::ptr; -use std::sync::atomic::{AtomicUsize, Ordering}; use vulkan_memory_allocator_sys::*; @@ -64,20 +63,3 @@ fn allocations_are_aligned_apart_and_freeable() { vmaDestroyVirtualBlock(block); } } - -static LEAKS: AtomicUsize = AtomicUsize::new(0); - -extern "C" fn count_leak(_expr: *const core::ffi::c_char) { - LEAKS.fetch_add(1, Ordering::Relaxed); -} - -#[test] -fn a_leak_reaches_the_handler() { - // SAFETY: the handler is a static function, and any thread may set it. - unsafe { vmaSysSetHandlers(None, Some(count_leak)) }; - let block = create_block(); - allocate(block, 64, 1); - // SAFETY: `block` is live and not used again. - unsafe { vmaDestroyVirtualBlock(block) }; - assert!(LEAKS.load(Ordering::Relaxed) >= 1); -}