Coverage Report

Created: 2026-02-26 06:46

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
335
loader_api_version loader_make_full_version(uint32_t version) {
122
335
    loader_api_version out_version;
123
335
    out_version.major = VK_API_VERSION_MAJOR(version);
124
335
    out_version.minor = VK_API_VERSION_MINOR(version);
125
335
    out_version.patch = VK_API_VERSION_PATCH(version);
126
335
    return out_version;
127
335
}
128
129
768
loader_api_version loader_combine_version(uint32_t major, uint32_t minor, uint32_t patch) {
130
768
    loader_api_version out_version;
131
768
    out_version.major = (uint16_t)major;
132
768
    out_version.minor = (uint16_t)minor;
133
768
    out_version.patch = (uint16_t)patch;
134
768
    return out_version;
135
768
}
136
137
// Helper macros for determining if a version is valid or not
138
768
bool loader_check_version_meets_required(loader_api_version required, loader_api_version version) {
139
    // major version is satisfied
140
768
    return (version.major > required.major) ||
141
           // major version is equal, minor version is patch version is greater to minimum minor
142
568
           (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
351
           (version.major == required.major && version.minor == required.minor && version.patch >= required.patch);
145
768
}
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
66.8k
void loader_free_layer_properties(const struct loader_instance *inst, struct loader_layer_properties *layer_properties) {
249
66.8k
    loader_instance_heap_free(inst, layer_properties->manifest_file_name);
250
66.8k
    loader_instance_heap_free(inst, layer_properties->lib_name);
251
66.8k
    loader_instance_heap_free(inst, layer_properties->functions.str_gipa);
252
66.8k
    loader_instance_heap_free(inst, layer_properties->functions.str_gdpa);
253
66.8k
    loader_instance_heap_free(inst, layer_properties->functions.str_negotiate_interface);
254
66.8k
    loader_destroy_generic_list(inst, (struct loader_generic_list *)&layer_properties->instance_extension_list);
255
66.8k
    if (layer_properties->device_extension_list.capacity > 0 && NULL != layer_properties->device_extension_list.list) {
256
52
        for (uint32_t i = 0; i < layer_properties->device_extension_list.count; i++) {
257
28
            free_string_list(inst, &layer_properties->device_extension_list.list[i].entrypoints);
258
28
        }
259
24
    }
260
66.8k
    loader_destroy_generic_list(inst, (struct loader_generic_list *)&layer_properties->device_extension_list);
261
66.8k
    loader_instance_heap_free(inst, layer_properties->disable_env_var.name);
262
66.8k
    loader_instance_heap_free(inst, layer_properties->disable_env_var.value);
263
66.8k
    loader_instance_heap_free(inst, layer_properties->enable_env_var.name);
264
66.8k
    loader_instance_heap_free(inst, layer_properties->enable_env_var.value);
265
66.8k
    free_string_list(inst, &layer_properties->component_layer_names);
266
66.8k
    loader_instance_heap_free(inst, layer_properties->pre_instance_functions.enumerate_instance_extension_properties);
267
66.8k
    loader_instance_heap_free(inst, layer_properties->pre_instance_functions.enumerate_instance_layer_properties);
268
66.8k
    loader_instance_heap_free(inst, layer_properties->pre_instance_functions.enumerate_instance_version);
269
66.8k
    free_string_list(inst, &layer_properties->override_paths);
270
66.8k
    free_string_list(inst, &layer_properties->blacklist_layer_names);
271
66.8k
    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
66.8k
    memset(layer_properties, 0, sizeof(struct loader_layer_properties));
275
66.8k
}
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
66.4k
VkResult loader_copy_to_new_str(const struct loader_instance *inst, const char *source_str, char **dest_str) {
288
66.4k
    assert(source_str && dest_str);
289
66.4k
    size_t str_len = strlen(source_str) + 1;
290
66.4k
    *dest_str = loader_instance_heap_calloc(inst, str_len, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
291
66.4k
    if (NULL == *dest_str) return VK_ERROR_OUT_OF_HOST_MEMORY;
292
66.4k
    loader_strncpy(*dest_str, str_len, source_str, str_len);
293
66.4k
    (*dest_str)[str_len - 1] = 0;
294
66.4k
    return VK_SUCCESS;
295
66.4k
}
296
297
6.49k
VkResult create_string_list(const struct loader_instance *inst, uint32_t allocated_count, struct loader_string_list *string_list) {
298
6.49k
    assert(string_list);
299
6.49k
    string_list->list = loader_instance_heap_calloc(inst, sizeof(char *) * allocated_count, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
300
6.49k
    if (NULL == string_list->list) {
301
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
302
0
    }
303
6.49k
    string_list->allocated_count = allocated_count;
304
6.49k
    string_list->count = 0;
305
6.49k
    return VK_SUCCESS;
306
6.49k
}
307
308
595k
VkResult increase_str_capacity_by_at_least_one(const struct loader_instance *inst, struct loader_string_list *string_list) {
309
595k
    assert(string_list);
310
595k
    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
595k
    } 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
595k
    return VK_SUCCESS;
328
595k
}
329
330
595k
VkResult append_str_to_string_list(const struct loader_instance *inst, struct loader_string_list *string_list, char *str) {
331
595k
    assert(string_list && str);
332
595k
    VkResult res = increase_str_capacity_by_at_least_one(inst, string_list);
333
595k
    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
595k
    string_list->list[string_list->count++] = str;
338
595k
    return VK_SUCCESS;
339
595k
}
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
291k
void free_string_list(const struct loader_instance *inst, struct loader_string_list *string_list) {
380
291k
    assert(string_list);
381
291k
    if (string_list->list) {
382
602k
        for (uint32_t i = 0; i < string_list->count; i++) {
383
595k
            loader_instance_heap_free(inst, string_list->list[i]);
384
595k
            string_list->list[i] = NULL;
385
595k
        }
386
6.49k
        loader_instance_heap_free(inst, string_list->list);
387
6.49k
    }
388
291k
    memset(string_list, 0, sizeof(struct loader_string_list));
389
291k
}
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
1.28k
uint32_t loader_parse_version_string(char *vers_str) {
666
1.28k
    uint32_t variant = 0, major = 0, minor = 0, patch = 0;
667
1.28k
    char *vers_tok;
668
1.28k
    char *context = NULL;
669
1.28k
    if (!vers_str) {
670
0
        return 0;
671
0
    }
672
673
1.28k
    vers_tok = thread_safe_strtok(vers_str, ".\"\n\r", &context);
674
1.28k
    if (NULL != vers_tok) {
675
824
        major = (uint16_t)atoi(vers_tok);
676
824
        vers_tok = thread_safe_strtok(NULL, ".\"\n\r", &context);
677
824
        if (NULL != vers_tok) {
678
603
            minor = (uint16_t)atoi(vers_tok);
679
603
            vers_tok = thread_safe_strtok(NULL, ".\"\n\r", &context);
680
603
            if (NULL != vers_tok) {
681
405
                patch = (uint16_t)atoi(vers_tok);
682
405
                vers_tok = thread_safe_strtok(NULL, ".\"\n\r", &context);
683
                // check that we are using a 4 part version string
684
405
                if (NULL != vers_tok) {
685
                    // if we are, move the values over into the correct place
686
9
                    variant = major;
687
9
                    major = minor;
688
9
                    minor = patch;
689
9
                    patch = (uint16_t)atoi(vers_tok);
690
9
                }
691
405
            }
692
603
        }
693
824
    }
694
695
1.28k
    return VK_MAKE_API_VERSION(variant, major, minor, patch);
696
1.28k
}
697
698
12.9k
bool compare_vk_extension_properties(const VkExtensionProperties *op1, const VkExtensionProperties *op2) {
699
12.9k
    return strcmp(op1->extensionName, op2->extensionName) == 0 ? true : false;
700
12.9k
}
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
393
bool has_vk_extension_property(const VkExtensionProperties *vk_ext_prop, const struct loader_extension_list *ext_list) {
713
13.3k
    for (uint32_t i = 0; i < ext_list->count; i++) {
714
12.9k
        if (compare_vk_extension_properties(&ext_list->list[i], vk_ext_prop)) return true;
715
12.9k
    }
716
367
    return false;
717
393
}
718
719
// Search the given ext_list for a device extension matching the given ext_prop
720
33
bool has_vk_dev_ext_property(const VkExtensionProperties *ext_prop, const struct loader_device_extension_list *ext_list) {
721
40
    for (uint32_t i = 0; i < ext_list->count; i++) {
722
12
        if (compare_vk_extension_properties(&ext_list->list[i].props, ext_prop)) return true;
723
12
    }
724
28
    return false;
725
33
}
726
727
VkResult loader_append_layer_property(const struct loader_instance *inst, struct loader_layer_list *layer_list,
728
47.2k
                                      struct loader_layer_properties *layer_property) {
729
47.2k
    VkResult res = VK_SUCCESS;
730
47.2k
    if (layer_list->capacity == 0) {
731
150
        res = loader_init_generic_list(inst, (struct loader_generic_list *)layer_list, sizeof(struct loader_layer_properties));
732
150
        if (VK_SUCCESS != res) {
733
0
            goto out;
734
0
        }
735
150
    }
736
737
    // Ensure enough room to add an entry
738
47.2k
    if ((layer_list->count + 1) * sizeof(struct loader_layer_properties) > layer_list->capacity) {
739
155
        void *new_ptr = loader_instance_heap_realloc(inst, layer_list->list, layer_list->capacity, layer_list->capacity * 2,
740
155
                                                     VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
741
155
        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
155
        layer_list->list = new_ptr;
747
155
        layer_list->capacity *= 2;
748
155
    }
749
47.2k
    memcpy(&layer_list->list[layer_list->count], layer_property, sizeof(struct loader_layer_properties));
750
47.2k
    layer_list->count++;
751
47.2k
    memset(layer_property, 0, sizeof(struct loader_layer_properties));
752
47.2k
out:
753
47.2k
    if (res != VK_SUCCESS) {
754
0
        loader_free_layer_properties(inst, layer_property);
755
0
    }
756
47.2k
    return res;
757
47.2k
}
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
3.12k
                                                                  struct loader_layer_list *layer_list) {
817
3.12k
    uint32_t i;
818
3.12k
    if (!layer_list) return;
819
820
50.0k
    for (i = 0; i < layer_list->count; i++) {
821
46.9k
        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
46.9k
        loader_free_layer_properties(inst, &(layer_list->list[i]));
828
46.9k
    }
829
3.12k
    layer_list->count = 0;
830
831
3.12k
    if (layer_list->capacity > 0) {
832
150
        layer_list->capacity = 0;
833
150
        loader_instance_heap_free(inst, layer_list->list);
834
150
    }
835
3.12k
    memset(layer_list, 0, sizeof(struct loader_layer_list));
836
3.12k
}
837
838
void loader_remove_layer_in_list(const struct loader_instance *inst, struct loader_layer_list *layer_list,
839
366
                                 uint32_t layer_to_remove) {
840
366
    if (layer_list == NULL || layer_to_remove >= layer_list->count) {
841
52
        return;
842
52
    }
843
314
    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
314
    if (layer_to_remove + 1 <= layer_list->count) {
848
314
        memmove(&layer_list->list[layer_to_remove], &layer_list->list[layer_to_remove + 1],
849
314
                sizeof(struct loader_layer_properties) * (layer_list->count - 1 - layer_to_remove));
850
314
    }
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
314
    layer_list->count--;
854
314
}
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
186
VkResult loader_init_generic_list(const struct loader_instance *inst, struct loader_generic_list *list_info, size_t element_size) {
1036
186
    size_t capacity = 32 * element_size;
1037
186
    list_info->count = 0;
1038
186
    list_info->capacity = 0;
1039
186
    list_info->list = loader_instance_heap_calloc(inst, capacity, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1040
186
    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
186
    list_info->capacity = capacity;
1045
186
    return VK_SUCCESS;
1046
186
}
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
133k
void loader_destroy_generic_list(const struct loader_instance *inst, struct loader_generic_list *list) {
1061
133k
    loader_instance_heap_free(inst, list->list);
1062
133k
    memset(list, 0, sizeof(struct loader_generic_list));
1063
133k
}
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
393
                                uint32_t prop_list_count, const VkExtensionProperties *props) {
1117
393
    if (ext_list->list == NULL || ext_list->capacity == 0) {
1118
12
        VkResult res = loader_init_generic_list(inst, (struct loader_generic_list *)ext_list, sizeof(VkExtensionProperties));
1119
12
        if (VK_SUCCESS != res) {
1120
0
            return res;
1121
0
        }
1122
12
    }
1123
1124
786
    for (uint32_t i = 0; i < prop_list_count; i++) {
1125
393
        const VkExtensionProperties *cur_ext = &props[i];
1126
1127
        // look for duplicates
1128
393
        if (has_vk_extension_property(cur_ext, ext_list)) {
1129
26
            continue;
1130
26
        }
1131
1132
        // add to list at end
1133
        // check for enough capacity
1134
367
        if (ext_list->count * sizeof(VkExtensionProperties) >= ext_list->capacity) {
1135
10
            void *new_ptr = loader_instance_heap_realloc(inst, ext_list->list, ext_list->capacity, ext_list->capacity * 2,
1136
10
                                                         VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1137
10
            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
10
            ext_list->list = new_ptr;
1143
1144
            // double capacity
1145
10
            ext_list->capacity *= 2;
1146
10
        }
1147
1148
367
        memcpy(&ext_list->list[ext_list->count], cur_ext, sizeof(VkExtensionProperties));
1149
367
        ext_list->count++;
1150
367
    }
1151
393
    return VK_SUCCESS;
1152
393
}
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
33
                                    const VkExtensionProperties *props, struct loader_string_list *entrys) {
1160
33
    VkResult res = VK_SUCCESS;
1161
33
    bool should_free_entrys = true;
1162
33
    if (ext_list->list == NULL || ext_list->capacity == 0) {
1163
24
        res = loader_init_generic_list(inst, (struct loader_generic_list *)ext_list, sizeof(struct loader_dev_ext_props));
1164
24
        if (VK_SUCCESS != res) {
1165
0
            goto out;
1166
0
        }
1167
24
    }
1168
1169
    // look for duplicates
1170
33
    if (has_vk_dev_ext_property(props, ext_list)) {
1171
5
        goto out;
1172
5
    }
1173
1174
28
    uint32_t idx = ext_list->count;
1175
    // add to list at end
1176
    // check for enough capacity
1177
28
    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
28
    memcpy(&ext_list->list[idx].props, props, sizeof(*props));
1194
28
    if (entrys) {
1195
0
        ext_list->list[idx].entrypoints = *entrys;
1196
0
        should_free_entrys = false;
1197
0
    }
1198
28
    ext_list->count++;
1199
33
out:
1200
33
    if (NULL != entrys && should_free_entrys) {
1201
0
        free_string_list(inst, entrys);
1202
0
    }
1203
33
    return res;
1204
28
}
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
234
                                                     const char *manifest_file_path, char **out_fullpath) {
2406
234
    assert(library_path && manifest_file_path && out_fullpath);
2407
234
    if (loader_platform_is_path_absolute(library_path)) {
2408
29
        *out_fullpath = library_path;
2409
29
        return VK_SUCCESS;
2410
29
    }
2411
205
    VkResult res = VK_SUCCESS;
2412
2413
205
    size_t library_path_len = strlen(library_path);
2414
205
    size_t manifest_file_path_str_len = strlen(manifest_file_path);
2415
205
    bool library_path_contains_directory_symbol = false;
2416
10.4M
    for (size_t i = 0; i < library_path_len; i++) {
2417
10.4M
        if (library_path[i] == DIRECTORY_SYMBOL) {
2418
173
            library_path_contains_directory_symbol = true;
2419
173
            break;
2420
173
        }
2421
10.4M
    }
2422
    // Means that the library_path is neither absolute nor relative - thus we should not modify it at all
2423
205
    if (!library_path_contains_directory_symbol) {
2424
32
        *out_fullpath = library_path;
2425
32
        return VK_SUCCESS;
2426
32
    }
2427
    // must include both a directory symbol and the null terminator
2428
173
    size_t new_str_len = library_path_len + manifest_file_path_str_len + 1 + 1;
2429
2430
173
    *out_fullpath = loader_instance_heap_calloc(inst, new_str_len, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
2431
173
    if (NULL == *out_fullpath) {
2432
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
2433
0
        goto out;
2434
0
    }
2435
173
    size_t cur_loc_in_out_fullpath = 0;
2436
    // look for the last occurrence of DIRECTORY_SYMBOL in manifest_file_path
2437
173
    size_t last_directory_symbol = 0;
2438
173
    bool found_directory_symbol = false;
2439
2.86k
    for (size_t i = 0; i < manifest_file_path_str_len; i++) {
2440
2.69k
        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
2.69k
    }
2446
    // Add manifest_file_path up to the last directory symbol
2447
173
    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
173
    loader_strncpy(&(*out_fullpath)[cur_loc_in_out_fullpath], new_str_len - cur_loc_in_out_fullpath, library_path,
2452
173
                   library_path_len);
2453
173
    cur_loc_in_out_fullpath += library_path_len + 1;
2454
173
    (*out_fullpath)[cur_loc_in_out_fullpath] = '\0';
2455
2456
173
out:
2457
173
    loader_instance_heap_free(inst, library_path);
2458
2459
173
    return res;
2460
173
}
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
25.3k
                                cJSON *layer_node, loader_api_version version, bool is_implicit, char *filename) {
2744
25.3k
    assert(layer_instance_list);
2745
25.3k
    char *library_path = NULL;
2746
25.3k
    VkResult result = VK_SUCCESS;
2747
25.3k
    struct loader_layer_properties props = {0};
2748
2749
25.3k
    result = loader_copy_to_new_str(inst, filename, &props.manifest_file_name);
2750
25.3k
    if (result == VK_ERROR_OUT_OF_HOST_MEMORY) {
2751
0
        goto out;
2752
0
    }
2753
2754
    // Parse name
2755
2756
25.3k
    result = loader_parse_json_string_to_existing_str(layer_node, "name", VK_MAX_EXTENSION_NAME_SIZE, props.info.layerName);
2757
25.3k
    if (VK_ERROR_INITIALIZATION_FAILED == result) {
2758
3.30k
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2759
3.30k
                   "Layer located at %s didn't find required layer value \"name\" in manifest JSON file, skipping this layer",
2760
3.30k
                   filename);
2761
3.30k
        goto out;
2762
3.30k
    }
2763
2764
    // Check if this layer's name matches the override layer name, set is_override to true if so.
2765
22.0k
    if (!strcmp(props.info.layerName, VK_OVERRIDE_LAYER_NAME)) {
2766
9.17k
        props.is_override = true;
2767
9.17k
    }
2768
2769
22.0k
    if (0 != strncmp(props.info.layerName, "VK_LAYER_", 9)) {
2770
7.03k
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0, "Layer name %s does not conform to naming standard (Policy #LLP_LAYER_3)",
2771
7.03k
                   props.info.layerName);
2772
7.03k
    }
2773
2774
    // Parse type
2775
22.0k
    char *type = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(layer_node, "type"));
2776
22.0k
    if (NULL == type) {
2777
15.1k
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2778
15.1k
                   "Layer located at %s didn't find required layer value \"type\" in manifest JSON file, skipping this layer",
2779
15.1k
                   filename);
2780
15.1k
        result = VK_ERROR_INITIALIZATION_FAILED;
2781
15.1k
        goto out;
2782
15.1k
    }
2783
2784
    // Add list entry
2785
6.87k
    if (!strcmp(type, "DEVICE")) {
2786
2
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Device layers are deprecated. Skipping layer %s",
2787
2
                   props.info.layerName);
2788
2
        result = VK_ERROR_INITIALIZATION_FAILED;
2789
2
        goto out;
2790
2
    }
2791
2792
    // Allow either GLOBAL or INSTANCE type interchangeably to handle layers that must work with older loaders
2793
6.87k
    if (!strcmp(type, "INSTANCE") || !strcmp(type, "GLOBAL")) {
2794
5.93k
        props.type_flags = VK_LAYER_TYPE_FLAG_INSTANCE_LAYER;
2795
5.93k
        if (!is_implicit) {
2796
5.78k
            props.type_flags |= VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER;
2797
5.78k
        }
2798
5.93k
    } else {
2799
939
        result = VK_ERROR_INITIALIZATION_FAILED;
2800
939
        goto out;
2801
939
    }
2802
2803
    // Parse api_version
2804
5.93k
    char *api_version = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(layer_node, "api_version"));
2805
5.93k
    if (NULL == api_version) {
2806
4.98k
        loader_log(
2807
4.98k
            inst, VULKAN_LOADER_WARN_BIT, 0,
2808
4.98k
            "Layer located at %s didn't find required layer value \"api_version\" in manifest JSON file, skipping this layer",
2809
4.98k
            filename);
2810
4.98k
        goto out;
2811
4.98k
    }
2812
2813
948
    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
948
    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
948
    char *implementation_version = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(layer_node, "implementation_version"));
2827
948
    if (NULL == implementation_version) {
2828
129
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2829
129
                   "Layer located at %s didn't find required layer value \"implementation_version\" in manifest JSON file, "
2830
129
                   "skipping this layer",
2831
129
                   filename);
2832
129
        goto out;
2833
129
    }
2834
819
    props.info.implementationVersion = atoi(implementation_version);
2835
2836
    // Parse description
2837
2838
819
    result =
2839
819
        loader_parse_json_string_to_existing_str(layer_node, "description", VK_MAX_EXTENSION_NAME_SIZE, props.info.description);
2840
819
    if (VK_ERROR_INITIALIZATION_FAILED == result) {
2841
104
        loader_log(
2842
104
            inst, VULKAN_LOADER_WARN_BIT, 0,
2843
104
            "Layer located at %s didn't find required layer value \"description\" in manifest JSON file, skipping this layer",
2844
104
            filename);
2845
104
        goto out;
2846
104
    }
2847
2848
    // Parse library_path
2849
2850
    // Library path no longer required unless component_layers is also not defined
2851
715
    result = loader_parse_json_string(layer_node, "library_path", &library_path);
2852
715
    if (result == VK_ERROR_OUT_OF_HOST_MEMORY) {
2853
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2854
0
                   "Skipping layer \"%s\" due to problem accessing the library_path value in the manifest JSON file",
2855
0
                   props.info.layerName);
2856
0
        result = VK_ERROR_OUT_OF_HOST_MEMORY;
2857
0
        goto out;
2858
0
    }
2859
715
    if (NULL != library_path) {
2860
234
        if (NULL != loader_cJSON_GetObjectItem(layer_node, "component_layers")) {
2861
0
            loader_log(
2862
0
                inst, VULKAN_LOADER_WARN_BIT, 0,
2863
0
                "Layer \"%s\" contains meta-layer-specific component_layers, but also defining layer library path.  Both are not "
2864
0
                "compatible, so skipping this layer",
2865
0
                props.info.layerName);
2866
0
            result = VK_ERROR_INITIALIZATION_FAILED;
2867
0
            loader_instance_heap_free(inst, library_path);
2868
0
            goto out;
2869
0
        }
2870
2871
        // This function takes ownership of library_path_str - so we don't need to clean it up
2872
234
        result = combine_manifest_directory_and_library_path(inst, library_path, filename, &props.lib_name);
2873
234
        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
2874
234
    }
2875
2876
    // Parse component_layers
2877
2878
715
    if (NULL == library_path) {
2879
481
        if (!loader_check_version_meets_required(LOADER_VERSION_1_1_0, version)) {
2880
230
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2881
230
                       "Layer \"%s\" contains meta-layer-specific component_layers, but using older JSON file version.",
2882
230
                       props.info.layerName);
2883
230
        }
2884
2885
481
        result = loader_parse_json_array_of_strings(inst, layer_node, "component_layers", &(props.component_layer_names));
2886
481
        if (VK_ERROR_OUT_OF_HOST_MEMORY == result) {
2887
0
            goto out;
2888
0
        }
2889
481
        if (VK_ERROR_INITIALIZATION_FAILED == result) {
2890
104
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2891
104
                       "Layer \"%s\" is missing both library_path and component_layers fields.  One or the other MUST be defined.  "
2892
104
                       "Skipping this layer",
2893
104
                       props.info.layerName);
2894
104
            goto out;
2895
104
        }
2896
        // This is now, officially, a meta-layer
2897
377
        props.type_flags |= VK_LAYER_TYPE_FLAG_META_LAYER;
2898
377
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Encountered meta-layer \"%s\"",
2899
377
                   props.info.layerName);
2900
377
    }
2901
2902
    // Parse blacklisted_layers
2903
2904
611
    if (props.is_override) {
2905
0
        result = loader_parse_json_array_of_strings(inst, layer_node, "blacklisted_layers", &(props.blacklist_layer_names));
2906
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == result) {
2907
0
            goto out;
2908
0
        }
2909
0
    }
2910
2911
    // Parse override_paths
2912
2913
611
    result = loader_parse_json_array_of_strings(inst, layer_node, "override_paths", &(props.override_paths));
2914
611
    if (VK_ERROR_OUT_OF_HOST_MEMORY == result) {
2915
0
        goto out;
2916
0
    }
2917
611
    if (NULL != props.override_paths.list && !loader_check_version_meets_required(loader_combine_version(1, 1, 0), version)) {
2918
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2919
0
                   "Layer \"%s\" contains meta-layer-specific override paths, but using older JSON file version.",
2920
0
                   props.info.layerName);
2921
0
    }
2922
2923
    // Parse disable_environment
2924
2925
611
    if (is_implicit) {
2926
141
        cJSON *disable_environment = loader_cJSON_GetObjectItem(layer_node, "disable_environment");
2927
141
        if (disable_environment == NULL) {
2928
7
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2929
7
                       "Layer \"%s\" doesn't contain required layer object disable_environment in the manifest JSON file, skipping "
2930
7
                       "this layer",
2931
7
                       props.info.layerName);
2932
7
            result = VK_ERROR_INITIALIZATION_FAILED;
2933
7
            goto out;
2934
7
        }
2935
2936
134
        if (!disable_environment->child || disable_environment->child->type != cJSON_String ||
2937
134
            !disable_environment->child->string || !disable_environment->child->valuestring) {
2938
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
2939
0
                       "Layer \"%s\" doesn't contain required child value in object disable_environment in the manifest JSON file, "
2940
0
                       "skipping this layer (Policy #LLP_LAYER_9)",
2941
0
                       props.info.layerName);
2942
0
            result = VK_ERROR_INITIALIZATION_FAILED;
2943
0
            goto out;
2944
0
        }
2945
134
        result = loader_copy_to_new_str(inst, disable_environment->child->string, &(props.disable_env_var.name));
2946
134
        if (VK_SUCCESS != result) goto out;
2947
134
        result = loader_copy_to_new_str(inst, disable_environment->child->valuestring, &(props.disable_env_var.value));
2948
134
        if (VK_SUCCESS != result) goto out;
2949
134
    }
2950
2951
    // Now get all optional items and objects and put in list:
2952
    // functions
2953
    // instance_extensions
2954
    // device_extensions
2955
    // enable_environment (implicit layers only)
2956
    // library_arch
2957
2958
    // Layer interface functions
2959
    //    vkGetInstanceProcAddr
2960
    //    vkGetDeviceProcAddr
2961
    //    vkNegotiateLoaderLayerInterfaceVersion (starting with JSON file 1.1.0)
2962
604
    cJSON *functions = loader_cJSON_GetObjectItem(layer_node, "functions");
2963
604
    if (functions != NULL) {
2964
0
        if (loader_check_version_meets_required(loader_combine_version(1, 1, 0), version)) {
2965
0
            result = loader_parse_json_string(functions, "vkNegotiateLoaderLayerInterfaceVersion",
2966
0
                                              &props.functions.str_negotiate_interface);
2967
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
2968
0
        }
2969
0
        result = loader_parse_json_string(functions, "vkGetInstanceProcAddr", &props.functions.str_gipa);
2970
0
        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
2971
2972
0
        if (NULL == props.functions.str_negotiate_interface && props.functions.str_gipa &&
2973
0
            loader_check_version_meets_required(loader_combine_version(1, 1, 0), version)) {
2974
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
2975
0
                       "Layer \"%s\" using deprecated \'vkGetInstanceProcAddr\' tag which was deprecated starting with JSON "
2976
0
                       "file version 1.1.0. The new vkNegotiateLoaderLayerInterfaceVersion function is preferred, though for "
2977
0
                       "compatibility reasons it may be desirable to continue using the deprecated tag.",
2978
0
                       props.info.layerName);
2979
0
        }
2980
2981
0
        result = loader_parse_json_string(functions, "vkGetDeviceProcAddr", &props.functions.str_gdpa);
2982
0
        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
2983
2984
0
        if (NULL == props.functions.str_negotiate_interface && props.functions.str_gdpa &&
2985
0
            loader_check_version_meets_required(loader_combine_version(1, 1, 0), version)) {
2986
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
2987
0
                       "Layer \"%s\" using deprecated \'vkGetDeviceProcAddr\' tag which was deprecated starting with JSON "
2988
0
                       "file version 1.1.0. The new vkNegotiateLoaderLayerInterfaceVersion function is preferred, though for "
2989
0
                       "compatibility reasons it may be desirable to continue using the deprecated tag.",
2990
0
                       props.info.layerName);
2991
0
        }
2992
0
    }
2993
2994
    // instance_extensions
2995
    //   array of {
2996
    //     name
2997
    //     spec_version
2998
    //   }
2999
3000
604
    cJSON *instance_extensions = loader_cJSON_GetObjectItem(layer_node, "instance_extensions");
3001
604
    if (instance_extensions != NULL && instance_extensions->type == cJSON_Array) {
3002
26
        cJSON *ext_item = NULL;
3003
473
        cJSON_ArrayForEach(ext_item, instance_extensions) {
3004
473
            if (ext_item->type != cJSON_Object) {
3005
48
                continue;
3006
48
            }
3007
3008
425
            VkExtensionProperties ext_prop = {0};
3009
425
            result = loader_parse_json_string_to_existing_str(ext_item, "name", VK_MAX_EXTENSION_NAME_SIZE, ext_prop.extensionName);
3010
425
            if (result == VK_ERROR_INITIALIZATION_FAILED) {
3011
22
                continue;
3012
22
            }
3013
403
            char *spec_version = NULL;
3014
403
            result = loader_parse_json_string(ext_item, "spec_version", &spec_version);
3015
403
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3016
403
            if (NULL != spec_version) {
3017
0
                ext_prop.specVersion = atoi(spec_version);
3018
0
            }
3019
403
            loader_instance_heap_free(inst, spec_version);
3020
403
            bool ext_unsupported = wsi_unsupported_instance_extension(&ext_prop);
3021
403
            if (!ext_unsupported) {
3022
393
                loader_add_to_ext_list(inst, &props.instance_extension_list, 1, &ext_prop);
3023
393
            }
3024
403
        }
3025
26
    }
3026
3027
    // device_extensions
3028
    //   array of {
3029
    //     name
3030
    //     spec_version
3031
    //     entrypoints
3032
    //   }
3033
604
    cJSON *device_extensions = loader_cJSON_GetObjectItem(layer_node, "device_extensions");
3034
604
    if (device_extensions != NULL && device_extensions->type == cJSON_Array) {
3035
58
        cJSON *ext_item = NULL;
3036
193
        cJSON_ArrayForEach(ext_item, device_extensions) {
3037
193
            if (ext_item->type != cJSON_Object) {
3038
152
                continue;
3039
152
            }
3040
3041
41
            VkExtensionProperties ext_prop = {0};
3042
41
            result = loader_parse_json_string_to_existing_str(ext_item, "name", VK_MAX_EXTENSION_NAME_SIZE, ext_prop.extensionName);
3043
41
            if (result == VK_ERROR_INITIALIZATION_FAILED) {
3044
8
                continue;
3045
8
            }
3046
3047
33
            char *spec_version = NULL;
3048
33
            result = loader_parse_json_string(ext_item, "spec_version", &spec_version);
3049
33
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3050
33
            if (NULL != spec_version) {
3051
8
                ext_prop.specVersion = atoi(spec_version);
3052
8
            }
3053
33
            loader_instance_heap_free(inst, spec_version);
3054
3055
33
            cJSON *entrypoints = loader_cJSON_GetObjectItem(ext_item, "entrypoints");
3056
33
            if (entrypoints == NULL) {
3057
33
                result = loader_add_to_dev_ext_list(inst, &props.device_extension_list, &ext_prop, NULL);
3058
33
                if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3059
33
                continue;
3060
33
            }
3061
3062
0
            struct loader_string_list entrys = {0};
3063
0
            result = loader_parse_json_array_of_strings(inst, ext_item, "entrypoints", &entrys);
3064
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3065
0
            result = loader_add_to_dev_ext_list(inst, &props.device_extension_list, &ext_prop, &entrys);
3066
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3067
0
        }
3068
58
    }
3069
604
    if (is_implicit) {
3070
134
        cJSON *enable_environment = loader_cJSON_GetObjectItem(layer_node, "enable_environment");
3071
3072
        // enable_environment is optional
3073
134
        if (enable_environment && enable_environment->child && enable_environment->child->type == cJSON_String &&
3074
2
            enable_environment->child->string && enable_environment->child->valuestring) {
3075
2
            result = loader_copy_to_new_str(inst, enable_environment->child->string, &(props.enable_env_var.name));
3076
2
            if (VK_SUCCESS != result) goto out;
3077
2
            result = loader_copy_to_new_str(inst, enable_environment->child->valuestring, &(props.enable_env_var.value));
3078
2
            if (VK_SUCCESS != result) goto out;
3079
2
        }
3080
134
    }
3081
3082
    // Read in the pre-instance stuff
3083
604
    cJSON *pre_instance = loader_cJSON_GetObjectItem(layer_node, "pre_instance_functions");
3084
604
    if (NULL != pre_instance) {
3085
        // Supported versions started in 1.1.2, so anything newer
3086
0
        if (!loader_check_version_meets_required(loader_combine_version(1, 1, 2), version)) {
3087
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
3088
0
                       "Found pre_instance_functions section in layer from \"%s\". This section is only valid in manifest version "
3089
0
                       "1.1.2 or later. The section will be ignored",
3090
0
                       filename);
3091
0
        } else if (!is_implicit) {
3092
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
3093
0
                       "Found pre_instance_functions section in explicit layer from \"%s\". This section is only valid in implicit "
3094
0
                       "layers. The section will be ignored",
3095
0
                       filename);
3096
0
        } else {
3097
0
            result = loader_parse_json_string(pre_instance, "vkEnumerateInstanceExtensionProperties",
3098
0
                                              &props.pre_instance_functions.enumerate_instance_extension_properties);
3099
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3100
3101
0
            result = loader_parse_json_string(pre_instance, "vkEnumerateInstanceLayerProperties",
3102
0
                                              &props.pre_instance_functions.enumerate_instance_layer_properties);
3103
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3104
3105
0
            result = loader_parse_json_string(pre_instance, "vkEnumerateInstanceVersion",
3106
0
                                              &props.pre_instance_functions.enumerate_instance_version);
3107
0
            if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3108
0
        }
3109
0
    }
3110
3111
604
    if (loader_cJSON_GetObjectItem(layer_node, "app_keys")) {
3112
46
        if (!props.is_override) {
3113
46
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3114
46
                       "Layer %s contains app_keys, but any app_keys can only be provided by the override meta layer. "
3115
46
                       "These will be ignored.",
3116
46
                       props.info.layerName);
3117
46
        }
3118
3119
46
        result = loader_parse_json_array_of_strings(inst, layer_node, "app_keys", &props.app_key_paths);
3120
46
        if (result == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
3121
46
    }
3122
3123
604
    char *library_arch = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(layer_node, "library_arch"));
3124
604
    if (NULL != library_arch) {
3125
0
        if ((strncmp(library_arch, "32", 2) == 0 && sizeof(void *) != 4) ||
3126
0
            (strncmp(library_arch, "64", 2) == 0 && sizeof(void *) != 8)) {
3127
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
3128
0
                       "The library architecture in layer %s doesn't match the current running architecture, skipping this layer",
3129
0
                       filename);
3130
0
            result = VK_ERROR_INITIALIZATION_FAILED;
3131
0
            goto out;
3132
0
        }
3133
0
    }
3134
3135
604
    result = VK_SUCCESS;
3136
3137
25.3k
out:
3138
    // Try to append the layer property
3139
25.3k
    if (VK_SUCCESS == result) {
3140
5.71k
        result = loader_append_layer_property(inst, layer_instance_list, &props);
3141
5.71k
    }
3142
    // If appending fails - free all the memory allocated in it
3143
25.3k
    if (VK_SUCCESS != result) {
3144
19.6k
        loader_free_layer_properties(inst, &props);
3145
19.6k
    }
3146
25.3k
    return result;
3147
604
}
3148
3149
333
bool is_valid_layer_json_version(const loader_api_version *layer_json) {
3150
    // Supported versions are: 1.0.0, 1.0.1, 1.1.0 - 1.1.2, and 1.2.0 - 1.2.1.
3151
333
    if ((layer_json->major == 1 && layer_json->minor == 2 && layer_json->patch < 2) ||
3152
333
        (layer_json->major == 1 && layer_json->minor == 1 && layer_json->patch < 3) ||
3153
328
        (layer_json->major == 1 && layer_json->minor == 0 && layer_json->patch < 2)) {
3154
59
        return true;
3155
59
    }
3156
274
    return false;
3157
333
}
3158
3159
// Given a cJSON struct (json) of the top level JSON object from layer manifest
3160
// file, add entry to the layer_list. Fill out the layer_properties in this list
3161
// entry from the input cJSON object.
3162
//
3163
// \returns
3164
// void
3165
// layer_list has a new entry and initialized accordingly.
3166
// If the json input object does not have all the required fields no entry
3167
// is added to the list.
3168
VkResult loader_add_layer_properties(const struct loader_instance *inst, struct loader_layer_list *layer_instance_list, cJSON *json,
3169
463
                                     bool is_implicit, char *filename) {
3170
    // The following Fields in layer manifest file that are required:
3171
    //   - "file_format_version"
3172
    //   - If more than one "layer" object are used, then the "layers" array is
3173
    //     required
3174
463
    VkResult result = VK_ERROR_INITIALIZATION_FAILED;
3175
    // Make sure sure the top level json value is an object
3176
463
    if (!json || json->type != cJSON_Object) {
3177
130
        goto out;
3178
130
    }
3179
333
    char *file_vers = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(json, "file_format_version"));
3180
333
    if (NULL == file_vers) {
3181
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3182
0
                   "loader_add_layer_properties: Manifest %s missing required field file_format_version", filename);
3183
0
        goto out;
3184
0
    }
