Coverage Report

Created: 2026-04-12 06:39

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