forked from ValveSoftware/Proton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmake_openxr
executable file
·2990 lines (2401 loc) · 112 KB
/
make_openxr
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# Wine Vulkan generator
#
# Copyright 2017-2018 Roderick Colenbrander
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
import argparse
import logging
import os
import re
import sys
import urllib.request
import xml.etree.ElementTree as ET
from collections import OrderedDict
from collections.abc import Sequence
from enum import Enum
# This script generates code for a Wine Vulkan ICD driver from Vulkan's xr.xml.
# Generating the code is like 10x worse than OpenGL, which is mostly a calling
# convention passthrough.
#
# The script parses xr.xml and maps functions and types to helper objects. These
# helper objects simplify the xml parsing and map closely to the Vulkan types.
# The code generation utilizes the helper objects during code generation and
# most of the ugly work is carried out by these objects.
#
# Vulkan ICD challenges:
# - Vulkan ICD loader (vulkan-1.dll) relies on a section at the start of
# 'dispatchable handles' (e.g. XrDevice, XrInstance) for it to insert
# its private data. It uses this area to stare its own dispatch tables
# for loader internal use. This means any dispatchable objects need wrapping.
#
# - Vulkan structures have different alignment between win32 and 32-bit Linux.
# This means structures with alignment differences need conversion logic.
# Often structures are nested, so the parent structure may not need any
# conversion, but some child may need some.
#
# xr.xml parsing challenges:
# - Contains type data for all platforms (generic Vulkan, Windows, Linux,..).
# Parsing of extension information required to pull in types and functions
# we really want to generate. Just tying all the data together is tricky.
#
# - Arrays are used all over the place for parameters or for structure members.
# Array length is often stored in a previous parameter or another structure
# member and thus needs careful parsing.
LOGGER = logging.Logger("openxr")
LOGGER.addHandler(logging.StreamHandler())
XR_XML_VERSION = "1.0.11"
WINE_XR_VERSION = (1, 1)
# Filenames to create.
WINE_OPENXR_H = "./wineopenxr.h"
WINE_OPENXR_DRIVER_H = "./wineopenxr_driver.h"
WINE_OPENXR_JSON = "./wineopenxr.json"
WINE_OPENXR_THUNKS_C = "./openxr_thunks.c"
WINE_OPENXR_THUNKS_H = "./openxr_thunks.h"
# Extension enum values start at a certain offset (EXT_BASE).
# Relative to the offset each extension has a block (EXT_BLOCK_SIZE)
# of values.
# Start for a given extension is:
# EXT_BASE + (extension_number-1) * EXT_BLOCK_SIZE
EXT_BASE = 1000000000
EXT_BLOCK_SIZE = 1000
UNSUPPORTED_EXTENSIONS = [
# Instance extensions
"XR_EXT_debug_report",
# Handling of XR_EXT_debug_report requires some consideration. The win32
# loader already provides it for us and it is somewhat usable. If we add
# plumbing down to the native layer, we will get each message twice as we
# use 2 loaders (win32+native), but we may get output from the driver.
# In any case callback conversion is required.
"XR_EXT_debug_utils",
"XR_EXT_validation_features",
"XR_EXT_validation_flags",
"XR_KHR_display", # Needs WSI work.
"XR_KHR_surface_protected_capabilities",
"XR_KHR_loader_init",
"XR_MSFT_perception_anchor_interop",
# Device extensions
"XR_AMD_display_native_hdr",
"XR_EXT_display_control", # Requires XR_EXT_display_surface_counter
"XR_EXT_full_screen_exclusive",
"XR_EXT_hdr_metadata", # Needs WSI work.
"XR_EXT_pipeline_creation_feedback",
"XR_GOOGLE_display_timing",
"XR_KHR_external_fence_win32",
"XR_KHR_external_memory_win32",
"XR_KHR_external_semaphore_win32",
# Relates to external_semaphore and needs type conversions in bitflags.
"XR_KHR_shared_presentable_image", # Needs WSI work.
"XR_KHR_win32_keyed_mutex",
# Extensions for other platforms
"XR_EXT_external_memory_dma_buf",
"XR_EXT_image_drm_format_modifier",
"XR_KHR_external_fence_fd",
"XR_KHR_external_memory_fd",
"XR_KHR_external_semaphore_fd",
# Deprecated extensions
"XR_NV_external_memory_capabilities",
"XR_NV_external_memory_win32",
]
ALLOWED_PROTECTS = [
"XR_USE_PLATFORM_WIN32",
"XR_USE_GRAPHICS_API_VULKAN",
"XR_USE_GRAPHICS_API_OPENGL",
"XR_USE_GRAPHICS_API_D3D11",
"XR_USE_GRAPHICS_API_D3D12",
]
# Functions part of our wineopenxr graphics driver interface.
# DRIVER_VERSION should be bumped on any change to driver interface
# in FUNCTION_OVERRIDES
DRIVER_VERSION = 1
# Table of functions for which we have a special implementation.
# These are regular device / instance functions for which we need
# to do more work compared to a regular thunk or because they are
# part of the driver interface.
# - dispatch set whether we need a function pointer in the device
# / instance dispatch table.
# - driver sets whether the API is part of the driver interface.
# - thunk sets whether to create a thunk in openxr_thunks.c.
FUNCTION_OVERRIDES = {
# Global functions
"xrCreateInstance" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrCreateApiLayerInstance" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrNegotiateLoaderRuntimeInterface" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrNegotiateLoaderApiLayerInterface" : {"dispatch" : False, "driver" : False, "thunk" : False},
"xrDestroyInstance" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrCreateSession" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrDestroySession" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrGetInstanceProcAddr" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrEnumerateInstanceExtensionProperties" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrConvertTimeToWin32PerformanceCounterKHR" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrConvertWin32PerformanceCounterToTimeKHR" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrGetD3D11GraphicsRequirementsKHR" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrGetD3D12GraphicsRequirementsKHR" : {"dispatch" : False, "driver" : True, "thunk" : False},
"xrGetVulkanGraphicsDeviceKHR" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrGetVulkanGraphicsDevice2KHR" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrGetVulkanDeviceExtensionsKHR" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrGetVulkanInstanceExtensionsKHR" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrCreateVulkanInstanceKHR" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrCreateVulkanDeviceKHR" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrPollEvent" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrEnumerateSwapchainImages" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrGetSystem" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrEnumerateSwapchainFormats" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrCreateSwapchain" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrDestroySwapchain" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrEndFrame" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrBeginFrame" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrAcquireSwapchainImage" : {"dispatch" : True, "driver" : True, "thunk" : False},
"xrReleaseSwapchainImage" : {"dispatch" : True, "driver" : True, "thunk" : False},
}
NOT_OUR_FUNCTIONS = [
# xr.xml defines that as a part of XR_LOADER_VERSION_1_0 commands but it looks like only layers should provide it
# (through dll export).
"xrNegotiateLoaderApiLayerInterface",
]
STRUCT_CHAIN_CONVERSIONS = [
"XrInstanceCreateInfo",
]
STRUCTS_PUT_FIRST = [
"XrUuid",
"XrExtent3Df",
]
AUTO_MAPPED_HANDLES = [
"XrSpace",
"XrSpatialAnchorMSFT",
"XrSpatialAnchorStoreConnectionMSFT",
"XrHandTrackerEXT",
"XrExportedLocalizationMapML",
"XrMarkerDetectorML",
"XrSceneMSFT",
"XrSceneObserverMSFT",
"XrSpatialGraphNodeBindingMSFT",
"XrFoveationProfileFB",
"XrTriangleMeshFB",
"XrPassthroughFB",
"XrPassthroughLayerFB",
"XrGeometryInstanceFB",
"XrEnvironmentDepthProviderMETA",
"XrVirtualKeyboardMETA",
"XrPlaneDetectorEXT",
"XrEyeTrackerFB",
"XrSpaceUserFB",
"XrBodyTrackerFB",
"XrFaceTrackerFB",
"XrFaceTracker2FB",
"XrEnvironmentDepthSwapchainMETA",
"XrPassthroughHTC",
"XrFacialTrackerHTC",
"XrPassthroughColorLutMETA",
]
class Direction(Enum):
""" Parameter direction: input, output, input_output. """
INPUT = 1
OUTPUT = 2
INPUT_OUTPUT = 3
class XrBaseType(object):
def __init__(self, name, _type, text, alias=None, requires=None):
""" OpenXR base type class.
XrBaseType is mostly used by OpenXR to define its own
base types like XrFlags through typedef out of e.g. uint32_t.
Args:
name (:obj:'str'): Name of the base type.
_type (:obj:'str'): Underlying type
alias (bool): type is an alias or not.
requires (:obj:'str', optional): Other types required.
Often bitmask values pull in a *FlagBits type.
"""
self.name = name
self.type = _type
self.alias = alias
self.requires = requires
self.required = False
self.text = text
def definition(self):
# Definition is similar for alias or non-alias as type
# is already set to alias.
return self.text + "\n"
def is_alias(self):
return bool(self.alias)
class XrConstant(object):
def __init__(self, name, value):
self.name = name
self.value = value
def definition(self):
text = "#define {0} {1}\n".format(self.name, self.value)
return text
class XrDefine(object):
def __init__(self, name, value):
self.name = name
self.value = value
@staticmethod
def from_xml(define):
name_elem = define.find("name")
if name_elem is None:
# <type category="define" name="some_name">some_value</type>
# At the time of writing there is only 1 define of this category
# 'XR_DEFINE_NON_DISPATCHABLE_HANDLE'.
name = define.attrib.get("name")
# We override behavior of XR_DEFINE_NON_DISPATCHABLE handle as the default
# definition various between 64-bit (uses pointers) and 32-bit (uses uint64_t).
# This complicates TRACEs in the thunks, so just use uint64_t.
if name == "XR_DEFINE_NON_DISPATCHABLE_HANDLE":
value = "#define XR_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object;"
else:
value = define.text
return XrDefine(name, value)
# With a name element the structure is like:
# <type category="define"><name>some_name</name>some_value</type>
name = name_elem.text
# Perform minimal parsing for constants, which we don't need, but are referenced
# elsewhere in xr.xml.
# - XR_API_VERSION is a messy, deprecated constant and we don't want generate code for it.
# - AHardwareBuffer/ANativeWindow are forward declarations for Android types, which leaked
# into the define region.
if name in ["XR_API_VERSION", "ANativeWindow"]:
return XrDefine(name, None)
# The body of the define is basically unstructured C code. It is not meant for easy parsing.
# Some lines contain deprecated values or comments, which we try to filter out.
value = ""
for line in define.text.splitlines():
value += "\n"
# Skip comments or deprecated values.
if "//" in line:
continue
value += line
for child in define:
value += child.text
if child.tail is not None:
# Split comments for XR_API_VERSION_1_0 / XR_API_VERSION_1_1
if "//" in child.tail:
value += child.tail.split("//")[0]
else:
value += child.tail
return XrDefine(name, value.rstrip(' '))
def definition(self):
if self.value is None:
return ""
# Nothing to do as the value was already put in the right form during parsing.
return "{0}\n".format(self.value)
def is_alias(self):
return False
class XrEnum(object):
def __init__(self, name, values, alias=None):
self.name = name
self.values = values
self.required = False
self.alias = alias
self.aliased_by = []
@staticmethod
def from_alias(enum, alias):
name = enum.attrib.get("name")
aliasee = XrEnum(name, alias.values, alias=alias)
alias.add_aliased_by(aliasee)
return aliasee
@staticmethod
def from_xml(enum):
name = enum.attrib.get("name")
values = []
for v in enum.findall("enum"):
# Value is either a value or a bitpos, only one can exist.
value = v.attrib.get("value")
alias_name = v.attrib.get("alias")
if alias_name:
alias = next(x for x in values if x.name == alias_name)
values.append(XrEnumValue(v.attrib.get("name"), value=alias.value, hex=alias.hex))
elif value:
# Some values are in hex form. We want to preserve the hex representation
# at least when we convert back to a string. Internally we want to use int.
if "0x" in value:
values.append(XrEnumValue(v.attrib.get("name"), value=int(value, 0), hex=True))
else:
values.append(XrEnumValue(v.attrib.get("name"), value=int(value, 0)))
else:
# bitmask
value = 1 << int(v.attrib.get("bitpos"))
values.append(XrEnumValue(v.attrib.get("name"), value=value, hex=True))
# vulkan.h contains a *_MAX_ENUM value set to 32-bit at the time of writing,
# which is to prepare for extensions as they can add values and hence affect
# the size definition.
max_name = re.sub(r'([0-9a-z_])([A-Z0-9])',r'\1_\2', name).upper() + "_MAX_ENUM"
values.append(XrEnumValue(max_name, value=0x7fffffff, hex=True))
return XrEnum(name, values)
def add(self, value):
""" Add a value to enum. """
# Extensions can add new enum values. When an extension is promoted to Core
# the registry defines the value twice once for old extension and once for
# new Core features. Add the duplicate if it's explicitly marked as an
# alias, otherwise ignore it.
for v in self.values:
if not value.is_alias() and v.value == value.value:
LOGGER.debug("Adding duplicate enum value {0} to {1}".format(v, self.name))
return
# Avoid adding duplicate aliases multiple times
if not any(x.name == value.name for x in self.values):
self.values.append(value)
def definition(self):
if self.is_alias():
return ""
text = "typedef enum {0}\n{{\n".format(self.name)
# Print values sorted, values can have been added in a random order.
values = sorted(self.values, key=lambda value: value.value if value.value is not None else 0x7ffffffe)
for value in values:
text += " {0},\n".format(value.definition())
text += "}} {0};\n".format(self.name)
for aliasee in self.aliased_by:
text += "typedef {0} {1};\n".format(self.name, aliasee.name)
text += "\n"
return text
def is_alias(self):
return bool(self.alias)
def add_aliased_by(self, aliasee):
self.aliased_by.append(aliasee)
class XrEnumValue(object):
def __init__(self, name, value=None, hex=False, alias=None):
self.name = name
self.value = value
self.hex = hex
self.alias = alias
def __repr__(self):
if self.is_alias():
return "{0}={1}".format(self.name, self.alias)
return "{0}={1}".format(self.name, self.value)
def definition(self):
""" Convert to text definition e.g. XR_FOO = 1 """
if self.is_alias():
return "{0} = {1}".format(self.name, self.alias)
# Hex is commonly used for FlagBits and sometimes within
# a non-FlagBits enum for a bitmask value as well.
if self.hex:
return "{0} = 0x{1:08x}".format(self.name, self.value)
else:
return "{0} = {1}".format(self.name, self.value)
def is_alias(self):
return self.alias is not None
class XrFunction(object):
def __init__(self, _type=None, name=None, params=[], extensions=[], alias=None):
self.extensions = []
self.name = name
self.type = _type
self.params = params
self.alias = alias
# For some functions we need some extra metadata from FUNCTION_OVERRIDES.
func_info = FUNCTION_OVERRIDES.get(self.name, None)
self.dispatch = func_info["dispatch"] if func_info else True
self.driver = func_info["driver"] if func_info else False
self.thunk_needed = func_info["thunk"] if func_info else True
self.private_thunk = func_info["private_thunk"] if func_info and "private_thunk" in func_info else False
if self.private_thunk:
self.thunk_needed = True
# Required is set while parsing which APIs and types are required
# and is used by the code generation.
self.required = True if func_info else False
@staticmethod
def from_alias(command, alias):
""" Create XrFunction from an alias command.
Args:
command: xml data for command
alias (XrFunction): function to use as a base for types / parameters.
Returns:
XrFunction
"""
func_name = command.attrib.get("name")
func_type = alias.type
params = alias.params
return XrFunction(_type=func_type, name=func_name, params=params, alias=alias)
@staticmethod
def from_xml(command, types):
proto = command.find("proto")
func_name = proto.find("name").text
func_type = proto.find("type").text
params = []
for param in command.findall("param"):
xr_param = XrParam.from_xml(param, types)
params.append(xr_param)
return XrFunction(_type=func_type, name=func_name, params=params)
def get_conversions(self):
""" Get a list of conversion functions required for this function if any.
Parameters which are structures may require conversion between win32
and the host platform. This function returns a list of conversions
required.
"""
conversions = []
for param in self.params:
convs = param.get_conversions()
if convs is not None:
conversions.extend(convs)
return conversions
def is_alias(self):
return bool(self.alias)
def is_core_func(self):
""" Returns whether the function is a core function.
Core functions are APIs defined by the spec to be part of the
Core API.
"""
return not self.extensions
def is_driver_func(self):
""" Returns if function is part of Wine driver interface. """
return self.driver
def is_global_func(self):
# Treat xrGetInstanceProcAddr as a global function as it
# can operate with NULL for xrInstance.
if self.name == "xrGetInstanceProcAddr":
return True
# Global functions are not passed a dispatchable object.
elif self.params[0].is_dispatchable():
return False
return True
def is_instance_func(self):
# Instance functions are passed XrInstance.
if self.params[0].type in ["XrInstance"]:
return True
return False
def is_required(self):
return self.required
def needs_conversion(self):
""" Check if the function needs any input/output type conversion.
Functions need input/output conversion if struct parameters have
alignment differences between Win32 and Linux 32-bit.
"""
for p in self.params:
if p.needs_conversion():
LOGGER.debug("Parameter {0} to {1} requires conversion".format(p.name, self.name))
return True
return False
def needs_dispatch(self):
return self.dispatch
def needs_thunk(self):
return self.thunk_needed
def needs_private_thunk(self):
return self.private_thunk
def pfn(self, prefix="p", call_conv=None, conv=False):
""" Create function pointer. """
if call_conv:
pfn = "{0} ({1} *{2}_{3})(".format(self.type, call_conv, prefix, self.name)
else:
pfn = "{0} (*{1}_{2})(".format(self.type, prefix, self.name)
for i, param in enumerate(self.params):
if param.const:
pfn += param.const + " "
pfn += param.type
if conv and param.needs_conversion():
pfn += "_host"
if param.is_pointer():
pfn += " " + param.pointer
if param.array_len is not None:
pfn += "[{0}]".format(param.array_len)
if i < len(self.params) - 1:
pfn += ", "
pfn += ")"
return pfn
def prototype(self, call_conv=None, prefix=None, postfix=None):
""" Generate prototype for given function.
Args:
call_conv (str, optional): calling convention e.g. WINAPI
prefix (str, optional): prefix to append prior to function name e.g. xrFoo -> wine_xrFoo
postfix (str, optional): text to append after function name but prior to semicolon
"""
proto = "{0}".format(self.type)
if call_conv is not None:
proto += " {0}".format(call_conv)
if prefix is not None:
proto += " {0}{1}(".format(prefix, self.name)
else:
proto += " {0}(".format(self.name)
# Add all the parameters.
proto += ", ".join([p.definition() for p in self.params])
if postfix is not None:
proto += ") {0}".format(postfix)
else:
proto += ")"
return proto
def body(self):
body = ""
if self.type != "void":
body += " {0} ret;\n\n".format(self.type)
if not self.needs_private_thunk():
body += " {0}".format(self.trace())
params = ", ".join([p.variable(conv=False) for p in self.params])
# Call the native Vulkan function.
if self.is_core_func():
# core functions are exported by the native loader, so avoid dispatch for those
if self.type == "void":
body += " {0}({1});\n".format(self.name, params)
else:
body += " ret = {0}({1});\n".format(self.name, params)
else:
if self.type == "void":
body += " {0}.p_{1}({2});\n".format(self.params[0].dispatch_table(), self.name, params)
else:
body += " ret = {0}.p_{1}({2});\n".format(self.params[0].dispatch_table(), self.name, params)
if "Destroy" in self.name:
for p in self.params:
if p.type in AUTO_MAPPED_HANDLES:
body += " unregister_dispatchable_handle((uint64_t){0});\n".format(p.name)
if "Create" in self.name:
for p in self.params:
if p.type in AUTO_MAPPED_HANDLES and p.is_pointer():
body += " if (!ret) register_dispatchable_handle((uint64_t)*{0}, &({1}));\n".format(p.name, self.params[0].dispatch_table())
if self.type != "void":
body += " return ret;\n"
return body
def body_conversion(self):
body = ""
# Declare a variable to hold the result for non-void functions.
if self.type != "void":
body += " {0} result;\n".format(self.type)
# Declare any tmp parameters for conversion.
for p in self.params:
if not p.needs_conversion():
continue
if p.is_dynamic_array():
body += " {0}_host *{1}_host;\n".format(p.type, p.name)
else:
body += " {0}_host {1}_host;\n".format(p.type, p.name)
if not self.needs_private_thunk():
body += " {0}\n".format(self.trace())
# Call any win_to_host conversion calls.
for p in self.params:
if not p.needs_input_conversion():
continue
body += p.copy(Direction.INPUT)
# Build list of parameters containing converted and non-converted parameters.
# The param itself knows if conversion is needed and applies it when we set conv=True.
params = ", ".join([p.variable(conv=True) for p in self.params])
# Call the native function.
if self.type == "void":
body += " {0}.p_{1}({2});\n".format(self.params[0].dispatch_table(), self.name, params)
else:
body += " result = {0}.p_{1}({2});\n".format(self.params[0].dispatch_table(), self.name, params)
body += "\n"
# Call any host_to_win conversion calls.
for p in self.params:
if not p.needs_output_conversion():
continue
body += p.copy(Direction.OUTPUT)
# Perform any required cleanups. Most of these are for array functions.
for p in self.params:
if not p.needs_free():
continue
body += p.free()
# Finally return the result.
if self.type != "void":
body += " return result;\n"
return body
def stub(self, call_conv=None, prefix=None):
stub = self.prototype(call_conv=call_conv, prefix=prefix)
stub += "\n{\n"
stub += " {0}".format(self.trace(message="stub: ", trace_func="WINE_FIXME"))
if self.type == "XrResult":
stub += " return XR_ERROR_OUT_OF_HOST_MEMORY;\n"
elif self.type == "XrBool32":
stub += " return XR_FALSE;\n"
elif self.type == "PFN_xrVoidFunction":
stub += " return NULL;\n"
stub += "}\n\n"
return stub
def thunk(self, call_conv=None, prefix=None):
thunk = self.prototype(call_conv=call_conv, prefix=prefix)
thunk += "\n{\n"
if self.needs_conversion():
thunk += "#if defined(USE_STRUCT_CONVERSION)\n"
thunk += self.body_conversion()
thunk += "#else\n"
thunk += self.body()
thunk += "#endif\n"
else:
thunk += self.body()
thunk += "}\n\n"
return thunk
def trace(self, message=None, trace_func=None):
""" Create a trace string including all parameters.
Args:
message (str, optional): text to print at start of trace message e.g. 'stub: '
trace_func (str, optional): used to override trace function e.g. FIXME, printf, etcetera.
"""
if trace_func is not None:
trace = "{0}(\"".format(trace_func)
else:
trace = "WINE_TRACE(\""
if message is not None:
trace += message
# First loop is for all the format strings.
trace += ", ".join([p.format_string() for p in self.params])
trace += "\\n\""
# Second loop for parameter names and optional conversions.
for param in self.params:
if param.format_conv is not None:
trace += ", " + param.format_conv.format(param.name)
else:
trace += ", {0}".format(param.name)
trace += ");\n"
return trace
class XrFunctionPointer(object):
def __init__(self, _type, name, members, params_text):
self.name = name
self.members = members
self.type = _type
self.required = False
self.params_text = params_text
@staticmethod
def from_xml(funcpointer):
members = []
begin = None
for t in funcpointer.findall("type"):
# General form:
# <type>void</type>* pUserData,
# Parsing of the tail (anything past </type>) is tricky since there
# can be other data on the next line like: const <type>int</type>..
const = True if begin and "const" in begin else False
_type = t.text
lines = t.tail.split(",\n")
if lines[0][0] == "*":
pointer = "*"
name = lines[0][1:].strip()
else:
pointer = None
name = lines[0].strip()
# Filter out ); if it is contained.
name = name.partition(");")[0]
# If tail encompasses multiple lines, assign the second line to begin
# for the next line.
try:
begin = lines[1].strip()
except IndexError:
begin = None
members.append(XrMember(const=const, _type=_type, pointer=pointer, name=name))
_type = funcpointer.text
name = funcpointer.find("name").text
params_text = None
if members == []:
index = 0
for elem_part in funcpointer.itertext():
index = index + 1
if index == 3:
p = re.findall(r'\([^)]*\)', elem_part)
params_text = next(iter(p), None)
if params_text:
params_text = params_text[1:-1]
break
return XrFunctionPointer(_type, name, members, params_text)
def definition(self):
text = "{0} {1})(\n".format(self.type, self.name)
first = True
if len(self.members) > 0:
for m in self.members:
if first:
text += " " + m.definition()
first = False
else:
text += ",\n " + m.definition()
elif self.params_text is not None:
text += self.params_text
else:
# Just make the compiler happy by adding a void parameter.
text += "void"
text += ");\n"
return text
class XrHandle(object):
def __init__(self, name, _type, parent, alias=None):
self.name = name
self.type = _type
self.parent = parent
self.alias = alias
self.required = False
@staticmethod
def from_alias(handle, alias):
name = handle.attrib.get("name")
return XrHandle(name, alias.type, alias.parent, alias=alias)
@staticmethod
def from_xml(handle):
name = handle.find("name").text
_type = handle.find("type").text
parent = handle.attrib.get("parent")
return XrHandle(name, _type, parent)
def dispatch_table(self):
if not self.is_dispatchable():
return None
if self.parent is None:
# Should only happen for XrInstance
return "funcs"
if self.parent in ["XrInstance"]:
return "wine_instance->funcs"
if self.parent in ["XrSession"]:
return "wine_session->wine_instance->funcs"
if self.parent in ["XrActionSet"]:
return "wine_action_set->wine_instance->funcs"
LOGGER.error("Unhandled dispatchable parent: {0}".format(self.parent))
def definition(self):
""" Generates handle definition e.g. XR_DEFINE_HANDLE(xrInstance) """
# Legacy types are typedef'ed to the new type if they are aliases.
if self.is_alias():
return "typedef {0} {1};\n".format(self.alias.name, self.name)
return "{0}({1})\n".format(self.type, self.name)
def is_alias(self):
return self.alias is not None
def is_dispatchable(self):
""" Some handles, like XrInstance, are dispatchable objects,
which means they contain a dispatch table of function pointers.
"""
return self.type == "XR_DEFINE_HANDLE"
def is_required(self):
return self.required
def native_handle(self, name):
""" Provide access to the native handle of a wrapped object. """
# Remember to add any new native handle whose parent is XrDevice
# to unwrap_object_handle() in openxr.c
if self.name == "XrCommandPool":
return "wine_cmd_pool_from_handle({0})->command_pool".format(name)
native_handle_name = None
if self.name in AUTO_MAPPED_HANDLES:
return None
if self.name == "XrInstance":
native_handle_name = "instance"
if self.name == "XrSession":
native_handle_name = "session"
if self.name == "XrSwapchain":
native_handle_name = "swapchain"
if self.name == "XrActionSet":
return None
if self.name == "XrAction":
return None
if native_handle_name:
return "((wine_{0} *){1})->{2}".format(self.name, name, native_handle_name)
if self.is_dispatchable():
LOGGER.error("Unhandled native handle for: {0}".format(self.name))
return None
class XrMember(object):
def __init__(self, const=False, struct_fwd_decl=False,_type=None, pointer=None, name=None, array_len=None,
dyn_array_len=None, optional=False, values=None):
self.const = const
self.struct_fwd_decl = struct_fwd_decl
self.name = name
self.pointer = pointer
self.type = _type
self.type_info = None
self.array_len = array_len
self.dyn_array_len = dyn_array_len
self.optional = optional
self.values = values
def __eq__(self, other):
""" Compare member based on name against a string.
This method is for convenience by XrStruct, which holds a number of members and needs quick checking
if certain members exist.
"""
return self.name == other
def __repr__(self):
return "{0} {1} {2} {3} {4} {5} {6}".format(self.const, self.struct_fwd_decl, self.type, self.pointer,
self.name, self.array_len, self.dyn_array_len)
@staticmethod
def from_xml(member):
""" Helper function for parsing a member tag within a struct or union. """
name_elem = member.find("name")
type_elem = member.find("type")
const = False
struct_fwd_decl = False
member_type = None
pointer = None
array_len = None
values = member.get("values")
if member.text:
if "const" in member.text:
const = True