3185
3186
333
    loader_log(inst, VULKAN_LOADER_INFO_BIT, 0, "Found manifest file %s (file version %s)", filename, file_vers);
3187
    // Get the major/minor/and patch as integers for easier comparison
3188
333
    loader_api_version json_version = loader_make_full_version(loader_parse_version_string(file_vers));
3189
3190
333
    if (!is_valid_layer_json_version(&json_version)) {
3191
274
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3192
274
                   "loader_add_layer_properties: %s has unknown layer manifest file version %d.%d.%d.  May cause errors.", filename,
3193
274
                   json_version.major, json_version.minor, json_version.patch);
3194
274
    }
3195
3196
    // If "layers" is present, read in the array of layer objects
3197
333
    cJSON *layers_node = loader_cJSON_GetObjectItem(json, "layers");
3198
333
    if (layers_node != NULL) {
3199
        // Supported versions started in 1.0.1, so anything newer
3200
286
        if (!loader_check_version_meets_required(loader_combine_version(1, 0, 1), json_version)) {
3201
98
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3202
98
                       "loader_add_layer_properties: \'layers\' tag not supported until file version 1.0.1, but %s is reporting "
3203
98
                       "version %s",
3204
98
                       filename, file_vers);
3205
98
        }
3206
286
        cJSON *layer_node = NULL;
3207
25.3k
        cJSON_ArrayForEach(layer_node, layers_node) {
3208
25.3k
            if (layer_node->type != cJSON_Object) {
3209
46
                loader_log(
3210
46
                    inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3211
46
                    "loader_add_layer_properties: Array element in \"layers\" field in manifest JSON file %s is not an object.  "
3212
46
                    "Skipping this file",
3213
46
                    filename);
3214
46
                goto out;
3215
46
            }
3216
25.2k
            result = loader_read_layer_json(inst, layer_instance_list, layer_node, json_version, is_implicit, filename);
3217
25.2k
        }
3218
286
    } else {
3219
        // Otherwise, try to read in individual layers
3220
47
        cJSON *layer_node = loader_cJSON_GetObjectItem(json, "layer");
3221
47
        if (layer_node == NULL) {
3222
            // Don't warn if this happens to be an ICD manifest
3223
0
            if (loader_cJSON_GetObjectItem(json, "ICD") == NULL) {
3224
0
                loader_log(
3225
0
                    inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3226
0
                    "loader_add_layer_properties: Can not find 'layer' object in manifest JSON file %s.  Skipping this file.",
3227
0
                    filename);
3228
0
            }
3229
0
            goto out;
3230
0
        }
3231
        // Loop through all "layer" objects in the file to get a count of them
3232
        // first.
3233
47
        uint16_t layer_count = 0;
3234
47
        cJSON *tempNode = layer_node;
3235
55
        do {
3236
55
            tempNode = tempNode->next;
3237
55
            layer_count++;
3238
55
        } while (tempNode != NULL);
3239
3240
        // Throw a warning if we encounter multiple "layer" objects in file
3241
        // versions newer than 1.0.0.  Having multiple objects with the same
3242
        // name at the same level is actually a JSON standard violation.
3243
47
        if (layer_count > 1 && loader_check_version_meets_required(loader_combine_version(1, 0, 1), json_version)) {
3244
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3245
0
                       "loader_add_layer_properties: Multiple 'layer' nodes are deprecated starting in file version \"1.0.1\".  "
3246
0
                       "Please use 'layers' : [] array instead in %s.",
3247
0
                       filename);
3248
47
        } else {
3249
55
            do {
3250
55
                result = loader_read_layer_json(inst, layer_instance_list, layer_node, json_version, is_implicit, filename);
3251
55
                layer_node = layer_node->next;
3252
55
            } while (layer_node != NULL);
3253
47
        }
3254
47
    }
3255
3256
463
out:
3257
3258
463
    return result;
3259
333
}
3260
3261
0
size_t determine_data_file_path_size(const char *cur_path, size_t relative_path_size) {
3262
0
    size_t path_size = 0;
3263
3264
0
    if (NULL != cur_path) {
3265
        // For each folder in cur_path, (detected by finding additional
3266
        // path separators in the string) we need to add the relative path on
3267
        // the end.  Plus, leave an additional two slots on the end to add an
3268
        // additional directory slash and path separator if needed
3269
0
        path_size += strlen(cur_path) + relative_path_size + 2;
3270
0
        for (const char *x = cur_path; *x; ++x) {
3271
0
            if (*x == PATH_SEPARATOR) {
3272
0
                path_size += relative_path_size + 2;
3273
0
            }
3274
0
        }
3275
0
    }
3276
3277
0
    return path_size;
3278
0
}
3279
3280
0
void copy_data_file_info(const char *cur_path, const char *relative_path, size_t relative_path_size, char **output_path) {
3281
0
    if (NULL != cur_path) {
3282
0
        uint32_t start = 0;
3283
0
        uint32_t stop = 0;
3284
0
        char *cur_write = *output_path;
3285
3286
0
        while (cur_path[start] != '\0') {
3287
0
            while (cur_path[start] == PATH_SEPARATOR && cur_path[start] != '\0') {
3288
0
                start++;
3289
0
            }
3290
0
            stop = start;
3291
0
            while (cur_path[stop] != PATH_SEPARATOR && cur_path[stop] != '\0') {
3292
0
                stop++;
3293
0
            }
3294
0
            const size_t s = stop - start;
3295
0
            if (s) {
3296
0
                memcpy(cur_write, &cur_path[start], s);
3297
0
                cur_write += s;
3298
3299
                // If this is a specific JSON file, just add it and don't add any
3300
                // relative path or directory symbol to it.
3301
0
                if (!is_json(cur_write - 5, s)) {
3302
                    // Add the relative directory if present.
3303
0
                    if (relative_path_size > 0) {
3304
                        // If last symbol written was not a directory symbol, add it.
3305
0
                        if (*(cur_write - 1) != DIRECTORY_SYMBOL) {
3306
0
                            *cur_write++ = DIRECTORY_SYMBOL;
3307
0
                        }
3308
0
                        memcpy(cur_write, relative_path, relative_path_size);
3309
0
                        cur_write += relative_path_size;
3310
0
                    }
3311
0
                }
3312
3313
0
                *cur_write++ = PATH_SEPARATOR;
3314
0
                start = stop;
3315
0
            }
3316
0
        }
3317
0
        *output_path = cur_write;
3318
0
    }
3319
0
}
3320
3321
// If the file found is a manifest file name, add it to the end of out_files manifest list.
3322
0
VkResult add_if_manifest_file(const struct loader_instance *inst, const char *file_name, struct loader_string_list *out_files) {
3323
0
    assert(NULL != file_name && "add_if_manifest_file: Received NULL pointer for file_name");
3324
0
    assert(NULL != out_files && "add_if_manifest_file: Received NULL pointer for out_files");
3325
3326
    // Look for files ending with ".json" suffix
3327
0
    size_t name_len = strlen(file_name);
3328
0
    const char *name_suffix = file_name + name_len - 5;
3329
0
    if (!is_json(name_suffix, name_len)) {
3330
        // Use incomplete to indicate invalid name, but to keep going.
3331
0
        return VK_INCOMPLETE;
3332
0
    }
3333
3334
0
    return copy_str_to_string_list(inst, out_files, file_name, name_len);
3335
0
}
3336
3337
// If the file found is a manifest file name, add it to the start of the out_files manifest list.
3338
0
VkResult prepend_if_manifest_file(const struct loader_instance *inst, const char *file_name, struct loader_string_list *out_files) {
3339
0
    assert(NULL != file_name && "prepend_if_manifest_file: Received NULL pointer for file_name");
3340
0
    assert(NULL != out_files && "prepend_if_manifest_file: Received NULL pointer for out_files");
3341
3342
    // Look for files ending with ".json" suffix
3343
0
    size_t name_len = strlen(file_name);
3344
0
    const char *name_suffix = file_name + name_len - 5;
3345
0
    if (!is_json(name_suffix, name_len)) {
3346
        // Use incomplete to indicate invalid name, but to keep going.
3347
0
        return VK_INCOMPLETE;
3348
0
    }
3349
3350
0
    return copy_str_to_start_of_string_list(inst, out_files, file_name, name_len);
3351
0
}
3352
3353
// Add any files found in the search_path.  If any path in the search path points to a specific JSON, attempt to
3354
// only open that one JSON.  Otherwise, if the path is a folder, search the folder for JSON files.
3355
0
VkResult add_data_files(const struct loader_instance *inst, char *search_path, struct loader_string_list *out_files) {
3356
0
    VkResult vk_result = VK_SUCCESS;
3357
0
    char full_path[2048];
3358
0
#if !defined(_WIN32)
3359
0
    char temp_path[2048];
3360
0
#endif
3361
3362
    // Now, parse the paths
3363
0
    char *next_file = search_path;
3364
0
    while (NULL != next_file && *next_file != '\0') {
3365
0
        char *name = NULL;
3366
0
        char *cur_file = next_file;
3367
0
        next_file = loader_get_next_path(cur_file);
3368
3369
        // Is this a JSON file, then try to open it.
3370
0
        size_t len = strlen(cur_file);
3371
0
        if (is_json(cur_file + len - 5, len)) {
3372
#if defined(_WIN32)
3373
            name = cur_file;
3374
#elif COMMON_UNIX_PLATFORMS
3375
            // Only Linux has relative paths, make a copy of location so it isn't modified
3376
0
            size_t str_len;
3377
0
            if (NULL != next_file) {
3378
0
                str_len = next_file - cur_file + 1;
3379
0
            } else {
3380
0
                str_len = strlen(cur_file) + 1;
3381
0
            }
3382
0
            if (str_len > sizeof(temp_path)) {
3383
0
                loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0, "add_data_files: Path to %s too long", cur_file);
3384
0
                continue;
3385
0
            }
3386
0
            strncpy(temp_path, cur_file, str_len);
3387
0
            name = temp_path;
3388
#else
3389
#warning add_data_files must define relative path copy for this platform
3390
#endif
3391
0
            loader_get_fullpath(cur_file, name, sizeof(full_path), full_path);
3392
0
            name = full_path;
3393
3394
0
            VkResult local_res;
3395
0
            local_res = add_if_manifest_file(inst, name, out_files);
3396
3397
            // Incomplete means this was not a valid data file.
3398
0
            if (local_res == VK_INCOMPLETE) {
3399
0
                continue;
3400
0
            } else if (local_res != VK_SUCCESS) {
3401
0
                vk_result = local_res;
3402
0
                break;
3403
0
            }
3404
0
        } else {  // Otherwise, treat it as a directory
3405
0
            DIR *dir_stream = loader_opendir(inst, cur_file);
3406
0
            if (NULL == dir_stream) {
3407
0
                continue;
3408
0
            }
3409
0
            while (1) {
3410
0
                errno = 0;
3411
0
                struct dirent *dir_entry = readdir(dir_stream);
3412
0
#if !defined(WIN32)  // Windows doesn't use readdir, don't check errors on functions which aren't called
3413
0
                if (errno != 0) {
3414
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "readdir failed with %d: %s", errno, strerror(errno));
3415
0
                    break;
3416
0
                }
3417
0
#endif
3418
0
                if (NULL == dir_entry) {
3419
0
                    break;
3420
0
                }
3421
3422
0
                name = &(dir_entry->d_name[0]);
3423
0
                loader_get_fullpath(name, cur_file, sizeof(full_path), full_path);
3424
0
                name = full_path;
3425
3426
0
                VkResult local_res;
3427
0
                local_res = add_if_manifest_file(inst, name, out_files);
3428
3429
                // Incomplete means this was not a valid data file.
3430
0
                if (local_res == VK_INCOMPLETE) {
3431
0
                    continue;
3432
0
                } else if (local_res != VK_SUCCESS) {
3433
0
                    vk_result = local_res;
3434
0
                    break;
3435
0
                }
3436
0
            }
3437
0
            loader_closedir(inst, dir_stream);
3438
0
            if (vk_result != VK_SUCCESS) {
3439
0
                goto out;
3440
0
            }
3441
0
        }
3442
0
    }
3443
3444
0
out:
3445
3446
0
    return vk_result;
3447
0
}
3448
3449
// Look for data files in the provided paths, but first check the environment override to determine if we should use that
3450
// instead.
3451
VkResult read_data_files_in_search_paths(const struct loader_instance *inst, enum loader_data_files_type manifest_type,
3452
0
                                         const char *path_override, bool *override_active, struct loader_string_list *out_files) {
3453
0
    VkResult vk_result = VK_SUCCESS;
3454
0
    char *override_env = NULL;
3455
0
    const char *override_path = NULL;
3456
0
    char *additional_env = NULL;
3457
0
    size_t search_path_size = 0;
3458
0
    char *search_path = NULL;
3459
0
    char *cur_path_ptr = NULL;
3460
0
#if COMMON_UNIX_PLATFORMS
3461
0
    const char *relative_location = NULL;  // Only used on unix platforms
3462
0
    size_t rel_size = 0;                   // unused in windows, dont declare so no compiler warnings are generated
3463
0
#endif
3464
3465
#if defined(_WIN32)
3466
    char *package_path = NULL;
3467
#elif COMMON_UNIX_PLATFORMS
3468
    // Determine how much space is needed to generate the full search path
3469
    // for the current manifest files.
3470
0
    char *xdg_config_home = loader_secure_getenv("XDG_CONFIG_HOME", inst);
3471
0
    char *xdg_config_dirs = loader_secure_getenv("XDG_CONFIG_DIRS", inst);
3472
3473
0
#if !defined(__Fuchsia__) && !defined(__QNX__)
3474
0
    if (NULL == xdg_config_dirs || '\0' == xdg_config_dirs[0]) {
3475
0
        xdg_config_dirs = FALLBACK_CONFIG_DIRS;
3476
0
    }
3477
0
#endif
3478
3479
0
    char *xdg_data_home = loader_secure_getenv("XDG_DATA_HOME", inst);
3480
0
    char *xdg_data_dirs = loader_secure_getenv("XDG_DATA_DIRS", inst);
3481
3482
0
#if !defined(__Fuchsia__) && !defined(__QNX__)
3483
0
    if (NULL == xdg_data_dirs || '\0' == xdg_data_dirs[0]) {
3484
0
        xdg_data_dirs = FALLBACK_DATA_DIRS;
3485
0
    }
3486
0
#endif
3487
3488
0
    char *home = NULL;
3489
0
    char *default_data_home = NULL;
3490
0
    char *default_config_home = NULL;
3491
0
    char *home_data_dir = NULL;
3492
0
    char *home_config_dir = NULL;
3493
3494
    // Only use HOME if XDG_DATA_HOME is not present on the system
3495
0
    home = loader_secure_getenv("HOME", inst);
3496
0
    if (home != NULL) {
3497
0
        if (NULL == xdg_config_home || '\0' == xdg_config_home[0]) {
3498
0
            const char config_suffix[] = "/.config";
3499
0
            size_t default_config_home_len = strlen(home) + sizeof(config_suffix) + 1;
3500
0
            default_config_home = loader_instance_heap_calloc(inst, default_config_home_len, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
3501
0
            if (default_config_home == NULL) {
3502
0
                vk_result = VK_ERROR_OUT_OF_HOST_MEMORY;
3503
0
                goto out;
3504
0
            }
3505
0
            strncpy(default_config_home, home, default_config_home_len);
3506
0
            strncat(default_config_home, config_suffix, default_config_home_len);
3507
0
        }
3508
0
        if (NULL == xdg_data_home || '\0' == xdg_data_home[0]) {
3509
0
            const char data_suffix[] = "/.local/share";
3510
0
            size_t default_data_home_len = strlen(home) + sizeof(data_suffix) + 1;
3511
0
            default_data_home = loader_instance_heap_calloc(inst, default_data_home_len, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
3512
0
            if (default_data_home == NULL) {
3513
0
                vk_result = VK_ERROR_OUT_OF_HOST_MEMORY;
3514
0
                goto out;
3515
0
            }
3516
0
            strncpy(default_data_home, home, default_data_home_len);
3517
0
            strncat(default_data_home, data_suffix, default_data_home_len);
3518
0
        }
3519
0
    }
3520
3521
0
    if (NULL != default_config_home) {
3522
0
        home_config_dir = default_config_home;
3523
0
    } else {
3524
0
        home_config_dir = xdg_config_home;
3525
0
    }
3526
0
    if (NULL != default_data_home) {
3527
0
        home_data_dir = default_data_home;
3528
0
    } else {
3529
0
        home_data_dir = xdg_data_home;
3530
0
    }
3531
#else
3532
#warning read_data_files_in_search_paths unsupported platform
3533
#endif
3534
3535
0
    switch (manifest_type) {
3536
0
        case LOADER_DATA_FILE_MANIFEST_DRIVER:
3537
0
            if (loader_settings_should_use_driver_environment_variables(inst)) {
3538
0
                override_env = loader_secure_getenv(VK_DRIVER_FILES_ENV_VAR, inst);
3539
0
                if (NULL == override_env) {
3540
                    // Not there, so fall back to the old name
3541
0
                    override_env = loader_secure_getenv(VK_ICD_FILENAMES_ENV_VAR, inst);
3542
0
                }
3543
0
                additional_env = loader_secure_getenv(VK_ADDITIONAL_DRIVER_FILES_ENV_VAR, inst);
3544
0
            }
3545
0
#if COMMON_UNIX_PLATFORMS
3546
0
            relative_location = VK_DRIVERS_INFO_RELATIVE_DIR;
3547
0
#endif
3548
#if defined(_WIN32)
3549
            package_path = windows_get_app_package_manifest_path(inst);
3550
#endif
3551
0
            break;
3552
0
        case LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER:
3553
0
            override_env = loader_secure_getenv(VK_IMPLICIT_LAYER_PATH_ENV_VAR, inst);
3554
0
            additional_env = loader_secure_getenv(VK_ADDITIONAL_IMPLICIT_LAYER_PATH_ENV_VAR, inst);
3555
0
#if COMMON_UNIX_PLATFORMS
3556
0
            relative_location = VK_ILAYERS_INFO_RELATIVE_DIR;
3557
0
#endif
3558
#if defined(_WIN32)
3559
            package_path = windows_get_app_package_manifest_path(inst);
3560
#endif
3561
0
            break;
3562
0
        case LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER:
3563
0
            override_env = loader_secure_getenv(VK_EXPLICIT_LAYER_PATH_ENV_VAR, inst);
3564
0
            additional_env = loader_secure_getenv(VK_ADDITIONAL_EXPLICIT_LAYER_PATH_ENV_VAR, inst);
3565
0
#if COMMON_UNIX_PLATFORMS
3566
0
            relative_location = VK_ELAYERS_INFO_RELATIVE_DIR;
3567
0
#endif
3568
0
            break;
3569
0
        default:
3570
0
            assert(false && "Shouldn't get here!");
3571
0
            break;
3572
0
    }
3573
3574
    // Log a message when VK_LAYER_PATH is set but the override layer paths take priority
3575
0
    if (manifest_type == LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER && NULL != override_env && NULL != path_override) {
3576
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0,
3577
0
                   "Ignoring VK_LAYER_PATH. The Override layer is active and has override paths set, which takes priority. "
3578
0
                   "VK_LAYER_PATH is set to %s",
3579
0
                   override_env);
3580
0
    }
3581
3582
0
    if (path_override != NULL) {
3583
0
        override_path = path_override;
3584
0
    } else if (override_env != NULL) {
3585
0
        override_path = override_env;
3586
0
    }
3587
3588
    // Add two by default for NULL terminator and one path separator on end (just in case)
3589
0
    search_path_size = 2;
3590
3591
    // If there's an override, use that (and the local folder if required) and nothing else
3592
0
    if (NULL != override_path) {
3593
        // Local folder and null terminator
3594
0
        search_path_size += strlen(override_path) + 2;
3595
0
    } else {
3596
        // Add the size of any additional search paths defined in the additive environment variable
3597
0
        if (NULL != additional_env) {
3598
0
            search_path_size += determine_data_file_path_size(additional_env, 0) + 2;
3599
#if defined(_WIN32)
3600
        }
3601
        if (NULL != package_path) {
3602
            search_path_size += determine_data_file_path_size(package_path, 0) + 2;
3603
        }
3604
        if (search_path_size == 2) {
3605
            goto out;
3606
        }
3607
#elif COMMON_UNIX_PLATFORMS
3608
        }
3609
3610
        // Add the general search folders (with the appropriate relative folder added)
3611
0
        rel_size = strlen(relative_location);
3612
0
        if (rel_size > 0) {
3613
#if defined(__APPLE__)
3614
            search_path_size += MAXPATHLEN;
3615
#endif
3616
            // Only add the home folders if defined
3617
0
            if (NULL != home_config_dir) {
3618
0
                search_path_size += determine_data_file_path_size(home_config_dir, rel_size);
3619
0
            }
3620
0
            search_path_size += determine_data_file_path_size(xdg_config_dirs, rel_size);
3621
0
            search_path_size += determine_data_file_path_size(SYSCONFDIR, rel_size);
3622
0
#if defined(EXTRASYSCONFDIR)
3623
0
            search_path_size += determine_data_file_path_size(EXTRASYSCONFDIR, rel_size);
3624
0
#endif
3625
            // Only add the home folders if defined
3626
0
            if (NULL != home_data_dir) {
3627
0
                search_path_size += determine_data_file_path_size(home_data_dir, rel_size);
3628
0
            }
3629
0
            search_path_size += determine_data_file_path_size(xdg_data_dirs, rel_size);
3630
0
        }
3631
#else
3632
#warning read_data_files_in_search_paths unsupported platform
3633
#endif
3634
0
    }
3635
3636
    // Allocate the required space
3637
0
    search_path = loader_instance_heap_calloc(inst, search_path_size, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
3638
0
    if (NULL == search_path) {
3639
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
3640
0
                   "read_data_files_in_search_paths: Failed to allocate space for search path of length %d",
3641
0
                   (uint32_t)search_path_size);
3642
0
        vk_result = VK_ERROR_OUT_OF_HOST_MEMORY;
3643
0
        goto out;
3644
0
    }
3645
3646
0
    cur_path_ptr = search_path;
3647
3648
    // Add the remaining paths to the list
3649
0
    if (NULL != override_path) {
3650
0
        size_t override_path_len = strlen(override_path);
3651
0
        loader_strncpy(cur_path_ptr, search_path_size, override_path, override_path_len);
3652
0
        cur_path_ptr += override_path_len;
3653
0
    } else {
3654
        // Add any additional search paths defined in the additive environment variable
3655
0
        if (NULL != additional_env) {
3656
0
            copy_data_file_info(additional_env, NULL, 0, &cur_path_ptr);
3657
0
        }
3658
3659
#if defined(_WIN32)
3660
        if (NULL != package_path) {
3661
            copy_data_file_info(package_path, NULL, 0, &cur_path_ptr);
3662
        }
3663
#elif COMMON_UNIX_PLATFORMS
3664
0
        if (rel_size > 0) {
3665
#if defined(__APPLE__)
3666
            // Add the bundle's Resources dir to the beginning of the search path.
3667
            // Looks for manifests in the bundle first, before any system directories.
3668
            // This also appears to work unmodified for iOS, it finds the app bundle on the devices
3669
            // file system. (RSW)
3670
            CFBundleRef main_bundle = CFBundleGetMainBundle();
3671
            if (NULL != main_bundle) {
3672
                CFURLRef ref = CFBundleCopyResourcesDirectoryURL(main_bundle);
3673
                if (NULL != ref) {
3674
                    if (CFURLGetFileSystemRepresentation(ref, TRUE, (UInt8 *)cur_path_ptr, search_path_size)) {
3675
                        cur_path_ptr += strlen(cur_path_ptr);
3676
                        *cur_path_ptr++ = DIRECTORY_SYMBOL;
3677
                        memcpy(cur_path_ptr, relative_location, rel_size);
3678
                        cur_path_ptr += rel_size;
3679
                        *cur_path_ptr++ = PATH_SEPARATOR;
3680
                    }
3681
                    CFRelease(ref);
3682
                }
3683
            }
3684
#endif  // __APPLE__
3685
3686
            // Only add the home folders if not NULL
3687
0
            if (NULL != home_config_dir) {
3688
0
                copy_data_file_info(home_config_dir, relative_location, rel_size, &cur_path_ptr);
3689
0
            }
3690
0
            copy_data_file_info(xdg_config_dirs, relative_location, rel_size, &cur_path_ptr);
3691
0
            copy_data_file_info(SYSCONFDIR, relative_location, rel_size, &cur_path_ptr);
3692
0
#if defined(EXTRASYSCONFDIR)
3693
0
            copy_data_file_info(EXTRASYSCONFDIR, relative_location, rel_size, &cur_path_ptr);
3694
0
#endif
3695
3696
            // Only add the home folders if not NULL
3697
0
            if (NULL != home_data_dir) {
3698
0
                copy_data_file_info(home_data_dir, relative_location, rel_size, &cur_path_ptr);
3699
0
            }
3700
0
            copy_data_file_info(xdg_data_dirs, relative_location, rel_size, &cur_path_ptr);
3701
0
        }
3702
3703
        // Remove the last path separator
3704
0
        --cur_path_ptr;
3705
3706
0
        assert(cur_path_ptr - search_path < (ptrdiff_t)search_path_size);
3707
0
        *cur_path_ptr = '\0';
3708
#else
3709
#warning read_data_files_in_search_paths unsupported platform
3710
#endif
3711
0
    }
3712
3713
    // Remove duplicate paths, or it would result in duplicate extensions, duplicate devices, etc.
3714
    // This uses minimal memory, but is O(N^2) on the number of paths. Expect only a few paths.
3715
0
    char path_sep_str[2] = {PATH_SEPARATOR, '\0'};
3716
0
    size_t search_path_updated_size = strlen(search_path);
3717
0
    for (size_t first = 0; first < search_path_updated_size;) {
3718
        // If this is an empty path, erase it
3719
0
        if (search_path[first] == PATH_SEPARATOR) {
3720
0
            memmove(&search_path[first], &search_path[first + 1], search_path_updated_size - first + 1);
3721
0
            search_path_updated_size -= 1;
3722
0
            continue;
3723
0
        }
3724
3725
0
        size_t first_end = first + 1;
3726
0
        first_end += strcspn(&search_path[first_end], path_sep_str);
3727
0
        for (size_t second = first_end + 1; second < search_path_updated_size;) {
3728
0
            size_t second_end = second + 1;
3729
0
            second_end += strcspn(&search_path[second_end], path_sep_str);
3730
0
            if (first_end - first == second_end - second &&
3731
0
                !strncmp(&search_path[first], &search_path[second], second_end - second)) {
3732
                // Found duplicate. Include PATH_SEPARATOR in second_end, then erase it from search_path.
3733
0
                if (search_path[second_end] == PATH_SEPARATOR) {
3734
0
                    second_end++;
3735
0
                }
3736
0
                memmove(&search_path[second], &search_path[second_end], search_path_updated_size - second_end + 1);
3737
0
                search_path_updated_size -= second_end - second;
3738
0
            } else {
3739
0
                second = second_end + 1;
3740
0
            }
3741
0
        }
3742
0
        first = first_end + 1;
3743
0
    }
3744
0
    search_path_size = search_path_updated_size;
3745
3746
    // Print out the paths being searched if debugging is enabled
3747
0
    uint32_t log_flags = 0;
3748
0
    if (search_path_size > 0) {
3749
0
        char *tmp_search_path = loader_instance_heap_alloc(inst, search_path_size + 1, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
3750
0
        if (NULL != tmp_search_path) {
3751
0
            loader_strncpy(tmp_search_path, search_path_size + 1, search_path, search_path_size);
3752
0
            tmp_search_path[search_path_size] = '\0';
3753
0
            if (manifest_type == LOADER_DATA_FILE_MANIFEST_DRIVER) {
3754
0
                log_flags = VULKAN_LOADER_DRIVER_BIT;
3755
0
                loader_log(inst, VULKAN_LOADER_DRIVER_BIT, 0, "Searching for driver manifest files");
3756
0
            } else {
3757
0
                log_flags = VULKAN_LOADER_LAYER_BIT;
3758
0
                loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "Searching for %s layer manifest files",
3759
0
                           manifest_type == LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER ? "explicit" : "implicit");
3760
0
            }
3761
0
            loader_log(inst, log_flags, 0, "   In following locations:");
3762
0
            char *cur_file;
3763
0
            char *next_file = tmp_search_path;
3764
0
            while (NULL != next_file && *next_file != '\0') {
3765
0
                cur_file = next_file;
3766
0
                next_file = loader_get_next_path(cur_file);
3767
0
                loader_log(inst, log_flags, 0, "      %s", cur_file);
3768
0
            }
3769
0
            loader_instance_heap_free(inst, tmp_search_path);
3770
0
        }
3771
0
    }
3772
3773
    // Now, parse the paths and add any manifest files found in them.
3774
0
    vk_result = add_data_files(inst, search_path, out_files);
3775
3776
0
    if (log_flags != 0 && out_files->count > 0) {
3777
0
        loader_log(inst, log_flags, 0, "   Found the following files:");
3778
0
        for (uint32_t cur_file = 0; cur_file < out_files->count; ++cur_file) {
3779
0
            loader_log(inst, log_flags, 0, "      %s", out_files->list[cur_file]);
3780
0
        }
3781
0
    } else {
3782
0
        loader_log(inst, log_flags, 0, "   Found no files");
3783
0
    }
3784
3785
0
    if (NULL != override_path) {
3786
0
        *override_active = true;
3787
0
    } else {
3788
0
        *override_active = false;
3789
0
    }
3790
3791
0
out:
3792
3793
0
    loader_free_getenv(additional_env, inst);
3794
0
    loader_free_getenv(override_env, inst);
3795
#if defined(_WIN32)
3796
    loader_instance_heap_free(inst, package_path);
3797
#elif COMMON_UNIX_PLATFORMS
3798
    loader_free_getenv(xdg_config_home, inst);
3799
0
    loader_free_getenv(xdg_config_dirs, inst);
3800
0
    loader_free_getenv(xdg_data_home, inst);
3801
0
    loader_free_getenv(xdg_data_dirs, inst);
3802
0
    loader_free_getenv(xdg_data_home, inst);
3803
0
    loader_free_getenv(home, inst);
3804
0
    loader_instance_heap_free(inst, default_data_home);
3805
0
    loader_instance_heap_free(inst, default_config_home);
3806
#else
3807
#warning read_data_files_in_search_paths unsupported platform
3808
#endif
3809
3810
0
    loader_instance_heap_free(inst, search_path);
3811
3812
0
    return vk_result;
3813
0
}
3814
3815
// Find the Vulkan library manifest files.
3816
//
3817
// This function scans the appropriate locations for a list of JSON manifest files based on the
3818
// "manifest_type".  The location is interpreted as Registry path on Windows and a directory path(s)
3819
// on Linux.
3820
// "home_location" is an additional directory in the users home directory to look at. It is
3821
// expanded into the dir path $XDG_DATA_HOME/home_location or $HOME/.local/share/home_location
3822
// depending on environment variables. This "home_location" is only used on Linux.
3823
//
3824
// \returns
3825
// VKResult
3826
// A string list of manifest files to be opened in out_files param.
3827
// List has a pointer to string for each manifest filename.
3828
// When done using the list in out_files, pointers should be freed.
3829
// Location or override  string lists can be either files or directories as
3830
// follows:
3831
//            | location | override
3832
// --------------------------------
3833
// Win ICD    | files    | files
3834
// Win Layer  | files    | dirs
3835
// Linux ICD  | dirs     | files
3836
// Linux Layer| dirs     | dirs
3837
3838
VkResult loader_get_data_files(const struct loader_instance *inst, enum loader_data_files_type manifest_type,
3839
0
                               const char *path_override, struct loader_string_list *out_files) {
3840
0
    VkResult res = VK_SUCCESS;
3841
0
    bool override_active = false;
3842
3843
    // Free and init the out_files information so there's no false data left from uninitialized variables.
3844
0
    free_string_list(inst, out_files);
3845
3846
0
    res = read_data_files_in_search_paths(inst, manifest_type, path_override, &override_active, out_files);
3847
0
    if (VK_SUCCESS != res) {
3848
0
        goto out;
3849
0
    }
3850
3851
#if defined(_WIN32)
3852
    // Read the registry if the override wasn't active.
3853
    if (!override_active) {
3854
        bool warn_if_not_present = false;
3855
        char *registry_location = NULL;
3856
3857
        switch (manifest_type) {
3858
            default:
3859
                goto out;
3860
            case LOADER_DATA_FILE_MANIFEST_DRIVER:
3861
                warn_if_not_present = true;
3862
                registry_location = VK_DRIVERS_INFO_REGISTRY_LOC;
3863
                break;
3864
            case LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER:
3865
                registry_location = VK_ILAYERS_INFO_REGISTRY_LOC;
3866
                break;
3867
            case LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER:
3868
                warn_if_not_present = true;
3869
                registry_location = VK_ELAYERS_INFO_REGISTRY_LOC;
3870
                break;
3871
        }
3872
        VkResult tmp_res =
3873
            windows_read_data_files_in_registry(inst, manifest_type, warn_if_not_present, registry_location, out_files);
3874
        // Only return an error if there was an error this time, and no manifest files from before.
3875
        if (VK_SUCCESS != tmp_res && out_files->count == 0) {
3876
            res = tmp_res;
3877
            goto out;
3878
        }
3879
    }
3880
#endif
3881
3882
0
out:
3883
3884
0
    if (VK_SUCCESS != res) {
3885
0
        free_string_list(inst, out_files);
3886
0
    }
3887
3888
0
    return res;
3889
0
}
3890
3891
struct ICDManifestInfo {
3892
    char *full_library_path;
3893
    uint32_t version;
3894
};
3895
3896
// Takes a json file, opens, reads, and parses an ICD Manifest out of it.
3897
// Should only return VK_SUCCESS, VK_ERROR_INCOMPATIBLE_DRIVER, or VK_ERROR_OUT_OF_HOST_MEMORY
3898
VkResult loader_parse_icd_manifest(const struct loader_instance *inst, char *file_str, struct ICDManifestInfo *icd,
3899
0
                                   bool *skipped_portability_drivers) {
3900
0
    VkResult res = VK_SUCCESS;
3901
0
    cJSON *icd_manifest_json = NULL;
3902
3903
0
    if (file_str == NULL) {
3904
0
        goto out;
3905
0
    }
3906
3907
0
    res = loader_get_json(inst, file_str, &icd_manifest_json);
3908
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
3909
0
        goto out;
3910
0
    }
3911
0
    if (res != VK_SUCCESS || NULL == icd_manifest_json) {
3912
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3913
0
        goto out;
3914
0
    }
3915
3916
0
    cJSON *file_format_version_json = loader_cJSON_GetObjectItem(icd_manifest_json, "file_format_version");
3917
0
    if (file_format_version_json == NULL) {
3918
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3919
0
                   "loader_parse_icd_manifest: ICD JSON %s does not have a \'file_format_version\' field. Skipping ICD JSON.",
3920
0
                   file_str);
3921
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3922
0
        goto out;
3923
0
    }
3924
3925
0
    char *file_vers_str = loader_cJSON_GetStringValue(file_format_version_json);
3926
0
    if (NULL == file_vers_str) {
3927
        // Only reason the print can fail is if there was an allocation issue
3928
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3929
0
                   "loader_parse_icd_manifest: Failed retrieving ICD JSON %s \'file_format_version\' field. Skipping ICD JSON",
3930
0
                   file_str);
3931
0
        goto out;
3932
0
    }
3933
0
    loader_log(inst, VULKAN_LOADER_DRIVER_BIT, 0, "Found ICD manifest file %s, version %s", file_str, file_vers_str);
3934
3935
    // Get the version of the driver manifest
3936
0
    loader_api_version json_file_version = loader_make_full_version(loader_parse_version_string(file_vers_str));
3937
3938
    // Loader only knows versions 1.0.0 and 1.0.1, anything above it is unknown
3939
0
    if (loader_check_version_meets_required(loader_combine_version(1, 0, 2), json_file_version)) {
3940
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3941
0
                   "loader_parse_icd_manifest: %s has unknown icd manifest file version %d.%d.%d. May cause errors.", file_str,
3942
0
                   json_file_version.major, json_file_version.minor, json_file_version.patch);
3943
0
    }
3944
3945
0
    cJSON *itemICD = loader_cJSON_GetObjectItem(icd_manifest_json, "ICD");
3946
0
    if (itemICD == NULL) {
3947
        // Don't warn if this happens to be a layer manifest file
3948
0
        if (loader_cJSON_GetObjectItem(icd_manifest_json, "layer") == NULL &&
3949
0
            loader_cJSON_GetObjectItem(icd_manifest_json, "layers") == NULL) {
3950
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3951
0
                       "loader_parse_icd_manifest: Can not find \'ICD\' object in ICD JSON file %s. Skipping ICD JSON", file_str);
3952
0
        }
3953
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3954
0
        goto out;
3955
0
    }
3956
3957
0
    cJSON *library_path_json = loader_cJSON_GetObjectItem(itemICD, "library_path");
3958
0
    if (library_path_json == NULL) {
3959
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3960
0
                   "loader_parse_icd_manifest: Failed to find \'library_path\' object in ICD JSON file %s. Skipping ICD JSON.",
3961
0
                   file_str);
3962
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3963
0
        goto out;
3964
0
    }
3965
0
    bool out_of_memory = false;
3966
0
    char *library_path = loader_cJSON_Print(library_path_json, &out_of_memory);
3967
0
    if (out_of_memory) {
3968
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3969
0
                   "loader_parse_icd_manifest: Failed retrieving ICD JSON %s \'library_path\' field. Skipping ICD JSON.", file_str);
3970
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
3971
0
        goto out;
3972
0
    } else if (!library_path || strlen(library_path) == 0) {
3973
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3974
0
                   "loader_parse_icd_manifest: ICD JSON %s \'library_path\' field is empty. Skipping ICD JSON.", file_str);
3975
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3976
0
        loader_instance_heap_free(inst, library_path);
3977
0
        goto out;
3978
0
    }
3979
3980
    // Print out the paths being searched if debugging is enabled
3981
0
    loader_log(inst, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_DRIVER_BIT, 0, "Searching for ICD drivers named %s", library_path);
3982
    // This function takes ownership of library_path - so we don't need to clean it up
3983
0
    res = combine_manifest_directory_and_library_path(inst, library_path, file_str, &icd->full_library_path);
3984
0
    if (VK_SUCCESS != res) {
3985
0
        goto out;
3986
0
    }
3987
3988
0
    cJSON *api_version_json = loader_cJSON_GetObjectItem(itemICD, "api_version");
3989
0
    if (api_version_json == NULL) {
3990
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3991
0
                   "loader_parse_icd_manifest: ICD JSON %s does not have an \'api_version\' field. Skipping ICD JSON.", file_str);
