blob: 841a02faea9993ecc407b4d119a49f00584944f7 [file] [log] [blame]
/*
*
* Copyright (c) 2014-2018 The Khronos Group Inc.
* Copyright (c) 2014-2018 Valve Corporation
* Copyright (c) 2014-2018 LunarG, Inc.
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Jon Ashburn <jon@lunarg.com>
* Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
* Author: Mark Young <marky@lunarg.com>
* Author: Lenny Komow <lenny@lunarg.com>
*
*/
// This needs to be defined first, or else we'll get redefinitions on NTSTATUS values
#ifdef _WIN32
#define UMDF_USING_NTSTATUS
#include <ntstatus.h>
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#if defined(__APPLE__)
#include <CoreFoundation/CoreFoundation.h>
#include <sys/param.h>
#endif
// Time related functions
#include <time.h>
#include <sys/types.h>
#if defined(_WIN32)
#include "dirent_on_windows.h"
#else // _WIN32
#include <dirent.h>
#endif // _WIN32
#include "vk_loader_platform.h"
#include "loader.h"
#include "gpa_helper.h"
#include "debug_utils.h"
#include "wsi.h"
#include "vulkan/vk_icd.h"
#include "cJSON.h"
#include "murmurhash.h"
#if defined(_WIN32)
#include <Cfgmgr32.h>
#include <initguid.h>
#include <Devpkey.h>
#include <winternl.h>
#include <d3dkmthk.h>
#endif
// This is a CMake generated file with #defines for any functions/includes
// that it found present. This is currently necessary to properly determine
// if secure_getenv or __secure_getenv are present
#if !defined(VULKAN_NON_CMAKE_BUILD)
#include "loader_cmake_config.h"
#endif // !defined(VULKAN_NON_CMAKE_BUILD)
// Generated file containing all the extension data
#include "vk_loader_extensions.c"
// Override layer information
#define VK_OVERRIDE_LAYER_NAME "VK_LAYER_LUNARG_override"
struct loader_struct loader = {0};
// TLS for instance for alloc/free callbacks
THREAD_LOCAL_DECL struct loader_instance *tls_instance;
static size_t loader_platform_combine_path(char *dest, size_t len, ...);
struct loader_phys_dev_per_icd {
uint32_t count;
VkPhysicalDevice *phys_devs;
struct loader_icd_term *this_icd_term;
};
enum loader_debug {
LOADER_INFO_BIT = 0x01,
LOADER_WARN_BIT = 0x02,
LOADER_PERF_BIT = 0x04,
LOADER_ERROR_BIT = 0x08,
LOADER_DEBUG_BIT = 0x10,
};
uint32_t g_loader_debug = 0;
uint32_t g_loader_log_msgs = 0;
enum loader_data_files_type {
LOADER_DATA_FILE_MANIFEST_ICD = 0,
LOADER_DATA_FILE_MANIFEST_LAYER,
LOADER_DATA_FILE_NUM_TYPES // Not a real field, used for possible loop terminator
};
// thread safety lock for accessing global data structures such as "loader"
// all entrypoints on the instance chain need to be locked except GPA
// additionally CreateDevice and DestroyDevice needs to be locked
loader_platform_thread_mutex loader_lock;
loader_platform_thread_mutex loader_json_lock;
LOADER_PLATFORM_THREAD_ONCE_DECLARATION(once_init);
// This loader supports Vulkan API version 1.1
uint32_t loader_major_version = 1;
uint32_t loader_minor_version = 1;
void *loader_instance_heap_alloc(const struct loader_instance *instance, size_t size, VkSystemAllocationScope alloc_scope) {
void *pMemory = NULL;
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
{
#else
if (instance && instance->alloc_callbacks.pfnAllocation) {
// These are internal structures, so it's best to align everything to
// the largest unit size which is the size of a uint64_t.
pMemory = instance->alloc_callbacks.pfnAllocation(instance->alloc_callbacks.pUserData, size, sizeof(uint64_t), alloc_scope);
} else {
#endif
pMemory = malloc(size);
}
return pMemory;
}
void loader_instance_heap_free(const struct loader_instance *instance, void *pMemory) {
if (pMemory != NULL) {
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
{
#else
if (instance && instance->alloc_callbacks.pfnFree) {
instance->alloc_callbacks.pfnFree(instance->alloc_callbacks.pUserData, pMemory);
} else {
#endif
free(pMemory);
}
}
}
void *loader_instance_heap_realloc(const struct loader_instance *instance, void *pMemory, size_t orig_size, size_t size,
VkSystemAllocationScope alloc_scope) {
void *pNewMem = NULL;
if (pMemory == NULL || orig_size == 0) {
pNewMem = loader_instance_heap_alloc(instance, size, alloc_scope);
} else if (size == 0) {
loader_instance_heap_free(instance, pMemory);
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
#else
} else if (instance && instance->alloc_callbacks.pfnReallocation) {
// These are internal structures, so it's best to align everything to
// the largest unit size which is the size of a uint64_t.
pNewMem = instance->alloc_callbacks.pfnReallocation(instance->alloc_callbacks.pUserData, pMemory, size, sizeof(uint64_t),
alloc_scope);
#endif
} else {
pNewMem = realloc(pMemory, size);
}
return pNewMem;
}
void *loader_instance_tls_heap_alloc(size_t size) {
return loader_instance_heap_alloc(tls_instance, size, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
}
void loader_instance_tls_heap_free(void *pMemory) { loader_instance_heap_free(tls_instance, pMemory); }
void *loader_device_heap_alloc(const struct loader_device *device, size_t size, VkSystemAllocationScope alloc_scope) {
void *pMemory = NULL;
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
{
#else
if (device && device->alloc_callbacks.pfnAllocation) {
// These are internal structures, so it's best to align everything to
// the largest unit size which is the size of a uint64_t.
pMemory = device->alloc_callbacks.pfnAllocation(device->alloc_callbacks.pUserData, size, sizeof(uint64_t), alloc_scope);
} else {
#endif
pMemory = malloc(size);
}
return pMemory;
}
void loader_device_heap_free(const struct loader_device *device, void *pMemory) {
if (pMemory != NULL) {
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
{
#else
if (device && device->alloc_callbacks.pfnFree) {
device->alloc_callbacks.pfnFree(device->alloc_callbacks.pUserData, pMemory);
} else {
#endif
free(pMemory);
}
}
}
void *loader_device_heap_realloc(const struct loader_device *device, void *pMemory, size_t orig_size, size_t size,
VkSystemAllocationScope alloc_scope) {
void *pNewMem = NULL;
if (pMemory == NULL || orig_size == 0) {
pNewMem = loader_device_heap_alloc(device, size, alloc_scope);
} else if (size == 0) {
loader_device_heap_free(device, pMemory);
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
#else
} else if (device && device->alloc_callbacks.pfnReallocation) {
// These are internal structures, so it's best to align everything to
// the largest unit size which is the size of a uint64_t.
pNewMem = device->alloc_callbacks.pfnReallocation(device->alloc_callbacks.pUserData, pMemory, size, sizeof(uint64_t),
alloc_scope);
#endif
} else {
pNewMem = realloc(pMemory, size);
}
return pNewMem;
}
// Environment variables
#if defined(__linux__) || defined(__APPLE__)
static inline char *loader_getenv(const char *name, const struct loader_instance *inst) {
// No allocation of memory necessary for Linux, but we should at least touch
// the inst pointer to get rid of compiler warnings.
(void)inst;
return getenv(name);
}
static inline char *loader_secure_getenv(const char *name, const struct loader_instance *inst) {
#if defined(__APPLE__)
// Apple does not appear to have a secure getenv implementation.
// The main difference between secure getenv and getenv is that secure getenv
// returns NULL if the process is being run with elevated privileges by a normal user.
// The idea is to prevent the reading of malicious environment variables by a process
// that can do damage.
// This algorithm is derived from glibc code that sets an internal
// variable (__libc_enable_secure) if the process is running under setuid or setgid.
return geteuid() != getuid() || getegid() != getgid() ? NULL : loader_getenv(name, inst);
#else
// Linux
#ifdef HAVE_SECURE_GETENV
(void)inst;
return secure_getenv(name);
#elif defined(HAVE___SECURE_GETENV)
(void)inst;
return __secure_getenv(name);
#else
#pragma message( \
"Warning: Falling back to non-secure getenv for environmental lookups! Consider" \
" updating to a different libc.")
return loader_getenv(name, inst);
#endif
#endif
}
static inline void loader_free_getenv(char *val, const struct loader_instance *inst) {
// No freeing of memory necessary for Linux, but we should at least touch
// the val and inst pointers to get rid of compiler warnings.
(void)val;
(void)inst;
}
#elif defined(WIN32)
static inline char *loader_getenv(const char *name, const struct loader_instance *inst) {
char *retVal;
DWORD valSize;
valSize = GetEnvironmentVariableA(name, NULL, 0);
// valSize DOES include the null terminator, so for any set variable
// will always be at least 1. If it's 0, the variable wasn't set.
if (valSize == 0) return NULL;
// Allocate the space necessary for the registry entry
if (NULL != inst && NULL != inst->alloc_callbacks.pfnAllocation) {
retVal = (char *)inst->alloc_callbacks.pfnAllocation(inst->alloc_callbacks.pUserData, valSize, sizeof(char *),
VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
} else {
retVal = (char *)malloc(valSize);
}
if (NULL != retVal) {
GetEnvironmentVariableA(name, retVal, valSize);
}
return retVal;
}
static inline char *loader_secure_getenv(const char *name, const struct loader_instance *inst) {
// No secure version for Windows as far as I know
return loader_getenv(name, inst);
}
static inline void loader_free_getenv(char *val, const struct loader_instance *inst) {
if (NULL != inst && NULL != inst->alloc_callbacks.pfnFree) {
inst->alloc_callbacks.pfnFree(inst->alloc_callbacks.pUserData, val);
} else {
free((void *)val);
}
}
#else
static inline char *loader_getenv(const char *name, const struct loader_instance *inst) {
// stub func
(void)inst;
(void)name;
return NULL;
}
static inline void loader_free_getenv(char *val, const struct loader_instance *inst) {
// stub func
(void)val;
(void)inst;
}
#endif
void loader_log(const struct loader_instance *inst, VkFlags msg_type, int32_t msg_code, const char *format, ...) {
char msg[512];
char cmd_line_msg[512];
size_t cmd_line_size = sizeof(cmd_line_msg);
va_list ap;
int ret;
va_start(ap, format);
ret = vsnprintf(msg, sizeof(msg), format, ap);
if ((ret >= (int)sizeof(msg)) || ret < 0) {
msg[sizeof(msg) - 1] = '\0';
}
va_end(ap);
if (inst) {
VkDebugUtilsMessageSeverityFlagBitsEXT severity = 0;
VkDebugUtilsMessageTypeFlagsEXT type;
VkDebugUtilsMessengerCallbackDataEXT callback_data;
VkDebugUtilsObjectNameInfoEXT object_name;
if ((msg_type & LOADER_INFO_BIT) != 0) {
severity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT;
} else if ((msg_type & LOADER_WARN_BIT) != 0) {
severity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
} else if ((msg_type & LOADER_ERROR_BIT) != 0) {
severity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
} else if ((msg_type & LOADER_DEBUG_BIT) != 0) {
severity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT;
}
if ((msg_type & LOADER_PERF_BIT) != 0) {
type = VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
} else {
type = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT;
}
callback_data.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT;
callback_data.pNext = NULL;
callback_data.flags = 0;
callback_data.pMessageIdName = "Loader Message";
callback_data.messageIdNumber = 0;
callback_data.pMessage = msg;
callback_data.queueLabelCount = 0;
callback_data.pQueueLabels = NULL;
callback_data.cmdBufLabelCount = 0;
callback_data.pCmdBufLabels = NULL;
callback_data.objectCount = 1;
callback_data.pObjects = &object_name;
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.pNext = NULL;
object_name.objectType = VK_OBJECT_TYPE_INSTANCE;
object_name.objectHandle = (uint64_t)(uintptr_t)inst;
object_name.pObjectName = NULL;
util_SubmitDebugUtilsMessageEXT(inst, severity, type, &callback_data);
}
if (!(msg_type & g_loader_log_msgs)) {
return;
}
cmd_line_msg[0] = '\0';
cmd_line_size -= 1;
size_t original_size = cmd_line_size;
va_start(ap, format);
if ((msg_type & LOADER_INFO_BIT) != 0) {
strncat(cmd_line_msg, "INFO", cmd_line_size);
cmd_line_size -= 4;
}
if ((msg_type & LOADER_WARN_BIT) != 0) {
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, " | ", cmd_line_size);
cmd_line_size -= 3;
}
strncat(cmd_line_msg, "WARNING", cmd_line_size);
cmd_line_size -= 7;
}
if ((msg_type & LOADER_PERF_BIT) != 0) {
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, " | ", cmd_line_size);
cmd_line_size -= 3;
}
strncat(cmd_line_msg, "PERF", cmd_line_size);
cmd_line_size -= 4;
}
if ((msg_type & LOADER_ERROR_BIT) != 0) {
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, " | ", cmd_line_size);
cmd_line_size -= 3;
}
strncat(cmd_line_msg, "ERROR", cmd_line_size);
cmd_line_size -= 5;
}
if ((msg_type & LOADER_DEBUG_BIT) != 0) {
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, " | ", cmd_line_size);
cmd_line_size -= 3;
}
strncat(cmd_line_msg, "DEBUG", cmd_line_size);
cmd_line_size -= 5;
}
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, ": ", cmd_line_size);
cmd_line_size -= 2;
}
if (0 < cmd_line_size) {
// If the message is too long, trim it down
if (strlen(msg) > cmd_line_size) {
msg[cmd_line_size - 1] = '\0';
}
strncat(cmd_line_msg, msg, cmd_line_size);
} else {
// Shouldn't get here, but check to make sure if we've already overrun
// the string boundary
assert(false);
}
#if defined(WIN32)
OutputDebugString(cmd_line_msg);
OutputDebugString("\n");
#endif
fputs(cmd_line_msg, stderr);
fputc('\n', stderr);
}
VKAPI_ATTR VkResult VKAPI_CALL vkSetInstanceDispatch(VkInstance instance, void *object) {
struct loader_instance *inst = loader_get_instance(instance);
if (!inst) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"vkSetInstanceDispatch: Can not retrieve Instance "
"dispatch table.");
return VK_ERROR_INITIALIZATION_FAILED;
}
loader_set_dispatch(object, inst->disp);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL vkSetDeviceDispatch(VkDevice device, void *object) {
struct loader_device *dev;
struct loader_icd_term *icd_term = loader_get_icd_and_device(device, &dev, NULL);
if (NULL == icd_term) {
return VK_ERROR_INITIALIZATION_FAILED;
}
loader_set_dispatch(object, &dev->loader_dispatch);
return VK_SUCCESS;
}
#if defined(_WIN32)
// Append the JSON path data to the list and allocate/grow the list if it's not large enough.
// Function returns true if filename was appended to reg_data list.
// Caller should free reg_data.
static bool loaderAddJsonEntry(const struct loader_instance *inst,
char **reg_data, // list of JSON files
PDWORD total_size, // size of reg_data
LPCTSTR key_name, // key name - used for debug prints - i.e. VulkanDriverName
DWORD key_type, // key data type
LPSTR json_path, // JSON string to add to the list reg_data
DWORD json_size, // size in bytes of json_path
VkResult *result) {
// Check for and ignore duplicates.
if (*reg_data && strstr(*reg_data, json_path)) {
// Success. The json_path is already in the list.
return true;
}
if (NULL == *reg_data) {
*reg_data = loader_instance_heap_alloc(inst, *total_size, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == *reg_data) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderAddJsonEntry: Failed to allocate space for registry data for key %s", json_path);
*result = VK_ERROR_OUT_OF_HOST_MEMORY;
return false;
}
*reg_data[0] = '\0';
} else if (strlen(*reg_data) + json_size + 1 > *total_size) {
void *new_ptr =
loader_instance_heap_realloc(inst, *reg_data, *total_size, *total_size * 2, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == new_ptr) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderAddJsonEntry: Failed to reallocate space for registry value of size %d for key %s", *total_size * 2,
json_path);
*result = VK_ERROR_OUT_OF_HOST_MEMORY;
return false;
}
*reg_data = new_ptr;
*total_size *= 2;
}
for (char *curr_filename = json_path; curr_filename[0] != '\0'; curr_filename += strlen(curr_filename) + 1) {
if (strlen(*reg_data) == 0) {
(void)snprintf(*reg_data, json_size + 1, "%s", curr_filename);
} else {
(void)snprintf(*reg_data + strlen(*reg_data), json_size + 2, "%c%s", PATH_SEPARATOR, curr_filename);
}
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0, "%s: Located json file \"%s\" from PnP registry: %s", __FUNCTION__,
curr_filename, key_name);
if (key_type == REG_SZ) {
break;
}
}
return true;
}
// Find the list of registry files (names VulkanDriverName/VulkanDriverNameWow) in hkr.
//
// This function looks for filename in given device handle, filename is then added to return list
// function return true if filename was appended to reg_data list
// If error occures result is updated with failure reason
bool loaderGetDeviceRegistryEntry(const struct loader_instance *inst, char **reg_data, PDWORD total_size, DEVINST dev_id, LPCTSTR value_name, VkResult *result)
{
HKEY hkrKey = INVALID_HANDLE_VALUE;
DWORD requiredSize, data_type;
char *manifest_path = NULL;
bool found = false;
if (NULL == total_size || NULL == reg_data) {
*result = VK_ERROR_INITIALIZATION_FAILED;
return false;
}
CONFIGRET status = CM_Open_DevNode_Key(dev_id, KEY_QUERY_VALUE, 0, RegDisposition_OpenExisting, &hkrKey, CM_REGISTRY_SOFTWARE);
if (status != CR_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: Failed to open registry key for DeviceID(%d)", dev_id);
*result = VK_ERROR_INITIALIZATION_FAILED;
return false;
}
// query value
LSTATUS ret = RegQueryValueEx(
hkrKey,
value_name,
NULL,
NULL,
NULL,
&requiredSize);
if (ret != ERROR_SUCCESS) {
if (ret == ERROR_FILE_NOT_FOUND) {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: Device ID(%d) Does not contain a value for \"%s\"", dev_id, value_name);
} else {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: DeviceID(%d) Failed to obtain %s size", dev_id, value_name);
}
goto out;
}
manifest_path = loader_instance_heap_alloc(inst, requiredSize, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (manifest_path == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: Failed to allocate space for DriverName.");
*result = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
ret = RegQueryValueEx(
hkrKey,
value_name,
NULL,
&data_type,
(BYTE *)manifest_path,
&requiredSize
);
if (ret != ERROR_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: DeviceID(%d) Failed to obtain %s", value_name);
*result = VK_ERROR_INITIALIZATION_FAILED;
goto out;
}
if (data_type != REG_SZ && data_type != REG_MULTI_SZ) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: Invalid %s data type. Expected REG_SZ or REG_MULTI_SZ.", value_name);
*result = VK_ERROR_INITIALIZATION_FAILED;
goto out;
}
found = loaderAddJsonEntry(inst, reg_data, total_size, value_name, data_type, manifest_path, requiredSize, result);
out:
if (manifest_path != NULL) {
loader_instance_heap_free(inst, manifest_path);
}
RegCloseKey(hkrKey);
return found;
}
// Find the list of registry files (names VulkanDriverName/VulkanDriverNameWow) in hkr .
//
// This function looks for display devices and childish software components
// for a list of files which are added to a returned list (function return
// value).
// Function return is a string with a ';' separated list of filenames.
// Function return is NULL if no valid name/value pairs are found in the key,
// or the key is not found.
//
// *reg_data contains a string list of filenames as pointer.
// When done using the returned string list, the caller should free the pointer.
VkResult loaderGetDeviceRegistryFiles(const struct loader_instance *inst, char **reg_data, PDWORD reg_data_size, LPCTSTR value_name) {
static const wchar_t *softwareComponentGUID = L"{5c4c3332-344d-483c-8739-259e934c9cc8}";
static const wchar_t *displayGUID = L"{4d36e968-e325-11ce-bfc1-08002be10318}";
const ULONG flags = CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT;
wchar_t childGuid[MAX_GUID_STRING_LEN + 2]; // +2 for brackets {}
ULONG childGuidSize = sizeof(childGuid);
DEVINST devID = 0, childID = 0;
wchar_t *pDeviceNames = NULL;
ULONG deviceNamesSize = 0;
VkResult result = VK_SUCCESS;
bool found = false;
if (NULL == reg_data) {
result = VK_ERROR_INITIALIZATION_FAILED;
return result;
}
// if after obtaining the DeviceNameSize, new device is added start over
do {
CM_Get_Device_ID_List_SizeW(&deviceNamesSize, displayGUID, flags);
if (pDeviceNames != NULL) {
loader_instance_heap_free(inst, pDeviceNames);
}
pDeviceNames = loader_instance_heap_alloc(inst, deviceNamesSize * sizeof(wchar_t), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (pDeviceNames == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: Failed to allocate space for display device names.");
result = VK_ERROR_OUT_OF_HOST_MEMORY;
return result;
}
} while (CM_Get_Device_ID_ListW(displayGUID, pDeviceNames, deviceNamesSize, flags) == CR_BUFFER_SMALL);
if (pDeviceNames) {
for (wchar_t *deviceName = pDeviceNames; *deviceName; deviceName += wcslen(deviceName) + 1) {
CONFIGRET status = CM_Locate_DevNodeW(&devID, deviceName, CM_LOCATE_DEVNODE_NORMAL);
if (CR_SUCCESS != status) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loaderGetDeviceRegistryFiles: failed to open DevNode %s",
deviceName);
continue;
}
ULONG ulStatus, ulProblem;
status = CM_Get_DevNode_Status(&ulStatus, &ulProblem, devID, 0);
if (CR_SUCCESS != status)
{
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loaderGetDeviceRegistryFiles: failed to probe device status %s",
deviceName);
continue;
}
if ((ulStatus & DN_HAS_PROBLEM) && (ulProblem == CM_PROB_NEED_RESTART || ulProblem == DN_NEED_RESTART)) {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: device %s is pending reboot, skipping ...", deviceName);
continue;
}
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0, "loaderGetDeviceRegistryFiles: opening device %s", deviceName);
if (loaderGetDeviceRegistryEntry(inst, reg_data, reg_data_size, devID, value_name, &result)) {
found = true;
continue;
}
else if (result == VK_ERROR_OUT_OF_HOST_MEMORY) {
break;
}
status = CM_Get_Child(&childID, devID, 0);
if (status != CR_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: unable to open child-device error:%d", status);
continue;
}
do {
wchar_t buffer[MAX_DEVICE_ID_LEN];
CM_Get_Device_IDW(childID, buffer, MAX_DEVICE_ID_LEN, 0);
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: Opening child device %d - %s", childID, buffer);
status = CM_Get_DevNode_Registry_PropertyW(childID, CM_DRP_CLASSGUID, NULL, &childGuid, &childGuidSize, 0);
if (status != CR_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: unable to obtain GUID for:%d error:%d", childID, status);
result = VK_ERROR_INITIALIZATION_FAILED;
continue;
}
if (wcscmp(childGuid, softwareComponentGUID) != 0) {
loader_log(inst, VK_DEBUG_REPORT_DEBUG_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: GUID for %d is not SoftwareComponent skipping", childID);
continue;
}
if (loaderGetDeviceRegistryEntry(inst, reg_data, reg_data_size, childID, value_name, &result)) {
found = true;
break; // check next-display-device
}
} while (CM_Get_Sibling(&childID, childID, 0) == CR_SUCCESS);
}
loader_instance_heap_free(inst, pDeviceNames);
}
if (!found && result != VK_ERROR_OUT_OF_HOST_MEMORY) {
result = VK_ERROR_INITIALIZATION_FAILED;
}
return result;
}
static char *loader_get_next_path(char *path);
// Find the list of registry files (names within a key) in key "location".
//
// This function looks in the registry (hive = DEFAULT_VK_REGISTRY_HIVE) key as
// given in "location"
// for a list or name/values which are added to a returned list (function return
// value).
// The DWORD values within the key must be 0 or they are skipped.
// Function return is a string with a ';' separated list of filenames.
// Function return is NULL if no valid name/value pairs are found in the key,
// or the key is not found.
//
// *reg_data contains a string list of filenames as pointer.
// When done using the returned string list, the caller should free the pointer.
VkResult loaderGetRegistryFiles(const struct loader_instance *inst, char *location, bool use_secondary_hive, char **reg_data,
PDWORD reg_data_size) {
LONG rtn_value;
HKEY hive = DEFAULT_VK_REGISTRY_HIVE, key;
DWORD access_flags;
char name[2048];
char *loc = location;
char *next;
DWORD idx;
DWORD name_size = sizeof(name);
DWORD value;
DWORD value_size = sizeof(value);
VkResult result = VK_SUCCESS;
bool found = false;
if (NULL == reg_data) {
result = VK_ERROR_INITIALIZATION_FAILED;
goto out;
}
while (*loc) {
next = loader_get_next_path(loc);
access_flags = KEY_QUERY_VALUE;
rtn_value = RegOpenKeyEx(hive, loc, 0, access_flags, &key);
if (ERROR_SUCCESS == rtn_value) {
idx = 0;
while ((rtn_value = RegEnumValue(key, idx++, name, &name_size, NULL, NULL, (LPBYTE)&value, &value_size)) ==
ERROR_SUCCESS) {
if (value_size == sizeof(value) && value == 0) {
if (NULL == *reg_data) {
*reg_data = loader_instance_heap_alloc(inst, *reg_data_size, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == *reg_data) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetRegistryFiles: Failed to allocate space for registry data for key %s", name);
RegCloseKey(key);
result = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
*reg_data[0] = '\0';
} else if (strlen(*reg_data) + name_size + 1 > *reg_data_size) {
void *new_ptr = loader_instance_heap_realloc(inst, *reg_data, *reg_data_size, *reg_data_size * 2,
VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == new_ptr) {
loader_log(
inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetRegistryFiles: Failed to reallocate space for registry value of size %d for key %s",
*reg_data_size * 2, name);
RegCloseKey(key);
result = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
*reg_data = new_ptr;
*reg_data_size *= 2;
}
loader_log(
inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0, "Located json file \"%s\" from registry \"%s\\%s\"", name,
hive == DEFAULT_VK_REGISTRY_HIVE ? DEFAULT_VK_REGISTRY_HIVE_STR : SECONDARY_VK_REGISTRY_HIVE_STR, location);
if (strlen(*reg_data) == 0) {
// The list is emtpy. Add the first entry.
(void)snprintf(*reg_data, name_size + 1, "%s", name);
found = true;
} else {
// At this point the reg_data variable contains other JSON paths, likely from the PNP/device section
// of the registry that we want to have precendence over this non-device specific section of the registry.
// To make sure we avoid enumerating old JSON files/drivers that might be present in the non-device specific
// area of the registry when a newer device specific JSON file is present, do a check before adding.
// Find the file name, without path, of the JSON file found in the non-device specific registry location.
// If the same JSON file name is already found in the list, don't add it again.
bool foundDuplicate = false;
char *pLastSlashName = strrchr(name, '\\');
if (pLastSlashName != NULL) {
char *foundMatch = strstr(*reg_data, pLastSlashName + 1);
if (foundMatch != NULL) {
foundDuplicate = true;
}
}
if (foundDuplicate == false) {
// Add the new entry to the list.
(void)snprintf(*reg_data + strlen(*reg_data), name_size + 2, "%c%s", PATH_SEPARATOR, name);
found = true;
} else {
loader_log(
inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"Skipping adding of json file \"%s\" from registry \"%s\\%s\" to the list due to duplication", name,
hive == DEFAULT_VK_REGISTRY_HIVE ? DEFAULT_VK_REGISTRY_HIVE_STR : SECONDARY_VK_REGISTRY_HIVE_STR,
location);
}
}
}
name_size = 2048;
}
RegCloseKey(key);
}
// Advance the location - if the next location is in the secondary hive, then reset the locations and advance the hive
if (use_secondary_hive && (hive == DEFAULT_VK_REGISTRY_HIVE) && (*next == '\0')) {
loc = location;
hive = SECONDARY_VK_REGISTRY_HIVE;
} else {
loc = next;
}
}
if (!found && result != VK_ERROR_OUT_OF_HOST_MEMORY) {
result = VK_ERROR_INITIALIZATION_FAILED;
}
out:
return result;
}
#endif // WIN32
// Combine path elements, separating each element with the platform-specific
// directory separator, and save the combined string to a destination buffer,
// not exceeding the given length. Path elements are given as variable args,
// with a NULL element terminating the list.
//
// \returns the total length of the combined string, not including an ASCII
// NUL termination character. This length may exceed the available storage:
// in this case, the written string will be truncated to avoid a buffer
// overrun, and the return value will greater than or equal to the storage
// size. A NULL argument may be provided as the destination buffer in order
// to determine the required string length without actually writing a string.
static size_t loader_platform_combine_path(char *dest, size_t len, ...) {
size_t required_len = 0;
va_list ap;
const char *component;
va_start(ap, len);
while ((component = va_arg(ap, const char *))) {
if (required_len > 0) {
// This path element is not the first non-empty element; prepend
// a directory separator if space allows
if (dest && required_len + 1 < len) {
(void)snprintf(dest + required_len, len - required_len, "%c", DIRECTORY_SYMBOL);
}
required_len++;
}
if (dest && required_len < len) {
strncpy(dest + required_len, component, len - required_len);
}
required_len += strlen(component);
}
va_end(ap);
// strncpy(3) won't add a NUL terminating byte in the event of truncation.
if (dest && required_len >= len) {
dest[len - 1] = '\0';
}
return required_len;
}
// Given string of three part form "maj.min.pat" convert to a vulkan version number.
static uint32_t loader_make_version(char *vers_str) {
uint32_t vers = 0, major = 0, minor = 0, patch = 0;
char *vers_tok;
if (!vers_str) {
return vers;
}
vers_tok = strtok(vers_str, ".\"\n\r");
if (NULL != vers_tok) {
major = (uint16_t)atoi(vers_tok);
vers_tok = strtok(NULL, ".\"\n\r");
if (NULL != vers_tok) {
minor = (uint16_t)atoi(vers_tok);
vers_tok = strtok(NULL, ".\"\n\r");
if (NULL != vers_tok) {
patch = (uint16_t)atoi(vers_tok);
}
}
}
return VK_MAKE_VERSION(major, minor, patch);
}
bool compare_vk_extension_properties(const VkExtensionProperties *op1, const VkExtensionProperties *op2) {
return strcmp(op1->extensionName, op2->extensionName) == 0 ? true : false;
}
// Search the given ext_array for an extension matching the given vk_ext_prop
bool has_vk_extension_property_array(const VkExtensionProperties *vk_ext_prop, const uint32_t count,
const VkExtensionProperties *ext_array) {
for (uint32_t i = 0; i < count; i++) {
if (compare_vk_extension_properties(vk_ext_prop, &ext_array[i])) return true;
}
return false;
}
// Search the given ext_list for an extension matching the given vk_ext_prop
bool has_vk_extension_property(const VkExtensionProperties *vk_ext_prop, const struct loader_extension_list *ext_list) {
for (uint32_t i = 0; i < ext_list->count; i++) {
if (compare_vk_extension_properties(&ext_list->list[i], vk_ext_prop)) return true;
}
return false;
}
// Search the given ext_list for a device extension matching the given ext_prop
bool has_vk_dev_ext_property(const VkExtensionProperties *ext_prop, const struct loader_device_extension_list *ext_list) {
for (uint32_t i = 0; i < ext_list->count; i++) {
if (compare_vk_extension_properties(&ext_list->list[i].props, ext_prop)) return true;
}
return false;
}
// Get the next unused layer property in the list. Init the property to zero.
static struct loader_layer_properties *loaderGetNextLayerPropertySlot(const struct loader_instance *inst,
struct loader_layer_list *layer_list) {
if (layer_list->capacity == 0) {
layer_list->list =
loader_instance_heap_alloc(inst, sizeof(struct loader_layer_properties) * 64, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (layer_list->list == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetNextLayerPropertySlot: Out of memory can "
"not add any layer properties to list");
return NULL;
}
memset(layer_list->list, 0, sizeof(struct loader_layer_properties) * 64);
layer_list->capacity = sizeof(struct loader_layer_properties) * 64;
}
// Ensure enough room to add an entry
if ((layer_list->count + 1) * sizeof(struct loader_layer_properties) > layer_list->capacity) {
void *new_ptr = loader_instance_heap_realloc(inst, layer_list->list, layer_list->capacity, layer_list->capacity * 2,
VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == new_ptr) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loaderGetNextLayerPropertySlot: realloc failed for layer list");
return NULL;
}
layer_list->list = new_ptr;
memset((uint8_t *)layer_list->list + layer_list->capacity, 0, layer_list->capacity);
layer_list->capacity *= 2;
}
layer_list->count++;
return &(layer_list->list[layer_list->count - 1]);
}
// Search the given layer list for a layer property matching the given layer name
static struct loader_layer_properties *loaderFindLayerProperty(const char *name, const struct loader_layer_list *layer_list) {
for (uint32_t i = 0; i < layer_list->count; i++) {
const VkLayerProperties *item = &layer_list->list[i].info;
if (strcmp(name, item->layerName) == 0) return &layer_list->list[i];
}
return NULL;
}
// Search the given layer list for a layer matching the given layer name
static bool loaderFindLayerNameInList(const char *name, const struct loader_layer_list *layer_list) {
if (NULL == layer_list) {
return false;
}
if (NULL != loaderFindLayerProperty(name, layer_list)) {
return true;
}
return false;
}
// Search the given meta-layer's component list for a layer matching the given layer name
static bool loaderFindLayerNameInMetaLayer(const struct loader_instance *inst, const char *layer_name,
struct loader_layer_list *layer_list, struct loader_layer_properties *meta_layer_props) {
for (uint32_t comp_layer = 0; comp_layer < meta_layer_props->num_component_layers; comp_layer++) {
if (!strcmp(meta_layer_props->component_layer_names[comp_layer], layer_name)) {
return true;
}
struct loader_layer_properties *comp_layer_props =
loaderFindLayerProperty(meta_layer_props->component_layer_names[comp_layer], layer_list);
if (comp_layer_props->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
return loaderFindLayerNameInMetaLayer(inst, layer_name, layer_list, comp_layer_props);
}
}
return false;
}
// Remove all layer properties entries from the list
void loaderDeleteLayerListAndProperties(const struct loader_instance *inst, struct loader_layer_list *layer_list) {
uint32_t i, j, k;
struct loader_device_extension_list *dev_ext_list;
struct loader_dev_ext_props *ext_props;
if (!layer_list) return;
for (i = 0; i < layer_list->count; i++) {
if (NULL != layer_list->list[i].component_layer_names) {
loader_instance_heap_free(inst, layer_list->list[i].component_layer_names);
layer_list->list[i].component_layer_names = NULL;
}
if (NULL != layer_list->list[i].override_paths) {
loader_instance_heap_free(inst, layer_list->list[i].override_paths);
layer_list->list[i].override_paths = NULL;
}
loader_destroy_generic_list(inst, (struct loader_generic_list *)&layer_list->list[i].instance_extension_list);
dev_ext_list = &layer_list->list[i].device_extension_list;
if (dev_ext_list->capacity > 0 && NULL != dev_ext_list->list) {
for (j = 0; j < dev_ext_list->count; j++) {
ext_props = &dev_ext_list->list[j];
if (ext_props->entrypoint_count > 0) {
for (k = 0; k < ext_props->entrypoint_count; k++) {
loader_instance_heap_free(inst, ext_props->entrypoints[k]);
}
loader_instance_heap_free(inst, ext_props->entrypoints);
}
}
}
loader_destroy_generic_list(inst, (struct loader_generic_list *)dev_ext_list);
}
layer_list->count = 0;
if (layer_list->capacity > 0) {
layer_list->capacity = 0;
loader_instance_heap_free(inst, layer_list->list);
}
}
// Remove all layers in the layer list that are not found inside the override layer.
// NOTE: This should only be called if an override layer is found and not expired.
void loaderRemoveLayersNotInOverride(const struct loader_instance *inst, struct loader_layer_list *layer_list) {
struct loader_layer_properties *override_prop = loaderFindLayerProperty(VK_OVERRIDE_LAYER_NAME, layer_list);
if (NULL == override_prop) {
return;
}
for (int32_t j = 0; j < (int32_t)(layer_list->count); j++) {
struct loader_layer_properties cur_layer_prop = layer_list->list[j];
const char *cur_layer_name = &cur_layer_prop.info.layerName[0];
// Skip the override layer itself.
if (!strcmp(VK_OVERRIDE_LAYER_NAME, cur_layer_name)) {
continue;
}
// If not found in the override layer, remove it
if (!loaderFindLayerNameInMetaLayer(inst, cur_layer_name, layer_list, override_prop)) {
loader_log(inst, VK_DEBUG_REPORT_DEBUG_BIT_EXT, 0,
"loaderRemoveLayersNotInOverride : Override layer is active, and layer %s is not list"
" inside of it. So removing layer from current layer list.",
cur_layer_name);
if (cur_layer_prop.type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
// Delete the component layers
loader_instance_heap_free(inst, cur_layer_prop.component_layer_names);
loader_instance_heap_free(inst, cur_layer_prop.override_paths);
}
// Remove the current invalid meta-layer from the layer list. Use memmove since we are
// overlapping the source and destination addresses.
memmove(&layer_list->list[j], &layer_list->list[j + 1],
sizeof(struct loader_layer_properties) * (layer_list->count - 1 - j));
// Decrement the count (because we now have one less) and decrement the loop index since we need to
// re-check this index.
layer_list->count--;
j--;
// Re-do the query for the override layer
override_prop = loaderFindLayerProperty(VK_OVERRIDE_LAYER_NAME, layer_list);
}
}
}
// Remove all layers in the layer list that are not found inside any implicit meta-layers.
void loaderRemoveLayersNotInImplicitMetaLayers(const struct loader_instance *inst, struct loader_layer_list *layer_list) {
int32_t i;
int32_t j;
int32_t layer_count = (int32_t)(layer_list->count);
for (i = 0; i < layer_count; i++) {
layer_list->list[i].keep = false;
}
for (i = 0; i < layer_count; i++) {
struct loader_layer_properties cur_layer_prop = layer_list->list[i];
if (0 == (cur_layer_prop.type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
cur_layer_prop.keep = true;
} else {
continue;
}
if (cur_layer_prop.type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
for (j = 0; j < layer_count; j++) {
struct loader_layer_properties layer_to_check = layer_list->list[j];
if (i == j) {
continue;
}
// For all layers found in this meta layer, we want to keep them as well.
if (loaderFindLayerNameInMetaLayer(inst, layer_to_check.info.layerName, layer_list, &cur_layer_prop)) {
cur_layer_prop.keep = true;
}
}
}
}
// Remove any layers we don't want to keep (Don't use layer_count here as we need it to be
// dynamically updated if we delete a layer property in the list).
for (i = 0; i < (int32_t)(layer_list->count); i++) {
struct loader_layer_properties cur_layer_prop = layer_list->list[i];
if (!cur_layer_prop.keep) {
loader_log(inst, VK_DEBUG_REPORT_DEBUG_BIT_EXT, 0,
"loaderRemoveLayersNotInOverride : Implicit meta-layers are active, and layer %s is not list"
" inside of any. So removing layer from current layer list.",
cur_layer_prop.info.layerName);
if (cur_layer_prop.type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
// Delete the component layers
loader_instance_heap_free(inst, cur_layer_prop.component_layer_names);
loader_instance_heap_free(inst, cur_layer_prop.override_paths);
}
// Remove the current invalid meta-layer from the layer list. Use memmove since we are
// overlapping the source and destination addresses.
memmove(&layer_list->list[i], &layer_list->list[i + 1],
sizeof(struct loader_layer_properties) * (layer_list->count - 1 - i));
// Decrement the count (because we now have one less) and decrement the loop index since we need to
// re-check this index.
layer_list->count--;
i--;
}
}
}
static VkResult loader_add_instance_extensions(const struct loader_instance *inst,
const PFN_vkEnumerateInstanceExtensionProperties fp_get_props, const char *lib_name,
struct loader_extension_list *ext_list) {
uint32_t i, count = 0;
VkExtensionProperties *ext_props;
VkResult res = VK_SUCCESS;
if (!fp_get_props) {
// No EnumerateInstanceExtensionProperties defined
goto out;
}
res = fp_get_props(NULL, &count, NULL);
if (res != VK_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_add_instance_extensions: Error getting Instance "
"extension count from %s",
lib_name);
goto out;
}
if (count == 0) {
// No ExtensionProperties to report
goto out;
}
ext_props = loader_stack_alloc(count * sizeof(VkExtensionProperties));
if (NULL == ext_props) {
res = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
res = fp_get_props(NULL, &count, ext_props);
if (res != VK_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_add_instance_extensions: Error getting Instance "
"extensions from %s",
lib_name);
goto out;
}
for (i = 0; i < count; i++) {
char spec_version[64];
bool ext_unsupported = wsi_unsupported_instance_extension(&ext_props[i]);
if (!ext_unsupported) {
(void)snprintf(spec_version, sizeof(spec_version), "%d.%d.%d", VK_VERSION_MAJOR(ext_props[i].specVersion),
VK_VERSION_MINOR(ext_props[i].specVersion), VK_VERSION_PATCH(ext_props[i].specVersion));
loader_log(inst, VK_DEBUG_REPORT_DEBUG_BIT_EXT, 0, "Instance Extension: %s (%s) version %s", ext_props[i].extensionName,
lib_name, spec_version);
res = loader_add_to_ext_list(inst, ext_list, 1, &ext_props[i]);
if (res != VK_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_add_instance_extensions: Failed to add %s "
"to Instance extension list",
lib_name);
goto out;
}
}
}
out:
return res;
}
// Initialize ext_list with the physical device extensions.
// The extension properties are passed as inputs in count and ext_props.
static VkResult loader_init_device_extensions(const struct loader_instance *inst, struct loader_physical_device_term *phys_dev_term,
uint32_t count, VkExtensionProperties *ext_props,
struct loader_extension_list *ext_list) {
VkResult res;
uint32_t i;
res = loader_init_generic_list(inst, (struct loader_generic_list *)ext_list, sizeof(VkExtensionProperties));
if (VK_SUCCESS != res) {
return res;
}
for (i = 0; i < count; i++) {
char spec_version[64];
(void)snprintf(spec_version, sizeof(spec_version), "%d.%d.%d", VK_VERSION_MAJOR(ext_props[i].specVersion),
VK_VERSION_MINOR(ext_props[i].specVersion), VK_VERSION_PATCH(ext_props[i].specVersion));
loader_log(inst, VK_DEBUG_REPORT_DEBUG_BIT_EXT, 0, "Device Extension: %s (%s) version %s", ext_props[i].extensionName,
phys_dev_term->this_icd_term->scanned_icd->lib_name, spec_version);
res = loader_add_to_ext_list(inst, ext_list, 1, &ext_props[i]);
if (res != VK_SUCCESS) return res;
}
return VK_SUCCESS;
}
VkResult loader_add_device_extensions(const struct loader_instance *inst,
PFN_vkEnumerateDeviceExtensionProperties fpEnumerateDeviceExtensionProperties,
VkPhysicalDevice physical_device, const char *lib_name,
struct loader_extension_list *ext_list) {
uint32_t i, count;
VkResult res;
VkExtensionProperties *ext_props;
res = fpEnumerateDeviceExtensionProperties(physical_device, NULL, &count, NULL);
if (res == VK_SUCCESS && count > 0) {
ext_props = loader_stack_alloc(count * sizeof(VkExtensionProperties));
if (!ext_props) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_add_device_extensions: Failed to allocate space"
" for device extension properties.");
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
res = fpEnumerateDeviceExtensionProperties(physical_device, NULL, &count, ext_props);
if (res != VK_SUCCESS) {
return res;
}
for (i = 0; i < count; i++) {
char spec_version[64];
(void)snprintf(spec_version, sizeof(spec_version), "%d.%d.%d", VK_VERSION_MAJOR(ext_props[i].specVersion),
VK_VERSION_MINOR(ext_props[i].specVersion), VK_VERSION_PATCH(ext_props[i].specVersion));
loader_log(inst, VK_DEBUG_REPORT_DEBUG_BIT_EXT, 0, "Device Extension: %s (%s) version %s", ext_props[i].extensionName,
lib_name, spec_version);
res = loader_add_to_ext_list(inst, ext_list, 1, &ext_props[i]);
if (res != VK_SUCCESS) {
return res;
}
}
} else {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_add_device_extensions: Error getting physical "
"device extension info count from library %s",
lib_name);
return res;
}
return VK_SUCCESS;
}
VkResult loader_init_generic_list(const struct loader_instance *inst, struct loader_generic_list *list_info, size_t element_size) {
size_t capacity = 32 * element_size;
list_info->count = 0;
list_info->capacity = 0;
list_info->list = loader_instance_heap_alloc(inst, capacity, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (list_info->list == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_init_generic_list: Failed to allocate space "
"for generic list");
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
memset(list_info->list, 0, capacity);
list_info->capacity = capacity;
return VK_SUCCESS;
}
void loader_destroy_generic_list(const struct loader_instance *inst, struct loader_generic_list *list) {
loader_instance_heap_free(inst, list->list);
list->count = 0;
list->capacity = 0;
}
// Append non-duplicate extension properties defined in props to the given ext_list.
// Return - Vk_SUCCESS on success
VkResult loader_add_to_ext_list(const struct loader_instance *inst, struct loader_extension_list *ext_list,
uint32_t prop_list_count, const VkExtensionProperties *props) {
uint32_t i;
const VkExtensionProperties *cur_ext;
if (ext_list->list == NULL || ext_list->capacity == 0) {
VkResult res = loader_init_generic_list(inst, (struct loader_generic_list *)ext_list, sizeof(VkExtensionProperties));
if (VK_SUCCESS != res) {
return res;
}
}
for (i = 0; i < prop_list_count; i++) {
cur_ext = &props[i];
// look for duplicates
if (has_vk_extension_property(cur_ext, ext_list)) {
continue;
}
// add to list at end
// check for enough capacity
if (ext_list->count * sizeof(VkExtensionProperties) >= ext_list->capacity) {
void *new_ptr = loader_instance_heap_realloc(inst, ext_list->list, ext_list->capacity, ext_list->capacity * 2,
VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (new_ptr == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_add_to_ext_list: Failed to reallocate "
"space for extension list");
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
ext_list->list = new_ptr;
// double capacity
ext_list->capacity *= 2;
}
memcpy(&ext_list->list[ext_list->count], cur_ext, sizeof(VkExtensionProperties));
ext_list->count++;
}
return VK_SUCCESS;
}
// Append one extension property defined in props with entrypoints defined in entries to the given
// ext_list. Do not append if a duplicate.
// Return - Vk_SUCCESS on success
VkResult loader_add_to_dev_ext_list(const struct loader_instance *inst, struct loader_device_extension_list *ext_list,
const VkExtensionProperties *props, uint32_t entry_count, char **entrys) {
uint32_t idx;
if (ext_list->list == NULL || ext_list->capacity == 0) {
VkResult res = loader_init_generic_list(inst, (struct loader_generic_list *)ext_list, sizeof(struct loader_dev_ext_props));
if (VK_SUCCESS != res) {
return res;
}
}
// look for duplicates
if (has_vk_dev_ext_property(props, ext_list)) {
return VK_SUCCESS;
}
idx = ext_list->count;
// add to list at end
// check for enough capacity
if (idx * sizeof(struct loader_dev_ext_props) >= ext_list->capacity) {
void *new_ptr = loader_instance_heap_realloc(inst, ext_list->list, ext_list->capacity, ext_list->capacity * 2,
VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == new_ptr) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_add_to_dev_ext_list: Failed to reallocate space for device extension list");
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
ext_list->list = new_ptr;
// double capacity
ext_list->capacity *= 2;
}
memcpy(&ext_list->list[idx].props, props, sizeof(*props));
ext_list->list[idx].entrypoint_count = entry_count;
if (entry_count == 0) {
ext_list->list[idx].entrypoints = NULL;
} else {
ext_list->list[idx].entrypoints =
loader_instance_heap_alloc(inst, sizeof(char *) * entry_count, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (ext_list->list[idx].entrypoints == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_add_to_dev_ext_list: Failed to allocate space "
"for device extension entrypoint list in list %d",
idx);
ext_list->list[idx].entrypoint_count = 0;
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
for (uint32_t i = 0; i < entry_count; i++) {
ext_list->list[idx].entrypoints[i] =
loader_instance_heap_alloc(inst, strlen(entrys[i]) + 1, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (ext_list->list[idx].entrypoints[i] == NULL) {
for (uint32_t j = 0; j < i; j++) {
loader_instance_heap_free(inst, ext_list->list[idx].entrypoints[j]);
}
loader_instance_heap_free(inst, ext_list->list[idx].entrypoints);
ext_list->list[idx].entrypoint_count = 0;
ext_list->list[idx].entrypoints = NULL;
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_add_to_dev_ext_list: Failed to allocate space "
"for device extension entrypoint %d name",
i);
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
strcpy(ext_list->list[idx].entrypoints[i], entrys[i]);
}
}
ext_list->count++;
return VK_SUCCESS;
}
// Prototypes needed.
bool loaderAddMetaLayer(const struct loader_instance *inst, const struct loader_layer_properties *prop,
struct loader_layer_list *target_list, struct loader_layer_list *expanded_target_list,
const struct loader_layer_list *source_list);
// Manage lists of VkLayerProperties
static bool loaderInitLayerList(const struct loader_instance *inst, struct loader_layer_list *list) {
list->capacity = 32 * sizeof(struct loader_layer_properties);
list->list = loader_instance_heap_alloc(inst, list->capacity, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (list->list == NULL) {
return false;
}
memset(list->list, 0, list->capacity);
list->count = 0;
return true;
}
// Search the given layer list for a list matching the given VkLayerProperties
bool loaderListHasLayerProperty(const VkLayerProperties *vk_layer_prop, const struct loader_layer_list *list) {
for (uint32_t i = 0; i < list->count; i++) {
if (strcmp(vk_layer_prop->layerName, list->list[i].info.layerName) == 0) return true;
}
return false;
}
void loaderDestroyLayerList(const struct loader_instance *inst, struct loader_device *device,
struct loader_layer_list *layer_list) {
if (device) {
loader_device_heap_free(device, layer_list->list);
} else {
loader_instance_heap_free(inst, layer_list->list);
}
layer_list->count = 0;
layer_list->capacity = 0;
}
// Append non-duplicate layer properties defined in prop_list to the given layer_info list
VkResult loaderAddLayerPropertiesToList(const struct loader_instance *inst, struct loader_layer_list *list,
uint32_t prop_list_count, const struct loader_layer_properties *props) {
uint32_t i;
struct loader_layer_properties *layer;
if (list->list == NULL || list->capacity == 0) {
loaderInitLayerList(inst, list);
}
if (list->list == NULL) return VK_SUCCESS;
for (i = 0; i < prop_list_count; i++) {
layer = (struct loader_layer_properties *)&props[i];
// Look for duplicates, and skip
if (loaderListHasLayerProperty(&layer->info, list)) {
continue;
}
// Check for enough capacity
if (((list->count + 1) * sizeof(struct loader_layer_properties)) >= list->capacity) {
size_t new_capacity = list->capacity * 2;
void *new_ptr =
loader_instance_heap_realloc(inst, list->list, list->capacity, new_capacity, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == new_ptr) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderAddLayerPropertiesToList: Realloc failed for when attempting to add new layer");
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
list->list = new_ptr;
list->capacity = new_capacity;
}
memcpy(&list->list[list->count], layer, sizeof(struct loader_layer_properties));
list->count++;
}
return VK_SUCCESS;
}
// Search the given search_list for any layers in the props list. Add these to the
// output layer_list. Don't add duplicates to the output layer_list.
static VkResult loaderAddLayerNamesToList(const struct loader_instance *inst, struct loader_layer_list *output_list,
struct loader_layer_list *expanded_output_list, uint32_t name_count,
const char *const *names, const struct loader_layer_list *source_list) {
struct loader_layer_properties *layer_prop;
VkResult err = VK_SUCCESS;
for (uint32_t i = 0; i < name_count; i++) {
const char *source_name = names[i];
layer_prop = loaderFindLayerProperty(source_name, source_list);
if (NULL == layer_prop) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loaderAddLayerNamesToList: Unable to find layer %s", source_name);
err = VK_ERROR_LAYER_NOT_PRESENT;
continue;
}
// If not a meta-layer, simply add it.
if (0 == (layer_prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER)) {
if (!loaderListHasLayerProperty(&layer_prop->info, output_list)) {
loaderAddLayerPropertiesToList(inst, output_list, 1, layer_prop);
}
if (!loaderListHasLayerProperty(&layer_prop->info, expanded_output_list)) {
loaderAddLayerPropertiesToList(inst, expanded_output_list, 1, layer_prop);
}
} else {
if (!loaderListHasLayerProperty(&layer_prop->info, output_list) ||
!loaderListHasLayerProperty(&layer_prop->info, expanded_output_list)) {
loaderAddMetaLayer(inst, layer_prop, output_list, expanded_output_list, source_list);
}
}
}
return err;
}
static bool checkExpiration(const struct loader_instance *inst, const struct loader_layer_properties *prop) {
time_t current = time(NULL);
struct tm tm_current = *localtime(&current);
struct tm tm_expiration = {
.tm_sec = 0,
.tm_min = prop->expiration.minute,
.tm_hour = prop->expiration.hour,
.tm_mday = prop->expiration.day,
.tm_mon = prop->expiration.month - 1,
.tm_year = prop->expiration.year - 1900,
.tm_isdst = tm_current.tm_isdst,
// wday and yday are ignored by mktime
};
time_t expiration = mktime(&tm_expiration);
return current < expiration;
}
// Determine if the provided implicit layer should be enabled by querying the appropriate environmental variables.
// For an implicit layer, at least a disable environment variable is required.
bool loaderImplicitLayerIsEnabled(const struct loader_instance *inst, const struct loader_layer_properties *prop) {
bool enable = false;
char *env_value = NULL;
// If no enable_environment variable is specified, this implicit layer is always be enabled by default.
if (prop->enable_env_var.name[0] == 0) {
enable = true;
} else {
// Otherwise, only enable this layer if the enable environment variable is defined
env_value = loader_secure_getenv(prop->enable_env_var.name, inst);
if (env_value && !strcmp(prop->enable_env_var.value, env_value)) {
enable = true;
}
loader_free_getenv(env_value, inst);
}
// The disable_environment has priority over everything else. If it is defined, the layer is always
// disabled.
env_value = loader_secure_getenv(prop->disable_env_var.name, inst);
if (env_value) {
enable = false;
}
loader_free_getenv(env_value, inst);
// If this layer has an expiration, check it to determine if this layer has expired.
if (prop->has_expiration) {
enable = checkExpiration(inst, prop);
}
return enable;
}
// Check the individual implicit layer for the enable/disable environment variable settings. Only add it after
// every check has passed indicating it should be used.
static void loaderAddImplicitLayer(const struct loader_instance *inst, const struct loader_layer_properties *prop,
struct loader_layer_list *target_list, struct loader_layer_list *expanded_target_list,
const struct loader_layer_list *source_list) {
bool enable = loaderImplicitLayerIsEnabled(inst, prop);
// If the implicit layer is supposed to be enable, make sure the layer supports at least the same API version
// that the application is asking (i.e. layer's API >= app's API). If it's not, disable this layer.
if (enable) {
uint16_t layer_api_major_version = VK_VERSION_MAJOR(prop->info.specVersion);
uint16_t layer_api_minor_version = VK_VERSION_MINOR(prop->info.specVersion);
if (inst->app_api_major_version > layer_api_major_version ||
(inst->app_api_major_version == layer_api_major_version && inst->app_api_minor_version > layer_api_minor_version)) {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loader_add_implicit_layer: Disabling implicit layer %s for using an old API version %d.%d versus "
"application requested %d.%d",
prop->info.layerName, layer_api_major_version, layer_api_minor_version, inst->app_api_major_version,
inst->app_api_minor_version);
enable = false;
}
}
if (enable) {
if (0 == (prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER)) {
if (!loaderListHasLayerProperty(&prop->info, target_list)) {
loaderAddLayerPropertiesToList(inst, target_list, 1, prop);
}
if (NULL != expanded_target_list && !loaderListHasLayerProperty(&prop->info, expanded_target_list)) {
loaderAddLayerPropertiesToList(inst, expanded_target_list, 1, prop);
}
} else {
if (!loaderListHasLayerProperty(&prop->info, target_list) ||
(NULL != expanded_target_list && !loaderListHasLayerProperty(&prop->info, expanded_target_list))) {
loaderAddMetaLayer(inst, prop, target_list, expanded_target_list, source_list);
}
}
}
}
// Add the component layers of a meta-layer to the active list of layers
bool loaderAddMetaLayer(const struct loader_instance *inst, const struct loader_layer_properties *prop,
struct loader_layer_list *target_list, struct loader_layer_list *expanded_target_list,
const struct loader_layer_list *source_list) {
bool found = true;
// If the meta-layer isn't present in the unexpanded list, add it.
if (!loaderListHasLayerProperty(&prop->info, target_list)) {
loaderAddLayerPropertiesToList(inst, target_list, 1, prop);
}
// We need to add all the individual component layers
for (uint32_t comp_layer = 0; comp_layer < prop->num_component_layers; comp_layer++) {
bool found_comp = false;
const struct loader_layer_properties *search_prop =
loaderFindLayerProperty(prop->component_layer_names[comp_layer], source_list);
if (search_prop != NULL) {
found_comp = true;
// If the component layer is itself an implicit layer, we need to do the implicit layer enable
// checks
if (0 == (search_prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
loaderAddImplicitLayer(inst, search_prop, target_list, expanded_target_list, source_list);
} else {
if (0 != (search_prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER)) {
found = loaderAddMetaLayer(inst, search_prop, target_list, expanded_target_list, source_list);
} else {
// Otherwise, just make sure it hasn't already been added to either list before we add it
if (!loaderListHasLayerProperty(&search_prop->info, target_list)) {
loaderAddLayerPropertiesToList(inst, target_list, 1, search_prop);
}
if (NULL != expanded_target_list && !loaderListHasLayerProperty(&search_prop->info, expanded_target_list)) {
loaderAddLayerPropertiesToList(inst, expanded_target_list, 1, search_prop);
}
}
}
}
if (!found_comp) {
loader_log(inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0,
"loaderAddMetaLayer: Failed to find layer name %s component layer "
"%s to activate",
search_prop->info.layerName, prop->component_layer_names[comp_layer]);
found = false;
}
}
// Add this layer to the overall target list (not the expanded one)
if (found && !loaderListHasLayerProperty(&prop->info, target_list)) {
loaderAddLayerPropertiesToList(inst, target_list, 1, prop);
}
return found;
}
// Search the source_list for any layer with a name that matches the given name and a type
// that matches the given type. Add all matching layers to the target_list.
// Do not add if found loader_layer_properties is already on the target_list.
void loaderAddLayerNameToList(const struct loader_instance *inst, const char *name, const enum layer_type_flags type_flags,
const struct loader_layer_list *source_list, struct loader_layer_list *target_list,
struct loader_layer_list *expanded_target_list) {
bool found = false;
for (uint32_t i = 0; i < source_list->count; i++) {
struct loader_layer_properties *source_prop = &source_list->list[i];
if (0 == strcmp(source_prop->info.layerName, name) && (source_prop->type_flags & type_flags) == type_flags) {
// If not a meta-layer, simply add it.
if (0 == (source_prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER)) {
if (!loaderListHasLayerProperty(&source_prop->info, target_list) &&
VK_SUCCESS == loaderAddLayerPropertiesToList(inst, target_list, 1, source_prop)) {
found = true;
}
if (!loaderListHasLayerProperty(&source_prop->info, expanded_target_list) &&
VK_SUCCESS == loaderAddLayerPropertiesToList(inst, expanded_target_list, 1, source_prop)) {
found = true;
}
} else {
found = loaderAddMetaLayer(inst, source_prop, target_list, expanded_target_list, source_list);
}
}
}
if (!found) {
loader_log(inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0, "loaderAddLayerNameToList: Failed to find layer name %s to activate",
name);
}
}
static VkExtensionProperties *get_extension_property(const char *name, const struct loader_extension_list *list) {
for (uint32_t i = 0; i < list->count; i++) {
if (strcmp(name, list->list[i].extensionName) == 0) return &list->list[i];
}
return NULL;
}
static VkExtensionProperties *get_dev_extension_property(const char *name, const struct loader_device_extension_list *list) {
for (uint32_t i = 0; i < list->count; i++) {
if (strcmp(name, list->list[i].props.extensionName) == 0) return &list->list[i].props;
}
return NULL;
}
// For Instance extensions implemented within the loader (i.e. DEBUG_REPORT
// the extension must provide two entry points for the loader to use:
// - "trampoline" entry point - this is the address returned by GetProcAddr
// and will always do what's necessary to support a
// global call.
// - "terminator" function - this function will be put at the end of the
// instance chain and will contain the necessary logic
// to call / process the extension for the appropriate
// ICDs that are available.
// There is no generic mechanism for including these functions, the references
// must be placed into the appropriate loader entry points.
// GetInstanceProcAddr: call extension GetInstanceProcAddr to check for GetProcAddr
// requests
// loader_coalesce_extensions(void) - add extension records to the list of global
// extension available to the app.
// instance_disp - add function pointer for terminator function
// to this array.
// The extension itself should be in a separate file that will be linked directly
// with the loader.
VkResult loader_get_icd_loader_instance_extensions(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list,
struct loader_extension_list *inst_exts) {
struct loader_extension_list icd_exts;
VkResult res = VK_SUCCESS;
char *env_value;
bool filter_extensions = true;
loader_log(inst, VK_DEBUG_REPORT_DEBUG_BIT_EXT, 0, "Build ICD instance extension list");
// Check if a user wants to disable the instance extension filtering behavior
env_value = loader_getenv("VK_LOADER_DISABLE_INST_EXT_FILTER", inst);
if (NULL != env_value && atoi(env_value) != 0) {
filter_extensions = false;
}
loader_free_getenv(env_value, inst);
// traverse scanned icd list adding non-duplicate extensions to the list
for (uint32_t i = 0; i < icd_tramp_list->count; i++) {
res = loader_init_generic_list(inst, (struct loader_generic_list *)&icd_exts, sizeof(VkExtensionProperties));
if (VK_SUCCESS != res) {
goto out;
}
res = loader_add_instance_extensions(inst, icd_tramp_list->scanned_list[i].EnumerateInstanceExtensionProperties,
icd_tramp_list->scanned_list[i].lib_name, &icd_exts);
if (VK_SUCCESS == res) {
if (filter_extensions) {
// Remove any extensions not recognized by the loader
for (int32_t j = 0; j < (int32_t)icd_exts.count; j++) {
// See if the extension is in the list of supported extensions
bool found = false;
for (uint32_t k = 0; LOADER_INSTANCE_EXTENSIONS[k] != NULL; k++) {
if (strcmp(icd_exts.list[j].extensionName, LOADER_INSTANCE_EXTENSIONS[k]) == 0) {
found = true;
break;
}
}
// If it isn't in the list, remove it
if (!found) {
for (uint32_t k = j + 1; k < icd_exts.count; k++) {
icd_exts.list[k - 1] = icd_exts.list[k];
}
--icd_exts.count;
--j;
}
}
}
res = loader_add_to_ext_list(inst, inst_exts, icd_exts.count, icd_exts.list);
}
loader_destroy_generic_list(inst, (struct loader_generic_list *)&icd_exts);
if (VK_SUCCESS != res) {
goto out;
}
};
// Traverse loader's extensions, adding non-duplicate extensions to the list
debug_utils_AddInstanceExtensions(inst, inst_exts);
out:
return res;
}
struct loader_icd_term *loader_get_icd_and_device(const VkDevice device, struct loader_device **found_dev, uint32_t *icd_index) {
*found_dev = NULL;
for (struct loader_instance *inst = loader.instances; inst; inst = inst->next) {
uint32_t index = 0;
for (struct loader_icd_term *icd_term = inst->icd_terms; icd_term; icd_term = icd_term->next) {
for (struct loader_device *dev = icd_term->logical_device_list; dev; dev = dev->next)
// Value comparison of device prevents object wrapping by layers
if (loader_get_dispatch(dev->icd_device) == loader_get_dispatch(device) ||
loader_get_dispatch(dev->chain_device) == loader_get_dispatch(device)) {
*found_dev = dev;
if (NULL != icd_index) {
*icd_index = index;
}
return icd_term;
}
index++;
}
}
return NULL;
}
void loader_destroy_logical_device(const struct loader_instance *inst, struct loader_device *dev,
const VkAllocationCallbacks *pAllocator) {
if (pAllocator) {
dev->alloc_callbacks = *pAllocator;
}
if (NULL != dev->expanded_activated_layer_list.list) {
loaderDeactivateLayers(inst, dev, &dev->expanded_activated_layer_list);
}
if (NULL != dev->app_activated_layer_list.list) {
loaderDestroyLayerList(inst, dev, &dev->app_activated_layer_list);
}
loader_device_heap_free(dev, dev);
}
struct loader_device *loader_create_logical_device(const struct loader_instance *inst, const VkAllocationCallbacks *pAllocator) {
struct loader_device *new_dev;
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
{
#else
if (pAllocator) {
new_dev = (struct loader_device *)pAllocator->pfnAllocation(pAllocator->pUserData, sizeof(struct loader_device),
sizeof(int *), VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
} else {
#endif
new_dev = (struct loader_device *)malloc(sizeof(struct loader_device));
}
if (!new_dev) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_create_logical_device: Failed to alloc struct "
"loader_device");
return NULL;
}
memset(new_dev, 0, sizeof(struct loader_device));
if (pAllocator) {
new_dev->alloc_callbacks = *pAllocator;
}
return new_dev;
}
void loader_add_logical_device(const struct loader_instance *inst, struct loader_icd_term *icd_term, struct loader_device *dev) {
dev->next = icd_term->logical_device_list;
icd_term->logical_device_list = dev;
}
void loader_remove_logical_device(const struct loader_instance *inst, struct loader_icd_term *icd_term,
struct loader_device *found_dev, const VkAllocationCallbacks *pAllocator) {
struct loader_device *dev, *prev_dev;
if (!icd_term || !found_dev) return;
prev_dev = NULL;
dev = icd_term->logical_device_list;
while (dev && dev != found_dev) {
prev_dev = dev;
dev = dev->next;
}
if (prev_dev)
prev_dev->next = found_dev->next;
else
icd_term->logical_device_list = found_dev->next;
loader_destroy_logical_device(inst, found_dev, pAllocator);
}
static void loader_icd_destroy(struct loader_instance *ptr_inst, struct loader_icd_term *icd_term,
const VkAllocationCallbacks *pAllocator) {
ptr_inst->total_icd_count--;
for (struct loader_device *dev = icd_term->logical_device_list; dev;) {
struct loader_device *next_dev = dev->next;
loader_destroy_logical_device(ptr_inst, dev, pAllocator);
dev = next_dev;
}
loader_instance_heap_free(ptr_inst, icd_term);
}
static struct loader_icd_term *loader_icd_create(const struct loader_instance *inst) {
struct loader_icd_term *icd_term;
icd_term = loader_instance_heap_alloc(inst, sizeof(struct loader_icd_term), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (!icd_term) {
return NULL;
}
memset(icd_term, 0, sizeof(struct loader_icd_term));
return icd_term;
}
static struct loader_icd_term *loader_icd_add(struct loader_instance *ptr_inst, const struct loader_scanned_icd *scanned_icd) {
struct loader_icd_term *icd_term;
icd_term = loader_icd_create(ptr_inst);
if (!icd_term) {
return NULL;
}
icd_term->scanned_icd = scanned_icd;
icd_term->this_instance = ptr_inst;
// Prepend to the list
icd_term->next = ptr_inst->icd_terms;
ptr_inst->icd_terms = icd_term;
ptr_inst->total_icd_count++;
return icd_term;
}
// Determine the ICD interface version to use.
// @param icd
// @param pVersion Output parameter indicating which version to use or 0 if
// the negotiation API is not supported by the ICD
// @return bool indicating true if the selected interface version is supported
// by the loader, false indicates the version is not supported
bool loader_get_icd_interface_version(PFN_vkNegotiateLoaderICDInterfaceVersion fp_negotiate_icd_version, uint32_t *pVersion) {
if (fp_negotiate_icd_version == NULL) {
// ICD does not support the negotiation API, it supports version 0 or 1
// calling code must determine if it is version 0 or 1
*pVersion = 0;
} else {
// ICD supports the negotiation API, so call it with the loader's
// latest version supported
*pVersion = CURRENT_LOADER_ICD_INTERFACE_VERSION;
VkResult result = fp_negotiate_icd_version(pVersion);
if (result == VK_ERROR_INCOMPATIBLE_DRIVER) {
// ICD no longer supports the loader's latest interface version so
// fail loading the ICD
return false;
}
}
#if MIN_SUPPORTED_LOADER_ICD_INTERFACE_VERSION > 0
if (*pVersion < MIN_SUPPORTED_LOADER_ICD_INTERFACE_VERSION) {
// Loader no longer supports the ICD's latest interface version so fail
// loading the ICD
return false;
}
#endif
return true;
}
void loader_scanned_icd_clear(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list) {
if (0 != icd_tramp_list->capacity) {
for (uint32_t i = 0; i < icd_tramp_list->count; i++) {
loader_platform_close_library(icd_tramp_list->scanned_list[i].handle);
loader_instance_heap_free(inst, icd_tramp_list->scanned_list[i].lib_name);
}
loader_instance_heap_free(inst, icd_tramp_list->scanned_list);
icd_tramp_list->capacity = 0;
icd_tramp_list->count = 0;
icd_tramp_list->scanned_list = NULL;
}
}
static VkResult loader_scanned_icd_init(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list) {
VkResult err = VK_SUCCESS;
loader_scanned_icd_clear(inst, icd_tramp_list);
icd_tramp_list->capacity = 8 * sizeof(struct loader_scanned_icd);
icd_tramp_list->scanned_list = loader_instance_heap_alloc(inst, icd_tramp_list->capacity, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == icd_tramp_list->scanned_list) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_scanned_icd_init: Realloc failed for layer list when "
"attempting to add new layer");
err = VK_ERROR_OUT_OF_HOST_MEMORY;
}
return err;
}
static VkResult loader_scanned_icd_add(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list,
const char *filename, uint32_t api_version) {
loader_platform_dl_handle handle;
PFN_vkCreateInstance fp_create_inst;
PFN_vkEnumerateInstanceExtensionProperties fp_get_inst_ext_props;
PFN_vkGetInstanceProcAddr fp_get_proc_addr;
PFN_GetPhysicalDeviceProcAddr fp_get_phys_dev_proc_addr = NULL;
PFN_vkNegotiateLoaderICDInterfaceVersion fp_negotiate_icd_version;
struct loader_scanned_icd *new_scanned_icd;
uint32_t interface_vers;
VkResult res = VK_SUCCESS;
// TODO implement smarter opening/closing of libraries. For now this
// function leaves libraries open and the scanned_icd_clear closes them
handle = loader_platform_open_library(filename);
if (NULL == handle) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, loader_platform_open_library_error(filename));
goto out;
}
// Get and settle on an ICD interface version
fp_negotiate_icd_version = loader_platform_get_proc_address(handle, "vk_icdNegotiateLoaderICDInterfaceVersion");
if (!loader_get_icd_interface_version(fp_negotiate_icd_version, &interface_vers)) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_scanned_icd_add: ICD %s doesn't support interface"
" version compatible with loader, skip this ICD.",
filename);
goto out;
}
fp_get_proc_addr = loader_platform_get_proc_address(handle, "vk_icdGetInstanceProcAddr");
if (NULL == fp_get_proc_addr) {
assert(interface_vers == 0);
// Use deprecated interface from version 0
fp_get_proc_addr = loader_platform_get_proc_address(handle, "vkGetInstanceProcAddr");
if (NULL == fp_get_proc_addr) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_scanned_icd_add: Attempt to retrieve either "
"\'vkGetInstanceProcAddr\' or "
"\'vk_icdGetInstanceProcAddr\' from ICD %s failed.",
filename);
goto out;
} else {
loader_log(inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0,
"loader_scanned_icd_add: Using deprecated ICD "
"interface of \'vkGetInstanceProcAddr\' instead of "
"\'vk_icdGetInstanceProcAddr\' for ICD %s",
filename);
}
fp_create_inst = loader_platform_get_proc_address(handle, "vkCreateInstance");
if (NULL == fp_create_inst) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_scanned_icd_add: Failed querying "
"\'vkCreateInstance\' via dlsym/loadlibrary for "
"ICD %s",
filename);
goto out;
}
fp_get_inst_ext_props = loader_platform_get_proc_address(handle, "vkEnumerateInstanceExtensionProperties");
if (NULL == fp_get_inst_ext_props) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_scanned_icd_add: Could not get \'vkEnumerate"
"InstanceExtensionProperties\' via dlsym/loadlibrary "
"for ICD %s",
filename);
goto out;
}
} else {
// Use newer interface version 1 or later
if (interface_vers == 0) {
interface_vers = 1;
}
fp_create_inst = (PFN_vkCreateInstance)fp_get_proc_addr(NULL, "vkCreateInstance");
if (NULL == fp_create_inst) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_scanned_icd_add: Could not get "
"\'vkCreateInstance\' via \'vk_icdGetInstanceProcAddr\'"
" for ICD %s",
filename);
goto out;
}
fp_get_inst_ext_props =
(PFN_vkEnumerateInstanceExtensionProperties)fp_get_proc_addr(NULL, "vkEnumerateInstanceExtensionProperties");
if (NULL == fp_get_inst_ext_props) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_scanned_icd_add: Could not get \'vkEnumerate"
"InstanceExtensionProperties\' via "
"\'vk_icdGetInstanceProcAddr\' for ICD %s",
filename);
goto out;
}
fp_get_phys_dev_proc_addr = loader_platform_get_proc_address(handle, "vk_icdGetPhysicalDeviceProcAddr");
}
// check for enough capacity
if ((icd_tramp_list->count * sizeof(struct loader_scanned_icd)) >= icd_tramp_list->capacity) {
void *new_ptr = loader_instance_heap_realloc(inst, icd_tramp_list->scanned_list, icd_tramp_list->capacity,
icd_tramp_list->capacity * 2, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == new_ptr) {
res = VK_ERROR_OUT_OF_HOST_MEMORY;
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_scanned_icd_add: Realloc failed on icd library list for ICD %s", filename);
goto out;
}
icd_tramp_list->scanned_list = new_ptr;
// double capacity
icd_tramp_list->capacity *= 2;
}
new_scanned_icd = &(icd_tramp_list->scanned_list[icd_tramp_list->count]);
new_scanned_icd->handle = handle;
new_scanned_icd->api_version = api_version;
new_scanned_icd->GetInstanceProcAddr = fp_get_proc_addr;
new_scanned_icd->GetPhysicalDeviceProcAddr = fp_get_phys_dev_proc_addr;
new_scanned_icd->EnumerateInstanceExtensionProperties = fp_get_inst_ext_props;
new_scanned_icd->CreateInstance = fp_create_inst;
new_scanned_icd->interface_version = interface_vers;
new_scanned_icd->lib_name = (char *)loader_instance_heap_alloc(inst, strlen(filename) + 1, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == new_scanned_icd->lib_name) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loader_scanned_icd_add: Out of memory can't add ICD %s", filename);
res = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
strcpy(new_scanned_icd->lib_name, filename);
icd_tramp_list->count++;
out:
return res;
}
static void loader_debug_init(void) {
char *env, *orig;
if (g_loader_debug > 0) return;
g_loader_debug = 0;
// Parse comma-separated debug options
orig = env = loader_getenv("VK_LOADER_DEBUG", NULL);
while (env) {
char *p = strchr(env, ',');
size_t len;
if (p)
len = p - env;
else
len = strlen(env);
if (len > 0) {
if (strncmp(env, "all", len) == 0) {
g_loader_debug = ~0u;
g_loader_log_msgs = ~0u;
} else if (strncmp(env, "warn", len) == 0) {
g_loader_debug |= LOADER_WARN_BIT;
g_loader_log_msgs |= VK_DEBUG_REPORT_WARNING_BIT_EXT;
} else if (strncmp(env, "info", len) == 0) {
g_loader_debug |= LOADER_INFO_BIT;
g_loader_log_msgs |= VK_DEBUG_REPORT_INFORMATION_BIT_EXT;
} else if (strncmp(env, "perf", len) == 0) {
g_loader_debug |= LOADER_PERF_BIT;
g_loader_log_msgs |= VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
} else if (strncmp(env, "error", len) == 0) {
g_loader_debug |= LOADER_ERROR_BIT;
g_loader_log_msgs |= VK_DEBUG_REPORT_ERROR_BIT_EXT;
} else if (strncmp(env, "debug", len) == 0) {
g_loader_debug |= LOADER_DEBUG_BIT;
g_loader_log_msgs |= VK_DEBUG_REPORT_DEBUG_BIT_EXT;
}
}
if (!p) break;
env = p + 1;
}
loader_free_getenv(orig, NULL);
}
void loader_initialize(void) {
// initialize mutexs
loader_platform_thread_create_mutex(&loader_lock);
loader_platform_thread_create_mutex(&loader_json_lock);
// initialize logging
loader_debug_init();
// initial cJSON to use alloc callbacks
cJSON_Hooks alloc_fns = {
.malloc_fn = loader_instance_tls_heap_alloc, .free_fn = loader_instance_tls_heap_free,
};
cJSON_InitHooks(&alloc_fns);
}
struct loader_data_files {
uint32_t count;
uint32_t alloc_count;
char **filename_list;
};
void loader_release() {
// release mutexs
loader_platform_thread_delete_mutex(&loader_lock);
loader_platform_thread_delete_mutex(&loader_json_lock);
}
// Get next file or dirname given a string list or registry key path
//
// \returns
// A pointer to first char in the next path.
// The next path (or NULL) in the list is returned in next_path.
// Note: input string is modified in some cases. PASS IN A COPY!
static char *loader_get_next_path(char *path) {
uint32_t len;
char *next;
if (path == NULL) return NULL;
next = strchr(path, PATH_SEPARATOR);
if (next == NULL) {
len = (uint32_t)strlen(path);
next = path + len;
} else {
*next = '\0';
next++;
}
return next;
}
// Given a path which is absolute or relative, expand the path if relative or
// leave the path unmodified if absolute. The base path to prepend to relative
// paths is given in rel_base.
//
// @return - A string in out_fullpath of the full absolute path
static void loader_expand_path(const char *path, const char *rel_base, size_t out_size, char *out_fullpath) {
if (loader_platform_is_path_absolute(path)) {
// do not prepend a base to an absolute path
rel_base = "";
}
loader_platform_combine_path(out_fullpath, out_size, rel_base, path, NULL);
}
// Given a filename (file) and a list of paths (dir), try to find an existing
// file in the paths. If filename already is a path then no searching in the given paths.
//
// @return - A string in out_fullpath of either the full path or file.
static void loader_get_fullpath(const char *file, const char *dirs, size_t out_size, char *out_fullpath) {
if (!loader_platform_is_path(file) && *dirs) {
char *dirs_copy, *dir, *next_dir;
dirs_copy = loader_stack_alloc(strlen(dirs) + 1);
strcpy(dirs_copy, dirs);
// find if file exists after prepending paths in given list
for (dir = dirs_copy; *dir && (next_dir = loader_get_next_path(dir)); dir = next_dir) {
loader_platform_combine_path(out_fullpath, out_size, dir, file, NULL);
if (loader_platform_file_exists(out_fullpath)) {
return;
}
}
}
(void)snprintf(out_fullpath, out_size, "%s", file);
}
// Read a JSON file into a buffer.
//
// @return - A pointer to a cJSON object representing the JSON parse tree.
// This returned buffer should be freed by caller.
static VkResult loader_get_json(const struct loader_instance *inst, const char *filename, cJSON **json) {
FILE *file = NULL;
char *json_buf;
size_t len;
VkResult res = VK_SUCCESS;
if (NULL == json) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loader_get_json: Received invalid JSON file");
res = VK_ERROR_INITIALIZATION_FAILED;
goto out;
}
*json = NULL;
file = fopen(filename, "rb");
if (!file) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loader_get_json: Failed to open JSON file %s", filename);
res = VK_ERROR_INITIALIZATION_FAILED;
goto out;
}
fseek(file, 0, SEEK_END);
len = ftell(file);
fseek(file, 0, SEEK_SET);
json_buf = (char *)loader_stack_alloc(len + 1);
if (json_buf == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_get_json: Failed to allocate space for "
"JSON file %s buffer of length %d",
filename, len);
res = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
if (fread(json_buf, sizeof(char), len, file) != len) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loader_get_json: Failed to read JSON file %s.", filename);
res = VK_ERROR_INITIALIZATION_FAILED;
goto out;
}
json_buf[len] = '\0';
// Parse text from file
*json = cJSON_Parse(json_buf);
if (*json == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loader_get_json: Failed to parse JSON file %s, "
"this is usually because something ran out of "
"memory.",
filename);
res = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
out:
if (NULL != file) {
fclose(file);
}
return res;
}
const char *std_validation_str = "VK_LAYER_LUNARG_standard_validation";
// Adds the legacy VK_LAYER_LUNARG_standard_validation as a meta-layer if it
// fails to find it in the list already. This is usually an indication that a
// newer loader is being used with an older layer set.
static bool loaderAddLegacyStandardValidationLayer(const struct loader_instance *inst,
struct loader_layer_list *layer_instance_list) {
uint32_t i;
bool success = true;
struct loader_layer_properties *props = loaderGetNextLayerPropertySlot(inst, layer_instance_list);
const char std_validation_names[6][VK_MAX_EXTENSION_NAME_SIZE] = {
"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", "VK_LAYER_LUNARG_object_tracker",
"VK_LAYER_LUNARG_core_validation", "VK_LAYER_GOOGLE_unique_objects"};
uint32_t layer_count = sizeof(std_validation_names) / sizeof(std_validation_names[0]);
loader_log(inst, VK_DEBUG_REPORT_DEBUG_BIT_EXT, 0,
"Adding VK_LAYER_LUNARG_standard_validation using the loader legacy path. This is"
" not an error.");
if (NULL == props) {
goto out;
}
memset(props, 0, sizeof(struct loader_layer_properties));
props->type_flags = VK_LAYER_TYPE_FLAG_INSTANCE_LAYER | VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER | VK_LAYER_TYPE_FLAG_META_LAYER;
strncpy(props->info.description, "LunarG Standard Validation Layer", sizeof(props->info.description));
props->info.implementationVersion = 1;
strncpy(props->info.layerName, std_validation_str, sizeof(props->info.layerName));
props->info.specVersion = VK_MAKE_VERSION(1, 0, VK_HEADER_VERSION);
props->component_layer_names =
loader_instance_heap_alloc(inst, sizeof(char[MAX_STRING_SIZE]) * layer_count, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == props->component_layer_names) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"Failed to allocate space for legacy VK_LAYER_LUNARG_standard_validation"
" meta-layer component_layers information.");
success = false;
goto out;
}
for (i = 0; i < layer_count; i++) {
strncpy(props->component_layer_names[i], std_validation_names[i], MAX_STRING_SIZE - 1);
props->component_layer_names[i][MAX_STRING_SIZE - 1] = '\0';
}
out:
if (!success && NULL != props && NULL != props->component_layer_names) {
loader_instance_heap_free(inst, props->component_layer_names);
props->component_layer_names = NULL;
}
return success;
}
// Verify that all component layers in a meta-layer are valid.
static bool verifyMetaLayerComponentLayers(const struct loader_instance *inst, struct loader_layer_properties *prop,
struct loader_layer_list *instance_layers) {
bool success = true;
const uint32_t expected_major = VK_VERSION_MAJOR(prop->info.specVersion);
const uint32_t expected_minor = VK_VERSION_MINOR(prop->info.specVersion);
for (uint32_t comp_layer = 0; comp_layer < prop->num_component_layers; comp_layer++) {
if (!loaderFindLayerNameInList(prop->component_layer_names[comp_layer], instance_layers)) {
if (NULL != inst) {
loader_log(inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0,
"verifyMetaLayerComponentLayers: Meta-layer %s can't find component layer %s at index %d."
" Skipping this layer.",
prop->info.layerName, prop->component_layer_names[comp_layer], comp_layer);
}
success = false;
break;
} else {
struct loader_layer_properties *comp_prop =
loaderFindLayerProperty(prop->component_layer_names[comp_layer], instance_layers);
if (comp_prop == NULL) {
if (NULL != inst) {
loader_log(inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0,
"verifyMetaLayerComponentLayers: Meta-layer %s can't find property for component layer "
"%s at index %d. Skipping this layer.",
prop->info.layerName, prop->component_layer_names[comp_layer], comp_layer);
}
success = false;
break;
}
// Check the version of each layer, they need to at least match MAJOR and MINOR
uint32_t cur_major = VK_VERSION_MAJOR(comp_prop->info.specVersion);
uint32_t cur_minor = VK_VERSION_MINOR(comp_prop->info.specVersion);
if (cur_major != expected_major || cur_minor != expected_minor) {
if (NULL != inst) {
loader_log(inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0,
"verifyMetaLayerComponentLayers: Meta-layer uses API version %d.%d, but com