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