3992
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
3993
0
        goto out;
3994
0
    }
3995
0
    char *version_str = loader_cJSON_GetStringValue(api_version_json);
3996
0
    if (NULL == version_str) {
3997
        // Only reason the print can fail is if there was an allocation issue
3998
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
3999
0
                   "loader_parse_icd_manifest: Failed retrieving ICD JSON %s \'api_version\' field. Skipping ICD JSON.", file_str);
4000
4001
0
        goto out;
4002
0
    }
4003
0
    icd->version = loader_parse_version_string(version_str);
4004
4005
0
    if (VK_API_VERSION_VARIANT(icd->version) != 0) {
4006
0
        loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4007
0
                   "loader_parse_icd_manifest: Driver's ICD JSON %s \'api_version\' field contains a non-zero variant value of %d. "
4008
0
                   " Skipping ICD JSON.",
4009
0
                   file_str, VK_API_VERSION_VARIANT(icd->version));
4010
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
4011
0
        goto out;
4012
0
    }
4013
4014
    // Skip over ICD's which contain a true "is_portability_driver" value whenever the application doesn't enable
4015
    // portability enumeration.
4016
0
    cJSON *is_portability_driver_json = loader_cJSON_GetObjectItem(itemICD, "is_portability_driver");
4017
0
    if (loader_cJSON_IsTrue(is_portability_driver_json) && inst && !inst->portability_enumeration_enabled) {
4018
0
        if (skipped_portability_drivers) {
4019
0
            *skipped_portability_drivers = true;
4020
0
        }
4021
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
4022
0
        goto out;
4023
0
    }
4024
4025
0
    char *library_arch_str = loader_cJSON_GetStringValue(loader_cJSON_GetObjectItem(itemICD, "library_arch"));
4026
0
    if (library_arch_str != NULL) {
4027
0
        if ((strncmp(library_arch_str, "32", 2) == 0 && sizeof(void *) != 4) ||
4028
0
            (strncmp(library_arch_str, "64", 2) == 0 && sizeof(void *) != 8)) {
4029
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
4030
0
                       "loader_parse_icd_manifest: Driver library architecture doesn't match the current running "
4031
0
                       "architecture, skipping this driver");
4032
0
            res = VK_ERROR_INCOMPATIBLE_DRIVER;
4033
0
            goto out;
4034
0
        }
4035
0
    }
4036
0
out:
4037
0
    loader_cJSON_Delete(icd_manifest_json);
4038
0
    return res;
4039
0
}
4040
4041
// Try to find the Vulkan ICD driver(s).
4042
//
4043
// This function scans the default system loader path(s) or path specified by either the
4044
// VK_DRIVER_FILES or VK_ICD_FILENAMES environment variable in order to find loadable
4045
// VK ICDs manifest files.
4046
// From these manifest files it finds the ICD libraries.
4047
//
4048
// skipped_portability_drivers is used to report whether the loader found drivers which report
4049
// portability but the application didn't enable the bit to enumerate them
4050
// Can be NULL
4051
//
4052
// \returns
4053
// Vulkan result
4054
// (on result == VK_SUCCESS) a list of icds that were discovered
4055
VkResult loader_icd_scan(const struct loader_instance *inst, struct loader_icd_tramp_list *icd_tramp_list,
4056
0
                         const VkInstanceCreateInfo *pCreateInfo, bool *skipped_portability_drivers) {
4057
0
    VkResult res = VK_SUCCESS;
4058
0
    struct loader_string_list manifest_files = {0};
4059
0
    struct loader_envvar_filter select_filter = {0};
4060
0
    struct loader_envvar_filter disable_filter = {0};
4061
0
    struct ICDManifestInfo *icd_details = NULL;
4062
4063
    // Set up the ICD Trampoline list so elements can be written into it.
4064
0
    res = loader_init_scanned_icd_list(inst, icd_tramp_list);
4065
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
4066
0
        return res;
4067
0
    }
4068
4069
0
    bool direct_driver_loading_exclusive_mode = false;
4070
0
    res = loader_scan_for_direct_drivers(inst, pCreateInfo, icd_tramp_list, &direct_driver_loading_exclusive_mode);
4071
0
    if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
4072
0
        goto out;
4073
0
    }
4074
0
    if (direct_driver_loading_exclusive_mode) {
4075
        // Make sure to jump over the system & env-var driver discovery mechanisms if exclusive mode is set, even if no drivers
4076
        // were successfully found through the direct driver loading mechanism
4077
0
        goto out;
4078
0
    }
4079
4080
0
    if (loader_settings_should_use_driver_environment_variables(inst)) {
4081
        // Parse the filter environment variables to determine if we have any special behavior
4082
0
        res = parse_generic_filter_environment_var(inst, VK_DRIVERS_SELECT_ENV_VAR, &select_filter);
4083
0
        if (VK_SUCCESS != res) {
4084
0
            goto out;
4085
0
        }
4086
0
        res = parse_generic_filter_environment_var(inst, VK_DRIVERS_DISABLE_ENV_VAR, &disable_filter);
4087
0
        if (VK_SUCCESS != res) {
4088
0
            goto out;
4089
0
        }
4090
0
    }
4091
4092
    // Get a list of manifest files for ICDs
4093
0
    res = loader_get_data_files(inst, LOADER_DATA_FILE_MANIFEST_DRIVER, NULL, &manifest_files);
4094
0
    if (VK_SUCCESS != res) {
4095
0
        goto out;
4096
0
    }
4097
4098
    // Add any drivers provided by the loader settings file
4099
0
    res = loader_settings_get_additional_driver_files(inst, &manifest_files);
4100
0
    if (VK_SUCCESS != res) {
4101
0
        goto out;
4102
0
    }
4103
4104
0
    icd_details = loader_stack_alloc(sizeof(struct ICDManifestInfo) * manifest_files.count);
4105
0
    if (NULL == icd_details) {
4106
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
4107
0
        goto out;
4108
0
    }
4109
0
    memset(icd_details, 0, sizeof(struct ICDManifestInfo) * manifest_files.count);
4110
4111
0
    for (uint32_t i = 0; i < manifest_files.count; i++) {
4112
0
        VkResult icd_res = VK_SUCCESS;
4113
4114
0
        icd_res = loader_parse_icd_manifest(inst, manifest_files.list[i], &icd_details[i], skipped_portability_drivers);
4115
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == icd_res) {
4116
0
            res = icd_res;
4117
0
            goto out;
4118
0
        } else if (VK_ERROR_INCOMPATIBLE_DRIVER == icd_res) {
4119
0
            continue;
4120
0
        }
4121
4122
0
        if (select_filter.count > 0 || disable_filter.count > 0) {
4123
            // Get only the filename for comparing to the filters
4124
0
            char *just_filename_str = strrchr(manifest_files.list[i], DIRECTORY_SYMBOL);
4125
4126
            // No directory symbol, just the filename
4127
0
            if (NULL == just_filename_str) {
4128
0
                just_filename_str = manifest_files.list[i];
4129
0
            } else {
4130
0
                just_filename_str++;
4131
0
            }
4132
4133
0
            bool name_matches_select =
4134
0
                (select_filter.count > 0 && check_name_matches_filter_environment_var(just_filename_str, &select_filter));
4135
0
            bool name_matches_disable =
4136
0
                (disable_filter.count > 0 && check_name_matches_filter_environment_var(just_filename_str, &disable_filter));
4137
4138
0
            if (name_matches_disable && !name_matches_select) {
4139
0
                loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4140
0
                           "Driver \"%s\" ignored because it was disabled by env var \'%s\'", just_filename_str,
4141
0
                           VK_DRIVERS_DISABLE_ENV_VAR);
4142
0
                continue;
4143
0
            }
4144
0
            if (select_filter.count != 0 && !name_matches_select) {
4145
0
                loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4146
0
                           "Driver \"%s\" ignored because not selected by env var \'%s\'", just_filename_str,
4147
0
                           VK_DRIVERS_SELECT_ENV_VAR);
4148
0
                continue;
4149
0
            }
4150
0
        }
4151
4152
0
        enum loader_layer_library_status lib_status;
4153
0
        icd_res =
4154
0
            loader_scanned_icd_add(inst, icd_tramp_list, icd_details[i].full_library_path, icd_details[i].version, &lib_status);
4155
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == icd_res) {
4156
0
            res = icd_res;
4157
0
            goto out;
4158
0
        } else if (VK_ERROR_INCOMPATIBLE_DRIVER == icd_res) {
4159
0
            switch (lib_status) {
4160
0
                case LOADER_LAYER_LIB_NOT_LOADED:
4161
0
                case LOADER_LAYER_LIB_ERROR_FAILED_TO_LOAD:
4162
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4163
0
                               "loader_icd_scan: Failed loading library associated with ICD JSON %s. Ignoring this JSON",
4164
0
                               icd_details[i].full_library_path);
4165
0
                    break;
4166
0
                case LOADER_LAYER_LIB_ERROR_WRONG_BIT_TYPE: {
4167
0
                    loader_log(inst, VULKAN_LOADER_DRIVER_BIT, 0, "Requested ICD %s was wrong bit-type. Ignoring this JSON",
4168
0
                               icd_details[i].full_library_path);
4169
0
                    break;
4170
0
                }
4171
0
                case LOADER_LAYER_LIB_SUCCESS_LOADED:
4172
0
                case LOADER_LAYER_LIB_ERROR_OUT_OF_MEMORY:
4173
                    // Shouldn't be able to reach this but if it is, best to report a debug
4174
0
                    loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
4175
0
                               "Shouldn't reach this. A valid version of requested ICD %s was loaded but something bad "
4176
0
                               "happened afterwards.",
4177
0
                               icd_details[i].full_library_path);
4178
0
                    break;
4179
0
            }
4180
0
        }
4181
0
    }
4182
4183
0
out:
4184
0
    if (NULL != icd_details) {
4185
        // Successfully got the icd_details structure, which means we need to free the paths contained within
4186
0
        for (uint32_t i = 0; i < manifest_files.count; i++) {
4187
0
            loader_instance_heap_free(inst, icd_details[i].full_library_path);
4188
0
        }
4189
0
    }
4190
0
    free_string_list(inst, &manifest_files);
4191
0
    return res;
4192
0
}
4193
4194
// Gets the layer data files corresponding to manifest_type & path_override, then parses the resulting json objects
4195
// into instance_layers
4196
// Manifest type must be either implicit or explicit
4197
VkResult loader_parse_instance_layers(struct loader_instance *inst, enum loader_data_files_type manifest_type,
4198
0
                                      const char *path_override, struct loader_layer_list *instance_layers) {
4199
0
    assert(manifest_type == LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER || manifest_type == LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER);
4200
0
    VkResult res = VK_SUCCESS;
4201
0
    struct loader_string_list manifest_files = {0};
4202
4203
0
    res = loader_get_data_files(inst, manifest_type, path_override, &manifest_files);
4204
0
    if (VK_SUCCESS != res) {
4205
0
        goto out;
4206
0
    }
4207
4208
0
    for (uint32_t i = 0; i < manifest_files.count; i++) {
4209
0
        char *file_str = manifest_files.list[i];
4210
0
        if (file_str == NULL) {
4211
0
            continue;
4212
0
        }
4213
4214
        // Parse file into JSON struct
4215
0
        cJSON *json = NULL;
4216
0
        VkResult local_res = loader_get_json(inst, file_str, &json);
4217
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == local_res) {
4218
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
4219
0
            goto out;
4220
0
        } else if (VK_SUCCESS != local_res || NULL == json) {
4221
0
            continue;
4222
0
        }
4223
4224
0
        local_res = loader_add_layer_properties(inst, instance_layers, json,
4225
0
                                                manifest_type == LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER, file_str);
4226
0
        loader_cJSON_Delete(json);
4227
4228
        // If the error is anything other than out of memory we still want to try to load the other layers
4229
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == local_res) {
4230
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
4231
0
            goto out;
4232
0
        }
4233
0
    }
4234
0
out:
4235
0
    free_string_list(inst, &manifest_files);
4236
4237
0
    return res;
4238
0
}
4239
4240
// Given a loader_layer_properties struct that is a valid override layer, concatenate the properties override paths and put them
4241
// into the output parameter override_paths
4242
VkResult get_override_layer_override_paths(struct loader_instance *inst, struct loader_layer_properties *prop,
4243
0
                                           char **override_paths) {
4244
0
    if (prop->override_paths.count > 0) {
4245
0
        char *cur_write_ptr = NULL;
4246
0
        size_t override_path_size = 0;
4247
0
        for (uint32_t j = 0; j < prop->override_paths.count; j++) {
4248
0
            override_path_size += determine_data_file_path_size(prop->override_paths.list[j], 0);
4249
0
        }
4250
0
        *override_paths = loader_instance_heap_alloc(inst, override_path_size, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
4251
0
        if (*override_paths == NULL) {
4252
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
4253
0
        }
4254
0
        cur_write_ptr = &(*override_paths)[0];
4255
0
        for (uint32_t j = 0; j < prop->override_paths.count; j++) {
4256
0
            copy_data_file_info(prop->override_paths.list[j], NULL, 0, &cur_write_ptr);
4257
0
        }
4258
4259
        // Subtract one from cur_write_ptr only if something was written so we can set the null terminator
4260
0
        if (*override_paths < cur_write_ptr) {
4261
0
            --cur_write_ptr;
4262
0
            assert(cur_write_ptr - (*override_paths) < (ptrdiff_t)override_path_size);
4263
0
        }
4264
        // Remove the last path separator
4265
0
        *cur_write_ptr = '\0';
4266
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Override layer has override paths set to %s",
4267
0
                   *override_paths);
4268
0
    }
4269
0
    return VK_SUCCESS;
4270
0
}
4271
4272
0
void loader_remove_duplicate_layers(struct loader_instance *inst, struct loader_layer_list *layers) {
4273
    // Remove duplicate layers (that share the same layerName)
4274
0
    for (uint32_t i = 0; i < layers->count; ++i) {
4275
0
        bool has_duplicate = false;
4276
0
        uint32_t duplicate_index = 0;
4277
0
        for (uint32_t j = i + 1; j < layers->count; ++j) {
4278
0
            if (strcmp(layers->list[i].info.layerName, layers->list[j].info.layerName) == 0) {
4279
0
                has_duplicate = true;
4280
0
                duplicate_index = j;
4281
0
                break;
4282
0
            }
4283
0
        }
4284
0
        if (has_duplicate) {
4285
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT, 0, "Removing layer %s (%s) because it is a duplicate of %s (%s)",
4286
0
                       layers->list[duplicate_index].info.layerName, layers->list[duplicate_index].manifest_file_name,
4287
0
                       layers->list[i].info.layerName, layers->list[i].manifest_file_name);
4288
0
            loader_remove_layer_in_list(inst, layers, duplicate_index);
4289
0
        }
4290
0
    }
4291
0
}
4292
4293
VkResult loader_scan_for_layers(struct loader_instance *inst, struct loader_layer_list *instance_layers,
4294
0
                                const struct loader_envvar_all_filters *filters) {
4295
0
    VkResult res = VK_SUCCESS;
4296
0
    struct loader_layer_list settings_layers = {0};
4297
0
    struct loader_layer_list regular_instance_layers = {0};
4298
0
    bool override_layer_valid = false;
4299
0
    char *override_paths = NULL;
4300
4301
0
    bool should_search_for_other_layers = true;
4302
0
    res = get_settings_layers(inst, &settings_layers, &should_search_for_other_layers);
4303
0
    if (VK_SUCCESS != res) {
4304
0
        goto out;
4305
0
    }
4306
4307
    // If we should not look for layers using other mechanisms, assign settings_layers to instance_layers and jump to the
4308
    // output
4309
0
    if (!should_search_for_other_layers) {
4310
0
        *instance_layers = settings_layers;
4311
0
        memset(&settings_layers, 0, sizeof(struct loader_layer_list));
4312
0
        goto out;
4313
0
    }
4314
4315
0
    res = loader_parse_instance_layers(inst, LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER, NULL, &regular_instance_layers);
4316
0
    if (VK_SUCCESS != res) {
4317
0
        goto out;
4318
0
    }
4319
4320
    // Remove any extraneous override layers.
4321
0
    remove_all_non_valid_override_layers(inst, &regular_instance_layers);
4322
4323
    // Check to see if the override layer is present, and use it's override paths.
4324
0
    for (uint32_t i = 0; i < regular_instance_layers.count; i++) {
4325
0
        struct loader_layer_properties *prop = &regular_instance_layers.list[i];
4326
0
        if (prop->is_override && loader_implicit_layer_is_enabled(inst, filters, prop) && prop->override_paths.count > 0) {
4327
0
            res = get_override_layer_override_paths(inst, prop, &override_paths);
4328
0
            if (VK_SUCCESS != res) {
4329
0
                goto out;
4330
0
            }
4331
0
            break;
4332
0
        }
4333
0
    }
4334
4335
    // Get a list of manifest files for explicit layers
4336
0
    res = loader_parse_instance_layers(inst, LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER, override_paths, &regular_instance_layers);
4337
0
    if (VK_SUCCESS != res) {
4338
0
        goto out;
4339
0
    }
4340
4341
    // Verify any meta-layers in the list are valid and all the component layers are
4342
    // actually present in the available layer list
4343
0
    res = verify_all_meta_layers(inst, filters, &regular_instance_layers, &override_layer_valid);
4344
0
    if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
4345
0
        return res;
4346
0
    }
4347
4348
0
    if (override_layer_valid) {
4349
0
        loader_remove_layers_in_blacklist(inst, &regular_instance_layers);
4350
0
        if (NULL != inst) {
4351
0
            inst->override_layer_present = true;
4352
0
        }
4353
0
    }
4354
4355
    // Remove disabled layers
4356
0
    for (uint32_t i = 0; i < regular_instance_layers.count; ++i) {
4357
0
        if (!loader_layer_is_available(inst, filters, &regular_instance_layers.list[i])) {
4358
0
            loader_remove_layer_in_list(inst, &regular_instance_layers, i);
4359
0
            i--;
4360
0
        }
4361
0
    }
4362
4363
    // Make sure no layers have the same layerName
4364
0
    loader_remove_duplicate_layers(inst, &regular_instance_layers);
4365
4366
0
    res = combine_settings_layers_with_regular_layers(inst, &settings_layers, &regular_instance_layers, instance_layers);
4367
4368
0
out:
4369
0
    loader_delete_layer_list_and_properties(inst, &settings_layers);
4370
0
    loader_delete_layer_list_and_properties(inst, &regular_instance_layers);
4371
4372
0
    loader_instance_heap_free(inst, override_paths);
4373
0
    return res;
4374
0
}
4375
4376
VkResult loader_scan_for_implicit_layers(struct loader_instance *inst, struct loader_layer_list *instance_layers,
4377
0
                                         const struct loader_envvar_all_filters *layer_filters) {
4378
0
    VkResult res = VK_SUCCESS;
4379
0
    struct loader_layer_list settings_layers = {0};
4380
0
    struct loader_layer_list regular_instance_layers = {0};
4381
0
    bool override_layer_valid = false;
4382
0
    char *override_paths = NULL;
4383
0
    bool implicit_metalayer_present = false;
4384
4385
0
    bool should_search_for_other_layers = true;
4386
0
    res = get_settings_layers(inst, &settings_layers, &should_search_for_other_layers);
4387
0
    if (VK_SUCCESS != res) {
4388
0
        goto out;
4389
0
    }
4390
4391
    // Remove layers from settings file that are off, are explicit, or are implicit layers that aren't active
4392
0
    for (uint32_t i = 0; i < settings_layers.count; ++i) {
4393
0
        if (settings_layers.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_OFF ||
4394
0
            settings_layers.list[i].settings_control_value == LOADER_SETTINGS_LAYER_UNORDERED_LAYER_LOCATION ||
4395
0
            (settings_layers.list[i].type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER) == VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER ||
4396
0
            !loader_implicit_layer_is_enabled(inst, layer_filters, &settings_layers.list[i])) {
4397
0
            loader_remove_layer_in_list(inst, &settings_layers, i);
4398
0
            i--;
4399
0
        }
4400
0
    }
4401
4402
    // If we should not look for layers using other mechanisms, assign settings_layers to instance_layers and jump to the
4403
    // output
4404
0
    if (!should_search_for_other_layers) {
4405
0
        *instance_layers = settings_layers;
4406
0
        memset(&settings_layers, 0, sizeof(struct loader_layer_list));
4407
0
        goto out;
4408
0
    }
4409
4410
0
    res = loader_parse_instance_layers(inst, LOADER_DATA_FILE_MANIFEST_IMPLICIT_LAYER, NULL, &regular_instance_layers);
4411
0
    if (VK_SUCCESS != res) {
4412
0
        goto out;
4413
0
    }
4414
4415
    // Remove any extraneous override layers.
4416
0
    remove_all_non_valid_override_layers(inst, &regular_instance_layers);
4417
4418
    // Check to see if either the override layer is present, or another implicit meta-layer.
4419
    // Each of these may require explicit layers to be enabled at this time.
4420
0
    for (uint32_t i = 0; i < regular_instance_layers.count; i++) {
4421
0
        struct loader_layer_properties *prop = &regular_instance_layers.list[i];
4422
0
        if (prop->is_override && loader_implicit_layer_is_enabled(inst, layer_filters, prop)) {
4423
0
            override_layer_valid = true;
4424
0
            res = get_override_layer_override_paths(inst, prop, &override_paths);
4425
0
            if (VK_SUCCESS != res) {
4426
0
                goto out;
4427
0
            }
4428
0
        } else if (!prop->is_override && prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER) {
4429
0
            implicit_metalayer_present = true;
4430
0
        }
4431
0
    }
4432
4433
    // If either the override layer or an implicit meta-layer are present, we need to add
4434
    // explicit layer info as well.  Not to worry, though, all explicit layers not included
4435
    // in the override layer will be removed below in loader_remove_layers_in_blacklist().
4436
0
    if (override_layer_valid || implicit_metalayer_present) {
4437
0
        res =
4438
0
            loader_parse_instance_layers(inst, LOADER_DATA_FILE_MANIFEST_EXPLICIT_LAYER, override_paths, &regular_instance_layers);
4439
0
        if (VK_SUCCESS != res) {
4440
0
            goto out;
4441
0
        }
4442
0
    }
4443
4444
    // Verify any meta-layers in the list are valid and all the component layers are
4445
    // actually present in the available layer list
4446
0
    res = verify_all_meta_layers(inst, layer_filters, &regular_instance_layers, &override_layer_valid);
4447
0
    if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
4448
0
        return res;
4449
0
    }
4450
4451
0
    if (override_layer_valid || implicit_metalayer_present) {
4452
0
        loader_remove_layers_not_in_implicit_meta_layers(inst, &regular_instance_layers);
4453
0
        if (override_layer_valid && inst != NULL) {
4454
0
            inst->override_layer_present = true;
4455
0
        }
4456
0
    }
4457
4458
    // Remove disabled layers
4459
0
    for (uint32_t i = 0; i < regular_instance_layers.count; ++i) {
4460
0
        if (!loader_implicit_layer_is_enabled(inst, layer_filters, &regular_instance_layers.list[i])) {
4461
0
            loader_remove_layer_in_list(inst, &regular_instance_layers, i);
4462
0
            i--;
4463
0
        }
4464
0
    }
4465
4466
    // Make sure no layers have the same layerName
4467
0
    loader_remove_duplicate_layers(inst, &regular_instance_layers);
4468
4469
0
    res = combine_settings_layers_with_regular_layers(inst, &settings_layers, &regular_instance_layers, instance_layers);
4470
4471
0
out:
4472
0
    loader_delete_layer_list_and_properties(inst, &settings_layers);
4473
0
    loader_delete_layer_list_and_properties(inst, &regular_instance_layers);
4474
4475
0
    loader_instance_heap_free(inst, override_paths);
4476
0
    return res;
4477
0
}
4478
4479
0
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL loader_gpdpa_instance_terminator(VkInstance inst, const char *pName) {
4480
    // inst is not wrapped
4481
0
    if (inst == VK_NULL_HANDLE) {
4482
0
        return NULL;
4483
0
    }
4484
4485
0
    VkLayerInstanceDispatchTable *disp_table = *(VkLayerInstanceDispatchTable **)inst;
4486
4487
0
    if (disp_table == NULL) return NULL;
4488
4489
0
    struct loader_instance *loader_inst = loader_get_instance(inst);
4490
4491
0
    if (loader_inst->instance_finished_creation) {
4492
0
        disp_table = &loader_inst->terminator_dispatch;
4493
0
    }
4494
4495
0
    bool found_name;
4496
0
    void *addr = loader_lookup_instance_dispatch_table(disp_table, pName, &found_name);
4497
0
    if (found_name) {
4498
0
        return addr;
4499
0
    }
4500
4501
    // Check if any drivers support the function, and if so, add it to the unknown function list
4502
0
    addr = loader_phys_dev_ext_gpa_term(loader_get_instance(inst), pName);
4503
0
    if (NULL != addr) return addr;
4504
4505
    // Don't call down the chain, this would be an infinite loop
4506
0
    loader_log(NULL, VULKAN_LOADER_DEBUG_BIT, 0, "loader_gpdpa_instance_terminator() unrecognized name %s", pName);
4507
0
    return NULL;
4508
0
}
4509
4510
0
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL loader_gpa_instance_terminator(VkInstance inst, const char *pName) {
4511
    // Global functions - Do not need a valid instance handle to query
4512
0
    if (!strcmp(pName, "vkGetInstanceProcAddr")) {
4513
0
        return (PFN_vkVoidFunction)loader_gpa_instance_terminator;
4514
0
    }
4515
0
    if (!strcmp(pName, "vk_layerGetPhysicalDeviceProcAddr")) {
4516
0
        return (PFN_vkVoidFunction)loader_gpdpa_instance_terminator;
4517
0
    }
4518
0
    if (!strcmp(pName, "vkCreateInstance")) {
4519
0
        return (PFN_vkVoidFunction)terminator_CreateInstance;
4520
0
    }
4521
    // If a layer is querying pre-instance functions using vkGetInstanceProcAddr, we need to return function pointers that match the
4522
    // Vulkan API
4523
0
    if (!strcmp(pName, "vkEnumerateInstanceLayerProperties")) {
4524
0
        return (PFN_vkVoidFunction)terminator_EnumerateInstanceLayerProperties;
4525
0
    }
4526
0
    if (!strcmp(pName, "vkEnumerateInstanceExtensionProperties")) {
4527
0
        return (PFN_vkVoidFunction)terminator_EnumerateInstanceExtensionProperties;
4528
0
    }
4529
0
    if (!strcmp(pName, "vkEnumerateInstanceVersion")) {
4530
0
        return (PFN_vkVoidFunction)terminator_EnumerateInstanceVersion;
4531
0
    }
4532
4533
    // While the spec is very clear that querying vkCreateDevice requires a valid VkInstance, because the loader allowed querying
4534
    // with a NULL VkInstance handle for a long enough time, it is impractical to fix this bug in the loader
4535
4536
    // As such, this is a bug to maintain compatibility for the RTSS layer (Riva Tuner Statistics Server) but may
4537
    // be depended upon by other layers out in the wild.
4538
0
    if (!strcmp(pName, "vkCreateDevice")) {
4539
0
        return (PFN_vkVoidFunction)terminator_CreateDevice;
4540
0
    }
4541
4542
    // inst is not wrapped
4543
0
    if (inst == VK_NULL_HANDLE) {
4544
0
        return NULL;
4545
0
    }
4546
0
    VkLayerInstanceDispatchTable *disp_table = *(VkLayerInstanceDispatchTable **)inst;
4547
4548
0
    if (disp_table == NULL) return NULL;
4549
4550
0
    struct loader_instance *loader_inst = loader_get_instance(inst);
4551
4552
    // The VK_EXT_debug_utils functions need a special case here so the terminators can still be found from
4553
    // vkGetInstanceProcAddr This is because VK_EXT_debug_utils is an instance level extension with device level functions, and
4554
    // is 'supported' by the loader.
4555
    // These functions need a terminator to handle the case of a driver not supporting VK_EXT_debug_utils when there are layers
4556
    // present which not check for NULL before calling the function.
4557
0
    if (!strcmp(pName, "vkSetDebugUtilsObjectNameEXT")) {
4558
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_SetDebugUtilsObjectNameEXT : NULL;
4559
0
    }
4560
0
    if (!strcmp(pName, "vkSetDebugUtilsObjectTagEXT")) {
4561
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_SetDebugUtilsObjectTagEXT : NULL;
4562
0
    }
4563
0
    if (!strcmp(pName, "vkQueueBeginDebugUtilsLabelEXT")) {
4564
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_QueueBeginDebugUtilsLabelEXT : NULL;
4565
0
    }
4566
0
    if (!strcmp(pName, "vkQueueEndDebugUtilsLabelEXT")) {
4567
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_QueueEndDebugUtilsLabelEXT : NULL;
4568
0
    }
4569
0
    if (!strcmp(pName, "vkQueueInsertDebugUtilsLabelEXT")) {
4570
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_QueueInsertDebugUtilsLabelEXT
4571
0
                                                               : NULL;
4572
0
    }
4573
0
    if (!strcmp(pName, "vkCmdBeginDebugUtilsLabelEXT")) {
4574
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_CmdBeginDebugUtilsLabelEXT : NULL;
4575
0
    }
4576
0
    if (!strcmp(pName, "vkCmdEndDebugUtilsLabelEXT")) {
4577
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_CmdEndDebugUtilsLabelEXT : NULL;
4578
0
    }
4579
0
    if (!strcmp(pName, "vkCmdInsertDebugUtilsLabelEXT")) {
4580
0
        return loader_inst->enabled_extensions.ext_debug_utils ? (PFN_vkVoidFunction)terminator_CmdInsertDebugUtilsLabelEXT : NULL;
4581
0
    }
4582
4583
0
    if (loader_inst->instance_finished_creation) {
4584
0
        disp_table = &loader_inst->terminator_dispatch;
4585
0
    }
4586
4587
0
    bool found_name;
4588
0
    void *addr = loader_lookup_instance_dispatch_table(disp_table, pName, &found_name);
4589
0
    if (found_name) {
4590
0
        return addr;
4591
0
    }
4592
4593
    // Check if it is an unknown physical device function, to see if any drivers support it.
4594
0
    addr = loader_phys_dev_ext_gpa_term(loader_get_instance(inst), pName);
4595
0
    if (addr) {
4596
0
        return addr;
4597
0
    }
4598
4599
    // Assume it is an unknown device function, check to see if any drivers support it.
4600
0
    addr = loader_dev_ext_gpa_term(loader_get_instance(inst), pName);
4601
0
    if (addr) {
4602
0
        return addr;
4603
0
    }
4604
4605
    // Don't call down the chain, this would be an infinite loop
4606
0
    loader_log(NULL, VULKAN_LOADER_DEBUG_BIT, 0, "loader_gpa_instance_terminator() unrecognized name %s", pName);
4607
0
    return NULL;
4608
0
}
4609
4610
0
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL loader_gpa_device_terminator(VkDevice device, const char *pName) {
4611
0
    struct loader_device *dev;
4612
0
    struct loader_icd_term *icd_term = loader_get_icd_and_device(device, &dev);
4613
4614
    // Return this function if a layer above here is asking for the vkGetDeviceProcAddr.
4615
    // This is so we can properly intercept any device commands needing a terminator.
4616
0
    if (!strcmp(pName, "vkGetDeviceProcAddr")) {
4617
0
        return (PFN_vkVoidFunction)loader_gpa_device_terminator;
4618
0
    }
4619
4620
    // NOTE: Device Funcs needing Trampoline/Terminator.
4621
    // Overrides for device functions needing a trampoline and
4622
    // a terminator because certain device entry-points still need to go
4623
    // through a terminator before hitting the ICD.  This could be for
4624
    // several reasons, but the main one is currently unwrapping an
4625
    // object before passing the appropriate info along to the ICD.
4626
    // This is why we also have to override the direct ICD call to
4627
    // vkGetDeviceProcAddr to intercept those calls.
4628
    // If the pName is for a 'known' function but isn't available, due to
4629
    // the corresponding extension/feature not being enabled, we need to
4630
    // return NULL and not call down to the driver's GetDeviceProcAddr.
4631
0
    if (NULL != dev) {
4632
0
        bool found_name = false;
4633
0
        PFN_vkVoidFunction addr = get_extension_device_proc_terminator(dev, pName, &found_name);
4634
0
        if (found_name) {
4635
0
            return addr;
4636
0
        }
4637
0
    }
4638
4639
0
    if (icd_term == NULL) {
4640
0
        return NULL;
4641
0
    }
4642
4643
0
    return icd_term->dispatch.GetDeviceProcAddr(device, pName);
4644
0
}
4645
4646
0
struct loader_instance *loader_get_instance(const VkInstance instance) {
4647
    // look up the loader_instance in our list by comparing dispatch tables, as
4648
    // there is no guarantee the instance is still a loader_instance* after any
4649
    // layers which wrap the instance object.
4650
0
    const VkLayerInstanceDispatchTable *disp;
4651
0
    struct loader_instance *ptr_instance = (struct loader_instance *)instance;
4652
0
    if (VK_NULL_HANDLE == instance || LOADER_MAGIC_NUMBER != ptr_instance->magic) {
4653
0
        return NULL;
4654
0
    } else {
4655
0
        disp = loader_get_instance_layer_dispatch(instance);
4656
0
        loader_platform_thread_lock_mutex(&loader_lock);
4657
0
        for (struct loader_instance *inst = loader.instances; inst; inst = inst->next) {
4658
0
            if (&inst->disp->layer_inst_disp == disp) {
4659
0
                ptr_instance = inst;
4660
0
                break;
4661
0
            }
4662
0
        }
4663
0
        loader_platform_thread_unlock_mutex(&loader_lock);
4664
0
    }
4665
0
    return ptr_instance;
4666
0
}
4667
4668
0
loader_platform_dl_handle loader_open_layer_file(const struct loader_instance *inst, struct loader_layer_properties *prop) {
4669
0
    if ((prop->lib_handle = loader_platform_open_library(prop->lib_name)) == NULL) {
4670
0
        loader_handle_load_library_error(inst, prop->lib_name, &prop->lib_status);
4671
0
    } else {
4672
0
        prop->lib_status = LOADER_LAYER_LIB_SUCCESS_LOADED;
4673
0
        loader_log(inst, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Loading layer library %s", prop->lib_name);
4674
0
    }
4675
4676
0
    return prop->lib_handle;
4677
0
}
4678
4679
// Go through the search_list and find any layers which match type. If layer
4680
// type match is found in then add it to ext_list.
4681
// 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
4682
// enabled layers
4683
VkResult loader_add_implicit_layers(const struct loader_instance *inst, const char *enabled_layers_env,
4684
                                    const struct loader_envvar_all_filters *filters, struct loader_pointer_layer_list *target_list,
4685
                                    struct loader_pointer_layer_list *expanded_target_list,
4686
0
                                    const struct loader_layer_list *source_list) {
4687
0
    for (uint32_t src_layer = 0; src_layer < source_list->count; src_layer++) {
4688
0
        struct loader_layer_properties *prop = &source_list->list[src_layer];
4689
0
        if (0 == (prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
4690
            // If this layer appears in the enabled_layers_env, don't add it. We will let loader_add_environment_layers handle it
4691
0
            if (NULL == enabled_layers_env || NULL == strstr(enabled_layers_env, prop->info.layerName)) {
4692
0
                VkResult result = loader_add_implicit_layer(inst, prop, filters, target_list, expanded_target_list, source_list);
4693
0
                if (result == VK_ERROR_OUT_OF_HOST_MEMORY) return result;
4694
0
            }
4695
0
        }
4696
0
    }
4697
0
    return VK_SUCCESS;
4698
0
}
4699
4700
0
void warn_if_layers_are_older_than_application(struct loader_instance *inst) {
4701
0
    for (uint32_t i = 0; i < inst->expanded_activated_layer_list.count; i++) {
4702
        // Verify that the layer api version is at least that of the application's request, if not, throw a warning since
4703
        // undefined behavior could occur.
4704
0
        struct loader_layer_properties *prop = inst->expanded_activated_layer_list.list[i];
4705
0
        loader_api_version prop_spec_version = loader_make_version(prop->info.specVersion);
4706
0
        if (!loader_check_version_meets_required(inst->app_api_version, prop_spec_version)) {
4707
0
            loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
4708
0
                       "Layer %s uses API version %u.%u which is older than the application specified "
4709
0
                       "API version of %u.%u. May cause issues.",
4710
0
                       prop->info.layerName, prop_spec_version.major, prop_spec_version.minor, inst->app_api_version.major,
4711
0
                       inst->app_api_version.minor);
4712
0
        }
4713
0
    }
4714
0
}
4715
4716
VkResult loader_enable_instance_layers(struct loader_instance *inst, const VkInstanceCreateInfo *pCreateInfo,
4717
                                       const struct loader_layer_list *instance_layers,
4718
0
                                       const struct loader_envvar_all_filters *layer_filters) {
4719
0
    VkResult res = VK_SUCCESS;
4720
0
    char *enabled_layers_env = NULL;
4721
4722
0
    assert(inst && "Cannot have null instance");
4723
4724
0
    if (!loader_init_pointer_layer_list(inst, &inst->app_activated_layer_list)) {
4725
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
4726
0
                   "loader_enable_instance_layers: Failed to initialize application version of the layer list");
4727
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
4728
0
        goto out;
4729
0
    }
4730
4731
0
    if (!loader_init_pointer_layer_list(inst, &inst->expanded_activated_layer_list)) {
4732
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
4733
0
                   "loader_enable_instance_layers: Failed to initialize expanded version of the layer list");
4734
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
4735
0
        goto out;
4736
0
    }
4737
4738
0
    if (inst->settings.settings_active && inst->settings.layer_configurations_active) {
4739
0
        res = enable_correct_layers_from_settings(inst, layer_filters, pCreateInfo->enabledLayerCount,
4740
0
                                                  pCreateInfo->ppEnabledLayerNames, &inst->instance_layer_list,
4741
0
                                                  &inst->app_activated_layer_list, &inst->expanded_activated_layer_list);
4742
0
        warn_if_layers_are_older_than_application(inst);
4743
4744
0
        goto out;
4745
0
    }
4746
4747
0
    enabled_layers_env = loader_getenv(ENABLED_LAYERS_ENV, inst);
4748
4749
    // Add any implicit layers first
4750
0
    res = loader_add_implicit_layers(inst, enabled_layers_env, layer_filters, &inst->app_activated_layer_list,
4751
0
                                     &inst->expanded_activated_layer_list, instance_layers);
