-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathgenerate-gpup-webgl
More file actions
executable file
·1341 lines (1095 loc) · 51.9 KB
/
generate-gpup-webgl
File metadata and controls
executable file
·1341 lines (1095 loc) · 51.9 KB
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/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# This script generates the source files for WebGL GPU process IPC.
#
# python3 -m black -l 150 Tools/Scripts/generate-gpup-webgl
# python3 -m mypy Tools/Scripts/generate-gpup-webgl
#
import argparse
import enum
import pathlib
import re
import sys
import collections
from typing import List, Dict, Iterable, Callable, Tuple, Set, Optional, Generator, Iterator, Counter
root_dir = (pathlib.Path(__file__).parent / ".." / "..").resolve()
functions_input_fns = [root_dir / "Source" / "WebKit" / "WebProcess" / "GPU" / "graphics" / "RemoteGraphicsContextGLProxy.h"]
types_input_fn = root_dir / "Source" / "WebKit" / "WebProcess" / "GPU" / "graphics" / "RemoteGraphicsContextGLProxy.h"
template_preamble = """/* Copyright (C) 2020 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This file is generated by generate-gpup-webgl. Do not edit.
"""
context_functions_header_fn = root_dir / "Source" / "WebKit" / "GPUProcess" / "graphics" / "RemoteGraphicsContextGLFunctionsGenerated.h"
context_functions_header_template = (
template_preamble
+ """// This file should be included in the private section of the
// RemoteGraphicsContextGL implementations.
#pragma once
{}
"""
)
context_functions_impl_fn = root_dir / "Source" / "WebKit" / "GPUProcess" / "graphics" / "RemoteGraphicsContextGLFunctionsGenerated.cpp"
context_functions_impl_template = (
template_preamble
+ """
#include "config.h"
#include "RemoteGraphicsContextGL.h"
#include "Logging.h"
#include <wtf/StdLibExtras.h>
#if ENABLE(GPU_PROCESS) && ENABLE(WEBGL)
#define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, m_connection);
namespace WebKit {{
using namespace WebCore;
{}
}}
#undef MESSAGE_CHECK
#endif
"""
)
context_messages_fn = root_dir / "Source" / "WebKit" / "GPUProcess" / "graphics" / "RemoteGraphicsContextGL.messages.in"
context_messages_template = (
template_preamble
+ """#if ENABLE(GPU_PROCESS) && ENABLE(WEBGL)
[
DispatchedFrom=WebContent,
DispatchedTo=GPU,
EnabledBy=WebGLEnabled && UseGPUProcessForWebGLEnabled
]
messages -> RemoteGraphicsContextGL Stream {{
void Reshape(int32_t width, int32_t height)
#if PLATFORM(COCOA)
void PrepareForDisplay(IPC::Semaphore finishedFence) -> (MachSendRight displayBuffer) Synchronous NotStreamEncodable NotStreamEncodableReply
#endif
#if USE(GRAPHICS_LAYER_WC)
void PrepareForDisplay() -> (std::optional<WebKit::WCContentBufferIdentifier> contentBuffer) Synchronous
#endif
#if USE(GBM)
void PrepareForDisplay() -> (uint64_t bufferID, struct std::optional<WebCore::DMABufBufferAttributes> dmabufAttributes, UnixFileDescriptor fenceFD) Synchronous NotStreamEncodableReply
#endif
#if !PLATFORM(COCOA) && !USE(GRAPHICS_LAYER_WC) && !USE(GBM)
void PrepareForDisplay() -> () Synchronous
#endif
void EnsureExtensionEnabled(WebCore::GCGLExtension extension)
void GetErrors() -> (GCGLErrorCodeSet returnValue) Synchronous
void copyNativeImageYFlipped(enum:bool WebCore::GraphicsContextGLSurfaceBuffer buffer, WebCore::RenderingResourceIdentifier nativeImageIdentifier)
#if ENABLE(MEDIA_STREAM) || ENABLE(WEB_CODECS)
void SurfaceBufferToVideoFrame(enum:bool WebCore::GraphicsContextGLSurfaceBuffer buffer) -> (struct std::optional<WebKit::RemoteVideoFrameProxyProperties> properties) Synchronous
#endif
#if ENABLE(VIDEO) && PLATFORM(COCOA)
void CopyTextureFromVideoFrame(struct WebKit::SharedVideoFrame frame, PlatformGLObject texture, uint32_t target, int32_t level, uint32_t internalFormat, uint32_t format, uint32_t type, bool premultiplyAlpha, bool flipY) -> (bool success) Synchronous NotStreamEncodable
void SetSharedVideoFrameSemaphore(IPC::Semaphore semaphore) NotStreamEncodable
void SetSharedVideoFrameMemory(WebCore::SharedMemory::Handle storageHandle) NotStreamEncodable
#endif
void SimulateEventForTesting(enum:uint8_t WebCore::GraphicsContextGLSimulatedEventForTesting event)
void GetBufferSubDataInline(uint32_t target, uint64_t offset, uint64_t dataSize) -> (std::span<const uint8_t> data) Synchronous
void GetBufferSubDataSharedMemory(uint32_t target, uint64_t offset, uint64_t dataSize, WebCore::SharedMemory::Handle handle) -> (bool valid) Synchronous NotStreamEncodable
void ReadPixelsInline(WebCore::IntRect rect, uint32_t format, uint32_t type, bool packReverseRowOrder) -> (std::optional<WebCore::IntSize> readArea, std::span<const uint8_t> data) Synchronous
void ReadPixelsSharedMemory(WebCore::IntRect rect, uint32_t format, uint32_t type, bool packReverseRowOrder, WebCore::SharedMemory::Handle handle) -> (std::optional<WebCore::IntSize> readArea) Synchronous NotStreamEncodable
void MultiDrawArraysANGLE(uint32_t mode, IPC::ArrayReferenceTuple<int32_t, int32_t> firstsAndCounts)
void MultiDrawArraysInstancedANGLE(uint32_t mode, IPC::ArrayReferenceTuple<int32_t, int32_t, int32_t> firstsCountsAandInstanceCounts)
void MultiDrawElementsANGLE(uint32_t mode, IPC::ArrayReferenceTuple<int32_t, int32_t> countsAndOffsets, uint32_t type)
void MultiDrawElementsInstancedANGLE(uint32_t mode, IPC::ArrayReferenceTuple<int32_t, int32_t, int32_t> countsOffsetsAndInstanceCounts, uint32_t type)
void MultiDrawArraysInstancedBaseInstanceANGLE(uint32_t mode, IPC::ArrayReferenceTuple<int32_t, int32_t, int32_t, uint32_t> firstsCountsInstanceCountsAndBaseInstances)
void MultiDrawElementsInstancedBaseVertexBaseInstanceANGLE(uint32_t mode, IPC::ArrayReferenceTuple<int32_t, int32_t, int32_t, int32_t, uint32_t> countsOffsetsInstanceCountsBaseVerticesAndBaseInstances, uint32_t type)
void DrawBuffers(std::span<const uint32_t> bufs)
void DrawBuffersEXT(std::span<const uint32_t> bufs)
void InvalidateFramebuffer(uint32_t target, std::span<const uint32_t> attachments)
void InvalidateSubFramebuffer(uint32_t target, std::span<const uint32_t> attachments, int32_t x, int32_t y, int32_t width, int32_t height)
#if ENABLE(WEBXR)
[EnabledBy=WebXREnabled] void FramebufferDiscard(uint32_t target, std::span<const uint32_t> attachments)
#endif
void SetDrawingBufferColorSpace(WebCore::DestinationColorSpace colorSpace)
{}
}}
#endif
"""
)
context_proxy_functions_fn = root_dir / "Source" / "WebKit" / "WebProcess" / "GPU" / "graphics" / "RemoteGraphicsContextGLProxyFunctionsGenerated.cpp"
context_proxy_functions_template = (
template_preamble
+ """
#include "config.h"
#include "RemoteGraphicsContextGLProxy.h"
#include <wtf/StdLibExtras.h>
#if ENABLE(GPU_PROCESS) && ENABLE(WEBGL)
namespace WebKit {{
{}
}}
#endif
"""
)
def write_file(fn, new_contents):
try:
with open(fn) as f:
if f.read() == new_contents:
return
except:
pass
with open(fn, "w") as f:
f.write(new_contents)
class cpp_type(object):
type_name: str
def __init__(self, type_name: str):
self.type_name = type_name
def __str__(self):
return self.type_name
def __hash__(self):
return hash(self.type_name)
def __repr__(self):
return self.type_name
def __eq__(self, other):
return self.type_name == other.type_name
def is_void(self) -> bool:
return self.type_name in ["void", "GCGLvoid", "const void", "const GCGLvoid"]
def is_const(self) -> bool:
return self.type_name.startswith("const ")
def is_container(self) -> bool:
return False
def is_output_buffer_type(self) -> bool:
return False
def is_span(self) -> bool:
return False
def is_dynamic_span(self) -> bool:
return False
def is_pointer(self) -> bool:
return False
def is_const_pointer(self) -> bool:
return False
def is_reference(self) -> bool:
return False
def is_rvalue_reference(self):
return False
def is_const_reference(self) -> bool:
return False
def get_value_type(self) -> "cpp_type":
return self
def get_decay_type(self) -> "cpp_type":
if self.is_const():
return get_cpp_type(self.type_name[6:])
return self
def get_rvalue_type(self) -> "cpp_type":
return get_cpp_type(self.type_name + "&&")
def get_pointer_type(self) -> "cpp_type":
return get_cpp_type(self.type_name + "*")
class cpp_type_container(cpp_type):
container_name: str
contained_type: cpp_type
arity: Optional[int]
def __init__(self, type_name: str, container_name: str, contained_type: cpp_type, arity: Optional[int] = None):
cpp_type.__init__(self, type_name)
self.container_name = container_name
self.contained_type = contained_type
self.arity = arity
def is_container(self) -> bool:
return True
def is_span(self) -> bool:
return self.container_name == "std::span"
def is_dynamic_span(self) -> bool:
return (self.container_name == "std::span" and self.arity is None) or self.container_name == "GCGLSpanTuple"
def is_array(self) -> bool:
return self.container_name == "std::array"
def get_container_name(self):
return self.container_name
def get_arity(self) -> Optional[int]:
return self.arity
def get_contained_type(self) -> cpp_type:
return self.contained_type
def is_output_buffer_type(self) -> bool:
return self.contained_type.is_const()
def create_cpp_type_container(type_name: str) -> Optional[cpp_type_container]:
# The logic to determine container is to just assume all templates are containers.
m = re.match(r"([\w:]+)<(.+)>$", type_name)
if not m:
return None
container_name = m[1]
# All templates are containers except these below.
if container_name in ["RefPtr", "Ref", "RetainPtr", "std::optional"]:
return None
templates = m[2]
arity = None
m = re.match(r"([^,]+),\s*(\d+)", templates)
if m:
templates = m[1]
arity = int(m[2])
return cpp_type_container(type_name, container_name, get_cpp_type(templates), arity)
class cpp_type_function(cpp_type):
def __init__(self, type_name: str, return_value_type: cpp_type, argument_types: List[cpp_type]):
cpp_type.__init__(self, type_name)
self.return_value_type = return_value_type
self.argument_types = argument_types
def cpp_split_args_specs(args_spec: str) -> Iterator[str]:
# https://stackoverflow.com/questions/33527245/python-split-by-comma-skipping-the-content-inside-parentheses
comma = r",(?!(?:[^<]*\<[^>]*\>)*[^<>]*\>)"
return filter(None, [a.strip() for a in re.split(comma, args_spec.strip())])
def create_cpp_type_function(type_name: str) -> Optional[cpp_type_function]:
m = re.match(r"(.*)\((.*)\)", type_name)
if not m:
return None
return_value_type = get_cpp_type(m[1])
args_types = [get_cpp_type(a) for a in cpp_split_args_specs(m[2])]
return cpp_type_function(type_name, return_value_type, args_types)
# Pointer or refererence
class cpp_type_indirect(cpp_type):
category: str
value_type: cpp_type
def __init__(self, type_name: str, category: str, value_type: cpp_type):
cpp_type.__init__(self, type_name)
self.category = category
self.value_type = value_type
def is_const_pointer(self):
return self.category == "*" and self.is_const()
def is_pointer(self):
return self.category == "*" and not self.is_const()
def is_const_reference(self):
return self.category == "&" and self.is_const()
def is_reference(self):
return self.category == "&" and not self.is_const()
def is_rvalue_reference(self):
return self.category == "&&"
def get_value_type(self):
return self.value_type
def create_cpp_type_indirect(type_name: str) -> Optional[cpp_type_indirect]:
m = re.match(r"const (.+)&&$", type_name)
if not m:
m = re.match(r"(.+)&&$", type_name)
if m:
return cpp_type_indirect(type_name, "&&", get_cpp_type(m[1]))
m = re.match(r"const (.+)&$", type_name)
if not m:
m = re.match(r"(.+)&$", type_name)
if m:
return cpp_type_indirect(type_name, "&", get_cpp_type(m[1]))
m = re.match(r"const (.+)\*$", type_name)
if not m:
m = re.match(r"(.+)\*$", type_name)
if m:
return cpp_type_indirect(type_name, "*", get_cpp_type(m[1]))
return None
class cpp_expr(object):
type: cpp_type
expr: str
def __init__(self, type: cpp_type, expr: str):
self.type = type
self.expr = expr
def __str__(self):
return self.expr
CppExprConverter = Callable[[cpp_expr, cpp_type], cpp_expr]
def cpp_reinterpret_cast_from_pointer_through(cast_through_type: cpp_type) -> Callable[[cpp_expr, cpp_type], cpp_expr]:
def cpp_reinterpret_cast_from_pointer(expr: cpp_expr, type: cpp_type) -> cpp_expr:
return cpp_expr(type, f"static_cast<{type.type_name}>(reinterpret_cast<{str(cast_through_type)}>({str(expr)}))")
return cpp_reinterpret_cast_from_pointer
def cpp_reinterpret_cast_to_pointer_through(cast_through_type: cpp_type) -> Callable[[cpp_expr, cpp_type], cpp_expr]:
def cpp_reinterpret_cast_to_pointer(expr: cpp_expr, type: cpp_type) -> cpp_expr:
return cpp_expr(type, f"reinterpret_cast<{type.type_name}>(static_cast<{str(cast_through_type)}>({str(expr)}))")
return cpp_reinterpret_cast_to_pointer
def cpp_static_cast(expr: cpp_expr, type: cpp_type) -> cpp_expr:
return cpp_expr(type, f"static_cast<{type.type_name}>({str(expr)})")
def cpp_implicit_cast(expr: cpp_expr, type: cpp_type) -> cpp_expr:
return cpp_expr(type, str(expr))
def cpp_array_reinterpret_cast_conversion(expr: cpp_expr, type: cpp_type_container) -> cpp_expr:
target_value_type = type.get_contained_type().get_decay_type()
target_arity = f", {type.arity}" if type.arity else ""
source_value_type = expr.type.get_contained_type().get_decay_type()
source_arity = f", {expr.type.arity}" if expr.type.arity else ""
if expr.type.is_array():
return cpp_expr(
type, f"spanReinterpretCast<const {target_value_type}{target_arity}>(std::span<const {source_value_type}{source_arity}>({str(expr)}))"
)
else:
return cpp_expr(type, f"spanReinterpretCast<const {target_value_type}{target_arity}>({str(expr)}.span())")
def cpp_move_expr(expr: cpp_expr) -> cpp_expr:
return cpp_expr(expr.type.get_rvalue_type(), f"WTF::move({str(expr)})")
cpp_types: Dict[str, cpp_type] = {}
cpp_type_constructors: List[Callable[[str], Optional[cpp_type]]] = [create_cpp_type_function, create_cpp_type_container, create_cpp_type_indirect]
def get_cpp_type(type_name: str):
r = cpp_types.get(type_name, None)
if r:
return r
for type_constr in cpp_type_constructors:
r = type_constr(type_name)
if r:
break
if not r:
r = cpp_type(type_name)
cpp_types[type_name] = r
return r
class cpp_arg(object):
name: str
type: cpp_type
def __init__(self, type: cpp_type, name: str):
self.name = name
self.type = type
def get_declaration(self):
if self.name == "completionHandler":
return "{}".format(self.type)
return str(self)
def __str__(self):
return "{} {}".format(self.type, self.name)
class cpp_decl(object):
type: cpp_type
name: str
def __init__(self, type: cpp_type, name: str):
self.type = type
self.name = name
def __str__(self):
return f"{str(self.type)} {self.name}"
class cpp_arg_list(object):
args: List[cpp_arg]
def __init__(self, args: List[cpp_arg]):
self.args = args
def names(self):
return ", ".join(a.name for a in self.args)
def exprs(self):
return [cpp_expr(a.type, a.name) for a in self.args]
def decls(self):
return [cpp_decl(a.type, a.name) for a in self.args]
def types(self):
return [a.type for a in self.args]
def get_declaration(self):
return ", ".join(a.get_declaration() for a in self.args)
def __str__(self):
return ", ".join(str(a) for a in self.args)
class cpp_func(object):
name: str
args: cpp_arg_list
return_type: cpp_type
enabled_by: str
message_check: str
cond: str
overload_suffix: str
def __init__(self, name: str, return_type: cpp_type, args: cpp_arg_list, enabled_by: str, message_check: str, cond: str):
self.name = name
self.return_type = return_type
self.args = args
self.enabled_by = enabled_by
self.message_check = message_check
self.cond = cond
self.overload_suffix = ""
def __str__(self):
return f"{self.return_type} {self.name}({str(self.args)})"
def get_args_categories(self) -> Tuple[List[cpp_arg], List[cpp_arg]]:
in_args = []
out_args = []
for a in self.args.args:
# fmt: off
if a.type.is_pointer() or \
a.type.is_reference():
out_args += [a]
elif isinstance(a.type, cpp_type_container) and (((a.type.is_span() or a.type.is_dynamic_span()) and not a.type.get_contained_type().is_const())):
out_args += [a]
else:
in_args += [a]
# fmt: on
return in_args, out_args
def is_implemented_type(self, type: cpp_type):
if type.is_const_pointer():
return False
return True
def is_implemented(self):
# " in a.type.type_name for a in self.args.args):
# return False
# if "GCGLsync" in self.return_type.type_name:
# return False
if any(a.name == "bufSize" for a in self.args.args):
return False
if any(a.type.is_pointer() and a.type.get_value_type().is_void() for a in self.args.args):
return False
if any(not self.is_implemented_type(a.type) for a in self.args.args):
return False
if self.return_type.is_pointer():
return False
if not self.is_implemented_type(self.return_type):
return False
return True
webkit_ipc_types: Dict[cpp_type, cpp_type] = {}
webkit_ipc_types_converters: Dict[Tuple[cpp_type, cpp_type], CppExprConverter] = {}
def webkit_ipc_convert_expr(expr: cpp_expr, type: cpp_type) -> cpp_expr:
"""Converts `expr` of type of `self` to `type`"""
convert = webkit_ipc_types_converters.get((expr.type, type), None)
if convert:
return convert(expr, type)
if expr.type == type:
return expr
elif expr.type.is_rvalue_reference() and expr.type.get_value_type() == type:
return webkit_ipc_move_expr(expr)
elif type.is_rvalue_reference() and type.get_value_type() == expr.type:
return webkit_ipc_move_expr(expr)
return cpp_implicit_cast(expr, type)
def webkit_ipc_get_span_transfer_type(type: cpp_type_container) -> cpp_type:
element_type = type.get_contained_type().get_decay_type()
arity = type.get_arity()
webkit_ipc_element_type = webkit_ipc_types[element_type] if not element_type.is_void() else get_cpp_type("uint8_t")
if arity is not None:
return get_cpp_type(f"std::span<const {str(webkit_ipc_element_type)}, {arity}>")
return get_cpp_type(f"std::span<const {str(webkit_ipc_element_type)}>")
def webkit_ipc_get_span_store_type(type: cpp_type_container) -> cpp_type:
element_type = type.get_contained_type().get_decay_type()
if element_type.is_void():
element_type = get_cpp_type("GCGLchar")
if type.is_dynamic_span():
inline_capacity = 16 if "float" in element_type.type_name else 4
return get_cpp_type(f"Vector<{str(element_type)}, {str(inline_capacity)}>")
return get_cpp_type(f"std::array<{str(element_type)}, {str(type.get_arity())}>")
# See messages.py function_parameter_type
webkit_ipc_builtin_types = set(
["uint8_t", "uint16_t", "uint32_t", "uint64_t", "int8_t", "int16_t", "int32_t", "int64_t", "bool", "float", "double" "bool"]
)
def webkit_ipc_get_message_forwarder_type(type: cpp_type) -> cpp_type:
if type.type_name in webkit_ipc_builtin_types:
return type
return type.get_rvalue_type()
def webkit_ipc_move_expr(expr: cpp_expr) -> cpp_expr:
if expr.type.type_name in webkit_ipc_builtin_types:
return expr
return cpp_move_expr(expr)
def webkit_ipc_msg_name(func: cpp_func):
return func.name[0].capitalize() + func.name[1:] + func.overload_suffix
def to_variable_name(name: str) -> str:
return name[0].lower() + name[1:]
def to_member_variable_name(name: str) -> str:
return f"m_{to_variable_name(name)}"
def is_create_func(func: cpp_func) -> bool:
return func.name.startswith("create")
def get_create_func_object_name(name: str) -> str:
return name[len("create") :]
def is_delete_func(func: cpp_func) -> bool:
return func.name.startswith("delete")
def get_delete_func_object_name(name: str) -> str:
return name[len("delete") :]
def webkit_ipc_msg_arg_type(cpp_type: cpp_type) -> cpp_type:
ipc_type = webkit_ipc_types[cpp_type]
# FIXME: the messages.py generator should read the serializers and not need this.
if ipc_type == get_cpp_type("WebCore::GraphicsContextGLFlipY"):
return get_cpp_type("enum:bool WebCore::GraphicsContextGLFlipY")
if ipc_type == get_cpp_type("WebCore::GraphicsContextGLSimulatedEventForTesting"):
return get_cpp_type("enum:uint8_t WebCore::GraphicsContextGLSimulatedEventForTesting")
return ipc_type
# FIXME: these should be removed and IPC should know this.
non_stream_types = set({"WebCore::GraphicsContextGL::ExternalImageSource&&", "WebCore::GraphicsContextGL::ExternalSyncSource&&"})
class webkit_ipc_msg(object):
cond: str
enabled_by: str
name: str
in_args: cpp_arg_list
out_args: cpp_arg_list
def __init__(self, func: cpp_func):
self.cond = func.cond
self.enabled_by = func.enabled_by
self.name = webkit_ipc_msg_name(func)
in_args, out_args = func.get_args_categories()
ipc_in_args = [cpp_arg(webkit_ipc_msg_arg_type(a.type), a.name) for a in in_args]
ipc_out_args = []
if is_create_func(func):
name = get_create_func_object_name(func.name)
ipc_in_args.insert(0, cpp_arg(webkit_ipc_types[func.return_type], to_variable_name(name)))
elif not func.return_type.is_void():
ipc_out_args += [cpp_arg(webkit_ipc_types[func.return_type], "returnValue")]
for a in out_args:
ipc_out_args += [cpp_arg(webkit_ipc_types[a.type], a.name)]
if a.type.is_dynamic_span():
ipc_in_args += [cpp_arg(get_cpp_type("uint64_t"), f"{a.name}Size")]
self.in_args = cpp_arg_list(ipc_in_args)
self.out_args = cpp_arg_list(ipc_out_args)
self.tags = []
if any(arg.type.type_name in non_stream_types for arg in in_args):
self.tags += ["NotStreamEncodable"]
def __str__(self):
tags = f" {' '.join(self.tags)}" if self.tags else ""
enabled_by = f"[EnabledBy={self.enabled_by}] " if self.enabled_by else ""
if len(self.out_args.args):
return f"\n {enabled_by}void {self.name}({str(self.in_args)}) -> ({str(self.out_args)}) Synchronous{tags}"
return f"\n {enabled_by}void {self.name}({str(self.in_args)}){tags}"
class webkit_ipc_cpp_proxy_impl(object):
cond: str
name: str
is_create: bool
msg_name: str
return_type: cpp_type
args: cpp_arg_list
pre_call_stmts: List[str]
call_stmts: List[str]
post_call_stmts: List[str]
return_stmts: List[str]
in_exprs: List[cpp_expr]
out_exprs: List[cpp_expr]
def __init__(self, cpp_func: cpp_func):
self.cond = cpp_func.cond
self.name = cpp_func.name
self.is_create = is_create_func(cpp_func)
self.msg_name = webkit_ipc_msg_name(cpp_func)
self.return_type = cpp_func.return_type
self.args = cpp_func.args
self.pre_call_stmts = []
self.call_stmts = []
self.post_call_stmts = []
self.return_stmts = []
self.in_exprs = []
self.out_exprs = []
in_args, out_args = cpp_func.get_args_categories()
self.process_return_value(cpp_func.return_type)
self.process_in_args(in_args)
self.process_out_args(out_args)
self.process_call()
def process_call(self):
in_exprs = ", ".join([str(i) for i in self.in_exprs])
out_exprs = ", ".join(str(o) for o in self.out_exprs)
is_async = (self.return_type.is_void() or self.is_create) and len(out_exprs) == 0
self.call_stmts += ["if (isContextLost())"]
if self.return_type.is_void():
self.call_stmts += [" return;"]
else:
self.call_stmts += [" return { };"]
if self.is_create:
self.call_stmts += [f"auto name = createObjectName();"]
if is_async:
self.call_stmts += [
f"auto sendResult = send(Messages::RemoteGraphicsContextGL::{self.msg_name}({in_exprs}));",
"if (sendResult != IPC::Error::NoError) {",
]
else:
self.call_stmts += [
f"auto sendResult = sendSync(Messages::RemoteGraphicsContextGL::{self.msg_name}({in_exprs}));",
"if (!sendResult.succeeded()) {",
]
if self.return_type.is_void():
self.call_stmts += [
" markContextLost();",
" return;",
"}",
]
else:
self.call_stmts += [
" markContextLost();",
" return { };",
"}",
]
def process_in_args(self, in_args: List[cpp_arg]):
if self.is_create:
self.in_exprs += [webkit_ipc_convert_expr(cpp_expr(self.return_type, "name"), webkit_ipc_types[self.return_type])]
for i in in_args:
if i.type.is_const_pointer():
assert False
else:
self.in_exprs += [webkit_ipc_convert_expr(cpp_expr(i.type, i.name), webkit_ipc_types[i.type])]
def process_out_args(self, out_args: List[cpp_arg]):
for o in out_args:
if o.type.is_pointer():
value_type = o.type.get_value_type()
webkit_ipc_value_type = webkit_ipc_types[value_type]
v = cpp_arg(webkit_ipc_value_type, o.name + "Reply")
e = cpp_expr(v.type, v.name)
self.out_exprs += [e]
self.post_call_stmts += [
# fmt: off
f"if ({o.name})",
f" *{o.name} = {webkit_ipc_convert_expr(e, value_type)};"
# fmt: on
]
elif o.type.is_reference():
value_type = o.type.get_value_type()
v = cpp_arg(value_type, o.name + "Reply")
e = cpp_expr(v.type, v.name)
self.out_exprs += [e]
self.post_call_stmts += [
f"{o.name} = WTF::move({v.name});",
]
elif o.type.is_span():
webkit_ipc_type = webkit_ipc_types[o.type]
assert isinstance(webkit_ipc_type, cpp_type_container)
v = cpp_arg(webkit_ipc_type, o.name + "Reply")
self.out_exprs += [cpp_expr(v.type, v.name)]
if o.type.is_dynamic_span():
self.in_exprs += [cpp_expr(get_cpp_type("size_t"), f"{o.name}.size()")]
self.post_call_stmts += [f"memcpySpan({o.name}, {v.name});"]
else:
self.out_exprs += [cpp_expr(o.type, o.name)]
if self.out_exprs:
out_exprs = ", ".join(str(o) for o in self.out_exprs)
self.post_call_stmts = [
f"auto& [{out_exprs}] = sendResult.reply();",
] + self.post_call_stmts
def process_return_value(self, return_type: cpp_type):
if return_type.is_void():
return
if self.is_create:
self.return_stmts = [f"return name;"]
return
self.return_type = return_type
ipc_return_type = webkit_ipc_types[return_type]
return_value_expr = cpp_expr(ipc_return_type, "returnValue")
self.out_exprs = [return_value_expr] + self.out_exprs
self.return_stmts = [f"return {str(webkit_ipc_convert_expr(return_value_expr, return_type))};"]
def __str__(self):
nolint = " // NOLINT" if "_" in self.name else ""
body = "".join(f"\n {b}" for b in self.pre_call_stmts + self.call_stmts + self.post_call_stmts + self.return_stmts)
return f"""\n{str(self.return_type)} RemoteGraphicsContextGLProxy::{self.name}({str(self.args)}){nolint}
{{{body}
}}"""
class webkit_ipc_cpp_proxy_placeholder(object):
name: str
return_type: cpp_type
args: cpp_arg_list
body: List[str]
def __init__(self, cpp_func: cpp_func):
self.name = cpp_func.name
self.return_type = cpp_func.return_type
self.args = cpp_func.args
self.body = ["notImplemented();"]
if cpp_func.return_type.type_name != "void":
self.body += ["return { };"]
def __str__(self):
nolint = " // NOLINT" if "_" in self.name else ""
body = "\n{\n " + "\n ".join(self.body) + "\n}"
return f"\n{str(self.return_type)} RemoteGraphicsContextGLProxy::{self.name}({str(self.args)}){nolint}{body}"
class context_proxy_cpp_webkit_ipc_generator(object):
"RemoteGraphicsContextGLProxy C++ implementation generator."
impls: List[webkit_ipc_cpp_proxy_impl]
unimpls: List[webkit_ipc_cpp_proxy_placeholder]
cond: str
def __init__(self, funcs: Iterable[cpp_func], unimplemented: Iterable[cpp_func]):
self.impls = [webkit_ipc_cpp_proxy_impl(f) for f in funcs]
self.unimpls = [webkit_ipc_cpp_proxy_placeholder(f) for f in unimplemented]
self.cond = ""
def open_cond(self, impl):
if self.cond != impl.cond:
close_cond = "#endif\n" if self.cond else ""
open_cond = f"\n#if {impl.cond}" if impl.cond else ""
self.cond = impl.cond
return f"{close_cond}{open_cond}"
return ""
def close_cond(self):
if self.cond:
self.cond = ""
return "\n#endif"
return ""
def get_functions(self):
return "\n".join(f"{self.open_cond(i)}{i}" for i in self.impls) + self.close_cond() + "\n".join(str(i) for i in self.unimpls)
def generate(self):
write_file(
context_proxy_functions_fn,
context_proxy_functions_template.format(self.get_functions()),
)
named_object_types = set(["PlatformGLObject", "GCGLExternalImage", "GCGLExternalSync"])
class webkit_ipc_cpp_impl(object):
cond: str
name: str
enabled_by: str
args: cpp_arg_list
pre_call_stmts: List[str]
call_stmts: List[str]
post_call_stmts: List[str]
in_exprs: List[cpp_expr]
out_exprs: List[cpp_expr]
return_value_expr: Optional[cpp_expr]
def __init__(self, cpp_func: cpp_func):
self.cond = cpp_func.cond
self.name = cpp_func.name
self.message_check = cpp_func.message_check
self.is_create = is_create_func(cpp_func)
self.is_delete = is_delete_func(cpp_func)
self.overload_suffix = cpp_func.overload_suffix
self.args = cpp_arg_list([])
self.pre_call_stmts = []
self.call_stmts = []
self.post_call_stmts = []
self.in_exprs = []
self.out_exprs = []
self.return_value_expr = None
self.pre_call_stmts += ["assertIsCurrent(workQueue());"]
if self.message_check:
self.pre_call_stmts += [f"MESSAGE_CHECK({self.message_check});"]
self.process_return_value(cpp_func.return_type)
in_args, out_args = cpp_func.get_args_categories()
self.process_args(cpp_func.args.args, set(in_args), set(out_args))
self.process_call()
def process_call(self):
in_exprs = ", ".join(str(e) for e in self.in_exprs)
is_async = len(self.out_exprs) == 0
call_expr = f"protect(m_context)->{self.name}({in_exprs})"
if not self.return_value_expr:
self.call_stmts += [f"{call_expr};"]
else:
self.call_stmts += [f"{str(self.return_value_expr)} = {call_expr};"]
if not is_async:
out_exprs = ", ".join(str(e) for e in self.out_exprs)
self.post_call_stmts += [f"completionHandler({out_exprs});"]
def process_args(self, args: List[cpp_arg], in_args: Set[cpp_arg], out_args: Set[cpp_arg]):
for a in args:
if a.type.is_const_pointer():
assert False
if a in in_args:
self.process_in_arg(a)
else:
self.process_out_arg(a)
if self.out_exprs:
out_arg_decls = ", ".join(f"{str(e.type)}" for e in self.out_exprs)
self.args.args += [cpp_arg(get_cpp_type(f"CompletionHandler<void({out_arg_decls})>&&"), "completionHandler")]
def process_in_arg(self, a: cpp_arg):
self.args.args += [cpp_arg(webkit_ipc_get_message_forwarder_type(webkit_ipc_types[a.type]), a.name)]
self.in_exprs += [webkit_ipc_convert_expr(cpp_expr(webkit_ipc_types[a.type], a.name), a.type)]
if a.type.type_name in named_object_types:
if self.is_create:
self.pre_call_stmts += [f"MESSAGE_CHECK({a.name});"]
if self.is_delete:
self.pre_call_stmts += [
f"MESSAGE_CHECK(m_objectNames.isValidKey({a.name}));",
f"if (!{a.name}) [[unlikely]]",
f" return;",
f"{a.name} = m_objectNames.take({a.name});",
]
else:
self.pre_call_stmts += [
f"MESSAGE_CHECK(m_objectNames.isValidKey({a.name}));",
f"if ({a.name})",
f" {a.name} = m_objectNames.get({a.name});",
]
def process_out_arg(self, a: cpp_arg):
if a.type.is_pointer():
value_arg = cpp_arg(a.type.get_value_type(), a.name)
self.pre_call_stmts += [f"{str(value_arg.type)} {str(value_arg.name)} = {{ }};"]
self.in_exprs += [cpp_expr(a.type, f"&{value_arg.name}")]
e = cpp_expr(value_arg.type, value_arg.name)
webkit_ipc_value_type = webkit_ipc_types[e.type]
self.out_exprs += [webkit_ipc_convert_expr(e, webkit_ipc_value_type)]
elif a.type.is_dynamic_span():
assert isinstance(a.type, cpp_type_container)