blob: 8608605fbddee9e410b11acceed73a2707621124 [file] [log] [blame]
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001#!/usr/bin/python3 -i
2#
Dave Houlton57ae22f2018-05-18 16:20:52 -06003# Copyright (c) 2015-2018 The Khronos Group Inc.
4# Copyright (c) 2015-2018 Valve Corporation
5# Copyright (c) 2015-2018 LunarG, Inc.
6# Copyright (c) 2015-2018 Google Inc.
Mark Lobodzinskid1461482017-07-18 13:56:09 -06007#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Author: Mark Lobodzinski <mark@lunarg.com>
Dave Houlton57ae22f2018-05-18 16:20:52 -060021# Author: Dave Houlton <daveh@lunarg.com>
Mark Lobodzinskid1461482017-07-18 13:56:09 -060022
Dave Houlton57ae22f2018-05-18 16:20:52 -060023import os,re,sys,string,json
Mark Lobodzinskid1461482017-07-18 13:56:09 -060024import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
Mark Lobodzinski62f71562017-10-24 13:41:18 -060027from common_codegen import *
Mark Lobodzinskid1461482017-07-18 13:56:09 -060028
Jamie Madill8d4cda22017-11-08 13:40:09 -050029# This is a workaround to use a Python 2.7 and 3.x compatible syntax.
30from io import open
31
Mark Lobodzinskid1461482017-07-18 13:56:09 -060032# ObjectTrackerGeneratorOptions - subclass of GeneratorOptions.
33#
34# Adds options used by ObjectTrackerOutputGenerator objects during
35# object_tracker layer generation.
36#
37# Additional members
38# prefixText - list of strings to prefix generated header with
39# (usually a copyright statement + calling convention macros).
40# protectFile - True if multiple inclusion protection should be
41# generated (based on the filename) around the entire header.
42# protectFeature - True if #ifndef..#endif protection should be
43# generated around a feature interface in the header file.
44# genFuncPointers - True if function pointer typedefs should be
45# generated
46# protectProto - If conditional protection should be generated
47# around prototype declarations, set to either '#ifdef'
48# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
49# to require opt-out (#ifndef protectProtoStr). Otherwise
50# set to None.
51# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
52# declarations, if protectProto is set
53# apicall - string to use for the function declaration prefix,
54# such as APICALL on Windows.
55# apientry - string to use for the calling convention macro,
56# in typedefs, such as APIENTRY.
57# apientryp - string to use for the calling convention macro
58# in function pointer typedefs, such as APIENTRYP.
59# indentFuncProto - True if prototype declarations should put each
60# parameter on a separate line
61# indentFuncPointer - True if typedefed function pointers should put each
62# parameter on a separate line
63# alignFuncParam - if nonzero and parameters are being put on a
64# separate line, align parameter names at the specified column
65class ObjectTrackerGeneratorOptions(GeneratorOptions):
66 def __init__(self,
67 filename = None,
68 directory = '.',
69 apiname = None,
70 profile = None,
71 versions = '.*',
72 emitversions = '.*',
73 defaultExtensions = None,
74 addExtensions = None,
75 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060076 emitExtensions = None,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060077 sortProcedure = regSortFeatures,
78 prefixText = "",
79 genFuncPointers = True,
80 protectFile = True,
81 protectFeature = True,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060082 apicall = '',
83 apientry = '',
84 apientryp = '',
85 indentFuncProto = True,
86 indentFuncPointer = False,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060087 alignFuncParam = 0,
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -060088 expandEnumerants = True,
89 valid_usage_path = ''):
Mark Lobodzinskid1461482017-07-18 13:56:09 -060090 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
91 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060092 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinskid1461482017-07-18 13:56:09 -060093 self.prefixText = prefixText
94 self.genFuncPointers = genFuncPointers
95 self.protectFile = protectFile
96 self.protectFeature = protectFeature
Mark Lobodzinskid1461482017-07-18 13:56:09 -060097 self.apicall = apicall
98 self.apientry = apientry
99 self.apientryp = apientryp
100 self.indentFuncProto = indentFuncProto
101 self.indentFuncPointer = indentFuncPointer
102 self.alignFuncParam = alignFuncParam
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600103 self.expandEnumerants = expandEnumerants
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600104 self.valid_usage_path = valid_usage_path
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600105
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600106
107# ObjectTrackerOutputGenerator - subclass of OutputGenerator.
108# Generates object_tracker layer object validation code
109#
110# ---- methods ----
111# ObjectTrackerOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
112# ---- methods overriding base class ----
113# beginFile(genOpts)
114# endFile()
115# beginFeature(interface, emit)
116# endFeature()
117# genCmd(cmdinfo)
118# genStruct()
119# genType()
120class ObjectTrackerOutputGenerator(OutputGenerator):
121 """Generate ObjectTracker code based on XML element attributes"""
122 # This is an ordered list of sections in the header file.
123 ALL_SECTIONS = ['command']
124 def __init__(self,
125 errFile = sys.stderr,
126 warnFile = sys.stderr,
127 diagFile = sys.stdout):
128 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
129 self.INDENT_SPACES = 4
130 self.intercepts = []
131 self.instance_extensions = []
132 self.device_extensions = []
133 # Commands which are not autogenerated but still intercepted
134 self.no_autogen_list = [
135 'vkDestroyInstance',
136 'vkDestroyDevice',
137 'vkUpdateDescriptorSets',
138 'vkDestroyDebugReportCallbackEXT',
139 'vkDebugReportMessageEXT',
140 'vkGetPhysicalDeviceQueueFamilyProperties',
141 'vkFreeCommandBuffers',
142 'vkDestroySwapchainKHR',
143 'vkDestroyDescriptorPool',
144 'vkDestroyCommandPool',
Mark Lobodzinski14ddc192017-10-25 16:57:04 -0600145 'vkGetPhysicalDeviceQueueFamilyProperties2',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600146 'vkGetPhysicalDeviceQueueFamilyProperties2KHR',
147 'vkResetDescriptorPool',
148 'vkBeginCommandBuffer',
149 'vkCreateDebugReportCallbackEXT',
150 'vkEnumerateInstanceLayerProperties',
151 'vkEnumerateDeviceLayerProperties',
152 'vkEnumerateInstanceExtensionProperties',
153 'vkEnumerateDeviceExtensionProperties',
154 'vkCreateDevice',
155 'vkCreateInstance',
156 'vkEnumeratePhysicalDevices',
157 'vkAllocateCommandBuffers',
158 'vkAllocateDescriptorSets',
159 'vkFreeDescriptorSets',
Tony Barbour2fd0c2c2017-08-08 12:51:33 -0600160 'vkCmdPushDescriptorSetKHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600161 'vkDebugMarkerSetObjectNameEXT',
162 'vkGetPhysicalDeviceProcAddr',
163 'vkGetDeviceProcAddr',
164 'vkGetInstanceProcAddr',
165 'vkEnumerateInstanceExtensionProperties',
166 'vkEnumerateInstanceLayerProperties',
167 'vkEnumerateDeviceLayerProperties',
168 'vkGetDeviceProcAddr',
169 'vkGetInstanceProcAddr',
170 'vkEnumerateDeviceExtensionProperties',
171 'vk_layerGetPhysicalDeviceProcAddr',
172 'vkNegotiateLoaderLayerInterfaceVersion',
173 'vkCreateComputePipelines',
174 'vkGetDeviceQueue',
Yiwei Zhang991d88d2018-02-14 14:39:46 -0800175 'vkGetDeviceQueue2',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600176 'vkGetSwapchainImagesKHR',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100177 'vkCreateDescriptorSetLayout',
Mark Lobodzinski5a1c8d22018-07-02 10:28:12 -0600178 'vkGetDescriptorSetLayoutSupport',
179 'vkGetDescriptorSetLayoutSupportKHR',
Mark Young6ba8abe2017-11-09 10:37:04 -0700180 'vkCreateDebugUtilsMessengerEXT',
181 'vkDestroyDebugUtilsMessengerEXT',
182 'vkSubmitDebugUtilsMessageEXT',
183 'vkSetDebugUtilsObjectNameEXT',
184 'vkSetDebugUtilsObjectTagEXT',
185 'vkQueueBeginDebugUtilsLabelEXT',
186 'vkQueueEndDebugUtilsLabelEXT',
187 'vkQueueInsertDebugUtilsLabelEXT',
188 'vkCmdBeginDebugUtilsLabelEXT',
189 'vkCmdEndDebugUtilsLabelEXT',
190 'vkCmdInsertDebugUtilsLabelEXT',
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600191 'vkGetDisplayModePropertiesKHR',
192 'vkGetPhysicalDeviceDisplayPropertiesKHR',
Piers Daniell16c253f2018-05-30 14:34:05 -0600193 'vkGetPhysicalDeviceDisplayProperties2KHR',
194 'vkGetDisplayPlaneSupportedDisplaysKHR',
195 'vkGetDisplayModeProperties2KHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600196 ]
197 # These VUIDS are not implicit, but are best handled in this layer. Codegen for vkDestroy calls will generate a key
198 # which is translated here into a good VU. Saves ~40 checks.
199 self.manual_vuids = dict()
200 self.manual_vuids = {
Dave Houlton57ae22f2018-05-18 16:20:52 -0600201 "fence-compatalloc": "\"VUID-vkDestroyFence-fence-01121\"",
202 "fence-nullalloc": "\"VUID-vkDestroyFence-fence-01122\"",
203 "event-compatalloc": "\"VUID-vkDestroyEvent-event-01146\"",
204 "event-nullalloc": "\"VUID-vkDestroyEvent-event-01147\"",
205 "buffer-compatalloc": "\"VUID-vkDestroyBuffer-buffer-00923\"",
206 "buffer-nullalloc": "\"VUID-vkDestroyBuffer-buffer-00924\"",
207 "image-compatalloc": "\"VUID-vkDestroyImage-image-01001\"",
208 "image-nullalloc": "\"VUID-vkDestroyImage-image-01002\"",
209 "shaderModule-compatalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01092\"",
210 "shaderModule-nullalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01093\"",
211 "pipeline-compatalloc": "\"VUID-vkDestroyPipeline-pipeline-00766\"",
212 "pipeline-nullalloc": "\"VUID-vkDestroyPipeline-pipeline-00767\"",
213 "sampler-compatalloc": "\"VUID-vkDestroySampler-sampler-01083\"",
214 "sampler-nullalloc": "\"VUID-vkDestroySampler-sampler-01084\"",
215 "renderPass-compatalloc": "\"VUID-vkDestroyRenderPass-renderPass-00874\"",
216 "renderPass-nullalloc": "\"VUID-vkDestroyRenderPass-renderPass-00875\"",
217 "descriptorUpdateTemplate-compatalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00356\"",
218 "descriptorUpdateTemplate-nullalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00357\"",
219 "imageView-compatalloc": "\"VUID-vkDestroyImageView-imageView-01027\"",
220 "imageView-nullalloc": "\"VUID-vkDestroyImageView-imageView-01028\"",
221 "pipelineCache-compatalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00771\"",
222 "pipelineCache-nullalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00772\"",
223 "pipelineLayout-compatalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00299\"",
224 "pipelineLayout-nullalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00300\"",
225 "descriptorSetLayout-compatalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00284\"",
226 "descriptorSetLayout-nullalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00285\"",
227 "semaphore-compatalloc": "\"VUID-vkDestroySemaphore-semaphore-01138\"",
228 "semaphore-nullalloc": "\"VUID-vkDestroySemaphore-semaphore-01139\"",
229 "queryPool-compatalloc": "\"VUID-vkDestroyQueryPool-queryPool-00794\"",
230 "queryPool-nullalloc": "\"VUID-vkDestroyQueryPool-queryPool-00795\"",
231 "bufferView-compatalloc": "\"VUID-vkDestroyBufferView-bufferView-00937\"",
232 "bufferView-nullalloc": "\"VUID-vkDestroyBufferView-bufferView-00938\"",
233 "surface-compatalloc": "\"VUID-vkDestroySurfaceKHR-surface-01267\"",
234 "surface-nullalloc": "\"VUID-vkDestroySurfaceKHR-surface-01268\"",
235 "framebuffer-compatalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00893\"",
236 "framebuffer-nullalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00894\"",
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600237 }
238
239 # Commands shadowed by interface functions and are not implemented
240 self.interface_functions = [
241 ]
242 self.headerVersion = None
243 # Internal state - accumulators for different inner block text
244 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
John Zulaufbb6e5e42018-08-06 16:00:07 -0600245 self.cmd_list = [] # list of commands processed to maintain ordering
246 self.cmd_info_dict = {} # Per entry-point data for code generation and validation
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600247 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
248 self.extension_structs = [] # List of all structs or sister-structs containing handles
249 # A sister-struct may contain no handles but shares <validextensionstructs> with one that does
250 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
251 self.struct_member_dict = dict()
252 # Named tuples to store struct and command data
253 self.StructType = namedtuple('StructType', ['name', 'value'])
John Zulaufbb6e5e42018-08-06 16:00:07 -0600254 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo', 'members', 'extra_protect', 'alias', 'iscreate', 'isdestroy', 'allocator'])
255 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'isconst', 'isoptional', 'iscount', 'iscreate', 'len', 'extstructs', 'cdecl', 'islocal'])
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600256 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
257 self.object_types = [] # List of all handle types
258 self.valid_vuids = set() # Set of all valid VUIDs
Dave Houlton57ae22f2018-05-18 16:20:52 -0600259 self.vuid_dict = dict() # VUID dictionary (from JSON)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600260 #
261 # Check if the parameter passed in is optional
262 def paramIsOptional(self, param):
263 # See if the handle is optional
264 isoptional = False
265 # Simple, if it's optional, return true
266 optString = param.attrib.get('optional')
267 if optString:
268 if optString == 'true':
269 isoptional = True
270 elif ',' in optString:
271 opts = []
272 for opt in optString.split(','):
273 val = opt.strip()
274 if val == 'true':
275 opts.append(True)
276 elif val == 'false':
277 opts.append(False)
278 else:
279 print('Unrecognized len attribute value',val)
280 isoptional = opts
John Zulauf9f6788c2018-04-04 14:54:11 -0600281 if not isoptional:
282 # Matching logic in parameter validation and ValidityOutputGenerator.isHandleOptional
283 optString = param.attrib.get('noautovalidity')
284 if optString and optString == 'true':
285 isoptional = True;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600286 return isoptional
287 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600288 # Get VUID identifier from implicit VUID tag
Dave Houlton57ae22f2018-05-18 16:20:52 -0600289 def GetVuid(self, parent, suffix):
290 vuid_string = 'VUID-%s-%s' % (parent, suffix)
291 vuid = "kVUIDUndefined"
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600292 if '->' in vuid_string:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600293 return vuid
294 if vuid_string in self.valid_vuids:
295 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600296 else:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600297 alias = self.cmd_info_dict[parent].alias if parent in self.cmd_info_dict else None
298 if alias:
299 alias_string = 'VUID-%s-%s' % (alias, suffix)
Dave Houlton57ae22f2018-05-18 16:20:52 -0600300 if alias_string in self.valid_vuids:
301 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600302 return vuid
303 #
304 # Increases indent by 4 spaces and tracks it globally
305 def incIndent(self, indent):
306 inc = ' ' * self.INDENT_SPACES
307 if indent:
308 return indent + inc
309 return inc
310 #
311 # Decreases indent by 4 spaces and tracks it globally
312 def decIndent(self, indent):
313 if indent and (len(indent) > self.INDENT_SPACES):
314 return indent[:-self.INDENT_SPACES]
315 return ''
316 #
317 # Override makeProtoName to drop the "vk" prefix
318 def makeProtoName(self, name, tail):
319 return self.genOpts.apientry + name[2:] + tail
320 #
321 # Check if the parameter passed in is a pointer to an array
322 def paramIsArray(self, param):
323 return param.attrib.get('len') is not None
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000324
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600325 #
326 # Generate the object tracker undestroyed object validation function
327 def GenReportFunc(self):
328 output_func = ''
Dave Houlton379f1422018-05-23 12:47:07 -0600329 output_func += 'void ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600330 output_func += ' DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);\n'
331 for handle in self.object_types:
332 if self.isHandleTypeNonDispatchable(handle):
333 output_func += ' DeviceReportUndestroyedObjects(device, %s, error_code);\n' % (self.GetVulkanObjType(handle))
334 output_func += '}\n'
335 return output_func
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000336
337 #
338 # Generate the object tracker undestroyed object destruction function
339 def GenDestroyFunc(self):
340 output_func = ''
341 output_func += 'void DestroyUndestroyedObjects(VkDevice device) {\n'
342 output_func += ' DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer);\n'
343 for handle in self.object_types:
344 if self.isHandleTypeNonDispatchable(handle):
345 output_func += ' DeviceDestroyUndestroyedObjects(device, %s);\n' % (self.GetVulkanObjType(handle))
346 output_func += '}\n'
347 return output_func
348
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600349 #
Dave Houlton57ae22f2018-05-18 16:20:52 -0600350 # Walk the JSON-derived dict and find all "vuid" key values
351 def ExtractVUIDs(self, d):
352 if hasattr(d, 'items'):
353 for k, v in d.items():
354 if k == "vuid":
355 yield v
356 elif isinstance(v, dict):
357 for s in self.ExtractVUIDs(v):
358 yield s
359 elif isinstance (v, list):
360 for l in v:
361 for s in self.ExtractVUIDs(l):
362 yield s
363
364 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600365 # Called at beginning of processing as file is opened
366 def beginFile(self, genOpts):
367 OutputGenerator.beginFile(self, genOpts)
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600368
369 self.valid_usage_path = genOpts.valid_usage_path
370 vu_json_filename = os.path.join(self.valid_usage_path + os.sep, 'validusage.json')
371 if os.path.isfile(vu_json_filename):
372 json_file = open(vu_json_filename, 'r')
373 self.vuid_dict = json.load(json_file)
374 json_file.close()
375 if len(self.vuid_dict) == 0:
376 print("Error: Could not find, or error loading %s/validusage.json\n", vu_json_filename)
377 sys.exit(1)
378
Dave Houlton57ae22f2018-05-18 16:20:52 -0600379 # Build a set of all vuid text strings found in validusage.json
380 for json_vuid_string in self.ExtractVUIDs(self.vuid_dict):
381 self.valid_vuids.add(json_vuid_string)
382
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600383 # File Comment
384 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
385 file_comment += '// See object_tracker_generator.py for modifications\n'
386 write(file_comment, file=self.outFile)
387 # Copyright Statement
388 copyright = ''
389 copyright += '\n'
390 copyright += '/***************************************************************************\n'
391 copyright += ' *\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600392 copyright += ' * Copyright (c) 2015-2018 The Khronos Group Inc.\n'
393 copyright += ' * Copyright (c) 2015-2018 Valve Corporation\n'
394 copyright += ' * Copyright (c) 2015-2018 LunarG, Inc.\n'
395 copyright += ' * Copyright (c) 2015-2018 Google Inc.\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600396 copyright += ' *\n'
397 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
398 copyright += ' * you may not use this file except in compliance with the License.\n'
399 copyright += ' * You may obtain a copy of the License at\n'
400 copyright += ' *\n'
401 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
402 copyright += ' *\n'
403 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
404 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
405 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
406 copyright += ' * See the License for the specific language governing permissions and\n'
407 copyright += ' * limitations under the License.\n'
408 copyright += ' *\n'
409 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600410 copyright += ' * Author: Dave Houlton <daveh@lunarg.com>\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600411 copyright += ' *\n'
412 copyright += ' ****************************************************************************/\n'
413 write(copyright, file=self.outFile)
414 # Namespace
415 self.newline()
416 write('#include "object_tracker.h"', file = self.outFile)
417 self.newline()
418 write('namespace object_tracker {', file = self.outFile)
419 #
420 # Now that the data is all collected and complete, generate and output the object validation routines
421 def endFile(self):
422 self.struct_member_dict = dict(self.structMembers)
423 # Generate the list of APIs that might need to handle wrapped extension structs
424 # self.GenerateCommandWrapExtensionList()
425 self.WrapCommands()
426 # Build undestroyed objects reporting function
427 report_func = self.GenReportFunc()
428 self.newline()
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000429 # Build undestroyed objects destruction function
430 destroy_func = self.GenDestroyFunc()
431 self.newline()
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600432 write('// ObjectTracker undestroyed objects validation function', file=self.outFile)
433 write('%s' % report_func, file=self.outFile)
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000434 write('%s' % destroy_func, file=self.outFile)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600435 # Actually write the interface to the output file.
436 if (self.emit):
437 self.newline()
438 if (self.featureExtraProtect != None):
439 write('#ifdef', self.featureExtraProtect, file=self.outFile)
440 # Write the object_tracker code to the file
441 if (self.sections['command']):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600442 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
443 if (self.featureExtraProtect != None):
444 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
445 else:
446 self.newline()
447
448 # Record intercepted procedures
449 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
John Zulauf9b777302018-10-08 11:15:51 -0600450 write('const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600451 write('\n'.join(self.intercepts), file=self.outFile)
452 write('};\n', file=self.outFile)
453 self.newline()
454 write('} // namespace object_tracker', file=self.outFile)
455 # Finish processing in superclass
456 OutputGenerator.endFile(self)
457 #
458 # Processing point at beginning of each extension definition
459 def beginFeature(self, interface, emit):
460 # Start processing in superclass
461 OutputGenerator.beginFeature(self, interface, emit)
462 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600463 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600464
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600465 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600466 white_list_entry = []
467 if (self.featureExtraProtect != None):
468 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
469 white_list_entry += [ '"%s"' % self.featureName ]
470 if (self.featureExtraProtect != None):
471 white_list_entry += [ '#endif' ]
472 featureType = interface.get('type')
473 if featureType == 'instance':
474 self.instance_extensions += white_list_entry
475 elif featureType == 'device':
476 self.device_extensions += white_list_entry
477 #
478 # Processing point at end of each extension definition
479 def endFeature(self):
480 # Finish processing in superclass
481 OutputGenerator.endFeature(self)
482 #
483 # Process enums, structs, etc.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700484 def genType(self, typeinfo, name, alias):
485 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600486 typeElem = typeinfo.elem
487 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
488 # Otherwise, emit the tag text.
489 category = typeElem.get('category')
490 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700491 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600492 if category == 'handle':
493 self.object_types.append(name)
494 #
495 # Append a definition to the specified section
496 def appendSection(self, section, text):
497 # self.sections[section].append('SECTION: ' + section + '\n')
498 self.sections[section].append(text)
499 #
500 # Check if the parameter passed in is a pointer
501 def paramIsPointer(self, param):
502 ispointer = False
503 for elem in param:
504 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
505 ispointer = True
506 return ispointer
507 #
508 # Get the category of a type
509 def getTypeCategory(self, typename):
510 types = self.registry.tree.findall("types/type")
511 for elem in types:
512 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
513 return elem.attrib.get('category')
514 #
515 # Check if a parent object is dispatchable or not
516 def isHandleTypeObject(self, handletype):
517 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
518 if handle is not None:
519 return True
520 else:
521 return False
522 #
523 # Check if a parent object is dispatchable or not
524 def isHandleTypeNonDispatchable(self, handletype):
525 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
526 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
527 return True
528 else:
529 return False
530 #
531 # Retrieve the type and name for a parameter
532 def getTypeNameTuple(self, param):
533 type = ''
534 name = ''
535 for elem in param:
536 if elem.tag == 'type':
537 type = noneStr(elem.text)
538 elif elem.tag == 'name':
539 name = noneStr(elem.text)
540 return (type, name)
541 #
542 # Retrieve the value of the len tag
543 def getLen(self, param):
544 result = None
545 len = param.attrib.get('len')
546 if len and len != 'null-terminated':
547 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
548 # have a null terminated array of strings. We strip the null-terminated from the
549 # 'len' field and only return the parameter specifying the string count
550 if 'null-terminated' in len:
551 result = len.split(',')[0]
552 else:
553 result = len
554 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
555 result = str(result).replace('::', '->')
556 return result
557 #
558 # Generate a VkStructureType based on a structure typename
559 def genVkStructureType(self, typename):
560 # Add underscore between lowercase then uppercase
561 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
562 # Change to uppercase
563 value = value.upper()
564 # Add STRUCTURE_TYPE_
565 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
566 #
567 # Struct parameter check generation.
568 # This is a special case of the <type> tag where the contents are interpreted as a set of
569 # <member> tags instead of freeform C type declarations. The <member> tags are just like
570 # <param> tags - they are a declaration of a struct or union member. Only simple member
571 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700572 def genStruct(self, typeinfo, typeName, alias):
573 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600574 members = typeinfo.elem.findall('.//member')
575 # Iterate over members once to get length parameters for arrays
576 lens = set()
577 for member in members:
578 len = self.getLen(member)
579 if len:
580 lens.add(len)
581 # Generate member info
582 membersInfo = []
583 for member in members:
584 # Get the member's type and name
585 info = self.getTypeNameTuple(member)
586 type = info[0]
587 name = info[1]
588 cdecl = self.makeCParamDecl(member, 0)
589 # Process VkStructureType
590 if type == 'VkStructureType':
591 # Extract the required struct type value from the comments
592 # embedded in the original text defining the 'typeinfo' element
593 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
594 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
595 if result:
596 value = result.group(0)
597 else:
598 value = self.genVkStructureType(typeName)
599 # Store the required type value
600 self.structTypes[typeName] = self.StructType(name=name, value=value)
601 # Store pointer/array/string info
602 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
603 membersInfo.append(self.CommandParam(type=type,
604 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600605 isconst=True if 'const' in cdecl else False,
606 isoptional=self.paramIsOptional(member),
607 iscount=True if name in lens else False,
608 len=self.getLen(member),
609 extstructs=extstructs,
610 cdecl=cdecl,
611 islocal=False,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600612 iscreate=False))
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600613 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
614 #
615 # Insert a lock_guard line
616 def lock_guard(self, indent):
617 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
618 #
619 # Determine if a struct has an object as a member or an embedded member
620 def struct_contains_object(self, struct_item):
621 struct_member_dict = dict(self.structMembers)
622 struct_members = struct_member_dict[struct_item]
623
624 for member in struct_members:
625 if self.isHandleTypeObject(member.type):
626 return True
627 elif member.type in struct_member_dict:
628 if self.struct_contains_object(member.type) == True:
629 return True
630 return False
631 #
632 # Return list of struct members which contain, or whose sub-structures contain an obj in a given list of parameters or members
633 def getParmeterStructsWithObjects(self, item_list):
634 struct_list = set()
635 for item in item_list:
636 paramtype = item.find('type')
637 typecategory = self.getTypeCategory(paramtype.text)
638 if typecategory == 'struct':
639 if self.struct_contains_object(paramtype.text) == True:
640 struct_list.add(item)
641 return struct_list
642 #
643 # Return list of objects from a given list of parameters or members
644 def getObjectsInParameterList(self, item_list, create_func):
645 object_list = set()
646 if create_func == True:
647 member_list = item_list[0:-1]
648 else:
649 member_list = item_list
650 for item in member_list:
651 if self.isHandleTypeObject(paramtype.text):
652 object_list.add(item)
653 return object_list
654 #
655 # Construct list of extension structs containing handles, or extension structs that share a <validextensionstructs>
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600656 # tag WITH an extension struct containing handles.
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600657 def GenerateCommandWrapExtensionList(self):
658 for struct in self.structMembers:
659 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
660 found = False;
661 for item in struct.members[1].extstructs.split(','):
662 if item != '' and self.struct_contains_object(item) == True:
663 found = True
664 if found == True:
665 for item in struct.members[1].extstructs.split(','):
666 if item != '' and item not in self.extension_structs:
667 self.extension_structs.append(item)
668 #
669 # Returns True if a struct may have a pNext chain containing an object
670 def StructWithExtensions(self, struct_type):
671 if struct_type in self.struct_member_dict:
672 param_info = self.struct_member_dict[struct_type]
673 if (len(param_info) > 1) and param_info[1].extstructs is not None:
674 for item in param_info[1].extstructs.split(','):
675 if item in self.extension_structs:
676 return True
677 return False
678 #
679 # Generate VulkanObjectType from object type
680 def GetVulkanObjType(self, type):
681 return 'kVulkanObjectType%s' % type[2:]
682 #
683 # Return correct dispatch table type -- instance or device
684 def GetDispType(self, type):
685 return 'instance' if type in ['VkInstance', 'VkPhysicalDevice'] else 'device'
686 #
687 # Generate source for creating a Vulkan object
John Zulaufbb6e5e42018-08-06 16:00:07 -0600688 def generate_create_object_code(self, indent, proto, params, cmd_info, allocator):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600689 create_obj_code = ''
690 handle_type = params[-1].find('type')
691 if self.isHandleTypeObject(handle_type.text):
692 # Check for special case where multiple handles are returned
693 object_array = False
694 if cmd_info[-1].len is not None:
695 object_array = True;
696 handle_name = params[-1].find('name')
697 create_obj_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
698 indent = self.incIndent(indent)
699 create_obj_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
700 object_dest = '*%s' % handle_name.text
701 if object_array == True:
702 create_obj_code += '%sfor (uint32_t index = 0; index < %s; index++) {\n' % (indent, cmd_info[-1].len)
703 indent = self.incIndent(indent)
704 object_dest = '%s[index]' % cmd_info[-1].name
John Zulaufbb6e5e42018-08-06 16:00:07 -0600705 create_obj_code += '%sCreateObject(%s, %s, %s, %s);\n' % (indent, params[0].find('name').text, object_dest, self.GetVulkanObjType(cmd_info[-1].type), allocator)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600706 if object_array == True:
707 indent = self.decIndent(indent)
708 create_obj_code += '%s}\n' % indent
709 indent = self.decIndent(indent)
710 create_obj_code += '%s}\n' % (indent)
711 return create_obj_code
712 #
713 # Generate source for destroying a non-dispatchable object
714 def generate_destroy_object_code(self, indent, proto, cmd_info):
715 destroy_obj_code = ''
716 object_array = False
717 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
718 # Check for special case where multiple handles are returned
719 if cmd_info[-1].len is not None:
720 object_array = True;
721 param = -1
722 else:
723 param = -2
724 compatalloc_vuid_string = '%s-compatalloc' % cmd_info[param].name
725 nullalloc_vuid_string = '%s-nullalloc' % cmd_info[param].name
Dave Houlton57ae22f2018-05-18 16:20:52 -0600726 compatalloc_vuid = self.manual_vuids.get(compatalloc_vuid_string, "kVUIDUndefined")
727 nullalloc_vuid = self.manual_vuids.get(nullalloc_vuid_string, "kVUIDUndefined")
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600728 if self.isHandleTypeObject(cmd_info[param].type) == True:
729 if object_array == True:
730 # This API is freeing an array of handles -- add loop control
731 destroy_obj_code += 'HEY, NEED TO DESTROY AN ARRAY\n'
732 else:
733 # Call Destroy a single time
734 destroy_obj_code += '%sif (skip) return;\n' % indent
735 destroy_obj_code += '%s{\n' % indent
736 destroy_obj_code += '%s std::lock_guard<std::mutex> lock(global_lock);\n' % indent
737 destroy_obj_code += '%s DestroyObject(%s, %s, %s, pAllocator, %s, %s);\n' % (indent, cmd_info[0].name, cmd_info[param].name, self.GetVulkanObjType(cmd_info[param].type), compatalloc_vuid, nullalloc_vuid)
738 destroy_obj_code += '%s}\n' % indent
739 return object_array, destroy_obj_code
740 #
741 # Output validation for a single object (obj_count is NULL) or a counted list of objects
742 def outputObjects(self, obj_type, obj_name, obj_count, prefix, index, indent, destroy_func, destroy_array, disp_name, parent_name, null_allowed, top_level):
743 decl_code = ''
744 pre_call_code = ''
745 post_call_code = ''
Dave Houlton57ae22f2018-05-18 16:20:52 -0600746 param_suffix = '%s-parameter' % (obj_name)
747 parent_suffix = '%s-parent' % (obj_name)
748 param_vuid = self.GetVuid(parent_name, param_suffix)
749 parent_vuid = self.GetVuid(parent_name, parent_suffix)
750
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600751 # If no parent VUID for this member, look for a commonparent VUID
Dave Houlton57ae22f2018-05-18 16:20:52 -0600752 if parent_vuid == 'kVUIDUndefined':
753 parent_vuid = self.GetVuid(parent_name, 'commonparent')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600754 if obj_count is not None:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600755 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, obj_count, index)
756 indent = self.incIndent(indent)
757 pre_call_code += '%s skip |= ValidateObject(%s, %s%s[%s], %s, %s, %s, %s);\n' % (indent, disp_name, prefix, obj_name, index, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
758 indent = self.decIndent(indent)
759 pre_call_code += '%s }\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600760 else:
761 pre_call_code += '%s skip |= ValidateObject(%s, %s%s, %s, %s, %s, %s);\n' % (indent, disp_name, prefix, obj_name, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
762 return decl_code, pre_call_code, post_call_code
763 #
764 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
765 # create_func means that this is API creates or allocates objects
766 # destroy_func indicates that this API destroys or frees objects
767 # destroy_array means that the destroy_func operated on an array of objects
768 def validate_objects(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, disp_name, parent_name, first_level_param):
769 decls = ''
770 pre_code = ''
771 post_code = ''
772 index = 'index%s' % str(array_index)
773 array_index += 1
774 # Process any objects in this structure and recurse for any sub-structs in this struct
775 for member in members:
776 # Handle objects
777 if member.iscreate and first_level_param and member == members[-1]:
778 continue
779 if self.isHandleTypeObject(member.type) == True:
780 count_name = member.len
781 if (count_name is not None):
782 count_name = '%s%s' % (prefix, member.len)
783 null_allowed = member.isoptional
784 (tmp_decl, tmp_pre, tmp_post) = self.outputObjects(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, disp_name, parent_name, str(null_allowed).lower(), first_level_param)
785 decls += tmp_decl
786 pre_code += tmp_pre
787 post_code += tmp_post
788 # Handle Structs that contain objects at some level
789 elif member.type in self.struct_member_dict:
790 # Structs at first level will have an object
791 if self.struct_contains_object(member.type) == True:
792 struct_info = self.struct_member_dict[member.type]
Jeff Bolz38b3ce72018-09-19 12:53:38 -0500793 # TODO (jbolz): Can this use paramIsPointer?
Jeff Bolzba74d972018-09-12 15:54:57 -0500794 ispointer = '*' in member.cdecl;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600795 # Struct Array
796 if member.len is not None:
797 # Update struct prefix
798 new_prefix = '%s%s' % (prefix, member.name)
799 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
800 indent = self.incIndent(indent)
801 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
802 indent = self.incIndent(indent)
803 local_prefix = '%s[%s].' % (new_prefix, index)
804 # Process sub-structs in this struct
805 (tmp_decl, tmp_pre, tmp_post) = self.validate_objects(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, disp_name, member.type, False)
806 decls += tmp_decl
807 pre_code += tmp_pre
808 post_code += tmp_post
809 indent = self.decIndent(indent)
810 pre_code += '%s }\n' % indent
811 indent = self.decIndent(indent)
812 pre_code += '%s }\n' % indent
813 # Single Struct
Jeff Bolzba74d972018-09-12 15:54:57 -0500814 elif ispointer:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600815 # Update struct prefix
816 new_prefix = '%s%s->' % (prefix, member.name)
817 # Declare safe_VarType for struct
818 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
819 indent = self.incIndent(indent)
820 # Process sub-structs in this struct
821 (tmp_decl, tmp_pre, tmp_post) = self.validate_objects(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, disp_name, member.type, False)
822 decls += tmp_decl
823 pre_code += tmp_pre
824 post_code += tmp_post
825 indent = self.decIndent(indent)
826 pre_code += '%s }\n' % indent
Jeff Bolzba74d972018-09-12 15:54:57 -0500827 else:
828 # Update struct prefix
829 new_prefix = '%s%s.' % (prefix, member.name)
830 # Declare safe_VarType for struct
831 # Process sub-structs in this struct
832 (tmp_decl, tmp_pre, tmp_post) = self.validate_objects(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, disp_name, member.type, False)
833 decls += tmp_decl
834 pre_code += tmp_pre
835 post_code += tmp_post
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600836 return decls, pre_code, post_code
837 #
838 # For a particular API, generate the object handling code
839 def generate_wrapping_code(self, cmd):
840 indent = ' '
841 proto = cmd.find('proto/name')
842 params = cmd.findall('param')
843 if proto.text is not None:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600844 cmddata = self.cmd_info_dict[proto.text]
845 cmd_info = cmddata.members
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600846 disp_name = cmd_info[0].name
John Zulaufbb6e5e42018-08-06 16:00:07 -0600847 # Handle object create operations if last parameter is created by this call
848 if cmddata.iscreate:
849 create_obj_code = self.generate_create_object_code(indent, proto, params, cmd_info, cmddata.allocator)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600850 else:
851 create_obj_code = ''
852 # Handle object destroy operations
John Zulaufbb6e5e42018-08-06 16:00:07 -0600853 if cmddata.isdestroy:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600854 (destroy_array, destroy_object_code) = self.generate_destroy_object_code(indent, proto, cmd_info)
855 else:
856 destroy_array = False
857 destroy_object_code = ''
858 paramdecl = ''
859 param_pre_code = ''
860 param_post_code = ''
861 create_func = True if create_obj_code else False
862 destroy_func = True if destroy_object_code else False
863 (paramdecl, param_pre_code, param_post_code) = self.validate_objects(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, disp_name, proto.text, True)
864 param_post_code += create_obj_code
865 if destroy_object_code:
866 if destroy_array == True:
867 param_post_code += destroy_object_code
868 else:
869 param_pre_code += destroy_object_code
870 if param_pre_code:
871 if (not destroy_func) or (destroy_array):
872 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
873 return paramdecl, param_pre_code, param_post_code
874 #
875 # Capture command parameter info needed to create, destroy, and validate objects
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700876 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600877
878 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700879 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600880 members = cmdinfo.elem.findall('.//param')
881 # Iterate over members once to get length parameters for arrays
882 lens = set()
883 for member in members:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600884 length = self.getLen(member)
885 if length:
886 lens.add(length)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600887 struct_member_dict = dict(self.structMembers)
John Zulaufbb6e5e42018-08-06 16:00:07 -0600888
889 # Set command invariant information needed at a per member level in validate...
890 is_create_command = any(filter(lambda pat: pat in cmdname, ('Create', 'Allocate', 'Enumerate', 'RegisterDeviceEvent', 'RegisterDisplayEvent')))
891 last_member_is_pointer = len(members) and self.paramIsPointer(members[-1])
892 iscreate = is_create_command or ('vkGet' in cmdname and last_member_is_pointer)
893 isdestroy = any([destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']])
894
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600895 # Generate member info
896 membersInfo = []
897 constains_extension_structs = False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600898 allocator = 'nullptr'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600899 for member in members:
900 # Get type and name of member
901 info = self.getTypeNameTuple(member)
902 type = info[0]
903 name = info[1]
904 cdecl = self.makeCParamDecl(member, 0)
905 # Check for parameter name in lens set
906 iscount = True if name in lens else False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600907 length = self.getLen(member)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600908 isconst = True if 'const' in cdecl else False
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600909 # Mark param as local if it is an array of objects
910 islocal = False;
911 if self.isHandleTypeObject(type) == True:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600912 if (length is not None) and (isconst == True):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600913 islocal = True
914 # Or if it's a struct that contains an object
915 elif type in struct_member_dict:
916 if self.struct_contains_object(type) == True:
917 islocal = True
John Zulaufbb6e5e42018-08-06 16:00:07 -0600918 if type == 'VkAllocationCallbacks':
919 allocator = name
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600920 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
921 membersInfo.append(self.CommandParam(type=type,
922 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600923 isconst=isconst,
924 isoptional=self.paramIsOptional(member),
925 iscount=iscount,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600926 len=length,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600927 extstructs=extstructs,
928 cdecl=cdecl,
929 islocal=islocal,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600930 iscreate=iscreate))
931
932 self.cmd_list.append(cmdname)
933 self.cmd_info_dict[cmdname] =self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo, members=membersInfo, iscreate=iscreate, isdestroy=isdestroy, allocator=allocator, extra_protect=self.featureExtraProtect, alias=alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600934 #
935 # Create code Create, Destroy, and validate Vulkan objects
936 def WrapCommands(self):
John Zulaufbb6e5e42018-08-06 16:00:07 -0600937 for cmdname in self.cmd_list:
938 cmddata = self.cmd_info_dict[cmdname]
939 cmdinfo = cmddata.cmdinfo
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600940 if cmdname in self.interface_functions:
941 continue
942 if cmdname in self.no_autogen_list:
943 decls = self.makeCDecls(cmdinfo.elem)
944 self.appendSection('command', '')
945 self.appendSection('command', '// Declare only')
946 self.appendSection('command', decls[0])
947 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
948 continue
949 # Generate object handling code
950 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
951 # If API doesn't contain any object handles, don't fool with it
952 if not api_decls and not api_pre and not api_post:
953 continue
John Zulaufbb6e5e42018-08-06 16:00:07 -0600954 feature_extra_protect = cmddata.extra_protect
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600955 if (feature_extra_protect != None):
956 self.appendSection('command', '')
957 self.appendSection('command', '#ifdef '+ feature_extra_protect)
958 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
959 # Add intercept to procmap
960 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
961 decls = self.makeCDecls(cmdinfo.elem)
962 self.appendSection('command', '')
963 self.appendSection('command', decls[0][:-1])
964 self.appendSection('command', '{')
965 self.appendSection('command', ' bool skip = false;')
966 # Handle return values, if any
967 resulttype = cmdinfo.elem.find('proto/type')
968 if (resulttype != None and resulttype.text == 'void'):
969 resulttype = None
970 if (resulttype != None):
971 assignresult = resulttype.text + ' result = '
972 else:
973 assignresult = ''
974 # Pre-pend declarations and pre-api-call codegen
975 if api_decls:
976 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
977 if api_pre:
978 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
979 # Generate the API call itself
980 # Gather the parameter items
981 params = cmdinfo.elem.findall('param/name')
982 # Pull out the text for each of the parameters, separate them by commas in a list
983 paramstext = ', '.join([str(param.text) for param in params])
984 # Use correct dispatch table
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600985 disp_name = cmdinfo.elem.find('param/name').text
Mark Lobodzinski17de5fd2018-06-22 15:09:53 -0600986 disp_type = cmdinfo.elem.find('param/type').text
987 if disp_type in ["VkInstance", "VkPhysicalDevice"] or cmdname == 'vkCreateInstance':
988 object_type = 'instance'
989 else:
990 object_type = 'device'
991 dispatch_table = 'GetLayerDataPtr(get_dispatch_key(%s), layer_data_map)->%s_dispatch_table.' % (disp_name, object_type)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600992 API = cmdinfo.elem.attrib.get('name').replace('vk', dispatch_table, 1)
993 # Put all this together for the final down-chain call
994 if assignresult != '':
Jamie Madillfc315192017-11-08 14:11:26 -0500995 if resulttype.text == 'VkResult':
996 self.appendSection('command', ' if (skip) return VK_ERROR_VALIDATION_FAILED_EXT;')
997 elif resulttype.text == 'VkBool32':
998 self.appendSection('command', ' if (skip) return VK_FALSE;')
999 else:
1000 raise Exception('Unknown result type ' + resulttype.text)
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001001 else:
1002 self.appendSection('command', ' if (skip) return;')
1003 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
1004 # And add the post-API-call codegen
1005 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
1006 # Handle the return result variable, if any
1007 if (resulttype != None):
1008 self.appendSection('command', ' return result;')
1009 self.appendSection('command', '}')
1010 if (feature_extra_protect != None):
1011 self.appendSection('command', '#endif // '+ feature_extra_protect)
1012 self.intercepts += [ '#endif' ]