4752
0
    if (res != VK_SUCCESS) {
4753
0
        goto out;
4754
0
    }
4755
4756
    // Add any layers specified via environment variable next
4757
0
    res = loader_add_environment_layers(inst, enabled_layers_env, layer_filters, &inst->app_activated_layer_list,
4758
0
                                        &inst->expanded_activated_layer_list, instance_layers);
4759
0
    if (res != VK_SUCCESS) {
4760
0
        goto out;
4761
0
    }
4762
4763
    // Add layers specified by the application
4764
0
    res = loader_add_layer_names_to_list(inst, layer_filters, &inst->app_activated_layer_list, &inst->expanded_activated_layer_list,
4765
0
                                         pCreateInfo->enabledLayerCount, pCreateInfo->ppEnabledLayerNames, instance_layers);
4766
4767
0
    warn_if_layers_are_older_than_application(inst);
4768
0
out:
4769
0
    if (enabled_layers_env != NULL) {
4770
0
        loader_free_getenv(enabled_layers_env, inst);
4771
0
    }
4772
4773
0
    return res;
4774
0
}
4775
4776
// Determine the layer interface version to use.
4777
bool loader_get_layer_interface_version(PFN_vkNegotiateLoaderLayerInterfaceVersion fp_negotiate_layer_version,
4778
0
                                        VkNegotiateLayerInterface *interface_struct) {
4779
0
    memset(interface_struct, 0, sizeof(VkNegotiateLayerInterface));
4780
0
    interface_struct->sType = LAYER_NEGOTIATE_INTERFACE_STRUCT;
4781
0
    interface_struct->loaderLayerInterfaceVersion = 1;
4782
0
    interface_struct->pNext = NULL;
4783
4784
0
    if (fp_negotiate_layer_version != NULL) {
4785
        // Layer supports the negotiation API, so call it with the loader's
4786
        // latest version supported
4787
0
        interface_struct->loaderLayerInterfaceVersion = CURRENT_LOADER_LAYER_INTERFACE_VERSION;
4788
0
        VkResult result = fp_negotiate_layer_version(interface_struct);
4789
4790
0
        if (result != VK_SUCCESS) {
4791
            // Layer no longer supports the loader's latest interface version so
4792
            // fail loading the Layer
4793
0
            return false;
4794
0
        }
4795
0
    }
4796
4797
0
    if (interface_struct->loaderLayerInterfaceVersion < MIN_SUPPORTED_LOADER_LAYER_INTERFACE_VERSION) {
4798
        // Loader no longer supports the layer's latest interface version so
4799
        // fail loading the layer
4800
0
        return false;
4801
0
    }
4802
4803
0
    return true;
4804
0
}
4805
4806
// Every extension that has a loader-defined trampoline needs to be marked as enabled or disabled so that we know whether or
4807
// not to return that trampoline when vkGetDeviceProcAddr is called
4808
void setup_logical_device_enabled_layer_extensions(const struct loader_instance *inst, struct loader_device *dev,
4809
                                                   const struct loader_extension_list *icd_exts,
4810
0
                                                   const VkDeviceCreateInfo *pCreateInfo) {
4811
    // no enabled extensions, early exit
4812
0
    if (pCreateInfo->ppEnabledExtensionNames == NULL) {
4813
0
        return;
4814
0
    }
4815
    // Can only setup debug marker as debug utils is an instance extensions.
4816
0
    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; ++i) {
4817
0
        if (pCreateInfo->ppEnabledExtensionNames[i] &&
4818
0
            !strcmp(pCreateInfo->ppEnabledExtensionNames[i], VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) {
4819
            // Check if its supported by the driver
4820
0
            for (uint32_t j = 0; j < icd_exts->count; ++j) {
4821
0
                if (!strcmp(icd_exts->list[j].extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) {
4822
0
                    dev->layer_extensions.ext_debug_marker_enabled = true;
4823
0
                }
4824
0
            }
4825
            // also check if any layers support it.
4826
0
            for (uint32_t j = 0; j < inst->app_activated_layer_list.count; j++) {
4827
0
                struct loader_layer_properties *layer = inst->app_activated_layer_list.list[j];
4828
0
                for (uint32_t k = 0; k < layer->device_extension_list.count; k++) {
4829
0
                    if (!strcmp(layer->device_extension_list.list[k].props.extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) {
4830
0
                        dev->layer_extensions.ext_debug_marker_enabled = true;
4831
0
                    }
4832
0
                }
4833
0
            }
4834
0
        }
4835
0
    }
4836
0
}
4837
4838
VKAPI_ATTR VkResult VKAPI_CALL loader_layer_create_device(VkInstance instance, VkPhysicalDevice physicalDevice,
4839
                                                          const VkDeviceCreateInfo *pCreateInfo,
4840
                                                          const VkAllocationCallbacks *pAllocator, VkDevice *pDevice,
4841
0
                                                          PFN_vkGetInstanceProcAddr layerGIPA, PFN_vkGetDeviceProcAddr *nextGDPA) {
4842
0
    VkResult res;
4843
0
    VkPhysicalDevice internal_device = VK_NULL_HANDLE;
4844
0
    struct loader_device *dev = NULL;
4845
0
    struct loader_instance *inst = NULL;
4846
4847
0
    if (instance != VK_NULL_HANDLE) {
4848
0
        inst = loader_get_instance(instance);
4849
0
        internal_device = physicalDevice;
4850
0
    } else {
4851
0
        struct loader_physical_device_tramp *phys_dev = (struct loader_physical_device_tramp *)physicalDevice;
4852
0
        internal_device = phys_dev->phys_dev;
4853
0
        inst = (struct loader_instance *)phys_dev->this_instance;
4854
0
    }
4855
4856
    // Get the physical device (ICD) extensions
4857
0
    struct loader_extension_list icd_exts = {0};
4858
0
    icd_exts.list = NULL;
4859
0
    res = loader_init_generic_list(inst, (struct loader_generic_list *)&icd_exts, sizeof(VkExtensionProperties));
4860
0
    if (VK_SUCCESS != res) {
4861
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "vkCreateDevice: Failed to create ICD extension list");
4862
0
        goto out;
4863
0
    }
4864
4865
0
    PFN_vkEnumerateDeviceExtensionProperties enumDeviceExtensionProperties = NULL;
4866
0
    if (layerGIPA != NULL) {
4867
0
        enumDeviceExtensionProperties =
4868
0
            (PFN_vkEnumerateDeviceExtensionProperties)layerGIPA(instance, "vkEnumerateDeviceExtensionProperties");
4869
0
    } else {
4870
0
        enumDeviceExtensionProperties = inst->disp->layer_inst_disp.EnumerateDeviceExtensionProperties;
4871
0
    }
4872
0
    res = loader_add_device_extensions(inst, enumDeviceExtensionProperties, internal_device, "Unknown", &icd_exts);
4873
0
    if (res != VK_SUCCESS) {
4874
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "vkCreateDevice: Failed to add extensions to list");
4875
0
        goto out;
4876
0
    }
4877
4878
    // Make sure requested extensions to be enabled are supported
4879
0
    res = loader_validate_device_extensions(inst, &inst->expanded_activated_layer_list, &icd_exts, pCreateInfo);
4880
0
    if (res != VK_SUCCESS) {
4881
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "vkCreateDevice: Failed to validate extensions in list");
4882
0
        goto out;
4883
0
    }
4884
4885
0
    dev = loader_create_logical_device(inst, pAllocator);
4886
0
    if (dev == NULL) {
4887
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
4888
0
        goto out;
4889
0
    }
4890
4891
0
    setup_logical_device_enabled_layer_extensions(inst, dev, &icd_exts, pCreateInfo);
4892
4893
0
    res = loader_create_device_chain(internal_device, pCreateInfo, pAllocator, inst, dev, layerGIPA, nextGDPA);
4894
0
    if (res != VK_SUCCESS) {
4895
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "vkCreateDevice:  Failed to create device chain.");
4896
0
        goto out;
4897
0
    }
4898
4899
0
    *pDevice = dev->chain_device;
4900
4901
    // Initialize any device extension dispatch entry's from the instance list
4902
0
    loader_init_dispatch_dev_ext(inst, dev);
4903
4904
    // Initialize WSI device extensions as part of core dispatch since loader
4905
    // has dedicated trampoline code for these
4906
0
    loader_init_device_extension_dispatch_table(&dev->loader_dispatch, inst->disp->layer_inst_disp.GetInstanceProcAddr,
4907
0
                                                dev->loader_dispatch.core_dispatch.GetDeviceProcAddr, inst->instance, *pDevice);
4908
4909
0
out:
4910
4911
    // Failure cleanup
4912
0
    if (VK_SUCCESS != res) {
4913
0
        if (NULL != dev) {
4914
            // Find the icd_term this device belongs to then remove it from that icd_term.
4915
            // Need to iterate the linked lists and remove the device from it. Don't delete
4916
            // the device here since it may not have been added to the icd_term and there
4917
            // are other allocations attached to it.
4918
0
            struct loader_icd_term *icd_term = inst->icd_terms;
4919
0
            bool found = false;
4920
0
            while (!found && NULL != icd_term) {
4921
0
                struct loader_device *cur_dev = icd_term->logical_device_list;
4922
0
                struct loader_device *prev_dev = NULL;
4923
0
                while (NULL != cur_dev) {
4924
0
                    if (cur_dev == dev) {
4925
0
                        if (cur_dev == icd_term->logical_device_list) {
4926
0
                            icd_term->logical_device_list = cur_dev->next;
4927
0
                        } else if (prev_dev) {
4928
0
                            prev_dev->next = cur_dev->next;
4929
0
                        }
4930
4931
0
                        found = true;
4932
0
                        break;
4933
0
                    }
4934
0
                    prev_dev = cur_dev;
4935
0
                    cur_dev = cur_dev->next;
4936
0
                }
4937
0
                icd_term = icd_term->next;
4938
0
            }
4939
            // Now destroy the device and the allocations associated with it.
4940
0
            loader_destroy_logical_device(dev, pAllocator);
4941
0
        }
4942
0
    }
4943
4944
0
    if (NULL != icd_exts.list) {
4945
0
        loader_destroy_generic_list(inst, (struct loader_generic_list *)&icd_exts);
4946
0
    }
4947
0
    return res;
4948
0
}
4949
4950
VKAPI_ATTR void VKAPI_CALL loader_layer_destroy_device(VkDevice device, const VkAllocationCallbacks *pAllocator,
4951
0
                                                       PFN_vkDestroyDevice destroyFunction) {
4952
0
    struct loader_device *dev;
4953
4954
0
    if (device == VK_NULL_HANDLE) {
4955
0
        return;
4956
0
    }
4957
4958
0
    struct loader_icd_term *icd_term = loader_get_icd_and_device(device, &dev);
4959
4960
0
    destroyFunction(device, pAllocator);
4961
0
    if (NULL != dev) {
4962
0
        dev->chain_device = NULL;
4963
0
        dev->icd_device = NULL;
4964
0
        loader_remove_logical_device(icd_term, dev, pAllocator);
4965
0
    }
4966
0
}
4967
4968
// Given the list of layers to activate in the loader_instance
4969
// structure. This function will add a VkLayerInstanceCreateInfo
4970
// structure to the VkInstanceCreateInfo.pNext pointer.
4971
// Each activated layer will have it's own VkLayerInstanceLink
4972
// structure that tells the layer what Get*ProcAddr to call to
4973
// get function pointers to the next layer down.
4974
// Once the chain info has been created this function will
4975
// execute the CreateInstance call chain. Each layer will
4976
// then have an opportunity in it's CreateInstance function
4977
// to setup it's dispatch table when the lower layer returns
4978
// successfully.
4979
// Each layer can wrap or not-wrap the returned VkInstance object
4980
// as it sees fit.
4981
// The instance chain is terminated by a loader function
4982
// that will call CreateInstance on all available ICD's and
4983
// cache those VkInstance objects for future use.
4984
VkResult loader_create_instance_chain(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator,
4985
0
                                      struct loader_instance *inst, VkInstance *created_instance) {
4986
0
    uint32_t num_activated_layers = 0;
4987
0
    struct activated_layer_info *activated_layers = NULL;
4988
0
    VkLayerInstanceCreateInfo chain_info;
4989
0
    VkLayerInstanceLink *layer_instance_link_info = NULL;
4990
0
    VkInstanceCreateInfo loader_create_info;
4991
0
    VkResult res;
4992
4993
0
    PFN_vkGetInstanceProcAddr next_gipa = loader_gpa_instance_terminator;
4994
0
    PFN_vkGetInstanceProcAddr cur_gipa = loader_gpa_instance_terminator;
4995
0
    PFN_vkGetDeviceProcAddr cur_gdpa = loader_gpa_device_terminator;
4996
0
    PFN_GetPhysicalDeviceProcAddr next_gpdpa = loader_gpdpa_instance_terminator;
4997
0
    PFN_GetPhysicalDeviceProcAddr cur_gpdpa = loader_gpdpa_instance_terminator;
4998
4999
0
    memcpy(&loader_create_info, pCreateInfo, sizeof(VkInstanceCreateInfo));
5000
5001
0
    if (inst->expanded_activated_layer_list.count > 0) {
5002
0
        chain_info.u.pLayerInfo = NULL;
5003
0
        chain_info.pNext = pCreateInfo->pNext;
5004
0
        chain_info.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
5005
0
        chain_info.function = VK_LAYER_LINK_INFO;
5006
0
        loader_create_info.pNext = &chain_info;
5007
5008
0
        layer_instance_link_info = loader_stack_alloc(sizeof(VkLayerInstanceLink) * inst->expanded_activated_layer_list.count);
5009
0
        if (!layer_instance_link_info) {
5010
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5011
0
                       "loader_create_instance_chain: Failed to alloc Instance objects for layer");
5012
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
5013
0
        }
5014
5015
0
        activated_layers = loader_stack_alloc(sizeof(struct activated_layer_info) * inst->expanded_activated_layer_list.count);
5016
0
        if (!activated_layers) {
5017
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5018
0
                       "loader_create_instance_chain: Failed to alloc activated layer storage array");
5019
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
5020
0
        }
5021
5022
        // Create instance chain of enabled layers
5023
0
        for (int32_t i = inst->expanded_activated_layer_list.count - 1; i >= 0; i--) {
5024
0
            struct loader_layer_properties *layer_prop = inst->expanded_activated_layer_list.list[i];
5025
0
            loader_platform_dl_handle lib_handle;
5026
5027
            // Skip it if a Layer with the same name has been already successfully activated
5028
0
            if (loader_names_array_has_layer_property(&layer_prop->info, num_activated_layers, activated_layers)) {
5029
0
                continue;
5030
0
            }
5031
5032
0
            lib_handle = loader_open_layer_file(inst, layer_prop);
5033
0
            if (layer_prop->lib_status == LOADER_LAYER_LIB_ERROR_OUT_OF_MEMORY) {
5034
0
                return VK_ERROR_OUT_OF_HOST_MEMORY;
5035
0
            }
5036
0
            if (!lib_handle) {
5037
0
                continue;
5038
0
            }
5039
5040
0
            if (NULL == layer_prop->functions.negotiate_layer_interface) {
5041
0
                PFN_vkNegotiateLoaderLayerInterfaceVersion negotiate_interface = NULL;
5042
0
                bool functions_in_interface = false;
5043
0
                if (!layer_prop->functions.str_negotiate_interface || strlen(layer_prop->functions.str_negotiate_interface) == 0) {
5044
0
                    negotiate_interface = (PFN_vkNegotiateLoaderLayerInterfaceVersion)loader_platform_get_proc_address(
5045
0
                        lib_handle, "vkNegotiateLoaderLayerInterfaceVersion");
5046
0
                } else {
5047
0
                    negotiate_interface = (PFN_vkNegotiateLoaderLayerInterfaceVersion)loader_platform_get_proc_address(
5048
0
                        lib_handle, layer_prop->functions.str_negotiate_interface);
5049
0
                }
5050
5051
                // If we can negotiate an interface version, then we can also
5052
                // get everything we need from the one function call, so try
5053
                // that first, and see if we can get all the function pointers
5054
                // necessary from that one call.
5055
0
                if (NULL != negotiate_interface) {
5056
0
                    layer_prop->functions.negotiate_layer_interface = negotiate_interface;
5057
5058
0
                    VkNegotiateLayerInterface interface_struct;
5059
5060
0
                    if (loader_get_layer_interface_version(negotiate_interface, &interface_struct)) {
5061
                        // Go ahead and set the properties version to the
5062
                        // correct value.
5063
0
                        layer_prop->interface_version = interface_struct.loaderLayerInterfaceVersion;
5064
5065
                        // If the interface is 2 or newer, we have access to the
5066
                        // new GetPhysicalDeviceProcAddr function, so grab it,
5067
                        // and the other necessary functions, from the
5068
                        // structure.
5069
0
                        if (interface_struct.loaderLayerInterfaceVersion > 1) {
5070
0
                            cur_gipa = interface_struct.pfnGetInstanceProcAddr;
5071
0
                            cur_gdpa = interface_struct.pfnGetDeviceProcAddr;
5072
0
                            cur_gpdpa = interface_struct.pfnGetPhysicalDeviceProcAddr;
5073
0
                            if (cur_gipa != NULL) {
5074
                                // We've set the functions, so make sure we
5075
                                // don't do the unnecessary calls later.
5076
0
                                functions_in_interface = true;
5077
0
                            }
5078
0
                        }
5079
0
                    }
5080
0
                }
5081
5082
0
                if (!functions_in_interface) {
5083
0
                    if ((cur_gipa = layer_prop->functions.get_instance_proc_addr) == NULL) {
5084
0
                        if (layer_prop->functions.str_gipa == NULL || strlen(layer_prop->functions.str_gipa) == 0) {
5085
0
                            cur_gipa =
5086
0
                                (PFN_vkGetInstanceProcAddr)loader_platform_get_proc_address(lib_handle, "vkGetInstanceProcAddr");
5087
0
                            layer_prop->functions.get_instance_proc_addr = cur_gipa;
5088
5089
0
                            if (NULL == cur_gipa) {
5090
0
                                loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
5091
0
                                           "loader_create_instance_chain: Failed to find \'vkGetInstanceProcAddr\' in layer \"%s\"",
5092
0
                                           layer_prop->lib_name);
5093
0
                                continue;
5094
0
                            }
5095
0
                        } else {
5096
0
                            cur_gipa = (PFN_vkGetInstanceProcAddr)loader_platform_get_proc_address(lib_handle,
5097
0
                                                                                                   layer_prop->functions.str_gipa);
5098
5099
0
                            if (NULL == cur_gipa) {
5100
0
                                loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
5101
0
                                           "loader_create_instance_chain: Failed to find \'%s\' in layer \"%s\"",
5102
0
                                           layer_prop->functions.str_gipa, layer_prop->lib_name);
5103
0
                                continue;
5104
0
                            }
5105
0
                        }
5106
0
                    }
5107
0
                }
5108
0
            }
5109
5110
0
            layer_instance_link_info[num_activated_layers].pNext = chain_info.u.pLayerInfo;
5111
0
            layer_instance_link_info[num_activated_layers].pfnNextGetInstanceProcAddr = next_gipa;
5112
0
            layer_instance_link_info[num_activated_layers].pfnNextGetPhysicalDeviceProcAddr = next_gpdpa;
5113
0
            next_gipa = cur_gipa;
5114
0
            if (layer_prop->interface_version > 1 && cur_gpdpa != NULL) {
5115
0
                layer_prop->functions.get_physical_device_proc_addr = cur_gpdpa;
5116
0
                next_gpdpa = cur_gpdpa;
5117
0
            }
5118
0
            if (layer_prop->interface_version > 1 && cur_gipa != NULL) {
5119
0
                layer_prop->functions.get_instance_proc_addr = cur_gipa;
5120
0
            }
5121
0
            if (layer_prop->interface_version > 1 && cur_gdpa != NULL) {
5122
0
                layer_prop->functions.get_device_proc_addr = cur_gdpa;
5123
0
            }
5124
5125
0
            chain_info.u.pLayerInfo = &layer_instance_link_info[num_activated_layers];
5126
5127
0
            res = fixup_library_binary_path(inst, &(layer_prop->lib_name), layer_prop->lib_handle, cur_gipa);
5128
0
            if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
5129
0
                return res;
5130
0
            }
5131
5132
0
            activated_layers[num_activated_layers].name = layer_prop->info.layerName;
5133
0
            activated_layers[num_activated_layers].manifest = layer_prop->manifest_file_name;
5134
0
            activated_layers[num_activated_layers].library = layer_prop->lib_name;
5135
0
            activated_layers[num_activated_layers].is_implicit = !(layer_prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER);
5136
0
            activated_layers[num_activated_layers].enabled_by_what = layer_prop->enabled_by_what;
5137
0
            if (activated_layers[num_activated_layers].is_implicit) {
5138
0
                activated_layers[num_activated_layers].disable_env = layer_prop->disable_env_var.name;
5139
0
                activated_layers[num_activated_layers].enable_name_env = layer_prop->enable_env_var.name;
5140
0
                activated_layers[num_activated_layers].enable_value_env = layer_prop->enable_env_var.value;
5141
0
            }
5142
5143
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Insert instance layer \"%s\" (%s)",
5144
0
                       layer_prop->info.layerName, layer_prop->lib_name);
5145
5146
0
            num_activated_layers++;
5147
0
        }
5148
0
    }
5149
5150
    // Make sure each layer requested by the application was actually loaded
5151
0
    for (uint32_t exp = 0; exp < inst->expanded_activated_layer_list.count; ++exp) {
5152
0
        struct loader_layer_properties *exp_layer_prop = inst->expanded_activated_layer_list.list[exp];
5153
0
        bool found = false;
5154
0
        for (uint32_t act = 0; act < num_activated_layers; ++act) {
5155
0
            if (!strcmp(activated_layers[act].name, exp_layer_prop->info.layerName)) {
5156
0
                found = true;
5157
0
                break;
5158
0
            }
5159
0
        }
5160
        // If it wasn't found, we want to at least log an error.  However, if it was enabled by the application directly,
5161
        // we want to return a bad layer error.
5162
0
        if (!found) {
5163
0
            bool app_requested = false;
5164
0
            for (uint32_t act = 0; act < pCreateInfo->enabledLayerCount; ++act) {
5165
0
                if (!strcmp(pCreateInfo->ppEnabledLayerNames[act], exp_layer_prop->info.layerName)) {
5166
0
                    app_requested = true;
5167
0
                    break;
5168
0
                }
5169
0
            }
5170
0
            VkFlags log_flag = VULKAN_LOADER_LAYER_BIT;
5171
0
            char ending = '.';
5172
0
            if (app_requested) {
5173
0
                log_flag |= VULKAN_LOADER_ERROR_BIT;
5174
0
                ending = '!';
5175
0
            } else {
5176
0
                log_flag |= VULKAN_LOADER_INFO_BIT;
5177
0
            }
5178
0
            switch (exp_layer_prop->lib_status) {
5179
0
                case LOADER_LAYER_LIB_NOT_LOADED:
5180
0
                    loader_log(inst, log_flag, 0, "Requested layer \"%s\" was not loaded%c", exp_layer_prop->info.layerName,
5181
0
                               ending);
5182
0
                    break;
5183
0
                case LOADER_LAYER_LIB_ERROR_WRONG_BIT_TYPE: {
5184
0
                    loader_log(inst, log_flag, 0, "Requested layer \"%s\" was wrong bit-type%c", exp_layer_prop->info.layerName,
5185
0
                               ending);
5186
0
                    break;
5187
0
                }
5188
0
                case LOADER_LAYER_LIB_ERROR_FAILED_TO_LOAD:
5189
0
                    loader_log(inst, log_flag, 0, "Requested layer \"%s\" failed to load%c", exp_layer_prop->info.layerName,
5190
0
                               ending);
5191
0
                    break;
5192
0
                case LOADER_LAYER_LIB_SUCCESS_LOADED:
5193
0
                case LOADER_LAYER_LIB_ERROR_OUT_OF_MEMORY:
5194
                    // Shouldn't be able to reach this but if it is, best to report a debug
5195
0
                    loader_log(inst, log_flag, 0,
5196
0
                               "Shouldn't reach this. A valid version of requested layer %s was loaded but was not found in the "
5197
0
                               "list of activated layers%c",
5198
0
                               exp_layer_prop->info.layerName, ending);
5199
0
                    break;
5200
0
            }
5201
0
            if (app_requested) {
5202
0
                return VK_ERROR_LAYER_NOT_PRESENT;
5203
0
            }
5204
0
        }
5205
0
    }
5206
5207
0
    VkLoaderFeatureFlags feature_flags = 0;
5208
#if defined(_WIN32)
5209
    feature_flags = windows_initialize_dxgi();
5210
#endif
5211
5212
    // The following line of code is actually invalid at least according to the Vulkan spec with header update 1.2.193 and onwards.
5213
    // The update required calls to vkGetInstanceProcAddr querying "global" functions (which includes vkCreateInstance) to pass NULL
5214
    // for the instance parameter. Because it wasn't required to be NULL before, there may be layers which expect the loader's
5215
    // behavior of passing a non-NULL value into vkGetInstanceProcAddr.
5216
    // In an abundance of caution, the incorrect code remains as is, with a big comment to indicate that its wrong
5217
0
    PFN_vkCreateInstance fpCreateInstance = (PFN_vkCreateInstance)next_gipa(*created_instance, "vkCreateInstance");
5218
0
    if (fpCreateInstance) {
5219
0
        VkLayerInstanceCreateInfo instance_dispatch;
5220
0
        instance_dispatch.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
5221
0
        instance_dispatch.pNext = loader_create_info.pNext;
5222
0
        instance_dispatch.function = VK_LOADER_DATA_CALLBACK;
5223
0
        instance_dispatch.u.pfnSetInstanceLoaderData = vkSetInstanceDispatch;
5224
5225
0
        VkLayerInstanceCreateInfo device_callback;
5226
0
        device_callback.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
5227
0
        device_callback.pNext = &instance_dispatch;
5228
0
        device_callback.function = VK_LOADER_LAYER_CREATE_DEVICE_CALLBACK;
5229
0
        device_callback.u.layerDevice.pfnLayerCreateDevice = loader_layer_create_device;
5230
0
        device_callback.u.layerDevice.pfnLayerDestroyDevice = loader_layer_destroy_device;
5231
5232
0
        VkLayerInstanceCreateInfo loader_features;
5233
0
        loader_features.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
5234
0
        loader_features.pNext = &device_callback;
5235
0
        loader_features.function = VK_LOADER_FEATURES;
5236
0
        loader_features.u.loaderFeatures = feature_flags;
5237
5238
0
        loader_create_info.pNext = &loader_features;
5239
5240
        // If layer debugging is enabled, let's print out the full callstack with layers in their
5241
        // defined order.
5242
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "vkCreateInstance layer callstack setup to:");
5243
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   <Application>");
5244
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "     ||");
5245
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   <Loader>");
5246
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "     ||");
5247
0
        for (uint32_t cur_layer = 0; cur_layer < num_activated_layers; ++cur_layer) {
5248
0
            uint32_t index = num_activated_layers - cur_layer - 1;
5249
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   %s", activated_layers[index].name);
5250
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Type: %s",
5251
0
                       activated_layers[index].is_implicit ? "Implicit" : "Explicit");
5252
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Enabled By: %s",
5253
0
                       get_enabled_by_what_str(activated_layers[index].enabled_by_what));
5254
0
            if (activated_layers[index].is_implicit) {
5255
0
                loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "               Disable Env Var:  %s",
5256
0
                           activated_layers[index].disable_env);
5257
0
                if (activated_layers[index].enable_name_env) {
5258
0
                    loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0,
5259
0
                               "               This layer was enabled because Env Var %s was set to Value %s",
5260
0
                               activated_layers[index].enable_name_env, activated_layers[index].enable_value_env);
5261
0
                }
5262
0
            }
5263
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Manifest: %s", activated_layers[index].manifest);
5264
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Library:  %s", activated_layers[index].library);
5265
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "     ||");
5266
0
        }
5267
0
        loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   <Drivers>");
5268
5269
0
        res = fpCreateInstance(&loader_create_info, pAllocator, created_instance);
5270
0
    } else {
5271
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0, "loader_create_instance_chain: Failed to find \'vkCreateInstance\'");
5272
        // Couldn't find CreateInstance function!
5273
0
        res = VK_ERROR_INITIALIZATION_FAILED;
5274
0
    }
5275
5276
0
    if (res == VK_SUCCESS) {
5277
        // Copy the current disp table into the terminator_dispatch table so we can use it in loader_gpa_instance_terminator()
5278
0
        memcpy(&inst->terminator_dispatch, &inst->disp->layer_inst_disp, sizeof(VkLayerInstanceDispatchTable));
5279
5280
0
        loader_init_instance_core_dispatch_table(&inst->disp->layer_inst_disp, next_gipa, *created_instance);
5281
0
        inst->instance = *created_instance;
5282
5283
0
        if (pCreateInfo->enabledLayerCount > 0 && pCreateInfo->ppEnabledLayerNames != NULL) {
5284
0
            res = create_string_list(inst, pCreateInfo->enabledLayerCount, &inst->enabled_layer_names);
5285
0
            if (res != VK_SUCCESS) {
5286
0
                return res;
5287
0
            }
5288
5289
0
            for (uint32_t i = 0; i < pCreateInfo->enabledLayerCount; ++i) {
5290
0
                res = copy_str_to_string_list(inst, &inst->enabled_layer_names, pCreateInfo->ppEnabledLayerNames[i],
5291
0
                                              strlen(pCreateInfo->ppEnabledLayerNames[i]));
5292
0
                if (res != VK_SUCCESS) return res;
5293
0
            }
5294
0
        }
5295
0
    }
5296
5297
0
    return res;
5298
0
}
5299
5300
0
void loader_activate_instance_layer_extensions(struct loader_instance *inst, VkInstance created_inst) {
5301
0
    loader_init_instance_extension_dispatch_table(&inst->disp->layer_inst_disp, inst->disp->layer_inst_disp.GetInstanceProcAddr,
5302
0
                                                  created_inst);
5303
0
}
5304
5305
#if defined(__APPLE__)
5306
VkResult loader_create_device_chain(const VkPhysicalDevice pd, const VkDeviceCreateInfo *pCreateInfo,
5307
                                    const VkAllocationCallbacks *pAllocator, const struct loader_instance *inst,
5308
                                    struct loader_device *dev, PFN_vkGetInstanceProcAddr callingLayer,
5309
                                    PFN_vkGetDeviceProcAddr *layerNextGDPA) __attribute__((optnone)) {
5310
#else
5311
VkResult loader_create_device_chain(const VkPhysicalDevice pd, const VkDeviceCreateInfo *pCreateInfo,
5312
                                    const VkAllocationCallbacks *pAllocator, const struct loader_instance *inst,
5313
                                    struct loader_device *dev, PFN_vkGetInstanceProcAddr callingLayer,
5314
0
                                    PFN_vkGetDeviceProcAddr *layerNextGDPA) {
5315
0
#endif
5316
0
    uint32_t num_activated_layers = 0;
5317
0
    struct activated_layer_info *activated_layers = NULL;
5318
0
    VkLayerDeviceLink *layer_device_link_info;
5319
0
    VkLayerDeviceCreateInfo chain_info;
5320
0
    VkDeviceCreateInfo loader_create_info;
5321
0
    VkDeviceGroupDeviceCreateInfo *original_device_group_create_info_struct = NULL;
5322
0
    VkResult res;
5323
5324
0
    PFN_vkGetDeviceProcAddr fpGDPA = NULL, nextGDPA = loader_gpa_device_terminator;
5325
0
    PFN_vkGetInstanceProcAddr fpGIPA = NULL, nextGIPA = loader_gpa_instance_terminator;
5326
5327
0
    memcpy(&loader_create_info, pCreateInfo, sizeof(VkDeviceCreateInfo));
5328
5329
0
    if (loader_create_info.enabledLayerCount > 0 && loader_create_info.ppEnabledLayerNames != NULL) {
5330
0
        bool invalid_device_layer_usage = false;
5331
5332
0
        if (loader_create_info.enabledLayerCount != inst->enabled_layer_names.count && loader_create_info.enabledLayerCount > 0) {
5333
0
            invalid_device_layer_usage = true;
5334
0
        } else if (loader_create_info.enabledLayerCount > 0 && loader_create_info.ppEnabledLayerNames == NULL) {
5335
0
            invalid_device_layer_usage = true;
5336
0
        } else if (loader_create_info.enabledLayerCount == 0 && loader_create_info.ppEnabledLayerNames != NULL) {
5337
0
            invalid_device_layer_usage = true;
5338
0
        } else if (inst->enabled_layer_names.list != NULL) {
5339
0
            for (uint32_t i = 0; i < loader_create_info.enabledLayerCount; i++) {
5340
0
                const char *device_layer_names = loader_create_info.ppEnabledLayerNames[i];
5341
5342
0
                if (strcmp(device_layer_names, inst->enabled_layer_names.list[i]) != 0) {
5343
0
                    invalid_device_layer_usage = true;
5344
0
                    break;
5345
0
                }
5346
0
            }
5347
0
        }
5348
5349
0
        if (invalid_device_layer_usage) {
5350
0
            loader_log(
5351
0
                inst, VULKAN_LOADER_WARN_BIT, 0,
5352
0
                "loader_create_device_chain: Using deprecated and ignored 'ppEnabledLayerNames' member of 'VkDeviceCreateInfo' "
5353
0
                "when creating a Vulkan device.");
5354
0
        }
5355
0
    }
5356
5357
    // Before we continue, we need to find out if the KHR_device_group extension is in the enabled list.  If it is, we then
5358
    // need to look for the corresponding VkDeviceGroupDeviceCreateInfo struct in the device list.  This is because we
5359
    // need to replace all the incoming physical device values (which are really loader trampoline physical device values)
5360
    // with the layer/ICD version.
5361
0
    {
5362
0
        VkBaseOutStructure *pNext = (VkBaseOutStructure *)loader_create_info.pNext;
5363
0
        VkBaseOutStructure *pPrev = (VkBaseOutStructure *)&loader_create_info;
5364
0
        while (NULL != pNext) {
5365
0
            if (VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO == pNext->sType) {
5366
0
                VkDeviceGroupDeviceCreateInfo *cur_struct = (VkDeviceGroupDeviceCreateInfo *)pNext;
5367
0
                if (0 < cur_struct->physicalDeviceCount && NULL != cur_struct->pPhysicalDevices) {
5368
0
                    VkDeviceGroupDeviceCreateInfo *temp_struct = loader_stack_alloc(sizeof(VkDeviceGroupDeviceCreateInfo));
5369
0
                    VkPhysicalDevice *phys_dev_array = NULL;
5370
0
                    if (NULL == temp_struct) {
5371
0
                        return VK_ERROR_OUT_OF_HOST_MEMORY;
5372
0
                    }
5373
0
                    memcpy(temp_struct, cur_struct, sizeof(VkDeviceGroupDeviceCreateInfo));
5374
0
                    phys_dev_array = loader_stack_alloc(sizeof(VkPhysicalDevice) * cur_struct->physicalDeviceCount);
5375
0
                    if (NULL == phys_dev_array) {
5376
0
                        return VK_ERROR_OUT_OF_HOST_MEMORY;
5377
0
                    }
5378
5379
                    // Before calling down, replace the incoming physical device values (which are really loader trampoline
5380
                    // physical devices) with the next layer (or possibly even the terminator) physical device values.
5381
0
                    struct loader_physical_device_tramp *cur_tramp;
5382
0
                    for (uint32_t phys_dev = 0; phys_dev < cur_struct->physicalDeviceCount; phys_dev++) {
5383
0
                        cur_tramp = (struct loader_physical_device_tramp *)cur_struct->pPhysicalDevices[phys_dev];
5384
0
                        phys_dev_array[phys_dev] = cur_tramp->phys_dev;
5385
0
                    }
5386
0
                    temp_struct->pPhysicalDevices = phys_dev_array;
5387
5388
0
                    original_device_group_create_info_struct = (VkDeviceGroupDeviceCreateInfo *)pPrev->pNext;
5389
5390
                    // Replace the old struct in the pNext chain with this one.
5391
0
                    pPrev->pNext = (VkBaseOutStructure *)temp_struct;
5392
0
                }
5393
0
                break;
5394
0
            }
5395
5396
0
            pPrev = pNext;
5397
0
            pNext = pNext->pNext;
5398
0
        }
5399
0
    }
5400
0
    if (inst->expanded_activated_layer_list.count > 0) {
5401
0
        layer_device_link_info = loader_stack_alloc(sizeof(VkLayerDeviceLink) * inst->expanded_activated_layer_list.count);
5402
0
        if (!layer_device_link_info) {
5403
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5404
0
                       "loader_create_device_chain: Failed to alloc Device objects for layer. Skipping Layer.");
5405
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
5406
0
        }
5407
5408
0
        activated_layers = loader_stack_alloc(sizeof(struct activated_layer_info) * inst->expanded_activated_layer_list.count);
5409
0
        if (!activated_layers) {
5410
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5411
0
                       "loader_create_device_chain: Failed to alloc activated layer storage array");
5412
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
5413
0
        }
5414
5415
0
        chain_info.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
5416
0
        chain_info.function = VK_LAYER_LINK_INFO;
5417
0
        chain_info.u.pLayerInfo = NULL;
5418
0
        chain_info.pNext = loader_create_info.pNext;
5419
0
        loader_create_info.pNext = &chain_info;
5420
5421
        // Create instance chain of enabled layers
5422
0
        for (int32_t i = inst->expanded_activated_layer_list.count - 1; i >= 0; i--) {
5423
0
            struct loader_layer_properties *layer_prop = inst->expanded_activated_layer_list.list[i];
5424
0
            loader_platform_dl_handle lib_handle = layer_prop->lib_handle;
5425
5426
            // Skip it if a Layer with the same name has been already successfully activated
5427
0
            if (loader_names_array_has_layer_property(&layer_prop->info, num_activated_layers, activated_layers)) {
5428
0
                continue;
5429
0
            }
5430
5431
            // Skip the layer if the handle is NULL - this is likely because the library failed to load but wasn't removed from
5432
            // the list.
5433
0
            if (!lib_handle) {
5434
0
                continue;
5435
0
            }
5436
5437
            // The Get*ProcAddr pointers will already be filled in if they were received from either the json file or the
5438
            // version negotiation
5439
0
            if ((fpGIPA = layer_prop->functions.get_instance_proc_addr) == NULL) {
5440
0
                if (layer_prop->functions.str_gipa == NULL || strlen(layer_prop->functions.str_gipa) == 0) {
5441
0
                    fpGIPA = (PFN_vkGetInstanceProcAddr)loader_platform_get_proc_address(lib_handle, "vkGetInstanceProcAddr");
5442
0
                    layer_prop->functions.get_instance_proc_addr = fpGIPA;
5443
0
                } else
5444
0
                    fpGIPA =
5445
0
                        (PFN_vkGetInstanceProcAddr)loader_platform_get_proc_address(lib_handle, layer_prop->functions.str_gipa);
5446
0
                if (!fpGIPA) {
5447
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
5448
0
                               "loader_create_device_chain: Failed to find \'vkGetInstanceProcAddr\' in layer \"%s\".  "
5449
0
                               "Skipping layer.",
5450
0
                               layer_prop->lib_name);
5451
0
                    continue;
5452
0
                }
5453
0
            }
5454
5455
0
            if (fpGIPA == callingLayer) {
5456
0
                if (layerNextGDPA != NULL) {
5457
0
                    *layerNextGDPA = nextGDPA;
5458
0
                }
5459
                // Break here because if fpGIPA is the same as callingLayer, that means a layer is trying to create a device,
5460
                // and once we don't want to continue any further as the next layer will be the calling layer
5461
0
                break;
5462
0
            }
5463
5464
0
            if ((fpGDPA = layer_prop->functions.get_device_proc_addr) == NULL) {
5465
0
                if (layer_prop->functions.str_gdpa == NULL || strlen(layer_prop->functions.str_gdpa) == 0) {
5466
0
                    fpGDPA = (PFN_vkGetDeviceProcAddr)loader_platform_get_proc_address(lib_handle, "vkGetDeviceProcAddr");
5467
0
                    layer_prop->functions.get_device_proc_addr = fpGDPA;
5468
0
                } else
5469
0
                    fpGDPA = (PFN_vkGetDeviceProcAddr)loader_platform_get_proc_address(lib_handle, layer_prop->functions.str_gdpa);
5470
0
                if (!fpGDPA) {
5471
0
                    loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0,
5472
0
                               "Failed to find vkGetDeviceProcAddr in layer \"%s\"", layer_prop->lib_name);
5473
0
                    continue;
5474
0
                }
5475
0
            }
