sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::ffi::c_void;
use std::mem::transmute;
use std::ptr::null;

use super::types::*;

mod gpus;
mod instance;

use self::instance::try_create_instance;

// SAFETY: `Vulkan` is only mutated through `&mut Gpus`, so a shared reference
// cannot call an externally synchronized Vulkan function. Moving it to another
// thread transfers exclusive ownership of the instance and library handle.
unsafe impl Send for Vulkan {}
// SAFETY: See the `Send` impl above; shared access only reads cached GPU data.
unsafe impl Sync for Vulkan {}

pub(crate) struct Vulkan {
    lib_handle: *mut c_void,
    instance: VkInstance,
    destroy_instance: PfnVkDestroyInstance,
    enumerate_physical_devices: PfnVkEnumeratePhysicalDevices,
    get_physical_device_memory_properties: PfnVkGetPhysicalDeviceMemoryProperties,
    get_physical_device_properties_2_khr: PfnVkGetPhysicalDeviceProperties2KHR,
    get_physical_device_memory_properties_2: Option<PfnVkGetPhysicalDeviceMemoryProperties2KHR>,
}

impl Vulkan {
    pub(crate) fn load() -> Option<Self> {
        unsafe {
            let lib_name = c"libvulkan.so.1";
            let lib_handle = libc::dlopen(lib_name.as_ptr(), libc::RTLD_NOW);
            if lib_handle.is_null() {
                sinf_debug!("Failed to load {lib_name:?}");
                return None;
            }

            match Self::load_symbols(lib_handle) {
                Some(ret) => Some(ret),
                None => {
                    libc::dlclose(lib_handle);
                    None
                }
            }
        }
    }

    unsafe fn load_symbols(lib_handle: *mut c_void) -> Option<Self> {
        unsafe {
            let create_instance = load_sym!(lib_handle, c"vkCreateInstance", PfnVkCreateInstance)?;
            let destroy_instance =
                load_sym!(lib_handle, c"vkDestroyInstance", PfnVkDestroyInstance)?;
            let enumerate_physical_devices = load_sym!(
                lib_handle,
                c"vkEnumeratePhysicalDevices",
                PfnVkEnumeratePhysicalDevices,
            )?;
            let get_physical_device_memory_properties = load_sym!(
                lib_handle,
                c"vkGetPhysicalDeviceMemoryProperties",
                PfnVkGetPhysicalDeviceMemoryProperties,
            )?;
            let get_instance_proc_addr = load_sym!(
                lib_handle,
                c"vkGetInstanceProcAddr",
                PfnVkGetInstanceProcAddr
            )?;

            let app_info = VkApplicationInfo {
                s_type: VK_STRUCTURE_TYPE_APPLICATION_INFO,
                p_next: null(),
                p_application_name: null(),
                application_version: 0,
                p_engine_name: null(),
                engine_version: 0,
                api_version: (1 << 22) | (1 << 12), // Vulkan 1.1.
            };

            // This extension must be enabled to query the `PCI` and "used memory" information.
            let mut extensions = vec![
                VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME.as_ptr(),
                VK_EXT_MEMORY_BUDGET_EXTENSION_NAME.as_ptr(),
            ];

            let instance =
                try_create_instance(create_instance, &extensions, &app_info).or_else(|| {
                    // Retry without the "used memory" extension.
                    extensions.pop();
                    try_create_instance(create_instance, &extensions, &app_info)
                })?;

            // Try to get the extension function address.
            let ext_fn_name = c"vkGetPhysicalDeviceProperties2KHR";
            let get_physical_device_properties_2_khr_ptr =
                get_instance_proc_addr(instance, ext_fn_name.as_ptr());

            if get_physical_device_properties_2_khr_ptr.is_null() {
                sinf_debug!("Extension function {ext_fn_name:?} not available");
                destroy_instance(instance, null());
                return None;
            }

            let ext_fn_name = c"vkGetPhysicalDeviceMemoryProperties2KHR";
            let get_physical_device_memory_properties_2 =
                get_instance_proc_addr(instance, ext_fn_name.as_ptr());
            let get_physical_device_memory_properties_2 = if get_physical_device_memory_properties_2
                .is_null()
            {
                None
            } else {
                Some(transmute::<
                    *mut c_void,
                    PfnVkGetPhysicalDeviceMemoryProperties2KHR,
                >(get_physical_device_memory_properties_2))
            };

            Some(Self {
                lib_handle,
                instance,
                destroy_instance,
                enumerate_physical_devices,
                get_physical_device_memory_properties,
                get_physical_device_properties_2_khr: transmute::<
                    *mut c_void,
                    PfnVkGetPhysicalDeviceProperties2KHR,
                >(
                    get_physical_device_properties_2_khr_ptr
                ),
                get_physical_device_memory_properties_2,
            })
        }
    }
}

impl Drop for Vulkan {
    fn drop(&mut self) {
        unsafe {
            // Clean up the Vulkan instance and the loaded library handle.
            (self.destroy_instance)(self.instance, null());
            libc::dlclose(self.lib_handle);
        }
    }
}