Debian Codegraph @

scripts/generators/loader_extension_generator.py

raw
1 #!/usr/bin/python3 -i
2 #
3 # Copyright (c) 2015-2022 The Khronos Group Inc.
4 # Copyright (c) 2015-2022 Valve Corporation
5 # Copyright (c) 2015-2022 LunarG, Inc.
6 # Copyright (c) 2015-2017 Google Inc.
7 # Copyright (c) 2021-2023 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 # Author: Mark Young <[email protected]>
23 # Author: Mark Lobodzinski <[email protected]>
24 # Author: Charles Giessen <[email protected]>
25
26 import re
27 import os
28 from base_generator import BaseGenerator
29 from vulkan_object import Version
30
31 WSI_EXT_NAMES = ['VK_KHR_surface',
32 'VK_KHR_display',
33 'VK_KHR_xlib_surface',
34 'VK_KHR_xcb_surface',
35 'VK_KHR_wayland_surface',
36 'VK_EXT_directfb_surface',
37 'VK_KHR_win32_surface',
38 'VK_KHR_android_surface',
39 'VK_GGP_stream_descriptor_surface',
40 'VK_MVK_macos_surface',
41 'VK_MVK_ios_surface',
42 'VK_EXT_headless_surface',
43 'VK_EXT_metal_surface',
44 'VK_FUCHSIA_imagepipe_surface',
45 'VK_KHR_swapchain',
46 'VK_KHR_display_swapchain',
47 'VK_KHR_get_display_properties2',
48 'VK_KHR_get_surface_capabilities2',
49 'VK_QNX_screen_surface',
50 'VK_NN_vi_surface']
51
52 ADD_INST_CMDS = ['vkCreateInstance',
53 'vkEnumerateInstanceExtensionProperties',
54 'vkEnumerateInstanceLayerProperties',
55 'vkEnumerateInstanceVersion']
56
57 AVOID_EXT_NAMES = ['VK_EXT_debug_report']
58
59 NULL_CHECK_EXT_NAMES= ['VK_EXT_debug_utils']
60
61 AVOID_CMD_NAMES = ['vkCreateDebugUtilsMessengerEXT',
62 'vkDestroyDebugUtilsMessengerEXT',
63 'vkSubmitDebugUtilsMessageEXT']
64
65 DEVICE_CMDS_NEED_TERM = ['vkGetDeviceProcAddr',
66 'vkCreateSwapchainKHR',
67 'vkCreateSharedSwapchainsKHR',
68 'vkGetDeviceGroupSurfacePresentModesKHR',
69 'vkDebugMarkerSetObjectTagEXT',
70 'vkDebugMarkerSetObjectNameEXT',
71 'vkSetDebugUtilsObjectNameEXT',
72 'vkSetDebugUtilsObjectTagEXT',
73 'vkQueueBeginDebugUtilsLabelEXT',
74 'vkQueueEndDebugUtilsLabelEXT',
75 'vkQueueInsertDebugUtilsLabelEXT',
76 'vkCmdBeginDebugUtilsLabelEXT',
77 'vkCmdEndDebugUtilsLabelEXT',
78 'vkCmdInsertDebugUtilsLabelEXT',
79 'vkGetDeviceGroupSurfacePresentModes2EXT']
80
81 DEVICE_CMDS_MUST_USE_TRAMP = ['vkSetDebugUtilsObjectNameEXT',
82 'vkSetDebugUtilsObjectTagEXT',
83 'vkDebugMarkerSetObjectNameEXT',
84 'vkDebugMarkerSetObjectTagEXT']
85
86 # These are the aliased functions that use the same terminator for both extension and core versions
87 # Generally, this is only applies to physical device level functions in instance extensions
88 SHARED_ALIASES = {
89 # 1.1 aliases
90 'vkEnumeratePhysicalDeviceGroupsKHR': 'vkEnumeratePhysicalDeviceGroups',
91 'vkGetPhysicalDeviceFeatures2KHR': 'vkGetPhysicalDeviceFeatures2',
92 'vkGetPhysicalDeviceProperties2KHR': 'vkGetPhysicalDeviceProperties2',
93 'vkGetPhysicalDeviceFormatProperties2KHR': 'vkGetPhysicalDeviceFormatProperties2',
94 'vkGetPhysicalDeviceImageFormatProperties2KHR': 'vkGetPhysicalDeviceImageFormatProperties2',
95 'vkGetPhysicalDeviceQueueFamilyProperties2KHR': 'vkGetPhysicalDeviceQueueFamilyProperties2',
96 'vkGetPhysicalDeviceMemoryProperties2KHR': 'vkGetPhysicalDeviceMemoryProperties2',
97 'vkGetPhysicalDeviceSparseImageFormatProperties2KHR': 'vkGetPhysicalDeviceSparseImageFormatProperties2',
98 'vkGetPhysicalDeviceExternalBufferPropertiesKHR': 'vkGetPhysicalDeviceExternalBufferProperties',
99 'vkGetPhysicalDeviceExternalSemaphorePropertiesKHR': 'vkGetPhysicalDeviceExternalSemaphoreProperties',
100 'vkGetPhysicalDeviceExternalFencePropertiesKHR': 'vkGetPhysicalDeviceExternalFenceProperties',
101 }
102
103 PRE_INSTANCE_FUNCTIONS = ['vkEnumerateInstanceExtensionProperties',
104 'vkEnumerateInstanceLayerProperties',
105 'vkEnumerateInstanceVersion']
106
107 # This class is a container for any source code, data, or other behavior that is necessary to
108 # customize the generator script for a specific target API variant (e.g. Vulkan SC). As such,
109 # all of these API-specific interfaces and their use in the generator script are part of the
110 # contract between this repository and its downstream users. Changing or removing any of these
111 # interfaces or their use in the generator script will have downstream effects and thus
112 # should be avoided unless absolutely necessary.
113 class APISpecific:
114 @staticmethod
115 def getApiVersionDisplayName(targetApiName: str, name: str) -> str:
116 match targetApiName:
117 case 'vulkan':
118 api_name = 'Vulkan'
119
120 version_number = name[name.find('_VERSION_') + len('_VERSION_'):].replace('_', '.')
121 return f'{api_name} {version_number}'
122
123 @staticmethod
124 def getFirstVersionName(targetApiName: str) -> str:
125 match targetApiName:
126 case 'vulkan':
127 return 'VK_VERSION_1_0'
128
129 # This handles the dependency across versions of APIs, even across API variants
130 # (e.g. maps VK_VERSION_1_2 to VKSC_VERSION_1_0 for Vulkan SC).
131 # This handles the lack of proper support for the "depends" attribute of <feature> tags in the XML.
132 @staticmethod
133 def getEffectiveVersionName(targetApiName: str, version: Version) -> str:
134 if version is None:
135 return APISpecific.getFirstVersionName(targetApiName)
136
137 match targetApiName:
138 case 'vulkan':
139 return version.name
140
141
142 class LoaderExtensionGenerator(BaseGenerator):
143 def __init__(self):
144 BaseGenerator.__init__(self)
145
146 self.core_commands = []
147 self.extension_commands = []
148 self.instance_extensions = []
149
150 def generate(self):
151
152 self.core_commands = [x for x in self.vk.commands.values() if len(x.extensions) == 0]
153 self.extension_commands = [x for x in self.vk.commands.values() if len(x.extensions) > 0]
154
155 self.instance_extensions = [x for x in self.vk.extensions.values() if x.instance]
156
157 out = []
158 self.add_preamble(out)
159
160 if self.filename == 'vk_loader_extensions.h':
161 self.print_vk_loader_extensions_h(out)
162 elif self.filename == 'vk_loader_extensions.c':
163 self.print_vk_loader_extensions_c(out)
164 elif self.filename == 'vk_layer_dispatch_table.h':
165 self.print_vk_layer_dispatch_table(out)
166
167 out.append('// clang-format on')
168
169 self.write(''.join(out))
170
171 def add_preamble(self, out):
172 out.append(f'''// *** THIS FILE IS GENERATED - DO NOT EDIT ***
173 // See {os.path.basename(__file__)} for modifications
174
175 /*
176 * Copyright (c) 2015-2025 The Khronos Group Inc.
177 * Copyright (c) 2015-2025 Valve Corporation
178 * Copyright (c) 2015-2025 LunarG, Inc.
179 * Copyright (c) 2021-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
180 * Copyright (c) 2023-2023 RasterGrid Kft.
181 *
182 * Licensed under the Apache License, Version 2.0 (the "License");
183 * you may not use this file except in compliance with the License.
184 * You may obtain a copy of the License at
185 *
186 * http://www.apache.org/licenses/LICENSE-2.0
187 *
188 * Unless required by applicable law or agreed to in writing, software
189 * distributed under the License is distributed on an "AS IS" BASIS,
190 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
191 * See the License for the specific language governing permissions and
192 * limitations under the License.
193 *
194 * Author: Mark Lobodzinski <[email protected]>
195 * Author: Mark Young <[email protected]>
196 * Author: Charles Giessen <[email protected]>
197 */
198
199 // clang-format off
200 ''')
201
202 def print_vk_loader_extensions_h(self, out):
203 out.append('#pragma once\n')
204 out.append('\n')
205 out.append('#include <stdbool.h>\n')
206 out.append('#include <vulkan/vulkan.h>\n')
207 out.append('#include <vulkan/vk_layer.h>\n')
208 out.append('#include "vk_layer_dispatch_table.h"\n')
209 out.append('\n\n')
210
211 self.OutputPrototypesInHeader(out)
212 self.OutputLoaderTerminators(out)
213 self.OutputIcdDispatchTable(out)
214 self.OutputIcdExtensionEnableUnion(out)
215 self.OutputDeviceFunctionTerminatorDispatchTable(out)
216
217
218 def print_vk_loader_extensions_c(self, out):
219 out.append('#include <stdio.h>\n')
220 out.append('#include <stdlib.h>\n')
221 out.append('#include <string.h>\n')
222 out.append('#include "loader.h"\n')
223 out.append('#include "vk_loader_extensions.h"\n')
224 out.append('#include <vulkan/vk_icd.h>\n')
225 out.append('#include "wsi.h"\n')
226 out.append('#include "debug_utils.h"\n')
227 out.append('#include "extension_manual.h"\n')
228 self.OutputUtilitiesInSource(out)
229 self.OutputIcdDispatchTableInit(out)
230 self.OutputLoaderDispatchTables(out)
231 self.InitDeviceFunctionTerminatorDispatchTable(out)
232 self.OutputDeviceFunctionTrampolinePrototypes(out)
233 self.OutputLoaderLookupFunc(out)
234 self.CreateTrampTermFuncs(out)
235 self.InstExtensionGPA(out)
236 self.InstantExtensionCreate(out)
237 self.DeviceExtensionGetTerminator(out)
238 self.InitInstLoaderExtensionDispatchTable(out)
239 self.OutputInstantExtensionWhitelistArray(out)
240
241 def print_vk_layer_dispatch_table(self, out):
242 out.append('#pragma once\n')
243 out.append('\n')
244 out.append('#include <vulkan/vulkan.h>\n')
245 out.append('\n')
246 self.OutputLayerInstanceDispatchTable(out)
247 self.OutputLayerDeviceDispatchTable(out)
248
249 def DescribeBlock(self, command, current_block, out, custom_commands_string = ' commands', indent = ' '):
250 effective_version_name = APISpecific.getEffectiveVersionName(self.targetApiName, command.version)
251 if command.extensions != current_block and effective_version_name != current_block:
252 if effective_version_name and len(command.extensions) == 0:
253 # Entry points that have an effective version in the target API
254 api_version_display_name = APISpecific.getApiVersionDisplayName(self.targetApiName, effective_version_name)
255 out.append(f"\n{indent}// ---- Core {api_version_display_name}{custom_commands_string}\n")
256 return effective_version_name
257 else:
258 # don't repeat unless the first extension is different (while rest can vary)
259 if not isinstance(current_block, list) or current_block[0] != command.extensions[0]:
260 out.append(f"\n{indent}// ---- {command.extensions[0] if len(command.extensions) > 0 else ''} extension{custom_commands_string}\n")
261 return command.extensions
262 else:
263 return current_block
264
265 def OutputPrototypesInHeader(self, out: list):
266 out.append('''// Structures defined externally, but used here
267 struct loader_instance;
268 struct loader_device;
269 struct loader_icd_term;
270 struct loader_dev_dispatch_table;
271
272 // Device extension error function
273 VKAPI_ATTR VkResult VKAPI_CALL vkDevExtError(VkDevice dev);
274
275 // Extension interception for vkGetInstanceProcAddr function, so we can return
276 // the appropriate information for any instance extensions we know about.
277 bool extension_instance_gpa(struct loader_instance *ptr_instance, const char *name, void **addr);
278
279 struct loader_instance_extension_enable_list; // Forward declaration
280
281 // Extension interception for vkCreateInstance function, so we can properly
282 // detect and enable any instance extension information for extensions we know
283 // about.
284 void fill_out_enabled_instance_extensions(uint32_t extension_count, const char *const * extension_list, struct loader_instance_extension_enable_list* enables);
285
286 // Extension interception for vkGetDeviceProcAddr function, so we can return
287 // an appropriate terminator if this is one of those few device commands requiring
288 // a terminator.
289 PFN_vkVoidFunction get_extension_device_proc_terminator(struct loader_device *dev, const char *name, bool* found_name);
290
291 // Dispatch table properly filled in with appropriate terminators for the
292 // supported extensions.
293 extern const VkLayerInstanceDispatchTable instance_disp;
294
295 // Array of extension strings for instance extensions we support.
296 extern const char *const LOADER_INSTANCE_EXTENSIONS[];
297
298 VKAPI_ATTR bool VKAPI_CALL loader_icd_init_entries(struct loader_instance* inst, struct loader_icd_term *icd_term);
299
300 // Init Device function pointer dispatch table with core commands
301 VKAPI_ATTR void VKAPI_CALL loader_init_device_dispatch_table(struct loader_dev_dispatch_table *dev_table, PFN_vkGetDeviceProcAddr gpa,
302 VkDevice dev);
303
304 // Init Device function pointer dispatch table with extension commands
305 VKAPI_ATTR void VKAPI_CALL loader_init_device_extension_dispatch_table(struct loader_dev_dispatch_table *dev_table,
306 PFN_vkGetInstanceProcAddr gipa,
307 PFN_vkGetDeviceProcAddr gdpa,
308 VkInstance inst,
309 VkDevice dev);
310
311 // Init Instance function pointer dispatch table with core commands
312 VKAPI_ATTR void VKAPI_CALL loader_init_instance_core_dispatch_table(VkLayerInstanceDispatchTable *table, PFN_vkGetInstanceProcAddr gpa,
313 VkInstance inst);
314
315 // Init Instance function pointer dispatch table with core commands
316 VKAPI_ATTR void VKAPI_CALL loader_init_instance_extension_dispatch_table(VkLayerInstanceDispatchTable *table, PFN_vkGetInstanceProcAddr gpa,
317 VkInstance inst);
318
319 // Device command lookup function
320 VKAPI_ATTR void* VKAPI_CALL loader_lookup_device_dispatch_table(const VkLayerDispatchTable *table, const char *name, bool* name_found);
321
322 // Instance command lookup function
323 VKAPI_ATTR void* VKAPI_CALL loader_lookup_instance_dispatch_table(const VkLayerInstanceDispatchTable *table, const char *name,
324 bool *found_name);
325
326 ''')
327
328 # Creates the prototypes for the loader's core instance command terminators
329 def OutputLoaderTerminators(self, out):
330 out.append('// Loader core instance terminators\n')
331
332 for command in [x for x in self.vk.commands.values() if len(x.extensions) == 0]:
333 if not (command.name in ADD_INST_CMDS) and not (command.params[0].type in ['VkInstance', 'VkPhysicalDevice']):
334 continue
335
336 mod_string = ''
337 new_terminator = command.cPrototype
338 mod_string = new_terminator.replace("VKAPI_CALL vk", "VKAPI_CALL terminator_")
339
340 if command.name in PRE_INSTANCE_FUNCTIONS:
341 pre_instance_basic_version = mod_string
342 mod_string = mod_string.replace("terminator_", "terminator_pre_instance_")
343 mod_string = mod_string.replace(command.name[2:] + '(\n', command.name[2:] + '(\n const Vk' + command.name[2:] + 'Chain* chain,\n')
344
345 if command.protect is not None:
346 out.append(f'#if defined({command.protect})\n')
347
348 if command.name in PRE_INSTANCE_FUNCTIONS:
349 out.append(pre_instance_basic_version)
350 out.append('\n')
351
352 out.append(mod_string)
353 out.append('\n')
354
355 if command.protect is not None:
356 out.append(f'#endif // {command.protect}\n')
357
358 out.append('\n')
359
360 # Create a dispatch table from the appropriate list
361 def OutputIcdDispatchTable(self, out):
362 skip_commands = ['vkGetInstanceProcAddr',
363 'vkEnumerateDeviceLayerProperties',
364 ]
365
366 out.append('// ICD function pointer dispatch table\n')
367 out.append('struct loader_icd_term_dispatch {\n')
368
369 current_block = ''
370 for command in self.vk.commands.values():
371 if (command.name in skip_commands or command.device )and command.name != 'vkGetDeviceProcAddr':
372 continue
373
374 current_block = self.DescribeBlock(command, current_block, out)
375
376 if command.protect:
377 out.append(f'#if defined({command.protect})\n')
378
379 out.append(f' PFN_{command.name} {command.name[2:]};\n')
380
381 if command.protect:
382 out.append(f'#endif // {command.protect}\n')
383 out.append('};\n\n')
384
385 # Create the extension enable union
386 def OutputIcdExtensionEnableUnion(self, out):
387
388 out.append( 'struct loader_instance_extension_enable_list {\n')
389 for extension in self.instance_extensions:
390 if extension.protect:
391 out.append(f'#if defined({extension.protect})\n')
392 out.append( f' uint8_t {extension.name[3:].lower()};\n')
393 if extension.protect:
394 out.append(f'#endif // defined({extension.protect})\n')
395
396 out.append( '};\n\n')
397
398 # Create a dispatch table solely for device functions which have custom terminators
399 def OutputDeviceFunctionTerminatorDispatchTable(self, out):
400 out.append('// Functions that required a terminator need to have a separate dispatch table which contains their corresponding\n')
401 out.append('// device function. This is used in the terminators themselves.\n')
402 out.append('struct loader_device_terminator_dispatch {\n')
403
404 # last_protect = None
405 current_block = ''
406 for command in self.vk.commands.values():
407 if len(command.extensions) == 0:
408 continue
409 if command.name in DEVICE_CMDS_NEED_TERM:
410 if command.protect is not None:
411 out.append( f'#if defined({command.protect})\n')
412
413 current_block = self.DescribeBlock(command, current_block, out)
414
415 out.append( f' PFN_{command.name} {command.name[2:]};\n')
416
417 if command.protect is not None:
418 out.append( f'#endif // {command.protect}\n')
419
420 out.append( '};\n\n')
421
422
423 # Create a layer instance dispatch table from the appropriate list
424 def OutputLayerInstanceDispatchTable(self, out):
425
426 out.append('// Instance function pointer dispatch table\n')
427 out.append('typedef struct VkLayerInstanceDispatchTable_ {\n')
428
429 # First add in an entry for GetPhysicalDeviceProcAddr. This will not
430 # ever show up in the XML or header, so we have to manually add it.
431 out.append(' // Manually add in GetPhysicalDeviceProcAddr entry\n')
432 out.append(' PFN_GetPhysicalDeviceProcAddr GetPhysicalDeviceProcAddr;\n')
433
434 current_block = ''
435 for command_name, command in self.vk.commands.items():
436 if not command.instance:
437 continue
438
439 current_block = self.DescribeBlock(command, current_block, out)
440
441 if command.protect:
442 out.append(f'#if defined({command.protect})\n')
443
444 out.append(f' PFN_{command_name} {command_name[2:]};\n')
445
446 if command.protect:
447 out.append(f'#endif // {command.protect}\n')
448
449 out.append('} VkLayerInstanceDispatchTable;\n\n')
450
451 # Create a layer device dispatch table from the appropriate list
452 def OutputLayerDeviceDispatchTable(self, out):
453
454 out.append('// Device function pointer dispatch table\n')
455 out.append('#define DEVICE_DISP_TABLE_MAGIC_NUMBER 0x10ADED040410ADEDUL\n')
456 out.append('typedef struct VkLayerDispatchTable_ {\n')
457 out.append(' uint64_t magic; // Should be DEVICE_DISP_TABLE_MAGIC_NUMBER\n')
458
459 current_block = ''
460 for command in [x for x in self.vk.commands.values() if x.device]:
461
462 current_block = self.DescribeBlock(command, current_block, out)
463
464 if command.protect:
465 out.append(f'#if defined({command.protect})\n')
466
467 out.append(f' PFN_{command.name} {command.name[2:]};\n')
468
469 if command.protect:
470 out.append(f'#endif // {command.protect}\n')
471 out.append('} VkLayerDispatchTable;\n\n')
472
473 def OutputUtilitiesInSource(self, out):
474 out.append('''
475 // Device extension error function
476 VKAPI_ATTR VkResult VKAPI_CALL vkDevExtError(VkDevice dev) {
477 struct loader_device *found_dev;
478 // The device going in is a trampoline device
479 struct loader_icd_term *icd_term = loader_get_icd_and_device(dev, &found_dev);
480
481 if (icd_term)
482 loader_log(icd_term->this_instance, VULKAN_LOADER_ERROR_BIT, 0,
483 "Bad destination in loader trampoline dispatch,"
484 "Are layers and extensions that you are calling enabled?");
485 return VK_ERROR_EXTENSION_NOT_PRESENT;
486 }
487
488 ''')
489
490
491 # Init a dispatch table from the appropriate list
492 def OutputIcdDispatchTableInit(self, out):
493 out.append('VKAPI_ATTR bool VKAPI_CALL loader_icd_init_entries(struct loader_instance* inst, struct loader_icd_term *icd_term) {\n')
494 out.append(' const PFN_vkGetInstanceProcAddr fp_gipa = icd_term->scanned_icd->GetInstanceProcAddr;\n')
495 out.append('\n')
496 out.append('#define LOOKUP_GIPA(func) icd_term->dispatch.func = (PFN_vk##func)fp_gipa(icd_term->instance, "vk" #func);\n')
497 out.append('\n')
498 out.append('#define LOOKUP_REQUIRED_GIPA(func) \\\n')
499 out.append(' do { \\\n')
500 out.append(' LOOKUP_GIPA(func); \\\n')
501 out.append(' if (!icd_term->dispatch.func) { \\\n')
502 out.append(' loader_log(inst, VULKAN_LOADER_WARN_BIT, 0, "Unable to load %s from ICD %s",\\\n')
503 out.append(' "vk"#func, icd_term->scanned_icd->lib_name); \\\n')
504 out.append(' return false; \\\n')
505 out.append(' } \\\n')
506 out.append(' } while (0)\n')
507 out.append('\n')
508
509
510 skip_gipa_commands = ['vkGetInstanceProcAddr',
511 'vkEnumerateDeviceLayerProperties',
512 'vkCreateInstance',
513 'vkEnumerateInstanceExtensionProperties',
514 'vkEnumerateInstanceLayerProperties',
515 'vkEnumerateInstanceVersion',
516 ]
517
518 current_block = ''
519 for command in [x for x in self.vk.commands.values() if x.instance or x.name == 'vkGetDeviceProcAddr']:
520 if command.name in skip_gipa_commands:
521 continue
522 custom_commands_string= ' commands' if len(command.extensions) > 0 else ''
523 current_block = self.DescribeBlock(command, current_block, out, custom_commands_string=custom_commands_string)
524
525 if command.protect is not None:
526 out.append( f'#if defined({command.protect})\n')
527
528 effective_version_name = APISpecific.getEffectiveVersionName(self.targetApiName, command.version)
529 if effective_version_name == APISpecific.getFirstVersionName(self.targetApiName) and len(command.extensions) == 0:
530 # The Core Vulkan code will be wrapped in a feature called VK_VERSION_#_#
531 # For example: VK_VERSION_1_0 wraps the core 1.0 Vulkan functionality
532 out.append(f' LOOKUP_REQUIRED_GIPA({command.name[2:]});\n')
533 else:
534 out.append( f' LOOKUP_GIPA({command.name[2:]});\n')
535
536 if command.protect is not None:
537 out.append(f'#endif // {command.protect}\n')
538
539 out.append('\n')
540 out.append('#undef LOOKUP_REQUIRED_GIPA\n')
541 out.append('#undef LOOKUP_GIPA\n')
542 out.append('\n')
543 out.append(' return true;\n')
544 out.append('};\n\n')
545
546
547 # Creates code to initialize the various dispatch tables
548 def OutputLoaderDispatchTables(self, out):
549 commands = []
550 gpa_param = ''
551 cur_type = ''
552
553 for x in range(0, 4):
554 if x == 0:
555 cur_type = 'device'
556 gpa_param = 'dev'
557 commands = self.core_commands
558
559 out.append('// Init Device function pointer dispatch table with core commands\n')
560 out.append('VKAPI_ATTR void VKAPI_CALL loader_init_device_dispatch_table(struct loader_dev_dispatch_table *dev_table, PFN_vkGetDeviceProcAddr gpa,\n')
561 out.append(' VkDevice dev) {\n')
562 out.append(' VkLayerDispatchTable *table = &dev_table->core_dispatch;\n')
563 out.append(' if (table->magic != DEVICE_DISP_TABLE_MAGIC_NUMBER) { abort(); }\n')
564 out.append(' for (uint32_t i = 0; i < MAX_NUM_UNKNOWN_EXTS; i++) dev_table->ext_dispatch[i] = (PFN_vkDevExt)vkDevExtError;\n')
565
566 elif x == 1:
567 cur_type = 'device'
568 gpa_param = 'dev'
569 commands = self.extension_commands
570
571 out.append('// Init Device function pointer dispatch table with extension commands\n')
572 out.append('VKAPI_ATTR void VKAPI_CALL loader_init_device_extension_dispatch_table(struct loader_dev_dispatch_table *dev_table,\n')
573 out.append(' PFN_vkGetInstanceProcAddr gipa,\n')
574 out.append(' PFN_vkGetDeviceProcAddr gdpa,\n')
575 out.append(' VkInstance inst,\n')
576 out.append(' VkDevice dev) {\n')
577 out.append(' VkLayerDispatchTable *table = &dev_table->core_dispatch;\n')
578 out.append(' table->magic = DEVICE_DISP_TABLE_MAGIC_NUMBER;\n')
579
580 elif x == 2:
581 cur_type = 'instance'
582 gpa_param = 'inst'
583 commands = self.core_commands
584
585 out.append('// Init Instance function pointer dispatch table with core commands\n')
586 out.append('VKAPI_ATTR void VKAPI_CALL loader_init_instance_core_dispatch_table(VkLayerInstanceDispatchTable *table, PFN_vkGetInstanceProcAddr gpa,\n')
587 out.append(' VkInstance inst) {\n')
588
589 else:
590 cur_type = 'instance'
591 gpa_param = 'inst'
592 commands = self.extension_commands
593
594 out.append('// Init Instance function pointer dispatch table with core commands\n')
595 out.append('VKAPI_ATTR void VKAPI_CALL loader_init_instance_extension_dispatch_table(VkLayerInstanceDispatchTable *table, PFN_vkGetInstanceProcAddr gpa,\n')
596 out.append(' VkInstance inst) {\n')
597
598 current_block = ''
599 for command in commands:
600 is_inst_handle_type = command.params[0].type in ['VkInstance', 'VkPhysicalDevice']
601 if ((cur_type == 'instance' and is_inst_handle_type) or (cur_type == 'device' and not is_inst_handle_type)):
602
603 current_block = self.DescribeBlock(command, current_block, out)
604
605 # Remove 'vk' from proto name
606 base_name = command.name[2:]
607
608 # Names to skip
609 if (base_name == 'CreateInstance' or base_name == 'CreateDevice' or
610 base_name == 'EnumerateInstanceExtensionProperties' or
611 base_name == 'EnumerateInstanceLayerProperties' or
612 base_name == 'EnumerateInstanceVersion'):
613 continue
614
615 if command.protect is not None:
616 out.append(f'#if defined({command.protect})\n')
617
618 # If we're looking for the proc we are passing in, just point the table to it. This fixes the issue where
619 # a layer overrides the function name for the loader.
620 if x == 1:
621 if base_name == 'GetDeviceProcAddr':
622 out.append(' table->GetDeviceProcAddr = gdpa;\n')
623 elif len(command.extensions) > 0 and self.vk.extensions[command.extensions[0]].instance:
624 out.append(f' table->{base_name} = (PFN_{command.name})gipa(inst, "{command.name}");\n')
625 else:
626 out.append(f' table->{base_name} = (PFN_{command.name})gdpa(dev, "{command.name}");\n')
627 elif (x < 1 and base_name == 'GetDeviceProcAddr'):
628 out.append(' table->GetDeviceProcAddr = gpa;\n')
629 elif (x > 1 and base_name == 'GetInstanceProcAddr'):
630 out.append(' table->GetInstanceProcAddr = gpa;\n')
631 else:
632 out.append(f' table->{base_name} = (PFN_{command.name})gpa({gpa_param}, "{command.name}");\n')
633
634 if command.protect is not None:
635 out.append(f'#endif // {command.protect}\n')
636
637 out.append('}\n\n')
638
639 #
640 # Create code to initialize a dispatch table from the appropriate list of extension entrypoints
641 def InitDeviceFunctionTerminatorDispatchTable(self, out):
642 out.append('// Functions that required a terminator need to have a separate dispatch table which contains their corresponding\n')
643 out.append('// device function. This is used in the terminators themselves.\n')
644 out.append('void init_extension_device_proc_terminator_dispatch(struct loader_device *dev) {\n')
645 out.append(' struct loader_device_terminator_dispatch* dispatch = &dev->loader_dispatch.extension_terminator_dispatch;\n')
646 out.append(' PFN_vkGetDeviceProcAddr gpda = (PFN_vkGetDeviceProcAddr)dev->phys_dev_term->this_icd_term->dispatch.GetDeviceProcAddr;\n')
647 current_block = ''
648 for command in [x for x in self.vk.commands.values() if x.extensions or x.version]:
649 if command.name in DEVICE_CMDS_NEED_TERM:
650 if command.protect is not None:
651 out.append(f'#if defined({command.protect})\n')
652
653 current_block = self.DescribeBlock(command, current_block, out)
654 enable_extension_expressions = []
655 for ext in command.extensions:
656 enable_extension_expressions.append(f'dev->driver_extensions.{ext[3:].lower()}_enabled')
657 out.append(f' if ({" || ".join(enable_extension_expressions)})\n')
658 out.append(f' dispatch->{command.name[2:]} = (PFN_{(command.name)})gpda(dev->icd_device, "{(command.name)}");\n')
659
660 if command.protect is not None:
661 out.append(f'#endif // {command.protect}\n')
662
663 out.append('}\n\n')
664
665
666 def OutputDeviceFunctionTrampolinePrototypes(self, out):
667 out.append('// These are prototypes for functions that need their trampoline called in all circumstances.\n')
668 out.append('// They are used in loader_lookup_device_dispatch_table but are defined afterwards.\n')
669 current_block = ''
670 for command in self.vk.commands.values():
671 if command.name in DEVICE_CMDS_MUST_USE_TRAMP:
672
673 if command.protect is not None:
674 out.append(f'#if defined({command.protect})\n')
675 current_block = self.DescribeBlock(command, current_block, out)
676
677 out.append(f'{command.cPrototype.replace("VKAPI_CALL vk", "VKAPI_CALL ")}\n')
678
679 if command.protect is not None:
680 out.append(f'#endif // {command.protect}\n')
681 out.append('\n')
682
683
684 #
685 # Create a lookup table function from the appropriate list of entrypoints
686 def OutputLoaderLookupFunc(self, out):
687 commands = []
688 cur_type = ''
689
690 for x in range(0, 2):
691 if x == 0:
692 cur_type = 'device'
693
694 out.append('// Device command lookup function\n')
695 out.append('VKAPI_ATTR void* VKAPI_CALL loader_lookup_device_dispatch_table(const VkLayerDispatchTable *table, const char *name, bool* found_name) {\n')
696 out.append(' if (!name || name[0] != \'v\' || name[1] != \'k\') {\n')
697 out.append(' *found_name = false;\n')
698 out.append(' return NULL;\n')
699 out.append(' }\n')
700 out.append('\n')
701 out.append(' name += 2;\n')
702 out.append(' *found_name = true;\n')
703 out.append(' struct loader_device* dev = (struct loader_device *)table;\n')
704 out.append(' const struct loader_instance* inst = dev->phys_dev_term->this_icd_term->this_instance;\n')
705 out.append(' uint32_t api_version = VK_MAKE_API_VERSION(0, inst->app_api_version.major, inst->app_api_version.minor, inst->app_api_version.patch);\n')
706 out.append('\n')
707 else:
708 cur_type = 'instance'
709
710 out.append('// Instance command lookup function\n')
711 out.append('VKAPI_ATTR void* VKAPI_CALL loader_lookup_instance_dispatch_table(const VkLayerInstanceDispatchTable *table, const char *name,\n')
712 out.append(' bool *found_name) {\n')
713 out.append(' if (!name || name[0] != \'v\' || name[1] != \'k\') {\n')
714 out.append(' *found_name = false;\n')
715 out.append(' return NULL;\n')
716 out.append(' }\n')
717 out.append('\n')
718 out.append(' *found_name = true;\n')
719 out.append(' name += 2;\n')
720
721
722 for command_list in [self.core_commands, self.extension_commands]:
723 commands = command_list
724
725 version_check = ''
726 current_block = ''
727 for command in commands:
728 is_inst_handle_type = command.params[0].type in ['VkInstance', 'VkPhysicalDevice']
729 if ((cur_type == 'instance' and is_inst_handle_type) or (cur_type == 'device' and not is_inst_handle_type)):
730
731 current_block = self.DescribeBlock(command, current_block, out)
732 if len(command.extensions) == 0:
733 if cur_type == 'device':
734 effective_version_name = APISpecific.getEffectiveVersionName(self.targetApiName, command.version)
735 api_version = effective_version_name.replace('_VERSION_', '_API_VERSION_')
736 version_check = f" if (dev->should_ignore_device_commands_from_newer_version && api_version < {api_version}) return NULL;\n"
737 else:
738 version_check = ''
739
740 # Remove 'vk' from proto name
741 base_name = command.name[2:]
742
743 if (base_name == 'CreateInstance' or base_name == 'CreateDevice' or
744 base_name == 'EnumerateInstanceExtensionProperties' or
745 base_name == 'EnumerateInstanceLayerProperties' or
746 base_name == 'EnumerateInstanceVersion'):
747 continue
748
749 if command.protect is not None:
750 out.append(f'#if defined({command.protect})\n')
751
752 out.append(f' if (!strcmp(name, "{base_name}")) ')
753 if command.name in DEVICE_CMDS_MUST_USE_TRAMP:
754 if version_check != '':
755 out.append(f'{{\n{version_check} return dev->layer_extensions.{command.extensions[0][3:].lower()}_enabled ? (void *){base_name} : NULL;\n }}\n')
756 else:
757 out.append(f'return dev->layer_extensions.{command.extensions[0][3:].lower()}_enabled ? (void *){base_name} : NULL;\n')
758
759 else:
760 if version_check != '':
761 out.append(f'{{\n{version_check} return (void *)table->{base_name};\n }}\n')
762 else:
763 out.append(f'return (void *)table->{base_name};\n')
764
765 if command.protect is not None:
766 out.append(f'#endif // {command.protect}\n')
767
768 out.append('\n')
769 out.append(' *found_name = false;\n')
770 out.append(' return NULL;\n')
771 out.append('}\n\n')
772
773
774 #
775 # Create the appropriate trampoline (and possibly terminator) functions
776 def CreateTrampTermFuncs(self, out):
777 # Some extensions have to be manually added. Skip those in the automatic
778 # generation. They will be manually added later.
779 manual_ext_commands = ['vkEnumeratePhysicalDeviceGroupsKHR',
780 'vkGetPhysicalDeviceExternalImageFormatPropertiesNV',
781 'vkGetPhysicalDeviceFeatures2KHR',
782 'vkGetPhysicalDeviceProperties2KHR',
783 'vkGetPhysicalDeviceFormatProperties2KHR',
784 'vkGetPhysicalDeviceImageFormatProperties2KHR',
785 'vkGetPhysicalDeviceQueueFamilyProperties2KHR',
786 'vkGetPhysicalDeviceMemoryProperties2KHR',
787 'vkGetPhysicalDeviceSparseImageFormatProperties2KHR',
788 'vkGetPhysicalDeviceSurfaceCapabilities2KHR',
789 'vkGetPhysicalDeviceSurfaceFormats2KHR',
790 'vkGetPhysicalDeviceSurfaceCapabilities2EXT',
791 'vkReleaseDisplayEXT',
792 'vkAcquireXlibDisplayEXT',
793 'vkGetRandROutputDisplayEXT',
794 'vkGetPhysicalDeviceExternalBufferPropertiesKHR',
795 'vkGetPhysicalDeviceExternalSemaphorePropertiesKHR',
796 'vkGetPhysicalDeviceExternalFencePropertiesKHR',
797 'vkGetPhysicalDeviceDisplayProperties2KHR',
798 'vkGetPhysicalDeviceDisplayPlaneProperties2KHR',
799 'vkGetDisplayModeProperties2KHR',
800 'vkGetDisplayPlaneCapabilities2KHR',
801 'vkGetPhysicalDeviceSurfacePresentModes2EXT',
802 'vkGetDeviceGroupSurfacePresentModes2EXT',
803 'vkGetPhysicalDeviceToolPropertiesEXT']
804
805 current_block = ''
806 for command in [x for x in self.vk.commands.values() if x.extensions]:
807 if (command.extensions[0] in WSI_EXT_NAMES or
808 command.extensions[0] in AVOID_EXT_NAMES or
809 command.name in AVOID_CMD_NAMES or
810 command.name in manual_ext_commands):
811 continue
812
813 current_block = self.DescribeBlock(command=command, current_block=current_block, out=out, custom_commands_string=' trampoline/terminators\n', indent='')
814
815 if command.protect is not None:
816 out.append(f'#if defined({command.protect})\n')
817
818 func_header = command.cPrototype.replace(";", " {\n")
819 tramp_header = func_header.replace("VKAPI_CALL vk", "VKAPI_CALL ")
820 return_prefix = ' '
821 base_name = command.name[2:]
822 has_surface = 0
823 update_structure_surface = 0
824 update_structure_string = ''
825 requires_terminator = 0
826 surface_var_name = ''
827 phys_dev_var_name = ''
828 instance_var_name = ''
829 has_return_type = False
830 always_use_param_name = True
831 surface_type_to_replace = ''
832 surface_name_replacement = ''
833 physdev_type_to_replace = ''
834 physdev_name_replacement = ''
835
836 for param in command.params:
837 if param.type == 'VkSurfaceKHR':
838 has_surface = 1
839 surface_var_name = param.name
840 requires_terminator = 1
841 always_use_param_name = False
842 surface_type_to_replace = 'VkSurfaceKHR'
843 surface_name_replacement = 'unwrapped_surface'
844 if param.type == 'VkPhysicalDeviceSurfaceInfo2KHR':
845 has_surface = 1
846 surface_var_name = param.name + '->surface'
847 requires_terminator = 1
848 update_structure_surface = 1
849 update_structure_string = ' VkPhysicalDeviceSurfaceInfo2KHR info_copy = *pSurfaceInfo;\n'
850 update_structure_string += ' info_copy.surface = unwrapped_surface;\n'
851 always_use_param_name = False
852 surface_type_to_replace = 'VkPhysicalDeviceSurfaceInfo2KHR'
853 surface_name_replacement = '&info_copy'
854 if param.type == 'VkPhysicalDevice':
855 requires_terminator = 1
856 phys_dev_var_name = param.name
857 always_use_param_name = False
858 physdev_type_to_replace = 'VkPhysicalDevice'
859 physdev_name_replacement = 'phys_dev_term->phys_dev'
860 if param.type == 'VkInstance':
861 requires_terminator = 1
862 instance_var_name = param.name
863
864 if command.returnType != 'void':
865 return_prefix += 'return '
866 has_return_type = True
867
868 if ( command.params[0].type in ['VkInstance', 'VkPhysicalDevice'] or
869 'DebugMarkerSetObject' in command.name or 'SetDebugUtilsObject' in command.name or
870 command.name in DEVICE_CMDS_NEED_TERM):
871 requires_terminator = 1
872
873 if requires_terminator == 1:
874 term_header = tramp_header.replace("VKAPI_CALL ", "VKAPI_CALL terminator_")
875
876 out.append(tramp_header)
877
878 if command.params[0].type == 'VkPhysicalDevice':
879 out.append(' const VkLayerInstanceDispatchTable *disp;\n')
880 out.append(f' VkPhysicalDevice unwrapped_phys_dev = loader_unwrap_physical_device({phys_dev_var_name});\n')
881 out.append(' if (VK_NULL_HANDLE == unwrapped_phys_dev) {\n')
882 out.append(' loader_log(NULL, VULKAN_LOADER_FATAL_ERROR_BIT | VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_VALIDATION_BIT, 0,\n')
883 out.append(f' "{command.name}: Invalid {phys_dev_var_name} "\n')
884 out.append(f' "[VUID-{command.name}-{phys_dev_var_name}-parameter]");\n')
885 out.append(' abort(); /* Intentionally fail so user can correct issue. */\n')
886 out.append(' }\n')
887 out.append(f' disp = loader_get_instance_layer_dispatch({phys_dev_var_name});\n')
888 elif command.params[0].type == 'VkInstance':
889 out.append(f' struct loader_instance *inst = loader_get_instance({instance_var_name});\n')
890 out.append(' if (NULL == inst) {\n')
891 out.append(' loader_log(\n')
892 out.append(' NULL, VULKAN_LOADER_FATAL_ERROR_BIT | VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_VALIDATION_BIT, 0,\n')
893 out.append(f' "{command.name}: Invalid instance [VUID-{command.name}-{instance_var_name}-parameter]");\n')
894 out.append(' abort(); /* Intentionally fail so user can correct issue. */\n')
895 out.append(' }\n')
896 out.append('#error("Not implemented. Likely needs to be manually generated!");\n')
897 else:
898 out.append(' const VkLayerDispatchTable *disp = loader_get_dispatch(')
899 out.append(command.params[0].name)
900 out.append(');\n')
901 out.append(' if (NULL == disp) {\n')
902 out.append(' loader_log(NULL, VULKAN_LOADER_FATAL_ERROR_BIT | VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_VALIDATION_BIT, 0,\n')
903 out.append(f' "{command.name}: Invalid {command.params[0].name} "\n')
904 out.append(f' "[VUID-{command.name}-{command.params[0].name}-parameter]");\n')
905 out.append(' abort(); /* Intentionally fail so user can correct issue. */\n')
906 out.append(' }\n')
907
908 if 'DebugMarkerSetObjectName' in command.name:
909 out.append(' VkDebugMarkerObjectNameInfoEXT local_name_info;\n')
910 out.append(' memcpy(&local_name_info, pNameInfo, sizeof(VkDebugMarkerObjectNameInfoEXT));\n')
911 out.append(' // If this is a physical device, we have to replace it with the proper one for the next call.\n')
912 out.append(' if (pNameInfo->objectType == VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT) {\n')
913 out.append(' struct loader_physical_device_tramp *phys_dev_tramp = (struct loader_physical_device_tramp *)(uintptr_t)pNameInfo->object;\n')
914 out.append(' local_name_info.object = (uint64_t)(uintptr_t)phys_dev_tramp->phys_dev;\n')
915 out.append(' }\n')
916 out.append(' if (pNameInfo->objectType == VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT) {\n')
917 out.append(' struct loader_instance* instance = (struct loader_instance *)(uintptr_t)pNameInfo->object;\n')
918 out.append(' local_name_info.object = (uint64_t)(uintptr_t)instance->instance;\n')
919 out.append(' }\n')
920 elif 'DebugMarkerSetObjectTag' in command.name:
921 out.append(' VkDebugMarkerObjectTagInfoEXT local_tag_info;\n')
922 out.append(' memcpy(&local_tag_info, pTagInfo, sizeof(VkDebugMarkerObjectTagInfoEXT));\n')
923 out.append(' // If this is a physical device, we have to replace it with the proper one for the next call.\n')
924 out.append(' if (pTagInfo->objectType == VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT) {\n')
925 out.append(' struct loader_physical_device_tramp *phys_dev_tramp = (struct loader_physical_device_tramp *)(uintptr_t)pTagInfo->object;\n')
926 out.append(' local_tag_info.object = (uint64_t)(uintptr_t)phys_dev_tramp->phys_dev;\n')
927 out.append(' }\n')
928 out.append(' if (pTagInfo->objectType == VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT) {\n')
929 out.append(' struct loader_instance* instance = (struct loader_instance *)(uintptr_t)pTagInfo->object;\n')
930 out.append(' local_tag_info.object = (uint64_t)(uintptr_t)instance->instance;\n')
931 out.append(' }\n')
932 elif 'SetDebugUtilsObjectName' in command.name:
933 out.append(' VkDebugUtilsObjectNameInfoEXT local_name_info;\n')
934 out.append(' memcpy(&local_name_info, pNameInfo, sizeof(VkDebugUtilsObjectNameInfoEXT));\n')
935 out.append(' // If this is a physical device, we have to replace it with the proper one for the next call.\n')
936 out.append(' if (pNameInfo->objectType == VK_OBJECT_TYPE_PHYSICAL_DEVICE) {\n')
937 out.append(' struct loader_physical_device_tramp *phys_dev_tramp = (struct loader_physical_device_tramp *)(uintptr_t)pNameInfo->objectHandle;\n')
938 out.append(' local_name_info.objectHandle = (uint64_t)(uintptr_t)phys_dev_tramp->phys_dev;\n')
939 out.append(' }\n')
940 out.append(' if (pNameInfo->objectType == VK_OBJECT_TYPE_INSTANCE) {\n')
941 out.append(' struct loader_instance* instance = (struct loader_instance *)(uintptr_t)pNameInfo->objectHandle;\n')
942 out.append(' local_name_info.objectHandle = (uint64_t)(uintptr_t)instance->instance;\n')
943 out.append(' }\n')
944 elif 'SetDebugUtilsObjectTag' in command.name:
945 out.append(' VkDebugUtilsObjectTagInfoEXT local_tag_info;\n')
946 out.append(' memcpy(&local_tag_info, pTagInfo, sizeof(VkDebugUtilsObjectTagInfoEXT));\n')
947 out.append(' // If this is a physical device, we have to replace it with the proper one for the next call.\n')
948 out.append(' if (pTagInfo->objectType == VK_OBJECT_TYPE_PHYSICAL_DEVICE) {\n')
949 out.append(' struct loader_physical_device_tramp *phys_dev_tramp = (struct loader_physical_device_tramp *)(uintptr_t)pTagInfo->objectHandle;\n')
950 out.append(' local_tag_info.objectHandle = (uint64_t)(uintptr_t)phys_dev_tramp->phys_dev;\n')
951 out.append(' }\n')
952 out.append(' if (pTagInfo->objectType == VK_OBJECT_TYPE_INSTANCE) {\n')
953 out.append(' struct loader_instance* instance = (struct loader_instance *)(uintptr_t)pTagInfo->objectHandle;\n')
954 out.append(' local_tag_info.objectHandle = (uint64_t)(uintptr_t)instance->instance;\n')
955 out.append(' }\n')
956
957 if command.extensions[0] in NULL_CHECK_EXT_NAMES:
958 out.append(' if (disp->' + base_name + ' != NULL) {\n')
959 out.append(' ')
960 out.append(return_prefix)
961 if command.params[0].type == 'VkInstance':
962 out.append('inst->')
963 out.append('disp->')
964 out.append(base_name)
965 out.append('(')
966 count = 0
967 for param in command.params:
968 if count != 0:
969 out.append(', ')
970
971 if param.type == 'VkPhysicalDevice':
972 out.append('unwrapped_phys_dev')
973 elif ('DebugMarkerSetObject' in command.name or 'SetDebugUtilsObject' in command.name) and param.name == 'pNameInfo':
974 out.append('&local_name_info')
975 elif ('DebugMarkerSetObject' in command.name or 'SetDebugUtilsObject' in command.name) and param.name == 'pTagInfo':
976 out.append('&local_tag_info')
977 else:
978 out.append(param.name)
979
980 count += 1
981 out.append(');\n')
982 if command.extensions[0] in NULL_CHECK_EXT_NAMES:
983 if command.returnType != 'void':
984 out.append(' } else {\n')
985 out.append(' return VK_SUCCESS;\n')
986 out.append(' }\n')
987 out.append('}\n\n')
988
989 out.append(term_header)
990 if command.params[0].type == 'VkPhysicalDevice':
991 out.append(f' struct loader_physical_device_term *phys_dev_term = (struct loader_physical_device_term *){phys_dev_var_name};\n')
992 out.append(' struct loader_icd_term *icd_term = phys_dev_term->this_icd_term;\n')
993 out.append(' if (NULL == icd_term->dispatch.')
994 out.append(base_name)
995 out.append(') {\n')
996 fatal_error_bit = '' if has_return_type and (len(command.extensions) == 0 or self.vk.extensions[command.extensions[0]].instance) else 'VULKAN_LOADER_FATAL_ERROR_BIT | '
997 out.append(f' loader_log(icd_term->this_instance, {fatal_error_bit}VULKAN_LOADER_ERROR_BIT, 0,\n')
998 out.append(' "ICD associated with VkPhysicalDevice does not support ')
999 out.append(base_name)
1000 out.append('");\n')
1001
1002 # If this is an instance function taking a physical device (i.e. pre Vulkan 1.1), we need to behave and not crash so return an
1003 # error here.
1004 if has_return_type and (len(command.extensions) == 0 or self.vk.extensions[command.extensions[0]].instance):
1005 out.append(' return VK_ERROR_EXTENSION_NOT_PRESENT;\n')
1006 else:
1007 out.append(' abort(); /* Intentionally fail so user can correct issue. */\n')
1008 out.append(' }\n')
1009
1010 if has_surface == 1:
1011 out.append(f' VkSurfaceKHR unwrapped_surface = {surface_var_name};\n')
1012 out.append(' VkResult unwrap_res = wsi_unwrap_icd_surface(icd_term, &unwrapped_surface);\n')
1013 out.append(' if (unwrap_res == VK_SUCCESS) {\n')
1014
1015 # If there's a structure with a surface, we need to update its internals with the correct surface for the ICD
1016 if update_structure_surface == 1:
1017 out.append(update_structure_string)
1018
1019 out.append(' ' + return_prefix + 'icd_term->dispatch.')
1020 out.append(base_name)
1021 out.append('(')
1022 count = 0
1023 for param in command.params:
1024 if count != 0:
1025 out.append(', ')
1026
1027 if not always_use_param_name:
1028 if surface_type_to_replace and surface_type_to_replace == param.type:
1029 out.append(surface_name_replacement)
1030 elif physdev_type_to_replace and physdev_type_to_replace == param.type:
1031 out.append(physdev_name_replacement)
1032 else:
1033 out.append(param.name)
1034 else:
1035 out.append(param.name)
1036
1037 count += 1
1038 out.append(');\n')
1039 if not has_return_type:
1040 out.append(' return;\n')
1041 out.append(' }\n')
1042
1043 out.append(return_prefix)
1044 out.append('icd_term->dispatch.')
1045 out.append(base_name)
1046 out.append('(')
1047 count = 0
1048 for param in command.params:
1049 if count != 0:
1050 out.append(', ')
1051
1052 if param.type == 'VkPhysicalDevice':
1053 out.append('phys_dev_term->phys_dev')
1054 else:
1055 out.append(param.name)
1056
1057 count += 1
1058 out.append(');\n')
1059
1060
1061 elif command.params[0].type == 'VkInstance':
1062 out.append(f' struct loader_instance *inst = loader_get_instance({instance_var_name});\n')
1063 out.append(' if (NULL == inst) {\n')
1064 out.append(' loader_log(\n')
1065 out.append(' NULL, VULKAN_LOADER_FATAL_ERROR_BIT | VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_VALIDATION_BIT, 0,\n')
1066 out.append(f' "{command.name}: Invalid instance [VUID-{command.name}-{instance_var_name}-parameter]");\n')
1067 out.append(' abort(); /* Intentionally fail so user can correct issue. */\n')
1068 out.append(' }\n')
1069 out.append('#error("Not implemented. Likely needs to be manually generated!");\n')
1070 elif command.extensions[0] in ['VK_EXT_debug_utils', 'VK_EXT_debug_marker']:
1071 if command.name in ['vkDebugMarkerSetObjectNameEXT', 'vkDebugMarkerSetObjectTagEXT', 'vkSetDebugUtilsObjectNameEXT' , 'vkSetDebugUtilsObjectTagEXT']:
1072
1073 is_debug_utils = command.extensions[0] == "VK_EXT_debug_utils"
1074 debug_struct_name = command.params[1].name
1075 local_struct = 'local_name_info' if 'ObjectName' in command.name else 'local_tag_info'
1076 member_name = 'objectHandle' if is_debug_utils else 'object'
1077 phys_dev_check = 'VK_OBJECT_TYPE_PHYSICAL_DEVICE' if is_debug_utils else 'VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT'
1078 surf_check = 'VK_OBJECT_TYPE_SURFACE_KHR' if is_debug_utils else 'VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT'
1079 inst_check = 'VK_OBJECT_TYPE_INSTANCE' if is_debug_utils else 'VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT'
1080 out.append(' struct loader_device *dev;\n')
1081 out.append(f' struct loader_icd_term *icd_term = loader_get_icd_and_device({ command.params[0].name}, &dev);\n')
1082 out.append(' if (NULL == icd_term || NULL == dev) {\n')
1083 out.append(f' loader_log(NULL, VULKAN_LOADER_FATAL_ERROR_BIT | VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_VALIDATION_BIT, 0, "{command.name[2:]}: Invalid device handle");\n')
1084 out.append(' abort(); /* Intentionally fail so user can correct issue. */\n')
1085 out.append(' }\n')
1086 out.append(f' { command.params[1].type} {local_struct};\n')
1087 out.append(f' memcpy(&{local_struct}, {debug_struct_name}, sizeof({ command.params[1].type}));\n')
1088 out.append(' // If this is a physical device, we have to replace it with the proper one for the next call.\n')
1089 out.append(f' if ({debug_struct_name}->objectType == {phys_dev_check}) {{\n')
1090 out.append(f' struct loader_physical_device_term *phys_dev_term = (struct loader_physical_device_term *)(uintptr_t){debug_struct_name}->{member_name};\n')
1091 out.append(f' {local_struct}.{member_name} = (uint64_t)(uintptr_t)phys_dev_term->phys_dev;\n')
1092 out.append(' // If this is a KHR_surface, and the ICD has created its own, we have to replace it with the proper one for the next call.\n')
1093 out.append(f' }} else if ({debug_struct_name}->objectType == {surf_check}) {{\n')
1094 out.append(' if (NULL != dev && NULL != dev->loader_dispatch.core_dispatch.CreateSwapchainKHR) {\n')
1095 out.append(f' VkSurfaceKHR surface = (VkSurfaceKHR)(uintptr_t){debug_struct_name}->{member_name};\n')
1096 out.append(' if (wsi_unwrap_icd_surface(icd_term, &surface) == VK_SUCCESS) {\n')
1097 out.append(f' {local_struct}.{member_name} = (uint64_t)surface;\n')
1098 out.append(' }\n')
1099 out.append(' }\n')
1100 out.append(' // If this is an instance we have to replace it with the proper one for the next call.\n')
1101 out.append(f' }} else if ({debug_struct_name}->objectType == {inst_check}) {{\n')
1102 out.append(f' {local_struct}.{member_name} = (uint64_t)(uintptr_t)icd_term->instance;\n')
1103 out.append(' }\n')
1104 out.append(' // Exit early if the driver does not support the function - this can happen as a layer or the loader itself supports\n')
1105 out.append(' // debug utils but the driver does not.\n')
1106 out.append(f' if (NULL == dev->loader_dispatch.extension_terminator_dispatch.{command.name[2:]})\n return VK_SUCCESS;\n')
1107 dispatch = 'dev->loader_dispatch.'
1108 else:
1109 out.append(f' struct loader_dev_dispatch_table *dispatch_table = loader_get_dev_dispatch({command.params[0].name});\n')
1110 out.append(' if (NULL == dispatch_table) {\n')
1111 out.append(f' loader_log(NULL, VULKAN_LOADER_FATAL_ERROR_BIT | VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_VALIDATION_BIT, 0, "{command.extensions[0]}: Invalid device handle");\n')
1112 out.append(' abort(); /* Intentionally fail so user can correct issue. */\n')
1113 out.append(' }\n')
1114 out.append(' // Only call down if the device supports the function\n')
1115 out.append(f' if (NULL != dispatch_table->extension_terminator_dispatch.{base_name})\n ')
1116 dispatch = 'dispatch_table->'
1117 out.append(' ')
1118 if has_return_type:
1119 out.append('return ')
1120 out.append(f'{dispatch}extension_terminator_dispatch.{base_name}(')
1121 count = 0
1122 for param in command.params:
1123 if count != 0:
1124 out.append(', ')
1125
1126 if param.type == 'VkPhysicalDevice':
1127 out.append('phys_dev_term->phys_dev')
1128 elif param.type == 'VkSurfaceKHR':
1129 out.append( 'unwrapped_surface')
1130 elif ('DebugMarkerSetObject' in command.name or 'SetDebugUtilsObject' in command.name) and param.name == 'pNameInfo':
1131 out.append( '&local_name_info')
1132 elif ('DebugMarkerSetObject' in command.name or 'SetDebugUtilsObject' in command.name) and param.name == 'pTagInfo':
1133 out.append('&local_tag_info')
1134 else:
1135 out.append(param.name)
1136 count += 1
1137
1138 out.append(');\n')
1139
1140 else:
1141 out.append('#error("Unknown error path!");\n')
1142
1143 out.append('}\n\n')
1144 else:
1145 out.append(tramp_header)
1146
1147 out.append(' const VkLayerDispatchTable *disp = loader_get_dispatch(')
1148 out.append(command.params[0].name)
1149 out.append(');\n')
1150 out.append(' if (NULL == disp) {\n')
1151 out.append(' loader_log(NULL, VULKAN_LOADER_FATAL_ERROR_BIT | VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_VALIDATION_BIT, 0,\n')
1152 out.append(f' "{command.name}: Invalid {command.params[0].name} "\n')
1153 out.append(f' "[VUID-{command.name}-{command.params[0].name}-parameter]");\n')
1154 out.append(' abort(); /* Intentionally fail so user can correct issue. */\n')
1155 out.append(' }\n')
1156
1157 if command.extensions[0] in NULL_CHECK_EXT_NAMES:
1158 out.append(' if (disp->' + base_name + ' != NULL) {\n')
1159 out.append(' ')
1160 out.append(return_prefix)
1161 out.append('disp->')
1162 out.append(base_name)
1163 out.append('(')
1164 count = 0
1165 for param in command.params:
1166 if count != 0:
1167 out.append(', ')
1168 out.append(param.name)
1169 count += 1
1170 out.append(');\n')
1171 if command.extensions[0] in NULL_CHECK_EXT_NAMES:
1172 if command.returnType != 'void':
1173 out.append(' } else {\n')
1174 out.append(' return VK_SUCCESS;\n')
1175 out.append(' }\n')
1176 out.append('}\n\n')
1177
1178 if command.protect is not None:
1179 out.append(f'#endif // {command.protect}\n')
1180
1181
1182
1183 #
1184 # Create a function for the extension GPA call
1185 def InstExtensionGPA(self, out):
1186 cur_extension_name = ''
1187
1188 out.append( '// GPA helpers for extensions\n')
1189 out.append( 'bool extension_instance_gpa(struct loader_instance *ptr_instance, const char *name, void **addr) {\n')
1190 out.append( ' *addr = NULL;\n\n')
1191
1192 for command in [x for x in self.vk.commands.values() if x.extensions]:
1193 if (command.version or
1194 command.extensions[0] in WSI_EXT_NAMES or
1195 command.extensions[0] in AVOID_EXT_NAMES or
1196 command.name in AVOID_CMD_NAMES ):
1197 continue
1198
1199 if command.extensions[0] != cur_extension_name:
1200 out.append( f'\n // ---- {command.extensions[0]} extension commands\n')
1201 cur_extension_name = command.extensions[0]
1202
1203 if command.protect is not None:
1204 out.append( f'#if defined({command.protect})\n')
1205
1206 #base_name = command.name[2:]
1207 base_name = SHARED_ALIASES[command.name] if command.name in SHARED_ALIASES else command.name[2:]
1208
1209 if len(command.extensions) > 0 and self.vk.extensions[command.extensions[0]].instance:
1210 out.append( f' if (!strcmp("{command.name}", name)) {{\n')
1211 out.append( ' *addr = (ptr_instance->enabled_extensions.')
1212 out.append( command.extensions[0][3:].lower())
1213 out.append( ' == 1)\n')
1214 out.append( f' ? (void *){base_name}\n')
1215 out.append( ' : NULL;\n')
1216 out.append( ' return true;\n')
1217 out.append( ' }\n')
1218 else:
1219 out.append( f' if (!strcmp("{command.name}", name)) {{\n')
1220 out.append( f' *addr = (void *){base_name};\n')
1221 out.append( ' return true;\n')
1222 out.append( ' }\n')
1223
1224 if command.protect is not None:
1225 out.append( f'#endif // {command.protect}\n')
1226
1227 out.append( ' return false;\n')
1228 out.append( '}\n\n')
1229
1230
1231
1232 #
1233 # Create the extension name init function
1234 def InstantExtensionCreate(self, out):
1235
1236 out.append( '// Used to keep track of all enabled instance extensions\n')
1237 out.append( 'void fill_out_enabled_instance_extensions(uint32_t extension_count, const char *const * extension_list, struct loader_instance_extension_enable_list* enables) {\n')
1238 out.append( ' for (uint32_t i = 0; i < extension_count; i++) {\n')
1239 e = ''
1240 cur_extension_name = ''
1241 for extension in self.instance_extensions:
1242 if extension.name != cur_extension_name:
1243 out.append( f'\n // ---- {extension.name} extension commands\n')
1244 cur_extension_name = extension.name
1245
1246 if extension.protect is not None:
1247 out.append( f'#if defined({extension.protect})\n')
1248
1249 out.append(f' {e}if (0 == strcmp(extension_list[i], ')
1250
1251 out.append( f'{extension.nameString})) {{ enables->{extension.name[3:].lower()} = 1; }}\n')
1252
1253 if extension.protect is not None:
1254 out.append( f'#endif // {extension.protect}\n')
1255 e = 'else '
1256
1257 out.append( ' }\n')
1258 out.append( '}\n\n')
1259
1260
1261 #
1262 # Create code to initialize a dispatch table from the appropriate list of extension entrypoints
1263 def DeviceExtensionGetTerminator(self, out):
1264 out.append('// Some device commands still need a terminator because the loader needs to unwrap something about them.\n')
1265 out.append('// In many cases, the item needing unwrapping is a VkPhysicalDevice or VkSurfaceKHR object. But there may be other items\n')
1266 out.append('// in the future.\n')
1267 out.append('PFN_vkVoidFunction get_extension_device_proc_terminator(struct loader_device *dev, const char *name, bool* found_name) {\n')
1268 out.append(''' *found_name = false;
1269 if (!name || name[0] != 'v' || name[1] != 'k') {
1270 return NULL;
1271 }
1272 name += 2;
1273 ''')
1274 last_protect = None
1275 last_ext = None
1276 for command in [x for x in self.vk.commands.values() if x.extensions]:
1277 version = command.version
1278 if command.name in DEVICE_CMDS_NEED_TERM:
1279 if version:
1280 out.append(f' // ---- Core {version.name} commands\n')
1281 else:
1282 last_protect = command.protect
1283 if command.protect is not None:
1284 out.append(f'#if defined({command.protect})\n')
1285 if last_ext != command.extensions[0]:
1286 out.append(f' // ---- {command.extensions[0]} extension commands\n')
1287 last_ext = command.extensions[0]
1288
1289 out.append(f' if (!strcmp(name, "{command.name[2:]}")) {{\n')
1290 out.append(' *found_name = true;\n')
1291 enable_extension_expressions = []
1292 for ext in command.extensions:
1293 enable_extension_expressions.append(f'dev->driver_extensions.{ext[3:].lower()}_enabled')
1294 out.append(f' return {" || ".join(enable_extension_expressions)} ?\n')
1295 out.append(f' (PFN_vkVoidFunction)terminator_{(command.name[2:])} : NULL;\n')
1296 out.append(' }\n')
1297
1298 if last_protect is not None:
1299 out.append(f'#endif // {last_protect}\n')
1300
1301 out.append(' return NULL;\n')
1302 out.append('}\n\n')
1303
1304
1305
1306 #
1307 # Create code to initialize a dispatch table from the appropriate list of core and extension entrypoints
1308 def InitInstLoaderExtensionDispatchTable(self, out):
1309 commands = []
1310
1311 out.append( '// This table contains the loader\'s instance dispatch table, which contains\n')
1312 out.append( '// default functions if no instance layers are activated. This contains\n')
1313 out.append( '// pointers to "terminator functions".\n')
1314 out.append( 'const VkLayerInstanceDispatchTable instance_disp = {\n')
1315
1316 for command_list in [self.core_commands, self.extension_commands]:
1317 commands = command_list
1318
1319 current_block = ''
1320 for command in commands:
1321 if command.params[0].type in ['VkInstance', 'VkPhysicalDevice']:
1322 current_block = self.DescribeBlock(command, current_block, out)
1323 # Remove 'vk' from proto name
1324 base_name = command.name[2:]
1325 aliased_name = SHARED_ALIASES[command.name][2:] if command.name in SHARED_ALIASES else base_name
1326
1327 if (base_name == 'CreateInstance' or base_name == 'CreateDevice' or
1328 base_name == 'EnumerateInstanceExtensionProperties' or
1329 base_name == 'EnumerateInstanceLayerProperties' or
1330 base_name == 'EnumerateInstanceVersion'):
1331 continue
1332
1333 if command.protect is not None:
1334 out.append( f'#if defined({command.protect})\n')
1335
1336 if base_name == 'GetInstanceProcAddr':
1337 out.append( f' .{base_name} = {command.name},\n')
1338 else:
1339 out.append( f' .{base_name} = terminator_{aliased_name},\n')
1340
1341 if command.protect is not None:
1342 out.append( f'#endif // {command.protect}\n')
1343 out.append( '};\n\n')
1344
1345
1346
1347 #
1348 # Create the extension name whitelist array
1349 def OutputInstantExtensionWhitelistArray(self, out):
1350 out.append( '// A null-terminated list of all of the instance extensions supported by the loader.\n')
1351 out.append( '// If an instance extension name is not in this list, but it is exported by one or more of the\n')
1352 out.append( '// ICDs detected by the loader, then the extension name not in the list will be filtered out\n')
1353 out.append( '// before passing the list of extensions to the application.\n')
1354 out.append( 'const char *const LOADER_INSTANCE_EXTENSIONS[] = {\n')
1355 for extension in self.instance_extensions:
1356
1357 if extension.protect is not None:
1358 out.append( f'#if defined({extension.protect})\n')
1359 out.append( ' ')
1360 out.append( extension.nameString + ',\n')
1361
1362 if extension.protect is not None:
1363 out.append( f'#endif // {extension.protect}\n')
1364 out.append( ' NULL };\n')