1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
|
#!/usr/bin/env python3
#
# Copyright (c) 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import ctypes
import json
import os
import platform
import sys
import xml.etree.ElementTree
if platform.system() == "Windows":
VKAPI_DLL = ctypes.windll
VKAPI_FUNCTYPE = ctypes.WINFUNCTYPE
else:
VKAPI_DLL = ctypes.cdll
VKAPI_FUNCTYPE = ctypes.CFUNCTYPE
# Vulkan types
VkInstance = ctypes.c_void_p
VkPhysicalDevice = ctypes.c_void_p
VkDevice = ctypes.c_void_p
VkResult = ctypes.c_int
class VkLayerProperties(ctypes.Structure):
_fields_ = [("c_layerName", ctypes.c_char * 256),
("c_specVersion", ctypes.c_uint32),
("c_implementationVersion", ctypes.c_uint32),
("c_description", ctypes.c_char * 256)]
def layer_name(self):
return self.c_layerName.decode()
def spec_version(self):
return "%d.%d.%d" % (
self.c_specVersion >> 22,
(self.c_specVersion >> 12) & 0x3ff,
self.c_specVersion & 0xfff)
def implementation_version(self):
return str(self.c_implementationVersion)
def description(self):
return self.c_description.decode()
def __eq__(self, other):
return (self.c_layerName == other.c_layerName and
self.c_specVersion == other.c_specVersion and
self.c_implementationVersion == other.c_implementationVersion and
self.c_description == other.c_description)
class VkExtensionProperties(ctypes.Structure):
_fields_ = [("c_extensionName", ctypes.c_char * 256),
("c_specVersion", ctypes.c_uint32)]
def extension_name(self):
return self.c_extensionName.decode()
def spec_version(self):
return str(self.c_specVersion)
# Vulkan commands
PFN_vkVoidFunction = VKAPI_FUNCTYPE(None)
PFN_vkEnumerateInstanceExtensionProperties = VKAPI_FUNCTYPE(
VkResult, ctypes.c_char_p, ctypes.POINTER(ctypes.c_uint32), ctypes.POINTER(VkExtensionProperties))
PFN_vkEnumerateDeviceExtensionProperties = VKAPI_FUNCTYPE(
VkResult, VkPhysicalDevice, ctypes.c_char_p, ctypes.POINTER(ctypes.c_uint32), ctypes.POINTER(VkExtensionProperties))
PFN_vkEnumerateInstanceLayerProperties = VKAPI_FUNCTYPE(
VkResult, ctypes.POINTER(ctypes.c_uint32), ctypes.POINTER(VkLayerProperties))
PFN_vkEnumerateDeviceLayerProperties = VKAPI_FUNCTYPE(
VkResult, VkPhysicalDevice, ctypes.POINTER(ctypes.c_uint32), ctypes.POINTER(VkLayerProperties))
PFN_vkGetInstanceProcAddr = VKAPI_FUNCTYPE(
PFN_vkVoidFunction, VkInstance, ctypes.c_char_p)
PFN_vkGetDeviceProcAddr = VKAPI_FUNCTYPE(
PFN_vkVoidFunction, VkDevice, ctypes.c_char_p)
class Layer(object):
def __init__(self, *args):
self.props = args[0]
self.is_global = args[1]
self.instance_extensions = args[2]
self.device_extensions = args[3]
self.gipa_name = args[4]
self.gdpa_name = args[5]
class LayerLibrary(object):
def __init__(self, path):
self.library = None
self.version = 0
self._load(path)
self._negotiate_version()
def introspect(self):
if self.version == 0:
layers = self._enumerate_layers_v0()
else:
raise RuntimeError("unsupported v%d library" % self.version)
return layers
def _load(self, path):
try:
abspath = os.path.abspath(path)
self.library = VKAPI_DLL.LoadLibrary(abspath)
except OSError:
raise RuntimeError("failed to load library")
def _unload(self):
# no clean way to unload
pass
def _negotiate_version(self):
# only v0
self.version = 0
def _enumerate_properties_errcheck_v0(self, result, func, args):
if isinstance(func, PFN_vkEnumerateInstanceLayerProperties):
func_name = "vkEnumerateInstanceLayerProperties"
elif isinstance(func, PFN_vkEnumerateDeviceLayerProperties):
func_name = "vkEnumerateDeviceLayerProperties"
elif isinstance(func, PFN_vkEnumerateInstanceExtensionProperties):
func_name = "vkEnumerateInstanceExtensionProperties"
elif isinstance(func, PFN_vkEnumerateDeviceExtensionProperties):
func_name = "vkEnumerateDeviceExtensionProperties"
else:
raise AssertionError("unexpected vkEnumerate*Properties call")
if result != 0:
raise RuntimeError(func_name + " failed with " + str(result))
# pProperties and pCount mismatch
if args[-1] and len(args[-1]) != args[-2].value:
raise RuntimeError("invalid pCount returned in " + func_name)
return args[-1]
def _enumerate_properties_prototype_v0(self, func_name):
prototypes = {
"vkEnumerateInstanceLayerProperties":
PFN_vkEnumerateInstanceLayerProperties,
"vkEnumerateDeviceLayerProperties":
PFN_vkEnumerateDeviceLayerProperties,
"vkEnumerateInstanceExtensionProperties":
PFN_vkEnumerateInstanceExtensionProperties,
"vkEnumerateDeviceExtensionProperties":
PFN_vkEnumerateDeviceExtensionProperties,
}
prototype = prototypes[func_name]
try:
proc = prototype((func_name, self.library))
except AttributeError:
raise RuntimeError(func_name + " is missing")
proc.errcheck = self._enumerate_properties_errcheck_v0
return proc
def _get_gipa_name_v0(self, layer_name, can_fallback):
names = [layer_name + "GetInstanceProcAddr"]
if can_fallback:
names.append("vkGetInstanceProcAddr")
for name in names:
try:
PFN_vkGetInstanceProcAddr((name, self.library))
return name
except AttributeError:
pass
raise RuntimeError(" or ".join(names) + " is missing")
def _get_gdpa_name_v0(self, layer_name, can_fallback):
names = [layer_name + "GetDeviceProcAddr"]
if can_fallback:
names.append("vkGetDeviceProcAddr")
for name in names:
try:
PFN_vkGetDeviceProcAddr((name, self.library))
return name
except AttributeError:
pass
raise RuntimeError(" or ".join(names) + " is missing")
def _enumerate_layers_v0(self):
tmp_count = ctypes.c_uint32()
# enumerate instance layers
enumerate_instance_layer_properties = self._enumerate_properties_prototype_v0(
"vkEnumerateInstanceLayerProperties")
enumerate_instance_layer_properties(tmp_count, None)
p_props = enumerate_instance_layer_properties(
tmp_count, (VkLayerProperties * tmp_count.value)())
# enumerate device layers
enumerate_device_layer_properties = self._enumerate_properties_prototype_v0(
"vkEnumerateDeviceLayerProperties")
enumerate_device_layer_properties(None, tmp_count, None)
dev_p_props = enumerate_device_layer_properties(
None, tmp_count, (VkLayerProperties * tmp_count.value)())
# there must not be device-only layers
for props in dev_p_props:
if props not in p_props:
raise RuntimeError(
"unexpected device-only layer " + props.layer_name())
layers = []
for props in p_props:
is_global = (props in dev_p_props)
# enumerate instance extensions
enumerate_instance_extension_properties = self._enumerate_properties_prototype_v0(
"vkEnumerateInstanceExtensionProperties")
enumerate_instance_extension_properties(
props.c_layerName, tmp_count, None)
instance_extensions = enumerate_instance_extension_properties(
props.c_layerName,
tmp_count,
(VkExtensionProperties * tmp_count.value)())
gipa_name = self._get_gipa_name_v0(
props.layer_name(),
len(p_props) == 1)
if is_global:
# enumerate device extensions
enumerate_device_extension_properties = self._enumerate_properties_prototype_v0(
"vkEnumerateDeviceExtensionProperties")
enumerate_device_extension_properties(
None, props.c_layerName, tmp_count, None)
device_extensions = enumerate_device_extension_properties(
None,
props.c_layerName,
tmp_count,
(VkExtensionProperties * tmp_count.value)())
gdpa_name = self._get_gdpa_name_v0(
props.layer_name(),
len(p_props) == 1)
else:
device_extensions = None
gdpa_name = None
layers.append(
Layer(props, is_global, instance_extensions, device_extensions, gipa_name, gdpa_name))
return layers
def serialize_layers(layers, path, ext_cmds):
data = {}
data["file_format_version"] = '1.0.0'
for idx, layer in enumerate(layers):
layer_data = {}
layer_data["name"] = layer.props.layer_name()
layer_data["api_version"] = layer.props.spec_version()
layer_data[
"implementation_version"] = layer.props.implementation_version()
layer_data["description"] = layer.props.description()
layer_data["type"] = "GLOBAL" if layer.is_global else "INSTANCE"
# TODO more flexible
layer_data["library_path"] = os.path.join(".", os.path.basename(path))
funcs = {}
if layer.gipa_name != "vkGetInstanceProcAddr":
funcs["vkGetInstanceProcAddr"] = layer.gipa_name
if layer.is_global and layer.gdpa_name != "vkGetDeviceProcAddr":
funcs["vkGetDeviceProcAddr"] = layer.gdpa_name
if funcs:
layer_data["functions"] = funcs
if layer.instance_extensions:
exts = [{
"name": ext.extension_name(),
"spec_version": ext.spec_version(),
} for ext in layer.instance_extensions]
layer_data["instance_extensions"] = exts
if layer.device_extensions:
exts = []
for ext in layer.device_extensions:
try:
cmds = ext_cmds[ext.extension_name()]
except KeyError:
raise RuntimeError(
"unknown device extension " + ext.extension_name())
else:
ext_data = {}
ext_data["name"] = ext.extension_name()
ext_data["spec_version"] = ext.spec_version()
if cmds:
ext_data["entrypoints"] = cmds
exts.append(ext_data)
layer_data["device_extensions"] = exts
if idx > 0:
data["layer.%d" % idx] = layer_data
else:
data["layer"] = layer_data
return data
def dump_json(data):
dump = json.dumps(data, indent=4, sort_keys=True)
# replace "layer.<idx>" by "layer"
lines = dump.split("\n")
for line in lines:
if line.startswith(" \"layer.") and line.endswith("\": {"):
line = " \"layer\": {"
print(line)
def parse_vk_xml(path):
"""Parse vk.xml to get commands added by extensions."""
tree = xml.etree.ElementTree.parse(path)
extensions = tree.find("extensions")
ext_cmds = {}
for ext in extensions.iter("extension"):
if ext.attrib["supported"] != "vulkan":
continue
cmds = []
for cmd in ext.iter("command"):
cmds.append(cmd.attrib["name"])
ext_cmds[ext.attrib["name"]] = cmds
return ext_cmds
def add_custom_ext_cmds(ext_cmds):
"""Add commands added by in-development extensions."""
# VK_LAYER_LUNARG_basic
ext_cmds["vkLayerBasicEXT"] = ["vkLayerBasicEXT"]
def main():
default_vk_xml = sys.path[0] + "/vk.xml" if sys.path[0] else "vk.xml"
parser = argparse.ArgumentParser(description="Introspect a layer library.")
parser.add_argument(
"-x", dest="vk_xml", default=default_vk_xml, help="Path to vk.xml")
parser.add_argument(
"layer_libs", metavar="layer-lib", nargs="+", help="Path to a layer library")
args = parser.parse_args()
try:
ext_cmds = parse_vk_xml(args.vk_xml)
except Exception as e:
print("failed to parse %s: %s" % (args.vk_xml, e))
sys.exit(-1)
add_custom_ext_cmds(ext_cmds)
for path in args.layer_libs:
try:
ll = LayerLibrary(path)
layers = ll.introspect()
data = serialize_layers(layers, path, ext_cmds)
dump_json(data)
except RuntimeError as err:
print("skipping %s: %s" % (path, err))
if __name__ == "__main__":
main()
|