Coverage Report

Created: 2025-08-25 06:15

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