blob: a435d0e4bafd53dfa61f0e84287b5ac20008e243 [file] [log] [blame]
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001#!/usr/bin/python3 -i
2#
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -07003# Copyright (c) 2015-2019 The Khronos Group Inc.
4# Copyright (c) 2015-2019 Valve Corporation
5# Copyright (c) 2015-2019 LunarG, Inc.
6# Copyright (c) 2015-2019 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,
Mike Schuchardt21638df2019-03-16 10:52:02 -070067 conventions = None,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060068 filename = None,
69 directory = '.',
70 apiname = None,
71 profile = None,
72 versions = '.*',
73 emitversions = '.*',
74 defaultExtensions = None,
75 addExtensions = None,
76 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060077 emitExtensions = None,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060078 sortProcedure = regSortFeatures,
79 prefixText = "",
80 genFuncPointers = True,
81 protectFile = True,
82 protectFeature = True,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060083 apicall = '',
84 apientry = '',
85 apientryp = '',
86 indentFuncProto = True,
87 indentFuncPointer = False,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060088 alignFuncParam = 0,
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -060089 expandEnumerants = True,
90 valid_usage_path = ''):
Mike Schuchardt21638df2019-03-16 10:52:02 -070091 GeneratorOptions.__init__(self, conventions, filename, directory, apiname, profile,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060092 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060093 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinskid1461482017-07-18 13:56:09 -060094 self.prefixText = prefixText
95 self.genFuncPointers = genFuncPointers
96 self.protectFile = protectFile
97 self.protectFeature = protectFeature
Mark Lobodzinskid1461482017-07-18 13:56:09 -060098 self.apicall = apicall
99 self.apientry = apientry
100 self.apientryp = apientryp
101 self.indentFuncProto = indentFuncProto
102 self.indentFuncPointer = indentFuncPointer
103 self.alignFuncParam = alignFuncParam
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600104 self.expandEnumerants = expandEnumerants
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600105 self.valid_usage_path = valid_usage_path
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600106
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600107
108# ObjectTrackerOutputGenerator - subclass of OutputGenerator.
109# Generates object_tracker layer object validation code
110#
111# ---- methods ----
112# ObjectTrackerOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
113# ---- methods overriding base class ----
114# beginFile(genOpts)
115# endFile()
116# beginFeature(interface, emit)
117# endFeature()
118# genCmd(cmdinfo)
119# genStruct()
120# genType()
121class ObjectTrackerOutputGenerator(OutputGenerator):
122 """Generate ObjectTracker code based on XML element attributes"""
123 # This is an ordered list of sections in the header file.
124 ALL_SECTIONS = ['command']
125 def __init__(self,
126 errFile = sys.stderr,
127 warnFile = sys.stderr,
128 diagFile = sys.stdout):
129 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
130 self.INDENT_SPACES = 4
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600131 self.prototypes = []
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600132 self.instance_extensions = []
133 self.device_extensions = []
134 # Commands which are not autogenerated but still intercepted
135 self.no_autogen_list = [
136 'vkDestroyInstance',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600137 'vkCreateInstance',
138 'vkEnumeratePhysicalDevices',
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600139 'vkGetPhysicalDeviceQueueFamilyProperties',
140 'vkGetPhysicalDeviceQueueFamilyProperties2',
141 'vkGetPhysicalDeviceQueueFamilyProperties2KHR',
142 'vkGetDeviceQueue',
143 'vkGetDeviceQueue2',
144 'vkCreateDescriptorSetLayout',
145 'vkDestroyDescriptorPool',
146 'vkDestroyCommandPool',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600147 'vkAllocateCommandBuffers',
148 'vkAllocateDescriptorSets',
149 'vkFreeDescriptorSets',
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600150 'vkFreeCommandBuffers',
151 'vkUpdateDescriptorSets',
152 'vkBeginCommandBuffer',
Mark Lobodzinski5a1c8d22018-07-02 10:28:12 -0600153 'vkGetDescriptorSetLayoutSupport',
154 'vkGetDescriptorSetLayoutSupportKHR',
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600155 'vkDestroySwapchainKHR',
156 'vkGetSwapchainImagesKHR',
157 'vkCmdPushDescriptorSetKHR',
158 'vkDestroyDevice',
159 'vkResetDescriptorPool',
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600160 'vkGetPhysicalDeviceDisplayPropertiesKHR',
Piers Daniell16c253f2018-05-30 14:34:05 -0600161 'vkGetPhysicalDeviceDisplayProperties2KHR',
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600162 'vkGetDisplayModePropertiesKHR',
Piers Daniell16c253f2018-05-30 14:34:05 -0600163 'vkGetDisplayModeProperties2KHR',
Shannon McPhersonf7d9cf62019-06-26 09:23:57 -0600164 'vkAcquirePerformanceConfigurationINTEL',
165 'vkReleasePerformanceConfigurationINTEL',
166 'vkQueueSetPerformanceConfigurationINTEL',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600167 ]
168 # These VUIDS are not implicit, but are best handled in this layer. Codegen for vkDestroy calls will generate a key
169 # which is translated here into a good VU. Saves ~40 checks.
170 self.manual_vuids = dict()
171 self.manual_vuids = {
Dave Houlton57ae22f2018-05-18 16:20:52 -0600172 "fence-compatalloc": "\"VUID-vkDestroyFence-fence-01121\"",
173 "fence-nullalloc": "\"VUID-vkDestroyFence-fence-01122\"",
174 "event-compatalloc": "\"VUID-vkDestroyEvent-event-01146\"",
175 "event-nullalloc": "\"VUID-vkDestroyEvent-event-01147\"",
176 "buffer-compatalloc": "\"VUID-vkDestroyBuffer-buffer-00923\"",
177 "buffer-nullalloc": "\"VUID-vkDestroyBuffer-buffer-00924\"",
178 "image-compatalloc": "\"VUID-vkDestroyImage-image-01001\"",
179 "image-nullalloc": "\"VUID-vkDestroyImage-image-01002\"",
180 "shaderModule-compatalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01092\"",
181 "shaderModule-nullalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01093\"",
182 "pipeline-compatalloc": "\"VUID-vkDestroyPipeline-pipeline-00766\"",
183 "pipeline-nullalloc": "\"VUID-vkDestroyPipeline-pipeline-00767\"",
184 "sampler-compatalloc": "\"VUID-vkDestroySampler-sampler-01083\"",
185 "sampler-nullalloc": "\"VUID-vkDestroySampler-sampler-01084\"",
186 "renderPass-compatalloc": "\"VUID-vkDestroyRenderPass-renderPass-00874\"",
187 "renderPass-nullalloc": "\"VUID-vkDestroyRenderPass-renderPass-00875\"",
188 "descriptorUpdateTemplate-compatalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00356\"",
189 "descriptorUpdateTemplate-nullalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00357\"",
190 "imageView-compatalloc": "\"VUID-vkDestroyImageView-imageView-01027\"",
191 "imageView-nullalloc": "\"VUID-vkDestroyImageView-imageView-01028\"",
192 "pipelineCache-compatalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00771\"",
193 "pipelineCache-nullalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00772\"",
194 "pipelineLayout-compatalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00299\"",
195 "pipelineLayout-nullalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00300\"",
196 "descriptorSetLayout-compatalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00284\"",
197 "descriptorSetLayout-nullalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00285\"",
198 "semaphore-compatalloc": "\"VUID-vkDestroySemaphore-semaphore-01138\"",
199 "semaphore-nullalloc": "\"VUID-vkDestroySemaphore-semaphore-01139\"",
200 "queryPool-compatalloc": "\"VUID-vkDestroyQueryPool-queryPool-00794\"",
201 "queryPool-nullalloc": "\"VUID-vkDestroyQueryPool-queryPool-00795\"",
202 "bufferView-compatalloc": "\"VUID-vkDestroyBufferView-bufferView-00937\"",
203 "bufferView-nullalloc": "\"VUID-vkDestroyBufferView-bufferView-00938\"",
204 "surface-compatalloc": "\"VUID-vkDestroySurfaceKHR-surface-01267\"",
205 "surface-nullalloc": "\"VUID-vkDestroySurfaceKHR-surface-01268\"",
206 "framebuffer-compatalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00893\"",
207 "framebuffer-nullalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00894\"",
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600208 }
209
210 # Commands shadowed by interface functions and are not implemented
211 self.interface_functions = [
212 ]
213 self.headerVersion = None
214 # Internal state - accumulators for different inner block text
215 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
John Zulaufbb6e5e42018-08-06 16:00:07 -0600216 self.cmd_list = [] # list of commands processed to maintain ordering
217 self.cmd_info_dict = {} # Per entry-point data for code generation and validation
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600218 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
219 self.extension_structs = [] # List of all structs or sister-structs containing handles
220 # A sister-struct may contain no handles but shares <validextensionstructs> with one that does
221 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
222 self.struct_member_dict = dict()
223 # Named tuples to store struct and command data
224 self.StructType = namedtuple('StructType', ['name', 'value'])
John Zulaufbb6e5e42018-08-06 16:00:07 -0600225 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo', 'members', 'extra_protect', 'alias', 'iscreate', 'isdestroy', 'allocator'])
226 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'isconst', 'isoptional', 'iscount', 'iscreate', 'len', 'extstructs', 'cdecl', 'islocal'])
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600227 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
228 self.object_types = [] # List of all handle types
229 self.valid_vuids = set() # Set of all valid VUIDs
Dave Houlton57ae22f2018-05-18 16:20:52 -0600230 self.vuid_dict = dict() # VUID dictionary (from JSON)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600231 #
232 # Check if the parameter passed in is optional
233 def paramIsOptional(self, param):
234 # See if the handle is optional
235 isoptional = False
236 # Simple, if it's optional, return true
237 optString = param.attrib.get('optional')
238 if optString:
239 if optString == 'true':
240 isoptional = True
241 elif ',' in optString:
242 opts = []
243 for opt in optString.split(','):
244 val = opt.strip()
245 if val == 'true':
246 opts.append(True)
247 elif val == 'false':
248 opts.append(False)
249 else:
250 print('Unrecognized len attribute value',val)
251 isoptional = opts
John Zulauf9f6788c2018-04-04 14:54:11 -0600252 if not isoptional:
253 # Matching logic in parameter validation and ValidityOutputGenerator.isHandleOptional
254 optString = param.attrib.get('noautovalidity')
255 if optString and optString == 'true':
256 isoptional = True;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600257 return isoptional
258 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600259 # Get VUID identifier from implicit VUID tag
Dave Houlton57ae22f2018-05-18 16:20:52 -0600260 def GetVuid(self, parent, suffix):
261 vuid_string = 'VUID-%s-%s' % (parent, suffix)
262 vuid = "kVUIDUndefined"
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600263 if '->' in vuid_string:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600264 return vuid
265 if vuid_string in self.valid_vuids:
266 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600267 else:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600268 alias = self.cmd_info_dict[parent].alias if parent in self.cmd_info_dict else None
269 if alias:
270 alias_string = 'VUID-%s-%s' % (alias, suffix)
Dave Houlton57ae22f2018-05-18 16:20:52 -0600271 if alias_string in self.valid_vuids:
Shannon McPhersonb1a8dd62019-06-06 11:42:47 -0600272 vuid = "\"%s\"" % alias_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600273 return vuid
274 #
275 # Increases indent by 4 spaces and tracks it globally
276 def incIndent(self, indent):
277 inc = ' ' * self.INDENT_SPACES
278 if indent:
279 return indent + inc
280 return inc
281 #
282 # Decreases indent by 4 spaces and tracks it globally
283 def decIndent(self, indent):
284 if indent and (len(indent) > self.INDENT_SPACES):
285 return indent[:-self.INDENT_SPACES]
286 return ''
287 #
288 # Override makeProtoName to drop the "vk" prefix
289 def makeProtoName(self, name, tail):
290 return self.genOpts.apientry + name[2:] + tail
291 #
292 # Check if the parameter passed in is a pointer to an array
293 def paramIsArray(self, param):
294 return param.attrib.get('len') is not None
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000295
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600296 #
297 # Generate the object tracker undestroyed object validation function
298 def GenReportFunc(self):
299 output_func = ''
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600300 output_func += 'bool ObjectLifetimes::ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {\n'
Mark Lobodzinski5183a032018-09-13 14:44:28 -0600301 output_func += ' bool skip = false;\n'
302 output_func += ' skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600303 for handle in self.object_types:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700304 if self.handle_types.IsNonDispatchable(handle):
Mark Lobodzinski5183a032018-09-13 14:44:28 -0600305 output_func += ' skip |= DeviceReportUndestroyedObjects(device, %s, error_code);\n' % (self.GetVulkanObjType(handle))
306 output_func += ' return skip;\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600307 output_func += '}\n'
308 return output_func
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000309
310 #
311 # Generate the object tracker undestroyed object destruction function
312 def GenDestroyFunc(self):
313 output_func = ''
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600314 output_func += 'void ObjectLifetimes::DestroyUndestroyedObjects(VkDevice device) {\n'
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000315 output_func += ' DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer);\n'
316 for handle in self.object_types:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700317 if self.handle_types.IsNonDispatchable(handle):
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000318 output_func += ' DeviceDestroyUndestroyedObjects(device, %s);\n' % (self.GetVulkanObjType(handle))
319 output_func += '}\n'
320 return output_func
321
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600322 #
Dave Houlton57ae22f2018-05-18 16:20:52 -0600323 # Walk the JSON-derived dict and find all "vuid" key values
324 def ExtractVUIDs(self, d):
325 if hasattr(d, 'items'):
326 for k, v in d.items():
327 if k == "vuid":
328 yield v
329 elif isinstance(v, dict):
330 for s in self.ExtractVUIDs(v):
331 yield s
332 elif isinstance (v, list):
333 for l in v:
334 for s in self.ExtractVUIDs(l):
335 yield s
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600336 #
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600337 # Separate content for validation source and header files
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600338 def otwrite(self, dest, formatstring):
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600339 if 'object_tracker.h' in self.genOpts.filename and (dest == 'hdr' or dest == 'both'):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600340 write(formatstring, file=self.outFile)
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600341 elif 'object_tracker.cpp' in self.genOpts.filename and (dest == 'cpp' or dest == 'both'):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600342 write(formatstring, file=self.outFile)
Dave Houlton57ae22f2018-05-18 16:20:52 -0600343
344 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600345 # Called at beginning of processing as file is opened
346 def beginFile(self, genOpts):
347 OutputGenerator.beginFile(self, genOpts)
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600348
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700349 # Initialize members that require the tree
350 self.handle_types = GetHandleTypes(self.registry.tree)
351 self.type_categories = GetTypeCategories(self.registry.tree)
352
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600353 header_file = (genOpts.filename == 'object_tracker.h')
354 source_file = (genOpts.filename == 'object_tracker.cpp')
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600355
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600356 if not header_file and not source_file:
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600357 print("Error: Output Filenames have changed, update generator source.\n")
358 sys.exit(1)
359
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600360 self.valid_usage_path = genOpts.valid_usage_path
361 vu_json_filename = os.path.join(self.valid_usage_path + os.sep, 'validusage.json')
362 if os.path.isfile(vu_json_filename):
363 json_file = open(vu_json_filename, 'r')
364 self.vuid_dict = json.load(json_file)
365 json_file.close()
366 if len(self.vuid_dict) == 0:
367 print("Error: Could not find, or error loading %s/validusage.json\n", vu_json_filename)
368 sys.exit(1)
369
Dave Houlton57ae22f2018-05-18 16:20:52 -0600370 # Build a set of all vuid text strings found in validusage.json
371 for json_vuid_string in self.ExtractVUIDs(self.vuid_dict):
372 self.valid_vuids.add(json_vuid_string)
373
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600374 # File Comment
375 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
376 file_comment += '// See object_tracker_generator.py for modifications\n'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600377 self.otwrite('both', file_comment)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600378 # Copyright Statement
379 copyright = ''
380 copyright += '\n'
381 copyright += '/***************************************************************************\n'
382 copyright += ' *\n'
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700383 copyright += ' * Copyright (c) 2015-2019 The Khronos Group Inc.\n'
384 copyright += ' * Copyright (c) 2015-2019 Valve Corporation\n'
385 copyright += ' * Copyright (c) 2015-2019 LunarG, Inc.\n'
386 copyright += ' * Copyright (c) 2015-2019 Google Inc.\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600387 copyright += ' *\n'
388 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
389 copyright += ' * you may not use this file except in compliance with the License.\n'
390 copyright += ' * You may obtain a copy of the License at\n'
391 copyright += ' *\n'
392 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
393 copyright += ' *\n'
394 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
395 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
396 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
397 copyright += ' * See the License for the specific language governing permissions and\n'
398 copyright += ' * limitations under the License.\n'
399 copyright += ' *\n'
400 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600401 copyright += ' * Author: Dave Houlton <daveh@lunarg.com>\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600402 copyright += ' *\n'
403 copyright += ' ****************************************************************************/\n'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600404 self.otwrite('both', copyright)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600405 self.newline()
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600406 self.otwrite('cpp', '#include "chassis.h"')
407 self.otwrite('cpp', '#include "object_lifetime_validation.h"')
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600408
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600409 #
410 # Now that the data is all collected and complete, generate and output the object validation routines
411 def endFile(self):
412 self.struct_member_dict = dict(self.structMembers)
413 # Generate the list of APIs that might need to handle wrapped extension structs
414 # self.GenerateCommandWrapExtensionList()
415 self.WrapCommands()
416 # Build undestroyed objects reporting function
417 report_func = self.GenReportFunc()
418 self.newline()
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000419 # Build undestroyed objects destruction function
420 destroy_func = self.GenDestroyFunc()
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600421 self.otwrite('cpp', '\n')
422 self.otwrite('cpp', '// ObjectTracker undestroyed objects validation function')
423 self.otwrite('cpp', '%s' % report_func)
424 self.otwrite('cpp', '%s' % destroy_func)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600425 # Actually write the interface to the output file.
426 if (self.emit):
427 self.newline()
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600428 if self.featureExtraProtect is not None:
429 prot = '#ifdef %s' % self.featureExtraProtect
430 self.otwrite('both', '%s' % prot)
431 # Write the object_tracker code to the file
432 if self.sections['command']:
433 source = ('\n'.join(self.sections['command']))
434 self.otwrite('both', '%s' % source)
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100435 if (self.featureExtraProtect is not None):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600436 prot = '\n#endif // %s', self.featureExtraProtect
437 self.otwrite('both', prot)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600438 else:
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600439 self.otwrite('both', '\n')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600440
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600441
442 self.otwrite('hdr', 'void PostCallRecordDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator);')
443 self.otwrite('hdr', 'void PreCallRecordResetDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags);')
444 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties *pQueueFamilyProperties);')
445 self.otwrite('hdr', 'void PreCallRecordFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers);')
446 self.otwrite('hdr', 'void PreCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount, const VkDescriptorSet *pDescriptorSets);')
447 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR *pQueueFamilyProperties);')
448 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR *pQueueFamilyProperties);')
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700449 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceDisplayPropertiesKHR(VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount, VkDisplayPropertiesKHR *pProperties, VkResult result);')
450 self.otwrite('hdr', 'void PostCallRecordGetDisplayModePropertiesKHR(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t *pPropertyCount, VkDisplayModePropertiesKHR *pProperties, VkResult result);')
451 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceDisplayProperties2KHR(VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount, VkDisplayProperties2KHR *pProperties, VkResult result);')
452 self.otwrite('hdr', 'void PostCallRecordGetDisplayModeProperties2KHR(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t *pPropertyCount, VkDisplayModeProperties2KHR *pProperties, VkResult result);')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600453 OutputGenerator.endFile(self)
454 #
455 # Processing point at beginning of each extension definition
456 def beginFeature(self, interface, emit):
457 # Start processing in superclass
458 OutputGenerator.beginFeature(self, interface, emit)
459 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600460 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600461
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600462 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600463 white_list_entry = []
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100464 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600465 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
466 white_list_entry += [ '"%s"' % self.featureName ]
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100467 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600468 white_list_entry += [ '#endif' ]
469 featureType = interface.get('type')
470 if featureType == 'instance':
471 self.instance_extensions += white_list_entry
472 elif featureType == 'device':
473 self.device_extensions += white_list_entry
474 #
475 # Processing point at end of each extension definition
476 def endFeature(self):
477 # Finish processing in superclass
478 OutputGenerator.endFeature(self)
479 #
480 # Process enums, structs, etc.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700481 def genType(self, typeinfo, name, alias):
482 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600483 typeElem = typeinfo.elem
484 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
485 # Otherwise, emit the tag text.
486 category = typeElem.get('category')
487 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700488 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600489 if category == 'handle':
490 self.object_types.append(name)
491 #
492 # Append a definition to the specified section
493 def appendSection(self, section, text):
494 # self.sections[section].append('SECTION: ' + section + '\n')
495 self.sections[section].append(text)
496 #
497 # Check if the parameter passed in is a pointer
498 def paramIsPointer(self, param):
499 ispointer = False
500 for elem in param:
Raul Tambre7b300182019-05-04 11:25:14 +0300501 if elem.tag == 'type' and elem.tail is not None and '*' in elem.tail:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600502 ispointer = True
503 return ispointer
504 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600505 # Retrieve the type and name for a parameter
506 def getTypeNameTuple(self, param):
507 type = ''
508 name = ''
509 for elem in param:
510 if elem.tag == 'type':
511 type = noneStr(elem.text)
512 elif elem.tag == 'name':
513 name = noneStr(elem.text)
514 return (type, name)
515 #
516 # Retrieve the value of the len tag
517 def getLen(self, param):
518 result = None
519 len = param.attrib.get('len')
520 if len and len != 'null-terminated':
521 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
522 # have a null terminated array of strings. We strip the null-terminated from the
523 # 'len' field and only return the parameter specifying the string count
524 if 'null-terminated' in len:
525 result = len.split(',')[0]
526 else:
527 result = len
528 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
529 result = str(result).replace('::', '->')
530 return result
531 #
532 # Generate a VkStructureType based on a structure typename
533 def genVkStructureType(self, typename):
534 # Add underscore between lowercase then uppercase
535 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
536 # Change to uppercase
537 value = value.upper()
538 # Add STRUCTURE_TYPE_
539 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
540 #
541 # Struct parameter check generation.
542 # This is a special case of the <type> tag where the contents are interpreted as a set of
543 # <member> tags instead of freeform C type declarations. The <member> tags are just like
544 # <param> tags - they are a declaration of a struct or union member. Only simple member
545 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700546 def genStruct(self, typeinfo, typeName, alias):
547 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600548 members = typeinfo.elem.findall('.//member')
549 # Iterate over members once to get length parameters for arrays
550 lens = set()
551 for member in members:
552 len = self.getLen(member)
553 if len:
554 lens.add(len)
555 # Generate member info
556 membersInfo = []
557 for member in members:
558 # Get the member's type and name
559 info = self.getTypeNameTuple(member)
560 type = info[0]
561 name = info[1]
562 cdecl = self.makeCParamDecl(member, 0)
563 # Process VkStructureType
564 if type == 'VkStructureType':
565 # Extract the required struct type value from the comments
566 # embedded in the original text defining the 'typeinfo' element
567 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
568 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
569 if result:
570 value = result.group(0)
571 else:
572 value = self.genVkStructureType(typeName)
573 # Store the required type value
574 self.structTypes[typeName] = self.StructType(name=name, value=value)
575 # Store pointer/array/string info
576 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
577 membersInfo.append(self.CommandParam(type=type,
578 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600579 isconst=True if 'const' in cdecl else False,
580 isoptional=self.paramIsOptional(member),
581 iscount=True if name in lens else False,
582 len=self.getLen(member),
583 extstructs=extstructs,
584 cdecl=cdecl,
585 islocal=False,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600586 iscreate=False))
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600587 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
588 #
589 # Insert a lock_guard line
590 def lock_guard(self, indent):
591 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
592 #
593 # Determine if a struct has an object as a member or an embedded member
594 def struct_contains_object(self, struct_item):
595 struct_member_dict = dict(self.structMembers)
596 struct_members = struct_member_dict[struct_item]
597
598 for member in struct_members:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700599 if member.type in self.handle_types:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600600 return True
Mike Schuchardtcf2eda02018-08-11 20:34:07 -0700601 # recurse for member structs, guard against infinite recursion
602 elif member.type in struct_member_dict and member.type != struct_item:
603 if self.struct_contains_object(member.type):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600604 return True
605 return False
606 #
607 # Return list of struct members which contain, or whose sub-structures contain an obj in a given list of parameters or members
608 def getParmeterStructsWithObjects(self, item_list):
609 struct_list = set()
610 for item in item_list:
611 paramtype = item.find('type')
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700612 typecategory = self.type_categories[paramtype.text]
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600613 if typecategory == 'struct':
614 if self.struct_contains_object(paramtype.text) == True:
615 struct_list.add(item)
616 return struct_list
617 #
618 # Return list of objects from a given list of parameters or members
619 def getObjectsInParameterList(self, item_list, create_func):
620 object_list = set()
621 if create_func == True:
622 member_list = item_list[0:-1]
623 else:
624 member_list = item_list
625 for item in member_list:
Mike Schuchardtf8690262019-07-11 10:08:33 -0700626 if paramtype.text in self.handle_types:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600627 object_list.add(item)
628 return object_list
629 #
630 # Construct list of extension structs containing handles, or extension structs that share a <validextensionstructs>
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600631 # tag WITH an extension struct containing handles.
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600632 def GenerateCommandWrapExtensionList(self):
633 for struct in self.structMembers:
634 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
635 found = False;
636 for item in struct.members[1].extstructs.split(','):
637 if item != '' and self.struct_contains_object(item) == True:
638 found = True
639 if found == True:
640 for item in struct.members[1].extstructs.split(','):
641 if item != '' and item not in self.extension_structs:
642 self.extension_structs.append(item)
643 #
644 # Returns True if a struct may have a pNext chain containing an object
645 def StructWithExtensions(self, struct_type):
646 if struct_type in self.struct_member_dict:
647 param_info = self.struct_member_dict[struct_type]
648 if (len(param_info) > 1) and param_info[1].extstructs is not None:
649 for item in param_info[1].extstructs.split(','):
650 if item in self.extension_structs:
651 return True
652 return False
653 #
654 # Generate VulkanObjectType from object type
655 def GetVulkanObjType(self, type):
656 return 'kVulkanObjectType%s' % type[2:]
657 #
658 # Return correct dispatch table type -- instance or device
659 def GetDispType(self, type):
660 return 'instance' if type in ['VkInstance', 'VkPhysicalDevice'] else 'device'
661 #
662 # Generate source for creating a Vulkan object
John Zulaufbb6e5e42018-08-06 16:00:07 -0600663 def generate_create_object_code(self, indent, proto, params, cmd_info, allocator):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600664 create_obj_code = ''
665 handle_type = params[-1].find('type')
Mark Lobodzinskidcf2bd22019-02-27 16:30:35 -0700666 is_create_pipelines = False
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600667
Mike Schuchardtf8690262019-07-11 10:08:33 -0700668 if handle_type.text in self.handle_types:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600669 # Check for special case where multiple handles are returned
670 object_array = False
671 if cmd_info[-1].len is not None:
672 object_array = True;
673 handle_name = params[-1].find('name')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600674 object_dest = '*%s' % handle_name.text
675 if object_array == True:
Mark Lobodzinskidcf2bd22019-02-27 16:30:35 -0700676 if 'CreateGraphicsPipelines' in proto.text or 'CreateComputePipelines' in proto.text or 'CreateRayTracingPipelines' in proto.text:
677 is_create_pipelines = True
678 create_obj_code += '%sif (VK_ERROR_VALIDATION_FAILED_EXT == result) return;\n' % indent
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600679 create_obj_code += '%sif (%s) {\n' % (indent, handle_name.text)
680 indent = self.incIndent(indent)
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600681 countispointer = ''
682 if 'uint32_t*' in cmd_info[-2].cdecl:
683 countispointer = '*'
684 create_obj_code += '%sfor (uint32_t index = 0; index < %s%s; index++) {\n' % (indent, countispointer, cmd_info[-1].len)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600685 indent = self.incIndent(indent)
686 object_dest = '%s[index]' % cmd_info[-1].name
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600687
688 dispobj = params[0].find('type').text
Mark Lobodzinskidcf2bd22019-02-27 16:30:35 -0700689 if is_create_pipelines:
Mark Lobodzinskifd2d0a42019-02-20 16:34:56 -0700690 create_obj_code += '%sif (!pPipelines[index]) continue;\n' % indent
Mark Lobodzinskiadd93232018-10-09 11:49:42 -0600691 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 -0600692 if object_array == True:
693 indent = self.decIndent(indent)
694 create_obj_code += '%s}\n' % indent
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600695 indent = self.decIndent(indent)
696 create_obj_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600697 indent = self.decIndent(indent)
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600698
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600699 return create_obj_code
700 #
701 # Generate source for destroying a non-dispatchable object
702 def generate_destroy_object_code(self, indent, proto, cmd_info):
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600703 validate_code = ''
704 record_code = ''
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600705 object_array = False
706 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
707 # Check for special case where multiple handles are returned
708 if cmd_info[-1].len is not None:
709 object_array = True;
710 param = -1
711 else:
712 param = -2
713 compatalloc_vuid_string = '%s-compatalloc' % cmd_info[param].name
714 nullalloc_vuid_string = '%s-nullalloc' % cmd_info[param].name
Dave Houlton57ae22f2018-05-18 16:20:52 -0600715 compatalloc_vuid = self.manual_vuids.get(compatalloc_vuid_string, "kVUIDUndefined")
716 nullalloc_vuid = self.manual_vuids.get(nullalloc_vuid_string, "kVUIDUndefined")
Mike Schuchardtf8690262019-07-11 10:08:33 -0700717 if cmd_info[param].type in self.handle_types:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600718 if object_array == True:
719 # This API is freeing an array of handles -- add loop control
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600720 validate_code += 'HEY, NEED TO DESTROY AN ARRAY\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600721 else:
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600722 dispobj = cmd_info[0].type
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600723 # Call Destroy a single time
Mark Lobodzinskiadd93232018-10-09 11:49:42 -0600724 validate_code += '%sskip |= ValidateDestroyObject(%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)
725 record_code += '%sRecordDestroyObject(%s, %s, %s);\n' % (indent, cmd_info[0].name, cmd_info[param].name, self.GetVulkanObjType(cmd_info[param].type))
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600726 return object_array, validate_code, record_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600727 #
728 # Output validation for a single object (obj_count is NULL) or a counted list of objects
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600729 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 -0600730 pre_call_code = ''
Dave Houlton57ae22f2018-05-18 16:20:52 -0600731 param_suffix = '%s-parameter' % (obj_name)
732 parent_suffix = '%s-parent' % (obj_name)
733 param_vuid = self.GetVuid(parent_name, param_suffix)
734 parent_vuid = self.GetVuid(parent_name, parent_suffix)
735
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600736 # If no parent VUID for this member, look for a commonparent VUID
Dave Houlton57ae22f2018-05-18 16:20:52 -0600737 if parent_vuid == 'kVUIDUndefined':
738 parent_vuid = self.GetVuid(parent_name, 'commonparent')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600739 if obj_count is not None:
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600740
741 pre_call_code += '%sif (%s%s) {\n' % (indent, prefix, obj_name)
742 indent = self.incIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600743 pre_call_code += '%sfor (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, obj_count, index)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600744 indent = self.incIndent(indent)
Mark Lobodzinskiadd93232018-10-09 11:49:42 -0600745 pre_call_code += '%sskip |= 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)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600746 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600747 pre_call_code += '%s}\n' % indent
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600748 indent = self.decIndent(indent)
749 pre_call_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600750 else:
Mark Lobodzinskiadd93232018-10-09 11:49:42 -0600751 pre_call_code += '%sskip |= 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)
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600752 return pre_call_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600753 #
754 # 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 -0600755 def validate_objects(self, members, indent, prefix, array_index, disp_name, parent_name, first_level_param):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600756 pre_code = ''
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600757 index = 'index%s' % str(array_index)
758 array_index += 1
759 # Process any objects in this structure and recurse for any sub-structs in this struct
760 for member in members:
761 # Handle objects
762 if member.iscreate and first_level_param and member == members[-1]:
763 continue
Mike Schuchardtf8690262019-07-11 10:08:33 -0700764 if member.type in self.handle_types:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600765 count_name = member.len
766 if (count_name is not None):
767 count_name = '%s%s' % (prefix, member.len)
768 null_allowed = member.isoptional
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600769 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 -0600770 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600771 # Handle Structs that contain objects at some level
772 elif member.type in self.struct_member_dict:
773 # Structs at first level will have an object
774 if self.struct_contains_object(member.type) == True:
775 struct_info = self.struct_member_dict[member.type]
Jeff Bolz38b3ce72018-09-19 12:53:38 -0500776 # TODO (jbolz): Can this use paramIsPointer?
Jeff Bolzba74d972018-09-12 15:54:57 -0500777 ispointer = '*' in member.cdecl;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600778 # Struct Array
779 if member.len is not None:
780 # Update struct prefix
781 new_prefix = '%s%s' % (prefix, member.name)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600782 pre_code += '%sif (%s%s) {\n' % (indent, prefix, member.name)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600783 indent = self.incIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600784 pre_code += '%sfor (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600785 indent = self.incIndent(indent)
786 local_prefix = '%s[%s].' % (new_prefix, index)
787 # Process sub-structs in this struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600788 tmp_pre = self.validate_objects(struct_info, indent, local_prefix, array_index, disp_name, member.type, False)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600789 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600790 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600791 pre_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600792 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600793 pre_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600794 # Single Struct
Jeff Bolzba74d972018-09-12 15:54:57 -0500795 elif ispointer:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600796 # Update struct prefix
797 new_prefix = '%s%s->' % (prefix, member.name)
798 # Declare safe_VarType for struct
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600799 pre_code += '%sif (%s%s) {\n' % (indent, prefix, member.name)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600800 indent = self.incIndent(indent)
801 # Process sub-structs in this struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600802 tmp_pre = self.validate_objects(struct_info, indent, new_prefix, array_index, disp_name, member.type, False)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600803 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600804 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600805 pre_code += '%s}\n' % indent
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600806 return pre_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600807 #
808 # For a particular API, generate the object handling code
809 def generate_wrapping_code(self, cmd):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600810 indent = ' '
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600811 pre_call_validate = ''
812 pre_call_record = ''
813 post_call_record = ''
814
815 destroy_array = False
816 validate_destroy_code = ''
817 record_destroy_code = ''
818
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600819 proto = cmd.find('proto/name')
820 params = cmd.findall('param')
821 if proto.text is not None:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600822 cmddata = self.cmd_info_dict[proto.text]
823 cmd_info = cmddata.members
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600824 disp_name = cmd_info[0].name
John Zulaufbb6e5e42018-08-06 16:00:07 -0600825 # Handle object create operations if last parameter is created by this call
826 if cmddata.iscreate:
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600827 post_call_record += self.generate_create_object_code(indent, proto, params, cmd_info, cmddata.allocator)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600828 # Handle object destroy operations
John Zulaufbb6e5e42018-08-06 16:00:07 -0600829 if cmddata.isdestroy:
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600830 (destroy_array, validate_destroy_code, record_destroy_code) = self.generate_destroy_object_code(indent, proto, cmd_info)
Mark Lobodzinski2a51e802018-09-12 16:07:01 -0600831
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600832 pre_call_record += record_destroy_code
833 pre_call_validate += self.validate_objects(cmd_info, indent, '', 0, disp_name, proto.text, True)
834 pre_call_validate += validate_destroy_code
835
836 return pre_call_validate, pre_call_record, post_call_record
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600837 #
838 # Capture command parameter info needed to create, destroy, and validate objects
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700839 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600840
841 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700842 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600843 members = cmdinfo.elem.findall('.//param')
844 # Iterate over members once to get length parameters for arrays
845 lens = set()
846 for member in members:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600847 length = self.getLen(member)
848 if length:
849 lens.add(length)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600850 struct_member_dict = dict(self.structMembers)
John Zulaufbb6e5e42018-08-06 16:00:07 -0600851
852 # Set command invariant information needed at a per member level in validate...
853 is_create_command = any(filter(lambda pat: pat in cmdname, ('Create', 'Allocate', 'Enumerate', 'RegisterDeviceEvent', 'RegisterDisplayEvent')))
854 last_member_is_pointer = len(members) and self.paramIsPointer(members[-1])
855 iscreate = is_create_command or ('vkGet' in cmdname and last_member_is_pointer)
856 isdestroy = any([destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']])
857
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600858 # Generate member info
859 membersInfo = []
860 constains_extension_structs = False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600861 allocator = 'nullptr'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600862 for member in members:
863 # Get type and name of member
864 info = self.getTypeNameTuple(member)
865 type = info[0]
866 name = info[1]
867 cdecl = self.makeCParamDecl(member, 0)
868 # Check for parameter name in lens set
869 iscount = True if name in lens else False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600870 length = self.getLen(member)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600871 isconst = True if 'const' in cdecl else False
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600872 # Mark param as local if it is an array of objects
873 islocal = False;
Mike Schuchardtf8690262019-07-11 10:08:33 -0700874 if type in self.handle_types:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600875 if (length is not None) and (isconst == True):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600876 islocal = True
877 # Or if it's a struct that contains an object
878 elif type in struct_member_dict:
879 if self.struct_contains_object(type) == True:
880 islocal = True
John Zulaufbb6e5e42018-08-06 16:00:07 -0600881 if type == 'VkAllocationCallbacks':
882 allocator = name
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600883 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
884 membersInfo.append(self.CommandParam(type=type,
885 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600886 isconst=isconst,
887 isoptional=self.paramIsOptional(member),
888 iscount=iscount,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600889 len=length,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600890 extstructs=extstructs,
891 cdecl=cdecl,
892 islocal=islocal,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600893 iscreate=iscreate))
894
895 self.cmd_list.append(cmdname)
896 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 -0600897 #
898 # Create code Create, Destroy, and validate Vulkan objects
899 def WrapCommands(self):
John Zulaufbb6e5e42018-08-06 16:00:07 -0600900 for cmdname in self.cmd_list:
901 cmddata = self.cmd_info_dict[cmdname]
902 cmdinfo = cmddata.cmdinfo
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600903 if cmdname in self.interface_functions:
904 continue
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600905 manual = False
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600906 if cmdname in self.no_autogen_list:
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600907 manual = True
908
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600909 # Generate object handling code
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600910 (pre_call_validate, pre_call_record, post_call_record) = self.generate_wrapping_code(cmdinfo.elem)
911
John Zulaufbb6e5e42018-08-06 16:00:07 -0600912 feature_extra_protect = cmddata.extra_protect
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100913 if (feature_extra_protect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600914 self.appendSection('command', '')
915 self.appendSection('command', '#ifdef '+ feature_extra_protect)
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600916 self.prototypes += [ '#ifdef %s' % feature_extra_protect ]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600917
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600918 # Add intercept to procmap
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600919 self.prototypes += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600920
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600921 decls = self.makeCDecls(cmdinfo.elem)
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600922
923 # Gather the parameter items
924 params = cmdinfo.elem.findall('param/name')
925 # Pull out the text for each of the parameters, separate them by commas in a list
926 paramstext = ', '.join([str(param.text) for param in params])
927 # Generate the API call template
928 fcn_call = cmdinfo.elem.attrib.get('name').replace('vk', 'TOKEN', 1) + '(' + paramstext + ');'
929
930 func_decl_template = decls[0][:-1].split('VKAPI_CALL ')
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600931 func_decl_template = func_decl_template[1]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600932
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700933 result_type = cmdinfo.elem.find('proto/type')
934
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600935 if 'object_tracker.h' in self.genOpts.filename:
936 # Output PreCallValidateAPI prototype if necessary
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600937 if pre_call_validate:
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600938 pre_cv_func_decl = 'bool PreCallValidate' + func_decl_template + ';'
939 self.appendSection('command', pre_cv_func_decl)
940
941 # Output PreCallRecordAPI prototype if necessary
942 if pre_call_record:
943 pre_cr_func_decl = 'void PreCallRecord' + func_decl_template + ';'
944 self.appendSection('command', pre_cr_func_decl)
945
946 # Output PosCallRecordAPI prototype if necessary
947 if post_call_record:
948 post_cr_func_decl = 'void PostCallRecord' + func_decl_template + ';'
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700949 if result_type.text == 'VkResult':
950 post_cr_func_decl = post_cr_func_decl.replace(')', ',\n VkResult result)')
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600951 self.appendSection('command', post_cr_func_decl)
952
953 if 'object_tracker.cpp' in self.genOpts.filename:
954 # Output PreCallValidateAPI function if necessary
955 if pre_call_validate and not manual:
956 pre_cv_func_decl = 'bool ObjectLifetimes::PreCallValidate' + func_decl_template + ' {'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600957 self.appendSection('command', '')
958 self.appendSection('command', pre_cv_func_decl)
959 self.appendSection('command', ' bool skip = false;')
960 self.appendSection('command', pre_call_validate)
961 self.appendSection('command', ' return skip;')
962 self.appendSection('command', '}')
963
964 # Output PreCallRecordAPI function if necessary
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600965 if pre_call_record and not manual:
966 pre_cr_func_decl = 'void ObjectLifetimes::PreCallRecord' + func_decl_template + ' {'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600967 self.appendSection('command', '')
968 self.appendSection('command', pre_cr_func_decl)
969 self.appendSection('command', pre_call_record)
970 self.appendSection('command', '}')
971
972 # Output PosCallRecordAPI function if necessary
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600973 if post_call_record and not manual:
974 post_cr_func_decl = 'void ObjectLifetimes::PostCallRecord' + func_decl_template + ' {'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600975 self.appendSection('command', '')
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700976
977 if result_type.text == 'VkResult':
978 post_cr_func_decl = post_cr_func_decl.replace(')', ',\n VkResult result)')
Mark Lobodzinskifd2d0a42019-02-20 16:34:56 -0700979 # The two createpipelines APIs may create on failure -- skip the success result check
980 if 'CreateGraphicsPipelines' not in cmdname and 'CreateComputePipelines' not in cmdname and 'CreateRayTracingPipelines' not in cmdname:
981 post_cr_func_decl = post_cr_func_decl.replace('{', '{\n if (result != VK_SUCCESS) return;')
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600982 self.appendSection('command', post_cr_func_decl)
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700983
984
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600985 self.appendSection('command', post_call_record)
986 self.appendSection('command', '}')
987
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100988 if (feature_extra_protect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600989 self.appendSection('command', '#endif // '+ feature_extra_protect)
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600990 self.prototypes += [ '#endif' ]