forked from KhronosGroup/Vulkan-Loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.c
8756 lines (7750 loc) · 385 KB
/
loader.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Copyright (c) 2014-2020 The Khronos Group Inc.
* Copyright (c) 2014-2020 Valve Corporation
* Copyright (c) 2014-2020 LunarG, Inc.
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Jon Ashburn <[email protected]>
* Author: Courtney Goeltzenleuchter <[email protected]>
* Author: Mark Young <[email protected]>
* Author: Lenny Komow <[email protected]>
*
*/
// This needs to be defined first, or else we'll get redefinitions on NTSTATUS values
#ifdef _WIN32
#define UMDF_USING_NTSTATUS
#include <ntstatus.h>
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#if defined(__APPLE__)
#include <CoreFoundation/CoreFoundation.h>
#include <sys/param.h>
#endif
// Time related functions
#include <time.h>
#include <sys/types.h>
#if defined(_WIN32)
#include "dirent_on_windows.h"
#else // _WIN32
#include <dirent.h>
#endif // _WIN32
#include "vk_loader_platform.h"
#include "loader.h"
#include "gpa_helper.h"
#include "debug_utils.h"
#include "wsi.h"
#include "vulkan/vk_icd.h"
#include "cJSON.h"
#include "murmurhash.h"
#if defined(_WIN32)
#include <cfgmgr32.h>
#include <initguid.h>
#include <devpkey.h>
#include <winternl.h>
#include <strsafe.h>
#ifdef __MINGW32__
#undef strcpy // fix error with redfined strcpy when building with MinGW-w64
#endif
#include <dxgi1_6.h>
#include "adapters.h"
typedef HRESULT (APIENTRY *PFN_CreateDXGIFactory1)(REFIID riid, void **ppFactory);
static PFN_CreateDXGIFactory1 fpCreateDXGIFactory1;
#endif
// This is a CMake generated file with #defines for any functions/includes
// that it found present. This is currently necessary to properly determine
// if secure_getenv or __secure_getenv are present
#if !defined(VULKAN_NON_CMAKE_BUILD)
#include "loader_cmake_config.h"
#endif // !defined(VULKAN_NON_CMAKE_BUILD)
// Generated file containing all the extension data
#include "vk_loader_extensions.c"
// Environment Variable information
#define VK_ICD_FILENAMES_ENV_VAR "VK_ICD_FILENAMES"
#define VK_LAYER_PATH_ENV_VAR "VK_LAYER_PATH"
// Override layer information
#define VK_OVERRIDE_LAYER_NAME "VK_LAYER_LUNARG_override"
struct loader_struct loader = {0};
// TLS for instance for alloc/free callbacks
THREAD_LOCAL_DECL struct loader_instance *tls_instance;
static size_t loader_platform_combine_path(char *dest, size_t len, ...);
struct loader_phys_dev_per_icd {
uint32_t count;
VkPhysicalDevice *phys_devs;
struct loader_icd_term *this_icd_term;
};
enum loader_debug {
LOADER_INFO_BIT = 0x01,
LOADER_WARN_BIT = 0x02,
LOADER_PERF_BIT = 0x04,
LOADER_ERROR_BIT = 0x08,
LOADER_DEBUG_BIT = 0x10,
};
uint32_t g_loader_debug = 0;
uint32_t g_loader_log_msgs = 0;
enum loader_data_files_type {
LOADER_DATA_FILE_MANIFEST_ICD = 0,
LOADER_DATA_FILE_MANIFEST_LAYER,
LOADER_DATA_FILE_NUM_TYPES // Not a real field, used for possible loop terminator
};
// thread safety lock for accessing global data structures such as "loader"
// all entrypoints on the instance chain need to be locked except GPA
// additionally CreateDevice and DestroyDevice needs to be locked
loader_platform_thread_mutex loader_lock;
loader_platform_thread_mutex loader_json_lock;
loader_platform_thread_mutex loader_preload_icd_lock;
// A list of ICDs that gets initialized when the loader does its global initialization. This list should never be used by anything
// other than EnumerateInstanceExtensionProperties(), vkDestroyInstance, and loader_release(). This list does not change
// functionality, but the fact that the libraries already been loaded causes any call that needs to load ICD libraries to speed up
// significantly. This can have a huge impact when making repeated calls to vkEnumerateInstanceExtensionProperties and
// vkCreateInstance.
static struct loader_icd_tramp_list scanned_icds;
LOADER_PLATFORM_THREAD_ONCE_DECLARATION(once_init);
void *loader_instance_heap_alloc(const struct loader_instance *instance, size_t size, VkSystemAllocationScope alloc_scope) {
void *pMemory = NULL;
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
{
#else
if (instance && instance->alloc_callbacks.pfnAllocation) {
// These are internal structures, so it's best to align everything to
// the largest unit size which is the size of a uint64_t.
pMemory = instance->alloc_callbacks.pfnAllocation(instance->alloc_callbacks.pUserData, size, sizeof(uint64_t), alloc_scope);
} else {
#endif
pMemory = malloc(size);
}
return pMemory;
}
void loader_instance_heap_free(const struct loader_instance *instance, void *pMemory) {
if (pMemory != NULL) {
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
{
#else
if (instance && instance->alloc_callbacks.pfnFree) {
instance->alloc_callbacks.pfnFree(instance->alloc_callbacks.pUserData, pMemory);
} else {
#endif
free(pMemory);
}
}
}
void *loader_instance_heap_realloc(const struct loader_instance *instance, void *pMemory, size_t orig_size, size_t size,
VkSystemAllocationScope alloc_scope) {
void *pNewMem = NULL;
if (pMemory == NULL || orig_size == 0) {
pNewMem = loader_instance_heap_alloc(instance, size, alloc_scope);
} else if (size == 0) {
loader_instance_heap_free(instance, pMemory);
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
#else
} else if (instance && instance->alloc_callbacks.pfnReallocation) {
// These are internal structures, so it's best to align everything to
// the largest unit size which is the size of a uint64_t.
pNewMem = instance->alloc_callbacks.pfnReallocation(instance->alloc_callbacks.pUserData, pMemory, size, sizeof(uint64_t),
alloc_scope);
#endif
} else {
pNewMem = realloc(pMemory, size);
}
return pNewMem;
}
void *loader_instance_tls_heap_alloc(size_t size) {
return loader_instance_heap_alloc(tls_instance, size, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
}
void loader_instance_tls_heap_free(void *pMemory) { loader_instance_heap_free(tls_instance, pMemory); }
void *loader_device_heap_alloc(const struct loader_device *device, size_t size, VkSystemAllocationScope alloc_scope) {
void *pMemory = NULL;
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
{
#else
if (device && device->alloc_callbacks.pfnAllocation) {
// These are internal structures, so it's best to align everything to
// the largest unit size which is the size of a uint64_t.
pMemory = device->alloc_callbacks.pfnAllocation(device->alloc_callbacks.pUserData, size, sizeof(uint64_t), alloc_scope);
} else {
#endif
pMemory = malloc(size);
}
return pMemory;
}
void loader_device_heap_free(const struct loader_device *device, void *pMemory) {
if (pMemory != NULL) {
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
{
#else
if (device && device->alloc_callbacks.pfnFree) {
device->alloc_callbacks.pfnFree(device->alloc_callbacks.pUserData, pMemory);
} else {
#endif
free(pMemory);
}
}
}
void *loader_device_heap_realloc(const struct loader_device *device, void *pMemory, size_t orig_size, size_t size,
VkSystemAllocationScope alloc_scope) {
void *pNewMem = NULL;
if (pMemory == NULL || orig_size == 0) {
pNewMem = loader_device_heap_alloc(device, size, alloc_scope);
} else if (size == 0) {
loader_device_heap_free(device, pMemory);
#if (DEBUG_DISABLE_APP_ALLOCATORS == 1)
#else
} else if (device && device->alloc_callbacks.pfnReallocation) {
// These are internal structures, so it's best to align everything to
// the largest unit size which is the size of a uint64_t.
pNewMem = device->alloc_callbacks.pfnReallocation(device->alloc_callbacks.pUserData, pMemory, size, sizeof(uint64_t),
alloc_scope);
#endif
} else {
pNewMem = realloc(pMemory, size);
}
return pNewMem;
}
// Environment variables
#if defined(__linux__) || defined(__APPLE__) || defined(__Fuchsia__)
static inline bool IsHighIntegrity() {
return geteuid() != getuid() || getegid() != getgid();
}
static inline char *loader_getenv(const char *name, const struct loader_instance *inst) {
// No allocation of memory necessary for Linux, but we should at least touch
// the inst pointer to get rid of compiler warnings.
(void)inst;
return getenv(name);
}
static inline char *loader_secure_getenv(const char *name, const struct loader_instance *inst) {
char *out;
#if defined(__APPLE__)
// Apple does not appear to have a secure getenv implementation.
// The main difference between secure getenv and getenv is that secure getenv
// returns NULL if the process is being run with elevated privileges by a normal user.
// The idea is to prevent the reading of malicious environment variables by a process
// that can do damage.
// This algorithm is derived from glibc code that sets an internal
// variable (__libc_enable_secure) if the process is running under setuid or setgid.
return IsHighIntegrity() ? NULL : loader_getenv(name, inst);
#elif defined(__Fuchsia__)
return loader_getenv(name, inst);
#else
// Linux
#if defined(HAVE_SECURE_GETENV) && !defined(USE_UNSAFE_FILE_SEARCH)
(void)inst;
out = secure_getenv(name);
#elif defined(HAVE___SECURE_GETENV) && !defined(USE_UNSAFE_FILE_SEARCH)
(void)inst;
out = __secure_getenv(name);
#else
out = loader_getenv(name, inst);
#if !defined(USE_UNSAFE_FILE_SEARCH)
loader_log(inst, LOADER_INFO_BIT, 0, "Loader is using non-secure environment variable lookup for %s", name);
#endif
#endif
return out;
#endif
}
static inline void loader_free_getenv(char *val, const struct loader_instance *inst) {
// No freeing of memory necessary for Linux, but we should at least touch
// the val and inst pointers to get rid of compiler warnings.
(void)val;
(void)inst;
}
#elif defined(WIN32)
static inline bool IsHighIntegrity() {
HANDLE process_token;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_QUERY_SOURCE, &process_token)) {
// Maximum possible size of SID_AND_ATTRIBUTES is maximum size of a SID + size of attributes DWORD.
uint8_t mandatory_label_buffer[SECURITY_MAX_SID_SIZE + sizeof(DWORD)];
DWORD buffer_size;
if (GetTokenInformation(process_token, TokenIntegrityLevel, mandatory_label_buffer, sizeof(mandatory_label_buffer),
&buffer_size) != 0) {
const TOKEN_MANDATORY_LABEL *mandatory_label = (const TOKEN_MANDATORY_LABEL *)mandatory_label_buffer;
const DWORD sub_authority_count = *GetSidSubAuthorityCount(mandatory_label->Label.Sid);
const DWORD integrity_level = *GetSidSubAuthority(mandatory_label->Label.Sid, sub_authority_count - 1);
CloseHandle(process_token);
return integrity_level > SECURITY_MANDATORY_MEDIUM_RID;
}
CloseHandle(process_token);
}
return false;
}
static inline char *loader_getenv(const char *name, const struct loader_instance *inst) {
char *retVal;
DWORD valSize;
valSize = GetEnvironmentVariableA(name, NULL, 0);
// valSize DOES include the null terminator, so for any set variable
// will always be at least 1. If it's 0, the variable wasn't set.
if (valSize == 0) return NULL;
// Allocate the space necessary for the registry entry
if (NULL != inst && NULL != inst->alloc_callbacks.pfnAllocation) {
retVal = (char *)inst->alloc_callbacks.pfnAllocation(inst->alloc_callbacks.pUserData, valSize, sizeof(char *),
VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
} else {
retVal = (char *)malloc(valSize);
}
if (NULL != retVal) {
GetEnvironmentVariableA(name, retVal, valSize);
}
return retVal;
}
static inline char *loader_secure_getenv(const char *name, const struct loader_instance *inst) {
#if !defined(USE_UNSAFE_FILE_SEARCH)
if (IsHighIntegrity()) {
loader_log(inst, LOADER_INFO_BIT, 0, "Loader is running with elevated permissions. Environment variable %s will be ignored",
name);
return NULL;
}
#endif
return loader_getenv(name, inst);
}
static inline void loader_free_getenv(char *val, const struct loader_instance *inst) {
if (NULL != inst && NULL != inst->alloc_callbacks.pfnFree) {
inst->alloc_callbacks.pfnFree(inst->alloc_callbacks.pUserData, val);
} else {
free((void *)val);
}
}
#else
static inline char *loader_getenv(const char *name, const struct loader_instance *inst) {
// stub func
(void)inst;
(void)name;
return NULL;
}
static inline void loader_free_getenv(char *val, const struct loader_instance *inst) {
// stub func
(void)val;
(void)inst;
}
#endif
void loader_log(const struct loader_instance *inst, VkFlags msg_type, int32_t msg_code, const char *format, ...) {
char msg[512];
char cmd_line_msg[512];
size_t cmd_line_size = sizeof(cmd_line_msg);
va_list ap;
int ret;
va_start(ap, format);
ret = vsnprintf(msg, sizeof(msg), format, ap);
if ((ret >= (int)sizeof(msg)) || ret < 0) {
msg[sizeof(msg) - 1] = '\0';
}
va_end(ap);
if (inst) {
VkDebugUtilsMessageSeverityFlagBitsEXT severity = 0;
VkDebugUtilsMessageTypeFlagsEXT type;
VkDebugUtilsMessengerCallbackDataEXT callback_data;
VkDebugUtilsObjectNameInfoEXT object_name;
if ((msg_type & LOADER_INFO_BIT) != 0) {
severity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT;
} else if ((msg_type & LOADER_WARN_BIT) != 0) {
severity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
} else if ((msg_type & LOADER_ERROR_BIT) != 0) {
severity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
} else if ((msg_type & LOADER_DEBUG_BIT) != 0) {
severity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT;
}
if ((msg_type & LOADER_PERF_BIT) != 0) {
type = VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
} else {
type = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT;
}
callback_data.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT;
callback_data.pNext = NULL;
callback_data.flags = 0;
callback_data.pMessageIdName = "Loader Message";
callback_data.messageIdNumber = 0;
callback_data.pMessage = msg;
callback_data.queueLabelCount = 0;
callback_data.pQueueLabels = NULL;
callback_data.cmdBufLabelCount = 0;
callback_data.pCmdBufLabels = NULL;
callback_data.objectCount = 1;
callback_data.pObjects = &object_name;
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.pNext = NULL;
object_name.objectType = VK_OBJECT_TYPE_INSTANCE;
object_name.objectHandle = (uint64_t)(uintptr_t)inst;
object_name.pObjectName = NULL;
util_SubmitDebugUtilsMessageEXT(inst, severity, type, &callback_data);
}
if (!(msg_type & g_loader_log_msgs)) {
return;
}
cmd_line_msg[0] = '\0';
cmd_line_size -= 1;
size_t original_size = cmd_line_size;
if ((msg_type & LOADER_INFO_BIT) != 0) {
strncat(cmd_line_msg, "INFO", cmd_line_size);
cmd_line_size -= 4;
}
if ((msg_type & LOADER_WARN_BIT) != 0) {
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, " | ", cmd_line_size);
cmd_line_size -= 3;
}
strncat(cmd_line_msg, "WARNING", cmd_line_size);
cmd_line_size -= 7;
}
if ((msg_type & LOADER_PERF_BIT) != 0) {
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, " | ", cmd_line_size);
cmd_line_size -= 3;
}
strncat(cmd_line_msg, "PERF", cmd_line_size);
cmd_line_size -= 4;
}
if ((msg_type & LOADER_ERROR_BIT) != 0) {
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, " | ", cmd_line_size);
cmd_line_size -= 3;
}
strncat(cmd_line_msg, "ERROR", cmd_line_size);
cmd_line_size -= 5;
}
if ((msg_type & LOADER_DEBUG_BIT) != 0) {
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, " | ", cmd_line_size);
cmd_line_size -= 3;
}
strncat(cmd_line_msg, "DEBUG", cmd_line_size);
cmd_line_size -= 5;
}
if (cmd_line_size != original_size) {
strncat(cmd_line_msg, ": ", cmd_line_size);
cmd_line_size -= 2;
}
if (0 < cmd_line_size) {
// If the message is too long, trim it down
if (strlen(msg) > cmd_line_size) {
msg[cmd_line_size - 1] = '\0';
}
strncat(cmd_line_msg, msg, cmd_line_size);
} else {
// Shouldn't get here, but check to make sure if we've already overrun
// the string boundary
assert(false);
}
#if defined(WIN32)
OutputDebugString(cmd_line_msg);
OutputDebugString("\n");
#endif
fputs(cmd_line_msg, stderr);
fputc('\n', stderr);
}
VKAPI_ATTR VkResult VKAPI_CALL vkSetInstanceDispatch(VkInstance instance, void *object) {
struct loader_instance *inst = loader_get_instance(instance);
if (!inst) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"vkSetInstanceDispatch: Can not retrieve Instance "
"dispatch table.");
return VK_ERROR_INITIALIZATION_FAILED;
}
loader_set_dispatch(object, inst->disp);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL vkSetDeviceDispatch(VkDevice device, void *object) {
struct loader_device *dev;
struct loader_icd_term *icd_term = loader_get_icd_and_device(device, &dev, NULL);
if (NULL == icd_term) {
return VK_ERROR_INITIALIZATION_FAILED;
}
loader_set_dispatch(object, &dev->loader_dispatch);
return VK_SUCCESS;
}
#if defined(_WIN32)
// Append the JSON path data to the list and allocate/grow the list if it's not large enough.
// Function returns true if filename was appended to reg_data list.
// Caller should free reg_data.
static bool loaderAddJsonEntry(const struct loader_instance *inst,
char **reg_data, // list of JSON files
PDWORD total_size, // size of reg_data
LPCSTR key_name, // key name - used for debug prints - i.e. VulkanDriverName
DWORD key_type, // key data type
LPSTR json_path, // JSON string to add to the list reg_data
DWORD json_size, // size in bytes of json_path
VkResult *result) {
// Check for and ignore duplicates.
if (*reg_data && strstr(*reg_data, json_path)) {
// Success. The json_path is already in the list.
return true;
}
if (NULL == *reg_data) {
*reg_data = loader_instance_heap_alloc(inst, *total_size, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == *reg_data) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderAddJsonEntry: Failed to allocate space for registry data for key %s", json_path);
*result = VK_ERROR_OUT_OF_HOST_MEMORY;
return false;
}
*reg_data[0] = '\0';
} else if (strlen(*reg_data) + json_size + 1 > *total_size) {
void *new_ptr =
loader_instance_heap_realloc(inst, *reg_data, *total_size, *total_size * 2, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == new_ptr) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderAddJsonEntry: Failed to reallocate space for registry value of size %d for key %s", *total_size * 2,
json_path);
*result = VK_ERROR_OUT_OF_HOST_MEMORY;
return false;
}
*reg_data = new_ptr;
*total_size *= 2;
}
for (char *curr_filename = json_path; curr_filename[0] != '\0'; curr_filename += strlen(curr_filename) + 1) {
if (strlen(*reg_data) == 0) {
(void)snprintf(*reg_data, json_size + 1, "%s", curr_filename);
} else {
(void)snprintf(*reg_data + strlen(*reg_data), json_size + 2, "%c%s", PATH_SEPARATOR, curr_filename);
}
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0, "%s: Located json file \"%s\" from PnP registry: %s", __FUNCTION__,
curr_filename, key_name);
if (key_type == REG_SZ) {
break;
}
}
return true;
}
// Find the list of registry files (names VulkanDriverName/VulkanDriverNameWow) in hkr.
//
// This function looks for filename in given device handle, filename is then added to return list
// function return true if filename was appended to reg_data list
// If error occurs result is updated with failure reason
bool loaderGetDeviceRegistryEntry(const struct loader_instance *inst, char **reg_data, PDWORD total_size, DEVINST dev_id,
LPCSTR value_name, VkResult *result) {
HKEY hkrKey = INVALID_HANDLE_VALUE;
DWORD requiredSize, data_type;
char *manifest_path = NULL;
bool found = false;
if (NULL == total_size || NULL == reg_data) {
*result = VK_ERROR_INITIALIZATION_FAILED;
return false;
}
CONFIGRET status = CM_Open_DevNode_Key(dev_id, KEY_QUERY_VALUE, 0, RegDisposition_OpenExisting, &hkrKey, CM_REGISTRY_SOFTWARE);
if (status != CR_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: Failed to open registry key for DeviceID(%d)", dev_id);
*result = VK_ERROR_INITIALIZATION_FAILED;
return false;
}
// query value
LSTATUS ret = RegQueryValueEx(
hkrKey,
value_name,
NULL,
NULL,
NULL,
&requiredSize);
if (ret != ERROR_SUCCESS) {
if (ret == ERROR_FILE_NOT_FOUND) {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: Device ID(%d) Does not contain a value for \"%s\"", dev_id, value_name);
} else {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: DeviceID(%d) Failed to obtain %s size", dev_id, value_name);
}
goto out;
}
manifest_path = loader_instance_heap_alloc(inst, requiredSize, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (manifest_path == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: Failed to allocate space for DriverName.");
*result = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
ret = RegQueryValueEx(
hkrKey,
value_name,
NULL,
&data_type,
(BYTE *)manifest_path,
&requiredSize
);
if (ret != ERROR_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: DeviceID(%d) Failed to obtain %s", value_name);
*result = VK_ERROR_INITIALIZATION_FAILED;
goto out;
}
if (data_type != REG_SZ && data_type != REG_MULTI_SZ) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryEntry: Invalid %s data type. Expected REG_SZ or REG_MULTI_SZ.", value_name);
*result = VK_ERROR_INITIALIZATION_FAILED;
goto out;
}
found = loaderAddJsonEntry(inst, reg_data, total_size, value_name, data_type, manifest_path, requiredSize, result);
out:
if (manifest_path != NULL) {
loader_instance_heap_free(inst, manifest_path);
}
RegCloseKey(hkrKey);
return found;
}
// Find the list of registry files (names VulkanDriverName/VulkanDriverNameWow) in hkr .
//
// This function looks for display devices and childish software components
// for a list of files which are added to a returned list (function return
// value).
// Function return is a string with a ';' separated list of filenames.
// Function return is NULL if no valid name/value pairs are found in the key,
// or the key is not found.
//
// *reg_data contains a string list of filenames as pointer.
// When done using the returned string list, the caller should free the pointer.
VkResult loaderGetDeviceRegistryFiles(const struct loader_instance *inst, char **reg_data, PDWORD reg_data_size,
LPCSTR value_name) {
static const wchar_t *softwareComponentGUID = L"{5c4c3332-344d-483c-8739-259e934c9cc8}";
static const wchar_t *displayGUID = L"{4d36e968-e325-11ce-bfc1-08002be10318}";
#ifdef CM_GETIDLIST_FILTER_PRESENT
const ULONG flags = CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT;
#else
const ULONG flags = 0x300;
#endif
wchar_t childGuid[MAX_GUID_STRING_LEN + 2]; // +2 for brackets {}
ULONG childGuidSize = sizeof(childGuid);
DEVINST devID = 0, childID = 0;
wchar_t *pDeviceNames = NULL;
ULONG deviceNamesSize = 0;
VkResult result = VK_SUCCESS;
bool found = false;
if (NULL == reg_data) {
result = VK_ERROR_INITIALIZATION_FAILED;
return result;
}
// if after obtaining the DeviceNameSize, new device is added start over
do {
CM_Get_Device_ID_List_SizeW(&deviceNamesSize, displayGUID, flags);
if (pDeviceNames != NULL) {
loader_instance_heap_free(inst, pDeviceNames);
}
pDeviceNames = loader_instance_heap_alloc(inst, deviceNamesSize * sizeof(wchar_t), VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (pDeviceNames == NULL) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: Failed to allocate space for display device names.");
result = VK_ERROR_OUT_OF_HOST_MEMORY;
return result;
}
} while (CM_Get_Device_ID_ListW(displayGUID, pDeviceNames, deviceNamesSize, flags) == CR_BUFFER_SMALL);
if (pDeviceNames) {
for (wchar_t *deviceName = pDeviceNames; *deviceName; deviceName += wcslen(deviceName) + 1) {
CONFIGRET status = CM_Locate_DevNodeW(&devID, deviceName, CM_LOCATE_DEVNODE_NORMAL);
if (CR_SUCCESS != status) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loaderGetDeviceRegistryFiles: failed to open DevNode %ls",
deviceName);
continue;
}
ULONG ulStatus, ulProblem;
status = CM_Get_DevNode_Status(&ulStatus, &ulProblem, devID, 0);
if (CR_SUCCESS != status)
{
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0, "loaderGetDeviceRegistryFiles: failed to probe device status %ls",
deviceName);
continue;
}
if ((ulStatus & DN_HAS_PROBLEM) && (ulProblem == CM_PROB_NEED_RESTART || ulProblem == DN_NEED_RESTART)) {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: device %ls is pending reboot, skipping ...", deviceName);
continue;
}
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0, "loaderGetDeviceRegistryFiles: opening device %ls", deviceName);
if (loaderGetDeviceRegistryEntry(inst, reg_data, reg_data_size, devID, value_name, &result)) {
found = true;
continue;
}
else if (result == VK_ERROR_OUT_OF_HOST_MEMORY) {
break;
}
status = CM_Get_Child(&childID, devID, 0);
if (status != CR_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: unable to open child-device error:%d", status);
continue;
}
do {
wchar_t buffer[MAX_DEVICE_ID_LEN];
CM_Get_Device_IDW(childID, buffer, MAX_DEVICE_ID_LEN, 0);
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: Opening child device %d - %ls", childID, buffer);
status = CM_Get_DevNode_Registry_PropertyW(childID, CM_DRP_CLASSGUID, NULL, &childGuid, &childGuidSize, 0);
if (status != CR_SUCCESS) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: unable to obtain GUID for:%d error:%d", childID, status);
result = VK_ERROR_INITIALIZATION_FAILED;
continue;
}
if (wcscmp(childGuid, softwareComponentGUID) != 0) {
loader_log(inst, VK_DEBUG_REPORT_DEBUG_BIT_EXT, 0,
"loaderGetDeviceRegistryFiles: GUID for %d is not SoftwareComponent skipping", childID);
continue;
}
if (loaderGetDeviceRegistryEntry(inst, reg_data, reg_data_size, childID, value_name, &result)) {
found = true;
break; // check next-display-device
}
} while (CM_Get_Sibling(&childID, childID, 0) == CR_SUCCESS);
}
loader_instance_heap_free(inst, pDeviceNames);
}
if (!found && result != VK_ERROR_OUT_OF_HOST_MEMORY) {
result = VK_ERROR_INITIALIZATION_FAILED;
}
return result;
}
static char *loader_get_next_path(char *path);
// Find the list of registry files (names within a key) in key "location".
//
// This function looks in the registry (hive = DEFAULT_VK_REGISTRY_HIVE) key as
// given in "location"
// for a list or name/values which are added to a returned list (function return
// value).
// The DWORD values within the key must be 0 or they are skipped.
// Function return is a string with a ';' separated list of filenames.
// Function return is NULL if no valid name/value pairs are found in the key,
// or the key is not found.
//
// *reg_data contains a string list of filenames as pointer.
// When done using the returned string list, the caller should free the pointer.
VkResult loaderGetRegistryFiles(const struct loader_instance *inst, char *location, bool use_secondary_hive, char **reg_data,
PDWORD reg_data_size) {
// This list contains all of the allowed ICDs. This allows us to verify that a device is actually present from the vendor
// specified. This does disallow other vendors, but any new driver should use the device-specific registries anyway.
static const struct {
const char *filename;
int vendor_id;
} known_drivers[] = {
#if defined(_WIN64)
{
.filename = "igvk64.json",
.vendor_id = 0x8086,
},
{
.filename = "nv-vk64.json",
.vendor_id = 0x10de,
},
{
.filename = "amd-vulkan64.json",
.vendor_id = 0x1002,
},
{
.filename = "amdvlk64.json",
.vendor_id = 0x1002,
},
#else
{
.filename = "igvk32.json",
.vendor_id = 0x8086,
},
{
.filename = "nv-vk32.json",
.vendor_id = 0x10de,
},
{
.filename = "amd-vulkan32.json",
.vendor_id = 0x1002,
},
{
.filename = "amdvlk32.json",
.vendor_id = 0x1002,
},
#endif
};
LONG rtn_value;
HKEY hive = DEFAULT_VK_REGISTRY_HIVE, key;
DWORD access_flags;
char name[2048];
char *loc = location;
char *next;
DWORD name_size = sizeof(name);
DWORD value;
DWORD value_size = sizeof(value);
VkResult result = VK_SUCCESS;
bool found = false;
IDXGIFactory1 *dxgi_factory = NULL;
bool is_driver = !strcmp(location, VK_DRIVERS_INFO_REGISTRY_LOC);
if (NULL == reg_data) {
result = VK_ERROR_INITIALIZATION_FAILED;
goto out;
}
if (is_driver) {
HRESULT hres = fpCreateDXGIFactory1(&IID_IDXGIFactory1, (void **)&dxgi_factory);
if (hres != S_OK) {
loader_log(
inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0,
"loaderGetRegistryFiles: Failed to create dxgi factory for ICD registry verification. No ICDs will be added from "
"legacy registry locations");
goto out;
}
}
while (*loc) {
next = loader_get_next_path(loc);
access_flags = KEY_QUERY_VALUE;
rtn_value = RegOpenKeyEx(hive, loc, 0, access_flags, &key);
if (ERROR_SUCCESS == rtn_value) {
for (DWORD idx = 0;
(rtn_value = RegEnumValue(key, idx++, name, &name_size, NULL, NULL, (LPBYTE)&value, &value_size)) == ERROR_SUCCESS;
name_size = sizeof(name), value_size = sizeof(value)) {
if (value_size == sizeof(value) && value == 0) {
if (NULL == *reg_data) {
*reg_data = loader_instance_heap_alloc(inst, *reg_data_size, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == *reg_data) {
loader_log(inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetRegistryFiles: Failed to allocate space for registry data for key %s", name);
RegCloseKey(key);
result = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
*reg_data[0] = '\0';
} else if (strlen(*reg_data) + name_size + 1 > *reg_data_size) {
void *new_ptr = loader_instance_heap_realloc(inst, *reg_data, *reg_data_size, *reg_data_size * 2,
VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == new_ptr) {
loader_log(
inst, VK_DEBUG_REPORT_ERROR_BIT_EXT, 0,
"loaderGetRegistryFiles: Failed to reallocate space for registry value of size %d for key %s",
*reg_data_size * 2, name);
RegCloseKey(key);
result = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
*reg_data = new_ptr;
*reg_data_size *= 2;
}
// We've now found a json file. If this is an ICD, we still need to check if there is actually a device
// that matches this ICD
loader_log(
inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0, "Located json file \"%s\" from registry \"%s\\%s\"", name,
hive == DEFAULT_VK_REGISTRY_HIVE ? DEFAULT_VK_REGISTRY_HIVE_STR : SECONDARY_VK_REGISTRY_HIVE_STR, location);
if (is_driver) {
int i;
for (i = 0; i < sizeof(known_drivers) / sizeof(known_drivers[0]); ++i) {
if (!strcmp(name + strlen(name) - strlen(known_drivers[i].filename), known_drivers[i].filename)) {
break;
}
}
if (i == sizeof(known_drivers) / sizeof(known_drivers[0])) {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"Driver %s is not recognized as a known driver. It will be assumed to be active", name);
} else {
bool found_gpu = false;
for (int j = 0;; ++j) {
IDXGIAdapter1 *adapter;
HRESULT hres = dxgi_factory->lpVtbl->EnumAdapters1(dxgi_factory, j, &adapter);
if (hres == DXGI_ERROR_NOT_FOUND) {
break;
} else if (hres != S_OK) {
loader_log(inst, VK_DEBUG_REPORT_WARNING_BIT_EXT, 0,
"Failed to enumerate DXGI adapters at index %d. As a result, drivers may be skipped", j);
continue;
}
DXGI_ADAPTER_DESC1 description;
hres = adapter->lpVtbl->GetDesc1(adapter, &description);
if (hres != S_OK) {
loader_log(
inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"Failed to get DXGI adapter information at index %d. As a result, drivers may be skipped", j);
continue;
}
if (description.VendorId == known_drivers[i].vendor_id) {
found_gpu = true;
break;
}
}
if (!found_gpu) {
loader_log(inst, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, 0,
"Dropping driver %s as no corresponding DXGI adapter was found", name);
continue;
}
}
}
if (strlen(*reg_data) == 0) {
// The list is emtpy. Add the first entry.
(void)snprintf(*reg_data, name_size + 1, "%s", name);
found = true;
} else {
// At this point the reg_data variable contains other JSON paths, likely from the PNP/device section