5476
5477
0
            layer_device_link_info[num_activated_layers].pNext = chain_info.u.pLayerInfo;
5478
0
            layer_device_link_info[num_activated_layers].pfnNextGetInstanceProcAddr = nextGIPA;
5479
0
            layer_device_link_info[num_activated_layers].pfnNextGetDeviceProcAddr = nextGDPA;
5480
0
            chain_info.u.pLayerInfo = &layer_device_link_info[num_activated_layers];
5481
0
            nextGIPA = fpGIPA;
5482
0
            nextGDPA = fpGDPA;
5483
5484
0
            activated_layers[num_activated_layers].name = layer_prop->info.layerName;
5485
0
            activated_layers[num_activated_layers].manifest = layer_prop->manifest_file_name;
5486
0
            activated_layers[num_activated_layers].library = layer_prop->lib_name;
5487
0
            activated_layers[num_activated_layers].is_implicit = !(layer_prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER);
5488
0
            activated_layers[num_activated_layers].enabled_by_what = layer_prop->enabled_by_what;
5489
0
            if (activated_layers[num_activated_layers].is_implicit) {
5490
0
                activated_layers[num_activated_layers].disable_env = layer_prop->disable_env_var.name;
5491
0
            }
5492
5493
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_LAYER_BIT, 0, "Inserted device layer \"%s\" (%s)",
5494
0
                       layer_prop->info.layerName, layer_prop->lib_name);
5495
5496
0
            num_activated_layers++;
5497
0
        }
5498
0
    }
5499
5500
0
    VkDevice created_device = (VkDevice)dev;
5501
0
    PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)nextGIPA(inst->instance, "vkCreateDevice");
5502
0
    if (fpCreateDevice) {
5503
0
        VkLayerDeviceCreateInfo create_info_disp;
5504
5505
0
        create_info_disp.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
5506
0
        create_info_disp.function = VK_LOADER_DATA_CALLBACK;
5507
5508
0
        create_info_disp.u.pfnSetDeviceLoaderData = vkSetDeviceDispatch;
5509
5510
        // If layer debugging is enabled, let's print out the full callstack with layers in their
5511
        // defined order.
5512
0
        uint32_t layer_driver_bits = VULKAN_LOADER_LAYER_BIT | VULKAN_LOADER_DRIVER_BIT;
5513
0
        loader_log(inst, layer_driver_bits, 0, "vkCreateDevice layer callstack setup to:");
5514
0
        loader_log(inst, layer_driver_bits, 0, "   <Application>");
5515
0
        loader_log(inst, layer_driver_bits, 0, "     ||");
5516
0
        loader_log(inst, layer_driver_bits, 0, "   <Loader>");
5517
0
        loader_log(inst, layer_driver_bits, 0, "     ||");
5518
0
        for (uint32_t cur_layer = 0; cur_layer < num_activated_layers; ++cur_layer) {
5519
0
            uint32_t index = num_activated_layers - cur_layer - 1;
5520
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "   %s", activated_layers[index].name);
5521
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Type: %s",
5522
0
                       activated_layers[index].is_implicit ? "Implicit" : "Explicit");
5523
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Enabled By: %s",
5524
0
                       get_enabled_by_what_str(activated_layers[index].enabled_by_what));
5525
0
            if (activated_layers[index].is_implicit) {
5526
0
                loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "               Disable Env Var:  %s",
5527
0
                           activated_layers[index].disable_env);
5528
0
            }
5529
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Manifest: %s", activated_layers[index].manifest);
5530
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "           Library:  %s", activated_layers[index].library);
5531
0
            loader_log(inst, VULKAN_LOADER_LAYER_BIT, 0, "     ||");
5532
0
        }
5533
0
        loader_log(inst, layer_driver_bits, 0, "   <Device>");
5534
0
        create_info_disp.pNext = loader_create_info.pNext;
5535
0
        loader_create_info.pNext = &create_info_disp;
5536
0
        res = fpCreateDevice(pd, &loader_create_info, pAllocator, &created_device);
5537
0
        if (res != VK_SUCCESS) {
5538
0
            return res;
5539
0
        }
5540
0
        dev->chain_device = created_device;
5541
5542
        // Because we changed the pNext chain to use our own VkDeviceGroupDeviceCreateInfo, we need to fixup the chain to
5543
        // point back at the original VkDeviceGroupDeviceCreateInfo.
5544
0
        VkBaseOutStructure *pNext = (VkBaseOutStructure *)loader_create_info.pNext;
5545
0
        VkBaseOutStructure *pPrev = (VkBaseOutStructure *)&loader_create_info;
5546
0
        while (NULL != pNext) {
5547
0
            if (VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO == pNext->sType) {
5548
0
                VkDeviceGroupDeviceCreateInfo *cur_struct = (VkDeviceGroupDeviceCreateInfo *)pNext;
5549
0
                if (0 < cur_struct->physicalDeviceCount && NULL != cur_struct->pPhysicalDevices) {
5550
0
                    pPrev->pNext = (VkBaseOutStructure *)original_device_group_create_info_struct;
5551
0
                }
5552
0
                break;
5553
0
            }
5554
5555
0
            pPrev = pNext;
5556
0
            pNext = pNext->pNext;
5557
0
        }
5558
5559
0
    } else {
5560
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5561
0
                   "loader_create_device_chain: Failed to find \'vkCreateDevice\' in layers or ICD");
5562
        // Couldn't find CreateDevice function!
5563
0
        return VK_ERROR_INITIALIZATION_FAILED;
5564
0
    }
5565
5566
    // Initialize device dispatch table
5567
0
    loader_init_device_dispatch_table(&dev->loader_dispatch, nextGDPA, dev->chain_device);
5568
    // Initialize the dispatch table to functions which need terminators
5569
    // These functions point directly to the driver, not the terminator functions
5570
0
    init_extension_device_proc_terminator_dispatch(dev);
5571
5572
0
    return res;
5573
0
}
5574
5575
VkResult loader_validate_layers(const struct loader_instance *inst, const uint32_t layer_count,
5576
0
                                const char *const *ppEnabledLayerNames, const struct loader_layer_list *list) {
5577
0
    struct loader_layer_properties *prop;
5578
5579
0
    if (layer_count > 0 && ppEnabledLayerNames == NULL) {
5580
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5581
0
                   "loader_validate_layers: ppEnabledLayerNames is NULL but enabledLayerCount is greater than zero");
5582
0
        return VK_ERROR_LAYER_NOT_PRESENT;
5583
0
    }
5584
5585
0
    for (uint32_t i = 0; i < layer_count; i++) {
5586
0
        VkStringErrorFlags result = vk_string_validate(MaxLoaderStringLength, ppEnabledLayerNames[i]);
5587
0
        if (result != VK_STRING_ERROR_NONE) {
5588
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5589
0
                       "loader_validate_layers: ppEnabledLayerNames contains string that is too long or is badly formed");
5590
0
            return VK_ERROR_LAYER_NOT_PRESENT;
5591
0
        }
5592
5593
0
        prop = loader_find_layer_property(ppEnabledLayerNames[i], list);
5594
0
        if (NULL == prop) {
5595
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5596
0
                       "loader_validate_layers: Layer %d does not exist in the list of available layers", i);
5597
0
            return VK_ERROR_LAYER_NOT_PRESENT;
5598
0
        }
5599
0
        if (inst->settings.settings_active && inst->settings.layer_configurations_active &&
5600
0
            prop->settings_control_value != LOADER_SETTINGS_LAYER_CONTROL_ON &&
5601
0
            prop->settings_control_value != LOADER_SETTINGS_LAYER_CONTROL_DEFAULT) {
5602
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5603
0
                       "loader_validate_layers: Layer %d was explicitly prevented from being enabled by the loader settings file",
5604
0
                       i);
5605
0
            return VK_ERROR_LAYER_NOT_PRESENT;
5606
0
        }
5607
0
    }
5608
0
    return VK_SUCCESS;
5609
0
}
5610
5611
VkResult loader_validate_instance_extensions(struct loader_instance *inst, const struct loader_extension_list *icd_exts,
5612
                                             const struct loader_layer_list *instance_layers,
5613
                                             const struct loader_envvar_all_filters *layer_filters,
5614
0
                                             const VkInstanceCreateInfo *pCreateInfo) {
5615
0
    VkExtensionProperties *extension_prop;
5616
0
    char *env_value;
5617
0
    char *enabled_layers_env = NULL;
5618
0
    bool check_if_known = true;
5619
0
    VkResult res = VK_SUCCESS;
5620
5621
0
    struct loader_pointer_layer_list active_layers = {0};
5622
0
    struct loader_pointer_layer_list expanded_layers = {0};
5623
5624
0
    if (pCreateInfo->enabledExtensionCount > 0 && pCreateInfo->ppEnabledExtensionNames == NULL) {
5625
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5626
0
                   "loader_validate_instance_extensions: Instance ppEnabledExtensionNames is NULL but enabledExtensionCount is "
5627
0
                   "greater than zero");
5628
0
        return VK_ERROR_EXTENSION_NOT_PRESENT;
5629
0
    }
5630
0
    if (!loader_init_pointer_layer_list(inst, &active_layers)) {
5631
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
5632
0
        goto out;
5633
0
    }
5634
0
    if (!loader_init_pointer_layer_list(inst, &expanded_layers)) {
5635
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
5636
0
        goto out;
5637
0
    }
5638
5639
0
    if (inst->settings.settings_active && inst->settings.layer_configurations_active) {
5640
0
        res = enable_correct_layers_from_settings(inst, layer_filters, pCreateInfo->enabledLayerCount,
5641
0
                                                  pCreateInfo->ppEnabledLayerNames, instance_layers, &active_layers,
5642
0
                                                  &expanded_layers);
5643
0
        if (res != VK_SUCCESS) {
5644
0
            goto out;
5645
0
        }
5646
0
    } else {
5647
0
        enabled_layers_env = loader_getenv(ENABLED_LAYERS_ENV, inst);
5648
5649
        // Build the lists of active layers (including meta layers) and expanded layers (with meta layers resolved to their
5650
        // components)
5651
0
        res =
5652
0
            loader_add_implicit_layers(inst, enabled_layers_env, layer_filters, &active_layers, &expanded_layers, instance_layers);
5653
0
        if (res != VK_SUCCESS) {
5654
0
            goto out;
5655
0
        }
5656
0
        res = loader_add_environment_layers(inst, enabled_layers_env, layer_filters, &active_layers, &expanded_layers,
5657
0
                                            instance_layers);
5658
0
        if (res != VK_SUCCESS) {
5659
0
            goto out;
5660
0
        }
5661
0
        res = loader_add_layer_names_to_list(inst, layer_filters, &active_layers, &expanded_layers, pCreateInfo->enabledLayerCount,
5662
0
                                             pCreateInfo->ppEnabledLayerNames, instance_layers);
5663
0
        if (VK_SUCCESS != res) {
5664
0
            goto out;
5665
0
        }
5666
0
    }
5667
0
    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
5668
0
        VkStringErrorFlags result = vk_string_validate(MaxLoaderStringLength, pCreateInfo->ppEnabledExtensionNames[i]);
5669
0
        if (result != VK_STRING_ERROR_NONE) {
5670
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5671
0
                       "loader_validate_instance_extensions: Instance ppEnabledExtensionNames contains "
5672
0
                       "string that is too long or is badly formed");
5673
0
            res = VK_ERROR_EXTENSION_NOT_PRESENT;
5674
0
            goto out;
5675
0
        }
5676
5677
        // Check if a user wants to disable the instance extension filtering behavior
5678
0
        env_value = loader_getenv("VK_LOADER_DISABLE_INST_EXT_FILTER", inst);
5679
0
        if (NULL != env_value && atoi(env_value) != 0) {
5680
0
            check_if_known = false;
5681
0
        }
5682
0
        loader_free_getenv(env_value, inst);
5683
5684
0
        if (check_if_known) {
5685
            // See if the extension is in the list of supported extensions
5686
0
            bool found = false;
5687
0
            for (uint32_t j = 0; LOADER_INSTANCE_EXTENSIONS[j] != NULL; j++) {
5688
0
                if (strcmp(pCreateInfo->ppEnabledExtensionNames[i], LOADER_INSTANCE_EXTENSIONS[j]) == 0) {
5689
0
                    found = true;
5690
0
                    break;
5691
0
                }
5692
0
            }
5693
5694
            // If it isn't in the list, return an error
5695
0
            if (!found) {
5696
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5697
0
                           "loader_validate_instance_extensions: Extension %s not found in list of known instance extensions.",
5698
0
                           pCreateInfo->ppEnabledExtensionNames[i]);
5699
0
                res = VK_ERROR_EXTENSION_NOT_PRESENT;
5700
0
                goto out;
5701
0
            }
5702
0
        }
5703
5704
0
        extension_prop = get_extension_property(pCreateInfo->ppEnabledExtensionNames[i], icd_exts);
5705
5706
0
        if (extension_prop) {
5707
0
            continue;
5708
0
        }
5709
5710
0
        extension_prop = NULL;
5711
5712
        // Not in global list, search layer extension lists
5713
0
        for (uint32_t j = 0; NULL == extension_prop && j < expanded_layers.count; ++j) {
5714
0
            extension_prop =
5715
0
                get_extension_property(pCreateInfo->ppEnabledExtensionNames[i], &expanded_layers.list[j]->instance_extension_list);
5716
0
            if (extension_prop) {
5717
                // Found the extension in one of the layers enabled by the app.
5718
0
                break;
5719
0
            }
5720
5721
0
            struct loader_layer_properties *layer_prop =
5722
0
                loader_find_layer_property(expanded_layers.list[j]->info.layerName, instance_layers);
5723
0
            if (NULL == layer_prop) {
5724
                // Should NOT get here, loader_validate_layers should have already filtered this case out.
5725
0
                continue;
5726
0
            }
5727
0
        }
5728
5729
0
        if (!extension_prop) {
5730
            // Didn't find extension name in any of the global layers, error out
5731
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
5732
0
                       "loader_validate_instance_extensions: Instance extension %s not supported by available ICDs or enabled "
5733
0
                       "layers.",
5734
0
                       pCreateInfo->ppEnabledExtensionNames[i]);
5735
0
            res = VK_ERROR_EXTENSION_NOT_PRESENT;
5736
0
            goto out;
5737
0
        }
5738
0
    }
5739
5740
0
out:
5741
0
    loader_destroy_pointer_layer_list(inst, &active_layers);
5742
0
    loader_destroy_pointer_layer_list(inst, &expanded_layers);
5743
0
    if (enabled_layers_env != NULL) {
5744
0
        loader_free_getenv(enabled_layers_env, inst);
5745
0
    }
5746
5747
0
    return res;
5748
0
}
5749
5750
VkResult loader_validate_device_extensions(struct loader_instance *this_instance,
5751
                                           const struct loader_pointer_layer_list *activated_device_layers,
5752
0
                                           const struct loader_extension_list *icd_exts, const VkDeviceCreateInfo *pCreateInfo) {
5753
    // Early out to prevent nullptr dereference
5754
0
    if (pCreateInfo->enabledExtensionCount == 0 || pCreateInfo->ppEnabledExtensionNames == NULL) {
5755
0
        return VK_SUCCESS;
5756
0
    }
5757
0
    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
5758
0
        if (pCreateInfo->ppEnabledExtensionNames[i] == NULL) {
5759
0
            continue;
5760
0
        }
5761
0
        VkStringErrorFlags result = vk_string_validate(MaxLoaderStringLength, pCreateInfo->ppEnabledExtensionNames[i]);
5762
0
        if (result != VK_STRING_ERROR_NONE) {
5763
0
            loader_log(this_instance, VULKAN_LOADER_ERROR_BIT, 0,
5764
0
                       "loader_validate_device_extensions: Device ppEnabledExtensionNames contains "
5765
0
                       "string that is too long or is badly formed");
5766
0
            return VK_ERROR_EXTENSION_NOT_PRESENT;
5767
0
        }
5768
5769
0
        const char *extension_name = pCreateInfo->ppEnabledExtensionNames[i];
5770
0
        VkExtensionProperties *extension_prop = get_extension_property(extension_name, icd_exts);
5771
5772
0
        if (extension_prop) {
5773
0
            continue;
5774
0
        }
5775
5776
        // Not in global list, search activated layer extension lists
5777
0
        for (uint32_t j = 0; j < activated_device_layers->count; j++) {
5778
0
            struct loader_layer_properties *layer_prop = activated_device_layers->list[j];
5779
5780
0
            extension_prop = get_dev_extension_property(extension_name, &layer_prop->device_extension_list);
5781
0
            if (extension_prop) {
5782
                // Found the extension in one of the layers enabled by the app.
5783
0
                break;
5784
0
            }
5785
0
        }
5786
5787
0
        if (!extension_prop) {
5788
            // Didn't find extension name in any of the device layers, error out
5789
0
            loader_log(this_instance, VULKAN_LOADER_ERROR_BIT, 0,
5790
0
                       "loader_validate_device_extensions: Device extension %s not supported by selected physical device "
5791
0
                       "or enabled layers.",
5792
0
                       pCreateInfo->ppEnabledExtensionNames[i]);
5793
0
            return VK_ERROR_EXTENSION_NOT_PRESENT;
5794
0
        }
5795
0
    }
5796
0
    return VK_SUCCESS;
5797
0
}
5798
5799
// Terminator functions for the Instance chain
5800
// All named terminator_<Vulkan API name>
5801
VKAPI_ATTR VkResult VKAPI_CALL terminator_CreateInstance(const VkInstanceCreateInfo *pCreateInfo,
5802
0
                                                         const VkAllocationCallbacks *pAllocator, VkInstance *pInstance) {
5803
0
    struct loader_icd_term *icd_term = NULL;
5804
0
    VkExtensionProperties *prop = NULL;
5805
0
    char **filtered_extension_names = NULL;
5806
0
    VkInstanceCreateInfo icd_create_info = {0};
5807
0
    VkResult res = VK_SUCCESS;
5808
0
    bool one_icd_successful = false;
5809
5810
0
    struct loader_instance *ptr_instance = (struct loader_instance *)*pInstance;
5811
0
    if (NULL == ptr_instance) {
5812
0
        loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
5813
0
                   "terminator_CreateInstance: Loader instance pointer null encountered.  Possibly set by active layer. (Policy "
5814
0
                   "#LLP_LAYER_21)");
5815
0
    } else if (LOADER_MAGIC_NUMBER != ptr_instance->magic) {
5816
0
        loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
5817
0
                   "terminator_CreateInstance: Instance pointer (%p) has invalid MAGIC value 0x%08" PRIx64
5818
0
                   ". Instance value possibly "
5819
0
                   "corrupted by active layer (Policy #LLP_LAYER_21).  ",
5820
0
                   ptr_instance, ptr_instance->magic);
5821
0
    }
5822
5823
    // Save the application version if it has been modified - layers sometimes needs features in newer API versions than
5824
    // what the application requested, and thus will increase the instance version to a level that suites their needs.
5825
0
    if (pCreateInfo->pApplicationInfo && pCreateInfo->pApplicationInfo->apiVersion) {
5826
0
        loader_api_version altered_version = loader_make_version(pCreateInfo->pApplicationInfo->apiVersion);
5827
0
        if (altered_version.major != ptr_instance->app_api_version.major ||
5828
0
            altered_version.minor != ptr_instance->app_api_version.minor) {
5829
0
            ptr_instance->app_api_version = altered_version;
5830
0
        }
5831
0
    }
5832
5833
0
    memcpy(&icd_create_info, pCreateInfo, sizeof(icd_create_info));
5834
5835
0
    icd_create_info.enabledLayerCount = 0;
5836
0
    icd_create_info.ppEnabledLayerNames = NULL;
5837
5838
    // NOTE: Need to filter the extensions to only those supported by the ICD.
5839
    //       No ICD will advertise support for layers. An ICD library could
5840
    //       support a layer, but it would be independent of the actual ICD,
5841
    //       just in the same library.
5842
0
    uint32_t extension_count = pCreateInfo->enabledExtensionCount;
5843
0
#if defined(LOADER_ENABLE_LINUX_SORT)
5844
0
    extension_count += 1;
5845
0
#endif  // LOADER_ENABLE_LINUX_SORT
5846
0
    filtered_extension_names = loader_stack_alloc(extension_count * sizeof(char *));
5847
0
    if (!filtered_extension_names) {
5848
0
        loader_log(ptr_instance, VULKAN_LOADER_ERROR_BIT, 0,
5849
0
                   "terminator_CreateInstance: Failed create extension name array for %d extensions", extension_count);
5850
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
5851
0
        goto out;
5852
0
    }
5853
0
    icd_create_info.ppEnabledExtensionNames = (const char *const *)filtered_extension_names;
5854
5855
    // Determine if Get Physical Device Properties 2 is available to this Instance
5856
0
    if (pCreateInfo->pApplicationInfo && pCreateInfo->pApplicationInfo->apiVersion >= VK_API_VERSION_1_1) {
5857
0
        ptr_instance->supports_get_dev_prop_2 = true;
5858
0
    } else {
5859
0
        for (uint32_t j = 0; j < pCreateInfo->enabledExtensionCount; j++) {
5860
0
            if (!strcmp(pCreateInfo->ppEnabledExtensionNames[j], VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
5861
0
                ptr_instance->supports_get_dev_prop_2 = true;
5862
0
                break;
5863
0
            }
5864
0
        }
5865
0
    }
5866
5867
0
    for (uint32_t i = 0; i < ptr_instance->icd_tramp_list.count; i++) {
5868
0
        icd_term = loader_icd_add(ptr_instance, &ptr_instance->icd_tramp_list.scanned_list[i]);
5869
0
        if (NULL == icd_term) {
5870
0
            loader_log(ptr_instance, VULKAN_LOADER_ERROR_BIT, 0,
5871
0
                       "terminator_CreateInstance: Failed to add ICD %d to ICD trampoline list.", i);
5872
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
5873
0
            goto out;
5874
0
        }
5875
5876
        // If any error happens after here, we need to remove the ICD from the list,
5877
        // because we've already added it, but haven't validated it
5878
5879
        // Make sure that we reset the pApplicationInfo so we don't get an old pointer
5880
0
        icd_create_info.pApplicationInfo = pCreateInfo->pApplicationInfo;
5881
0
        icd_create_info.enabledExtensionCount = 0;
5882
0
        struct loader_extension_list icd_exts = {0};
5883
5884
        // traverse scanned icd list adding non-duplicate extensions to the list
5885
0
        res = loader_init_generic_list(ptr_instance, (struct loader_generic_list *)&icd_exts, sizeof(VkExtensionProperties));
5886
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
5887
            // If out of memory, bail immediately.
5888
0
            goto out;
5889
0
        } else if (VK_SUCCESS != res) {
5890
            // Something bad happened with this ICD, so free it and try the
5891
            // next.
5892
0
            ptr_instance->icd_terms = icd_term->next;
5893
0
            icd_term->next = NULL;
5894
0
            loader_icd_destroy(ptr_instance, icd_term, pAllocator);
5895
0
            continue;
5896
0
        }
5897
5898
0
        res = loader_add_instance_extensions(ptr_instance, icd_term->scanned_icd->EnumerateInstanceExtensionProperties,
5899
0
                                             icd_term->scanned_icd->lib_name, &icd_exts);
5900
0
        if (VK_SUCCESS != res) {
5901
0
            loader_destroy_generic_list(ptr_instance, (struct loader_generic_list *)&icd_exts);
5902
0
            if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
5903
                // If out of memory, bail immediately.
5904
0
                goto out;
5905
0
            } else {
5906
                // Something bad happened with this ICD, so free it and try the next.
5907
0
                ptr_instance->icd_terms = icd_term->next;
5908
0
                icd_term->next = NULL;
5909
0
                loader_icd_destroy(ptr_instance, icd_term, pAllocator);
5910
0
                continue;
5911
0
            }
5912
0
        }
5913
5914
0
        for (uint32_t j = 0; j < pCreateInfo->enabledExtensionCount; j++) {
5915
0
            prop = get_extension_property(pCreateInfo->ppEnabledExtensionNames[j], &icd_exts);
5916
0
            if (prop) {
5917
0
                filtered_extension_names[icd_create_info.enabledExtensionCount] = (char *)pCreateInfo->ppEnabledExtensionNames[j];
5918
0
                icd_create_info.enabledExtensionCount++;
5919
0
            }
5920
0
        }
5921
0
#if defined(LOADER_ENABLE_LINUX_SORT)
5922
        // Force on "VK_KHR_get_physical_device_properties2" for Linux as we use it for GPU sorting.  This
5923
        // should be done if the API version of either the application or the driver does not natively support
5924
        // the core version of vkGetPhysicalDeviceProperties2 entrypoint.
5925
0
        if ((ptr_instance->app_api_version.major == 1 && ptr_instance->app_api_version.minor == 0) ||
5926
0
            (VK_API_VERSION_MAJOR(icd_term->scanned_icd->api_version) == 1 &&
5927
0
             VK_API_VERSION_MINOR(icd_term->scanned_icd->api_version) == 0)) {
5928
0
            prop = get_extension_property(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, &icd_exts);
5929
0
            if (prop) {
5930
0
                filtered_extension_names[icd_create_info.enabledExtensionCount] =
5931
0
                    (char *)VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
5932
0
                icd_create_info.enabledExtensionCount++;
5933
5934
                // At least one ICD supports this, so the instance should be able to support it
5935
0
                ptr_instance->supports_get_dev_prop_2 = true;
5936
0
            }
5937
0
        }
5938
0
#endif  // LOADER_ENABLE_LINUX_SORT
5939
5940
        // Determine if vkGetPhysicalDeviceProperties2 is available to this Instance
5941
        // Also determine if VK_EXT_surface_maintenance1 is available on the ICD
5942
0
        if (icd_term->scanned_icd->api_version >= VK_API_VERSION_1_1) {
5943
0
            icd_term->enabled_instance_extensions.khr_get_physical_device_properties2 = true;
5944
0
        }
5945
0
        fill_out_enabled_instance_extensions(icd_create_info.enabledExtensionCount, (const char *const *)filtered_extension_names,
5946
0
                                             &icd_term->enabled_instance_extensions);
5947
5948
0
        loader_destroy_generic_list(ptr_instance, (struct loader_generic_list *)&icd_exts);
5949
5950
        // Get the driver version from vkEnumerateInstanceVersion
5951
0
        uint32_t icd_version = VK_API_VERSION_1_0;
5952
0
        VkResult icd_result = VK_SUCCESS;
5953
0
        if (icd_term->scanned_icd->api_version >= VK_API_VERSION_1_1) {
5954
0
            PFN_vkEnumerateInstanceVersion icd_enumerate_instance_version =
5955
0
                (PFN_vkEnumerateInstanceVersion)icd_term->scanned_icd->GetInstanceProcAddr(NULL, "vkEnumerateInstanceVersion");
5956
0
            if (icd_enumerate_instance_version != NULL) {
5957
0
                icd_result = icd_enumerate_instance_version(&icd_version);
5958
0
                if (icd_result != VK_SUCCESS) {
5959
0
                    icd_version = VK_API_VERSION_1_0;
5960
0
                    loader_log(ptr_instance, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
5961
0
                               "terminator_CreateInstance: ICD \"%s\" vkEnumerateInstanceVersion returned error. The ICD will be "
5962
0
                               "treated as a 1.0 ICD",
5963
0
                               icd_term->scanned_icd->lib_name);
5964
0
                } else if (VK_API_VERSION_MINOR(icd_version) == 0) {
5965
0
                    loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
5966
0
                               "terminator_CreateInstance: Manifest ICD for \"%s\" contained a 1.1 or greater API version, but "
5967
0
                               "vkEnumerateInstanceVersion returned 1.0, treating as a 1.0 ICD",
5968
0
                               icd_term->scanned_icd->lib_name);
5969
0
                }
5970
0
            } else {
5971
0
                loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
5972
0
                           "terminator_CreateInstance: Manifest ICD for \"%s\" contained a 1.1 or greater API version, but does "
5973
0
                           "not support vkEnumerateInstanceVersion, treating as a 1.0 ICD",
5974
0
                           icd_term->scanned_icd->lib_name);
5975
0
            }
5976
0
        }
5977
5978
        // Remove the portability enumeration flag bit if the ICD doesn't support the extension
5979
0
        if ((pCreateInfo->flags & VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR) == 1) {
5980
0
            bool supports_portability_enumeration = false;
5981
0
            for (uint32_t j = 0; j < icd_create_info.enabledExtensionCount; j++) {
5982
0
                if (strcmp(filtered_extension_names[j], VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0) {
5983
0
                    supports_portability_enumeration = true;
5984
0
                    break;
5985
0
                }
5986
0
            }
5987
            // If the icd supports the extension, use the flags as given, otherwise remove the portability bit
5988
0
            icd_create_info.flags = supports_portability_enumeration
5989
0
                                        ? pCreateInfo->flags
5990
0
                                        : pCreateInfo->flags & (~VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR);
5991
0
        }
5992
5993
        // Create an instance, substituting the version to 1.0 if necessary
5994
0
        VkApplicationInfo icd_app_info = {0};
5995
0
        const uint32_t api_variant = 0;
5996
0
        const uint32_t api_version_1_0 = VK_API_VERSION_1_0;
5997
0
        uint32_t icd_version_nopatch =
5998
0
            VK_MAKE_API_VERSION(api_variant, VK_API_VERSION_MAJOR(icd_version), VK_API_VERSION_MINOR(icd_version), 0);
5999
0
        uint32_t requested_version = (pCreateInfo == NULL || pCreateInfo->pApplicationInfo == NULL)
6000
0
                                         ? api_version_1_0
6001
0
                                         : pCreateInfo->pApplicationInfo->apiVersion;
6002
0
        if ((requested_version != 0) && (icd_version_nopatch == api_version_1_0)) {
6003
0
            if (icd_create_info.pApplicationInfo == NULL) {
6004
0
                memset(&icd_app_info, 0, sizeof(icd_app_info));
6005
0
            } else {
6006
0
                memmove(&icd_app_info, icd_create_info.pApplicationInfo, sizeof(icd_app_info));
6007
0
            }
6008
0
            icd_app_info.apiVersion = icd_version;
6009
0
            icd_create_info.pApplicationInfo = &icd_app_info;
6010
0
        }
6011
6012
        // If the settings file has device_configurations, we need to raise the ApiVersion drivers use to 1.1 if the driver
6013
        // supports 1.1 or higher. This allows 1.0 apps to use the device_configurations without the app having to set its own
6014
        // ApiVersion to 1.1 on its own.
6015
0
        if (ptr_instance->settings.settings_active && ptr_instance->settings.device_configurations_active &&
6016
0
            ptr_instance->settings.device_configuration_count > 0 && icd_version >= VK_API_VERSION_1_1 &&
6017
0
            requested_version < VK_API_VERSION_1_1) {
6018
0
            if (NULL != pCreateInfo->pApplicationInfo) {
6019
0
                memcpy(&icd_app_info, pCreateInfo->pApplicationInfo, sizeof(VkApplicationInfo));
6020
0
            }
6021
0
            icd_app_info.apiVersion = VK_API_VERSION_1_1;
6022
0
            icd_create_info.pApplicationInfo = &icd_app_info;
6023
6024
0
            loader_log(
6025
0
                ptr_instance, VULKAN_LOADER_INFO_BIT, 0,
6026
0
                "terminator_CreateInstance: Raising the VkApplicationInfo::apiVersion from 1.0 to 1.1 on driver \"%s\" so that "
6027
0
                "the loader settings file is able to use this driver in the device_configuration selection logic.",
6028
0
                icd_term->scanned_icd->lib_name);
6029
0
        }
6030
6031
0
        icd_result =
6032
0
            ptr_instance->icd_tramp_list.scanned_list[i].CreateInstance(&icd_create_info, pAllocator, &(icd_term->instance));
6033
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == icd_result) {
6034
            // If out of memory, bail immediately.
6035
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
6036
0
            goto out;
6037
0
        } else if (VK_SUCCESS != icd_result) {
6038
0
            loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
6039
0
                       "terminator_CreateInstance: Received return code %i from call to vkCreateInstance in ICD %s. Skipping "
6040
0
                       "this driver.",
6041
0
                       icd_result, icd_term->scanned_icd->lib_name);
6042
0
            ptr_instance->icd_terms = icd_term->next;
6043
0
            icd_term->next = NULL;
6044
0
            loader_icd_destroy(ptr_instance, icd_term, pAllocator);
6045
0
            continue;
6046
0
        }
6047
6048
0
        if (!loader_icd_init_entries(ptr_instance, icd_term)) {
6049
0
            loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
6050
0
                       "terminator_CreateInstance: Failed to find required entrypoints in ICD %s. Skipping this driver.",
6051
0
                       icd_term->scanned_icd->lib_name);
6052
0
            ptr_instance->icd_terms = icd_term->next;
6053
0
            icd_term->next = NULL;
6054
0
            loader_icd_destroy(ptr_instance, icd_term, pAllocator);
6055
0
            continue;
6056
0
        }
6057
6058
0
        if (ptr_instance->icd_tramp_list.scanned_list[i].interface_version < 3 &&
6059
0
            (
6060
0
#if defined(VK_USE_PLATFORM_XLIB_KHR)
6061
0
                NULL != icd_term->dispatch.CreateXlibSurfaceKHR ||
6062
0
#endif  // VK_USE_PLATFORM_XLIB_KHR
6063
0
#if defined(VK_USE_PLATFORM_XCB_KHR)
6064
0
                NULL != icd_term->dispatch.CreateXcbSurfaceKHR ||
6065
0
#endif  // VK_USE_PLATFORM_XCB_KHR
6066
0
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
6067
0
                NULL != icd_term->dispatch.CreateWaylandSurfaceKHR ||
6068
0
#endif  // VK_USE_PLATFORM_WAYLAND_KHR
6069
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
6070
                NULL != icd_term->dispatch.CreateAndroidSurfaceKHR ||
6071
#endif  // VK_USE_PLATFORM_ANDROID_KHR
6072
#if defined(VK_USE_PLATFORM_WIN32_KHR)
6073
                NULL != icd_term->dispatch.CreateWin32SurfaceKHR ||
6074
#endif  // VK_USE_PLATFORM_WIN32_KHR
6075
0
                NULL != icd_term->dispatch.DestroySurfaceKHR)) {
6076
0
            loader_log(ptr_instance, VULKAN_LOADER_WARN_BIT, 0,
6077
0
                       "terminator_CreateInstance: Driver %s supports interface version %u but still exposes VkSurfaceKHR"
6078
0
                       " create/destroy entrypoints (Policy #LDP_DRIVER_8)",
6079
0
                       ptr_instance->icd_tramp_list.scanned_list[i].lib_name,
6080
0
                       ptr_instance->icd_tramp_list.scanned_list[i].interface_version);
6081
0
        }
6082
6083
        // If we made it this far, at least one ICD was successful
6084
0
        one_icd_successful = true;
6085
0
    }
6086
6087
    // For vkGetPhysicalDeviceProperties2, at least one ICD needs to support the extension for the
6088
    // instance to have it
6089
0
    if (ptr_instance->enabled_extensions.khr_get_physical_device_properties2) {
6090
0
        bool at_least_one_supports = false;
6091
0
        icd_term = ptr_instance->icd_terms;
6092
0
        while (icd_term != NULL) {
6093
0
            if (icd_term->enabled_instance_extensions.khr_get_physical_device_properties2) {
6094
0
                at_least_one_supports = true;
6095
0
                break;
6096
0
            }
6097
0
            icd_term = icd_term->next;
6098
0
        }
6099
0
        if (!at_least_one_supports) {
6100
0
            ptr_instance->enabled_extensions.khr_get_physical_device_properties2 = false;
6101
0
        }
6102
0
    }
6103
6104
    // If no ICDs were added to instance list and res is unchanged from it's initial value, the loader was unable to
6105
    // find a suitable ICD.
6106
0
    if (VK_SUCCESS == res && (ptr_instance->icd_terms == NULL || !one_icd_successful)) {
6107
0
        loader_log(ptr_instance, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6108
0
                   "terminator_CreateInstance: Found no drivers!");
6109
0
        res = VK_ERROR_INCOMPATIBLE_DRIVER;
6110
0
    }
6111
6112
0
out:
6113
6114
0
    ptr_instance->create_terminator_invalid_extension = false;
