-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathJavaScriptEnvironment.swift
More file actions
4133 lines (3726 loc) · 215 KB
/
JavaScriptEnvironment.swift
File metadata and controls
4133 lines (3726 loc) · 215 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
// Copyright 2019 Google LLC
//
// 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
//
// https://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 Foundation
public class JavaScriptEnvironment: ComponentBase {
// Possible return values of the 'typeof' operator.
public static let jsTypeNames = ["undefined", "boolean", "number", "string", "symbol", "function", "object", "bigint"]
// TODO: use it in all places where it can be used.
public static let typedArrayConstructors = [
"Uint8Array", "Int8Array", "Uint16Array", "Int16Array",
"Uint32Array", "Int32Array", "Float16Array", "Float32Array", "Float64Array",
"Uint8ClampedArray", "BigInt64Array", "BigUint64Array",
]
// Integer values that are more likely to trigger edge-cases.
public static let InterestingIntegers: [Int64] = [
-9223372036854775808, -9223372036854775807, // Int64 min, mostly for BigInts
-9007199254740992, -9007199254740991, -9007199254740990, // Smallest integer value that is still precisely representable by a double
-4294967297, -4294967296, -4294967295, // Negative Uint32 max
-2147483649, -2147483648, -2147483647, // Int32 min
-1073741824, -536870912, -268435456, // -2**32 / {4, 8, 16}
-65537, -65536, -65535, // -2**16
-4096, -1024, -256, -128, // Other powers of two
-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 64, // Numbers around 0
127, 128, 129, // 2**7
255, 256, 257, // 2**8
512, 1000, 1024, 4096, 10000, // Misc numbers
65535, 65536, 65537, // 2**16
268435439, 268435440, 268435441, // V8 String kMaxLength (32-bit)
536870887, 536870888, 536870889, // V8 String kMaxLength (64-bit)
268435456, 536870912, 1073741824, // 2**32 / {4, 8, 16}
1073741823, 1073741824, 1073741825, // 2**30
2147483647, 2147483648, 2147483649, // Int32 max
4294967295, 4294967296, 4294967297, // Uint32 max
9007199254740990, 9007199254740991, 9007199254740992, // Biggest integer value that is still precisely representable by a double
9223372036854775807, // Int64 max, mostly for BigInts
]
static let wellKnownSymbols = ["iterator", "asyncIterator", "match", "matchAll", "replace", "search", "split", "hasInstance", "isConcatSpreadable", "unscopables", "species", "toPrimitive", "toStringTag", "dispose", "asyncDispose"]
public let interestingIntegers = InterestingIntegers
// Double values that are more likely to trigger edge-cases.
public let interestingFloats = [-Double.infinity, -Double.greatestFiniteMagnitude, -1e-15, -1e12, -1e9, -1e6, -1e3, -5.0, -4.0, -3.0, -2.0, -1.0, -Double.ulpOfOne, -Double.leastNormalMagnitude, -0.0, 0.0, Double.leastNormalMagnitude, Double.ulpOfOne, 1.0, 2.0, 3.0, 4.0, 5.0, 1e3, 1e6, 1e9, 1e12, 1e-15, Double.greatestFiniteMagnitude, Double.infinity, Double.nan]
// TODO more?
public let interestingStrings = jsTypeNames
// Copied from
// https://cs.chromium.org/chromium/src/testing/libfuzzer/fuzzers/dicts/regexp.dict
public let interestingRegExps = [
// These do *not* work with unicode or unicodeSets
(pattern: #"a\q"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"{12,3b"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"a{z}"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[z-\d]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"{z}"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"{"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"(x)(x)(x)(x)(x)(x)(x)(x)(x)(x)\11"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\111]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\c!"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\11a]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\c!]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\c~]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\[\]\{\}\(\)\%\^\#\ "#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\[\]\{\}\(\)\%\^\#\ ]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\118"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\00011]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\c~"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"{,}"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[-123]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[-\xf0\x9f\x92\xa9]+"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"a{,}"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"{12,"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"(?!a)?a"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\111"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"(?!a)?a\1"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\1111]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"a{12,3b"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\c1]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"(?=a){0,10}a"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\q"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"a{12z}"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\011"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\d-z]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\011]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\8"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\11a"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\118]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\1112"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"a{12,"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\d-\d]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\11"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"(x)(x)(x)\4*"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"(?:(?=a))a\1"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"a{}"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\c_"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"a{"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"(x)(x)(x)\4"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\c"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\x3z"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\c_]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"{1z}"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"(?=a){1,10}a"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\1111"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\u003z"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[\11]"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"\9"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"}"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"{}"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"(?=a){9,10}a"#, incompatibleFlags: .unicode | .unicodeSets),
(pattern: #"[a-b-c]"#, incompatibleFlags: .unicode | .unicodeSets),
// These work with all flags
(pattern: #"(x)(x)(x)\1*"#, incompatibleFlags: .empty),
(pattern: #"\x01"#, incompatibleFlags: .empty),
(pattern: #"(?: foo )"#, incompatibleFlags: .empty),
(pattern: #"(ab|cde)"#, incompatibleFlags: .empty),
(pattern: #"foo|(bar|baz)|quux"#, incompatibleFlags: .empty),
(pattern: #"(?:a*)*"#, incompatibleFlags: .empty),
(pattern: #"a{0,1}?"#, incompatibleFlags: .empty),
(pattern: #"(?:a+)?"#, incompatibleFlags: .empty),
(pattern: #"a$"#, incompatibleFlags: .empty),
(pattern: #"a(?=b)"#, incompatibleFlags: .empty),
(pattern: #"foo[z]*"#, incompatibleFlags: .empty),
(pattern: #"\u{12345}\u{23456}"#, incompatibleFlags: .empty),
(pattern: #"(?!(a))\1"#, incompatibleFlags: .empty),
(pattern: #"abc+?"#, incompatibleFlags: .empty),
(pattern: #"a*b"#, incompatibleFlags: .empty),
(pattern: #"(?:a?)*"#, incompatibleFlags: .empty),
(pattern: #"\xf0\x9f\x92\xa9"#, incompatibleFlags: .empty),
(pattern: #"a{1,2}?"#, incompatibleFlags: .empty),
(pattern: #"a\n"#, incompatibleFlags: .empty),
(pattern: #"\P{Decimal_Number}"#, incompatibleFlags: .empty),
(pattern: #"(?=)"#, incompatibleFlags: .empty),
(pattern: #"\1(a)"#, incompatibleFlags: .empty),
(pattern: #"."#, incompatibleFlags: .empty),
(pattern: #"()"#, incompatibleFlags: .empty),
(pattern: #"(a)"#, incompatibleFlags: .empty),
(pattern: #"(?:a{5,1000000}){3,1000000}"#, incompatibleFlags: .empty),
(pattern: #"a\Sc"#, incompatibleFlags: .empty),
(pattern: #"a(?=b)c"#, incompatibleFlags: .empty),
(pattern: #"a{0}"#, incompatibleFlags: .empty),
(pattern: #"(?:a*)+"#, incompatibleFlags: .empty),
(pattern: #"\ud808\udf45*"#, incompatibleFlags: .empty),
(pattern: #"a\w"#, incompatibleFlags: .empty),
(pattern: #"(?:a+)*"#, incompatibleFlags: .empty),
(pattern: #"a(?:b)"#, incompatibleFlags: .empty),
(pattern: #"(?<=a)"#, incompatibleFlags: .empty),
(pattern: #"(x)(x)(x)\3"#, incompatibleFlags: .empty),
(pattern: #"foo(?<=bar)baz"#, incompatibleFlags: .empty),
(pattern: #"\xe2\x81\xa3"#, incompatibleFlags: .empty),
(pattern: #"ab\b\d\bcd"#, incompatibleFlags: .empty),
(pattern: #"[\ca]"#, incompatibleFlags: .empty),
(pattern: #"[\xf0\x9f\x92\xa9-\xf4\x8f\xbf\xbf]"#, incompatibleFlags: .empty),
(pattern: #"\p{Script_Extensions=Greek}"#, incompatibleFlags: .empty),
(pattern: #"\cj\cJ\ci\cI\ck\cK"#, incompatibleFlags: .empty),
(pattern: #"a\fb\nc\rd\te\vf"#, incompatibleFlags: .empty),
(pattern: #"\p{General_Category=Decimal_Number}"#, incompatibleFlags: .empty),
(pattern: #"\u{12345}"#, incompatibleFlags: .empty),
(pattern: #"a\b!"#, incompatibleFlags: .empty),
(pattern: #"a[^a]"#, incompatibleFlags: .empty),
(pattern: #"\1\2(a(?:\1(b\1\2))\2)\1"#, incompatibleFlags: .empty),
(pattern: #"(?:ab)+"#, incompatibleFlags: .empty),
(pattern: #"[^123]"#, incompatibleFlags: .empty),
(pattern: #"a(?!b)"#, incompatibleFlags: .empty),
(pattern: #"a\Bb"#, incompatibleFlags: .empty),
(pattern: #"(?:ab)?"#, incompatibleFlags: .empty),
(pattern: #"(?<a>)"#, incompatibleFlags: .empty),
(pattern: #"(?<!)"#, incompatibleFlags: .empty),
(pattern: #"a."#, incompatibleFlags: .empty),
(pattern: #"[]"#, incompatibleFlags: .empty),
(pattern: #"a\S"#, incompatibleFlags: .empty),
(pattern: #"abc"#, incompatibleFlags: .empty),
(pattern: #"(?<!a)"#, incompatibleFlags: .empty),
(pattern: #"\x60"#, incompatibleFlags: .empty),
(pattern: #"[\p{Script_Extensions=Mongolian}&&\p{Number}]"#, incompatibleFlags: .empty),
(pattern: #"a\nb\bc"#, incompatibleFlags: .empty),
(pattern: #"(?:ab)|cde"#, incompatibleFlags: .empty),
(pattern: #"^"#, incompatibleFlags: .empty),
(pattern: #"a\W"#, incompatibleFlags: .empty),
(pattern: #"a"#, incompatibleFlags: .empty),
(pattern: #"a[a]"#, incompatibleFlags: .empty),
(pattern: #"(x)(x)(x)\1"#, incompatibleFlags: .empty),
(pattern: #"[\cA]"#, incompatibleFlags: .empty),
(pattern: #"(ab)\1"#, incompatibleFlags: .empty),
(pattern: #"a(?=bbb|bb)c"#, incompatibleFlags: .empty),
(pattern: #"(x)(x)(x)(x)(x)(x)(x)(x)(x)(x)\10"#, incompatibleFlags: .empty),
(pattern: #"\P{sc=Greek}"#, incompatibleFlags: .empty),
(pattern: #"foo(?!bar)baz"#, incompatibleFlags: .empty),
(pattern: #"xyz??"#, incompatibleFlags: .empty),
(pattern: #"a[bc]d"#, incompatibleFlags: .empty),
(pattern: #"a*?"#, incompatibleFlags: .empty),
(pattern: #"((\xed\xa0\x80))\x02"#, incompatibleFlags: .empty),
(pattern: #"a+"#, incompatibleFlags: .empty),
(pattern: #"\P{scx=Greek}"#, incompatibleFlags: .empty),
(pattern: #"(?<=)"#, incompatibleFlags: .empty),
(pattern: #"(?:foo)"#, incompatibleFlags: .empty),
(pattern: #"xyz{1,}?"#, incompatibleFlags: .empty),
(pattern: #"(a)\1"#, incompatibleFlags: .empty),
(pattern: #"a[a-z]"#, incompatibleFlags: .empty),
(pattern: #"\p{Nd}"#, incompatibleFlags: .empty),
(pattern: #"(?:ab)"#, incompatibleFlags: .empty),
(pattern: #"a+b|c"#, incompatibleFlags: .empty),
(pattern: #"(ab|cde)\1"#, incompatibleFlags: .empty),
(pattern: #"(\xed\xb0\x80)\x01"#, incompatibleFlags: .empty),
(pattern: #"((((.).).).)"#, incompatibleFlags: .empty),
(pattern: #"(?:a?)+"#, incompatibleFlags: .empty),
(pattern: #"(a\1)"#, incompatibleFlags: .empty),
(pattern: #"\P{Any}"#, incompatibleFlags: .empty),
(pattern: #"xyz{93}"#, incompatibleFlags: .empty),
(pattern: #"\x0f"#, incompatibleFlags: .empty),
(pattern: #"(ab)"#, incompatibleFlags: .empty),
(pattern: #"\w|\d"#, incompatibleFlags: .empty),
(pattern: #"xyz{1,32}"#, incompatibleFlags: .empty),
(pattern: #"[x\dz]"#, incompatibleFlags: .empty),
(pattern: #"\xed\xa0\x80"#, incompatibleFlags: .empty),
(pattern: #"xyz{1,}"#, incompatibleFlags: .empty),
(pattern: #"\p{gc=Nd}"#, incompatibleFlags: .empty),
(pattern: #"\xed\xb0\x80"#, incompatibleFlags: .empty),
(pattern: #"[\0]"#, incompatibleFlags: .empty),
(pattern: #"^xxx$"#, incompatibleFlags: .empty),
(pattern: #"a?"#, incompatibleFlags: .empty),
(pattern: #"a\s"#, incompatibleFlags: .empty),
(pattern: #"a+?"#, incompatibleFlags: .empty),
(pattern: #"xyz{0,1}?"#, incompatibleFlags: .empty),
(pattern: #"(\1a)"#, incompatibleFlags: .empty),
(pattern: #"a(?!bbb|bb)c"#, incompatibleFlags: .empty),
(pattern: #"\p{Script=Greek}"#, incompatibleFlags: .empty),
(pattern: #"\u0060"#, incompatibleFlags: .empty),
(pattern: #"[xyz]"#, incompatibleFlags: .empty),
(pattern: #"(?:a+){0,0}"#, incompatibleFlags: .empty),
(pattern: #"(\2)(\1)"#, incompatibleFlags: .empty),
(pattern: #"xyz{1,32}?"#, incompatibleFlags: .empty),
(pattern: #"(?<a>.)"#, incompatibleFlags: .empty),
(pattern: #"[\cz]"#, incompatibleFlags: .empty),
(pattern: #"(x)(x)(x)\3*"#, incompatibleFlags: .empty),
(pattern: #"foo(?<!bar)baz"#, incompatibleFlags: .empty),
(pattern: #"abc+"#, incompatibleFlags: .empty),
(pattern: #"foo(?=bar)baz"#, incompatibleFlags: .empty),
(pattern: #"a|bc"#, incompatibleFlags: .empty),
(pattern: #"abc|def"#, incompatibleFlags: .empty),
(pattern: #"a*b|c"#, incompatibleFlags: .empty),
(pattern: #"(x)(x)(x)\2"#, incompatibleFlags: .empty),
(pattern: #"(?<a>.)\k<a>"#, incompatibleFlags: .empty),
(pattern: #"(?:a+)+"#, incompatibleFlags: .empty),
(pattern: #"(?=.)"#, incompatibleFlags: .empty),
(pattern: #"\p{Changes_When_NFKC_Casefolded}"#, incompatibleFlags: .empty),
(pattern: #"a\sc"#, incompatibleFlags: .empty),
(pattern: #"a||bc"#, incompatibleFlags: .empty),
(pattern: #"a+b"#, incompatibleFlags: .empty),
(pattern: #"[\cZ]"#, incompatibleFlags: .empty),
(pattern: #"a|b"#, incompatibleFlags: .empty),
(pattern: #"\u0034"#, incompatibleFlags: .empty),
(pattern: #"\cA"#, incompatibleFlags: .empty),
(pattern: #"ab|c"#, incompatibleFlags: .empty),
(pattern: #"abc|def|ghi"#, incompatibleFlags: .empty),
(pattern: #"(?:ab|cde)"#, incompatibleFlags: .empty),
(pattern: #"xyz?"#, incompatibleFlags: .empty),
(pattern: #"[a-zA-Z0-9]"#, incompatibleFlags: .empty),
(pattern: #"(?:a?)?"#, incompatibleFlags: .empty),
(pattern: #"xyz{0,1}"#, incompatibleFlags: .empty),
(pattern: #"a\D"#, incompatibleFlags: .empty),
(pattern: #"(?!\1(a\1)\1)\1"#, incompatibleFlags: .empty),
(pattern: #"a\bc"#, incompatibleFlags: .empty),
(pattern: #"\P{gc=Decimal_Number}"#, incompatibleFlags: .empty),
(pattern: #"\b"#, incompatibleFlags: .empty),
(pattern: #"[x]"#, incompatibleFlags: .empty),
(pattern: #"(?:ab){4,7}"#, incompatibleFlags: .empty),
(pattern: #"a??"#, incompatibleFlags: .empty),
(pattern: #"(?<a>(?<b>(?<c>(?<d>.).).).)"#, incompatibleFlags: .empty),
(pattern: #"[\xe2\x81\xa3]"#, incompatibleFlags: .empty),
]
public let interestingRegExpQuantifiers = ["*", "+", "?"]
/// Identifiers that should be used for custom properties and methods.
public static let CustomPropertyNames = ["a", "b", "c", "d", "e", "f", "g", "h"]
public static let CustomMethodNames = ["m", "n", "o", "?", "67", "valueOf", "toString"]
public static let CustomPrivateMethodNames = ["m", "n", "o", "p"]
public private(set) var builtins = Set<String>()
public let customProperties = Set<String>(CustomPropertyNames)
public let customMethods = Set<String>(CustomMethodNames)
public let customPrivateMethods = Set<String>(CustomPrivateMethodNames)
public private(set) var builtinProperties = Set<String>()
public private(set) var builtinMethods = Set<String>()
// Something that can generate a variable
public typealias EnvironmentValueGenerator = (ProgramBuilder) -> Variable
private var builtinTypes: [String: ILType] = [:]
private var groups: [String: ObjectGroup] = [:]
private var enums: [String: ILType] = [:]
// Producing generators, keyed on `type.group`
private var producingGenerators: [String: (generator: EnvironmentValueGenerator, probability: Double)] = [:]
// Named string generators, keyed on `type.group`
private var namedStringGenerators: [String: () -> String] = [:]
private var producingMethods: [ILType: [(group: String, method: String)]] = [:]
private var producingProperties: [ILType: [(group: String, property: String)]] = [:]
private var subtypes: [ILType: [ILType]] = [:]
private let validMethodDefinitionName: Regex<AnyRegexOutput>?
private let validDotNotationName: Regex<AnyRegexOutput>?
private let validPropertyIndex: Regex<AnyRegexOutput>?
public init(additionalBuiltins: [String: ILType] = [:], additionalObjectGroups: [ObjectGroup] = [], additionalEnumerations: [ILType] = []) {
// A simple approximation of a valid JS identifier (used in dot
// notation and for method definitions).
let simpleId = "[_$a-zA-Z][_$a-zA-Z0-9]*"
// A non-negative integer (with no leading zero) for index access
// without quotes.
let index = "[1-9]\\d*|0"
// Initialize regular expressions to determine valid property
// identifiers:
// At method definition site, we support simple identifiers and
// non-negative numbers. Other names will be quoted.
// We don't support unquoted doubles.
self.validMethodDefinitionName = try! Regex("^(\(index)|\(simpleId))$")
// For dot notation we only support simple identifiers. We don't
// support all possible names according to JS spec.
// Unsupported names will be accessed with bracket notation.
self.validDotNotationName = try! Regex("^(\(simpleId))$")
// Valid indexes to use in bracket notation without quotes.
self.validPropertyIndex = try! Regex("^(\(index))$")
super.init(name: "JavaScriptEnvironment")
// Build model of the JavaScript environment
// Register all object groups that we use to model the JavaScript runtime environment.
// The object groups allow us to associate type information for properties and methods
// with groups of related objects, e.g. strings, arrays, etc.
// It generally doesn't hurt to leave all of these enabled. If specific APIs should be disabled,
// it is best to either just disable the builtin that exposes it (e.g. Map constructor) or
// selectively disable methods/properties by commenting out parts of the ObjectGroup and
// Type definitions at the end of this file.
registerObjectGroup(.jsStrings)
registerObjectGroup(.jsArrays)
registerObjectGroup(.jsArguments)
registerObjectGroup(.jsIterator)
registerObjectGroup(.jsIteratorPrototype)
registerObjectGroup(.jsIteratorConstructor)
registerObjectGroup(.jsGenerators)
registerObjectGroup(.jsPromises)
registerObjectGroup(.jsRegExps)
registerObjectGroup(.jsFunctions)
registerObjectGroup(.jsFunctionPrototype)
registerObjectGroup(.jsFunctionConstructor)
registerObjectGroup(.jsSymbols)
registerObjectGroup(.jsMaps)
registerObjectGroup(.jsMapPrototype)
registerObjectGroup(.jsMapConstructor)
registerObjectGroup(.jsWeakMaps)
registerObjectGroup(.jsWeakMapPrototype)
registerObjectGroup(.jsWeakMapConstructor)
registerObjectGroup(.jsSets)
registerObjectGroup(.jsSetPrototype)
registerObjectGroup(.jsSetConstructor)
registerObjectGroup(.jsWeakSets)
registerObjectGroup(.jsWeakSetPrototype)
registerObjectGroup(.jsWeakSetConstructor)
registerObjectGroup(.jsWeakRefs)
registerObjectGroup(.jsWeakRefPrototype)
registerObjectGroup(.jsWeakRefConstructor)
registerObjectGroup(.jsFinalizationRegistrys)
registerObjectGroup(.jsFinalizationRegistryPrototype)
registerObjectGroup(.jsFinalizationRegistryConstructor)
registerObjectGroup(.jsDisposableStacks)
registerObjectGroup(.jsDisposableStackPrototype)
registerObjectGroup(.jsDisposableStackConstructor)
registerObjectGroup(.jsAsyncDisposableStacks)
registerObjectGroup(.jsAsyncDisposableStackPrototype)
registerObjectGroup(.jsAsyncDisposableStackConstructor)
registerObjectGroup(.jsArrayBuffers)
registerObjectGroup(.jsSharedArrayBuffers)
for variant in ["Uint8Array", "Int8Array", "Uint16Array", "Int16Array", "Uint32Array", "Int32Array", "Float16Array", "Float32Array", "Float64Array", "Uint8ClampedArray", "BigInt64Array", "BigUint64Array"] {
registerObjectGroup(.jsTypedArrays(variant))
registerObjectGroup(.jsTypedArrayPrototype(variant))
registerObjectGroup(.jsTypedArrayConstructor(variant))
}
registerObjectGroup(.jsDataViews)
registerObjectGroup(.jsDataViewPrototype)
registerObjectGroup(.jsDataViewConstructor)
registerObjectGroup(.jsObjectConstructor)
registerObjectGroup(.jsPromiseConstructor)
registerObjectGroup(.jsPromisePrototype)
registerObjectGroup(.jsProxyConstructor)
registerObjectGroup(.jsArrayConstructor)
registerObjectGroup(.jsStringConstructor)
registerObjectGroup(.jsStringPrototype)
registerObjectGroup(.jsSymbolConstructor)
registerObjectGroup(.jsBigIntConstructor)
registerObjectGroup(.jsRegExpPrototype)
registerObjectGroup(.jsRegExpConstructor)
registerObjectGroup(.jsBooleanConstructor)
registerObjectGroup(.jsNumberConstructor)
registerObjectGroup(.jsMathObject)
registerObjectGroup(.jsAtomicsObject)
registerObjectGroup(.jsDate)
registerObjectGroup(.jsDateConstructor)
registerObjectGroup(.jsDatePrototype)
registerObjectGroup(.jsJSONObject)
registerObjectGroup(.jsReflectObject)
registerObjectGroup(.jsArrayBufferConstructor)
registerObjectGroup(.jsArrayBufferPrototype)
registerObjectGroup(.jsSharedArrayBufferConstructor)
registerObjectGroup(.jsSharedArrayBufferPrototype)
for variant in ["Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "AggregateError", "URIError", "SuppressedError"] {
registerObjectGroup(.jsError(variant))
registerObjectGroup(.jsErrorPrototype(variant))
registerObjectGroup(.jsErrorConstructor(variant))
}
registerObjectGroup(.jsWebAssemblyCompileOptions)
registerObjectGroup(.jsWebAssemblyModuleConstructor)
registerObjectGroup(.jsWebAssemblyGlobalConstructor)
registerObjectGroup(.jsWebAssemblyGlobalPrototype)
registerObjectGroup(.jsWebAssemblyInstanceConstructor)
registerObjectGroup(.jsWebAssemblyInstance)
registerObjectGroup(.jsWebAssemblyModule)
registerObjectGroup(.jsWebAssemblyMemoryPrototype)
registerObjectGroup(.jsWebAssemblyMemoryConstructor)
registerObjectGroup(.jsWebAssemblyTablePrototype)
registerObjectGroup(.jsWebAssemblyTableConstructor)
registerObjectGroup(.jsWebAssemblyTagPrototype)
registerObjectGroup(.jsWebAssemblyTagConstructor)
registerObjectGroup(.jsWebAssemblyException)
registerObjectGroup(.jsWebAssemblyExceptionPrototype)
registerObjectGroup(.jsWebAssemblyExceptionConstructor)
registerObjectGroup(.jsWebAssembly)
registerObjectGroup(.jsWasmGlobal)
registerObjectGroup(.jsWasmMemory)
registerObjectGroup(.wasmTable)
registerObjectGroup(.jsWasmTag)
registerObjectGroup(.jsWasmSuspendingObject)
registerObjectGroup(.jsTemporalObject)
registerObjectGroup(.jsTemporalNow)
registerObjectGroup(.jsTemporalInstant)
registerObjectGroup(.jsTemporalInstantConstructor)
registerObjectGroup(.jsTemporalInstantPrototype)
registerObjectGroup(.jsTemporalDuration)
registerObjectGroup(.jsTemporalDurationConstructor)
registerObjectGroup(.jsTemporalDurationPrototype)
registerObjectGroup(.jsTemporalPlainTime)
registerObjectGroup(.jsTemporalPlainTimeConstructor)
registerObjectGroup(.jsTemporalPlainTimePrototype)
registerObjectGroup(.jsTemporalPlainYearMonth)
registerObjectGroup(.jsTemporalPlainYearMonthConstructor)
registerObjectGroup(.jsTemporalPlainYearMonthPrototype)
registerObjectGroup(.jsTemporalPlainMonthDay)
registerObjectGroup(.jsTemporalPlainMonthDayConstructor)
registerObjectGroup(.jsTemporalPlainMonthDayPrototype)
registerObjectGroup(.jsTemporalPlainDate)
registerObjectGroup(.jsTemporalPlainDateConstructor)
registerObjectGroup(.jsTemporalPlainDatePrototype)
registerObjectGroup(.jsTemporalPlainDateTime)
registerObjectGroup(.jsTemporalPlainDateTimeConstructor)
registerObjectGroup(.jsTemporalPlainDateTimePrototype)
registerObjectGroup(.jsTemporalZonedDateTime)
registerObjectGroup(.jsTemporalZonedDateTimeConstructor)
registerObjectGroup(.jsTemporalZonedDateTimePrototype)
registerObjectGroup(.jsIntlObject)
registerObjectGroup(.jsIntlCollator)
registerObjectGroup(.jsIntlCollatorConstructor)
registerObjectGroup(.jsIntlCollatorPrototype)
registerObjectGroup(.jsIntlDisplayNames)
registerObjectGroup(.jsIntlDisplayNamesConstructor)
registerObjectGroup(.jsIntlDisplayNamesPrototype)
registerObjectGroup(.jsIntlDurationFormat)
registerObjectGroup(.jsIntlDurationFormatConstructor)
registerObjectGroup(.jsIntlDurationFormatPrototype)
registerObjectGroup(.jsIntlDateTimeFormat)
registerObjectGroup(.jsIntlDateTimeFormatConstructor)
registerObjectGroup(.jsIntlDateTimeFormatPrototype)
registerObjectGroup(.jsIntlListFormat)
registerObjectGroup(.jsIntlListFormatConstructor)
registerObjectGroup(.jsIntlListFormatPrototype)
registerObjectGroup(.jsIntlLocale)
registerObjectGroup(.jsIntlLocaleConstructor)
registerObjectGroup(.jsIntlLocalePrototype)
registerObjectGroup(.jsIntlNumberFormat)
registerObjectGroup(.jsIntlNumberFormatConstructor)
registerObjectGroup(.jsIntlNumberFormatPrototype)
registerObjectGroup(.jsIntlPluralRules)
registerObjectGroup(.jsIntlPluralRulesConstructor)
registerObjectGroup(.jsIntlPluralRulesPrototype)
registerObjectGroup(.jsIntlRelativeTimeFormat)
registerObjectGroup(.jsIntlRelativeTimeFormatConstructor)
registerObjectGroup(.jsIntlRelativeTimeFormatPrototype)
registerObjectGroup(.jsIntlSegmenter)
registerObjectGroup(.jsIntlSegmenterConstructor)
registerObjectGroup(.jsIntlSegmenterPrototype)
registerObjectGroup(.jsIntlSegmenterSegments)
for group in additionalObjectGroups {
registerObjectGroup(group)
}
registerEnumeration(.jsTemporalCalendarEnum)
registerEnumeration(ObjectGroup.jsTemporalDirectionParam)
registerEnumeration(ObjectGroup.jsIntlRelativeTimeFormatUnitEnum)
registerEnumeration(ObjectGroup.jsIntlSupportedValuesEnum)
registerEnumeration(OptionsBag.jsTemporalUnitEnum)
registerEnumeration(OptionsBag.jsTemporalRoundingModeEnum)
registerEnumeration(OptionsBag.jsTemporalShowCalendarEnum)
registerEnumeration(OptionsBag.jsTemporalShowOffsetEnum)
registerEnumeration(OptionsBag.jsTemporalShowTimeZoneEnum)
registerEnumeration(OptionsBag.jsTemporalOverflowEnum)
registerEnumeration(OptionsBag.jsTemporalDisambiguationEnum)
registerEnumeration(OptionsBag.jsTemporalOffsetEnum)
registerEnumeration(OptionsBag.jsIntlLocaleMatcherEnum)
registerEnumeration(OptionsBag.jsIntlNumberingSystemEnum)
registerEnumeration(OptionsBag.jsIntlHourCycleEnum)
registerEnumeration(OptionsBag.jsIntlLongShortNarrowEnum)
registerEnumeration(OptionsBag.jsIntlLongShortEnum)
registerEnumeration(OptionsBag.jsIntlAutoAlwaysEnum)
registerEnumeration(OptionsBag.jsIntlNumeric2DigitEnum)
registerEnumeration(OptionsBag.jsIntlMonthEnum)
registerEnumeration(OptionsBag.jsIntlTimeZoneNameEnum)
registerEnumeration(OptionsBag.jsIntlFormatMatcherEnum)
registerEnumeration(OptionsBag.jsIntlFullLongMediumShort)
registerEnumeration(OptionsBag.jsIntlCollatorUsageEnum)
registerEnumeration(OptionsBag.jsIntlCollationEnum)
registerEnumeration(OptionsBag.jsIntlCollationTypeEnum)
registerEnumeration(OptionsBag.jsIntlCaseFirstEnum)
registerEnumeration(OptionsBag.jsIntlCollatorSensitivityEnum)
registerEnumeration(OptionsBag.jsIntlDisplayNamesTypeEnum)
registerEnumeration(OptionsBag.jsIntlDisplayNamesFallbackEnum)
registerEnumeration(OptionsBag.jsIntlDisplayNamesLanguageDisplayEnum)
registerEnumeration(OptionsBag.jsIntlDurationFormatStyleEnum)
registerEnumeration(OptionsBag.jsIntlListFormatTypeEnum)
registerEnumeration(OptionsBag.jsIntlNumberFormatStyleEnum)
registerEnumeration(OptionsBag.jsIntlCurrencySystemEnum)
registerEnumeration(OptionsBag.jsIntlCurrencyDisplayEnum)
registerEnumeration(OptionsBag.jsIntlCurrencySignEnum)
registerEnumeration(OptionsBag.jsIntlRoundingPriorityEnum)
registerEnumeration(OptionsBag.jsIntlRoundingModeEnum)
registerEnumeration(OptionsBag.jsIntlTrailingZeroDisplayEnum)
registerEnumeration(OptionsBag.jsIntlNumberFormatNotationEnum)
registerEnumeration(OptionsBag.jsIntlNumberFormatGroupingEnum)
registerEnumeration(OptionsBag.jsIntlSignDisplayEnum)
registerEnumeration(OptionsBag.jsIntlPluralRulesTypeEnum)
registerEnumeration(OptionsBag.jsIntlSegmenterGranularityEnum)
registerEnumeration(OptionsBag.base64Alphabet)
registerEnumeration(OptionsBag.base64LastChunkHandling)
for enumeration in additionalEnumerations {
assert(enumeration.isEnumeration)
registerEnumeration(enumeration)
}
registerOptionsBag(.jsTemporalDifferenceSettingOrRoundTo)
registerOptionsBag(.jsTemporalToStringSettings)
registerOptionsBag(.jsTemporalOverflowSettings)
registerOptionsBag(.jsTemporalZonedInterpretationSettings)
registerOptionsBag(.jsTemporalDurationRoundToSettings)
registerOptionsBag(.jsTemporalDurationTotalOfSettings)
registerOptionsBag(.toBase64Settings)
registerOptionsBag(.fromBase64Settings)
registerOptionsBag(.jsTemporalPlainDateToZDTSettings)
registerOptionsBag(.jsIntlDateTimeFormatSettings)
registerOptionsBag(.jsIntlCollatorSettings)
registerOptionsBag(.jsIntlDisplayNamesSettings)
registerOptionsBag(.jsIntlDurationFormatSettings)
registerOptionsBag(.jsIntlListFormatSettings)
registerOptionsBag(.jsIntlLocaleSettings)
registerOptionsBag(.jsIntlNumberFormatSettings)
registerOptionsBag(.jsIntlPluralRulesSettings)
registerOptionsBag(.jsIntlRelativeTimeFormatSettings)
registerOptionsBag(.jsIntlSegmenterSettings)
registerOptionsBag(.jsIntlLocaleMatcherSettings)
registerTemporalFieldsObject(.jsTemporalPlainTimeLikeObject, forWith: false, dateFields: false, timeFields: true, zonedFields: false)
registerTemporalFieldsObject(.jsTemporalPlainDateLikeObject, forWith: false, dateFields: true, timeFields: false, zonedFields: false)
registerTemporalFieldsObject(.jsTemporalPlainDateLikeObjectForWith, forWith: true, dateFields: true, timeFields: false, zonedFields: false)
registerTemporalFieldsObject(.jsTemporalPlainDateTimeLikeObject, forWith: false, dateFields: true, timeFields: true, zonedFields: false)
registerTemporalFieldsObject(.jsTemporalPlainDateTimeLikeObjectForWith, forWith: true, dateFields: true, timeFields: true, zonedFields: false)
registerTemporalFieldsObject(.jsTemporalZonedDateTimeLikeObject, forWith: false, dateFields: true, timeFields: true, zonedFields: true)
registerTemporalFieldsObject(.jsTemporalZonedDateTimeLikeObjectForWith, forWith: true, dateFields: true, timeFields: true, zonedFields: true)
// This isn't a normal "temporal fields object" but is similar, and needs a similar producing generator
registerObjectGroup(.jsTemporalDurationLikeObject)
addProducingGenerator(forType: ObjectGroup.jsTemporalDurationLikeObject.instanceType, with: { b in b.createTemporalDurationFieldsObject() })
addNamedStringGenerator(forType: ObjectGroup.jsTemporalTimeZoneLike,
with: {
if Bool.random() {
return ProgramBuilder.randomTimeZoneString()
} else {
return ProgramBuilder.randomUTCOffsetString(mayHaveSeconds: true)
}
})
addNamedStringGenerator(forType: .jsIntlLocaleString, with: { ProgramBuilder.constructIntlLocaleString() })
addNamedStringGenerator(forType: .jsIntlLanguageString, with: { ProgramBuilder.constructIntlLanguageString() })
addNamedStringGenerator(forType: .jsIntlScriptString, with: { ProgramBuilder.constructIntlScriptString() })
addNamedStringGenerator(forType: .jsIntlRegionString, with: { ProgramBuilder.constructIntlRegionString() })
addNamedStringGenerator(forType: .jsIntlVariantString, with: { ProgramBuilder.constructIntlVariantString() })
addNamedStringGenerator(forType: .jsIntlUnitString, with: { ProgramBuilder.constructIntlUnit() })
// Temporal types are produced by a large number of methods; which means findOrGenerateType(), when asked to produce
// a Temporal type, will tend towards trying to call a method on another Temporal type, which needs more Temporal types,
// leading to a large amount of code generated. We do wish to test these codepaths as well, but by and large we
// just want a freshly generated type.
addProducingGenerator(forType: .jsTemporalInstant, with: { $0.constructTemporalInstant() }, probability: 0.9)
addProducingGenerator(forType: .jsTemporalDuration, with: { $0.constructTemporalDuration() }, probability: 0.9)
addProducingGenerator(forType: .jsTemporalPlainTime, with: { $0.constructTemporalTime() }, probability: 0.9)
addProducingGenerator(forType: .jsTemporalPlainYearMonth, with: { $0.constructTemporalYearMonth() }, probability: 0.9)
addProducingGenerator(forType: .jsTemporalPlainMonthDay, with: { $0.constructTemporalMonthDay() }, probability: 0.9)
addProducingGenerator(forType: .jsTemporalPlainDate, with: { $0.constructTemporalDate() }, probability: 0.9)
addProducingGenerator(forType: .jsTemporalPlainDateTime, with: { $0.constructTemporalDateTime() }, probability: 0.9)
addProducingGenerator(forType: .jsTemporalZonedDateTime, with: { $0.constructTemporalZonedDateTime() }, probability: 0.9)
// Register builtins that should be available for fuzzing.
// Here it is easy to selectively disable/enable some APIs for fuzzing by
// just commenting out the corresponding lines.
registerBuiltin("Object", ofType: .jsObjectConstructor)
registerBuiltin("Array", ofType: .jsArrayConstructor)
registerBuiltin("Function", ofType: .jsFunctionConstructor)
registerBuiltin("String", ofType: .jsStringConstructor)
registerBuiltin("Boolean", ofType: .jsBooleanConstructor)
registerBuiltin("Number", ofType: .jsNumberConstructor)
registerBuiltin("Symbol", ofType: .jsSymbolConstructor)
registerBuiltin("Iterator", ofType: .jsIteratorConstructor)
registerBuiltin("BigInt", ofType: .jsBigIntConstructor)
registerBuiltin("RegExp", ofType: .jsRegExpConstructor)
for variant in ["Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "SuppressedError", "AggregateError"] {
registerBuiltin(variant, ofType: .jsErrorConstructor(variant))
}
registerBuiltin("ArrayBuffer", ofType: .jsArrayBufferConstructor)
registerBuiltin("SharedArrayBuffer", ofType: .jsSharedArrayBufferConstructor)
for variant in ["Uint8Array", "Int8Array", "Uint16Array", "Int16Array", "Uint32Array", "Int32Array", "Float16Array", "Float32Array", "Float64Array", "Uint8ClampedArray", "BigInt64Array", "BigUint64Array"] {
registerBuiltin(variant, ofType: .jsTypedArrayConstructor(variant))
}
registerBuiltin("DataView", ofType: .jsDataViewConstructor)
registerBuiltin("Date", ofType: .jsDateConstructor)
registerBuiltin("Promise", ofType: .jsPromiseConstructor)
registerBuiltin("Proxy", ofType: .jsProxyConstructor)
registerBuiltin("Map", ofType: .jsMapConstructor)
registerBuiltin("WeakMap", ofType: .jsWeakMapConstructor)
registerBuiltin("Set", ofType: .jsSetConstructor)
registerBuiltin("WeakSet", ofType: .jsWeakSetConstructor)
registerBuiltin("WeakRef", ofType: .jsWeakRefConstructor)
registerBuiltin("FinalizationRegistry", ofType: .jsFinalizationRegistryConstructor)
registerBuiltin("DisposableStack", ofType: .jsDisposableStackConstructor)
registerBuiltin("AsyncDisposableStack", ofType: .jsAsyncDisposableStackConstructor)
registerBuiltin("Math", ofType: .jsMathObject)
registerBuiltin("Atomics", ofType: .jsAtomicsObject)
registerBuiltin("JSON", ofType: .jsJSONObject)
registerBuiltin("Reflect", ofType: .jsReflectObject)
registerBuiltin("isNaN", ofType: .jsIsNaNFunction)
registerBuiltin("isFinite", ofType: .jsIsFiniteFunction)
//registerBuiltin("escape:", ofType: .jsEscapeFunction)
//registerBuiltin("unescape:", ofType: .jsUnescapeFunction)
//registerBuiltin("decodeURI:", ofType: .jsDecodeURIFunction)
//registerBuiltin("decodeURIComponent:", ofType: .jsDecodeURIComponentFunction)
//registerBuiltin("encodeURI:", ofType: .jsEncodeURIFunction)
//registerBuiltin("encodeURIComponent:", ofType: .jsEncodeURIComponentFunction)
registerBuiltin("eval", ofType: .jsEvalFunction)
registerBuiltin("parseInt", ofType: .jsParseIntFunction)
registerBuiltin("parseFloat", ofType: .jsParseFloatFunction)
registerBuiltin("undefined", ofType: .jsUndefined)
registerBuiltin("NaN", ofType: .jsNaN)
registerBuiltin("Infinity", ofType: .jsInfinity)
registerBuiltin("Temporal", ofType: .jsTemporalObject)
registerBuiltin("Intl", ofType: .jsIntlObject)
registerBuiltin("WebAssembly", ofType: ObjectGroup.jsWebAssembly.instanceType)
for (builtin, type) in additionalBuiltins {
registerBuiltin(builtin, ofType: type)
}
// Add some well-known builtin properties and methods.
builtinProperties.insert("__proto__")
builtinProperties.insert("constructor")
builtinMethods.insert("valueOf")
builtinMethods.insert("toString")
}
override func initialize() {
// Ensure that some of the common property/method names exist.
assert(builtinProperties.contains("__proto__"))
assert(builtinProperties.contains("constructor"))
assert(builtinMethods.contains("valueOf"))
assert(builtinMethods.contains("toString"))
checkConstructorAvailability()
// Log detailed information about the environment here so users are aware of it and can modify things if they like.
logger.info("Initialized static JS environment model")
logger.info("Have \(builtins.count) available builtins: \(builtins.sorted())")
logger.info("Have \(groups.count) different object groups: \(groups.keys.sorted())")
logger.info("Have \(builtinProperties.count) builtin property names: \(builtinProperties.sorted())")
logger.info("Have \(builtinMethods.count) builtin method names: \(builtinMethods.sorted())")
logger.info("Have \(customProperties.count) custom property names: \(customProperties.sorted())")
logger.info("Have \(customMethods.count) custom method names: \(customMethods.sorted())")
logger.info("Have \(customPrivateMethods.count) custom private method names: \(customPrivateMethods.sorted())")
}
func checkConstructorAvailability() {
logger.info("Checking constructor availability...")
// These constructors return types that are well-known instead of .object types.
let knownExceptions = [
"Boolean", // returns .boolean
"Number", // returns .number
"Object", // returns plain .object
"Proxy", // returns .jsAnything
]
for builtin in builtins where type(ofBuiltin: builtin).Is(.constructor()) {
if knownExceptions.contains(builtin) { continue }
if !hasGroup(builtin) { logger.warning("Missing group info for constructable \(builtin)")}
if type(ofBuiltin: builtin).signature == nil {
logger.warning("Missing signature for builtin \(builtin)")
} else {
if !type(ofBuiltin: builtin).signature!.outputType.Is(.object(ofGroup: builtin)) {
logger.warning("Signature for builtin \(builtin) is mismatching")
}
}
}
logger.info("Done checking constructor availability...")
}
public func hasBuiltin(_ name: String) -> Bool {
return self.builtinTypes.keys.contains(name)
}
public func hasGroup(_ name: String) -> Bool {
return self.groups.keys.contains(name)
}
// Add a generator that produces an object of the provided `type`.
//
// The probability is how often this generator should be called when this type is required.
//
// The default probability (1) is for groups that are never generated as return types of other objects.
// Use a lower probability if there are other ways to generate the object.
//
// Note that Fuzzilli is able to discover ways to construct types on its own. There are two use cases for this:
// - "Options bag" type objects where no JS API produces them, so we *must* run a producing generator
// - Temporal objects: These can be obtained from the result of other API calls, however a
// a lot of these API calls need more Temporal objects, leading to runaway recursion attempting
// to generate a large number of Temporal objects. Instead, we bias heavily towards the producing generator.
public func addProducingGenerator(forType type: ILType, with generator: @escaping EnvironmentValueGenerator, probability: Double = 1.0) {
assert(type.Is(.object()), "Producing generators can only be registered for objects, found \(type)")
producingGenerators[type.group!] = (generator, probability)
}
// Register a generator for a custom named string.
public func addNamedStringGenerator(forType type: ILType, with generator: @escaping () -> String) {
assert(type.Is(.string), "Named string generators can only be registered for strings, found \(type)")
namedStringGenerators[type.group!] = generator
}
private func addProducingMethod(forType type: ILType, by method: String, on group: String) {
if producingMethods[type] == nil {
producingMethods[type] = []
}
producingMethods[type]! += [(group: group, method: method)]
}
@discardableResult private func addProducingProperty(forType type: ILType, by property: String, on group: String) -> ILType {
let actualType: ILType
if type.Is(.constructor()) {
actualType = type.signature!.outputType
} else {
actualType = type
}
if producingProperties[actualType] == nil {
producingProperties[actualType] = []
}
producingProperties[actualType]! += [(group: group, property: property)]
return actualType
}
public func registerEnumeration(_ type: ILType) {
assert(type.isEnumeration)
let group = type.group!
assert(enums[group] == nil, "Registered duplicate enum \(group)")
enums[group] = type
}
public func registerObjectGroup(_ group: ObjectGroup) {
assert(groups[group.name] == nil, "Registered duplicate enum \(group.name)")
groups[group.name] = group
builtinProperties.formUnion(group.properties.keys)
builtinMethods.formUnion(group.methods.keys)
//func register
// Step 1: Initialize `subtypes`
//
subtypes[group.instanceType] = [group.instanceType]
var current = group
while let parent = current.parent {
// Parent groups are supposed to be defined before child groups
current = groups[parent]!
subtypes[current.instanceType]! += [group.instanceType]
}
//
// Step 2: Initialize `producingMethods`
//
for overloads in group.methods {
for method in overloads.value {
assert(method.outputType != .nothing,
"Method \(overloads.key) in group \(group.name) has .nothing as outputType")
if method.outputType == .undefined {
continue
}
let type = method.outputType
addProducingMethod(forType: type, by: overloads.key, on: group.name)
if let groupName = type.group {
if var current = groups[groupName] {
while let parent = current.parent {
current = groups[parent]!
addProducingMethod(forType: current.instanceType, by: overloads.key, on: group.name)
}
}
}
}
}
//
// Step 3: Initialize `producingProperties`
//
for property in group.properties {
let producedType = addProducingProperty(forType: property.value, by: property.key, on: group.name)
if let groupName = producedType.group {
if var current = groups[groupName] {
while let parent = current.parent {
current = groups[parent]!
addProducingProperty(forType: current.instanceType, by: property.key, on: group.name)
}
}
}
}
}
// Temporal has a large number of "fields" object (aka "partial temporal objects" or "temporal-like objects")
// which have a number of datetime-like fields. These are never produced as a result from any JS APIs, so we cannot
// expect instances of them to already exist in scope. Instead, we generate them ourselves when requested.
public func registerTemporalFieldsObject(_ group: ObjectGroup, forWith: Bool, dateFields: Bool, timeFields: Bool, zonedFields: Bool) {
registerObjectGroup(group)
addProducingGenerator(forType: group.instanceType, with: { b in
b.createTemporalFieldsObject(forWith: forWith, dateFields: dateFields, timeFields: timeFields, zonedFields: zonedFields)
})
}
public func registerBuiltin(_ name: String, ofType type: ILType) {
assert(builtinTypes[name] == nil)
builtinTypes[name] = type
builtins.insert(name)
let producedType = addProducingProperty(forType: type, by: name, on: "")
if let groupName = producedType.group {
if var current = groups[groupName] {
while let parent = current.parent {
current = groups[parent]!
addProducingProperty(forType: current.instanceType, by: name, on: "")
}
}
}
}
public func registerOptionsBag(_ bag: OptionsBag) {
registerObjectGroup(bag.group)
for property in bag.properties.values {
if property.isEnumeration {
assert(enums[property.group!] != nil, "Enum \(property.group!) used in options bag but not registered on the JavaScriptEnvironment")
}
}
addProducingGenerator(forType: bag.group.instanceType, with: { b in b.createOptionsBag(bag) })
}
public func type(ofBuiltin builtinName: String) -> ILType {
if let type = builtinTypes[builtinName] {
return type
} else {
logger.warning("Missing type for builtin \(builtinName)")
return .jsAnything
}
}
public func type (ofGroup groupName: String) -> ILType {
if let type = groups[groupName]?.instanceType {
return type
} else {
logger.warning("Missing type for group \(groupName)")
return .jsAnything
}
}
public func type(ofProperty propertyName: String, on baseType: ILType) -> ILType {
if let groupName = baseType.group {
if let group = groups[groupName] {
if let type = group.properties[propertyName] {
return type
}
if let signatures = group.methods[propertyName] {
return .unboundFunction(signatures.first, receiver: baseType)
}
} else if !baseType.isEnumerationOrNamedString {
// This shouldn't happen, probably forgot to register the object group.
logger.warning("No type information for object group \(groupName) available")
}
}
return .jsAnything
}
public func signatures(ofMethod methodName: String, on baseType: ILType) -> [Signature] {
if let groupName = baseType.group {
if let group = groups[groupName] {
if let signatures = group.methods[methodName] {
return signatures
}
} else if !baseType.isEnumerationOrNamedString {
// This shouldn't happen, probably forgot to register the object group
logger.warning("No type information for object group \(groupName) available")
}
}
return [.forUnknownFunction]
}
public func getEnum(ofName name: String) -> ILType? {
return enums[name]
}
public func getProducingMethods(ofType type: ILType) -> [(group: String, method: String)] {
guard let array = producingMethods[type] else {
return []
}
return array
}
// For ObjectGroups, get a generator that is registered as being able to produce this
// ObjectGroup.
public func getProducingGenerator(ofType type: ILType) -> (generator: EnvironmentValueGenerator, probability: Double)? {
type.group.flatMap {producingGenerators[$0]}
}
// For named strings, get a generator that is registered as being able to produce this
// named string.
public func getNamedStringGenerator(ofName name: String) -> (() -> String)? {
namedStringGenerators[name]
}
// If the object group refers to a constructor, get its path.
public func getPathIfConstructor(ofGroup groupName: String) -> [String]? {
guard let group = groups[groupName] else {
return nil
}
return group.constructorPath
}
public func getProducingProperties(ofType type: ILType) -> [(group: String, property: String)] {
guard let array = producingProperties[type] else {
return []
}
return array
}
public func getSubtypes(ofType type: ILType) -> [ILType] {
guard let array = subtypes[type] else {
return [type]
}
return array
}
public func isSubtype(_ type: ILType, of parent: ILType) -> Bool {
return getSubtypes(ofType: parent).reduce(false) {
$0 || type.Is($1)
}
}
func isValidNameForMethodDefinition(_ name: String) -> Bool {