Coverage Report

Created: 2026-01-17 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/vulkan-loader/loader/loader.c
Line
Count
Source
1
/*
2
 *
3
 * Copyright (c) 2014-2023 The Khronos Group Inc.
4
 * Copyright (c) 2014-2023 Valve Corporation
5
 * Copyright (c) 2014-2023 LunarG, Inc.
6
 * Copyright (C) 2015 Google Inc.
7
 * Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
8
 * Copyright (c) 2023-2023 RasterGrid Kft.
9
 *
10
 * Licensed under the Apache License, Version 2.0 (the "License");
11
 * you may not use this file except in compliance with the License.
12
 * You may obtain a copy of the License at
13
 *
14
 *     http://www.apache.org/licenses/LICENSE-2.0
15
 *
16
 * Unless required by applicable law or agreed to in writing, software
17
 * distributed under the License is distributed on an "AS IS" BASIS,
18
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
 * See the License for the specific language governing permissions and
20
 * limitations under the License.
21
22
 *
23
 * Author: Jon Ashburn <jon@lunarg.com>
24
 * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
25
 * Author: Mark Young <marky@lunarg.com>
26
 * Author: Lenny Komow <lenny@lunarg.com>
27
 * Author: Charles Giessen <charles@lunarg.com>
28
 *
29
 */
30
31
#include "loader.h"
32
33
#include <errno.h>
34
#include <inttypes.h>
35
#include <limits.h>
36
#include <stdio.h>
37
#include <stdlib.h>
38
#include <stdarg.h>
39
#include <stdbool.h>
40
#include <string.h>
41
#include <stddef.h>
42
43
#if defined(__APPLE__)
44
#include <CoreFoundation/CoreFoundation.h>
45
#include <sys/param.h>
46
#endif
47
48
#include <sys/types.h>
49
#if defined(_WIN32)
50
#include "dirent_on_windows.h"
51
#elif COMMON_UNIX_PLATFORMS
52
#include <dirent.h>
53
#else
54
#warning dirent.h not available on this platform
55
#endif  // _WIN32
56
57
#include "allocation.h"
58
#include "stack_allocation.h"
59
#include "cJSON.h"
60
#include "debug_utils.h"
61
#include "loader_environment.h"
62
#include "loader_json.h"
63
#include "log.h"
64
#include "unknown_function_handling.h"
65
#include "vk_loader_platform.h"
66
#include "wsi.h"
67
68
#if defined(WIN32)
69
#include "loader_windows.h"
70
#endif
71
#if defined(LOADER_ENABLE_LINUX_SORT)
72
// This header is currently only used when sorting Linux devices, so don't include it otherwise.
73
#include "loader_linux.h"
74
#endif  // LOADER_ENABLE_LINUX_SORT
75
76
// Generated file containing all the extension data
77
#include "vk_loader_extensions.c"
78
79
struct loader_struct loader = {0};
80
81
struct activated_layer_info {
82
    char *name;
83
    char *manifest;
84
    char *library;
85
    bool is_implicit;
86
    enum loader_layer_enabled_by_what enabled_by_what;
87
    char *disable_env;
88
    char *enable_name_env;
89
    char *enable_value_env;
90
};
91
92
// thread safety lock for accessing global data structures such as "loader"
93
// all entrypoints on the instance chain need to be locked except GPA
94
// additionally CreateDevice and DestroyDevice needs to be locked
95
loader_platform_thread_mutex loader_lock;
96
loader_platform_thread_mutex loader_preload_icd_lock;
97
loader_platform_thread_mutex loader_global_instance_list_lock;
98
99
// A list of ICDs that gets initialized when the loader does its global initialization. This list should never be used by anything
100
// other than EnumerateInstanceExtensionProperties(), vkDestroyInstance, and loader_release(). This list does not change
101
// functionality, but the fact that the libraries already been loaded causes any call that needs to load ICD libraries to speed up
102
// significantly. This can have a huge impact when making repeated calls to vkEnumerateInstanceExtensionProperties and
103
// vkCreateInstance.
104
struct loader_icd_tramp_list preloaded_icds;
105
106
// controls whether loader_platform_close_library() closes the libraries or not - controlled by an environment
107
// variables - this is just the definition of the variable, usage is in vk_loader_platform.h
108
bool loader_disable_dynamic_library_unloading;
109
110
LOADER_PLATFORM_THREAD_ONCE_DECLARATION(once_init);
111
112
// Creates loader_api_version struct that contains the major and minor fields, setting patch to 0
113
0
loader_api_version loader_make_version(uint32_t version) {
114
0
    loader_api_version out_version;
115
0
    out_version.major = VK_API_VERSION_MAJOR(version);
116
0
    out_version.minor = VK_API_VERSION_MINOR(version);
117
0
    out_version.patch = 0;
118
0
    return out_version;
119
0
}
120
121
// Creates loader_api_version struct containing the major, minor, and patch fields
122
2
loader_api_version loader_make_full_version(uint32_t version) {
123
2
    loader_api_version out_version;
124
2
    out_version.major = VK_API_VERSION_MAJOR(version);
125
2
    out_version.minor = VK_API_VERSION_MINOR(version);
126
2
    out_version.patch = VK_API_VERSION_PATCH(version);
127
2
    return out_version;
128
2
}
129
130
0
loader_api_version loader_combine_version(uint32_t major, uint32_t minor, uint32_t patch) {
131
0
    loader_api_version out_version;
132
0
    out_version.major = (uint16_t)major;
133
0
    out_version.minor = (uint16_t)minor;
134
0
    out_version.patch = (uint16_t)patch;
135
0
    return out_version;
136
0
}
137
138
// Helper macros for determining if a version is valid or not
139
0
bool loader_check_version_meets_required(loader_api_version required, loader_api_version version) {
140
    // major version is satisfied
141
0
    return (version.major > required.major) ||
142
           // major version is equal, minor version is patch version is greater to minimum minor
143
0
           (version.major == required.major && version.minor > required.minor) ||
144
           // major and minor version are equal, patch version is greater or equal to minimum patch
145
0
           (version.major == required.major && version.minor == required.minor && version.patch >= required.patch);
146
0
}
147
148
0
const char *get_enabled_by_what_str(enum loader_layer_enabled_by_what enabled_by_what) {
149
0
    switch (enabled_by_what) {
150
0
        default:
151
0
            assert(true && "Shouldn't reach this");
152
0
            return "Unknown";
153
0
        case (ENABLED_BY_WHAT_UNSET):
154
0
            assert(true && "Shouldn't reach this");
155
0
            return "Unknown";
156
0
        case (ENABLED_BY_WHAT_LOADER_SETTINGS_FILE):
157
0
            return "Loader Settings File (Vulkan Configurator)";
158
0
        case (ENABLED_BY_WHAT_IMPLICIT_LAYER):
159
0
            return "Implicit Layer";
160
0
        case (ENABLED_BY_WHAT_VK_INSTANCE_LAYERS):
161
0
            return "Environment Variable VK_INSTANCE_LAYERS";
162
0
        case (ENABLED_BY_WHAT_VK_LOADER_LAYERS_ENABLE):
163
0
            return "Environment Variable VK_LOADER_LAYERS_ENABLE";
164
0
        case (ENABLED_BY_WHAT_IN_APPLICATION_API):
165
0
            return "By the Application";
166
0
        case (ENABLED_BY_WHAT_META_LAYER):
167
0
            return "Meta Layer (Vulkan Configurator)";
168
0
    }
169
0
}
170
171
// Wrapper around opendir so that the dirent_on_windows gets the instance it needs
172
// while linux opendir & readdir does not
173
0
DIR *loader_opendir(const struct loader_instance *instance, const char *name) {
174
#if defined(_WIN32)
175
    return opendir(instance ? &instance->alloc_callbacks : NULL, name);
176
#elif COMMON_UNIX_PLATFORMS
177
    (void)instance;
178
0
    return opendir(name);
179
#else
180
#warning dirent.h - opendir not available on this platform
181
#endif  // _WIN32
182
0
}
183
0
int loader_closedir(const struct loader_instance *instance, DIR *dir) {
184
#if defined(_WIN32)
185
    return closedir(instance ? &instance->alloc_callbacks : NULL, dir);
186
#elif COMMON_UNIX_PLATFORMS
187
    (void)instance;
188
0
    return closedir(dir);
189
#else
190
#warning dirent.h - closedir not available on this platform
191
#endif  // _WIN32
192
0
}
193
194
0
bool is_json(const char *path, size_t len) {
195
0
    if (len < 5) {
196
0
        return false;
197
0
    }
198
0
    return !strncmp(path, ".json", 5);
199
0
}
200
201
// Handle error from to library loading
202
void loader_handle_load_library_error(const struct loader_instance *inst, const char *filename,
203
0
                                      enum loader_layer_library_status *lib_status) {
204
0
    const char *error_message = loader_platform_open_library_error(filename);
205
    // If the error is due to incompatible architecture (eg 32 bit vs 64 bit), report it with INFO level
206
    // Discussed in Github issue 262 & 644
207
    // "wrong ELF class" is a linux error, " with error 193" is a windows error
208
0
    VkFlags err_flag = VULKAN_LOADER_ERROR_BIT;
209
0
    if (strstr(error_message, "wrong ELF class:") != NULL || strstr(error_message, " with error 193") != NULL) {
210
0
        err_flag = VULKAN_LOADER_INFO_BIT;
211
0
        if (NULL != lib_status) {
212
0
            *lib_status = LOADER_LAYER_LIB_ERROR_WRONG_BIT_TYPE;
213
0
        }
214
0
    }
215
    // Check if the error is due to lack of memory
216
    // "with error 8" is the windows error code for OOM cases, aka ERROR_NOT_ENOUGH_MEMORY
217
    // Linux doesn't have such a nice error message - only if there are reported issues should this be called
218
0
    else if (strstr(error_message, " with error 8") != NULL) {
219
0
        if (NULL != lib_status) {
220
0
            *lib_status = LOADER_LAYER_LIB_ERROR_OUT_OF_MEMORY;
221
0
        }
222
0
    } else if (NULL != lib_status) {
223
0
        *lib_status = LOADER_LAYER_LIB_ERROR_FAILED_TO_LOAD;
224
0
    }
225
0
    loader_log(inst, err_flag, 0, "%s", error_message);
226
0
}
227
228
0
VKAPI_ATTR VkResult VKAPI_CALL vkSetInstanceDispatch(VkInstance instance, void *object) {
229
0
    struct loader_instance *inst = loader_get_instance(instance);
230
0
    if (!inst) {
231
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "vkSetInstanceDispatch: Can not retrieve Instance dispatch table.");
232
0
        return VK_ERROR_INITIALIZATION_FAILED;
233
0
    }
234
0
    loader_set_dispatch(object, inst->disp);
235
0
    return VK_SUCCESS;
236
0
}
237
238
0
VKAPI_ATTR VkResult VKAPI_CALL vkSetDeviceDispatch(VkDevice device, void *object) {
239
0
    struct loader_device *dev;
240
0
    struct loader_icd_term *icd_term = loader_get_icd_and_device(device, &dev);
241
242
0
    if (NULL == icd_term || NULL == dev) {
243
0
        return VK_ERROR_INITIALIZATION_FAILED;
244
0
    }
245
0
    loader_set_dispatch(object, &dev->loader_dispatch);
246
0
    return VK_SUCCESS;
247
0
}
248
249
0
void loader_free_layer_properties(const struct loader_instance *inst, struct loader_layer_properties *layer_properties) {
250
0
    loader_instance_heap_free(inst, layer_properties->manifest_file_name);
251
0
    loader_instance_heap_free(inst, layer_properties->lib_name);
252
0
    loader_instance_heap_free(inst, layer_properties->functions.str_gipa);
253
0
    loader_instance_heap_free(inst, layer_properties->functions.str_gdpa);
254
0
    loader_instance_heap_free(inst, layer_properties->functions.str_negotiate_interface);
255
0
    loader_destroy_generic_list(inst, (struct loader_generic_list *)&layer_properties->instance_extension_list);
256
0
    if (layer_properties->device_extension_list.capacity > 0 && NULL != layer_properties->device_extension_list.list) {
257
0
        for (uint32_t i = 0; i < layer_properties->device_extension_list.count; i++) {
258
0
            free_string_list(inst, &layer_properties->device_extension_list.list[i].entrypoints);
259
0
        }
260
0
    }
261
0
    loader_destroy_generic_list(inst, (struct loader_generic_list *)&layer_properties->device_extension_list);
262
0
    loader_instance_heap_free(inst, layer_properties->disable_env_var.name);
263
0
    loader_instance_heap_free(inst, layer_properties->disable_env_var.value);
264
0
    loader_instance_heap_free(inst, layer_properties->enable_env_var.name);
265
0
    loader_instance_heap_free(inst, layer_properties->enable_env_var.value);
266
0
    free_string_list(inst, &layer_properties->component_layer_names);
267
0
    loader_instance_heap_free(inst, layer_properties->pre_instance_functions.enumerate_instance_extension_properties);
268
0
    loader_instance_heap_free(inst, layer_properties->pre_instance_functions.enumerate_instance_layer_properties);
269
0
    loader_instance_heap_free(inst, layer_properties->pre_instance_functions.enumerate_instance_version);
270
0
    free_string_list(inst, &layer_properties->override_paths);
271
0
    free_string_list(inst, &layer_properties->blacklist_layer_names);
272
0
    free_string_list(inst, &layer_properties->app_key_paths);
273
274
    // Make sure to clear out the removed layer, in case new layers are added in the previous location
275
0
    memset(layer_properties, 0, sizeof(struct loader_layer_properties));
276
0
}
277
278
0
VkResult loader_init_library_list(struct loader_layer_list *instance_layers, loader_platform_dl_handle **libs) {
279
0
    if (instance_layers->count > 0) {
280
0
        *libs = loader_calloc(NULL, sizeof(loader_platform_dl_handle) * instance_layers->count, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
281
0
        if (*libs == NULL) {
282
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
283
0
        }
284
0
    }
285
0
    return VK_SUCCESS;
286
0
}
287
288
0
VkResult loader_copy_to_new_str(const struct loader_instance *inst, const char *source_str, char **dest_str) {
289
0
    assert(source_str && dest_str);
290
0
    size_t str_len = strlen(source_str) + 1;
291
0
    *dest_str = loader_instance_heap_calloc(inst, str_len, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
292
0
    if (NULL == *dest_str) return VK_ERROR_OUT_OF_HOST_MEMORY;
293
0
    loader_strncpy(*dest_str, str_len, source_str, str_len);
294
0
    (*dest_str)[str_len - 1] = 0;
295
0
    return VK_SUCCESS;
296
0
}
297
298
0
VkResult create_string_list(const struct loader_instance *inst, uint32_t allocated_count, struct loader_string_list *string_list) {
299
0
    assert(string_list);
300
0
    string_list->list = loader_instance_heap_calloc(inst, sizeof(char *) * allocated_count, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
301
0
    if (NULL == string_list->list) {
302
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
303
0
    }
304
0
    string_list->allocated_count = allocated_count;
305
0
    string_list->count = 0;
306
0
    return VK_SUCCESS;
307
0
}
308
309
0
VkResult increase_str_capacity_by_at_least_one(const struct loader_instance *inst, struct loader_string_list *string_list) {
310
0
    assert(string_list);
311
0
    if (string_list->allocated_count == 0) {
312
0
        string_list->allocated_count = 32;
313
0
        string_list->list =
314
0
            loader_instance_heap_calloc(inst, sizeof(char *) * string_list->allocated_count, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
315
0
        if (NULL == string_list->list) {
316
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
317
0
        }
318
0
    } else if (string_list->count + 1 > string_list->allocated_count) {
319
0
        uint32_t new_allocated_count = string_list->allocated_count * 2;
320
0
        void *new_ptr = loader_instance_heap_realloc(inst, string_list->list, sizeof(char *) * string_list->allocated_count,
321
0
                                                     sizeof(char *) * new_allocated_count, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
322
0
        if (NULL == new_ptr) {
323
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
324
0
        }
325
0
        string_list->list = new_ptr;
326
0
        string_list->allocated_count *= 2;
327
0
    }
328
0
    return VK_SUCCESS;
329
0
}
330
331
0
VkResult append_str_to_string_list(const struct loader_instance *inst, struct loader_string_list *string_list, char *str) {
332
0
    assert(string_list && str);
333
0
    VkResult res = increase_str_capacity_by_at_least_one(inst, string_list);
334
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
335
0
        loader_instance_heap_free(inst, str);  // Must clean up in case of failure
336
0
        return res;
337
0
    }
338
0
    string_list->list[string_list->count++] = str;
339
0
    return VK_SUCCESS;
340
0
}
341
342
0
VkResult prepend_str_to_string_list(const struct loader_instance *inst, struct loader_string_list *string_list, char *str) {
343
0
    assert(string_list && str);
344
0
    VkResult res = increase_str_capacity_by_at_least_one(inst, string_list);
345
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
346
0
        loader_instance_heap_free(inst, str);  // Must clean up in case of failure
347
0
        return res;
348
0
    }
349
    // Shift everything down one
350
0
    void *ptr_to_list = memmove(string_list->list + 1, string_list->list, sizeof(char *) * string_list->count);
351
0
    if (ptr_to_list) string_list->list[0] = str;  // Write new string to start of list
352
0
    string_list->count++;
353
0
    return VK_SUCCESS;
354
0
}
355
356
VkResult copy_str_to_string_list(const struct loader_instance *inst, struct loader_string_list *string_list, const char *str,
357
0
                                 size_t str_len) {
358
0
    assert(string_list && str);
359
0
    char *new_str = loader_instance_heap_calloc(inst, sizeof(char *) * str_len + 1, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
360
0
    if (NULL == new_str) {
361
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
362
0
    }
363
0
    loader_strncpy(new_str, sizeof(char *) * str_len + 1, str, str_len);
364
0
    new_str[str_len] = '\0';
365
0
    return append_str_to_string_list(inst, string_list, new_str);
366
0
}
367
368
VkResult copy_str_to_start_of_string_list(const struct loader_instance *inst, struct loader_string_list *string_list,
369
0
                                          const char *str, size_t str_len) {
370
0
    assert(string_list && str);
371
0
    char *new_str = loader_instance_heap_calloc(inst, sizeof(char *) * str_len + 1, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
372
0
    if (NULL == new_str) {
373
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
374
0
    }
375
0
    loader_strncpy(new_str, sizeof(char *) * str_len + 1, str, str_len);
376
0
    new_str[str_len] = '\0';
377
0
    return prepend_str_to_string_list(inst, string_list, new_str);
378
0
}
379
380
0
void free_string_list(const struct loader_instance *inst, struct loader_string_list *string_list) {
381
0
    assert(string_list);
382
0
    if (string_list->list) {
383
0
        for (uint32_t i = 0; i < string_list->count; i++) {
384
0
            loader_instance_heap_free(inst, string_list->list[i]);
385
0
            string_list->list[i] = NULL;
386
0
        }
387
0
        loader_instance_heap_free(inst, string_list->list);
388
0
    }
389
0
    memset(string_list, 0, sizeof(struct loader_string_list));
390
0
}
391
392
// In place modify the passed in path to do the following:
393
// If HAVE_REALPATH is defined, then this simply calls realpath() so its behavior is defined by realpath()
394
// Else:
395
// * Windows-only: Replace forward slashes with backwards slashes (platform correct directory separator)
396
// * Replace contiguous directory separators with a single directory separator
397
// * Replace "/./" separator with "/" (where / is the platform correct directory separator)
398
// * Replace "/<directory_name>/../" with just "/" (where / is the platform correct directory separator)
399
0
VkResult normalize_path(const struct loader_instance *inst, char **passed_in_path) {
400
    // passed_in_path doesn't point to anything, can't modify inplace so just return
401
0
    if (passed_in_path == NULL) {
402
0
        return VK_SUCCESS;
403
0
    }
404
405
// POSIX systems has the realpath() function to do this for us, fallback to basic normalization on other platforms
406
0
#if defined(HAVE_REALPATH)
407
0
    char *path = loader_instance_heap_calloc(inst, PATH_MAX, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
408
0
    if (NULL == path) {
409
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
410
0
    }
411
0
    char *ret = realpath(*passed_in_path, path);
412
0
    if (NULL == ret) {
413
        // error path
414
0
        int error_code = errno;
415
0
        loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
416
0
                   "normalize_path: Call to realpath() failed with error code %d when given the path %s", error_code,
417
0
                   *passed_in_path);
418
0
        loader_instance_heap_free(inst, path);
419
0
    } else {
420
        // Replace string pointed to by passed_in_path with the one given to us by realpath()
421
0
        loader_instance_heap_free(inst, *passed_in_path);
422
0
        *passed_in_path = path;
423
0
    }
424
0
    return VK_SUCCESS;
425
426
// Windows has GetFullPathName which does essentially the same thing. Note that we call GetFullPathNameA because the path has
427
// already been converted from the wide char format when it was initially gotten
428
#elif defined(WIN32)
429
    VkResult res = VK_SUCCESS;
430
    DWORD path_len = (DWORD)strlen(*passed_in_path) + 1;
431
    char *path = loader_instance_heap_calloc(inst, (size_t)path_len, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
432
    if (NULL == path) {
433
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
434
        goto out;
435
    }
436
    DWORD actual_len = GetFullPathNameA(*passed_in_path, path_len, path, NULL);
437
    if (actual_len == 0) {
438
        size_t last_error = (size_t)GetLastError();
439
        loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
440
                   "normalize_path: Call to GetFullPathNameA() failed with error code %zu when given the path %s", last_error,
441
                   *passed_in_path);
442
        res = VK_ERROR_INITIALIZATION_FAILED;
443
        goto out;
444
    }
445
446
    // If path_len wasn't big enough, need to realloc and call again
447
    // actual_len doesn't include null terminator
448
    if (actual_len + 1 > path_len) {
449
        char *new_path = loader_instance_heap_realloc(inst, path, path_len, actual_len + 1, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
450
        if (NULL == new_path) {
451
            loader_instance_heap_free(inst, path);
452
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
453
            goto out;
454
        }
455
        path = new_path;
456
        // store the updated allocation size (sans null terminator)
457
        path_len = actual_len + 1;
458
459
        actual_len = GetFullPathNameA(*passed_in_path, path_len, path, NULL);
460
        if (actual_len == 0) {
461
            size_t last_error = (size_t)GetLastError();
462
            loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
463
                       "normalize_path: Call to GetFullPathNameA() failed with error code %zu when given the path %s", last_error,
464
                       *passed_in_path);
465
            res = VK_ERROR_INITIALIZATION_FAILED;
466
            goto out;
467
            // actual_len doesn't include null terminator
468
        } else if (actual_len + 1 != path_len) {
469
            loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
470
                       "normalize_path: Call to GetFullPathNameA() with too small of a buffer when given the path %s after the "
471
                       "initial call to GetFullPathNameA() failed for the same reason. Buffer size is %zu, actual size is %zu",
472
                       *passed_in_path, (size_t)path_len, (size_t)actual_len);
473
            res = VK_ERROR_INITIALIZATION_FAILED;
474
            goto out;
475
        }
476
    }
477
    // Replace string pointed to by passed_in_path with the one given to us by realpath()
478
    loader_instance_heap_free(inst, *passed_in_path);
479
    *passed_in_path = path;
480
out:
481
    if (VK_SUCCESS != res) {
482
        if (NULL != path) {
483
            loader_instance_heap_free(inst, path);
484
        }
485
    }
486
    return res;
487
488
#else
489
    (void)inst;
490
    char *path = *passed_in_path;
491
    size_t path_len = strlen(path) + 1;
492
493
    size_t output_index = 0;
494
    // Iterate through the string up to the last character, excluding the null terminator
495
    for (size_t i = 0; i < path_len - 1; i++) {
496
        if (i + 1 < path_len && path[i] == DIRECTORY_SYMBOL && path[i + 1] == DIRECTORY_SYMBOL) {
497
            continue;
498
        } else if (i + 2 < path_len && path[i] == DIRECTORY_SYMBOL && path[i + 1] == '.' && path[i + 2] == DIRECTORY_SYMBOL) {
499
            i += 1;
500
        } else {
501
            path[output_index++] = path[i];
502
        }
503
    }
504
    // Add null terminator and set the new length
505
    path[output_index++] = '\0';
506
    path_len = output_index;
507
508
    // Loop while there are still ..'s in the path. Easiest implementation resolves them one by one, which requires quadratic
509
    // iteration through the string
510
    char *directory_stack = loader_stack_alloc(path_len);
511
    if (directory_stack == NULL) {
512
        return VK_ERROR_OUT_OF_HOST_MEMORY;
513
    }
514
515
    size_t top_of_stack = 0;
516
517
    // Iterate through the path, push characters as we see them, if we find a "..", pop off the top of the directory stack until the
518
    // current directory is gone.
519
    for (size_t i = 0; i < path_len - 1; i++) {
520
        // if the next part of path is "/../" we need to pop from the directory stack until we hit the previous directory symbol.
521
        if (i + 3 < path_len && path[i] == DIRECTORY_SYMBOL && path[i + 1] == '.' && path[i + 2] == '.' && path_len &&
522
            path[i + 3] == DIRECTORY_SYMBOL) {
523
            // Pop until we hit the next directory symbol in the stack
524
            while (top_of_stack > 0 && directory_stack[top_of_stack - 1] != DIRECTORY_SYMBOL) {
525
                top_of_stack--;
526
                directory_stack[top_of_stack] = '\0';
527
            }
528
            // Amend the directory stack so that the top isn't a directory separator
529
            if (top_of_stack > 0 && directory_stack[top_of_stack - 1] == DIRECTORY_SYMBOL) {
530
                top_of_stack--;
531
                directory_stack[top_of_stack] = '\0';
532
            }
533
            i += 2;  // need to skip the second dot & directory separator
534
        } else {
535
            // push characters as we come across them
536
            directory_stack[top_of_stack++] = path[i];
537
        }
538
    }
539
540
    // Can't forget the null terminator
541
    directory_stack[top_of_stack] = '\0';
542
543
    // We now have the path without any ..'s, so just copy it out
544
    loader_strncpy(path, path_len, directory_stack, path_len);
545
    path[top_of_stack] = '\0';
546
    path_len = top_of_stack + 1;
547
548
    return VK_SUCCESS;
549
#endif
550
0
}
551
552
// Queries the path to the library that lib_handle & gipa are associated with, allocating a string to hold it and returning it in
553
// out_path
554
VkResult get_library_path_of_dl_handle(const struct loader_instance *inst, loader_platform_dl_handle lib_handle,
555
0
                                       PFN_vkGetInstanceProcAddr gipa, char **out_path) {
556
0
#if COMMON_UNIX_PLATFORMS
557
0
    (void)lib_handle;
558
0
    Dl_info dl_info = {0};
559
0
    if (dladdr(gipa, &dl_info) != 0 && NULL != dl_info.dli_fname) {
560
0
        return loader_copy_to_new_str(inst, dl_info.dli_fname, out_path);
561
0
    }
562
0
    return VK_SUCCESS;
563
564
#elif defined(WIN32)
565
    (void)gipa;
566
    size_t module_file_name_len = MAX_PATH;  // start with reasonably large buffer
567
    wchar_t *buffer_utf16 = (wchar_t *)loader_stack_alloc(module_file_name_len * sizeof(wchar_t));
568
    DWORD ret = GetModuleFileNameW(lib_handle, buffer_utf16, (DWORD)module_file_name_len);
569
    if (ret == 0) {
570
        return VK_SUCCESS;
571
    }
572
    while (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
573
        module_file_name_len *= 2;
574
        buffer_utf16 = (wchar_t *)loader_stack_alloc(module_file_name_len * sizeof(wchar_t));
575
        ret = GetModuleFileNameW(lib_handle, buffer_utf16, (DWORD)module_file_name_len);
576
        if (ret == 0) {
577
            return VK_SUCCESS;
578
        }
579
    }
580
581
    // Need to convert from utf16 to utf8
582
    int buffer_utf8_size = WideCharToMultiByte(CP_UTF8, 0, buffer_utf16, -1, NULL, 0, NULL, NULL);
583
    if (buffer_utf8_size <= 0) {
584
        return VK_SUCCESS;
585
    }
586
587
    char *buffer_utf8 = loader_instance_heap_calloc(inst, buffer_utf8_size, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
588
    if (NULL == buffer_utf8) {
589
        return VK_ERROR_OUT_OF_HOST_MEMORY;
590
    }
591
    if (WideCharToMultiByte(CP_UTF8, 0, buffer_utf16, -1, buffer_utf8, buffer_utf8_size, NULL, NULL) != buffer_utf8_size) {
592
        return VK_SUCCESS;
593
    }
594
595
    // Successfully got the 'real' path to the library.
596
    *out_path = buffer_utf8;
597
    return VK_SUCCESS;
598
599
#else
600
    // Do nothing, platform doesn't handle getting the path to a library
601
#endif
602
0
}
603
604
// Find and replace the path that was loaded using the lib_name path with the real path of the library. This is done to provide
605
// accurate logging info for users.
606
// This function prints a warning if there is a mismatch between the lib_name path and the real path.
607
VkResult fixup_library_binary_path(const struct loader_instance *inst, char **lib_name, loader_platform_dl_handle lib_handle,
608
0
                                   PFN_vkGetInstanceProcAddr gipa) {
609
0
    if (lib_name == NULL) {
610
        // do nothing as we got an invalid lib_path pointer
611
0
        return VK_SUCCESS;
612
0
    }
613
614
0
    bool system_path = true;
615
0
    size_t lib_name_len = strlen(*lib_name) + 1;
616
0
    for (size_t i = 0; i < lib_name_len; i++) {
617
0
        if ((*lib_name)[i] == DIRECTORY_SYMBOL) {
618
0
            system_path = false;
619
0
            break;
620
0
        }
621
0
    }
622
623
0
    if (!system_path) {
624
        // The OS path we get for a binary is normalized, so we need to normalize the path passed into LoadLibrary/dlopen so that
625
        // mismatches are minimized. EG, do not warn when we give dlopen/LoadLibrary "/foo/./bar" but get "/foo/bar" as the loaded
626
        // binary path from the OS.
627
0
        VkResult res = normalize_path(inst, lib_name);
628
0
        if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
629
0
            return res;
630
0
        }
631
0
    }
632
0
    char *os_determined_lib_name = NULL;
633
0
    VkResult res = get_library_path_of_dl_handle(inst, lib_handle, gipa, &os_determined_lib_name);
634
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
635
0
        return res;
636
0
    }
637
638
0
    if (NULL != os_determined_lib_name) {
639
        // Normalize the path so that the comparison doesn't yield false positives
640
0
        res = normalize_path(inst, &os_determined_lib_name);
641
0
        if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
642
0
            loader_instance_heap_free(inst, os_determined_lib_name);
643
0
            return res;
644
0
        }
645
646
0
        if (0 != strcmp(os_determined_lib_name, *lib_name)) {
647
            // Paths do not match, so we need to replace lib_name with the real path
648
0
            if (!system_path) {
649
                // Only warn when the library_path is relative or absolute, not system. EG lib_name had no directory separators
650
0
                loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
651
0
                           "Path to given binary %s was found to differ from OS loaded path %s", *lib_name, os_determined_lib_name);
652
0
            }
653
0
            loader_instance_heap_free(inst, *lib_name);
654
0
            *lib_name = os_determined_lib_name;
655
0
        } else {
656
            // Paths match, so just need to free temporary allocation
657
0
            loader_instance_heap_free(inst, os_determined_lib_name);
658
0
        }
659
0
    }
660
661
0
    return res;
662
0
}
663
664
// Given string of three part form "maj.min.pat" convert to a vulkan version number.
665
// Also can understand four part form "variant.major.minor.patch" if provided.
666
0
uint32_t loader_parse_version_string(char *vers_str) {
667
0
    uint32_t variant = 0, major = 0, minor = 0, patch = 0;
668
0
    char *vers_tok;
669
0
    char *context = NULL;
670
0
    if (!vers_str) {
671
0
        return 0;
672
0
    }
673
674
0
    vers_tok = thread_safe_strtok(vers_str, ".\"\n\r", &context);
675
0
    if (NULL != vers_tok) {
676
0
        major = (uint16_t)atoi(vers_tok);
677
0
        vers_tok = thread_safe_strtok(NULL, ".\"\n\r", &context);
678
0
        if (NULL != vers_tok) {
679
0
            minor = (uint16_t)atoi(vers_tok);
680
0
            vers_tok = thread_safe_strtok(NULL, ".\"\n\r", &context);
681
0
            if (NULL != vers_tok) {
682
0
                patch = (uint16_t)atoi(vers_tok);
683
0
                vers_tok = thread_safe_strtok(NULL, ".\"\n\r", &context);
684
                // check that we are using a 4 part version string
685
0
                if (NULL != vers_tok) {
686
                    // if we are, move the values over into the correct place
687
0
                    variant = major;
688
0
                    major = minor;
689
0
                    minor = patch;
690
0
                    patch = (uint16_t)atoi(vers_tok);
691
0
                }
692
0
            }
693
0
        }
694
0
    }
695
696
0
    return VK_MAKE_API_VERSION(variant, major, minor, patch);
697
0
}
698
699
0
bool compare_vk_extension_properties(const VkExtensionProperties *op1, const VkExtensionProperties *op2) {
700
0
    return strcmp(op1->extensionName, op2->extensionName) == 0 ? true : false;
701
0
}
702
703
// Search the given ext_array for an extension matching the given vk_ext_prop
704
bool has_vk_extension_property_array(const VkExtensionProperties *vk_ext_prop, const uint32_t count,
705
0
                                     const VkExtensionProperties *ext_array) {
706
0
    for (uint32_t i = 0; i < count; i++) {
707
0
        if (compare_vk_extension_properties(vk_ext_prop, &ext_array[i])) return true;
708
0
    }
709
0
    return false;
710
0
}
711
712
// Search the given ext_list for an extension matching the given vk_ext_prop
713
0
bool has_vk_extension_property(const VkExtensionProperties *vk_ext_prop, const struct loader_extension_list *ext_list) {
714
0
    for (uint32_t i = 0; i < ext_list->count; i++) {
715
0
        if (compare_vk_extension_properties(&ext_list->list[i], vk_ext_prop)) return true;
716
0
    }
717
0
    return false;
718
0
}
719
720
// Search the given ext_list for a device extension matching the given ext_prop
721
0
bool has_vk_dev_ext_property(const VkExtensionProperties *ext_prop, const struct loader_device_extension_list *ext_list) {
722
0
    for (uint32_t i = 0; i < ext_list->count; i++) {
723
0
        if (compare_vk_extension_properties(&ext_list->list[i].props, ext_prop)) return true;
724
0
    }
725
0
    return false;
726
0
}
727
728
VkResult loader_append_layer_property(const struct loader_instance *inst, struct loader_layer_list *layer_list,
729
0
                                      struct loader_layer_properties *layer_property) {
730
0
    VkResult res = VK_SUCCESS;
731
0
    if (layer_list->capacity == 0) {
732
0
        res = loader_init_generic_list(inst, (struct loader_generic_list *)layer_list, sizeof(struct loader_layer_properties));
733
0
        if (VK_SUCCESS != res) {
734
0
            goto out;
735
0
        }
736
0
    }
737
738
    // Ensure enough room to add an entry
739
0
    if ((layer_list->count + 1) * sizeof(struct loader_layer_properties) > layer_list->capacity) {
740
0
        void *new_ptr = loader_instance_heap_realloc(inst, layer_list->list, layer_list->capacity, layer_list->capacity * 2,
741
0
                                                     VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
742
0
        if (NULL == new_ptr) {
743
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_append_layer_property: realloc failed for layer list");
744
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
745
0
            goto out;
746
0
        }
747
0
        layer_list->list = new_ptr;
748
0
        layer_list->capacity *= 2;
749
0
    }
750
0
    memcpy(&layer_list->list[layer_list->count], layer_property, sizeof(struct loader_layer_properties));
751
0
    layer_list->count++;
752
0
    memset(layer_property, 0, sizeof(struct loader_layer_properties));
753
0
out:
754
0
    if (res != VK_SUCCESS) {
755
0
        loader_free_layer_properties(inst, layer_property);
756
0
    }
757
0
    return res;
758
0
}
759
760
// Search the given layer list for a layer property matching the given layer name
761
0
struct loader_layer_properties *loader_find_layer_property(const char *name, const struct loader_layer_list *layer_list) {
762
0
    for (uint32_t i = 0; i < layer_list->count; i++) {
763
0
        const VkLayerProperties *item = &layer_list->list[i].info;
764
0
        if (strcmp(name, item->layerName) == 0) return &layer_list->list[i];
765
0
    }
766
0
    return NULL;
767
0
}
768
769
struct loader_layer_properties *loader_find_pointer_layer_property(const char *name,
770
0
                                                                   const struct loader_pointer_layer_list *layer_list) {
771
0
    for (uint32_t i = 0; i < layer_list->count; i++) {
772
0
        const VkLayerProperties *item = &layer_list->list[i]->info;
773
0
        if (strcmp(name, item->layerName) == 0) return layer_list->list[i];
774
0
    }
775
0
    return NULL;
776
0
}
777
778
// Search the given layer list for a layer matching the given layer name
779
0
bool loader_find_layer_name_in_list(const char *name, const struct loader_pointer_layer_list *layer_list) {
780
0
    if (NULL == layer_list) {
781
0
        return false;
782
0
    }
783
0
    if (NULL != loader_find_pointer_layer_property(name, layer_list)) {
784
0
        return true;
785
0
    }
786
0
    return false;
787
0
}
788
789
// Search the given meta-layer's component list for a layer matching the given layer name
790
bool loader_find_layer_name_in_meta_layer(const struct loader_instance *inst, const char *layer_name,
791
0
                                          struct loader_layer_list *layer_list, struct loader_layer_properties *meta_layer_props) {
792
0
    for (uint32_t comp_layer = 0; comp_layer < meta_layer_props->component_layer_names.count; comp_layer++) {
793
0
        if (!strcmp(meta_layer_props->component_layer_names.list[comp_layer], layer_name)) {
794
0
            return true;
795
0
        }
796
0
        struct loader_layer_properties *comp_layer_props =
797
0
            loader_find_layer_property(meta_layer_props->component_layer_names.list[comp_layer], layer_list);
798
0
        if (comp_layer_props->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
799
0
            return loader_find_layer_name_in_meta_layer(inst, layer_name, layer_list, comp_layer_props);
800
0
        }
801
0
    }
802
0
    return false;
803
0
}
804
805
// Search the override layer's blacklist for a layer matching the given layer name
806
0
bool loader_find_layer_name_in_blacklist(const char *layer_name, struct loader_layer_properties *meta_layer_props) {
807
0
    for (uint32_t black_layer = 0; black_layer < meta_layer_props->blacklist_layer_names.count; ++black_layer) {
808
0
        if (!strcmp(meta_layer_props->blacklist_layer_names.list[black_layer], layer_name)) {
809
0
            return true;
810
0
        }
811
0
    }
812
0
    return false;
813
0
}
814
815
// Remove all layer properties entries from the list
816
TEST_FUNCTION_EXPORT void loader_delete_layer_list_and_properties(const struct loader_instance *inst,
817
0
                                                                  struct loader_layer_list *layer_list) {
818
0
    uint32_t i;
819
0
    if (!layer_list) return;
820
821
0
    for (i = 0; i < layer_list->count; i++) {
822
0
        if (layer_list->list[i].lib_handle) {
823
0
            loader_platform_close_library(layer_list->list[i].lib_handle);
824
0
            loader_log(inst, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Unloading layer library %s",
825
0
                       layer_list->list[i].lib_name);
826
0
            layer_list->list[i].lib_handle = NULL;
827
0
        }
828
0
        loader_free_layer_properties(inst, &(layer_list->list[i]));
829
0
    }
830
0
    layer_list->count = 0;
831
832
0
    if (layer_list->capacity > 0) {
833
0
        layer_list->capacity = 0;
834
0
        loader_instance_heap_free(inst, layer_list->list);
835
0
    }
836
0
    memset(layer_list, 0, sizeof(struct loader_layer_list));
837
0
}
838
839
void loader_remove_layer_in_list(const struct loader_instance *inst, struct loader_layer_list *layer_list,
840
0
                                 uint32_t layer_to_remove) {
841
0
    if (layer_list == NULL || layer_to_remove >= layer_list->count) {
842
0
        return;
843
0
    }
844
0
    loader_free_layer_properties(inst, &(layer_list->list[layer_to_remove]));
845
846
    // Remove the current invalid meta-layer from the layer list.  Use memmove since we are
847
    // overlapping the source and destination addresses.
848
0
    if (layer_to_remove + 1 <= layer_list->count) {
849
0
        memmove(&layer_list->list[layer_to_remove], &layer_list->list[layer_to_remove + 1],
850
0
                sizeof(struct loader_layer_properties) * (layer_list->count - 1 - layer_to_remove));
851
0
    }
852
    // Decrement the count (because we now have one less) and decrement the loop index since we need to
853
    // re-check this index.
854
0
    layer_list->count--;
855
0
}
856
857
// Remove all layers in the layer list that are blacklisted by the override layer.
858
// NOTE: This should only be called if an override layer is found and not expired.
859
0
void loader_remove_layers_in_blacklist(const struct loader_instance *inst, struct loader_layer_list *layer_list) {
860
0
    struct loader_layer_properties *override_prop = loader_find_layer_property(VK_OVERRIDE_LAYER_NAME, layer_list);
861
0
    if (NULL == override_prop) {
862
0
        return;
863
0
    }
864
865
0
    for (int32_t j = 0; j < (int32_t)(layer_list->count); j++) {
866
0
        struct loader_layer_properties cur_layer_prop = layer_list->list[j];
867
0
        const char *cur_layer_name = &cur_layer_prop.info.layerName[0];
868
869
        // Skip the override layer itself.
870
0
        if (!strcmp(VK_OVERRIDE_LAYER_NAME, cur_layer_name)) {
871
0
            continue;
872
0
        }
873
874
        // If found in the override layer's blacklist, remove it
875
0
        if (loader_find_layer_name_in_blacklist(cur_layer_name, override_prop)) {
876
0
            loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
877
0
                       "loader_remove_layers_in_blacklist: Override layer is active and layer %s is in the blacklist inside of it. "
878
0
                       "Removing that layer from current layer list.",
879
0
                       cur_layer_name);
880
0
            loader_remove_layer_in_list(inst, layer_list, j);
881
0
            j--;
882
883
            // Re-do the query for the override layer
884
0
            override_prop = loader_find_layer_property(VK_OVERRIDE_LAYER_NAME, layer_list);
885
0
        }
886
0
    }
887
0
}
888
889
// Remove all layers in the layer list that are not found inside any implicit meta-layers.
890
0
void loader_remove_layers_not_in_implicit_meta_layers(const struct loader_instance *inst, struct loader_layer_list *layer_list) {
891
0
    int32_t i;
892
0
    int32_t j;
893
0
    int32_t layer_count = (int32_t)(layer_list->count);
894
895
0
    for (i = 0; i < layer_count; i++) {
896
0
        layer_list->list[i].keep = false;
897
0
    }
898
899
0
    for (i = 0; i < layer_count; i++) {
900
0
        struct loader_layer_properties *cur_layer_prop = &layer_list->list[i];
901
902
0
        if (0 == (cur_layer_prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
903
0
            cur_layer_prop->keep = true;
904
0
            continue;
905
0
        }
906
0
        for (j = 0; j < layer_count; j++) {
907
0
            struct loader_layer_properties *layer_to_check = &layer_list->list[j];
908
909
0
            if (i == j) {
910
0
                continue;
911
0
            }
912
913
0
            if (layer_to_check->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
914
                // For all layers found in this meta layer, we want to keep them as well.
915
0
                if (loader_find_layer_name_in_meta_layer(inst, cur_layer_prop->info.layerName, layer_list, layer_to_check)) {
916
0
                    cur_layer_prop->keep = true;
917
0
                }
918
0
            }
919
0
        }
920
0
    }
921
922
    // Remove any layers we don't want to keep (Don't use layer_count here as we need it to be
923
    // dynamically updated if we delete a layer property in the list).
924
0
    for (i = 0; i < (int32_t)(layer_list->count); i++) {
925
0
        struct loader_layer_properties *cur_layer_prop = &layer_list->list[i];
926
0
        if (!cur_layer_prop->keep) {
927
0
            loader_log(
928
0
                inst, VULKAN_LOADER_DEBUG_BIT, 0,
929
0
                "loader_remove_layers_not_in_implicit_meta_layers : Implicit meta-layers are active, and layer %s is not list "
930
0
                "inside of any.  So removing layer from current layer list.",
931
0
                cur_layer_prop->info.layerName);
932
0
            loader_remove_layer_in_list(inst, layer_list, i);
933
0
            i--;
934
0
        }
935
0
    }
936
0
}
937
938
VkResult loader_add_instance_extensions(const struct loader_instance *inst,
939
                                        const PFN_vkEnumerateInstanceExtensionProperties fp_get_props, const char *lib_name,
940
0
                                        struct loader_extension_list *ext_list) {
941
0
    uint32_t i, count = 0;
942
0
    VkExtensionProperties *ext_props;
943
0
    VkResult res = VK_SUCCESS;
944
945
0
    if (!fp_get_props) {
946
        // No EnumerateInstanceExtensionProperties defined
947
0
        goto out;
948
0
    }
949
950
    // Make sure we never call ourself by accident, this should never happen outside of error paths
951
0
    if (fp_get_props == vkEnumerateInstanceExtensionProperties) {
952
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
953
0
                   "loader_add_instance_extensions: %s's vkEnumerateInstanceExtensionProperties points to the loader, this would "
954
0
                   "lead to infinite recursion.",
955
0
                   lib_name);
956
0
        goto out;
957
0
    }
958
959
0
    res = fp_get_props(NULL, &count, NULL);
960
0
    if (res != VK_SUCCESS) {
961
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
962
0
                   "loader_add_instance_extensions: Error getting Instance extension count from %s", lib_name);
963
0
        goto out;
964
0
    }
965
966
0
    if (count == 0) {
967
        // No ExtensionProperties to report
968
0
        goto out;
969
0
    }
970
971
0
    ext_props = loader_stack_alloc(count * sizeof(VkExtensionProperties));
972
0
    if (NULL == ext_props) {
973
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
974
0
        goto out;
975
0
    }
976
0
    memset(ext_props, 0, count * sizeof(VkExtensionProperties));
977
978
0
    res = fp_get_props(NULL, &count, ext_props);
979
0
    if (res != VK_SUCCESS) {
980
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_add_instance_extensions: Error getting Instance extensions from %s",
981
0
                   lib_name);
982
0
        goto out;
983
0
    }
984
985
0
    for (i = 0; i < count; i++) {
986
0
        bool ext_unsupported = wsi_unsupported_instance_extension(&ext_props[i]);
987
0
        if (!ext_unsupported) {
988
0
            res = loader_add_to_ext_list(inst, ext_list, 1, &ext_props[i]);
989
0
            if (res != VK_SUCCESS) {
990
0
                goto out;
991
0
            }
992
0
        }
993
0
    }
994
995
0
out:
996
0
    return res;
997
0
}
998
999
VkResult loader_add_device_extensions(const struct loader_instance *inst,
1000
                                      PFN_vkEnumerateDeviceExtensionProperties fpEnumerateDeviceExtensionProperties,
1001
                                      VkPhysicalDevice physical_device, const char *lib_name,
1002
0
                                      struct loader_extension_list *ext_list) {
1003
0
    uint32_t i = 0, count = 0;
1004
0
    VkResult res = VK_SUCCESS;
1005
0
    VkExtensionProperties *ext_props = NULL;
1006
1007
0
    res = fpEnumerateDeviceExtensionProperties(physical_device, NULL, &count, NULL);
1008
0
    if (res != VK_SUCCESS) {
1009
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
1010
0
                   "loader_add_device_extensions: Error getting physical device extension info count from library %s", lib_name);
1011
0
        return res;
1012
0
    }
1013
0
    if (count > 0) {
1014
0
        ext_props = loader_stack_alloc(count * sizeof(VkExtensionProperties));
1015
0
        if (!ext_props) {
1016
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
1017
0
                       "loader_add_device_extensions: Failed to allocate space for device extension properties from library %s.",
1018
0
                       lib_name);
1019
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
1020
0
        }
1021
0
        res = fpEnumerateDeviceExtensionProperties(physical_device, NULL, &count, ext_props);
1022
0
        if (res != VK_SUCCESS) {
1023
0
            return res;
1024
0
        }
1025
0
        for (i = 0; i < count; i++) {
1026
0
            res = loader_add_to_ext_list(inst, ext_list, 1, &ext_props[i]);
1027
0
            if (res != VK_SUCCESS) {
1028
0
                return res;
1029
0
            }
1030
0
        }
1031
0
    }
1032
1033
0
    return VK_SUCCESS;
1034
0
}
1035
1036
0
VkResult loader_init_generic_list(const struct loader_instance *inst, struct loader_generic_list *list_info, size_t element_size) {
1037
0
    size_t capacity = 32 * element_size;
1038
0
    list_info->count = 0;
1039
0
    list_info->capacity = 0;
1040
0
    list_info->list = loader_instance_heap_calloc(inst, capacity, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1041
0
    if (list_info->list == NULL) {
1042
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_init_generic_list: Failed to allocate space for generic list");
1043
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
1044
0
    }
1045
0
    list_info->capacity = capacity;
1046
0
    return VK_SUCCESS;
1047
0
}
1048
1049
0
VkResult loader_resize_generic_list(const struct loader_instance *inst, struct loader_generic_list *list_info) {
1050
0
    void *new_ptr = loader_instance_heap_realloc(inst, list_info->list, list_info->capacity, list_info->capacity * 2,
1051
0
                                                 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1052
0
    if (new_ptr == NULL) {
1053
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_resize_generic_list: Failed to allocate space for generic list");
1054
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
1055
0
    }
1056
0
    list_info->list = new_ptr;
1057
0
    list_info->capacity = list_info->capacity * 2;
1058
0
    return VK_SUCCESS;
1059
0
}
1060
1061
0
void loader_destroy_generic_list(const struct loader_instance *inst, struct loader_generic_list *list) {
1062
0
    loader_instance_heap_free(inst, list->list);
1063
0
    memset(list, 0, sizeof(struct loader_generic_list));
1064
0
}
1065
1066
VkResult loader_get_next_available_entry(const struct loader_instance *inst, struct loader_used_object_list *list_info,
1067
0
                                         uint32_t *free_index, const VkAllocationCallbacks *pAllocator) {
1068
0
    if (NULL == list_info->list) {
1069
0
        VkResult res =
1070
0
            loader_init_generic_list(inst, (struct loader_generic_list *)list_info, sizeof(struct loader_used_object_status));
1071
0
        if (VK_SUCCESS != res) {
1072
0
            return res;
1073
0
        }
1074
0
    }
1075
0
    for (uint32_t i = 0; i < list_info->capacity / sizeof(struct loader_used_object_status); i++) {
1076
0
        if (list_info->list[i].status == VK_FALSE) {
1077
0
            list_info->list[i].status = VK_TRUE;
1078
0
            if (pAllocator) {
1079
0
                list_info->list[i].allocation_callbacks = *pAllocator;
1080
0
            } else {
1081
0
                memset(&list_info->list[i].allocation_callbacks, 0, sizeof(VkAllocationCallbacks));
1082
0
            }
1083
0
            *free_index = i;
1084
0
            return VK_SUCCESS;
1085
0
        }
1086
0
    }
1087
    // No free space, must resize
1088
1089
0
    size_t old_capacity = list_info->capacity;
1090
0
    VkResult res = loader_resize_generic_list(inst, (struct loader_generic_list *)list_info);
1091
0
    if (VK_SUCCESS != res) {
1092
0
        return res;
1093
0
    }
1094
0
    uint32_t new_index = (uint32_t)(old_capacity / sizeof(struct loader_used_object_status));
1095
    // Zero out the newly allocated back half of list.
1096
0
    memset(&list_info->list[new_index], 0, old_capacity);
1097
0
    list_info->list[new_index].status = VK_TRUE;
1098
0
    if (pAllocator) {
1099
0
        list_info->list[new_index].allocation_callbacks = *pAllocator;
1100
0
    } else {
1101
0
        memset(&list_info->list[new_index].allocation_callbacks, 0, sizeof(VkAllocationCallbacks));
1102
0
    }
1103
0
    *free_index = new_index;
1104
0
    return VK_SUCCESS;
1105
0
}
1106
1107
0
void loader_release_object_from_list(struct loader_used_object_list *list_info, uint32_t index_to_free) {
1108
0
    if (list_info->list && list_info->capacity > index_to_free * sizeof(struct loader_used_object_status)) {
1109
0
        list_info->list[index_to_free].status = VK_FALSE;
1110
0
        memset(&list_info->list[index_to_free].allocation_callbacks, 0, sizeof(VkAllocationCallbacks));
1111
0
    }
1112
0
}
1113
1114
// Append non-duplicate extension properties defined in props to the given ext_list.
1115
// Return - Vk_SUCCESS on success
1116
VkResult loader_add_to_ext_list(const struct loader_instance *inst, struct loader_extension_list *ext_list,
1117
0
                                uint32_t prop_list_count, const VkExtensionProperties *props) {
1118
0
    if (ext_list->list == NULL || ext_list->capacity == 0) {
1119
0
        VkResult res = loader_init_generic_list(inst, (struct loader_generic_list *)ext_list, sizeof(VkExtensionProperties));
1120
0
        if (VK_SUCCESS != res) {
1121
0
            return res;
1122
0
        }
1123
0
    }
1124
1125
0
    for (uint32_t i = 0; i < prop_list_count; i++) {
1126
0
        const VkExtensionProperties *cur_ext = &props[i];
1127
1128
        // look for duplicates
1129
0
        if (has_vk_extension_property(cur_ext, ext_list)) {
1130
0
            continue;
1131
0
        }
1132
1133
        // add to list at end
1134
        // check for enough capacity
1135
0
        if (ext_list->count * sizeof(VkExtensionProperties) >= ext_list->capacity) {
1136
0
            void *new_ptr = loader_instance_heap_realloc(inst, ext_list->list, ext_list->capacity, ext_list->capacity * 2,
1137
0
                                                         VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1138
0
            if (new_ptr == NULL) {
1139
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
1140
0
                           "loader_add_to_ext_list: Failed to reallocate space for extension list");
1141
0
                return VK_ERROR_OUT_OF_HOST_MEMORY;
1142
0
            }
1143
0
            ext_list->list = new_ptr;
1144
1145
            // double capacity
1146
0
            ext_list->capacity *= 2;
1147
0
        }
1148
1149
0
        memcpy(&ext_list->list[ext_list->count], cur_ext, sizeof(VkExtensionProperties));
1150
0
        ext_list->count++;
1151
0
    }
1152
0
    return VK_SUCCESS;
1153
0
}
1154
1155
// Append one extension property defined in props with entrypoints defined in entries to the given
1156
// ext_list. Do not append if a duplicate.
1157
// If this is a duplicate, this function free's the passed in entries - as in it takes ownership over that list (if it is not
1158
// NULL) Return - Vk_SUCCESS on success
1159
VkResult loader_add_to_dev_ext_list(const struct loader_instance *inst, struct loader_device_extension_list *ext_list,
1160
0
                                    const VkExtensionProperties *props, struct loader_string_list *entrys) {
1161
0
    VkResult res = VK_SUCCESS;
1162
0
    bool should_free_entrys = true;
1163
0
    if (ext_list->list == NULL || ext_list->capacity == 0) {
1164
0
        res = loader_init_generic_list(inst, (struct loader_generic_list *)ext_list, sizeof(struct loader_dev_ext_props));
1165
0
        if (VK_SUCCESS != res) {
1166
0
            goto out;
1167
0
        }
1168
0
    }
1169
1170
    // look for duplicates
1171
0
    if (has_vk_dev_ext_property(props, ext_list)) {
1172
0
        goto out;
1173
0
    }
1174
1175
0
    uint32_t idx = ext_list->count;
1176
    // add to list at end
1177
    // check for enough capacity
1178
0
    if (idx * sizeof(struct loader_dev_ext_props) >= ext_list->capacity) {
1179
0
        void *new_ptr = loader_instance_heap_realloc(inst, ext_list->list, ext_list->capacity, ext_list->capacity * 2,
1180
0
                                                     VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1181
1182
0
        if (NULL == new_ptr) {
1183
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
1184
0
                       "loader_add_to_dev_ext_list: Failed to reallocate space for device extension list");
1185
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
1186
0
            goto out;
1187
0
        }
1188
0
        ext_list->list = new_ptr;
1189
1190
        // double capacity
1191
0
        ext_list->capacity *= 2;
1192
0
    }
1193
1194
0
    memcpy(&ext_list->list[idx].props, props, sizeof(*props));
1195
0
    if (entrys) {
1196
0
        ext_list->list[idx].entrypoints = *entrys;
1197
0
        should_free_entrys = false;
1198
0
    }
1199
0
    ext_list->count++;
1200
0
out:
1201
0
    if (NULL != entrys && should_free_entrys) {
1202
0
        free_string_list(inst, entrys);
1203
0
    }
1204
0
    return res;
1205
0
}
1206
1207
// Create storage for pointers to loader_layer_properties
1208
0
bool loader_init_pointer_layer_list(const struct loader_instance *inst, struct loader_pointer_layer_list *list) {
1209
0
    list->capacity = 32 * sizeof(void *);
1210
0
    list->list = loader_instance_heap_calloc(inst, list->capacity, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1211
0
    if (list->list == NULL) {
1212
0
        return false;
1213
0
    }
1214
0
    list->count = 0;
1215
0
    return true;
1216
0
}
1217
1218
// Search the given array of layer names for an entry matching the given VkLayerProperties
1219
bool loader_names_array_has_layer_property(const VkLayerProperties *vk_layer_prop, uint32_t layer_info_count,
1220
0
                                           struct activated_layer_info *layer_info) {
1221
0
    for (uint32_t i = 0; i < layer_info_count; i++) {
1222
0
        if (strcmp(vk_layer_prop->layerName, layer_info[i].name) == 0) {
1223
0
            return true;
1224
0
        }
1225
0
    }
1226
0
    return false;
1227
0
}
1228
1229
0
void loader_destroy_pointer_layer_list(const struct loader_instance *inst, struct loader_pointer_layer_list *layer_list) {
1230
0
    loader_instance_heap_free(inst, layer_list->list);
1231
0
    memset(layer_list, 0, sizeof(struct loader_pointer_layer_list));
1232
0
}
1233
1234
// Append layer properties defined in prop_list to the given layer_info list
1235
VkResult loader_add_layer_properties_to_list(const struct loader_instance *inst, struct loader_pointer_layer_list *list,
1236
0
                                             struct loader_layer_properties *props) {
1237
0
    if (list->list == NULL || list->capacity == 0) {
1238
0
        if (!loader_init_pointer_layer_list(inst, list)) {
1239
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
1240
0
        }
1241
0
    }
1242
1243
    // Check for enough capacity
1244
0
    if (((list->count + 1) * sizeof(struct loader_layer_properties)) >= list->capacity) {
1245
0
        size_t new_capacity = list->capacity * 2;
1246
0
        void *new_ptr =
1247
0
            loader_instance_heap_realloc(inst, list->list, list->capacity, new_capacity, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1248
0
        if (NULL == new_ptr) {
1249
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
1250
0
                       "loader_add_layer_properties_to_list: Realloc failed for when attempting to add new layer");
1251
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
1252
0
        }
1253
0
        list->list = new_ptr;
1254
0
        list->capacity = new_capacity;
1255
0
    }
1256
0
    list->list[list->count++] = props;
1257
1258
0
    return VK_SUCCESS;
1259
0
}
1260
1261
// Determine if the provided explicit layer should be available by querying the appropriate environmental variables.
1262
bool loader_layer_is_available(const struct loader_instance *inst, const struct loader_envvar_all_filters *filters,
1263
0
                               const struct loader_layer_properties *prop) {
1264
0
    bool available = true;
1265
0
    bool is_implicit = (0 == (prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER));
1266
0
    bool disabled_by_type =
1267
0
        (is_implicit) ? (filters->disable_filter.disable_all_implicit) : (filters->disable_filter.disable_all_explicit);
1268
0
    if ((filters->disable_filter.disable_all || disabled_by_type ||
1269
0
         check_name_matches_filter_environment_var(prop->info.layerName, &filters->disable_filter.additional_filters)) &&
1270
0
        !check_name_matches_filter_environment_var(prop->info.layerName, &filters->allow_filter)) {
1271
0
        available = false;
1272
0
    }
1273
0
    if (check_name_matches_filter_environment_var(prop->info.layerName, &filters->enable_filter)) {
1274
0
        available = true;
1275
0
    } else if (!available) {
1276
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
1277
0
                   "Layer \"%s\" forced disabled because name matches filter of env var \'%s\'.", prop->info.layerName,
1278
0
                   VK_LAYERS_DISABLE_ENV_VAR);
1279
0
    }
1280
1281
0
    return available;
1282
0
}
1283
1284
// Search the given search_list for any layers in the props list.  Add these to the
1285
// output layer_list.
1286
VkResult loader_add_layer_names_to_list(const struct loader_instance *inst, const struct loader_envvar_all_filters *filters,
1287
                                        struct loader_pointer_layer_list *output_list,
1288
                                        struct loader_pointer_layer_list *expanded_output_list, uint32_t name_count,
1289
0
                                        const char *const *names, const struct loader_layer_list *source_list) {
1290
0
    VkResult err = VK_SUCCESS;
1291
1292
0
    for (uint32_t i = 0; i < name_count; i++) {
1293
0
        const char *source_name = names[i];
1294
1295
0
        struct loader_layer_properties *layer_prop = loader_find_layer_property(source_name, source_list);
1296
0
        if (NULL == layer_prop) {
1297
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
1298
0
                       "loader_add_layer_names_to_list: Unable to find layer \"%s\"", source_name);
1299
0
            err = VK_ERROR_LAYER_NOT_PRESENT;
1300
0
            continue;
1301
0
        }
1302
1303
        // Make sure the layer isn't already in the output_list, skip adding it if it is.
1304
0
        if (loader_find_layer_name_in_list(source_name, output_list)) {
1305
0
            continue;
1306
0
        }
1307
1308
0
        if (!loader_layer_is_available(inst, filters, layer_prop)) {
1309
0
            continue;
1310
0
        }
1311
1312
        // If not a meta-layer, simply add it.
1313
0
        if (0 == (layer_prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER)) {
1314
0
            layer_prop->enabled_by_what = ENABLED_BY_WHAT_IN_APPLICATION_API;
1315
0
            err = loader_add_layer_properties_to_list(inst, output_list, layer_prop);
1316
0
            if (err == VK_ERROR_OUT_OF_HOST_MEMORY) return err;
1317
0
            err = loader_add_layer_properties_to_list(inst, expanded_output_list, layer_prop);
1318
0
            if (err == VK_ERROR_OUT_OF_HOST_MEMORY) return err;
1319
0
        } else {
1320
0
            err = loader_add_meta_layer(inst, filters, layer_prop, output_list, expanded_output_list, source_list, NULL);
1321
0
            if (err == VK_ERROR_OUT_OF_HOST_MEMORY) return err;
1322
0
        }
1323
0
    }
1324
1325
0
    return err;
1326
0
}
1327
1328
// Determine if the provided implicit layer should be enabled by querying the appropriate environmental variables.
1329
// For an implicit layer, at least a disable environment variable is required.
1330
bool loader_implicit_layer_is_enabled(const struct loader_instance *inst, const struct loader_envvar_all_filters *filters,
1331
0
                                      const struct loader_layer_properties *prop) {
1332
0
    bool enable = false;
1333
0
    bool forced_disabled = false;
1334
0
    bool forced_enabled = false;
1335
1336
0
    if ((filters->disable_filter.disable_all || filters->disable_filter.disable_all_implicit ||
1337
0
         check_name_matches_filter_environment_var(prop->info.layerName, &filters->disable_filter.additional_filters)) &&
1338
0
        !check_name_matches_filter_environment_var(prop->info.layerName, &filters->allow_filter)) {
1339
0
        forced_disabled = true;
1340
0
    }
1341
0
    if (check_name_matches_filter_environment_var(prop->info.layerName, &filters->enable_filter)) {
1342
0
        forced_enabled = true;
1343
0
    }
1344
1345
    // If no enable_environment variable is specified, this implicit layer is always be enabled by default.
1346
0
    if (NULL == prop->enable_env_var.name) {
1347
0
        enable = true;
1348
0
    } else {
1349
0
        char *env_value = loader_getenv(prop->enable_env_var.name, inst);
1350
0
        if (env_value && !strcmp(prop->enable_env_var.value, env_value)) {
1351
0
            enable = true;
1352
0
        }
1353
1354
        // Otherwise, only enable this layer if the enable environment variable is defined
1355
0
        loader_free_getenv(env_value, inst);
1356
0
    }
1357
1358
0
    if (forced_enabled) {
1359
        // Only report a message that we've forced on a layer if it wouldn't have been enabled
1360
        // normally.
1361
0
        if (!enable) {
1362
0
            enable = true;
1363
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
1364
0
                       "Implicit layer \"%s\" forced enabled due to env var \'%s\'.", prop->info.layerName,
1365
0
                       VK_LAYERS_ENABLE_ENV_VAR);
1366
0
        }
1367
0
    } else if (enable && forced_disabled) {
1368
0
        enable = false;
1369
        // Report a message that we've forced off a layer if it would have been enabled normally.
1370
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
1371
0
                   "Implicit layer \"%s\" forced disabled because name matches filter of env var \'%s\'.", prop->info.layerName,
1372
0
                   VK_LAYERS_DISABLE_ENV_VAR);
1373
0
        return enable;
1374
0
    }
1375
1376
    // The disable_environment has priority over everything else.  If it is defined, the layer is always
1377
    // disabled.
1378
0
    if (NULL != prop->disable_env_var.name) {
1379
0
        char *env_value = loader_getenv(prop->disable_env_var.name, inst);
1380
0
        if (NULL != env_value) {
1381
0
            enable = false;
1382
0
        }
1383
0
        loader_free_getenv(env_value, inst);
1384
0
    } else if ((prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER) == 0) {
1385
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
1386
0
                   "Implicit layer \"%s\" missing disabled environment variable!", prop->info.layerName);
1387
0
    }
1388
1389
    // Enable this layer if it is included in the override layer
1390
0
    if (inst != NULL && inst->override_layer_present) {
1391
0
        struct loader_layer_properties *override = NULL;
1392
0
        for (uint32_t i = 0; i < inst->instance_layer_list.count; ++i) {
1393
0
            if (strcmp(inst->instance_layer_list.list[i].info.layerName, VK_OVERRIDE_LAYER_NAME) == 0) {
1394
0
                override = &inst->instance_layer_list.list[i];
1395
0
                break;
1396
0
            }
1397
0
        }
1398
0
        if (override != NULL) {
1399
0
            for (uint32_t i = 0; i < override->component_layer_names.count; ++i) {
1400
0
                if (strcmp(override->component_layer_names.list[i], prop->info.layerName) == 0) {
1401
0
                    enable = true;
1402
0
                    break;
1403
0
                }
1404
0
            }
1405
0
        }
1406
0
    }
1407
1408
0
    return enable;
1409
0
}
1410
1411
// Check the individual implicit layer for the enable/disable environment variable settings.  Only add it after
1412
// every check has passed indicating it should be used, including making sure a layer of the same name hasn't already been
1413
// added.
1414
VkResult loader_add_implicit_layer(const struct loader_instance *inst, struct loader_layer_properties *prop,
1415
                                   const struct loader_envvar_all_filters *filters, struct loader_pointer_layer_list *target_list,
1416
                                   struct loader_pointer_layer_list *expanded_target_list,
1417
0
                                   const struct loader_layer_list *source_list) {
1418
0
    VkResult result = VK_SUCCESS;
1419
0
    if (loader_implicit_layer_is_enabled(inst, filters, prop)) {
1420
0
        if (0 == (prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER)) {
1421
            // Make sure the layer isn't already in the output_list, skip adding it if it is.
1422
0
            if (loader_find_layer_name_in_list(&prop->info.layerName[0], target_list)) {
1423
0
                return result;
1424
0
            }
1425
0
            prop->enabled_by_what = ENABLED_BY_WHAT_IMPLICIT_LAYER;
1426
0
            result = loader_add_layer_properties_to_list(inst, target_list, prop);
1427
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) return result;
1428
0
            if (NULL != expanded_target_list) {
1429
0
                result = loader_add_layer_properties_to_list(inst, expanded_target_list, prop);
1430
0
            }
1431
0
        } else {
1432
0
            result = loader_add_meta_layer(inst, filters, prop, target_list, expanded_target_list, source_list, NULL);
1433
0
        }
1434
0
    }
1435
0
    return result;
1436
0
}
1437
1438
// Add the component layers of a meta-layer to the active list of layers
1439
VkResult loader_add_meta_layer(const struct loader_instance *inst, const struct loader_envvar_all_filters *filters,
1440
                               struct loader_layer_properties *prop, struct loader_pointer_layer_list *target_list,
1441
                               struct loader_pointer_layer_list *expanded_target_list, const struct loader_layer_list *source_list,
1442
0
                               bool *out_found_all_component_layers) {
1443
0
    VkResult result = VK_SUCCESS;
1444
0
    bool found_all_component_layers = true;
1445
1446
    // We need to add all the individual component layers
1447
0
    loader_api_version meta_layer_api_version = loader_make_version(prop->info.specVersion);
1448
0
    for (uint32_t comp_layer = 0; comp_layer < prop->component_layer_names.count; comp_layer++) {
1449
0
        struct loader_layer_properties *search_prop =
1450
0
            loader_find_layer_property(prop->component_layer_names.list[comp_layer], source_list);
1451
0
        if (search_prop != NULL) {
1452
0
            loader_api_version search_prop_version = loader_make_version(prop->info.specVersion);
1453
0
            if (!loader_check_version_meets_required(meta_layer_api_version, search_prop_version)) {
1454
0
                loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
1455
0
                           "Meta-layer \"%s\" API version %u.%u, component layer \"%s\" version %u.%u, may have "
1456
0
                           "incompatibilities (Policy #LLP_LAYER_8)!",
1457
0
                           prop->info.layerName, meta_layer_api_version.major, meta_layer_api_version.minor,
1458
0
                           search_prop->info.layerName, search_prop_version.major, search_prop_version.minor);
1459
0
            }
1460
1461
0
            if (!loader_layer_is_available(inst, filters, search_prop)) {
1462
0
                loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
1463
0
                           "Meta Layer \"%s\" component layer \"%s\" disabled.", prop->info.layerName, search_prop->info.layerName);
1464
0
                continue;
1465
0
            }
1466
1467
            // If the component layer is itself an implicit layer, we need to do the implicit layer enable
1468
            // checks
1469
0
            if (0 == (search_prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
1470
0
                search_prop->enabled_by_what = ENABLED_BY_WHAT_META_LAYER;
1471
0
                result = loader_add_implicit_layer(inst, search_prop, filters, target_list, expanded_target_list, source_list);
1472
0
                if (result == VK_ERROR_OUT_OF_HOST_MEMORY) return result;
1473
0
            } else {
1474
0
                if (0 != (search_prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER)) {
1475
0
                    bool found_layers_in_component_meta_layer = true;
1476
0
                    search_prop->enabled_by_what = ENABLED_BY_WHAT_META_LAYER;
1477
0
                    result = loader_add_meta_layer(inst, filters, search_prop, target_list, expanded_target_list, source_list,
1478
0
                                                   &found_layers_in_component_meta_layer);
1479
0
                    if (result == VK_ERROR_OUT_OF_HOST_MEMORY) return result;
1480
0
                    if (!found_layers_in_component_meta_layer) found_all_component_layers = false;
1481
0
                } else if (!loader_find_layer_name_in_list(&search_prop->info.layerName[0], target_list)) {
1482
                    // Make sure the layer isn't already in the output_list, skip adding it if it is.
1483
0
                    search_prop->enabled_by_what = ENABLED_BY_WHAT_META_LAYER;
1484
0
                    result = loader_add_layer_properties_to_list(inst, target_list, search_prop);
1485
0
                    if (result == VK_ERROR_OUT_OF_HOST_MEMORY) return result;
1486
0
                    if (NULL != expanded_target_list) {
1487
0
                        result = loader_add_layer_properties_to_list(inst, expanded_target_list, search_prop);
1488
0
                        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) return result;
1489
0
                    }
1490
0
                }
1491
0
            }
1492
0
        } else {
1493
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
1494
0
                       "Failed to find layer name \"%s\" component layer \"%s\" to activate (Policy #LLP_LAYER_7)",
1495
0
                       prop->component_layer_names.list[comp_layer], prop->component_layer_names.list[comp_layer]);
1496
0
            found_all_component_layers = false;
1497
0
        }
1498
0
    }
1499
1500
    // Add this layer to the overall target list (not the expanded one)
1501
0
    if (found_all_component_layers) {
1502
0
        prop->enabled_by_what = ENABLED_BY_WHAT_META_LAYER;
1503
0
        result = loader_add_layer_properties_to_list(inst, target_list, prop);
1504
0
        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) return result;
1505
        // Write the result to out_found_all_component_layers in case this function is being recursed
1506
0
        if (out_found_all_component_layers) *out_found_all_component_layers = found_all_component_layers;
1507
0
    }
1508
1509
0
    return result;
1510
0
}
1511
1512
0
VkExtensionProperties *get_extension_property(const char *name, const struct loader_extension_list *list) {
1513
0
    for (uint32_t i = 0; i < list->count; i++) {
1514
0
        if (strcmp(name, list->list[i].extensionName) == 0) return &list->list[i];
1515
0
    }
1516
0
    return NULL;
1517
0
}
1518
1519
0
VkExtensionProperties *get_dev_extension_property(const char *name, const struct loader_device_extension_list *list) {
1520
0
    for (uint32_t i = 0; i < list->count; i++) {
1521
0
        if (strcmp(name, list->list[i].props.extensionName) == 0) return &list->list[i].props;
1522
0
    }
1523
0
    return NULL;
1524
0
}
1525
1526
// For Instance extensions implemented within the loader (i.e. DEBUG_REPORT
1527
// the extension must provide two entry points for the loader to use:
1528
// - "trampoline" entry point - this is the address returned by GetProcAddr
1529
//                              and will always do what's necessary to support a
1530
//                              global call.
1531
// - "terminator" function    - this function will be put at the end of the
1532
//                              instance chain and will contain the necessary logic
1533
//                              to call / process the extension for the appropriate
1534
//                              ICDs that are available.
1535
// There is no generic mechanism for including these functions, the references
1536
// must be placed into the appropriate loader entry points.
1537
// GetInstanceProcAddr: call extension GetInstanceProcAddr to check for GetProcAddr
1538
// requests
1539
// loader_coalesce_extensions(void) - add extension records to the list of global
1540
//                                    extension available to the app.
1541
// instance_disp                    - add function pointer for terminator function
1542
//                                    to this array.
1543
// The extension itself should be in a separate file that will be linked directly
1544
// with the loader.
1545
VkResult loader_get_icd_loader_instance_extensions(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list,
1546
0
                                                   struct loader_extension_list *inst_exts) {
1547
0
    struct loader_extension_list icd_exts;
1548
0
    VkResult res = VK_SUCCESS;
1549
0
    char *env_value;
1550
0
    bool filter_extensions = true;
1551
1552
    // Check if a user wants to disable the instance extension filtering behavior
1553
0
    env_value = loader_getenv("VK_LOADER_DISABLE_INST_EXT_FILTER", inst);
1554
0
    if (NULL != env_value && atoi(env_value) != 0) {
1555
0
        filter_extensions = false;
1556
0
    }
1557
0
    loader_free_getenv(env_value, inst);
1558
1559
    // traverse scanned icd list adding non-duplicate extensions to the list
1560
0
    for (uint32_t i = 0; i < icd_tramp_list->count; i++) {
1561
0
        res = loader_init_generic_list(inst, (struct loader_generic_list *)&icd_exts, sizeof(VkExtensionProperties));
1562
0
        if (VK_SUCCESS != res) {
1563
0
            goto out;
1564
0
        }
1565
0
        res = loader_add_instance_extensions(inst, icd_tramp_list->scanned_list[i].EnumerateInstanceExtensionProperties,
1566
0
                                             icd_tramp_list->scanned_list[i].lib_name, &icd_exts);
1567
0
        if (VK_SUCCESS == res) {
1568
0
            if (filter_extensions) {
1569
                // Remove any extensions not recognized by the loader
1570
0
                for (int32_t j = 0; j < (int32_t)icd_exts.count; j++) {
1571
                    // See if the extension is in the list of supported extensions
1572
0
                    bool found = false;
1573
0
                    for (uint32_t k = 0; LOADER_INSTANCE_EXTENSIONS[k] != NULL; k++) {
1574
0
                        if (strcmp(icd_exts.list[j].extensionName, LOADER_INSTANCE_EXTENSIONS[k]) == 0) {
1575
0
                            found = true;
1576
0
                            break;
1577
0
                        }
1578
0
                    }
1579
1580
                    // If it isn't in the list, remove it
1581
0
                    if (!found) {
1582
0
                        for (uint32_t k = j + 1; k < icd_exts.count; k++) {
1583
0
                            icd_exts.list[k - 1] = icd_exts.list[k];
1584
0
                        }
1585
0
                        --icd_exts.count;
1586
0
                        --j;
1587
0
                    }
1588
0
                }
1589
0
            }
1590
1591
0
            res = loader_add_to_ext_list(inst, inst_exts, icd_exts.count, icd_exts.list);
1592
0
        }
1593
0
        loader_destroy_generic_list(inst, (struct loader_generic_list *)&icd_exts);
1594
0
        if (VK_SUCCESS != res) {
1595
0
            goto out;
1596
0
        }
1597
0
    };
1598
1599
    // Traverse loader's extensions, adding non-duplicate extensions to the list
1600
0
    res = add_debug_extensions_to_ext_list(inst, inst_exts);
1601
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
1602
0
        goto out;
1603
0
    }
1604
0
    const VkExtensionProperties portability_enumeration_extension_info[] = {
1605
0
        {VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME, VK_KHR_PORTABILITY_ENUMERATION_SPEC_VERSION}};
1606
1607
    // Add VK_KHR_portability_subset
1608
0
    res = loader_add_to_ext_list(inst, inst_exts, sizeof(portability_enumeration_extension_info) / sizeof(VkExtensionProperties),
1609
0
                                 portability_enumeration_extension_info);
1610
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
1611
0
        goto out;
1612
0
    }
1613
1614
0
    const VkExtensionProperties direct_driver_loading_extension_info[] = {
1615
0
        {VK_LUNARG_DIRECT_DRIVER_LOADING_EXTENSION_NAME, VK_LUNARG_DIRECT_DRIVER_LOADING_SPEC_VERSION}};
1616
1617
    // Add VK_LUNARG_direct_driver_loading
1618
0
    res = loader_add_to_ext_list(inst, inst_exts, sizeof(direct_driver_loading_extension_info) / sizeof(VkExtensionProperties),
1619
0
                                 direct_driver_loading_extension_info);
1620
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
1621
0
        goto out;
1622
0
    }
1623
1624
0
out:
1625
0
    return res;
1626
0
}
1627
1628
0
struct loader_icd_term *loader_get_icd_and_device(const void *device, struct loader_device **found_dev) {
1629
0
    VkLayerDispatchTable *dispatch_table_device = loader_get_dispatch(device);
1630
0
    if (NULL == dispatch_table_device) {
1631
0
        *found_dev = NULL;
1632
0
        return NULL;
1633
0
    }
1634
0
    loader_platform_thread_lock_mutex(&loader_global_instance_list_lock);
1635
0
    *found_dev = NULL;
1636
1637
0
    for (struct loader_instance *inst = loader.instances; inst; inst = inst->next) {
1638
0
        for (struct loader_icd_term *icd_term = inst->icd_terms; icd_term; icd_term = icd_term->next) {
1639
0
            for (struct loader_device *dev = icd_term->logical_device_list; dev; dev = dev->next) {
1640
                // Value comparison of device prevents object wrapping by layers
1641
0
                if (loader_get_dispatch(dev->icd_device) == dispatch_table_device ||
1642
0
                    (dev->chain_device != VK_NULL_HANDLE && loader_get_dispatch(dev->chain_device) == dispatch_table_device)) {
1643
0
                    *found_dev = dev;
1644
0
                    loader_platform_thread_unlock_mutex(&loader_global_instance_list_lock);
1645
0
                    return icd_term;
1646
0
                }
1647
0
            }
1648
0
        }
1649
0
    }
1650
0
    loader_platform_thread_unlock_mutex(&loader_global_instance_list_lock);
1651
0
    return NULL;
1652
0
}
1653
1654
0
void loader_destroy_logical_device(struct loader_device *dev, const VkAllocationCallbacks *pAllocator) {
1655
0
    if (pAllocator) {
1656
0
        dev->alloc_callbacks = *pAllocator;
1657
0
    }
1658
0
    loader_device_heap_free(dev, dev);
1659
0
}
1660
1661
0
struct loader_device *loader_create_logical_device(const struct loader_instance *inst, const VkAllocationCallbacks *pAllocator) {
1662
0
    struct loader_device *new_dev;
1663
0
    new_dev = loader_calloc(pAllocator, sizeof(struct loader_device), VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1664
1665
0
    if (!new_dev) {
1666
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_create_logical_device: Failed to alloc struct loader_device");
1667
0
        return NULL;
1668
0
    }
1669
1670
0
    new_dev->loader_dispatch.core_dispatch.magic = DEVICE_DISP_TABLE_MAGIC_NUMBER;
1671
1672
0
    if (pAllocator) {
1673
0
        new_dev->alloc_callbacks = *pAllocator;
1674
0
    }
1675
1676
0
    return new_dev;
1677
0
}
1678
1679
0
void loader_add_logical_device(struct loader_icd_term *icd_term, struct loader_device *dev) {
1680
0
    dev->next = icd_term->logical_device_list;
1681
0
    icd_term->logical_device_list = dev;
1682
0
}
1683
1684
void loader_remove_logical_device(struct loader_icd_term *icd_term, struct loader_device *found_dev,
1685
0
                                  const VkAllocationCallbacks *pAllocator) {
1686
0
    struct loader_device *dev, *prev_dev;
1687
1688
0
    if (!icd_term || !found_dev) return;
1689
1690
0
    prev_dev = NULL;
1691
0
    dev = icd_term->logical_device_list;
1692
0
    while (dev && dev != found_dev) {
1693
0
        prev_dev = dev;
1694
0
        dev = dev->next;
1695
0
    }
1696
1697
0
    if (prev_dev)
1698
0
        prev_dev->next = found_dev->next;
1699
0
    else
1700
0
        icd_term->logical_device_list = found_dev->next;
1701
0
    loader_destroy_logical_device(found_dev, pAllocator);
1702
0
}
1703
1704
0
const VkAllocationCallbacks *ignore_null_callback(const VkAllocationCallbacks *callbacks) {
1705
0
    return NULL != callbacks->pfnAllocation && NULL != callbacks->pfnFree && NULL != callbacks->pfnReallocation &&
1706
0
                   NULL != callbacks->pfnInternalAllocation && NULL != callbacks->pfnInternalFree
1707
0
               ? callbacks
1708
0
               : NULL;
1709
0
}
1710
1711
// Try to close any open objects on the loader_icd_term - this must be done before destroying the instance
1712
0
void loader_icd_close_objects(struct loader_instance *ptr_inst, struct loader_icd_term *icd_term) {
1713
0
    for (uint32_t i = 0; i < icd_term->surface_list.capacity / sizeof(VkSurfaceKHR); i++) {
1714
0
        if (ptr_inst->surfaces_list.capacity > i * sizeof(struct loader_used_object_status) &&
1715
0
            ptr_inst->surfaces_list.list[i].status == VK_TRUE && NULL != icd_term->surface_list.list &&
1716
0
            icd_term->surface_list.list[i] && NULL != icd_term->dispatch.DestroySurfaceKHR) {
1717
0
            icd_term->dispatch.DestroySurfaceKHR(icd_term->instance, icd_term->surface_list.list[i],
1718
0
                                                 ignore_null_callback(&(ptr_inst->surfaces_list.list[i].allocation_callbacks)));
1719
0
            icd_term->surface_list.list[i] = (VkSurfaceKHR)(uintptr_t)NULL;
1720
0
        }
1721
0
    }
1722
0
    for (uint32_t i = 0; i < icd_term->debug_utils_messenger_list.capacity / sizeof(VkDebugUtilsMessengerEXT); i++) {
1723
0
        if (ptr_inst->debug_utils_messengers_list.capacity > i * sizeof(struct loader_used_object_status) &&
1724
0
            ptr_inst->debug_utils_messengers_list.list[i].status == VK_TRUE && NULL != icd_term->debug_utils_messenger_list.list &&
1725
0
            icd_term->debug_utils_messenger_list.list[i] && NULL != icd_term->dispatch.DestroyDebugUtilsMessengerEXT) {
1726
0
            icd_term->dispatch.DestroyDebugUtilsMessengerEXT(
1727
0
                icd_term->instance, icd_term->debug_utils_messenger_list.list[i],
1728
0
                ignore_null_callback(&(ptr_inst->debug_utils_messengers_list.list[i].allocation_callbacks)));
1729
0
            icd_term->debug_utils_messenger_list.list[i] = (VkDebugUtilsMessengerEXT)(uintptr_t)NULL;
1730
0
        }
1731
0
    }
1732
0
    for (uint32_t i = 0; i < icd_term->debug_report_callback_list.capacity / sizeof(VkDebugReportCallbackEXT); i++) {
1733
0
        if (ptr_inst->debug_report_callbacks_list.capacity > i * sizeof(struct loader_used_object_status) &&
1734
0
            ptr_inst->debug_report_callbacks_list.list[i].status == VK_TRUE && NULL != icd_term->debug_report_callback_list.list &&
1735
0
            icd_term->debug_report_callback_list.list[i] && NULL != icd_term->dispatch.DestroyDebugReportCallbackEXT) {
1736
0
            icd_term->dispatch.DestroyDebugReportCallbackEXT(
1737
0
                icd_term->instance, icd_term->debug_report_callback_list.list[i],
1738
0
                ignore_null_callback(&(ptr_inst->debug_report_callbacks_list.list[i].allocation_callbacks)));
1739
0
            icd_term->debug_report_callback_list.list[i] = (VkDebugReportCallbackEXT)(uintptr_t)NULL;
1740
0
        }
1741
0
    }
1742
0
}
1743
// Free resources allocated inside the loader_icd_term
1744
void loader_icd_destroy(struct loader_instance *ptr_inst, struct loader_icd_term *icd_term,
1745
0
                        const VkAllocationCallbacks *pAllocator) {
1746
0
    ptr_inst->icd_terms_count--;
1747
0
    for (struct loader_device *dev = icd_term->logical_device_list; dev;) {
1748
0
        struct loader_device *next_dev = dev->next;
1749
0
        loader_destroy_logical_device(dev, pAllocator);
1750
0
        dev = next_dev;
1751
0
    }
1752
1753
0
    loader_destroy_generic_list(ptr_inst, (struct loader_generic_list *)&icd_term->surface_list);
1754
0
    loader_destroy_generic_list(ptr_inst, (struct loader_generic_list *)&icd_term->debug_utils_messenger_list);
1755
0
    loader_destroy_generic_list(ptr_inst, (struct loader_generic_list *)&icd_term->debug_report_callback_list);
1756
1757
0
    loader_instance_heap_free(ptr_inst, icd_term);
1758
0
}
1759
1760
0
struct loader_icd_term *loader_icd_add(struct loader_instance *ptr_inst, const struct loader_scanned_icd *scanned_icd) {
1761
0
    struct loader_icd_term *icd_term;
1762
1763
0
    icd_term = loader_instance_heap_calloc(ptr_inst, sizeof(struct loader_icd_term), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1764
0
    if (!icd_term) {
1765
0
        return NULL;
1766
0
    }
1767
1768
0
    icd_term->scanned_icd = scanned_icd;
1769
0
    icd_term->this_instance = ptr_inst;
1770
1771
    // Prepend to the list
1772
0
    icd_term->next = ptr_inst->icd_terms;
1773
0
    ptr_inst->icd_terms = icd_term;
1774
0
    ptr_inst->icd_terms_count++;
1775
1776
0
    return icd_term;
1777
0
}
1778
// Closes the library handle in the scanned ICD, free the lib_name string, and zeros out all data
1779
0
void loader_unload_scanned_icd(struct loader_instance *inst, struct loader_scanned_icd *scanned_icd) {
1780
0
    if (NULL == scanned_icd) {
1781
0
        return;
1782
0
    }
1783
0
    if (scanned_icd->handle) {
1784
0
        loader_platform_close_library(scanned_icd->handle);
1785
0
        scanned_icd->handle = NULL;
1786
0
    }
1787
0
    loader_instance_heap_free(inst, scanned_icd->lib_name);
1788
0
    memset(scanned_icd, 0, sizeof(struct loader_scanned_icd));
1789
0
}
1790
1791
// Determine the ICD interface version to use.
1792
//     @param icd
1793
//     @param pVersion Output parameter indicating which version to use or 0 if
1794
//            the negotiation API is not supported by the ICD
1795
//     @return  bool indicating true if the selected interface version is supported
1796
//            by the loader, false indicates the version is not supported
1797
0
bool loader_get_icd_interface_version(PFN_vkNegotiateLoaderICDInterfaceVersion fp_negotiate_icd_version, uint32_t *pVersion) {
1798
0
    if (fp_negotiate_icd_version == NULL) {
1799
        // ICD does not support the negotiation API, it supports version 0 or 1
1800
        // calling code must determine if it is version 0 or 1
1801
0
        *pVersion = 0;
1802
0
    } else {
1803
        // ICD supports the negotiation API, so call it with the loader's
1804
        // latest version supported
1805
0
        *pVersion = CURRENT_LOADER_ICD_INTERFACE_VERSION;
1806
0
        VkResult result = fp_negotiate_icd_version(pVersion);
1807
1808
0
        if (result == VK_ERROR_INCOMPATIBLE_DRIVER) {
1809
            // ICD no longer supports the loader's latest interface version so
1810
            // fail loading the ICD
1811
0
            return false;
1812
0
        }
1813
0
    }
1814
1815
#if MIN_SUPPORTED_LOADER_ICD_INTERFACE_VERSION > 0
1816
    if (*pVersion < MIN_SUPPORTED_LOADER_ICD_INTERFACE_VERSION) {
1817
        // Loader no longer supports the ICD's latest interface version so fail
1818
        // loading the ICD
1819
        return false;
1820
    }
1821
#endif
1822
0
    return true;
1823
0
}
1824
1825
0
void loader_clear_scanned_icd_list(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list) {
1826
0
    if (0 != icd_tramp_list->capacity && icd_tramp_list->scanned_list) {
1827
0
        for (uint32_t i = 0; i < icd_tramp_list->count; i++) {
1828
0
            if (icd_tramp_list->scanned_list[i].handle) {
1829
0
                loader_platform_close_library(icd_tramp_list->scanned_list[i].handle);
1830
0
                icd_tramp_list->scanned_list[i].handle = NULL;
1831
0
            }
1832
0
            loader_instance_heap_free(inst, icd_tramp_list->scanned_list[i].lib_name);
1833
0
        }
1834
0
        loader_instance_heap_free(inst, icd_tramp_list->scanned_list);
1835
0
    }
1836
0
    memset(icd_tramp_list, 0, sizeof(struct loader_icd_tramp_list));
1837
0
}
1838
1839
0
VkResult loader_init_scanned_icd_list(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list) {
1840
0
    VkResult res = VK_SUCCESS;
1841
0
    loader_clear_scanned_icd_list(inst, icd_tramp_list);
1842
0
    icd_tramp_list->capacity = 8 * sizeof(struct loader_scanned_icd);
1843
0
    icd_tramp_list->scanned_list = loader_instance_heap_alloc(inst, icd_tramp_list->capacity, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1844
0
    if (NULL == icd_tramp_list->scanned_list) {
1845
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
1846
0
                   "loader_init_scanned_icd_list: Realloc failed for layer list when attempting to add new layer");
1847
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
1848
0
    }
1849
0
    return res;
1850
0
}
1851
1852
VkResult loader_add_direct_driver(const struct loader_instance *inst, uint32_t index,
1853
0
                                  const VkDirectDriverLoadingInfoLUNARG *pDriver, struct loader_icd_tramp_list *icd_tramp_list) {
1854
    // Assume pDriver is valid, since there is no real way to check it. Calling code should make sure the pointer to the array
1855
    // of VkDirectDriverLoadingInfoLUNARG structures is non-null.
1856
0
    if (NULL == pDriver->pfnGetInstanceProcAddr) {
1857
0
        loader_log(
1858
0
            inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
1859
0
            "loader_add_direct_driver: VkDirectDriverLoadingInfoLUNARG structure at index %d contains a NULL pointer for the "
1860
0
            "pfnGetInstanceProcAddr member, skipping.",
1861
0
            index);
1862
0
        return VK_ERROR_INITIALIZATION_FAILED;
1863
0
    }
1864
1865
0
    PFN_vkGetInstanceProcAddr fp_get_proc_addr = pDriver->pfnGetInstanceProcAddr;
1866
0
    PFN_vkCreateInstance fp_create_inst = NULL;
1867
0
    PFN_vkEnumerateInstanceExtensionProperties fp_get_inst_ext_props = NULL;
1868
0
    PFN_GetPhysicalDeviceProcAddr fp_get_phys_dev_proc_addr = NULL;
1869
0
    PFN_vkNegotiateLoaderICDInterfaceVersion fp_negotiate_icd_version = NULL;
1870
#if defined(VK_USE_PLATFORM_WIN32_KHR)
1871
    PFN_vk_icdEnumerateAdapterPhysicalDevices fp_enum_dxgi_adapter_phys_devs = NULL;
1872
#endif
1873
0
    struct loader_scanned_icd *new_scanned_icd;
1874
0
    uint32_t interface_version = 0;
1875
1876
    // Try to get the negotiate ICD interface version function
1877
0
    fp_negotiate_icd_version = (PFN_vk_icdNegotiateLoaderICDInterfaceVersion)pDriver->pfnGetInstanceProcAddr(
1878
0
        NULL, "vk_icdNegotiateLoaderICDInterfaceVersion");
1879
1880
0
    if (NULL == fp_negotiate_icd_version) {
1881
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
1882
0
                   "loader_add_direct_driver: Could not get 'vk_icdNegotiateLoaderICDInterfaceVersion' from "
1883
0
                   "VkDirectDriverLoadingInfoLUNARG structure at "
1884
0
                   "index %d, skipping.",
1885
0
                   index);
1886
0
        return VK_ERROR_INITIALIZATION_FAILED;
1887
0
    }
1888
1889
0
    if (!loader_get_icd_interface_version(fp_negotiate_icd_version, &interface_version)) {
1890
0
        loader_log(
1891
0
            inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
1892
0
            "loader_add_direct_driver: VkDirectDriverLoadingInfoLUNARG structure at index %d supports interface version %d, "
1893
0
            "which is incompatible with the Loader Driver Interface version that supports the VK_LUNARG_direct_driver_loading "
1894
0
            "extension, skipping.",
1895
0
            index, interface_version);
1896
0
        return VK_ERROR_INITIALIZATION_FAILED;
1897
0
    }
1898
1899
0
    if (interface_version < 7) {
1900
0
        loader_log(
1901
0
            inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
1902
0
            "loader_add_direct_driver: VkDirectDriverLoadingInfoLUNARG structure at index %d supports interface version %d, "
1903
0
            "which is incompatible with the Loader Driver Interface version that supports the VK_LUNARG_direct_driver_loading "
1904
0
            "extension, skipping.",
1905
0
            index, interface_version);
1906
0
        return VK_ERROR_INITIALIZATION_FAILED;
1907
0
    }
1908
1909
0
    fp_create_inst = (PFN_vkCreateInstance)pDriver->pfnGetInstanceProcAddr(NULL, "vkCreateInstance");
1910
0
    if (NULL == fp_create_inst) {
1911
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
1912
0
                   "loader_add_direct_driver: Could not get 'vkCreateInstance' from VkDirectDriverLoadingInfoLUNARG structure at "
1913
0
                   "index %d, skipping.",
1914
0
                   index);
1915
0
        return VK_ERROR_INITIALIZATION_FAILED;
1916
0
    }
1917
0
    fp_get_inst_ext_props =
1918
0
        (PFN_vkEnumerateInstanceExtensionProperties)pDriver->pfnGetInstanceProcAddr(NULL, "vkEnumerateInstanceExtensionProperties");
1919
0
    if (NULL == fp_get_inst_ext_props) {
1920
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
1921
0
                   "loader_add_direct_driver: Could not get 'vkEnumerateInstanceExtensionProperties' from "
1922
0
                   "VkDirectDriverLoadingInfoLUNARG structure at index %d, skipping.",
1923
0
                   index);
1924
0
        return VK_ERROR_INITIALIZATION_FAILED;
1925
0
    }
1926
1927
0
    fp_get_phys_dev_proc_addr =
1928
0
        (PFN_vk_icdGetPhysicalDeviceProcAddr)pDriver->pfnGetInstanceProcAddr(NULL, "vk_icdGetPhysicalDeviceProcAddr");
1929
#if defined(VK_USE_PLATFORM_WIN32_KHR)
1930
    // Query "vk_icdEnumerateAdapterPhysicalDevices" with vk_icdGetInstanceProcAddr if the library reports interface version
1931
    // 7 or greater, otherwise fallback to loading it from the platform dynamic linker
1932
    fp_enum_dxgi_adapter_phys_devs =
1933
        (PFN_vk_icdEnumerateAdapterPhysicalDevices)pDriver->pfnGetInstanceProcAddr(NULL, "vk_icdEnumerateAdapterPhysicalDevices");
1934
#endif
1935
1936
    // check for enough capacity
1937
0
    if ((icd_tramp_list->count * sizeof(struct loader_scanned_icd)) >= icd_tramp_list->capacity) {
1938
0
        void *new_ptr = loader_instance_heap_realloc(inst, icd_tramp_list->scanned_list, icd_tramp_list->capacity,
1939
0
                                                     icd_tramp_list->capacity * 2, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1940
0
        if (NULL == new_ptr) {
1941
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
1942
0
                       "loader_add_direct_driver: Realloc failed on icd library list for ICD index %u", index);
1943
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
1944
0
        }
1945
0
        icd_tramp_list->scanned_list = new_ptr;
1946
1947
        // double capacity
1948
0
        icd_tramp_list->capacity *= 2;
1949
0
    }
1950
1951
    // Driver must be 1.1 to support version 7
1952
0
    uint32_t api_version = VK_API_VERSION_1_1;
1953
0
    PFN_vkEnumerateInstanceVersion icd_enumerate_instance_version =
1954
0
        (PFN_vkEnumerateInstanceVersion)pDriver->pfnGetInstanceProcAddr(NULL, "vkEnumerateInstanceVersion");
1955
1956
0
    if (icd_enumerate_instance_version) {
1957
0
        VkResult res = icd_enumerate_instance_version(&api_version);
1958
0
        if (res != VK_SUCCESS) {
1959
0
            return res;
1960
0
        }
1961
0
    }
1962
1963
0
    new_scanned_icd = &(icd_tramp_list->scanned_list[icd_tramp_list->count]);
1964
0
    new_scanned_icd->handle = NULL;
1965
0
    new_scanned_icd->api_version = api_version;
1966
0
    new_scanned_icd->GetInstanceProcAddr = fp_get_proc_addr;
1967
0
    new_scanned_icd->GetPhysicalDeviceProcAddr = fp_get_phys_dev_proc_addr;
1968
0
    new_scanned_icd->EnumerateInstanceExtensionProperties = fp_get_inst_ext_props;
1969
0
    new_scanned_icd->CreateInstance = fp_create_inst;
1970
#if defined(VK_USE_PLATFORM_WIN32_KHR)
1971
    new_scanned_icd->EnumerateAdapterPhysicalDevices = fp_enum_dxgi_adapter_phys_devs;
1972
#endif
1973
0
    new_scanned_icd->interface_version = interface_version;
1974
1975
0
    new_scanned_icd->lib_name = NULL;
1976
0
    icd_tramp_list->count++;
1977
1978
0
    loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
1979
0
               "loader_add_direct_driver: Adding driver found in index %d of "
1980
0
               "VkDirectDriverLoadingListLUNARG::pDrivers structure. pfnGetInstanceProcAddr was set to %p",
1981
0
               index, pDriver->pfnGetInstanceProcAddr);
1982
1983
0
    return VK_SUCCESS;
1984
0
}
1985
1986
// Search through VkInstanceCreateInfo's pNext chain for any drivers from the direct driver loading extension and load them.
1987
VkResult loader_scan_for_direct_drivers(const struct loader_instance *inst, const VkInstanceCreateInfo *pCreateInfo,
1988
0
                                        struct loader_icd_tramp_list *icd_tramp_list, bool *direct_driver_loading_exclusive_mode) {
1989
0
    if (NULL == pCreateInfo) {
1990
        // Don't do this logic unless we are being called from vkCreateInstance, when pCreateInfo will be non-null
1991
0
        return VK_SUCCESS;
1992
0
    }
1993
0
    bool direct_driver_loading_enabled = false;
1994
    // Try to if VK_LUNARG_direct_driver_loading is enabled and if we are using it exclusively
1995
    // Skip this step if inst is NULL, aka when this function is being called before instance creation
1996
0
    if (inst != NULL && pCreateInfo->ppEnabledExtensionNames && pCreateInfo->enabledExtensionCount > 0) {
1997
        // Look through the enabled extension list, make sure VK_LUNARG_direct_driver_loading is present
1998
0
        for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1999
0
            if (strcmp(pCreateInfo->ppEnabledExtensionNames[i], VK_LUNARG_DIRECT_DRIVER_LOADING_EXTENSION_NAME) == 0) {
2000
0
                direct_driver_loading_enabled = true;
2001
0
                break;
2002
0
            }
2003
0
        }
2004
0
    }
2005
0
    const VkDirectDriverLoadingListLUNARG *ddl_list = NULL;
2006
    // Find the VkDirectDriverLoadingListLUNARG struct in the pNext chain of vkInstanceCreateInfo
2007
0
    const void *pNext = pCreateInfo->pNext;
2008
0
    while (pNext) {
2009
0
        VkBaseInStructure out_structure = {0};
2010
0
        memcpy(&out_structure, pNext, sizeof(VkBaseInStructure));
2011
0
        if (out_structure.sType == VK_STRUCTURE_TYPE_DIRECT_DRIVER_LOADING_LIST_LUNARG) {
2012
0
            ddl_list = (VkDirectDriverLoadingListLUNARG *)pNext;
2013
0
            break;
2014
0
        }
2015
0
        pNext = out_structure.pNext;
2016
0
    }
2017
0
    if (NULL == ddl_list) {
2018
0
        if (direct_driver_loading_enabled) {
2019
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
2020
0
                       "loader_scan_for_direct_drivers: The VK_LUNARG_direct_driver_loading extension was enabled but the "
2021
0
                       "pNext chain of "
2022
0
                       "VkInstanceCreateInfo did not contain the "
2023
0
                       "VkDirectDriverLoadingListLUNARG structure.");
2024
0
        }
2025
        // Always want to exit early if there was no VkDirectDriverLoadingListLUNARG in the pNext chain
2026
0
        return VK_SUCCESS;
2027
0
    }
2028
2029
0
    if (!direct_driver_loading_enabled) {
2030
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
2031
0
                   "loader_scan_for_direct_drivers: The pNext chain of VkInstanceCreateInfo contained the "
2032
0
                   "VkDirectDriverLoadingListLUNARG structure, but the VK_LUNARG_direct_driver_loading extension was "
2033
0
                   "not enabled.");
2034
0
        return VK_SUCCESS;
2035
0
    }
2036
    // If we are using exclusive mode, skip looking for any more drivers from system or environment variables
2037
0
    if (ddl_list->mode == VK_DIRECT_DRIVER_LOADING_MODE_EXCLUSIVE_LUNARG) {
2038
0
        *direct_driver_loading_exclusive_mode = true;
2039
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
2040
0
                   "loader_scan_for_direct_drivers: The VK_LUNARG_direct_driver_loading extension is active and specified "
2041
0
                   "VK_DIRECT_DRIVER_LOADING_MODE_EXCLUSIVE_LUNARG, skipping system and environment "
2042
0
                   "variable driver search mechanisms.");
2043
0
    }
2044
0
    if (NULL == ddl_list->pDrivers) {
2045
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
2046
0
                   "loader_scan_for_direct_drivers: The VkDirectDriverLoadingListLUNARG structure in the pNext chain of "
2047
0
                   "VkInstanceCreateInfo has a NULL pDrivers member.");
2048
0
        return VK_SUCCESS;
2049
0
    }
2050
0
    if (ddl_list->driverCount == 0) {
2051
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
2052
0
                   "loader_scan_for_direct_drivers: The VkDirectDriverLoadingListLUNARG structure in the pNext chain of "
2053
0
                   "VkInstanceCreateInfo has a non-null pDrivers member but a driverCount member with a value "
2054
0
                   "of zero.");
2055
0
        return VK_SUCCESS;
2056
0
    }
2057
    // Go through all VkDirectDriverLoadingInfoLUNARG entries and add each driver
2058
    // Because icd_tramp's are prepended, this will result in the drivers appearing at the end
2059
0
    for (uint32_t i = 0; i < ddl_list->driverCount; i++) {
2060
0
        VkResult res = loader_add_direct_driver(inst, i, &ddl_list->pDrivers[i], icd_tramp_list);
2061
0
        if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
2062
0
            return res;
2063
0
        }
2064
0
    }
2065
2066
0
    return VK_SUCCESS;
2067
0
}
2068
2069
VkResult loader_scanned_icd_add(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list,
2070
0
                                const char *filename, uint32_t api_version, enum loader_layer_library_status *lib_status) {
2071
0
    loader_platform_dl_handle handle = NULL;
2072
0
    PFN_vkCreateInstance fp_create_inst = NULL;
2073
0
    PFN_vkEnumerateInstanceExtensionProperties fp_get_inst_ext_props = NULL;
2074
0
    PFN_vkGetInstanceProcAddr fp_get_proc_addr = NULL;
2075
0
    PFN_GetPhysicalDeviceProcAddr fp_get_phys_dev_proc_addr = NULL;
2076
0
    PFN_vkNegotiateLoaderICDInterfaceVersion fp_negotiate_icd_version = NULL;
2077
#if defined(VK_USE_PLATFORM_WIN32_KHR)
2078
    PFN_vk_icdEnumerateAdapterPhysicalDevices fp_enum_dxgi_adapter_phys_devs = NULL;
2079
#endif
2080
0
    struct loader_scanned_icd *new_scanned_icd = NULL;
2081
0
    uint32_t interface_vers;
2082
0
    VkResult res = VK_SUCCESS;
2083
2084
    // This shouldn't happen, but the check is necessary because dlopen returns a handle to the main program when
2085
    // filename is NULL
2086
0
    if (filename == NULL) {
2087
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_scanned_icd_add: A NULL filename was used, skipping this ICD");
2088
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
2089
0
        goto out;
2090
0
    }
2091
2092
// TODO implement smarter opening/closing of libraries. For now this
2093
// function leaves libraries open and the scanned_icd_clear closes them
2094
#if defined(__Fuchsia__)
2095
    handle = loader_platform_open_driver(filename);
2096
#else
2097
0
    handle = loader_platform_open_library(filename);
2098
0
#endif
2099
0
    if (NULL == handle) {
2100
0
        loader_handle_load_library_error(inst, filename, lib_status);
2101
0
        if (lib_status && *lib_status == LOADER_LAYER_LIB_ERROR_OUT_OF_MEMORY) {
2102
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
2103
0
        } else {
2104
0
            res = VK_ERROR_INCOMPATIBLE_DRIVER;
2105
0
        }
2106
0
        goto out;
2107
0
    }
2108
2109
    // Try to load the driver's exported vk_icdNegotiateLoaderICDInterfaceVersion
2110
0
    fp_negotiate_icd_version = loader_platform_get_proc_address(handle, "vk_icdNegotiateLoaderICDInterfaceVersion");
2111
2112
    // If it isn't exported, we are dealing with either a v0, v1, or a v7 and up driver
2113
0
    if (NULL == fp_negotiate_icd_version) {
2114
        // Try to load the driver's exported vk_icdGetInstanceProcAddr - if this is a v7 or up driver, we can use it to get
2115
        // the driver's vk_icdNegotiateLoaderICDInterfaceVersion function
2116
0
        fp_get_proc_addr = loader_platform_get_proc_address(handle, "vk_icdGetInstanceProcAddr");
2117
2118
        // If we successfully loaded vk_icdGetInstanceProcAddr, try to get vk_icdNegotiateLoaderICDInterfaceVersion
2119
0
        if (fp_get_proc_addr) {
2120
0
            fp_negotiate_icd_version =
2121
0
                (PFN_vk_icdNegotiateLoaderICDInterfaceVersion)fp_get_proc_addr(NULL, "vk_icdNegotiateLoaderICDInterfaceVersion");
2122
0
        }
2123
0
    }
2124
2125
    // Try to negotiate the Loader and Driver Interface Versions
2126
    // loader_get_icd_interface_version will check if fp_negotiate_icd_version is NULL, so we don't have to.
2127
    // If it *is* NULL, that means this driver uses interface version 0 or 1
2128
0
    if (!loader_get_icd_interface_version(fp_negotiate_icd_version, &interface_vers)) {
2129
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
2130
0
                   "loader_scanned_icd_add: ICD %s doesn't support interface version compatible with loader, skip this ICD.",
2131
0
                   filename);
2132
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
2133
0
        goto out;
2134
0
    }
2135
2136
    // If we didn't already query vk_icdGetInstanceProcAddr, try now
2137
0
    if (NULL == fp_get_proc_addr) {
2138
0
        fp_get_proc_addr = loader_platform_get_proc_address(handle, "vk_icdGetInstanceProcAddr");
2139
0
    }
2140
2141
    // If vk_icdGetInstanceProcAddr is NULL, this ICD is using version 0 and so we should respond accordingly.
2142
0
    if (NULL == fp_get_proc_addr) {
2143
        // Exporting vk_icdNegotiateLoaderICDInterfaceVersion but not vk_icdGetInstanceProcAddr violates Version 2's
2144
        // requirements, as for Version 2 to be supported Version 1 must also be supported
2145
0
        if (interface_vers != 0) {
2146
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
2147
0
                       "loader_scanned_icd_add: ICD %s reports an interface version of %d but doesn't export "
2148
0
                       "vk_icdGetInstanceProcAddr, skip this ICD.",
2149
0
                       filename, interface_vers);
2150
0
            res = VK_ERROR_INCOMPATIBLE_DRIVER;
2151
0
            goto out;
2152
0
        }
2153
        // Use deprecated interface from version 0
2154
0
        fp_get_proc_addr = loader_platform_get_proc_address(handle, "vkGetInstanceProcAddr");
2155
0
        if (NULL == fp_get_proc_addr) {
2156
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
2157
0
                       "loader_scanned_icd_add: Attempt to retrieve either \'vkGetInstanceProcAddr\' or "
2158
0
                       "\'vk_icdGetInstanceProcAddr\' from ICD %s failed.",
2159
0
                       filename);
2160
0
            res = VK_ERROR_INCOMPATIBLE_DRIVER;
2161
0
            goto out;
2162
0
        } else {
2163
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2164
0
                       "loader_scanned_icd_add: Using deprecated ICD interface of \'vkGetInstanceProcAddr\' instead of "
2165
0
                       "\'vk_icdGetInstanceProcAddr\' for ICD %s",
2166
0
                       filename);
2167
0
        }
2168
0
        fp_create_inst = loader_platform_get_proc_address(handle, "vkCreateInstance");
2169
0
        if (NULL == fp_create_inst) {
2170
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
2171
0
                       "loader_scanned_icd_add:  Failed querying \'vkCreateInstance\' via dlsym/LoadLibrary for ICD %s", filename);
2172
0
            res = VK_ERROR_INCOMPATIBLE_DRIVER;
2173
0
            goto out;
2174
0
        }
2175
0
        fp_get_inst_ext_props = loader_platform_get_proc_address(handle, "vkEnumerateInstanceExtensionProperties");
2176
0
        if (NULL == fp_get_inst_ext_props) {
2177
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
2178
0
                       "loader_scanned_icd_add: Could not get \'vkEnumerateInstanceExtensionProperties\' via dlsym/LoadLibrary "
2179
0
                       "for ICD %s",
2180
0
                       filename);
2181
0
            res = VK_ERROR_INCOMPATIBLE_DRIVER;
2182
0
            goto out;
2183
0
        }
2184
0
    } else {
2185
        // vk_icdGetInstanceProcAddr was successfully found, we can assume the version is at least one
2186
        // If vk_icdNegotiateLoaderICDInterfaceVersion was also found, interface_vers must be 2 or greater, so this check is
2187
        // fine
2188
0
        if (interface_vers == 0) {
2189
0
            interface_vers = 1;
2190
0
        }
2191
2192
0
        fp_create_inst = (PFN_vkCreateInstance)fp_get_proc_addr(NULL, "vkCreateInstance");
2193
0
        if (NULL == fp_create_inst) {
2194
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
2195
0
                       "loader_scanned_icd_add: Could not get \'vkCreateInstance\' via \'vk_icdGetInstanceProcAddr\' for ICD %s",
2196
0
                       filename);
2197
0
            res = VK_ERROR_INCOMPATIBLE_DRIVER;
2198
0
            goto out;
2199
0
        }
2200
0
        fp_get_inst_ext_props =
2201
0
            (PFN_vkEnumerateInstanceExtensionProperties)fp_get_proc_addr(NULL, "vkEnumerateInstanceExtensionProperties");
2202
0
        if (NULL == fp_get_inst_ext_props) {
2203
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
2204
0
                       "loader_scanned_icd_add: Could not get \'vkEnumerateInstanceExtensionProperties\' via "
2205
0
                       "\'vk_icdGetInstanceProcAddr\' for ICD %s",
2206
0
                       filename);
2207
0
            res = VK_ERROR_INCOMPATIBLE_DRIVER;
2208
0
            goto out;
2209
0
        }
2210
        // Query "vk_icdGetPhysicalDeviceProcAddr" with vk_icdGetInstanceProcAddr if the library reports interface version 7 or
2211
        // greater, otherwise fallback to loading it from the platform dynamic linker
2212
0
        if (interface_vers >= 7) {
2213
0
            fp_get_phys_dev_proc_addr =
2214
0
                (PFN_vk_icdGetPhysicalDeviceProcAddr)fp_get_proc_addr(NULL, "vk_icdGetPhysicalDeviceProcAddr");
2215
0
        }
2216
0
        if (NULL == fp_get_phys_dev_proc_addr && interface_vers >= 3) {
2217
0
            fp_get_phys_dev_proc_addr = loader_platform_get_proc_address(handle, "vk_icdGetPhysicalDeviceProcAddr");
2218
0
        }
2219
#if defined(VK_USE_PLATFORM_WIN32_KHR)
2220
        // Query "vk_icdEnumerateAdapterPhysicalDevices" with vk_icdGetInstanceProcAddr if the library reports interface version
2221
        // 7 or greater, otherwise fallback to loading it from the platform dynamic linker
2222
        if (interface_vers >= 7) {
2223
            fp_enum_dxgi_adapter_phys_devs =
2224
                (PFN_vk_icdEnumerateAdapterPhysicalDevices)fp_get_proc_addr(NULL, "vk_icdEnumerateAdapterPhysicalDevices");
2225
        }
2226
        if (NULL == fp_enum_dxgi_adapter_phys_devs && interface_vers >= 6) {
2227
            fp_enum_dxgi_adapter_phys_devs = loader_platform_get_proc_address(handle, "vk_icdEnumerateAdapterPhysicalDevices");
2228
        }
2229
#endif
2230
0
    }
2231
2232
    // check for enough capacity
2233
0
    if ((icd_tramp_list->count * sizeof(struct loader_scanned_icd)) >= icd_tramp_list->capacity) {
2234
0
        void *new_ptr = loader_instance_heap_realloc(inst, icd_tramp_list->scanned_list, icd_tramp_list->capacity,
2235
0
                                                     icd_tramp_list->capacity * 2, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
2236
0
        if (NULL == new_ptr) {
2237
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
2238
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_scanned_icd_add: Realloc failed on icd library list for ICD %s",
2239
0
                       filename);
2240
0
            goto out;
2241
0
        }
2242
0
        icd_tramp_list->scanned_list = new_ptr;
2243
2244
        // double capacity
2245
0
        icd_tramp_list->capacity *= 2;
2246
0
    }
2247
2248
0
    loader_api_version api_version_struct = loader_make_version(api_version);
2249
0
    if (interface_vers <= 4 && loader_check_version_meets_required(LOADER_VERSION_1_1_0, api_version_struct)) {
2250
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2251
0
                   "loader_scanned_icd_add: Driver %s supports Vulkan %u.%u, but only supports loader interface version %u."
2252
0
                   " Interface version 5 or newer required to support this version of Vulkan (Policy #LDP_DRIVER_7)",
2253
0
                   filename, api_version_struct.major, api_version_struct.minor, interface_vers);
2254
0
    }
2255
2256
0
    new_scanned_icd = &(icd_tramp_list->scanned_list[icd_tramp_list->count]);
2257
0
    new_scanned_icd->handle = handle;
2258
0
    new_scanned_icd->api_version = api_version;
2259
0
    new_scanned_icd->GetInstanceProcAddr = fp_get_proc_addr;
2260
0
    new_scanned_icd->GetPhysicalDeviceProcAddr = fp_get_phys_dev_proc_addr;
2261
0
    new_scanned_icd->EnumerateInstanceExtensionProperties = fp_get_inst_ext_props;
2262
0
    new_scanned_icd->CreateInstance = fp_create_inst;
2263
#if defined(VK_USE_PLATFORM_WIN32_KHR)
2264
    new_scanned_icd->EnumerateAdapterPhysicalDevices = fp_enum_dxgi_adapter_phys_devs;
2265
#endif
2266
0
    new_scanned_icd->interface_version = interface_vers;
2267
2268
0
    res = loader_copy_to_new_str(inst, filename, &new_scanned_icd->lib_name);
2269
0
    if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
2270
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_scanned_icd_add: Out of memory can't add ICD %s", filename);
2271
0
        goto out;
2272
0
    }
2273
2274
    // Uses OS calls to find the 'true' path to the binary, for more accurate logging later on.
2275
0
    res = fixup_library_binary_path(inst, &(new_scanned_icd->lib_name), new_scanned_icd->handle, fp_get_proc_addr);
2276
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
2277
0
        loader_instance_heap_free(inst, new_scanned_icd->lib_name);
2278
0
        goto out;
2279
0
    }
2280
2281
0
    icd_tramp_list->count++;
2282
2283
0
out:
2284
0
    if (res != VK_SUCCESS) {
2285
0
        if (NULL != handle) {
2286
0
            loader_platform_close_library(handle);
2287
0
        }
2288
0
    }
2289
2290
0
    return res;
2291
0
}
2292
2293
#if defined(_WIN32)
2294
BOOL __stdcall loader_initialize(PINIT_ONCE InitOnce, PVOID Parameter, PVOID *Context) {
2295
    (void)InitOnce;
2296
    (void)Parameter;
2297
    (void)Context;
2298
#else
2299
2
void loader_initialize(void) {
2300
2
    loader_platform_thread_create_mutex(&loader_lock);
2301
2
    loader_platform_thread_create_mutex(&loader_preload_icd_lock);
2302
2
    loader_platform_thread_create_mutex(&loader_global_instance_list_lock);
2303
2
    init_global_loader_settings();
2304
2
#endif
2305
2306
    // initialize logging
2307
2
    loader_init_global_debug_level();
2308
#if defined(_WIN32)
2309
    windows_initialization();
2310
#endif
2311
2312
2
    loader_api_version version = loader_make_full_version(VK_HEADER_VERSION_COMPLETE);
2313
2
    loader_log(NULL, VULKAN_LOADER_INFO_BIT, 0, "Vulkan Loader Version %d.%d.%d", version.major, version.minor, version.patch);
2314
2315
#if defined(GIT_BRANCH_NAME) && defined(GIT_TAG_INFO)
2316
    loader_log(NULL, VULKAN_LOADER_INFO_BIT, 0, "[Vulkan Loader Git - Tag: " GIT_BRANCH_NAME ", Branch/Commit: " GIT_TAG_INFO "]");
2317
#endif
2318
2319
2
    char *loader_disable_dynamic_library_unloading_env_var = loader_getenv("VK_LOADER_DISABLE_DYNAMIC_LIBRARY_UNLOADING", NULL);
2320
2
    if (loader_disable_dynamic_library_unloading_env_var &&
2321
0
        0 == strncmp(loader_disable_dynamic_library_unloading_env_var, "1", 2)) {
2322
0
        loader_disable_dynamic_library_unloading = true;
2323
0
        loader_log(NULL, VULKAN_LOADER_WARN_BIT, 0, "Vulkan Loader: library unloading is disabled");
2324
2
    } else {
2325
2
        loader_disable_dynamic_library_unloading = false;
2326
2
    }
2327
2
    loader_free_getenv(loader_disable_dynamic_library_unloading_env_var, NULL);
2328
#if defined(LOADER_USE_UNSAFE_FILE_SEARCH)
2329
    loader_log(NULL, VULKAN_LOADER_WARN_BIT, 0, "Vulkan Loader: unsafe searching is enabled");
2330
#endif
2331
#if defined(_WIN32)
2332
    return TRUE;
2333
#endif
2334
2
}
2335
2336
0
void loader_release(void) {
2337
    // Guarantee release of the preloaded ICD libraries. This may have already been called in vkDestroyInstance.
2338
0
    loader_unload_preloaded_icds();
2339
2340
    // release mutexes
2341
0
    teardown_global_loader_settings();
2342
0
    loader_platform_thread_delete_mutex(&loader_lock);
2343
0
    loader_platform_thread_delete_mutex(&loader_preload_icd_lock);
2344
0
    loader_platform_thread_delete_mutex(&loader_global_instance_list_lock);
2345
0
}
2346
2347
// Preload the ICD libraries that are likely to be needed so we don't repeatedly load/unload them later
2348
0
void loader_preload_icds(void) {
2349
0
    loader_platform_thread_lock_mutex(&loader_preload_icd_lock);
2350
2351
    // Already preloaded, skip loading again.
2352
0
    if (preloaded_icds.scanned_list != NULL) {
2353
0
        loader_platform_thread_unlock_mutex(&loader_preload_icd_lock);
2354
0
        return;
2355
0
    }
2356
2357
0
    VkResult result = loader_icd_scan(NULL, &preloaded_icds, NULL, NULL);
2358
0
    if (result != VK_SUCCESS) {
2359
0
        loader_clear_scanned_icd_list(NULL, &preloaded_icds);
2360
0
    }
2361
0
    loader_platform_thread_unlock_mutex(&loader_preload_icd_lock);
2362
0
}
2363
2364
// Release the ICD libraries that were preloaded
2365
0
void loader_unload_preloaded_icds(void) {
2366
0
    loader_platform_thread_lock_mutex(&loader_preload_icd_lock);
2367
0
    loader_clear_scanned_icd_list(NULL, &preloaded_icds);
2368
0
    loader_platform_thread_unlock_mutex(&loader_preload_icd_lock);
2369
0
}
2370
2371
#if !defined(_WIN32)
2372
2
__attribute__((constructor)) void loader_init_library(void) { loader_initialize(); }
2373
2374
0
__attribute__((destructor)) void loader_free_library(void) { loader_release(); }
2375
#endif
2376
2377
// Get next file or dirname given a string list or registry key path
2378
//
2379
// \returns
2380
// A pointer to first char in the next path.
2381
// The next path (or NULL) in the list is returned in next_path.
2382
// Note: input string is modified in some cases. PASS IN A COPY!
2383
0
char *loader_get_next_path(char *path) {
2384
0
    uint32_t len;
2385
0
    char *next;
2386
2387
0
    if (path == NULL) return NULL;
2388
0
    next = strchr(path, PATH_SEPARATOR);
2389
0
    if (next == NULL) {
2390
0
        len = (uint32_t)strlen(path);
2391
0
        next = path + len;
2392
0
    } else {
2393
0
        *next = '\0';
2394
0
        next++;
2395
0
    }
2396
2397
0
    return next;
2398
0
}
2399
2400
/* Processes a json manifest's library_path and the location of the json manifest to create the path of the library
2401
 * The output is stored in out_fullpath by allocating a string - so its the caller's responsibility to free it
2402
 * The output is the combination of the base path of manifest_file_path concatenated with library path
2403
 * If library_path is an absolute path, we do not prepend the base path of manifest_file_path
2404
 *
2405
 * This function takes ownership of library_path - caller does not need to worry about freeing it.
2406
 */
2407
VkResult combine_manifest_directory_and_library_path(const struct loader_instance *inst, char *library_path,
2408
0
                                                     const char *manifest_file_path, char **out_fullpath) {
2409
0
    assert(library_path && manifest_file_path && out_fullpath);
2410
0
    if (loader_platform_is_path_absolute(library_path)) {
2411
0
        *out_fullpath = library_path;
2412
0
        return VK_SUCCESS;
2413
0
    }
2414
0
    VkResult res = VK_SUCCESS;
2415
2416
0
    size_t library_path_len = strlen(library_path);
2417
0
    size_t manifest_file_path_str_len = strlen(manifest_file_path);
2418
0
    bool library_path_contains_directory_symbol = false;
2419
0
    for (size_t i = 0; i < library_path_len; i++) {
2420
0
        if (library_path[i] == DIRECTORY_SYMBOL) {
2421
0
            library_path_contains_directory_symbol = true;
2422
0
            break;
2423
0
        }
2424
0
    }
2425
    // Means that the library_path is neither absolute nor relative - thus we should not modify it at all
2426
0
    if (!library_path_contains_directory_symbol) {
2427
0
        *out_fullpath = library_path;
2428
0
        return VK_SUCCESS;
2429
0
    }
2430
    // must include both a directory symbol and the null terminator
2431
0
    size_t new_str_len = library_path_len + manifest_file_path_str_len + 1 + 1;
2432
2433
0
    *out_fullpath = loader_instance_heap_calloc(inst, new_str_len, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
2434
0
    if (NULL == *out_fullpath) {
2435
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
2436
0
        goto out;
2437
0
    }
2438
0
    size_t cur_loc_in_out_fullpath = 0;
2439
    // look for the last occurrence of DIRECTORY_SYMBOL in manifest_file_path
2440
0
    size_t last_directory_symbol = 0;
2441
0
    bool found_directory_symbol = false;
2442
0
    for (size_t i = 0; i < manifest_file_path_str_len; i++) {
2443
0
        if (manifest_file_path[i] == DIRECTORY_SYMBOL) {
2444
0
            last_directory_symbol = i + 1;  // we want to include the symbol
2445
0
            found_directory_symbol = true;
2446
            // dont break because we want to find the last occurrence
2447
0
        }
2448
0
    }
2449
    // Add manifest_file_path up to the last directory symbol
2450
0
    if (found_directory_symbol) {
2451
0
        loader_strncpy(*out_fullpath, new_str_len, manifest_file_path, last_directory_symbol);
2452
0
        cur_loc_in_out_fullpath += last_directory_symbol;
2453
0
    }
2454
0
    loader_strncpy(&(*out_fullpath)[cur_loc_in_out_fullpath], new_str_len - cur_loc_in_out_fullpath, library_path,
2455
0
                   library_path_len);
2456
0
    cur_loc_in_out_fullpath += library_path_len + 1;
2457
0
    (*out_fullpath)[cur_loc_in_out_fullpath] = '\0';
2458
2459
0
out:
2460
0
    loader_instance_heap_free(inst, library_path);
2461
2462
0
    return res;
2463
0
}
2464
2465
// Given a filename (file)  and a list of paths (in_dirs), try to find an existing
2466
// file in the paths.  If filename already is a path then no searching in the given paths.
2467
//
2468
// @return - A string in out_fullpath of either the full path or file.
2469
0
void loader_get_fullpath(const char *file, const char *in_dirs, size_t out_size, char *out_fullpath) {
2470
0
    if (!loader_platform_is_path(file) && *in_dirs) {
2471
0
        size_t dirs_copy_len = strlen(in_dirs) + 1;
2472
0
        char *dirs_copy = loader_stack_alloc(dirs_copy_len);
2473
0
        loader_strncpy(dirs_copy, dirs_copy_len, in_dirs, dirs_copy_len);
2474
2475
        // find if file exists after prepending paths in given list
2476
        // for (dir = dirs_copy; *dir && (next_dir = loader_get_next_path(dir)); dir = next_dir) {
2477
0
        char *dir = dirs_copy;
2478
0
        char *next_dir = loader_get_next_path(dir);
2479
0
        while (*dir && next_dir) {
2480
0
            int path_concat_ret = snprintf(out_fullpath, out_size, "%s%c%s", dir, DIRECTORY_SYMBOL, file);
2481
0
            if (path_concat_ret < 0) {
2482
0
                continue;
2483
0
            }
2484
0
            if (loader_platform_file_exists(out_fullpath)) {
2485
0
                return;
2486
0
            }
2487
0
            dir = next_dir;
2488
0
            next_dir = loader_get_next_path(dir);
2489
0
        }
2490
0
    }
2491
2492
0
    (void)snprintf(out_fullpath, out_size, "%s", file);
2493
0
}
2494
2495
// Verify that all component layers in a meta-layer are valid.
2496
// This function is potentially recursive so we pass in an array of "already checked" (length of the instance_layers->count) meta
2497
// layers, preventing a stack overflow verifying  meta layers that are each other's component layers
2498
bool verify_meta_layer_component_layers(const struct loader_instance *inst, size_t prop_index,
2499
0
                                        struct loader_layer_list *instance_layers, bool *already_checked_meta_layers) {
2500
0
    struct loader_layer_properties *prop = &instance_layers->list[prop_index];
2501
0
    loader_api_version meta_layer_version = loader_make_version(prop->info.specVersion);
2502
2503
0
    if (NULL == already_checked_meta_layers) {
2504
0
        already_checked_meta_layers = loader_stack_alloc(sizeof(bool) * instance_layers->count);
2505
0
        if (already_checked_meta_layers == NULL) {
2506
0
            return false;
2507
0
        }
2508
0
        memset(already_checked_meta_layers, 0, sizeof(bool) * instance_layers->count);
2509
0
    }
2510
2511
    // Mark this meta layer as 'already checked', indicating which layers have already been recursed.
2512
0
    already_checked_meta_layers[prop_index] = true;
2513
2514
0
    for (uint32_t comp_layer = 0; comp_layer < prop->component_layer_names.count; comp_layer++) {
2515
0
        struct loader_layer_properties *comp_prop =
2516
0
            loader_find_layer_property(prop->component_layer_names.list[comp_layer], instance_layers);
2517
0
        if (comp_prop == NULL) {
2518
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2519
0
                       "verify_meta_layer_component_layers: Meta-layer %s can't find component layer %s at index %d."
2520
0
                       "  Skipping this layer.",
2521
0
                       prop->info.layerName, prop->component_layer_names.list[comp_layer], comp_layer);
2522
2523
0
            return false;
2524
0
        }
2525
2526
        // Check the version of each layer, they need to be at least MAJOR and MINOR
2527
0
        loader_api_version comp_prop_version = loader_make_version(comp_prop->info.specVersion);
2528
0
        if (!loader_check_version_meets_required(meta_layer_version, comp_prop_version)) {
2529
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2530
0
                       "verify_meta_layer_component_layers: Meta-layer uses API version %d.%d, but component "
2531
0
                       "layer %d has API version %d.%d that is lower.  Skipping this layer.",
2532
0
                       meta_layer_version.major, meta_layer_version.minor, comp_layer, comp_prop_version.major,
2533
0
                       comp_prop_version.minor);
2534
2535
0
            return false;
2536
0
        }
2537
2538
        // Make sure the layer isn't using it's own name
2539
0
        if (!strcmp(prop->info.layerName, prop->component_layer_names.list[comp_layer])) {
2540
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2541
0
                       "verify_meta_layer_component_layers: Meta-layer %s lists itself in its component layer "
2542
0
                       "list at index %d.  Skipping this layer.",
2543
0
                       prop->info.layerName, comp_layer);
2544
2545
0
            return false;
2546
0
        }
2547
0
        if (comp_prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
2548
0
            size_t comp_prop_index = INT32_MAX;
2549
            // Make sure we haven't verified this meta layer before
2550
0
            for (uint32_t i = 0; i < instance_layers->count; i++) {
2551
0
                if (strcmp(comp_prop->info.layerName, instance_layers->list[i].info.layerName) == 0) {
2552
0
                    comp_prop_index = i;
2553
0
                }
2554
0
            }
2555
0
            if (comp_prop_index != INT32_MAX && already_checked_meta_layers[comp_prop_index]) {
2556
0
                loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2557
0
                           "verify_meta_layer_component_layers: Recursive dependency between Meta-layer %s and  Meta-layer %s.  "
2558
0
                           "Skipping this layer.",
2559
0
                           instance_layers->list[prop_index].info.layerName, comp_prop->info.layerName);
2560
0
                return false;
2561
0
            }
2562
2563
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
2564
0
                       "verify_meta_layer_component_layers: Adding meta-layer %s which also contains meta-layer %s",
2565
0
                       prop->info.layerName, comp_prop->info.layerName);
2566
2567
            // Make sure if the layer is using a meta-layer in its component list that we also verify that.
2568
0
            if (!verify_meta_layer_component_layers(inst, comp_prop_index, instance_layers, already_checked_meta_layers)) {
2569
0
                loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2570
0
                           "Meta-layer %s component layer %s can not find all component layers."
2571
0
                           "  Skipping this layer.",
2572
0
                           prop->info.layerName, prop->component_layer_names.list[comp_layer]);
2573
0
                return false;
2574
0
            }
2575
0
        }
2576
0
    }
2577
    // Didn't exit early so that means it passed all checks
2578
0
    loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0,
2579
0
               "Meta-layer \"%s\" all %d component layers appear to be valid.", prop->info.layerName,
2580
0
               prop->component_layer_names.count);
2581
2582
    // If layer logging is on, list the internals included in the meta-layer
2583
0
    for (uint32_t comp_layer = 0; comp_layer < prop->component_layer_names.count; comp_layer++) {
2584
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "  [%d] %s", comp_layer, prop->component_layer_names.list[comp_layer]);
2585
0
    }
2586
0
    return true;
2587
0
}
2588
2589
// Add any instance and device extensions from component layers to this layer
2590
// list, so that anyone querying extensions will only need to look at the meta-layer
2591
bool update_meta_layer_extensions_from_component_layers(const struct loader_instance *inst, struct loader_layer_properties *prop,
2592
0
                                                        struct loader_layer_list *instance_layers) {
2593
0
    VkResult res = VK_SUCCESS;
2594
0
    for (uint32_t comp_layer = 0; comp_layer < prop->component_layer_names.count; comp_layer++) {
2595
0
        struct loader_layer_properties *comp_prop =
2596
0
            loader_find_layer_property(prop->component_layer_names.list[comp_layer], instance_layers);
2597
2598
0
        if (NULL != comp_prop->instance_extension_list.list) {
2599
0
            for (uint32_t ext = 0; ext < comp_prop->instance_extension_list.count; ext++) {
2600
0
                loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0, "Meta-layer %s component layer %s adding instance extension %s",
2601
0
                           prop->info.layerName, prop->component_layer_names.list[comp_layer],
2602
0
                           comp_prop->instance_extension_list.list[ext].extensionName);
2603
2604
0
                if (!has_vk_extension_property(&comp_prop->instance_extension_list.list[ext], &prop->instance_extension_list)) {
2605
0
                    res = loader_add_to_ext_list(inst, &prop->instance_extension_list, 1,
2606
0
                                                 &comp_prop->instance_extension_list.list[ext]);
2607
0
                    if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
2608
0
                        return res;
2609
0
                    }
2610
0
                }
2611
0
            }
2612
0
        }
2613
0
        if (NULL != comp_prop->device_extension_list.list) {
2614
0
            for (uint32_t ext = 0; ext < comp_prop->device_extension_list.count; ext++) {
2615
0
                loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0, "Meta-layer %s component layer %s adding device extension %s",
2616
0
                           prop->info.layerName, prop->component_layer_names.list[comp_layer],
2617
0
                           comp_prop->device_extension_list.list[ext].props.extensionName);
2618
2619
0
                if (!has_vk_dev_ext_property(&comp_prop->device_extension_list.list[ext].props, &prop->device_extension_list)) {
2620
0
                    loader_add_to_dev_ext_list(inst, &prop->device_extension_list,
2621
0
                                               &comp_prop->device_extension_list.list[ext].props, NULL);
2622
0
                    if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
2623
0
                        return res;
2624
0
                    }
2625
0
                }
2626
0
            }
2627
0
        }
2628
0
    }
2629
0
    return res;
2630
0
}
2631
2632
// Verify that all meta-layers in a layer list are valid.
2633
VkResult verify_all_meta_layers(struct loader_instance *inst, const struct loader_envvar_all_filters *filters,
2634
0
                                struct loader_layer_list *instance_layers, bool *override_layer_present) {
2635
0
    VkResult res = VK_SUCCESS;
2636
0
    *override_layer_present = false;
2637
0
    for (int32_t i = 0; i < (int32_t)instance_layers->count; i++) {
2638
0
        struct loader_layer_properties *prop = &instance_layers->list[i];
2639
2640
        // If this is a meta-layer, make sure it is valid
2641
0
        if (prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
2642
0
            if (verify_meta_layer_component_layers(inst, i, instance_layers, NULL)) {
2643
                // If any meta layer is valid, update its extension list to include the extensions from its component layers.
2644
0
                res = update_meta_layer_extensions_from_component_layers(inst, prop, instance_layers);
2645
0
                if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
2646
0
                    return res;
2647
0
                }
2648
0
                if (prop->is_override && loader_implicit_layer_is_enabled(inst, filters, prop)) {
2649
0
                    *override_layer_present = true;
2650
0
                }
2651
0
            } else {
2652
0
                loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
2653
0
                           "Removing meta-layer %s from instance layer list since it appears invalid.", prop->info.layerName);
2654
2655
0
                loader_remove_layer_in_list(inst, instance_layers, i);
2656
0
                i--;
2657
0
            }
2658
0
        }
2659
0
    }
2660
0
    return res;
2661
0
}
2662
2663
// If the current working directory matches any app_key_path of the layers, remove all other override layers.
2664
// Otherwise if no matching app_key was found, remove all but the global override layer, which has no app_key_path.
2665
0
void remove_all_non_valid_override_layers(struct loader_instance *inst, struct loader_layer_list *instance_layers) {
2666
0
    if (instance_layers == NULL) {
2667
0
        return;
2668
0
    }
2669
2670
0
    char cur_path[1024];
2671
0
    char *ret = loader_platform_executable_path(cur_path, 1024);
2672
0
    if (NULL == ret) {
2673
0
        return;
2674
0
    }
2675
    // Find out if there is an override layer with same the app_key_path as the path to the current executable.
2676
    // If more than one is found, remove it and use the first layer
2677
    // Remove any layers which aren't global and do not have the same app_key_path as the path to the current executable.
2678
0
    bool found_active_override_layer = false;
2679
0
    int global_layer_index = -1;
2680
0
    for (uint32_t i = 0; i < instance_layers->count; i++) {
2681
0
        struct loader_layer_properties *props = &instance_layers->list[i];
2682
0
        if (strcmp(props->info.layerName, VK_OVERRIDE_LAYER_NAME) == 0) {
2683
0
            if (props->app_key_paths.count > 0) {  // not the global layer
2684
0
                for (uint32_t j = 0; j < props->app_key_paths.count; j++) {
2685
0
                    if (strcmp(props->app_key_paths.list[j], cur_path) == 0) {
2686
0
                        if (!found_active_override_layer) {
2687
0
                            found_active_override_layer = true;
2688
0
                        } else {
2689
0
                            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
2690
0
                                       "remove_all_non_valid_override_layers: Multiple override layers where the same path in "
2691
0
                                       "app_keys "
2692
0
                                       "was found. Using the first layer found");
2693
2694
                            // Remove duplicate active override layers that have the same app_key_path
2695
0
                            loader_remove_layer_in_list(inst, instance_layers, i);
2696
0
                            i--;
2697
0
                        }
2698
0
                    }
2699
0
                }
2700
0
                if (!found_active_override_layer) {
2701
0
                    loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0,
2702
0
                               "--Override layer found but not used because app \'%s\' is not in \'app_keys\' list!", cur_path);
2703
2704
                    // Remove non-global override layers that don't have an app_key that matches cur_path
2705
0
                    loader_remove_layer_in_list(inst, instance_layers, i);
2706
0
                    i--;
2707
0
                }
2708
0
            } else {
2709
0
                if (global_layer_index == -1) {
2710
0
                    global_layer_index = i;
2711
0
                } else {
2712
0
                    loader_log(
2713
0
                        inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
2714
0
                        "remove_all_non_valid_override_layers: Multiple global override layers found. Using the first global "
2715
0
                        "layer found");
2716
0
                    loader_remove_layer_in_list(inst, instance_layers, i);
2717
0
                    i--;
2718
0
                }
2719
0
            }
2720
0
        }
2721
0
    }
2722
    // Remove global layer if layer with same the app_key_path as the path to the current executable is found
2723
0
    if (found_active_override_layer && global_layer_index >= 0) {
2724
0
        loader_remove_layer_in_list(inst, instance_layers, global_layer_index);
2725
0
    }
2726
    // Should be at most 1 override layer in the list now.
2727
0
    if (found_active_override_layer) {
2728
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Using the override layer for app key %s", cur_path);
2729
0
    } else if (global_layer_index >= 0) {
2730
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Using the global override layer");
2731
0
    }
2732
0
}
2733
2734
/* The following are required in the "layer" object:
2735
 * "name"
2736
 * "type"
2737
 * (for non-meta layers) "library_path"
2738
 * (for meta layers) "component_layers"
2739
 * "api_version"
2740
 * "implementation_version"
2741
 * "description"
2742
 * (for implicit layers) "disable_environment"
2743
 */
2744
2745
VkResult loader_read_layer_json(const struct loader_instance *inst, struct loader_layer_list *layer_instance_list,
2746
0
                                cJSON *layer_node, loader_api_version version, bool is_implicit, char *filename) {
2747
0
    assert(layer_instance_list);
2748
0
    char *library_path = NULL;
2749
0
    VkResult result = VK_SUCCESS;
2750
0
    struct loader_layer_properties props = {0};
2751
2752
0
    result = loader_copy_to_new_str(inst, filename, &props.manifest_file_name);
2753
0
    if (result == VK_ERROR_OUT_OF_HOST_MEMORY) {
2754
0
        goto out;
2755
0
    }
2756
2757
    // Parse name
2758
2759
0
    result = loader_parse_json_string_to_existing_str(layer_node, "name", VK_MAX_EXTENSION_NAME_SIZE, props.info.layerName);
2760
0
    if (VK_ERROR_INITIALIZATION_FAILED == result) {
2761
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2762
0
                   "Layer located at %s didn't find required layer value \"name\" in manifest JSON file, skipping this layer",
2763
0
                   filename);
2764
0
        goto out;
2765
0
    }
2766
2767
    // Check if this layer's name matches the override layer name, set is_override to true if so.
2768
0
    if (!strcmp(props.info.layerName, VK_OVERRIDE_LAYER_NAME)) {
2769
0
        props.is_override = true;
2770
0
    }
2771
2772
0
    if (0 != strncmp(props.info.layerName, "VK_LAYER_", 9)) {
2773
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0, "Layer name %s does not conform to naming standard (Policy #LLP_LAYER_3)",
2774
0
                   props.info.layerName);
2775
0
    }
2776
2777
    // Parse type
2778
0
    char *type = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(layer_node, "type"));
2779
0
    if (NULL == type) {
2780
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2781
0
                   "Layer located at %s didn't find required layer value \"type\" in manifest JSON file, skipping this layer",
2782
0
                   filename);
2783
0
        result = VK_ERROR_INITIALIZATION_FAILED;
2784
0
        goto out;
2785
0
    }
2786
2787
    // Add list entry
2788
0
    if (!strcmp(type, "DEVICE")) {
2789
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Device layers are deprecated. Skipping layer %s",
2790
0
                   props.info.layerName);
2791
0
        result = VK_ERROR_INITIALIZATION_FAILED;
2792
0
        goto out;
2793
0
    }
2794
2795
    // Allow either GLOBAL or INSTANCE type interchangeably to handle layers that must work with older loaders
2796
0
    if (!strcmp(type, "INSTANCE") || !strcmp(type, "GLOBAL")) {
2797
0
        props.type_flags = VK_LAYER_TYPE_FLAG_INSTANCE_LAYER;
2798
0
        if (!is_implicit) {
2799
0
            props.type_flags |= VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER;
2800
0
        }
2801
0
    } else {
2802
0
        result = VK_ERROR_INITIALIZATION_FAILED;
2803
0
        goto out;
2804
0
    }
2805
2806
    // Parse api_version
2807
0
    char *api_version = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(layer_node, "api_version"));
2808
0
    if (NULL == api_version) {
2809
0
        loader_log(
2810
0
            inst, VULKAN_LOADER_WARN_BIT, 0,
2811
0
            "Layer located at %s didn't find required layer value \"api_version\" in manifest JSON file, skipping this layer",
2812
0
            filename);
2813
0
        goto out;
2814
0
    }
2815
2816
0
    props.info.specVersion = loader_parse_version_string(api_version);
2817
2818
    // Make sure the layer's manifest doesn't contain a non zero variant value
2819
0
    if (VK_API_VERSION_VARIANT(props.info.specVersion) != 0) {
2820
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0,
2821
0
                   "Layer \"%s\" has an \'api_version\' field which contains a non-zero variant value of %d. "
2822
0
                   " Skipping Layer.",
2823
0
                   props.info.layerName, VK_API_VERSION_VARIANT(props.info.specVersion));
2824
0
        result = VK_ERROR_INITIALIZATION_FAILED;
2825
0
        goto out;
2826
0
    }
2827
2828
    // Parse implementation_version
2829
0
    char *implementation_version = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(layer_node, "implementation_version"));
2830
0
    if (NULL == implementation_version) {
2831
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2832
0
                   "Layer located at %s didn't find required layer value \"implementation_version\" in manifest JSON file, "
2833
0
                   "skipping this layer",
2834
0
                   filename);
2835
0
        goto out;
2836
0
    }
2837
0
    props.info.implementationVersion = atoi(implementation_version);
2838
2839
    // Parse description
2840
2841
0
    result =
2842
0
        loader_parse_json_string_to_existing_str(layer_node, "description", VK_MAX_EXTENSION_NAME_SIZE, props.info.description);
2843
0
    if (VK_ERROR_INITIALIZATION_FAILED == result) {
2844
0
        loader_log(
2845
0
            inst, VULKAN_LOADER_WARN_BIT, 0,
2846
0
            "Layer located at %s didn't find required layer value \"description\" in manifest JSON file, skipping this layer",
2847
0
            filename);
2848
0
        goto out;
2849
0
    }
2850
2851
    // Parse library_path
2852
2853
    // Library path no longer required unless component_layers is also not defined
2854
0
    result = loader_parse_json_string(layer_node, "library_path", &library_path);
2855
0
    if (result == VK_ERROR_OUT_OF_HOST_MEMORY) {
2856
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2857
0
                   "Skipping layer \"%s\" due to problem accessing the library_path value in the manifest JSON file",
2858
0
                   props.info.layerName);
2859
0
        result = VK_ERROR_OUT_OF_HOST_MEMORY;
2860
0
        goto out;
2861
0
    }
2862
0
    if (NULL != library_path) {
2863
0
        if (NULL != loader_cJSON_GetObjectItem(layer_node, "component_layers")) {
2864
0
            loader_log(
2865
0
                inst, VULKAN_LOADER_WARN_BIT, 0,
2866
0
                "Layer \"%s\" contains meta-layer-specific component_layers, but also defining layer library path.  Both are not "
2867
0
                "compatible, so skipping this layer",
2868
0
                props.info.layerName);
2869
0
            result = VK_ERROR_INITIALIZATION_FAILED;
2870
0
            loader_instance_heap_free(inst, library_path);
2871
0
            goto out;
2872
0
        }
2873
2874
        // This function takes ownership of library_path_str - so we don't need to clean it up
2875
0
        result = combine_manifest_directory_and_library_path(inst, library_path, filename, &props.lib_name);
2876
0
        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
2877
0
    }
2878
2879
    // Parse component_layers
2880
2881
0
    if (NULL == library_path) {
2882
0
        if (!loader_check_version_meets_required(LOADER_VERSION_1_1_0, version)) {
2883
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2884
0
                       "Layer \"%s\" contains meta-layer-specific component_layers, but using older JSON file version.",
2885
0
                       props.info.layerName);
2886
0
        }
2887
2888
0
        result = loader_parse_json_array_of_strings(inst, layer_node, "component_layers", &(props.component_layer_names));
2889
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == result) {
2890
0
            goto out;
2891
0
        }
2892
0
        if (VK_ERROR_INITIALIZATION_FAILED == result) {
2893
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2894
0
                       "Layer \"%s\" is missing both library_path and component_layers fields.  One or the other MUST be defined.  "
2895
0
                       "Skipping this layer",
2896
0
                       props.info.layerName);
2897
0
            goto out;
2898
0
        }
2899
        // This is now, officially, a meta-layer
2900
0
        props.type_flags |= VK_LAYER_TYPE_FLAG_META_LAYER;
2901
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Encountered meta-layer \"%s\"",
2902
0
                   props.info.layerName);
2903
0
    }
2904
2905
    // Parse blacklisted_layers
2906
2907
0
    if (props.is_override) {
2908
0
        result = loader_parse_json_array_of_strings(inst, layer_node, "blacklisted_layers", &(props.blacklist_layer_names));
2909
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == result) {
2910
0
            goto out;
2911
0
        }
2912
0
    }
2913
2914
    // Parse override_paths
2915
2916
0
    result = loader_parse_json_array_of_strings(inst, layer_node, "override_paths", &(props.override_paths));
2917
0
    if (VK_ERROR_OUT_OF_HOST_MEMORY == result) {
2918
0
        goto out;
2919
0
    }
2920
0
    if (NULL != props.override_paths.list && !loader_check_version_meets_required(loader_combine_version(1, 1, 0), version)) {
2921
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2922
0
                   "Layer \"%s\" contains meta-layer-specific override paths, but using older JSON file version.",
2923
0
                   props.info.layerName);
2924
0
    }
2925
2926
    // Parse disable_environment
2927
2928
0
    if (is_implicit) {
2929
0
        cJSON *disable_environment = loader_cJSON_GetObjectItem(layer_node, "disable_environment");
2930
0
        if (disable_environment == NULL) {
2931
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2932
0
                       "Layer \"%s\" doesn't contain required layer object disable_environment in the manifest JSON file, skipping "
2933
0
                       "this layer",
2934
0
                       props.info.layerName);
2935
0
            result = VK_ERROR_INITIALIZATION_FAILED;
2936
0
            goto out;
2937
0
        }
2938
2939
0
        if (!disable_environment->child || disable_environment->child->type != cJSON_String ||
2940
0
            !disable_environment->child->string || !disable_environment->child->valuestring) {
2941
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2942
0
                       "Layer \"%s\" doesn't contain required child value in object disable_environment in the manifest JSON file, "
2943
0
                       "skipping this layer (Policy #LLP_LAYER_9)",
2944
0
                       props.info.layerName);
2945
0
            result = VK_ERROR_INITIALIZATION_FAILED;
2946
0
            goto out;
2947
0
        }
2948
0
        result = loader_copy_to_new_str(inst, disable_environment->child->string, &(props.disable_env_var.name));
2949
0
        if (VK_SUCCESS != result) goto out;
2950
0
        result = loader_copy_to_new_str(inst, disable_environment->child->valuestring, &(props.disable_env_var.value));
2951
0
        if (VK_SUCCESS != result) goto out;
2952
0
    }
2953
2954
    // Now get all optional items and objects and put in list:
2955
    // functions
2956
    // instance_extensions
2957
    // device_extensions
2958
    // enable_environment (implicit layers only)
2959
    // library_arch
2960
2961
    // Layer interface functions
2962
    //    vkGetInstanceProcAddr
2963
    //    vkGetDeviceProcAddr
2964
    //    vkNegotiateLoaderLayerInterfaceVersion (starting with JSON file 1.1.0)
2965
0
    cJSON *functions = loader_cJSON_GetObjectItem(layer_node, "functions");
2966
0
    if (functions != NULL) {
2967
0
        if (loader_check_version_meets_required(loader_combine_version(1, 1, 0), version)) {
2968
0
            result = loader_parse_json_string(functions, "vkNegotiateLoaderLayerInterfaceVersion",
2969
0
                                              &props.functions.str_negotiate_interface);
2970
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
2971
0
        }
2972
0
        result = loader_parse_json_string(functions, "vkGetInstanceProcAddr", &props.functions.str_gipa);
2973
0
        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
2974
2975
0
        if (NULL == props.functions.str_negotiate_interface && props.functions.str_gipa &&
2976
0
            loader_check_version_meets_required(loader_combine_version(1, 1, 0), version)) {
2977
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
2978
0
                       "Layer \"%s\" using deprecated \'vkGetInstanceProcAddr\' tag which was deprecated starting with JSON "
2979
0
                       "file version 1.1.0. The new vkNegotiateLoaderLayerInterfaceVersion function is preferred, though for "
2980
0
                       "compatibility reasons it may be desirable to continue using the deprecated tag.",
2981
0
                       props.info.layerName);
2982
0
        }
2983
2984
0
        result = loader_parse_json_string(functions, "vkGetDeviceProcAddr", &props.functions.str_gdpa);
2985
0
        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
2986
2987
0
        if (NULL == props.functions.str_negotiate_interface && props.functions.str_gdpa &&
2988
0
            loader_check_version_meets_required(loader_combine_version(1, 1, 0), version)) {
2989
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
2990
0
                       "Layer \"%s\" using deprecated \'vkGetDeviceProcAddr\' tag which was deprecated starting with JSON "
2991
0
                       "file version 1.1.0. The new vkNegotiateLoaderLayerInterfaceVersion function is preferred, though for "
2992
0
                       "compatibility reasons it may be desirable to continue using the deprecated tag.",
2993
0
                       props.info.layerName);
2994
0
        }
2995
0
    }
2996
2997
    // instance_extensions
2998
    //   array of {
2999
    //     name
3000
    //     spec_version
3001
    //   }
3002
3003
0
    cJSON *instance_extensions = loader_cJSON_GetObjectItem(layer_node, "instance_extensions");
3004
0
    if (instance_extensions != NULL && instance_extensions->type == cJSON_Array) {
3005
0
        cJSON *ext_item = NULL;
3006
0
        cJSON_ArrayForEach(ext_item, instance_extensions) {
3007
0
            if (ext_item->type != cJSON_Object) {
3008
0
                continue;
3009
0
            }
3010
3011
0
            VkExtensionProperties ext_prop = {0};
3012
0
            result = loader_parse_json_string_to_existing_str(ext_item, "name", VK_MAX_EXTENSION_NAME_SIZE, ext_prop.extensionName);
3013
0
            if (result == VK_ERROR_INITIALIZATION_FAILED) {
3014
0
                continue;
3015
0
            }
3016
0
            char *spec_version = NULL;
3017
0
            result = loader_parse_json_string(ext_item, "spec_version", &spec_version);
3018
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3019
0
            if (NULL != spec_version) {
3020
0
                ext_prop.specVersion = atoi(spec_version);
3021
0
            }
3022
0
            loader_instance_heap_free(inst, spec_version);
3023
0
            bool ext_unsupported = wsi_unsupported_instance_extension(&ext_prop);
3024
0
            if (!ext_unsupported) {
3025
0
                loader_add_to_ext_list(inst, &props.instance_extension_list, 1, &ext_prop);
3026
0
            }
3027
0
        }
3028
0
    }
3029
3030
    // device_extensions
3031
    //   array of {
3032
    //     name
3033
    //     spec_version
3034
    //     entrypoints
3035
    //   }
3036
0
    cJSON *device_extensions = loader_cJSON_GetObjectItem(layer_node, "device_extensions");
3037
0
    if (device_extensions != NULL && device_extensions->type == cJSON_Array) {
3038
0
        cJSON *ext_item = NULL;
3039
0
        cJSON_ArrayForEach(ext_item, device_extensions) {
3040
0
            if (ext_item->type != cJSON_Object) {
3041
0
                continue;
3042
0
            }
3043
3044
0
            VkExtensionProperties ext_prop = {0};
3045
0
            result = loader_parse_json_string_to_existing_str(ext_item, "name", VK_MAX_EXTENSION_NAME_SIZE, ext_prop.extensionName);
3046
0
            if (result == VK_ERROR_INITIALIZATION_FAILED) {
3047
0
                continue;
3048
0
            }
3049
3050
0
            char *spec_version = NULL;
3051
0
            result = loader_parse_json_string(ext_item, "spec_version", &spec_version);
3052
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3053
0
            if (NULL != spec_version) {
3054
0
                ext_prop.specVersion = atoi(spec_version);
3055
0
            }
3056
0
            loader_instance_heap_free(inst, spec_version);
3057
3058
0
            cJSON *entrypoints = loader_cJSON_GetObjectItem(ext_item, "entrypoints");
3059
0
            if (entrypoints == NULL) {
3060
0
                result = loader_add_to_dev_ext_list(inst, &props.device_extension_list, &ext_prop, NULL);
3061
0
                if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3062
0
                continue;
3063
0
            }
3064
3065
0
            struct loader_string_list entrys = {0};
3066
0
            result = loader_parse_json_array_of_strings(inst, ext_item, "entrypoints", &entrys);
3067
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3068
0
            result = loader_add_to_dev_ext_list(inst, &props.device_extension_list, &ext_prop, &entrys);
3069
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3070
0
        }
3071
0
    }
3072
0
    if (is_implicit) {
3073
0
        cJSON *enable_environment = loader_cJSON_GetObjectItem(layer_node, "enable_environment");
3074
3075
        // enable_environment is optional
3076
0
        if (enable_environment && enable_environment->child && enable_environment->child->type == cJSON_String &&
3077
0
            enable_environment->child->string && enable_environment->child->valuestring) {
3078
0
            result = loader_copy_to_new_str(inst, enable_environment->child->string, &(props.enable_env_var.name));
3079
0
            if (VK_SUCCESS != result) goto out;
3080
0
            result = loader_copy_to_new_str(inst, enable_environment->child->valuestring, &(props.enable_env_var.value));
3081
0
            if (VK_SUCCESS != result) goto out;
3082
0
        }
3083
0
    }
3084
3085
    // Read in the pre-instance stuff
3086
0
    cJSON *pre_instance = loader_cJSON_GetObjectItem(layer_node, "pre_instance_functions");
3087
0
    if (NULL != pre_instance) {
3088
        // Supported versions started in 1.1.2, so anything newer
3089
0
        if (!loader_check_version_meets_required(loader_combine_version(1, 1, 2), version)) {
3090
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
3091
0
                       "Found pre_instance_functions section in layer from \"%s\". This section is only valid in manifest version "
3092
0
                       "1.1.2 or later. The section will be ignored",
3093
0
                       filename);
3094
0
        } else if (!is_implicit) {
3095
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
3096
0
                       "Found pre_instance_functions section in explicit layer from \"%s\". This section is only valid in implicit "
3097
0
                       "layers. The section will be ignored",
3098
0
                       filename);
3099
0
        } else {
3100
0
            result = loader_parse_json_string(pre_instance, "vkEnumerateInstanceExtensionProperties",
3101
0
                                              &props.pre_instance_functions.enumerate_instance_extension_properties);
3102
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3103
3104
0
            result = loader_parse_json_string(pre_instance, "vkEnumerateInstanceLayerProperties",
3105
0
                                              &props.pre_instance_functions.enumerate_instance_layer_properties);
3106
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3107
3108
0
            result = loader_parse_json_string(pre_instance, "vkEnumerateInstanceVersion",
3109
0
                                              &props.pre_instance_functions.enumerate_instance_version);
3110
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3111
0
        }
3112
0
    }
3113
3114
0
    if (loader_cJSON_GetObjectItem(layer_node, "app_keys")) {
3115
0
        if (!props.is_override) {
3116
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3117
0
                       "Layer %s contains app_keys, but any app_keys can only be provided by the override meta layer. "
3118
0
                       "These will be ignored.",
3119
0
                       props.info.layerName);
3120
0
        }
3121
3122
0
        result = loader_parse_json_array_of_strings(inst, layer_node, "app_keys", &props.app_key_paths);
3123
0
        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3124
0
    }
3125
3126
0
    char *library_arch = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(layer_node, "library_arch"));
3127
0
    if (NULL != library_arch) {
3128
0
        if ((strncmp(library_arch, "32", 2) == 0 && sizeof(void *) != 4) ||
3129
0
            (strncmp(library_arch, "64", 2) == 0 && sizeof(void *) != 8)) {
3130
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
3131
0
                       "The library architecture in layer %s doesn't match the current running architecture, skipping this layer",
3132
0
                       filename);
3133
0
            result = VK_ERROR_INITIALIZATION_FAILED;
3134
0
            goto out;
3135
0
        }
3136
0
    }
3137
3138
0
    result = VK_SUCCESS;
3139
3140
0
out:
3141
    // Try to append the layer property
3142
0
    if (VK_SUCCESS == result) {
3143
0
        result = loader_append_layer_property(inst, layer_instance_list, &props);
3144
0
    }
3145
    // If appending fails - free all the memory allocated in it
3146
0
    if (VK_SUCCESS != result) {
3147
0
        loader_free_layer_properties(inst, &props);
3148
0
    }
3149
0
    return result;
3150
0
}
3151
3152
0
bool is_valid_layer_json_version(const loader_api_version *layer_json) {
3153
    // Supported versions are: 1.0.0, 1.0.1, 1.1.0 - 1.1.2, and 1.2.0 - 1.2.1.
3154
0
    if ((layer_json->major == 1 && layer_json->minor == 2 && layer_json->patch < 2) ||
3155
0
        (layer_json->major == 1 && layer_json->minor == 1 && layer_json->patch < 3) ||
3156
0
        (layer_json->major == 1 && layer_json->minor == 0 && layer_json->patch < 2)) {
3157
0
        return true;
3158
0
    }
3159
0
    return false;
3160
0
}
3161
3162
// Given a cJSON struct (json) of the top level JSON object from layer manifest
3163
// file, add entry to the layer_list. Fill out the layer_properties in this list
3164
// entry from the input cJSON object.
3165
//
3166
// \returns
3167
// void
3168
// layer_list has a new entry and initialized accordingly.
3169
// If the json input object does not have all the required fields no entry
3170
// is added to the list.
3171
VkResult loader_add_layer_properties(const struct loader_instance *inst, struct loader_layer_list *layer_instance_list, cJSON *json,
3172
0
                                     bool is_implicit, char *filename) {
3173
    // The following Fields in layer manifest file that are required:
3174
    //   - "file_format_version"
3175
    //   - If more than one "layer" object are used, then the "layers" array is
3176
    //     required
3177
0
    VkResult result = VK_ERROR_INITIALIZATION_FAILED;
3178
    // Make sure sure the top level json value is an object
3179
0
    if (!json || json->type != cJSON_Object) {
3180
0
        goto out;
3181
0
    }
3182
0
    char *file_vers = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(json, "file_format_version"));
3183
0
    if (NULL == file_vers) {
3184
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3185
0
                   "loader_add_layer_properties: Manifest %s missing required field file_format_version", filename);
3186
0
        goto out;
3187
0
    }
3188
3189
0
    loader_log(inst, VULKAN_LOADER_INFO_BIT, 0, "Found manifest file %s (file version %s)", filename, file_vers);
3190
    // Get the major/minor/and patch as integers for easier comparison
3191
0
    loader_api_version json_version = loader_make_full_version(loader_parse_version_string(file_vers));
3192
3193
0
    if (!is_valid_layer_json_version(&json_version)) {
3194
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3195
0
                   "loader_add_layer_properties: %s has unknown layer manifest file version %d.%d.%d.  May cause errors.", filename,
3196
0
                   json_version.major, json_version.minor, json_version.patch);
3197
0
    }
3198
3199
    // If "layers" is present, read in the array of layer objects
3200
0
    cJSON *layers_node = loader_cJSON_GetObjectItem(json, "layers");
3201
0
    if (layers_node != NULL) {
3202
        // Supported versions started in 1.0.1, so anything newer
3203
0
        if (!loader_check_version_meets_required(loader_combine_version(1, 0, 1), json_version)) {
3204
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3205
0
                       "loader_add_layer_properties: \'layers\' tag not supported until file version 1.0.1, but %s is reporting "
3206
0
                       "version %s",
3207
0
                       filename, file_vers);
3208
0
        }
3209
0
        cJSON *layer_node = NULL;
3210
0
        cJSON_ArrayForEach(layer_node, layers_node) {
3211
0
            if (layer_node->type != cJSON_Object) {
3212
0
                loader_log(
3213
0
                    inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3214
0
                    "loader_add_layer_properties: Array element in \"layers\" field in manifest JSON file %s is not an object.  "
3215
0
                    "Skipping this file",
3216
0
                    filename);
3217
0
                goto out;
3218
0
            }
3219
0
            result = loader_read_layer_json(inst, layer_instance_list, layer_node, json_version, is_implicit, filename);
3220
0
        }
3221
0
    } else {
3222
        // Otherwise, try to read in individual layers
3223
0
        cJSON *layer_node = loader_cJSON_GetObjectItem(json, "layer");
3224
0
        if (layer_node == NULL) {
3225
            // Don't warn if this happens to be an ICD manifest
3226
0
            if (loader_cJSON_GetObjectItem(json, "ICD") == NULL) {
3227
0
                loader_log(
3228
0
                    inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3229
0
                    "loader_add_layer_properties: Can not find 'layer' object in manifest JSON file %s.  Skipping this file.",
3230
0
                    filename);
3231
0
            }
3232
0
            goto out;
3233
0
        }
3234
        // Loop through all "layer" objects in the file to get a count of them
3235
        // first.
3236
0
        uint16_t layer_count = 0;
3237
0
        cJSON *tempNode = layer_node;
3238
0
        do {
3239
0
            tempNode = tempNode->next;
3240
0
            layer_count++;
3241
0
        } while (tempNode != NULL);
3242
3243
        // Throw a warning if we encounter multiple "layer" objects in file
3244
        // versions newer than 1.0.0.  Having multiple objects with the same
3245
        // name at the same level is actually a JSON standard violation.
3246
0
        if (layer_count > 1 && loader_check_version_meets_required(loader_combine_version(1, 0, 1), json_version)) {
3247
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3248
0
                       "loader_add_layer_properties: Multiple 'layer' nodes are deprecated starting in file version \"1.0.1\".  "
3249
0
                       "Please use 'layers' : [] array instead in %s.",
3250
0
                       filename);
3251
0
        } else {
3252
0
            do {
3253
0
                result = loader_read_layer_json(inst, layer_instance_list, layer_node, json_version, is_implicit, filename);
3254
0
                layer_node = layer_node->next;
3255
0
            } while (layer_node != NULL);
3256
0
        }
3257
0
    }
3258
3259
0
out:
3260
3261
0
    return result;
3262
0
}
3263
3264
0
size_t determine_data_file_path_size(const char *cur_path, size_t relative_path_size) {
3265
0
    size_t path_size = 0;
3266
3267
0
    if (NULL != cur_path) {
3268
        // For each folder in cur_path, (detected by finding additional
3269
        // path separators in the string) we need to add the relative path on
3270
        // the end.  Plus, leave an additional two slots on the end to add an
3271
        // additional directory slash and path separator if needed
3272
0
        path_size += strlen(cur_path) + relative_path_size + 2;
3273
0
        for (const char *x = cur_path; *x; ++x) {
3274
0
            if (*x == PATH_SEPARATOR) {
3275
0
                path_size += relative_path_size + 2;
3276
0
            }
3277
0
        }
3278
0
    }
3279
3280
0
    return path_size;
3281
0
}
3282
3283
0
void copy_data_file_info(const char *cur_path, const char *relative_path, size_t relative_path_size, char **output_path) {
3284
0
    if (NULL != cur_path) {
3285
0
        uint32_t start = 0;
3286
0
        uint32_t stop = 0;
3287
0
        char *cur_write = *output_path;
3288
3289
0
        while (cur_path[start] != '\0') {
3290
0
            while (cur_path[start] == PATH_SEPARATOR && cur_path[start] != '\0') {
3291
0
                start++;
3292
0
            }
3293
0
            stop = start;
3294
0
            while (cur_path[stop] != PATH_SEPARATOR && cur_path[stop] != '\0') {
3295
0
                stop++;
3296
0
            }
3297
0
            const size_t s = stop - start;
3298
0
            if (s) {
3299
0
                memcpy(cur_write, &cur_path[start], s);
3300
0
                cur_write += s;
3301
3302
                // If this is a specific JSON file, just add it and don't add any
3303
                // relative path or directory symbol to it.
3304
0
                if (!is_json(cur_write - 5, s)) {
3305
                    // Add the relative directory if present.
3306
0
                    if (relative_path_size > 0) {
3307
                        // If last symbol written was not a directory symbol, add it.
3308
0
                        if (*(cur_write - 1) != DIRECTORY_SYMBOL) {
3309
0
                            *cur_write++ = DIRECTORY_SYMBOL;
3310
0
                        }
3311
0
                        memcpy(cur_write, relative_path, relative_path_size);
3312
0
                        cur_write += relative_path_size;
3313
0
                    }
3314
0
                }
3315
3316
0
                *cur_write++ = PATH_SEPARATOR;
3317
0
                start = stop;
3318
0
            }
3319
0
        }
3320
0
        *output_path = cur_write;
3321
0
    }
3322
0
}
3323
3324
// If the file found is a manifest file name, add it to the end of out_files manifest list.
3325
0
VkResult add_if_manifest_file(const struct loader_instance *inst, const char *file_name, struct loader_string_list *out_files) {
3326
0
    assert(NULL != file_name && "add_if_manifest_file: Received NULL pointer for file_name");
3327
0
    assert(NULL != out_files && "add_if_manifest_file: Received NULL pointer for out_files");
3328
3329
    // Look for files ending with ".json" suffix
3330
0
    size_t name_len = strlen(file_name);
3331
0
    const char *name_suffix = file_name + name_len - 5;
3332
0
    if (!is_json(name_suffix, name_len)) {
3333
        // Use incomplete to indicate invalid name, but to keep going.
3334
0
        return VK_INCOMPLETE;
3335
0
    }
3336
3337
0
    return copy_str_to_string_list(inst, out_files, file_name, name_len);
3338
0
}
3339
3340
// If the file found is a manifest file name, add it to the start of the out_files manifest list.
3341
0
VkResult prepend_if_manifest_file(const struct loader_instance *inst, const char *file_name, struct loader_string_list *out_files) {
3342
0
    assert(NULL != file_name && "prepend_if_manifest_file: Received NULL pointer for file_name");
3343
0
    assert(NULL != out_files && "prepend_if_manifest_file: Received NULL pointer for out_files");
3344
3345
    // Look for files ending with ".json" suffix
3346
0
    size_t name_len = strlen(file_name);
3347
0
    const char *name_suffix = file_name + name_len - 5;
3348
0
    if (!is_json(name_suffix, name_len)) {
3349
        // Use incomplete to indicate invalid name, but to keep going.
3350
0
        return VK_INCOMPLETE;
3351
0
    }
3352
3353
0
    return copy_str_to_start_of_string_list(inst, out_files, file_name, name_len);
3354
0
}
3355
3356
// Add any files found in the search_path.  If any path in the search path points to a specific JSON, attempt to
3357
// only open that one JSON.  Otherwise, if the path is a folder, search the folder for JSON files.
3358
0
VkResult add_data_files(const struct loader_instance *inst, char *search_path, struct loader_string_list *out_files) {
3359
0
    VkResult vk_result = VK_SUCCESS;
3360
0
    char full_path[2048];
3361
0
#if !defined(_WIN32)
3362
0
    char temp_path[2048];
3363
0
#endif
3364
3365
    // Now, parse the paths
3366
0
    char *next_file = search_path;
3367
0
    while (NULL != next_file && *next_file != '\0') {
3368
0
        char *name = NULL;
3369
0
        char *cur_file = next_file;
3370
0
        next_file = loader_get_next_path(cur_file);
3371
3372
        // Is this a JSON file, then try to open it.
3373
0
        size_t len = strlen(cur_file);
3374
0
        if (is_json(cur_file + len - 5, len)) {
3375
#if defined(_WIN32)
3376
            name = cur_file;
3377
#elif COMMON_UNIX_PLATFORMS
3378
            // Only Linux has relative paths, make a copy of location so it isn't modified
3379
0
            size_t str_len;
3380
0
            if (NULL != next_file) {
3381
0
                str_len = next_file - cur_file + 1;
3382
0
            } else {
3383
0
                str_len = strlen(cur_file) + 1;
3384
0
            }
3385
0
            if (str_len > sizeof(temp_path)) {
3386
0
                loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0, "add_data_files: Path to %s too long", cur_file);
3387
0
                continue;
3388
0
            }
3389
0
            strncpy(temp_path, cur_file, str_len);
3390
0
            name = temp_path;
3391
#else
3392
#warning add_data_files must define relative path copy for this platform
3393
#endif
3394
0
            loader_get_fullpath(cur_file, name, sizeof(full_path), full_path);
3395
0
            name = full_path;
3396
3397
0
            VkResult local_res;
3398
0
            local_res = add_if_manifest_file(inst, name, out_files);
3399
3400
            // Incomplete means this was not a valid data file.
3401
0
            if (local_res == VK_INCOMPLETE) {
3402
0
                continue;
3403
0
            } else if (local_res != VK_SUCCESS) {
3404
0
                vk_result = local_res;
3405
0
                break;
3406
0
            }
3407
0
        } else {  // Otherwise, treat it as a directory
3408
0
            DIR *dir_stream = loader_opendir(inst, cur_file);
3409
0
            if (NULL == dir_stream) {
3410
0
                continue;
3411
0
            }
3412
0
            while (1) {
3413
0
                errno = 0;
3414
0
                struct dirent *dir_entry = readdir(dir_stream);
3415
0
#if !defined(WIN32)  // Windows doesn't use readdir, don't check errors on functions which aren't called
3416
0
                if (errno != 0) {
3417
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "readdir failed with %d: %s", errno, strerror(errno));
3418
0
                    break;
3419
0
                }
3420
0
#endif
3421
0
                if (NULL == dir_entry) {
3422
0
                    break;
3423
0
                }
3424
3425
0
                name = &(dir_entry->d_name[0]);
3426
0
                loader_get_fullpath(name, cur_file, sizeof(full_path), full_path);
3427
0
                name = full_path;
3428
3429
0
                VkResult local_res;
3430
0
                local_res = add_if_manifest_file(inst, name, out_files);
3431
3432
                // Incomplete means this was not a valid data file.
3433
0
                if (local_res == VK_INCOMPLETE) {
3434
0
                    continue;
3435
0
                } else if (local_res != VK_SUCCESS) {
3436
0
                    vk_result = local_res;
3437
0
                    break;
3438
0
                }
3439
0
            }
3440
0
            loader_closedir(inst, dir_stream);
3441
0
            if (vk_result != VK_SUCCESS) {
3442
0
                goto out;
3443
0
            }
3444
0
        }
3445
0
    }
3446
3447
0
out:
3448
3449
0
    return vk_result;
3450
0
}
3451
3452
// Look for data files in the provided paths, but first check the environment override to determine if we should use that
3453
// instead.
3454
VkResult read_data_files_in_search_paths(const struct loader_instance *inst, enum loader_data_files_type manifest_type,
3455
0
                                         const char *path_override, bool *override_active, struct loader_string_list *out_files) {
3456
0
    VkResult vk_result = VK_SUCCESS;
3457
0
    char *override_env = NULL;
3458
0
    const char *override_path = NULL;
3459
0
    char *additional_env = NULL;
3460
0
    size_t search_path_size = 0;
3461
0
    char *search_path = NULL;
3462
0
    char *cur_path_ptr = NULL;
3463
0
#if COMMON_UNIX_PLATFORMS
3464
0
    const char *relative_location = NULL;  // Only used on unix platforms
3465
0
    size_t rel_size = 0;                   // unused in windows, dont declare so no compiler warnings are generated
3466
0
#endif
3467
3468
#if defined(_WIN32)
3469
    char *package_path = NULL;
3470
#elif COMMON_UNIX_PLATFORMS
3471
    // Determine how much space is needed to generate the full search path
3472
    // for the current manifest files.
3473
0
    char *xdg_config_home = loader_secure_getenv("XDG_CONFIG_HOME", inst);
3474
0
    char *xdg_config_dirs = loader_secure_getenv("XDG_CONFIG_DIRS", inst);
3475
3476
0
#if !defined(__Fuchsia__) && !defined(__QNX__)
3477
0
    if (NULL == xdg_config_dirs || '\0' == xdg_config_dirs[0]) {
3478
0
        xdg_config_dirs = FALLBACK_CONFIG_DIRS;
3479
0
    }
3480
0
#endif
3481
3482
0
    char *xdg_data_home = loader_secure_getenv("XDG_DATA_HOME", inst);
3483
0
    char *xdg_data_dirs = loader_secure_getenv("XDG_DATA_DIRS", inst);
3484
3485
0
#if !defined(__Fuchsia__) && !defined(__QNX__)
3486
0
    if (NULL == xdg_data_dirs || '\0' == xdg_data_dirs[0]) {
3487
0
        xdg_data_dirs = FALLBACK_DATA_DIRS;
3488
0
    }
3489
0
#endif
3490
3491
0
    char *home = NULL;
3492
0
    char *default_data_home = NULL;
3493
0
    char *default_config_home = NULL;
3494
0
    char *home_data_dir = NULL;
3495
0
    char *home_config_dir = NULL;
3496
3497
    // Only use HOME if XDG_DATA_HOME is not present on the system
3498
0
    home = loader_secure_getenv("HOME", inst);
3499
0
    if (home != NULL) {
3500
0
        if (NULL == xdg_config_home || '\0' == xdg_config_home[0]) {
3501
0
            const char config_suffix[] = "/.config";
3502
0
            size_t default_config_home_len = strlen(home) + sizeof(config_suffix) + 1;
3503
0
            default_config_home = loader_instance_heap_calloc(inst, default_config_home_len, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
3504
0
            if (default_config_home == NULL) {
3505
0
                vk_result = VK_ERROR_OUT_OF_HOST_MEMORY;
3506
0
                goto out;
3507
0
            }
3508
0
            strncpy(default_config_home, home, default_config_home_len);
3509
0
            strncat(default_config_home, config_suffix, default_config_home_len);
3510
0
        }
3511
0
        if (NULL == xdg_data_home || '\0' == xdg_data_home[0]) {
3512
0
            const char data_suffix[] = "/.local/share";
3513
0
            size_t default_data_home_len = strlen(home) + sizeof(data_suffix) + 1;
3514
0
            default_data_home = loader_instance_heap_calloc(inst, default_data_home_len, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
3515
0
            if (default_data_home == NULL) {
3516
0
                vk_result = VK_ERROR_OUT_OF_HOST_MEMORY;
3517
0
                goto out;
3518
0
            }
3519
0
            strncpy(default_data_home, home, default_data_home_len);
3520
0
            strncat(default_data_home, data_suffix, default_data_home_len);
3521
0
        }
3522
0
    }
3523
3524
0
    if (NULL != default_config_home) {
3525
0
        home_config_dir = default_config_home;
3526
0
    } else {
3527
0
        home_config_dir = xdg_config_home;
3528
0
    }
3529
0
    if (NULL != default_data_home) {
3530
0
        home_data_dir = default_data_home;
3531
0
    } else {
3532
0
        home_data_dir = xdg_data_home;
3533
0
    }
3534
#else
3535
#warning read_data_files_in_search_paths unsupported platform
3536
#endif
3537
3538
0
    switch (manifest_type) {
3539
0
        case LOADER_DATA_FILE_MANIFEST_DRIVER:
3540
0
            if (loader_settings_should_use_driver_environment_variables(inst)) {
3541
0
                override_env = loader_secure_getenv(VK_DRIVER_FILES_ENV_VAR, inst);
3542
0
                if (NULL == override_env) {
3543
                    // Not there, so fall back to the old name
3544
0
                    override_env = loader_secure_getenv(VK_ICD_FILENAMES_ENV_VAR, inst);
3545
0
                }
3546
0
                additional_env = loader_secure_getenv(VK_ADDITIONAL_DRIVER_FILES_ENV_VAR, inst);
3547
0
            }
3548
0
#if COMMON_UNIX_PLATFORMS
3549
0
            relative_location = VK_DRIVERS_INFO_RELATIVE_DIR;
3550
0
#endif
3551
#if defined(_WIN32)
3552
            package_path = windows_get_app_package_manifest_path(inst);
3553
#endif
3554
0
            break;
3555
0
        case LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER:
3556
0
            override_env = loader_secure_getenv(VK_IMPLICIT_LAYER_PATH_ENV_VAR, inst);
3557
0
            additional_env = loader_secure_getenv(VK_ADDITIONAL_IMPLICIT_LAYER_PATH_ENV_VAR, inst);
3558
0
#if COMMON_UNIX_PLATFORMS
3559
0
            relative_location = VK_ILAYERS_INFO_RELATIVE_DIR;
3560
0
#endif
3561
#if defined(_WIN32)
3562
            package_path = windows_get_app_package_manifest_path(inst);
3563
#endif
3564
0
            break;
3565
0
        case LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER:
3566
0
            override_env = loader_secure_getenv(VK_EXPLICIT_LAYER_PATH_ENV_VAR, inst);
3567
0
            additional_env = loader_secure_getenv(VK_ADDITIONAL_EXPLICIT_LAYER_PATH_ENV_VAR, inst);
3568
0
#if COMMON_UNIX_PLATFORMS
3569
0
            relative_location = VK_ELAYERS_INFO_RELATIVE_DIR;
3570
0
#endif
3571
0
            break;
3572
0
        default:
3573
0
            assert(false && "Shouldn't get here!");
3574
0
            break;
3575
0
    }
3576
3577
    // Log a message when VK_LAYER_PATH is set but the override layer paths take priority
3578
0
    if (manifest_type == LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER && NULL != override_env && NULL != path_override) {
3579
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3580
0
                   "Ignoring VK_LAYER_PATH. The Override layer is active and has override paths set, which takes priority. "
3581
0
                   "VK_LAYER_PATH is set to %s",
3582
0
                   override_env);
3583
0
    }
3584
3585
0
    if (path_override != NULL) {
3586
0
        override_path = path_override;
3587
0
    } else if (override_env != NULL) {
3588
0
        override_path = override_env;
3589
0
    }
3590
3591
    // Add two by default for NULL terminator and one path separator on end (just in case)
3592
0
    search_path_size = 2;
3593
3594
    // If there's an override, use that (and the local folder if required) and nothing else
3595
0
    if (NULL != override_path) {
3596
        // Local folder and null terminator
3597
0
        search_path_size += strlen(override_path) + 2;
3598
0
    } else {
3599
        // Add the size of any additional search paths defined in the additive environment variable
3600
0
        if (NULL != additional_env) {
3601
0
            search_path_size += determine_data_file_path_size(additional_env, 0) + 2;
3602
#if defined(_WIN32)
3603
        }
3604
        if (NULL != package_path) {
3605
            search_path_size += determine_data_file_path_size(package_path, 0) + 2;
3606
        }
3607
        if (search_path_size == 2) {
3608
            goto out;
3609
        }
3610
#elif COMMON_UNIX_PLATFORMS
3611
        }
3612
3613
        // Add the general search folders (with the appropriate relative folder added)
3614
0
        rel_size = strlen(relative_location);
3615
0
        if (rel_size > 0) {
3616
#if defined(__APPLE__)
3617
            search_path_size += MAXPATHLEN;
3618
#endif
3619
            // Only add the home folders if defined
3620
0
            if (NULL != home_config_dir) {
3621
0
                search_path_size += determine_data_file_path_size(home_config_dir, rel_size);
3622
0
            }
3623
0
            search_path_size += determine_data_file_path_size(xdg_config_dirs, rel_size);
3624
0
            search_path_size += determine_data_file_path_size(SYSCONFDIR, rel_size);
3625
0
#if defined(EXTRASYSCONFDIR)
3626
0
            search_path_size += determine_data_file_path_size(EXTRASYSCONFDIR, rel_size);
3627
0
#endif
3628
            // Only add the home folders if defined
3629
0
            if (NULL != home_data_dir) {
3630
0
                search_path_size += determine_data_file_path_size(home_data_dir, rel_size);
3631
0
            }
3632
0
            search_path_size += determine_data_file_path_size(xdg_data_dirs, rel_size);
3633
0
        }
3634
#else
3635
#warning read_data_files_in_search_paths unsupported platform
3636
#endif
3637
0
    }
3638
3639
    // Allocate the required space
3640
0
    search_path = loader_instance_heap_calloc(inst, search_path_size, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
3641
0
    if (NULL == search_path) {
3642
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
3643
0
                   "read_data_files_in_search_paths: Failed to allocate space for search path of length %d",
3644
0
                   (uint32_t)search_path_size);
3645
0
        vk_result = VK_ERROR_OUT_OF_HOST_MEMORY;
3646
0
        goto out;
3647
0
    }
3648
3649
0
    cur_path_ptr = search_path;
3650
3651
    // Add the remaining paths to the list
3652
0
    if (NULL != override_path) {
3653
0
        size_t override_path_len = strlen(override_path);
3654
0
        loader_strncpy(cur_path_ptr, search_path_size, override_path, override_path_len);
3655
0
        cur_path_ptr += override_path_len;
3656
0
    } else {
3657
        // Add any additional search paths defined in the additive environment variable
3658
0
        if (NULL != additional_env) {
3659
0
            copy_data_file_info(additional_env, NULL, 0, &cur_path_ptr);
3660
0
        }
3661
3662
#if defined(_WIN32)
3663
        if (NULL != package_path) {
3664
            copy_data_file_info(package_path, NULL, 0, &cur_path_ptr);
3665
        }
3666
#elif COMMON_UNIX_PLATFORMS
3667
0
        if (rel_size > 0) {
3668
#if defined(__APPLE__)
3669
            // Add the bundle's Resources dir to the beginning of the search path.
3670
            // Looks for manifests in the bundle first, before any system directories.
3671
            // This also appears to work unmodified for iOS, it finds the app bundle on the devices
3672
            // file system. (RSW)
3673
            CFBundleRef main_bundle = CFBundleGetMainBundle();
3674
            if (NULL != main_bundle) {
3675
                CFURLRef ref = CFBundleCopyResourcesDirectoryURL(main_bundle);
3676
                if (NULL != ref) {
3677
                    if (CFURLGetFileSystemRepresentation(ref, TRUE, (UInt8 *)cur_path_ptr, search_path_size)) {
3678
                        cur_path_ptr += strlen(cur_path_ptr);
3679
                        *cur_path_ptr++ = DIRECTORY_SYMBOL;
3680
                        memcpy(cur_path_ptr, relative_location, rel_size);
3681
                        cur_path_ptr += rel_size;
3682
                        *cur_path_ptr++ = PATH_SEPARATOR;
3683
                    }
3684
                    CFRelease(ref);
3685
                }
3686
            }
3687
#endif  // __APPLE__
3688
3689
            // Only add the home folders if not NULL
3690
0
            if (NULL != home_config_dir) {
3691
0
                copy_data_file_info(home_config_dir, relative_location, rel_size, &cur_path_ptr);
3692
0
            }
3693
0
            copy_data_file_info(xdg_config_dirs, relative_location, rel_size, &cur_path_ptr);
3694
0
            copy_data_file_info(SYSCONFDIR, relative_location, rel_size, &cur_path_ptr);
3695
0
#if defined(EXTRASYSCONFDIR)
3696
0
            copy_data_file_info(EXTRASYSCONFDIR, relative_location, rel_size, &cur_path_ptr);
3697
0
#endif
3698
3699
            // Only add the home folders if not NULL
3700
0
            if (NULL != home_data_dir) {
3701
0
                copy_data_file_info(home_data_dir, relative_location, rel_size, &cur_path_ptr);
3702
0
            }
3703
0
            copy_data_file_info(xdg_data_dirs, relative_location, rel_size, &cur_path_ptr);
3704
0
        }
3705
3706
        // Remove the last path separator
3707
0
        --cur_path_ptr;
3708
3709
0
        assert(cur_path_ptr - search_path < (ptrdiff_t)search_path_size);
3710
0
        *cur_path_ptr = '\0';
3711
#else
3712
#warning read_data_files_in_search_paths unsupported platform
3713
#endif
3714
0
    }
3715
3716
    // Remove duplicate paths, or it would result in duplicate extensions, duplicate devices, etc.
3717
    // This uses minimal memory, but is O(N^2) on the number of paths. Expect only a few paths.
3718
0
    char path_sep_str[2] = {PATH_SEPARATOR, '\0'};
3719
0
    size_t search_path_updated_size = strlen(search_path);
3720
0
    for (size_t first = 0; first < search_path_updated_size;) {
3721
        // If this is an empty path, erase it
3722
0
        if (search_path[first] == PATH_SEPARATOR) {
3723
0
            memmove(&search_path[first], &search_path[first + 1], search_path_updated_size - first + 1);
3724
0
            search_path_updated_size -= 1;
3725
0
            continue;
3726
0
        }
3727
3728
0
        size_t first_end = first + 1;
3729
0
        first_end += strcspn(&search_path[first_end], path_sep_str);
3730
0
        for (size_t second = first_end + 1; second < search_path_updated_size;) {
3731
0
            size_t second_end = second + 1;
3732
0
            second_end += strcspn(&search_path[second_end], path_sep_str);
3733
0
            if (first_end - first == second_end - second &&
3734
0
                !strncmp(&search_path[first], &search_path[second], second_end - second)) {
3735
                // Found duplicate. Include PATH_SEPARATOR in second_end, then erase it from search_path.
3736
0
                if (search_path[second_end] == PATH_SEPARATOR) {
3737
0
                    second_end++;
3738
0
                }
3739
0
                memmove(&search_path[second], &search_path[second_end], search_path_updated_size - second_end + 1);
3740
0
                search_path_updated_size -= second_end - second;
3741
0
            } else {
3742
0
                second = second_end + 1;
3743
0
            }
3744
0
        }
3745
0
        first = first_end + 1;
3746
0
    }
3747
0
    search_path_size = search_path_updated_size;
3748
3749
    // Print out the paths being searched if debugging is enabled
3750
0
    uint32_t log_flags = 0;
3751
0
    if (search_path_size > 0) {
3752
0
        char *tmp_search_path = loader_instance_heap_alloc(inst, search_path_size + 1, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
3753
0
        if (NULL != tmp_search_path) {
3754
0
            loader_strncpy(tmp_search_path, search_path_size + 1, search_path, search_path_size);
3755
0
            tmp_search_path[search_path_size] = '\0';
3756
0
            if (manifest_type == LOADER_DATA_FILE_MANIFEST_DRIVER) {
3757
0
                log_flags = VULKAN_LOADER_DRIVER_BIT;
3758
0
                loader_log(inst, VULKAN_LOADER_DRIVER_BIT, 0, "Searching for driver manifest files");
3759
0
            } else {
3760
0
                log_flags = VULKAN_LOADER_LAYER_BIT;
3761
0
                loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "Searching for %s layer manifest files",
3762
0
                           manifest_type == LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER ? "explicit" : "implicit");
3763
0
            }
3764
0
            loader_log(inst, log_flags, 0, "   In following locations:");
3765
0
            char *cur_file;
3766
0
            char *next_file = tmp_search_path;
3767
0
            while (NULL != next_file && *next_file != '\0') {
3768
0
                cur_file = next_file;
3769
0
                next_file = loader_get_next_path(cur_file);
3770
0
                loader_log(inst, log_flags, 0, "      %s", cur_file);
3771
0
            }
3772
0
            loader_instance_heap_free(inst, tmp_search_path);
3773
0
        }
3774
0
    }
3775
3776
    // Now, parse the paths and add any manifest files found in them.
3777
0
    vk_result = add_data_files(inst, search_path, out_files);
3778
3779
0
    if (log_flags != 0 && out_files->count > 0) {
3780
0
        loader_log(inst, log_flags, 0, "   Found the following files:");
3781
0
        for (uint32_t cur_file = 0; cur_file < out_files->count; ++cur_file) {
3782
0
            loader_log(inst, log_flags, 0, "      %s", out_files->list[cur_file]);
3783
0
        }
3784
0
    } else {
3785
0
        loader_log(inst, log_flags, 0, "   Found no files");
3786
0
    }
3787
3788
0
    if (NULL != override_path) {
3789
0
        *override_active = true;
3790
0
    } else {
3791
0
        *override_active = false;
3792
0
    }
3793
3794
0
out:
3795
3796
0
    loader_free_getenv(additional_env, inst);
3797
0
    loader_free_getenv(override_env, inst);
3798
#if defined(_WIN32)
3799
    loader_instance_heap_free(inst, package_path);
3800
#elif COMMON_UNIX_PLATFORMS
3801
    loader_free_getenv(xdg_config_home, inst);
3802
0
    loader_free_getenv(xdg_config_dirs, inst);
3803
0
    loader_free_getenv(xdg_data_home, inst);
3804
0
    loader_free_getenv(xdg_data_dirs, inst);
3805
0
    loader_free_getenv(xdg_data_home, inst);
3806
0
    loader_free_getenv(home, inst);
3807
0
    loader_instance_heap_free(inst, default_data_home);
3808
0
    loader_instance_heap_free(inst, default_config_home);
3809
#else
3810
#warning read_data_files_in_search_paths unsupported platform
3811
#endif
3812
3813
0
    loader_instance_heap_free(inst, search_path);
3814
3815
0
    return vk_result;
3816
0
}
3817
3818
// Find the Vulkan library manifest files.
3819
//
3820
// This function scans the appropriate locations for a list of JSON manifest files based on the
3821
// "manifest_type".  The location is interpreted as Registry path on Windows and a directory path(s)
3822
// on Linux.
3823
// "home_location" is an additional directory in the users home directory to look at. It is
3824
// expanded into the dir path $XDG_DATA_HOME/home_location or $HOME/.local/share/home_location
3825
// depending on environment variables. This "home_location" is only used on Linux.
3826
//
3827
// \returns
3828
// VKResult
3829
// A string list of manifest files to be opened in out_files param.
3830
// List has a pointer to string for each manifest filename.
3831
// When done using the list in out_files, pointers should be freed.
3832
// Location or override  string lists can be either files or directories as
3833
// follows:
3834
//            | location | override
3835
// --------------------------------
3836
// Win ICD    | files    | files
3837
// Win Layer  | files    | dirs
3838
// Linux ICD  | dirs     | files
3839
// Linux Layer| dirs     | dirs
3840
3841
VkResult loader_get_data_files(const struct loader_instance *inst, enum loader_data_files_type manifest_type,
3842
0
                               const char *path_override, struct loader_string_list *out_files) {
3843
0
    VkResult res = VK_SUCCESS;
3844
0
    bool override_active = false;
3845
3846
    // Free and init the out_files information so there's no false data left from uninitialized variables.
3847
0
    free_string_list(inst, out_files);
3848
3849
0
    res = read_data_files_in_search_paths(inst, manifest_type, path_override, &override_active, out_files);
3850
0
    if (VK_SUCCESS != res) {
3851
0
        goto out;
3852
0
    }
3853
3854
#if defined(_WIN32)
3855
    // Read the registry if the override wasn't active.
3856
    if (!override_active) {
3857
        bool warn_if_not_present = false;
3858
        char *registry_location = NULL;
3859
3860
        switch (manifest_type) {
3861
            default:
3862
                goto out;
3863
            case LOADER_DATA_FILE_MANIFEST_DRIVER:
3864
                warn_if_not_present = true;
3865
                registry_location = VK_DRIVERS_INFO_REGISTRY_LOC;
3866
                break;
3867
            case LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER:
3868
                registry_location = VK_ILAYERS_INFO_REGISTRY_LOC;
3869
                break;
3870
            case LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER:
3871
                warn_if_not_present = true;
3872
                registry_location = VK_ELAYERS_INFO_REGISTRY_LOC;
3873
                break;
3874
        }
3875
        VkResult tmp_res =
3876
            windows_read_data_files_in_registry(inst, manifest_type, warn_if_not_present, registry_location, out_files);
3877
        // Only return an error if there was an error this time, and no manifest files from before.
3878
        if (VK_SUCCESS != tmp_res && out_files->count == 0) {
3879
            res = tmp_res;
3880
            goto out;
3881
        }
3882
    }
3883
#endif
3884
3885
0
out:
3886
3887
0
    if (VK_SUCCESS != res) {
3888
0
        free_string_list(inst, out_files);
3889
0
    }
3890
3891
0
    return res;
3892
0
}
3893
3894
struct ICDManifestInfo {
3895
    char *full_library_path;
3896
    uint32_t version;
3897
};
3898
3899
// Takes a json file, opens, reads, and parses an ICD Manifest out of it.
3900
// Should only return VK_SUCCESS, VK_ERROR_INCOMPATIBLE_DRIVER, or VK_ERROR_OUT_OF_HOST_MEMORY
3901
VkResult loader_parse_icd_manifest(const struct loader_instance *inst, char *file_str, struct ICDManifestInfo *icd,
3902
0
                                   bool *skipped_portability_drivers) {
3903
0
    VkResult res = VK_SUCCESS;
3904
0
    cJSON *icd_manifest_json = NULL;
3905
3906
0
    if (file_str == NULL) {
3907
0
        goto out;
3908
0
    }
3909
3910
0
    res = loader_get_json(inst, file_str, &icd_manifest_json);
3911
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
3912
0
        goto out;
3913
0
    }
3914
0
    if (res != VK_SUCCESS || NULL == icd_manifest_json) {
3915
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3916
0
        goto out;
3917
0
    }
3918
3919
0
    cJSON *file_format_version_json = loader_cJSON_GetObjectItem(icd_manifest_json, "file_format_version");
3920
0
    if (file_format_version_json == NULL) {
3921
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3922
0
                   "loader_parse_icd_manifest: ICD JSON %s does not have a \'file_format_version\' field. Skipping ICD JSON.",
3923
0
                   file_str);
3924
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3925
0
        goto out;
3926
0
    }
3927
3928
0
    char *file_vers_str = loader_cJSON_GetStringValue(file_format_version_json);
3929
0
    if (NULL == file_vers_str) {
3930
        // Only reason the print can fail is if there was an allocation issue
3931
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3932
0
                   "loader_parse_icd_manifest: Failed retrieving ICD JSON %s \'file_format_version\' field. Skipping ICD JSON",
3933
0
                   file_str);
3934
0
        goto out;
3935
0
    }
3936
0
    loader_log(inst, VULKAN_LOADER_DRIVER_BIT, 0, "Found ICD manifest file %s, version %s", file_str, file_vers_str);
3937
3938
    // Get the version of the driver manifest
3939
0
    loader_api_version json_file_version = loader_make_full_version(loader_parse_version_string(file_vers_str));
3940
3941
    // Loader only knows versions 1.0.0 and 1.0.1, anything above it is unknown
3942
0
    if (loader_check_version_meets_required(loader_combine_version(1, 0, 2), json_file_version)) {
3943
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3944
0
                   "loader_parse_icd_manifest: %s has unknown icd manifest file version %d.%d.%d. May cause errors.", file_str,
3945
0
                   json_file_version.major, json_file_version.minor, json_file_version.patch);
3946
0
    }
3947
3948
0
    cJSON *itemICD = loader_cJSON_GetObjectItem(icd_manifest_json, "ICD");
3949
0
    if (itemICD == NULL) {
3950
        // Don't warn if this happens to be a layer manifest file
3951
0
        if (loader_cJSON_GetObjectItem(icd_manifest_json, "layer") == NULL &&
3952
0
            loader_cJSON_GetObjectItem(icd_manifest_json, "layers") == NULL) {
3953
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3954
0
                       "loader_parse_icd_manifest: Can not find \'ICD\' object in ICD JSON file %s. Skipping ICD JSON", file_str);
3955
0
        }
3956
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3957
0
        goto out;
3958
0
    }
3959
3960
0
    cJSON *library_path_json = loader_cJSON_GetObjectItem(itemICD, "library_path");
3961
0
    if (library_path_json == NULL) {
3962
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3963
0
                   "loader_parse_icd_manifest: Failed to find \'library_path\' object in ICD JSON file %s. Skipping ICD JSON.",
3964
0
                   file_str);
3965
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3966
0
        goto out;
3967
0
    }
3968
0
    bool out_of_memory = false;
3969
0
    char *library_path = loader_cJSON_Print(library_path_json, &out_of_memory);
3970
0
    if (out_of_memory) {
3971
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3972
0
                   "loader_parse_icd_manifest: Failed retrieving ICD JSON %s \'library_path\' field. Skipping ICD JSON.", file_str);
3973
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
3974
0
        goto out;
3975
0
    } else if (!library_path || strlen(library_path) == 0) {
3976
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3977
0
                   "loader_parse_icd_manifest: ICD JSON %s \'library_path\' field is empty. Skipping ICD JSON.", file_str);
3978
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3979
0
        loader_instance_heap_free(inst, library_path);
3980
0
        goto out;
3981
0
    }
3982
3983
    // Print out the paths being searched if debugging is enabled
3984
0
    loader_log(inst, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_DRIVER_BIT, 0, "Searching for ICD drivers named %s", library_path);
3985
    // This function takes ownership of library_path - so we don't need to clean it up
3986
0
    res = combine_manifest_directory_and_library_path(inst, library_path, file_str, &icd->full_library_path);
3987
0
    if (VK_SUCCESS != res) {
3988
0
        goto out;
3989
0
    }
3990
3991
0
    cJSON *api_version_json = loader_cJSON_GetObjectItem(itemICD, "api_version");
3992
0
    if (api_version_json == NULL) {
3993
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3994
0
                   "loader_parse_icd_manifest: ICD JSON %s does not have an \'api_version\' field. Skipping ICD JSON.", file_str);
3995
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3996
0
        goto out;
3997
0
    }
3998
0
    char *version_str = loader_cJSON_GetStringValue(api_version_json);
3999
0
    if (NULL == version_str) {
4000
        // Only reason the print can fail is if there was an allocation issue
4001
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4002
0
                   "loader_parse_icd_manifest: Failed retrieving ICD JSON %s \'api_version\' field. Skipping ICD JSON.", file_str);
4003
4004
0
        goto out;
4005
0
    }
4006
0
    icd->version = loader_parse_version_string(version_str);
4007
4008
0
    if (VK_API_VERSION_VARIANT(icd->version) != 0) {
4009
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4010
0
                   "loader_parse_icd_manifest: Driver's ICD JSON %s \'api_version\' field contains a non-zero variant value of %d. "
4011
0
                   " Skipping ICD JSON.",
4012
0
                   file_str, VK_API_VERSION_VARIANT(icd->version));
4013
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
4014
0
        goto out;
4015
0
    }
4016
4017
    // Skip over ICD's which contain a true "is_portability_driver" value whenever the application doesn't enable
4018
    // portability enumeration.
4019
0
    cJSON *is_portability_driver_json = loader_cJSON_GetObjectItem(itemICD, "is_portability_driver");
4020
0
    if (loader_cJSON_IsTrue(is_portability_driver_json) && inst && !inst->portability_enumeration_enabled) {
4021
0
        if (skipped_portability_drivers) {
4022
0
            *skipped_portability_drivers = true;
4023
0
        }
4024
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
4025
0
        goto out;
4026
0
    }
4027
4028
0
    char *library_arch_str = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(itemICD, "library_arch"));
4029
0
    if (library_arch_str != NULL) {
4030
0
        if ((strncmp(library_arch_str, "32", 2) == 0 && sizeof(void *) != 4) ||
4031
0
            (strncmp(library_arch_str, "64", 2) == 0 && sizeof(void *) != 8)) {
4032
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
4033
0
                       "loader_parse_icd_manifest: Driver library architecture doesn't match the current running "
4034
0
                       "architecture, skipping this driver");
4035
0
            res = VK_ERROR_INCOMPATIBLE_DRIVER;
4036
0
            goto out;
4037
0
        }
4038
0
    }
4039
0
out:
4040
0
    loader_cJSON_Delete(icd_manifest_json);
4041
0
    return res;
4042
0
}
4043
4044
// Try to find the Vulkan ICD driver(s).
4045
//
4046
// This function scans the default system loader path(s) or path specified by either the
4047
// VK_DRIVER_FILES or VK_ICD_FILENAMES environment variable in order to find loadable
4048
// VK ICDs manifest files.
4049
// From these manifest files it finds the ICD libraries.
4050
//
4051
// skipped_portability_drivers is used to report whether the loader found drivers which report
4052
// portability but the application didn't enable the bit to enumerate them
4053
// Can be NULL
4054
//
4055
// \returns
4056
// Vulkan result
4057
// (on result == VK_SUCCESS) a list of icds that were discovered
4058
VkResult loader_icd_scan(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list,
4059
0
                         const VkInstanceCreateInfo *pCreateInfo, bool *skipped_portability_drivers) {
4060
0
    VkResult res = VK_SUCCESS;
4061
0
    struct loader_string_list manifest_files = {0};
4062
0
    struct loader_envvar_filter select_filter = {0};
4063
0
    struct loader_envvar_filter disable_filter = {0};
4064
0
    struct ICDManifestInfo *icd_details = NULL;
4065
4066
    // Set up the ICD Trampoline list so elements can be written into it.
4067
0
    res = loader_init_scanned_icd_list(inst, icd_tramp_list);
4068
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
4069
0
        return res;
4070
0
    }
4071
4072
0
    bool direct_driver_loading_exclusive_mode = false;
4073
0
    res = loader_scan_for_direct_drivers(inst, pCreateInfo, icd_tramp_list, &direct_driver_loading_exclusive_mode);
4074
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
4075
0
        goto out;
4076
0
    }
4077
0
    if (direct_driver_loading_exclusive_mode) {
4078
        // Make sure to jump over the system & env-var driver discovery mechanisms if exclusive mode is set, even if no drivers
4079
        // were successfully found through the direct driver loading mechanism
4080
0
        goto out;
4081
0
    }
4082
4083
0
    if (loader_settings_should_use_driver_environment_variables(inst)) {
4084
        // Parse the filter environment variables to determine if we have any special behavior
4085
0
        res = parse_generic_filter_environment_var(inst, VK_DRIVERS_SELECT_ENV_VAR, &select_filter);
4086
0
        if (VK_SUCCESS != res) {
4087
0
            goto out;
4088
0
        }
4089
0
        res = parse_generic_filter_environment_var(inst, VK_DRIVERS_DISABLE_ENV_VAR, &disable_filter);
4090
0
        if (VK_SUCCESS != res) {
4091
0
            goto out;
4092
0
        }
4093
0
    }
4094
4095
    // Get a list of manifest files for ICDs
4096
0
    res = loader_get_data_files(inst, LOADER_DATA_FILE_MANIFEST_DRIVER, NULL, &manifest_files);
4097
0
    if (VK_SUCCESS != res) {
4098
0
        goto out;
4099
0
    }
4100
4101
    // Add any drivers provided by the loader settings file
4102
0
    res = loader_settings_get_additional_driver_files(inst, &manifest_files);
4103
0
    if (VK_SUCCESS != res) {
4104
0
        goto out;
4105
0
    }
4106
4107
0
    icd_details = loader_stack_alloc(sizeof(struct ICDManifestInfo) * manifest_files.count);
4108
0
    if (NULL == icd_details) {
4109
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
4110
0
        goto out;
4111
0
    }
4112
0
    memset(icd_details, 0, sizeof(struct ICDManifestInfo) * manifest_files.count);
4113
4114
0
    for (uint32_t i = 0; i < manifest_files.count; i++) {
4115
0
        VkResult icd_res = VK_SUCCESS;
4116
4117
0
        icd_res = loader_parse_icd_manifest(inst, manifest_files.list[i], &icd_details[i], skipped_portability_drivers);
4118
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == icd_res) {
4119
0
            res = icd_res;
4120
0
            goto out;
4121
0
        } else if (VK_ERROR_INCOMPATIBLE_DRIVER == icd_res) {
4122
0
            continue;
4123
0
        }
4124
4125
0
        if (select_filter.count > 0 || disable_filter.count > 0) {
4126
            // Get only the filename for comparing to the filters
4127
0
            char *just_filename_str = strrchr(manifest_files.list[i], DIRECTORY_SYMBOL);
4128
4129
            // No directory symbol, just the filename
4130
0
            if (NULL == just_filename_str) {
4131
0
                just_filename_str = manifest_files.list[i];
4132
0
            } else {
4133
0
                just_filename_str++;
4134
0
            }
4135
4136
0
            bool name_matches_select =
4137
0
                (select_filter.count > 0 && check_name_matches_filter_environment_var(just_filename_str, &select_filter));
4138
0
            bool name_matches_disable =
4139
0
                (disable_filter.count > 0 && check_name_matches_filter_environment_var(just_filename_str, &disable_filter));
4140
4141
0
            if (name_matches_disable && !name_matches_select) {
4142
0
                loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4143
0
                           "Driver \"%s\" ignored because it was disabled by env var \'%s\'", just_filename_str,
4144
0
                           VK_DRIVERS_DISABLE_ENV_VAR);
4145
0
                continue;
4146
0
            }
4147
0
            if (select_filter.count != 0 && !name_matches_select) {
4148
0
                loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4149
0
                           "Driver \"%s\" ignored because not selected by env var \'%s\'", just_filename_str,
4150
0
                           VK_DRIVERS_SELECT_ENV_VAR);
4151
0
                continue;
4152
0
            }
4153
0
        }
4154
4155
0
        enum loader_layer_library_status lib_status;
4156
0
        icd_res =
4157
0
            loader_scanned_icd_add(inst, icd_tramp_list, icd_details[i].full_library_path, icd_details[i].version, &lib_status);
4158
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == icd_res) {
4159
0
            res = icd_res;
4160
0
            goto out;
4161
0
        } else if (VK_ERROR_INCOMPATIBLE_DRIVER == icd_res) {
4162
0
            switch (lib_status) {
4163
0
                case LOADER_LAYER_LIB_NOT_LOADED:
4164
0
                case LOADER_LAYER_LIB_ERROR_FAILED_TO_LOAD:
4165
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4166
0
                               "loader_icd_scan: Failed loading library associated with ICD JSON %s. Ignoring this JSON",
4167
0
                               icd_details[i].full_library_path);
4168
0
                    break;
4169
0
                case LOADER_LAYER_LIB_ERROR_WRONG_BIT_TYPE: {
4170
0
                    loader_log(inst, VULKAN_LOADER_DRIVER_BIT, 0, "Requested ICD %s was wrong bit-type. Ignoring this JSON",
4171
0
                               icd_details[i].full_library_path);
4172
0
                    break;
4173
0
                }
4174
0
                case LOADER_LAYER_LIB_SUCCESS_LOADED:
4175
0
                case LOADER_LAYER_LIB_ERROR_OUT_OF_MEMORY:
4176
                    // Shouldn't be able to reach this but if it is, best to report a debug
4177
0
                    loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4178
0
                               "Shouldn't reach this. A valid version of requested ICD %s was loaded but something bad "
4179
0
                               "happened afterwards.",
4180
0
                               icd_details[i].full_library_path);
4181
0
                    break;
4182
0
            }
4183
0
        }
4184
0
    }
4185
4186
0
out:
4187
0
    if (NULL != icd_details) {
4188
        // Successfully got the icd_details structure, which means we need to free the paths contained within
4189
0
        for (uint32_t i = 0; i < manifest_files.count; i++) {
4190
0
            loader_instance_heap_free(inst, icd_details[i].full_library_path);
4191
0
        }
4192
0
    }
4193
0
    free_string_list(inst, &manifest_files);
4194
0
    return res;
4195
0
}
4196
4197
// Gets the layer data files corresponding to manifest_type & path_override, then parses the resulting json objects
4198
// into instance_layers
4199
// Manifest type must be either implicit or explicit
4200
VkResult loader_parse_instance_layers(struct loader_instance *inst, enum loader_data_files_type manifest_type,
4201
0
                                      const char *path_override, struct loader_layer_list *instance_layers) {
4202
0
    assert(manifest_type == LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER || manifest_type == LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER);
4203
0
    VkResult res = VK_SUCCESS;
4204
0
    struct loader_string_list manifest_files = {0};
4205
4206
0
    res = loader_get_data_files(inst, manifest_type, path_override, &manifest_files);
4207
0
    if (VK_SUCCESS != res) {
4208
0
        goto out;
4209
0
    }
4210
4211
0
    for (uint32_t i = 0; i < manifest_files.count; i++) {
4212
0
        char *file_str = manifest_files.list[i];
4213
0
        if (file_str == NULL) {
4214
0
            continue;
4215
0
        }
4216
4217
        // Parse file into JSON struct
4218
0
        cJSON *json = NULL;
4219
0
        VkResult local_res = loader_get_json(inst, file_str, &json);
4220
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == local_res) {
4221
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
4222
0
            goto out;
4223
0
        } else if (VK_SUCCESS != local_res || NULL == json) {
4224
0
            continue;
4225
0
        }
4226
4227
0
        local_res = loader_add_layer_properties(inst, instance_layers, json,
4228
0
                                                manifest_type == LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER, file_str);
4229
0
        loader_cJSON_Delete(json);
4230
4231
        // If the error is anything other than out of memory we still want to try to load the other layers
4232
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == local_res) {
4233
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
4234
0
            goto out;
4235
0
        }
4236
0
    }
4237
0
out:
4238
0
    free_string_list(inst, &manifest_files);
4239
4240
0
    return res;
4241
0
}
4242
4243
// Given a loader_layer_properties struct that is a valid override layer, concatenate the properties override paths and put them
4244
// into the output parameter override_paths
4245
VkResult get_override_layer_override_paths(struct loader_instance *inst, struct loader_layer_properties *prop,
4246
0
                                           char **override_paths) {
4247
0
    if (prop->override_paths.count > 0) {
4248
0
        char *cur_write_ptr = NULL;
4249
0
        size_t override_path_size = 0;
4250
0
        for (uint32_t j = 0; j < prop->override_paths.count; j++) {
4251
0
            override_path_size += determine_data_file_path_size(prop->override_paths.list[j], 0);
4252
0
        }
4253
0
        *override_paths = loader_instance_heap_alloc(inst, override_path_size, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
4254
0
        if (*override_paths == NULL) {
4255
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
4256
0
        }
4257
0
        cur_write_ptr = &(*override_paths)[0];
4258
0
        for (uint32_t j = 0; j < prop->override_paths.count; j++) {
4259
0
            copy_data_file_info(prop->override_paths.list[j], NULL, 0, &cur_write_ptr);
4260
0
        }
4261
4262
        // Subtract one from cur_write_ptr only if something was written so we can set the null terminator
4263
0
        if (*override_paths < cur_write_ptr) {
4264
0
            --cur_write_ptr;
4265
0
            assert(cur_write_ptr - (*override_paths) < (ptrdiff_t)override_path_size);
4266
0
        }
4267
        // Remove the last path separator
4268
0
        *cur_write_ptr = '\0';
4269
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Override layer has override paths set to %s",
4270
0
                   *override_paths);
4271
0
    }
4272
0
    return VK_SUCCESS;
4273
0
}
4274
4275
0
void loader_remove_duplicate_layers(struct loader_instance *inst, struct loader_layer_list *layers) {
4276
    // Remove duplicate layers (that share the same layerName)
4277
0
    for (uint32_t i = 0; i < layers->count; ++i) {
4278
0
        bool has_duplicate = false;
4279
0
        uint32_t duplicate_index = 0;
4280
0
        for (uint32_t j = i + 1; j < layers->count; ++j) {
4281
0
            if (strcmp(layers->list[i].info.layerName, layers->list[j].info.layerName) == 0) {
4282
0
                has_duplicate = true;
4283
0
                duplicate_index = j;
4284
0
                break;
4285
0
            }
4286
0
        }
4287
0
        if (has_duplicate) {
4288
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0, "Removing layer %s (%s) because it is a duplicate of %s (%s)",
4289
0
                       layers->list[duplicate_index].info.layerName, layers->list[duplicate_index].manifest_file_name,
4290
0
                       layers->list[i].info.layerName, layers->list[i].manifest_file_name);
4291
0
            loader_remove_layer_in_list(inst, layers, duplicate_index);
4292
0
        }
4293
0
    }
4294
0
}
4295
4296
VkResult loader_scan_for_layers(struct loader_instance *inst, struct loader_layer_list *instance_layers,
4297
0
                                const struct loader_envvar_all_filters *filters) {
4298
0
    VkResult res = VK_SUCCESS;
4299
0
    struct loader_layer_list settings_layers = {0};
4300
0
    struct loader_layer_list regular_instance_layers = {0};
4301
0
    bool override_layer_valid = false;
4302
0
    char *override_paths = NULL;
4303
4304
0
    bool should_search_for_other_layers = true;
4305
0
    res = get_settings_layers(inst, &settings_layers, &should_search_for_other_layers);
4306
0
    if (VK_SUCCESS != res) {
4307
0
        goto out;
4308
0
    }
4309
4310
    // If we should not look for layers using other mechanisms, assign settings_layers to instance_layers and jump to the
4311
    // output
4312
0
    if (!should_search_for_other_layers) {
4313
0
        *instance_layers = settings_layers;
4314
0
        memset(&settings_layers, 0, sizeof(struct loader_layer_list));
4315
0
        goto out;
4316
0
    }
4317
4318
0
    res = loader_parse_instance_layers(inst, LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER, NULL, &regular_instance_layers);
4319
0
    if (VK_SUCCESS != res) {
4320
0
        goto out;
4321
0
    }
4322
4323
    // Remove any extraneous override layers.
4324
0
    remove_all_non_valid_override_layers(inst, &regular_instance_layers);
4325
4326
    // Check to see if the override layer is present, and use it's override paths.
4327
0
    for (uint32_t i = 0; i < regular_instance_layers.count; i++) {
4328
0
        struct loader_layer_properties *prop = &regular_instance_layers.list[i];
4329
0
        if (prop->is_override && loader_implicit_layer_is_enabled(inst, filters, prop) && prop->override_paths.count > 0) {
4330
0
            res = get_override_layer_override_paths(inst, prop, &override_paths);
4331
0
            if (VK_SUCCESS != res) {
4332
0
                goto out;
4333
0
            }
4334
0
            break;
4335
0
        }
4336
0
    }
4337
4338
    // Get a list of manifest files for explicit layers
4339
0
    res = loader_parse_instance_layers(inst, LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER, override_paths, &regular_instance_layers);
4340
0
    if (VK_SUCCESS != res) {
4341
0
        goto out;
4342
0
    }
4343
4344
    // Verify any meta-layers in the list are valid and all the component layers are
4345
    // actually present in the available layer list
4346
0
    res = verify_all_meta_layers(inst, filters, &regular_instance_layers, &override_layer_valid);
4347
0
    if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
4348
0
        return res;
4349
0
    }
4350
4351
0
    if (override_layer_valid) {
4352
0
        loader_remove_layers_in_blacklist(inst, &regular_instance_layers);
4353
0
        if (NULL != inst) {
4354
0
            inst->override_layer_present = true;
4355
0
        }
4356
0
    }
4357
4358
    // Remove disabled layers
4359
0
    for (uint32_t i = 0; i < regular_instance_layers.count; ++i) {
4360
0
        if (!loader_layer_is_available(inst, filters, &regular_instance_layers.list[i])) {
4361
0
            loader_remove_layer_in_list(inst, &regular_instance_layers, i);
4362
0
            i--;
4363
0
        }
4364
0
    }
4365
4366
    // Make sure no layers have the same layerName
4367
0
    loader_remove_duplicate_layers(inst, &regular_instance_layers);
4368
4369
0
    res = combine_settings_layers_with_regular_layers(inst, &settings_layers, &regular_instance_layers, instance_layers);
4370
4371
0
out:
4372
0
    loader_delete_layer_list_and_properties(inst, &settings_layers);
4373
0
    loader_delete_layer_list_and_properties(inst, &regular_instance_layers);
4374
4375
0
    loader_instance_heap_free(inst, override_paths);
4376
0
    return res;
4377
0
}
4378
4379
VkResult loader_scan_for_implicit_layers(struct loader_instance *inst, struct loader_layer_list *instance_layers,
4380
0
                                         const struct loader_envvar_all_filters *layer_filters) {
4381
0
    VkResult res = VK_SUCCESS;
4382
0
    struct loader_layer_list settings_layers = {0};
4383
0
    struct loader_layer_list regular_instance_layers = {0};
4384
0
    bool override_layer_valid = false;
4385
0
    char *override_paths = NULL;
4386
0
    bool implicit_metalayer_present = false;
4387
4388
0
    bool should_search_for_other_layers = true;
4389
0
    res = get_settings_layers(inst, &settings_layers, &should_search_for_other_layers);
4390
0
    if (VK_SUCCESS != res) {
4391
0
        goto out;
4392
0
    }
4393
4394
    // Remove layers from settings file that are off, are explicit, or are implicit layers that aren't active
4395
0
    for (uint32_t i = 0; i < settings_layers.count; ++i) {
4396
0
        if (settings_layers.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_OFF ||
4397
0
            settings_layers.list[i].settings_control_value == LOADER_SETTINGS_LAYER_UNORDERED_LAYER_LOCATION ||
4398
0
            (settings_layers.list[i].type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER) == VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER ||
4399
0
            !loader_implicit_layer_is_enabled(inst, layer_filters, &settings_layers.list[i])) {
4400
0
            loader_remove_layer_in_list(inst, &settings_layers, i);
4401
0
            i--;
4402
0
        }
4403
0
    }
4404
4405
    // If we should not look for layers using other mechanisms, assign settings_layers to instance_layers and jump to the
4406
    // output
4407
0
    if (!should_search_for_other_layers) {
4408
0
        *instance_layers = settings_layers;
4409
0
        memset(&settings_layers, 0, sizeof(struct loader_layer_list));
4410
0
        goto out;
4411
0
    }
4412
4413
0
    res = loader_parse_instance_layers(inst, LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER, NULL, &regular_instance_layers);
4414
0
    if (VK_SUCCESS != res) {
4415
0
        goto out;
4416
0
    }
4417
4418
    // Remove any extraneous override layers.
4419
0
    remove_all_non_valid_override_layers(inst, &regular_instance_layers);
4420
4421
    // Check to see if either the override layer is present, or another implicit meta-layer.
4422
    // Each of these may require explicit layers to be enabled at this time.
4423
0
    for (uint32_t i = 0; i < regular_instance_layers.count; i++) {
4424
0
        struct loader_layer_properties *prop = &regular_instance_layers.list[i];
4425
0
        if (prop->is_override && loader_implicit_layer_is_enabled(inst, layer_filters, prop)) {
4426
0
            override_layer_valid = true;
4427
0
            res = get_override_layer_override_paths(inst, prop, &override_paths);
4428
0
            if (VK_SUCCESS != res) {
4429
0
                goto out;
4430
0
            }
4431
0
        } else if (!prop->is_override && prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
4432
0
            implicit_metalayer_present = true;
4433
0
        }
4434
0
    }
4435
4436
    // If either the override layer or an implicit meta-layer are present, we need to add
4437
    // explicit layer info as well.  Not to worry, though, all explicit layers not included
4438
    // in the override layer will be removed below in loader_remove_layers_in_blacklist().
4439
0
    if (override_layer_valid || implicit_metalayer_present) {
4440
0
        res =
4441
0
            loader_parse_instance_layers(inst, LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER, override_paths, &regular_instance_layers);
4442
0
        if (VK_SUCCESS != res) {
4443
0
            goto out;
4444
0
        }
4445
0
    }
4446
4447
    // Verify any meta-layers in the list are valid and all the component layers are
4448
    // actually present in the available layer list
4449
0
    res = verify_all_meta_layers(inst, layer_filters, &regular_instance_layers, &override_layer_valid);
4450
0
    if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
4451
0
        return res;
4452
0
    }
4453
4454
0
    if (override_layer_valid || implicit_metalayer_present) {
4455
0
        loader_remove_layers_not_in_implicit_meta_layers(inst, &regular_instance_layers);
4456
0
        if (override_layer_valid && inst != NULL) {
4457
0
            inst->override_layer_present = true;
4458
0
        }
4459
0
    }
4460
4461
    // Remove disabled layers
4462
0
    for (uint32_t i = 0; i < regular_instance_layers.count; ++i) {
4463
0
        if (!loader_implicit_layer_is_enabled(inst, layer_filters, &regular_instance_layers.list[i])) {
4464
0
            loader_remove_layer_in_list(inst, &regular_instance_layers, i);
4465
0
            i--;
4466
0
        }
4467
0
    }
4468
4469
    // Make sure no layers have the same layerName
4470
0
    loader_remove_duplicate_layers(inst, &regular_instance_layers);
4471
4472
0
    res = combine_settings_layers_with_regular_layers(inst, &settings_layers, &regular_instance_layers, instance_layers);
4473
4474
0
out:
4475
0
    loader_delete_layer_list_and_properties(inst, &settings_layers);
4476
0
    loader_delete_layer_list_and_properties(inst, &regular_instance_layers);
4477
4478
0
    loader_instance_heap_free(inst, override_paths);
4479
0
    return res;
4480
0
}
4481
4482
0
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL loader_gpdpa_instance_terminator(VkInstance inst, const char *pName) {
4483
    // inst is not wrapped
4484
0
    if (inst == VK_NULL_HANDLE) {
4485
0
        return NULL;
4486
0
    }
4487
4488
0
    VkLayerInstanceDispatchTable *disp_table = *(VkLayerInstanceDispatchTable **)inst;
4489
4490
0
    if (disp_table == NULL) return NULL;
4491
4492
0
    struct loader_instance *loader_inst = loader_get_instance(inst);
4493
4494
0
    if (loader_inst->instance_finished_creation) {
4495
0
        disp_table = &loader_inst->terminator_dispatch;
4496
0
    }
4497
4498
0
    bool found_name;
4499
0
    void *addr = loader_lookup_instance_dispatch_table(disp_table, pName, &found_name);
4500
0
    if (found_name) {
4501
0
        return addr;
4502
0
    }
4503
4504
    // Check if any drivers support the function, and if so, add it to the unknown function list
4505
0
    addr = loader_phys_dev_ext_gpa_term(loader_get_instance(inst), pName);
4506
0
    if (NULL != addr) return addr;
4507
4508
    // Don't call down the chain, this would be an infinite loop
4509
0
    loader_log(NULL, VULKAN_LOADER_DEBUG_BIT, 0, "loader_gpdpa_instance_terminator() unrecognized name %s", pName);
4510
0
    return NULL;
4511
0
}
4512
4513
0
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL loader_gpa_instance_terminator(VkInstance inst, const char *pName) {
4514
    // Global functions - Do not need a valid instance handle to query
4515
0
    if (!strcmp(pName, "vkGetInstanceProcAddr")) {
4516
0
        return (PFN_vkVoidFunction)loader_gpa_instance_terminator;
4517
0
    }
4518
0
    if (!strcmp(pName, "vk_layerGetPhysicalDeviceProcAddr")) {
4519
0
        return (PFN_vkVoidFunction)loader_gpdpa_instance_terminator;
4520
0
    }
4521
0
    if (!strcmp(pName, "vkCreateInstance")) {
4522
0
        return (PFN_vkVoidFunction)terminator_CreateInstance;
4523
0
    }
4524
    // If a layer is querying pre-instance functions using vkGetInstanceProcAddr, we need to return function pointers that match the
4525
    // Vulkan API
4526
0
    if (!strcmp(pName, "vkEnumerateInstanceLayerProperties")) {
4527
0
        return (PFN_vkVoidFunction)terminator_EnumerateInstanceLayerProperties;
4528
0
    }
4529
0
    if (!strcmp(pName, "vkEnumerateInstanceExtensionProperties")) {
4530
0
        return (PFN_vkVoidFunction)terminator_EnumerateInstanceExtensionProperties;
4531
0
    }
4532
0
    if (!strcmp(pName, "vkEnumerateInstanceVersion")) {
4533
0
        return (PFN_vkVoidFunction)terminator_EnumerateInstanceVersion;
4534
0
    }
4535
4536
    // While the spec is very clear that querying vkCreateDevice requires a valid VkInstance, because the loader allowed querying
4537
    // with a NULL VkInstance handle for a long enough time, it is impractical to fix this bug in the loader
4538
4539
    // As such, this is a bug to maintain compatibility for the RTSS layer (Riva Tuner Statistics Server) but may
4540
    // be depended upon by other layers out in the wild.
4541
0
    if (!strcmp(pName, "vkCreateDevice")) {
4542
0
        return (PFN_vkVoidFunction)terminator_CreateDevice;
4543
0
    }
4544
4545
    // inst is not wrapped
4546
0
    if (inst == VK_NULL_HANDLE) {
4547
0
        return NULL;
4548
0
    }
4549
0
    VkLayerInstanceDispatchTable *disp_table = *(VkLayerInstanceDispatchTable **)inst;
4550
4551
0
    if (disp_table == NULL) return NULL;
4552
4553
0
    struct loader_instance *loader_inst = loader_get_instance(inst);
4554
4555
    // The VK_EXT_debug_utils functions need a special case here so the terminators can still be found from
4556
    // vkGetInstanceProcAddr This is because VK_EXT_debug_utils is an instance level extension with device level functions, and
4557
    // is 'supported' by the loader.
4558
    // These functions need a terminator to handle the case of a driver not supporting VK_EXT_debug_utils when there are layers
4559
    // present which not check for NULL before calling the function.
4560
0
    if (!strcmp(pName, "vkSetDebugUtilsObjectNameEXT")) {
4561
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_SetDebugUtilsObjectNameEXT : NULL;
4562
0
    }
4563
0
    if (!strcmp(pName, "vkSetDebugUtilsObjectTagEXT")) {
4564
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_SetDebugUtilsObjectTagEXT : NULL;
4565
0
    }
4566
0
    if (!strcmp(pName, "vkQueueBeginDebugUtilsLabelEXT")) {
4567
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_QueueBeginDebugUtilsLabelEXT : NULL;
4568
0
    }
4569
0
    if (!strcmp(pName, "vkQueueEndDebugUtilsLabelEXT")) {
4570
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_QueueEndDebugUtilsLabelEXT : NULL;
4571
0
    }
4572
0
    if (!strcmp(pName, "vkQueueInsertDebugUtilsLabelEXT")) {
4573
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_QueueInsertDebugUtilsLabelEXT
4574
0
                                                               : NULL;
4575
0
    }
4576
0
    if (!strcmp(pName, "vkCmdBeginDebugUtilsLabelEXT")) {
4577
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_CmdBeginDebugUtilsLabelEXT : NULL;
4578
0
    }
4579
0
    if (!strcmp(pName, "vkCmdEndDebugUtilsLabelEXT")) {
4580
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_CmdEndDebugUtilsLabelEXT : NULL;
4581
0
    }
4582
0
    if (!strcmp(pName, "vkCmdInsertDebugUtilsLabelEXT")) {
4583
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_CmdInsertDebugUtilsLabelEXT : NULL;
4584
0
    }
4585
4586
0
    if (loader_inst->instance_finished_creation) {
4587
0
        disp_table = &loader_inst->terminator_dispatch;
4588
0
    }
4589
4590
0
    bool found_name;
4591
0
    void *addr = loader_lookup_instance_dispatch_table(disp_table, pName, &found_name);
4592
0
    if (found_name) {
4593
0
        return addr;
4594
0
    }
4595
4596
    // Check if it is an unknown physical device function, to see if any drivers support it.
4597
0
    addr = loader_phys_dev_ext_gpa_term(loader_get_instance(inst), pName);
4598
0
    if (addr) {
4599
0
        return addr;
4600
0
    }
4601
4602
    // Assume it is an unknown device function, check to see if any drivers support it.
4603
0
    addr = loader_dev_ext_gpa_term(loader_get_instance(inst), pName);
4604
0
    if (addr) {
4605
0
        return addr;
4606
0
    }
4607
4608
    // Don't call down the chain, this would be an infinite loop
4609
0
    loader_log(NULL, VULKAN_LOADER_DEBUG_BIT, 0, "loader_gpa_instance_terminator() unrecognized name %s", pName);
4610
0
    return NULL;
4611
0
}
4612
4613
0
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL loader_gpa_device_terminator(VkDevice device, const char *pName) {
4614
0
    struct loader_device *dev;
4615
0
    struct loader_icd_term *icd_term = loader_get_icd_and_device(device, &dev);
4616
4617
    // Return this function if a layer above here is asking for the vkGetDeviceProcAddr.
4618
    // This is so we can properly intercept any device commands needing a terminator.
4619
0
    if (!strcmp(pName, "vkGetDeviceProcAddr")) {
4620
0
        return (PFN_vkVoidFunction)loader_gpa_device_terminator;
4621
0
    }
4622
4623
    // NOTE: Device Funcs needing Trampoline/Terminator.
4624
    // Overrides for device functions needing a trampoline and
4625
    // a terminator because certain device entry-points still need to go
4626
    // through a terminator before hitting the ICD.  This could be for
4627
    // several reasons, but the main one is currently unwrapping an
4628
    // object before passing the appropriate info along to the ICD.
4629
    // This is why we also have to override the direct ICD call to
4630
    // vkGetDeviceProcAddr to intercept those calls.
4631
    // If the pName is for a 'known' function but isn't available, due to
4632
    // the corresponding extension/feature not being enabled, we need to
4633
    // return NULL and not call down to the driver's GetDeviceProcAddr.
4634
0
    if (NULL != dev) {
4635
0
        bool found_name = false;
4636
0
        PFN_vkVoidFunction addr = get_extension_device_proc_terminator(dev, pName, &found_name);
4637
0
        if (found_name) {
4638
0
            return addr;
4639
0
        }
4640
0
    }
4641
4642
0
    if (icd_term == NULL) {
4643
0
        return NULL;
4644
0
    }
4645
4646
0
    return icd_term->dispatch.GetDeviceProcAddr(device, pName);
4647
0
}
4648
4649
0
struct loader_instance *loader_get_instance(const VkInstance instance) {
4650
    // look up the loader_instance in our list by comparing dispatch tables, as
4651
    // there is no guarantee the instance is still a loader_instance* after any
4652
    // layers which wrap the instance object.
4653
0
    const VkLayerInstanceDispatchTable *disp;
4654
0
    struct loader_instance *ptr_instance = (struct loader_instance *)instance;
4655
0
    if (VK_NULL_HANDLE == instance || LOADER_MAGIC_NUMBER != ptr_instance->magic) {
4656
0
        return NULL;
4657
0
    } else {
4658
0
        disp = loader_get_instance_layer_dispatch(instance);
4659
0
        loader_platform_thread_lock_mutex(&loader_global_instance_list_lock);
4660
0
        for (struct loader_instance *inst = loader.instances; inst; inst = inst->next) {
4661
0
            if (&inst->disp->layer_inst_disp == disp) {
4662
0
                ptr_instance = inst;
4663
0
                break;
4664
0
            }
4665
0
        }
4666
0
        loader_platform_thread_unlock_mutex(&loader_global_instance_list_lock);
4667
0
    }
4668
0
    return ptr_instance;
4669
0
}
4670
4671
0
loader_platform_dl_handle loader_open_layer_file(const struct loader_instance *inst, struct loader_layer_properties *prop) {
4672
0
    if ((prop->lib_handle = loader_platform_open_library(prop->lib_name)) == NULL) {
4673
0
        loader_handle_load_library_error(inst, prop->lib_name, &prop->lib_status);
4674
0
    } else {
4675
0
        prop->lib_status = LOADER_LAYER_LIB_SUCCESS_LOADED;
4676
0
        loader_log(inst, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Loading layer library %s", prop->lib_name);
4677
0
    }
4678
4679
0
    return prop->lib_handle;
4680
0
}
4681
4682
// Go through the search_list and find any layers which match type. If layer
4683
// type match is found in then add it to ext_list.
4684
// If the layer name is in enabled_layers_env, do not add it to the list, that way it can be ordered alongside the other env-var
4685
// enabled layers
4686
VkResult loader_add_implicit_layers(const struct loader_instance *inst, const char *enabled_layers_env,
4687
                                    const struct loader_envvar_all_filters *filters, struct loader_pointer_layer_list *target_list,
4688
                                    struct loader_pointer_layer_list *expanded_target_list,
4689
0
                                    const struct loader_layer_list *source_list) {
4690
0
    for (uint32_t src_layer = 0; src_layer < source_list->count; src_layer++) {
4691
0
        struct loader_layer_properties *prop = &source_list->list[src_layer];
4692
0
        if (0 == (prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
4693
            // If this layer appears in the enabled_layers_env, don't add it. We will let loader_add_environment_layers handle it
4694
0
            if (NULL == enabled_layers_env || NULL == strstr(enabled_layers_env, prop->info.layerName)) {
4695
0
                VkResult result = loader_add_implicit_layer(inst, prop, filters, target_list, expanded_target_list, source_list);
4696
0
                if (result == VK_ERROR_OUT_OF_HOST_MEMORY) return result;
4697
0
            }
4698
0
        }
4699
0
    }
4700
0
    return VK_SUCCESS;
4701
0
}
4702
4703
0
void warn_if_layers_are_older_than_application(struct loader_instance *inst) {
4704
0
    for (uint32_t i = 0; i < inst->expanded_activated_layer_list.count; i++) {
4705
        // Verify that the layer api version is at least that of the application's request, if not, throw a warning since
4706
        // undefined behavior could occur.
4707
0
        struct loader_layer_properties *prop = inst->expanded_activated_layer_list.list[i];
4708
0
        loader_api_version prop_spec_version = loader_make_version(prop->info.specVersion);
4709
0
        if (!loader_check_version_meets_required(inst->app_api_version, prop_spec_version)) {
4710
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
4711
0
                       "Layer %s uses API version %u.%u which is older than the application specified "
4712
0
                       "API version of %u.%u. May cause issues.",
4713
0
                       prop->info.layerName, prop_spec_version.major, prop_spec_version.minor, inst->app_api_version.major,
4714
0
                       inst->app_api_version.minor);
4715
0
        }
4716
0
    }
4717
0
}
4718
4719
VkResult loader_enable_instance_layers(struct loader_instance *inst, const VkInstanceCreateInfo *pCreateInfo,
4720
                                       const struct loader_layer_list *instance_layers,
4721
0
                                       const struct loader_envvar_all_filters *layer_filters) {
4722
0
    VkResult res = VK_SUCCESS;
4723
0
    char *enabled_layers_env = NULL;
4724
4725
0
    assert(inst && "Cannot have null instance");
4726
4727
0
    if (!loader_init_pointer_layer_list(inst, &inst->app_activated_layer_list)) {
4728
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
4729
0
                   "loader_enable_instance_layers: Failed to initialize application version of the layer list");
4730
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
4731
0
        goto out;
4732
0
    }
4733
4734
0
    if (!loader_init_pointer_layer_list(inst, &inst->expanded_activated_layer_list)) {
4735
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
4736
0
                   "loader_enable_instance_layers: Failed to initialize expanded version of the layer list");
4737
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
4738
0
        goto out;
4739
0
    }
4740
4741
0
    if (inst->settings.settings_active && inst->settings.layer_configurations_active) {
4742
0
        res = enable_correct_layers_from_settings(inst, layer_filters, pCreateInfo->enabledLayerCount,
4743
0
                                                  pCreateInfo->ppEnabledLayerNames, &inst->instance_layer_list,
4744
0
                                                  &inst->app_activated_layer_list, &inst->expanded_activated_layer_list);
4745
0
        warn_if_layers_are_older_than_application(inst);
4746
4747
0
        goto out;
4748
0
    }
4749
4750
0
    enabled_layers_env = loader_getenv(ENABLED_LAYERS_ENV, inst);
4751
4752
    // Add any implicit layers first
4753
0
    res = loader_add_implicit_layers(inst, enabled_layers_env, layer_filters, &inst->app_activated_layer_list,
4754
0
                                     &inst->expanded_activated_layer_list, instance_layers);
4755
0
    if (res != VK_SUCCESS) {
4756
0
        goto out;
4757
0
    }
4758
4759
    // Add any layers specified via environment variable next
4760
0
    res = loader_add_environment_layers(inst, enabled_layers_env, layer_filters, &inst->app_activated_layer_list,
4761
0
                                        &inst->expanded_activated_layer_list, instance_layers);
4762
0
    if (res != VK_SUCCESS) {
4763
0
        goto out;
4764
0
    }
4765
4766
    // Add layers specified by the application
4767
0
    res = loader_add_layer_names_to_list(inst, layer_filters, &inst->app_activated_layer_list, &inst->expanded_activated_layer_list,
4768
0
                                         pCreateInfo->enabledLayerCount, pCreateInfo->ppEnabledLayerNames, instance_layers);
4769
4770
0
    warn_if_layers_are_older_than_application(inst);
4771
0
out:
4772
0
    if (enabled_layers_env != NULL) {
4773
0
        loader_free_getenv(enabled_layers_env, inst);
4774
0
    }
4775
4776
0
    return res;
4777
0
}
4778
4779
// Determine the layer interface version to use.
4780
bool loader_get_layer_interface_version(PFN_vkNegotiateLoaderLayerInterfaceVersion fp_negotiate_layer_version,
4781
0
                                        VkNegotiateLayerInterface *interface_struct) {
4782
0
    memset(interface_struct, 0, sizeof(VkNegotiateLayerInterface));
4783
0
    interface_struct->sType = LAYER_NEGOTIATE_INTERFACE_STRUCT;
4784
0
    interface_struct->loaderLayerInterfaceVersion = 1;
4785
0
    interface_struct->pNext = NULL;
4786
4787
0
    if (fp_negotiate_layer_version != NULL) {
4788
        // Layer supports the negotiation API, so call it with the loader's
4789
        // latest version supported
4790
0
        interface_struct->loaderLayerInterfaceVersion = CURRENT_LOADER_LAYER_INTERFACE_VERSION;
4791
0
        VkResult result = fp_negotiate_layer_version(interface_struct);
4792
4793
0
        if (result != VK_SUCCESS) {
4794
            // Layer no longer supports the loader's latest interface version so
4795
            // fail loading the Layer
4796
0
            return false;
4797
0
        }
4798
0
    }
4799
4800
0
    if (interface_struct->loaderLayerInterfaceVersion < MIN_SUPPORTED_LOADER_LAYER_INTERFACE_VERSION) {
4801
        // Loader no longer supports the layer's latest interface version so
4802
        // fail loading the layer
4803
0
        return false;
4804
0
    }
4805
4806
0
    return true;
4807
0
}
4808
4809
// Every extension that has a loader-defined trampoline needs to be marked as enabled or disabled so that we know whether or
4810
// not to return that trampoline when vkGetDeviceProcAddr is called
4811
void setup_logical_device_enabled_layer_extensions(const struct loader_instance *inst, struct loader_device *dev,
4812
                                                   const struct loader_extension_list *icd_exts,
4813
0
                                                   const VkDeviceCreateInfo *pCreateInfo) {
4814
    // no enabled extensions, early exit
4815
0
    if (pCreateInfo->ppEnabledExtensionNames == NULL) {
4816
0
        return;
4817
0
    }
4818
    // Can only setup debug marker as debug utils is an instance extensions.
4819
0
    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; ++i) {
4820
0
        if (pCreateInfo->ppEnabledExtensionNames[i] &&
4821
0
            !strcmp(pCreateInfo->ppEnabledExtensionNames[i], VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) {
4822
            // Check if its supported by the driver
4823
0
            for (uint32_t j = 0; j < icd_exts->count; ++j) {
4824
0
                if (!strcmp(icd_exts->list[j].extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) {
4825
0
                    dev->layer_extensions.ext_debug_marker_enabled = true;
4826
0
                }
4827
0
            }
4828
            // also check if any layers support it.
4829
0
            for (uint32_t j = 0; j < inst->app_activated_layer_list.count; j++) {
4830
0
                struct loader_layer_properties *layer = inst->app_activated_layer_list.list[j];
4831
0
                for (uint32_t k = 0; k < layer->device_extension_list.count; k++) {
4832
0
                    if (!strcmp(layer->device_extension_list.list[k].props.extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) {
4833
0
                        dev->layer_extensions.ext_debug_marker_enabled = true;
4834
0
                    }
4835
0
                }
4836
0
            }
4837
0
        }
4838
0
    }
4839
0
}
4840
4841
VKAPI_ATTR VkResult VKAPI_CALL loader_layer_create_device(VkInstance instance, VkPhysicalDevice physicalDevice,
4842
                                                          const VkDeviceCreateInfo *pCreateInfo,
4843
                                                          const VkAllocationCallbacks *pAllocator, VkDevice *pDevice,
4844
0
                                                          PFN_vkGetInstanceProcAddr layerGIPA, PFN_vkGetDeviceProcAddr *nextGDPA) {
4845
0
    VkResult res;
4846
0
    VkPhysicalDevice internal_device = VK_NULL_HANDLE;
4847
0
    struct loader_device *dev = NULL;
4848
0
    struct loader_instance *inst = NULL;
4849
4850
0
    if (instance != VK_NULL_HANDLE) {
4851
0
        inst = loader_get_instance(instance);
4852
0
        internal_device = physicalDevice;
4853
0
    } else {
4854
0
        struct loader_physical_device_tramp *phys_dev = (struct loader_physical_device_tramp *)physicalDevice;
4855
0
        internal_device = phys_dev->phys_dev;
4856
0
        inst = (struct loader_instance *)phys_dev->this_instance;
4857
0
    }
4858
4859
    // Get the physical device (ICD) extensions
4860
0
    struct loader_extension_list icd_exts = {0};
4861
0
    icd_exts.list = NULL;
4862
0
    res = loader_init_generic_list(inst, (struct loader_generic_list *)&icd_exts, sizeof(VkExtensionProperties));
4863
0
    if (VK_SUCCESS != res) {
4864
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "vkCreateDevice: Failed to create ICD extension list");
4865
0
        goto out;
4866
0
    }
4867
4868
0
    PFN_vkEnumerateDeviceExtensionProperties enumDeviceExtensionProperties = NULL;
4869
0
    if (layerGIPA != NULL) {
4870
0
        enumDeviceExtensionProperties =
4871
0
            (PFN_vkEnumerateDeviceExtensionProperties)layerGIPA(instance, "vkEnumerateDeviceExtensionProperties");
4872
0
    } else {
4873
0
        enumDeviceExtensionProperties = inst->disp->layer_inst_disp.EnumerateDeviceExtensionProperties;
4874
0
    }
4875
0
    res = loader_add_device_extensions(inst, enumDeviceExtensionProperties, internal_device, "Unknown", &icd_exts);
4876
0
    if (res != VK_SUCCESS) {
4877
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "vkCreateDevice: Failed to add extensions to list");
4878
0
        goto out;
4879
0
    }
4880
4881
    // Make sure requested extensions to be enabled are supported
4882
0
    res = loader_validate_device_extensions(inst, &inst->expanded_activated_layer_list, &icd_exts, pCreateInfo);
4883
0
    if (res != VK_SUCCESS) {
4884
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "vkCreateDevice: Failed to validate extensions in list");
4885
0
        goto out;
4886
0
    }
4887
4888
0
    dev = loader_create_logical_device(inst, pAllocator);
4889
0
    if (dev == NULL) {
4890
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
4891
0
        goto out;
4892
0
    }
4893
4894
0
    setup_logical_device_enabled_layer_extensions(inst, dev, &icd_exts, pCreateInfo);
4895
4896
0
    res = loader_create_device_chain(internal_device, pCreateInfo, pAllocator, inst, dev, layerGIPA, nextGDPA);
4897
0
    if (res != VK_SUCCESS) {
4898
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "vkCreateDevice:  Failed to create device chain.");
4899
0
        goto out;
4900
0
    }
4901
4902
0
    *pDevice = dev->chain_device;
4903
4904
    // Initialize any device extension dispatch entry's from the instance list
4905
0
    loader_init_dispatch_dev_ext(inst, dev);
4906
4907
    // Initialize WSI device extensions as part of core dispatch since loader
4908
    // has dedicated trampoline code for these
4909
0
    loader_init_device_extension_dispatch_table(&dev->loader_dispatch, inst->disp->layer_inst_disp.GetInstanceProcAddr,
4910
0
                                                dev->loader_dispatch.core_dispatch.GetDeviceProcAddr, inst->instance, *pDevice);
4911
4912
0
out:
4913
4914
    // Failure cleanup
4915
0
    if (VK_SUCCESS != res) {
4916
0
        if (NULL != dev) {
4917
            // Find the icd_term this device belongs to then remove it from that icd_term.
4918
            // Need to iterate the linked lists and remove the device from it. Don't delete
4919
            // the device here since it may not have been added to the icd_term and there
4920
            // are other allocations attached to it.
4921
0
            struct loader_icd_term *icd_term = inst->icd_terms;
4922
0
            bool found = false;
4923
0
            while (!found && NULL != icd_term) {
4924
0
                struct loader_device *cur_dev = icd_term->logical_device_list;
4925
0
                struct loader_device *prev_dev = NULL;
4926
0
                while (NULL != cur_dev) {
4927
0
                    if (cur_dev == dev) {
4928
0
                        if (cur_dev == icd_term->logical_device_list) {
4929
0
                            icd_term->logical_device_list = cur_dev->next;
4930
0
                        } else if (prev_dev) {
4931
0
                            prev_dev->next = cur_dev->next;
4932
0
                        }
4933
4934
0
                        found = true;
4935
0
                        break;
4936
0
                    }
4937
0
                    prev_dev = cur_dev;
4938
0
                    cur_dev = cur_dev->next;
4939
0
                }
4940
0
                icd_term = icd_term->next;
4941
0
            }
4942
            // Now destroy the device and the allocations associated with it.
4943
0
            loader_destroy_logical_device(dev, pAllocator);
4944
0
        }
4945
0
    }
4946
4947
0
    if (NULL != icd_exts.list) {
4948
0
        loader_destroy_generic_list(inst, (struct loader_generic_list *)&icd_exts);
4949
0
    }
4950
0
    return res;
4951
0
}
4952
4953
VKAPI_ATTR void VKAPI_CALL loader_layer_destroy_device(VkDevice device, const VkAllocationCallbacks *pAllocator,
4954
0
                                                       PFN_vkDestroyDevice destroyFunction) {
4955
0
    struct loader_device *dev;
4956
4957
0
    if (device == VK_NULL_HANDLE) {
4958
0
        return;
4959
0
    }
4960
4961
0
    struct loader_icd_term *icd_term = loader_get_icd_and_device(device, &dev);
4962
4963
0
    destroyFunction(device, pAllocator);
4964
0
    if (NULL != dev) {
4965
0
        dev->chain_device = NULL;
4966
0
        dev->icd_device = NULL;
4967
0
        loader_remove_logical_device(icd_term, dev, pAllocator);
4968
0
    }
4969
0
}
4970
4971
// Given the list of layers to activate in the loader_instance
4972
// structure. This function will add a VkLayerInstanceCreateInfo
4973
// structure to the VkInstanceCreateInfo.pNext pointer.
4974
// Each activated layer will have it's own VkLayerInstanceLink
4975
// structure that tells the layer what Get*ProcAddr to call to
4976
// get function pointers to the next layer down.
4977
// Once the chain info has been created this function will
4978
// execute the CreateInstance call chain. Each layer will
4979
// then have an opportunity in it's CreateInstance function
4980
// to setup it's dispatch table when the lower layer returns
4981
// successfully.
4982
// Each layer can wrap or not-wrap the returned VkInstance object
4983
// as it sees fit.
4984
// The instance chain is terminated by a loader function
4985
// that will call CreateInstance on all available ICD's and
4986
// cache those VkInstance objects for future use.
4987
VkResult loader_create_instance_chain(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator,
4988
0
                                      struct loader_instance *inst, VkInstance *created_instance) {
4989
0
    uint32_t num_activated_layers = 0;
4990
0
    struct activated_layer_info *activated_layers = NULL;
4991
0
    VkLayerInstanceCreateInfo chain_info;
4992
0
    VkLayerInstanceLink *layer_instance_link_info = NULL;
4993
0
    VkInstanceCreateInfo loader_create_info;
4994
0
    VkResult res;
4995
4996
0
    PFN_vkGetInstanceProcAddr next_gipa = loader_gpa_instance_terminator;
4997
0
    PFN_vkGetInstanceProcAddr cur_gipa = loader_gpa_instance_terminator;
4998
0
    PFN_vkGetDeviceProcAddr cur_gdpa = loader_gpa_device_terminator;
4999
0
    PFN_GetPhysicalDeviceProcAddr next_gpdpa = loader_gpdpa_instance_terminator;
5000
0
    PFN_GetPhysicalDeviceProcAddr cur_gpdpa = loader_gpdpa_instance_terminator;
5001
5002
0
    memcpy(&loader_create_info, pCreateInfo, sizeof(VkInstanceCreateInfo));
5003
5004
0
    if (inst->expanded_activated_layer_list.count > 0) {
5005
0
        chain_info.u.pLayerInfo = NULL;
5006
0
        chain_info.pNext = pCreateInfo->pNext;
5007
0
        chain_info.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
5008
0
        chain_info.function = VK_LAYER_LINK_INFO;
5009
0
        loader_create_info.pNext = &chain_info;
5010
5011
0
        layer_instance_link_info = loader_stack_alloc(sizeof(VkLayerInstanceLink) * inst->expanded_activated_layer_list.count);
5012
0
        if (!layer_instance_link_info) {
5013
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5014
0
                       "loader_create_instance_chain: Failed to alloc Instance objects for layer");
5015
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
5016
0
        }
5017
5018
0
        activated_layers = loader_stack_alloc(sizeof(struct activated_layer_info) * inst->expanded_activated_layer_list.count);
5019
0
        if (!activated_layers) {
5020
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5021
0
                       "loader_create_instance_chain: Failed to alloc activated layer storage array");
5022
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
5023
0
        }
5024
5025
        // Create instance chain of enabled layers
5026
0
        for (int32_t i = inst->expanded_activated_layer_list.count - 1; i >= 0; i--) {
5027
0
            struct loader_layer_properties *layer_prop = inst->expanded_activated_layer_list.list[i];
5028
0
            loader_platform_dl_handle lib_handle;
5029
5030
            // Skip it if a Layer with the same name has been already successfully activated
5031
0
            if (loader_names_array_has_layer_property(&layer_prop->info, num_activated_layers, activated_layers)) {
5032
0
                continue;
5033
0
            }
5034
5035
0
            lib_handle = loader_open_layer_file(inst, layer_prop);
5036
0
            if (layer_prop->lib_status == LOADER_LAYER_LIB_ERROR_OUT_OF_MEMORY) {
5037
0
                return VK_ERROR_OUT_OF_HOST_MEMORY;
5038
0
            }
5039
0
            if (!lib_handle) {
5040
0
                continue;
5041
0
            }
5042
5043
0
            if (NULL == layer_prop->functions.negotiate_layer_interface) {
5044
0
                PFN_vkNegotiateLoaderLayerInterfaceVersion negotiate_interface = NULL;
5045
0
                bool functions_in_interface = false;
5046
0
                if (!layer_prop->functions.str_negotiate_interface || strlen(layer_prop->functions.str_negotiate_interface) == 0) {
5047
0
                    negotiate_interface = (PFN_vkNegotiateLoaderLayerInterfaceVersion)loader_platform_get_proc_address(
5048
0
                        lib_handle, "vkNegotiateLoaderLayerInterfaceVersion");
5049
0
                } else {
5050
0
                    negotiate_interface = (PFN_vkNegotiateLoaderLayerInterfaceVersion)loader_platform_get_proc_address(
5051
0
                        lib_handle, layer_prop->functions.str_negotiate_interface);
5052
0
                }
5053
5054
                // If we can negotiate an interface version, then we can also
5055
                // get everything we need from the one function call, so try
5056
                // that first, and see if we can get all the function pointers
5057
                // necessary from that one call.
5058
0
                if (NULL != negotiate_interface) {
5059
0
                    layer_prop->functions.negotiate_layer_interface = negotiate_interface;
5060
5061
0
                    VkNegotiateLayerInterface interface_struct;
5062
5063
0
                    if (loader_get_layer_interface_version(negotiate_interface, &interface_struct)) {
5064
                        // Go ahead and set the properties version to the
5065
                        // correct value.
5066
0
                        layer_prop->interface_version = interface_struct.loaderLayerInterfaceVersion;
5067
5068
                        // If the interface is 2 or newer, we have access to the
5069
                        // new GetPhysicalDeviceProcAddr function, so grab it,
5070
                        // and the other necessary functions, from the
5071
                        // structure.
5072
0
                        if (interface_struct.loaderLayerInterfaceVersion > 1) {
5073
0
                            cur_gipa = interface_struct.pfnGetInstanceProcAddr;
5074
0
                            cur_gdpa = interface_struct.pfnGetDeviceProcAddr;
5075
0
                            cur_gpdpa = interface_struct.pfnGetPhysicalDeviceProcAddr;
5076
0
                            if (cur_gipa != NULL) {
5077
                                // We've set the functions, so make sure we
5078
                                // don't do the unnecessary calls later.
5079
0
                                functions_in_interface = true;
5080
0
                            }
5081
0
                        }
5082
0
                    }
5083
0
                }
5084
5085
0
                if (!functions_in_interface) {
5086
0
                    if ((cur_gipa = layer_prop->functions.get_instance_proc_addr) == NULL) {
5087
0
                        if (layer_prop->functions.str_gipa == NULL || strlen(layer_prop->functions.str_gipa) == 0) {
5088
0
                            cur_gipa =
5089
0
                                (PFN_vkGetInstanceProcAddr)loader_platform_get_proc_address(lib_handle, "vkGetInstanceProcAddr");
5090
0
                            layer_prop->functions.get_instance_proc_addr = cur_gipa;
5091
5092
0
                            if (NULL == cur_gipa) {
5093
0
                                loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
5094
0
                                           "loader_create_instance_chain: Failed to find \'vkGetInstanceProcAddr\' in layer \"%s\"",
5095
0
                                           layer_prop->lib_name);
5096
0
                                continue;
5097
0
                            }
5098
0
                        } else {
5099
0
                            cur_gipa = (PFN_vkGetInstanceProcAddr)loader_platform_get_proc_address(lib_handle,
5100
0
                                                                                                   layer_prop->functions.str_gipa);
5101
5102
0
                            if (NULL == cur_gipa) {
5103
0
                                loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
5104
0
                                           "loader_create_instance_chain: Failed to find \'%s\' in layer \"%s\"",
5105
0
                                           layer_prop->functions.str_gipa, layer_prop->lib_name);
5106
0
                                continue;
5107
0
                            }
5108
0
                        }
5109
0
                    }
5110
0
                }
5111
0
            }
5112
5113
0
            layer_instance_link_info[num_activated_layers].pNext = chain_info.u.pLayerInfo;
5114
0
            layer_instance_link_info[num_activated_layers].pfnNextGetInstanceProcAddr = next_gipa;
5115
0
            layer_instance_link_info[num_activated_layers].pfnNextGetPhysicalDeviceProcAddr = next_gpdpa;
5116
0
            next_gipa = cur_gipa;
5117
0
            if (layer_prop->interface_version > 1 && cur_gpdpa != NULL) {
5118
0
                layer_prop->functions.get_physical_device_proc_addr = cur_gpdpa;
5119
0
                next_gpdpa = cur_gpdpa;
5120
0
            }
5121
0
            if (layer_prop->interface_version > 1 && cur_gipa != NULL) {
5122
0
                layer_prop->functions.get_instance_proc_addr = cur_gipa;
5123
0
            }
5124
0
            if (layer_prop->interface_version > 1 && cur_gdpa != NULL) {
5125
0
                layer_prop->functions.get_device_proc_addr = cur_gdpa;
5126
0
            }
5127
5128
0
            chain_info.u.pLayerInfo = &layer_instance_link_info[num_activated_layers];
5129
5130
0
            res = fixup_library_binary_path(inst, &(layer_prop->lib_name), layer_prop->lib_handle, cur_gipa);
5131
0
            if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
5132
0
                return res;
5133
0
            }
5134
5135
0
            activated_layers[num_activated_layers].name = layer_prop->info.layerName;
5136
0
            activated_layers[num_activated_layers].manifest = layer_prop->manifest_file_name;
5137
0
            activated_layers[num_activated_layers].library = layer_prop->lib_name;
5138
0
            activated_layers[num_activated_layers].is_implicit = !(layer_prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER);
5139
0
            activated_layers[num_activated_layers].enabled_by_what = layer_prop->enabled_by_what;
5140
0
            if (activated_layers[num_activated_layers].is_implicit) {
5141
0
                activated_layers[num_activated_layers].disable_env = layer_prop->disable_env_var.name;
5142
0
                activated_layers[num_activated_layers].enable_name_env = layer_prop->enable_env_var.name;
5143
0
                activated_layers[num_activated_layers].enable_value_env = layer_prop->enable_env_var.value;
5144
0
            }
5145
5146
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Insert instance layer \"%s\" (%s)",
5147
0
                       layer_prop->info.layerName, layer_prop->lib_name);
5148
5149
0
            num_activated_layers++;
5150
0
        }
5151
0
    }
5152
5153
    // Make sure each layer requested by the application was actually loaded
5154
0
    for (uint32_t exp = 0; exp < inst->expanded_activated_layer_list.count; ++exp) {
5155
0
        struct loader_layer_properties *exp_layer_prop = inst->expanded_activated_layer_list.list[exp];
5156
0
        bool found = false;
5157
0
        for (uint32_t act = 0; act < num_activated_layers; ++act) {
5158
0
            if (!strcmp(activated_layers[act].name, exp_layer_prop->info.layerName)) {
5159
0
                found = true;
5160
0
                break;
5161
0
            }
5162
0
        }
5163
        // If it wasn't found, we want to at least log an error.  However, if it was enabled by the application directly,
5164
        // we want to return a bad layer error.
5165
0
        if (!found) {
5166
0
            bool app_requested = false;
5167
0
            for (uint32_t act = 0; act < pCreateInfo->enabledLayerCount; ++act) {
5168
0
                if (!strcmp(pCreateInfo->ppEnabledLayerNames[act], exp_layer_prop->info.layerName)) {
5169
0
                    app_requested = true;
5170
0
                    break;
5171
0
                }
5172
0
            }
5173
0
            VkFlags log_flag = VULKAN_LOADER_LAYER_BIT;
5174
0
            char ending = '.';
5175
0
            if (app_requested) {
5176
0
                log_flag |= VULKAN_LOADER_ERROR_BIT;
5177
0
                ending = '!';
5178
0
            } else {
5179
0
                log_flag |= VULKAN_LOADER_INFO_BIT;
5180
0
            }
5181
0
            switch (exp_layer_prop->lib_status) {
5182
0
                case LOADER_LAYER_LIB_NOT_LOADED:
5183
0
                    loader_log(inst, log_flag, 0, "Requested layer \"%s\" was not loaded%c", exp_layer_prop->info.layerName,
5184
0
                               ending);
5185
0
                    break;
5186
0
                case LOADER_LAYER_LIB_ERROR_WRONG_BIT_TYPE: {
5187
0
                    loader_log(inst, log_flag, 0, "Requested layer \"%s\" was wrong bit-type%c", exp_layer_prop->info.layerName,
5188
0
                               ending);
5189
0
                    break;
5190
0
                }
5191
0
                case LOADER_LAYER_LIB_ERROR_FAILED_TO_LOAD:
5192
0
                    loader_log(inst, log_flag, 0, "Requested layer \"%s\" failed to load%c", exp_layer_prop->info.layerName,
5193
0
                               ending);
5194
0
                    break;
5195
0
                case LOADER_LAYER_LIB_SUCCESS_LOADED:
5196
0
                case LOADER_LAYER_LIB_ERROR_OUT_OF_MEMORY:
5197
                    // Shouldn't be able to reach this but if it is, best to report a debug
5198
0
                    loader_log(inst, log_flag, 0,
5199
0
                               "Shouldn't reach this. A valid version of requested layer %s was loaded but was not found in the "
5200
0
                               "list of activated layers%c",
5201
0
                               exp_layer_prop->info.layerName, ending);
5202
0
                    break;
5203
0
            }
5204
0
            if (app_requested) {
5205
0
                return VK_ERROR_LAYER_NOT_PRESENT;
5206
0
            }
5207
0
        }
5208
0
    }
5209
5210
0
    VkLoaderFeatureFlags feature_flags = 0;
5211
#if defined(_WIN32)
5212
    feature_flags = windows_initialize_dxgi();
5213
#endif
5214
5215
    // The following line of code is actually invalid at least according to the Vulkan spec with header update 1.2.193 and onwards.
5216
    // The update required calls to vkGetInstanceProcAddr querying "global" functions (which includes vkCreateInstance) to pass NULL
5217
    // for the instance parameter. Because it wasn't required to be NULL before, there may be layers which expect the loader's
5218
    // behavior of passing a non-NULL value into vkGetInstanceProcAddr.
5219
    // In an abundance of caution, the incorrect code remains as is, with a big comment to indicate that its wrong
5220
0
    PFN_vkCreateInstance fpCreateInstance = (PFN_vkCreateInstance)next_gipa(*created_instance, "vkCreateInstance");
5221
0
    if (fpCreateInstance) {
5222
0
        VkLayerInstanceCreateInfo instance_dispatch;
5223
0
        instance_dispatch.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
5224
0
        instance_dispatch.pNext = loader_create_info.pNext;
5225
0
        instance_dispatch.function = VK_LOADER_DATA_CALLBACK;
5226
0
        instance_dispatch.u.pfnSetInstanceLoaderData = vkSetInstanceDispatch;
5227
5228
0
        VkLayerInstanceCreateInfo device_callback;
5229
0
        device_callback.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
5230
0
        device_callback.pNext = &instance_dispatch;
5231
0
        device_callback.function = VK_LOADER_LAYER_CREATE_DEVICE_CALLBACK;
5232
0
        device_callback.u.layerDevice.pfnLayerCreateDevice = loader_layer_create_device;
5233
0
        device_callback.u.layerDevice.pfnLayerDestroyDevice = loader_layer_destroy_device;
5234
5235
0
        VkLayerInstanceCreateInfo loader_features;
5236
0
        loader_features.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
5237
0
        loader_features.pNext = &device_callback;
5238
0
        loader_features.function = VK_LOADER_FEATURES;
5239
0
        loader_features.u.loaderFeatures = feature_flags;
5240
5241
0
        loader_create_info.pNext = &loader_features;
5242
5243
        // If layer debugging is enabled, let's print out the full callstack with layers in their
5244
        // defined order.
5245
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "vkCreateInstance layer callstack setup to:");
5246
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   <Application>");
5247
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "     ||");
5248
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   <Loader>");
5249
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "     ||");
5250
0
        for (uint32_t cur_layer = 0; cur_layer < num_activated_layers; ++cur_layer) {
5251
0
            uint32_t index = num_activated_layers - cur_layer - 1;
5252
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   %s", activated_layers[index].name);
5253
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Type: %s",
5254
0
                       activated_layers[index].is_implicit ? "Implicit" : "Explicit");
5255
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Enabled By: %s",
5256
0
                       get_enabled_by_what_str(activated_layers[index].enabled_by_what));
5257
0
            if (activated_layers[index].is_implicit) {
5258
0
                loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "               Disable Env Var:  %s",
5259
0
                           activated_layers[index].disable_env);
5260
0
                if (activated_layers[index].enable_name_env) {
5261
0
                    loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0,
5262
0
                               "               This layer was enabled because Env Var %s was set to Value %s",
5263
0
                               activated_layers[index].enable_name_env, activated_layers[index].enable_value_env);
5264
0
                }
5265
0
            }
5266
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Manifest: %s", activated_layers[index].manifest);
5267
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Library:  %s", activated_layers[index].library);
5268
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "     ||");
5269
0
        }
5270
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   <Drivers>");
5271
5272
0
        res = fpCreateInstance(&loader_create_info, pAllocator, created_instance);
5273
0
    } else {
5274
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_create_instance_chain: Failed to find \'vkCreateInstance\'");
5275
        // Couldn't find CreateInstance function!
5276
0
        res = VK_ERROR_INITIALIZATION_FAILED;
5277
0
    }
5278
5279
0
    if (res == VK_SUCCESS) {
5280
        // Copy the current disp table into the terminator_dispatch table so we can use it in loader_gpa_instance_terminator()
5281
0
        memcpy(&inst->terminator_dispatch, &inst->disp->layer_inst_disp, sizeof(VkLayerInstanceDispatchTable));
5282
5283
0
        loader_init_instance_core_dispatch_table(&inst->disp->layer_inst_disp, next_gipa, *created_instance);
5284
0
        inst->instance = *created_instance;
5285
5286
0
        if (pCreateInfo->enabledLayerCount > 0 && pCreateInfo->ppEnabledLayerNames != NULL) {
5287
0
            res = create_string_list(inst, pCreateInfo->enabledLayerCount, &inst->enabled_layer_names);
5288
0
            if (res != VK_SUCCESS) {
5289
0
                return res;
5290
0
            }
5291
5292
0
            for (uint32_t i = 0; i < pCreateInfo->enabledLayerCount; ++i) {
5293
0
                res = copy_str_to_string_list(inst, &inst->enabled_layer_names, pCreateInfo->ppEnabledLayerNames[i],
5294
0
                                              strlen(pCreateInfo->ppEnabledLayerNames[i]));
5295
0
                if (res != VK_SUCCESS) return res;
5296
0
            }
5297
0
        }
5298
0
    }
5299
5300
0
    return res;
5301
0
}
5302
5303
0
void loader_activate_instance_layer_extensions(struct loader_instance *inst, VkInstance created_inst) {
5304
0
    loader_init_instance_extension_dispatch_table(&inst->disp->layer_inst_disp, inst->disp->layer_inst_disp.GetInstanceProcAddr,
5305
0
                                                  created_inst);
5306
0
}
5307
5308
#if defined(__APPLE__)
5309
VkResult loader_create_device_chain(const VkPhysicalDevice pd, const VkDeviceCreateInfo *pCreateInfo,
5310
                                    const VkAllocationCallbacks *pAllocator, const struct loader_instance *inst,
5311
                                    struct loader_device *dev, PFN_vkGetInstanceProcAddr callingLayer,
5312
                                    PFN_vkGetDeviceProcAddr *layerNextGDPA) __attribute__((optnone)) {
5313
#else
5314
VkResult loader_create_device_chain(const VkPhysicalDevice pd, const VkDeviceCreateInfo *pCreateInfo,
5315
                                    const VkAllocationCallbacks *pAllocator, const struct loader_instance *inst,
5316
                                    struct loader_device *dev, PFN_vkGetInstanceProcAddr callingLayer,
5317
0
                                    PFN_vkGetDeviceProcAddr *layerNextGDPA) {
5318
0
#endif
5319
0
    uint32_t num_activated_layers = 0;
5320
0
    struct activated_layer_info *activated_layers = NULL;
5321
0
    VkLayerDeviceLink *layer_device_link_info;
5322
0
    VkLayerDeviceCreateInfo chain_info;
5323
0
    VkDeviceCreateInfo loader_create_info;
5324
0
    VkDeviceGroupDeviceCreateInfo *original_device_group_create_info_struct = NULL;
5325
0
    VkResult res;
5326
5327
0
    PFN_vkGetDeviceProcAddr fpGDPA = NULL, nextGDPA = loader_gpa_device_terminator;
5328
0
    PFN_vkGetInstanceProcAddr fpGIPA = NULL, nextGIPA = loader_gpa_instance_terminator;
5329
5330
0
    memcpy(&loader_create_info, pCreateInfo, sizeof(VkDeviceCreateInfo));
5331
5332
0
    if (loader_create_info.enabledLayerCount > 0 && loader_create_info.ppEnabledLayerNames != NULL) {
5333
0
        bool invalid_device_layer_usage = false;
5334
5335
0
        if (loader_create_info.enabledLayerCount != inst->enabled_layer_names.count && loader_create_info.enabledLayerCount > 0) {
5336
0
            invalid_device_layer_usage = true;
5337
0
        } else if (loader_create_info.enabledLayerCount > 0 && loader_create_info.ppEnabledLayerNames == NULL) {
5338
0
            invalid_device_layer_usage = true;
5339
0
        } else if (loader_create_info.enabledLayerCount == 0 && loader_create_info.ppEnabledLayerNames != NULL) {
5340
0
            invalid_device_layer_usage = true;
5341
0
        } else if (inst->enabled_layer_names.list != NULL) {
5342
0
            for (uint32_t i = 0; i < loader_create_info.enabledLayerCount; i++) {
5343
0
                const char *device_layer_names = loader_create_info.ppEnabledLayerNames[i];
5344
5345
0
                if (strcmp(device_layer_names, inst->enabled_layer_names.list[i]) != 0) {
5346
0
                    invalid_device_layer_usage = true;
5347
0
                    break;
5348
0
                }
5349
0
            }
5350
0
        }
5351
5352
0
        if (invalid_device_layer_usage) {
5353
0
            loader_log(
5354
0
                inst, VULKAN_LOADER_WARN_BIT, 0,
5355
0
                "loader_create_device_chain: Using deprecated and ignored 'ppEnabledLayerNames' member of 'VkDeviceCreateInfo' "
5356
0
                "when creating a Vulkan device.");
5357
0
        }
5358
0
    }
5359
5360
    // Before we continue, we need to find out if the KHR_device_group extension is in the enabled list.  If it is, we then
5361
    // need to look for the corresponding VkDeviceGroupDeviceCreateInfo struct in the device list.  This is because we
5362
    // need to replace all the incoming physical device values (which are really loader trampoline physical device values)
5363
    // with the layer/ICD version.
5364
0
    {
5365
0
        VkBaseOutStructure *pNext = (VkBaseOutStructure *)loader_create_info.pNext;
5366
0
        VkBaseOutStructure *pPrev = (VkBaseOutStructure *)&loader_create_info;
5367
0
        while (NULL != pNext) {
5368
0
            if (VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO == pNext->sType) {
5369
0
                VkDeviceGroupDeviceCreateInfo *cur_struct = (VkDeviceGroupDeviceCreateInfo *)pNext;
5370
0
                if (0 < cur_struct->physicalDeviceCount && NULL != cur_struct->pPhysicalDevices) {
5371
0
                    VkDeviceGroupDeviceCreateInfo *temp_struct = loader_stack_alloc(sizeof(VkDeviceGroupDeviceCreateInfo));
5372
0
                    VkPhysicalDevice *phys_dev_array = NULL;
5373
0
                    if (NULL == temp_struct) {
5374
0
                        return VK_ERROR_OUT_OF_HOST_MEMORY;
5375
0
                    }
5376
0
                    memcpy(temp_struct, cur_struct, sizeof(VkDeviceGroupDeviceCreateInfo));
5377
0
                    phys_dev_array = loader_stack_alloc(sizeof(VkPhysicalDevice) * cur_struct->physicalDeviceCount);
5378
0
                    if (NULL == phys_dev_array) {
5379
0
                        return VK_ERROR_OUT_OF_HOST_MEMORY;
5380
0
                    }
5381
5382
                    // Before calling down, replace the incoming physical device values (which are really loader trampoline
5383
                    // physical devices) with the next layer (or possibly even the terminator) physical device values.
5384
0
                    struct loader_physical_device_tramp *cur_tramp;
5385
0
                    for (uint32_t phys_dev = 0; phys_dev < cur_struct->physicalDeviceCount; phys_dev++) {
5386
0
                        cur_tramp = (struct loader_physical_device_tramp *)cur_struct->pPhysicalDevices[phys_dev];
5387
0
                        phys_dev_array[phys_dev] = cur_tramp->phys_dev;
5388
0
                    }
5389
0
                    temp_struct->pPhysicalDevices = phys_dev_array;
5390
5391
0
                    original_device_group_create_info_struct = (VkDeviceGroupDeviceCreateInfo *)pPrev->pNext;
5392
5393
                    // Replace the old struct in the pNext chain with this one.
5394
0
                    pPrev->pNext = (VkBaseOutStructure *)temp_struct;
5395
0
                }
5396
0
                break;
5397
0
            }
5398
5399
0
            pPrev = pNext;
5400
0
            pNext = pNext->pNext;
5401
0
        }
5402
0
    }
5403
0
    if (inst->expanded_activated_layer_list.count > 0) {
5404
0
        layer_device_link_info = loader_stack_alloc(sizeof(VkLayerDeviceLink) * inst->expanded_activated_layer_list.count);
5405
0
        if (!layer_device_link_info) {
5406
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5407
0
                       "loader_create_device_chain: Failed to alloc Device objects for layer. Skipping Layer.");
5408
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
5409
0
        }
5410
5411
0
        activated_layers = loader_stack_alloc(sizeof(struct activated_layer_info) * inst->expanded_activated_layer_list.count);
5412
0
        if (!activated_layers) {
5413
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5414
0
                       "loader_create_device_chain: Failed to alloc activated layer storage array");
5415
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
5416
0
        }
5417
5418
0
        chain_info.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
5419
0
        chain_info.function = VK_LAYER_LINK_INFO;
5420
0
        chain_info.u.pLayerInfo = NULL;
5421
0
        chain_info.pNext = loader_create_info.pNext;
5422
0
        loader_create_info.pNext = &chain_info;
5423
5424
        // Create instance chain of enabled layers
5425
0
        for (int32_t i = inst->expanded_activated_layer_list.count - 1; i >= 0; i--) {
5426
0
            struct loader_layer_properties *layer_prop = inst->expanded_activated_layer_list.list[i];
5427
0
            loader_platform_dl_handle lib_handle = layer_prop->lib_handle;
5428
5429
            // Skip it if a Layer with the same name has been already successfully activated
5430
0
            if (loader_names_array_has_layer_property(&layer_prop->info, num_activated_layers, activated_layers)) {
5431
0
                continue;
5432
0
            }
5433
5434
            // Skip the layer if the handle is NULL - this is likely because the library failed to load but wasn't removed from
5435
            // the list.
5436
0
            if (!lib_handle) {
5437
0
                continue;
5438
0
            }
5439
5440
            // The Get*ProcAddr pointers will already be filled in if they were received from either the json file or the
5441
            // version negotiation
5442
0
            if ((fpGIPA = layer_prop->functions.get_instance_proc_addr) == NULL) {
5443
0
                if (layer_prop->functions.str_gipa == NULL || strlen(layer_prop->functions.str_gipa) == 0) {
5444
0
                    fpGIPA = (PFN_vkGetInstanceProcAddr)loader_platform_get_proc_address(lib_handle, "vkGetInstanceProcAddr");
5445
0
                    layer_prop->functions.get_instance_proc_addr = fpGIPA;
5446
0
                } else
5447
0
                    fpGIPA =
5448
0
                        (PFN_vkGetInstanceProcAddr)loader_platform_get_proc_address(lib_handle, layer_prop->functions.str_gipa);
5449
0
                if (!fpGIPA) {
5450
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
5451
0
                               "loader_create_device_chain: Failed to find \'vkGetInstanceProcAddr\' in layer \"%s\".  "
5452
0
                               "Skipping layer.",
5453
0
                               layer_prop->lib_name);
5454
0
                    continue;
5455
0
                }
5456
0
            }
5457
5458
0
            if (fpGIPA == callingLayer) {
5459
0
                if (layerNextGDPA != NULL) {
5460
0
                    *layerNextGDPA = nextGDPA;
5461
0
                }
5462
                // Break here because if fpGIPA is the same as callingLayer, that means a layer is trying to create a device,
5463
                // and once we don't want to continue any further as the next layer will be the calling layer
5464
0
                break;
5465
0
            }
5466
5467
0
            if ((fpGDPA = layer_prop->functions.get_device_proc_addr) == NULL) {
5468
0
                if (layer_prop->functions.str_gdpa == NULL || strlen(layer_prop->functions.str_gdpa) == 0) {
5469
0
                    fpGDPA = (PFN_vkGetDeviceProcAddr)loader_platform_get_proc_address(lib_handle, "vkGetDeviceProcAddr");
5470
0
                    layer_prop->functions.get_device_proc_addr = fpGDPA;
5471
0
                } else
5472
0
                    fpGDPA = (PFN_vkGetDeviceProcAddr)loader_platform_get_proc_address(lib_handle, layer_prop->functions.str_gdpa);
5473
0
                if (!fpGDPA) {
5474
0
                    loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0,
5475
0
                               "Failed to find vkGetDeviceProcAddr in layer \"%s\"", layer_prop->lib_name);
5476
0
                    continue;
5477
0
                }
5478
0
            }
5479
5480
0
            layer_device_link_info[num_activated_layers].pNext = chain_info.u.pLayerInfo;
5481
0
            layer_device_link_info[num_activated_layers].pfnNextGetInstanceProcAddr = nextGIPA;
5482
0
            layer_device_link_info[num_activated_layers].pfnNextGetDeviceProcAddr = nextGDPA;
5483
0
            chain_info.u.pLayerInfo = &layer_device_link_info[num_activated_layers];
5484
0
            nextGIPA = fpGIPA;
5485
0
            nextGDPA = fpGDPA;
5486
5487
0
            activated_layers[num_activated_layers].name = layer_prop->info.layerName;
5488
0
            activated_layers[num_activated_layers].manifest = layer_prop->manifest_file_name;
5489
0
            activated_layers[num_activated_layers].library = layer_prop->lib_name;
5490
0
            activated_layers[num_activated_layers].is_implicit = !(layer_prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER);
5491
0
            activated_layers[num_activated_layers].enabled_by_what = layer_prop->enabled_by_what;
5492
0
            if (activated_layers[num_activated_layers].is_implicit) {
5493
0
                activated_layers[num_activated_layers].disable_env = layer_prop->disable_env_var.name;
5494
0
            }
5495
5496
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Inserted device layer \"%s\" (%s)",
5497
0
                       layer_prop->info.layerName, layer_prop->lib_name);
5498
5499
0
            num_activated_layers++;
5500
0
        }
5501
0
    }
5502
5503
0
    VkDevice created_device = (VkDevice)dev;
5504
0
    PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)nextGIPA(inst->instance, "vkCreateDevice");
5505
0
    if (fpCreateDevice) {
5506
0
        VkLayerDeviceCreateInfo create_info_disp;
5507
5508
0
        create_info_disp.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
5509
0
        create_info_disp.function = VK_LOADER_DATA_CALLBACK;
5510
5511
0
        create_info_disp.u.pfnSetDeviceLoaderData = vkSetDeviceDispatch;
5512
5513
        // If layer debugging is enabled, let's print out the full callstack with layers in their
5514
        // defined order.
5515
0
        uint32_t layer_driver_bits = VULKAN_LOADER_LAYER_BIT | VULKAN_LOADER_DRIVER_BIT;
5516
0
        loader_log(inst, layer_driver_bits, 0, "vkCreateDevice layer callstack setup to:");
5517
0
        loader_log(inst, layer_driver_bits, 0, "   <Application>");
5518
0
        loader_log(inst, layer_driver_bits, 0, "     ||");
5519
0
        loader_log(inst, layer_driver_bits, 0, "   <Loader>");
5520
0
        loader_log(inst, layer_driver_bits, 0, "     ||");
5521
0
        for (uint32_t cur_layer = 0; cur_layer < num_activated_layers; ++cur_layer) {
5522
0
            uint32_t index = num_activated_layers - cur_layer - 1;
5523
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   %s", activated_layers[index].name);
5524
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Type: %s",
5525
0
                       activated_layers[index].is_implicit ? "Implicit" : "Explicit");
5526
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Enabled By: %s",
5527
0
                       get_enabled_by_what_str(activated_layers[index].enabled_by_what));
5528
0
            if (activated_layers[index].is_implicit) {
5529
0
                loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "               Disable Env Var:  %s",
5530
0
                           activated_layers[index].disable_env);
5531
0
            }
5532
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Manifest: %s", activated_layers[index].manifest);
5533
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Library:  %s", activated_layers[index].library);
5534
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "     ||");
5535
0
        }
5536
0
        loader_log(inst, layer_driver_bits, 0, "   <Device>");
5537
0
        create_info_disp.pNext = loader_create_info.pNext;
5538
0
        loader_create_info.pNext = &create_info_disp;
5539
0
        res = fpCreateDevice(pd, &loader_create_info, pAllocator, &created_device);
5540
0
        if (res != VK_SUCCESS) {
5541
0
            return res;
5542
0
        }
5543
0
        dev->chain_device = created_device;
5544
5545
        // Because we changed the pNext chain to use our own VkDeviceGroupDeviceCreateInfo, we need to fixup the chain to
5546
        // point back at the original VkDeviceGroupDeviceCreateInfo.
5547
0
        VkBaseOutStructure *pNext = (VkBaseOutStructure *)loader_create_info.pNext;
5548
0
        VkBaseOutStructure *pPrev = (VkBaseOutStructure *)&loader_create_info;
5549
0
        while (NULL != pNext) {
5550
0
            if (VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO == pNext->sType) {
5551
0
                VkDeviceGroupDeviceCreateInfo *cur_struct = (VkDeviceGroupDeviceCreateInfo *)pNext;
5552
0
                if (0 < cur_struct->physicalDeviceCount && NULL != cur_struct->pPhysicalDevices) {
5553
0
                    pPrev->pNext = (VkBaseOutStructure *)original_device_group_create_info_struct;
5554
0
                }
5555
0
                break;
5556
0
            }
5557
5558
0
            pPrev = pNext;
5559
0
            pNext = pNext->pNext;
5560
0
        }
5561
5562
0
    } else {
5563
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5564
0
                   "loader_create_device_chain: Failed to find \'vkCreateDevice\' in layers or ICD");
5565
        // Couldn't find CreateDevice function!
5566
0
        return VK_ERROR_INITIALIZATION_FAILED;
5567
0
    }
5568
5569
    // Initialize device dispatch table
5570
0
    loader_init_device_dispatch_table(&dev->loader_dispatch, nextGDPA, dev->chain_device);
5571
    // Initialize the dispatch table to functions which need terminators
5572
    // These functions point directly to the driver, not the terminator functions
5573
0
    init_extension_device_proc_terminator_dispatch(dev);
5574
5575
0
    return res;
5576
0
}
5577
5578
VkResult loader_validate_layers(const struct loader_instance *inst, const uint32_t layer_count,
5579
0
                                const char *const *ppEnabledLayerNames, const struct loader_layer_list *list) {
5580
0
    struct loader_layer_properties *prop;
5581
5582
0
    if (layer_count > 0 && ppEnabledLayerNames == NULL) {
5583
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5584
0
                   "loader_validate_layers: ppEnabledLayerNames is NULL but enabledLayerCount is greater than zero");
5585
0
        return VK_ERROR_LAYER_NOT_PRESENT;
5586
0
    }
5587
5588
0
    for (uint32_t i = 0; i < layer_count; i++) {
5589
0
        VkStringErrorFlags result = vk_string_validate(MaxLoaderStringLength, ppEnabledLayerNames[i]);
5590
0
        if (result != VK_STRING_ERROR_NONE) {
5591
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5592
0
                       "loader_validate_layers: ppEnabledLayerNames contains string that is too long or is badly formed");
5593
0
            return VK_ERROR_LAYER_NOT_PRESENT;
5594
0
        }
5595
5596
0
        prop = loader_find_layer_property(ppEnabledLayerNames[i], list);
5597
0
        if (NULL == prop) {
5598
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5599
0
                       "loader_validate_layers: Layer %d does not exist in the list of available layers", i);
5600
0
            return VK_ERROR_LAYER_NOT_PRESENT;
5601
0
        }
5602
0
        if (inst->settings.settings_active && inst->settings.layer_configurations_active &&
5603
0
            prop->settings_control_value != LOADER_SETTINGS_LAYER_CONTROL_ON &&
5604
0
            prop->settings_control_value != LOADER_SETTINGS_LAYER_CONTROL_DEFAULT) {
5605
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5606
0
                       "loader_validate_layers: Layer %d was explicitly prevented from being enabled by the loader settings file",
5607
0
                       i);
5608
0
            return VK_ERROR_LAYER_NOT_PRESENT;
5609
0
        }
5610
0
    }
5611
0
    return VK_SUCCESS;
5612
0
}
5613
5614
VkResult loader_validate_instance_extensions(struct loader_instance *inst, const struct loader_extension_list *icd_exts,
5615
                                             const struct loader_layer_list *instance_layers,
5616
                                             const struct loader_envvar_all_filters *layer_filters,
5617
0
                                             const VkInstanceCreateInfo *pCreateInfo) {
5618
0
    VkExtensionProperties *extension_prop;
5619
0
    char *env_value;
5620
0
    char *enabled_layers_env = NULL;
5621
0
    bool check_if_known = true;
5622
0
    VkResult res = VK_SUCCESS;
5623
5624
0
    struct loader_pointer_layer_list active_layers = {0};
5625
0
    struct loader_pointer_layer_list expanded_layers = {0};
5626
5627
0
    if (pCreateInfo->enabledExtensionCount > 0 && pCreateInfo->ppEnabledExtensionNames == NULL) {
5628
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5629
0
                   "loader_validate_instance_extensions: Instance ppEnabledExtensionNames is NULL but enabledExtensionCount is "
5630
0
                   "greater than zero");
5631
0
        return VK_ERROR_EXTENSION_NOT_PRESENT;
5632
0
    }
5633
0
    if (!loader_init_pointer_layer_list(inst, &active_layers)) {
5634
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
5635
0
        goto out;
5636
0
    }
5637
0
    if (!loader_init_pointer_layer_list(inst, &expanded_layers)) {
5638
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
5639
0
        goto out;
5640
0
    }
5641
5642
0
    if (inst->settings.settings_active && inst->settings.layer_configurations_active) {
5643
0
        res = enable_correct_layers_from_settings(inst, layer_filters, pCreateInfo->enabledLayerCount,
5644
0
                                                  pCreateInfo->ppEnabledLayerNames, instance_layers, &active_layers,
5645
0
                                                  &expanded_layers);
5646
0
        if (res != VK_SUCCESS) {
5647
0
            goto out;
5648
0
        }
5649
0
    } else {
5650
0
        enabled_layers_env = loader_getenv(ENABLED_LAYERS_ENV, inst);
5651
5652
        // Build the lists of active layers (including meta layers) and expanded layers (with meta layers resolved to their
5653
        // components)
5654
0
        res =
5655
0
            loader_add_implicit_layers(inst, enabled_layers_env, layer_filters, &active_layers, &expanded_layers, instance_layers);
5656
0
        if (res != VK_SUCCESS) {
5657
0
            goto out;
5658
0
        }
5659
0
        res = loader_add_environment_layers(inst, enabled_layers_env, layer_filters, &active_layers, &expanded_layers,
5660
0
                                            instance_layers);
5661
0
        if (res != VK_SUCCESS) {
5662
0
            goto out;
5663
0
        }
5664
0
        res = loader_add_layer_names_to_list(inst, layer_filters, &active_layers, &expanded_layers, pCreateInfo->enabledLayerCount,
5665
0
                                             pCreateInfo->ppEnabledLayerNames, instance_layers);
5666
0
        if (VK_SUCCESS != res) {
5667
0
            goto out;
5668
0
        }
5669
0
    }
5670
0
    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
5671
0
        VkStringErrorFlags result = vk_string_validate(MaxLoaderStringLength, pCreateInfo->ppEnabledExtensionNames[i]);
5672
0
        if (result != VK_STRING_ERROR_NONE) {
5673
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5674
0
                       "loader_validate_instance_extensions: Instance ppEnabledExtensionNames contains "
5675
0
                       "string that is too long or is badly formed");
5676
0
            res = VK_ERROR_EXTENSION_NOT_PRESENT;
5677
0
            goto out;
5678
0
        }
5679
5680
        // Check if a user wants to disable the instance extension filtering behavior
5681
0
        env_value = loader_getenv("VK_LOADER_DISABLE_INST_EXT_FILTER", inst);
5682
0
        if (NULL != env_value && atoi(env_value) != 0) {
5683
0
            check_if_known = false;
5684
0
        }
5685
0
        loader_free_getenv(env_value, inst);
5686
5687
0
        if (check_if_known) {
5688
            // See if the extension is in the list of supported extensions
5689
0
            bool found = false;
5690
0
            for (uint32_t j = 0; LOADER_INSTANCE_EXTENSIONS[j] != NULL; j++) {
5691
0
                if (strcmp(pCreateInfo->ppEnabledExtensionNames[i], LOADER_INSTANCE_EXTENSIONS[j]) == 0) {
5692
0
                    found = true;
5693
0
                    break;
5694
0
                }
5695
0
            }
5696
5697
            // If it isn't in the list, return an error
5698
0
            if (!found) {
5699
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5700
0
                           "loader_validate_instance_extensions: Extension %s not found in list of known instance extensions.",
5701
0
                           pCreateInfo->ppEnabledExtensionNames[i]);
5702
0
                res = VK_ERROR_EXTENSION_NOT_PRESENT;
5703
0
                goto out;
5704
0
            }
5705
0
        }
5706
5707
0
        extension_prop = get_extension_property(pCreateInfo->ppEnabledExtensionNames[i], icd_exts);
5708
5709
0
        if (extension_prop) {
5710
0
            continue;
5711
0
        }
5712
5713
0
        extension_prop = NULL;
5714
5715
        // Not in global list, search layer extension lists
5716
0
        for (uint32_t j = 0; NULL == extension_prop && j < expanded_layers.count; ++j) {
5717
0
            extension_prop =
5718
0
                get_extension_property(pCreateInfo->ppEnabledExtensionNames[i], &expanded_layers.list[j]->instance_extension_list);
5719
0
            if (extension_prop) {
5720
                // Found the extension in one of the layers enabled by the app.
5721
0
                break;
5722
0
            }
5723
5724
0
            struct loader_layer_properties *layer_prop =
5725
0
                loader_find_layer_property(expanded_layers.list[j]->info.layerName, instance_layers);
5726
0
            if (NULL == layer_prop) {
5727
                // Should NOT get here, loader_validate_layers should have already filtered this case out.
5728
0
                continue;
5729
0
            }
5730
0
        }
5731
5732
0
        if (!extension_prop) {
5733
            // Didn't find extension name in any of the global layers, error out
5734
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5735
0
                       "loader_validate_instance_extensions: Instance extension %s not supported by available ICDs or enabled "
5736
0
                       "layers.",
5737
0
                       pCreateInfo->ppEnabledExtensionNames[i]);
5738
0
            res = VK_ERROR_EXTENSION_NOT_PRESENT;
5739
0
            goto out;
5740
0
        }
5741
0
    }
5742
5743
0
out:
5744
0
    loader_destroy_pointer_layer_list(inst, &active_layers);
5745
0
    loader_destroy_pointer_layer_list(inst, &expanded_layers);
5746
0
    if (enabled_layers_env != NULL) {
5747
0
        loader_free_getenv(enabled_layers_env, inst);
5748
0
    }
5749
5750
0
    return res;
5751
0
}
5752
5753
VkResult loader_validate_device_extensions(struct loader_instance *this_instance,
5754
                                           const struct loader_pointer_layer_list *activated_device_layers,
5755
0
                                           const struct loader_extension_list *icd_exts, const VkDeviceCreateInfo *pCreateInfo) {
5756
    // Early out to prevent nullptr dereference
5757
0
    if (pCreateInfo->enabledExtensionCount == 0 || pCreateInfo->ppEnabledExtensionNames == NULL) {
5758
0
        return VK_SUCCESS;
5759
0
    }
5760
0
    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
5761
0
        if (pCreateInfo->ppEnabledExtensionNames[i] == NULL) {
5762
0
            continue;
5763
0
        }
5764
0
        VkStringErrorFlags result = vk_string_validate(MaxLoaderStringLength, pCreateInfo->ppEnabledExtensionNames[i]);
5765
0
        if (result != VK_STRING_ERROR_NONE) {
5766
0
            loader_log(this_instance, VULKAN_LOADER_ERROR_BIT, 0,
5767
0
                       "loader_validate_device_extensions: Device ppEnabledExtensionNames contains "
5768
0
                       "string that is too long or is badly formed");
5769
0
            return VK_ERROR_EXTENSION_NOT_PRESENT;
5770
0
        }
5771
5772
0
        const char *extension_name = pCreateInfo->ppEnabledExtensionNames[i];
5773
0
        VkExtensionProperties *extension_prop = get_extension_property(extension_name, icd_exts);
5774
5775
0
        if (extension_prop) {
5776
0
            continue;
5777
0
        }
5778
5779
        // Not in global list, search activated layer extension lists
5780
0
        for (uint32_t j = 0; j < activated_device_layers->count; j++) {
5781
0
            struct loader_layer_properties *layer_prop = activated_device_layers->list[j];
5782
5783
0
            extension_prop = get_dev_extension_property(extension_name, &layer_prop->device_extension_list);
5784
0
            if (extension_prop) {
5785
                // Found the extension in one of the layers enabled by the app.
5786
0
                break;
5787
0
            }
5788
0
        }
5789
5790
0
        if (!extension_prop) {
5791
            // Didn't find extension name in any of the device layers, error out
5792
0
            loader_log(this_instance, VULKAN_LOADER_ERROR_BIT, 0,
5793
0
                       "loader_validate_device_extensions: Device extension %s not supported by selected physical device "
5794
0
                       "or enabled layers.",
5795
0
                       pCreateInfo->ppEnabledExtensionNames[i]);
5796
0
            return VK_ERROR_EXTENSION_NOT_PRESENT;
5797
0
        }
5798
0
    }
5799
0
    return VK_SUCCESS;
5800
0
}
5801
5802
// Terminator functions for the Instance chain
5803
// All named terminator_<Vulkan API name>
5804
VKAPI_ATTR VkResult VKAPI_CALL terminator_CreateInstance(const VkInstanceCreateInfo *pCreateInfo,
5805
0
                                                         const VkAllocationCallbacks *pAllocator, VkInstance *pInstance) {
5806
0
    struct loader_icd_term *icd_term = NULL;
5807
0
    VkExtensionProperties *prop = NULL;
5808
0
    char **filtered_extension_names = NULL;
5809
0
    VkInstanceCreateInfo icd_create_info = {0};
5810
0
    VkResult res = VK_SUCCESS;
5811
0
    bool one_icd_successful = false;
5812
5813
0
    struct loader_instance *ptr_instance = (struct loader_instance *)*pInstance;
5814
0
    if (NULL == ptr_instance) {
5815
0
        loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
5816
0
                   "terminator_CreateInstance: Loader instance pointer null encountered.  Possibly set by active layer. (Policy "
5817
0
                   "#LLP_LAYER_21)");
5818
0
    } else if (LOADER_MAGIC_NUMBER != ptr_instance->magic) {
5819
0
        loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
5820
0
                   "terminator_CreateInstance: Instance pointer (%p) has invalid MAGIC value 0x%08" PRIx64
5821
0
                   ". Instance value possibly "
5822
0
                   "corrupted by active layer (Policy #LLP_LAYER_21).  ",
5823
0
                   ptr_instance, ptr_instance->magic);
5824
0
    }
5825
5826
    // Save the application version if it has been modified - layers sometimes needs features in newer API versions than
5827
    // what the application requested, and thus will increase the instance version to a level that suites their needs.
5828
0
    if (pCreateInfo->pApplicationInfo && pCreateInfo->pApplicationInfo->apiVersion) {
5829
0
        loader_api_version altered_version = loader_make_version(pCreateInfo->pApplicationInfo->apiVersion);
5830
0
        if (altered_version.major != ptr_instance->app_api_version.major ||
5831
0
            altered_version.minor != ptr_instance->app_api_version.minor) {
5832
0
            ptr_instance->app_api_version = altered_version;
5833
0
        }
5834
0
    }
5835
5836
0
    memcpy(&icd_create_info, pCreateInfo, sizeof(icd_create_info));
5837
5838
0
    icd_create_info.enabledLayerCount = 0;
5839
0
    icd_create_info.ppEnabledLayerNames = NULL;
5840
5841
    // NOTE: Need to filter the extensions to only those supported by the ICD.
5842
    //       No ICD will advertise support for layers. An ICD library could
5843
    //       support a layer, but it would be independent of the actual ICD,
5844
    //       just in the same library.
5845
0
    uint32_t extension_count = pCreateInfo->enabledExtensionCount;
5846
0
#if defined(LOADER_ENABLE_LINUX_SORT)
5847
0
    extension_count += 1;
5848
0
#endif  // LOADER_ENABLE_LINUX_SORT
5849
0
    filtered_extension_names = loader_stack_alloc(extension_count * sizeof(char *));
5850
0
    if (!filtered_extension_names) {
5851
0
        loader_log(ptr_instance, VULKAN_LOADER_ERROR_BIT, 0,
5852
0
                   "terminator_CreateInstance: Failed create extension name array for %d extensions", extension_count);
5853
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
5854
0
        goto out;
5855
0
    }
5856
0
    icd_create_info.ppEnabledExtensionNames = (const char *const *)filtered_extension_names;
5857
5858
    // Determine if Get Physical Device Properties 2 is available to this Instance
5859
0
    if (pCreateInfo->pApplicationInfo && pCreateInfo->pApplicationInfo->apiVersion >= VK_API_VERSION_1_1) {
5860
0
        ptr_instance->supports_get_dev_prop_2 = true;
5861
0
    } else {
5862
0
        for (uint32_t j = 0; j < pCreateInfo->enabledExtensionCount; j++) {
5863
0
            if (!strcmp(pCreateInfo->ppEnabledExtensionNames[j], VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
5864
0
                ptr_instance->supports_get_dev_prop_2 = true;
5865
0
                break;
5866
0
            }
5867
0
        }
5868
0
    }
5869
5870
0
    for (uint32_t i = 0; i < ptr_instance->icd_tramp_list.count; i++) {
5871
0
        icd_term = loader_icd_add(ptr_instance, &ptr_instance->icd_tramp_list.scanned_list[i]);
5872
0
        if (NULL == icd_term) {
5873
0
            loader_log(ptr_instance, VULKAN_LOADER_ERROR_BIT, 0,
5874
0
                       "terminator_CreateInstance: Failed to add ICD %d to ICD trampoline list.", i);
5875
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
5876
0
            goto out;
5877
0
        }
5878
5879
        // If any error happens after here, we need to remove the ICD from the list,
5880
        // because we've already added it, but haven't validated it
5881
5882
        // Make sure that we reset the pApplicationInfo so we don't get an old pointer
5883
0
        icd_create_info.pApplicationInfo = pCreateInfo->pApplicationInfo;
5884
0
        icd_create_info.enabledExtensionCount = 0;
5885
0
        struct loader_extension_list icd_exts = {0};
5886
5887
        // traverse scanned icd list adding non-duplicate extensions to the list
5888
0
        res = loader_init_generic_list(ptr_instance, (struct loader_generic_list *)&icd_exts, sizeof(VkExtensionProperties));
5889
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
5890
            // If out of memory, bail immediately.
5891
0
            goto out;
5892
0
        } else if (VK_SUCCESS != res) {
5893
            // Something bad happened with this ICD, so free it and try the
5894
            // next.
5895
0
            ptr_instance->icd_terms = icd_term->next;
5896
0
            icd_term->next = NULL;
5897
0
            loader_icd_destroy(ptr_instance, icd_term, pAllocator);
5898
0
            continue;
5899
0
        }
5900
5901
0
        res = loader_add_instance_extensions(ptr_instance, icd_term->scanned_icd->EnumerateInstanceExtensionProperties,
5902
0
                                             icd_term->scanned_icd->lib_name, &icd_exts);
5903
0
        if (VK_SUCCESS != res) {
5904
0
            loader_destroy_generic_list(ptr_instance, (struct loader_generic_list *)&icd_exts);
5905
0
            if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
5906
                // If out of memory, bail immediately.
5907
0
                goto out;
5908
0
            } else {
5909
                // Something bad happened with this ICD, so free it and try the next.
5910
0
                ptr_instance->icd_terms = icd_term->next;
5911
0
                icd_term->next = NULL;
5912
0
                loader_icd_destroy(ptr_instance, icd_term, pAllocator);
5913
0
                continue;
5914
0
            }
5915
0
        }
5916
5917
0
        for (uint32_t j = 0; j < pCreateInfo->enabledExtensionCount; j++) {
5918
0
            prop = get_extension_property(pCreateInfo->ppEnabledExtensionNames[j], &icd_exts);
5919
0
            if (prop) {
5920
0
                filtered_extension_names[icd_create_info.enabledExtensionCount] = (char *)pCreateInfo->ppEnabledExtensionNames[j];
5921
0
                icd_create_info.enabledExtensionCount++;
5922
0
            }
5923
0
        }
5924
0
#if defined(LOADER_ENABLE_LINUX_SORT)
5925
        // Force on "VK_KHR_get_physical_device_properties2" for Linux as we use it for GPU sorting.  This
5926
        // should be done if the API version of either the application or the driver does not natively support
5927
        // the core version of vkGetPhysicalDeviceProperties2 entrypoint.
5928
0
        if ((ptr_instance->app_api_version.major == 1 && ptr_instance->app_api_version.minor == 0) ||
5929
0
            (VK_API_VERSION_MAJOR(icd_term->scanned_icd->api_version) == 1 &&
5930
0
             VK_API_VERSION_MINOR(icd_term->scanned_icd->api_version) == 0)) {
5931
0
            prop = get_extension_property(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, &icd_exts);
5932
0
            if (prop) {
5933
0
                filtered_extension_names[icd_create_info.enabledExtensionCount] =
5934
0
                    (char *)VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
5935
0
                icd_create_info.enabledExtensionCount++;
5936
5937
                // At least one ICD supports this, so the instance should be able to support it
5938
0
                ptr_instance->supports_get_dev_prop_2 = true;
5939
0
            }
5940
0
        }
5941
0
#endif  // LOADER_ENABLE_LINUX_SORT
5942
5943
        // Determine if vkGetPhysicalDeviceProperties2 is available to this Instance
5944
        // Also determine if VK_EXT_surface_maintenance1 is available on the ICD
5945
0
        if (icd_term->scanned_icd->api_version >= VK_API_VERSION_1_1) {
5946
0
            icd_term->enabled_instance_extensions.khr_get_physical_device_properties2 = true;
5947
0
        }
5948
0
        fill_out_enabled_instance_extensions(icd_create_info.enabledExtensionCount, (const char *const *)filtered_extension_names,
5949
0
                                             &icd_term->enabled_instance_extensions);
5950
5951
0
        loader_destroy_generic_list(ptr_instance, (struct loader_generic_list *)&icd_exts);
5952
5953
        // Get the driver version from vkEnumerateInstanceVersion
5954
0
        uint32_t icd_version = VK_API_VERSION_1_0;
5955
0
        VkResult icd_result = VK_SUCCESS;
5956
0
        if (icd_term->scanned_icd->api_version >= VK_API_VERSION_1_1) {
5957
0
            PFN_vkEnumerateInstanceVersion icd_enumerate_instance_version =
5958
0
                (PFN_vkEnumerateInstanceVersion)icd_term->scanned_icd->GetInstanceProcAddr(NULL, "vkEnumerateInstanceVersion");
5959
0
            if (icd_enumerate_instance_version != NULL) {
5960
0
                icd_result = icd_enumerate_instance_version(&icd_version);
5961
0
                if (icd_result != VK_SUCCESS) {
5962
0
                    icd_version = VK_API_VERSION_1_0;
5963
0
                    loader_log(ptr_instance, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
5964
0
                               "terminator_CreateInstance: ICD \"%s\" vkEnumerateInstanceVersion returned error. The ICD will be "
5965
0
                               "treated as a 1.0 ICD",
5966
0
                               icd_term->scanned_icd->lib_name);
5967
0
                } else if (VK_API_VERSION_MINOR(icd_version) == 0) {
5968
0
                    loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
5969
0
                               "terminator_CreateInstance: Manifest ICD for \"%s\" contained a 1.1 or greater API version, but "
5970
0
                               "vkEnumerateInstanceVersion returned 1.0, treating as a 1.0 ICD",
5971
0
                               icd_term->scanned_icd->lib_name);
5972
0
                }
5973
0
            } else {
5974
0
                loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
5975
0
                           "terminator_CreateInstance: Manifest ICD for \"%s\" contained a 1.1 or greater API version, but does "
5976
0
                           "not support vkEnumerateInstanceVersion, treating as a 1.0 ICD",
5977
0
                           icd_term->scanned_icd->lib_name);
5978
0
            }
5979
0
        }
5980
5981
        // Remove the portability enumeration flag bit if the ICD doesn't support the extension
5982
0
        if ((pCreateInfo->flags & VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR) == 1) {
5983
0
            bool supports_portability_enumeration = false;
5984
0
            for (uint32_t j = 0; j < icd_create_info.enabledExtensionCount; j++) {
5985
0
                if (strcmp(filtered_extension_names[j], VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) {
5986
0
                    supports_portability_enumeration = true;
5987
0
                    break;
5988
0
                }
5989
0
            }
5990
            // If the icd supports the extension, use the flags as given, otherwise remove the portability bit
5991
0
            icd_create_info.flags = supports_portability_enumeration
5992
0
                                        ? pCreateInfo->flags
5993
0
                                        : pCreateInfo->flags & (~VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR);
5994
0
        }
5995
5996
        // Create an instance, substituting the version to 1.0 if necessary
5997
0
        VkApplicationInfo icd_app_info = {0};
5998
0
        const uint32_t api_variant = 0;
5999
0
        const uint32_t api_version_1_0 = VK_API_VERSION_1_0;
6000
0
        uint32_t icd_version_nopatch =
6001
0
            VK_MAKE_API_VERSION(api_variant, VK_API_VERSION_MAJOR(icd_version), VK_API_VERSION_MINOR(icd_version), 0);
6002
0
        uint32_t requested_version = (pCreateInfo == NULL || pCreateInfo->pApplicationInfo == NULL)
6003
0
                                         ? api_version_1_0
6004
0
                                         : pCreateInfo->pApplicationInfo->apiVersion;
6005
0
        if ((requested_version != 0) && (icd_version_nopatch == api_version_1_0)) {
6006
0
            if (icd_create_info.pApplicationInfo == NULL) {
6007
0
                memset(&icd_app_info, 0, sizeof(icd_app_info));
6008
0
            } else {
6009
0
                memmove(&icd_app_info, icd_create_info.pApplicationInfo, sizeof(icd_app_info));
6010
0
            }
6011
0
            icd_app_info.apiVersion = icd_version;
6012
0
            icd_create_info.pApplicationInfo = &icd_app_info;
6013
0
        }
6014
6015
        // If the settings file has device_configurations, we need to raise the ApiVersion drivers use to 1.1 if the driver
6016
        // supports 1.1 or higher. This allows 1.0 apps to use the device_configurations without the app having to set its own
6017
        // ApiVersion to 1.1 on its own.
6018
0
        if (ptr_instance->settings.settings_active && ptr_instance->settings.device_configurations_active &&
6019
0
            ptr_instance->settings.device_configuration_count > 0 && icd_version >= VK_API_VERSION_1_1 &&
6020
0
            requested_version < VK_API_VERSION_1_1) {
6021
0
            if (NULL != pCreateInfo->pApplicationInfo) {
6022
0
                memcpy(&icd_app_info, pCreateInfo->pApplicationInfo, sizeof(VkApplicationInfo));
6023
0
            }
6024
0
            icd_app_info.apiVersion = VK_API_VERSION_1_1;
6025
0
            icd_create_info.pApplicationInfo = &icd_app_info;
6026
6027
0
            loader_log(
6028
0
                ptr_instance, VULKAN_LOADER_INFO_BIT, 0,
6029
0
                "terminator_CreateInstance: Raising the VkApplicationInfo::apiVersion from 1.0 to 1.1 on driver \"%s\" so that "
6030
0
                "the loader settings file is able to use this driver in the device_configuration selection logic.",
6031
0
                icd_term->scanned_icd->lib_name);
6032
0
        }
6033
6034
0
        icd_result =
6035
0
            ptr_instance->icd_tramp_list.scanned_list[i].CreateInstance(&icd_create_info, pAllocator, &(icd_term->instance));
6036
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == icd_result) {
6037
            // If out of memory, bail immediately.
6038
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
6039
0
            goto out;
6040
0
        } else if (VK_SUCCESS != icd_result) {
6041
0
            loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
6042
0
                       "terminator_CreateInstance: Received return code %i from call to vkCreateInstance in ICD %s. Skipping "
6043
0
                       "this driver.",
6044
0
                       icd_result, icd_term->scanned_icd->lib_name);
6045
0
            ptr_instance->icd_terms = icd_term->next;
6046
0
            icd_term->next = NULL;
6047
0
            loader_icd_destroy(ptr_instance, icd_term, pAllocator);
6048
0
            continue;
6049
0
        }
6050
6051
0
        if (!loader_icd_init_entries(ptr_instance, icd_term)) {
6052
0
            loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
6053
0
                       "terminator_CreateInstance: Failed to find required entrypoints in ICD %s. Skipping this driver.",
6054
0
                       icd_term->scanned_icd->lib_name);
6055
0
            ptr_instance->icd_terms = icd_term->next;
6056
0
            icd_term->next = NULL;
6057
0
            loader_icd_destroy(ptr_instance, icd_term, pAllocator);
6058
0
            continue;
6059
0
        }
6060
6061
0
        if (ptr_instance->icd_tramp_list.scanned_list[i].interface_version < 3 &&
6062
0
            (
6063
0
#if defined(VK_USE_PLATFORM_XLIB_KHR)
6064
0
                NULL != icd_term->dispatch.CreateXlibSurfaceKHR ||
6065
0
#endif  // VK_USE_PLATFORM_XLIB_KHR
6066
0
#if defined(VK_USE_PLATFORM_XCB_KHR)
6067
0
                NULL != icd_term->dispatch.CreateXcbSurfaceKHR ||
6068
0
#endif  // VK_USE_PLATFORM_XCB_KHR
6069
0
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
6070
0
                NULL != icd_term->dispatch.CreateWaylandSurfaceKHR ||
6071
0
#endif  // VK_USE_PLATFORM_WAYLAND_KHR
6072
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
6073
                NULL != icd_term->dispatch.CreateAndroidSurfaceKHR ||
6074
#endif  // VK_USE_PLATFORM_ANDROID_KHR
6075
#if defined(VK_USE_PLATFORM_WIN32_KHR)
6076
                NULL != icd_term->dispatch.CreateWin32SurfaceKHR ||
6077
#endif  // VK_USE_PLATFORM_WIN32_KHR
6078
0
                NULL != icd_term->dispatch.DestroySurfaceKHR)) {
6079
0
            loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
6080
0
                       "terminator_CreateInstance: Driver %s supports interface version %u but still exposes VkSurfaceKHR"
6081
0
                       " create/destroy entrypoints (Policy #LDP_DRIVER_8)",
6082
0
                       ptr_instance->icd_tramp_list.scanned_list[i].lib_name,
6083
0
                       ptr_instance->icd_tramp_list.scanned_list[i].interface_version);
6084
0
        }
6085
6086
        // If we made it this far, at least one ICD was successful
6087
0
        one_icd_successful = true;
6088
0
    }
6089
6090
    // For vkGetPhysicalDeviceProperties2, at least one ICD needs to support the extension for the
6091
    // instance to have it
6092
0
    if (ptr_instance->enabled_extensions.khr_get_physical_device_properties2) {
6093
0
        bool at_least_one_supports = false;
6094
0
        icd_term = ptr_instance->icd_terms;
6095
0
        while (icd_term != NULL) {
6096
0
            if (icd_term->enabled_instance_extensions.khr_get_physical_device_properties2) {
6097
0
                at_least_one_supports = true;
6098
0
                break;
6099
0
            }
6100
0
            icd_term = icd_term->next;
6101
0
        }
6102
0
        if (!at_least_one_supports) {
6103
0
            ptr_instance->enabled_extensions.khr_get_physical_device_properties2 = false;
6104
0
        }
6105
0
    }
6106
6107
    // If no ICDs were added to instance list and res is unchanged from it's initial value, the loader was unable to
6108
    // find a suitable ICD.
6109
0
    if (VK_SUCCESS == res && (ptr_instance->icd_terms == NULL || !one_icd_successful)) {
6110
0
        loader_log(ptr_instance, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6111
0
                   "terminator_CreateInstance: Found no drivers!");
6112
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
6113
0
    }
6114
6115
0
out:
6116
6117
0
    ptr_instance->create_terminator_invalid_extension = false;
6118
6119
0
    if (VK_SUCCESS != res) {
6120
0
        if (VK_ERROR_EXTENSION_NOT_PRESENT == res) {
6121
0
            ptr_instance->create_terminator_invalid_extension = true;
6122
0
        }
6123
6124
0
        while (NULL != ptr_instance->icd_terms) {
6125
0
            icd_term = ptr_instance->icd_terms;
6126
0
            ptr_instance->icd_terms = icd_term->next;
6127
0
            if (NULL != icd_term->instance) {
6128
0
                loader_icd_close_objects(ptr_instance, icd_term);
6129
0
                icd_term->dispatch.DestroyInstance(icd_term->instance, pAllocator);
6130
0
            }
6131
0
            loader_icd_destroy(ptr_instance, icd_term, pAllocator);
6132
0
        }
6133
0
    } else {
6134
        // Check for enabled extensions here to setup the loader structures so the loader knows what extensions
6135
        // it needs to worry about.
6136
        // We do it here and again above the layers in the trampoline function since the trampoline function
6137
        // may think different extensions are enabled than what's down here.
6138
        // This is why we don't clear inside of these function calls.
6139
        // The clearing should actually be handled by the overall memset of the pInstance structure in the
6140
        // trampoline.
6141
0
        fill_out_enabled_instance_extensions(pCreateInfo->enabledExtensionCount, pCreateInfo->ppEnabledExtensionNames,
6142
0
                                             &ptr_instance->enabled_extensions);
6143
0
    }
6144
6145
0
    return res;
6146
0
}
6147
6148
0
VKAPI_ATTR void VKAPI_CALL terminator_DestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) {
6149
0
    struct loader_instance *ptr_instance = loader_get_instance(instance);
6150
0
    if (NULL == ptr_instance) {
6151
0
        return;
6152
0
    }
6153
6154
    // Remove this instance from the list of instances:
6155
0
    struct loader_instance *prev = NULL;
6156
0
    loader_platform_thread_lock_mutex(&loader_global_instance_list_lock);
6157
0
    struct loader_instance *next = loader.instances;
6158
0
    while (next != NULL) {
6159
0
        if (next == ptr_instance) {
6160
            // Remove this instance from the list:
6161
0
            if (prev)
6162
0
                prev->next = next->next;
6163
0
            else
6164
0
                loader.instances = next->next;
6165
0
            break;
6166
0
        }
6167
0
        prev = next;
6168
0
        next = next->next;
6169
0
    }
6170
0
    loader_platform_thread_unlock_mutex(&loader_global_instance_list_lock);
6171
6172
0
    struct loader_icd_term *icd_terms = ptr_instance->icd_terms;
6173
0
    while (NULL != icd_terms) {
6174
0
        if (icd_terms->instance) {
6175
0
            loader_icd_close_objects(ptr_instance, icd_terms);
6176
0
            icd_terms->dispatch.DestroyInstance(icd_terms->instance, pAllocator);
6177
0
        }
6178
0
        struct loader_icd_term *next_icd_term = icd_terms->next;
6179
0
        icd_terms->instance = VK_NULL_HANDLE;
6180
0
        loader_icd_destroy(ptr_instance, icd_terms, pAllocator);
6181
6182
0
        icd_terms = next_icd_term;
6183
0
    }
6184
6185
0
    loader_clear_scanned_icd_list(ptr_instance, &ptr_instance->icd_tramp_list);
6186
0
    loader_destroy_generic_list(ptr_instance, (struct loader_generic_list *)&ptr_instance->ext_list);
6187
0
    if (NULL != ptr_instance->phys_devs_term) {
6188
0
        for (uint32_t i = 0; i < ptr_instance->phys_dev_count_term; i++) {
6189
0
            for (uint32_t j = i + 1; j < ptr_instance->phys_dev_count_term; j++) {
6190
0
                if (ptr_instance->phys_devs_term[i] == ptr_instance->phys_devs_term[j]) {
6191
0
                    ptr_instance->phys_devs_term[j] = NULL;
6192
0
                }
6193
0
            }
6194
0
        }
6195
0
        for (uint32_t i = 0; i < ptr_instance->phys_dev_count_term; i++) {
6196
0
            loader_instance_heap_free(ptr_instance, ptr_instance->phys_devs_term[i]);
6197
0
        }
6198
0
        loader_instance_heap_free(ptr_instance, ptr_instance->phys_devs_term);
6199
0
    }
6200
0
    if (NULL != ptr_instance->phys_dev_groups_term) {
6201
0
        for (uint32_t i = 0; i < ptr_instance->phys_dev_group_count_term; i++) {
6202
0
            loader_instance_heap_free(ptr_instance, ptr_instance->phys_dev_groups_term[i]);
6203
0
        }
6204
0
        loader_instance_heap_free(ptr_instance, ptr_instance->phys_dev_groups_term);
6205
0
    }
6206
0
    loader_free_dev_ext_table(ptr_instance);
6207
0
    loader_free_phys_dev_ext_table(ptr_instance);
6208
6209
0
    free_string_list(ptr_instance, &ptr_instance->enabled_layer_names);
6210
0
}
6211
6212
VKAPI_ATTR VkResult VKAPI_CALL terminator_CreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo *pCreateInfo,
6213
0
                                                       const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) {
6214
0
    VkResult res = VK_SUCCESS;
6215
0
    struct loader_physical_device_term *phys_dev_term;
6216
0
    phys_dev_term = (struct loader_physical_device_term *)physicalDevice;
6217
0
    struct loader_icd_term *icd_term = phys_dev_term->this_icd_term;
6218
6219
0
    struct loader_device *dev = (struct loader_device *)*pDevice;
6220
0
    PFN_vkCreateDevice fpCreateDevice = icd_term->dispatch.CreateDevice;
6221
0
    struct loader_extension_list icd_exts;
6222
6223
0
    VkBaseOutStructure *caller_dgci_container = NULL;
6224
0
    VkDeviceGroupDeviceCreateInfo *caller_dgci = NULL;
6225
6226
0
    if (NULL == dev) {
6227
0
        loader_log(icd_term->this_instance, VULKAN_LOADER_WARN_BIT, 0,
6228
0
                   "terminator_CreateDevice: Loader device pointer null encountered.  Possibly set by active layer. (Policy "
6229
0
                   "#LLP_LAYER_22)");
6230
0
    } else if (DEVICE_DISP_TABLE_MAGIC_NUMBER != dev->loader_dispatch.core_dispatch.magic) {
6231
0
        loader_log(icd_term->this_instance, VULKAN_LOADER_WARN_BIT, 0,
6232
0
                   "terminator_CreateDevice: Device pointer (%p) has invalid MAGIC value 0x%08" PRIx64
6233
0
                   ". The expected value is "
6234
0
                   "0x10ADED040410ADED. Device value possibly "
6235
0
                   "corrupted by active layer (Policy #LLP_LAYER_22).  ",
6236
0
                   dev, dev->loader_dispatch.core_dispatch.magic);
6237
0
    }
6238
6239
0
    dev->phys_dev_term = phys_dev_term;
6240
6241
0
    icd_exts.list = NULL;
6242
6243
0
    if (fpCreateDevice == NULL) {
6244
0
        loader_log(icd_term->this_instance, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6245
0
                   "terminator_CreateDevice: No vkCreateDevice command exposed by ICD %s", icd_term->scanned_icd->lib_name);
6246
0
        res = VK_ERROR_INITIALIZATION_FAILED;
6247
0
        goto out;
6248
0
    }
6249
6250
0
    VkDeviceCreateInfo localCreateInfo;
6251
0
    memcpy(&localCreateInfo, pCreateInfo, sizeof(localCreateInfo));
6252
6253
    // NOTE: Need to filter the extensions to only those supported by the ICD.
6254
    //       No ICD will advertise support for layers. An ICD library could support a layer,
6255
    //       but it would be independent of the actual ICD, just in the same library.
6256
0
    char **filtered_extension_names = NULL;
6257
0
    if (0 < pCreateInfo->enabledExtensionCount) {
6258
0
        filtered_extension_names = loader_stack_alloc(pCreateInfo->enabledExtensionCount * sizeof(char *));
6259
0
        if (NULL == filtered_extension_names) {
6260
0
            loader_log(icd_term->this_instance, VULKAN_LOADER_ERROR_BIT, 0,
6261
0
                       "terminator_CreateDevice: Failed to create extension name storage for %d extensions",
6262
0
                       pCreateInfo->enabledExtensionCount);
6263
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
6264
0
        }
6265
0
    }
6266
6267
0
    localCreateInfo.enabledLayerCount = 0;
6268
0
    localCreateInfo.ppEnabledLayerNames = NULL;
6269
6270
0
    localCreateInfo.enabledExtensionCount = 0;
6271
0
    localCreateInfo.ppEnabledExtensionNames = (const char *const *)filtered_extension_names;
6272
6273
    // Get the physical device (ICD) extensions
6274
0
    res = loader_init_generic_list(icd_term->this_instance, (struct loader_generic_list *)&icd_exts, sizeof(VkExtensionProperties));
6275
0
    if (VK_SUCCESS != res) {
6276
0
        goto out;
6277
0
    }
6278
6279
0
    res = loader_add_device_extensions(icd_term->this_instance, icd_term->dispatch.EnumerateDeviceExtensionProperties,
6280
0
                                       phys_dev_term->phys_dev, icd_term->scanned_icd->lib_name, &icd_exts);
6281
0
    if (res != VK_SUCCESS) {
6282
0
        goto out;
6283
0
    }
6284
6285
0
    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
6286
0
        if (pCreateInfo->ppEnabledExtensionNames == NULL) {
6287
0
            continue;
6288
0
        }
6289
0
        const char *extension_name = pCreateInfo->ppEnabledExtensionNames[i];
6290
0
        if (extension_name == NULL) {
6291
0
            continue;
6292
0
        }
6293
0
        VkExtensionProperties *prop = get_extension_property(extension_name, &icd_exts);
6294
0
        if (prop) {
6295
0
            filtered_extension_names[localCreateInfo.enabledExtensionCount] = (char *)extension_name;
6296
0
            localCreateInfo.enabledExtensionCount++;
6297
0
        } else {
6298
0
            loader_log(icd_term->this_instance, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6299
0
                       "vkCreateDevice extension %s not available for devices associated with ICD %s", extension_name,
6300
0
                       icd_term->scanned_icd->lib_name);
6301
0
        }
6302
0
    }
6303
6304
    // Before we continue, If KHX_device_group is the list of enabled and viable extensions, then we then need to look for the
6305
    // corresponding VkDeviceGroupDeviceCreateInfo struct in the device list and replace all the physical device values (which
6306
    // are really loader physical device terminator values) with the ICD versions.
6307
    // if (icd_term->this_instance->enabled_extensions.khr_device_group_creation == 1) {
6308
0
    {
6309
0
        VkBaseOutStructure *pNext = (VkBaseOutStructure *)localCreateInfo.pNext;
6310
0
        VkBaseOutStructure *pPrev = (VkBaseOutStructure *)&localCreateInfo;
6311
0
        while (NULL != pNext) {
6312
0
            if (VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO == pNext->sType) {
6313
0
                VkDeviceGroupDeviceCreateInfo *cur_struct = (VkDeviceGroupDeviceCreateInfo *)pNext;
6314
0
                if (0 < cur_struct->physicalDeviceCount && NULL != cur_struct->pPhysicalDevices) {
6315
0
                    VkDeviceGroupDeviceCreateInfo *temp_struct = loader_stack_alloc(sizeof(VkDeviceGroupDeviceCreateInfo));
6316
0
                    VkPhysicalDevice *phys_dev_array = NULL;
6317
0
                    if (NULL == temp_struct) {
6318
0
                        return VK_ERROR_OUT_OF_HOST_MEMORY;
6319
0
                    }
6320
0
                    memcpy(temp_struct, cur_struct, sizeof(VkDeviceGroupDeviceCreateInfo));
6321
0
                    phys_dev_array = loader_stack_alloc(sizeof(VkPhysicalDevice) * cur_struct->physicalDeviceCount);
6322
0
                    if (NULL == phys_dev_array) {
6323
0
                        return VK_ERROR_OUT_OF_HOST_MEMORY;
6324
0
                    }
6325
6326
                    // Before calling down, replace the incoming physical device values (which are really loader terminator
6327
                    // physical devices) with the ICDs physical device values.
6328
0
                    struct loader_physical_device_term *cur_term;
6329
0
                    for (uint32_t phys_dev = 0; phys_dev < cur_struct->physicalDeviceCount; phys_dev++) {
6330
0
                        cur_term = (struct loader_physical_device_term *)cur_struct->pPhysicalDevices[phys_dev];
6331
0
                        phys_dev_array[phys_dev] = cur_term->phys_dev;
6332
0
                    }
6333
0
                    temp_struct->pPhysicalDevices = phys_dev_array;
6334
6335
                    // Keep track of pointers to restore pNext chain before returning
6336
0
                    caller_dgci_container = pPrev;
6337
0
                    caller_dgci = cur_struct;
6338
6339
                    // Replace the old struct in the pNext chain with this one.
6340
0
                    pPrev->pNext = (VkBaseOutStructure *)temp_struct;
6341
0
                }
6342
0
                break;
6343
0
            }
6344
6345
0
            pPrev = pNext;
6346
0
            pNext = pNext->pNext;
6347
0
        }
6348
0
    }
6349
6350
    // Handle loader emulation for structs that are not supported by the ICD:
6351
    // Presently, the emulation leaves the pNext chain alone. This means that the ICD will receive items in the chain which
6352
    // are not recognized by the ICD. If this causes the ICD to fail, then the items would have to be removed here. The current
6353
    // implementation does not remove them because copying the pNext chain would be impossible if the loader does not recognize
6354
    // the any of the struct types, as the loader would not know the size to allocate and copy.
6355
    // if (icd_term->dispatch.GetPhysicalDeviceFeatures2 == NULL && icd_term->dispatch.GetPhysicalDeviceFeatures2KHR == NULL) {
6356
0
    {
6357
0
        const void *pNext = localCreateInfo.pNext;
6358
0
        while (pNext != NULL) {
6359
0
            VkBaseInStructure pNext_in_structure = {0};
6360
0
            memcpy(&pNext_in_structure, pNext, sizeof(VkBaseInStructure));
6361
0
            switch (pNext_in_structure.sType) {
6362
0
                case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: {
6363
0
                    const VkPhysicalDeviceFeatures2KHR *features = pNext;
6364
6365
0
                    if (icd_term->dispatch.GetPhysicalDeviceFeatures2 == NULL &&
6366
0
                        icd_term->dispatch.GetPhysicalDeviceFeatures2KHR == NULL) {
6367
0
                        loader_log(icd_term->this_instance, VULKAN_LOADER_INFO_BIT, 0,
6368
0
                                   "vkCreateDevice: Emulating handling of VkPhysicalDeviceFeatures2 in pNext chain for ICD \"%s\"",
6369
0
                                   icd_term->scanned_icd->lib_name);
6370
6371
                        // Verify that VK_KHR_get_physical_device_properties2 is enabled
6372
0
                        if (icd_term->this_instance->enabled_extensions.khr_get_physical_device_properties2) {
6373
0
                            localCreateInfo.pEnabledFeatures = &features->features;
6374
0
                        }
6375
0
                    }
6376
6377
                    // Leave this item in the pNext chain for now
6378
6379
0
                    pNext = features->pNext;
6380
0
                    break;
6381
0
                }
6382
6383
0
                case VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO: {
6384
0
                    const VkDeviceGroupDeviceCreateInfo *group_info = pNext;
6385
6386
0
                    if (icd_term->dispatch.EnumeratePhysicalDeviceGroups == NULL &&
6387
0
                        icd_term->dispatch.EnumeratePhysicalDeviceGroupsKHR == NULL) {
6388
0
                        loader_log(icd_term->this_instance, VULKAN_LOADER_INFO_BIT, 0,
6389
0
                                   "vkCreateDevice: Emulating handling of VkPhysicalDeviceGroupProperties in pNext chain for "
6390
0
                                   "ICD \"%s\"",
6391
0
                                   icd_term->scanned_icd->lib_name);
6392
6393
                        // The group must contain only this one device, since physical device groups aren't actually supported
6394
0
                        if (group_info->physicalDeviceCount != 1) {
6395
0
                            loader_log(icd_term->this_instance, VULKAN_LOADER_ERROR_BIT, 0,
6396
0
                                       "vkCreateDevice: Emulation failed to create device from device group info");
6397
0
                            res = VK_ERROR_INITIALIZATION_FAILED;
6398
0
                            goto out;
6399
0
                        }
6400
0
                    }
6401
6402
                    // Nothing needs to be done here because we're leaving the item in the pNext chain and because the spec
6403
                    // states that the physicalDevice argument must be included in the device group, and we've already checked
6404
                    // that it is
6405
6406
0
                    pNext = group_info->pNext;
6407
0
                    break;
6408
0
                }
6409
6410
                // Multiview properties are also allowed, but since VK_KHX_multiview is a device extension, we'll just let the
6411
                // ICD handle that error when the user enables the extension here
6412
0
                default: {
6413
0
                    pNext = pNext_in_structure.pNext;
6414
0
                    break;
6415
0
                }
6416
0
            }
6417
0
        }
6418
0
    }
6419
6420
0
    VkBool32 maintenance5_feature_enabled = false;
6421
    // Look for the VkPhysicalDeviceMaintenance5FeaturesKHR struct to see if the feature was enabled
6422
0
    {
6423
0
        const void *pNext = localCreateInfo.pNext;
6424
0
        while (pNext != NULL) {
6425
0
            VkBaseInStructure pNext_in_structure = {0};
6426
0
            memcpy(&pNext_in_structure, pNext, sizeof(VkBaseInStructure));
6427
0
            switch (pNext_in_structure.sType) {
6428
0
                case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR: {
6429
0
                    const VkPhysicalDeviceMaintenance5FeaturesKHR *maintenance_features = pNext;
6430
0
                    if (maintenance_features->maintenance5 == VK_TRUE) {
6431
0
                        maintenance5_feature_enabled = true;
6432
0
                    }
6433
0
                    pNext = maintenance_features->pNext;
6434
0
                    break;
6435
0
                }
6436
6437
0
                default: {
6438
0
                    pNext = pNext_in_structure.pNext;
6439
0
                    break;
6440
0
                }
6441
0
            }
6442
0
        }
6443
0
    }
6444
6445
    // Every extension that has a loader-defined terminator needs to be marked as enabled or disabled so that we know whether or
6446
    // not to return that terminator when vkGetDeviceProcAddr is called
6447
0
    for (uint32_t i = 0; i < localCreateInfo.enabledExtensionCount; ++i) {
6448
0
        if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_KHR_SWAPCHAIN_EXTENSION_NAME)) {
6449
0
            dev->driver_extensions.khr_swapchain_enabled = true;
6450
0
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME)) {
6451
0
            dev->driver_extensions.khr_display_swapchain_enabled = true;
6452
0
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_KHR_DEVICE_GROUP_EXTENSION_NAME)) {
6453
0
            dev->driver_extensions.khr_device_group_enabled = true;
6454
0
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) {
6455
0
            dev->driver_extensions.ext_debug_marker_enabled = true;
6456
#if defined(VK_USE_PLATFORM_WIN32_KHR)
6457
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_EXT_FULL_SCREEN_EXCLUSIVE_EXTENSION_NAME)) {
6458
            dev->driver_extensions.ext_full_screen_exclusive_enabled = true;
6459
#endif
6460
0
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_KHR_MAINTENANCE_5_EXTENSION_NAME) &&
6461
0
                   maintenance5_feature_enabled) {
6462
0
            dev->should_ignore_device_commands_from_newer_version = true;
6463
0
        }
6464
0
    }
6465
0
    dev->layer_extensions.ext_debug_utils_enabled = icd_term->this_instance->enabled_extensions.ext_debug_utils;
6466
0
    dev->driver_extensions.ext_debug_utils_enabled = icd_term->this_instance->enabled_extensions.ext_debug_utils;
6467
6468
0
    VkPhysicalDeviceProperties properties;
6469
0
    icd_term->dispatch.GetPhysicalDeviceProperties(phys_dev_term->phys_dev, &properties);
6470
0
    if (properties.apiVersion >= VK_API_VERSION_1_1) {
6471
0
        dev->driver_extensions.version_1_1_enabled = true;
6472
0
    }
6473
0
    if (properties.apiVersion >= VK_API_VERSION_1_2) {
6474
0
        dev->driver_extensions.version_1_2_enabled = true;
6475
0
    }
6476
0
    if (properties.apiVersion >= VK_API_VERSION_1_3) {
6477
0
        dev->driver_extensions.version_1_3_enabled = true;
6478
0
    }
6479
6480
0
    loader_log(icd_term->this_instance, VULKAN_LOADER_LAYER_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6481
0
               "       Using \"%s\" with driver: \"%s\"", properties.deviceName, icd_term->scanned_icd->lib_name);
6482
6483
0
    res = fpCreateDevice(phys_dev_term->phys_dev, &localCreateInfo, pAllocator, &dev->icd_device);
6484
0
    if (res != VK_SUCCESS) {
6485
0
        loader_log(icd_term->this_instance, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6486
0
                   "terminator_CreateDevice: Failed in ICD %s vkCreateDevice call", icd_term->scanned_icd->lib_name);
6487
0
        goto out;
6488
0
    }
6489
6490
0
    *pDevice = dev->icd_device;
6491
0
    loader_add_logical_device(icd_term, dev);
6492
6493
    // Init dispatch pointer in new device object
6494
0
    loader_init_dispatch(*pDevice, &dev->loader_dispatch);
6495
6496
0
out:
6497
0
    if (NULL != icd_exts.list) {
6498
0
        loader_destroy_generic_list(icd_term->this_instance, (struct loader_generic_list *)&icd_exts);
6499
0
    }
6500
6501
    // Restore pNext pointer to old VkDeviceGroupDeviceCreateInfo
6502
    // in the chain to maintain consistency for the caller.
6503
0
    if (caller_dgci_container != NULL) {
6504
0
        caller_dgci_container->pNext = (VkBaseOutStructure *)caller_dgci;
6505
0
    }
6506
6507
0
    return res;
6508
0
}
6509
6510
// Update the trampoline physical devices with the wrapped version.
6511
// We always want to re-use previous physical device pointers since they may be used by an application
6512
// after returning previously.
6513
0
VkResult setup_loader_tramp_phys_devs(struct loader_instance *inst, uint32_t phys_dev_count, VkPhysicalDevice *phys_devs) {
6514
0
    VkResult res = VK_SUCCESS;
6515
0
    uint32_t found_count = 0;
6516
0
    uint32_t old_count = inst->phys_dev_count_tramp;
6517
0
    uint32_t new_count = inst->total_gpu_count;
6518
0
    struct loader_physical_device_tramp **new_phys_devs = NULL;
6519
6520
0
    if (0 == phys_dev_count) {
6521
0
        return VK_SUCCESS;
6522
0
    }
6523
0
    if (phys_dev_count > new_count) {
6524
0
        new_count = phys_dev_count;
6525
0
    }
6526
6527
    // We want an old to new index array and a new to old index array
6528
0
    int32_t *old_to_new_index = (int32_t *)loader_stack_alloc(sizeof(int32_t) * old_count);
6529
0
    int32_t *new_to_old_index = (int32_t *)loader_stack_alloc(sizeof(int32_t) * new_count);
6530
0
    if (NULL == old_to_new_index || NULL == new_to_old_index) {
6531
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
6532
0
    }
6533
6534
    // Initialize both
6535
0
    for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6536
0
        old_to_new_index[cur_idx] = -1;
6537
0
    }
6538
0
    for (uint32_t cur_idx = 0; cur_idx < new_count; ++cur_idx) {
6539
0
        new_to_old_index[cur_idx] = -1;
6540
0
    }
6541
6542
    // Figure out the old->new and new->old indices
6543
0
    for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6544
0
        for (uint32_t new_idx = 0; new_idx < phys_dev_count; ++new_idx) {
6545
0
            if (inst->phys_devs_tramp[cur_idx]->phys_dev == phys_devs[new_idx]) {
6546
0
                old_to_new_index[cur_idx] = (int32_t)new_idx;
6547
0
                new_to_old_index[new_idx] = (int32_t)cur_idx;
6548
0
                found_count++;
6549
0
                break;
6550
0
            }
6551
0
        }
6552
0
    }
6553
6554
    // If we found exactly the number of items we were looking for as we had before.  Then everything
6555
    // we already have is good enough and we just need to update the array that was passed in with
6556
    // the loader values.
6557
0
    if (found_count == phys_dev_count && 0 != old_count && old_count == new_count) {
6558
0
        for (uint32_t new_idx = 0; new_idx < phys_dev_count; ++new_idx) {
6559
0
            for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6560
0
                if (old_to_new_index[cur_idx] == (int32_t)new_idx) {
6561
0
                    phys_devs[new_idx] = (VkPhysicalDevice)inst->phys_devs_tramp[cur_idx];
6562
0
                    break;
6563
0
                }
6564
0
            }
6565
0
        }
6566
        // Nothing else to do for this path
6567
0
        res = VK_SUCCESS;
6568
0
    } else {
6569
        // Something is different, so do the full path of checking every device and creating a new array to use.
6570
        // This can happen if a device was added, or removed, or we hadn't previously queried all the data and we
6571
        // have more to store.
6572
0
        new_phys_devs = loader_instance_heap_calloc(inst, sizeof(struct loader_physical_device_tramp *) * new_count,
6573
0
                                                    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6574
0
        if (NULL == new_phys_devs) {
6575
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6576
0
                       "setup_loader_tramp_phys_devs:  Failed to allocate new physical device array of size %d", new_count);
6577
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
6578
0
            goto out;
6579
0
        }
6580
6581
0
        if (new_count > phys_dev_count) {
6582
0
            found_count = phys_dev_count;
6583
0
        } else {
6584
0
            found_count = new_count;
6585
0
        }
6586
6587
        // First try to see if an old item exists that matches the new item.  If so, just copy it over.
6588
0
        for (uint32_t new_idx = 0; new_idx < found_count; ++new_idx) {
6589
0
            bool old_item_found = false;
6590
0
            for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6591
0
                if (old_to_new_index[cur_idx] == (int32_t)new_idx) {
6592
                    // Copy over old item to correct spot in the new array
6593
0
                    new_phys_devs[new_idx] = inst->phys_devs_tramp[cur_idx];
6594
0
                    old_item_found = true;
6595
0
                    break;
6596
0
                }
6597
0
            }
6598
            // Something wasn't found, so it's new so add it to the new list
6599
0
            if (!old_item_found) {
6600
0
                new_phys_devs[new_idx] = loader_instance_heap_alloc(inst, sizeof(struct loader_physical_device_tramp),
6601
0
                                                                    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6602
0
                if (NULL == new_phys_devs[new_idx]) {
6603
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6604
0
                               "setup_loader_tramp_phys_devs:  Failed to allocate new trampoline physical device");
6605
0
                    res = VK_ERROR_OUT_OF_HOST_MEMORY;
6606
0
                    goto out;
6607
0
                }
6608
6609
                // Initialize the new physicalDevice object
6610
0
                loader_set_dispatch((void *)new_phys_devs[new_idx], inst->disp);
6611
0
                new_phys_devs[new_idx]->this_instance = inst;
6612
0
                new_phys_devs[new_idx]->phys_dev = phys_devs[new_idx];
6613
0
                new_phys_devs[new_idx]->magic = PHYS_TRAMP_MAGIC_NUMBER;
6614
0
            }
6615
6616
0
            phys_devs[new_idx] = (VkPhysicalDevice)new_phys_devs[new_idx];
6617
0
        }
6618
6619
        // We usually get here if the user array is smaller than the total number of devices, so copy the
6620
        // remaining devices we have over to the new array.
6621
0
        uint32_t start = found_count;
6622
0
        for (uint32_t new_idx = start; new_idx < new_count; ++new_idx) {
6623
0
            for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6624
0
                if (old_to_new_index[cur_idx] == -1) {
6625
0
                    new_phys_devs[new_idx] = inst->phys_devs_tramp[cur_idx];
6626
0
                    old_to_new_index[cur_idx] = new_idx;
6627
0
                    found_count++;
6628
0
                    break;
6629
0
                }
6630
0
            }
6631
0
        }
6632
0
    }
6633
6634
0
out:
6635
6636
0
    if (NULL != new_phys_devs) {
6637
0
        if (VK_SUCCESS != res) {
6638
0
            for (uint32_t new_idx = 0; new_idx < found_count; ++new_idx) {
6639
                // If an OOM occurred inside the copying of the new physical devices into the existing array
6640
                // will leave some of the old physical devices in the array which may have been copied into
6641
                // the new array, leading to them being freed twice. To avoid this we just make sure to not
6642
                // delete physical devices which were copied.
6643
0
                bool found = false;
6644
0
                for (uint32_t cur_idx = 0; cur_idx < inst->phys_dev_count_tramp; cur_idx++) {
6645
0
                    if (new_phys_devs[new_idx] == inst->phys_devs_tramp[cur_idx]) {
6646
0
                        found = true;
6647
0
                        break;
6648
0
                    }
6649
0
                }
6650
0
                if (!found) {
6651
0
                    loader_instance_heap_free(inst, new_phys_devs[new_idx]);
6652
0
                }
6653
0
            }
6654
0
            loader_instance_heap_free(inst, new_phys_devs);
6655
0
        } else {
6656
0
            if (new_count > inst->total_gpu_count) {
6657
0
                inst->total_gpu_count = new_count;
6658
0
            }
6659
            // Free everything in the old array that was not copied into the new array
6660
            // here.  We can't attempt to do that before here since the previous loop
6661
            // looking before the "out:" label may hit an out of memory condition resulting
6662
            // in memory leaking.
6663
0
            if (NULL != inst->phys_devs_tramp) {
6664
0
                for (uint32_t i = 0; i < inst->phys_dev_count_tramp; i++) {
6665
0
                    bool found = false;
6666
0
                    for (uint32_t j = 0; j < inst->total_gpu_count; j++) {
6667
0
                        if (inst->phys_devs_tramp[i] == new_phys_devs[j]) {
6668
0
                            found = true;
6669
0
                            break;
6670
0
                        }
6671
0
                    }
6672
0
                    if (!found) {
6673
0
                        loader_instance_heap_free(inst, inst->phys_devs_tramp[i]);
6674
0
                    }
6675
0
                }
6676
0
                loader_instance_heap_free(inst, inst->phys_devs_tramp);
6677
0
            }
6678
0
            inst->phys_devs_tramp = new_phys_devs;
6679
0
            inst->phys_dev_count_tramp = found_count;
6680
0
        }
6681
0
    }
6682
0
    if (VK_SUCCESS != res) {
6683
0
        inst->total_gpu_count = 0;
6684
0
    }
6685
6686
0
    return res;
6687
0
}
6688
6689
#if defined(LOADER_ENABLE_LINUX_SORT)
6690
0
bool is_linux_sort_enabled(struct loader_instance *inst) {
6691
0
    bool sort_items = inst->supports_get_dev_prop_2;
6692
0
    char *env_value = loader_getenv("VK_LOADER_DISABLE_SELECT", inst);
6693
0
    if (NULL != env_value) {
6694
0
        int32_t int_env_val = atoi(env_value);
6695
0
        loader_free_getenv(env_value, inst);
6696
0
        if (int_env_val != 0) {
6697
0
            sort_items = false;
6698
0
        }
6699
0
    }
6700
0
    return sort_items;
6701
0
}
6702
#endif  // LOADER_ENABLE_LINUX_SORT
6703
6704
// Look for physical_device in the provided phys_devs list, return true if found and put the index into out_idx, otherwise
6705
// return false
6706
bool find_phys_dev(VkPhysicalDevice physical_device, uint32_t phys_devs_count, struct loader_physical_device_term **phys_devs,
6707
0
                   uint32_t *out_idx) {
6708
0
    if (NULL == phys_devs) return false;
6709
0
    for (uint32_t idx = 0; idx < phys_devs_count; idx++) {
6710
0
        if (NULL != phys_devs[idx] && physical_device == phys_devs[idx]->phys_dev) {
6711
0
            *out_idx = idx;
6712
0
            return true;
6713
0
        }
6714
0
    }
6715
0
    return false;
6716
0
}
6717
6718
// Add physical_device to new_phys_devs
6719
VkResult check_and_add_to_new_phys_devs(struct loader_instance *inst, VkPhysicalDevice physical_device,
6720
                                        struct loader_icd_physical_devices *dev_array, uint32_t *cur_new_phys_dev_count,
6721
0
                                        struct loader_physical_device_term **new_phys_devs) {
6722
0
    uint32_t out_idx = 0;
6723
0
    uint32_t idx = *cur_new_phys_dev_count;
6724
    // Check if the physical_device already exists in the new_phys_devs buffer, that means it was found from both
6725
    // EnumerateAdapterPhysicalDevices and EnumeratePhysicalDevices and we need to skip it.
6726
0
    if (find_phys_dev(physical_device, idx, new_phys_devs, &out_idx)) {
6727
0
        return VK_SUCCESS;
6728
0
    }
6729
    // Check if it was found in a previous call to vkEnumeratePhysicalDevices, we can just copy over the old data.
6730
0
    if (find_phys_dev(physical_device, inst->phys_dev_count_term, inst->phys_devs_term, &out_idx)) {
6731
0
        new_phys_devs[idx] = inst->phys_devs_term[out_idx];
6732
0
        (*cur_new_phys_dev_count)++;
6733
0
        return VK_SUCCESS;
6734
0
    }
6735
6736
    // Exit in case something is already present - this shouldn't happen but better to be safe than overwrite existing data
6737
    // since this code has been refactored a half dozen times.
6738
0
    if (NULL != new_phys_devs[idx]) {
6739
0
        return VK_SUCCESS;
6740
0
    }
6741
    // If this physical device is new, we need to allocate space for it.
6742
0
    new_phys_devs[idx] =
6743
0
        loader_instance_heap_alloc(inst, sizeof(struct loader_physical_device_term), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6744
0
    if (NULL == new_phys_devs[idx]) {
6745
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6746
0
                   "check_and_add_to_new_phys_devs:  Failed to allocate physical device terminator object %d", idx);
6747
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
6748
0
    }
6749
6750
0
    loader_set_dispatch((void *)new_phys_devs[idx], inst->disp);
6751
0
    new_phys_devs[idx]->this_icd_term = dev_array->icd_term;
6752
0
    new_phys_devs[idx]->phys_dev = physical_device;
6753
6754
    // Increment the count of new physical devices
6755
0
    (*cur_new_phys_dev_count)++;
6756
0
    return VK_SUCCESS;
6757
0
}
6758
6759
/* Enumerate all physical devices from ICDs and add them to inst->phys_devs_term
6760
 *
6761
 * There are two methods to find VkPhysicalDevices - vkEnumeratePhysicalDevices and vkEnumerateAdapterPhysicalDevices
6762
 * The latter is supported on windows only and on devices supporting ICD Interface Version 6 and greater.
6763
 *
6764
 * Once all physical devices are acquired, they need to be pulled into a single list of `loader_physical_device_term`'s.
6765
 * They also need to be setup - the icd_term, icd_index, phys_dev, and disp (dispatch table) all need the correct data.
6766
 * Additionally, we need to keep using already setup physical devices as they may be in use, thus anything enumerated
6767
 * that is already in inst->phys_devs_term will be carried over.
6768
 */
6769
6770
0
VkResult setup_loader_term_phys_devs(struct loader_instance *inst) {
6771
0
    VkResult res = VK_SUCCESS;
6772
0
    struct loader_icd_term *icd_term;
6773
0
    uint32_t windows_sorted_devices_count = 0;
6774
0
    struct loader_icd_physical_devices *windows_sorted_devices_array = NULL;
6775
0
    uint32_t icd_count = 0;
6776
0
    struct loader_icd_physical_devices *icd_phys_dev_array = NULL;
6777
0
    uint32_t new_phys_devs_capacity = 0;
6778
0
    uint32_t new_phys_devs_count = 0;
6779
0
    struct loader_physical_device_term **new_phys_devs = NULL;
6780
6781
#if defined(_WIN32)
6782
    // Get the physical devices supported by platform sorting mechanism into a separate list
6783
    res = windows_read_sorted_physical_devices(inst, &windows_sorted_devices_count, &windows_sorted_devices_array);
6784
    if (VK_SUCCESS != res) {
6785
        goto out;
6786
    }
6787
#endif
6788
6789
0
    icd_count = inst->icd_terms_count;
6790
6791
    // Allocate something to store the physical device characteristics that we read from each ICD.
6792
0
    icd_phys_dev_array =
6793
0
        (struct loader_icd_physical_devices *)loader_stack_alloc(sizeof(struct loader_icd_physical_devices) * icd_count);
6794
0
    if (NULL == icd_phys_dev_array) {
6795
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6796
0
                   "setup_loader_term_phys_devs:  Failed to allocate temporary ICD Physical device info array of size %d",
6797
0
                   icd_count);
6798
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
6799
0
        goto out;
6800
0
    }
6801
0
    memset(icd_phys_dev_array, 0, sizeof(struct loader_icd_physical_devices) * icd_count);
6802
6803
    // For each ICD, query the number of physical devices, and then get an
6804
    // internal value for those physical devices.
6805
0
    icd_term = inst->icd_terms;
6806
0
    uint32_t icd_idx = 0;
6807
0
    while (NULL != icd_term) {
6808
0
        res = icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &icd_phys_dev_array[icd_idx].device_count, NULL);
6809
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
6810
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6811
0
                       "setup_loader_term_phys_devs: Call to \'vkEnumeratePhysicalDevices\' in ICD %s failed with error code "
6812
0
                       "VK_ERROR_OUT_OF_HOST_MEMORY",
6813
0
                       icd_term->scanned_icd->lib_name);
6814
0
            goto out;
6815
0
        } else if (VK_SUCCESS == res) {
6816
0
            icd_phys_dev_array[icd_idx].physical_devices =
6817
0
                (VkPhysicalDevice *)loader_stack_alloc(icd_phys_dev_array[icd_idx].device_count * sizeof(VkPhysicalDevice));
6818
0
            if (NULL == icd_phys_dev_array[icd_idx].physical_devices) {
6819
0
                loader_log(
6820
0
                    inst, VULKAN_LOADER_ERROR_BIT, 0,
6821
0
                    "setup_loader_term_phys_devs: Failed to allocate temporary ICD Physical device array for ICD %s of size %d",
6822
0
                    icd_term->scanned_icd->lib_name, icd_phys_dev_array[icd_idx].device_count);
6823
0
                res = VK_ERROR_OUT_OF_HOST_MEMORY;
6824
0
                goto out;
6825
0
            }
6826
6827
0
            res = icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &(icd_phys_dev_array[icd_idx].device_count),
6828
0
                                                              icd_phys_dev_array[icd_idx].physical_devices);
6829
0
            if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
6830
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6831
0
                           "setup_loader_term_phys_devs: Call to \'vkEnumeratePhysicalDevices\' in ICD %s failed with error code "
6832
0
                           "VK_ERROR_OUT_OF_HOST_MEMORY",
6833
0
                           icd_term->scanned_icd->lib_name);
6834
0
                goto out;
6835
0
            }
6836
0
            if (VK_SUCCESS != res) {
6837
0
                loader_log(
6838
0
                    inst, VULKAN_LOADER_ERROR_BIT, 0,
6839
0
                    "setup_loader_term_phys_devs: Call to \'vkEnumeratePhysicalDevices\' in ICD %s failed with error code %d",
6840
0
                    icd_term->scanned_icd->lib_name, res);
6841
0
                icd_phys_dev_array[icd_idx].device_count = 0;
6842
0
                icd_phys_dev_array[icd_idx].physical_devices = 0;
6843
0
            }
6844
0
        } else {
6845
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6846
0
                       "setup_loader_term_phys_devs: Call to \'vkEnumeratePhysicalDevices\' in ICD %s failed with error code %d",
6847
0
                       icd_term->scanned_icd->lib_name, res);
6848
0
            icd_phys_dev_array[icd_idx].device_count = 0;
6849
0
            icd_phys_dev_array[icd_idx].physical_devices = 0;
6850
0
        }
6851
0
        icd_phys_dev_array[icd_idx].icd_term = icd_term;
6852
0
        icd_term->physical_device_count = icd_phys_dev_array[icd_idx].device_count;
6853
0
        icd_term = icd_term->next;
6854
0
        ++icd_idx;
6855
0
    }
6856
6857
    // Add up both the windows sorted and non windows found physical device counts
6858
0
    for (uint32_t i = 0; i < windows_sorted_devices_count; ++i) {
6859
0
        new_phys_devs_capacity += windows_sorted_devices_array[i].device_count;
6860
0
    }
6861
0
    for (uint32_t i = 0; i < icd_count; ++i) {
6862
0
        new_phys_devs_capacity += icd_phys_dev_array[i].device_count;
6863
0
    }
6864
6865
    // Bail out if there are no physical devices reported
6866
0
    if (0 == new_phys_devs_capacity) {
6867
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6868
0
                   "setup_loader_term_phys_devs:  Failed to detect any valid GPUs in the current config");
6869
0
        res = VK_ERROR_INITIALIZATION_FAILED;
6870
0
        goto out;
6871
0
    }
6872
6873
    // Create an allocation large enough to hold both the windows sorting enumeration and non-windows physical device
6874
    // enumeration
6875
0
    new_phys_devs = loader_instance_heap_calloc(inst, sizeof(struct loader_physical_device_term *) * new_phys_devs_capacity,
6876
0
                                                VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6877
0
    if (NULL == new_phys_devs) {
6878
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6879
0
                   "setup_loader_term_phys_devs:  Failed to allocate new physical device array of size %d", new_phys_devs_capacity);
6880
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
6881
0
        goto out;
6882
0
    }
6883
6884
    // Copy over everything found through sorted enumeration
6885
0
    for (uint32_t i = 0; i < windows_sorted_devices_count; ++i) {
6886
0
        for (uint32_t j = 0; j < windows_sorted_devices_array[i].device_count; ++j) {
6887
0
            res = check_and_add_to_new_phys_devs(inst, windows_sorted_devices_array[i].physical_devices[j],
6888
0
                                                 &windows_sorted_devices_array[i], &new_phys_devs_count, new_phys_devs);
6889
0
            if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
6890
0
                goto out;
6891
0
            }
6892
0
        }
6893
0
    }
6894
6895
// Now go through the rest of the physical devices and add them to new_phys_devs
6896
0
#if defined(LOADER_ENABLE_LINUX_SORT)
6897
6898
0
    if (is_linux_sort_enabled(inst)) {
6899
0
        for (uint32_t dev = new_phys_devs_count; dev < new_phys_devs_capacity; ++dev) {
6900
0
            new_phys_devs[dev] =
6901
0
                loader_instance_heap_alloc(inst, sizeof(struct loader_physical_device_term), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6902
0
            if (NULL == new_phys_devs[dev]) {
6903
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6904
0
                           "setup_loader_term_phys_devs:  Failed to allocate physical device terminator object %d", dev);
6905
0
                res = VK_ERROR_OUT_OF_HOST_MEMORY;
6906
0
                goto out;
6907
0
            }
6908
0
        }
6909
6910
        // Get the physical devices supported by platform sorting mechanism into a separate list
6911
        // Pass in a sublist to the function so it only operates on the correct elements. This means passing in a pointer to the
6912
        // current next element in new_phys_devs and passing in a `count` of currently unwritten elements
6913
0
        res = linux_read_sorted_physical_devices(inst, icd_count, icd_phys_dev_array, new_phys_devs_capacity - new_phys_devs_count,
6914
0
                                                 &new_phys_devs[new_phys_devs_count]);
6915
0
        if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
6916
0
            goto out;
6917
0
        }
6918
        // Keep previously allocated physical device info since apps may already be using that!
6919
0
        for (uint32_t new_idx = new_phys_devs_count; new_idx < new_phys_devs_capacity; new_idx++) {
6920
0
            for (uint32_t old_idx = 0; old_idx < inst->phys_dev_count_term; old_idx++) {
6921
0
                if (new_phys_devs[new_idx]->phys_dev == inst->phys_devs_term[old_idx]->phys_dev) {
6922
0
                    loader_log(inst, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6923
0
                               "Copying old device %u into new device %u", old_idx, new_idx);
6924
                    // Free the old new_phys_devs info since we're not using it before we assign the new info
6925
0
                    loader_instance_heap_free(inst, new_phys_devs[new_idx]);
6926
0
                    new_phys_devs[new_idx] = inst->phys_devs_term[old_idx];
6927
0
                    break;
6928
0
                }
6929
0
            }
6930
0
        }
6931
        // now set the count to the capacity, as now the list is filled in
6932
0
        new_phys_devs_count = new_phys_devs_capacity;
6933
        // We want the following code to run if either linux sorting is disabled at compile time or runtime
6934
0
    } else {
6935
0
#endif  // LOADER_ENABLE_LINUX_SORT
6936
6937
        // Copy over everything found through the non-sorted means.
6938
0
        for (uint32_t i = 0; i < icd_count; ++i) {
6939
0
            for (uint32_t j = 0; j < icd_phys_dev_array[i].device_count; ++j) {
6940
0
                res = check_and_add_to_new_phys_devs(inst, icd_phys_dev_array[i].physical_devices[j], &icd_phys_dev_array[i],
6941
0
                                                     &new_phys_devs_count, new_phys_devs);
6942
0
                if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
6943
0
                    goto out;
6944
0
                }
6945
0
            }
6946
0
        }
6947
0
#if defined(LOADER_ENABLE_LINUX_SORT)
6948
0
    }
6949
0
#endif  // LOADER_ENABLE_LINUX_SORT
6950
0
out:
6951
6952
0
    if (VK_SUCCESS != res) {
6953
0
        if (NULL != new_phys_devs) {
6954
            // We've encountered an error, so we should free the new buffers.
6955
0
            for (uint32_t i = 0; i < new_phys_devs_capacity; i++) {
6956
                // May not have allocated this far, skip it if we hadn't.
6957
0
                if (new_phys_devs[i] == NULL) continue;
6958
6959
                // If an OOM occurred inside the copying of the new physical devices into the existing array
6960
                // will leave some of the old physical devices in the array which may have been copied into
6961
                // the new array, leading to them being freed twice. To avoid this we just make sure to not
6962
                // delete physical devices which were copied.
6963
0
                bool found = false;
6964
0
                if (NULL != inst->phys_devs_term) {
6965
0
                    for (uint32_t old_idx = 0; old_idx < inst->phys_dev_count_term; old_idx++) {
6966
0
                        if (new_phys_devs[i] == inst->phys_devs_term[old_idx]) {
6967
0
                            found = true;
6968
0
                            break;
6969
0
                        }
6970
0
                    }
6971
0
                }
6972
0
                if (!found) {
6973
0
                    loader_instance_heap_free(inst, new_phys_devs[i]);
6974
0
                }
6975
0
            }
6976
0
            loader_instance_heap_free(inst, new_phys_devs);
6977
0
        }
6978
0
        inst->total_gpu_count = 0;
6979
0
    } else {
6980
0
        if (NULL != inst->phys_devs_term) {
6981
            // Free everything in the old array that was not copied into the new array
6982
            // here.  We can't attempt to do that before here since the previous loop
6983
            // looking before the "out:" label may hit an out of memory condition resulting
6984
            // in memory leaking.
6985
0
            for (uint32_t i = 0; i < inst->phys_dev_count_term; i++) {
6986
0
                bool found = false;
6987
0
                for (uint32_t j = 0; j < new_phys_devs_count; j++) {
6988
0
                    if (new_phys_devs != NULL && inst->phys_devs_term[i] == new_phys_devs[j]) {
6989
0
                        found = true;
6990
0
                        break;
6991
0
                    }
6992
0
                }
6993
0
                if (!found) {
6994
0
                    loader_instance_heap_free(inst, inst->phys_devs_term[i]);
6995
0
                }
6996
0
            }
6997
0
            loader_instance_heap_free(inst, inst->phys_devs_term);
6998
0
        }
6999
7000
        // Swap out old and new devices list
7001
0
        inst->phys_dev_count_term = new_phys_devs_count;
7002
0
        inst->phys_devs_term = new_phys_devs;
7003
0
        inst->total_gpu_count = new_phys_devs_count;
7004
0
    }
7005
7006
0
    if (windows_sorted_devices_array != NULL) {
7007
0
        for (uint32_t i = 0; i < windows_sorted_devices_count; ++i) {
7008
0
            if (windows_sorted_devices_array[i].device_count > 0 && windows_sorted_devices_array[i].physical_devices != NULL) {
7009
0
                loader_instance_heap_free(inst, windows_sorted_devices_array[i].physical_devices);
7010
0
            }
7011
0
        }
7012
0
        loader_instance_heap_free(inst, windows_sorted_devices_array);
7013
0
    }
7014
7015
0
    return res;
7016
0
}
7017
/**
7018
 * Iterates through all drivers and unloads any which do not contain physical devices.
7019
 * This saves address space, which for 32 bit applications is scarce.
7020
 * This must only be called after a call to vkEnumeratePhysicalDevices that isn't just querying the count
7021
 */
7022
0
void unload_drivers_without_physical_devices(struct loader_instance *inst) {
7023
0
    struct loader_icd_term *cur_icd_term = inst->icd_terms;
7024
0
    struct loader_icd_term *prev_icd_term = NULL;
7025
7026
0
    while (NULL != cur_icd_term) {
7027
0
        struct loader_icd_term *next_icd_term = cur_icd_term->next;
7028
0
        if (cur_icd_term->physical_device_count == 0) {
7029
0
            uint32_t cur_scanned_icd_index = UINT32_MAX;
7030
0
            if (inst->icd_tramp_list.scanned_list) {
7031
0
                for (uint32_t i = 0; i < inst->icd_tramp_list.count; i++) {
7032
0
                    if (&(inst->icd_tramp_list.scanned_list[i]) == cur_icd_term->scanned_icd) {
7033
0
                        cur_scanned_icd_index = i;
7034
0
                        break;
7035
0
                    }
7036
0
                }
7037
0
            }
7038
0
            if (cur_scanned_icd_index != UINT32_MAX) {
7039
0
                loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
7040
0
                           "Removing driver %s due to not having any physical devices", cur_icd_term->scanned_icd->lib_name);
7041
7042
0
                const VkAllocationCallbacks *allocation_callbacks = ignore_null_callback(&(inst->alloc_callbacks));
7043
0
                if (cur_icd_term->instance) {
7044
0
                    loader_icd_close_objects(inst, cur_icd_term);
7045
0
                    cur_icd_term->dispatch.DestroyInstance(cur_icd_term->instance, allocation_callbacks);
7046
0
                }
7047
0
                cur_icd_term->instance = VK_NULL_HANDLE;
7048
0
                loader_icd_destroy(inst, cur_icd_term, allocation_callbacks);
7049
0
                cur_icd_term = NULL;
7050
0
                struct loader_scanned_icd *scanned_icd_to_remove = &inst->icd_tramp_list.scanned_list[cur_scanned_icd_index];
7051
                // Iterate through preloaded ICDs and remove the corresponding driver from that list
7052
0
                loader_platform_thread_lock_mutex(&loader_preload_icd_lock);
7053
0
                if (NULL != preloaded_icds.scanned_list) {
7054
0
                    for (uint32_t i = 0; i < preloaded_icds.count; i++) {
7055
0
                        if (NULL != preloaded_icds.scanned_list[i].lib_name && NULL != scanned_icd_to_remove->lib_name &&
7056
0
                            strcmp(preloaded_icds.scanned_list[i].lib_name, scanned_icd_to_remove->lib_name) == 0) {
7057
0
                            loader_unload_scanned_icd(NULL, &preloaded_icds.scanned_list[i]);
7058
                            // condense the list so that it doesn't contain empty elements.
7059
0
                            if (i < preloaded_icds.count - 1) {
7060
0
                                memcpy((void *)&preloaded_icds.scanned_list[i],
7061
0
                                       (void *)&preloaded_icds.scanned_list[preloaded_icds.count - 1],
7062
0
                                       sizeof(struct loader_scanned_icd));
7063
0
                                memset((void *)&preloaded_icds.scanned_list[preloaded_icds.count - 1], 0,
7064
0
                                       sizeof(struct loader_scanned_icd));
7065
0
                            }
7066
0
                            if (i > 0) {
7067
0
                                preloaded_icds.count--;
7068
0
                            }
7069
7070
0
                            break;
7071
0
                        }
7072
0
                    }
7073
0
                }
7074
0
                loader_platform_thread_unlock_mutex(&loader_preload_icd_lock);
7075
7076
0
                loader_unload_scanned_icd(inst, scanned_icd_to_remove);
7077
0
            }
7078
7079
0
            if (NULL == prev_icd_term) {
7080
0
                inst->icd_terms = next_icd_term;
7081
0
            } else {
7082
0
                prev_icd_term->next = next_icd_term;
7083
0
            }
7084
0
        } else {
7085
0
            prev_icd_term = cur_icd_term;
7086
0
        }
7087
0
        cur_icd_term = next_icd_term;
7088
0
    }
7089
0
}
7090
7091
VkResult setup_loader_tramp_phys_dev_groups(struct loader_instance *inst, uint32_t group_count,
7092
0
                                            VkPhysicalDeviceGroupProperties *groups) {
7093
0
    VkResult res = VK_SUCCESS;
7094
0
    uint32_t cur_idx;
7095
0
    uint32_t dev_idx;
7096
7097
0
    if (0 == group_count) {
7098
0
        return VK_SUCCESS;
7099
0
    }
7100
7101
    // Generate a list of all the devices and convert them to the loader ID
7102
0
    uint32_t phys_dev_count = 0;
7103
0
    for (cur_idx = 0; cur_idx < group_count; ++cur_idx) {
7104
0
        phys_dev_count += groups[cur_idx].physicalDeviceCount;
7105
0
    }
7106
0
    VkPhysicalDevice *devices = (VkPhysicalDevice *)loader_stack_alloc(sizeof(VkPhysicalDevice) * phys_dev_count);
7107
0
    if (NULL == devices) {
7108
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
7109
0
    }
7110
7111
0
    uint32_t cur_device = 0;
7112
0
    for (cur_idx = 0; cur_idx < group_count; ++cur_idx) {
7113
0
        for (dev_idx = 0; dev_idx < groups[cur_idx].physicalDeviceCount; ++dev_idx) {
7114
0
            devices[cur_device++] = groups[cur_idx].physicalDevices[dev_idx];
7115
0
        }
7116
0
    }
7117
7118
    // Update the devices based on the loader physical device values.
7119
0
    res = setup_loader_tramp_phys_devs(inst, phys_dev_count, devices);
7120
0
    if (VK_SUCCESS != res) {
7121
0
        return res;
7122
0
    }
7123
7124
    // Update the devices in the group structures now
7125
0
    cur_device = 0;
7126
0
    for (cur_idx = 0; cur_idx < group_count; ++cur_idx) {
7127
0
        for (dev_idx = 0; dev_idx < groups[cur_idx].physicalDeviceCount; ++dev_idx) {
7128
0
            groups[cur_idx].physicalDevices[dev_idx] = devices[cur_device++];
7129
0
        }
7130
0
    }
7131
7132
0
    return res;
7133
0
}
7134
7135
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumeratePhysicalDevices(VkInstance instance, uint32_t *pPhysicalDeviceCount,
7136
0
                                                                   VkPhysicalDevice *pPhysicalDevices) {
7137
0
    struct loader_instance *inst = (struct loader_instance *)instance;
7138
0
    VkResult res = VK_SUCCESS;
7139
7140
    // Always call the setup loader terminator physical devices because they may
7141
    // have changed at any point.
7142
0
    res = setup_loader_term_phys_devs(inst);
7143
0
    if (VK_SUCCESS != res) {
7144
0
        goto out;
7145
0
    }
7146
7147
0
    if (inst->settings.settings_active && inst->settings.device_configurations_active) {
7148
        // Use settings file device_configurations if present
7149
0
        if (NULL == pPhysicalDevices) {
7150
            // take the minimum of the settings configurations count and number of terminators
7151
0
            *pPhysicalDeviceCount = (inst->settings.device_configuration_count < inst->phys_dev_count_term)
7152
0
                                        ? inst->settings.device_configuration_count
7153
0
                                        : inst->phys_dev_count_term;
7154
0
        } else {
7155
0
            res = loader_apply_settings_device_configurations(inst, pPhysicalDeviceCount, pPhysicalDevices);
7156
0
        }
7157
0
    } else {
7158
        // Otherwise just copy the physical devices up normally and pass it up the chain
7159
0
        uint32_t copy_count = inst->phys_dev_count_term;
7160
0
        if (NULL != pPhysicalDevices) {
7161
0
            if (copy_count > *pPhysicalDeviceCount) {
7162
0
                copy_count = *pPhysicalDeviceCount;
7163
0
                loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
7164
0
                           "terminator_EnumeratePhysicalDevices : Trimming device count from %d to %d.", inst->phys_dev_count_term,
7165
0
                           copy_count);
7166
0
                res = VK_INCOMPLETE;
7167
0
            }
7168
7169
0
            for (uint32_t i = 0; i < copy_count; i++) {
7170
0
                pPhysicalDevices[i] = (VkPhysicalDevice)inst->phys_devs_term[i];
7171
0
            }
7172
0
        }
7173
7174
0
        *pPhysicalDeviceCount = copy_count;
7175
0
    }
7176
7177
0
out:
7178
7179
0
    return res;
7180
0
}
7181
7182
VkResult check_physical_device_extensions_for_driver_properties_extension(struct loader_physical_device_term *phys_dev_term,
7183
0
                                                                          bool *supports_driver_properties) {
7184
0
    *supports_driver_properties = false;
7185
0
    uint32_t extension_count = 0;
7186
0
    VkResult res = phys_dev_term->this_icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL,
7187
0
                                                                                             &extension_count, NULL);
7188
0
    if (res != VK_SUCCESS || extension_count == 0) {
7189
0
        return VK_SUCCESS;
7190
0
    }
7191
0
    VkExtensionProperties *extension_data = loader_stack_alloc(sizeof(VkExtensionProperties) * extension_count);
7192
0
    if (NULL == extension_data) {
7193
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
7194
0
    }
7195
7196
0
    res = phys_dev_term->this_icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL, &extension_count,
7197
0
                                                                                    extension_data);
7198
0
    if (res != VK_SUCCESS) {
7199
0
        return VK_SUCCESS;
7200
0
    }
7201
0
    for (uint32_t j = 0; j < extension_count; j++) {
7202
0
        if (!strcmp(extension_data[j].extensionName, VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME)) {
7203
0
            *supports_driver_properties = true;
7204
0
            return VK_SUCCESS;
7205
0
        }
7206
0
    }
7207
0
    return VK_SUCCESS;
7208
0
}
7209
7210
// Helper struct containing the relevant details of a VkPhysicalDevice necessary for applying the loader settings device
7211
// configurations.
7212
typedef struct physical_device_configuration_details {
7213
    bool pd_was_added;
7214
    bool pd_supports_vulkan_11;
7215
    bool pd_supports_driver_properties;
7216
    VkPhysicalDeviceProperties properties;
7217
    VkPhysicalDeviceIDProperties device_id_properties;
7218
    VkPhysicalDeviceDriverProperties driver_properties;
7219
7220
} physical_device_configuration_details;
7221
7222
// Apply the device_configurations in the settings file to the output VkPhysicalDeviceList.
7223
// That means looking up each VkPhysicalDevice's deviceUUID, filtering using that, and putting them in the order of
7224
// device_configurations in the settings file.
7225
VkResult loader_apply_settings_device_configurations(struct loader_instance *inst, uint32_t *pPhysicalDeviceCount,
7226
0
                                                     VkPhysicalDevice *pPhysicalDevices) {
7227
0
    loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
7228
0
               "Reordering the output of vkEnumeratePhysicalDevices to match the loader settings device configurations list");
7229
7230
0
    physical_device_configuration_details *pd_details =
7231
0
        loader_stack_alloc(inst->phys_dev_count_term * sizeof(physical_device_configuration_details));
7232
0
    if (NULL == pd_details) {
7233
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
7234
0
    }
7235
0
    memset(pd_details, 0, inst->phys_dev_count_term * sizeof(physical_device_configuration_details));
7236
7237
0
    for (uint32_t i = 0; i < inst->phys_dev_count_term; i++) {
7238
0
        struct loader_physical_device_term *phys_dev_term = inst->phys_devs_term[i];
7239
7240
0
        phys_dev_term->this_icd_term->dispatch.GetPhysicalDeviceProperties(phys_dev_term->phys_dev, &pd_details[i].properties);
7241
0
        if (pd_details[i].properties.apiVersion < VK_API_VERSION_1_1) {
7242
            // Device isn't eligible for sorting
7243
0
            continue;
7244
0
        }
7245
0
        pd_details[i].pd_supports_vulkan_11 = true;
7246
0
        if (pd_details[i].properties.apiVersion >= VK_API_VERSION_1_2) {
7247
0
            pd_details[i].pd_supports_driver_properties = true;
7248
0
        }
7249
7250
        // If this physical device isn't 1.2, then we need to check if it supports VK_KHR_driver_properties
7251
0
        if (!pd_details[i].pd_supports_driver_properties) {
7252
0
            VkResult res = check_physical_device_extensions_for_driver_properties_extension(
7253
0
                phys_dev_term, &pd_details[i].pd_supports_driver_properties);
7254
0
            if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
7255
0
                return res;
7256
0
            }
7257
0
        }
7258
7259
0
        pd_details[i].device_id_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
7260
0
        pd_details[i].driver_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES;
7261
0
        if (pd_details[i].pd_supports_driver_properties) {
7262
0
            pd_details[i].device_id_properties.pNext = (void *)&pd_details[i].driver_properties;
7263
0
        }
7264
7265
0
        VkPhysicalDeviceProperties2 props2 = {0};
7266
0
        props2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
7267
0
        props2.pNext = (void *)&pd_details[i].device_id_properties;
7268
0
        if (phys_dev_term->this_icd_term->dispatch.GetPhysicalDeviceProperties2) {
7269
0
            phys_dev_term->this_icd_term->dispatch.GetPhysicalDeviceProperties2(phys_dev_term->phys_dev, &props2);
7270
0
        }
7271
0
    }
7272
7273
    // Loop over the setting's device configurations, find each VkPhysicalDevice which matches the deviceUUID given, add to the
7274
    // pPhysicalDevices output list.
7275
0
    uint32_t written_output_index = 0;
7276
7277
0
    for (uint32_t i = 0; i < inst->settings.device_configuration_count; i++) {
7278
0
        uint8_t *current_deviceUUID = inst->settings.device_configurations[i].deviceUUID;
7279
0
        uint8_t *current_driverUUID = inst->settings.device_configurations[i].driverUUID;
7280
0
        bool configuration_found = false;
7281
0
        for (uint32_t j = 0; j < inst->phys_dev_count_term; j++) {
7282
            // Don't compare deviceUUID's if they have nothing, since we require deviceUUID's to effectively sort them.
7283
0
            if (!pd_details[j].pd_supports_vulkan_11) {
7284
0
                continue;
7285
0
            }
7286
0
            if (memcmp(current_deviceUUID, pd_details[j].device_id_properties.deviceUUID, sizeof(uint8_t) * VK_UUID_SIZE) == 0 &&
7287
0
                memcmp(current_driverUUID, pd_details[j].device_id_properties.driverUUID, sizeof(uint8_t) * VK_UUID_SIZE) == 0 &&
7288
0
                inst->settings.device_configurations[i].driverVersion == pd_details[j].properties.driverVersion) {
7289
0
                configuration_found = true;
7290
                // Catch when there are more device_configurations than space available in the output
7291
0
                if (written_output_index >= *pPhysicalDeviceCount) {
7292
0
                    *pPhysicalDeviceCount = written_output_index;  // write out how many were written
7293
0
                    return VK_INCOMPLETE;
7294
0
                }
7295
0
                if (pd_details[j].pd_supports_driver_properties) {
7296
0
                    loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
7297
0
                               "pPhysicalDevices array index %d is set to \"%s\" (%s, version %d) ", written_output_index,
7298
0
                               pd_details[j].properties.deviceName, pd_details[i].driver_properties.driverName,
7299
0
                               pd_details[i].properties.driverVersion);
7300
0
                } else {
7301
0
                    loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
7302
0
                               "pPhysicalDevices array index %d is set to \"%s\" (driver version %d) ", written_output_index,
7303
0
                               pd_details[j].properties.deviceName, pd_details[i].properties.driverVersion);
7304
0
                }
7305
0
                pPhysicalDevices[written_output_index++] = (VkPhysicalDevice)inst->phys_devs_term[j];
7306
0
                pd_details[j].pd_was_added = true;
7307
0
                break;
7308
0
            }
7309
0
        }
7310
0
        if (!configuration_found) {
7311
0
            char device_uuid_str[UUID_STR_LEN] = {0};
7312
0
            loader_log_generate_uuid_string(current_deviceUUID, device_uuid_str);
7313
0
            char driver_uuid_str[UUID_STR_LEN] = {0};
7314
0
            loader_log_generate_uuid_string(current_deviceUUID, driver_uuid_str);
7315
7316
            // Log that this configuration was missing.
7317
0
            if (inst->settings.device_configurations[i].deviceName[0] != '\0' &&
7318
0
                inst->settings.device_configurations[i].driverName[0] != '\0') {
7319
0
                loader_log(
7320
0
                    inst, VULKAN_LOADER_WARN_BIT, 0,
7321
0
                    "loader_apply_settings_device_configurations: settings file contained device_configuration which does not "
7322
0
                    "appear in the enumerated VkPhysicalDevices. Missing VkPhysicalDevice with deviceName: \"%s\", "
7323
0
                    "deviceUUID: %s, driverName: %s, driverUUID: %s, driverVersion: %d",
7324
0
                    inst->settings.device_configurations[i].deviceName, device_uuid_str,
7325
0
                    inst->settings.device_configurations[i].driverName, driver_uuid_str,
7326
0
                    inst->settings.device_configurations[i].driverVersion);
7327
0
            } else if (inst->settings.device_configurations[i].deviceName[0] != '\0') {
7328
0
                loader_log(
7329
0
                    inst, VULKAN_LOADER_WARN_BIT, 0,
7330
0
                    "loader_apply_settings_device_configurations: settings file contained device_configuration which does not "
7331
0
                    "appear in the enumerated VkPhysicalDevices. Missing VkPhysicalDevice with deviceName: \"%s\", "
7332
0
                    "deviceUUID: %s, driverUUID: %s, driverVersion: %d",
7333
0
                    inst->settings.device_configurations[i].deviceName, device_uuid_str, driver_uuid_str,
7334
0
                    inst->settings.device_configurations[i].driverVersion);
7335
0
            } else {
7336
0
                loader_log(
7337
0
                    inst, VULKAN_LOADER_WARN_BIT, 0,
7338
0
                    "loader_apply_settings_device_configurations: settings file contained device_configuration which does not "
7339
0
                    "appear in the enumerated VkPhysicalDevices. Missing VkPhysicalDevice with deviceUUID: "
7340
0
                    "%s, driverUUID: %s, driverVersion: %d",
7341
0
                    device_uuid_str, driver_uuid_str, inst->settings.device_configurations[i].driverVersion);
7342
0
            }
7343
0
        }
7344
0
    }
7345
7346
0
    for (uint32_t j = 0; j < inst->phys_dev_count_term; j++) {
7347
0
        if (!pd_details[j].pd_was_added) {
7348
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
7349
0
                       "VkPhysicalDevice \"%s\" did not appear in the settings file device configurations list, so was not added "
7350
0
                       "to the pPhysicalDevices array",
7351
0
                       pd_details[j].properties.deviceName);
7352
0
        }
7353
0
    }
7354
7355
0
    if (written_output_index == 0) {
7356
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
7357
0
                   "loader_apply_settings_device_configurations: None of the settings file device configurations had "
7358
0
                   "deviceUUID's that corresponded to enumerated VkPhysicalDevices. Returning VK_ERROR_INITIALIZATION_FAILED");
7359
0
        return VK_ERROR_INITIALIZATION_FAILED;
7360
0
    }
7361
7362
0
    *pPhysicalDeviceCount = written_output_index;  // update with how many were written
7363
0
    return VK_SUCCESS;
7364
0
}
7365
7366
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,
7367
                                                                             const char *pLayerName, uint32_t *pPropertyCount,
7368
0
                                                                             VkExtensionProperties *pProperties) {
7369
0
    if (NULL == pPropertyCount) {
7370
0
        return VK_INCOMPLETE;
7371
0
    }
7372
7373
0
    struct loader_physical_device_term *phys_dev_term;
7374
7375
    // Any layer or trampoline wrapping should be removed at this point in time can just cast to the expected
7376
    // type for VkPhysicalDevice.
7377
0
    phys_dev_term = (struct loader_physical_device_term *)physicalDevice;
7378
7379
    // if we got here with a non-empty pLayerName, look up the extensions
7380
    // from the json
7381
0
    if (pLayerName != NULL && strlen(pLayerName) > 0) {
7382
0
        uint32_t count;
7383
0
        uint32_t copy_size;
7384
0
        const struct loader_instance *inst = phys_dev_term->this_icd_term->this_instance;
7385
0
        struct loader_device_extension_list *dev_ext_list = NULL;
7386
0
        struct loader_device_extension_list local_ext_list;
7387
0
        memset(&local_ext_list, 0, sizeof(local_ext_list));
7388
0
        if (vk_string_validate(MaxLoaderStringLength, pLayerName) == VK_STRING_ERROR_NONE) {
7389
0
            for (uint32_t i = 0; i < inst->instance_layer_list.count; i++) {
7390
0
                struct loader_layer_properties *props = &inst->instance_layer_list.list[i];
7391
0
                if (strcmp(props->info.layerName, pLayerName) == 0) {
7392
0
                    dev_ext_list = &props->device_extension_list;
7393
0
                }
7394
0
            }
7395
7396
0
            count = (dev_ext_list == NULL) ? 0 : dev_ext_list->count;
7397
0
            if (pProperties == NULL) {
7398
0
                *pPropertyCount = count;
7399
0
                loader_destroy_generic_list(inst, (struct loader_generic_list *)&local_ext_list);
7400
0
                return VK_SUCCESS;
7401
0
            }
7402
7403
0
            copy_size = *pPropertyCount < count ? *pPropertyCount : count;
7404
0
            for (uint32_t i = 0; i < copy_size; i++) {
7405
0
                memcpy(&pProperties[i], &dev_ext_list->list[i].props, sizeof(VkExtensionProperties));
7406
0
            }
7407
0
            *pPropertyCount = copy_size;
7408
7409
0
            loader_destroy_generic_list(inst, (struct loader_generic_list *)&local_ext_list);
7410
0
            if (copy_size < count) {
7411
0
                return VK_INCOMPLETE;
7412
0
            }
7413
0
        } else {
7414
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7415
0
                       "vkEnumerateDeviceExtensionProperties:  pLayerName is too long or is badly formed");
7416
0
            return VK_ERROR_EXTENSION_NOT_PRESENT;
7417
0
        }
7418
7419
0
        return VK_SUCCESS;
7420
0
    }
7421
7422
    // user is querying driver extensions and has supplied their own storage - just fill it out
7423
0
    else if (pProperties) {
7424
0
        struct loader_icd_term *icd_term = phys_dev_term->this_icd_term;
7425
0
        uint32_t written_count = *pPropertyCount;
7426
0
        VkResult res =
7427
0
            icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL, &written_count, pProperties);
7428
0
        if (res != VK_SUCCESS) {
7429
0
            return res;
7430
0
        }
7431
7432
        // Iterate over active layers, if they are an implicit layer, add their device extensions
7433
        // After calling into the driver, written_count contains the amount of device extensions written. We can therefore write
7434
        // layer extensions starting at that point in pProperties
7435
0
        for (uint32_t i = 0; i < icd_term->this_instance->expanded_activated_layer_list.count; i++) {
7436
0
            struct loader_layer_properties *layer_props = icd_term->this_instance->expanded_activated_layer_list.list[i];
7437
0
            if (0 == (layer_props->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
7438
0
                struct loader_device_extension_list *layer_ext_list = &layer_props->device_extension_list;
7439
0
                for (uint32_t j = 0; j < layer_ext_list->count; j++) {
7440
0
                    struct loader_dev_ext_props *cur_ext_props = &layer_ext_list->list[j];
7441
                    // look for duplicates
7442
0
                    if (has_vk_extension_property_array(&cur_ext_props->props, written_count, pProperties)) {
7443
0
                        continue;
7444
0
                    }
7445
7446
0
                    if (*pPropertyCount <= written_count) {
7447
0
                        return VK_INCOMPLETE;
7448
0
                    }
7449
7450
0
                    memcpy(&pProperties[written_count], &cur_ext_props->props, sizeof(VkExtensionProperties));
7451
0
                    written_count++;
7452
0
                }
7453
0
            }
7454
0
        }
7455
        // Make sure we update the pPropertyCount with the how many were written
7456
0
        *pPropertyCount = written_count;
7457
0
        return res;
7458
0
    }
7459
    // Use `goto out;` for rest of this function
7460
7461
    // This case is during the call down the instance chain with pLayerName == NULL and pProperties == NULL
7462
0
    struct loader_icd_term *icd_term = phys_dev_term->this_icd_term;
7463
0
    struct loader_extension_list all_exts = {0};
7464
0
    VkResult res;
7465
7466
    // We need to find the count without duplicates. This requires querying the driver for the names of the extensions.
7467
0
    res = icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL, &all_exts.count, NULL);
7468
0
    if (res != VK_SUCCESS) {
7469
0
        goto out;
7470
0
    }
7471
    // Then allocate memory to store the physical device extension list + the extensions layers provide
7472
    // all_exts.count currently is the number of driver extensions
7473
0
    all_exts.capacity = sizeof(VkExtensionProperties) * (all_exts.count + 20);
7474
0
    all_exts.list = loader_instance_heap_alloc(icd_term->this_instance, all_exts.capacity, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
7475
0
    if (NULL == all_exts.list) {
7476
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
7477
0
        goto out;
7478
0
    }
7479
7480
    // Get the available device extensions and put them in all_exts.list
7481
0
    res = icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL, &all_exts.count, all_exts.list);
7482
0
    if (res != VK_SUCCESS) {
7483
0
        goto out;
7484
0
    }
7485
7486
    // Iterate over active layers, if they are an implicit layer, add their device extensions to all_exts.list
7487
0
    for (uint32_t i = 0; i < icd_term->this_instance->expanded_activated_layer_list.count; i++) {
7488
0
        struct loader_layer_properties *layer_props = icd_term->this_instance->expanded_activated_layer_list.list[i];
7489
0
        if (0 == (layer_props->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
7490
0
            struct loader_device_extension_list *layer_ext_list = &layer_props->device_extension_list;
7491
0
            for (uint32_t j = 0; j < layer_ext_list->count; j++) {
7492
0
                res = loader_add_to_ext_list(icd_term->this_instance, &all_exts, 1, &layer_ext_list->list[j].props);
7493
0
                if (res != VK_SUCCESS) {
7494
0
                    goto out;
7495
0
                }
7496
0
            }
7497
0
        }
7498
0
    }
7499
7500
    // Write out the final de-duplicated count to pPropertyCount
7501
0
    *pPropertyCount = all_exts.count;
7502
0
    res = VK_SUCCESS;
7503
7504
0
out:
7505
7506
0
    loader_destroy_generic_list(icd_term->this_instance, (struct loader_generic_list *)&all_exts);
7507
0
    return res;
7508
0
}
7509
7510
0
VkStringErrorFlags vk_string_validate(const int max_length, const char *utf8) {
7511
0
    VkStringErrorFlags result = VK_STRING_ERROR_NONE;
7512
0
    int num_char_bytes = 0;
7513
0
    int i, j;
7514
7515
0
    if (utf8 == NULL) {
7516
0
        return VK_STRING_ERROR_NULL_PTR;
7517
0
    }
7518
7519
0
    for (i = 0; i <= max_length; i++) {
7520
0
        if (utf8[i] == 0) {
7521
0
            break;
7522
0
        } else if (i == max_length) {
7523
0
            result |= VK_STRING_ERROR_LENGTH;
7524
0
            break;
7525
0
        } else if ((utf8[i] >= 0x20) && (utf8[i] < 0x7f)) {
7526
0
            num_char_bytes = 0;
7527
0
        } else if ((utf8[i] & UTF8_ONE_BYTE_MASK) == UTF8_ONE_BYTE_CODE) {
7528
0
            num_char_bytes = 1;
7529
0
        } else if ((utf8[i] & UTF8_TWO_BYTE_MASK) == UTF8_TWO_BYTE_CODE) {
7530
0
            num_char_bytes = 2;
7531
0
        } else if ((utf8[i] & UTF8_THREE_BYTE_MASK) == UTF8_THREE_BYTE_CODE) {
7532
0
            num_char_bytes = 3;
7533
0
        } else {
7534
0
            result = VK_STRING_ERROR_BAD_DATA;
7535
0
        }
7536
7537
        // Validate the following num_char_bytes of data
7538
0
        for (j = 0; (j < num_char_bytes) && (i < max_length); j++) {
7539
0
            if (++i == max_length) {
7540
0
                result |= VK_STRING_ERROR_LENGTH;
7541
0
                break;
7542
0
            }
7543
0
            if ((utf8[i] & UTF8_DATA_BYTE_MASK) != UTF8_DATA_BYTE_CODE) {
7544
0
                result |= VK_STRING_ERROR_BAD_DATA;
7545
0
            }
7546
0
        }
7547
0
    }
7548
0
    return result;
7549
0
}
7550
7551
0
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumerateInstanceVersion(uint32_t *pApiVersion) {
7552
    // NOTE: The Vulkan WG doesn't want us checking pApiVersion for NULL, but instead
7553
    // prefers us crashing.
7554
0
    *pApiVersion = VK_HEADER_VERSION_COMPLETE;
7555
0
    return VK_SUCCESS;
7556
0
}
7557
7558
VKAPI_ATTR VkResult VKAPI_CALL terminator_pre_instance_EnumerateInstanceVersion(const VkEnumerateInstanceVersionChain *chain,
7559
0
                                                                                uint32_t *pApiVersion) {
7560
0
    (void)chain;
7561
0
    return terminator_EnumerateInstanceVersion(pApiVersion);
7562
0
}
7563
7564
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pPropertyCount,
7565
0
                                                                               VkExtensionProperties *pProperties) {
7566
0
    struct loader_extension_list *global_ext_list = NULL;
7567
0
    struct loader_layer_list instance_layers;
7568
0
    struct loader_extension_list local_ext_list;
7569
0
    struct loader_icd_tramp_list icd_tramp_list;
7570
0
    uint32_t copy_size;
7571
0
    VkResult res = VK_SUCCESS;
7572
0
    struct loader_envvar_all_filters layer_filters = {0};
7573
7574
0
    memset(&local_ext_list, 0, sizeof(local_ext_list));
7575
0
    memset(&instance_layers, 0, sizeof(instance_layers));
7576
0
    memset(&icd_tramp_list, 0, sizeof(icd_tramp_list));
7577
7578
0
    res = parse_layer_environment_var_filters(NULL, &layer_filters);
7579
0
    if (VK_SUCCESS != res) {
7580
0
        goto out;
7581
0
    }
7582
7583
    // Get layer libraries if needed
7584
0
    if (pLayerName && strlen(pLayerName) != 0) {
7585
0
        if (vk_string_validate(MaxLoaderStringLength, pLayerName) != VK_STRING_ERROR_NONE) {
7586
0
            assert(VK_FALSE && "vkEnumerateInstanceExtensionProperties: pLayerName is too long or is badly formed");
7587
0
            res = VK_ERROR_EXTENSION_NOT_PRESENT;
7588
0
            goto out;
7589
0
        }
7590
7591
0
        res = loader_scan_for_layers(NULL, &instance_layers, &layer_filters);
7592
0
        if (VK_SUCCESS != res) {
7593
0
            goto out;
7594
0
        }
7595
0
        for (uint32_t i = 0; i < instance_layers.count; i++) {
7596
0
            struct loader_layer_properties *props = &instance_layers.list[i];
7597
0
            if (strcmp(props->info.layerName, pLayerName) == 0) {
7598
0
                global_ext_list = &props->instance_extension_list;
7599
0
                break;
7600
0
            }
7601
0
        }
7602
0
    } else {
7603
        // Preload ICD libraries so subsequent calls to EnumerateInstanceExtensionProperties don't have to load them
7604
0
        loader_preload_icds();
7605
7606
        // Scan/discover all ICD libraries
7607
0
        res = loader_icd_scan(NULL, &icd_tramp_list, NULL, NULL);
7608
        // EnumerateInstanceExtensionProperties can't return anything other than OOM or VK_ERROR_LAYER_NOT_PRESENT
7609
0
        if ((VK_SUCCESS != res && icd_tramp_list.count > 0) || res == VK_ERROR_OUT_OF_HOST_MEMORY) {
7610
0
            goto out;
7611
0
        }
7612
        // Get extensions from all ICD's, merge so no duplicates
7613
0
        res = loader_get_icd_loader_instance_extensions(NULL, &icd_tramp_list, &local_ext_list);
7614
0
        if (VK_SUCCESS != res) {
7615
0
            goto out;
7616
0
        }
7617
0
        loader_clear_scanned_icd_list(NULL, &icd_tramp_list);
7618
7619
        // Append enabled implicit layers.
7620
0
        res = loader_scan_for_implicit_layers(NULL, &instance_layers, &layer_filters);
7621
0
        if (VK_SUCCESS != res) {
7622
0
            goto out;
7623
0
        }
7624
0
        for (uint32_t i = 0; i < instance_layers.count; i++) {
7625
0
            struct loader_extension_list *ext_list = &instance_layers.list[i].instance_extension_list;
7626
0
            loader_add_to_ext_list(NULL, &local_ext_list, ext_list->count, ext_list->list);
7627
0
        }
7628
7629
0
        global_ext_list = &local_ext_list;
7630
0
    }
7631
7632
0
    if (global_ext_list == NULL) {
7633
0
        res = VK_ERROR_LAYER_NOT_PRESENT;
7634
0
        goto out;
7635
0
    }
7636
7637
0
    if (pProperties == NULL) {
7638
0
        *pPropertyCount = global_ext_list->count;
7639
0
        goto out;
7640
0
    }
7641
7642
0
    copy_size = *pPropertyCount < global_ext_list->count ? *pPropertyCount : global_ext_list->count;
7643
0
    for (uint32_t i = 0; i < copy_size; i++) {
7644
0
        memcpy(&pProperties[i], &global_ext_list->list[i], sizeof(VkExtensionProperties));
7645
0
    }
7646
0
    *pPropertyCount = copy_size;
7647
7648
0
    if (copy_size < global_ext_list->count) {
7649
0
        res = VK_INCOMPLETE;
7650
0
        goto out;
7651
0
    }
7652
7653
0
out:
7654
0
    loader_destroy_generic_list(NULL, (struct loader_generic_list *)&icd_tramp_list);
7655
0
    loader_destroy_generic_list(NULL, (struct loader_generic_list *)&local_ext_list);
7656
0
    loader_delete_layer_list_and_properties(NULL, &instance_layers);
7657
0
    return res;
7658
0
}
7659
7660
VKAPI_ATTR VkResult VKAPI_CALL terminator_pre_instance_EnumerateInstanceExtensionProperties(
7661
    const VkEnumerateInstanceExtensionPropertiesChain *chain, const char *pLayerName, uint32_t *pPropertyCount,
7662
0
    VkExtensionProperties *pProperties) {
7663
0
    (void)chain;
7664
0
    return terminator_EnumerateInstanceExtensionProperties(pLayerName, pPropertyCount, pProperties);
7665
0
}
7666
7667
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumerateInstanceLayerProperties(uint32_t *pPropertyCount,
7668
0
                                                                           VkLayerProperties *pProperties) {
7669
0
    VkResult result = VK_SUCCESS;
7670
0
    struct loader_layer_list instance_layer_list;
7671
0
    struct loader_envvar_all_filters layer_filters = {0};
7672
7673
0
    LOADER_PLATFORM_THREAD_ONCE(&once_init, loader_initialize);
7674
7675
0
    result = parse_layer_environment_var_filters(NULL, &layer_filters);
7676
0
    if (VK_SUCCESS != result) {
7677
0
        goto out;
7678
0
    }
7679
7680
    // Get layer libraries
7681
0
    memset(&instance_layer_list, 0, sizeof(instance_layer_list));
7682
0
    result = loader_scan_for_layers(NULL, &instance_layer_list, &layer_filters);
7683
0
    if (VK_SUCCESS != result) {
7684
0
        goto out;
7685
0
    }
7686
7687
0
    uint32_t layers_to_write_out = 0;
7688
0
    for (uint32_t i = 0; i < instance_layer_list.count; i++) {
7689
0
        if (instance_layer_list.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_ON ||
7690
0
            instance_layer_list.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_DEFAULT) {
7691
0
            layers_to_write_out++;
7692
0
        }
7693
0
    }
7694
7695
0
    if (pProperties == NULL) {
7696
0
        *pPropertyCount = layers_to_write_out;
7697
0
        goto out;
7698
0
    }
7699
7700
0
    uint32_t output_properties_index = 0;
7701
0
    for (uint32_t i = 0; i < instance_layer_list.count; i++) {
7702
0
        if (output_properties_index < *pPropertyCount &&
7703
0
            (instance_layer_list.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_ON ||
7704
0
             instance_layer_list.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_DEFAULT)) {
7705
0
            memcpy(&pProperties[output_properties_index], &instance_layer_list.list[i].info, sizeof(VkLayerProperties));
7706
0
            output_properties_index++;
7707
0
        }
7708
0
    }
7709
0
    if (output_properties_index < layers_to_write_out) {
7710
        // Indicates that we had more elements to write but ran out of room
7711
0
        result = VK_INCOMPLETE;
7712
0
    }
7713
7714
0
    *pPropertyCount = output_properties_index;
7715
7716
0
out:
7717
7718
0
    loader_delete_layer_list_and_properties(NULL, &instance_layer_list);
7719
0
    return result;
7720
0
}
7721
7722
VKAPI_ATTR VkResult VKAPI_CALL terminator_pre_instance_EnumerateInstanceLayerProperties(
7723
0
    const VkEnumerateInstanceLayerPropertiesChain *chain, uint32_t *pPropertyCount, VkLayerProperties *pProperties) {
7724
0
    (void)chain;
7725
0
    return terminator_EnumerateInstanceLayerProperties(pPropertyCount, pProperties);
7726
0
}
7727
7728
// ---- Vulkan Core 1.1 terminators
7729
7730
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumeratePhysicalDeviceGroups(
7731
0
    VkInstance instance, uint32_t *pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupProperties *pPhysicalDeviceGroupProperties) {
7732
0
    struct loader_instance *inst = (struct loader_instance *)instance;
7733
7734
0
    VkResult res = VK_SUCCESS;
7735
0
    struct loader_icd_term *icd_term;
7736
0
    uint32_t total_count = 0;
7737
0
    uint32_t cur_icd_group_count = 0;
7738
0
    VkPhysicalDeviceGroupProperties **new_phys_dev_groups = NULL;
7739
0
    struct loader_physical_device_group_term *local_phys_dev_groups = NULL;
7740
0
    PFN_vkEnumeratePhysicalDeviceGroups fpEnumeratePhysicalDeviceGroups = NULL;
7741
0
    struct loader_icd_physical_devices *sorted_phys_dev_array = NULL;
7742
0
    uint32_t sorted_count = 0;
7743
7744
    // For each ICD, query the number of physical device groups, and then get an
7745
    // internal value for those physical devices.
7746
0
    icd_term = inst->icd_terms;
7747
0
    while (NULL != icd_term) {
7748
0
        cur_icd_group_count = 0;
7749
7750
        // Get the function pointer to use to call into the ICD. This could be the core or KHR version
7751
0
        if (inst->enabled_extensions.khr_device_group_creation) {
7752
0
            fpEnumeratePhysicalDeviceGroups = icd_term->dispatch.EnumeratePhysicalDeviceGroupsKHR;
7753
0
        } else {
7754
0
            fpEnumeratePhysicalDeviceGroups = icd_term->dispatch.EnumeratePhysicalDeviceGroups;
7755
0
        }
7756
7757
0
        if (NULL == fpEnumeratePhysicalDeviceGroups) {
7758
            // Treat each ICD's GPU as it's own group if the extension isn't supported
7759
0
            res = icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &cur_icd_group_count, NULL);
7760
0
            if (res != VK_SUCCESS) {
7761
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7762
0
                           "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of \'EnumeratePhysicalDevices\' "
7763
0
                           "to ICD %s to get plain phys dev count.",
7764
0
                           icd_term->scanned_icd->lib_name);
7765
0
                continue;
7766
0
            }
7767
0
        } else {
7768
            // Query the actual group info
7769
0
            res = fpEnumeratePhysicalDeviceGroups(icd_term->instance, &cur_icd_group_count, NULL);
7770
0
            if (res != VK_SUCCESS) {
7771
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7772
0
                           "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7773
0
                           "\'EnumeratePhysicalDeviceGroups\' to ICD %s to get count.",
7774
0
                           icd_term->scanned_icd->lib_name);
7775
0
                continue;
7776
0
            }
7777
0
        }
7778
0
        total_count += cur_icd_group_count;
7779
0
        icd_term = icd_term->next;
7780
0
    }
7781
7782
    // If GPUs not sorted yet, look through them and generate list of all available GPUs
7783
0
    if (0 == total_count || 0 == inst->total_gpu_count) {
7784
0
        res = setup_loader_term_phys_devs(inst);
7785
0
        if (VK_SUCCESS != res) {
7786
0
            goto out;
7787
0
        }
7788
0
    }
7789
7790
0
    if (NULL != pPhysicalDeviceGroupProperties) {
7791
        // Create an array for the new physical device groups, which will be stored
7792
        // in the instance for the Terminator code.
7793
0
        new_phys_dev_groups = (VkPhysicalDeviceGroupProperties **)loader_instance_heap_calloc(
7794
0
            inst, total_count * sizeof(VkPhysicalDeviceGroupProperties *), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
7795
0
        if (NULL == new_phys_dev_groups) {
7796
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7797
0
                       "terminator_EnumeratePhysicalDeviceGroups:  Failed to allocate new physical device group array of size %d",
7798
0
                       total_count);
7799
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
7800
0
            goto out;
7801
0
        }
7802
7803
        // Create a temporary array (on the stack) to keep track of the
7804
        // returned VkPhysicalDevice values.
7805
0
        local_phys_dev_groups = loader_stack_alloc(sizeof(struct loader_physical_device_group_term) * total_count);
7806
        // Initialize the memory to something valid
7807
0
        memset(local_phys_dev_groups, 0, sizeof(struct loader_physical_device_group_term) * total_count);
7808
7809
#if defined(_WIN32)
7810
        // Get the physical devices supported by platform sorting mechanism into a separate list
7811
        res = windows_read_sorted_physical_devices(inst, &sorted_count, &sorted_phys_dev_array);
7812
        if (VK_SUCCESS != res) {
7813
            goto out;
7814
        }
7815
#endif
7816
7817
0
        cur_icd_group_count = 0;
7818
0
        icd_term = inst->icd_terms;
7819
0
        while (NULL != icd_term) {
7820
0
            uint32_t count_this_time = total_count - cur_icd_group_count;
7821
7822
            // Get the function pointer to use to call into the ICD. This could be the core or KHR version
7823
0
            if (inst->enabled_extensions.khr_device_group_creation) {
7824
0
                fpEnumeratePhysicalDeviceGroups = icd_term->dispatch.EnumeratePhysicalDeviceGroupsKHR;
7825
0
            } else {
7826
0
                fpEnumeratePhysicalDeviceGroups = icd_term->dispatch.EnumeratePhysicalDeviceGroups;
7827
0
            }
7828
7829
0
            if (NULL == fpEnumeratePhysicalDeviceGroups) {
7830
0
                icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &count_this_time, NULL);
7831
7832
0
                VkPhysicalDevice *phys_dev_array = loader_stack_alloc(sizeof(VkPhysicalDevice) * count_this_time);
7833
0
                if (NULL == phys_dev_array) {
7834
0
                    loader_log(
7835
0
                        inst, VULKAN_LOADER_ERROR_BIT, 0,
7836
0
                        "terminator_EnumeratePhysicalDeviceGroups:  Failed to allocate local physical device array of size %d",
7837
0
                        count_this_time);
7838
0
                    res = VK_ERROR_OUT_OF_HOST_MEMORY;
7839
0
                    goto out;
7840
0
                }
7841
7842
0
                res = icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &count_this_time, phys_dev_array);
7843
0
                if (res != VK_SUCCESS) {
7844
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7845
0
                               "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7846
0
                               "\'EnumeratePhysicalDevices\' to ICD %s to get plain phys dev count.",
7847
0
                               icd_term->scanned_icd->lib_name);
7848
0
                    goto out;
7849
0
                }
7850
7851
                // Add each GPU as it's own group
7852
0
                for (uint32_t indiv_gpu = 0; indiv_gpu < count_this_time; indiv_gpu++) {
7853
0
                    uint32_t cur_index = indiv_gpu + cur_icd_group_count;
7854
0
                    local_phys_dev_groups[cur_index].this_icd_term = icd_term;
7855
0
                    local_phys_dev_groups[cur_index].group_props.physicalDeviceCount = 1;
7856
0
                    local_phys_dev_groups[cur_index].group_props.physicalDevices[0] = phys_dev_array[indiv_gpu];
7857
0
                }
7858
7859
0
            } else {
7860
0
                res = fpEnumeratePhysicalDeviceGroups(icd_term->instance, &count_this_time, NULL);
7861
0
                if (res != VK_SUCCESS) {
7862
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7863
0
                               "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7864
0
                               "\'EnumeratePhysicalDeviceGroups\' to ICD %s to get group count.",
7865
0
                               icd_term->scanned_icd->lib_name);
7866
0
                    goto out;
7867
0
                }
7868
0
                if (cur_icd_group_count + count_this_time < *pPhysicalDeviceGroupCount) {
7869
                    // The total amount is still less than the amount of physical device group data passed in
7870
                    // by the callee.  Therefore, we don't have to allocate any temporary structures and we
7871
                    // can just use the data that was passed in.
7872
0
                    res = fpEnumeratePhysicalDeviceGroups(icd_term->instance, &count_this_time,
7873
0
                                                          &pPhysicalDeviceGroupProperties[cur_icd_group_count]);
7874
0
                    if (res != VK_SUCCESS) {
7875
0
                        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7876
0
                                   "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7877
0
                                   "\'EnumeratePhysicalDeviceGroups\' to ICD %s to get group information.",
7878
0
                                   icd_term->scanned_icd->lib_name);
7879
0
                        goto out;
7880
0
                    }
7881
0
                    for (uint32_t group = 0; group < count_this_time; ++group) {
7882
0
                        uint32_t cur_index = group + cur_icd_group_count;
7883
0
                        local_phys_dev_groups[cur_index].group_props = pPhysicalDeviceGroupProperties[cur_index];
7884
0
                        local_phys_dev_groups[cur_index].this_icd_term = icd_term;
7885
0
                    }
7886
0
                } else {
7887
                    // There's not enough space in the callee's allocated pPhysicalDeviceGroupProperties structs,
7888
                    // so we have to allocate temporary versions to collect all the data.  However, we need to make
7889
                    // sure that at least the ones we do query utilize any pNext data in the callee's version.
7890
0
                    VkPhysicalDeviceGroupProperties *tmp_group_props =
7891
0
                        loader_stack_alloc(count_this_time * sizeof(VkPhysicalDeviceGroupProperties));
7892
0
                    for (uint32_t group = 0; group < count_this_time; group++) {
7893
0
                        tmp_group_props[group].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES;
7894
0
                        uint32_t cur_index = group + cur_icd_group_count;
7895
0
                        if (*pPhysicalDeviceGroupCount > cur_index) {
7896
0
                            tmp_group_props[group].pNext = pPhysicalDeviceGroupProperties[cur_index].pNext;
7897
0
                        } else {
7898
0
                            tmp_group_props[group].pNext = NULL;
7899
0
                        }
7900
0
                        tmp_group_props[group].subsetAllocation = false;
7901
0
                    }
7902
7903
0
                    res = fpEnumeratePhysicalDeviceGroups(icd_term->instance, &count_this_time, tmp_group_props);
7904
0
                    if (res != VK_SUCCESS) {
7905
0
                        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7906
0
                                   "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7907
0
                                   "\'EnumeratePhysicalDeviceGroups\' to ICD %s  to get group information for temp data.",
7908
0
                                   icd_term->scanned_icd->lib_name);
7909
0
                        goto out;
7910
0
                    }
7911
0
                    for (uint32_t group = 0; group < count_this_time; ++group) {
7912
0
                        uint32_t cur_index = group + cur_icd_group_count;
7913
0
                        local_phys_dev_groups[cur_index].group_props = tmp_group_props[group];
7914
0
                        local_phys_dev_groups[cur_index].this_icd_term = icd_term;
7915
0
                    }
7916
0
                }
7917
0
                if (VK_SUCCESS != res) {
7918
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7919
0
                               "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7920
0
                               "\'EnumeratePhysicalDeviceGroups\' to ICD %s to get content.",
7921
0
                               icd_term->scanned_icd->lib_name);
7922
0
                    goto out;
7923
0
                }
7924
0
            }
7925
7926
0
            cur_icd_group_count += count_this_time;
7927
0
            icd_term = icd_term->next;
7928
0
        }
7929
7930
0
#if defined(LOADER_ENABLE_LINUX_SORT)
7931
0
        if (is_linux_sort_enabled(inst)) {
7932
            // Get the physical devices supported by platform sorting mechanism into a separate list
7933
0
            res = linux_sort_physical_device_groups(inst, total_count, local_phys_dev_groups);
7934
0
        }
7935
#elif defined(_WIN32)
7936
        // The Windows sorting information is only on physical devices.  We need to take that and convert it to the group
7937
        // information if it's present.
7938
        if (sorted_count > 0) {
7939
            res =
7940
                windows_sort_physical_device_groups(inst, total_count, local_phys_dev_groups, sorted_count, sorted_phys_dev_array);
7941
        }
7942
#endif  // LOADER_ENABLE_LINUX_SORT
7943
7944
        // Just to be safe, make sure we successfully completed setup_loader_term_phys_devs above
7945
        // before attempting to do the following.  By verifying that setup_loader_term_phys_devs ran
7946
        // first, it guarantees that each physical device will have a loader-specific handle.
7947
0
        if (NULL != inst->phys_devs_term) {
7948
0
            for (uint32_t group = 0; group < total_count; group++) {
7949
0
                for (uint32_t group_gpu = 0; group_gpu < local_phys_dev_groups[group].group_props.physicalDeviceCount;
7950
0
                     group_gpu++) {
7951
0
                    bool found = false;
7952
0
                    for (uint32_t term_gpu = 0; term_gpu < inst->phys_dev_count_term; term_gpu++) {
7953
0
                        if (local_phys_dev_groups[group].group_props.physicalDevices[group_gpu] ==
7954
0
                            inst->phys_devs_term[term_gpu]->phys_dev) {
7955
0
                            local_phys_dev_groups[group].group_props.physicalDevices[group_gpu] =
7956
0
                                (VkPhysicalDevice)inst->phys_devs_term[term_gpu];
7957
0
                            found = true;
7958
0
                            break;
7959
0
                        }
7960
0
                    }
7961
0
                    if (!found) {
7962
0
                        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7963
0
                                   "terminator_EnumeratePhysicalDeviceGroups:  Failed to find GPU %d in group %d returned by "
7964
0
                                   "\'EnumeratePhysicalDeviceGroups\' in list returned by \'EnumeratePhysicalDevices\'",
7965
0
                                   group_gpu, group);
7966
0
                        res = VK_ERROR_INITIALIZATION_FAILED;
7967
0
                        goto out;
7968
0
                    }
7969
0
                }
7970
0
            }
7971
0
        }
7972
7973
0
        uint32_t idx = 0;
7974
7975
        // Copy or create everything to fill the new array of physical device groups
7976
0
        for (uint32_t group = 0; group < total_count; group++) {
7977
            // Skip groups which have been included through sorting
7978
0
            if (local_phys_dev_groups[group].group_props.physicalDeviceCount == 0) {
7979
0
                continue;
7980
0
            }
7981
7982
            // Find the VkPhysicalDeviceGroupProperties object in local_phys_dev_groups
7983
0
            VkPhysicalDeviceGroupProperties *group_properties = &local_phys_dev_groups[group].group_props;
7984
7985
            // Check if this physical device group with the same contents is already in the old buffer
7986
0
            for (uint32_t old_idx = 0; old_idx < inst->phys_dev_group_count_term; old_idx++) {
7987
0
                if (NULL != group_properties && NULL != inst->phys_dev_groups_term[old_idx] &&
7988
0
                    group_properties->physicalDeviceCount == inst->phys_dev_groups_term[old_idx]->physicalDeviceCount) {
7989
0
                    bool found_all_gpus = true;
7990
0
                    for (uint32_t old_gpu = 0; old_gpu < inst->phys_dev_groups_term[old_idx]->physicalDeviceCount; old_gpu++) {
7991
0
                        bool found_gpu = false;
7992
0
                        for (uint32_t new_gpu = 0; new_gpu < group_properties->physicalDeviceCount; new_gpu++) {
7993
0
                            if (group_properties->physicalDevices[new_gpu] ==
7994
0
                                inst->phys_dev_groups_term[old_idx]->physicalDevices[old_gpu]) {
7995
0
                                found_gpu = true;
7996
0
                                break;
7997
0
                            }
7998
0
                        }
7999
8000
0
                        if (!found_gpu) {
8001
0
                            found_all_gpus = false;
8002
0
                            break;
8003
0
                        }
8004
0
                    }
8005
0
                    if (!found_all_gpus) {
8006
0
                        continue;
8007
0
                    } else {
8008
0
                        new_phys_dev_groups[idx] = inst->phys_dev_groups_term[old_idx];
8009
0
                        break;
8010
0
                    }
8011
0
                }
8012
0
            }
8013
            // If this physical device group isn't in the old buffer, create it
8014
0
            if (group_properties != NULL && NULL == new_phys_dev_groups[idx]) {
8015
0
                new_phys_dev_groups[idx] = (VkPhysicalDeviceGroupProperties *)loader_instance_heap_alloc(
8016
0
                    inst, sizeof(VkPhysicalDeviceGroupProperties), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
8017
0
                if (NULL == new_phys_dev_groups[idx]) {
8018
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
8019
0
                               "terminator_EnumeratePhysicalDeviceGroups:  Failed to allocate physical device group Terminator "
8020
0
                               "object %d",
8021
0
                               idx);
8022
0
                    total_count = idx;
8023
0
                    res = VK_ERROR_OUT_OF_HOST_MEMORY;
8024
0
                    goto out;
8025
0
                }
8026
0
                memcpy(new_phys_dev_groups[idx], group_properties, sizeof(VkPhysicalDeviceGroupProperties));
8027
0
            }
8028
8029
0
            ++idx;
8030
0
        }
8031
0
    }
8032
8033
0
out:
8034
8035
0
    if (NULL != pPhysicalDeviceGroupProperties) {
8036
0
        if (VK_SUCCESS != res) {
8037
0
            if (NULL != new_phys_dev_groups) {
8038
                // We've encountered an error, so we should free the new buffers.
8039
0
                for (uint32_t i = 0; i < total_count; i++) {
8040
                    // If an OOM occurred inside the copying of the new physical device groups into the existing array will
8041
                    // leave some of the old physical device groups in the array which may have been copied into the new array,
8042
                    // leading to them being freed twice. To avoid this we just make sure to not delete physical device groups
8043
                    // which were copied.
8044
0
                    bool found = false;
8045
0
                    if (NULL != inst->phys_devs_term) {
8046
0
                        for (uint32_t old_idx = 0; old_idx < inst->phys_dev_group_count_term; old_idx++) {
8047
0
                            if (new_phys_dev_groups[i] == inst->phys_dev_groups_term[old_idx]) {
8048
0
                                found = true;
8049
0
                                break;
8050
0
                            }
8051
0
                        }
8052
0
                    }
8053
0
                    if (!found) {
8054
0
                        loader_instance_heap_free(inst, new_phys_dev_groups[i]);
8055
0
                    }
8056
0
                }
8057
0
                loader_instance_heap_free(inst, new_phys_dev_groups);
8058
0
            }
8059
0
        } else {
8060
0
            if (NULL != inst->phys_dev_groups_term) {
8061
                // Free everything in the old array that was not copied into the new array
8062
                // here.  We can't attempt to do that before here since the previous loop
8063
                // looking before the "out:" label may hit an out of memory condition resulting
8064
                // in memory leaking.
8065
0
                for (uint32_t i = 0; i < inst->phys_dev_group_count_term; i++) {
8066
0
                    bool found = false;
8067
0
                    for (uint32_t j = 0; j < total_count; j++) {
8068
0
                        if (inst->phys_dev_groups_term[i] == new_phys_dev_groups[j]) {
8069
0
                            found = true;
8070
0
                            break;
8071
0
                        }
8072
0
                    }
8073
0
                    if (!found) {
8074
0
                        loader_instance_heap_free(inst, inst->phys_dev_groups_term[i]);
8075
0
                    }
8076
0
                }
8077
0
                loader_instance_heap_free(inst, inst->phys_dev_groups_term);
8078
0
            }
8079
8080
            // Swap in the new physical device group list
8081
0
            inst->phys_dev_group_count_term = total_count;
8082
0
            inst->phys_dev_groups_term = new_phys_dev_groups;
8083
0
        }
8084
8085
0
        if (sorted_phys_dev_array != NULL) {
8086
0
            for (uint32_t i = 0; i < sorted_count; ++i) {
8087
0
                if (sorted_phys_dev_array[i].device_count > 0 && sorted_phys_dev_array[i].physical_devices != NULL) {
8088
0
                    loader_instance_heap_free(inst, sorted_phys_dev_array[i].physical_devices);
8089
0
                }
8090
0
            }
8091
0
            loader_instance_heap_free(inst, sorted_phys_dev_array);
8092
0
        }
8093
8094
0
        uint32_t copy_count = inst->phys_dev_group_count_term;
8095
0
        if (NULL != pPhysicalDeviceGroupProperties) {
8096
0
            if (copy_count > *pPhysicalDeviceGroupCount) {
8097
0
                copy_count = *pPhysicalDeviceGroupCount;
8098
0
                loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
8099
0
                           "terminator_EnumeratePhysicalDeviceGroups : Trimming device count from %d to %d.",
8100
0
                           inst->phys_dev_group_count_term, copy_count);
8101
0
                res = VK_INCOMPLETE;
8102
0
            }
8103
8104
0
            for (uint32_t i = 0; i < copy_count; i++) {
8105
0
                memcpy(&pPhysicalDeviceGroupProperties[i], inst->phys_dev_groups_term[i], sizeof(VkPhysicalDeviceGroupProperties));
8106
0
            }
8107
0
        }
8108
8109
0
        *pPhysicalDeviceGroupCount = copy_count;
8110
8111
0
    } else {
8112
0
        *pPhysicalDeviceGroupCount = total_count;
8113
0
    }
8114
0
    return res;
8115
0
}
8116
8117
0
VkResult get_device_driver_id(VkPhysicalDevice physicalDevice, VkDriverId *driverId) {
8118
0
    VkPhysicalDeviceDriverProperties physical_device_driver_props = {0};
8119
0
    physical_device_driver_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES;
8120
8121
0
    VkPhysicalDeviceProperties2 props2 = {0};
8122
0
    props2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
8123
0
    props2.pNext = &physical_device_driver_props;
8124
8125
0
    struct loader_physical_device_term *phys_dev_term = (struct loader_physical_device_term *)physicalDevice;
8126
0
    struct loader_icd_term *icd_term = phys_dev_term->this_icd_term;
8127
0
    const struct loader_instance *inst = icd_term->this_instance;
8128
8129
0
    assert(inst != NULL);
8130
8131
    // Get the function pointer to use to call into the ICD. This could be the core or KHR version
8132
0
    PFN_vkGetPhysicalDeviceProperties2 fpGetPhysicalDeviceProperties2 = NULL;
8133
0
    if (loader_check_version_meets_required(LOADER_VERSION_1_1_0, inst->app_api_version)) {
8134
0
        fpGetPhysicalDeviceProperties2 = icd_term->dispatch.GetPhysicalDeviceProperties2;
8135
0
    }
8136
0
    if (fpGetPhysicalDeviceProperties2 == NULL && inst->enabled_extensions.khr_get_physical_device_properties2) {
8137
0
        fpGetPhysicalDeviceProperties2 = icd_term->dispatch.GetPhysicalDeviceProperties2KHR;
8138
0
    }
8139
8140
0
    if (fpGetPhysicalDeviceProperties2 == NULL) {
8141
0
        *driverId = 0;
8142
0
        return VK_ERROR_UNKNOWN;
8143
0
    }
8144
8145
0
    fpGetPhysicalDeviceProperties2(phys_dev_term->phys_dev, &props2);
8146
8147
0
    *driverId = physical_device_driver_props.driverID;
8148
0
    return VK_SUCCESS;
8149
0
}
8150
8151
VkResult loader_filter_enumerated_physical_device(const struct loader_instance *inst,
8152
                                                  const struct loader_envvar_id_filter *device_id_filter,
8153
                                                  const struct loader_envvar_id_filter *vendor_id_filter,
8154
                                                  const struct loader_envvar_id_filter *driver_id_filter,
8155
                                                  const uint32_t in_PhysicalDeviceCount,
8156
                                                  const VkPhysicalDevice *in_pPhysicalDevices, uint32_t *out_pPhysicalDeviceCount,
8157
0
                                                  VkPhysicalDevice *out_pPhysicalDevices) {
8158
0
    uint32_t filtered_physical_device_count = 0;
8159
0
    for (uint32_t i = 0; i < in_PhysicalDeviceCount; i++) {
8160
0
        VkPhysicalDeviceProperties dev_props = {0};
8161
0
        inst->disp->layer_inst_disp.GetPhysicalDeviceProperties(in_pPhysicalDevices[i], &dev_props);
8162
8163
0
        if ((0 != device_id_filter->count) && !check_id_matches_filter_environment_var(dev_props.deviceID, device_id_filter)) {
8164
0
            continue;
8165
0
        }
8166
8167
0
        if ((0 != vendor_id_filter->count) && !check_id_matches_filter_environment_var(dev_props.vendorID, vendor_id_filter)) {
8168
0
            continue;
8169
0
        }
8170
8171
0
        if (0 != driver_id_filter->count) {
8172
0
            VkDriverId driver_id;
8173
0
            VkResult res = get_device_driver_id(in_pPhysicalDevices[i], &driver_id);
8174
8175
0
            if ((res != VK_SUCCESS) || !check_id_matches_filter_environment_var(driver_id, driver_id_filter)) {
8176
0
                continue;
8177
0
            }
8178
0
        }
8179
8180
0
        if ((NULL != out_pPhysicalDevices) && (filtered_physical_device_count < *out_pPhysicalDeviceCount)) {
8181
0
            out_pPhysicalDevices[filtered_physical_device_count] = in_pPhysicalDevices[i];
8182
0
        }
8183
0
        filtered_physical_device_count++;
8184
0
    }
8185
8186
0
    if ((NULL == out_pPhysicalDevices) || (filtered_physical_device_count < *out_pPhysicalDeviceCount)) {
8187
0
        *out_pPhysicalDeviceCount = filtered_physical_device_count;
8188
0
    }
8189
8190
0
    return (*out_pPhysicalDeviceCount < filtered_physical_device_count) ? VK_INCOMPLETE : VK_SUCCESS;
8191
0
}
8192
8193
VkResult loader_filter_enumerated_physical_device_groups(
8194
    const struct loader_instance *inst, const struct loader_envvar_id_filter *device_id_filter,
8195
    const struct loader_envvar_id_filter *vendor_id_filter, const struct loader_envvar_id_filter *driver_id_filter,
8196
    const uint32_t in_PhysicalDeviceGroupCount, const VkPhysicalDeviceGroupProperties *in_pPhysicalDeviceGroupProperties,
8197
0
    uint32_t *out_PhysicalDeviceGroupCount, VkPhysicalDeviceGroupProperties *out_pPhysicalDeviceGroupProperties) {
8198
0
    uint32_t filtered_physical_device_group_count = 0;
8199
0
    for (uint32_t i = 0; i < in_PhysicalDeviceGroupCount; i++) {
8200
0
        const VkPhysicalDeviceGroupProperties *device_group = &in_pPhysicalDeviceGroupProperties[i];
8201
8202
0
        bool skip_group = false;
8203
0
        for (uint32_t j = 0; j < device_group->physicalDeviceCount; j++) {
8204
0
            VkPhysicalDeviceProperties dev_props = {0};
8205
0
            inst->disp->layer_inst_disp.GetPhysicalDeviceProperties(device_group->physicalDevices[j], &dev_props);
8206
8207
0
            if ((0 != device_id_filter->count) && !check_id_matches_filter_environment_var(dev_props.deviceID, device_id_filter)) {
8208
0
                skip_group = true;
8209
0
                break;
8210
0
            }
8211
8212
0
            if ((0 != vendor_id_filter->count) && !check_id_matches_filter_environment_var(dev_props.vendorID, vendor_id_filter)) {
8213
0
                skip_group = true;
8214
0
                break;
8215
0
            }
8216
8217
0
            if (0 != driver_id_filter->count) {
8218
0
                VkDriverId driver_id;
8219
0
                VkResult res = get_device_driver_id(device_group->physicalDevices[j], &driver_id);
8220
8221
0
                if ((res != VK_SUCCESS) || !check_id_matches_filter_environment_var(driver_id, driver_id_filter)) {
8222
0
                    skip_group = true;
8223
0
                    break;
8224
0
                }
8225
0
            }
8226
0
        }
8227
8228
0
        if (skip_group) {
8229
0
            continue;
8230
0
        }
8231
8232
0
        if ((NULL != out_pPhysicalDeviceGroupProperties) &&
8233
0
            (filtered_physical_device_group_count < *out_PhysicalDeviceGroupCount)) {
8234
0
            out_pPhysicalDeviceGroupProperties[filtered_physical_device_group_count] = *device_group;
8235
0
        }
8236
8237
0
        filtered_physical_device_group_count++;
8238
0
    }
8239
8240
0
    if ((NULL == out_pPhysicalDeviceGroupProperties) || (filtered_physical_device_group_count < *out_PhysicalDeviceGroupCount)) {
8241
0
        *out_PhysicalDeviceGroupCount = filtered_physical_device_group_count;
8242
0
    }
8243
8244
0
    return (*out_PhysicalDeviceGroupCount < filtered_physical_device_group_count) ? VK_INCOMPLETE : VK_SUCCESS;
8245
0
}