blob: 135faee4fd65b14684361a229f0f65f75bd6c095 [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)
495 # Change to uppercase
496 value = value.upper()
497 # Add STRUCTURE_TYPE_
498 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
499 #
500 # Get the cached VkStructureType value for the specified struct typename, or generate a VkStructureType
501 # value assuming the struct is defined by a different feature
502 def getStructType(self, typename):
503 value = None
504 if typename in self.structTypes:
505 value = self.structTypes[typename].value
506 else:
507 value = self.genVkStructureType(typename)
508 self.logMsg('diag', 'ParameterValidation: Generating {} for {} structure type that was not defined by the current feature'.format(value, typename))
509 return value
510 #
511 # Retrieve the value of the len tag
512 def getLen(self, param):
513 result = None
514 len = param.attrib.get('len')
515 if len and len != 'null-terminated':
516 # For string arrays, 'len' can look like 'count,null-terminated',
517 # indicating that we have a null terminated array of strings. We
518 # strip the null-terminated from the 'len' field and only return
519 # the parameter specifying the string count
520 if 'null-terminated' in len:
521 result = len.split(',')[0]
522 else:
523 result = len
524 result = str(result).replace('::', '->')
525 return result
526 #
527 # Retrieve the type and name for a parameter
528 def getTypeNameTuple(self, param):
529 type = ''
530 name = ''
531 for elem in param:
532 if elem.tag == 'type':
533 type = noneStr(elem.text)
534 elif elem.tag == 'name':
535 name = noneStr(elem.text)
536 return (type, name)
537 #
538 # Find a named parameter in a parameter list
539 def getParamByName(self, params, name):
540 for param in params:
541 if param.name == name:
542 return param
543 return None
544 #
545 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
546 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
547 def parseLateXMath(self, source):
548 name = 'ERROR'
549 decoratedName = 'ERROR'
550 if 'mathit' in source:
551 # Matches expressions similar to 'latexmath:[$\lceil{\mathit{rasterizationSamples} \over 32}\rceil$]'
552 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)
553 if not match or match.group(1) != match.group(4):
554 raise 'Unrecognized latexmath expression'
555 name = match.group(2)
556 decoratedName = '{}({}/{})'.format(*match.group(1, 2, 3))
557 else:
558 # Matches expressions similar to 'latexmath : [$dataSize \over 4$]'
559 match = re.match(r'latexmath\s*\:\s*\[\s*\$\s*(\w+)\s*\\over\s*(\d+)\s*\$\s*\]', source)
560 name = match.group(1)
561 decoratedName = '{}/{}'.format(*match.group(1, 2))
562 return name, decoratedName
563 #
564 # Get the length paramater record for the specified parameter name
565 def getLenParam(self, params, name):
566 lenParam = None
567 if name:
568 if '->' in name:
569 # The count is obtained by dereferencing a member of a struct parameter
570 lenParam = self.CommandParam(name=name, iscount=True, ispointer=False, isbool=False, israngedenum=False, isconst=False,
571 isstaticarray=None, isoptional=False, type=None, noautovalidity=False, len=None, extstructs=None,
572 condition=None, cdecl=None)
573 elif 'latexmath' in name:
574 lenName, decoratedName = self.parseLateXMath(name)
575 lenParam = self.getParamByName(params, lenName)
576 # TODO: Zero-check the result produced by the equation?
577 # Copy the stored len parameter entry and overwrite the name with the processed latexmath equation
578 #param = self.getParamByName(params, lenName)
579 #lenParam = self.CommandParam(name=decoratedName, iscount=param.iscount, ispointer=param.ispointer,
580 # isoptional=param.isoptional, type=param.type, len=param.len,
581 # isstaticarray=param.isstaticarray, extstructs=param.extstructs,
582 # noautovalidity=True, condition=None, cdecl=param.cdecl)
583 else:
584 lenParam = self.getParamByName(params, name)
585 return lenParam
586 #
587 # Convert a vulkan.h command declaration into a parameter_validation.h definition
588 def getCmdDef(self, cmd):
589 #
590 # Strip the trailing ';' and split into individual lines
591 lines = cmd.cdecl[:-1].split('\n')
592 # Replace Vulkan prototype
593 lines[0] = 'static bool parameter_validation_' + cmd.name + '('
594 # Replace the first argument with debug_report_data, when the first
595 # argument is a handle (not vkCreateInstance)
596 reportData = ' debug_report_data*'.ljust(self.genOpts.alignFuncParam) + 'report_data,'
597 if cmd.name != 'vkCreateInstance':
598 lines[1] = reportData
599 else:
600 lines.insert(1, reportData)
601 return '\n'.join(lines)
602 #
603 # Generate the code to check for a NULL dereference before calling the
604 # validation function
605 def genCheckedLengthCall(self, name, exprs):
606 count = name.count('->')
607 if count:
608 checkedExpr = []
609 localIndent = ''
610 elements = name.split('->')
611 # Open the if expression blocks
612 for i in range(0, count):
613 checkedExpr.append(localIndent + 'if ({} != NULL) {{\n'.format('->'.join(elements[0:i+1])))
614 localIndent = self.incIndent(localIndent)
615 # Add the validation expression
616 for expr in exprs:
617 checkedExpr.append(localIndent + expr)
618 # Close the if blocks
619 for i in range(0, count):
620 localIndent = self.decIndent(localIndent)
621 checkedExpr.append(localIndent + '}\n')
622 return [checkedExpr]
623 # No if statements were required
624 return exprs
625 #
626 # Generate code to check for a specific condition before executing validation code
627 def genConditionalCall(self, prefix, condition, exprs):
628 checkedExpr = []
629 localIndent = ''
630 formattedCondition = condition.format(prefix)
631 checkedExpr.append(localIndent + 'if ({})\n'.format(formattedCondition))
632 checkedExpr.append(localIndent + '{\n')
633 localIndent = self.incIndent(localIndent)
634 for expr in exprs:
635 checkedExpr.append(localIndent + expr)
636 localIndent = self.decIndent(localIndent)
637 checkedExpr.append(localIndent + '}\n')
638 return [checkedExpr]
639 #
640 # Generate the sType check string
641 def makeStructTypeCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
642 checkExpr = []
643 stype = self.structTypes[value.type]
644 if lenValue:
645 # This is an array with a pointer to a count value
646 if lenValue.ispointer:
647 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
648 checkExpr.append('skipCall |= validate_struct_type_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {}, {});\n'.format(
649 funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec))
650 # This is an array with an integer count value
651 else:
652 checkExpr.append('skipCall |= validate_struct_type_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {});\n'.format(
653 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec))
654 # This is an individual struct
655 else:
656 checkExpr.append('skipCall |= validate_struct_type(report_data, "{}", {ppp}"{}"{pps}, "{sv}", {}{vn}, {sv}, {});\n'.format(
657 funcPrintName, valuePrintName, prefix, valueRequired, vn=value.name, sv=stype.value, **postProcSpec))
658 return checkExpr
659 #
660 # Generate the handle check string
661 def makeHandleCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
662 checkExpr = []
663 if lenValue:
664 if lenValue.ispointer:
665 # This is assumed to be an output array with a pointer to a count value
666 raise('Unsupported parameter validation case: Output handle array elements are not NULL checked')
667 else:
668 # This is an array with an integer count value
669 checkExpr.append('skipCall |= validate_handle_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {});\n'.format(
670 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
671 else:
672 # This is assumed to be an output handle pointer
673 raise('Unsupported parameter validation case: Output handles are not NULL checked')
674 return checkExpr
675 #
676 # Generate check string for an array of VkFlags values
677 def makeFlagsArrayCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
678 checkExpr = []
679 flagBitsName = value.type.replace('Flags', 'FlagBits')
680 if not flagBitsName in self.flagBits:
681 raise('Unsupported parameter validation case: array of reserved VkFlags')
682 else:
683 allFlags = 'All' + flagBitsName
684 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))
685 return checkExpr
686 #
687 # Generate pNext check string
688 def makeStructNextCheck(self, prefix, value, funcPrintName, valuePrintName, postProcSpec):
689 checkExpr = []
690 # Generate an array of acceptable VkStructureType values for pNext
691 extStructCount = 0
692 extStructVar = 'NULL'
693 extStructNames = 'NULL'
694 if value.extstructs:
695 structs = value.extstructs.split(',')
696 checkExpr.append('const VkStructureType allowedStructs[] = {' + ', '.join([self.getStructType(s) for s in structs]) + '};\n')
697 extStructCount = 'ARRAY_SIZE(allowedStructs)'
698 extStructVar = 'allowedStructs'
699 extStructNames = '"' + ', '.join(structs) + '"'
700 checkExpr.append('skipCall |= validate_struct_pnext(report_data, "{}", {ppp}"{}"{pps}, {}, {}{}, {}, {}, GeneratedHeaderVersion);\n'.format(
701 funcPrintName, valuePrintName, extStructNames, prefix, value.name, extStructCount, extStructVar, **postProcSpec))
702 return checkExpr
703 #
704 # Generate the pointer check string
705 def makePointerCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
706 checkExpr = []
707 if lenValue:
708 # This is an array with a pointer to a count value
709 if lenValue.ispointer:
710 # If count and array parameters are optional, there will be no validation
711 if valueRequired == 'true' or lenPtrRequired == 'true' or lenValueRequired == 'true':
712 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
713 checkExpr.append('skipCall |= validate_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {});\n'.format(
714 funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
715 # This is an array with an integer count value
716 else:
717 # If count and array parameters are optional, there will be no validation
718 if valueRequired == 'true' or lenValueRequired == 'true':
719 # Arrays of strings receive special processing
720 validationFuncName = 'validate_array' if value.type != 'char' else 'validate_string_array'
721 checkExpr.append('skipCall |= {}(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {});\n'.format(
722 validationFuncName, funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
723 if checkExpr:
724 if lenValue and ('->' in lenValue.name):
725 # Add checks to ensure the validation call does not dereference a NULL pointer to obtain the count
726 checkExpr = self.genCheckedLengthCall(lenValue.name, checkExpr)
727 # This is an individual struct that is not allowed to be NULL
728 elif not value.isoptional:
729 # Function pointers need a reinterpret_cast to void*
730 if value.type[:4] == 'PFN_':
731 checkExpr.append('skipCall |= validate_required_pointer(report_data, "{}", {ppp}"{}"{pps}, reinterpret_cast<const void*>({}{}));\n'.format(funcPrintName, valuePrintName, prefix, value.name, **postProcSpec))
732 else:
733 checkExpr.append('skipCall |= validate_required_pointer(report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcPrintName, valuePrintName, prefix, value.name, **postProcSpec))
734 return checkExpr
735 #
736 # Process struct member validation code, performing name suibstitution if required
737 def processStructMemberCode(self, line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec):
738 # Build format specifier list
739 kwargs = {}
740 if '{postProcPrefix}' in line:
741 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
742 if type(memberDisplayNamePrefix) is tuple:
743 kwargs['postProcPrefix'] = 'ParameterName('
744 else:
745 kwargs['postProcPrefix'] = postProcSpec['ppp']
746 if '{postProcSuffix}' in line:
747 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
748 if type(memberDisplayNamePrefix) is tuple:
749 kwargs['postProcSuffix'] = ', ParameterName::IndexVector{{ {}{} }})'.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
750 else:
751 kwargs['postProcSuffix'] = postProcSpec['pps']
752 if '{postProcInsert}' in line:
753 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
754 if type(memberDisplayNamePrefix) is tuple:
755 kwargs['postProcInsert'] = '{}{}, '.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
756 else:
757 kwargs['postProcInsert'] = postProcSpec['ppi']
758 if '{funcName}' in line:
759 kwargs['funcName'] = funcName
760 if '{valuePrefix}' in line:
761 kwargs['valuePrefix'] = memberNamePrefix
762 if '{displayNamePrefix}' in line:
763 # Check for a tuple that includes a format string and format parameters to be used with the ParameterName class
764 if type(memberDisplayNamePrefix) is tuple:
765 kwargs['displayNamePrefix'] = memberDisplayNamePrefix[0]
766 else:
767 kwargs['displayNamePrefix'] = memberDisplayNamePrefix
768
769 if kwargs:
770 # Need to escape the C++ curly braces
771 if 'IndexVector' in line:
772 line = line.replace('IndexVector{ ', 'IndexVector{{ ')
773 line = line.replace(' }),', ' }}),')
774 return line.format(**kwargs)
775 return line
776 #
777 # Process struct validation code for inclusion in function or parent struct validation code
778 def expandStructCode(self, lines, funcName, memberNamePrefix, memberDisplayNamePrefix, indent, output, postProcSpec):
779 for line in lines:
780 if output:
781 output[-1] += '\n'
782 if type(line) is list:
783 for sub in line:
784 output.append(self.processStructMemberCode(indent + sub, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
785 else:
786 output.append(self.processStructMemberCode(indent + line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
787 return output
788 #
789 # Process struct pointer/array validation code, perfoeming name substitution if required
790 def expandStructPointerCode(self, prefix, value, lenValue, funcName, valueDisplayName, postProcSpec):
791 expr = []
792 expr.append('if ({}{} != NULL)\n'.format(prefix, value.name))
793 expr.append('{')
794 indent = self.incIndent(None)
795 if lenValue:
796 # Need to process all elements in the array
797 indexName = lenValue.name.replace('Count', 'Index')
798 expr[-1] += '\n'
799 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < {}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
800 expr.append(indent + '{')
801 indent = self.incIndent(indent)
802 # Prefix for value name to display in error message
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -0700803 if value.ispointer == 2:
804 memberNamePrefix = '{}{}[{}]->'.format(prefix, value.name, indexName)
805 memberDisplayNamePrefix = ('{}[%i]->'.format(valueDisplayName), indexName)
806 else:
807 memberNamePrefix = '{}{}[{}].'.format(prefix, value.name, indexName)
808 memberDisplayNamePrefix = ('{}[%i].'.format(valueDisplayName), indexName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600809 else:
810 memberNamePrefix = '{}{}->'.format(prefix, value.name)
811 memberDisplayNamePrefix = '{}->'.format(valueDisplayName)
812 #
813 # Expand the struct validation lines
814 expr = self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, indent, expr, postProcSpec)
815 #
816 if lenValue:
817 # Close if and for scopes
818 indent = self.decIndent(indent)
819 expr.append(indent + '}\n')
820 expr.append('}\n')
821 return expr
822 #
823 # Generate the parameter checking code
824 def genFuncBody(self, funcName, values, valuePrefix, displayNamePrefix, structTypeName):
825 lines = [] # Generated lines of code
826 unused = [] # Unused variable names
827 for value in values:
828 usedLines = []
829 lenParam = None
830 #
831 # 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.
832 postProcSpec = {}
833 postProcSpec['ppp'] = '' if not structTypeName else '{postProcPrefix}'
834 postProcSpec['pps'] = '' if not structTypeName else '{postProcSuffix}'
835 postProcSpec['ppi'] = '' if not structTypeName else '{postProcInsert}'
836 #
837 # Generate the full name of the value, which will be printed in the error message, by adding the variable prefix to the value name
838 valueDisplayName = '{}{}'.format(displayNamePrefix, value.name)
839 #
840 # Check for NULL pointers, ignore the inout count parameters that
841 # will be validated with their associated array
842 if (value.ispointer or value.isstaticarray) and not value.iscount:
843 #
844 # Parameters for function argument generation
845 req = 'true' # Paramerter cannot be NULL
846 cpReq = 'true' # Count pointer cannot be NULL
847 cvReq = 'true' # Count value cannot be 0
848 lenDisplayName = None # Name of length parameter to print with validation messages; parameter name with prefix applied
849 #
850 # Generate required/optional parameter strings for the pointer and count values
851 if value.isoptional:
852 req = 'false'
853 if value.len:
854 # The parameter is an array with an explicit count parameter
855 lenParam = self.getLenParam(values, value.len)
856 lenDisplayName = '{}{}'.format(displayNamePrefix, lenParam.name)
857 if lenParam.ispointer:
858 # Count parameters that are pointers are inout
859 if type(lenParam.isoptional) is list:
860 if lenParam.isoptional[0]:
861 cpReq = 'false'
862 if lenParam.isoptional[1]:
863 cvReq = 'false'
864 else:
865 if lenParam.isoptional:
866 cpReq = 'false'
867 else:
868 if lenParam.isoptional:
869 cvReq = 'false'
870 #
871 # The parameter will not be processes when tagged as 'noautovalidity'
872 # For the pointer to struct case, the struct pointer will not be validated, but any
873 # members not tagged as 'noatuvalidity' will be validated
874 if value.noautovalidity:
875 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
876 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
877 else:
878 #
879 # If this is a pointer to a struct with an sType field, verify the type
880 if value.type in self.structTypes:
881 usedLines += self.makeStructTypeCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
882 # 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
883 elif value.type in self.handleTypes and value.isconst and not self.isHandleOptional(value, lenParam):
884 usedLines += self.makeHandleCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
885 elif value.type in self.flags and value.isconst:
886 usedLines += self.makeFlagsArrayCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
887 elif value.isbool and value.isconst:
888 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))
889 elif value.israngedenum and value.isconst:
890 enumRange = self.enumRanges[value.type]
891 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))
892 elif value.name == 'pNext':
893 # We need to ignore VkDeviceCreateInfo and VkInstanceCreateInfo, as the loader manipulates them in a way that is not documented in vk.xml
894 if not structTypeName in ['VkDeviceCreateInfo', 'VkInstanceCreateInfo']:
895 usedLines += self.makeStructNextCheck(valuePrefix, value, funcName, valueDisplayName, postProcSpec)
896 else:
897 usedLines += self.makePointerCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
898 #
899 # If this is a pointer to a struct (input), see if it contains members that need to be checked
900 if value.type in self.validatedStructs and value.isconst:
901 usedLines.append(self.expandStructPointerCode(valuePrefix, value, lenParam, funcName, valueDisplayName, postProcSpec))
902 # Non-pointer types
903 else:
904 #
905 # The parameter will not be processes when tagged as 'noautovalidity'
906 # For the struct case, the struct type will not be validated, but any
907 # members not tagged as 'noatuvalidity' will be validated
908 if value.noautovalidity:
909 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
910 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
911 else:
912 if value.type in self.structTypes:
913 stype = self.structTypes[value.type]
914 usedLines.append('skipCall |= validate_struct_type(report_data, "{}", {ppp}"{}"{pps}, "{sv}", &({}{vn}), {sv}, false);\n'.format(
915 funcName, valueDisplayName, valuePrefix, vn=value.name, sv=stype.value, **postProcSpec))
916 elif value.type in self.handleTypes:
917 if not self.isHandleOptional(value, None):
918 usedLines.append('skipCall |= validate_required_handle(report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec))
919 elif value.type in self.flags:
920 flagBitsName = value.type.replace('Flags', 'FlagBits')
921 if not flagBitsName in self.flagBits:
922 usedLines.append('skipCall |= validate_reserved_flags(report_data, "{}", {ppp}"{}"{pps}, {pf}{});\n'.format(funcName, valueDisplayName, value.name, pf=valuePrefix, **postProcSpec))
923 else:
924 flagsRequired = 'false' if value.isoptional else 'true'
925 allFlagsName = 'All' + flagBitsName
926 usedLines.append('skipCall |= validate_flags(report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {pf}{}, {});\n'.format(funcName, valueDisplayName, flagBitsName, allFlagsName, value.name, flagsRequired, pf=valuePrefix, **postProcSpec))
927 elif value.isbool:
928 usedLines.append('skipCall |= validate_bool32(report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec))
929 elif value.israngedenum:
930 enumRange = self.enumRanges[value.type]
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -0700931 if value.type == "VkObjectEntryTypeNVX":
932 garbage = 2
Mark Lobodzinski85672672016-10-13 08:36:42 -0600933 usedLines.append('skipCall |= validate_ranged_enum(report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {}, {}{});\n'.format(funcName, valueDisplayName, value.type, enumRange[0], enumRange[1], valuePrefix, value.name, **postProcSpec))
934 #
935 # If this is a struct, see if it contains members that need to be checked
936 if value.type in self.validatedStructs:
937 memberNamePrefix = '{}{}.'.format(valuePrefix, value.name)
938 memberDisplayNamePrefix = '{}.'.format(valueDisplayName)
939 usedLines.append(self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, '', [], postProcSpec))
940 #
941 # Append the parameter check to the function body for the current command
942 if usedLines:
943 # Apply special conditional checks
944 if value.condition:
945 usedLines = self.genConditionalCall(valuePrefix, value.condition, usedLines)
946 lines += usedLines
947 elif not value.iscount:
948 # If no expression was generated for this value, it is unreferenced by the validation function, unless
949 # it is an array count, which is indirectly referenced for array valiadation.
950 unused.append(value.name)
951 return lines, unused
952 #
953 # Generate the struct member check code from the captured data
954 def processStructMemberData(self):
955 indent = self.incIndent(None)
956 for struct in self.structMembers:
957 #
958 # The string returned by genFuncBody will be nested in an if check for a NULL pointer, so needs its indent incremented
959 lines, unused = self.genFuncBody('{funcName}', struct.members, '{valuePrefix}', '{displayNamePrefix}', struct.name)
960 if lines:
961 self.validatedStructs[struct.name] = lines
962 #
963 # Generate the command param check code from the captured data
964 def processCmdData(self):
965 indent = self.incIndent(None)
966 for command in self.commands:
967 # Skip first parameter if it is a dispatch handle (everything except vkCreateInstance)
968 startIndex = 0 if command.name == 'vkCreateInstance' else 1
969 lines, unused = self.genFuncBody(command.name, command.params[startIndex:], '', '', None)
970 if lines:
971 cmdDef = self.getCmdDef(command) + '\n'
972 cmdDef += '{\n'
973 # Process unused parameters, Ignoring the first dispatch handle parameter, which is not
974 # processed by parameter_validation (except for vkCreateInstance, which does not have a
975 # handle as its first parameter)
976 if unused:
977 for name in unused:
978 cmdDef += indent + 'UNUSED_PARAMETER({});\n'.format(name)
979 if len(unused) > 0:
980 cmdDef += '\n'
981 cmdDef += indent + 'bool skipCall = false;\n'
982 for line in lines:
983 cmdDef += '\n'
984 if type(line) is list:
985 for sub in line:
986 cmdDef += indent + sub
987 else:
988 cmdDef += indent + line
989 cmdDef += '\n'
990 cmdDef += indent + 'return skipCall;\n'
991 cmdDef += '}\n'
992 self.appendSection('command', cmdDef)