Files
leleka/crates/libc-shim/src/lib.rs
T

365 lines
15 KiB
Rust

//! Windows stand-in for the few `libc` symbols that the CUDA-facing crates call (`dlopen` family, `mlock`, page size,
//! `rlimit`, `geteuid`). Consumers depend on it under the name `libc` on Windows only
//! (`libc = { package = "leleka-libc-shim", ... }`), so the Linux call sites compile unchanged against either.
//!
//! Library names are mapped inside [`dlopen`]: `libcuda.so.1` becomes `nvcuda.dll`, and so on ([`windows_library_name`]).
//! On other targets the crate is empty.
#![cfg(windows)]
#![cfg(windows)]
pub use libc::*;
mod cuda_trace;
pub use cuda_trace::set_sync as cuda_trace_set_sync;
use std::ffi::CStr;
use windows_sys::Win32::{
Foundation::{FreeLibrary, HMODULE},
System::{
LibraryLoader::{
AddDllDirectory, GetModuleHandleA, GetProcAddress, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA,
},
Memory::{VirtualLock, VirtualUnlock},
SystemInformation::{GetSystemInfo, SYSTEM_INFO},
},
};
pub const RTLD_LAZY: c_int = 0x1;
pub const RTLD_NOW: c_int = 0x2;
pub const RTLD_LOCAL: c_int = 0;
pub const RTLD_GLOBAL: c_int = 0x100;
pub const RTLD_NOLOAD: c_int = 0x4;
/// Windows names of the shared objects the Linux code asks for by soname. Anything else passes through unchanged.
pub fn windows_library_name(unix_name: &str) -> &str {
match unix_name {
"libcuda.so.1" | "libcuda.so" => "nvcuda.dll",
"libnvidia-ml.so.1" | "libnvidia-ml.so" => "nvml.dll",
"libcublas.so.12" => "cublas64_12.dll",
"libcublasLt.so.12" => "cublasLt64_12.dll",
"libcudart.so.12" => "cudart64_12.dll",
other => other,
}
}
/// Environment variable naming extra directories (`;`-separated) that `dlopen` may load DLLs from, next to the
/// application directory and System32. `leleka run` sets it from `runtime.env` (`LD_LIBRARY_PATH`) so that the CUDA 12
/// cuBLAS DLLs can stay where the operator keeps them; `PATH` itself is not searched by the safe loader flags used here.
pub const DLL_DIRS_ENV: &str = "LELEKA_DLL_DIRS";
/// Register the directories of [`DLL_DIRS_ENV`] with the loader once per process.
fn register_extra_dll_directories() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
let Some(list) = std::env::var_os(DLL_DIRS_ENV) else {
return;
};
for dir in std::env::split_paths(&list).filter(|d| d.is_absolute()) {
let wide: Vec<u16> = std::os::windows::ffi::OsStrExt::encode_wide(dir.as_os_str())
.chain(Some(0))
.collect();
// SAFETY: `wide` is a NUL-terminated UTF-16 absolute path that outlives the call; the returned cookie is
// not needed because the directory stays registered for the life of the process.
let _ = unsafe { AddDllDirectory(wide.as_ptr()) };
}
});
}
/// `dlopen`: loads the DLL that stands for `filename` from the application directory or the system directories.
/// `RTLD_NOLOAD` only looks for an already loaded module. Returns null on failure (there is no `dlerror`).
///
/// # Safety
/// `filename` must be null or point to a NUL-terminated string.
pub unsafe fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void {
if filename.is_null() {
return std::ptr::null_mut();
}
// SAFETY: the caller guarantees a NUL-terminated string.
let name = unsafe { CStr::from_ptr(filename) };
let Ok(text) = name.to_str() else {
return std::ptr::null_mut();
};
let mapped = windows_library_name(text);
let Ok(c_name) = std::ffi::CString::new(mapped) else {
return std::ptr::null_mut();
};
if flags & RTLD_NOLOAD != 0 {
// SAFETY: valid NUL-terminated name; GetModuleHandleA does not change the reference count.
let handle = unsafe { GetModuleHandleA(c_name.as_ptr().cast()) };
return handle as *mut c_void;
}
register_extra_dll_directories();
// SAFETY: valid NUL-terminated name; no file handle is passed (reserved, must be null).
let handle = unsafe {
LoadLibraryExA(
c_name.as_ptr().cast(),
std::ptr::null_mut(),
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_SYSTEM32,
)
};
handle as *mut c_void
}
/// `dlsym`.
///
/// # Safety
/// `handle` is a value returned by [`dlopen`]; `symbol` is NUL-terminated.
pub unsafe fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void {
if handle.is_null() || symbol.is_null() {
return std::ptr::null_mut();
}
// SAFETY: a live module handle and a NUL-terminated symbol name, per the contract.
match unsafe { GetProcAddress(handle as HMODULE, symbol.cast()) } {
Some(function) => {
let address = function as usize as *mut c_void;
// SAFETY: the caller guarantees a NUL-terminated symbol name.
cuda_trace::interpose(handle, unsafe { CStr::from_ptr(symbol) }, address)
}
None => std::ptr::null_mut(),
}
}
/// `dlclose`; returns 0 on success.
///
/// # Safety
/// `handle` is a value returned by [`dlopen`] and is closed once.
pub unsafe fn dlclose(handle: *mut c_void) -> c_int {
if handle.is_null() {
return -1;
}
// SAFETY: a live module handle owned by the caller.
c_int::from(unsafe { FreeLibrary(handle as HMODULE) } == 0)
}
/// There is no POSIX uid; report a non-root one so that "am I root" branches take the user path.
pub fn geteuid() -> u32 {
1000
}
pub const RLIMIT_MEMLOCK: c_int = 8;
pub const RLIMIT_STACK: c_int = 3;
pub const RLIM_INFINITY: u64 = u64::MAX;
#[repr(C)]
#[derive(Clone, Copy, Debug)]
#[allow(non_camel_case_types)]
pub struct rlimit {
pub rlim_cur: u64,
pub rlim_max: u64,
}
/// `getrlimit`: Windows has no `RLIMIT_MEMLOCK`; the working-set quota is the real bound and `VirtualLock` reports it.
///
/// # Safety
/// `limit` points to a writable `rlimit`.
pub unsafe fn getrlimit(resource: c_int, limit: *mut rlimit) -> c_int {
// The stack answers like a default Linux shell (8 MiB) so callers that size worker threads from it keep working.
let current = if resource == RLIMIT_STACK { 8 << 20 } else { RLIM_INFINITY };
// SAFETY: writable per the contract.
unsafe {
*limit = rlimit { rlim_cur: current, rlim_max: RLIM_INFINITY };
}
0
}
/// `setrlimit`: accepted and ignored (see [`getrlimit`]).
///
/// # Safety
/// `limit` points to a readable `rlimit`.
pub unsafe fn setrlimit(_resource: c_int, _limit: *const rlimit) -> c_int {
0
}
pub const _SC_PAGESIZE: c_int = 30;
/// `sysconf(_SC_PAGESIZE)`; every other name answers -1.
pub fn sysconf(name: c_int) -> i64 {
if name != _SC_PAGESIZE {
return -1;
}
let mut info = std::mem::MaybeUninit::<SYSTEM_INFO>::zeroed();
// SAFETY: GetSystemInfo fills the structure it is given.
unsafe { GetSystemInfo(info.as_mut_ptr()) };
// SAFETY: initialised by the call above.
i64::from(unsafe { info.assume_init() }.dwPageSize)
}
/// `mlock` on `VirtualLock`; 0 on success, -1 on failure (errno is not set: use `std::io::Error::last_os_error`).
///
/// # Safety
/// The range is committed memory of this process.
pub unsafe fn mlock(addr: *const c_void, len: usize) -> c_int {
// SAFETY: VirtualLock validates the range itself and fails cleanly for foreign addresses.
if unsafe { VirtualLock(addr as *mut c_void, len) } == 0 { -1 } else { 0 }
}
/// `munlock` on `VirtualUnlock`.
///
/// # Safety
/// The range was passed to [`mlock`].
pub unsafe fn munlock(addr: *const c_void, len: usize) -> c_int {
// SAFETY: as for mlock.
if unsafe { VirtualUnlock(addr as *mut c_void, len) } == 0 { -1 } else { 0 }
}
/// Physical memory the OS can hand out without paging (`ullAvailPhys` of `GlobalMemoryStatusEx`: free plus standby pages, the
/// closest figure to Linux `MemAvailable`), and the installed total. `None` when the call fails.
pub fn physical_memory() -> Option<(u64, u64)> {
use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
let mut status = MEMORYSTATUSEX {
dwLength: std::mem::size_of::<MEMORYSTATUSEX>() as u32,
dwMemoryLoad: 0,
ullTotalPhys: 0,
ullAvailPhys: 0,
ullTotalPageFile: 0,
ullAvailPageFile: 0,
ullTotalVirtual: 0,
ullAvailVirtual: 0,
ullAvailExtendedVirtual: 0,
};
// SAFETY: `status` is a writable MEMORYSTATUSEX with dwLength set as the API requires.
if unsafe { GlobalMemoryStatusEx(&mut status) } == 0 {
return None;
}
Some((status.ullTotalPhys, status.ullAvailPhys))
}
/// A new handle on the same file with its own file object (`ReOpenFile`, read access, shared with readers): positional reads through
/// two such handles run in parallel, while two `try_clone`s of one synchronous handle share one file object and the I/O manager runs
/// their requests one at a time, whatever the thread count.
pub fn reopen_file_read(file: &std::fs::File) -> std::io::Result<std::fs::File> {
use std::os::windows::io::{AsRawHandle, FromRawHandle};
use windows_sys::Win32::Foundation::{GENERIC_READ, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, ReOpenFile};
// SAFETY: the raw handle belongs to `file`, which outlives the call; ReOpenFile returns a new handle (or INVALID_HANDLE_VALUE).
let handle = unsafe { ReOpenFile(file.as_raw_handle().cast(), GENERIC_READ, FILE_SHARE_READ, 0) };
if handle == INVALID_HANDLE_VALUE {
return Err(std::io::Error::last_os_error());
}
// SAFETY: `handle` is a valid, owned file handle that nothing else closes.
Ok(unsafe { std::fs::File::from_raw_handle(handle.cast()) })
}
/// Memory priority of the calling thread (1 very low .. 5 normal, the default): the standby-list priority the file pages it faults in
/// get, which decides what the memory manager repurposes first when it needs RAM. `false` when the call is refused.
pub fn set_thread_memory_priority(priority: u32) -> bool {
use windows_sys::Win32::System::Threading::{GetCurrentThread, MEMORY_PRIORITY_INFORMATION, SetThreadInformation, ThreadMemoryPriority};
let info = MEMORY_PRIORITY_INFORMATION { MemoryPriority: priority };
// SAFETY: the current-thread pseudo handle and a live MEMORY_PRIORITY_INFORMATION of exactly the size passed.
unsafe {
SetThreadInformation(
GetCurrentThread(),
ThreadMemoryPriority,
std::ptr::from_ref(&info).cast(),
std::mem::size_of::<MEMORY_PRIORITY_INFORMATION>() as u32,
) != 0
}
}
pub const PTHREAD_STACK_MIN: usize = 16384;
pub const MADV_WILLNEED: c_int = 3;
pub const MADV_DONTNEED: c_int = 4;
pub const MADV_POPULATE_READ: c_int = 22;
/// `madvise` is a hint on POSIX; here it is accepted and ignored.
///
/// # Safety
/// Never dereferences its arguments.
pub unsafe fn madvise(_addr: *mut c_void, _len: usize, _advice: c_int) -> c_int {
0
}
/// `dwAllocationGranularity`: the alignment of a file-view offset (64 KiB), the Windows counterpart of the page size for `mmap` offsets.
pub fn allocation_granularity() -> u64 {
let mut info = std::mem::MaybeUninit::<SYSTEM_INFO>::zeroed();
// SAFETY: GetSystemInfo fills the structure it is given.
unsafe { GetSystemInfo(info.as_mut_ptr()) };
// SAFETY: initialised by the call above.
u64::from(unsafe { info.assume_init() }.dwAllocationGranularity)
}
/// Maps `len` bytes of an open file read-only and shared (the `mmap(PROT_READ, MAP_SHARED)` of the Linux code), starting at
/// `offset` (which must be a multiple of the allocation granularity, 64 KiB). `len == 0` maps to the end of the file.
/// Returns null on failure; see `std::io::Error::last_os_error`.
///
/// # Safety
/// `file` is a live file HANDLE opened for reading. Like any file mapping, a file truncated while mapped faults on access.
pub unsafe fn map_file_readonly(file: *mut c_void, offset: u64, len: usize) -> *mut c_void {
use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_READ, MapViewOfFile, PAGE_READONLY};
// SAFETY: a live file handle per the contract; no name, no security attributes; size 0 = the whole file.
let mapping = unsafe { CreateFileMappingW(file, std::ptr::null(), PAGE_READONLY, 0, 0, std::ptr::null()) };
if mapping.is_null() {
return std::ptr::null_mut();
}
// SAFETY: `mapping` was just created; the view keeps the section alive after the handle is closed below.
let view = unsafe { MapViewOfFile(mapping, FILE_MAP_READ, (offset >> 32) as u32, offset as u32, len) };
// SAFETY: closing the handle we created; the view (if any) holds its own reference.
unsafe { windows_sys::Win32::Foundation::CloseHandle(mapping) };
view.Value
}
/// Unmaps a view returned by [`map_file_readonly`] (the `munmap` of the Linux code; the length is not needed).
///
/// # Safety
/// `base` is exactly a pointer returned by [`map_file_readonly`], unmapped once, with no live references into it.
pub unsafe fn unmap_file(base: *mut c_void) -> c_int {
use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, UnmapViewOfFile};
// SAFETY: per the contract.
c_int::from(unsafe { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: base }) } == 0) * -1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn soname_mapping() {
assert_eq!(windows_library_name("libcuda.so.1"), "nvcuda.dll");
assert_eq!(windows_library_name("libnvidia-ml.so.1"), "nvml.dll");
assert_eq!(windows_library_name("libcublasLt.so.12"), "cublasLt64_12.dll");
assert_eq!(windows_library_name("foo.dll"), "foo.dll");
}
#[test]
fn dl_family_round_trip_on_kernel32() {
// SAFETY: static NUL-terminated names; kernel32 is always loaded.
unsafe {
let handle = dlopen(c"kernel32.dll".as_ptr(), RTLD_NOW | RTLD_LOCAL);
assert!(!handle.is_null());
assert!(!dlsym(handle, c"GetTickCount".as_ptr()).is_null());
assert!(dlsym(handle, c"NoSuchSymbolXYZ".as_ptr()).is_null());
assert_eq!(dlclose(handle), 0);
assert!(!dlopen(c"kernel32.dll".as_ptr(), RTLD_NOW | RTLD_NOLOAD).is_null());
assert!(dlopen(c"no-such-library-xyz.dll".as_ptr(), RTLD_NOW).is_null());
}
}
#[test]
fn read_only_file_mapping_round_trip() {
use std::os::windows::io::AsRawHandle;
let path = std::env::temp_dir().join(format!("leleka-shim-map-{}.bin", std::process::id()));
std::fs::write(&path, b"mapped bytes").unwrap();
let file = std::fs::File::open(&path).unwrap();
// SAFETY: a live handle; the view is read once and unmapped before the file goes away.
unsafe {
let base = map_file_readonly(file.as_raw_handle().cast(), 0, 0);
assert!(!base.is_null());
assert_eq!(std::slice::from_raw_parts(base.cast::<u8>(), 12), b"mapped bytes");
assert_eq!(unmap_file(base), 0);
}
drop(file);
std::fs::remove_file(path).unwrap();
}
#[test]
fn page_size_and_limits() {
assert_eq!(sysconf(_SC_PAGESIZE), 4096);
let mut lim = rlimit { rlim_cur: 0, rlim_max: 0 };
// SAFETY: a writable local.
assert_eq!(unsafe { getrlimit(RLIMIT_MEMLOCK, &mut lim) }, 0);
assert_eq!(lim.rlim_cur, RLIM_INFINITY);
}
}