1#!/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: Tobin Ehlis <tobine@google.com>
21# Author: Mark Lobodzinski <mark@lunarg.com>
22
23import os,re,sys
24import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
27
28# UniqueObjectsGeneratorOptions - subclass of GeneratorOptions.
29#
30# Adds options used by UniqueObjectsOutputGenerator objects during
31# unique objects 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 UniqueObjectsGeneratorOptions(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# UniqueObjectsOutputGenerator - subclass of OutputGenerator.
102# Generates unique objects layer non-dispatchable handle-wrapping code.
103#
104# ---- methods ----
105# UniqueObjectsOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
106# ---- methods overriding base class ----
107# beginFile(genOpts)
108# endFile()
109# beginFeature(interface, emit)
110# endFeature()
111# genCmd(cmdinfo)
112# genStruct()
113# genType()
114class UniqueObjectsOutputGenerator(OutputGenerator):
115    """Generate UniqueObjects code based on XML element attributes"""
116    # This is an ordered list of sections in the header file.
117    ALL_SECTIONS = ['command']
118    def __init__(self,
119                 errFile = sys.stderr,
120                 warnFile = sys.stderr,
121                 diagFile = sys.stdout):
122        OutputGenerator.__init__(self, errFile, warnFile, diagFile)
123        self.INDENT_SPACES = 4
124        # Commands to ignore
125        self.intercepts = []
126        # Commands which are not autogenerated but still intercepted
127        self.no_autogen_list = [
128            'vkGetDeviceProcAddr',
129            'vkGetInstanceProcAddr',
130            'vkCreateInstance',
131            'vkDestroyInstance',
132            'vkCreateDevice',
133            'vkDestroyDevice',
134            'vkAllocateMemory',
135            'vkCreateComputePipelines',
136            'vkCreateGraphicsPipelines',
137            'vkCreateSwapchainKHR',
138            'vkGetSwapchainImagesKHR',
139            'vkEnumerateInstanceLayerProperties',
140            'vkEnumerateDeviceLayerProperties',
141            'vkEnumerateInstanceExtensionProperties',
142            ]
143        # Commands shadowed by interface functions and are not implemented
144        self.interface_functions = [
145            'vkGetPhysicalDeviceDisplayPropertiesKHR',
146            'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
147            'vkGetDisplayPlaneSupportedDisplaysKHR',
148            'vkGetDisplayModePropertiesKHR',
149            # DebugReport APIs are hooked, but handled separately in the source file
150            'vkCreateDebugReportCallbackEXT',
151            'vkDestroyDebugReportCallbackEXT',
152            'vkDebugReportMessageEXT',
153            ]
154        self.headerVersion = None
155        # Internal state - accumulators for different inner block text
156        self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
157        self.structNames = []                             # List of Vulkan struct typenames
158        self.structTypes = dict()                         # Map of Vulkan struct typename to required VkStructureType
159        self.handleTypes = set()                          # Set of handle type names
160        self.commands = []                                # List of CommandData records for all Vulkan commands
161        self.structMembers = []                           # List of StructMemberData records for all Vulkan structs
162        self.flags = set()                                # Map of flags typenames
163        # Named tuples to store struct and command data
164        self.StructType = namedtuple('StructType', ['name', 'value'])
165        self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy'])
166        self.CommandData = namedtuple('CommandData', ['name', 'return_type', 'params', 'cdecl'])
167        self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
168    #
169    def incIndent(self, indent):
170        inc = ' ' * self.INDENT_SPACES
171        if indent:
172            return indent + inc
173        return inc
174    #
175    def decIndent(self, indent):
176        if indent and (len(indent) > self.INDENT_SPACES):
177            return indent[:-self.INDENT_SPACES]
178        return ''
179    #
180    # Override makeProtoName to drop the "vk" prefix
181    def makeProtoName(self, name, tail):
182        return self.genOpts.apientry + name[2:] + tail
183    #
184    # Check if the parameter passed in is a pointer to an array
185    def paramIsArray(self, param):
186        return param.attrib.get('len') is not None
187    #
188    def beginFile(self, genOpts):
189        OutputGenerator.beginFile(self, genOpts)
190        # User-supplied prefix text, if any (list of strings)
191        if (genOpts.prefixText):
192            for s in genOpts.prefixText:
193                write(s, file=self.outFile)
194        # Namespace
195        self.newline()
196        write('namespace unique_objects {', file = self.outFile)
197    #
198    def endFile(self):
199        self.newline()
200        # Record intercepted procedures
201        write('// intercepts', file=self.outFile)
202        write('struct { const char* name; PFN_vkVoidFunction pFunc;} procmap[] = {', file=self.outFile)
203        write('\n'.join(self.intercepts), file=self.outFile)
204        write('};\n', file=self.outFile)
205        self.newline()
206        write('} // namespace unique_objects', file=self.outFile)
207        # Finish processing in superclass
208        OutputGenerator.endFile(self)
209    #
210    def beginFeature(self, interface, emit):
211        # Start processing in superclass
212        OutputGenerator.beginFeature(self, interface, emit)
213        self.headerVersion = None
214        self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
215        self.structNames = []
216        self.structTypes = dict()
217        self.handleTypes = set()
218        self.commands = []
219        self.structMembers = []
220        self.cmdMembers = []
221        self.flags = set()
222        self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
223        self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
224    #
225    def endFeature(self):
226        # Actually write the interface to the output file.
227        if (self.emit):
228            self.newline()
229            if (self.featureExtraProtect != None):
230                write('#ifdef', self.featureExtraProtect, file=self.outFile)
231            # Write the unique_objects code to the file
232            if (self.sections['command']):
233                if (self.genOpts.protectProto):
234                    write(self.genOpts.protectProto,
235                          self.genOpts.protectProtoStr, file=self.outFile)
236                write('\n'.join(self.sections['command']), end='', file=self.outFile)
237            if (self.featureExtraProtect != None):
238                write('\n#endif //', self.featureExtraProtect, file=self.outFile)
239            else:
240                self.newline()
241        # Finish processing in superclass
242        OutputGenerator.endFeature(self)
243    #
244    def genType(self, typeinfo, name):
245        OutputGenerator.genType(self, typeinfo, name)
246        typeElem = typeinfo.elem
247        # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
248        # Otherwise, emit the tag text.
249        category = typeElem.get('category')
250        if (category == 'struct' or category == 'union'):
251            self.structNames.append(name)
252            self.genStruct(typeinfo, name)
253    #
254    # Append a definition to the specified section
255    def appendSection(self, section, text):
256        # self.sections[section].append('SECTION: ' + section + '\n')
257        self.sections[section].append(text)
258    #
259    # Check if the parameter passed in is a pointer
260    def paramIsPointer(self, param):
261        ispointer = False
262        for elem in param:
263            if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
264                ispointer = True
265        return ispointer
266    #
267    # Get the category of a type
268    def getTypeCategory(self, typename):
269        types = self.registry.tree.findall("types/type")
270        for elem in types:
271            if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
272                return elem.attrib.get('category')
273    #
274    # Check if a parent object is dispatchable or not
275    def isHandleTypeNonDispatchable(self, handletype):
276        handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
277        if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
278            return True
279        else:
280            return False
281    #
282    # Retrieve the type and name for a parameter
283    def getTypeNameTuple(self, param):
284        type = ''
285        name = ''
286        for elem in param:
287            if elem.tag == 'type':
288                type = noneStr(elem.text)
289            elif elem.tag == 'name':
290                name = noneStr(elem.text)
291        return (type, name)
292    #
293    # Retrieve the value of the len tag
294    def getLen(self, param):
295        result = None
296        len = param.attrib.get('len')
297        if len and len != 'null-terminated':
298            # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
299            # have a null terminated array of strings.  We strip the null-terminated from the
300            # 'len' field and only return the parameter specifying the string count
301            if 'null-terminated' in len:
302                result = len.split(',')[0]
303            else:
304                result = len
305            # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
306            result = str(result).replace('::', '->')
307        return result
308    #
309    # Generate a VkStructureType based on a structure typename
310    def genVkStructureType(self, typename):
311        # Add underscore between lowercase then uppercase
312        value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
313        # Change to uppercase
314        value = value.upper()
315        # Add STRUCTURE_TYPE_
316        return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
317    #
318    # Struct parameter check generation.
319    # This is a special case of the <type> tag where the contents are interpreted as a set of
320    # <member> tags instead of freeform C type declarations. The <member> tags are just like
321    # <param> tags - they are a declaration of a struct or union member. Only simple member
322    # declarations are supported (no nested structs etc.)
323    def genStruct(self, typeinfo, typeName):
324        OutputGenerator.genStruct(self, typeinfo, typeName)
325        members = typeinfo.elem.findall('.//member')
326        # Iterate over members once to get length parameters for arrays
327        lens = set()
328        for member in members:
329            len = self.getLen(member)
330            if len:
331                lens.add(len)
332        # Generate member info
333        membersInfo = []
334        for member in members:
335            # Get the member's type and name
336            info = self.getTypeNameTuple(member)
337            type = info[0]
338            name = info[1]
339            cdecl = self.makeCParamDecl(member, 0)
340            # Process VkStructureType
341            if type == 'VkStructureType':
342                # Extract the required struct type value from the comments
343                # embedded in the original text defining the 'typeinfo' element
344                rawXml = etree.tostring(typeinfo.elem).decode('ascii')
345                result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
346                if result:
347                    value = result.group(0)
348                else:
349                    value = self.genVkStructureType(typeName)
350                # Store the required type value
351                self.structTypes[typeName] = self.StructType(name=name, value=value)
352            # Store pointer/array/string info
353            membersInfo.append(self.CommandParam(type=type,
354                                                 name=name,
355                                                 ispointer=self.paramIsPointer(member),
356                                                 isconst=True if 'const' in cdecl else False,
357                                                 iscount=True if name in lens else False,
358                                                 len=self.getLen(member),
359                                                 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
360                                                 cdecl=cdecl,
361                                                 islocal=False,
362                                                 iscreate=False,
363                                                 isdestroy=False))
364        self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
365    #
366    # Insert a lock_guard line
367    def lock_guard(self, indent):
368        return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
369    #
370    # Determine if a struct has an NDO as a member or an embedded member
371    def struct_contains_ndo(self, struct_item):
372        struct_member_dict = dict(self.structMembers)
373        struct_members = struct_member_dict[struct_item]
374
375        for member in struct_members:
376            if self.isHandleTypeNonDispatchable(member.type):
377                return True
378            elif member.type in struct_member_dict:
379                if self.struct_contains_ndo(member.type) == True:
380                    return True
381        return False
382    #
383    # Return list of struct members which contain, or which sub-structures contain
384    # an NDO in a given list of parameters or members
385    def getParmeterStructsWithNdos(self, item_list):
386        struct_list = set()
387        for item in item_list:
388            paramtype = item.find('type')
389            typecategory = self.getTypeCategory(paramtype.text)
390            if typecategory == 'struct':
391                if self.struct_contains_ndo(paramtype.text) == True:
392                    struct_list.add(item)
393        return struct_list
394    #
395    # Return list of non-dispatchable objects from a given list of parameters or members
396    def getNdosInParameterList(self, item_list, create_func):
397        ndo_list = set()
398        if create_func == True:
399            member_list = item_list[0:-1]
400        else:
401            member_list = item_list
402        for item in member_list:
403            if self.isHandleTypeNonDispatchable(paramtype.text):
404                ndo_list.add(item)
405        return ndo_list
406    #
407    # Generate source for creating a non-dispatchable object
408    def generate_create_ndo_code(self, indent, proto, params, cmd_info):
409        create_ndo_code = ''
410        if True in [create_txt in proto.text for create_txt in ['Create', 'Allocate']]:
411            handle_type = params[-1].find('type')
412            if self.isHandleTypeNonDispatchable(handle_type.text):
413                # Check for special case where multiple handles are returned
414                ndo_array = False
415                if cmd_info[-1].len is not None:
416                    ndo_array = True;
417                handle_name = params[-1].find('name')
418                create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
419                indent = self.incIndent(indent)
420                create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
421                ndo_dest = '*%s' % handle_name.text
422                if ndo_array == True:
423                    create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
424                    indent = self.incIndent(indent)
425                    ndo_dest = '%s[index0]' % cmd_info[-1].name
426                create_ndo_code += '%suint64_t unique_id = global_unique_id++;\n' % (indent)
427                create_ndo_code += '%sdev_data->unique_id_mapping[unique_id] = reinterpret_cast<uint64_t &>(%s);\n' % (indent, ndo_dest)
428                create_ndo_code += '%s%s = reinterpret_cast<%s&>(unique_id);\n' % (indent, ndo_dest, handle_type.text)
429                if ndo_array == True:
430                    indent = self.decIndent(indent)
431                    create_ndo_code += '%s}\n' % indent
432                indent = self.decIndent(indent)
433                create_ndo_code += '%s}\n' % (indent)
434        return create_ndo_code
435    #
436    # Generate source for destroying a non-dispatchable object
437    def generate_destroy_ndo_code(self, indent, proto, cmd_info):
438        destroy_ndo_code = ''
439        ndo_array = False
440        if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
441            # Check for special case where multiple handles are returned
442            if cmd_info[-1].len is not None:
443                ndo_array = True;
444                param = -1
445            else:
446                param = -2
447            if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
448                if ndo_array == True:
449                    # This API is freeing an array of handles.  Remove them from the unique_id map.
450                    destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
451                    indent = self.incIndent(indent)
452                    destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
453                    destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
454                    indent = self.incIndent(indent)
455                    destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
456                    destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
457                    destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(unique_id);\n' % (indent)
458                    indent = self.decIndent(indent);
459                    destroy_ndo_code += '%s}\n' % indent
460                    indent = self.decIndent(indent);
461                    destroy_ndo_code += '%s}\n' % indent
462                else:
463                    # Remove a single handle from the map
464                    destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
465                    destroy_ndo_code += '%suint64_t %s_id = reinterpret_cast<uint64_t &>(%s);\n' % (indent, cmd_info[param].name, cmd_info[param].name)
466                    destroy_ndo_code += '%s%s = (%s)dev_data->unique_id_mapping[%s_id];\n' % (indent, cmd_info[param].name, cmd_info[param].type, cmd_info[param].name)
467                    destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
468                    destroy_ndo_code += '%slock.unlock();\n' % (indent)
469        return ndo_array, destroy_ndo_code
470
471    #
472    # Clean up local declarations
473    def cleanUpLocalDeclarations(self, indent, prefix, name, len):
474        cleanup = '%sif (local_%s%s)\n' % (indent, prefix, name)
475        if len is not None:
476            cleanup += '%s    delete[] local_%s%s;\n' % (indent, prefix, name)
477        else:
478            cleanup += '%s    delete local_%s%s;\n' % (indent, prefix, name)
479        return cleanup
480    #
481    # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
482    def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
483        decl_code = ''
484        pre_call_code = ''
485        post_call_code = ''
486        if ndo_count is not None:
487            if top_level == True:
488                decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
489            pre_call_code += '%s    if (%s%s) {\n' % (indent, prefix, ndo_name)
490            indent = self.incIndent(indent)
491            if top_level == True:
492                pre_call_code += '%s    local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
493                pre_call_code += '%s    for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
494                indent = self.incIndent(indent)
495                pre_call_code += '%s    local_%s%s[%s] = (%s)dev_data->unique_id_mapping[reinterpret_cast<const uint64_t &>(%s[%s])];\n' % (indent, prefix, ndo_name, index, ndo_type, ndo_name, index)
496            else:
497                pre_call_code += '%s    for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
498                indent = self.incIndent(indent)
499                pre_call_code += '%s    %s%s[%s] = (%s)dev_data->unique_id_mapping[reinterpret_cast<const uint64_t &>(%s%s[%s])];\n' % (indent, prefix, ndo_name, index, ndo_type, prefix, ndo_name, index)
500            indent = self.decIndent(indent)
501            pre_call_code += '%s    }\n' % indent
502            indent = self.decIndent(indent)
503            pre_call_code += '%s    }\n' % indent
504            if top_level == True:
505                post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
506                indent = self.incIndent(indent)
507                post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
508        else:
509            if top_level == True:
510                if (destroy_func == False) or (destroy_array == True):       #### LUGMAL This line needs to be skipped for destroy_ndo and not destroy_array
511                    pre_call_code += '%s    %s = (%s)dev_data->unique_id_mapping[reinterpret_cast<uint64_t &>(%s)];\n' % (indent, ndo_name, ndo_type, ndo_name)
512            else:
513                # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
514                # as part of the string and explicitly print it
515                fix = str(prefix).strip('local_');
516                pre_call_code += '%s    if (%s%s) {\n' % (indent, fix, ndo_name)
517                indent = self.incIndent(indent)
518                pre_call_code += '%s    %s%s = (%s)dev_data->unique_id_mapping[reinterpret_cast<const uint64_t &>(%s%s)];\n' % (indent, prefix, ndo_name, ndo_type, fix, ndo_name)
519                indent = self.decIndent(indent)
520                pre_call_code += '%s    }\n' % indent
521        return decl_code, pre_call_code, post_call_code
522    #
523    # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
524    # create_func means that this is API creates or allocates NDOs
525    # destroy_func indicates that this API destroys or frees NDOs
526    # destroy_array means that the destroy_func operated on an array of NDOs
527    def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
528        decls = ''
529        pre_code = ''
530        post_code = ''
531        struct_member_dict = dict(self.structMembers)
532        index = 'index%s' % str(array_index)
533        array_index += 1
534        # Process any NDOs in this structure and recurse for any sub-structs in this struct
535        for member in members:
536            # Handle NDOs
537            if self.isHandleTypeNonDispatchable(member.type) == True:
538                count_name = member.len
539                if (count_name is not None):
540                    if first_level_param == False:
541                        count_name = '%s%s' % (prefix, member.len)
542
543                if (first_level_param == False) or (create_func == False):
544                    (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
545                    decls += tmp_decl
546                    pre_code += tmp_pre
547                    post_code += tmp_post
548            # Handle Structs that contain NDOs at some level
549            elif member.type in struct_member_dict:
550                # All structs at first level will have an NDO
551                if self.struct_contains_ndo(member.type) == True:
552                    struct_info = struct_member_dict[member.type]
553                    # Struct Array
554                    if member.len is not None:
555                        # Update struct prefix
556                        if first_level_param == True:
557                            new_prefix = 'local_%s' % member.name
558                            # Declare safe_VarType for struct
559                            decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix)
560                        else:
561                            new_prefix = '%s%s' % (prefix, member.name)
562                        pre_code += '%s    if (%s%s) {\n' % (indent, prefix, member.name)
563                        indent = self.incIndent(indent)
564                        if first_level_param == True:
565                            pre_code += '%s    %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len)
566                        pre_code += '%s    for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
567                        indent = self.incIndent(indent)
568                        if first_level_param == True:
569                            pre_code += '%s    %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index)
570                        local_prefix = '%s[%s].' % (new_prefix, index)
571                        # Process sub-structs in this struct
572                        (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False)
573                        decls += tmp_decl
574                        pre_code += tmp_pre
575                        post_code += tmp_post
576                        indent = self.decIndent(indent)
577                        pre_code += '%s    }\n' % indent
578                        indent = self.decIndent(indent)
579                        pre_code += '%s    }\n' % indent
580                        if first_level_param == True:
581                            post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len)
582                    # Single Struct
583                    else:
584                        # Update struct prefix
585                        if first_level_param == True:
586                            new_prefix = 'local_%s->' % member.name
587                            decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name)
588                        else:
589                            new_prefix = '%s%s->' % (prefix, member.name)
590                        # Declare safe_VarType for struct
591                        pre_code += '%s    if (%s%s) {\n' % (indent, prefix, member.name)
592                        indent = self.incIndent(indent)
593                        if first_level_param == True:
594                            pre_code += '%s    local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name)
595                        # Process sub-structs in this struct
596                        (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
597                        decls += tmp_decl
598                        pre_code += tmp_pre
599                        post_code += tmp_post
600                        indent = self.decIndent(indent)
601                        pre_code += '%s    }\n' % indent
602                        if first_level_param == True:
603                            post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len)
604        return decls, pre_code, post_code
605    #
606    # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
607    def generate_wrapping_code(self, cmd):
608        indent = '    '
609        proto = cmd.find('proto/name')
610        params = cmd.findall('param')
611        if proto.text is not None:
612            cmd_member_dict = dict(self.cmdMembers)
613            cmd_info = cmd_member_dict[proto.text]
614            # Handle ndo create/allocate operations
615            if cmd_info[0].iscreate:
616                create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
617            else:
618                create_ndo_code = ''
619            # Handle ndo destroy/free operations
620            if cmd_info[0].isdestroy:
621                (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
622            else:
623                destroy_array = False
624                destroy_ndo_code = ''
625            paramdecl = ''
626            param_pre_code = ''
627            param_post_code = ''
628            create_func = True if create_ndo_code else False
629            destroy_func = True if destroy_ndo_code else False
630            (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
631            param_post_code += create_ndo_code
632            if destroy_ndo_code:
633                if destroy_array == True:
634                    param_post_code += destroy_ndo_code
635                else:
636                    param_pre_code += destroy_ndo_code
637            if param_pre_code:
638                if (not destroy_func) or (destroy_array):
639                    param_pre_code = '%s{\n%s%s%s%s}\n' % ('    ', indent, self.lock_guard(indent), param_pre_code, indent)
640        return paramdecl, param_pre_code, param_post_code
641    #
642    # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
643    def genCmd(self, cmdinfo, cmdname):
644        if cmdname in self.interface_functions:
645            return
646        if cmdname in self.no_autogen_list:
647            decls = self.makeCDecls(cmdinfo.elem)
648            self.appendSection('command', '')
649            self.appendSection('command', '// Declare only')
650            self.appendSection('command', decls[0])
651            self.intercepts += [ '    {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ]
652            return
653        # Add struct-member type information to command parameter information
654        OutputGenerator.genCmd(self, cmdinfo, cmdname)
655        members = cmdinfo.elem.findall('.//param')
656        # Iterate over members once to get length parameters for arrays
657        lens = set()
658        for member in members:
659            len = self.getLen(member)
660            if len:
661                lens.add(len)
662        struct_member_dict = dict(self.structMembers)
663        # Generate member info
664        membersInfo = []
665        for member in members:
666            # Get type and name of member
667            info = self.getTypeNameTuple(member)
668            type = info[0]
669            name = info[1]
670            cdecl = self.makeCParamDecl(member, 0)
671            # Check for parameter name in lens set
672            iscount = True if name in lens else False
673            len = self.getLen(member)
674            isconst = True if 'const' in cdecl else False
675            ispointer = self.paramIsPointer(member)
676            # Mark param as local if it is an array of NDOs
677            islocal = False;
678            if self.isHandleTypeNonDispatchable(type) == True:
679                if (len is not None) and (isconst == True):
680                    islocal = True
681            # Or if it's a struct that contains an NDO
682            elif type in struct_member_dict:
683                if self.struct_contains_ndo(type) == True:
684                    islocal = True
685
686            isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
687            iscreate = True if True in [create_txt in cmdname for create_txt in ['Create', 'Allocate']] else False
688
689            membersInfo.append(self.CommandParam(type=type,
690                                                 name=name,
691                                                 ispointer=ispointer,
692                                                 isconst=isconst,
693                                                 iscount=iscount,
694                                                 len=len,
695                                                 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
696                                                 cdecl=cdecl,
697                                                 islocal=islocal,
698                                                 iscreate=iscreate,
699                                                 isdestroy=isdestroy))
700        self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
701        # Generate NDO wrapping/unwrapping code for all parameters
702        (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
703        # If API doesn't contain an NDO's, don't fool with it
704        if not api_decls and not api_pre and not api_post:
705            return
706        # Record that the function will be intercepted
707        if (self.featureExtraProtect != None):
708            self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ]
709        self.intercepts += [ '    {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ]
710        if (self.featureExtraProtect != None):
711            self.intercepts += [ '#endif' ]
712        decls = self.makeCDecls(cmdinfo.elem)
713        self.appendSection('command', '')
714        self.appendSection('command', decls[0][:-1])
715        self.appendSection('command', '{')
716        # Setup common to call wrappers, first parameter is always dispatchable
717        dispatchable_type = cmdinfo.elem.find('param/type').text
718        dispatchable_name = cmdinfo.elem.find('param/name').text
719        # Generate local instance/pdev/device data lookup
720        self.appendSection('command', '    layer_data *dev_data = get_my_data_ptr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
721        # Handle return values, if any
722        resulttype = cmdinfo.elem.find('proto/type')
723        if (resulttype != None and resulttype.text == 'void'):
724          resulttype = None
725        if (resulttype != None):
726            assignresult = resulttype.text + ' result = '
727        else:
728            assignresult = ''
729        # Pre-pend declarations and pre-api-call codegen
730        if api_decls:
731            self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
732        if api_pre:
733            self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
734        # Generate the API call itself
735        # Gather the parameter items
736        params = cmdinfo.elem.findall('param/name')
737        # Pull out the text for each of the parameters, separate them by commas in a list
738        paramstext = ', '.join([str(param.text) for param in params])
739        # If any of these paramters has been replaced by a local var, fix up the list
740        cmd_member_dict = dict(self.cmdMembers)
741        params = cmd_member_dict[cmdname]
742        for param in params:
743            if param.islocal == True:
744                if param.ispointer == True:
745                    paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
746                else:
747                    paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
748        # Use correct dispatch table
749        if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
750            API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->instance_dispatch_table->',1)
751        else:
752            API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->device_dispatch_table->',1)
753        # Put all this together for the final down-chain call
754        self.appendSection('command', '    ' + assignresult + API + '(' + paramstext + ');')
755        # And add the post-API-call codegen
756        self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
757        # Handle the return result variable, if any
758        if (resulttype != None):
759            self.appendSection('command', '    return result;')
760        self.appendSection('command', '}')
761