blob: 0d922051ac0c110deab092df00e08cef6e942b0f [file] [log] [blame]
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001#!/usr/bin/python3 -i
2#
3# Copyright (c) 2015-2017 The Khronos Group Inc.
4# Copyright (c) 2015-2017 Valve Corporation
5# Copyright (c) 2015-2017 LunarG, Inc.
6# Copyright (c) 2015-2017 Google Inc.
7#
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>
21
22import os,re,sys,string
23import xml.etree.ElementTree as etree
24from generator import *
25from collections import namedtuple
26from vuid_mapping import *
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,
88 expandEnumerants = True):
Mark Lobodzinskid1461482017-07-18 13:56:09 -060089 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
90 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060091 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinskid1461482017-07-18 13:56:09 -060092 self.prefixText = prefixText
93 self.genFuncPointers = genFuncPointers
94 self.protectFile = protectFile
95 self.protectFeature = protectFeature
Mark Lobodzinskid1461482017-07-18 13:56:09 -060096 self.apicall = apicall
97 self.apientry = apientry
98 self.apientryp = apientryp
99 self.indentFuncProto = indentFuncProto
100 self.indentFuncPointer = indentFuncPointer
101 self.alignFuncParam = alignFuncParam
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600102 self.expandEnumerants = expandEnumerants
103
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600104
105# ObjectTrackerOutputGenerator - subclass of OutputGenerator.
106# Generates object_tracker layer object validation code
107#
108# ---- methods ----
109# ObjectTrackerOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
110# ---- methods overriding base class ----
111# beginFile(genOpts)
112# endFile()
113# beginFeature(interface, emit)
114# endFeature()
115# genCmd(cmdinfo)
116# genStruct()
117# genType()
118class ObjectTrackerOutputGenerator(OutputGenerator):
119 """Generate ObjectTracker code based on XML element attributes"""
120 # This is an ordered list of sections in the header file.
121 ALL_SECTIONS = ['command']
122 def __init__(self,
123 errFile = sys.stderr,
124 warnFile = sys.stderr,
125 diagFile = sys.stdout):
126 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
127 self.INDENT_SPACES = 4
128 self.intercepts = []
129 self.instance_extensions = []
130 self.device_extensions = []
131 # Commands which are not autogenerated but still intercepted
132 self.no_autogen_list = [
133 'vkDestroyInstance',
134 'vkDestroyDevice',
135 'vkUpdateDescriptorSets',
136 'vkDestroyDebugReportCallbackEXT',
137 'vkDebugReportMessageEXT',
138 'vkGetPhysicalDeviceQueueFamilyProperties',
139 'vkFreeCommandBuffers',
140 'vkDestroySwapchainKHR',
141 'vkDestroyDescriptorPool',
142 'vkDestroyCommandPool',
Mark Lobodzinski14ddc192017-10-25 16:57:04 -0600143 'vkGetPhysicalDeviceQueueFamilyProperties2',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600144 'vkGetPhysicalDeviceQueueFamilyProperties2KHR',
145 'vkResetDescriptorPool',
146 'vkBeginCommandBuffer',
147 'vkCreateDebugReportCallbackEXT',
148 'vkEnumerateInstanceLayerProperties',
149 'vkEnumerateDeviceLayerProperties',
150 'vkEnumerateInstanceExtensionProperties',
151 'vkEnumerateDeviceExtensionProperties',
152 'vkCreateDevice',
153 'vkCreateInstance',
154 'vkEnumeratePhysicalDevices',
155 'vkAllocateCommandBuffers',
156 'vkAllocateDescriptorSets',
157 'vkFreeDescriptorSets',
Tony Barbour2fd0c2c2017-08-08 12:51:33 -0600158 'vkCmdPushDescriptorSetKHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600159 'vkDebugMarkerSetObjectNameEXT',
160 'vkGetPhysicalDeviceProcAddr',
161 'vkGetDeviceProcAddr',
162 'vkGetInstanceProcAddr',
163 'vkEnumerateInstanceExtensionProperties',
164 'vkEnumerateInstanceLayerProperties',
165 'vkEnumerateDeviceLayerProperties',
166 'vkGetDeviceProcAddr',
167 'vkGetInstanceProcAddr',
168 'vkEnumerateDeviceExtensionProperties',
169 'vk_layerGetPhysicalDeviceProcAddr',
170 'vkNegotiateLoaderLayerInterfaceVersion',
171 'vkCreateComputePipelines',
172 'vkGetDeviceQueue',
173 'vkGetSwapchainImagesKHR',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100174 'vkCreateDescriptorSetLayout',
Mark Young6ba8abe2017-11-09 10:37:04 -0700175 'vkCreateDebugUtilsMessengerEXT',
176 'vkDestroyDebugUtilsMessengerEXT',
177 'vkSubmitDebugUtilsMessageEXT',
178 'vkSetDebugUtilsObjectNameEXT',
179 'vkSetDebugUtilsObjectTagEXT',
180 'vkQueueBeginDebugUtilsLabelEXT',
181 'vkQueueEndDebugUtilsLabelEXT',
182 'vkQueueInsertDebugUtilsLabelEXT',
183 'vkCmdBeginDebugUtilsLabelEXT',
184 'vkCmdEndDebugUtilsLabelEXT',
185 'vkCmdInsertDebugUtilsLabelEXT',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600186 ]
187 # These VUIDS are not implicit, but are best handled in this layer. Codegen for vkDestroy calls will generate a key
188 # which is translated here into a good VU. Saves ~40 checks.
189 self.manual_vuids = dict()
190 self.manual_vuids = {
191 "fence-compatalloc": "VALIDATION_ERROR_24e008c2",
192 "fence-nullalloc": "VALIDATION_ERROR_24e008c4",
193 "event-compatalloc": "VALIDATION_ERROR_24c008f4",
194 "event-nullalloc": "VALIDATION_ERROR_24c008f6",
195 "buffer-compatalloc": "VALIDATION_ERROR_23c00736",
196 "buffer-nullalloc": "VALIDATION_ERROR_23c00738",
197 "image-compatalloc": "VALIDATION_ERROR_252007d2",
198 "image-nullalloc": "VALIDATION_ERROR_252007d4",
199 "shaderModule-compatalloc": "VALIDATION_ERROR_26a00888",
200 "shaderModule-nullalloc": "VALIDATION_ERROR_26a0088a",
201 "pipeline-compatalloc": "VALIDATION_ERROR_25c005fc",
202 "pipeline-nullalloc": "VALIDATION_ERROR_25c005fe",
203 "sampler-compatalloc": "VALIDATION_ERROR_26600876",
204 "sampler-nullalloc": "VALIDATION_ERROR_26600878",
205 "renderPass-compatalloc": "VALIDATION_ERROR_264006d4",
206 "renderPass-nullalloc": "VALIDATION_ERROR_264006d6",
207 "descriptorUpdateTemplate-compatalloc": "VALIDATION_ERROR_248002c8",
208 "descriptorUpdateTemplate-nullalloc": "VALIDATION_ERROR_248002ca",
209 "imageView-compatalloc": "VALIDATION_ERROR_25400806",
210 "imageView-nullalloc": "VALIDATION_ERROR_25400808",
211 "pipelineCache-compatalloc": "VALIDATION_ERROR_25e00606",
212 "pipelineCache-nullalloc": "VALIDATION_ERROR_25e00608",
213 "pipelineLayout-compatalloc": "VALIDATION_ERROR_26000256",
214 "pipelineLayout-nullalloc": "VALIDATION_ERROR_26000258",
215 "descriptorSetLayout-compatalloc": "VALIDATION_ERROR_24600238",
216 "descriptorSetLayout-nullalloc": "VALIDATION_ERROR_2460023a",
217 "semaphore-compatalloc": "VALIDATION_ERROR_268008e4",
218 "semaphore-nullalloc": "VALIDATION_ERROR_268008e6",
219 "queryPool-compatalloc": "VALIDATION_ERROR_26200634",
220 "queryPool-nullalloc": "VALIDATION_ERROR_26200636",
221 "bufferView-compatalloc": "VALIDATION_ERROR_23e00752",
222 "bufferView-nullalloc": "VALIDATION_ERROR_23e00754",
223 "surface-compatalloc": "VALIDATION_ERROR_26c009e6",
224 "surface-nullalloc": "VALIDATION_ERROR_26c009e8",
225 "framebuffer-compatalloc": "VALIDATION_ERROR_250006fa",
226 "framebuffer-nullalloc": "VALIDATION_ERROR_250006fc",
227 }
228
229 # Commands shadowed by interface functions and are not implemented
230 self.interface_functions = [
231 ]
232 self.headerVersion = None
233 # Internal state - accumulators for different inner block text
234 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
235 self.cmdMembers = []
236 self.cmd_feature_protect = [] # Save ifdef's for each command
237 self.cmd_info_data = [] # Save the cmdinfo data for validating the handles when processing is complete
238 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
239 self.extension_structs = [] # List of all structs or sister-structs containing handles
240 # A sister-struct may contain no handles but shares <validextensionstructs> with one that does
241 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
242 self.struct_member_dict = dict()
243 # Named tuples to store struct and command data
244 self.StructType = namedtuple('StructType', ['name', 'value'])
245 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
246 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
247 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
248 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'isoptional', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
249 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
250 self.object_types = [] # List of all handle types
251 self.valid_vuids = set() # Set of all valid VUIDs
252 self.vuid_file = None
253 # Cover cases where file is built from scripts directory, Lin/Win, or Android build structure
Jamie Madillc47ddf92017-12-20 14:45:11 -0500254 # Set cwd to the script directory to more easily locate the header.
255 previous_dir = os.getcwd()
256 os.chdir(os.path.dirname(sys.argv[0]))
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600257 vuid_filename_locations = [
258 './vk_validation_error_messages.h',
259 '../layers/vk_validation_error_messages.h',
260 '../../layers/vk_validation_error_messages.h',
261 '../../../layers/vk_validation_error_messages.h',
262 ]
263 for vuid_filename in vuid_filename_locations:
264 if os.path.isfile(vuid_filename):
Lenny Komowb79f04a2017-09-18 17:07:00 -0600265 self.vuid_file = open(vuid_filename, "r", encoding="utf8")
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600266 break
267 if self.vuid_file == None:
268 print("Error: Could not find vk_validation_error_messages.h")
Jamie Madill3935f7c2017-11-08 13:50:14 -0500269 sys.exit(1)
Jamie Madillc47ddf92017-12-20 14:45:11 -0500270 os.chdir(previous_dir)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600271 #
272 # Check if the parameter passed in is optional
273 def paramIsOptional(self, param):
274 # See if the handle is optional
275 isoptional = False
276 # Simple, if it's optional, return true
277 optString = param.attrib.get('optional')
278 if optString:
279 if optString == 'true':
280 isoptional = True
281 elif ',' in optString:
282 opts = []
283 for opt in optString.split(','):
284 val = opt.strip()
285 if val == 'true':
286 opts.append(True)
287 elif val == 'false':
288 opts.append(False)
289 else:
290 print('Unrecognized len attribute value',val)
291 isoptional = opts
292 return isoptional
293 #
294 # Convert decimal number to 8 digit hexadecimal lower-case representation
295 def IdToHex(self, dec_num):
296 if dec_num > 4294967295:
297 print ("ERROR: Decimal # %d can't be represented in 8 hex digits" % (dec_num))
298 sys.exit()
299 hex_num = hex(dec_num)
300 return hex_num[2:].zfill(8)
301 #
302 # Get VUID identifier from implicit VUID tag
303 def GetVuid(self, vuid_string):
304 if '->' in vuid_string:
305 return "VALIDATION_ERROR_UNDEFINED"
306 vuid_num = self.IdToHex(convertVUID(vuid_string))
307 if vuid_num in self.valid_vuids:
308 vuid = "VALIDATION_ERROR_%s" % vuid_num
309 else:
310 vuid = "VALIDATION_ERROR_UNDEFINED"
311 return vuid
312 #
313 # Increases indent by 4 spaces and tracks it globally
314 def incIndent(self, indent):
315 inc = ' ' * self.INDENT_SPACES
316 if indent:
317 return indent + inc
318 return inc
319 #
320 # Decreases indent by 4 spaces and tracks it globally
321 def decIndent(self, indent):
322 if indent and (len(indent) > self.INDENT_SPACES):
323 return indent[:-self.INDENT_SPACES]
324 return ''
325 #
326 # Override makeProtoName to drop the "vk" prefix
327 def makeProtoName(self, name, tail):
328 return self.genOpts.apientry + name[2:] + tail
329 #
330 # Check if the parameter passed in is a pointer to an array
331 def paramIsArray(self, param):
332 return param.attrib.get('len') is not None
333 #
334 # Generate the object tracker undestroyed object validation function
335 def GenReportFunc(self):
336 output_func = ''
337 output_func += 'void ReportUndestroyedObjects(VkDevice device, enum UNIQUE_VALIDATION_ERROR_CODE error_code) {\n'
338 output_func += ' DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);\n'
339 for handle in self.object_types:
340 if self.isHandleTypeNonDispatchable(handle):
341 output_func += ' DeviceReportUndestroyedObjects(device, %s, error_code);\n' % (self.GetVulkanObjType(handle))
342 output_func += '}\n'
343 return output_func
344 #
345 # Called at beginning of processing as file is opened
346 def beginFile(self, genOpts):
347 OutputGenerator.beginFile(self, genOpts)
348 # Open vk_validation_error_messages.h file to verify computed VUIDs
349 for line in self.vuid_file:
350 # Grab hex number from enum definition
351 vuid_list = line.split('0x')
352 # If this is a valid enumeration line, remove trailing comma and CR
353 if len(vuid_list) == 2:
354 vuid_num = vuid_list[1][:-2]
355 # Make sure this is a good hex number before adding to set
356 if len(vuid_num) == 8 and all(c in string.hexdigits for c in vuid_num):
357 self.valid_vuids.add(vuid_num)
358 # File Comment
359 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
360 file_comment += '// See object_tracker_generator.py for modifications\n'
361 write(file_comment, file=self.outFile)
362 # Copyright Statement
363 copyright = ''
364 copyright += '\n'
365 copyright += '/***************************************************************************\n'
366 copyright += ' *\n'
367 copyright += ' * Copyright (c) 2015-2017 The Khronos Group Inc.\n'
368 copyright += ' * Copyright (c) 2015-2017 Valve Corporation\n'
369 copyright += ' * Copyright (c) 2015-2017 LunarG, Inc.\n'
370 copyright += ' * Copyright (c) 2015-2017 Google Inc.\n'
371 copyright += ' *\n'
372 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
373 copyright += ' * you may not use this file except in compliance with the License.\n'
374 copyright += ' * You may obtain a copy of the License at\n'
375 copyright += ' *\n'
376 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
377 copyright += ' *\n'
378 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
379 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
380 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
381 copyright += ' * See the License for the specific language governing permissions and\n'
382 copyright += ' * limitations under the License.\n'
383 copyright += ' *\n'
384 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
385 copyright += ' *\n'
386 copyright += ' ****************************************************************************/\n'
387 write(copyright, file=self.outFile)
388 # Namespace
389 self.newline()
390 write('#include "object_tracker.h"', file = self.outFile)
391 self.newline()
392 write('namespace object_tracker {', file = self.outFile)
393 #
394 # Now that the data is all collected and complete, generate and output the object validation routines
395 def endFile(self):
396 self.struct_member_dict = dict(self.structMembers)
397 # Generate the list of APIs that might need to handle wrapped extension structs
398 # self.GenerateCommandWrapExtensionList()
399 self.WrapCommands()
400 # Build undestroyed objects reporting function
401 report_func = self.GenReportFunc()
402 self.newline()
403 write('// ObjectTracker undestroyed objects validation function', file=self.outFile)
404 write('%s' % report_func, file=self.outFile)
405 # Actually write the interface to the output file.
406 if (self.emit):
407 self.newline()
408 if (self.featureExtraProtect != None):
409 write('#ifdef', self.featureExtraProtect, file=self.outFile)
410 # Write the object_tracker code to the file
411 if (self.sections['command']):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600412 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
413 if (self.featureExtraProtect != None):
414 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
415 else:
416 self.newline()
417
418 # Record intercepted procedures
419 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
420 write('const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
421 write('\n'.join(self.intercepts), file=self.outFile)
422 write('};\n', file=self.outFile)
423 self.newline()
424 write('} // namespace object_tracker', file=self.outFile)
425 # Finish processing in superclass
426 OutputGenerator.endFile(self)
427 #
428 # Processing point at beginning of each extension definition
429 def beginFeature(self, interface, emit):
430 # Start processing in superclass
431 OutputGenerator.beginFeature(self, interface, emit)
432 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600433 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600434
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600435 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600436 white_list_entry = []
437 if (self.featureExtraProtect != None):
438 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
439 white_list_entry += [ '"%s"' % self.featureName ]
440 if (self.featureExtraProtect != None):
441 white_list_entry += [ '#endif' ]
442 featureType = interface.get('type')
443 if featureType == 'instance':
444 self.instance_extensions += white_list_entry
445 elif featureType == 'device':
446 self.device_extensions += white_list_entry
447 #
448 # Processing point at end of each extension definition
449 def endFeature(self):
450 # Finish processing in superclass
451 OutputGenerator.endFeature(self)
452 #
453 # Process enums, structs, etc.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700454 def genType(self, typeinfo, name, alias):
455 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600456 typeElem = typeinfo.elem
457 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
458 # Otherwise, emit the tag text.
459 category = typeElem.get('category')
460 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700461 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600462 if category == 'handle':
463 self.object_types.append(name)
464 #
465 # Append a definition to the specified section
466 def appendSection(self, section, text):
467 # self.sections[section].append('SECTION: ' + section + '\n')
468 self.sections[section].append(text)
469 #
470 # Check if the parameter passed in is a pointer
471 def paramIsPointer(self, param):
472 ispointer = False
473 for elem in param:
474 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
475 ispointer = True
476 return ispointer
477 #
478 # Get the category of a type
479 def getTypeCategory(self, typename):
480 types = self.registry.tree.findall("types/type")
481 for elem in types:
482 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
483 return elem.attrib.get('category')
484 #
485 # Check if a parent object is dispatchable or not
486 def isHandleTypeObject(self, handletype):
487 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
488 if handle is not None:
489 return True
490 else:
491 return False
492 #
493 # Check if a parent object is dispatchable or not
494 def isHandleTypeNonDispatchable(self, handletype):
495 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
496 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
497 return True
498 else:
499 return False
500 #
501 # Retrieve the type and name for a parameter
502 def getTypeNameTuple(self, param):
503 type = ''
504 name = ''
505 for elem in param:
506 if elem.tag == 'type':
507 type = noneStr(elem.text)
508 elif elem.tag == 'name':
509 name = noneStr(elem.text)
510 return (type, name)
511 #
512 # Retrieve the value of the len tag
513 def getLen(self, param):
514 result = None
515 len = param.attrib.get('len')
516 if len and len != 'null-terminated':
517 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
518 # have a null terminated array of strings. We strip the null-terminated from the
519 # 'len' field and only return the parameter specifying the string count
520 if 'null-terminated' in len:
521 result = len.split(',')[0]
522 else:
523 result = len
524 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
525 result = str(result).replace('::', '->')
526 return result
527 #
528 # Generate a VkStructureType based on a structure typename
529 def genVkStructureType(self, typename):
530 # Add underscore between lowercase then uppercase
531 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
532 # Change to uppercase
533 value = value.upper()
534 # Add STRUCTURE_TYPE_
535 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
536 #
537 # Struct parameter check generation.
538 # This is a special case of the <type> tag where the contents are interpreted as a set of
539 # <member> tags instead of freeform C type declarations. The <member> tags are just like
540 # <param> tags - they are a declaration of a struct or union member. Only simple member
541 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700542 def genStruct(self, typeinfo, typeName, alias):
543 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600544 members = typeinfo.elem.findall('.//member')
545 # Iterate over members once to get length parameters for arrays
546 lens = set()
547 for member in members:
548 len = self.getLen(member)
549 if len:
550 lens.add(len)
551 # Generate member info
552 membersInfo = []
553 for member in members:
554 # Get the member's type and name
555 info = self.getTypeNameTuple(member)
556 type = info[0]
557 name = info[1]
558 cdecl = self.makeCParamDecl(member, 0)
559 # Process VkStructureType
560 if type == 'VkStructureType':
561 # Extract the required struct type value from the comments
562 # embedded in the original text defining the 'typeinfo' element
563 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
564 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
565 if result:
566 value = result.group(0)
567 else:
568 value = self.genVkStructureType(typeName)
569 # Store the required type value
570 self.structTypes[typeName] = self.StructType(name=name, value=value)
571 # Store pointer/array/string info
572 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
573 membersInfo.append(self.CommandParam(type=type,
574 name=name,
575 ispointer=self.paramIsPointer(member),
576 isconst=True if 'const' in cdecl else False,
577 isoptional=self.paramIsOptional(member),
578 iscount=True if name in lens else False,
579 len=self.getLen(member),
580 extstructs=extstructs,
581 cdecl=cdecl,
582 islocal=False,
583 iscreate=False,
584 isdestroy=False,
585 feature_protect=self.featureExtraProtect))
586 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
587 #
588 # Insert a lock_guard line
589 def lock_guard(self, indent):
590 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
591 #
592 # Determine if a struct has an object as a member or an embedded member
593 def struct_contains_object(self, struct_item):
594 struct_member_dict = dict(self.structMembers)
595 struct_members = struct_member_dict[struct_item]
596
597 for member in struct_members:
598 if self.isHandleTypeObject(member.type):
599 return True
600 elif member.type in struct_member_dict:
601 if self.struct_contains_object(member.type) == True:
602 return True
603 return False
604 #
605 # Return list of struct members which contain, or whose sub-structures contain an obj in a given list of parameters or members
606 def getParmeterStructsWithObjects(self, item_list):
607 struct_list = set()
608 for item in item_list:
609 paramtype = item.find('type')
610 typecategory = self.getTypeCategory(paramtype.text)
611 if typecategory == 'struct':
612 if self.struct_contains_object(paramtype.text) == True:
613 struct_list.add(item)
614 return struct_list
615 #
616 # Return list of objects from a given list of parameters or members
617 def getObjectsInParameterList(self, item_list, create_func):
618 object_list = set()
619 if create_func == True:
620 member_list = item_list[0:-1]
621 else:
622 member_list = item_list
623 for item in member_list:
624 if self.isHandleTypeObject(paramtype.text):
625 object_list.add(item)
626 return object_list
627 #
628 # Construct list of extension structs containing handles, or extension structs that share a <validextensionstructs>
629 # tag WITH an extension struct containing handles.
630 def GenerateCommandWrapExtensionList(self):
631 for struct in self.structMembers:
632 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
633 found = False;
634 for item in struct.members[1].extstructs.split(','):
635 if item != '' and self.struct_contains_object(item) == True:
636 found = True
637 if found == True:
638 for item in struct.members[1].extstructs.split(','):
639 if item != '' and item not in self.extension_structs:
640 self.extension_structs.append(item)
641 #
642 # Returns True if a struct may have a pNext chain containing an object
643 def StructWithExtensions(self, struct_type):
644 if struct_type in self.struct_member_dict:
645 param_info = self.struct_member_dict[struct_type]
646 if (len(param_info) > 1) and param_info[1].extstructs is not None:
647 for item in param_info[1].extstructs.split(','):
648 if item in self.extension_structs:
649 return True
650 return False
651 #
652 # Generate VulkanObjectType from object type
653 def GetVulkanObjType(self, type):
654 return 'kVulkanObjectType%s' % type[2:]
655 #
656 # Return correct dispatch table type -- instance or device
657 def GetDispType(self, type):
658 return 'instance' if type in ['VkInstance', 'VkPhysicalDevice'] else 'device'
659 #
660 # Generate source for creating a Vulkan object
661 def generate_create_object_code(self, indent, proto, params, cmd_info):
662 create_obj_code = ''
663 handle_type = params[-1].find('type')
664 if self.isHandleTypeObject(handle_type.text):
665 # Check for special case where multiple handles are returned
666 object_array = False
667 if cmd_info[-1].len is not None:
668 object_array = True;
669 handle_name = params[-1].find('name')
670 create_obj_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
671 indent = self.incIndent(indent)
672 create_obj_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
673 object_dest = '*%s' % handle_name.text
674 if object_array == True:
675 create_obj_code += '%sfor (uint32_t index = 0; index < %s; index++) {\n' % (indent, cmd_info[-1].len)
676 indent = self.incIndent(indent)
677 object_dest = '%s[index]' % cmd_info[-1].name
678 create_obj_code += '%sCreateObject(%s, %s, %s, pAllocator);\n' % (indent, params[0].find('name').text, object_dest, self.GetVulkanObjType(cmd_info[-1].type))
679 if object_array == True:
680 indent = self.decIndent(indent)
681 create_obj_code += '%s}\n' % indent
682 indent = self.decIndent(indent)
683 create_obj_code += '%s}\n' % (indent)
684 return create_obj_code
685 #
686 # Generate source for destroying a non-dispatchable object
687 def generate_destroy_object_code(self, indent, proto, cmd_info):
688 destroy_obj_code = ''
689 object_array = False
690 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
691 # Check for special case where multiple handles are returned
692 if cmd_info[-1].len is not None:
693 object_array = True;
694 param = -1
695 else:
696 param = -2
697 compatalloc_vuid_string = '%s-compatalloc' % cmd_info[param].name
698 nullalloc_vuid_string = '%s-nullalloc' % cmd_info[param].name
699 compatalloc_vuid = self.manual_vuids.get(compatalloc_vuid_string, "VALIDATION_ERROR_UNDEFINED")
700 nullalloc_vuid = self.manual_vuids.get(nullalloc_vuid_string, "VALIDATION_ERROR_UNDEFINED")
701 if self.isHandleTypeObject(cmd_info[param].type) == True:
702 if object_array == True:
703 # This API is freeing an array of handles -- add loop control
704 destroy_obj_code += 'HEY, NEED TO DESTROY AN ARRAY\n'
705 else:
706 # Call Destroy a single time
707 destroy_obj_code += '%sif (skip) return;\n' % indent
708 destroy_obj_code += '%s{\n' % indent
709 destroy_obj_code += '%s std::lock_guard<std::mutex> lock(global_lock);\n' % indent
710 destroy_obj_code += '%s DestroyObject(%s, %s, %s, pAllocator, %s, %s);\n' % (indent, cmd_info[0].name, cmd_info[param].name, self.GetVulkanObjType(cmd_info[param].type), compatalloc_vuid, nullalloc_vuid)
711 destroy_obj_code += '%s}\n' % indent
712 return object_array, destroy_obj_code
713 #
714 # Output validation for a single object (obj_count is NULL) or a counted list of objects
715 def outputObjects(self, obj_type, obj_name, obj_count, prefix, index, indent, destroy_func, destroy_array, disp_name, parent_name, null_allowed, top_level):
716 decl_code = ''
717 pre_call_code = ''
718 post_call_code = ''
719 param_vuid_string = 'VUID-%s-%s-parameter' % (parent_name, obj_name)
720 parent_vuid_string = 'VUID-%s-%s-parent' % (parent_name, obj_name)
721 param_vuid = self.GetVuid(param_vuid_string)
722 parent_vuid = self.GetVuid(parent_vuid_string)
723 # If no parent VUID for this member, look for a commonparent VUID
724 if parent_vuid == 'VALIDATION_ERROR_UNDEFINED':
725 commonparent_vuid_string = 'VUID-%s-commonparent' % parent_name
726 parent_vuid = self.GetVuid(commonparent_vuid_string)
727 if obj_count is not None:
728 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, obj_name)
729 indent = self.incIndent(indent)
730 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, obj_count, index)
731 indent = self.incIndent(indent)
732 pre_call_code += '%s skip |= ValidateObject(%s, %s%s[%s], %s, %s, %s, %s);\n' % (indent, disp_name, prefix, obj_name, index, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
733 indent = self.decIndent(indent)
734 pre_call_code += '%s }\n' % indent
735 indent = self.decIndent(indent)
736 pre_call_code += '%s }\n' % indent
737 else:
738 pre_call_code += '%s skip |= ValidateObject(%s, %s%s, %s, %s, %s, %s);\n' % (indent, disp_name, prefix, obj_name, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
739 return decl_code, pre_call_code, post_call_code
740 #
741 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
742 # create_func means that this is API creates or allocates objects
743 # destroy_func indicates that this API destroys or frees objects
744 # destroy_array means that the destroy_func operated on an array of objects
745 def validate_objects(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, disp_name, parent_name, first_level_param):
746 decls = ''
747 pre_code = ''
748 post_code = ''
749 index = 'index%s' % str(array_index)
750 array_index += 1
751 # Process any objects in this structure and recurse for any sub-structs in this struct
752 for member in members:
753 # Handle objects
754 if member.iscreate and first_level_param and member == members[-1]:
755 continue
756 if self.isHandleTypeObject(member.type) == True:
757 count_name = member.len
758 if (count_name is not None):
759 count_name = '%s%s' % (prefix, member.len)
760 null_allowed = member.isoptional
761 (tmp_decl, tmp_pre, tmp_post) = self.outputObjects(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, disp_name, parent_name, str(null_allowed).lower(), first_level_param)
762 decls += tmp_decl
763 pre_code += tmp_pre
764 post_code += tmp_post
765 # Handle Structs that contain objects at some level
766 elif member.type in self.struct_member_dict:
767 # Structs at first level will have an object
768 if self.struct_contains_object(member.type) == True:
769 struct_info = self.struct_member_dict[member.type]
770 # Struct Array
771 if member.len is not None:
772 # Update struct prefix
773 new_prefix = '%s%s' % (prefix, member.name)
774 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
775 indent = self.incIndent(indent)
776 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
777 indent = self.incIndent(indent)
778 local_prefix = '%s[%s].' % (new_prefix, index)
779 # Process sub-structs in this struct
780 (tmp_decl, tmp_pre, tmp_post) = self.validate_objects(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, disp_name, member.type, False)
781 decls += tmp_decl
782 pre_code += tmp_pre
783 post_code += tmp_post
784 indent = self.decIndent(indent)
785 pre_code += '%s }\n' % indent
786 indent = self.decIndent(indent)
787 pre_code += '%s }\n' % indent
788 # Single Struct
789 else:
790 # Update struct prefix
791 new_prefix = '%s%s->' % (prefix, member.name)
792 # Declare safe_VarType for struct
793 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
794 indent = self.incIndent(indent)
795 # Process sub-structs in this struct
796 (tmp_decl, tmp_pre, tmp_post) = self.validate_objects(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, disp_name, member.type, False)
797 decls += tmp_decl
798 pre_code += tmp_pre
799 post_code += tmp_post
800 indent = self.decIndent(indent)
801 pre_code += '%s }\n' % indent
802 return decls, pre_code, post_code
803 #
804 # For a particular API, generate the object handling code
805 def generate_wrapping_code(self, cmd):
806 indent = ' '
807 proto = cmd.find('proto/name')
808 params = cmd.findall('param')
809 if proto.text is not None:
810 cmd_member_dict = dict(self.cmdMembers)
811 cmd_info = cmd_member_dict[proto.text]
812 disp_name = cmd_info[0].name
813 # Handle object create operations
814 if cmd_info[0].iscreate:
815 create_obj_code = self.generate_create_object_code(indent, proto, params, cmd_info)
816 else:
817 create_obj_code = ''
818 # Handle object destroy operations
819 if cmd_info[0].isdestroy:
820 (destroy_array, destroy_object_code) = self.generate_destroy_object_code(indent, proto, cmd_info)
821 else:
822 destroy_array = False
823 destroy_object_code = ''
824 paramdecl = ''
825 param_pre_code = ''
826 param_post_code = ''
827 create_func = True if create_obj_code else False
828 destroy_func = True if destroy_object_code else False
829 (paramdecl, param_pre_code, param_post_code) = self.validate_objects(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, disp_name, proto.text, True)
830 param_post_code += create_obj_code
831 if destroy_object_code:
832 if destroy_array == True:
833 param_post_code += destroy_object_code
834 else:
835 param_pre_code += destroy_object_code
836 if param_pre_code:
837 if (not destroy_func) or (destroy_array):
838 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
839 return paramdecl, param_pre_code, param_post_code
840 #
841 # Capture command parameter info needed to create, destroy, and validate objects
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700842 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600843
844 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700845 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600846 members = cmdinfo.elem.findall('.//param')
847 # Iterate over members once to get length parameters for arrays
848 lens = set()
849 for member in members:
850 len = self.getLen(member)
851 if len:
852 lens.add(len)
853 struct_member_dict = dict(self.structMembers)
854 # Generate member info
855 membersInfo = []
856 constains_extension_structs = False
857 for member in members:
858 # Get type and name of member
859 info = self.getTypeNameTuple(member)
860 type = info[0]
861 name = info[1]
862 cdecl = self.makeCParamDecl(member, 0)
863 # Check for parameter name in lens set
864 iscount = True if name in lens else False
865 len = self.getLen(member)
866 isconst = True if 'const' in cdecl else False
867 ispointer = self.paramIsPointer(member)
868 # Mark param as local if it is an array of objects
869 islocal = False;
870 if self.isHandleTypeObject(type) == True:
871 if (len is not None) and (isconst == True):
872 islocal = True
873 # Or if it's a struct that contains an object
874 elif type in struct_member_dict:
875 if self.struct_contains_object(type) == True:
876 islocal = True
877 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
878 iscreate = True if True in [create_txt in cmdname for create_txt in ['Create', 'Allocate', 'Enumerate', 'RegisterDeviceEvent', 'RegisterDisplayEvent']] or ('vkGet' in cmdname and member == members[-1] and ispointer == True) else False
879 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
880 membersInfo.append(self.CommandParam(type=type,
881 name=name,
882 ispointer=ispointer,
883 isconst=isconst,
884 isoptional=self.paramIsOptional(member),
885 iscount=iscount,
886 len=len,
887 extstructs=extstructs,
888 cdecl=cdecl,
889 islocal=islocal,
890 iscreate=iscreate,
891 isdestroy=isdestroy,
892 feature_protect=self.featureExtraProtect))
893 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
894 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
895 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
896 #
897 # Create code Create, Destroy, and validate Vulkan objects
898 def WrapCommands(self):
899 cmd_member_dict = dict(self.cmdMembers)
900 cmd_info_dict = dict(self.cmd_info_data)
901 cmd_protect_dict = dict(self.cmd_feature_protect)
902 for api_call in self.cmdMembers:
903 cmdname = api_call.name
904 cmdinfo = cmd_info_dict[api_call.name]
905 if cmdname in self.interface_functions:
906 continue
907 if cmdname in self.no_autogen_list:
908 decls = self.makeCDecls(cmdinfo.elem)
909 self.appendSection('command', '')
910 self.appendSection('command', '// Declare only')
911 self.appendSection('command', decls[0])
912 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
913 continue
914 # Generate object handling code
915 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
916 # If API doesn't contain any object handles, don't fool with it
917 if not api_decls and not api_pre and not api_post:
918 continue
919 feature_extra_protect = cmd_protect_dict[api_call.name]
920 if (feature_extra_protect != None):
921 self.appendSection('command', '')
922 self.appendSection('command', '#ifdef '+ feature_extra_protect)
923 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
924 # Add intercept to procmap
925 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
926 decls = self.makeCDecls(cmdinfo.elem)
927 self.appendSection('command', '')
928 self.appendSection('command', decls[0][:-1])
929 self.appendSection('command', '{')
930 self.appendSection('command', ' bool skip = false;')
931 # Handle return values, if any
932 resulttype = cmdinfo.elem.find('proto/type')
933 if (resulttype != None and resulttype.text == 'void'):
934 resulttype = None
935 if (resulttype != None):
936 assignresult = resulttype.text + ' result = '
937 else:
938 assignresult = ''
939 # Pre-pend declarations and pre-api-call codegen
940 if api_decls:
941 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
942 if api_pre:
943 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
944 # Generate the API call itself
945 # Gather the parameter items
946 params = cmdinfo.elem.findall('param/name')
947 # Pull out the text for each of the parameters, separate them by commas in a list
948 paramstext = ', '.join([str(param.text) for param in params])
949 # Use correct dispatch table
950 disp_type = cmdinfo.elem.find('param/type').text
951 disp_name = cmdinfo.elem.find('param/name').text
952 dispatch_table = 'get_dispatch_table(ot_%s_table_map, %s)->' % (self.GetDispType(disp_type), disp_name)
953 API = cmdinfo.elem.attrib.get('name').replace('vk', dispatch_table, 1)
954 # Put all this together for the final down-chain call
955 if assignresult != '':
Jamie Madillfc315192017-11-08 14:11:26 -0500956 if resulttype.text == 'VkResult':
957 self.appendSection('command', ' if (skip) return VK_ERROR_VALIDATION_FAILED_EXT;')
958 elif resulttype.text == 'VkBool32':
959 self.appendSection('command', ' if (skip) return VK_FALSE;')
960 else:
961 raise Exception('Unknown result type ' + resulttype.text)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600962 else:
963 self.appendSection('command', ' if (skip) return;')
964 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
965 # And add the post-API-call codegen
966 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
967 # Handle the return result variable, if any
968 if (resulttype != None):
969 self.appendSection('command', ' return result;')
970 self.appendSection('command', '}')
971 if (feature_extra_protect != None):
972 self.appendSection('command', '#endif // '+ feature_extra_protect)
973 self.intercepts += [ '#endif' ]