Coverage Report

Created: 2025-12-31 06:56

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