Coverage Report

Created: 2026-10-19 06:59

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