6115
6116
0
    if (VK_SUCCESS != res) {
6117
0
        if (VK_ERROR_EXTENSION_NOT_PRESENT == res) {
6118
0
            ptr_instance->create_terminator_invalid_extension = true;
6119
0
        }
6120
6121
0
        while (NULL != ptr_instance->icd_terms) {
6122
0
            icd_term = ptr_instance->icd_terms;
6123
0
            ptr_instance->icd_terms = icd_term->next;
6124
0
            if (NULL != icd_term->instance) {
6125
0
                loader_icd_close_objects(ptr_instance, icd_term);
6126
0
                icd_term->dispatch.DestroyInstance(icd_term->instance, pAllocator);
6127
0
            }
6128
0
            loader_icd_destroy(ptr_instance, icd_term, pAllocator);
6129
0
        }
6130
0
    } else {
6131
        // Check for enabled extensions here to setup the loader structures so the loader knows what extensions
6132
        // it needs to worry about.
6133
        // We do it here and again above the layers in the trampoline function since the trampoline function
6134
        // may think different extensions are enabled than what's down here.
6135
        // This is why we don't clear inside of these function calls.
6136
        // The clearing should actually be handled by the overall memset of the pInstance structure in the
6137
        // trampoline.
6138
0
        fill_out_enabled_instance_extensions(pCreateInfo->enabledExtensionCount, pCreateInfo->ppEnabledExtensionNames,
6139
0
                                             &ptr_instance->enabled_extensions);
6140
0
    }
6141
6142
0
    return res;
6143
0
}
6144
6145
0
VKAPI_ATTR void VKAPI_CALL terminator_DestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) {
6146
0
    struct loader_instance *ptr_instance = loader_get_instance(instance);
6147
0
    if (NULL == ptr_instance) {
6148
0
        return;
6149
0
    }
6150
6151
    // Remove this instance from the list of instances:
6152
0
    struct loader_instance *prev = NULL;
6153
0
    struct loader_instance *next = loader.instances;
6154
0
    while (next != NULL) {
6155
0
        if (next == ptr_instance) {
6156
            // Remove this instance from the list:
6157
0
            if (prev)
6158
0
                prev->next = next->next;
6159
0
            else
6160
0
                loader.instances = next->next;
6161
0
            break;
6162
0
        }
6163
0
        prev = next;
6164
0
        next = next->next;
6165
0
    }
6166
6167
0
    struct loader_icd_term *icd_terms = ptr_instance->icd_terms;
6168
0
    while (NULL != icd_terms) {
6169
0
        if (icd_terms->instance) {
6170
0
            loader_icd_close_objects(ptr_instance, icd_terms);
6171
0
            icd_terms->dispatch.DestroyInstance(icd_terms->instance, pAllocator);
6172
0
        }
6173
0
        struct loader_icd_term *next_icd_term = icd_terms->next;
6174
0
        icd_terms->instance = VK_NULL_HANDLE;
6175
0
        loader_icd_destroy(ptr_instance, icd_terms, pAllocator);
6176
6177
0
        icd_terms = next_icd_term;
6178
0
    }
6179
6180
0
    loader_clear_scanned_icd_list(ptr_instance, &ptr_instance->icd_tramp_list);
6181
0
    loader_destroy_generic_list(ptr_instance, (struct loader_generic_list *)&ptr_instance->ext_list);
6182
0
    if (NULL != ptr_instance->phys_devs_term) {
6183
0
        for (uint32_t i = 0; i < ptr_instance->phys_dev_count_term; i++) {
6184
0
            for (uint32_t j = i + 1; j < ptr_instance->phys_dev_count_term; j++) {
6185
0
                if (ptr_instance->phys_devs_term[i] == ptr_instance->phys_devs_term[j]) {
6186
0
                    ptr_instance->phys_devs_term[j] = NULL;
6187
0
                }
6188
0
            }
6189
0
        }
6190
0
        for (uint32_t i = 0; i < ptr_instance->phys_dev_count_term; i++) {
6191
0
            loader_instance_heap_free(ptr_instance, ptr_instance->phys_devs_term[i]);
6192
0
        }
6193
0
        loader_instance_heap_free(ptr_instance, ptr_instance->phys_devs_term);
6194
0
    }
6195
0
    if (NULL != ptr_instance->phys_dev_groups_term) {
6196
0
        for (uint32_t i = 0; i < ptr_instance->phys_dev_group_count_term; i++) {
6197
0
            loader_instance_heap_free(ptr_instance, ptr_instance->phys_dev_groups_term[i]);
6198
0
        }
6199
0
        loader_instance_heap_free(ptr_instance, ptr_instance->phys_dev_groups_term);
6200
0
    }
6201
0
    loader_free_dev_ext_table(ptr_instance);
6202
0
    loader_free_phys_dev_ext_table(ptr_instance);
6203
6204
0
    free_string_list(ptr_instance, &ptr_instance->enabled_layer_names);
6205
0
}
6206
6207
VKAPI_ATTR VkResult VKAPI_CALL terminator_CreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo *pCreateInfo,
6208
0
                                                       const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) {
6209
0
    VkResult res = VK_SUCCESS;
6210
0
    struct loader_physical_device_term *phys_dev_term;
6211
0
    phys_dev_term = (struct loader_physical_device_term *)physicalDevice;
6212
0
    struct loader_icd_term *icd_term = phys_dev_term->this_icd_term;
6213
6214
0
    struct loader_device *dev = (struct loader_device *)*pDevice;
6215
0
    PFN_vkCreateDevice fpCreateDevice = icd_term->dispatch.CreateDevice;
6216
0
    struct loader_extension_list icd_exts;
6217
6218
0
    VkBaseOutStructure *caller_dgci_container = NULL;
6219
0
    VkDeviceGroupDeviceCreateInfo *caller_dgci = NULL;
6220
6221
0
    if (NULL == dev) {
6222
0
        loader_log(icd_term->this_instance, VULKAN_LOADER_WARN_BIT, 0,
6223
0
                   "terminator_CreateDevice: Loader device pointer null encountered.  Possibly set by active layer. (Policy "
6224
0
                   "#LLP_LAYER_22)");
6225
0
    } else if (DEVICE_DISP_TABLE_MAGIC_NUMBER != dev->loader_dispatch.core_dispatch.magic) {
6226
0
        loader_log(icd_term->this_instance, VULKAN_LOADER_WARN_BIT, 0,
6227
0
                   "terminator_CreateDevice: Device pointer (%p) has invalid MAGIC value 0x%08" PRIx64
6228
0
                   ". The expected value is "
6229
0
                   "0x10ADED040410ADED. Device value possibly "
6230
0
                   "corrupted by active layer (Policy #LLP_LAYER_22).  ",
6231
0
                   dev, dev->loader_dispatch.core_dispatch.magic);
6232
0
    }
6233
6234
0
    dev->phys_dev_term = phys_dev_term;
6235
6236
0
    icd_exts.list = NULL;
6237
6238
0
    if (fpCreateDevice == NULL) {
6239
0
        loader_log(icd_term->this_instance, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6240
0
                   "terminator_CreateDevice: No vkCreateDevice command exposed by ICD %s", icd_term->scanned_icd->lib_name);
6241
0
        res = VK_ERROR_INITIALIZATION_FAILED;
6242
0
        goto out;
6243
0
    }
6244
6245
0
    VkDeviceCreateInfo localCreateInfo;
6246
0
    memcpy(&localCreateInfo, pCreateInfo, sizeof(localCreateInfo));
6247
6248
    // NOTE: Need to filter the extensions to only those supported by the ICD.
6249
    //       No ICD will advertise support for layers. An ICD library could support a layer,
6250
    //       but it would be independent of the actual ICD, just in the same library.
6251
0
    char **filtered_extension_names = NULL;
6252
0
    if (0 < pCreateInfo->enabledExtensionCount) {
6253
0
        filtered_extension_names = loader_stack_alloc(pCreateInfo->enabledExtensionCount * sizeof(char *));
6254
0
        if (NULL == filtered_extension_names) {
6255
0
            loader_log(icd_term->this_instance, VULKAN_LOADER_ERROR_BIT, 0,
6256
0
                       "terminator_CreateDevice: Failed to create extension name storage for %d extensions",
6257
0
                       pCreateInfo->enabledExtensionCount);
6258
0
            return VK_ERROR_OUT_OF_HOST_MEMORY;
6259
0
        }
6260
0
    }
6261
6262
0
    localCreateInfo.enabledLayerCount = 0;
6263
0
    localCreateInfo.ppEnabledLayerNames = NULL;
6264
6265
0
    localCreateInfo.enabledExtensionCount = 0;
6266
0
    localCreateInfo.ppEnabledExtensionNames = (const char *const *)filtered_extension_names;
6267
6268
    // Get the physical device (ICD) extensions
6269
0
    res = loader_init_generic_list(icd_term->this_instance, (struct loader_generic_list *)&icd_exts, sizeof(VkExtensionProperties));
6270
0
    if (VK_SUCCESS != res) {
6271
0
        goto out;
6272
0
    }
6273
6274
0
    res = loader_add_device_extensions(icd_term->this_instance, icd_term->dispatch.EnumerateDeviceExtensionProperties,
6275
0
                                       phys_dev_term->phys_dev, icd_term->scanned_icd->lib_name, &icd_exts);
6276
0
    if (res != VK_SUCCESS) {
6277
0
        goto out;
6278
0
    }
6279
6280
0
    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
6281
0
        if (pCreateInfo->ppEnabledExtensionNames == NULL) {
6282
0
            continue;
6283
0
        }
6284
0
        const char *extension_name = pCreateInfo->ppEnabledExtensionNames[i];
6285
0
        if (extension_name == NULL) {
6286
0
            continue;
6287
0
        }
6288
0
        VkExtensionProperties *prop = get_extension_property(extension_name, &icd_exts);
6289
0
        if (prop) {
6290
0
            filtered_extension_names[localCreateInfo.enabledExtensionCount] = (char *)extension_name;
6291
0
            localCreateInfo.enabledExtensionCount++;
6292
0
        } else {
6293
0
            loader_log(icd_term->this_instance, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6294
0
                       "vkCreateDevice extension %s not available for devices associated with ICD %s", extension_name,
6295
0
                       icd_term->scanned_icd->lib_name);
6296
0
        }
6297
0
    }
6298
6299
    // Before we continue, If KHX_device_group is the list of enabled and viable extensions, then we then need to look for the
6300
    // corresponding VkDeviceGroupDeviceCreateInfo struct in the device list and replace all the physical device values (which
6301
    // are really loader physical device terminator values) with the ICD versions.
6302
    // if (icd_term->this_instance->enabled_extensions.khr_device_group_creation == 1) {
6303
0
    {
6304
0
        VkBaseOutStructure *pNext = (VkBaseOutStructure *)localCreateInfo.pNext;
6305
0
        VkBaseOutStructure *pPrev = (VkBaseOutStructure *)&localCreateInfo;
6306
0
        while (NULL != pNext) {
6307
0
            if (VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO == pNext->sType) {
6308
0
                VkDeviceGroupDeviceCreateInfo *cur_struct = (VkDeviceGroupDeviceCreateInfo *)pNext;
6309
0
                if (0 < cur_struct->physicalDeviceCount && NULL != cur_struct->pPhysicalDevices) {
6310
0
                    VkDeviceGroupDeviceCreateInfo *temp_struct = loader_stack_alloc(sizeof(VkDeviceGroupDeviceCreateInfo));
6311
0
                    VkPhysicalDevice *phys_dev_array = NULL;
6312
0
                    if (NULL == temp_struct) {
6313
0
                        return VK_ERROR_OUT_OF_HOST_MEMORY;
6314
0
                    }
6315
0
                    memcpy(temp_struct, cur_struct, sizeof(VkDeviceGroupDeviceCreateInfo));
6316
0
                    phys_dev_array = loader_stack_alloc(sizeof(VkPhysicalDevice) * cur_struct->physicalDeviceCount);
6317
0
                    if (NULL == phys_dev_array) {
6318
0
                        return VK_ERROR_OUT_OF_HOST_MEMORY;
6319
0
                    }
6320
6321
                    // Before calling down, replace the incoming physical device values (which are really loader terminator
6322
                    // physical devices) with the ICDs physical device values.
6323
0
                    struct loader_physical_device_term *cur_term;
6324
0
                    for (uint32_t phys_dev = 0; phys_dev < cur_struct->physicalDeviceCount; phys_dev++) {
6325
0
                        cur_term = (struct loader_physical_device_term *)cur_struct->pPhysicalDevices[phys_dev];
6326
0
                        phys_dev_array[phys_dev] = cur_term->phys_dev;
6327
0
                    }
6328
0
                    temp_struct->pPhysicalDevices = phys_dev_array;
6329
6330
                    // Keep track of pointers to restore pNext chain before returning
6331
0
                    caller_dgci_container = pPrev;
6332
0
                    caller_dgci = cur_struct;
6333
6334
                    // Replace the old struct in the pNext chain with this one.
6335
0
                    pPrev->pNext = (VkBaseOutStructure *)temp_struct;
6336
0
                }
6337
0
                break;
6338
0
            }
6339
6340
0
            pPrev = pNext;
6341
0
            pNext = pNext->pNext;
6342
0
        }
6343
0
    }
6344
6345
    // Handle loader emulation for structs that are not supported by the ICD:
6346
    // Presently, the emulation leaves the pNext chain alone. This means that the ICD will receive items in the chain which
6347
    // are not recognized by the ICD. If this causes the ICD to fail, then the items would have to be removed here. The current
6348
    // implementation does not remove them because copying the pNext chain would be impossible if the loader does not recognize
6349
    // the any of the struct types, as the loader would not know the size to allocate and copy.
6350
    // if (icd_term->dispatch.GetPhysicalDeviceFeatures2 == NULL && icd_term->dispatch.GetPhysicalDeviceFeatures2KHR == NULL) {
6351
0
    {
6352
0
        const void *pNext = localCreateInfo.pNext;
6353
0
        while (pNext != NULL) {
6354
0
            VkBaseInStructure pNext_in_structure = {0};
6355
0
            memcpy(&pNext_in_structure, pNext, sizeof(VkBaseInStructure));
6356
0
            switch (pNext_in_structure.sType) {
6357
0
                case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: {
6358
0
                    const VkPhysicalDeviceFeatures2KHR *features = pNext;
6359
6360
0
                    if (icd_term->dispatch.GetPhysicalDeviceFeatures2 == NULL &&
6361
0
                        icd_term->dispatch.GetPhysicalDeviceFeatures2KHR == NULL) {
6362
0
                        loader_log(icd_term->this_instance, VULKAN_LOADER_INFO_BIT, 0,
6363
0
                                   "vkCreateDevice: Emulating handling of VkPhysicalDeviceFeatures2 in pNext chain for ICD \"%s\"",
6364
0
                                   icd_term->scanned_icd->lib_name);
6365
6366
                        // Verify that VK_KHR_get_physical_device_properties2 is enabled
6367
0
                        if (icd_term->this_instance->enabled_extensions.khr_get_physical_device_properties2) {
6368
0
                            localCreateInfo.pEnabledFeatures = &features->features;
6369
0
                        }
6370
0
                    }
6371
6372
                    // Leave this item in the pNext chain for now
6373
6374
0
                    pNext = features->pNext;
6375
0
                    break;
6376
0
                }
6377
6378
0
                case VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO: {
6379
0
                    const VkDeviceGroupDeviceCreateInfo *group_info = pNext;
6380
6381
0
                    if (icd_term->dispatch.EnumeratePhysicalDeviceGroups == NULL &&
6382
0
                        icd_term->dispatch.EnumeratePhysicalDeviceGroupsKHR == NULL) {
6383
0
                        loader_log(icd_term->this_instance, VULKAN_LOADER_INFO_BIT, 0,
6384
0
                                   "vkCreateDevice: Emulating handling of VkPhysicalDeviceGroupProperties in pNext chain for "
6385
0
                                   "ICD \"%s\"",
6386
0
                                   icd_term->scanned_icd->lib_name);
6387
6388
                        // The group must contain only this one device, since physical device groups aren't actually supported
6389
0
                        if (group_info->physicalDeviceCount != 1) {
6390
0
                            loader_log(icd_term->this_instance, VULKAN_LOADER_ERROR_BIT, 0,
6391
0
                                       "vkCreateDevice: Emulation failed to create device from device group info");
6392
0
                            res = VK_ERROR_INITIALIZATION_FAILED;
6393
0
                            goto out;
6394
0
                        }
6395
0
                    }
6396
6397
                    // Nothing needs to be done here because we're leaving the item in the pNext chain and because the spec
6398
                    // states that the physicalDevice argument must be included in the device group, and we've already checked
6399
                    // that it is
6400
6401
0
                    pNext = group_info->pNext;
6402
0
                    break;
6403
0
                }
6404
6405
                // Multiview properties are also allowed, but since VK_KHX_multiview is a device extension, we'll just let the
6406
                // ICD handle that error when the user enables the extension here
6407
0
                default: {
6408
0
                    pNext = pNext_in_structure.pNext;
6409
0
                    break;
6410
0
                }
6411
0
            }
6412
0
        }
6413
0
    }
6414
6415
0
    VkBool32 maintenance5_feature_enabled = false;
6416
    // Look for the VkPhysicalDeviceMaintenance5FeaturesKHR struct to see if the feature was enabled
6417
0
    {
6418
0
        const void *pNext = localCreateInfo.pNext;
6419
0
        while (pNext != NULL) {
6420
0
            VkBaseInStructure pNext_in_structure = {0};
6421
0
            memcpy(&pNext_in_structure, pNext, sizeof(VkBaseInStructure));
6422
0
            switch (pNext_in_structure.sType) {
6423
0
                case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR: {
6424
0
                    const VkPhysicalDeviceMaintenance5FeaturesKHR *maintenance_features = pNext;
6425
0
                    if (maintenance_features->maintenance5 == VK_TRUE) {
6426
0
                        maintenance5_feature_enabled = true;
6427
0
                    }
6428
0
                    pNext = maintenance_features->pNext;
6429
0
                    break;
6430
0
                }
6431
6432
0
                default: {
6433
0
                    pNext = pNext_in_structure.pNext;
6434
0
                    break;
6435
0
                }
6436
0
            }
6437
0
        }
6438
0
    }
6439
6440
    // Every extension that has a loader-defined terminator needs to be marked as enabled or disabled so that we know whether or
6441
    // not to return that terminator when vkGetDeviceProcAddr is called
6442
0
    for (uint32_t i = 0; i < localCreateInfo.enabledExtensionCount; ++i) {
6443
0
        if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_KHR_SWAPCHAIN_EXTENSION_NAME)) {
6444
0
            dev->driver_extensions.khr_swapchain_enabled = true;
6445
0
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME)) {
6446
0
            dev->driver_extensions.khr_display_swapchain_enabled = true;
6447
0
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_KHR_DEVICE_GROUP_EXTENSION_NAME)) {
6448
0
            dev->driver_extensions.khr_device_group_enabled = true;
6449
0
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) {
6450
0
            dev->driver_extensions.ext_debug_marker_enabled = true;
6451
#if defined(VK_USE_PLATFORM_WIN32_KHR)
6452
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_EXT_FULL_SCREEN_EXCLUSIVE_EXTENSION_NAME)) {
6453
            dev->driver_extensions.ext_full_screen_exclusive_enabled = true;
6454
#endif
6455
0
        } else if (!strcmp(localCreateInfo.ppEnabledExtensionNames[i], VK_KHR_MAINTENANCE_5_EXTENSION_NAME) &&
6456
0
                   maintenance5_feature_enabled) {
6457
0
            dev->should_ignore_device_commands_from_newer_version = true;
6458
0
        }
6459
0
    }
6460
0
    dev->layer_extensions.ext_debug_utils_enabled = icd_term->this_instance->enabled_extensions.ext_debug_utils;
6461
0
    dev->driver_extensions.ext_debug_utils_enabled = icd_term->this_instance->enabled_extensions.ext_debug_utils;
6462
6463
0
    VkPhysicalDeviceProperties properties;
6464
0
    icd_term->dispatch.GetPhysicalDeviceProperties(phys_dev_term->phys_dev, &properties);
6465
0
    if (properties.apiVersion >= VK_API_VERSION_1_1) {
6466
0
        dev->driver_extensions.version_1_1_enabled = true;
6467
0
    }
6468
0
    if (properties.apiVersion >= VK_API_VERSION_1_2) {
6469
0
        dev->driver_extensions.version_1_2_enabled = true;
6470
0
    }
6471
0
    if (properties.apiVersion >= VK_API_VERSION_1_3) {
6472
0
        dev->driver_extensions.version_1_3_enabled = true;
6473
0
    }
6474
6475
0
    loader_log(icd_term->this_instance, VULKAN_LOADER_LAYER_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6476
0
               "       Using \"%s\" with driver: \"%s\"", properties.deviceName, icd_term->scanned_icd->lib_name);
6477
6478
0
    res = fpCreateDevice(phys_dev_term->phys_dev, &localCreateInfo, pAllocator, &dev->icd_device);
6479
0
    if (res != VK_SUCCESS) {
6480
0
        loader_log(icd_term->this_instance, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6481
0
                   "terminator_CreateDevice: Failed in ICD %s vkCreateDevice call", icd_term->scanned_icd->lib_name);
6482
0
        goto out;
6483
0
    }
6484
6485
0
    *pDevice = dev->icd_device;
6486
0
    loader_add_logical_device(icd_term, dev);
6487
6488
    // Init dispatch pointer in new device object
6489
0
    loader_init_dispatch(*pDevice, &dev->loader_dispatch);
6490
6491
0
out:
6492
0
    if (NULL != icd_exts.list) {
6493
0
        loader_destroy_generic_list(icd_term->this_instance, (struct loader_generic_list *)&icd_exts);
6494
0
    }
6495
6496
    // Restore pNext pointer to old VkDeviceGroupDeviceCreateInfo
6497
    // in the chain to maintain consistency for the caller.
6498
0
    if (caller_dgci_container != NULL) {
6499
0
        caller_dgci_container->pNext = (VkBaseOutStructure *)caller_dgci;
6500
0
    }
6501
6502
0
    return res;
6503
0
}
6504
6505
// Update the trampoline physical devices with the wrapped version.
6506
// We always want to re-use previous physical device pointers since they may be used by an application
6507
// after returning previously.
6508
0
VkResult setup_loader_tramp_phys_devs(struct loader_instance *inst, uint32_t phys_dev_count, VkPhysicalDevice *phys_devs) {
6509
0
    VkResult res = VK_SUCCESS;
6510
0
    uint32_t found_count = 0;
6511
0
    uint32_t old_count = inst->phys_dev_count_tramp;
6512
0
    uint32_t new_count = inst->total_gpu_count;
6513
0
    struct loader_physical_device_tramp **new_phys_devs = NULL;
6514
6515
0
    if (0 == phys_dev_count) {
6516
0
        return VK_SUCCESS;
6517
0
    }
6518
0
    if (phys_dev_count > new_count) {
6519
0
        new_count = phys_dev_count;
6520
0
    }
6521
6522
    // We want an old to new index array and a new to old index array
6523
0
    int32_t *old_to_new_index = (int32_t *)loader_stack_alloc(sizeof(int32_t) * old_count);
6524
0
    int32_t *new_to_old_index = (int32_t *)loader_stack_alloc(sizeof(int32_t) * new_count);
6525
0
    if (NULL == old_to_new_index || NULL == new_to_old_index) {
6526
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
6527
0
    }
6528
6529
    // Initialize both
6530
0
    for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6531
0
        old_to_new_index[cur_idx] = -1;
6532
0
    }
6533
0
    for (uint32_t cur_idx = 0; cur_idx < new_count; ++cur_idx) {
6534
0
        new_to_old_index[cur_idx] = -1;
6535
0
    }
6536
6537
    // Figure out the old->new and new->old indices
6538
0
    for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6539
0
        for (uint32_t new_idx = 0; new_idx < phys_dev_count; ++new_idx) {
6540
0
            if (inst->phys_devs_tramp[cur_idx]->phys_dev == phys_devs[new_idx]) {
6541
0
                old_to_new_index[cur_idx] = (int32_t)new_idx;
6542
0
                new_to_old_index[new_idx] = (int32_t)cur_idx;
6543
0
                found_count++;
6544
0
                break;
6545
0
            }
6546
0
        }
6547
0
    }
6548
6549
    // If we found exactly the number of items we were looking for as we had before.  Then everything
6550
    // we already have is good enough and we just need to update the array that was passed in with
6551
    // the loader values.
6552
0
    if (found_count == phys_dev_count && 0 != old_count && old_count == new_count) {
6553
0
        for (uint32_t new_idx = 0; new_idx < phys_dev_count; ++new_idx) {
6554
0
            for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6555
0
                if (old_to_new_index[cur_idx] == (int32_t)new_idx) {
6556
0
                    phys_devs[new_idx] = (VkPhysicalDevice)inst->phys_devs_tramp[cur_idx];
6557
0
                    break;
6558
0
                }
6559
0
            }
6560
0
        }
6561
        // Nothing else to do for this path
6562
0
        res = VK_SUCCESS;
6563
0
    } else {
6564
        // Something is different, so do the full path of checking every device and creating a new array to use.
6565
        // This can happen if a device was added, or removed, or we hadn't previously queried all the data and we
6566
        // have more to store.
6567
0
        new_phys_devs = loader_instance_heap_calloc(inst, sizeof(struct loader_physical_device_tramp *) * new_count,
6568
0
                                                    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6569
0
        if (NULL == new_phys_devs) {
6570
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6571
0
                       "setup_loader_tramp_phys_devs:  Failed to allocate new physical device array of size %d", new_count);
6572
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
6573
0
            goto out;
6574
0
        }
6575
6576
0
        if (new_count > phys_dev_count) {
6577
0
            found_count = phys_dev_count;
6578
0
        } else {
6579
0
            found_count = new_count;
6580
0
        }
6581
6582
        // First try to see if an old item exists that matches the new item.  If so, just copy it over.
6583
0
        for (uint32_t new_idx = 0; new_idx < found_count; ++new_idx) {
6584
0
            bool old_item_found = false;
6585
0
            for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6586
0
                if (old_to_new_index[cur_idx] == (int32_t)new_idx) {
6587
                    // Copy over old item to correct spot in the new array
6588
0
                    new_phys_devs[new_idx] = inst->phys_devs_tramp[cur_idx];
6589
0
                    old_item_found = true;
6590
0
                    break;
6591
0
                }
6592
0
            }
6593
            // Something wasn't found, so it's new so add it to the new list
6594
0
            if (!old_item_found) {
6595
0
                new_phys_devs[new_idx] = loader_instance_heap_alloc(inst, sizeof(struct loader_physical_device_tramp),
6596
0
                                                                    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6597
0
                if (NULL == new_phys_devs[new_idx]) {
6598
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6599
0
                               "setup_loader_tramp_phys_devs:  Failed to allocate new trampoline physical device");
6600
0
                    res = VK_ERROR_OUT_OF_HOST_MEMORY;
6601
0
                    goto out;
6602
0
                }
6603
6604
                // Initialize the new physicalDevice object
6605
0
                loader_set_dispatch((void *)new_phys_devs[new_idx], inst->disp);
6606
0
                new_phys_devs[new_idx]->this_instance = inst;
6607
0
                new_phys_devs[new_idx]->phys_dev = phys_devs[new_idx];
6608
0
                new_phys_devs[new_idx]->magic = PHYS_TRAMP_MAGIC_NUMBER;
6609
0
            }
6610
6611
0
            phys_devs[new_idx] = (VkPhysicalDevice)new_phys_devs[new_idx];
6612
0
        }
6613
6614
        // We usually get here if the user array is smaller than the total number of devices, so copy the
6615
        // remaining devices we have over to the new array.
6616
0
        uint32_t start = found_count;
6617
0
        for (uint32_t new_idx = start; new_idx < new_count; ++new_idx) {
6618
0
            for (uint32_t cur_idx = 0; cur_idx < old_count; ++cur_idx) {
6619
0
                if (old_to_new_index[cur_idx] == -1) {
6620
0
                    new_phys_devs[new_idx] = inst->phys_devs_tramp[cur_idx];
6621
0
                    old_to_new_index[cur_idx] = new_idx;
6622
0
                    found_count++;
6623
0
                    break;
6624
0
                }
6625
0
            }
6626
0
        }
6627
0
    }
6628
6629
0
out:
6630
6631
0
    if (NULL != new_phys_devs) {
6632
0
        if (VK_SUCCESS != res) {
6633
0
            for (uint32_t new_idx = 0; new_idx < found_count; ++new_idx) {
6634
                // If an OOM occurred inside the copying of the new physical devices into the existing array
6635
                // will leave some of the old physical devices in the array which may have been copied into
6636
                // the new array, leading to them being freed twice. To avoid this we just make sure to not
6637
                // delete physical devices which were copied.
6638
0
                bool found = false;
6639
0
                for (uint32_t cur_idx = 0; cur_idx < inst->phys_dev_count_tramp; cur_idx++) {
6640
0
                    if (new_phys_devs[new_idx] == inst->phys_devs_tramp[cur_idx]) {
6641
0
                        found = true;
6642
0
                        break;
6643
0
                    }
6644
0
                }
6645
0
                if (!found) {
6646
0
                    loader_instance_heap_free(inst, new_phys_devs[new_idx]);
6647
0
                }
6648
0
            }
6649
0
            loader_instance_heap_free(inst, new_phys_devs);
6650
0
        } else {
6651
0
            if (new_count > inst->total_gpu_count) {
6652
0
                inst->total_gpu_count = new_count;
6653
0
            }
6654
            // Free everything in the old array that was not copied into the new array
6655
            // here.  We can't attempt to do that before here since the previous loop
6656
            // looking before the "out:" label may hit an out of memory condition resulting
6657
            // in memory leaking.
6658
0
            if (NULL != inst->phys_devs_tramp) {
6659
0
                for (uint32_t i = 0; i < inst->phys_dev_count_tramp; i++) {
6660
0
                    bool found = false;
6661
0
                    for (uint32_t j = 0; j < inst->total_gpu_count; j++) {
6662
0
                        if (inst->phys_devs_tramp[i] == new_phys_devs[j]) {
6663
0
                            found = true;
6664
0
                            break;
6665
0
                        }
6666
0
                    }
6667
0
                    if (!found) {
6668
0
                        loader_instance_heap_free(inst, inst->phys_devs_tramp[i]);
6669
0
                    }
6670
0
                }
6671
0
                loader_instance_heap_free(inst, inst->phys_devs_tramp);
6672
0
            }
6673
0
            inst->phys_devs_tramp = new_phys_devs;
6674
0
            inst->phys_dev_count_tramp = found_count;
6675
0
        }
6676
0
    }
6677
0
    if (VK_SUCCESS != res) {
6678
0
        inst->total_gpu_count = 0;
6679
0
    }
6680
6681
0
    return res;
6682
0
}
6683
6684
#if defined(LOADER_ENABLE_LINUX_SORT)
6685
0
bool is_linux_sort_enabled(struct loader_instance *inst) {
6686
0
    bool sort_items = inst->supports_get_dev_prop_2;
6687
0
    char *env_value = loader_getenv("VK_LOADER_DISABLE_SELECT", inst);
6688
0
    if (NULL != env_value) {
6689
0
        int32_t int_env_val = atoi(env_value);
6690
0
        loader_free_getenv(env_value, inst);
6691
0
        if (int_env_val != 0) {
6692
0
            sort_items = false;
6693
0
        }
6694
0
    }
6695
0
    return sort_items;
6696
0
}
6697
#endif  // LOADER_ENABLE_LINUX_SORT
6698
6699
// Look for physical_device in the provided phys_devs list, return true if found and put the index into out_idx, otherwise
6700
// return false
6701
bool find_phys_dev(VkPhysicalDevice physical_device, uint32_t phys_devs_count, struct loader_physical_device_term **phys_devs,
6702
0
                   uint32_t *out_idx) {
6703
0
    if (NULL == phys_devs) return false;
6704
0
    for (uint32_t idx = 0; idx < phys_devs_count; idx++) {
6705
0
        if (NULL != phys_devs[idx] && physical_device == phys_devs[idx]->phys_dev) {
6706
0
            *out_idx = idx;
6707
0
            return true;
6708
0
        }
6709
0
    }
6710
0
    return false;
6711
0
}
6712
6713
// Add physical_device to new_phys_devs
6714
VkResult check_and_add_to_new_phys_devs(struct loader_instance *inst, VkPhysicalDevice physical_device,
6715
                                        struct loader_icd_physical_devices *dev_array, uint32_t *cur_new_phys_dev_count,
6716
0
                                        struct loader_physical_device_term **new_phys_devs) {
6717
0
    uint32_t out_idx = 0;
6718
0
    uint32_t idx = *cur_new_phys_dev_count;
6719
    // Check if the physical_device already exists in the new_phys_devs buffer, that means it was found from both
6720
    // EnumerateAdapterPhysicalDevices and EnumeratePhysicalDevices and we need to skip it.
6721
0
    if (find_phys_dev(physical_device, idx, new_phys_devs, &out_idx)) {
6722
0
        return VK_SUCCESS;
6723
0
    }
6724
    // Check if it was found in a previous call to vkEnumeratePhysicalDevices, we can just copy over the old data.
6725
0
    if (find_phys_dev(physical_device, inst->phys_dev_count_term, inst->phys_devs_term, &out_idx)) {
6726
0
        new_phys_devs[idx] = inst->phys_devs_term[out_idx];
6727
0
        (*cur_new_phys_dev_count)++;
6728
0
        return VK_SUCCESS;
6729
0
    }
6730
6731
    // Exit in case something is already present - this shouldn't happen but better to be safe than overwrite existing data
6732
    // since this code has been refactored a half dozen times.
6733
0
    if (NULL != new_phys_devs[idx]) {
6734
0
        return VK_SUCCESS;
6735
0
    }
6736
    // If this physical device is new, we need to allocate space for it.
6737
0
    new_phys_devs[idx] =
6738
0
        loader_instance_heap_alloc(inst, sizeof(struct loader_physical_device_term), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6739
0
    if (NULL == new_phys_devs[idx]) {
6740
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6741
0
                   "check_and_add_to_new_phys_devs:  Failed to allocate physical device terminator object %d", idx);
6742
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
6743
0
    }
6744
6745
0
    loader_set_dispatch((void *)new_phys_devs[idx], inst->disp);
6746
0
    new_phys_devs[idx]->this_icd_term = dev_array->icd_term;
6747
0
    new_phys_devs[idx]->phys_dev = physical_device;
6748
6749
    // Increment the count of new physical devices
6750
0
    (*cur_new_phys_dev_count)++;
6751
0
    return VK_SUCCESS;
6752
0
}
6753
6754
/* Enumerate all physical devices from ICDs and add them to inst->phys_devs_term
6755
 *
6756
 * There are two methods to find VkPhysicalDevices - vkEnumeratePhysicalDevices and vkEnumerateAdapterPhysicalDevices
6757
 * The latter is supported on windows only and on devices supporting ICD Interface Version 6 and greater.
6758
 *
6759
 * Once all physical devices are acquired, they need to be pulled into a single list of `loader_physical_device_term`'s.
6760
 * They also need to be setup - the icd_term, icd_index, phys_dev, and disp (dispatch table) all need the correct data.
6761
 * Additionally, we need to keep using already setup physical devices as they may be in use, thus anything enumerated
6762
 * that is already in inst->phys_devs_term will be carried over.
6763
 */
6764
6765
0
VkResult setup_loader_term_phys_devs(struct loader_instance *inst) {
6766
0
    VkResult res = VK_SUCCESS;
6767
0
    struct loader_icd_term *icd_term;
6768
0
    uint32_t windows_sorted_devices_count = 0;
6769
0
    struct loader_icd_physical_devices *windows_sorted_devices_array = NULL;
6770
0
    uint32_t icd_count = 0;
6771
0
    struct loader_icd_physical_devices *icd_phys_dev_array = NULL;
6772
0
    uint32_t new_phys_devs_capacity = 0;
6773
0
    uint32_t new_phys_devs_count = 0;
6774
0
    struct loader_physical_device_term **new_phys_devs = NULL;
6775
6776
#if defined(_WIN32)
6777
    // Get the physical devices supported by platform sorting mechanism into a separate list
6778
    res = windows_read_sorted_physical_devices(inst, &windows_sorted_devices_count, &windows_sorted_devices_array);
6779
    if (VK_SUCCESS != res) {
6780
        goto out;
6781
    }
6782
#endif
6783
6784
0
    icd_count = inst->icd_terms_count;
6785
6786
    // Allocate something to store the physical device characteristics that we read from each ICD.
6787
0
    icd_phys_dev_array =
6788
0
        (struct loader_icd_physical_devices *)loader_stack_alloc(sizeof(struct loader_icd_physical_devices) * icd_count);
6789
0
    if (NULL == icd_phys_dev_array) {
6790
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6791
0
                   "setup_loader_term_phys_devs:  Failed to allocate temporary ICD Physical device info array of size %d",
6792
0
                   icd_count);
6793
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
6794
0
        goto out;
6795
0
    }
6796
0
    memset(icd_phys_dev_array, 0, sizeof(struct loader_icd_physical_devices) * icd_count);
6797
6798
    // For each ICD, query the number of physical devices, and then get an
6799
    // internal value for those physical devices.
6800
0
    icd_term = inst->icd_terms;
6801
0
    uint32_t icd_idx = 0;
6802
0
    while (NULL != icd_term) {
6803
0
        res = icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &icd_phys_dev_array[icd_idx].device_count, NULL);
6804
0
        if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
6805
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6806
0
                       "setup_loader_term_phys_devs: Call to \'vkEnumeratePhysicalDevices\' in ICD %s failed with error code "
6807
0
                       "VK_ERROR_OUT_OF_HOST_MEMORY",
6808
0
                       icd_term->scanned_icd->lib_name);
6809
0
            goto out;
6810
0
        } else if (VK_SUCCESS == res) {
6811
0
            icd_phys_dev_array[icd_idx].physical_devices =
6812
0
                (VkPhysicalDevice *)loader_stack_alloc(icd_phys_dev_array[icd_idx].device_count * sizeof(VkPhysicalDevice));
6813
0
            if (NULL == icd_phys_dev_array[icd_idx].physical_devices) {
6814
0
                loader_log(
6815
0
                    inst, VULKAN_LOADER_ERROR_BIT, 0,
6816
0
                    "setup_loader_term_phys_devs: Failed to allocate temporary ICD Physical device array for ICD %s of size %d",
6817
0
                    icd_term->scanned_icd->lib_name, icd_phys_dev_array[icd_idx].device_count);
6818
0
                res = VK_ERROR_OUT_OF_HOST_MEMORY;
6819
0
                goto out;
6820
0
            }
6821
6822
0
            res = icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &(icd_phys_dev_array[icd_idx].device_count),
6823
0
                                                              icd_phys_dev_array[icd_idx].physical_devices);
