blob: 3a5c87ac3cb5406cf63c96d8820a1a7fbb44596a [file] [log] [blame]
Mark Lobodzinski85672672016-10-13 08:36:42 -06001#!/usr/bin/python3 -i
2#
3# Copyright (c) 2015-2016 The Khronos Group Inc.
4# Copyright (c) 2015-2016 Valve Corporation
5# Copyright (c) 2015-2016 LunarG, Inc.
6# Copyright (c) 2015-2016 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: Dustin Graves <dustin@lunarg.com>
21
22import os,re,sys
23import xml.etree.ElementTree as etree
24from generator import *
25from collections import namedtuple
26
27
28# ParamCheckerGeneratorOptions - subclass of GeneratorOptions.
29#
30# Adds options used by ParamCheckerOutputGenerator object during Parameter
31# validation layer generation.
32#
33# Additional members
34# prefixText - list of strings to prefix generated header with
35# (usually a copyright statement + calling convention macros).
36# protectFile - True if multiple inclusion protection should be
37# generated (based on the filename) around the entire header.
38# protectFeature - True if #ifndef..#endif protection should be
39# generated around a feature interface in the header file.
40# genFuncPointers - True if function pointer typedefs should be
41# generated
42# protectProto - If conditional protection should be generated
43# around prototype declarations, set to either '#ifdef'
44# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
45# to require opt-out (#ifndef protectProtoStr). Otherwise
46# set to None.
47# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
48# declarations, if protectProto is set
49# apicall - string to use for the function declaration prefix,
50# such as APICALL on Windows.
51# apientry - string to use for the calling convention macro,
52# in typedefs, such as APIENTRY.
53# apientryp - string to use for the calling convention macro
54# in function pointer typedefs, such as APIENTRYP.
55# indentFuncProto - True if prototype declarations should put each
56# parameter on a separate line
57# indentFuncPointer - True if typedefed function pointers should put each
58# parameter on a separate line
59# alignFuncParam - if nonzero and parameters are being put on a
60# separate line, align parameter names at the specified column
61class ParamCheckerGeneratorOptions(GeneratorOptions):
62 def __init__(self,
63 filename = None,
64 directory = '.',
65 apiname = None,
66 profile = None,
67 versions = '.*',
68 emitversions = '.*',
69 defaultExtensions = None,
70 addExtensions = None,
71 removeExtensions = None,
72 sortProcedure = regSortFeatures,
73 prefixText = "",
74 genFuncPointers = True,
75 protectFile = True,
76 protectFeature = True,
77 protectProto = None,
78 protectProtoStr = None,
79 apicall = '',
80 apientry = '',
81 apientryp = '',
82 indentFuncProto = True,
83 indentFuncPointer = False,
84 alignFuncParam = 0):
85 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
86 versions, emitversions, defaultExtensions,
87 addExtensions, removeExtensions, sortProcedure)
88 self.prefixText = prefixText
89 self.genFuncPointers = genFuncPointers
90 self.protectFile = protectFile
91 self.protectFeature = protectFeature
92 self.protectProto = protectProto
93 self.protectProtoStr = protectProtoStr
94 self.apicall = apicall
95 self.apientry = apientry
96 self.apientryp = apientryp
97 self.indentFuncProto = indentFuncProto
98 self.indentFuncPointer = indentFuncPointer
99 self.alignFuncParam = alignFuncParam
100
101# ParamCheckerOutputGenerator - subclass of OutputGenerator.
102# Generates param checker layer code.
103#
104# ---- methods ----
105# ParamCheckerOutputGenerator(errFile, warnFile, diagFile) - args as for
106# OutputGenerator. Defines additional internal state.
107# ---- methods overriding base class ----
108# beginFile(genOpts)
109# endFile()
110# beginFeature(interface, emit)
111# endFeature()
112# genType(typeinfo,name)
113# genStruct(typeinfo,name)
114# genGroup(groupinfo,name)
115# genEnum(enuminfo, name)
116# genCmd(cmdinfo)
117class ParamCheckerOutputGenerator(OutputGenerator):
118 """Generate ParamChecker code based on XML element attributes"""
119 # This is an ordered list of sections in the header file.
120 ALL_SECTIONS = ['command']
121 def __init__(self,
122 errFile = sys.stderr,
123 warnFile = sys.stderr,
124 diagFile = sys.stdout):
125 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
126 self.INDENT_SPACES = 4
127 # Commands to ignore
128 self.blacklist = [
129 'vkGetInstanceProcAddr',
130 'vkGetDeviceProcAddr',
131 'vkEnumerateInstanceLayerProperties',
132 'vkEnumerateInstanceExtensionsProperties',
133 'vkEnumerateDeviceLayerProperties',
134 'vkEnumerateDeviceExtensionsProperties',
135 'vkCreateDebugReportCallbackEXT',
136 'vkDebugReportMessageEXT']
137 # Validation conditions for some special case struct members that are conditionally validated
138 self.structMemberValidationConditions = { 'VkPipelineColorBlendStateCreateInfo' : { 'logicOp' : '{}logicOpEnable == VK_TRUE' } }
139 # Header version
140 self.headerVersion = None
141 # Internal state - accumulators for different inner block text
142 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
143 self.structNames = [] # List of Vulkan struct typenames
144 self.stypes = [] # Values from the VkStructureType enumeration
145 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
146 self.handleTypes = set() # Set of handle type names
147 self.commands = [] # List of CommandData records for all Vulkan commands
148 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
149 self.validatedStructs = dict() # Map of structs type names to generated validation code for that struct type
150 self.enumRanges = dict() # Map of enum name to BEGIN/END range values
151 self.flags = set() # Map of flags typenames
152 self.flagBits = dict() # Map of flag bits typename to list of values
Chris Forbes78ea32d2016-11-28 11:14:17 +1300153 self.newFlags = set() # Map of flags typenames /defined in the current feature/
Mark Lobodzinski85672672016-10-13 08:36:42 -0600154 # Named tuples to store struct and command data
155 self.StructType = namedtuple('StructType', ['name', 'value'])
156 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isbool', 'israngedenum',
157 'isconst', 'isoptional', 'iscount', 'noautovalidity', 'len', 'extstructs',
158 'condition', 'cdecl'])
159 self.CommandData = namedtuple('CommandData', ['name', 'params', 'cdecl'])
160 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
161 #
162 def incIndent(self, indent):
163 inc = ' ' * self.INDENT_SPACES
164 if indent:
165 return indent + inc
166 return inc
167 #
168 def decIndent(self, indent):
169 if indent and (len(indent) > self.INDENT_SPACES):
170 return indent[:-self.INDENT_SPACES]
171 return ''
172 #
173 def beginFile(self, genOpts):
174 OutputGenerator.beginFile(self, genOpts)
175 # C-specific
176 #
177 # User-supplied prefix text, if any (list of strings)
178 if (genOpts.prefixText):
179 for s in genOpts.prefixText:
180 write(s, file=self.outFile)
181 #
182 # Multiple inclusion protection & C++ wrappers.
183 if (genOpts.protectFile and self.genOpts.filename):
184 headerSym = re.sub('\.h', '_H', os.path.basename(self.genOpts.filename)).upper()
185 write('#ifndef', headerSym, file=self.outFile)
186 write('#define', headerSym, '1', file=self.outFile)
187 self.newline()
188 #
189 # Headers
190 write('#include <string>', file=self.outFile)
191 self.newline()
192 write('#include "vulkan/vulkan.h"', file=self.outFile)
193 write('#include "vk_layer_extension_utils.h"', file=self.outFile)
194 write('#include "parameter_validation_utils.h"', file=self.outFile)
195 #
196 # Macros
197 self.newline()
198 write('#ifndef UNUSED_PARAMETER', file=self.outFile)
199 write('#define UNUSED_PARAMETER(x) (void)(x)', file=self.outFile)
200 write('#endif // UNUSED_PARAMETER', file=self.outFile)
201 #
202 # Namespace
203 self.newline()
204 write('namespace parameter_validation {', file = self.outFile)
205 def endFile(self):
206 # C-specific
207 self.newline()
208 # Namespace
209 write('} // namespace parameter_validation', file = self.outFile)
210 # Finish C++ wrapper and multiple inclusion protection
211 if (self.genOpts.protectFile and self.genOpts.filename):
212 self.newline()
213 write('#endif', file=self.outFile)
214 # Finish processing in superclass
215 OutputGenerator.endFile(self)
216 def beginFeature(self, interface, emit):
217 # Start processing in superclass
218 OutputGenerator.beginFeature(self, interface, emit)
219 # C-specific
220 # Accumulate includes, defines, types, enums, function pointer typedefs,
221 # end function prototypes separately for this feature. They're only
222 # printed in endFeature().
223 self.headerVersion = None
224 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
225 self.structNames = []
226 self.stypes = []
227 self.structTypes = dict()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600228 self.commands = []
229 self.structMembers = []
230 self.validatedStructs = dict()
Chris Forbes78ea32d2016-11-28 11:14:17 +1300231 self.newFlags = set()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600232 def endFeature(self):
233 # C-specific
234 # Actually write the interface to the output file.
235 if (self.emit):
236 self.newline()
237 # If type declarations are needed by other features based on
238 # this one, it may be necessary to suppress the ExtraProtect,
239 # or move it below the 'for section...' loop.
240 if (self.featureExtraProtect != None):
241 write('#ifdef', self.featureExtraProtect, file=self.outFile)
242 # Generate the struct member checking code from the captured data
243 self.processStructMemberData()
244 # Generate the command parameter checking code from the captured data
245 self.processCmdData()
246 # Write the declaration for the HeaderVersion
247 if self.headerVersion:
248 write('const uint32_t GeneratedHeaderVersion = {};'.format(self.headerVersion), file=self.outFile)
249 self.newline()
250 # Write the declarations for the VkFlags values combining all flag bits
Chris Forbes78ea32d2016-11-28 11:14:17 +1300251 for flag in sorted(self.newFlags):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600252 flagBits = flag.replace('Flags', 'FlagBits')
253 if flagBits in self.flagBits:
254 bits = self.flagBits[flagBits]
255 decl = 'const {} All{} = {}'.format(flag, flagBits, bits[0])
256 for bit in bits[1:]:
257 decl += '|' + bit
258 decl += ';'
259 write(decl, file=self.outFile)
260 self.newline()
261 # Write the parameter validation code to the file
262 if (self.sections['command']):
263 if (self.genOpts.protectProto):
264 write(self.genOpts.protectProto,
265 self.genOpts.protectProtoStr, file=self.outFile)
Jamie Madill24aa9742016-12-13 17:02:57 -0500266 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600267 if (self.featureExtraProtect != None):
268 write('#endif /*', self.featureExtraProtect, '*/', file=self.outFile)
269 else:
270 self.newline()
271 # Finish processing in superclass
272 OutputGenerator.endFeature(self)
273 #
274 # Append a definition to the specified section
275 def appendSection(self, section, text):
276 # self.sections[section].append('SECTION: ' + section + '\n')
277 self.sections[section].append(text)
278 #
279 # Type generation
280 def genType(self, typeinfo, name):
281 OutputGenerator.genType(self, typeinfo, name)
282 typeElem = typeinfo.elem
283 # If the type is a struct type, traverse the imbedded <member> tags
284 # generating a structure. Otherwise, emit the tag text.
285 category = typeElem.get('category')
286 if (category == 'struct' or category == 'union'):
287 self.structNames.append(name)
288 self.genStruct(typeinfo, name)
289 elif (category == 'handle'):
290 self.handleTypes.add(name)
291 elif (category == 'bitmask'):
292 self.flags.add(name)
Chris Forbes78ea32d2016-11-28 11:14:17 +1300293 self.newFlags.add(name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600294 elif (category == 'define'):
295 if name == 'VK_HEADER_VERSION':
296 nameElem = typeElem.find('name')
297 self.headerVersion = noneStr(nameElem.tail).strip()
298 #
299 # Struct parameter check generation.
300 # This is a special case of the <type> tag where the contents are
301 # interpreted as a set of <member> tags instead of freeform C
302 # C type declarations. The <member> tags are just like <param>
303 # tags - they are a declaration of a struct or union member.
304 # Only simple member declarations are supported (no nested
305 # structs etc.)
306 def genStruct(self, typeinfo, typeName):
307 OutputGenerator.genStruct(self, typeinfo, typeName)
308 conditions = self.structMemberValidationConditions[typeName] if typeName in self.structMemberValidationConditions else None
309 members = typeinfo.elem.findall('.//member')
310 #
311 # Iterate over members once to get length parameters for arrays
312 lens = set()
313 for member in members:
314 len = self.getLen(member)
315 if len:
316 lens.add(len)
317 #
318 # Generate member info
319 membersInfo = []
320 for member in members:
321 # Get the member's type and name
322 info = self.getTypeNameTuple(member)
323 type = info[0]
324 name = info[1]
325 stypeValue = ''
326 cdecl = self.makeCParamDecl(member, 0)
327 # Process VkStructureType
328 if type == 'VkStructureType':
329 # Extract the required struct type value from the comments
330 # embedded in the original text defining the 'typeinfo' element
331 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
332 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
333 if result:
334 value = result.group(0)
335 else:
336 value = self.genVkStructureType(typeName)
337 # Store the required type value
338 self.structTypes[typeName] = self.StructType(name=name, value=value)
339 #
340 # Store pointer/array/string info
341 # Check for parameter name in lens set
342 iscount = False
343 if name in lens:
344 iscount = True
345 # The pNext members are not tagged as optional, but are treated as
346 # optional for parameter NULL checks. Static array members
347 # are also treated as optional to skip NULL pointer validation, as
348 # they won't be NULL.
349 isstaticarray = self.paramIsStaticArray(member)
350 isoptional = False
351 if self.paramIsOptional(member) or (name == 'pNext') or (isstaticarray):
352 isoptional = True
353 membersInfo.append(self.CommandParam(type=type, name=name,
354 ispointer=self.paramIsPointer(member),
355 isstaticarray=isstaticarray,
356 isbool=True if type == 'VkBool32' else False,
357 israngedenum=True if type in self.enumRanges else False,
358 isconst=True if 'const' in cdecl else False,
359 isoptional=isoptional,
360 iscount=iscount,
361 noautovalidity=True if member.attrib.get('noautovalidity') is not None else False,
362 len=self.getLen(member),
363 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
364 condition=conditions[name] if conditions and name in conditions else None,
365 cdecl=cdecl))
366 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
367 #
368 # Capture group (e.g. C "enum" type) info to be used for
369 # param check code generation.
370 # These are concatenated together with other types.
371 def genGroup(self, groupinfo, groupName):
372 OutputGenerator.genGroup(self, groupinfo, groupName)
373 groupElem = groupinfo.elem
374 #
375 # Store the sType values
376 if groupName == 'VkStructureType':
377 for elem in groupElem.findall('enum'):
378 self.stypes.append(elem.get('name'))
379 elif 'FlagBits' in groupName:
380 bits = []
381 for elem in groupElem.findall('enum'):
382 bits.append(elem.get('name'))
383 if bits:
384 self.flagBits[groupName] = bits
385 else:
386 # Determine if begin/end ranges are needed (we don't do this for VkStructureType, which has a more finely grained check)
387 expandName = re.sub(r'([0-9a-z_])([A-Z0-9][^A-Z0-9]?)',r'\1_\2',groupName).upper()
388 expandPrefix = expandName
389 expandSuffix = ''
390 expandSuffixMatch = re.search(r'[A-Z][A-Z]+$',groupName)
391 if expandSuffixMatch:
392 expandSuffix = '_' + expandSuffixMatch.group()
393 # Strip off the suffix from the prefix
394 expandPrefix = expandName.rsplit(expandSuffix, 1)[0]
395 isEnum = ('FLAG_BITS' not in expandPrefix)
396 if isEnum:
397 self.enumRanges[groupName] = (expandPrefix + '_BEGIN_RANGE' + expandSuffix, expandPrefix + '_END_RANGE' + expandSuffix)
398 #
399 # Capture command parameter info to be used for param
400 # check code generation.
401 def genCmd(self, cmdinfo, name):
402 OutputGenerator.genCmd(self, cmdinfo, name)
403 if name not in self.blacklist:
404 params = cmdinfo.elem.findall('param')
405 # Get list of array lengths
406 lens = set()
407 for param in params:
408 len = self.getLen(param)
409 if len:
410 lens.add(len)
411 # Get param info
412 paramsInfo = []
413 for param in params:
414 paramInfo = self.getTypeNameTuple(param)
415 cdecl = self.makeCParamDecl(param, 0)
416 # Check for parameter name in lens set
417 iscount = False
418 if paramInfo[1] in lens:
419 iscount = True
420 paramsInfo.append(self.CommandParam(type=paramInfo[0], name=paramInfo[1],
421 ispointer=self.paramIsPointer(param),
422 isstaticarray=self.paramIsStaticArray(param),
423 isbool=True if paramInfo[0] == 'VkBool32' else False,
424 israngedenum=True if paramInfo[0] in self.enumRanges else False,
425 isconst=True if 'const' in cdecl else False,
426 isoptional=self.paramIsOptional(param),
427 iscount=iscount,
428 noautovalidity=True if param.attrib.get('noautovalidity') is not None else False,
429 len=self.getLen(param),
430 extstructs=None,
431 condition=None,
432 cdecl=cdecl))
433 self.commands.append(self.CommandData(name=name, params=paramsInfo, cdecl=self.makeCDecls(cmdinfo.elem)[0]))
434 #
435 # Check if the parameter passed in is a pointer
436 def paramIsPointer(self, param):
437 ispointer = 0
438 paramtype = param.find('type')
439 if (paramtype.tail is not None) and ('*' in paramtype.tail):
440 ispointer = paramtype.tail.count('*')
441 elif paramtype.text[:4] == 'PFN_':
442 # Treat function pointer typedefs as a pointer to a single value
443 ispointer = 1
444 return ispointer
445 #
446 # Check if the parameter passed in is a static array
447 def paramIsStaticArray(self, param):
448 isstaticarray = 0
449 paramname = param.find('name')
450 if (paramname.tail is not None) and ('[' in paramname.tail):
451 isstaticarray = paramname.tail.count('[')
452 return isstaticarray
453 #
454 # Check if the parameter passed in is optional
455 # Returns a list of Boolean values for comma separated len attributes (len='false,true')
456 def paramIsOptional(self, param):
457 # See if the handle is optional
458 isoptional = False
459 # Simple, if it's optional, return true
460 optString = param.attrib.get('optional')
461 if optString:
462 if optString == 'true':
463 isoptional = True
464 elif ',' in optString:
465 opts = []
466 for opt in optString.split(','):
467 val = opt.strip()
468 if val == 'true':
469 opts.append(True)
470 elif val == 'false':
471 opts.append(False)
472 else:
473 print('Unrecognized len attribute value',val)
474 isoptional = opts
475 return isoptional
476 #
477 # Check if the handle passed in is optional
478 # Uses the same logic as ValidityOutputGenerator.isHandleOptional
479 def isHandleOptional(self, param, lenParam):
480 # Simple, if it's optional, return true
481 if param.isoptional:
482 return True
483 # If no validity is being generated, it usually means that validity is complex and not absolute, so let's say yes.
484 if param.noautovalidity:
485 return True
486 # If the parameter is an array and we haven't already returned, find out if any of the len parameters are optional
487 if lenParam and lenParam.isoptional:
488 return True
489 return False
490 #
491 # Generate a VkStructureType based on a structure typename
492 def genVkStructureType(self, typename):
493 # Add underscore between lowercase then uppercase
494 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
Mark Young39389872017-01-19 21:10:49 -0700495 value = value.replace('D3_D12', 'D3D12')
496 value = value.replace('Device_IDProp', 'Device_ID_Prop')
Mark Lobodzinski85672672016-10-13 08:36:42 -0600497 # Change to uppercase
498 value = value.upper()
499 # Add STRUCTURE_TYPE_
500 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
501 #
502 # Get the cached VkStructureType value for the specified struct typename, or generate a VkStructureType
503 # value assuming the struct is defined by a different feature
504 def getStructType(self, typename):
505 value = None
506 if typename in self.structTypes:
507 value = self.structTypes[typename].value
508 else:
509 value = self.genVkStructureType(typename)
510 self.logMsg('diag', 'ParameterValidation: Generating {} for {} structure type that was not defined by the current feature'.format(value, typename))
511 return value
512 #
513 # Retrieve the value of the len tag
514 def getLen(self, param):
515 result = None
516 len = param.attrib.get('len')
517 if len and len != 'null-terminated':
518 # For string arrays, 'len' can look like 'count,null-terminated',
519 # indicating that we have a null terminated array of strings. We
520 # strip the null-terminated from the 'len' field and only return
521 # the parameter specifying the string count
522 if 'null-terminated' in len:
523 result = len.split(',')[0]
524 else:
525 result = len
526 result = str(result).replace('::', '->')
527 return result
528 #
529 # Retrieve the type and name for a parameter
530 def getTypeNameTuple(self, param):
531 type = ''
532 name = ''
533 for elem in param:
534 if elem.tag == 'type':
535 type = noneStr(elem.text)
536 elif elem.tag == 'name':
537 name = noneStr(elem.text)
538 return (type, name)
539 #
540 # Find a named parameter in a parameter list
541 def getParamByName(self, params, name):
542 for param in params:
543 if param.name == name:
544 return param
545 return None
546 #
547 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
548 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
549 def parseLateXMath(self, source):
550 name = 'ERROR'
551 decoratedName = 'ERROR'
552 if 'mathit' in source:
553 # Matches expressions similar to 'latexmath:[$\lceil{\mathit{rasterizationSamples} \over 32}\rceil$]'
554 match = re.match(r'latexmath\s*\:\s*\[\s*\$\\l(\w+)\s*\{\s*\\mathit\s*\{\s*(\w+)\s*\}\s*\\over\s*(\d+)\s*\}\s*\\r(\w+)\$\s*\]', source)
555 if not match or match.group(1) != match.group(4):
556 raise 'Unrecognized latexmath expression'
557 name = match.group(2)
558 decoratedName = '{}({}/{})'.format(*match.group(1, 2, 3))
559 else:
560 # Matches expressions similar to 'latexmath : [$dataSize \over 4$]'
561 match = re.match(r'latexmath\s*\:\s*\[\s*\$\s*(\w+)\s*\\over\s*(\d+)\s*\$\s*\]', source)
562 name = match.group(1)
563 decoratedName = '{}/{}'.format(*match.group(1, 2))
564 return name, decoratedName
565 #
566 # Get the length paramater record for the specified parameter name
567 def getLenParam(self, params, name):
568 lenParam = None
569 if name:
570 if '->' in name:
571 # The count is obtained by dereferencing a member of a struct parameter
572 lenParam = self.CommandParam(name=name, iscount=True, ispointer=False, isbool=False, israngedenum=False, isconst=False,
573 isstaticarray=None, isoptional=False, type=None, noautovalidity=False, len=None, extstructs=None,
574 condition=None, cdecl=None)
575 elif 'latexmath' in name:
576 lenName, decoratedName = self.parseLateXMath(name)
577 lenParam = self.getParamByName(params, lenName)
578 # TODO: Zero-check the result produced by the equation?
579 # Copy the stored len parameter entry and overwrite the name with the processed latexmath equation
580 #param = self.getParamByName(params, lenName)
581 #lenParam = self.CommandParam(name=decoratedName, iscount=param.iscount, ispointer=param.ispointer,
582 # isoptional=param.isoptional, type=param.type, len=param.len,
583 # isstaticarray=param.isstaticarray, extstructs=param.extstructs,
584 # noautovalidity=True, condition=None, cdecl=param.cdecl)
585 else:
586 lenParam = self.getParamByName(params, name)
587 return lenParam
588 #
589 # Convert a vulkan.h command declaration into a parameter_validation.h definition
590 def getCmdDef(self, cmd):
591 #
592 # Strip the trailing ';' and split into individual lines
593 lines = cmd.cdecl[:-1].split('\n')
594 # Replace Vulkan prototype
595 lines[0] = 'static bool parameter_validation_' + cmd.name + '('
596 # Replace the first argument with debug_report_data, when the first
597 # argument is a handle (not vkCreateInstance)
598 reportData = ' debug_report_data*'.ljust(self.genOpts.alignFuncParam) + 'report_data,'
599 if cmd.name != 'vkCreateInstance':
600 lines[1] = reportData
601 else:
602 lines.insert(1, reportData)
603 return '\n'.join(lines)
604 #
605 # Generate the code to check for a NULL dereference before calling the
606 # validation function
607 def genCheckedLengthCall(self, name, exprs):
608 count = name.count('->')
609 if count:
610 checkedExpr = []
611 localIndent = ''
612 elements = name.split('->')
613 # Open the if expression blocks
614 for i in range(0, count):
615 checkedExpr.append(localIndent + 'if ({} != NULL) {{\n'.format('->'.join(elements[0:i+1])))
616 localIndent = self.incIndent(localIndent)
617 # Add the validation expression
618 for expr in exprs:
619 checkedExpr.append(localIndent + expr)
620 # Close the if blocks
621 for i in range(0, count):
622 localIndent = self.decIndent(localIndent)
623 checkedExpr.append(localIndent + '}\n')
624 return [checkedExpr]
625 # No if statements were required
626 return exprs
627 #
628 # Generate code to check for a specific condition before executing validation code
629 def genConditionalCall(self, prefix, condition, exprs):
630 checkedExpr = []
631 localIndent = ''
632 formattedCondition = condition.format(prefix)
633 checkedExpr.append(localIndent + 'if ({})\n'.format(formattedCondition))
634 checkedExpr.append(localIndent + '{\n')
635 localIndent = self.incIndent(localIndent)
636 for expr in exprs:
637 checkedExpr.append(localIndent + expr)
638 localIndent = self.decIndent(localIndent)
639 checkedExpr.append(localIndent + '}\n')
640 return [checkedExpr]
641 #
642 # Generate the sType check string
643 def makeStructTypeCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
644 checkExpr = []
645 stype = self.structTypes[value.type]
646 if lenValue:
647 # This is an array with a pointer to a count value
648 if lenValue.ispointer:
649 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
650 checkExpr.append('skipCall |= validate_struct_type_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {}, {});\n'.format(
651 funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec))
652 # This is an array with an integer count value
653 else:
654 checkExpr.append('skipCall |= validate_struct_type_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {});\n'.format(
655 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec))
656 # This is an individual struct
657 else:
658 checkExpr.append('skipCall |= validate_struct_type(report_data, "{}", {ppp}"{}"{pps}, "{sv}", {}{vn}, {sv}, {});\n'.format(
659 funcPrintName, valuePrintName, prefix, valueRequired, vn=value.name, sv=stype.value, **postProcSpec))
660 return checkExpr
661 #
662 # Generate the handle check string
663 def makeHandleCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
664 checkExpr = []
665 if lenValue:
666 if lenValue.ispointer:
667 # This is assumed to be an output array with a pointer to a count value
668 raise('Unsupported parameter validation case: Output handle array elements are not NULL checked')
669 else:
670 # This is an array with an integer count value
671 checkExpr.append('skipCall |= validate_handle_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {});\n'.format(
672 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
673 else:
674 # This is assumed to be an output handle pointer
675 raise('Unsupported parameter validation case: Output handles are not NULL checked')
676 return checkExpr
677 #
678 # Generate check string for an array of VkFlags values
679 def makeFlagsArrayCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
680 checkExpr = []
681 flagBitsName = value.type.replace('Flags', 'FlagBits')
682 if not flagBitsName in self.flagBits:
683 raise('Unsupported parameter validation case: array of reserved VkFlags')
684 else:
685 allFlags = 'All' + flagBitsName
686 checkExpr.append('skipCall |= validate_flags_array(report_data, "{}", {ppp}"{}"{pps}, {ppp}"{}"{pps}, "{}", {}, {pf}{}, {pf}{}, {}, {});\n'.format(funcPrintName, lenPrintName, valuePrintName, flagBitsName, allFlags, lenValue.name, value.name, lenValueRequired, valueRequired, pf=prefix, **postProcSpec))
687 return checkExpr
688 #
689 # Generate pNext check string
690 def makeStructNextCheck(self, prefix, value, funcPrintName, valuePrintName, postProcSpec):
691 checkExpr = []
692 # Generate an array of acceptable VkStructureType values for pNext
693 extStructCount = 0
694 extStructVar = 'NULL'
695 extStructNames = 'NULL'
696 if value.extstructs:
697 structs = value.extstructs.split(',')
698 checkExpr.append('const VkStructureType allowedStructs[] = {' + ', '.join([self.getStructType(s) for s in structs]) + '};\n')
699 extStructCount = 'ARRAY_SIZE(allowedStructs)'
700 extStructVar = 'allowedStructs'
701 extStructNames = '"' + ', '.join(structs) + '"'
702 checkExpr.append('skipCall |= validate_struct_pnext(report_data, "{}", {ppp}"{}"{pps}, {}, {}{}, {}, {}, GeneratedHeaderVersion);\n'.format(
703 funcPrintName, valuePrintName, extStructNames, prefix, value.name, extStructCount, extStructVar, **postProcSpec))
704 return checkExpr
705 #
706 # Generate the pointer check string
707 def makePointerCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
708 checkExpr = []
709 if lenValue:
710 # This is an array with a pointer to a count value
711 if lenValue.ispointer:
712 # If count and array parameters are optional, there will be no validation
713 if valueRequired == 'true' or lenPtrRequired == 'true' or lenValueRequired == 'true':
714 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
715 checkExpr.append('skipCall |= validate_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {});\n'.format(
716 funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
717 # This is an array with an integer count value
718 else:
719 # If count and array parameters are optional, there will be no validation
720 if valueRequired == 'true' or lenValueRequired == 'true':
721 # Arrays of strings receive special processing
722 validationFuncName = 'validate_array' if value.type != 'char' else 'validate_string_array'
723 checkExpr.append('skipCall |= {}(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {});\n'.format(
724 validationFuncName, funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
725 if checkExpr:
726 if lenValue and ('->' in lenValue.name):
727 # Add checks to ensure the validation call does not dereference a NULL pointer to obtain the count
728 checkExpr = self.genCheckedLengthCall(lenValue.name, checkExpr)
729 # This is an individual struct that is not allowed to be NULL
730 elif not value.isoptional:
731 # Function pointers need a reinterpret_cast to void*
732 if value.type[:4] == 'PFN_':
733 checkExpr.append('skipCall |= validate_required_pointer(report_data, "{}", {ppp}"{}"{pps}, reinterpret_cast<const void*>({}{}));\n'.format(funcPrintName, valuePrintName, prefix, value.name, **postProcSpec))
734 else:
735 checkExpr.append('skipCall |= validate_required_pointer(report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcPrintName, valuePrintName, prefix, value.name, **postProcSpec))
736 return checkExpr
737 #
738 # Process struct member validation code, performing name suibstitution if required
739 def processStructMemberCode(self, line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec):
740 # Build format specifier list
741 kwargs = {}
742 if '{postProcPrefix}' in line:
743 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
744 if type(memberDisplayNamePrefix) is tuple:
745 kwargs['postProcPrefix'] = 'ParameterName('
746 else:
747 kwargs['postProcPrefix'] = postProcSpec['ppp']
748 if '{postProcSuffix}' in line:
749 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
750 if type(memberDisplayNamePrefix) is tuple:
751 kwargs['postProcSuffix'] = ', ParameterName::IndexVector{{ {}{} }})'.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
752 else:
753 kwargs['postProcSuffix'] = postProcSpec['pps']
754 if '{postProcInsert}' in line:
755 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
756 if type(memberDisplayNamePrefix) is tuple:
757 kwargs['postProcInsert'] = '{}{}, '.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
758 else:
759 kwargs['postProcInsert'] = postProcSpec['ppi']
760 if '{funcName}' in line:
761 kwargs['funcName'] = funcName
762 if '{valuePrefix}' in line:
763 kwargs['valuePrefix'] = memberNamePrefix
764 if '{displayNamePrefix}' in line:
765 # Check for a tuple that includes a format string and format parameters to be used with the ParameterName class
766 if type(memberDisplayNamePrefix) is tuple:
767 kwargs['displayNamePrefix'] = memberDisplayNamePrefix[0]
768 else:
769 kwargs['displayNamePrefix'] = memberDisplayNamePrefix
770
771 if kwargs:
772 # Need to escape the C++ curly braces
773 if 'IndexVector' in line:
774 line = line.replace('IndexVector{ ', 'IndexVector{{ ')
775 line = line.replace(' }),', ' }}),')
776 return line.format(**kwargs)
777 return line
778 #
779 # Process struct validation code for inclusion in function or parent struct validation code
780 def expandStructCode(self, lines, funcName, memberNamePrefix, memberDisplayNamePrefix, indent, output, postProcSpec):
781 for line in lines:
782 if output:
783 output[-1] += '\n'
784 if type(line) is list:
785 for sub in line:
786 output.append(self.processStructMemberCode(indent + sub, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
787 else:
788 output.append(self.processStructMemberCode(indent + line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
789 return output
790 #
791 # Process struct pointer/array validation code, perfoeming name substitution if required
792 def expandStructPointerCode(self, prefix, value, lenValue, funcName, valueDisplayName, postProcSpec):
793 expr = []
794 expr.append('if ({}{} != NULL)\n'.format(prefix, value.name))
795 expr.append('{')
796 indent = self.incIndent(None)
797 if lenValue:
798 # Need to process all elements in the array
799 indexName = lenValue.name.replace('Count', 'Index')
800 expr[-1] += '\n'
Mark Young39389872017-01-19 21:10:49 -0700801 if lenValue.ispointer:
802 # If the length value is a pointer, de-reference it for the count.
803 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < *{}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
804 else:
805 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < {}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600806 expr.append(indent + '{')
807 indent = self.incIndent(indent)
808 # Prefix for value name to display in error message
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -0700809 if value.ispointer == 2:
810 memberNamePrefix = '{}{}[{}]->'.format(prefix, value.name, indexName)
811 memberDisplayNamePrefix = ('{}[%i]->'.format(valueDisplayName), indexName)
812 else:
813 memberNamePrefix = '{}{}[{}].'.format(prefix, value.name, indexName)
814 memberDisplayNamePrefix = ('{}[%i].'.format(valueDisplayName), indexName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600815 else:
816 memberNamePrefix = '{}{}->'.format(prefix, value.name)
817 memberDisplayNamePrefix = '{}->'.format(valueDisplayName)
818 #
819 # Expand the struct validation lines
820 expr = self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, indent, expr, postProcSpec)
821 #
822 if lenValue:
823 # Close if and for scopes
824 indent = self.decIndent(indent)
825 expr.append(indent + '}\n')
826 expr.append('}\n')
827 return expr
828 #
829 # Generate the parameter checking code
830 def genFuncBody(self, funcName, values, valuePrefix, displayNamePrefix, structTypeName):
831 lines = [] # Generated lines of code
832 unused = [] # Unused variable names
833 for value in values:
834 usedLines = []
835 lenParam = None
836 #
837 # Prefix and suffix for post processing of parameter names for struct members. Arrays of structures need special processing to include the array index in the full parameter name.
838 postProcSpec = {}
839 postProcSpec['ppp'] = '' if not structTypeName else '{postProcPrefix}'
840 postProcSpec['pps'] = '' if not structTypeName else '{postProcSuffix}'
841 postProcSpec['ppi'] = '' if not structTypeName else '{postProcInsert}'
842 #
843 # Generate the full name of the value, which will be printed in the error message, by adding the variable prefix to the value name
844 valueDisplayName = '{}{}'.format(displayNamePrefix, value.name)
845 #
846 # Check for NULL pointers, ignore the inout count parameters that
847 # will be validated with their associated array
848 if (value.ispointer or value.isstaticarray) and not value.iscount:
849 #
850 # Parameters for function argument generation
851 req = 'true' # Paramerter cannot be NULL
852 cpReq = 'true' # Count pointer cannot be NULL
853 cvReq = 'true' # Count value cannot be 0
854 lenDisplayName = None # Name of length parameter to print with validation messages; parameter name with prefix applied
855 #
856 # Generate required/optional parameter strings for the pointer and count values
857 if value.isoptional:
858 req = 'false'
859 if value.len:
860 # The parameter is an array with an explicit count parameter
861 lenParam = self.getLenParam(values, value.len)
862 lenDisplayName = '{}{}'.format(displayNamePrefix, lenParam.name)
863 if lenParam.ispointer:
864 # Count parameters that are pointers are inout
865 if type(lenParam.isoptional) is list:
866 if lenParam.isoptional[0]:
867 cpReq = 'false'
868 if lenParam.isoptional[1]:
869 cvReq = 'false'
870 else:
871 if lenParam.isoptional:
872 cpReq = 'false'
873 else:
874 if lenParam.isoptional:
875 cvReq = 'false'
876 #
877 # The parameter will not be processes when tagged as 'noautovalidity'
878 # For the pointer to struct case, the struct pointer will not be validated, but any
879 # members not tagged as 'noatuvalidity' will be validated
880 if value.noautovalidity:
881 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
882 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
883 else:
884 #
885 # If this is a pointer to a struct with an sType field, verify the type
886 if value.type in self.structTypes:
887 usedLines += self.makeStructTypeCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
888 # If this is an input handle array that is not allowed to contain NULL handles, verify that none of the handles are VK_NULL_HANDLE
889 elif value.type in self.handleTypes and value.isconst and not self.isHandleOptional(value, lenParam):
890 usedLines += self.makeHandleCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
891 elif value.type in self.flags and value.isconst:
892 usedLines += self.makeFlagsArrayCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
893 elif value.isbool and value.isconst:
894 usedLines.append('skipCall |= validate_bool32_array(report_data, "{}", {ppp}"{}"{pps}, {ppp}"{}"{pps}, {pf}{}, {pf}{}, {}, {});\n'.format(funcName, lenDisplayName, valueDisplayName, lenParam.name, value.name, cvReq, req, pf=valuePrefix, **postProcSpec))
895 elif value.israngedenum and value.isconst:
896 enumRange = self.enumRanges[value.type]
897 usedLines.append('skipCall |= validate_ranged_enum_array(report_data, "{}", {ppp}"{}"{pps}, {ppp}"{}"{pps}, "{}", {}, {}, {pf}{}, {pf}{}, {}, {});\n'.format(funcName, lenDisplayName, valueDisplayName, value.type, enumRange[0], enumRange[1], lenParam.name, value.name, cvReq, req, pf=valuePrefix, **postProcSpec))
898 elif value.name == 'pNext':
899 # We need to ignore VkDeviceCreateInfo and VkInstanceCreateInfo, as the loader manipulates them in a way that is not documented in vk.xml
900 if not structTypeName in ['VkDeviceCreateInfo', 'VkInstanceCreateInfo']:
901 usedLines += self.makeStructNextCheck(valuePrefix, value, funcName, valueDisplayName, postProcSpec)
902 else:
903 usedLines += self.makePointerCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
904 #
905 # If this is a pointer to a struct (input), see if it contains members that need to be checked
906 if value.type in self.validatedStructs and value.isconst:
907 usedLines.append(self.expandStructPointerCode(valuePrefix, value, lenParam, funcName, valueDisplayName, postProcSpec))
908 # Non-pointer types
909 else:
910 #
911 # The parameter will not be processes when tagged as 'noautovalidity'
912 # For the struct case, the struct type will not be validated, but any
913 # members not tagged as 'noatuvalidity' will be validated
914 if value.noautovalidity:
915 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
916 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
917 else:
918 if value.type in self.structTypes:
919 stype = self.structTypes[value.type]
920 usedLines.append('skipCall |= validate_struct_type(report_data, "{}", {ppp}"{}"{pps}, "{sv}", &({}{vn}), {sv}, false);\n'.format(
921 funcName, valueDisplayName, valuePrefix, vn=value.name, sv=stype.value, **postProcSpec))
922 elif value.type in self.handleTypes:
923 if not self.isHandleOptional(value, None):
924 usedLines.append('skipCall |= validate_required_handle(report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec))
925 elif value.type in self.flags:
926 flagBitsName = value.type.replace('Flags', 'FlagBits')
927 if not flagBitsName in self.flagBits:
928 usedLines.append('skipCall |= validate_reserved_flags(report_data, "{}", {ppp}"{}"{pps}, {pf}{});\n'.format(funcName, valueDisplayName, value.name, pf=valuePrefix, **postProcSpec))
929 else:
930 flagsRequired = 'false' if value.isoptional else 'true'
931 allFlagsName = 'All' + flagBitsName
932 usedLines.append('skipCall |= validate_flags(report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {pf}{}, {});\n'.format(funcName, valueDisplayName, flagBitsName, allFlagsName, value.name, flagsRequired, pf=valuePrefix, **postProcSpec))
933 elif value.isbool:
934 usedLines.append('skipCall |= validate_bool32(report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec))
935 elif value.israngedenum:
936 enumRange = self.enumRanges[value.type]
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -0700937 if value.type == "VkObjectEntryTypeNVX":
938 garbage = 2
Mark Lobodzinski85672672016-10-13 08:36:42 -0600939 usedLines.append('skipCall |= validate_ranged_enum(report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {}, {}{});\n'.format(funcName, valueDisplayName, value.type, enumRange[0], enumRange[1], valuePrefix, value.name, **postProcSpec))
940 #
941 # If this is a struct, see if it contains members that need to be checked
942 if value.type in self.validatedStructs:
943 memberNamePrefix = '{}{}.'.format(valuePrefix, value.name)
944 memberDisplayNamePrefix = '{}.'.format(valueDisplayName)
945 usedLines.append(self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, '', [], postProcSpec))
946 #
947 # Append the parameter check to the function body for the current command
948 if usedLines:
949 # Apply special conditional checks
950 if value.condition:
951 usedLines = self.genConditionalCall(valuePrefix, value.condition, usedLines)
952 lines += usedLines
953 elif not value.iscount:
954 # If no expression was generated for this value, it is unreferenced by the validation function, unless
955 # it is an array count, which is indirectly referenced for array valiadation.
956 unused.append(value.name)
957 return lines, unused
958 #
959 # Generate the struct member check code from the captured data
960 def processStructMemberData(self):
961 indent = self.incIndent(None)
962 for struct in self.structMembers:
963 #
964 # The string returned by genFuncBody will be nested in an if check for a NULL pointer, so needs its indent incremented
965 lines, unused = self.genFuncBody('{funcName}', struct.members, '{valuePrefix}', '{displayNamePrefix}', struct.name)
966 if lines:
967 self.validatedStructs[struct.name] = lines
968 #
969 # Generate the command param check code from the captured data
970 def processCmdData(self):
971 indent = self.incIndent(None)
972 for command in self.commands:
973 # Skip first parameter if it is a dispatch handle (everything except vkCreateInstance)
974 startIndex = 0 if command.name == 'vkCreateInstance' else 1
975 lines, unused = self.genFuncBody(command.name, command.params[startIndex:], '', '', None)
976 if lines:
977 cmdDef = self.getCmdDef(command) + '\n'
978 cmdDef += '{\n'
979 # Process unused parameters, Ignoring the first dispatch handle parameter, which is not
980 # processed by parameter_validation (except for vkCreateInstance, which does not have a
981 # handle as its first parameter)
982 if unused:
983 for name in unused:
984 cmdDef += indent + 'UNUSED_PARAMETER({});\n'.format(name)
985 if len(unused) > 0:
986 cmdDef += '\n'
987 cmdDef += indent + 'bool skipCall = false;\n'
988 for line in lines:
989 cmdDef += '\n'
990 if type(line) is list:
991 for sub in line:
992 cmdDef += indent + sub
993 else:
994 cmdDef += indent + line
995 cmdDef += '\n'
996 cmdDef += indent + 'return skipCall;\n'
997 cmdDef += '}\n'
998 self.appendSection('command', cmdDef)