Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@ include = [
"/THIRD_PARTY_LICENSES.md",
]

[dependencies]
log = "0.4.14"

[build-dependencies]
cc = "1.2"
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
16 changes: 0 additions & 16 deletions src/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
}
40 changes: 36 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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");
43 changes: 43 additions & 0 deletions src/report.rs
Original file line number Diff line number Diff line change
@@ -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
}
48 changes: 26 additions & 22 deletions src/vma.cpp
Original file line number Diff line number Diff line change
@@ -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 <atomic>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>

static_assert(VMA_VERSION == VK_MAKE_VERSION(3, 5, 0), "src/bindings.rs is generated from VMA 3.5.0");

static std::atomic<VmaSysCheckFailedHandler> check_failed_handler{nullptr};
static std::atomic<VmaSysLeakHandler> 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);
}
19 changes: 0 additions & 19 deletions src/vma.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
26 changes: 26 additions & 0 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -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);
}
}
74 changes: 74 additions & 0 deletions tests/fallback.rs
Original file line number Diff line number Diff line change
@@ -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<Output> {
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}");
}
40 changes: 40 additions & 0 deletions tests/to_logger.rs
Original file line number Diff line number Diff line change
@@ -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<Vec<String>> = 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:?}");
}
Loading
Loading