6824
0
            if (VK_ERROR_OUT_OF_HOST_MEMORY == res) {
6825
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6826
0
                           "setup_loader_term_phys_devs: Call to \'vkEnumeratePhysicalDevices\' in ICD %s failed with error code "
6827
0
                           "VK_ERROR_OUT_OF_HOST_MEMORY",
6828
0
                           icd_term->scanned_icd->lib_name);
6829
0
                goto out;
6830
0
            }
6831
0
            if (VK_SUCCESS != res) {
6832
0
                loader_log(
6833
0
                    inst, VULKAN_LOADER_ERROR_BIT, 0,
6834
0
                    "setup_loader_term_phys_devs: Call to \'vkEnumeratePhysicalDevices\' in ICD %s failed with error code %d",
6835
0
                    icd_term->scanned_icd->lib_name, res);
6836
0
                icd_phys_dev_array[icd_idx].device_count = 0;
6837
0
                icd_phys_dev_array[icd_idx].physical_devices = 0;
6838
0
            }
6839
0
        } else {
6840
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6841
0
                       "setup_loader_term_phys_devs: Call to \'vkEnumeratePhysicalDevices\' in ICD %s failed with error code %d",
6842
0
                       icd_term->scanned_icd->lib_name, res);
6843
0
            icd_phys_dev_array[icd_idx].device_count = 0;
6844
0
            icd_phys_dev_array[icd_idx].physical_devices = 0;
6845
0
        }
6846
0
        icd_phys_dev_array[icd_idx].icd_term = icd_term;
6847
0
        icd_term->physical_device_count = icd_phys_dev_array[icd_idx].device_count;
6848
0
        icd_term = icd_term->next;
6849
0
        ++icd_idx;
6850
0
    }
6851
6852
    // Add up both the windows sorted and non windows found physical device counts
6853
0
    for (uint32_t i = 0; i < windows_sorted_devices_count; ++i) {
6854
0
        new_phys_devs_capacity += windows_sorted_devices_array[i].device_count;
6855
0
    }
6856
0
    for (uint32_t i = 0; i < icd_count; ++i) {
6857
0
        new_phys_devs_capacity += icd_phys_dev_array[i].device_count;
6858
0
    }
6859
6860
    // Bail out if there are no physical devices reported
6861
0
    if (0 == new_phys_devs_capacity) {
6862
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6863
0
                   "setup_loader_term_phys_devs:  Failed to detect any valid GPUs in the current config");
6864
0
        res = VK_ERROR_INITIALIZATION_FAILED;
6865
0
        goto out;
6866
0
    }
6867
6868
    // Create an allocation large enough to hold both the windows sorting enumeration and non-windows physical device
6869
    // enumeration
6870
0
    new_phys_devs = loader_instance_heap_calloc(inst, sizeof(struct loader_physical_device_term *) * new_phys_devs_capacity,
6871
0
                                                VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6872
0
    if (NULL == new_phys_devs) {
6873
0
        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6874
0
                   "setup_loader_term_phys_devs:  Failed to allocate new physical device array of size %d", new_phys_devs_capacity);
6875
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
6876
0
        goto out;
6877
0
    }
6878
6879
    // Copy over everything found through sorted enumeration
6880
0
    for (uint32_t i = 0; i < windows_sorted_devices_count; ++i) {
6881
0
        for (uint32_t j = 0; j < windows_sorted_devices_array[i].device_count; ++j) {
6882
0
            res = check_and_add_to_new_phys_devs(inst, windows_sorted_devices_array[i].physical_devices[j],
6883
0
                                                 &windows_sorted_devices_array[i], &new_phys_devs_count, new_phys_devs);
6884
0
            if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
6885
0
                goto out;
6886
0
            }
6887
0
        }
6888
0
    }
6889
6890
// Now go through the rest of the physical devices and add them to new_phys_devs
6891
0
#if defined(LOADER_ENABLE_LINUX_SORT)
6892
6893
0
    if (is_linux_sort_enabled(inst)) {
6894
0
        for (uint32_t dev = new_phys_devs_count; dev < new_phys_devs_capacity; ++dev) {
6895
0
            new_phys_devs[dev] =
6896
0
                loader_instance_heap_alloc(inst, sizeof(struct loader_physical_device_term), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
6897
0
            if (NULL == new_phys_devs[dev]) {
6898
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
6899
0
                           "setup_loader_term_phys_devs:  Failed to allocate physical device terminator object %d", dev);
6900
0
                res = VK_ERROR_OUT_OF_HOST_MEMORY;
6901
0
                goto out;
6902
0
            }
6903
0
        }
6904
6905
        // Get the physical devices supported by platform sorting mechanism into a separate list
6906
        // Pass in a sublist to the function so it only operates on the correct elements. This means passing in a pointer to the
6907
        // current next element in new_phys_devs and passing in a `count` of currently unwritten elements
6908
0
        res = linux_read_sorted_physical_devices(inst, icd_count, icd_phys_dev_array, new_phys_devs_capacity - new_phys_devs_count,
6909
0
                                                 &new_phys_devs[new_phys_devs_count]);
6910
0
        if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
6911
0
            goto out;
6912
0
        }
6913
        // Keep previously allocated physical device info since apps may already be using that!
6914
0
        for (uint32_t new_idx = new_phys_devs_count; new_idx < new_phys_devs_capacity; new_idx++) {
6915
0
            for (uint32_t old_idx = 0; old_idx < inst->phys_dev_count_term; old_idx++) {
6916
0
                if (new_phys_devs[new_idx]->phys_dev == inst->phys_devs_term[old_idx]->phys_dev) {
6917
0
                    loader_log(inst, VULKAN_LOADER_DEBUG_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
6918
0
                               "Copying old device %u into new device %u", old_idx, new_idx);
6919
                    // Free the old new_phys_devs info since we're not using it before we assign the new info
6920
0
                    loader_instance_heap_free(inst, new_phys_devs[new_idx]);
6921
0
                    new_phys_devs[new_idx] = inst->phys_devs_term[old_idx];
6922
0
                    break;
6923
0
                }
6924
0
            }
6925
0
        }
6926
        // now set the count to the capacity, as now the list is filled in
6927
0
        new_phys_devs_count = new_phys_devs_capacity;
6928
        // We want the following code to run if either linux sorting is disabled at compile time or runtime
6929
0
    } else {
6930
0
#endif  // LOADER_ENABLE_LINUX_SORT
6931
6932
        // Copy over everything found through the non-sorted means.
6933
0
        for (uint32_t i = 0; i < icd_count; ++i) {
6934
0
            for (uint32_t j = 0; j < icd_phys_dev_array[i].device_count; ++j) {
6935
0
                res = check_and_add_to_new_phys_devs(inst, icd_phys_dev_array[i].physical_devices[j], &icd_phys_dev_array[i],
6936
0
                                                     &new_phys_devs_count, new_phys_devs);
6937
0
                if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
6938
0
                    goto out;
6939
0
                }
6940
0
            }
6941
0
        }
6942
0
#if defined(LOADER_ENABLE_LINUX_SORT)
6943
0
    }
6944
0
#endif  // LOADER_ENABLE_LINUX_SORT
6945
0
out:
6946
6947
0
    if (VK_SUCCESS != res) {
6948
0
        if (NULL != new_phys_devs) {
6949
            // We've encountered an error, so we should free the new buffers.
6950
0
            for (uint32_t i = 0; i < new_phys_devs_capacity; i++) {
6951
                // May not have allocated this far, skip it if we hadn't.
6952
0
                if (new_phys_devs[i] == NULL) continue;
6953
6954
                // If an OOM occurred inside the copying of the new physical devices into the existing array
6955
                // will leave some of the old physical devices in the array which may have been copied into
6956
                // the new array, leading to them being freed twice. To avoid this we just make sure to not
6957
                // delete physical devices which were copied.
6958
0
                bool found = false;
6959
0
                if (NULL != inst->phys_devs_term) {
6960
0
                    for (uint32_t old_idx = 0; old_idx < inst->phys_dev_count_term; old_idx++) {
6961
0
                        if (new_phys_devs[i] == inst->phys_devs_term[old_idx]) {
6962
0
                            found = true;
6963
0
                            break;
6964
0
                        }
6965
0
                    }
6966
0
                }
6967
0
                if (!found) {
6968
0
                    loader_instance_heap_free(inst, new_phys_devs[i]);
6969
0
                }
6970
0
            }
6971
0
            loader_instance_heap_free(inst, new_phys_devs);
6972
0
        }
6973
0
        inst->total_gpu_count = 0;
6974
0
    } else {
6975
0
        if (NULL != inst->phys_devs_term) {
6976
            // Free everything in the old array that was not copied into the new array
6977
            // here.  We can't attempt to do that before here since the previous loop
6978
            // looking before the "out:" label may hit an out of memory condition resulting
6979
            // in memory leaking.
6980
0
            for (uint32_t i = 0; i < inst->phys_dev_count_term; i++) {
6981
0
                bool found = false;
6982
0
                for (uint32_t j = 0; j < new_phys_devs_count; j++) {
6983
0
                    if (new_phys_devs != NULL && inst->phys_devs_term[i] == new_phys_devs[j]) {
6984
0
                        found = true;
6985
0
                        break;
6986
0
                    }
6987
0
                }
6988
0
                if (!found) {
6989
0
                    loader_instance_heap_free(inst, inst->phys_devs_term[i]);
6990
0
                }
6991
0
            }
6992
0
            loader_instance_heap_free(inst, inst->phys_devs_term);
6993
0
        }
6994
6995
        // Swap out old and new devices list
6996
0
        inst->phys_dev_count_term = new_phys_devs_count;
6997
0
        inst->phys_devs_term = new_phys_devs;
6998
0
        inst->total_gpu_count = new_phys_devs_count;
6999
0
    }
7000
7001
0
    if (windows_sorted_devices_array != NULL) {
7002
0
        for (uint32_t i = 0; i < windows_sorted_devices_count; ++i) {
7003
0
            if (windows_sorted_devices_array[i].device_count > 0 && windows_sorted_devices_array[i].physical_devices != NULL) {
7004
0
                loader_instance_heap_free(inst, windows_sorted_devices_array[i].physical_devices);
7005
0
            }
7006
0
        }
7007
0
        loader_instance_heap_free(inst, windows_sorted_devices_array);
7008
0
    }
7009
7010
0
    return res;
7011
0
}
7012
/**
7013
 * Iterates through all drivers and unloads any which do not contain physical devices.
7014
 * This saves address space, which for 32 bit applications is scarce.
7015
 * This must only be called after a call to vkEnumeratePhysicalDevices that isn't just querying the count
7016
 */
7017
0
void unload_drivers_without_physical_devices(struct loader_instance *inst) {
7018
0
    struct loader_icd_term *cur_icd_term = inst->icd_terms;
7019
0
    struct loader_icd_term *prev_icd_term = NULL;
7020
7021
0
    while (NULL != cur_icd_term) {
7022
0
        struct loader_icd_term *next_icd_term = cur_icd_term->next;
7023
0
        if (cur_icd_term->physical_device_count == 0) {
7024
0
            uint32_t cur_scanned_icd_index = UINT32_MAX;
7025
0
            if (inst->icd_tramp_list.scanned_list) {
7026
0
                for (uint32_t i = 0; i < inst->icd_tramp_list.count; i++) {
7027
0
                    if (&(inst->icd_tramp_list.scanned_list[i]) == cur_icd_term->scanned_icd) {
7028
0
                        cur_scanned_icd_index = i;
7029
0
                        break;
7030
0
                    }
7031
0
                }
7032
0
            }
7033
0
            if (cur_scanned_icd_index != UINT32_MAX) {
7034
0
                loader_log(inst, VULKAN_LOADER_INFO_BIT | VULKAN_LOADER_DRIVER_BIT, 0,
7035
0
                           "Removing driver %s due to not having any physical devices", cur_icd_term->scanned_icd->lib_name);
7036
7037
0
                const VkAllocationCallbacks *allocation_callbacks = ignore_null_callback(&(inst->alloc_callbacks));
7038
0
                if (cur_icd_term->instance) {
7039
0
                    loader_icd_close_objects(inst, cur_icd_term);
7040
0
                    cur_icd_term->dispatch.DestroyInstance(cur_icd_term->instance, allocation_callbacks);
7041
0
                }
7042
0
                cur_icd_term->instance = VK_NULL_HANDLE;
7043
0
                loader_icd_destroy(inst, cur_icd_term, allocation_callbacks);
7044
0
                cur_icd_term = NULL;
7045
0
                struct loader_scanned_icd *scanned_icd_to_remove = &inst->icd_tramp_list.scanned_list[cur_scanned_icd_index];
7046
                // Iterate through preloaded ICDs and remove the corresponding driver from that list
7047
0
                loader_platform_thread_lock_mutex(&loader_preload_icd_lock);
7048
0
                if (NULL != preloaded_icds.scanned_list) {
7049
0
                    for (uint32_t i = 0; i < preloaded_icds.count; i++) {
7050
0
                        if (NULL != preloaded_icds.scanned_list[i].lib_name && NULL != scanned_icd_to_remove->lib_name &&
7051
0
                            strcmp(preloaded_icds.scanned_list[i].lib_name, scanned_icd_to_remove->lib_name) == 0) {
7052
0
                            loader_unload_scanned_icd(NULL, &preloaded_icds.scanned_list[i]);
7053
                            // condense the list so that it doesn't contain empty elements.
7054
0
                            if (i < preloaded_icds.count - 1) {
7055
0
                                memcpy((void *)&preloaded_icds.scanned_list[i],
7056
0
                                       (void *)&preloaded_icds.scanned_list[preloaded_icds.count - 1],
7057
0
                                       sizeof(struct loader_scanned_icd));
7058
0
                                memset((void *)&preloaded_icds.scanned_list[preloaded_icds.count - 1], 0,
7059
0
                                       sizeof(struct loader_scanned_icd));
7060
0
                            }
7061
0
                            if (i > 0) {
7062
0
                                preloaded_icds.count--;
7063
0
                            }
7064
7065
0
                            break;
7066
0
                        }
7067
0
                    }
7068
0
                }
7069
0
                loader_platform_thread_unlock_mutex(&loader_preload_icd_lock);
7070
7071
0
                loader_unload_scanned_icd(inst, scanned_icd_to_remove);
7072
0
            }
7073
7074
0
            if (NULL == prev_icd_term) {
7075
0
                inst->icd_terms = next_icd_term;
7076
0
            } else {
7077
0
                prev_icd_term->next = next_icd_term;
7078
0
            }
7079
0
        } else {
7080
0
            prev_icd_term = cur_icd_term;
7081
0
        }
7082
0
        cur_icd_term = next_icd_term;
7083
0
    }
7084
0
}
7085
7086
VkResult setup_loader_tramp_phys_dev_groups(struct loader_instance *inst, uint32_t group_count,
7087
0
                                            VkPhysicalDeviceGroupProperties *groups) {
7088
0
    VkResult res = VK_SUCCESS;
7089
0
    uint32_t cur_idx;
7090
0
    uint32_t dev_idx;
7091
7092
0
    if (0 == group_count) {
7093
0
        return VK_SUCCESS;
7094
0
    }
7095
7096
    // Generate a list of all the devices and convert them to the loader ID
7097
0
    uint32_t phys_dev_count = 0;
7098
0
    for (cur_idx = 0; cur_idx < group_count; ++cur_idx) {
7099
0
        phys_dev_count += groups[cur_idx].physicalDeviceCount;
7100
0
    }
7101
0
    VkPhysicalDevice *devices = (VkPhysicalDevice *)loader_stack_alloc(sizeof(VkPhysicalDevice) * phys_dev_count);
7102
0
    if (NULL == devices) {
7103
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
7104
0
    }
7105
7106
0
    uint32_t cur_device = 0;
7107
0
    for (cur_idx = 0; cur_idx < group_count; ++cur_idx) {
7108
0
        for (dev_idx = 0; dev_idx < groups[cur_idx].physicalDeviceCount; ++dev_idx) {
7109
0
            devices[cur_device++] = groups[cur_idx].physicalDevices[dev_idx];
7110
0
        }
7111
0
    }
7112
7113
    // Update the devices based on the loader physical device values.
7114
0
    res = setup_loader_tramp_phys_devs(inst, phys_dev_count, devices);
7115
0
    if (VK_SUCCESS != res) {
7116
0
        return res;
7117
0
    }
7118
7119
    // Update the devices in the group structures now
7120
0
    cur_device = 0;
7121
0
    for (cur_idx = 0; cur_idx < group_count; ++cur_idx) {
7122
0
        for (dev_idx = 0; dev_idx < groups[cur_idx].physicalDeviceCount; ++dev_idx) {
7123
0
            groups[cur_idx].physicalDevices[dev_idx] = devices[cur_device++];
7124
0
        }
7125
0
    }
7126
7127
0
    return res;
7128
0
}
7129
7130
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumeratePhysicalDevices(VkInstance instance, uint32_t *pPhysicalDeviceCount,
7131
0
                                                                   VkPhysicalDevice *pPhysicalDevices) {
7132
0
    struct loader_instance *inst = (struct loader_instance *)instance;
7133
0
    VkResult res = VK_SUCCESS;
7134
7135
    // Always call the setup loader terminator physical devices because they may
7136
    // have changed at any point.
7137
0
    res = setup_loader_term_phys_devs(inst);
7138
0
    if (VK_SUCCESS != res) {
7139
0
        goto out;
7140
0
    }
7141
7142
0
    if (inst->settings.settings_active && inst->settings.device_configurations_active) {
7143
        // Use settings file device_configurations if present
7144
0
        if (NULL == pPhysicalDevices) {
7145
            // take the minimum of the settings configurations count and number of terminators
7146
0
            *pPhysicalDeviceCount = (inst->settings.device_configuration_count < inst->phys_dev_count_term)
7147
0
                                        ? inst->settings.device_configuration_count
7148
0
                                        : inst->phys_dev_count_term;
7149
0
        } else {
7150
0
            res = loader_apply_settings_device_configurations(inst, pPhysicalDeviceCount, pPhysicalDevices);
7151
0
        }
7152
0
    } else {
7153
        // Otherwise just copy the physical devices up normally and pass it up the chain
7154
0
        uint32_t copy_count = inst->phys_dev_count_term;
7155
0
        if (NULL != pPhysicalDevices) {
7156
0
            if (copy_count > *pPhysicalDeviceCount) {
7157
0
                copy_count = *pPhysicalDeviceCount;
7158
0
                loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
7159
0
                           "terminator_EnumeratePhysicalDevices : Trimming device count from %d to %d.", inst->phys_dev_count_term,
7160
0
                           copy_count);
7161
0
                res = VK_INCOMPLETE;
7162
0
            }
7163
7164
0
            for (uint32_t i = 0; i < copy_count; i++) {
7165
0
                pPhysicalDevices[i] = (VkPhysicalDevice)inst->phys_devs_term[i];
7166
0
            }
7167
0
        }
7168
7169
0
        *pPhysicalDeviceCount = copy_count;
7170
0
    }
7171
7172
0
out:
7173
7174
0
    return res;
7175
0
}
7176
7177
VkResult check_physical_device_extensions_for_driver_properties_extension(struct loader_physical_device_term *phys_dev_term,
7178
0
                                                                          bool *supports_driver_properties) {
7179
0
    *supports_driver_properties = false;
7180
0
    uint32_t extension_count = 0;
7181
0
    VkResult res = phys_dev_term->this_icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL,
7182
0
                                                                                             &extension_count, NULL);
7183
0
    if (res != VK_SUCCESS || extension_count == 0) {
7184
0
        return VK_SUCCESS;
7185
0
    }
7186
0
    VkExtensionProperties *extension_data = loader_stack_alloc(sizeof(VkExtensionProperties) * extension_count);
7187
0
    if (NULL == extension_data) {
7188
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
7189
0
    }
7190
7191
0
    res = phys_dev_term->this_icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL, &extension_count,
7192
0
                                                                                    extension_data);
7193
0
    if (res != VK_SUCCESS) {
7194
0
        return VK_SUCCESS;
7195
0
    }
7196
0
    for (uint32_t j = 0; j < extension_count; j++) {
7197
0
        if (!strcmp(extension_data[j].extensionName, VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME)) {
7198
0
            *supports_driver_properties = true;
7199
0
            return VK_SUCCESS;
7200
0
        }
7201
0
    }
7202
0
    return VK_SUCCESS;
7203
0
}
7204
7205
// Helper struct containing the relevant details of a VkPhysicalDevice necessary for applying the loader settings device
7206
// configurations.
7207
typedef struct physical_device_configuration_details {
7208
    bool pd_was_added;
7209
    bool pd_supports_vulkan_11;
7210
    bool pd_supports_driver_properties;
7211
    VkPhysicalDeviceProperties properties;
7212
    VkPhysicalDeviceIDProperties device_id_properties;
7213
    VkPhysicalDeviceDriverProperties driver_properties;
7214
7215
} physical_device_configuration_details;
7216
7217
// Apply the device_configurations in the settings file to the output VkPhysicalDeviceList.
7218
// That means looking up each VkPhysicalDevice's deviceUUID, filtering using that, and putting them in the order of
7219
// device_configurations in the settings file.
7220
VkResult loader_apply_settings_device_configurations(struct loader_instance *inst, uint32_t *pPhysicalDeviceCount,
7221
0
                                                     VkPhysicalDevice *pPhysicalDevices) {
7222
0
    loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
7223
0
               "Reordering the output of vkEnumeratePhysicalDevices to match the loader settings device configurations list");
7224
7225
0
    physical_device_configuration_details *pd_details =
7226
0
        loader_stack_alloc(inst->phys_dev_count_term * sizeof(physical_device_configuration_details));
7227
0
    if (NULL == pd_details) {
7228
0
        return VK_ERROR_OUT_OF_HOST_MEMORY;
7229
0
    }
7230
0
    memset(pd_details, 0, inst->phys_dev_count_term * sizeof(physical_device_configuration_details));
7231
7232
0
    for (uint32_t i = 0; i < inst->phys_dev_count_term; i++) {
7233
0
        struct loader_physical_device_term *phys_dev_term = inst->phys_devs_term[i];
7234
7235
0
        phys_dev_term->this_icd_term->dispatch.GetPhysicalDeviceProperties(phys_dev_term->phys_dev, &pd_details[i].properties);
7236
0
        if (pd_details[i].properties.apiVersion < VK_API_VERSION_1_1) {
7237
            // Device isn't eligible for sorting
7238
0
            continue;
7239
0
        }
7240
0
        pd_details[i].pd_supports_vulkan_11 = true;
7241
0
        if (pd_details[i].properties.apiVersion >= VK_API_VERSION_1_2) {
7242
0
            pd_details[i].pd_supports_driver_properties = true;
7243
0
        }
7244
7245
        // If this physical device isn't 1.2, then we need to check if it supports VK_KHR_driver_properties
7246
0
        if (!pd_details[i].pd_supports_driver_properties) {
7247
0
            VkResult res = check_physical_device_extensions_for_driver_properties_extension(
7248
0
                phys_dev_term, &pd_details[i].pd_supports_driver_properties);
7249
0
            if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {
7250
0
                return res;
7251
0
            }
7252
0
        }
7253
7254
0
        pd_details[i].device_id_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES;
7255
0
        pd_details[i].driver_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES;
7256
0
        if (pd_details[i].pd_supports_driver_properties) {
7257
0
            pd_details[i].device_id_properties.pNext = (void *)&pd_details[i].driver_properties;
7258
0
        }
7259
7260
0
        VkPhysicalDeviceProperties2 props2 = {0};
7261
0
        props2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
7262
0
        props2.pNext = (void *)&pd_details[i].device_id_properties;
7263
0
        if (phys_dev_term->this_icd_term->dispatch.GetPhysicalDeviceProperties2) {
7264
0
            phys_dev_term->this_icd_term->dispatch.GetPhysicalDeviceProperties2(phys_dev_term->phys_dev, &props2);
7265
0
        }
7266
0
    }
7267
7268
    // Loop over the setting's device configurations, find each VkPhysicalDevice which matches the deviceUUID given, add to the
7269
    // pPhysicalDevices output list.
7270
0
    uint32_t written_output_index = 0;
7271
7272
0
    for (uint32_t i = 0; i < inst->settings.device_configuration_count; i++) {
7273
0
        uint8_t *current_deviceUUID = inst->settings.device_configurations[i].deviceUUID;
7274
0
        uint8_t *current_driverUUID = inst->settings.device_configurations[i].driverUUID;
7275
0
        bool configuration_found = false;
7276
0
        for (uint32_t j = 0; j < inst->phys_dev_count_term; j++) {
7277
            // Don't compare deviceUUID's if they have nothing, since we require deviceUUID's to effectively sort them.
7278
0
            if (!pd_details[j].pd_supports_vulkan_11) {
7279
0
                continue;
7280
0
            }
7281
0
            if (memcmp(current_deviceUUID, pd_details[j].device_id_properties.deviceUUID, sizeof(uint8_t) * VK_UUID_SIZE) == 0 &&
7282
0
                memcmp(current_driverUUID, pd_details[j].device_id_properties.driverUUID, sizeof(uint8_t) * VK_UUID_SIZE) == 0 &&
7283
0
                inst->settings.device_configurations[i].driverVersion == pd_details[j].properties.driverVersion) {
7284
0
                configuration_found = true;
7285
                // Catch when there are more device_configurations than space available in the output
7286
0
                if (written_output_index >= *pPhysicalDeviceCount) {
7287
0
                    *pPhysicalDeviceCount = written_output_index;  // write out how many were written
7288
0
                    return VK_INCOMPLETE;
7289
0
                }
7290
0
                if (pd_details[j].pd_supports_driver_properties) {
7291
0
                    loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
7292
0
                               "pPhysicalDevices array index %d is set to \"%s\" (%s, version %d) ", written_output_index,
7293
0
                               pd_details[j].properties.deviceName, pd_details[i].driver_properties.driverName,
7294
0
                               pd_details[i].properties.driverVersion);
7295
0
                } else {
7296
0
                    loader_log(inst, VULKAN_LOADER_DEBUG_BIT, 0,
7297
0
                               "pPhysicalDevices array index %d is set to \"%s\" (driver version %d) ", written_output_index,
7298
0
                               pd_details[j].properties.deviceName, pd_details[i].properties.driverVersion);
7299
0
                }
7300
0
                pPhysicalDevices[written_output_index++] = (VkPhysicalDevice)inst->phys_devs_term[j];
7301
0
                pd_details[j].pd_was_added = true;
7302
0
                break;
7303
0
            }
7304
0
        }
7305
0
        if (!configuration_found) {
7306
0
            char device_uuid_str[UUID_STR_LEN] = {0};
7307
0
            loader_log_generate_uuid_string(current_deviceUUID, device_uuid_str);
7308
0
            char driver_uuid_str[UUID_STR_LEN] = {0};
7309
0
            loader_log_generate_uuid_string(current_deviceUUID, driver_uuid_str);
7310
7311
            // Log that this configuration was missing.
7312
0
            if (inst->settings.device_configurations[i].deviceName[0] != '\0' &&
7313
0
                inst->settings.device_configurations[i].driverName[0] != '\0') {
7314
0
                loader_log(
7315
0
                    inst, VULKAN_LOADER_WARN_BIT, 0,
7316
0
                    "loader_apply_settings_device_configurations: settings file contained device_configuration which does not "
7317
0
                    "appear in the enumerated VkPhysicalDevices. Missing VkPhysicalDevice with deviceName: \"%s\", "
7318
0
                    "deviceUUID: %s, driverName: %s, driverUUID: %s, driverVersion: %d",
7319
0
                    inst->settings.device_configurations[i].deviceName, device_uuid_str,
7320
0
                    inst->settings.device_configurations[i].driverName, driver_uuid_str,
7321
0
                    inst->settings.device_configurations[i].driverVersion);
7322
0
            } else if (inst->settings.device_configurations[i].deviceName[0] != '\0') {
7323
0
                loader_log(
7324
0
                    inst, VULKAN_LOADER_WARN_BIT, 0,
7325
0
                    "loader_apply_settings_device_configurations: settings file contained device_configuration which does not "
7326
0
                    "appear in the enumerated VkPhysicalDevices. Missing VkPhysicalDevice with deviceName: \"%s\", "
7327
0
                    "deviceUUID: %s, driverUUID: %s, driverVersion: %d",
7328
0
                    inst->settings.device_configurations[i].deviceName, device_uuid_str, driver_uuid_str,
7329
0
                    inst->settings.device_configurations[i].driverVersion);
7330
0
            } else {
7331
0
                loader_log(
7332
0
                    inst, VULKAN_LOADER_WARN_BIT, 0,
7333
0
                    "loader_apply_settings_device_configurations: settings file contained device_configuration which does not "
7334
0
                    "appear in the enumerated VkPhysicalDevices. Missing VkPhysicalDevice with deviceUUID: "
7335
0
                    "%s, driverUUID: %s, driverVersion: %d",
7336
0
                    device_uuid_str, driver_uuid_str, inst->settings.device_configurations[i].driverVersion);
7337
0
            }
7338
0
        }
7339
0
    }
7340
7341
0
    for (uint32_t j = 0; j < inst->phys_dev_count_term; j++) {
7342
0
        if (!pd_details[j].pd_was_added) {
7343
0
            loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
7344
0
                       "VkPhysicalDevice \"%s\" did not appear in the settings file device configurations list, so was not added "
7345
0
                       "to the pPhysicalDevices array",
7346
0
                       pd_details[j].properties.deviceName);
7347
0
        }
7348
0
    }
7349
7350
0
    if (written_output_index == 0) {
7351
0
        loader_log(inst, VULKAN_LOADER_WARN_BIT, 0,
7352
0
                   "loader_apply_settings_device_configurations: None of the settings file device configurations had "
7353
0
                   "deviceUUID's that corresponded to enumerated VkPhysicalDevices. Returning VK_ERROR_INITIALIZATION_FAILED");
7354
0
        return VK_ERROR_INITIALIZATION_FAILED;
7355
0
    }
7356
7357
0
    *pPhysicalDeviceCount = written_output_index;  // update with how many were written
7358
0
    return VK_SUCCESS;
7359
0
}
7360
7361
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,
7362
                                                                             const char *pLayerName, uint32_t *pPropertyCount,
7363
0
                                                                             VkExtensionProperties *pProperties) {
7364
0
    if (NULL == pPropertyCount) {
7365
0
        return VK_INCOMPLETE;
7366
0
    }
7367
7368
0
    struct loader_physical_device_term *phys_dev_term;
7369
7370
    // Any layer or trampoline wrapping should be removed at this point in time can just cast to the expected
7371
    // type for VkPhysicalDevice.
7372
0
    phys_dev_term = (struct loader_physical_device_term *)physicalDevice;
7373
7374
    // if we got here with a non-empty pLayerName, look up the extensions
7375
    // from the json
7376
0
    if (pLayerName != NULL && strlen(pLayerName) > 0) {
7377
0
        uint32_t count;
7378
0
        uint32_t copy_size;
7379
0
        const struct loader_instance *inst = phys_dev_term->this_icd_term->this_instance;
7380
0
        struct loader_device_extension_list *dev_ext_list = NULL;
7381
0
        struct loader_device_extension_list local_ext_list;
7382
0
        memset(&local_ext_list, 0, sizeof(local_ext_list));
7383
0
        if (vk_string_validate(MaxLoaderStringLength, pLayerName) == VK_STRING_ERROR_NONE) {
7384
0
            for (uint32_t i = 0; i < inst->instance_layer_list.count; i++) {
7385
0
                struct loader_layer_properties *props = &inst->instance_layer_list.list[i];
7386
0
                if (strcmp(props->info.layerName, pLayerName) == 0) {
7387
0
                    dev_ext_list = &props->device_extension_list;
7388
0
                }
7389
0
            }
7390
7391
0
            count = (dev_ext_list == NULL) ? 0 : dev_ext_list->count;
7392
0
            if (pProperties == NULL) {
7393
0
                *pPropertyCount = count;
7394
0
                loader_destroy_generic_list(inst, (struct loader_generic_list *)&local_ext_list);
7395
0
                return VK_SUCCESS;
7396
0
            }
7397
7398
0
            copy_size = *pPropertyCount < count ? *pPropertyCount : count;
7399
0
            for (uint32_t i = 0; i < copy_size; i++) {
7400
0
                memcpy(&pProperties[i], &dev_ext_list->list[i].props, sizeof(VkExtensionProperties));
7401
0
            }
7402
0
            *pPropertyCount = copy_size;
7403
7404
0
            loader_destroy_generic_list(inst, (struct loader_generic_list *)&local_ext_list);
7405
0
            if (copy_size < count) {
7406
0
                return VK_INCOMPLETE;
7407
0
            }
7408
0
        } else {
7409
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7410
0
                       "vkEnumerateDeviceExtensionProperties:  pLayerName is too long or is badly formed");
7411
0
            return VK_ERROR_EXTENSION_NOT_PRESENT;
7412
0
        }
7413
7414
0
        return VK_SUCCESS;
7415
0
    }
7416
7417
    // user is querying driver extensions and has supplied their own storage - just fill it out
7418
0
    else if (pProperties) {
7419
0
        struct loader_icd_term *icd_term = phys_dev_term->this_icd_term;
7420
0
        uint32_t written_count = *pPropertyCount;
7421
0
        VkResult res =
7422
0
            icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL, &written_count, pProperties);
7423
0
        if (res != VK_SUCCESS) {
7424
0
            return res;
7425
0
        }
7426
7427
        // Iterate over active layers, if they are an implicit layer, add their device extensions
7428
        // After calling into the driver, written_count contains the amount of device extensions written. We can therefore write
7429
        // layer extensions starting at that point in pProperties
7430
0
        for (uint32_t i = 0; i < icd_term->this_instance->expanded_activated_layer_list.count; i++) {
7431
0
            struct loader_layer_properties *layer_props = icd_term->this_instance->expanded_activated_layer_list.list[i];
7432
0
            if (0 == (layer_props->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
7433
0
                struct loader_device_extension_list *layer_ext_list = &layer_props->device_extension_list;
7434
0
                for (uint32_t j = 0; j < layer_ext_list->count; j++) {
7435
0
                    struct loader_dev_ext_props *cur_ext_props = &layer_ext_list->list[j];
7436
                    // look for duplicates
7437
0
                    if (has_vk_extension_property_array(&cur_ext_props->props, written_count, pProperties)) {
7438
0
                        continue;
7439
0
                    }
7440
7441
0
                    if (*pPropertyCount <= written_count) {
7442
0
                        return VK_INCOMPLETE;
7443
0
                    }
7444
7445
0
                    memcpy(&pProperties[written_count], &cur_ext_props->props, sizeof(VkExtensionProperties));
7446
0
                    written_count++;
7447
0
                }
7448
0
            }
7449
0
        }
7450
        // Make sure we update the pPropertyCount with the how many were written
7451
0
        *pPropertyCount = written_count;
7452
0
        return res;
7453
0
    }
7454
    // Use `goto out;` for rest of this function
7455
7456
    // This case is during the call down the instance chain with pLayerName == NULL and pProperties == NULL
7457
0
    struct loader_icd_term *icd_term = phys_dev_term->this_icd_term;
7458
0
    struct loader_extension_list all_exts = {0};
7459
0
    VkResult res;
7460
7461
    // We need to find the count without duplicates. This requires querying the driver for the names of the extensions.
7462
0
    res = icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL, &all_exts.count, NULL);
7463
0
    if (res != VK_SUCCESS) {
7464
0
        goto out;
7465
0
    }
7466
    // Then allocate memory to store the physical device extension list + the extensions layers provide
7467
    // all_exts.count currently is the number of driver extensions
7468
0
    all_exts.capacity = sizeof(VkExtensionProperties) * (all_exts.count + 20);
