blob: ed923a7df0e09276be11f0d1f882f86ea3583f34 [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 = ''
Mark Lobodzinski5183a032018-09-13 14:44:28 -0600329 output_func += 'bool ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {\n'
330 output_func += ' bool skip = false;\n'
331 output_func += ' skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600332 for handle in self.object_types:
333 if self.isHandleTypeNonDispatchable(handle):
Mark Lobodzinski5183a032018-09-13 14:44:28 -0600334 output_func += ' skip |= DeviceReportUndestroyedObjects(device, %s, error_code);\n' % (self.GetVulkanObjType(handle))
335 output_func += ' return skip;\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600336 output_func += '}\n'
337 return output_func
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000338
339 #
340 # Generate the object tracker undestroyed object destruction function
341 def GenDestroyFunc(self):
342 output_func = ''
343 output_func += 'void DestroyUndestroyedObjects(VkDevice device) {\n'
344 output_func += ' DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer);\n'
345 for handle in self.object_types:
346 if self.isHandleTypeNonDispatchable(handle):
347 output_func += ' DeviceDestroyUndestroyedObjects(device, %s);\n' % (self.GetVulkanObjType(handle))
348 output_func += '}\n'
349 return output_func
350
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600351 #
Dave Houlton57ae22f2018-05-18 16:20:52 -0600352 # Walk the JSON-derived dict and find all "vuid" key values
353 def ExtractVUIDs(self, d):
354 if hasattr(d, 'items'):
355 for k, v in d.items():
356 if k == "vuid":
357 yield v
358 elif isinstance(v, dict):
359 for s in self.ExtractVUIDs(v):
360 yield s
361 elif isinstance (v, list):
362 for l in v:
363 for s in self.ExtractVUIDs(l):
364 yield s
365
366 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600367 # Called at beginning of processing as file is opened
368 def beginFile(self, genOpts):
369 OutputGenerator.beginFile(self, genOpts)
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600370
371 self.valid_usage_path = genOpts.valid_usage_path
372 vu_json_filename = os.path.join(self.valid_usage_path + os.sep, 'validusage.json')
373 if os.path.isfile(vu_json_filename):
374 json_file = open(vu_json_filename, 'r')
375 self.vuid_dict = json.load(json_file)
376 json_file.close()
377 if len(self.vuid_dict) == 0:
378 print("Error: Could not find, or error loading %s/validusage.json\n", vu_json_filename)
379 sys.exit(1)
380
Dave Houlton57ae22f2018-05-18 16:20:52 -0600381 # Build a set of all vuid text strings found in validusage.json
382 for json_vuid_string in self.ExtractVUIDs(self.vuid_dict):
383 self.valid_vuids.add(json_vuid_string)
384
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600385 # File Comment
386 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
387 file_comment += '// See object_tracker_generator.py for modifications\n'
388 write(file_comment, file=self.outFile)
389 # Copyright Statement
390 copyright = ''
391 copyright += '\n'
392 copyright += '/***************************************************************************\n'
393 copyright += ' *\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600394 copyright += ' * Copyright (c) 2015-2018 The Khronos Group Inc.\n'
395 copyright += ' * Copyright (c) 2015-2018 Valve Corporation\n'
396 copyright += ' * Copyright (c) 2015-2018 LunarG, Inc.\n'
397 copyright += ' * Copyright (c) 2015-2018 Google Inc.\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600398 copyright += ' *\n'
399 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
400 copyright += ' * you may not use this file except in compliance with the License.\n'
401 copyright += ' * You may obtain a copy of the License at\n'
402 copyright += ' *\n'
403 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
404 copyright += ' *\n'
405 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
406 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
407 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
408 copyright += ' * See the License for the specific language governing permissions and\n'
409 copyright += ' * limitations under the License.\n'
410 copyright += ' *\n'
411 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600412 copyright += ' * Author: Dave Houlton <daveh@lunarg.com>\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600413 copyright += ' *\n'
414 copyright += ' ****************************************************************************/\n'
415 write(copyright, file=self.outFile)
416 # Namespace
417 self.newline()
418 write('#include "object_tracker.h"', file = self.outFile)
419 self.newline()
420 write('namespace object_tracker {', file = self.outFile)
421 #
422 # Now that the data is all collected and complete, generate and output the object validation routines
423 def endFile(self):
424 self.struct_member_dict = dict(self.structMembers)
425 # Generate the list of APIs that might need to handle wrapped extension structs
426 # self.GenerateCommandWrapExtensionList()
427 self.WrapCommands()
428 # Build undestroyed objects reporting function
429 report_func = self.GenReportFunc()
430 self.newline()
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000431 # Build undestroyed objects destruction function
432 destroy_func = self.GenDestroyFunc()
433 self.newline()
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600434 write('// ObjectTracker undestroyed objects validation function', file=self.outFile)
435 write('%s' % report_func, file=self.outFile)
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000436 write('%s' % destroy_func, file=self.outFile)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600437 # Actually write the interface to the output file.
438 if (self.emit):
439 self.newline()
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100440 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600441 write('#ifdef', self.featureExtraProtect, file=self.outFile)
442 # Write the object_tracker code to the file
443 if (self.sections['command']):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600444 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100445 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600446 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
447 else:
448 self.newline()
449
450 # Record intercepted procedures
451 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
John Zulauf9b777302018-10-08 11:15:51 -0600452 write('const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600453 write('\n'.join(self.intercepts), file=self.outFile)
454 write('};\n', file=self.outFile)
455 self.newline()
456 write('} // namespace object_tracker', file=self.outFile)
457 # Finish processing in superclass
458 OutputGenerator.endFile(self)
459 #
460 # Processing point at beginning of each extension definition
461 def beginFeature(self, interface, emit):
462 # Start processing in superclass
463 OutputGenerator.beginFeature(self, interface, emit)
464 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600465 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600466
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600467 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600468 white_list_entry = []
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100469 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600470 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
471 white_list_entry += [ '"%s"' % self.featureName ]
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100472 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600473 white_list_entry += [ '#endif' ]
474 featureType = interface.get('type')
475 if featureType == 'instance':
476 self.instance_extensions += white_list_entry
477 elif featureType == 'device':
478 self.device_extensions += white_list_entry
479 #
480 # Processing point at end of each extension definition
481 def endFeature(self):
482 # Finish processing in superclass
483 OutputGenerator.endFeature(self)
484 #
485 # Process enums, structs, etc.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700486 def genType(self, typeinfo, name, alias):
487 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600488 typeElem = typeinfo.elem
489 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
490 # Otherwise, emit the tag text.
491 category = typeElem.get('category')
492 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700493 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600494 if category == 'handle':
495 self.object_types.append(name)
496 #
497 # Append a definition to the specified section
498 def appendSection(self, section, text):
499 # self.sections[section].append('SECTION: ' + section + '\n')
500 self.sections[section].append(text)
501 #
502 # Check if the parameter passed in is a pointer
503 def paramIsPointer(self, param):
504 ispointer = False
505 for elem in param:
506 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
507 ispointer = True
508 return ispointer
509 #
510 # Get the category of a type
511 def getTypeCategory(self, typename):
512 types = self.registry.tree.findall("types/type")
513 for elem in types:
514 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
515 return elem.attrib.get('category')
516 #
517 # Check if a parent object is dispatchable or not
518 def isHandleTypeObject(self, handletype):
519 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
520 if handle is not None:
521 return True
522 else:
523 return False
524 #
525 # Check if a parent object is dispatchable or not
526 def isHandleTypeNonDispatchable(self, handletype):
527 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
528 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
529 return True
530 else:
531 return False
532 #
533 # Retrieve the type and name for a parameter
534 def getTypeNameTuple(self, param):
535 type = ''
536 name = ''
537 for elem in param:
538 if elem.tag == 'type':
539 type = noneStr(elem.text)
540 elif elem.tag == 'name':
541 name = noneStr(elem.text)
542 return (type, name)
543 #
544 # Retrieve the value of the len tag
545 def getLen(self, param):
546 result = None
547 len = param.attrib.get('len')
548 if len and len != 'null-terminated':
549 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
550 # have a null terminated array of strings. We strip the null-terminated from the
551 # 'len' field and only return the parameter specifying the string count
552 if 'null-terminated' in len:
553 result = len.split(',')[0]
554 else:
555 result = len
556 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
557 result = str(result).replace('::', '->')
558 return result
559 #
560 # Generate a VkStructureType based on a structure typename
561 def genVkStructureType(self, typename):
562 # Add underscore between lowercase then uppercase
563 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
564 # Change to uppercase
565 value = value.upper()
566 # Add STRUCTURE_TYPE_
567 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
568 #
569 # Struct parameter check generation.
570 # This is a special case of the <type> tag where the contents are interpreted as a set of
571 # <member> tags instead of freeform C type declarations. The <member> tags are just like
572 # <param> tags - they are a declaration of a struct or union member. Only simple member
573 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700574 def genStruct(self, typeinfo, typeName, alias):
575 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600576 members = typeinfo.elem.findall('.//member')
577 # Iterate over members once to get length parameters for arrays
578 lens = set()
579 for member in members:
580 len = self.getLen(member)
581 if len:
582 lens.add(len)
583 # Generate member info
584 membersInfo = []
585 for member in members:
586 # Get the member's type and name
587 info = self.getTypeNameTuple(member)
588 type = info[0]
589 name = info[1]
590 cdecl = self.makeCParamDecl(member, 0)
591 # Process VkStructureType
592 if type == 'VkStructureType':
593 # Extract the required struct type value from the comments
594 # embedded in the original text defining the 'typeinfo' element
595 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
596 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
597 if result:
598 value = result.group(0)
599 else:
600 value = self.genVkStructureType(typeName)
601 # Store the required type value
602 self.structTypes[typeName] = self.StructType(name=name, value=value)
603 # Store pointer/array/string info
604 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
605 membersInfo.append(self.CommandParam(type=type,
606 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600607 isconst=True if 'const' in cdecl else False,
608 isoptional=self.paramIsOptional(member),
609 iscount=True if name in lens else False,
610 len=self.getLen(member),
611 extstructs=extstructs,
612 cdecl=cdecl,
613 islocal=False,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600614 iscreate=False))
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600615 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
616 #
617 # Insert a lock_guard line
618 def lock_guard(self, indent):
619 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
620 #
621 # Determine if a struct has an object as a member or an embedded member
622 def struct_contains_object(self, struct_item):
623 struct_member_dict = dict(self.structMembers)
624 struct_members = struct_member_dict[struct_item]
625
626 for member in struct_members:
627 if self.isHandleTypeObject(member.type):
628 return True
Mike Schuchardtcf2eda02018-08-11 20:34:07 -0700629 # recurse for member structs, guard against infinite recursion
630 elif member.type in struct_member_dict and member.type != struct_item:
631 if self.struct_contains_object(member.type):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600632 return True
633 return False
634 #
635 # Return list of struct members which contain, or whose sub-structures contain an obj in a given list of parameters or members
636 def getParmeterStructsWithObjects(self, item_list):
637 struct_list = set()
638 for item in item_list:
639 paramtype = item.find('type')
640 typecategory = self.getTypeCategory(paramtype.text)
641 if typecategory == 'struct':
642 if self.struct_contains_object(paramtype.text) == True:
643 struct_list.add(item)
644 return struct_list
645 #
646 # Return list of objects from a given list of parameters or members
647 def getObjectsInParameterList(self, item_list, create_func):
648 object_list = set()
649 if create_func == True:
650 member_list = item_list[0:-1]
651 else:
652 member_list = item_list
653 for item in member_list:
654 if self.isHandleTypeObject(paramtype.text):
655 object_list.add(item)
656 return object_list
657 #
658 # Construct list of extension structs containing handles, or extension structs that share a <validextensionstructs>
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600659 # tag WITH an extension struct containing handles.
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600660 def GenerateCommandWrapExtensionList(self):
661 for struct in self.structMembers:
662 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
663 found = False;
664 for item in struct.members[1].extstructs.split(','):
665 if item != '' and self.struct_contains_object(item) == True:
666 found = True
667 if found == True:
668 for item in struct.members[1].extstructs.split(','):
669 if item != '' and item not in self.extension_structs:
670 self.extension_structs.append(item)
671 #
672 # Returns True if a struct may have a pNext chain containing an object
673 def StructWithExtensions(self, struct_type):
674 if struct_type in self.struct_member_dict:
675 param_info = self.struct_member_dict[struct_type]
676 if (len(param_info) > 1) and param_info[1].extstructs is not None:
677 for item in param_info[1].extstructs.split(','):
678 if item in self.extension_structs:
679 return True
680 return False
681 #
682 # Generate VulkanObjectType from object type
683 def GetVulkanObjType(self, type):
684 return 'kVulkanObjectType%s' % type[2:]
685 #
686 # Return correct dispatch table type -- instance or device
687 def GetDispType(self, type):
688 return 'instance' if type in ['VkInstance', 'VkPhysicalDevice'] else 'device'
689 #
690 # Generate source for creating a Vulkan object
John Zulaufbb6e5e42018-08-06 16:00:07 -0600691 def generate_create_object_code(self, indent, proto, params, cmd_info, allocator):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600692 create_obj_code = ''
693 handle_type = params[-1].find('type')
694 if self.isHandleTypeObject(handle_type.text):
695 # Check for special case where multiple handles are returned
696 object_array = False
697 if cmd_info[-1].len is not None:
698 object_array = True;
699 handle_name = params[-1].find('name')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600700 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
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600705
706 dispobj = params[0].find('type').text
707 calltype = 'Device'
708 if dispobj == 'VkInstance' or dispobj == 'VkPhysicalDevice':
709 calltype = 'Instance'
710
711 create_obj_code += '%s%sCreateObject(%s, %s, %s, %s);\n' % (indent, calltype, params[0].find('name').text, object_dest, self.GetVulkanObjType(cmd_info[-1].type), allocator)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600712 if object_array == True:
713 indent = self.decIndent(indent)
714 create_obj_code += '%s}\n' % indent
715 indent = self.decIndent(indent)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600716 return create_obj_code
717 #
718 # Generate source for destroying a non-dispatchable object
719 def generate_destroy_object_code(self, indent, proto, cmd_info):
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600720 validate_code = ''
721 record_code = ''
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600722 object_array = False
723 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
724 # Check for special case where multiple handles are returned
725 if cmd_info[-1].len is not None:
726 object_array = True;
727 param = -1
728 else:
729 param = -2
730 compatalloc_vuid_string = '%s-compatalloc' % cmd_info[param].name
731 nullalloc_vuid_string = '%s-nullalloc' % cmd_info[param].name
Dave Houlton57ae22f2018-05-18 16:20:52 -0600732 compatalloc_vuid = self.manual_vuids.get(compatalloc_vuid_string, "kVUIDUndefined")
733 nullalloc_vuid = self.manual_vuids.get(nullalloc_vuid_string, "kVUIDUndefined")
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600734 if self.isHandleTypeObject(cmd_info[param].type) == True:
735 if object_array == True:
736 # This API is freeing an array of handles -- add loop control
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600737 validate_code += 'HEY, NEED TO DESTROY AN ARRAY\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600738 else:
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600739 dispobj = cmd_info[0].type
740 calltype = 'Device'
741 if dispobj == 'VkInstance' or dispobj == 'VkPhysicalDevice':
742 calltype = 'Instance'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600743 # Call Destroy a single time
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600744 validate_code += '%s skip |= %sValidateDestroyObject(%s, %s, %s, pAllocator, %s, %s);\n' % (indent, calltype, cmd_info[0].name, cmd_info[param].name, self.GetVulkanObjType(cmd_info[param].type), compatalloc_vuid, nullalloc_vuid)
745 record_code += '%s %sRecordDestroyObject(%s, %s, %s);\n' % (indent, calltype, cmd_info[0].name, cmd_info[param].name, self.GetVulkanObjType(cmd_info[param].type))
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600746 return object_array, validate_code, record_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600747 #
748 # Output validation for a single object (obj_count is NULL) or a counted list of objects
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600749 def outputObjects(self, obj_type, obj_name, obj_count, prefix, index, indent, disp_name, parent_name, null_allowed, top_level):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600750 pre_call_code = ''
Dave Houlton57ae22f2018-05-18 16:20:52 -0600751 param_suffix = '%s-parameter' % (obj_name)
752 parent_suffix = '%s-parent' % (obj_name)
753 param_vuid = self.GetVuid(parent_name, param_suffix)
754 parent_vuid = self.GetVuid(parent_name, parent_suffix)
755
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600756 # If no parent VUID for this member, look for a commonparent VUID
Dave Houlton57ae22f2018-05-18 16:20:52 -0600757 if parent_vuid == 'kVUIDUndefined':
758 parent_vuid = self.GetVuid(parent_name, 'commonparent')
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600759 calltype = 'Device'
760 if disp_name == 'instance' or disp_name == 'physicalDevice':
761 calltype = 'Instance'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600762 if obj_count is not None:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600763 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, obj_count, index)
764 indent = self.incIndent(indent)
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600765 pre_call_code += '%s skip |= %sValidateObject(%s, %s%s[%s], %s, %s, %s, %s);\n' % (indent, calltype, disp_name, prefix, obj_name, index, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600766 indent = self.decIndent(indent)
767 pre_call_code += '%s }\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600768 else:
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600769 pre_call_code += '%s skip |= %sValidateObject(%s, %s%s, %s, %s, %s, %s);\n' % (indent, calltype, disp_name, prefix, obj_name, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600770 return pre_call_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600771 #
772 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600773 def validate_objects(self, members, indent, prefix, array_index, disp_name, parent_name, first_level_param):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600774 pre_code = ''
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600775 index = 'index%s' % str(array_index)
776 array_index += 1
777 # Process any objects in this structure and recurse for any sub-structs in this struct
778 for member in members:
779 # Handle objects
780 if member.iscreate and first_level_param and member == members[-1]:
781 continue
782 if self.isHandleTypeObject(member.type) == True:
783 count_name = member.len
784 if (count_name is not None):
785 count_name = '%s%s' % (prefix, member.len)
786 null_allowed = member.isoptional
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600787 tmp_pre = self.outputObjects(member.type, member.name, count_name, prefix, index, indent, disp_name, parent_name, str(null_allowed).lower(), first_level_param)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600788 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600789 # Handle Structs that contain objects at some level
790 elif member.type in self.struct_member_dict:
791 # Structs at first level will have an object
792 if self.struct_contains_object(member.type) == True:
793 struct_info = self.struct_member_dict[member.type]
Jeff Bolz38b3ce72018-09-19 12:53:38 -0500794 # TODO (jbolz): Can this use paramIsPointer?
Jeff Bolzba74d972018-09-12 15:54:57 -0500795 ispointer = '*' in member.cdecl;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600796 # Struct Array
797 if member.len is not None:
798 # Update struct prefix
799 new_prefix = '%s%s' % (prefix, member.name)
800 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
801 indent = self.incIndent(indent)
802 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
803 indent = self.incIndent(indent)
804 local_prefix = '%s[%s].' % (new_prefix, index)
805 # Process sub-structs in this struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600806 tmp_pre = self.validate_objects(struct_info, indent, local_prefix, array_index, disp_name, member.type, False)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600807 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600808 indent = self.decIndent(indent)
809 pre_code += '%s }\n' % indent
810 indent = self.decIndent(indent)
811 pre_code += '%s }\n' % indent
812 # Single Struct
Jeff Bolzba74d972018-09-12 15:54:57 -0500813 elif ispointer:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600814 # Update struct prefix
815 new_prefix = '%s%s->' % (prefix, member.name)
816 # Declare safe_VarType for struct
817 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
818 indent = self.incIndent(indent)
819 # Process sub-structs in this struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600820 tmp_pre = self.validate_objects(struct_info, indent, new_prefix, array_index, disp_name, member.type, False)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600821 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600822 indent = self.decIndent(indent)
823 pre_code += '%s }\n' % indent
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600824 return pre_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600825 #
826 # For a particular API, generate the object handling code
827 def generate_wrapping_code(self, cmd):
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600828 indent = ''
829 pre_call_validate = ''
830 pre_call_record = ''
831 post_call_record = ''
832
833 destroy_array = False
834 validate_destroy_code = ''
835 record_destroy_code = ''
836
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600837 proto = cmd.find('proto/name')
838 params = cmd.findall('param')
839 if proto.text is not None:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600840 cmddata = self.cmd_info_dict[proto.text]
841 cmd_info = cmddata.members
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600842 disp_name = cmd_info[0].name
John Zulaufbb6e5e42018-08-06 16:00:07 -0600843 # Handle object create operations if last parameter is created by this call
844 if cmddata.iscreate:
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600845 post_call_record += self.generate_create_object_code(indent, proto, params, cmd_info, cmddata.allocator)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600846 # Handle object destroy operations
John Zulaufbb6e5e42018-08-06 16:00:07 -0600847 if cmddata.isdestroy:
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600848 (destroy_array, validate_destroy_code, record_destroy_code) = self.generate_destroy_object_code(indent, proto, cmd_info)
Mark Lobodzinski2a51e802018-09-12 16:07:01 -0600849
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600850 pre_call_record += record_destroy_code
851 pre_call_validate += self.validate_objects(cmd_info, indent, '', 0, disp_name, proto.text, True)
852 pre_call_validate += validate_destroy_code
853
854 return pre_call_validate, pre_call_record, post_call_record
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600855 #
856 # Capture command parameter info needed to create, destroy, and validate objects
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700857 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600858
859 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700860 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600861 members = cmdinfo.elem.findall('.//param')
862 # Iterate over members once to get length parameters for arrays
863 lens = set()
864 for member in members:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600865 length = self.getLen(member)
866 if length:
867 lens.add(length)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600868 struct_member_dict = dict(self.structMembers)
John Zulaufbb6e5e42018-08-06 16:00:07 -0600869
870 # Set command invariant information needed at a per member level in validate...
871 is_create_command = any(filter(lambda pat: pat in cmdname, ('Create', 'Allocate', 'Enumerate', 'RegisterDeviceEvent', 'RegisterDisplayEvent')))
872 last_member_is_pointer = len(members) and self.paramIsPointer(members[-1])
873 iscreate = is_create_command or ('vkGet' in cmdname and last_member_is_pointer)
874 isdestroy = any([destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']])
875
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600876 # Generate member info
877 membersInfo = []
878 constains_extension_structs = False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600879 allocator = 'nullptr'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600880 for member in members:
881 # Get type and name of member
882 info = self.getTypeNameTuple(member)
883 type = info[0]
884 name = info[1]
885 cdecl = self.makeCParamDecl(member, 0)
886 # Check for parameter name in lens set
887 iscount = True if name in lens else False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600888 length = self.getLen(member)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600889 isconst = True if 'const' in cdecl else False
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600890 # Mark param as local if it is an array of objects
891 islocal = False;
892 if self.isHandleTypeObject(type) == True:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600893 if (length is not None) and (isconst == True):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600894 islocal = True
895 # Or if it's a struct that contains an object
896 elif type in struct_member_dict:
897 if self.struct_contains_object(type) == True:
898 islocal = True
John Zulaufbb6e5e42018-08-06 16:00:07 -0600899 if type == 'VkAllocationCallbacks':
900 allocator = name
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600901 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
902 membersInfo.append(self.CommandParam(type=type,
903 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600904 isconst=isconst,
905 isoptional=self.paramIsOptional(member),
906 iscount=iscount,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600907 len=length,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600908 extstructs=extstructs,
909 cdecl=cdecl,
910 islocal=islocal,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600911 iscreate=iscreate))
912
913 self.cmd_list.append(cmdname)
914 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 -0600915 #
916 # Create code Create, Destroy, and validate Vulkan objects
917 def WrapCommands(self):
John Zulaufbb6e5e42018-08-06 16:00:07 -0600918 for cmdname in self.cmd_list:
919 cmddata = self.cmd_info_dict[cmdname]
920 cmdinfo = cmddata.cmdinfo
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600921 if cmdname in self.interface_functions:
922 continue
923 if cmdname in self.no_autogen_list:
924 decls = self.makeCDecls(cmdinfo.elem)
925 self.appendSection('command', '')
926 self.appendSection('command', '// Declare only')
927 self.appendSection('command', decls[0])
928 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
929 continue
930 # Generate object handling code
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600931 (pre_call_validate, pre_call_record, post_call_record) = self.generate_wrapping_code(cmdinfo.elem)
932
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600933 # If API doesn't contain any object handles, don't fool with it
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600934 if not pre_call_validate and not pre_call_record and not post_call_record:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600935 continue
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600936
John Zulaufbb6e5e42018-08-06 16:00:07 -0600937 feature_extra_protect = cmddata.extra_protect
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100938 if (feature_extra_protect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600939 self.appendSection('command', '')
940 self.appendSection('command', '#ifdef '+ feature_extra_protect)
941 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600942
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600943 # Add intercept to procmap
944 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600945
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600946 decls = self.makeCDecls(cmdinfo.elem)
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600947
948 # Gather the parameter items
949 params = cmdinfo.elem.findall('param/name')
950 # Pull out the text for each of the parameters, separate them by commas in a list
951 paramstext = ', '.join([str(param.text) for param in params])
952 # Generate the API call template
953 fcn_call = cmdinfo.elem.attrib.get('name').replace('vk', 'TOKEN', 1) + '(' + paramstext + ');'
954
955 func_decl_template = decls[0][:-1].split('VKAPI_CALL ')
956 func_decl_template = func_decl_template[1] + ' {'
957
958 # Output PreCallValidateAPI function if necessary
959 if pre_call_validate:
960 pre_cv_func_decl = 'static bool PreCallValidate' + func_decl_template
961 self.appendSection('command', '')
962 self.appendSection('command', pre_cv_func_decl)
963 self.appendSection('command', ' bool skip = false;')
964 self.appendSection('command', pre_call_validate)
965 self.appendSection('command', ' return skip;')
966 self.appendSection('command', '}')
967
968 # Output PreCallRecordAPI function if necessary
969 if pre_call_record:
970 pre_cr_func_decl = 'static void PreCallRecord' + func_decl_template
971 self.appendSection('command', '')
972 self.appendSection('command', pre_cr_func_decl)
973 self.appendSection('command', pre_call_record)
974 self.appendSection('command', '}')
975
976 # Output PosCallRecordAPI function if necessary
977 if post_call_record:
978 post_cr_func_decl = 'static void PostCallRecord' + func_decl_template
979 self.appendSection('command', '')
980 self.appendSection('command', post_cr_func_decl)
981 self.appendSection('command', post_call_record)
982 self.appendSection('command', '}')
983
984 # Output API function:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600985 self.appendSection('command', '')
986 self.appendSection('command', decls[0][:-1])
987 self.appendSection('command', '{')
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600988
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600989 # Handle return values, if any
990 resulttype = cmdinfo.elem.find('proto/type')
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100991 if (resulttype is not None and resulttype.text == 'void'):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600992 resulttype = None
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100993 if (resulttype is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600994 assignresult = resulttype.text + ' result = '
995 else:
996 assignresult = ''
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600997
998 # Output all pre-API-call source
999 if pre_call_validate:
1000 self.appendSection('command', ' bool skip = false;')
1001 if pre_call_validate or pre_call_record:
1002 self.appendSection('command', ' {')
1003 self.appendSection('command', ' std::lock_guard<std::mutex> lock(global_lock);')
1004 # If necessary, add call to PreCallValidateApi(...);
1005 if pre_call_validate:
1006 pcv_call = fcn_call.replace('TOKEN', ' skip |= PreCallValidate', 1)
1007 self.appendSection('command', pcv_call)
1008 if assignresult != '':
1009 if resulttype.text == 'VkResult':
1010 self.appendSection('command', ' if (skip) return VK_ERROR_VALIDATION_FAILED_EXT;')
1011 elif resulttype.text == 'VkBool32':
1012 self.appendSection('command', ' if (skip) return VK_FALSE;')
1013 else:
1014 raise Exception('Unknown result type ' + resulttype.text)
1015 else:
1016 self.appendSection('command', ' if (skip) return;')
1017 # If necessary, add call to PreCallRecordApi(...);
1018 if pre_call_record:
1019 pre_cr_call = fcn_call.replace('TOKEN', ' PreCallRecord', 1)
1020 self.appendSection('command', pre_cr_call)
1021
1022 if pre_call_validate or pre_call_record:
1023 self.appendSection('command', ' }')
1024
1025 # Build down-chain call strings and output source
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001026 # Use correct dispatch table
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001027 disp_name = cmdinfo.elem.find('param/name').text
Mark Lobodzinski17de5fd2018-06-22 15:09:53 -06001028 disp_type = cmdinfo.elem.find('param/type').text
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -06001029 map_type = ''
Mark Lobodzinski17de5fd2018-06-22 15:09:53 -06001030 if disp_type in ["VkInstance", "VkPhysicalDevice"] or cmdname == 'vkCreateInstance':
1031 object_type = 'instance'
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -06001032 map_type = 'instance_'
Mark Lobodzinski17de5fd2018-06-22 15:09:53 -06001033 else:
1034 object_type = 'device'
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -06001035 dispatch_table = 'GetLayerDataPtr(get_dispatch_key(%s), %slayer_data_map)->%s_dispatch_table.' % (disp_name, map_type, object_type)
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -06001036 down_chain_call = fcn_call.replace('TOKEN', dispatch_table, 1)
1037 self.appendSection('command', ' ' + assignresult + down_chain_call)
1038
1039 # If necessary, add call to PostCallRecordApi(...);
1040 if post_call_record:
1041 if assignresult:
1042 if resulttype.text == 'VkResult':
1043 self.appendSection('command', ' if (VK_SUCCESS == result) {')
1044 elif resulttype.text == 'VkBool32':
1045 self.appendSection('command', ' if (VK_TRUE == result) {')
1046 self.appendSection('command', ' std::lock_guard<std::mutex> lock(global_lock);')
1047 post_cr_call = fcn_call.replace('TOKEN', ' PostCallRecord', 1)
1048 self.appendSection('command', post_cr_call)
1049 self.appendSection('command', ' }')
1050
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001051 # Handle the return result variable, if any
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001052 if (resulttype is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001053 self.appendSection('command', ' return result;')
1054 self.appendSection('command', '}')
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +01001055 if (feature_extra_protect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001056 self.appendSection('command', '#endif // '+ feature_extra_protect)
1057 self.intercepts += [ '#endif' ]