7469
0
    all_exts.list = loader_instance_heap_alloc(icd_term->this_instance, all_exts.capacity, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
7470
0
    if (NULL == all_exts.list) {
7471
0
        res = VK_ERROR_OUT_OF_HOST_MEMORY;
7472
0
        goto out;
7473
0
    }
7474
7475
    // Get the available device extensions and put them in all_exts.list
7476
0
    res = icd_term->dispatch.EnumerateDeviceExtensionProperties(phys_dev_term->phys_dev, NULL, &all_exts.count, all_exts.list);
7477
0
    if (res != VK_SUCCESS) {
7478
0
        goto out;
7479
0
    }
7480
7481
    // Iterate over active layers, if they are an implicit layer, add their device extensions to all_exts.list
7482
0
    for (uint32_t i = 0; i < icd_term->this_instance->expanded_activated_layer_list.count; i++) {
7483
0
        struct loader_layer_properties *layer_props = icd_term->this_instance->expanded_activated_layer_list.list[i];
7484
0
        if (0 == (layer_props->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER)) {
7485
0
            struct loader_device_extension_list *layer_ext_list = &layer_props->device_extension_list;
7486
0
            for (uint32_t j = 0; j < layer_ext_list->count; j++) {
7487
0
                res = loader_add_to_ext_list(icd_term->this_instance, &all_exts, 1, &layer_ext_list->list[j].props);
7488
0
                if (res != VK_SUCCESS) {
7489
0
                    goto out;
7490
0
                }
7491
0
            }
7492
0
        }
7493
0
    }
7494
7495
    // Write out the final de-duplicated count to pPropertyCount
7496
0
    *pPropertyCount = all_exts.count;
7497
0
    res = VK_SUCCESS;
7498
7499
0
out:
7500
7501
0
    loader_destroy_generic_list(icd_term->this_instance, (struct loader_generic_list *)&all_exts);
7502
0
    return res;
7503
0
}
7504
7505
0
VkStringErrorFlags vk_string_validate(const int max_length, const char *utf8) {
7506
0
    VkStringErrorFlags result = VK_STRING_ERROR_NONE;
7507
0
    int num_char_bytes = 0;
7508
0
    int i, j;
7509
7510
0
    if (utf8 == NULL) {
7511
0
        return VK_STRING_ERROR_NULL_PTR;
7512
0
    }
7513
7514
0
    for (i = 0; i <= max_length; i++) {
7515
0
        if (utf8[i] == 0) {
7516
0
            break;
7517
0
        } else if (i == max_length) {
7518
0
            result |= VK_STRING_ERROR_LENGTH;
7519
0
            break;
7520
0
        } else if ((utf8[i] >= 0x20) && (utf8[i] < 0x7f)) {
7521
0
            num_char_bytes = 0;
7522
0
        } else if ((utf8[i] & UTF8_ONE_BYTE_MASK) == UTF8_ONE_BYTE_CODE) {
7523
0
            num_char_bytes = 1;
7524
0
        } else if ((utf8[i] & UTF8_TWO_BYTE_MASK) == UTF8_TWO_BYTE_CODE) {
7525
0
            num_char_bytes = 2;
7526
0
        } else if ((utf8[i] & UTF8_THREE_BYTE_MASK) == UTF8_THREE_BYTE_CODE) {
7527
0
            num_char_bytes = 3;
7528
0
        } else {
7529
0
            result = VK_STRING_ERROR_BAD_DATA;
7530
0
        }
7531
7532
        // Validate the following num_char_bytes of data
7533
0
        for (j = 0; (j < num_char_bytes) && (i < max_length); j++) {
7534
0
            if (++i == max_length) {
7535
0
                result |= VK_STRING_ERROR_LENGTH;
7536
0
                break;
7537
0
            }
7538
0
            if ((utf8[i] & UTF8_DATA_BYTE_MASK) != UTF8_DATA_BYTE_CODE) {
7539
0
                result |= VK_STRING_ERROR_BAD_DATA;
7540
0
            }
7541
0
        }
7542
0
    }
7543
0
    return result;
7544
0
}
7545
7546
0
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumerateInstanceVersion(uint32_t *pApiVersion) {
7547
    // NOTE: The Vulkan WG doesn't want us checking pApiVersion for NULL, but instead
7548
    // prefers us crashing.
7549
0
    *pApiVersion = VK_HEADER_VERSION_COMPLETE;
7550
0
    return VK_SUCCESS;
7551
0
}
7552
7553
VKAPI_ATTR VkResult VKAPI_CALL terminator_pre_instance_EnumerateInstanceVersion(const VkEnumerateInstanceVersionChain *chain,
7554
0
                                                                                uint32_t *pApiVersion) {
7555
0
    (void)chain;
7556
0
    return terminator_EnumerateInstanceVersion(pApiVersion);
7557
0
}
7558
7559
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pPropertyCount,
7560
0
                                                                               VkExtensionProperties *pProperties) {
7561
0
    struct loader_extension_list *global_ext_list = NULL;
7562
0
    struct loader_layer_list instance_layers;
7563
0
    struct loader_extension_list local_ext_list;
7564
0
    struct loader_icd_tramp_list icd_tramp_list;
7565
0
    uint32_t copy_size;
7566
0
    VkResult res = VK_SUCCESS;
7567
0
    struct loader_envvar_all_filters layer_filters = {0};
7568
7569
0
    memset(&local_ext_list, 0, sizeof(local_ext_list));
7570
0
    memset(&instance_layers, 0, sizeof(instance_layers));
7571
0
    memset(&icd_tramp_list, 0, sizeof(icd_tramp_list));
7572
7573
0
    res = parse_layer_environment_var_filters(NULL, &layer_filters);
7574
0
    if (VK_SUCCESS != res) {
7575
0
        goto out;
7576
0
    }
7577
7578
    // Get layer libraries if needed
7579
0
    if (pLayerName && strlen(pLayerName) != 0) {
7580
0
        if (vk_string_validate(MaxLoaderStringLength, pLayerName) != VK_STRING_ERROR_NONE) {
7581
0
            assert(VK_FALSE && "vkEnumerateInstanceExtensionProperties: pLayerName is too long or is badly formed");
7582
0
            res = VK_ERROR_EXTENSION_NOT_PRESENT;
7583
0
            goto out;
7584
0
        }
7585
7586
0
        res = loader_scan_for_layers(NULL, &instance_layers, &layer_filters);
7587
0
        if (VK_SUCCESS != res) {
7588
0
            goto out;
7589
0
        }
7590
0
        for (uint32_t i = 0; i < instance_layers.count; i++) {
7591
0
            struct loader_layer_properties *props = &instance_layers.list[i];
7592
0
            if (strcmp(props->info.layerName, pLayerName) == 0) {
7593
0
                global_ext_list = &props->instance_extension_list;
7594
0
                break;
7595
0
            }
7596
0
        }
7597
0
    } else {
7598
        // Preload ICD libraries so subsequent calls to EnumerateInstanceExtensionProperties don't have to load them
7599
0
        loader_preload_icds();
7600
7601
        // Scan/discover all ICD libraries
7602
0
        res = loader_icd_scan(NULL, &icd_tramp_list, NULL, NULL);
7603
        // EnumerateInstanceExtensionProperties can't return anything other than OOM or VK_ERROR_LAYER_NOT_PRESENT
7604
0
        if ((VK_SUCCESS != res && icd_tramp_list.count > 0) || res == VK_ERROR_OUT_OF_HOST_MEMORY) {
7605
0
            goto out;
7606
0
        }
7607
        // Get extensions from all ICD's, merge so no duplicates
7608
0
        res = loader_get_icd_loader_instance_extensions(NULL, &icd_tramp_list, &local_ext_list);
7609
0
        if (VK_SUCCESS != res) {
7610
0
            goto out;
7611
0
        }
7612
0
        loader_clear_scanned_icd_list(NULL, &icd_tramp_list);
7613
7614
        // Append enabled implicit layers.
7615
0
        res = loader_scan_for_implicit_layers(NULL, &instance_layers, &layer_filters);
7616
0
        if (VK_SUCCESS != res) {
7617
0
            goto out;
7618
0
        }
7619
0
        for (uint32_t i = 0; i < instance_layers.count; i++) {
7620
0
            struct loader_extension_list *ext_list = &instance_layers.list[i].instance_extension_list;
7621
0
            loader_add_to_ext_list(NULL, &local_ext_list, ext_list->count, ext_list->list);
7622
0
        }
7623
7624
0
        global_ext_list = &local_ext_list;
7625
0
    }
7626
7627
0
    if (global_ext_list == NULL) {
7628
0
        res = VK_ERROR_LAYER_NOT_PRESENT;
7629
0
        goto out;
7630
0
    }
7631
7632
0
    if (pProperties == NULL) {
7633
0
        *pPropertyCount = global_ext_list->count;
7634
0
        goto out;
7635
0
    }
7636
7637
0
    copy_size = *pPropertyCount < global_ext_list->count ? *pPropertyCount : global_ext_list->count;
7638
0
    for (uint32_t i = 0; i < copy_size; i++) {
7639
0
        memcpy(&pProperties[i], &global_ext_list->list[i], sizeof(VkExtensionProperties));
7640
0
    }
7641
0
    *pPropertyCount = copy_size;
7642
7643
0
    if (copy_size < global_ext_list->count) {
7644
0
        res = VK_INCOMPLETE;
7645
0
        goto out;
7646
0
    }
7647
7648
0
out:
7649
0
    loader_destroy_generic_list(NULL, (struct loader_generic_list *)&icd_tramp_list);
7650
0
    loader_destroy_generic_list(NULL, (struct loader_generic_list *)&local_ext_list);
7651
0
    loader_delete_layer_list_and_properties(NULL, &instance_layers);
7652
0
    return res;
7653
0
}
7654
7655
VKAPI_ATTR VkResult VKAPI_CALL terminator_pre_instance_EnumerateInstanceExtensionProperties(
7656
    const VkEnumerateInstanceExtensionPropertiesChain *chain, const char *pLayerName, uint32_t *pPropertyCount,
7657
0
    VkExtensionProperties *pProperties) {
7658
0
    (void)chain;
7659
0
    return terminator_EnumerateInstanceExtensionProperties(pLayerName, pPropertyCount, pProperties);
7660
0
}
7661
7662
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumerateInstanceLayerProperties(uint32_t *pPropertyCount,
7663
0
                                                                           VkLayerProperties *pProperties) {
7664
0
    VkResult result = VK_SUCCESS;
7665
0
    struct loader_layer_list instance_layer_list;
7666
0
    struct loader_envvar_all_filters layer_filters = {0};
7667
7668
0
    LOADER_PLATFORM_THREAD_ONCE(&once_init, loader_initialize);
7669
7670
0
    result = parse_layer_environment_var_filters(NULL, &layer_filters);
7671
0
    if (VK_SUCCESS != result) {
7672
0
        goto out;
7673
0
    }
7674
7675
    // Get layer libraries
7676
0
    memset(&instance_layer_list, 0, sizeof(instance_layer_list));
7677
0
    result = loader_scan_for_layers(NULL, &instance_layer_list, &layer_filters);
7678
0
    if (VK_SUCCESS != result) {
7679
0
        goto out;
7680
0
    }
7681
7682
0
    uint32_t layers_to_write_out = 0;
7683
0
    for (uint32_t i = 0; i < instance_layer_list.count; i++) {
7684
0
        if (instance_layer_list.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_ON ||
7685
0
            instance_layer_list.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_DEFAULT) {
7686
0
            layers_to_write_out++;
7687
0
        }
7688
0
    }
7689
7690
0
    if (pProperties == NULL) {
7691
0
        *pPropertyCount = layers_to_write_out;
7692
0
        goto out;
7693
0
    }
7694
7695
0
    uint32_t output_properties_index = 0;
7696
0
    for (uint32_t i = 0; i < instance_layer_list.count; i++) {
7697
0
        if (output_properties_index < *pPropertyCount &&
7698
0
            (instance_layer_list.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_ON ||
7699
0
             instance_layer_list.list[i].settings_control_value == LOADER_SETTINGS_LAYER_CONTROL_DEFAULT)) {
7700
0
            memcpy(&pProperties[output_properties_index], &instance_layer_list.list[i].info, sizeof(VkLayerProperties));
7701
0
            output_properties_index++;
7702
0
        }
7703
0
    }
7704
0
    if (output_properties_index < layers_to_write_out) {
7705
        // Indicates that we had more elements to write but ran out of room
7706
0
        result = VK_INCOMPLETE;
7707
0
    }
7708
7709
0
    *pPropertyCount = output_properties_index;
7710
7711
0
out:
7712
7713
0
    loader_delete_layer_list_and_properties(NULL, &instance_layer_list);
7714
0
    return result;
7715
0
}
7716
7717
VKAPI_ATTR VkResult VKAPI_CALL terminator_pre_instance_EnumerateInstanceLayerProperties(
7718
0
    const VkEnumerateInstanceLayerPropertiesChain *chain, uint32_t *pPropertyCount, VkLayerProperties *pProperties) {
7719
0
    (void)chain;
7720
0
    return terminator_EnumerateInstanceLayerProperties(pPropertyCount, pProperties);
7721
0
}
7722
7723
// ---- Vulkan Core 1.1 terminators
7724
7725
VKAPI_ATTR VkResult VKAPI_CALL terminator_EnumeratePhysicalDeviceGroups(
7726
0
    VkInstance instance, uint32_t *pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupProperties *pPhysicalDeviceGroupProperties) {
7727
0
    struct loader_instance *inst = (struct loader_instance *)instance;
7728
7729
0
    VkResult res = VK_SUCCESS;
7730
0
    struct loader_icd_term *icd_term;
7731
0
    uint32_t total_count = 0;
7732
0
    uint32_t cur_icd_group_count = 0;
7733
0
    VkPhysicalDeviceGroupProperties **new_phys_dev_groups = NULL;
7734
0
    struct loader_physical_device_group_term *local_phys_dev_groups = NULL;
7735
0
    PFN_vkEnumeratePhysicalDeviceGroups fpEnumeratePhysicalDeviceGroups = NULL;
7736
0
    struct loader_icd_physical_devices *sorted_phys_dev_array = NULL;
7737
0
    uint32_t sorted_count = 0;
7738
7739
    // For each ICD, query the number of physical device groups, and then get an
7740
    // internal value for those physical devices.
7741
0
    icd_term = inst->icd_terms;
7742
0
    while (NULL != icd_term) {
7743
0
        cur_icd_group_count = 0;
7744
7745
        // Get the function pointer to use to call into the ICD. This could be the core or KHR version
7746
0
        if (inst->enabled_extensions.khr_device_group_creation) {
7747
0
            fpEnumeratePhysicalDeviceGroups = icd_term->dispatch.EnumeratePhysicalDeviceGroupsKHR;
7748
0
        } else {
7749
0
            fpEnumeratePhysicalDeviceGroups = icd_term->dispatch.EnumeratePhysicalDeviceGroups;
7750
0
        }
7751
7752
0
        if (NULL == fpEnumeratePhysicalDeviceGroups) {
7753
            // Treat each ICD's GPU as it's own group if the extension isn't supported
7754
0
            res = icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &cur_icd_group_count, NULL);
7755
0
            if (res != VK_SUCCESS) {
7756
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7757
0
                           "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of \'EnumeratePhysicalDevices\' "
7758
0
                           "to ICD %s to get plain phys dev count.",
7759
0
                           icd_term->scanned_icd->lib_name);
7760
0
                continue;
7761
0
            }
7762
0
        } else {
7763
            // Query the actual group info
7764
0
            res = fpEnumeratePhysicalDeviceGroups(icd_term->instance, &cur_icd_group_count, NULL);
7765
0
            if (res != VK_SUCCESS) {
7766
0
                loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7767
0
                           "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7768
0
                           "\'EnumeratePhysicalDeviceGroups\' to ICD %s to get count.",
7769
0
                           icd_term->scanned_icd->lib_name);
7770
0
                continue;
7771
0
            }
7772
0
        }
7773
0
        total_count += cur_icd_group_count;
7774
0
        icd_term = icd_term->next;
7775
0
    }
7776
7777
    // If GPUs not sorted yet, look through them and generate list of all available GPUs
7778
0
    if (0 == total_count || 0 == inst->total_gpu_count) {
7779
0
        res = setup_loader_term_phys_devs(inst);
7780
0
        if (VK_SUCCESS != res) {
7781
0
            goto out;
7782
0
        }
7783
0
    }
7784
7785
0
    if (NULL != pPhysicalDeviceGroupProperties) {
7786
        // Create an array for the new physical device groups, which will be stored
7787
        // in the instance for the Terminator code.
7788
0
        new_phys_dev_groups = (VkPhysicalDeviceGroupProperties **)loader_instance_heap_calloc(
7789
0
            inst, total_count * sizeof(VkPhysicalDeviceGroupProperties *), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
7790
0
        if (NULL == new_phys_dev_groups) {
7791
0
            loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7792
0
                       "terminator_EnumeratePhysicalDeviceGroups:  Failed to allocate new physical device group array of size %d",
7793
0
                       total_count);
7794
0
            res = VK_ERROR_OUT_OF_HOST_MEMORY;
7795
0
            goto out;
7796
0
        }
7797
7798
        // Create a temporary array (on the stack) to keep track of the
7799
        // returned VkPhysicalDevice values.
7800
0
        local_phys_dev_groups = loader_stack_alloc(sizeof(struct loader_physical_device_group_term) * total_count);
7801
        // Initialize the memory to something valid
7802
0
        memset(local_phys_dev_groups, 0, sizeof(struct loader_physical_device_group_term) * total_count);
7803
7804
#if defined(_WIN32)
7805
        // Get the physical devices supported by platform sorting mechanism into a separate list
7806
        res = windows_read_sorted_physical_devices(inst, &sorted_count, &sorted_phys_dev_array);
7807
        if (VK_SUCCESS != res) {
7808
            goto out;
7809
        }
7810
#endif
7811
7812
0
        cur_icd_group_count = 0;
7813
0
        icd_term = inst->icd_terms;
7814
0
        while (NULL != icd_term) {
7815
0
            uint32_t count_this_time = total_count - cur_icd_group_count;
7816
7817
            // Get the function pointer to use to call into the ICD. This could be the core or KHR version
7818
0
            if (inst->enabled_extensions.khr_device_group_creation) {
7819
0
                fpEnumeratePhysicalDeviceGroups = icd_term->dispatch.EnumeratePhysicalDeviceGroupsKHR;
7820
0
            } else {
7821
0
                fpEnumeratePhysicalDeviceGroups = icd_term->dispatch.EnumeratePhysicalDeviceGroups;
7822
0
            }
7823
7824
0
            if (NULL == fpEnumeratePhysicalDeviceGroups) {
7825
0
                icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &count_this_time, NULL);
7826
7827
0
                VkPhysicalDevice *phys_dev_array = loader_stack_alloc(sizeof(VkPhysicalDevice) * count_this_time);
7828
0
                if (NULL == phys_dev_array) {
7829
0
                    loader_log(
7830
0
                        inst, VULKAN_LOADER_ERROR_BIT, 0,
7831
0
                        "terminator_EnumeratePhysicalDeviceGroups:  Failed to allocate local physical device array of size %d",
7832
0
                        count_this_time);
7833
0
                    res = VK_ERROR_OUT_OF_HOST_MEMORY;
7834
0
                    goto out;
7835
0
                }
7836
7837
0
                res = icd_term->dispatch.EnumeratePhysicalDevices(icd_term->instance, &count_this_time, phys_dev_array);
7838
0
                if (res != VK_SUCCESS) {
7839
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7840
0
                               "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7841
0
                               "\'EnumeratePhysicalDevices\' to ICD %s to get plain phys dev count.",
7842
0
                               icd_term->scanned_icd->lib_name);
7843
0
                    goto out;
7844
0
                }
7845
7846
                // Add each GPU as it's own group
7847
0
                for (uint32_t indiv_gpu = 0; indiv_gpu < count_this_time; indiv_gpu++) {
7848
0
                    uint32_t cur_index = indiv_gpu + cur_icd_group_count;
7849
0
                    local_phys_dev_groups[cur_index].this_icd_term = icd_term;
7850
0
                    local_phys_dev_groups[cur_index].group_props.physicalDeviceCount = 1;
7851
0
                    local_phys_dev_groups[cur_index].group_props.physicalDevices[0] = phys_dev_array[indiv_gpu];
7852
0
                }
7853
7854
0
            } else {
7855
0
                res = fpEnumeratePhysicalDeviceGroups(icd_term->instance, &count_this_time, NULL);
7856
0
                if (res != VK_SUCCESS) {
7857
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7858
0
                               "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7859
0
                               "\'EnumeratePhysicalDeviceGroups\' to ICD %s to get group count.",
7860
0
                               icd_term->scanned_icd->lib_name);
7861
0
                    goto out;
7862
0
                }
7863
0
                if (cur_icd_group_count + count_this_time < *pPhysicalDeviceGroupCount) {
7864
                    // The total amount is still less than the amount of physical device group data passed in
7865
                    // by the callee.  Therefore, we don't have to allocate any temporary structures and we
7866
                    // can just use the data that was passed in.
7867
0
                    res = fpEnumeratePhysicalDeviceGroups(icd_term->instance, &count_this_time,
7868
0
                                                          &pPhysicalDeviceGroupProperties[cur_icd_group_count]);
7869
0
                    if (res != VK_SUCCESS) {
7870
0
                        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7871
0
                                   "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7872
0
                                   "\'EnumeratePhysicalDeviceGroups\' to ICD %s to get group information.",
7873
0
                                   icd_term->scanned_icd->lib_name);
7874
0
                        goto out;
7875
0
                    }
7876
0
                    for (uint32_t group = 0; group < count_this_time; ++group) {
7877
0
                        uint32_t cur_index = group + cur_icd_group_count;
7878
0
                        local_phys_dev_groups[cur_index].group_props = pPhysicalDeviceGroupProperties[cur_index];
7879
0
                        local_phys_dev_groups[cur_index].this_icd_term = icd_term;
7880
0
                    }
7881
0
                } else {
7882
                    // There's not enough space in the callee's allocated pPhysicalDeviceGroupProperties structs,
7883
                    // so we have to allocate temporary versions to collect all the data.  However, we need to make
7884
                    // sure that at least the ones we do query utilize any pNext data in the callee's version.
7885
0
                    VkPhysicalDeviceGroupProperties *tmp_group_props =
7886
0
                        loader_stack_alloc(count_this_time * sizeof(VkPhysicalDeviceGroupProperties));
7887
0
                    for (uint32_t group = 0; group < count_this_time; group++) {
7888
0
                        tmp_group_props[group].sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES;
7889
0
                        uint32_t cur_index = group + cur_icd_group_count;
7890
0
                        if (*pPhysicalDeviceGroupCount > cur_index) {
7891
0
                            tmp_group_props[group].pNext = pPhysicalDeviceGroupProperties[cur_index].pNext;
7892
0
                        } else {
7893
0
                            tmp_group_props[group].pNext = NULL;
7894
0
                        }
7895
0
                        tmp_group_props[group].subsetAllocation = false;
7896
0
                    }
7897
7898
0
                    res = fpEnumeratePhysicalDeviceGroups(icd_term->instance, &count_this_time, tmp_group_props);
7899
0
                    if (res != VK_SUCCESS) {
7900
0
                        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7901
0
                                   "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7902
0
                                   "\'EnumeratePhysicalDeviceGroups\' to ICD %s  to get group information for temp data.",
7903
0
                                   icd_term->scanned_icd->lib_name);
7904
0
                        goto out;
7905
0
                    }
7906
0
                    for (uint32_t group = 0; group < count_this_time; ++group) {
7907
0
                        uint32_t cur_index = group + cur_icd_group_count;
7908
0
                        local_phys_dev_groups[cur_index].group_props = tmp_group_props[group];
7909
0
                        local_phys_dev_groups[cur_index].this_icd_term = icd_term;
7910
0
                    }
7911
0
                }
7912
0
                if (VK_SUCCESS != res) {
7913
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7914
0
                               "terminator_EnumeratePhysicalDeviceGroups:  Failed during dispatch call of "
7915
0
                               "\'EnumeratePhysicalDeviceGroups\' to ICD %s to get content.",
7916
0
                               icd_term->scanned_icd->lib_name);
7917
0
                    goto out;
7918
0
                }
7919
0
            }
7920
7921
0
            cur_icd_group_count += count_this_time;
7922
0
            icd_term = icd_term->next;
7923
0
        }
7924
7925
0
#if defined(LOADER_ENABLE_LINUX_SORT)
7926
0
        if (is_linux_sort_enabled(inst)) {
7927
            // Get the physical devices supported by platform sorting mechanism into a separate list
7928
0
            res = linux_sort_physical_device_groups(inst, total_count, local_phys_dev_groups);
7929
0
        }
7930
#elif defined(_WIN32)
7931
        // The Windows sorting information is only on physical devices.  We need to take that and convert it to the group
7932
        // information if it's present.
7933
        if (sorted_count > 0) {
7934
            res =
7935
                windows_sort_physical_device_groups(inst, total_count, local_phys_dev_groups, sorted_count, sorted_phys_dev_array);
7936
        }
7937
#endif  // LOADER_ENABLE_LINUX_SORT
7938
7939
        // Just to be safe, make sure we successfully completed setup_loader_term_phys_devs above
7940
        // before attempting to do the following.  By verifying that setup_loader_term_phys_devs ran
7941
        // first, it guarantees that each physical device will have a loader-specific handle.
7942
0
        if (NULL != inst->phys_devs_term) {
7943
0
            for (uint32_t group = 0; group < total_count; group++) {
7944
0
                for (uint32_t group_gpu = 0; group_gpu < local_phys_dev_groups[group].group_props.physicalDeviceCount;
7945
0
                     group_gpu++) {
7946
0
                    bool found = false;
7947
0
                    for (uint32_t term_gpu = 0; term_gpu < inst->phys_dev_count_term; term_gpu++) {
7948
0
                        if (local_phys_dev_groups[group].group_props.physicalDevices[group_gpu] ==
7949
0
                            inst->phys_devs_term[term_gpu]->phys_dev) {
7950
0
                            local_phys_dev_groups[group].group_props.physicalDevices[group_gpu] =
7951
0
                                (VkPhysicalDevice)inst->phys_devs_term[term_gpu];
7952
0
                            found = true;
7953
0
                            break;
7954
0
                        }
7955
0
                    }
7956
0
                    if (!found) {
7957
0
                        loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
7958
0
                                   "terminator_EnumeratePhysicalDeviceGroups:  Failed to find GPU %d in group %d returned by "
7959
0
                                   "\'EnumeratePhysicalDeviceGroups\' in list returned by \'EnumeratePhysicalDevices\'",
7960
0
                                   group_gpu, group);
7961
0
                        res = VK_ERROR_INITIALIZATION_FAILED;
7962
0
                        goto out;
7963
0
                    }
7964
0
                }
7965
0
            }
7966
0
        }
7967
7968
0
        uint32_t idx = 0;
7969
7970
        // Copy or create everything to fill the new array of physical device groups
7971
0
        for (uint32_t group = 0; group < total_count; group++) {
7972
            // Skip groups which have been included through sorting
7973
0
            if (local_phys_dev_groups[group].group_props.physicalDeviceCount == 0) {
7974
0
                continue;
7975
0
            }
7976
7977
            // Find the VkPhysicalDeviceGroupProperties object in local_phys_dev_groups
7978
0
            VkPhysicalDeviceGroupProperties *group_properties = &local_phys_dev_groups[group].group_props;
7979
7980
            // Check if this physical device group with the same contents is already in the old buffer
7981
0
            for (uint32_t old_idx = 0; old_idx < inst->phys_dev_group_count_term; old_idx++) {
7982
0
                if (NULL != group_properties && NULL != inst->phys_dev_groups_term[old_idx] &&
7983
0
                    group_properties->physicalDeviceCount == inst->phys_dev_groups_term[old_idx]->physicalDeviceCount) {
7984
0
                    bool found_all_gpus = true;
7985
0
                    for (uint32_t old_gpu = 0; old_gpu < inst->phys_dev_groups_term[old_idx]->physicalDeviceCount; old_gpu++) {
7986
0
                        bool found_gpu = false;
7987
0
                        for (uint32_t new_gpu = 0; new_gpu < group_properties->physicalDeviceCount; new_gpu++) {
7988
0
                            if (group_properties->physicalDevices[new_gpu] ==
7989
0
                                inst->phys_dev_groups_term[old_idx]->physicalDevices[old_gpu]) {
7990
0
                                found_gpu = true;
7991
0
                                break;
7992
0
                            }
7993
0
                        }
7994
7995
0
                        if (!found_gpu) {
7996
0
                            found_all_gpus = false;
7997
0
                            break;
7998
0
                        }
7999
0
                    }
8000
0
                    if (!found_all_gpus) {
8001
0
                        continue;
8002
0
                    } else {
8003
0
                        new_phys_dev_groups[idx] = inst->phys_dev_groups_term[old_idx];
8004
0
                        break;
8005
0
                    }
8006
0
                }
8007
0
            }
8008
            // If this physical device group isn't in the old buffer, create it
8009
0
            if (group_properties != NULL && NULL == new_phys_dev_groups[idx]) {
8010
0
                new_phys_dev_groups[idx] = (VkPhysicalDeviceGroupProperties *)loader_instance_heap_alloc(
8011
0
                    inst, sizeof(VkPhysicalDeviceGroupProperties), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
8012
0
                if (NULL == new_phys_dev_groups[idx]) {
8013
0
                    loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
8014
0
                               "terminator_EnumeratePhysicalDeviceGroups:  Failed to allocate physical device group Terminator "
8015
0
                               "object %d",
8016
0
                               idx);
8017
0
                    total_count = idx;
8018
0
                    res = VK_ERROR_OUT_OF_HOST_MEMORY;
8019
0
                    goto out;
8020
0
                }
8021
0
                memcpy(new_phys_dev_groups[idx], group_properties, sizeof(VkPhysicalDeviceGroupProperties));
8022
0
            }
8023
8024
0
            ++idx;
8025
0
        }
8026
0
    }
8027
8028
0
out:
8029
8030
0
    if (NULL != pPhysicalDeviceGroupProperties) {
8031
0
        if (VK_SUCCESS != res) {
8032
0
            if (NULL != new_phys_dev_groups) {
8033
                // We've encountered an error, so we should free the new buffers.
8034
0
                for (uint32_t i = 0; i < total_count; i++) {
8035
                    // If an OOM occurred inside the copying of the new physical device groups into the existing array will
8036
                    // leave some of the old physical device groups in the array which may have been copied into the new array,
8037
                    // leading to them being freed twice. To avoid this we just make sure to not delete physical device groups
8038
                    // which were copied.
8039
0
                    bool found = false;
8040
0
                    if (NULL != inst->phys_devs_term) {
8041
0
                        for (uint32_t old_idx = 0; old_idx < inst->phys_dev_group_count_term; old_idx++) {
8042
0
                            if (new_phys_dev_groups[i] == inst->phys_dev_groups_term[old_idx]) {
8043
0
                                found = true;
8044
0
                                break;
8045
0
                            }
8046
0
                        }
8047
0
                    }
8048
0
                    if (!found) {
8049
0
                        loader_instance_heap_free(inst, new_phys_dev_groups[i]);
8050
0
                    }
8051
0
                }
8052
0
                loader_instance_heap_free(inst, new_phys_dev_groups);
8053
0
            }
8054
0
        } else {
8055
0
            if (NULL != inst->phys_dev_groups_term) {
8056
                // Free everything in the old array that was not copied into the new array
8057
                // here.  We can't attempt to do that before here since the previous loop
8058
                // looking before the "out:" label may hit an out of memory condition resulting
8059
                // in memory leaking.
8060
0
                for (uint32_t i = 0; i < inst->phys_dev_group_count_term; i++) {
8061
0
                    bool found = false;
8062
0
                    for (uint32_t j = 0; j < total_count; j++) {
8063
0
                        if (inst->phys_dev_groups_term[i] == new_phys_dev_groups[j]) {
8064
0
                            found = true;
8065
0
                            break;
8066
0
                        }
8067
0
                    }
8068
0
                    if (!found) {
8069
0
                        loader_instance_heap_free(inst, inst->phys_dev_groups_term[i]);
8070
0
                    }
8071
0
                }
8072
0
                loader_instance_heap_free(inst, inst->phys_dev_groups_term);
8073
0
            }
8074
8075
            // Swap in the new physical device group list
8076
0
            inst->phys_dev_group_count_term = total_count;
8077
0
            inst->phys_dev_groups_term = new_phys_dev_groups;
8078
0
        }
8079
8080
0
        if (sorted_phys_dev_array != NULL) {
8081
0
            for (uint32_t i = 0; i < sorted_count; ++i) {
8082
0
                if (sorted_phys_dev_array[i].device_count > 0 && sorted_phys_dev_array[i].physical_devices != NULL) {
8083
0
                    loader_instance_heap_free(inst, sorted_phys_dev_array[i].physical_devices);
8084
0
                }
8085
0
            }
8086
0
            loader_instance_heap_free(inst, sorted_phys_dev_array);
8087
0
        }
8088
8089
0
        uint32_t copy_count = inst->phys_dev_group_count_term;
8090
0
        if (NULL != pPhysicalDeviceGroupProperties) {
8091
0
            if (copy_count > *pPhysicalDeviceGroupCount) {
8092
0
                copy_count = *pPhysicalDeviceGroupCount;
8093
0
                loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
8094
0
                           "terminator_EnumeratePhysicalDeviceGroups : Trimming device count from %d to %d.",
8095
0
                           inst->phys_dev_group_count_term, copy_count);
8096
0
                res = VK_INCOMPLETE;
8097
0
            }
8098
8099
0
            for (uint32_t i = 0; i < copy_count; i++) {
8100
0
                memcpy(&pPhysicalDeviceGroupProperties[i], inst->phys_dev_groups_term[i], sizeof(VkPhysicalDeviceGroupProperties));
8101
0
            }
8102
0
        }
8103
8104
0
        *pPhysicalDeviceGroupCount = copy_count;
8105
8106
0
    } else {
8107
0
        *pPhysicalDeviceGroupCount = total_count;
8108
0
    }
8109
0
    return res;
8110
0
}
8111
8112
0
VkResult get_device_driver_id(VkPhysicalDevice physicalDevice, VkDriverId *driverId) {
8113
0
    VkPhysicalDeviceDriverProperties physical_device_driver_props = {0};
8114
0
    physical_device_driver_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES;
8115
8116
0
    VkPhysicalDeviceProperties2 props2 = {0};
8117
0
    props2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
8118
0
    props2.pNext = &physical_device_driver_props;
8119
8120
0
    struct loader_physical_device_term *phys_dev_term = (struct loader_physical_device_term *)physicalDevice;
8121
0
    struct loader_icd_term *icd_term = phys_dev_term->this_icd_term;
8122
0
    const struct loader_instance *inst = icd_term->this_instance;
8123
8124
0
    assert(inst != NULL);
8125
8126
    // Get the function pointer to use to call into the ICD. This could be the core or KHR version
8127
0
    PFN_vkGetPhysicalDeviceProperties2 fpGetPhysicalDeviceProperties2 = NULL;
8128
0
    if (loader_check_version_meets_required(LOADER_VERSION_1_1_0, inst->app_api_version)) {
8129
0
        fpGetPhysicalDeviceProperties2 = icd_term->dispatch.GetPhysicalDeviceProperties2;
8130
0
    }
8131
0
    if (fpGetPhysicalDeviceProperties2 == NULL && inst->enabled_extensions.khr_get_physical_device_properties2) {
8132
0
        fpGetPhysicalDeviceProperties2 = icd_term->dispatch.GetPhysicalDeviceProperties2KHR;
8133
0
    }
8134
8135
0
    if (fpGetPhysicalDeviceProperties2 == NULL) {
8136
0
        *driverId = 0;
8137
0
        return VK_ERROR_UNKNOWN;
8138
0
    }
8139
8140
0
    fpGetPhysicalDeviceProperties2(phys_dev_term->phys_dev, &props2);
8141
8142
0
    *driverId = physical_device_driver_props.driverID;
8143
0
    return VK_SUCCESS;
8144
0
}
8145
8146
VkResult loader_filter_enumerated_physical_device(const struct loader_instance *inst,
8147
                                                  const struct loader_envvar_id_filter *device_id_filter,
8148
                                                  const struct loader_envvar_id_filter *vendor_id_filter,
8149
                                                  const struct loader_envvar_id_filter *driver_id_filter,
8150
                                                  const uint32_t in_PhysicalDeviceCount,
8151
                                                  const VkPhysicalDevice *in_pPhysicalDevices, uint32_t *out_pPhysicalDeviceCount,
8152
0
                                                  VkPhysicalDevice *out_pPhysicalDevices) {
8153
0
    uint32_t filtered_physical_device_count = 0;
8154
0
    for (uint32_t i = 0; i < in_PhysicalDeviceCount; i++) {
8155
0
        VkPhysicalDeviceProperties dev_props = {0};
8156
0
        inst->disp->layer_inst_disp.GetPhysicalDeviceProperties(in_pPhysicalDevices[i], &dev_props);
8157
8158
0
        if ((0 != device_id_filter->count) && !check_id_matches_filter_environment_var(dev_props.deviceID, device_id_filter)) {
8159
0
            continue;
8160
0
        }
8161
8162
0
        if ((0 != vendor_id_filter->count) && !check_id_matches_filter_environment_var(dev_props.vendorID, vendor_id_filter)) {
8163
0
            continue;
8164
0
        }
8165
8166
0
        if (0 != driver_id_filter->count) {
8167
0
            VkDriverId driver_id;
8168
0
            VkResult res = get_device_driver_id(in_pPhysicalDevices[i], &driver_id);
8169
8170
0
            if ((res != VK_SUCCESS) || !check_id_matches_filter_environment_var(driver_id, driver_id_filter)) {
8171
0
                continue;
8172
0
            }
8173
0
        }
8174
8175
0
        if ((NULL != out_pPhysicalDevices) && (filtered_physical_device_count < *out_pPhysicalDeviceCount)) {
8176
0
            out_pPhysicalDevices[filtered_physical_device_count] = in_pPhysicalDevices[i];
8177
0
        }
8178
0
        filtered_physical_device_count++;
8179
0
    }
8180
8181
0
    if ((NULL == out_pPhysicalDevices) || (filtered_physical_device_count < *out_pPhysicalDeviceCount)) {
8182
0
        *out_pPhysicalDeviceCount = filtered_physical_device_count;
8183
0
    }
8184
8185
0
    return (*out_pPhysicalDeviceCount < filtered_physical_device_count) ? VK_INCOMPLETE : VK_SUCCESS;
8186
0
}
8187
8188
VkResult loader_filter_enumerated_physical_device_groups(
8189
    const struct loader_instance *inst, const struct loader_envvar_id_filter *device_id_filter,
8190
    const struct loader_envvar_id_filter *vendor_id_filter, const struct loader_envvar_id_filter *driver_id_filter,
8191
    const uint32_t in_PhysicalDeviceGroupCount, const VkPhysicalDeviceGroupProperties *in_pPhysicalDeviceGroupProperties,
8192
0
    uint32_t *out_PhysicalDeviceGroupCount, VkPhysicalDeviceGroupProperties *out_pPhysicalDeviceGroupProperties) {
8193
0
    uint32_t filtered_physical_device_group_count = 0;
8194
0
    for (uint32_t i = 0; i < in_PhysicalDeviceGroupCount; i++) {
8195
0
        const VkPhysicalDeviceGroupProperties *device_group = &in_pPhysicalDeviceGroupProperties[i];
8196
8197
0
        bool skip_group = false;
8198
0
        for (uint32_t j = 0; j < device_group->physicalDeviceCount; j++) {
8199
0
            VkPhysicalDeviceProperties dev_props = {0};
8200
0
            inst->disp->layer_inst_disp.GetPhysicalDeviceProperties(device_group->physicalDevices[j], &dev_props);
8201
8202
0
            if ((0 != device_id_filter->count) && !check_id_matches_filter_environment_var(dev_props.deviceID, device_id_filter)) {
8203
0
                skip_group = true;
8204
0
                break;
8205
0
            }
8206
8207
0
            if ((0 != vendor_id_filter->count) && !check_id_matches_filter_environment_var(dev_props.vendorID, vendor_id_filter)) {
8208
0
                skip_group = true;
8209
0
                break;
8210
0
            }
8211
8212
0
            if (0 != driver_id_filter->count) {
8213
0
                VkDriverId driver_id;
8214
0
                VkResult res = get_device_driver_id(device_group->physicalDevices[j], &driver_id);
8215
8216
0
                if ((res != VK_SUCCESS) || !check_id_matches_filter_environment_var(driver_id, driver_id_filter)) {
8217
0
                    skip_group = true;
8218
0
                    break;
8219
0
                }
8220
0
            }
8221
0
        }
8222
8223
0
        if (skip_group) {
8224
0
            continue;
8225
0
        }
8226
8227
0
        if ((NULL != out_pPhysicalDeviceGroupProperties) &&
8228
0
            (filtered_physical_device_group_count < *out_PhysicalDeviceGroupCount)) {
8229
0
            out_pPhysicalDeviceGroupProperties[filtered_physical_device_group_count] = *device_group;
8230
0
        }
8231
8232
0
        filtered_physical_device_group_count++;
8233
0
    }
8234
8235
0
    if ((NULL == out_pPhysicalDeviceGroupProperties) || (filtered_physical_device_group_count < *out_PhysicalDeviceGroupCount)) {
8236
0
        *out_PhysicalDeviceGroupCount = filtered_physical_device_group_count;
8237
0
    }
8238
8239
0
    return (*out_PhysicalDeviceGroupCount < filtered_physical_device_group_count) ? VK_INCOMPLETE : VK_SUCCESS;
8240
0
}