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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "ctypes/CTypes.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/SizePrintfMacros.h"
#include "mozilla/Sprintf.h"
#include "mozilla/Vector.h"
#include <limits>
#include <math.h>
#include <stdint.h>
#if defined(XP_WIN)
#include <float.h>
#endif
#if defined(SOLARIS)
#include <ieeefp.h>
#endif
#ifdef HAVE_SSIZE_T
#include <sys/types.h>
#endif
#if defined(XP_UNIX)
#include <errno.h>
#elif defined(XP_WIN)
#include <windows.h>
#endif
#include "jscntxt.h"
#include "jsexn.h"
#include "jsfun.h"
#include "jsnum.h"
#include "jsprf.h"
#include "builtin/TypedObject.h"
#include "ctypes/Library.h"
#include "gc/Policy.h"
#include "gc/Zone.h"
#include "js/Vector.h"
#include "jsatominlines.h"
#include "jsobjinlines.h"
using namespace std;
using JS::AutoCheckCannotGC;
namespace js {
namespace ctypes {
template <typename CharT>
size_t
GetDeflatedUTF8StringLength(JSContext* maybecx, const CharT* chars,
size_t nchars)
{
size_t nbytes;
const CharT* end;
unsigned c, c2;
nbytes = nchars;
for (end = chars + nchars; chars != end; chars++) {
c = *chars;
if (c < 0x80)
continue;
if (0xD800 <= c && c <= 0xDFFF) {
/* Surrogate pair. */
chars++;
/* nbytes sets 1 length since this is surrogate pair. */
nbytes--;
if (c >= 0xDC00 || chars == end)
goto bad_surrogate;
c2 = *chars;
if (c2 < 0xDC00 || c2 > 0xDFFF)
goto bad_surrogate;
c = ((c - 0xD800) << 10) + (c2 - 0xDC00) + 0x10000;
}
c >>= 11;
nbytes++;
while (c) {
c >>= 5;
nbytes++;
}
}
return nbytes;
bad_surrogate:
if (maybecx) {
js::gc::AutoSuppressGC suppress(maybecx);
char buffer[10];
SprintfLiteral(buffer, "0x%x", c);
JS_ReportErrorFlagsAndNumberASCII(maybecx, JSREPORT_ERROR,
GetErrorMessage,
nullptr, JSMSG_BAD_SURROGATE_CHAR,
buffer);
}
return (size_t) -1;
}
template size_t
GetDeflatedUTF8StringLength(JSContext* maybecx, const Latin1Char* chars,
size_t nchars);
template size_t
GetDeflatedUTF8StringLength(JSContext* maybecx, const char16_t* chars,
size_t nchars);
static size_t
GetDeflatedUTF8StringLength(JSContext* maybecx, JSLinearString* str)
{
size_t length = str->length();
JS::AutoCheckCannotGC nogc;
return str->hasLatin1Chars()
? GetDeflatedUTF8StringLength(maybecx, str->latin1Chars(nogc), length)
: GetDeflatedUTF8StringLength(maybecx, str->twoByteChars(nogc), length);
}
template <typename CharT>
bool
DeflateStringToUTF8Buffer(JSContext* maybecx, const CharT* src, size_t srclen,
char* dst, size_t* dstlenp)
{
size_t i, utf8Len;
char16_t c, c2;
uint32_t v;
uint8_t utf8buf[6];
size_t dstlen = *dstlenp;
size_t origDstlen = dstlen;
while (srclen) {
c = *src++;
srclen--;
if (c >= 0xDC00 && c <= 0xDFFF)
goto badSurrogate;
if (c < 0xD800 || c > 0xDBFF) {
v = c;
} else {
if (srclen < 1)
goto badSurrogate;
c2 = *src;
if ((c2 < 0xDC00) || (c2 > 0xDFFF))
goto badSurrogate;
src++;
srclen--;
v = ((c - 0xD800) << 10) + (c2 - 0xDC00) + 0x10000;
}
if (v < 0x0080) {
/* no encoding necessary - performance hack */
if (dstlen == 0)
goto bufferTooSmall;
*dst++ = (char) v;
utf8Len = 1;
} else {
utf8Len = js::OneUcs4ToUtf8Char(utf8buf, v);
if (utf8Len > dstlen)
goto bufferTooSmall;
for (i = 0; i < utf8Len; i++)
*dst++ = (char) utf8buf[i];
}
dstlen -= utf8Len;
}
*dstlenp = (origDstlen - dstlen);
return true;
badSurrogate:
*dstlenp = (origDstlen - dstlen);
/* Delegate error reporting to the measurement function. */
if (maybecx)
GetDeflatedUTF8StringLength(maybecx, src - 1, srclen + 1);
return false;
bufferTooSmall:
*dstlenp = (origDstlen - dstlen);
if (maybecx) {
js::gc::AutoSuppressGC suppress(maybecx);
JS_ReportErrorNumberASCII(maybecx, GetErrorMessage, nullptr,
JSMSG_BUFFER_TOO_SMALL);
}
return false;
}
template bool
DeflateStringToUTF8Buffer(JSContext* maybecx, const Latin1Char* src, size_t srclen,
char* dst, size_t* dstlenp);
template bool
DeflateStringToUTF8Buffer(JSContext* maybecx, const char16_t* src, size_t srclen,
char* dst, size_t* dstlenp);
static bool
DeflateStringToUTF8Buffer(JSContext* maybecx, JSLinearString* str, char* dst,
size_t* dstlenp)
{
size_t length = str->length();
JS::AutoCheckCannotGC nogc;
return str->hasLatin1Chars()
? DeflateStringToUTF8Buffer(maybecx, str->latin1Chars(nogc), length, dst, dstlenp)
: DeflateStringToUTF8Buffer(maybecx, str->twoByteChars(nogc), length, dst, dstlenp);
}
/*******************************************************************************
** JSAPI function prototypes
*******************************************************************************/
// We use an enclosing struct here out of paranoia about the ability of gcc 4.4
// (and maybe 4.5) to correctly compile this if it were a template function.
// See also the comments in dom/workers/Events.cpp (and other adjacent files) by
// the |struct Property| there.
template<JS::IsAcceptableThis Test, JS::NativeImpl Impl>
struct Property
{
static bool
Fun(JSContext* cx, unsigned argc, JS::Value* vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
return JS::CallNonGenericMethod<Test, Impl>(cx, args);
}
};
static bool ConstructAbstract(JSContext* cx, unsigned argc, Value* vp);
namespace CType {
static bool ConstructData(JSContext* cx, unsigned argc, Value* vp);
static bool ConstructBasic(JSContext* cx, HandleObject obj, const CallArgs& args);
static void Trace(JSTracer* trc, JSObject* obj);
static void Finalize(JSFreeOp* fop, JSObject* obj);
bool IsCType(HandleValue v);
bool IsCTypeOrProto(HandleValue v);
bool PrototypeGetter(JSContext* cx, const JS::CallArgs& args);
bool NameGetter(JSContext* cx, const JS::CallArgs& args);
bool SizeGetter(JSContext* cx, const JS::CallArgs& args);
bool PtrGetter(JSContext* cx, const JS::CallArgs& args);
static bool CreateArray(JSContext* cx, unsigned argc, Value* vp);
static bool ToString(JSContext* cx, unsigned argc, Value* vp);
static bool ToSource(JSContext* cx, unsigned argc, Value* vp);
static bool HasInstance(JSContext* cx, HandleObject obj, MutableHandleValue v, bool* bp);
/*
* Get the global "ctypes" object.
*
* |obj| must be a CType object.
*
* This function never returns nullptr.
*/
static JSObject* GetGlobalCTypes(JSContext* cx, JSObject* obj);
} // namespace CType
namespace ABI {
bool IsABI(JSObject* obj);
static bool ToSource(JSContext* cx, unsigned argc, Value* vp);
} // namespace ABI
namespace PointerType {
static bool Create(JSContext* cx, unsigned argc, Value* vp);
static bool ConstructData(JSContext* cx, HandleObject obj, const CallArgs& args);
bool IsPointerType(HandleValue v);
bool IsPointer(HandleValue v);
bool TargetTypeGetter(JSContext* cx, const JS::CallArgs& args);
bool ContentsGetter(JSContext* cx, const JS::CallArgs& args);
bool ContentsSetter(JSContext* cx, const JS::CallArgs& args);
static bool IsNull(JSContext* cx, unsigned argc, Value* vp);
static bool Increment(JSContext* cx, unsigned argc, Value* vp);
static bool Decrement(JSContext* cx, unsigned argc, Value* vp);
// The following is not an instance function, since we don't want to expose arbitrary
// pointer arithmetic at this moment.
static bool OffsetBy(JSContext* cx, const CallArgs& args, int offset);
} // namespace PointerType
namespace ArrayType {
bool IsArrayType(HandleValue v);
bool IsArrayOrArrayType(HandleValue v);
static bool Create(JSContext* cx, unsigned argc, Value* vp);
static bool ConstructData(JSContext* cx, HandleObject obj, const CallArgs& args);
bool ElementTypeGetter(JSContext* cx, const JS::CallArgs& args);
bool LengthGetter(JSContext* cx, const JS::CallArgs& args);
static bool Getter(JSContext* cx, HandleObject obj, HandleId idval, MutableHandleValue vp);
static bool Setter(JSContext* cx, HandleObject obj, HandleId idval, MutableHandleValue vp,
ObjectOpResult& result);
static bool AddressOfElement(JSContext* cx, unsigned argc, Value* vp);
} // namespace ArrayType
namespace StructType {
bool IsStruct(HandleValue v);
static bool Create(JSContext* cx, unsigned argc, Value* vp);
static bool ConstructData(JSContext* cx, HandleObject obj, const CallArgs& args);
bool FieldsArrayGetter(JSContext* cx, const JS::CallArgs& args);
enum {
SLOT_FIELDNAME
};
static bool FieldGetter(JSContext* cx, unsigned argc, Value* vp);
static bool FieldSetter(JSContext* cx, unsigned argc, Value* vp);
static bool AddressOfField(JSContext* cx, unsigned argc, Value* vp);
static bool Define(JSContext* cx, unsigned argc, Value* vp);
} // namespace StructType
namespace FunctionType {
static bool Create(JSContext* cx, unsigned argc, Value* vp);
static bool ConstructData(JSContext* cx, HandleObject typeObj,
HandleObject dataObj, HandleObject fnObj, HandleObject thisObj, HandleValue errVal);
static bool Call(JSContext* cx, unsigned argc, Value* vp);
bool IsFunctionType(HandleValue v);
bool ArgTypesGetter(JSContext* cx, const JS::CallArgs& args);
bool ReturnTypeGetter(JSContext* cx, const JS::CallArgs& args);
bool ABIGetter(JSContext* cx, const JS::CallArgs& args);
bool IsVariadicGetter(JSContext* cx, const JS::CallArgs& args);
} // namespace FunctionType
namespace CClosure {
static void Trace(JSTracer* trc, JSObject* obj);
static void Finalize(JSFreeOp* fop, JSObject* obj);
// libffi callback
static void ClosureStub(ffi_cif* cif, void* result, void** args,
void* userData);
struct ArgClosure : public ScriptEnvironmentPreparer::Closure {
ArgClosure(ffi_cif* cifArg, void* resultArg, void** argsArg, ClosureInfo* cinfoArg)
: cif(cifArg), result(resultArg), args(argsArg), cinfo(cinfoArg) {}
bool operator()(JSContext *cx) override;
ffi_cif* cif;
void* result;
void** args;
ClosureInfo* cinfo;
};
} // namespace CClosure
namespace CData {
static void Finalize(JSFreeOp* fop, JSObject* obj);
bool ValueGetter(JSContext* cx, const JS::CallArgs& args);
bool ValueSetter(JSContext* cx, const JS::CallArgs& args);
static bool Address(JSContext* cx, unsigned argc, Value* vp);
static bool ReadString(JSContext* cx, unsigned argc, Value* vp);
static bool ReadStringReplaceMalformed(JSContext* cx, unsigned argc, Value* vp);
static bool ToSource(JSContext* cx, unsigned argc, Value* vp);
static JSString* GetSourceString(JSContext* cx, HandleObject typeObj,
void* data);
bool ErrnoGetter(JSContext* cx, const JS::CallArgs& args);
#if defined(XP_WIN)
bool LastErrorGetter(JSContext* cx, const JS::CallArgs& args);
#endif // defined(XP_WIN)
} // namespace CData
namespace CDataFinalizer {
/*
* Attach a C function as a finalizer to a JS object.
*
* This function is available from JS as |ctypes.withFinalizer|.
*
* JavaScript signature:
* function(CData, CData): CDataFinalizer
* value finalizer finalizable
*
* Where |finalizer| is a one-argument function taking a value
* with the same type as |value|.
*/
static bool Construct(JSContext* cx, unsigned argc, Value* vp);
/*
* Private data held by |CDataFinalizer|.
*
* See also |enum CDataFinalizerSlot| for the slots of
* |CDataFinalizer|.
*
* Note: the private data may be nullptr, if |dispose|, |forget| or the
* finalizer has already been called.
*/
struct Private {
/*
* The C data to pass to the code.
* Finalization/|dispose|/|forget| release this memory.
*/
void* cargs;
/*
* The total size of the buffer pointed by |cargs|
*/
size_t cargs_size;
/*
* Low-level signature information.
* Finalization/|dispose|/|forget| release this memory.
*/
ffi_cif CIF;
/*
* The C function to invoke during finalization.
* Do not deallocate this.
*/
uintptr_t code;
/*
* A buffer for holding the return value.
* Finalization/|dispose|/|forget| release this memory.
*/
void* rvalue;
};
/*
* Methods of instances of |CDataFinalizer|
*/
namespace Methods {
static bool Dispose(JSContext* cx, unsigned argc, Value* vp);
static bool Forget(JSContext* cx, unsigned argc, Value* vp);
static bool ReadString(JSContext* cx, unsigned argc, Value* vp);
static bool ToSource(JSContext* cx, unsigned argc, Value* vp);
static bool ToString(JSContext* cx, unsigned argc, Value* vp);
} // namespace Methods
/*
* Utility functions
*
* @return true if |obj| is a CDataFinalizer, false otherwise.
*/
static bool IsCDataFinalizer(JSObject* obj);
/*
* Clean up the finalization information of a CDataFinalizer.
*
* Used by |Finalize|, |Dispose| and |Forget|.
*
* @param p The private information of the CDataFinalizer. If nullptr,
* this function does nothing.
* @param obj Either nullptr, if the object should not be cleaned up (i.e.
* during finalization) or a CDataFinalizer JSObject. Always use nullptr
* if you are calling from a finalizer.
*/
static void Cleanup(Private* p, JSObject* obj);
/*
* Perform the actual call to the finalizer code.
*/
static void CallFinalizer(CDataFinalizer::Private* p,
int* errnoStatus,
int32_t* lastErrorStatus);
/*
* Return the CType of a CDataFinalizer object, or nullptr if the object
* has been cleaned-up already.
*/
static JSObject* GetCType(JSContext* cx, JSObject* obj);
/*
* Perform finalization of a |CDataFinalizer|
*/
static void Finalize(JSFreeOp* fop, JSObject* obj);
/*
* Return the Value contained by this finalizer.
*
* Note that the Value is actually not recorded, but converted back from C.
*/
static bool GetValue(JSContext* cx, JSObject* obj, MutableHandleValue result);
} // namespace CDataFinalizer
// Int64Base provides functions common to Int64 and UInt64.
namespace Int64Base {
JSObject* Construct(JSContext* cx, HandleObject proto, uint64_t data,
bool isUnsigned);
uint64_t GetInt(JSObject* obj);
bool ToString(JSContext* cx, JSObject* obj, const CallArgs& args,
bool isUnsigned);
bool ToSource(JSContext* cx, JSObject* obj, const CallArgs& args,
bool isUnsigned);
static void Finalize(JSFreeOp* fop, JSObject* obj);
} // namespace Int64Base
namespace Int64 {
static bool Construct(JSContext* cx, unsigned argc, Value* vp);
static bool ToString(JSContext* cx, unsigned argc, Value* vp);
static bool ToSource(JSContext* cx, unsigned argc, Value* vp);
static bool Compare(JSContext* cx, unsigned argc, Value* vp);
static bool Lo(JSContext* cx, unsigned argc, Value* vp);
static bool Hi(JSContext* cx, unsigned argc, Value* vp);
static bool Join(JSContext* cx, unsigned argc, Value* vp);
} // namespace Int64
namespace UInt64 {
static bool Construct(JSContext* cx, unsigned argc, Value* vp);
static bool ToString(JSContext* cx, unsigned argc, Value* vp);
static bool ToSource(JSContext* cx, unsigned argc, Value* vp);
static bool Compare(JSContext* cx, unsigned argc, Value* vp);
static bool Lo(JSContext* cx, unsigned argc, Value* vp);
static bool Hi(JSContext* cx, unsigned argc, Value* vp);
static bool Join(JSContext* cx, unsigned argc, Value* vp);
} // namespace UInt64
/*******************************************************************************
** JSClass definitions and initialization functions
*******************************************************************************/
// Class representing the 'ctypes' object itself. This exists to contain the
// JSCTypesCallbacks set of function pointers.
static const JSClass sCTypesGlobalClass = {
"ctypes",
JSCLASS_HAS_RESERVED_SLOTS(CTYPESGLOBAL_SLOTS)
};
static const JSClass sCABIClass = {
"CABI",
JSCLASS_HAS_RESERVED_SLOTS(CABI_SLOTS)
};
// Class representing ctypes.{C,Pointer,Array,Struct,Function}Type.prototype.
// This exists to give said prototypes a class of "CType", and to provide
// reserved slots for stashing various other prototype objects.
static const JSClassOps sCTypeProtoClassOps = {
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
ConstructAbstract, nullptr, ConstructAbstract
};
static const JSClass sCTypeProtoClass = {
"CType",
JSCLASS_HAS_RESERVED_SLOTS(CTYPEPROTO_SLOTS),
&sCTypeProtoClassOps
};
// Class representing ctypes.CData.prototype and the 'prototype' properties
// of CTypes. This exists to give said prototypes a class of "CData".
static const JSClass sCDataProtoClass = {
"CData",
0
};
static const JSClassOps sCTypeClassOps = {
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, CType::Finalize,
CType::ConstructData, CType::HasInstance, CType::ConstructData,
CType::Trace
};
static const JSClass sCTypeClass = {
"CType",
JSCLASS_HAS_RESERVED_SLOTS(CTYPE_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&sCTypeClassOps
};
static const JSClassOps sCDataClassOps = {
nullptr, nullptr, ArrayType::Getter, ArrayType::Setter,
nullptr, nullptr, nullptr, CData::Finalize,
FunctionType::Call, nullptr, FunctionType::Call
};
static const JSClass sCDataClass = {
"CData",
JSCLASS_HAS_RESERVED_SLOTS(CDATA_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&sCDataClassOps
};
static const JSClassOps sCClosureClassOps = {
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, CClosure::Finalize,
nullptr, nullptr, nullptr, CClosure::Trace
};
static const JSClass sCClosureClass = {
"CClosure",
JSCLASS_HAS_RESERVED_SLOTS(CCLOSURE_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&sCClosureClassOps
};
/*
* Class representing the prototype of CDataFinalizer.
*/
static const JSClass sCDataFinalizerProtoClass = {
"CDataFinalizer",
0
};
/*
* Class representing instances of CDataFinalizer.
*
* Instances of CDataFinalizer have both private data (with type
* |CDataFinalizer::Private|) and slots (see |CDataFinalizerSlots|).
*/
static const JSClassOps sCDataFinalizerClassOps = {
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, CDataFinalizer::Finalize
};
static const JSClass sCDataFinalizerClass = {
"CDataFinalizer",
JSCLASS_HAS_PRIVATE |
JSCLASS_HAS_RESERVED_SLOTS(CDATAFINALIZER_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&sCDataFinalizerClassOps
};
#define CTYPESFN_FLAGS \
(JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)
#define CTYPESCTOR_FLAGS \
(CTYPESFN_FLAGS | JSFUN_CONSTRUCTOR)
#define CTYPESACC_FLAGS \
(JSPROP_ENUMERATE | JSPROP_PERMANENT)
#define CABIFN_FLAGS \
(JSPROP_READONLY | JSPROP_PERMANENT)
#define CDATAFN_FLAGS \
(JSPROP_READONLY | JSPROP_PERMANENT)
#define CDATAFINALIZERFN_FLAGS \
(JSPROP_READONLY | JSPROP_PERMANENT)
static const JSPropertySpec sCTypeProps[] = {
JS_PSG("name",
(Property<CType::IsCType, CType::NameGetter>::Fun),
CTYPESACC_FLAGS),
JS_PSG("size",
(Property<CType::IsCType, CType::SizeGetter>::Fun),
CTYPESACC_FLAGS),
JS_PSG("ptr",
(Property<CType::IsCType, CType::PtrGetter>::Fun),
CTYPESACC_FLAGS),
JS_PSG("prototype",
(Property<CType::IsCTypeOrProto, CType::PrototypeGetter>::Fun),
CTYPESACC_FLAGS),
JS_PS_END
};
static const JSFunctionSpec sCTypeFunctions[] = {
JS_FN("array", CType::CreateArray, 0, CTYPESFN_FLAGS),
JS_FN("toString", CType::ToString, 0, CTYPESFN_FLAGS),
JS_FN("toSource", CType::ToSource, 0, CTYPESFN_FLAGS),
JS_FS_END
};
static const JSFunctionSpec sCABIFunctions[] = {
JS_FN("toSource", ABI::ToSource, 0, CABIFN_FLAGS),
JS_FN("toString", ABI::ToSource, 0, CABIFN_FLAGS),
JS_FS_END
};
static const JSPropertySpec sCDataProps[] = {
JS_PSGS("value",
(Property<CData::IsCData, CData::ValueGetter>::Fun),
(Property<CData::IsCData, CData::ValueSetter>::Fun),
JSPROP_PERMANENT),
JS_PS_END
};
static const JSFunctionSpec sCDataFunctions[] = {
JS_FN("address", CData::Address, 0, CDATAFN_FLAGS),
JS_FN("readString", CData::ReadString, 0, CDATAFN_FLAGS),
JS_FN("readStringReplaceMalformed", CData::ReadStringReplaceMalformed, 0, CDATAFN_FLAGS),
JS_FN("toSource", CData::ToSource, 0, CDATAFN_FLAGS),
JS_FN("toString", CData::ToSource, 0, CDATAFN_FLAGS),
JS_FS_END
};
static const JSFunctionSpec sCDataFinalizerFunctions[] = {
JS_FN("dispose", CDataFinalizer::Methods::Dispose, 0, CDATAFINALIZERFN_FLAGS),
JS_FN("forget", CDataFinalizer::Methods::Forget, 0, CDATAFINALIZERFN_FLAGS),
JS_FN("readString", CDataFinalizer::Methods::ReadString, 0, CDATAFINALIZERFN_FLAGS),
JS_FN("toString", CDataFinalizer::Methods::ToString, 0, CDATAFINALIZERFN_FLAGS),
JS_FN("toSource", CDataFinalizer::Methods::ToSource, 0, CDATAFINALIZERFN_FLAGS),
JS_FS_END
};
static const JSFunctionSpec sPointerFunction =
JS_FN("PointerType", PointerType::Create, 1, CTYPESCTOR_FLAGS);
static const JSPropertySpec sPointerProps[] = {
JS_PSG("targetType",
(Property<PointerType::IsPointerType, PointerType::TargetTypeGetter>::Fun),
CTYPESACC_FLAGS),
JS_PS_END
};
static const JSFunctionSpec sPointerInstanceFunctions[] = {
JS_FN("isNull", PointerType::IsNull, 0, CTYPESFN_FLAGS),
JS_FN("increment", PointerType::Increment, 0, CTYPESFN_FLAGS),
JS_FN("decrement", PointerType::Decrement, 0, CTYPESFN_FLAGS),
JS_FS_END
};
static const JSPropertySpec sPointerInstanceProps[] = {
JS_PSGS("contents",
(Property<PointerType::IsPointer, PointerType::ContentsGetter>::Fun),
(Property<PointerType::IsPointer, PointerType::ContentsSetter>::Fun),
JSPROP_PERMANENT),
JS_PS_END
};
static const JSFunctionSpec sArrayFunction =
JS_FN("ArrayType", ArrayType::Create, 1, CTYPESCTOR_FLAGS);
static const JSPropertySpec sArrayProps[] = {
JS_PSG("elementType",
(Property<ArrayType::IsArrayType, ArrayType::ElementTypeGetter>::Fun),
CTYPESACC_FLAGS),
JS_PSG("length",
(Property<ArrayType::IsArrayOrArrayType, ArrayType::LengthGetter>::Fun),
CTYPESACC_FLAGS),
JS_PS_END
};
static const JSFunctionSpec sArrayInstanceFunctions[] = {
JS_FN("addressOfElement", ArrayType::AddressOfElement, 1, CDATAFN_FLAGS),
JS_FS_END
};
static const JSPropertySpec sArrayInstanceProps[] = {
JS_PSG("length",
(Property<ArrayType::IsArrayOrArrayType, ArrayType::LengthGetter>::Fun),
JSPROP_PERMANENT),
JS_PS_END
};
static const JSFunctionSpec sStructFunction =
JS_FN("StructType", StructType::Create, 2, CTYPESCTOR_FLAGS);
static const JSPropertySpec sStructProps[] = {
JS_PSG("fields",
(Property<StructType::IsStruct, StructType::FieldsArrayGetter>::Fun),
CTYPESACC_FLAGS),
JS_PS_END
};
static const JSFunctionSpec sStructFunctions[] = {
JS_FN("define", StructType::Define, 1, CDATAFN_FLAGS),
JS_FS_END
};
static const JSFunctionSpec sStructInstanceFunctions[] = {
JS_FN("addressOfField", StructType::AddressOfField, 1, CDATAFN_FLAGS),
JS_FS_END
};
static const JSFunctionSpec sFunctionFunction =
JS_FN("FunctionType", FunctionType::Create, 2, CTYPESCTOR_FLAGS);
static const JSPropertySpec sFunctionProps[] = {
JS_PSG("argTypes",
(Property<FunctionType::IsFunctionType, FunctionType::ArgTypesGetter>::Fun),
CTYPESACC_FLAGS),
JS_PSG("returnType",
(Property<FunctionType::IsFunctionType, FunctionType::ReturnTypeGetter>::Fun),
CTYPESACC_FLAGS),
JS_PSG("abi",
(Property<FunctionType::IsFunctionType, FunctionType::ABIGetter>::Fun),
CTYPESACC_FLAGS),
JS_PSG("isVariadic",
(Property<FunctionType::IsFunctionType, FunctionType::IsVariadicGetter>::Fun),
CTYPESACC_FLAGS),
JS_PS_END
};
static const JSFunctionSpec sFunctionInstanceFunctions[] = {
JS_FN("call", js::fun_call, 1, CDATAFN_FLAGS),
JS_FN("apply", js::fun_apply, 2, CDATAFN_FLAGS),
JS_FS_END
};
static const JSClass sInt64ProtoClass = {
"Int64",
0
};
static const JSClass sUInt64ProtoClass = {
"UInt64",
0
};
static const JSClassOps sInt64ClassOps = {
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, Int64Base::Finalize
};
static const JSClass sInt64Class = {
"Int64",
JSCLASS_HAS_RESERVED_SLOTS(INT64_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&sInt64ClassOps
};
static const JSClass sUInt64Class = {
"UInt64",
JSCLASS_HAS_RESERVED_SLOTS(INT64_SLOTS) |
JSCLASS_FOREGROUND_FINALIZE,
&sInt64ClassOps
};
static const JSFunctionSpec sInt64StaticFunctions[] = {
JS_FN("compare", Int64::Compare, 2, CTYPESFN_FLAGS),
JS_FN("lo", Int64::Lo, 1, CTYPESFN_FLAGS),
JS_FN("hi", Int64::Hi, 1, CTYPESFN_FLAGS),
// "join" is defined specially; see InitInt64Class.
JS_FS_END
};
static const JSFunctionSpec sUInt64StaticFunctions[] = {
JS_FN("compare", UInt64::Compare, 2, CTYPESFN_FLAGS),
JS_FN("lo", UInt64::Lo, 1, CTYPESFN_FLAGS),
JS_FN("hi", UInt64::Hi, 1, CTYPESFN_FLAGS),
// "join" is defined specially; see InitInt64Class.
JS_FS_END
};
static const JSFunctionSpec sInt64Functions[] = {
JS_FN("toString", Int64::ToString, 0, CTYPESFN_FLAGS),
JS_FN("toSource", Int64::ToSource, 0, CTYPESFN_FLAGS),
JS_FS_END
};
static const JSFunctionSpec sUInt64Functions[] = {
JS_FN("toString", UInt64::ToString, 0, CTYPESFN_FLAGS),
JS_FN("toSource", UInt64::ToSource, 0, CTYPESFN_FLAGS),
JS_FS_END
};
static const JSPropertySpec sModuleProps[] = {
JS_PSG("errno",
(Property<IsCTypesGlobal, CData::ErrnoGetter>::Fun),
JSPROP_PERMANENT),
#if defined(XP_WIN)
JS_PSG("winLastError",
(Property<IsCTypesGlobal, CData::LastErrorGetter>::Fun),
JSPROP_PERMANENT),
#endif // defined(XP_WIN)
JS_PS_END
};
static const JSFunctionSpec sModuleFunctions[] = {
JS_FN("CDataFinalizer", CDataFinalizer::Construct, 2, CTYPESFN_FLAGS),
JS_FN("open", Library::Open, 1, CTYPESFN_FLAGS),
JS_FN("cast", CData::Cast, 2, CTYPESFN_FLAGS),
JS_FN("getRuntime", CData::GetRuntime, 1, CTYPESFN_FLAGS),
JS_FN("libraryName", Library::Name, 1, CTYPESFN_FLAGS),
JS_FS_END
};
static MOZ_ALWAYS_INLINE JSString*
NewUCString(JSContext* cx, const AutoString& from)
{
return JS_NewUCStringCopyN(cx, from.begin(), from.length());
}
/*
* Return a size rounded up to a multiple of a power of two.
*
* Note: |align| must be a power of 2.
*/
static MOZ_ALWAYS_INLINE size_t
Align(size_t val, size_t align)
{
// Ensure that align is a power of two.
MOZ_ASSERT(align != 0 && (align & (align - 1)) == 0);
return ((val - 1) | (align - 1)) + 1;
}
static ABICode
GetABICode(JSObject* obj)
{
// make sure we have an object representing a CABI class,
// and extract the enumerated class type from the reserved slot.
if (JS_GetClass(obj) != &sCABIClass)
return INVALID_ABI;
Value result = JS_GetReservedSlot(obj, SLOT_ABICODE);
return ABICode(result.toInt32());
}
static const JSErrorFormatString ErrorFormatString[CTYPESERR_LIMIT] = {
#define MSG_DEF(name, count, exception, format) \
{ #name, format, count, exception } ,
#include "ctypes/ctypes.msg"
#undef MSG_DEF
};
static const JSErrorFormatString*
GetErrorMessage(void* userRef, const unsigned errorNumber)
{
if (0 < errorNumber && errorNumber < CTYPESERR_LIMIT)
return &ErrorFormatString[errorNumber];
return nullptr;
}
static const char*
EncodeLatin1(JSContext* cx, AutoString& str, JSAutoByteString& bytes)
{
return bytes.encodeLatin1(cx, NewUCString(cx, str));
}
static const char*
CTypesToSourceForError(JSContext* cx, HandleValue val, JSAutoByteString& bytes)
{
if (val.isObject() &&
(CType::IsCType(&val.toObject()) || CData::IsCData(&val.toObject()))) {
RootedString str(cx, JS_ValueToSource(cx, val));
return bytes.encodeLatin1(cx, str);
}
return ValueToSourceForError(cx, val, bytes);
}
static void
BuildCStyleFunctionTypeSource(JSContext* cx, HandleObject typeObj,
HandleString nameStr, unsigned ptrCount,
AutoString& source);
static void
BuildCStyleTypeSource(JSContext* cx, JSObject* typeObj_, AutoString& source)
{
RootedObject typeObj(cx, typeObj_);
MOZ_ASSERT(CType::IsCType(typeObj));
switch (CType::GetTypeCode(typeObj)) {
#define BUILD_SOURCE(name, fromType, ffiType) \
case TYPE_##name: \
AppendString(source, #name); \
break;
CTYPES_FOR_EACH_TYPE(BUILD_SOURCE)
#undef BUILD_SOURCE
case TYPE_void_t:
AppendString(source, "void");
break;
case TYPE_pointer: {
unsigned ptrCount = 0;
TypeCode type;
RootedObject baseTypeObj(cx, typeObj);
do {
baseTypeObj = PointerType::GetBaseType(baseTypeObj);
ptrCount++;
type = CType::GetTypeCode(baseTypeObj);
} while (type == TYPE_pointer || type == TYPE_array);
if (type == TYPE_function) {
BuildCStyleFunctionTypeSource(cx, baseTypeObj, nullptr, ptrCount,
source);
break;
}
BuildCStyleTypeSource(cx, baseTypeObj, source);
AppendChars(source, '*', ptrCount);
break;
}
case TYPE_struct: {
RootedString name(cx, CType::GetName(cx, typeObj));
AppendString(source, "struct ");
AppendString(source, name);
break;
}
case TYPE_function:
BuildCStyleFunctionTypeSource(cx, typeObj, nullptr, 0, source);
break;
case TYPE_array:
MOZ_CRASH("TYPE_array shouldn't appear in function type");
}
}
static void
BuildCStyleFunctionTypeSource(JSContext* cx, HandleObject typeObj,
HandleString nameStr, unsigned ptrCount,
AutoString& source)
{
MOZ_ASSERT(CType::IsCType(typeObj));
FunctionInfo* fninfo = FunctionType::GetFunctionInfo(typeObj);
BuildCStyleTypeSource(cx, fninfo->mReturnType, source);
AppendString(source, " ");
if (nameStr) {
MOZ_ASSERT(ptrCount == 0);
AppendString(source, nameStr);
} else if (ptrCount) {
AppendString(source, "(");
AppendChars(source, '*', ptrCount);
AppendString(source, ")");
}
AppendString(source, "(");
if (fninfo->mArgTypes.length() > 0) {
for (size_t i = 0; i < fninfo->mArgTypes.length(); ++i) {
BuildCStyleTypeSource(cx, fninfo->mArgTypes[i], source);
if (i != fninfo->mArgTypes.length() - 1 || fninfo->mIsVariadic) {
AppendString(source, ", ");
}
}
if (fninfo->mIsVariadic) {
AppendString(source, "...");
}
}
AppendString(source, ")");
}
static void
BuildFunctionTypeSource(JSContext* cx, HandleObject funObj, AutoString& source)
{
MOZ_ASSERT(CData::IsCData(funObj) || CType::IsCType(funObj));
if (CData::IsCData(funObj)) {
Value slot = JS_GetReservedSlot(funObj, SLOT_REFERENT);
if (!slot.isUndefined() && Library::IsLibrary(&slot.toObject())) {
slot = JS_GetReservedSlot(funObj, SLOT_FUNNAME);
MOZ_ASSERT(!slot.isUndefined());
RootedObject typeObj(cx, CData::GetCType(funObj));
RootedObject baseTypeObj(cx, PointerType::GetBaseType(typeObj));
RootedString nameStr(cx, slot.toString());
BuildCStyleFunctionTypeSource(cx, baseTypeObj, nameStr, 0, source);
return;
}
}
RootedValue funVal(cx, ObjectValue(*funObj));
RootedString funcStr(cx, JS_ValueToSource(cx, funVal));
if (!funcStr) {
JS_ClearPendingException(cx);
AppendString(source, "<<error converting function to string>>");
return;
}
AppendString(source, funcStr);
}
enum class ConversionType {
Argument = 0,
Construct,
Finalizer,
Return,
Setter
};
static void
BuildConversionPosition(JSContext* cx, ConversionType convType,
HandleObject funObj, unsigned argIndex,
AutoString& source)
{
switch (convType) {
case ConversionType::Argument: {
MOZ_ASSERT(funObj);
AppendString(source, " at argument ");
AppendUInt(source, argIndex + 1);
AppendString(source, " of ");
BuildFunctionTypeSource(cx, funObj, source);
break;
}
case ConversionType::Finalizer:
MOZ_ASSERT(funObj);
AppendString(source, " at argument 1 of ");
BuildFunctionTypeSource(cx, funObj, source);
break;
case ConversionType::Return:
MOZ_ASSERT(funObj);
AppendString(source, " at the return value of ");
BuildFunctionTypeSource(cx, funObj, source);
break;
default:
MOZ_ASSERT(!funObj);
break;
}
}
static JSFlatString*
GetFieldName(HandleObject structObj, unsigned fieldIndex)
{
const FieldInfoHash* fields = StructType::GetFieldInfo(structObj);
for (FieldInfoHash::Range r = fields->all(); !r.empty(); r.popFront()) {
if (r.front().value().mIndex == fieldIndex) {
return (&r.front())->key();
}
}
return nullptr;
}
static void
BuildTypeSource(JSContext* cx, JSObject* typeObj_, bool makeShort,
AutoString& result);
static bool
ConvError(JSContext* cx, const char* expectedStr, HandleValue actual,
ConversionType convType,
HandleObject funObj = nullptr, unsigned argIndex = 0,
HandleObject arrObj = nullptr, unsigned arrIndex = 0)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr)
return false;
if (arrObj) {
MOZ_ASSERT(CType::IsCType(arrObj));
switch (CType::GetTypeCode(arrObj)) {
case TYPE_array: {
MOZ_ASSERT(!funObj);
char indexStr[16];
SprintfLiteral(indexStr, "%u", arrIndex);
AutoString arrSource;
JSAutoByteString arrBytes;
BuildTypeSource(cx, arrObj, true, arrSource);
const char* arrStr = EncodeLatin1(cx, arrSource, arrBytes);
if (!arrStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_CONV_ERROR_ARRAY,
valStr, indexStr, arrStr);
break;
}
case TYPE_struct: {
JSFlatString* name = GetFieldName(arrObj, arrIndex);
MOZ_ASSERT(name);
JSAutoByteString nameBytes;
const char* nameStr = nameBytes.encodeLatin1(cx, name);
if (!nameStr)
return false;
AutoString structSource;
JSAutoByteString structBytes;
BuildTypeSource(cx, arrObj, true, structSource);
const char* structStr = EncodeLatin1(cx, structSource, structBytes);
if (!structStr)
return false;
JSAutoByteString posBytes;
const char* posStr;
if (funObj) {
AutoString posSource;
BuildConversionPosition(cx, convType, funObj, argIndex, posSource);
posStr = EncodeLatin1(cx, posSource, posBytes);
if (!posStr)
return false;
} else {
posStr = "";
}
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_CONV_ERROR_STRUCT,
valStr, nameStr, expectedStr, structStr, posStr);
break;
}
default:
MOZ_CRASH("invalid arrObj value");
}
return false;
}
switch (convType) {
case ConversionType::Argument: {
MOZ_ASSERT(funObj);
char indexStr[16];
SprintfLiteral(indexStr, "%u", argIndex + 1);
AutoString funSource;
JSAutoByteString funBytes;
BuildFunctionTypeSource(cx, funObj, funSource);
const char* funStr = EncodeLatin1(cx, funSource, funBytes);
if (!funStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_CONV_ERROR_ARG,
valStr, indexStr, funStr);
break;
}
case ConversionType::Finalizer: {
MOZ_ASSERT(funObj);
AutoString funSource;
JSAutoByteString funBytes;
BuildFunctionTypeSource(cx, funObj, funSource);
const char* funStr = EncodeLatin1(cx, funSource, funBytes);
if (!funStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_CONV_ERROR_FIN, valStr, funStr);
break;
}
case ConversionType::Return: {
MOZ_ASSERT(funObj);
AutoString funSource;
JSAutoByteString funBytes;
BuildFunctionTypeSource(cx, funObj, funSource);
const char* funStr = EncodeLatin1(cx, funSource, funBytes);
if (!funStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_CONV_ERROR_RET, valStr, funStr);
break;
}
case ConversionType::Setter:
case ConversionType::Construct:
MOZ_ASSERT(!funObj);
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_CONV_ERROR_SET, valStr, expectedStr);
break;
}
return false;
}
static bool
ConvError(JSContext* cx, HandleObject expectedType, HandleValue actual,
ConversionType convType,
HandleObject funObj = nullptr, unsigned argIndex = 0,
HandleObject arrObj = nullptr, unsigned arrIndex = 0)
{
MOZ_ASSERT(CType::IsCType(expectedType));
AutoString expectedSource;
JSAutoByteString expectedBytes;
BuildTypeSource(cx, expectedType, true, expectedSource);
const char* expectedStr = EncodeLatin1(cx, expectedSource, expectedBytes);
if (!expectedStr)
return false;
return ConvError(cx, expectedStr, actual, convType, funObj, argIndex,
arrObj, arrIndex);
}
static bool
ArgumentConvError(JSContext* cx, HandleValue actual, const char* funStr,
unsigned argIndex)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr)
return false;
char indexStr[16];
SprintfLiteral(indexStr, "%u", argIndex + 1);
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_CONV_ERROR_ARG, valStr, indexStr, funStr);
return false;
}
static bool
ArgumentLengthError(JSContext* cx, const char* fun, const char* count,
const char* s)
{
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_WRONG_ARG_LENGTH, fun, count, s);
return false;
}
static bool
ArrayLengthMismatch(JSContext* cx, unsigned expectedLength, HandleObject arrObj,
unsigned actualLength, HandleValue actual,
ConversionType convType)
{
MOZ_ASSERT(arrObj && CType::IsCType(arrObj));
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr)
return false;
char expectedLengthStr[16];
SprintfLiteral(expectedLengthStr, "%u", expectedLength);
char actualLengthStr[16];
SprintfLiteral(actualLengthStr, "%u", actualLength);
AutoString arrSource;
JSAutoByteString arrBytes;
BuildTypeSource(cx, arrObj, true, arrSource);
const char* arrStr = EncodeLatin1(cx, arrSource, arrBytes);
if (!arrStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_ARRAY_MISMATCH,
valStr, arrStr, expectedLengthStr, actualLengthStr);
return false;
}
static bool
ArrayLengthOverflow(JSContext* cx, unsigned expectedLength, HandleObject arrObj,
unsigned actualLength, HandleValue actual,
ConversionType convType)
{
MOZ_ASSERT(arrObj && CType::IsCType(arrObj));
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr)
return false;
char expectedLengthStr[16];
SprintfLiteral(expectedLengthStr, "%u", expectedLength);
char actualLengthStr[16];
SprintfLiteral(actualLengthStr, "%u", actualLength);
AutoString arrSource;
JSAutoByteString arrBytes;
BuildTypeSource(cx, arrObj, true, arrSource);
const char* arrStr = EncodeLatin1(cx, arrSource, arrBytes);
if (!arrStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_ARRAY_OVERFLOW,
valStr, arrStr, expectedLengthStr, actualLengthStr);
return false;
}
static bool
ArgumentRangeMismatch(JSContext* cx, const char* func, const char* range)
{
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
CTYPESMSG_ARG_RANGE_MISMATCH, func, range);
return false;
}
static bool
ArgumentTypeMismatch(JSContext* cx, const char* arg, const char* func,
const char* type)
{
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
CTYPESMSG_ARG_TYPE_MISMATCH, arg, func, type);
return false;
}
static bool
CannotConstructError(JSContext* cx, const char* type)
{
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
CTYPESMSG_CANNOT_CONSTRUCT, type);
return false;
}
static bool
DuplicateFieldError(JSContext* cx, Handle<JSFlatString*> name)
{
JSAutoByteString nameBytes;
const char* nameStr = nameBytes.encodeLatin1(cx, name);
if (!nameStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_DUPLICATE_FIELD, nameStr);
return false;
}
static bool
EmptyFinalizerCallError(JSContext* cx, const char* funName)
{
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
CTYPESMSG_EMPTY_FIN_CALL, funName);
return false;
}
static bool
EmptyFinalizerError(JSContext* cx, ConversionType convType,
HandleObject funObj = nullptr, unsigned argIndex = 0)
{
JSAutoByteString posBytes;
const char* posStr;
if (funObj) {
AutoString posSource;
BuildConversionPosition(cx, convType, funObj, argIndex, posSource);
posStr = EncodeLatin1(cx, posSource, posBytes);
if (!posStr)
return false;
} else {
posStr = "";
}
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_EMPTY_FIN, posStr);
return false;
}
static bool
FieldCountMismatch(JSContext* cx,
unsigned expectedCount, HandleObject structObj,
unsigned actualCount, HandleValue actual,
ConversionType convType,
HandleObject funObj = nullptr, unsigned argIndex = 0)
{
MOZ_ASSERT(structObj && CType::IsCType(structObj));
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr)
return false;
AutoString structSource;
JSAutoByteString structBytes;
BuildTypeSource(cx, structObj, true, structSource);
const char* structStr = EncodeLatin1(cx, structSource, structBytes);
if (!structStr)
return false;
char expectedCountStr[16];
SprintfLiteral(expectedCountStr, "%u", expectedCount);
char actualCountStr[16];
SprintfLiteral(actualCountStr, "%u", actualCount);
JSAutoByteString posBytes;
const char* posStr;
if (funObj) {
AutoString posSource;
BuildConversionPosition(cx, convType, funObj, argIndex, posSource);
posStr = EncodeLatin1(cx, posSource, posBytes);
if (!posStr)
return false;
} else {
posStr = "";
}
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_FIELD_MISMATCH,
valStr, structStr, expectedCountStr, actualCountStr,
posStr);
return false;
}
static bool
FieldDescriptorCountError(JSContext* cx, HandleValue typeVal, size_t length)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, typeVal, valBytes);
if (!valStr)
return false;
char lengthStr[16];
SprintfLiteral(lengthStr, "%" PRIuSIZE, length);
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_FIELD_DESC_COUNT, valStr, lengthStr);
return false;
}
static bool
FieldDescriptorNameError(JSContext* cx, HandleId id)
{
JSAutoByteString idBytes;
RootedValue idVal(cx, IdToValue(id));
const char* propStr = CTypesToSourceForError(cx, idVal, idBytes);
if (!propStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_FIELD_DESC_NAME, propStr);
return false;
}
static bool
FieldDescriptorSizeError(JSContext* cx, HandleObject typeObj, HandleId id)
{
RootedValue typeVal(cx, ObjectValue(*typeObj));
JSAutoByteString typeBytes;
const char* typeStr = CTypesToSourceForError(cx, typeVal, typeBytes);
if (!typeStr)
return false;
RootedString idStr(cx, IdToString(cx, id));
JSAutoByteString idBytes;
const char* propStr = idBytes.encodeLatin1(cx, idStr);
if (!propStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_FIELD_DESC_SIZE, typeStr, propStr);
return false;
}
static bool
FieldDescriptorNameTypeError(JSContext* cx, HandleValue typeVal)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, typeVal, valBytes);
if (!valStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_FIELD_DESC_NAMETYPE, valStr);
return false;
}
static bool
FieldDescriptorTypeError(JSContext* cx, HandleValue poroVal, HandleId id)
{
JSAutoByteString typeBytes;
const char* typeStr = CTypesToSourceForError(cx, poroVal, typeBytes);
if (!typeStr)
return false;
RootedString idStr(cx, IdToString(cx, id));
JSAutoByteString idBytes;
const char* propStr = idBytes.encodeLatin1(cx, idStr);
if (!propStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_FIELD_DESC_TYPE, typeStr, propStr);
return false;
}
static bool
FieldMissingError(JSContext* cx, JSObject* typeObj, JSFlatString* name_)
{
JSAutoByteString typeBytes;
RootedString name(cx, name_);
RootedValue typeVal(cx, ObjectValue(*typeObj));
const char* typeStr = CTypesToSourceForError(cx, typeVal, typeBytes);
if (!typeStr)
return false;
JSAutoByteString nameBytes;
const char* nameStr = nameBytes.encodeLatin1(cx, name);
if (!nameStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_FIELD_MISSING, typeStr, nameStr);
return false;
}
static bool
FinalizerSizeError(JSContext* cx, HandleObject funObj, HandleValue actual)
{
MOZ_ASSERT(CType::IsCType(funObj));
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr)
return false;
AutoString funSource;
JSAutoByteString funBytes;
BuildFunctionTypeSource(cx, funObj, funSource);
const char* funStr = EncodeLatin1(cx, funSource, funBytes);
if (!funStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_FIN_SIZE_ERROR, funStr, valStr);
return false;
}
static bool
FunctionArgumentLengthMismatch(JSContext* cx,
unsigned expectedCount, unsigned actualCount,
HandleObject funObj, HandleObject typeObj,
bool isVariadic)
{
AutoString funSource;
JSAutoByteString funBytes;
Value slot = JS_GetReservedSlot(funObj, SLOT_REFERENT);
if (!slot.isUndefined() && Library::IsLibrary(&slot.toObject())) {
BuildFunctionTypeSource(cx, funObj, funSource);
} else {
BuildFunctionTypeSource(cx, typeObj, funSource);
}
const char* funStr = EncodeLatin1(cx, funSource, funBytes);
if (!funStr)
return false;
char expectedCountStr[16];
SprintfLiteral(expectedCountStr, "%u", expectedCount);
char actualCountStr[16];
SprintfLiteral(actualCountStr, "%u", actualCount);
const char* variadicStr = isVariadic ? " or more": "";
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_ARG_COUNT_MISMATCH,
funStr, expectedCountStr, variadicStr,
actualCountStr);
return false;
}
static bool
FunctionArgumentTypeError(JSContext* cx,
uint32_t index, HandleValue typeVal, const char* reason)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, typeVal, valBytes);
if (!valStr)
return false;
char indexStr[16];
SprintfLiteral(indexStr, "%u", index + 1);
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_ARG_TYPE_ERROR,
indexStr, reason, valStr);
return false;
}
static bool
FunctionReturnTypeError(JSContext* cx, HandleValue type, const char* reason)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, type, valBytes);
if (!valStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_RET_TYPE_ERROR, reason, valStr);
return false;
}
static bool
IncompatibleCallee(JSContext* cx, const char* funName, HandleObject actualObj)
{
JSAutoByteString valBytes;
RootedValue val(cx, ObjectValue(*actualObj));
const char* valStr = CTypesToSourceForError(cx, val, valBytes);
if (!valStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_INCOMPATIBLE_CALLEE, funName, valStr);
return false;
}
static bool
IncompatibleThisProto(JSContext* cx, const char* funName,
const char* actualType)
{
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_INCOMPATIBLE_THIS,
funName, actualType);
return false;
}
static bool
IncompatibleThisProto(JSContext* cx, const char* funName, HandleValue actualVal)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actualVal, valBytes);
if (!valStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_INCOMPATIBLE_THIS_VAL,
funName, "incompatible object", valStr);
return false;
}
static bool
IncompatibleThisType(JSContext* cx, const char* funName, const char* actualType)
{
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
CTYPESMSG_INCOMPATIBLE_THIS_TYPE,
funName, actualType);
return false;
}
static bool
IncompatibleThisType(JSContext* cx, const char* funName, const char* actualType,
HandleValue actualVal)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actualVal, valBytes);
if (!valStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_INCOMPATIBLE_THIS_VAL,
funName, actualType, valStr);
return false;
}
static bool
InvalidIndexError(JSContext* cx, HandleValue val)
{
JSAutoByteString idBytes;
const char* indexStr = CTypesToSourceForError(cx, val, idBytes);
if (!indexStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_INVALID_INDEX, indexStr);
return false;
}
static bool
InvalidIndexError(JSContext* cx, HandleId id)
{
RootedValue idVal(cx, IdToValue(id));
return InvalidIndexError(cx, idVal);
}
static bool
InvalidIndexRangeError(JSContext* cx, size_t index, size_t length)
{
char indexStr[16];
SprintfLiteral(indexStr, "%" PRIuSIZE, index);
char lengthStr[16];
SprintfLiteral(lengthStr,"%" PRIuSIZE, length);
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
CTYPESMSG_INVALID_RANGE, indexStr, lengthStr);
return false;
}
static bool
NonPrimitiveError(JSContext* cx, HandleObject typeObj)
{
MOZ_ASSERT(CType::IsCType(typeObj));
AutoString typeSource;
JSAutoByteString typeBytes;
BuildTypeSource(cx, typeObj, true, typeSource);
const char* typeStr = EncodeLatin1(cx, typeSource, typeBytes);
if (!typeStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_NON_PRIMITIVE, typeStr);
return false;
}
static bool
NonStringBaseError(JSContext* cx, HandleValue thisVal)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, thisVal, valBytes);
if (!valStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_NON_STRING_BASE, valStr);
return false;
}
static bool
NullPointerError(JSContext* cx, const char* action, HandleObject obj)
{
JSAutoByteString valBytes;
RootedValue val(cx, ObjectValue(*obj));
const char* valStr = CTypesToSourceForError(cx, val, valBytes);
if (!valStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_NULL_POINTER, action, valStr);
return false;
}
static bool
PropNameNonStringError(JSContext* cx, HandleId id, HandleValue actual,
ConversionType convType,
HandleObject funObj = nullptr, unsigned argIndex = 0)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr)
return false;
JSAutoByteString idBytes;
RootedValue idVal(cx, IdToValue(id));
const char* propStr = CTypesToSourceForError(cx, idVal, idBytes);
if (!propStr)
return false;
JSAutoByteString posBytes;
const char* posStr;
if (funObj) {
AutoString posSource;
BuildConversionPosition(cx, convType, funObj, argIndex, posSource);
posStr = EncodeLatin1(cx, posSource, posBytes);
if (!posStr)
return false;
} else {
posStr = "";
}
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_PROP_NONSTRING, propStr, valStr, posStr);
return false;
}
static bool
SizeOverflow(JSContext* cx, const char* name, const char* limit)
{
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
CTYPESMSG_SIZE_OVERFLOW, name, limit);
return false;
}
static bool
TypeError(JSContext* cx, const char* expected, HandleValue actual)
{
JSAutoByteString bytes;
const char* src = CTypesToSourceForError(cx, actual, bytes);
if (!src)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_TYPE_ERROR, expected, src);
return false;
}
static bool
TypeOverflow(JSContext* cx, const char* expected, HandleValue actual)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_TYPE_OVERFLOW, valStr, expected);
return false;
}
static bool
UndefinedSizeCastError(JSContext* cx, HandleObject targetTypeObj)
{
AutoString targetTypeSource;
JSAutoByteString targetTypeBytes;
BuildTypeSource(cx, targetTypeObj, true, targetTypeSource);
const char* targetTypeStr = EncodeLatin1(cx, targetTypeSource,
targetTypeBytes);
if (!targetTypeStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_UNDEFINED_SIZE_CAST, targetTypeStr);
return false;
}
static bool
SizeMismatchCastError(JSContext* cx,
HandleObject sourceTypeObj, HandleObject targetTypeObj,
size_t sourceSize, size_t targetSize)
{
AutoString sourceTypeSource;
JSAutoByteString sourceTypeBytes;
BuildTypeSource(cx, sourceTypeObj, true, sourceTypeSource);
const char* sourceTypeStr = EncodeLatin1(cx, sourceTypeSource,
sourceTypeBytes);
if (!sourceTypeStr)
return false;
AutoString targetTypeSource;
JSAutoByteString targetTypeBytes;
BuildTypeSource(cx, targetTypeObj, true, targetTypeSource);
const char* targetTypeStr = EncodeLatin1(cx, targetTypeSource,
targetTypeBytes);
if (!targetTypeStr)
return false;
char sourceSizeStr[16];
char targetSizeStr[16];
SprintfLiteral(sourceSizeStr, "%" PRIuSIZE, sourceSize);
SprintfLiteral(targetSizeStr, "%" PRIuSIZE, targetSize);
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_SIZE_MISMATCH_CAST,
targetTypeStr, sourceTypeStr,
targetSizeStr, sourceSizeStr);
return false;
}
static bool
UndefinedSizePointerError(JSContext* cx, const char* action, HandleObject obj)
{
JSAutoByteString valBytes;
RootedValue val(cx, ObjectValue(*obj));
const char* valStr = CTypesToSourceForError(cx, val, valBytes);
if (!valStr)
return false;
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_UNDEFINED_SIZE, action, valStr);
return false;
}
static bool
VariadicArgumentTypeError(JSContext* cx, uint32_t index, HandleValue actual)
{
JSAutoByteString valBytes;
const char* valStr = CTypesToSourceForError(cx, actual, valBytes);
if (!valStr)
return false;
char indexStr[16];
SprintfLiteral(indexStr, "%u", index + 1);
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
CTYPESMSG_VARG_TYPE_ERROR, indexStr, valStr);
return false;
}
static JSObject*
InitCTypeClass(JSContext* cx, HandleObject ctypesObj)
{
JSFunction* fun = JS_DefineFunction(cx, ctypesObj, "CType", ConstructAbstract, 0,
CTYPESCTOR_FLAGS);
if (!fun)
return nullptr;
RootedObject ctor(cx, JS_GetFunctionObject(fun));
RootedObject fnproto(cx);
if (!JS_GetPrototype(cx, ctor, &fnproto))
return nullptr;
MOZ_ASSERT(ctor);
MOZ_ASSERT(fnproto);
// Set up ctypes.CType.prototype.
RootedObject prototype(cx, JS_NewObjectWithGivenProto(cx, &sCTypeProtoClass, fnproto));
if (!prototype)
return nullptr;
if (!JS_DefineProperty(cx, ctor, "prototype", prototype,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return nullptr;
if (!JS_DefineProperty(cx, prototype, "constructor", ctor,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return nullptr;
// Define properties and functions common to all CTypes.
if (!JS_DefineProperties(cx, prototype, sCTypeProps) ||
!JS_DefineFunctions(cx, prototype, sCTypeFunctions))
return nullptr;
if (!JS_FreezeObject(cx, ctor) || !JS_FreezeObject(cx, prototype))
return nullptr;
return prototype;
}
static JSObject*
InitABIClass(JSContext* cx)
{
RootedObject obj(cx, JS_NewPlainObject(cx));
if (!obj)
return nullptr;
if (!JS_DefineFunctions(cx, obj, sCABIFunctions))
return nullptr;
return obj;
}
static JSObject*
InitCDataClass(JSContext* cx, HandleObject parent, HandleObject CTypeProto)
{
JSFunction* fun = JS_DefineFunction(cx, parent, "CData", ConstructAbstract, 0,
CTYPESCTOR_FLAGS);
if (!fun)
return nullptr;
RootedObject ctor(cx, JS_GetFunctionObject(fun));
MOZ_ASSERT(ctor);
// Set up ctypes.CData.__proto__ === ctypes.CType.prototype.
// (Note that 'ctypes.CData instanceof Function' is still true, thanks to the
// prototype chain.)
if (!JS_SetPrototype(cx, ctor, CTypeProto))
return nullptr;
// Set up ctypes.CData.prototype.
RootedObject prototype(cx, JS_NewObject(cx, &sCDataProtoClass));
if (!prototype)
return nullptr;
if (!JS_DefineProperty(cx, ctor, "prototype", prototype,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return nullptr;
if (!JS_DefineProperty(cx, prototype, "constructor", ctor,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return nullptr;
// Define properties and functions common to all CDatas.
if (!JS_DefineProperties(cx, prototype, sCDataProps) ||
!JS_DefineFunctions(cx, prototype, sCDataFunctions))
return nullptr;
if (//!JS_FreezeObject(cx, prototype) || // XXX fixme - see bug 541212!
!JS_FreezeObject(cx, ctor))
return nullptr;
return prototype;
}
static bool
DefineABIConstant(JSContext* cx,
HandleObject ctypesObj,
const char* name,
ABICode code,
HandleObject prototype)
{
RootedObject obj(cx, JS_NewObjectWithGivenProto(cx, &sCABIClass, prototype));
if (!obj)
return false;
JS_SetReservedSlot(obj, SLOT_ABICODE, Int32Value(code));
if (!JS_FreezeObject(cx, obj))
return false;
return JS_DefineProperty(cx, ctypesObj, name, obj,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
}
// Set up a single type constructor for
// ctypes.{Pointer,Array,Struct,Function}Type.
static bool
InitTypeConstructor(JSContext* cx,
HandleObject parent,
HandleObject CTypeProto,
HandleObject CDataProto,
const JSFunctionSpec spec,
const JSFunctionSpec* fns,
const JSPropertySpec* props,
const JSFunctionSpec* instanceFns,
const JSPropertySpec* instanceProps,
MutableHandleObject typeProto,
MutableHandleObject dataProto)
{
JSFunction* fun = js::DefineFunctionWithReserved(cx, parent, spec.name, spec.call.op,
spec.nargs, spec.flags);
if (!fun)
return false;
RootedObject obj(cx, JS_GetFunctionObject(fun));
if (!obj)
return false;
// Set up the .prototype and .prototype.constructor properties.
typeProto.set(JS_NewObjectWithGivenProto(cx, &sCTypeProtoClass, CTypeProto));
if (!typeProto)
return false;
// Define property before proceeding, for GC safety.
if (!JS_DefineProperty(cx, obj, "prototype", typeProto,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return false;
if (fns && !JS_DefineFunctions(cx, typeProto, fns))
return false;
if (!JS_DefineProperties(cx, typeProto, props))
return false;
if (!JS_DefineProperty(cx, typeProto, "constructor", obj,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return false;
// Stash ctypes.{Pointer,Array,Struct}Type.prototype on a reserved slot of
// the type constructor, for faster lookup.
js::SetFunctionNativeReserved(obj, SLOT_FN_CTORPROTO, ObjectValue(*typeProto));
// Create an object to serve as the common ancestor for all CData objects
// created from the given type constructor. This has ctypes.CData.prototype
// as its prototype, such that it inherits the properties and functions
// common to all CDatas.
dataProto.set(JS_NewObjectWithGivenProto(cx, &sCDataProtoClass, CDataProto));
if (!dataProto)
return false;
// Define functions and properties on the 'dataProto' object that are common
// to all CData objects created from this type constructor. (These will
// become functions and properties on CData objects created from this type.)
if (instanceFns && !JS_DefineFunctions(cx, dataProto, instanceFns))
return false;
if (instanceProps && !JS_DefineProperties(cx, dataProto, instanceProps))
return false;
// Link the type prototype to the data prototype.
JS_SetReservedSlot(typeProto, SLOT_OURDATAPROTO, ObjectValue(*dataProto));
if (!JS_FreezeObject(cx, obj) ||
//!JS_FreezeObject(cx, dataProto) || // XXX fixme - see bug 541212!
!JS_FreezeObject(cx, typeProto))
return false;
return true;
}
static JSObject*
InitInt64Class(JSContext* cx,
HandleObject parent,
const JSClass* clasp,
JSNative construct,
const JSFunctionSpec* fs,
const JSFunctionSpec* static_fs)
{
// Init type class and constructor
RootedObject prototype(cx, JS_InitClass(cx, parent, nullptr, clasp, construct,
0, nullptr, fs, nullptr, static_fs));
if (!prototype)
return nullptr;
RootedObject ctor(cx, JS_GetConstructor(cx, prototype));
if (!ctor)
return nullptr;
// Define the 'join' function as an extended native and stash
// ctypes.{Int64,UInt64}.prototype in a reserved slot of the new function.
MOZ_ASSERT(clasp == &sInt64ProtoClass || clasp == &sUInt64ProtoClass);
JSNative native = (clasp == &sInt64ProtoClass) ? Int64::Join : UInt64::Join;
JSFunction* fun = js::DefineFunctionWithReserved(cx, ctor, "join", native,
2, CTYPESFN_FLAGS);
if (!fun)
return nullptr;
js::SetFunctionNativeReserved(fun, SLOT_FN_INT64PROTO, ObjectValue(*prototype));
if (!JS_FreezeObject(cx, ctor))
return nullptr;
if (!JS_FreezeObject(cx, prototype))
return nullptr;
return prototype;
}
static void
AttachProtos(JSObject* proto, const AutoObjectVector& protos)
{
// For a given 'proto' of [[Class]] "CTypeProto", attach each of the 'protos'
// to the appropriate CTypeProtoSlot. (SLOT_CTYPES is the last slot
// of [[Class]] "CTypeProto" that we fill in this automated manner.)
for (uint32_t i = 0; i <= SLOT_CTYPES; ++i)
JS_SetReservedSlot(proto, i, ObjectOrNullValue(protos[i]));
}
static bool
InitTypeClasses(JSContext* cx, HandleObject ctypesObj)
{
// Initialize the ctypes.CType class. This acts as an abstract base class for
// the various types, and provides the common API functions. It has:
// * [[Class]] "Function"
// * __proto__ === Function.prototype
// * A constructor that throws a TypeError. (You can't construct an
// abstract type!)
// * 'prototype' property:
// * [[Class]] "CTypeProto"
// * __proto__ === Function.prototype
// * A constructor that throws a TypeError. (You can't construct an
// abstract type instance!)
// * 'constructor' property === ctypes.CType
// * Provides properties and functions common to all CTypes.
RootedObject CTypeProto(cx, InitCTypeClass(cx, ctypesObj));
if (!CTypeProto)
return false;
// Initialize the ctypes.CData class. This acts as an abstract base class for
// instances of the various types, and provides the common API functions.
// It has:
// * [[Class]] "Function"
// * __proto__ === Function.prototype
// * A constructor that throws a TypeError. (You can't construct an
// abstract type instance!)
// * 'prototype' property:
// * [[Class]] "CDataProto"
// * 'constructor' property === ctypes.CData
// * Provides properties and functions common to all CDatas.
RootedObject CDataProto(cx, InitCDataClass(cx, ctypesObj, CTypeProto));
if (!CDataProto)
return false;
// Link CTypeProto to CDataProto.
JS_SetReservedSlot(CTypeProto, SLOT_OURDATAPROTO, ObjectValue(*CDataProto));
// Create and attach the special class constructors: ctypes.PointerType,
// ctypes.ArrayType, ctypes.StructType, and ctypes.FunctionType.
// Each of these constructors 'c' has, respectively:
// * [[Class]] "Function"
// * __proto__ === Function.prototype
// * A constructor that creates a user-defined type.
// * 'prototype' property:
// * [[Class]] "CTypeProto"
// * __proto__ === ctypes.CType.prototype
// * 'constructor' property === 'c'
// We also construct an object 'p' to serve, given a type object 't'
// constructed from one of these type constructors, as
// 't.prototype.__proto__'. This object has:
// * [[Class]] "CDataProto"
// * __proto__ === ctypes.CData.prototype
// * Properties and functions common to all CDatas.
// Therefore an instance 't' of ctypes.{Pointer,Array,Struct,Function}Type
// will have, resp.:
// * [[Class]] "CType"
// * __proto__ === ctypes.{Pointer,Array,Struct,Function}Type.prototype
// * A constructor which creates and returns a CData object, containing
// binary data of the given type.
// * 'prototype' property:
// * [[Class]] "CDataProto"
// * __proto__ === 'p', the prototype object from above
// * 'constructor' property === 't'
AutoObjectVector protos(cx);
if (!protos.resize(CTYPEPROTO_SLOTS))
return false;
if (!InitTypeConstructor(cx, ctypesObj, CTypeProto, CDataProto,
sPointerFunction, nullptr, sPointerProps,
sPointerInstanceFunctions, sPointerInstanceProps,
protos[SLOT_POINTERPROTO], protos[SLOT_POINTERDATAPROTO]))
return false;
if (!InitTypeConstructor(cx, ctypesObj, CTypeProto, CDataProto,
sArrayFunction, nullptr, sArrayProps,
sArrayInstanceFunctions, sArrayInstanceProps,
protos[SLOT_ARRAYPROTO], protos[SLOT_ARRAYDATAPROTO]))
return false;
if (!InitTypeConstructor(cx, ctypesObj, CTypeProto, CDataProto,
sStructFunction, sStructFunctions, sStructProps,
sStructInstanceFunctions, nullptr,
protos[SLOT_STRUCTPROTO], protos[SLOT_STRUCTDATAPROTO]))
return false;
if (!InitTypeConstructor(cx, ctypesObj, CTypeProto, protos[SLOT_POINTERDATAPROTO],
sFunctionFunction, nullptr, sFunctionProps, sFunctionInstanceFunctions, nullptr,
protos[SLOT_FUNCTIONPROTO], protos[SLOT_FUNCTIONDATAPROTO]))
return false;
protos[SLOT_CDATAPROTO].set(CDataProto);
// Create and attach the ctypes.{Int64,UInt64} constructors.
// Each of these has, respectively:
// * [[Class]] "Function"
// * __proto__ === Function.prototype
// * A constructor that creates a ctypes.{Int64,UInt64} object, respectively.
// * 'prototype' property:
// * [[Class]] {"Int64Proto","UInt64Proto"}
// * 'constructor' property === ctypes.{Int64,UInt64}
protos[SLOT_INT64PROTO].set(InitInt64Class(cx, ctypesObj, &sInt64ProtoClass,
Int64::Construct, sInt64Functions, sInt64StaticFunctions));
if (!protos[SLOT_INT64PROTO])
return false;
protos[SLOT_UINT64PROTO].set(InitInt64Class(cx, ctypesObj, &sUInt64ProtoClass,
UInt64::Construct, sUInt64Functions, sUInt64StaticFunctions));
if (!protos[SLOT_UINT64PROTO])
return false;
// Finally, store a pointer to the global ctypes object.
// Note that there is no other reliable manner of locating this object.
protos[SLOT_CTYPES].set(ctypesObj);
// Attach the prototypes just created to each of ctypes.CType.prototype,
// and the special type constructors, so we can access them when constructing
// instances of those types.
AttachProtos(CTypeProto, protos);
AttachProtos(protos[SLOT_POINTERPROTO], protos);
AttachProtos(protos[SLOT_ARRAYPROTO], protos);
AttachProtos(protos[SLOT_STRUCTPROTO], protos);
AttachProtos(protos[SLOT_FUNCTIONPROTO], protos);
RootedObject ABIProto(cx, InitABIClass(cx));
if (!ABIProto)
return false;
// Attach objects representing ABI constants.
if (!DefineABIConstant(cx, ctypesObj, "default_abi", ABI_DEFAULT, ABIProto) ||
!DefineABIConstant(cx, ctypesObj, "stdcall_abi", ABI_STDCALL, ABIProto) ||
!DefineABIConstant(cx, ctypesObj, "thiscall_abi", ABI_THISCALL, ABIProto) ||
!DefineABIConstant(cx, ctypesObj, "winapi_abi", ABI_WINAPI, ABIProto))
return false;
// Create objects representing the builtin types, and attach them to the
// ctypes object. Each type object 't' has:
// * [[Class]] "CType"
// * __proto__ === ctypes.CType.prototype
// * A constructor which creates and returns a CData object, containing
// binary data of the given type.
// * 'prototype' property:
// * [[Class]] "CDataProto"
// * __proto__ === ctypes.CData.prototype
// * 'constructor' property === 't'
#define DEFINE_TYPE(name, type, ffiType) \
RootedObject typeObj_##name(cx); \
{ \
RootedValue typeVal(cx, Int32Value(sizeof(type))); \
RootedValue alignVal(cx, Int32Value(ffiType.alignment)); \
typeObj_##name = CType::DefineBuiltin(cx, ctypesObj, #name, CTypeProto, \
CDataProto, #name, TYPE_##name, \
typeVal, alignVal, &ffiType); \
if (!typeObj_##name) \
return false; \
}
CTYPES_FOR_EACH_TYPE(DEFINE_TYPE)
#undef DEFINE_TYPE
// Alias 'ctypes.unsigned' as 'ctypes.unsigned_int', since they represent
// the same type in C.
if (!JS_DefineProperty(cx, ctypesObj, "unsigned", typeObj_unsigned_int,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return false;
// Alias 'ctypes.jschar' as 'ctypes.char16_t' to prevent breaking addons
// that are still using jschar (bug 1064935).
if (!JS_DefineProperty(cx, ctypesObj, "jschar", typeObj_char16_t,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return false;
// Create objects representing the special types void_t and voidptr_t.
RootedObject typeObj(cx,
CType::DefineBuiltin(cx, ctypesObj, "void_t", CTypeProto, CDataProto, "void",
TYPE_void_t, JS::UndefinedHandleValue, JS::UndefinedHandleValue,
&ffi_type_void));
if (!typeObj)
return false;
typeObj = PointerType::CreateInternal(cx, typeObj);
if (!typeObj)
return false;
if (!JS_DefineProperty(cx, ctypesObj, "voidptr_t", typeObj,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return false;
return true;
}
bool
IsCTypesGlobal(JSObject* obj)
{
return JS_GetClass(obj) == &sCTypesGlobalClass;
}
bool
IsCTypesGlobal(HandleValue v)
{
return v.isObject() && IsCTypesGlobal(&v.toObject());
}
// Get the JSCTypesCallbacks struct from the 'ctypes' object 'obj'.
const JSCTypesCallbacks*
GetCallbacks(JSObject* obj)
{
MOZ_ASSERT(IsCTypesGlobal(obj));
Value result = JS_GetReservedSlot(obj, SLOT_CALLBACKS);
if (result.isUndefined())
return nullptr;
return static_cast<const JSCTypesCallbacks*>(result.toPrivate());
}
// Utility function to access a property of an object as an object
// returns false and sets the error if the property does not exist
// or is not an object
static bool GetObjectProperty(JSContext* cx, HandleObject obj,
const char* property, MutableHandleObject result)
{
RootedValue val(cx);
if (!JS_GetProperty(cx, obj, property, &val)) {
return false;
}
if (val.isPrimitive()) {
JS_ReportErrorASCII(cx, "missing or non-object field");
return false;
}
result.set(val.toObjectOrNull());
return true;
}
} /* namespace ctypes */
} /* namespace js */
using namespace js;
using namespace js::ctypes;
JS_PUBLIC_API(bool)
JS_InitCTypesClass(JSContext* cx, HandleObject global)
{
// attach ctypes property to global object
RootedObject ctypes(cx, JS_NewObject(cx, &sCTypesGlobalClass));
if (!ctypes)
return false;
if (!JS_DefineProperty(cx, global, "ctypes", ctypes,
JSPROP_READONLY | JSPROP_PERMANENT,
JS_STUBGETTER, JS_STUBSETTER)){
return false;
}
if (!InitTypeClasses(cx, ctypes))
return false;
// attach API functions and properties
if (!JS_DefineFunctions(cx, ctypes, sModuleFunctions) ||
!JS_DefineProperties(cx, ctypes, sModuleProps))
return false;
// Set up ctypes.CDataFinalizer.prototype.
RootedObject ctor(cx);
if (!GetObjectProperty(cx, ctypes, "CDataFinalizer", &ctor))
return false;
RootedObject prototype(cx, JS_NewObject(cx, &sCDataFinalizerProtoClass));
if (!prototype)
return false;
if (!JS_DefineFunctions(cx, prototype, sCDataFinalizerFunctions))
return false;
if (!JS_DefineProperty(cx, ctor, "prototype", prototype,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return false;
if (!JS_DefineProperty(cx, prototype, "constructor", ctor,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return false;
// Seal the ctypes object, to prevent modification.
return JS_FreezeObject(cx, ctypes);
}
JS_PUBLIC_API(void)
JS_SetCTypesCallbacks(JSObject* ctypesObj, const JSCTypesCallbacks* callbacks)
{
MOZ_ASSERT(callbacks);
MOZ_ASSERT(IsCTypesGlobal(ctypesObj));
// Set the callbacks on a reserved slot.
JS_SetReservedSlot(ctypesObj, SLOT_CALLBACKS,
PrivateValue(const_cast<JSCTypesCallbacks*>(callbacks)));
}
namespace js {
JS_FRIEND_API(size_t)
SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf, JSObject* obj)
{
if (!CData::IsCData(obj))
return 0;
size_t n = 0;
Value slot = JS_GetReservedSlot(obj, ctypes::SLOT_OWNS);
if (!slot.isUndefined()) {
bool owns = slot.toBoolean();
slot = JS_GetReservedSlot(obj, ctypes::SLOT_DATA);
if (!slot.isUndefined()) {
char** buffer = static_cast<char**>(slot.toPrivate());
n += mallocSizeOf(buffer);
if (owns)
n += mallocSizeOf(*buffer);
}
}
return n;
}
namespace ctypes {
/*******************************************************************************
** Type conversion functions
*******************************************************************************/
// Enforce some sanity checks on type widths and properties.
// Where the architecture is 64-bit, make sure it's LP64 or LLP64. (ctypes.int
// autoconverts to a primitive JS number; to support ILP64 architectures, it
// would need to autoconvert to an Int64 object instead. Therefore we enforce
// this invariant here.)
JS_STATIC_ASSERT(sizeof(bool) == 1 || sizeof(bool) == 4);
JS_STATIC_ASSERT(sizeof(char) == 1);
JS_STATIC_ASSERT(sizeof(short) == 2);
JS_STATIC_ASSERT(sizeof(int) == 4);
JS_STATIC_ASSERT(sizeof(unsigned) == 4);
JS_STATIC_ASSERT(sizeof(long) == 4 || sizeof(long) == 8);
JS_STATIC_ASSERT(sizeof(long long) == 8);
JS_STATIC_ASSERT(sizeof(size_t) == sizeof(uintptr_t));
JS_STATIC_ASSERT(sizeof(float) == 4);
JS_STATIC_ASSERT(sizeof(PRFuncPtr) == sizeof(void*));
JS_STATIC_ASSERT(numeric_limits<double>::is_signed);
// Templated helper to convert FromType to TargetType, for the default case
// where the trivial POD constructor will do.
template<class TargetType, class FromType>
struct ConvertImpl {
static MOZ_ALWAYS_INLINE TargetType Convert(FromType d) {
return TargetType(d);
}
};
#ifdef _MSC_VER
// MSVC can't perform double to unsigned __int64 conversion when the
// double is greater than 2^63 - 1. Help it along a little.
template<>
struct ConvertImpl<uint64_t, double> {
static MOZ_ALWAYS_INLINE uint64_t Convert(double d) {
return d > 0x7fffffffffffffffui64 ?
uint64_t(d - 0x8000000000000000ui64) + 0x8000000000000000ui64 :
uint64_t(d);
}
};
#endif
// C++ doesn't guarantee that exact values are the only ones that will
// round-trip. In fact, on some platforms, including SPARC, there are pairs of
// values, a uint64_t and a double, such that neither value is exactly
// representable in the other type, but they cast to each other.
#if defined(SPARC) || defined(__powerpc__)
// Simulate x86 overflow behavior
template<>
struct ConvertImpl<uint64_t, double> {
static MOZ_ALWAYS_INLINE uint64_t Convert(double d) {
return d >= 0xffffffffffffffff ?
0x8000000000000000 : uint64_t(d);
}
};
template<>
struct ConvertImpl<int64_t, double> {
static MOZ_ALWAYS_INLINE int64_t Convert(double d) {
return d >= 0x7fffffffffffffff ?
0x8000000000000000 : int64_t(d);
}
};
#endif
template<class TargetType, class FromType>
static MOZ_ALWAYS_INLINE TargetType Convert(FromType d)
{
return ConvertImpl<TargetType, FromType>::Convert(d);
}
template<class TargetType, class FromType>
static MOZ_ALWAYS_INLINE bool IsAlwaysExact()
{
// Return 'true' if TargetType can always exactly represent FromType.
// This means that:
// 1) TargetType must be the same or more bits wide as FromType. For integers
// represented in 'n' bits, unsigned variants will have 'n' digits while
// signed will have 'n - 1'. For floating point types, 'digits' is the
// mantissa width.
// 2) If FromType is signed, TargetType must also be signed. (Floating point
// types are always signed.)
// 3) If TargetType is an exact integral type, FromType must be also.
if (numeric_limits<TargetType>::digits < numeric_limits<FromType>::digits)
return false;
if (numeric_limits<FromType>::is_signed &&
!numeric_limits<TargetType>::is_signed)
return false;
if (!numeric_limits<FromType>::is_exact &&
numeric_limits<TargetType>::is_exact)
return false;
return true;
}
// Templated helper to determine if FromType 'i' converts losslessly to
// TargetType 'j'. Default case where both types are the same signedness.
template<class TargetType, class FromType, bool TargetSigned, bool FromSigned>
struct IsExactImpl {
static MOZ_ALWAYS_INLINE bool Test(FromType i, TargetType j) {
JS_STATIC_ASSERT(numeric_limits<TargetType>::is_exact);
return FromType(j) == i;
}
};
// Specialization where TargetType is unsigned, FromType is signed.
template<class TargetType, class FromType>
struct IsExactImpl<TargetType, FromType, false, true> {
static MOZ_ALWAYS_INLINE bool Test(FromType i, TargetType j) {
JS_STATIC_ASSERT(numeric_limits<TargetType>::is_exact);
return i >= 0 && FromType(j) == i;
}
};
// Specialization where TargetType is signed, FromType is unsigned.
template<class TargetType, class FromType>
struct IsExactImpl<TargetType, FromType, true, false> {
static MOZ_ALWAYS_INLINE bool Test(FromType i, TargetType j) {
JS_STATIC_ASSERT(numeric_limits<TargetType>::is_exact);
return TargetType(i) >= 0 && FromType(j) == i;
}
};
// Convert FromType 'i' to TargetType 'result', returning true iff 'result'
// is an exact representation of 'i'.
template<class TargetType, class FromType>
static MOZ_ALWAYS_INLINE bool ConvertExact(FromType i, TargetType* result)
{
// Require that TargetType is integral, to simplify conversion.
JS_STATIC_ASSERT(numeric_limits<TargetType>::is_exact);
*result = Convert<TargetType>(i);
// See if we can avoid a dynamic check.
if (IsAlwaysExact<TargetType, FromType>())
return true;
// Return 'true' if 'i' is exactly representable in 'TargetType'.
return IsExactImpl<TargetType,
FromType,
numeric_limits<TargetType>::is_signed,
numeric_limits<FromType>::is_signed>::Test(i, *result);
}
// Templated helper to determine if Type 'i' is negative. Default case
// where IntegerType is unsigned.
template<class Type, bool IsSigned>
struct IsNegativeImpl {
static MOZ_ALWAYS_INLINE bool Test(Type i) {
return false;
}
};
// Specialization where Type is signed.
template<class Type>
struct IsNegativeImpl<Type, true> {
static MOZ_ALWAYS_INLINE bool Test(Type i) {
return i < 0;
}
};
// Determine whether Type 'i' is negative.
template<class Type>
static MOZ_ALWAYS_INLINE bool IsNegative(Type i)
{
return IsNegativeImpl<Type, numeric_limits<Type>::is_signed>::Test(i);
}
// Implicitly convert val to bool, allowing bool, int, and double
// arguments numerically equal to 0 or 1.
static bool
jsvalToBool(JSContext* cx, HandleValue val, bool* result)
{
if (val.isBoolean()) {
*result = val.toBoolean();
return true;
}
if (val.isInt32()) {
int32_t i = val.toInt32();
*result = i != 0;
return i == 0 || i == 1;
}
if (val.isDouble()) {
double d = val.toDouble();
*result = d != 0;
// Allow -0.
return d == 1 || d == 0;
}
// Don't silently convert null to bool. It's probably a mistake.
return false;
}
// Implicitly convert val to IntegerType, allowing bool, int, double,
// Int64, UInt64, and CData integer types 't' where all values of 't' are
// representable by IntegerType.
template<class IntegerType>
static bool
jsvalToInteger(JSContext* cx, HandleValue val, IntegerType* result)
{
JS_STATIC_ASSERT(numeric_limits<IntegerType>::is_exact);
if (val.isInt32()) {
// Make sure the integer fits in the alotted precision, and has the right
// sign.
int32_t i = val.toInt32();
return ConvertExact(i, result);
}
if (val.isDouble()) {
// Don't silently lose bits here -- check that val really is an
// integer value, and has the right sign.
double d = val.toDouble();
return ConvertExact(d, result);
}
if (val.isObject()) {
JSObject* obj = &val.toObject();
if (CData::IsCData(obj)) {
JSObject* typeObj = CData::GetCType(obj);
void* data = CData::GetData(obj);
// Check whether the source type is always representable, with exact
// precision, by the target type. If it is, convert the value.
switch (CType::GetTypeCode(typeObj)) {
#define INTEGER_CASE(name, fromType, ffiType) \
case TYPE_##name: \
if (!IsAlwaysExact<IntegerType, fromType>()) \
return false; \
*result = IntegerType(*static_cast<fromType*>(data)); \
return true;
CTYPES_FOR_EACH_INT_TYPE(INTEGER_CASE)
CTYPES_FOR_EACH_WRAPPED_INT_TYPE(INTEGER_CASE)
#undef INTEGER_CASE
case TYPE_void_t:
case TYPE_bool:
case TYPE_float:
case TYPE_double:
case TYPE_float32_t:
case TYPE_float64_t:
case TYPE_char:
case TYPE_signed_char:
case TYPE_unsigned_char:
case TYPE_char16_t:
case TYPE_pointer:
case TYPE_function:
case TYPE_array:
case TYPE_struct:
// Not a compatible number type.
return false;
}
}
if (Int64::IsInt64(obj)) {
// Make sure the integer fits in IntegerType.
int64_t i = Int64Base::GetInt(obj);
return ConvertExact(i, result);
}
if (UInt64::IsUInt64(obj)) {
// Make sure the integer fits in IntegerType.
uint64_t i = Int64Base::GetInt(obj);
return ConvertExact(i, result);
}
if (CDataFinalizer::IsCDataFinalizer(obj)) {
RootedValue innerData(cx);
if (!CDataFinalizer::GetValue(cx, obj, &innerData)) {
return false; // Nothing to convert
}
return jsvalToInteger(cx, innerData, result);
}
return false;
}
if (val.isBoolean()) {
// Implicitly promote boolean values to 0 or 1, like C.
*result = val.toBoolean();
MOZ_ASSERT(*result == 0 || *result == 1);
return true;
}
// Don't silently convert null to an integer. It's probably a mistake.
return false;
}
// Implicitly convert val to FloatType, allowing int, double,
// Int64, UInt64, and CData numeric types 't' where all values of 't' are
// representable by FloatType.
template<class FloatType>
static bool
jsvalToFloat(JSContext* cx, HandleValue val, FloatType* result)
{
JS_STATIC_ASSERT(!numeric_limits<FloatType>::is_exact);
// The following casts may silently throw away some bits, but there's
// no good way around it. Sternly requiring that the 64-bit double
// argument be exactly representable as a 32-bit float is
// unrealistic: it would allow 1/2 to pass but not 1/3.
if (val.isInt32()) {
*result = FloatType(val.toInt32());
return true;
}
if (val.isDouble()) {
*result = FloatType(val.toDouble());
return true;
}
if (val.isObject()) {
JSObject* obj = &val.toObject();
if (CData::IsCData(obj)) {
JSObject* typeObj = CData::GetCType(obj);
void* data = CData::GetData(obj);
// Check whether the source type is always representable, with exact
// precision, by the target type. If it is, convert the value.
switch (CType::GetTypeCode(typeObj)) {
#define NUMERIC_CASE(name, fromType, ffiType) \
case TYPE_##name: \
if (!IsAlwaysExact<FloatType, fromType>()) \
return false; \
*result = FloatType(*static_cast<fromType*>(data)); \
return true;
CTYPES_FOR_EACH_FLOAT_TYPE(NUMERIC_CASE)
CTYPES_FOR_EACH_INT_TYPE(NUMERIC_CASE)
CTYPES_FOR_EACH_WRAPPED_INT_TYPE(NUMERIC_CASE)
#undef NUMERIC_CASE
case TYPE_void_t:
case TYPE_bool:
case TYPE_char:
case TYPE_signed_char:
case TYPE_unsigned_char:
case TYPE_char16_t:
case TYPE_pointer:
case TYPE_function:
case TYPE_array:
case TYPE_struct:
// Not a compatible number type.
return false;
}
}
}
// Don't silently convert true to 1.0 or false to 0.0, even though C/C++
// does it. It's likely to be a mistake.
return false;
}
template <class IntegerType, class CharT>
static bool
StringToInteger(JSContext* cx, CharT* cp, size_t length, IntegerType* result,
bool* overflow)
{
JS_STATIC_ASSERT(numeric_limits<IntegerType>::is_exact);
const CharT* end = cp + length;
if (cp == end)
return false;
IntegerType sign = 1;
if (cp[0] == '-') {
if (!numeric_limits<IntegerType>::is_signed)
return false;
sign = -1;
++cp;
}
// Assume base-10, unless the string begins with '0x' or '0X'.
IntegerType base = 10;
if (end - cp > 2 && cp[0] == '0' && (cp[1] == 'x' || cp[1] == 'X')) {
cp += 2;
base = 16;
}
// Scan the string left to right and build the number,
// checking for valid characters 0 - 9, a - f, A - F and overflow.
IntegerType i = 0;
while (cp != end) {
char16_t c = *cp++;
if (c >= '0' && c <= '9')
c -= '0';
else if (base == 16 && c >= 'a' && c <= 'f')
c = c - 'a' + 10;
else if (base == 16 && c >= 'A' && c <= 'F')
c = c - 'A' + 10;
else
return false;
IntegerType ii = i;
i = ii * base + sign * c;
if (i / base != ii) {
*overflow = true;
return false;
}
}
*result = i;
return true;
}
template<class IntegerType>
static bool
StringToInteger(JSContext* cx, JSString* string, IntegerType* result,
bool* overflow)
{
JSLinearString* linear = string->ensureLinear(cx);
if (!linear)
return false;
AutoCheckCannotGC nogc;
size_t length = linear->length();
return string->hasLatin1Chars()
? StringToInteger<IntegerType>(cx, linear->latin1Chars(nogc), length,
result, overflow)
: StringToInteger<IntegerType>(cx, linear->twoByteChars(nogc), length,
result, overflow);
}
// Implicitly convert val to IntegerType, allowing int, double,
// Int64, UInt64, and optionally a decimal or hexadecimal string argument.
// (This is common code shared by jsvalToSize and the Int64/UInt64 constructors.)
template<class IntegerType>
static bool
jsvalToBigInteger(JSContext* cx,
HandleValue val,
bool allowString,
IntegerType* result,
bool* overflow)
{
JS_STATIC_ASSERT(numeric_limits<IntegerType>::is_exact);
if (val.isInt32()) {
// Make sure the integer fits in the alotted precision, and has the right
// sign.
int32_t i = val.toInt32();
return ConvertExact(i, result);
}
if (val.isDouble()) {
// Don't silently lose bits here -- check that val really is an
// integer value, and has the right sign.
double d = val.toDouble();
return ConvertExact(d, result);
}
if (allowString && val.isString()) {
// Allow conversion from base-10 or base-16 strings, provided the result
// fits in IntegerType. (This allows an Int64 or UInt64 object to be passed
// to the JS array element operator, which will automatically call
// toString() on the object for us.)
return StringToInteger(cx, val.toString(), result, overflow);
}
if (val.isObject()) {
// Allow conversion from an Int64 or UInt64 object directly.
JSObject* obj = &val.toObject();
if (UInt64::IsUInt64(obj)) {
// Make sure the integer fits in IntegerType.
uint64_t i = Int64Base::GetInt(obj);
return ConvertExact(i, result);
}
if (Int64::IsInt64(obj)) {
// Make sure the integer fits in IntegerType.
int64_t i = Int64Base::GetInt(obj);
return ConvertExact(i, result);
}
if (CDataFinalizer::IsCDataFinalizer(obj)) {
RootedValue innerData(cx);
if (!CDataFinalizer::GetValue(cx, obj, &innerData)) {
return false; // Nothing to convert
}
return jsvalToBigInteger(cx, innerData, allowString, result, overflow);
}
}
return false;
}
// Implicitly convert val to a size value, where the size value is represented
// by size_t but must also fit in a double.
static bool
jsvalToSize(JSContext* cx, HandleValue val, bool allowString, size_t* result)
{
bool dummy;
if (!jsvalToBigInteger(cx, val, allowString, result, &dummy))
return false;
// Also check that the result fits in a double.
return Convert<size_t>(double(*result)) == *result;
}
// Implicitly convert val to IntegerType, allowing int, double,
// Int64, UInt64, and optionally a decimal or hexadecimal string argument.
// (This is common code shared by jsvalToSize and the Int64/UInt64 constructors.)
template<class IntegerType>
static bool
jsidToBigInteger(JSContext* cx,
jsid val,
bool allowString,
IntegerType* result)
{
JS_STATIC_ASSERT(numeric_limits<IntegerType>::is_exact);
if (JSID_IS_INT(val)) {
// Make sure the integer fits in the alotted precision, and has the right
// sign.
int32_t i = JSID_TO_INT(val);
return ConvertExact(i, result);
}
if (allowString && JSID_IS_STRING(val)) {
// Allow conversion from base-10 or base-16 strings, provided the result
// fits in IntegerType. (This allows an Int64 or UInt64 object to be passed
// to the JS array element operator, which will automatically call
// toString() on the object for us.)
bool dummy;
return StringToInteger(cx, JSID_TO_STRING(val), result, &dummy);
}
return false;
}
// Implicitly convert val to a size value, where the size value is represented
// by size_t but must also fit in a double.
static bool
jsidToSize(JSContext* cx, jsid val, bool allowString, size_t* result)
{
if (!jsidToBigInteger(cx, val, allowString, result))
return false;
// Also check that the result fits in a double.
return Convert<size_t>(double(*result)) == *result;
}
// Implicitly convert a size value to a Value, ensuring that the size_t value
// fits in a double.
static bool
SizeTojsval(JSContext* cx, size_t size, MutableHandleValue result)
{
if (Convert<size_t>(double(size)) != size) {
return false;
}
result.setNumber(double(size));
return true;
}
// Forcefully convert val to IntegerType when explicitly requested.
template<class IntegerType>
static bool
jsvalToIntegerExplicit(HandleValue val, IntegerType* result)
{
JS_STATIC_ASSERT(numeric_limits<IntegerType>::is_exact);
if (val.isDouble()) {
// Convert -Inf, Inf, and NaN to 0; otherwise, convert by C-style cast.
double d = val.toDouble();
*result = mozilla::IsFinite(d) ? IntegerType(d) : 0;
return true;
}
if (val.isObject()) {
// Convert Int64 and UInt64 values by C-style cast.
JSObject* obj = &val.toObject();
if (Int64::IsInt64(obj)) {
int64_t i = Int64Base::GetInt(obj);
*result = IntegerType(i);
return true;
}
if (UInt64::IsUInt64(obj)) {
uint64_t i = Int64Base::GetInt(obj);
*result = IntegerType(i);
return true;
}
}
return false;
}
// Forcefully convert val to a pointer value when explicitly requested.
static bool
jsvalToPtrExplicit(JSContext* cx, HandleValue val, uintptr_t* result)
{
if (val.isInt32()) {
// int32_t always fits in intptr_t. If the integer is negative, cast through
// an intptr_t intermediate to sign-extend.
int32_t i = val.toInt32();
*result = i < 0 ? uintptr_t(intptr_t(i)) : uintptr_t(i);
return true;
}
if (val.isDouble()) {
double d = val.toDouble();
if (d < 0) {
// Cast through an intptr_t intermediate to sign-extend.
intptr_t i = Convert<intptr_t>(d);
if (double(i) != d)
return false;
*result = uintptr_t(i);
return true;
}
// Don't silently lose bits here -- check that val really is an
// integer value, and has the right sign.
*result = Convert<uintptr_t>(d);
return double(*result) == d;
}
if (val.isObject()) {
JSObject* obj = &val.toObject();
if (Int64::IsInt64(obj)) {
int64_t i = Int64Base::GetInt(obj);
intptr_t p = intptr_t(i);
// Make sure the integer fits in the alotted precision.
if (int64_t(p) != i)
return false;
*result = uintptr_t(p);
return true;
}
if (UInt64::IsUInt64(obj)) {
uint64_t i = Int64Base::GetInt(obj);
// Make sure the integer fits in the alotted precision.
*result = uintptr_t(i);
return uint64_t(*result) == i;
}
}
return false;
}
template<class IntegerType, class CharType, size_t N, class AP>
void
IntegerToString(IntegerType i, int radix, mozilla::Vector<CharType, N, AP>& result)
{
JS_STATIC_ASSERT(numeric_limits<IntegerType>::is_exact);
// The buffer must be big enough for all the bits of IntegerType to fit,
// in base-2, including '-'.
CharType buffer[sizeof(IntegerType) * 8 + 1];
CharType* end = buffer + sizeof(buffer) / sizeof(CharType);
CharType* cp = end;
// Build the string in reverse. We use multiplication and subtraction
// instead of modulus because that's much faster.
const bool isNegative = IsNegative(i);
size_t sign = isNegative ? -1 : 1;
do {
IntegerType ii = i / IntegerType(radix);
size_t index = sign * size_t(i - ii * IntegerType(radix));
*--cp = "0123456789abcdefghijklmnopqrstuvwxyz"[index];
i = ii;
} while (i != 0);
if (isNegative)
*--cp = '-';
MOZ_ASSERT(cp >= buffer);
if (!result.append(cp, end))
return;
}
template<class CharType>
static size_t
strnlen(const CharType* begin, size_t max)
{
for (const CharType* s = begin; s != begin + max; ++s)
if (*s == 0)
return s - begin;
return max;
}
// Convert C binary value 'data' of CType 'typeObj' to a JS primitive, where
// possible; otherwise, construct and return a CData object. The following
// semantics apply when constructing a CData object for return:
// * If 'wantPrimitive' is true, the caller indicates that 'result' must be
// a JS primitive, and ConvertToJS will fail if 'result' would be a CData
// object. Otherwise:
// * If a CData object 'parentObj' is supplied, the new CData object is
// dependent on the given parent and its buffer refers to a slice of the
// parent's buffer.
// * If 'parentObj' is null, the new CData object may or may not own its
// resulting buffer depending on the 'ownResult' argument.
static bool
ConvertToJS(JSContext* cx,
HandleObject typeObj,
HandleObject parentObj,
void* data,
bool wantPrimitive,
bool ownResult,
MutableHandleValue result)
{
MOZ_ASSERT(!parentObj || CData::IsCData(parentObj));
MOZ_ASSERT(!parentObj || !ownResult);
MOZ_ASSERT(!wantPrimitive || !ownResult);
TypeCode typeCode = CType::GetTypeCode(typeObj);
switch (typeCode) {
case TYPE_void_t:
result.setUndefined();
break;
case TYPE_bool:
result.setBoolean(*static_cast<bool*>(data));
break;
#define INT_CASE(name, type, ffiType) \
case TYPE_##name: { \
type value = *static_cast<type*>(data); \
if (sizeof(type) < 4) \
result.setInt32(int32_t(value)); \
else \
result.setDouble(double(value)); \
break; \
}
CTYPES_FOR_EACH_INT_TYPE(INT_CASE)
#undef INT_CASE
#define WRAPPED_INT_CASE(name, type, ffiType) \
case TYPE_##name: { \
/* Return an Int64 or UInt64 object - do not convert to a JS number. */ \
uint64_t value; \
RootedObject proto(cx); \
if (!numeric_limits<type>::is_signed) { \
value = *static_cast<type*>(data); \
/* Get ctypes.UInt64.prototype from ctypes.CType.prototype. */ \
proto = CType::GetProtoFromType(cx, typeObj, SLOT_UINT64PROTO); \
if (!proto) \
return false; \
} else { \
value = int64_t(*static_cast<type*>(data)); \
/* Get ctypes.Int64.prototype from ctypes.CType.prototype. */ \
proto = CType::GetProtoFromType(cx, typeObj, SLOT_INT64PROTO); \
if (!proto) \
return false; \
} \
\
JSObject* obj = Int64Base::Construct(cx, proto, value, \
!numeric_limits<type>::is_signed); \
if (!obj) \
return false; \
result.setObject(*obj); \
break; \
}
CTYPES_FOR_EACH_WRAPPED_INT_TYPE(WRAPPED_INT_CASE)
#undef WRAPPED_INT_CASE
#define FLOAT_CASE(name, type, ffiType) \
case TYPE_##name: { \
type value = *static_cast<type*>(data); \
result.setDouble(double(value)); \
break; \
}
CTYPES_FOR_EACH_FLOAT_TYPE(FLOAT_CASE)
#undef FLOAT_CASE
#define CHAR_CASE(name, type, ffiType) \
case TYPE_##name: \
/* Convert to an integer. We have no idea what character encoding to */ \
/* use, if any. */ \
result.setInt32(*static_cast<type*>(data)); \
break;
CTYPES_FOR_EACH_CHAR_TYPE(CHAR_CASE)
#undef CHAR_CASE
case TYPE_char16_t: {
// Convert the char16_t to a 1-character string.
JSString* str = JS_NewUCStringCopyN(cx, static_cast<char16_t*>(data), 1);
if (!str)
return false;
result.setString(str);
break;
}
case TYPE_pointer:
case TYPE_array:
case TYPE_struct: {
// We're about to create a new CData object to return. If the caller doesn't
// want this, return early.
if (wantPrimitive) {
return NonPrimitiveError(cx, typeObj);
}
JSObject* obj = CData::Create(cx, typeObj, parentObj, data, ownResult);
if (!obj)
return false;
result.setObject(*obj);
break;
}
case TYPE_function:
MOZ_CRASH("cannot return a FunctionType");
}
return true;
}
// Determine if the contents of a typed array can be converted without
// ambiguity to a C type. Elements of a Int8Array are converted to
// ctypes.int8_t, UInt8Array to ctypes.uint8_t, etc.
bool CanConvertTypedArrayItemTo(JSObject* baseType, JSObject* valObj, JSContext* cx) {
TypeCode baseTypeCode = CType::GetTypeCode(baseType);
if (baseTypeCode == TYPE_void_t || baseTypeCode == TYPE_char) {
return true;
}
TypeCode elementTypeCode;
switch (JS_GetArrayBufferViewType(valObj)) {
case Scalar::Int8:
elementTypeCode = TYPE_int8_t;
break;
case Scalar::Uint8:
case Scalar::Uint8Clamped:
elementTypeCode = TYPE_uint8_t;
break;
case Scalar::Int16:
elementTypeCode = TYPE_int16_t;
break;
case Scalar::Uint16:
elementTypeCode = TYPE_uint16_t;
break;
case Scalar::Int32:
elementTypeCode = TYPE_int32_t;
break;
case Scalar::Uint32:
elementTypeCode = TYPE_uint32_t;
break;
case Scalar::Float32:
elementTypeCode = TYPE_float32_t;
break;
case Scalar::Float64:
elementTypeCode = TYPE_float64_t;
break;
default:
return false;
}
return elementTypeCode == baseTypeCode;
}
// Implicitly convert Value 'val' to a C binary representation of CType
// 'targetType', storing the result in 'buffer'. Adequate space must be
// provided in 'buffer' by the caller. This function generally does minimal
// coercion between types. There are two cases in which this function is used:
// 1) The target buffer is internal to a CData object; we simply write data
// into it.
// 2) We are converting an argument for an ffi call, in which case 'convType'
// will be 'ConversionType::Argument'. This allows us to handle a special
// case: if necessary, we can autoconvert a JS string primitive to a
// pointer-to-character type. In this case, ownership of the allocated string
// is handed off to the caller; 'freePointer' will be set to indicate this.
static bool
ImplicitConvert(JSContext* cx,
HandleValue val,
JSObject* targetType_,
void* buffer,
ConversionType convType,
bool* freePointer,
HandleObject funObj = nullptr, unsigned argIndex = 0,
HandleObject arrObj = nullptr, unsigned arrIndex = 0)
{
RootedObject targetType(cx, targetType_);
MOZ_ASSERT(CType::IsSizeDefined(targetType));
// First, check if val is either a CData object or a CDataFinalizer
// of type targetType.
JSObject* sourceData = nullptr;
JSObject* sourceType = nullptr;
RootedObject valObj(cx, nullptr);
if (val.isObject()) {
valObj = &val.toObject();
if (CData::IsCData(valObj)) {
sourceData = valObj;
sourceType = CData::GetCType(sourceData);
// If the types are equal, copy the buffer contained within the CData.
// (Note that the buffers may overlap partially or completely.)
if (CType::TypesEqual(sourceType, targetType)) {
size_t size = CType::GetSize(sourceType);
memmove(buffer, CData::GetData(sourceData), size);
return true;
}
} else if (CDataFinalizer::IsCDataFinalizer(valObj)) {
sourceData = valObj;
sourceType = CDataFinalizer::GetCType(cx, sourceData);
CDataFinalizer::Private* p = (CDataFinalizer::Private*)
JS_GetPrivate(sourceData);
if (!p) {
// We have called |dispose| or |forget| already.
return EmptyFinalizerError(cx, convType, funObj, argIndex);
}
// If the types are equal, copy the buffer contained within the CData.
if (CType::TypesEqual(sourceType, targetType)) {
memmove(buffer, p->cargs, p->cargs_size);
return true;
}
}
}
TypeCode targetCode = CType::GetTypeCode(targetType);
switch (targetCode) {
case TYPE_bool: {
// Do not implicitly lose bits, but allow the values 0, 1, and -0.
// Programs can convert explicitly, if needed, using `Boolean(v)` or `!!v`.
bool result;
if (!jsvalToBool(cx, val, &result))
return ConvError(cx, "boolean", val, convType, funObj, argIndex,
arrObj, arrIndex);
*static_cast<bool*>(buffer) = result;
break;
}
#define CHAR16_CASE(name, type, ffiType) \
case TYPE_##name: { \
/* Convert from a 1-character string, regardless of encoding, */ \
/* or from an integer, provided the result fits in 'type'. */ \
type result; \
if (val.isString()) { \
JSString* str = val.toString(); \
if (str->length() != 1) \
return ConvError(cx, #name, val, convType, funObj, argIndex, \
arrObj, arrIndex); \
JSLinearString* linear = str->ensureLinear(cx); \
if (!linear) \
return false; \
result = linear->latin1OrTwoByteChar(0); \
} else if (!jsvalToInteger(cx, val, &result)) { \
return ConvError(cx, #name, val, convType, funObj, argIndex, \
arrObj, arrIndex); \
} \
*static_cast<type*>(buffer) = result; \
break; \
}
CTYPES_FOR_EACH_CHAR16_TYPE(CHAR16_CASE)
#undef CHAR16_CASE
#define INTEGRAL_CASE(name, type, ffiType) \
case TYPE_##name: { \
/* Do not implicitly lose bits. */ \
type result; \
if (!jsvalToInteger(cx, val, &result)) \
return ConvError(cx, #name, val, convType, funObj, argIndex, \
arrObj, arrIndex); \
*static_cast<type*>(buffer) = result; \
break; \
}
CTYPES_FOR_EACH_INT_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_WRAPPED_INT_TYPE(INTEGRAL_CASE)
// It's hard to believe ctypes.char16_t("f") should work yet ctypes.char("f")
// should not. Ditto for ctypes.{un,}signed_char. But this is how ctypes
// has always worked, so preserve these semantics, and don't switch to an
// algorithm similar to that in DEFINE_CHAR16_TYPE above, just yet.
CTYPES_FOR_EACH_CHAR_TYPE(INTEGRAL_CASE)
#undef INTEGRAL_CASE
#define FLOAT_CASE(name, type, ffiType) \
case TYPE_##name: { \
type result; \
if (!jsvalToFloat(cx, val, &result)) \
return ConvError(cx, #name, val, convType, funObj, argIndex, \
arrObj, arrIndex); \
*static_cast<type*>(buffer) = result; \
break; \
}
CTYPES_FOR_EACH_FLOAT_TYPE(FLOAT_CASE)
#undef FLOAT_CASE
case TYPE_pointer: {
if (val.isNull()) {
// Convert to a null pointer.
*static_cast<void**>(buffer) = nullptr;
break;
}
JS::Rooted<JSObject*> baseType(cx, PointerType::GetBaseType(targetType));
if (sourceData) {
// First, determine if the targetType is ctypes.void_t.ptr.
TypeCode sourceCode = CType::GetTypeCode(sourceType);
void* sourceBuffer = CData::GetData(sourceData);
bool voidptrTarget = CType::GetTypeCode(baseType) == TYPE_void_t;
if (sourceCode == TYPE_pointer && voidptrTarget) {
// Autoconvert if targetType is ctypes.voidptr_t.
*static_cast<void**>(buffer) = *static_cast<void**>(sourceBuffer);
break;
}
if (sourceCode == TYPE_array) {
// Autoconvert an array to a ctypes.void_t.ptr or to
// sourceType.elementType.ptr, just like C.
JSObject* elementType = ArrayType::GetBaseType(sourceType);
if (voidptrTarget || CType::TypesEqual(baseType, elementType)) {
*static_cast<void**>(buffer) = sourceBuffer;
break;
}
}
} else if (convType == ConversionType::Argument && val.isString()) {
// Convert the string for the ffi call. This requires allocating space
// which the caller assumes ownership of.
// TODO: Extend this so we can safely convert strings at other times also.
JSString* sourceString = val.toString();
size_t sourceLength = sourceString->length();
JSLinearString* sourceLinear = sourceString->ensureLinear(cx);
if (!sourceLinear)
return false;
switch (CType::GetTypeCode(baseType)) {
case TYPE_char:
case TYPE_signed_char:
case TYPE_unsigned_char: {
// Convert from UTF-16 to UTF-8.
size_t nbytes = GetDeflatedUTF8StringLength(cx, sourceLinear);
if (nbytes == (size_t) -1)
return false;
char** charBuffer = static_cast<char**>(buffer);
*charBuffer = cx->pod_malloc<char>(nbytes + 1);
if (!*charBuffer) {
JS_ReportAllocationOverflow(cx);
return false;
}
ASSERT_OK(DeflateStringToUTF8Buffer(cx, sourceLinear, *charBuffer, &nbytes));
(*charBuffer)[nbytes] = 0;
*freePointer = true;
break;
}
case TYPE_char16_t: {
// Copy the char16_t string data. (We could provide direct access to the
// JSString's buffer, but this approach is safer if the caller happens
// to modify the string.)
char16_t** char16Buffer = static_cast<char16_t**>(buffer);
*char16Buffer = cx->pod_malloc<char16_t>(sourceLength + 1);
if (!*char16Buffer) {
JS_ReportAllocationOverflow(cx);
return false;
}
*freePointer = true;
if (sourceLinear->hasLatin1Chars()) {
AutoCheckCannotGC nogc;
CopyAndInflateChars(*char16Buffer, sourceLinear->latin1Chars(nogc), sourceLength);
} else {
AutoCheckCannotGC nogc;
mozilla::PodCopy(*char16Buffer, sourceLinear->twoByteChars(nogc), sourceLength);
}
(*char16Buffer)[sourceLength] = 0;
break;
}
default:
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
break;
} else if (val.isObject() && JS_IsArrayBufferObject(valObj)) {
// Convert ArrayBuffer to pointer without any copy. This is only valid
// when converting an argument to a function call, as it is possible for
// the pointer to be invalidated by anything that runs JS code. (It is
// invalid to invoke JS code from a ctypes function call.)
if (convType != ConversionType::Argument) {
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
void* ptr;
{
JS::AutoCheckCannotGC nogc;
bool isShared;
ptr = JS_GetArrayBufferData(valObj, &isShared, nogc);
MOZ_ASSERT(!isShared); // Because ArrayBuffer
}
if (!ptr) {
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
*static_cast<void**>(buffer) = ptr;
break;
} else if (val.isObject() && JS_IsSharedArrayBufferObject(valObj)) {
// CTypes has not yet opted in to allowing shared memory pointers
// to escape. Exporting a pointer to the shared buffer without
// indicating sharedness would expose client code to races.
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
} else if (val.isObject() && JS_IsArrayBufferViewObject(valObj)) {
// Same as ArrayBuffer, above, though note that this will take the
// offset of the view into account.
if(!CanConvertTypedArrayItemTo(baseType, valObj, cx)) {
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
if (convType != ConversionType::Argument) {
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
void* ptr;
{
JS::AutoCheckCannotGC nogc;
bool isShared;
ptr = JS_GetArrayBufferViewData(valObj, &isShared, nogc);
if (isShared) {
// Opt out of shared memory, for now. Exporting a
// pointer to the shared buffer without indicating
// sharedness would expose client code to races.
ptr = nullptr;
}
}
if (!ptr) {
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
*static_cast<void**>(buffer) = ptr;
break;
}
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
case TYPE_array: {
MOZ_ASSERT(!funObj);
RootedObject baseType(cx, ArrayType::GetBaseType(targetType));
size_t targetLength = ArrayType::GetLength(targetType);
if (val.isString()) {
JSString* sourceString = val.toString();
size_t sourceLength = sourceString->length();
JSLinearString* sourceLinear = sourceString->ensureLinear(cx);
if (!sourceLinear)
return false;
switch (CType::GetTypeCode(baseType)) {
case TYPE_char:
case TYPE_signed_char:
case TYPE_unsigned_char: {
// Convert from UTF-16 or Latin1 to UTF-8.
size_t nbytes =
GetDeflatedUTF8StringLength(cx, sourceLinear);
if (nbytes == (size_t) -1)
return false;
if (targetLength < nbytes) {
MOZ_ASSERT(!funObj);
return ArrayLengthOverflow(cx, targetLength, targetType, nbytes, val,
convType);
}
char* charBuffer = static_cast<char*>(buffer);
ASSERT_OK(DeflateStringToUTF8Buffer(cx, sourceLinear, charBuffer,
&nbytes));
if (targetLength > nbytes)
charBuffer[nbytes] = 0;
break;
}
case TYPE_char16_t: {
// Copy the string data, char16_t for char16_t, including the terminator
// if there's space.
if (targetLength < sourceLength) {
MOZ_ASSERT(!funObj);
return ArrayLengthOverflow(cx, targetLength, targetType,
sourceLength, val, convType);
}
char16_t* dest = static_cast<char16_t*>(buffer);
if (sourceLinear->hasLatin1Chars()) {
AutoCheckCannotGC nogc;
CopyAndInflateChars(dest, sourceLinear->latin1Chars(nogc), sourceLength);
} else {
AutoCheckCannotGC nogc;
mozilla::PodCopy(dest, sourceLinear->twoByteChars(nogc), sourceLength);
}
if (targetLength > sourceLength)
dest[sourceLength] = 0;
break;
}
default:
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
} else {
ESClass cls;
if (!GetClassOfValue(cx, val, &cls))
return false;
if (cls == ESClass::Array) {
// Convert each element of the array by calling ImplicitConvert.
uint32_t sourceLength;
if (!JS_GetArrayLength(cx, valObj, &sourceLength) ||
targetLength != size_t(sourceLength)) {
MOZ_ASSERT(!funObj);
return ArrayLengthMismatch(cx, targetLength, targetType,
size_t(sourceLength), val, convType);
}
// Convert into an intermediate, in case of failure.
size_t elementSize = CType::GetSize(baseType);
size_t arraySize = elementSize * targetLength;
auto intermediate = cx->make_pod_array<char>(arraySize);
if (!intermediate) {
JS_ReportAllocationOverflow(cx);
return false;
}
RootedValue item(cx);
for (uint32_t i = 0; i < sourceLength; ++i) {
if (!JS_GetElement(cx, valObj, i, &item))
return false;
char* data = intermediate.get() + elementSize * i;
if (!ImplicitConvert(cx, item, baseType, data, convType, nullptr,
funObj, argIndex, targetType, i))
return false;
}
memcpy(buffer, intermediate.get(), arraySize);
} else if (cls == ESClass::ArrayBuffer || cls == ESClass::SharedArrayBuffer) {
// Check that array is consistent with type, then
// copy the array.
const bool bufferShared = cls == ESClass::SharedArrayBuffer;
uint32_t sourceLength = bufferShared ? JS_GetSharedArrayBufferByteLength(valObj)
: JS_GetArrayBufferByteLength(valObj);
size_t elementSize = CType::GetSize(baseType);
size_t arraySize = elementSize * targetLength;
if (arraySize != size_t(sourceLength)) {
MOZ_ASSERT(!funObj);
return ArrayLengthMismatch(cx, arraySize, targetType,
size_t(sourceLength), val, convType);
}
SharedMem<void*> target = SharedMem<void*>::unshared(buffer);
JS::AutoCheckCannotGC nogc;
bool isShared;
SharedMem<void*> src =
(bufferShared ?
SharedMem<void*>::shared(JS_GetSharedArrayBufferData(valObj, &isShared, nogc)) :
SharedMem<void*>::unshared(JS_GetArrayBufferData(valObj, &isShared, nogc)));
MOZ_ASSERT(isShared == bufferShared);
jit::AtomicOperations::memcpySafeWhenRacy(target, src, sourceLength);
break;
} else if (JS_IsTypedArrayObject(valObj)) {
// Check that array is consistent with type, then
// copy the array. It is OK to copy from shared to unshared
// or vice versa.
if (!CanConvertTypedArrayItemTo(baseType, valObj, cx)) {
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
uint32_t sourceLength = JS_GetTypedArrayByteLength(valObj);
size_t elementSize = CType::GetSize(baseType);
size_t arraySize = elementSize * targetLength;
if (arraySize != size_t(sourceLength)) {
MOZ_ASSERT(!funObj);
return ArrayLengthMismatch(cx, arraySize, targetType,
size_t(sourceLength), val, convType);
}
SharedMem<void*> target = SharedMem<void*>::unshared(buffer);
JS::AutoCheckCannotGC nogc;
bool isShared;
SharedMem<void*> src =
SharedMem<void*>::shared(JS_GetArrayBufferViewData(valObj, &isShared, nogc));
jit::AtomicOperations::memcpySafeWhenRacy(target, src, sourceLength);
break;
} else {
// Don't implicitly convert to string. Users can implicitly convert
// with `String(x)` or `""+x`.
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
}
break;
}
case TYPE_struct: {
if (val.isObject() && !sourceData) {
// Enumerate the properties of the object; if they match the struct
// specification, convert the fields.
Rooted<IdVector> props(cx, IdVector(cx));
if (!JS_Enumerate(cx, valObj, &props))
return false;
// Convert into an intermediate, in case of failure.
size_t structSize = CType::GetSize(targetType);
auto intermediate = cx->make_pod_array<char>(structSize);
if (!intermediate) {
JS_ReportAllocationOverflow(cx);
return false;
}
const FieldInfoHash* fields = StructType::GetFieldInfo(targetType);
if (props.length() != fields->count()) {
return FieldCountMismatch(cx, fields->count(), targetType,
props.length(), val, convType,
funObj, argIndex);
}
RootedId id(cx);
for (size_t i = 0; i < props.length(); ++i) {
id = props[i];
if (!JSID_IS_STRING(id)) {
return PropNameNonStringError(cx, id, val, convType,
funObj, argIndex);
}
JSFlatString* name = JSID_TO_FLAT_STRING(id);
const FieldInfo* field = StructType::LookupField(cx, targetType, name);
if (!field)
return false;
RootedValue prop(cx);
if (!JS_GetPropertyById(cx, valObj, id, &prop))
return false;
// Convert the field via ImplicitConvert().
char* fieldData = intermediate.get() + field->mOffset;
if (!ImplicitConvert(cx, prop, field->mType, fieldData, convType,
nullptr, funObj, argIndex, targetType, i))
return false;
}
memcpy(buffer, intermediate.get(), structSize);
break;
}
return ConvError(cx, targetType, val, convType, funObj, argIndex,
arrObj, arrIndex);
}
case TYPE_void_t:
case TYPE_function:
MOZ_CRASH("invalid type");
}
return true;
}
// Convert Value 'val' to a C binary representation of CType 'targetType',
// storing the result in 'buffer'. This function is more forceful than
// ImplicitConvert.
static bool
ExplicitConvert(JSContext* cx, HandleValue val, HandleObject targetType,
void* buffer, ConversionType convType)
{
// If ImplicitConvert succeeds, use that result.
if (ImplicitConvert(cx, val, targetType, buffer, convType, nullptr))
return true;
// If ImplicitConvert failed, and there is no pending exception, then assume
// hard failure (out of memory, or some other similarly serious condition).
// We store any pending exception in case we need to re-throw it.
RootedValue ex(cx);
if (!JS_GetPendingException(cx, &ex))
return false;
// Otherwise, assume soft failure. Clear the pending exception so that we
// can throw a different one as required.
JS_ClearPendingException(cx);
TypeCode type = CType::GetTypeCode(targetType);
switch (type) {
case TYPE_bool: {
*static_cast<bool*>(buffer) = ToBoolean(val);
break;
}
#define INTEGRAL_CASE(name, type, ffiType) \
case TYPE_##name: { \
/* Convert numeric values with a C-style cast, and */ \
/* allow conversion from a base-10 or base-16 string. */ \
type result; \
bool overflow = false; \
if (!jsvalToIntegerExplicit(val, &result) && \
(!val.isString() || \
!StringToInteger(cx, val.toString(), &result, &overflow))) { \
if (overflow) { \
return TypeOverflow(cx, #name, val); \
} \
return ConvError(cx, #name, val, convType); \
} \
*static_cast<type*>(buffer) = result; \
break; \
}
CTYPES_FOR_EACH_INT_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_WRAPPED_INT_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_CHAR_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_CHAR16_TYPE(INTEGRAL_CASE)
#undef INTEGRAL_CASE
case TYPE_pointer: {
// Convert a number, Int64 object, or UInt64 object to a pointer.
uintptr_t result;
if (!jsvalToPtrExplicit(cx, val, &result))
return ConvError(cx, targetType, val, convType);
*static_cast<uintptr_t*>(buffer) = result;
break;
}
case TYPE_float32_t:
case TYPE_float64_t:
case TYPE_float:
case TYPE_double:
case TYPE_array:
case TYPE_struct:
// ImplicitConvert is sufficient. Re-throw the exception it generated.
JS_SetPendingException(cx, ex);
return false;
case TYPE_void_t:
case TYPE_function:
MOZ_CRASH("invalid type");
}
return true;
}
// Given a CType 'typeObj', generate a string describing the C type declaration
// corresponding to 'typeObj'. For instance, the CType constructed from
// 'ctypes.int32_t.ptr.array(4).ptr.ptr' will result in the type string
// 'int32_t*(**)[4]'.
static JSString*
BuildTypeName(JSContext* cx, JSObject* typeObj_)
{
AutoString result;
RootedObject typeObj(cx, typeObj_);
// Walk the hierarchy of types, outermost to innermost, building up the type
// string. This consists of the base type, which goes on the left.
// Derived type modifiers (* and []) build from the inside outward, with
// pointers on the left and arrays on the right. An excellent description
// of the rules for building C type declarations can be found at:
// http://unixwiz.net/techtips/reading-cdecl.html
TypeCode prevGrouping = CType::GetTypeCode(typeObj), currentGrouping;
while (true) {
currentGrouping = CType::GetTypeCode(typeObj);
switch (currentGrouping) {
case TYPE_pointer: {
// Pointer types go on the left.
PrependString(result, "*");
typeObj = PointerType::GetBaseType(typeObj);
prevGrouping = currentGrouping;
continue;
}
case TYPE_array: {
if (prevGrouping == TYPE_pointer) {
// Outer type is pointer, inner type is array. Grouping is required.
PrependString(result, "(");
AppendString(result, ")");
}
// Array types go on the right.
AppendString(result, "[");
size_t length;
if (ArrayType::GetSafeLength(typeObj, &length))
IntegerToString(length, 10, result);
AppendString(result, "]");
typeObj = ArrayType::GetBaseType(typeObj);
prevGrouping = currentGrouping;
continue;
}
case TYPE_function: {
FunctionInfo* fninfo = FunctionType::GetFunctionInfo(typeObj);
// Add in the calling convention, if it's not cdecl.
// There's no trailing or leading space needed here, as none of the
// modifiers can produce a string beginning with an identifier ---
// except for TYPE_function itself, which is fine because functions
// can't return functions.
ABICode abi = GetABICode(fninfo->mABI);
if (abi == ABI_STDCALL)
PrependString(result, "__stdcall");
else if (abi == ABI_THISCALL)
PrependString(result, "__thiscall");
else if (abi == ABI_WINAPI)
PrependString(result, "WINAPI");
// Function application binds more tightly than dereferencing, so
// wrap pointer types in parens. Functions can't return functions
// (only pointers to them), and arrays can't hold functions
// (similarly), so we don't need to address those cases.
if (prevGrouping == TYPE_pointer) {
PrependString(result, "(");
AppendString(result, ")");
}
// Argument list goes on the right.
AppendString(result, "(");
for (size_t i = 0; i < fninfo->mArgTypes.length(); ++i) {
RootedObject argType(cx, fninfo->mArgTypes[i]);
JSString* argName = CType::GetName(cx, argType);
AppendString(result, argName);
if (i != fninfo->mArgTypes.length() - 1 ||
fninfo->mIsVariadic)
AppendString(result, ", ");
}
if (fninfo->mIsVariadic)
AppendString(result, "...");
AppendString(result, ")");
// Set 'typeObj' to the return type, and let the loop process it.
// 'prevGrouping' doesn't matter here, because functions cannot return
// arrays -- thus the parenthetical rules don't get tickled.
typeObj = fninfo->mReturnType;
continue;
}
default:
// Either a basic or struct type. Use the type's name as the base type.
break;
}
break;
}
// If prepending the base type name directly would splice two
// identifiers, insert a space.
if (('a' <= result[0] && result[0] <= 'z') ||
('A' <= result[0] && result[0] <= 'Z') ||
(result[0] == '_'))
PrependString(result, " ");
// Stick the base type and derived type parts together.
JSString* baseName = CType::GetName(cx, typeObj);
PrependString(result, baseName);
return NewUCString(cx, result);
}
// Given a CType 'typeObj', generate a string 'result' such that 'eval(result)'
// would construct the same CType. If 'makeShort' is true, assume that any
// StructType 't' is bound to an in-scope variable of name 't.name', and use
// that variable in place of generating a string to construct the type 't'.
// (This means the type comparison function CType::TypesEqual will return true
// when comparing the input and output of BuildTypeSource, since struct
// equality is determined by strict JSObject pointer equality.)
static void
BuildTypeSource(JSContext* cx,
JSObject* typeObj_,
bool makeShort,
AutoString& result)
{
RootedObject typeObj(cx, typeObj_);
// Walk the types, building up the toSource() string.
switch (CType::GetTypeCode(typeObj)) {
case TYPE_void_t:
#define CASE_FOR_TYPE(name, type, ffiType) case TYPE_##name:
CTYPES_FOR_EACH_TYPE(CASE_FOR_TYPE)
#undef CASE_FOR_TYPE
{
AppendString(result, "ctypes.");
JSString* nameStr = CType::GetName(cx, typeObj);
AppendString(result, nameStr);
break;
}
case TYPE_pointer: {
RootedObject baseType(cx, PointerType::GetBaseType(typeObj));
// Specialcase ctypes.voidptr_t.
if (CType::GetTypeCode(baseType) == TYPE_void_t) {
AppendString(result, "ctypes.voidptr_t");
break;
}
// Recursively build the source string, and append '.ptr'.
BuildTypeSource(cx, baseType, makeShort, result);
AppendString(result, ".ptr");
break;
}
case TYPE_function: {
FunctionInfo* fninfo = FunctionType::GetFunctionInfo(typeObj);
AppendString(result, "ctypes.FunctionType(");
switch (GetABICode(fninfo->mABI)) {
case ABI_DEFAULT:
AppendString(result, "ctypes.default_abi, ");
break;
case ABI_STDCALL:
AppendString(result, "ctypes.stdcall_abi, ");
break;
case ABI_THISCALL:
AppendString(result, "ctypes.thiscall_abi, ");
break;
case ABI_WINAPI:
AppendString(result, "ctypes.winapi_abi, ");
break;
case INVALID_ABI:
MOZ_CRASH("invalid abi");
}
// Recursively build the source string describing the function return and
// argument types.
BuildTypeSource(cx, fninfo->mReturnType, true, result);
if (fninfo->mArgTypes.length() > 0) {
AppendString(result, ", [");
for (size_t i = 0; i < fninfo->mArgTypes.length(); ++i) {
BuildTypeSource(cx, fninfo->mArgTypes[i], true, result);
if (i != fninfo->mArgTypes.length() - 1 ||
fninfo->mIsVariadic)
AppendString(result, ", ");
}
if (fninfo->mIsVariadic)
AppendString(result, "\"...\"");
AppendString(result, "]");
}
AppendString(result, ")");
break;
}
case TYPE_array: {
// Recursively build the source string, and append '.array(n)',
// where n is the array length, or the empty string if the array length
// is undefined.
JSObject* baseType = ArrayType::GetBaseType(typeObj);
BuildTypeSource(cx, baseType, makeShort, result);
AppendString(result, ".array(");
size_t length;
if (ArrayType::GetSafeLength(typeObj, &length))
IntegerToString(length, 10, result);
AppendString(result, ")");
break;
}
case TYPE_struct: {
JSString* name = CType::GetName(cx, typeObj);
if (makeShort) {
// Shorten the type declaration by assuming that StructType 't' is bound
// to an in-scope variable of name 't.name'.
AppendString(result, name);
break;
}
// Write the full struct declaration.
AppendString(result, "ctypes.StructType(\"");
AppendString(result, name);
AppendString(result, "\"");
// If it's an opaque struct, we're done.
if (!CType::IsSizeDefined(typeObj)) {
AppendString(result, ")");
break;
}
AppendString(result, ", [");
const FieldInfoHash* fields = StructType::GetFieldInfo(typeObj);
size_t length = fields->count();
Vector<const FieldInfoHash::Entry*, 64, SystemAllocPolicy> fieldsArray;
if (!fieldsArray.resize(length))
break;
for (FieldInfoHash::Range r = fields->all(); !r.empty(); r.popFront())
fieldsArray[r.front().value().mIndex] = &r.front();
for (size_t i = 0; i < length; ++i) {
const FieldInfoHash::Entry* entry = fieldsArray[i];
AppendString(result, "{ \"");
AppendString(result, entry->key());
AppendString(result, "\": ");
BuildTypeSource(cx, entry->value().mType, true, result);
AppendString(result, " }");
if (i != length - 1)
AppendString(result, ", ");
}
AppendString(result, "])");
break;
}
}
}
// Given a CData object of CType 'typeObj' with binary value 'data', generate a
// string 'result' such that 'eval(result)' would construct a CData object with
// the same CType and containing the same binary value. This assumes that any
// StructType 't' is bound to an in-scope variable of name 't.name'. (This means
// the type comparison function CType::TypesEqual will return true when
// comparing the types, since struct equality is determined by strict JSObject
// pointer equality.) Further, if 'isImplicit' is true, ensure that the
// resulting string can ImplicitConvert successfully if passed to another data
// constructor. (This is important when called recursively, since fields of
// structs and arrays are converted with ImplicitConvert.)
static bool
BuildDataSource(JSContext* cx,
HandleObject typeObj,
void* data,
bool isImplicit,
AutoString& result)
{
TypeCode type = CType::GetTypeCode(typeObj);
switch (type) {
case TYPE_bool:
if (*static_cast<bool*>(data))
AppendString(result, "true");
else
AppendString(result, "false");
break;
#define INTEGRAL_CASE(name, type, ffiType) \
case TYPE_##name: \
/* Serialize as a primitive decimal integer. */ \
IntegerToString(*static_cast<type*>(data), 10, result); \
break;
CTYPES_FOR_EACH_INT_TYPE(INTEGRAL_CASE)
#undef INTEGRAL_CASE
#define WRAPPED_INT_CASE(name, type, ffiType) \
case TYPE_##name: \
/* Serialize as a wrapped decimal integer. */ \
if (!numeric_limits<type>::is_signed) \
AppendString(result, "ctypes.UInt64(\""); \
else \
AppendString(result, "ctypes.Int64(\""); \
\
IntegerToString(*static_cast<type*>(data), 10, result); \
AppendString(result, "\")"); \
break;
CTYPES_FOR_EACH_WRAPPED_INT_TYPE(WRAPPED_INT_CASE)
#undef WRAPPED_INT_CASE
#define FLOAT_CASE(name, type, ffiType) \
case TYPE_##name: { \
/* Serialize as a primitive double. */ \
double fp = *static_cast<type*>(data); \
ToCStringBuf cbuf; \
char* str = NumberToCString(cx, &cbuf, fp); \
if (!str || !result.append(str, strlen(str))) { \
JS_ReportOutOfMemory(cx); \
return false; \
} \
break; \
}
CTYPES_FOR_EACH_FLOAT_TYPE(FLOAT_CASE)
#undef FLOAT_CASE
#define CHAR_CASE(name, type, ffiType) \
case TYPE_##name: \
/* Serialize as an integer. */ \
IntegerToString(*static_cast<type*>(data), 10, result); \
break;
CTYPES_FOR_EACH_CHAR_TYPE(CHAR_CASE)
#undef CHAR_CASE
case TYPE_char16_t: {
// Serialize as a 1-character JS string.
JSString* str = JS_NewUCStringCopyN(cx, static_cast<char16_t*>(data), 1);
if (!str)
return false;
// Escape characters, and quote as necessary.
RootedValue valStr(cx, StringValue(str));
JSString* src = JS_ValueToSource(cx, valStr);
if (!src)
return false;
AppendString(result, src);
break;
}
case TYPE_pointer:
case TYPE_function: {
if (isImplicit) {
// The result must be able to ImplicitConvert successfully.
// Wrap in a type constructor, then serialize for ExplicitConvert.
BuildTypeSource(cx, typeObj, true, result);
AppendString(result, "(");
}
// Serialize the pointer value as a wrapped hexadecimal integer.
uintptr_t ptr = *static_cast<uintptr_t*>(data);
AppendString(result, "ctypes.UInt64(\"0x");
IntegerToString(ptr, 16, result);
AppendString(result, "\")");
if (isImplicit)
AppendString(result, ")");
break;
}
case TYPE_array: {
// Serialize each element of the array recursively. Each element must
// be able to ImplicitConvert successfully.
RootedObject baseType(cx, ArrayType::GetBaseType(typeObj));
AppendString(result, "[");
size_t length = ArrayType::GetLength(typeObj);
size_t elementSize = CType::GetSize(baseType);
for (size_t i = 0; i < length; ++i) {
char* element = static_cast<char*>(data) + elementSize * i;
if (!BuildDataSource(cx, baseType, element, true, result))
return false;
if (i + 1 < length)
AppendString(result, ", ");
}
AppendString(result, "]");
break;
}
case TYPE_struct: {
if (isImplicit) {
// The result must be able to ImplicitConvert successfully.
// Serialize the data as an object with properties, rather than
// a sequence of arguments to the StructType constructor.
AppendString(result, "{");
}
// Serialize each field of the struct recursively. Each field must
// be able to ImplicitConvert successfully.
const FieldInfoHash* fields = StructType::GetFieldInfo(typeObj);
size_t length = fields->count();
Vector<const FieldInfoHash::Entry*, 64, SystemAllocPolicy> fieldsArray;
if (!fieldsArray.resize(length))
return false;
for (FieldInfoHash::Range r = fields->all(); !r.empty(); r.popFront())
fieldsArray[r.front().value().mIndex] = &r.front();
for (size_t i = 0; i < length; ++i) {
const FieldInfoHash::Entry* entry = fieldsArray[i];
if (isImplicit) {
AppendString(result, "\"");
AppendString(result, entry->key());
AppendString(result, "\": ");
}
char* fieldData = static_cast<char*>(data) + entry->value().mOffset;
RootedObject entryType(cx, entry->value().mType);
if (!BuildDataSource(cx, entryType, fieldData, true, result))
return false;
if (i + 1 != length)
AppendString(result, ", ");
}
if (isImplicit)
AppendString(result, "}");
break;
}
case TYPE_void_t:
MOZ_CRASH("invalid type");
}
return true;
}
/*******************************************************************************
** JSAPI callback function implementations
*******************************************************************************/
bool
ConstructAbstract(JSContext* cx,
unsigned argc,
Value* vp)
{
// Calling an abstract base class constructor is disallowed.
return CannotConstructError(cx, "abstract type");
}
/*******************************************************************************
** CType implementation
*******************************************************************************/
bool
CType::ConstructData(JSContext* cx,
unsigned argc,
Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// get the callee object...
RootedObject obj(cx, &args.callee());
if (!CType::IsCType(obj)) {
return IncompatibleCallee(cx, "CType constructor", obj);
}
// How we construct the CData object depends on what type we represent.
// An instance 'd' of a CData object of type 't' has:
// * [[Class]] "CData"
// * __proto__ === t.prototype
switch (GetTypeCode(obj)) {
case TYPE_void_t:
return CannotConstructError(cx, "void_t");
case TYPE_function:
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
CTYPESMSG_FUNCTION_CONSTRUCT);
return false;
case TYPE_pointer:
return PointerType::ConstructData(cx, obj, args);
case TYPE_array:
return ArrayType::ConstructData(cx, obj, args);
case TYPE_struct:
return StructType::ConstructData(cx, obj, args);
default:
return ConstructBasic(cx, obj, args);
}
}
bool
CType::ConstructBasic(JSContext* cx,
HandleObject obj,
const CallArgs& args)
{
if (args.length() > 1) {
return ArgumentLengthError(cx, "CType constructor", "at most one", "");
}
// construct a CData object
RootedObject result(cx, CData::Create(cx, obj, nullptr, nullptr, true));
if (!result)
return false;
if (args.length() == 1) {
if (!ExplicitConvert(cx, args[0], obj, CData::GetData(result),
ConversionType::Construct))
return false;
}
args.rval().setObject(*result);
return true;
}
JSObject*
CType::Create(JSContext* cx,
HandleObject typeProto,
HandleObject dataProto,
TypeCode type,
JSString* name_,
HandleValue size,
HandleValue align,
ffi_type* ffiType)
{
RootedString name(cx, name_);
// Create a CType object with the properties and slots common to all CTypes.
// Each type object 't' has:
// * [[Class]] "CType"
// * __proto__ === 'typeProto'; one of ctypes.{CType,PointerType,ArrayType,
// StructType}.prototype
// * A constructor which creates and returns a CData object, containing
// binary data of the given type.
// * 'prototype' property:
// * [[Class]] "CDataProto"
// * __proto__ === 'dataProto'; an object containing properties and
// functions common to all CData objects of types derived from
// 'typeProto'. (For instance, this could be ctypes.CData.prototype
// for simple types, or something representing structs for StructTypes.)
// * 'constructor' property === 't'
// * Additional properties specified by 'ps', as appropriate for the
// specific type instance 't'.
RootedObject typeObj(cx, JS_NewObjectWithGivenProto(cx, &sCTypeClass, typeProto));
if (!typeObj)
return nullptr;
// Set up the reserved slots.
JS_SetReservedSlot(typeObj, SLOT_TYPECODE, Int32Value(type));
if (ffiType)
JS_SetReservedSlot(typeObj, SLOT_FFITYPE, PrivateValue(ffiType));
if (name)
JS_SetReservedSlot(typeObj, SLOT_NAME, StringValue(name));
JS_SetReservedSlot(typeObj, SLOT_SIZE, size);
JS_SetReservedSlot(typeObj, SLOT_ALIGN, align);
if (dataProto) {
// Set up the 'prototype' and 'prototype.constructor' properties.
RootedObject prototype(cx, JS_NewObjectWithGivenProto(cx, &sCDataProtoClass, dataProto));
if (!prototype)
return nullptr;
if (!JS_DefineProperty(cx, prototype, "constructor", typeObj,
JSPROP_READONLY | JSPROP_PERMANENT))
return nullptr;
// Set the 'prototype' object.
//if (!JS_FreezeObject(cx, prototype)) // XXX fixme - see bug 541212!
// return nullptr;
JS_SetReservedSlot(typeObj, SLOT_PROTO, ObjectValue(*prototype));
}
if (!JS_FreezeObject(cx, typeObj))
return nullptr;
// Assert a sanity check on size and alignment: size % alignment should always
// be zero.
MOZ_ASSERT_IF(IsSizeDefined(typeObj),
GetSize(typeObj) % GetAlignment(typeObj) == 0);
return typeObj;
}
JSObject*
CType::DefineBuiltin(JSContext* cx,
HandleObject ctypesObj,
const char* propName,
JSObject* typeProto_,
JSObject* dataProto_,
const char* name,
TypeCode type,
HandleValue size,
HandleValue align,
ffi_type* ffiType)
{
RootedObject typeProto(cx, typeProto_);
RootedObject dataProto(cx, dataProto_);
RootedString nameStr(cx, JS_NewStringCopyZ(cx, name));
if (!nameStr)
return nullptr;
// Create a new CType object with the common properties and slots.
RootedObject typeObj(cx, Create(cx, typeProto, dataProto, type, nameStr, size, align, ffiType));
if (!typeObj)
return nullptr;
// Define the CType as a 'propName' property on 'ctypesObj'.
if (!JS_DefineProperty(cx, ctypesObj, propName, typeObj,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return nullptr;
return typeObj;
}
void
CType::Finalize(JSFreeOp* fop, JSObject* obj)
{
// Make sure our TypeCode slot is legit. If it's not, bail.
Value slot = JS_GetReservedSlot(obj, SLOT_TYPECODE);
if (slot.isUndefined())
return;
// The contents of our slots depends on what kind of type we are.
switch (TypeCode(slot.toInt32())) {
case TYPE_function: {
// Free the FunctionInfo.
slot = JS_GetReservedSlot(obj, SLOT_FNINFO);
if (!slot.isUndefined())
FreeOp::get(fop)->delete_(static_cast<FunctionInfo*>(slot.toPrivate()));
break;
}
case TYPE_struct: {
// Free the FieldInfoHash table.
slot = JS_GetReservedSlot(obj, SLOT_FIELDINFO);
if (!slot.isUndefined()) {
void* info = slot.toPrivate();
FreeOp::get(fop)->delete_(static_cast<FieldInfoHash*>(info));
}
}
MOZ_FALLTHROUGH;
case TYPE_array: {
// Free the ffi_type info.
slot = JS_GetReservedSlot(obj, SLOT_FFITYPE);
if (!slot.isUndefined()) {
ffi_type* ffiType = static_cast<ffi_type*>(slot.toPrivate());
FreeOp::get(fop)->free_(ffiType->elements);
FreeOp::get(fop)->delete_(ffiType);
}
break;
}
default:
// Nothing to do here.
break;
}
}
void
CType::Trace(JSTracer* trc, JSObject* obj)
{
// Make sure our TypeCode slot is legit. If it's not, bail.
Value slot = obj->as<NativeObject>().getSlot(SLOT_TYPECODE);
if (slot.isUndefined())
return;
// The contents of our slots depends on what kind of type we are.
switch (TypeCode(slot.toInt32())) {
case TYPE_struct: {
slot = obj->as<NativeObject>().getReservedSlot(SLOT_FIELDINFO);
if (slot.isUndefined())
return;
FieldInfoHash* fields = static_cast<FieldInfoHash*>(slot.toPrivate());
fields->trace(trc);
break;
}
case TYPE_function: {
// Check if we have a FunctionInfo.
slot = obj->as<NativeObject>().getReservedSlot(SLOT_FNINFO);
if (slot.isUndefined())
return;
FunctionInfo* fninfo = static_cast<FunctionInfo*>(slot.toPrivate());
MOZ_ASSERT(fninfo);
// Identify our objects to the tracer.
JS::TraceEdge(trc, &fninfo->mABI, "abi");
JS::TraceEdge(trc, &fninfo->mReturnType, "returnType");
for (size_t i = 0; i < fninfo->mArgTypes.length(); ++i)
JS::TraceEdge(trc, &fninfo->mArgTypes[i], "argType");
break;
}
default:
// Nothing to do here.
break;
}
}
bool
CType::IsCType(JSObject* obj)
{
return JS_GetClass(obj) == &sCTypeClass;
}
bool
CType::IsCTypeProto(JSObject* obj)
{
return JS_GetClass(obj) == &sCTypeProtoClass;
}
TypeCode
CType::GetTypeCode(JSObject* typeObj)
{
MOZ_ASSERT(IsCType(typeObj));
Value result = JS_GetReservedSlot(typeObj, SLOT_TYPECODE);
return TypeCode(result.toInt32());
}
bool
CType::TypesEqual(JSObject* t1, JSObject* t2)
{
MOZ_ASSERT(IsCType(t1) && IsCType(t2));
// Fast path: check for object equality.
if (t1 == t2)
return true;
// First, perform shallow comparison.
TypeCode c1 = GetTypeCode(t1);
TypeCode c2 = GetTypeCode(t2);
if (c1 != c2)
return false;
// Determine whether the types require shallow or deep comparison.
switch (c1) {
case TYPE_pointer: {
// Compare base types.
JSObject* b1 = PointerType::GetBaseType(t1);
JSObject* b2 = PointerType::GetBaseType(t2);
return TypesEqual(b1, b2);
}
case TYPE_function: {
FunctionInfo* f1 = FunctionType::GetFunctionInfo(t1);
FunctionInfo* f2 = FunctionType::GetFunctionInfo(t2);
// Compare abi, return type, and argument types.
if (f1->mABI != f2->mABI)
return false;
if (!TypesEqual(f1->mReturnType, f2->mReturnType))
return false;
if (f1->mArgTypes.length() != f2->mArgTypes.length())
return false;
if (f1->mIsVariadic != f2->mIsVariadic)
return false;
for (size_t i = 0; i < f1->mArgTypes.length(); ++i) {
if (!TypesEqual(f1->mArgTypes[i], f2->mArgTypes[i]))
return false;
}
return true;
}
case TYPE_array: {
// Compare length, then base types.
// An undefined length array matches other undefined length arrays.
size_t s1 = 0, s2 = 0;
bool d1 = ArrayType::GetSafeLength(t1, &s1);
bool d2 = ArrayType::GetSafeLength(t2, &s2);
if (d1 != d2 || (d1 && s1 != s2))
return false;
JSObject* b1 = ArrayType::GetBaseType(t1);
JSObject* b2 = ArrayType::GetBaseType(t2);
return TypesEqual(b1, b2);
}
case TYPE_struct:
// Require exact type object equality.
return false;
default:
// Shallow comparison is sufficient.
return true;
}
}
bool
CType::GetSafeSize(JSObject* obj, size_t* result)
{
MOZ_ASSERT(CType::IsCType(obj));
Value size = JS_GetReservedSlot(obj, SLOT_SIZE);
// The "size" property can be an int, a double, or JS::UndefinedValue()
// (for arrays of undefined length), and must always fit in a size_t.
if (size.isInt32()) {
*result = size.toInt32();
return true;
}
if (size.isDouble()) {
*result = Convert<size_t>(size.toDouble());
return true;
}
MOZ_ASSERT(size.isUndefined());
return false;
}
size_t
CType::GetSize(JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
Value size = JS_GetReservedSlot(obj, SLOT_SIZE);
MOZ_ASSERT(!size.isUndefined());
// The "size" property can be an int, a double, or JS::UndefinedValue()
// (for arrays of undefined length), and must always fit in a size_t.
// For callers who know it can never be JS::UndefinedValue(), return a size_t
// directly.
if (size.isInt32())
return size.toInt32();
return Convert<size_t>(size.toDouble());
}
bool
CType::IsSizeDefined(JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
Value size = JS_GetReservedSlot(obj, SLOT_SIZE);
// The "size" property can be an int, a double, or JS::UndefinedValue()
// (for arrays of undefined length), and must always fit in a size_t.
MOZ_ASSERT(size.isInt32() || size.isDouble() || size.isUndefined());
return !size.isUndefined();
}
size_t
CType::GetAlignment(JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
Value slot = JS_GetReservedSlot(obj, SLOT_ALIGN);
return static_cast<size_t>(slot.toInt32());
}
ffi_type*
CType::GetFFIType(JSContext* cx, JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
Value slot = JS_GetReservedSlot(obj, SLOT_FFITYPE);
if (!slot.isUndefined()) {
return static_cast<ffi_type*>(slot.toPrivate());
}
UniquePtrFFIType result;
switch (CType::GetTypeCode(obj)) {
case TYPE_array:
result = ArrayType::BuildFFIType(cx, obj);
break;
case TYPE_struct:
result = StructType::BuildFFIType(cx, obj);
break;
default:
MOZ_CRASH("simple types must have an ffi_type");
}
if (!result)
return nullptr;
JS_SetReservedSlot(obj, SLOT_FFITYPE, PrivateValue(result.get()));
return result.release();
}
JSString*
CType::GetName(JSContext* cx, HandleObject obj)
{
MOZ_ASSERT(CType::IsCType(obj));
Value string = JS_GetReservedSlot(obj, SLOT_NAME);
if (!string.isUndefined())
return string.toString();
// Build the type name lazily.
JSString* name = BuildTypeName(cx, obj);
if (!name)
return nullptr;
JS_SetReservedSlot(obj, SLOT_NAME, StringValue(name));
return name;
}
JSObject*
CType::GetProtoFromCtor(JSObject* obj, CTypeProtoSlot slot)
{
// Get ctypes.{Pointer,Array,Struct}Type.prototype from a reserved slot
// on the type constructor.
Value protoslot = js::GetFunctionNativeReserved(obj, SLOT_FN_CTORPROTO);
JSObject* proto = &protoslot.toObject();
MOZ_ASSERT(proto);
MOZ_ASSERT(CType::IsCTypeProto(proto));
// Get the desired prototype.
Value result = JS_GetReservedSlot(proto, slot);
return &result.toObject();
}
JSObject*
CType::GetProtoFromType(JSContext* cx, JSObject* objArg, CTypeProtoSlot slot)
{
MOZ_ASSERT(IsCType(objArg));
RootedObject obj(cx, objArg);
// Get the prototype of the type object.
RootedObject proto(cx);
if (!JS_GetPrototype(cx, obj, &proto))
return nullptr;
MOZ_ASSERT(proto);
MOZ_ASSERT(CType::IsCTypeProto(proto));
// Get the requested ctypes.{Pointer,Array,Struct,Function}Type.prototype.
Value result = JS_GetReservedSlot(proto, slot);
MOZ_ASSERT(result.isObject());
return &result.toObject();
}
bool
CType::IsCTypeOrProto(HandleValue v)
{
if (!v.isObject())
return false;
JSObject* obj = &v.toObject();
return CType::IsCType(obj) || CType::IsCTypeProto(obj);
}
bool
CType::PrototypeGetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
unsigned slot = CType::IsCTypeProto(obj) ? (unsigned) SLOT_OURDATAPROTO
: (unsigned) SLOT_PROTO;
args.rval().set(JS_GetReservedSlot(obj, slot));
MOZ_ASSERT(args.rval().isObject() || args.rval().isUndefined());
return true;
}
bool
CType::IsCType(HandleValue v)
{
return v.isObject() && CType::IsCType(&v.toObject());
}
bool
CType::NameGetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
JSString* name = CType::GetName(cx, obj);
if (!name)
return false;
args.rval().setString(name);
return true;
}
bool
CType::SizeGetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
args.rval().set(JS_GetReservedSlot(obj, SLOT_SIZE));
MOZ_ASSERT(args.rval().isNumber() || args.rval().isUndefined());
return true;
}
bool
CType::PtrGetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
JSObject* pointerType = PointerType::CreateInternal(cx, obj);
if (!pointerType)
return false;
args.rval().setObject(*pointerType);
return true;
}
bool
CType::CreateArray(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject baseType(cx, JS_THIS_OBJECT(cx, vp));
if (!baseType)
return false;
if (!CType::IsCType(baseType)) {
return IncompatibleThisProto(cx, "CType.prototype.array", args.thisv());
}
// Construct and return a new ArrayType object.
if (args.length() > 1) {
return ArgumentLengthError(cx, "CType.prototype.array", "at most one", "");
}
// Convert the length argument to a size_t.
size_t length = 0;
if (args.length() == 1 && !jsvalToSize(cx, args[0], false, &length)) {
return ArgumentTypeMismatch(cx, "", "CType.prototype.array",
"a nonnegative integer");
}
JSObject* result = ArrayType::CreateInternal(cx, baseType, length, args.length() == 1);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
bool
CType::ToString(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
if (!obj)
return false;
if (!CType::IsCType(obj) && !CType::IsCTypeProto(obj)) {
return IncompatibleThisProto(cx, "CType.prototype.toString",
InformalValueTypeName(args.thisv()));
}
// Create the appropriate string depending on whether we're sCTypeClass or
// sCTypeProtoClass.
JSString* result;
if (CType::IsCType(obj)) {
AutoString type;
AppendString(type, "type ");
AppendString(type, GetName(cx, obj));
result = NewUCString(cx, type);
}
else {
result = JS_NewStringCopyZ(cx, "[CType proto object]");
}
if (!result)
return false;
args.rval().setString(result);
return true;
}
bool
CType::ToSource(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSObject* obj = JS_THIS_OBJECT(cx, vp);
if (!obj)
return false;
if (!CType::IsCType(obj) && !CType::IsCTypeProto(obj)) {
return IncompatibleThisProto(cx, "CType.prototype.toSource",
InformalValueTypeName(args.thisv()));
}
// Create the appropriate string depending on whether we're sCTypeClass or
// sCTypeProtoClass.
JSString* result;
if (CType::IsCType(obj)) {
AutoString source;
BuildTypeSource(cx, obj, false, source);
result = NewUCString(cx, source);
} else {
result = JS_NewStringCopyZ(cx, "[CType proto object]");
}
if (!result)
return false;
args.rval().setString(result);
return true;
}
bool
CType::HasInstance(JSContext* cx, HandleObject obj, MutableHandleValue v, bool* bp)
{
MOZ_ASSERT(CType::IsCType(obj));
Value slot = JS_GetReservedSlot(obj, SLOT_PROTO);
JS::Rooted<JSObject*> prototype(cx, &slot.toObject());
MOZ_ASSERT(prototype);
MOZ_ASSERT(CData::IsCDataProto(prototype));
*bp = false;
if (v.isPrimitive())
return true;
RootedObject proto(cx, &v.toObject());
for (;;) {
if (!JS_GetPrototype(cx, proto, &proto))
return false;
if (!proto)
break;
if (proto == prototype) {
*bp = true;
break;
}
}
return true;
}
static JSObject*
CType::GetGlobalCTypes(JSContext* cx, JSObject* objArg)
{
MOZ_ASSERT(CType::IsCType(objArg));
RootedObject obj(cx, objArg);
RootedObject objTypeProto(cx);
if (!JS_GetPrototype(cx, obj, &objTypeProto))
return nullptr;
MOZ_ASSERT(objTypeProto);
MOZ_ASSERT(CType::IsCTypeProto(objTypeProto));
Value valCTypes = JS_GetReservedSlot(objTypeProto, SLOT_CTYPES);
MOZ_ASSERT(valCTypes.isObject());
return &valCTypes.toObject();
}
/*******************************************************************************
** ABI implementation
*******************************************************************************/
bool
ABI::IsABI(JSObject* obj)
{
return JS_GetClass(obj) == &sCABIClass;
}
bool
ABI::ToSource(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 0) {
return ArgumentLengthError(cx, "ABI.prototype.toSource", "no", "s");
}
JSObject* obj = JS_THIS_OBJECT(cx, vp);
if (!obj)
return false;
if (!ABI::IsABI(obj)) {
return IncompatibleThisProto(cx, "ABI.prototype.toSource",
InformalValueTypeName(args.thisv()));
}
JSString* result;
switch (GetABICode(obj)) {
case ABI_DEFAULT:
result = JS_NewStringCopyZ(cx, "ctypes.default_abi");
break;
case ABI_STDCALL:
result = JS_NewStringCopyZ(cx, "ctypes.stdcall_abi");
break;
case ABI_THISCALL:
result = JS_NewStringCopyZ(cx, "ctypes.thiscall_abi");
break;
case ABI_WINAPI:
result = JS_NewStringCopyZ(cx, "ctypes.winapi_abi");
break;
default:
JS_ReportErrorASCII(cx, "not a valid ABICode");
return false;
}
if (!result)
return false;
args.rval().setString(result);
return true;
}
/*******************************************************************************
** PointerType implementation
*******************************************************************************/
bool
PointerType::Create(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Construct and return a new PointerType object.
if (args.length() != 1) {
return ArgumentLengthError(cx, "PointerType", "one", "");
}
Value arg = args[0];
RootedObject obj(cx);
if (arg.isPrimitive() || !CType::IsCType(obj = &arg.toObject())) {
return ArgumentTypeMismatch(cx, "", "PointerType", "a CType");
}
JSObject* result = CreateInternal(cx, obj);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
JSObject*
PointerType::CreateInternal(JSContext* cx, HandleObject baseType)
{
// check if we have a cached PointerType on our base CType.
Value slot = JS_GetReservedSlot(baseType, SLOT_PTR);
if (!slot.isUndefined())
return &slot.toObject();
// Get ctypes.PointerType.prototype and the common prototype for CData objects
// of this type, or ctypes.FunctionType.prototype for function pointers.
CTypeProtoSlot slotId = CType::GetTypeCode(baseType) == TYPE_function ?
SLOT_FUNCTIONDATAPROTO : SLOT_POINTERDATAPROTO;
RootedObject dataProto(cx, CType::GetProtoFromType(cx, baseType, slotId));
if (!dataProto)
return nullptr;
RootedObject typeProto(cx, CType::GetProtoFromType(cx, baseType, SLOT_POINTERPROTO));
if (!typeProto)
return nullptr;
// Create a new CType object with the common properties and slots.
RootedValue sizeVal(cx, Int32Value(sizeof(void*)));
RootedValue alignVal(cx, Int32Value(ffi_type_pointer.alignment));
JSObject* typeObj = CType::Create(cx, typeProto, dataProto, TYPE_pointer,
nullptr, sizeVal, alignVal,
&ffi_type_pointer);
if (!typeObj)
return nullptr;
// Set the target type. (This will be 'null' for an opaque pointer type.)
JS_SetReservedSlot(typeObj, SLOT_TARGET_T, ObjectValue(*baseType));
// Finally, cache our newly-created PointerType on our pointed-to CType.
JS_SetReservedSlot(baseType, SLOT_PTR, ObjectValue(*typeObj));
return typeObj;
}
bool
PointerType::ConstructData(JSContext* cx,
HandleObject obj,
const CallArgs& args)
{
if (!CType::IsCType(obj) || CType::GetTypeCode(obj) != TYPE_pointer) {
return IncompatibleCallee(cx, "PointerType constructor", obj);
}
if (args.length() > 3) {
return ArgumentLengthError(cx, "PointerType constructor", "0, 1, 2, or 3",
"s");
}
RootedObject result(cx, CData::Create(cx, obj, nullptr, nullptr, true));
if (!result)
return false;
// Set return value early, must not observe *vp after
args.rval().setObject(*result);
// There are 3 things that we might be creating here:
// 1 - A null pointer (no arguments)
// 2 - An initialized pointer (1 argument)
// 3 - A closure (1-3 arguments)
//
// The API doesn't give us a perfect way to distinguish 2 and 3, but the
// heuristics we use should be fine.
//
// Case 1 - Null pointer
//
if (args.length() == 0)
return true;
// Analyze the arguments a bit to decide what to do next.
RootedObject baseObj(cx, PointerType::GetBaseType(obj));
bool looksLikeClosure = CType::GetTypeCode(baseObj) == TYPE_function &&
args[0].isObject() && JS::IsCallable(&args[0].toObject());
//
// Case 2 - Initialized pointer
//
if (!looksLikeClosure) {
if (args.length() != 1) {
return ArgumentLengthError(cx, "FunctionType constructor", "one", "");
}
return ExplicitConvert(cx, args[0], obj, CData::GetData(result),
ConversionType::Construct);
}
//
// Case 3 - Closure
//
// The second argument is an optional 'this' parameter with which to invoke
// the given js function. Callers may leave this blank, or pass null if they
// wish to pass the third argument.
RootedObject thisObj(cx, nullptr);
if (args.length() >= 2) {
if (args[1].isNull()) {
thisObj = nullptr;
} else if (args[1].isObject()) {
thisObj = &args[1].toObject();
} else if (!JS_ValueToObject(cx, args[1], &thisObj)) {
return false;
}
}
// The third argument is an optional error sentinel that js-ctypes will return
// if an exception is raised while executing the closure. The type must match
// the return type of the callback.
RootedValue errVal(cx);
if (args.length() == 3)
errVal = args[2];
RootedObject fnObj(cx, &args[0].toObject());
return FunctionType::ConstructData(cx, baseObj, result, fnObj, thisObj, errVal);
}
JSObject*
PointerType::GetBaseType(JSObject* obj)
{
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_pointer);
Value type = JS_GetReservedSlot(obj, SLOT_TARGET_T);
MOZ_ASSERT(!type.isNull());
return &type.toObject();
}
bool
PointerType::IsPointerType(HandleValue v)
{
if (!v.isObject())
return false;
JSObject* obj = &v.toObject();
return CType::IsCType(obj) && CType::GetTypeCode(obj) == TYPE_pointer;
}
bool
PointerType::IsPointer(HandleValue v)
{
if (!v.isObject())
return false;
JSObject* obj = &v.toObject();
return CData::IsCData(obj) && CType::GetTypeCode(CData::GetCType(obj)) == TYPE_pointer;
}
bool
PointerType::TargetTypeGetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
args.rval().set(JS_GetReservedSlot(obj, SLOT_TARGET_T));
MOZ_ASSERT(args.rval().isObject());
return true;
}
bool
PointerType::IsNull(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSObject* obj = JS_THIS_OBJECT(cx, vp);
if (!obj)
return false;
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "PointerType.prototype.isNull",
args.thisv());
}
// Get pointer type and base type.
JSObject* typeObj = CData::GetCType(obj);
if (CType::GetTypeCode(typeObj) != TYPE_pointer) {
return IncompatibleThisType(cx, "PointerType.prototype.isNull",
"non-PointerType CData", args.thisv());
}
void* data = *static_cast<void**>(CData::GetData(obj));
args.rval().setBoolean(data == nullptr);
return true;
}
bool
PointerType::OffsetBy(JSContext* cx, const CallArgs& args, int offset)
{
RootedObject obj(cx, JS_THIS_OBJECT(cx, args.base()));
if (!obj)
return false;
if (!CData::IsCData(obj)) {
if (offset == 1) {
return IncompatibleThisProto(cx, "PointerType.prototype.increment",
args.thisv());
}
return IncompatibleThisProto(cx, "PointerType.prototype.decrement",
args.thisv());
}
RootedObject typeObj(cx, CData::GetCType(obj));
if (CType::GetTypeCode(typeObj) != TYPE_pointer) {
if (offset == 1) {
return IncompatibleThisType(cx, "PointerType.prototype.increment",
"non-PointerType CData", args.thisv());
}
return IncompatibleThisType(cx, "PointerType.prototype.decrement",
"non-PointerType CData", args.thisv());
}
RootedObject baseType(cx, PointerType::GetBaseType(typeObj));
if (!CType::IsSizeDefined(baseType)) {
return UndefinedSizePointerError(cx, "modify", obj);
}
size_t elementSize = CType::GetSize(baseType);
char* data = static_cast<char*>(*static_cast<void**>(CData::GetData(obj)));
void* address = data + offset * elementSize;
// Create a PointerType CData object containing the new address.
JSObject* result = CData::Create(cx, typeObj, nullptr, &address, true);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
bool
PointerType::Increment(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
return OffsetBy(cx, args, 1);
}
bool
PointerType::Decrement(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
return OffsetBy(cx, args, -1);
}
bool
PointerType::ContentsGetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
RootedObject baseType(cx, GetBaseType(CData::GetCType(obj)));
if (!CType::IsSizeDefined(baseType)) {
return UndefinedSizePointerError(cx, "get contents of", obj);
}
void* data = *static_cast<void**>(CData::GetData(obj));
if (data == nullptr) {
return NullPointerError(cx, "read contents of", obj);
}
RootedValue result(cx);
if (!ConvertToJS(cx, baseType, nullptr, data, false, false, &result))
return false;
args.rval().set(result);
return true;
}
bool
PointerType::ContentsSetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
RootedObject baseType(cx, GetBaseType(CData::GetCType(obj)));
if (!CType::IsSizeDefined(baseType)) {
return UndefinedSizePointerError(cx, "set contents of", obj);
}
void* data = *static_cast<void**>(CData::GetData(obj));
if (data == nullptr) {
return NullPointerError(cx, "write contents to", obj);
}
args.rval().setUndefined();
return ImplicitConvert(cx, args.get(0), baseType, data,
ConversionType::Setter, nullptr);
}
/*******************************************************************************
** ArrayType implementation
*******************************************************************************/
bool
ArrayType::Create(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Construct and return a new ArrayType object.
if (args.length() < 1 || args.length() > 2) {
return ArgumentLengthError(cx, "ArrayType", "one or two", "s");
}
if (args[0].isPrimitive() || !CType::IsCType(&args[0].toObject())) {
return ArgumentTypeMismatch(cx, "first ", "ArrayType", "a CType");
}
// Convert the length argument to a size_t.
size_t length = 0;
if (args.length() == 2 && !jsvalToSize(cx, args[1], false, &length)) {
return ArgumentTypeMismatch(cx, "second ", "ArrayType",
"a nonnegative integer");
}
RootedObject baseType(cx, &args[0].toObject());
JSObject* result = CreateInternal(cx, baseType, length, args.length() == 2);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
JSObject*
ArrayType::CreateInternal(JSContext* cx,
HandleObject baseType,
size_t length,
bool lengthDefined)
{
// Get ctypes.ArrayType.prototype and the common prototype for CData objects
// of this type, from ctypes.CType.prototype.
RootedObject typeProto(cx, CType::GetProtoFromType(cx, baseType, SLOT_ARRAYPROTO));
if (!typeProto)
return nullptr;
RootedObject dataProto(cx, CType::GetProtoFromType(cx, baseType, SLOT_ARRAYDATAPROTO));
if (!dataProto)
return nullptr;
// Determine the size of the array from the base type, if possible.
// The size of the base type must be defined.
// If our length is undefined, both our size and length will be undefined.
size_t baseSize;
if (!CType::GetSafeSize(baseType, &baseSize)) {
JS_ReportErrorASCII(cx, "base size must be defined");
return nullptr;
}
RootedValue sizeVal(cx);
RootedValue lengthVal(cx);
if (lengthDefined) {
// Check for overflow, and convert to an int or double as required.
size_t size = length * baseSize;
if (length > 0 && size / length != baseSize) {
SizeOverflow(cx, "array size", "size_t");
return nullptr;
}
if (!SizeTojsval(cx, size, &sizeVal)) {
SizeOverflow(cx, "array size", "JavaScript number");
return nullptr;
}
if (!SizeTojsval(cx, length, &lengthVal)) {
SizeOverflow(cx, "array length", "JavaScript number");
return nullptr;
}
}
RootedValue alignVal(cx, Int32Value(CType::GetAlignment(baseType)));
// Create a new CType object with the common properties and slots.
JSObject* typeObj = CType::Create(cx, typeProto, dataProto, TYPE_array, nullptr,
sizeVal, alignVal, nullptr);
if (!typeObj)
return nullptr;
// Set the element type.
JS_SetReservedSlot(typeObj, SLOT_ELEMENT_T, ObjectValue(*baseType));
// Set the length.
JS_SetReservedSlot(typeObj, SLOT_LENGTH, lengthVal);
return typeObj;
}
bool
ArrayType::ConstructData(JSContext* cx,
HandleObject obj_,
const CallArgs& args)
{
RootedObject obj(cx, obj_); // Make a mutable version
if (!CType::IsCType(obj) || CType::GetTypeCode(obj) != TYPE_array) {
return IncompatibleCallee(cx, "ArrayType constructor", obj);
}
// Decide whether we have an object to initialize from. We'll override this
// if we get a length argument instead.
bool convertObject = args.length() == 1;
// Check if we're an array of undefined length. If we are, allow construction
// with a length argument, or with an actual JS array.
if (CType::IsSizeDefined(obj)) {
if (args.length() > 1) {
return ArgumentLengthError(cx, "size defined ArrayType constructor",
"at most one", "");
}
} else {
if (args.length() != 1) {
return ArgumentLengthError(cx, "size undefined ArrayType constructor",
"one", "");
}
RootedObject baseType(cx, GetBaseType(obj));
size_t length;
if (jsvalToSize(cx, args[0], false, &length)) {
// Have a length, rather than an object to initialize from.
convertObject = false;
} else if (args[0].isObject()) {
// We were given an object with a .length property.
// This could be a JS array, or a CData array.
RootedObject arg(cx, &args[0].toObject());
RootedValue lengthVal(cx);
if (!JS_GetProperty(cx, arg, "length", &lengthVal) ||
!jsvalToSize(cx, lengthVal, false, &length)) {
return ArgumentTypeMismatch(cx, "",
"size undefined ArrayType constructor",
"an array object or integer");
}
} else if (args[0].isString()) {
// We were given a string. Size the array to the appropriate length,
// including space for the terminator.
JSString* sourceString = args[0].toString();
size_t sourceLength = sourceString->length();
JSLinearString* sourceLinear = sourceString->ensureLinear(cx);
if (!sourceLinear)
return false;
switch (CType::GetTypeCode(baseType)) {
case TYPE_char:
case TYPE_signed_char:
case TYPE_unsigned_char: {
// Determine the UTF-8 length.
length = GetDeflatedUTF8StringLength(cx, sourceLinear);
if (length == (size_t) -1)
return false;
++length;
break;
}
case TYPE_char16_t:
length = sourceLength + 1;
break;
default:
return ConvError(cx, obj, args[0], ConversionType::Construct);
}
} else {
return ArgumentTypeMismatch(cx, "",
"size undefined ArrayType constructor",
"an array object or integer");
}
// Construct a new ArrayType of defined length, for the new CData object.
obj = CreateInternal(cx, baseType, length, true);
if (!obj)
return false;
}
JSObject* result = CData::Create(cx, obj, nullptr, nullptr, true);
if (!result)
return false;
args.rval().setObject(*result);
if (convertObject) {
if (!ExplicitConvert(cx, args[0], obj, CData::GetData(result),
ConversionType::Construct))
return false;
}
return true;
}
JSObject*
ArrayType::GetBaseType(JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_array);
Value type = JS_GetReservedSlot(obj, SLOT_ELEMENT_T);
MOZ_ASSERT(!type.isNull());
return &type.toObject();
}
bool
ArrayType::GetSafeLength(JSObject* obj, size_t* result)
{
MOZ_ASSERT(CType::IsCType(obj));
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_array);
Value length = JS_GetReservedSlot(obj, SLOT_LENGTH);
// The "length" property can be an int, a double, or JS::UndefinedValue()
// (for arrays of undefined length), and must always fit in a size_t.
if (length.isInt32()) {
*result = length.toInt32();
return true;
}
if (length.isDouble()) {
*result = Convert<size_t>(length.toDouble());
return true;
}
MOZ_ASSERT(length.isUndefined());
return false;
}
size_t
ArrayType::GetLength(JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_array);
Value length = JS_GetReservedSlot(obj, SLOT_LENGTH);
MOZ_ASSERT(!length.isUndefined());
// The "length" property can be an int, a double, or JS::UndefinedValue()
// (for arrays of undefined length), and must always fit in a size_t.
// For callers who know it can never be JS::UndefinedValue(), return a size_t
// directly.
if (length.isInt32())
return length.toInt32();
return Convert<size_t>(length.toDouble());
}
UniquePtrFFIType
ArrayType::BuildFFIType(JSContext* cx, JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_array);
MOZ_ASSERT(CType::IsSizeDefined(obj));
JSObject* baseType = ArrayType::GetBaseType(obj);
ffi_type* ffiBaseType = CType::GetFFIType(cx, baseType);
if (!ffiBaseType)
return nullptr;
size_t length = ArrayType::GetLength(obj);
// Create an ffi_type to represent the array. This is necessary for the case
// where the array is part of a struct. Since libffi has no intrinsic
// support for array types, we approximate it by creating a struct type
// with elements of type 'baseType' and with appropriate size and alignment
// values. It would be nice to not do all the work of setting up 'elements',
// but some libffi platforms currently require that it be meaningful. I'm
// looking at you, x86_64.
auto ffiType = cx->make_unique<ffi_type>();
if (!ffiType) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
ffiType->type = FFI_TYPE_STRUCT;
ffiType->size = CType::GetSize(obj);
ffiType->alignment = CType::GetAlignment(obj);
ffiType->elements = cx->pod_malloc<ffi_type*>(length + 1);
if (!ffiType->elements) {
JS_ReportAllocationOverflow(cx);
return nullptr;
}
for (size_t i = 0; i < length; ++i)
ffiType->elements[i] = ffiBaseType;
ffiType->elements[length] = nullptr;
return Move(ffiType);
}
bool
ArrayType::IsArrayType(HandleValue v)
{
if (!v.isObject())
return false;
JSObject* obj = &v.toObject();
return CType::IsCType(obj) && CType::GetTypeCode(obj) == TYPE_array;
}
bool
ArrayType::IsArrayOrArrayType(HandleValue v)
{
if (!v.isObject())
return false;
JSObject* obj = &v.toObject();
// Allow both CTypes and CDatas of the ArrayType persuasion by extracting the
// CType if we're dealing with a CData.
if (CData::IsCData(obj)) {
obj = CData::GetCType(obj);
}
return CType::IsCType(obj) && CType::GetTypeCode(obj) == TYPE_array;
}
bool
ArrayType::ElementTypeGetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
args.rval().set(JS_GetReservedSlot(obj, SLOT_ELEMENT_T));
MOZ_ASSERT(args.rval().isObject());
return true;
}
bool
ArrayType::LengthGetter(JSContext* cx, const JS::CallArgs& args)
{
JSObject* obj = &args.thisv().toObject();
// This getter exists for both CTypes and CDatas of the ArrayType persuasion.
// If we're dealing with a CData, get the CType from it.
if (CData::IsCData(obj))
obj = CData::GetCType(obj);
args.rval().set(JS_GetReservedSlot(obj, SLOT_LENGTH));
MOZ_ASSERT(args.rval().isNumber() || args.rval().isUndefined());
return true;
}
bool
ArrayType::Getter(JSContext* cx, HandleObject obj, HandleId idval, MutableHandleValue vp)
{
// This should never happen, but we'll check to be safe.
if (!CData::IsCData(obj)) {
RootedValue objVal(cx, ObjectValue(*obj));
return IncompatibleThisProto(cx, "ArrayType property getter", objVal);
}
// Bail early if we're not an ArrayType. (This setter is present for all
// CData, regardless of CType.)
JSObject* typeObj = CData::GetCType(obj);
if (CType::GetTypeCode(typeObj) != TYPE_array)
return true;
// Convert the index to a size_t and bounds-check it.
size_t index;
size_t length = GetLength(typeObj);
bool ok = jsidToSize(cx, idval, true, &index);
int32_t dummy;
if (!ok && JSID_IS_SYMBOL(idval))
return true;
bool dummy2;
if (!ok && JSID_IS_STRING(idval) &&
!StringToInteger(cx, JSID_TO_STRING(idval), &dummy, &dummy2)) {
// String either isn't a number, or doesn't fit in size_t.
// Chances are it's a regular property lookup, so return.
return true;
}
if (!ok) {
return InvalidIndexError(cx, idval);
}
if (index >= length) {
return InvalidIndexRangeError(cx, index, length);
}
RootedObject baseType(cx, GetBaseType(typeObj));
size_t elementSize = CType::GetSize(baseType);
char* data = static_cast<char*>(CData::GetData(obj)) + elementSize * index;
return ConvertToJS(cx, baseType, obj, data, false, false, vp);
}
bool
ArrayType::Setter(JSContext* cx, HandleObject obj, HandleId idval, MutableHandleValue vp,
ObjectOpResult& result)
{
// This should never happen, but we'll check to be safe.
if (!CData::IsCData(obj)) {
RootedValue objVal(cx, ObjectValue(*obj));
return IncompatibleThisProto(cx, "ArrayType property setter", objVal);
}
// Bail early if we're not an ArrayType. (This setter is present for all
// CData, regardless of CType.)
RootedObject typeObj(cx, CData::GetCType(obj));
if (CType::GetTypeCode(typeObj) != TYPE_array)
return result.succeed();
// Convert the index to a size_t and bounds-check it.
size_t index;
size_t length = GetLength(typeObj);
bool ok = jsidToSize(cx, idval, true, &index);
int32_t dummy;
if (!ok && JSID_IS_SYMBOL(idval))
return true;
bool dummy2;
if (!ok && JSID_IS_STRING(idval) &&
!StringToInteger(cx, JSID_TO_STRING(idval), &dummy, &dummy2)) {
// String either isn't a number, or doesn't fit in size_t.
// Chances are it's a regular property lookup, so return.
return result.succeed();
}
if (!ok) {
return InvalidIndexError(cx, idval);
}
if (index >= length) {
return InvalidIndexRangeError(cx, index, length);
}
RootedObject baseType(cx, GetBaseType(typeObj));
size_t elementSize = CType::GetSize(baseType);
char* data = static_cast<char*>(CData::GetData(obj)) + elementSize * index;
if (!ImplicitConvert(cx, vp, baseType, data, ConversionType::Setter,
nullptr, nullptr, 0, typeObj, index))
return false;
return result.succeed();
}
bool
ArrayType::AddressOfElement(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
if (!obj)
return false;
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "ArrayType.prototype.addressOfElement",
args.thisv());
}
RootedObject typeObj(cx, CData::GetCType(obj));
if (CType::GetTypeCode(typeObj) != TYPE_array) {
return IncompatibleThisType(cx, "ArrayType.prototype.addressOfElement",
"non-ArrayType CData", args.thisv());
}
if (args.length() != 1) {
return ArgumentLengthError(cx, "ArrayType.prototype.addressOfElement",
"one", "");
}
RootedObject baseType(cx, GetBaseType(typeObj));
RootedObject pointerType(cx, PointerType::CreateInternal(cx, baseType));
if (!pointerType)
return false;
// Create a PointerType CData object containing null.
RootedObject result(cx, CData::Create(cx, pointerType, nullptr, nullptr, true));
if (!result)
return false;
args.rval().setObject(*result);
// Convert the index to a size_t and bounds-check it.
size_t index;
size_t length = GetLength(typeObj);
if (!jsvalToSize(cx, args[0], false, &index)) {
return InvalidIndexError(cx, args[0]);
}
if (index >= length) {
return InvalidIndexRangeError(cx, index, length);
}
// Manually set the pointer inside the object, so we skip the conversion step.
void** data = static_cast<void**>(CData::GetData(result));
size_t elementSize = CType::GetSize(baseType);
*data = static_cast<char*>(CData::GetData(obj)) + elementSize * index;
return true;
}
/*******************************************************************************
** StructType implementation
*******************************************************************************/
// For a struct field descriptor 'val' of the form { name : type }, extract
// 'name' and 'type'.
static JSFlatString*
ExtractStructField(JSContext* cx, HandleValue val, MutableHandleObject typeObj)
{
if (val.isPrimitive()) {
FieldDescriptorNameTypeError(cx, val);
return nullptr;
}
RootedObject obj(cx, &val.toObject());
Rooted<IdVector> props(cx, IdVector(cx));
if (!JS_Enumerate(cx, obj, &props))
return nullptr;
// make sure we have one, and only one, property
if (props.length() != 1) {
FieldDescriptorCountError(cx, val, props.length());
return nullptr;
}
RootedId nameid(cx, props[0]);
if (!JSID_IS_STRING(nameid)) {
FieldDescriptorNameError(cx, nameid);
return nullptr;
}
RootedValue propVal(cx);
if (!JS_GetPropertyById(cx, obj, nameid, &propVal))
return nullptr;
if (propVal.isPrimitive() || !CType::IsCType(&propVal.toObject())) {
FieldDescriptorTypeError(cx, propVal, nameid);
return nullptr;
}
// Undefined size or zero size struct members are illegal.
// (Zero-size arrays are legal as struct members in C++, but libffi will
// choke on a zero-size struct, so we disallow them.)
typeObj.set(&propVal.toObject());
size_t size;
if (!CType::GetSafeSize(typeObj, &size) || size == 0) {
FieldDescriptorSizeError(cx, typeObj, nameid);
return nullptr;
}
return JSID_TO_FLAT_STRING(nameid);
}
// For a struct field with 'name' and 'type', add an element of the form
// { name : type }.
static bool
AddFieldToArray(JSContext* cx,
MutableHandleValue element,
JSFlatString* name_,
JSObject* typeObj_)
{
RootedObject typeObj(cx, typeObj_);
Rooted<JSFlatString*> name(cx, name_);
RootedObject fieldObj(cx, JS_NewPlainObject(cx));
if (!fieldObj)
return false;
element.setObject(*fieldObj);
AutoStableStringChars nameChars(cx);
if (!nameChars.initTwoByte(cx, name))
return false;
if (!JS_DefineUCProperty(cx, fieldObj,
nameChars.twoByteChars(), name->length(),
typeObj,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
return false;
return JS_FreezeObject(cx, fieldObj);
}
bool
StructType::Create(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Construct and return a new StructType object.
if (args.length() < 1 || args.length() > 2) {
return ArgumentLengthError(cx, "StructType", "one or two", "s");
}
Value name = args[0];
if (!name.isString()) {
return ArgumentTypeMismatch(cx, "first ", "StructType", "a string");
}
// Get ctypes.StructType.prototype from the ctypes.StructType constructor.
RootedObject typeProto(cx, CType::GetProtoFromCtor(&args.callee(), SLOT_STRUCTPROTO));
// Create a simple StructType with no defined fields. The result will be
// non-instantiable as CData, will have no 'prototype' property, and will
// have undefined size and alignment and no ffi_type.
RootedObject result(cx, CType::Create(cx, typeProto, nullptr, TYPE_struct,
name.toString(),
JS::UndefinedHandleValue,
JS::UndefinedHandleValue, nullptr));
if (!result)
return false;
if (args.length() == 2) {
RootedObject arr(cx, args[1].isObject() ? &args[1].toObject() : nullptr);
bool isArray;
if (!arr) {
isArray = false;
} else {
if (!JS_IsArrayObject(cx, arr, &isArray))
return false;
}
if (!isArray)
return ArgumentTypeMismatch(cx, "second ", "StructType", "an array");
// Define the struct fields.
if (!DefineInternal(cx, result, arr))
return false;
}
args.rval().setObject(*result);
return true;
}
bool
StructType::DefineInternal(JSContext* cx, JSObject* typeObj_, JSObject* fieldsObj_)
{
RootedObject typeObj(cx, typeObj_);
RootedObject fieldsObj(cx, fieldsObj_);
uint32_t len;
ASSERT_OK(JS_GetArrayLength(cx, fieldsObj, &len));
// Get the common prototype for CData objects of this type from
// ctypes.CType.prototype.
RootedObject dataProto(cx, CType::GetProtoFromType(cx, typeObj, SLOT_STRUCTDATAPROTO));
if (!dataProto)
return false;
// Set up the 'prototype' and 'prototype.constructor' properties.
// The prototype will reflect the struct fields as properties on CData objects
// created from this type.
RootedObject prototype(cx, JS_NewObjectWithGivenProto(cx, &sCDataProtoClass, dataProto));
if (!prototype)
return false;
if (!JS_DefineProperty(cx, prototype, "constructor", typeObj,
JSPROP_READONLY | JSPROP_PERMANENT))
return false;
// Create a FieldInfoHash to stash on the type object.
Rooted<FieldInfoHash> fields(cx);
if (!fields.init(len)) {
JS_ReportOutOfMemory(cx);
return false;
}
// Process the field types.
size_t structSize, structAlign;
if (len != 0) {
structSize = 0;
structAlign = 0;
for (uint32_t i = 0; i < len; ++i) {
RootedValue item(cx);
if (!JS_GetElement(cx, fieldsObj, i, &item))
return false;
RootedObject fieldType(cx, nullptr);
Rooted<JSFlatString*> name(cx, ExtractStructField(cx, item, &fieldType));
if (!name)
return false;
// Make sure each field name is unique
FieldInfoHash::AddPtr entryPtr = fields.lookupForAdd(name);
if (entryPtr) {
return DuplicateFieldError(cx, name);
}
// Add the field to the StructType's 'prototype' property.
AutoStableStringChars nameChars(cx);
if (!nameChars.initTwoByte(cx, name))
return false;
RootedFunction getter(cx, NewFunctionWithReserved(cx, StructType::FieldGetter, 0, 0, nullptr));
if (!getter)
return false;
SetFunctionNativeReserved(getter, StructType::SLOT_FIELDNAME,
StringValue(JS_FORGET_STRING_FLATNESS(name)));
RootedObject getterObj(cx, JS_GetFunctionObject(getter));
RootedFunction setter(cx, NewFunctionWithReserved(cx, StructType::FieldSetter, 1, 0, nullptr));
if (!setter)
return false;
SetFunctionNativeReserved(setter, StructType::SLOT_FIELDNAME,
StringValue(JS_FORGET_STRING_FLATNESS(name)));
RootedObject setterObj(cx, JS_GetFunctionObject(setter));
if (!JS_DefineUCProperty(cx, prototype,
nameChars.twoByteChars(), name->length(), UndefinedHandleValue,
JSPROP_SHARED | JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_GETTER | JSPROP_SETTER,
JS_DATA_TO_FUNC_PTR(JSNative, getterObj.get()),
JS_DATA_TO_FUNC_PTR(JSNative, setterObj.get())))
{
return false;
}
size_t fieldSize = CType::GetSize(fieldType);
size_t fieldAlign = CType::GetAlignment(fieldType);
size_t fieldOffset = Align(structSize, fieldAlign);
// Check for overflow. Since we hold invariant that fieldSize % fieldAlign
// be zero, we can safely check fieldOffset + fieldSize without first
// checking fieldOffset for overflow.
if (fieldOffset + fieldSize < structSize) {
SizeOverflow(cx, "struct size", "size_t");
return false;
}
// Add field name to the hash
FieldInfo info;
info.mType = fieldType;
info.mIndex = i;
info.mOffset = fieldOffset;
if (!fields.add(entryPtr, name, info)) {
JS_ReportOutOfMemory(cx);
return false;
}
structSize = fieldOffset + fieldSize;
if (fieldAlign > structAlign)
structAlign = fieldAlign;
}
// Pad the struct tail according to struct alignment.
size_t structTail = Align(structSize, structAlign);
if (structTail < structSize) {
SizeOverflow(cx, "struct size", "size_t");
return false;
}
structSize = structTail;
} else {
// Empty structs are illegal in C, but are legal and have a size of
// 1 byte in C++. We're going to allow them, and trick libffi into
// believing this by adding a char member. The resulting struct will have
// no getters or setters, and will be initialized to zero.
structSize = 1;
structAlign = 1;
}
RootedValue sizeVal(cx);
if (!SizeTojsval(cx, structSize, &sizeVal)) {
SizeOverflow(cx, "struct size", "double");
return false;
}
// Move the field hash to the heap and store it in the typeObj.
FieldInfoHash *heapHash = cx->new_<FieldInfoHash>(mozilla::Move(fields.get()));
if (!heapHash) {
JS_ReportOutOfMemory(cx);
return false;
}
MOZ_ASSERT(heapHash->initialized());
JS_SetReservedSlot(typeObj, SLOT_FIELDINFO, PrivateValue(heapHash));
JS_SetReservedSlot(typeObj, SLOT_SIZE, sizeVal);
JS_SetReservedSlot(typeObj, SLOT_ALIGN, Int32Value(structAlign));
//if (!JS_FreezeObject(cx, prototype)0 // XXX fixme - see bug 541212!
// return false;
JS_SetReservedSlot(typeObj, SLOT_PROTO, ObjectValue(*prototype));
return true;
}
UniquePtrFFIType
StructType::BuildFFIType(JSContext* cx, JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_struct);
MOZ_ASSERT(CType::IsSizeDefined(obj));
const FieldInfoHash* fields = GetFieldInfo(obj);
size_t len = fields->count();
size_t structSize = CType::GetSize(obj);
size_t structAlign = CType::GetAlignment(obj);
auto ffiType = cx->make_unique<ffi_type>();
if (!ffiType) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
ffiType->type = FFI_TYPE_STRUCT;
size_t count = len != 0 ? len + 1 : 2;
auto elements = cx->make_pod_array<ffi_type*>(count);
if (!elements) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
if (len != 0) {
elements[len] = nullptr;
for (FieldInfoHash::Range r = fields->all(); !r.empty(); r.popFront()) {
const FieldInfoHash::Entry& entry = r.front();
ffi_type* fieldType = CType::GetFFIType(cx, entry.value().mType);
if (!fieldType)
return nullptr;
elements[entry.value().mIndex] = fieldType;
}
} else {
// Represent an empty struct as having a size of 1 byte, just like C++.
MOZ_ASSERT(structSize == 1);
MOZ_ASSERT(structAlign == 1);
elements[0] = &ffi_type_uint8;
elements[1] = nullptr;
}
ffiType->elements = elements.release();
#ifdef DEBUG
// Perform a sanity check: the result of our struct size and alignment
// calculations should match libffi's. We force it to do this calculation
// by calling ffi_prep_cif.
ffi_cif cif;
ffiType->size = 0;
ffiType->alignment = 0;
ffi_status status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, ffiType.get(), nullptr);
MOZ_ASSERT(status == FFI_OK);
MOZ_ASSERT(structSize == ffiType->size);
MOZ_ASSERT(structAlign == ffiType->alignment);
#else
// Fill in the ffi_type's size and align fields. This makes libffi treat the
// type as initialized; it will not recompute the values. (We assume
// everything agrees; if it doesn't, we really want to know about it, which
// is the purpose of the above debug-only check.)
ffiType->size = structSize;
ffiType->alignment = structAlign;
#endif
return Move(ffiType);
}
bool
StructType::Define(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
if (!obj)
return false;
if (!CType::IsCType(obj)) {
return IncompatibleThisProto(cx, "StructType.prototype.define",
args.thisv());
}
if (CType::GetTypeCode(obj) != TYPE_struct) {
return IncompatibleThisType(cx, "StructType.prototype.define",
"non-StructType", args.thisv());
}
if (CType::IsSizeDefined(obj)) {
JS_ReportErrorASCII(cx, "StructType has already been defined");
return false;
}
if (args.length() != 1) {
return ArgumentLengthError(cx, "StructType.prototype.define", "one", "");
}
HandleValue arg = args[0];
if (arg.isPrimitive()) {
return ArgumentTypeMismatch(cx, "", "StructType.prototype.define",
"an array");
}
bool isArray;
if (!arg.isObject()) {
isArray = false;
} else {
if (!JS_IsArrayObject(cx, arg, &isArray))
return false;
}
if (!isArray) {
return ArgumentTypeMismatch(cx, "", "StructType.prototype.define",
"an array");
}
RootedObject arr(cx, &arg.toObject());
return DefineInternal(cx, obj, arr);
}
bool
StructType::ConstructData(JSContext* cx,
HandleObject obj,
const CallArgs& args)
{
if (!CType::IsCType(obj) || CType::GetTypeCode(obj) != TYPE_struct) {
return IncompatibleCallee(cx, "StructType constructor", obj);
}
if (!CType::IsSizeDefined(obj)) {
JS_ReportErrorASCII(cx, "cannot construct an opaque StructType");
return false;
}
JSObject* result = CData::Create(cx, obj, nullptr, nullptr, true);
if (!result)
return false;
args.rval().setObject(*result);
if (args.length() == 0)
return true;
char* buffer = static_cast<char*>(CData::GetData(result));
const FieldInfoHash* fields = GetFieldInfo(obj);
if (args.length() == 1) {
// There are two possible interpretations of the argument:
// 1) It may be an object '{ ... }' with properties representing the
// struct fields intended to ExplicitConvert wholesale to our StructType.
// 2) If the struct contains one field, the arg may be intended to
// ImplicitConvert directly to that arg's CType.
// Thankfully, the conditions for these two possibilities to succeed
// are mutually exclusive, so we can pick the right one.
// Try option 1) first.
if (ExplicitConvert(cx, args[0], obj, buffer, ConversionType::Construct))
return true;
if (fields->count() != 1)
return false;
// If ExplicitConvert failed, and there is no pending exception, then assume
// hard failure (out of memory, or some other similarly serious condition).
if (!JS_IsExceptionPending(cx))
return false;
// Otherwise, assume soft failure, and clear the pending exception so that we
// can throw a different one as required.
JS_ClearPendingException(cx);
// Fall through to try option 2).
}
// We have a type constructor of the form 'ctypes.StructType(a, b, c, ...)'.
// ImplicitConvert each field.
if (args.length() == fields->count()) {
for (FieldInfoHash::Range r = fields->all(); !r.empty(); r.popFront()) {
const FieldInfo& field = r.front().value();
MOZ_ASSERT(field.mIndex < fields->count()); /* Quantified invariant */
if (!ImplicitConvert(cx, args[field.mIndex], field.mType,
buffer + field.mOffset, ConversionType::Construct,
nullptr, nullptr, 0, obj, field.mIndex))
return false;
}
return true;
}
size_t count = fields->count();
if (count >= 2) {
char fieldLengthStr[32];
SprintfLiteral(fieldLengthStr, "0, 1, or %" PRIuSIZE, count);
return ArgumentLengthError(cx, "StructType constructor", fieldLengthStr,
"s");
}
return ArgumentLengthError(cx, "StructType constructor", "at most one", "");
}
const FieldInfoHash*
StructType::GetFieldInfo(JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_struct);
Value slot = JS_GetReservedSlot(obj, SLOT_FIELDINFO);
MOZ_ASSERT(!slot.isUndefined() && slot.toPrivate());
return static_cast<const FieldInfoHash*>(slot.toPrivate());
}
const FieldInfo*
StructType::LookupField(JSContext* cx, JSObject* obj, JSFlatString* name)
{
MOZ_ASSERT(CType::IsCType(obj));
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_struct);
FieldInfoHash::Ptr ptr = GetFieldInfo(obj)->lookup(name);
if (ptr)
return &ptr->value();
FieldMissingError(cx, obj, name);
return nullptr;
}
JSObject*
StructType::BuildFieldsArray(JSContext* cx, JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_struct);
MOZ_ASSERT(CType::IsSizeDefined(obj));
const FieldInfoHash* fields = GetFieldInfo(obj);
size_t len = fields->count();
// Prepare a new array for the 'fields' property of the StructType.
JS::AutoValueVector fieldsVec(cx);
if (!fieldsVec.resize(len))
return nullptr;
for (FieldInfoHash::Range r = fields->all(); !r.empty(); r.popFront()) {
const FieldInfoHash::Entry& entry = r.front();
// Add the field descriptor to the array.
if (!AddFieldToArray(cx, fieldsVec[entry.value().mIndex],
entry.key(), entry.value().mType))
return nullptr;
}
RootedObject fieldsProp(cx, JS_NewArrayObject(cx, fieldsVec));
if (!fieldsProp)
return nullptr;
// Seal the fields array.
if (!JS_FreezeObject(cx, fieldsProp))
return nullptr;
return fieldsProp;
}
/* static */ bool
StructType::IsStruct(HandleValue v)
{
if (!v.isObject())
return false;
JSObject* obj = &v.toObject();
return CType::IsCType(obj) && CType::GetTypeCode(obj) == TYPE_struct;
}
bool
StructType::FieldsArrayGetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
args.rval().set(JS_GetReservedSlot(obj, SLOT_FIELDS));
if (!CType::IsSizeDefined(obj)) {
MOZ_ASSERT(args.rval().isUndefined());
return true;
}
if (args.rval().isUndefined()) {
// Build the 'fields' array lazily.
JSObject* fields = BuildFieldsArray(cx, obj);
if (!fields)
return false;
JS_SetReservedSlot(obj, SLOT_FIELDS, ObjectValue(*fields));
args.rval().setObject(*fields);
}
MOZ_ASSERT(args.rval().isObject());
return true;
}
bool
StructType::FieldGetter(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (!args.thisv().isObject()) {
return IncompatibleThisProto(cx, "StructType property getter", args.thisv());
}
RootedObject obj(cx, &args.thisv().toObject());
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "StructType property getter", args.thisv());
}
JSObject* typeObj = CData::GetCType(obj);
if (CType::GetTypeCode(typeObj) != TYPE_struct) {
return IncompatibleThisType(cx, "StructType property getter",
"non-StructType CData", args.thisv());
}
RootedValue nameVal(cx, GetFunctionNativeReserved(&args.callee(), SLOT_FIELDNAME));
Rooted<JSFlatString*> name(cx, JS_FlattenString(cx, nameVal.toString()));
if (!name)
return false;
const FieldInfo* field = LookupField(cx, typeObj, name);
if (!field)
return false;
char* data = static_cast<char*>(CData::GetData(obj)) + field->mOffset;
RootedObject fieldType(cx, field->mType);
return ConvertToJS(cx, fieldType, obj, data, false, false, args.rval());
}
bool
StructType::FieldSetter(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (!args.thisv().isObject()) {
return IncompatibleThisProto(cx, "StructType property setter", args.thisv());
}
RootedObject obj(cx, &args.thisv().toObject());
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "StructType property setter", args.thisv());
}
RootedObject typeObj(cx, CData::GetCType(obj));
if (CType::GetTypeCode(typeObj) != TYPE_struct) {
return IncompatibleThisType(cx, "StructType property setter",
"non-StructType CData", args.thisv());
}
RootedValue nameVal(cx, GetFunctionNativeReserved(&args.callee(), SLOT_FIELDNAME));
Rooted<JSFlatString*> name(cx, JS_FlattenString(cx, nameVal.toString()));
if (!name)
return false;
const FieldInfo* field = LookupField(cx, typeObj, name);
if (!field)
return false;
args.rval().setUndefined();
char* data = static_cast<char*>(CData::GetData(obj)) + field->mOffset;
return ImplicitConvert(cx, args.get(0), field->mType, data, ConversionType::Setter, nullptr,
nullptr, 0, typeObj, field->mIndex);
}
bool
StructType::AddressOfField(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
if (!obj)
return false;
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "StructType.prototype.addressOfField",
args.thisv());
}
JSObject* typeObj = CData::GetCType(obj);
if (CType::GetTypeCode(typeObj) != TYPE_struct) {
return IncompatibleThisType(cx, "StructType.prototype.addressOfField",
"non-StructType CData", args.thisv());
}
if (args.length() != 1) {
return ArgumentLengthError(cx, "StructType.prototype.addressOfField",
"one", "");
}
if (!args[0].isString()) {
return ArgumentTypeMismatch(cx, "", "StructType.prototype.addressOfField",
"a string");
}
JSFlatString* str = JS_FlattenString(cx, args[0].toString());
if (!str)
return false;
const FieldInfo* field = LookupField(cx, typeObj, str);
if (!field)
return false;
RootedObject baseType(cx, field->mType);
RootedObject pointerType(cx, PointerType::CreateInternal(cx, baseType));
if (!pointerType)
return false;
// Create a PointerType CData object containing null.
JSObject* result = CData::Create(cx, pointerType, nullptr, nullptr, true);
if (!result)
return false;
args.rval().setObject(*result);
// Manually set the pointer inside the object, so we skip the conversion step.
void** data = static_cast<void**>(CData::GetData(result));
*data = static_cast<char*>(CData::GetData(obj)) + field->mOffset;
return true;
}
/*******************************************************************************
** FunctionType implementation
*******************************************************************************/
// Helper class for handling allocation of function arguments.
struct AutoValue
{
AutoValue() : mData(nullptr) { }
~AutoValue()
{
js_free(mData);
}
bool SizeToType(JSContext* cx, JSObject* type)
{
// Allocate a minimum of sizeof(ffi_arg) to handle small integers.
size_t size = Align(CType::GetSize(type), sizeof(ffi_arg));
mData = js_malloc(size);
if (mData)
memset(mData, 0, size);
return mData != nullptr;
}
void* mData;
};
static bool
GetABI(JSContext* cx, HandleValue abiType, ffi_abi* result)
{
if (abiType.isPrimitive())
return false;
ABICode abi = GetABICode(abiType.toObjectOrNull());
// determine the ABI from the subset of those available on the
// given platform. ABI_DEFAULT specifies the default
// C calling convention (cdecl) on each platform.
switch (abi) {
case ABI_DEFAULT:
*result = FFI_DEFAULT_ABI;
return true;
case ABI_THISCALL:
#if defined(_WIN64)
*result = FFI_WIN64;
return true;
#elif defined(_WIN32)
*result = FFI_THISCALL;
return true;
#else
break;
#endif
case ABI_STDCALL:
case ABI_WINAPI:
#if (defined(_WIN32) && !defined(_WIN64)) || defined(_OS2)
*result = FFI_STDCALL;
return true;
#elif (defined(_WIN64))
// We'd like the same code to work across Win32 and Win64, so stdcall_api
// and winapi_abi become aliases to the lone Win64 ABI.
*result = FFI_WIN64;
return true;
#endif
case INVALID_ABI:
break;
}
return false;
}
static JSObject*
PrepareType(JSContext* cx, uint32_t index, HandleValue type)
{
if (type.isPrimitive() || !CType::IsCType(type.toObjectOrNull())) {
FunctionArgumentTypeError(cx, index, type, "is not a ctypes type");
return nullptr;
}
JSObject* result = type.toObjectOrNull();
TypeCode typeCode = CType::GetTypeCode(result);
if (typeCode == TYPE_array) {
// convert array argument types to pointers, just like C.
// ImplicitConvert will do the same, when passing an array as data.
RootedObject baseType(cx, ArrayType::GetBaseType(result));
result = PointerType::CreateInternal(cx, baseType);
if (!result)
return nullptr;
} else if (typeCode == TYPE_void_t || typeCode == TYPE_function) {
// disallow void or function argument types
FunctionArgumentTypeError(cx, index, type, "cannot be void or function");
return nullptr;
}
if (!CType::IsSizeDefined(result)) {
FunctionArgumentTypeError(cx, index, type, "must have defined size");
return nullptr;
}
// libffi cannot pass types of zero size by value.
MOZ_ASSERT(CType::GetSize(result) != 0);
return result;
}
static JSObject*
PrepareReturnType(JSContext* cx, HandleValue type)
{
if (type.isPrimitive() || !CType::IsCType(type.toObjectOrNull())) {
FunctionReturnTypeError(cx, type, "is not a ctypes type");
return nullptr;
}
JSObject* result = type.toObjectOrNull();
TypeCode typeCode = CType::GetTypeCode(result);
// Arrays and functions can never be return types.
if (typeCode == TYPE_array || typeCode == TYPE_function) {
FunctionReturnTypeError(cx, type, "cannot be an array or function");
return nullptr;
}
if (typeCode != TYPE_void_t && !CType::IsSizeDefined(result)) {
FunctionReturnTypeError(cx, type, "must have defined size");
return nullptr;
}
// libffi cannot pass types of zero size by value.
MOZ_ASSERT(typeCode == TYPE_void_t || CType::GetSize(result) != 0);
return result;
}
static MOZ_ALWAYS_INLINE bool
IsEllipsis(JSContext* cx, HandleValue v, bool* isEllipsis)
{
*isEllipsis = false;
if (!v.isString())
return true;
JSString* str = v.toString();
if (str->length() != 3)
return true;
JSLinearString* linear = str->ensureLinear(cx);
if (!linear)
return false;
char16_t dot = '.';
*isEllipsis = (linear->latin1OrTwoByteChar(0) == dot &&
linear->latin1OrTwoByteChar(1) == dot &&
linear->latin1OrTwoByteChar(2) == dot);
return true;
}
static bool
PrepareCIF(JSContext* cx,
FunctionInfo* fninfo)
{
ffi_abi abi;
RootedValue abiType(cx, ObjectOrNullValue(fninfo->mABI));
if (!GetABI(cx, abiType, &abi)) {
JS_ReportErrorASCII(cx, "Invalid ABI specification");
return false;
}
ffi_type* rtype = CType::GetFFIType(cx, fninfo->mReturnType);
if (!rtype)
return false;
ffi_status status =
ffi_prep_cif(&fninfo->mCIF,
abi,
fninfo->mFFITypes.length(),
rtype,
fninfo->mFFITypes.begin());
switch (status) {
case FFI_OK:
return true;
case FFI_BAD_ABI:
JS_ReportErrorASCII(cx, "Invalid ABI specification");
return false;
case FFI_BAD_TYPEDEF:
JS_ReportErrorASCII(cx, "Invalid type specification");
return false;
default:
JS_ReportErrorASCII(cx, "Unknown libffi error");
return false;
}
}
void
FunctionType::BuildSymbolName(JSString* name,
JSObject* typeObj,
AutoCString& result)
{
FunctionInfo* fninfo = GetFunctionInfo(typeObj);
switch (GetABICode(fninfo->mABI)) {
case ABI_DEFAULT:
case ABI_THISCALL:
case ABI_WINAPI:
// For cdecl or WINAPI functions, no mangling is necessary.
AppendString(result, name);
break;
case ABI_STDCALL: {
#if (defined(_WIN32) && !defined(_WIN64)) || defined(_OS2)
// On WIN32, stdcall functions look like:
// _foo@40
// where 'foo' is the function name, and '40' is the aligned size of the
// arguments.
AppendString(result, "_");
AppendString(result, name);
AppendString(result, "@");
// Compute the suffix by aligning each argument to sizeof(ffi_arg).
size_t size = 0;
for (size_t i = 0; i < fninfo->mArgTypes.length(); ++i) {
JSObject* argType = fninfo->mArgTypes[i];
size += Align(CType::GetSize(argType), sizeof(ffi_arg));
}
IntegerToString(size, 10, result);
#elif defined(_WIN64)
// On Win64, stdcall is an alias to the default ABI for compatibility, so no
// mangling is done.
AppendString(result, name);
#endif
break;
}
case INVALID_ABI:
MOZ_CRASH("invalid abi");
}
}
static bool
CreateFunctionInfo(JSContext* cx,
HandleObject typeObj,
HandleValue abiType,
HandleObject returnType,
const HandleValueArray& args)
{
FunctionInfo* fninfo(cx->new_<FunctionInfo>());
if (!fninfo) {
JS_ReportOutOfMemory(cx);
return false;
}
// Stash the FunctionInfo in a reserved slot.
JS_SetReservedSlot(typeObj, SLOT_FNINFO, PrivateValue(fninfo));
ffi_abi abi;
if (!GetABI(cx, abiType, &abi)) {
JS_ReportErrorASCII(cx, "Invalid ABI specification");
return false;
}
fninfo->mABI = abiType.toObjectOrNull();
fninfo->mReturnType = returnType;
// prepare the argument types
if (!fninfo->mArgTypes.reserve(args.length()) ||
!fninfo->mFFITypes.reserve(args.length())) {
JS_ReportOutOfMemory(cx);
return false;
}
fninfo->mIsVariadic = false;
for (uint32_t i = 0; i < args.length(); ++i) {
bool isEllipsis;
if (!IsEllipsis(cx, args[i], &isEllipsis))
return false;
if (isEllipsis) {
fninfo->mIsVariadic = true;
if (i < 1) {
JS_ReportErrorASCII(cx, "\"...\" may not be the first and only parameter "
"type of a variadic function declaration");
return false;
}
if (i < args.length() - 1) {
JS_ReportErrorASCII(cx, "\"...\" must be the last parameter type of a "
"variadic function declaration");
return false;
}
if (GetABICode(fninfo->mABI) != ABI_DEFAULT) {
JS_ReportErrorASCII(cx, "Variadic functions must use the __cdecl calling "
"convention");
return false;
}
break;
}
JSObject* argType = PrepareType(cx, i, args[i]);
if (!argType)
return false;
ffi_type* ffiType = CType::GetFFIType(cx, argType);
if (!ffiType)
return false;
fninfo->mArgTypes.infallibleAppend(argType);
fninfo->mFFITypes.infallibleAppend(ffiType);
}
if (fninfo->mIsVariadic) {
// wait to PrepareCIF until function is called
return true;
}
if (!PrepareCIF(cx, fninfo))
return false;
return true;
}
bool
FunctionType::Create(JSContext* cx, unsigned argc, Value* vp)
{
// Construct and return a new FunctionType object.
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() < 2 || args.length() > 3) {
return ArgumentLengthError(cx, "FunctionType", "two or three", "s");
}
AutoValueVector argTypes(cx);
RootedObject arrayObj(cx, nullptr);
if (args.length() == 3) {
// Prepare an array of Values for the arguments.
bool isArray;
if (!args[2].isObject()) {
isArray = false;
} else {
if (!JS_IsArrayObject(cx, args[2], &isArray))
return false;
}
if (!isArray)
return ArgumentTypeMismatch(cx, "third ", "FunctionType", "an array");
arrayObj = &args[2].toObject();
uint32_t len;
ASSERT_OK(JS_GetArrayLength(cx, arrayObj, &len));
if (!argTypes.resize(len)) {
JS_ReportOutOfMemory(cx);
return false;
}
}
// Pull out the argument types from the array, if any.
MOZ_ASSERT_IF(argTypes.length(), arrayObj);
for (uint32_t i = 0; i < argTypes.length(); ++i) {
if (!JS_GetElement(cx, arrayObj, i, argTypes[i]))
return false;
}
JSObject* result = CreateInternal(cx, args[0], args[1], argTypes);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
JSObject*
FunctionType::CreateInternal(JSContext* cx,
HandleValue abi,
HandleValue rtype,
const HandleValueArray& args)
{
// Prepare the result type
RootedObject returnType(cx, PrepareReturnType(cx, rtype));
if (!returnType)
return nullptr;
// Get ctypes.FunctionType.prototype and the common prototype for CData objects
// of this type, from ctypes.CType.prototype.
RootedObject typeProto(cx, CType::GetProtoFromType(cx, returnType, SLOT_FUNCTIONPROTO));
if (!typeProto)
return nullptr;
RootedObject dataProto(cx, CType::GetProtoFromType(cx, returnType, SLOT_FUNCTIONDATAPROTO));
if (!dataProto)
return nullptr;
// Create a new CType object with the common properties and slots.
RootedObject typeObj(cx, CType::Create(cx, typeProto, dataProto, TYPE_function,
nullptr, JS::UndefinedHandleValue,
JS::UndefinedHandleValue, nullptr));
if (!typeObj)
return nullptr;
// Determine and check the types, and prepare the function CIF.
if (!CreateFunctionInfo(cx, typeObj, abi, returnType, args))
return nullptr;
return typeObj;
}
// Construct a function pointer to a JS function (see CClosure::Create()).
// Regular function pointers are constructed directly in
// PointerType::ConstructData().
bool
FunctionType::ConstructData(JSContext* cx,
HandleObject typeObj,
HandleObject dataObj,
HandleObject fnObj,
HandleObject thisObj,
HandleValue errVal)
{
MOZ_ASSERT(CType::GetTypeCode(typeObj) == TYPE_function);
PRFuncPtr* data = static_cast<PRFuncPtr*>(CData::GetData(dataObj));
FunctionInfo* fninfo = FunctionType::GetFunctionInfo(typeObj);
if (fninfo->mIsVariadic) {
JS_ReportErrorASCII(cx, "Can't declare a variadic callback function");
return false;
}
if (GetABICode(fninfo->mABI) == ABI_WINAPI) {
JS_ReportErrorASCII(cx, "Can't declare a ctypes.winapi_abi callback function, "
"use ctypes.stdcall_abi instead");
return false;
}
RootedObject closureObj(cx, CClosure::Create(cx, typeObj, fnObj, thisObj, errVal, data));
if (!closureObj)
return false;
// Set the closure object as the referent of the new CData object.
JS_SetReservedSlot(dataObj, SLOT_REFERENT, ObjectValue(*closureObj));
// Seal the CData object, to prevent modification of the function pointer.
// This permanently associates this object with the closure, and avoids
// having to do things like reset SLOT_REFERENT when someone tries to
// change the pointer value.
// XXX This will need to change when bug 541212 is fixed -- CData::ValueSetter
// could be called on a frozen object.
return JS_FreezeObject(cx, dataObj);
}
typedef Vector<AutoValue, 16, SystemAllocPolicy> AutoValueAutoArray;
static bool
ConvertArgument(JSContext* cx,
HandleObject funObj,
unsigned argIndex,
HandleValue arg,
JSObject* type,
AutoValue* value,
AutoValueAutoArray* strings)
{
if (!value->SizeToType(cx, type)) {
JS_ReportAllocationOverflow(cx);
return false;
}
bool freePointer = false;
if (!ImplicitConvert(cx, arg, type, value->mData,
ConversionType::Argument, &freePointer,
funObj, argIndex))
return false;
if (freePointer) {
// ImplicitConvert converted a string for us, which we have to free.
// Keep track of it.
if (!strings->growBy(1)) {
JS_ReportOutOfMemory(cx);
return false;
}
strings->back().mData = *static_cast<char**>(value->mData);
}
return true;
}
bool
FunctionType::Call(JSContext* cx,
unsigned argc,
Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// get the callee object...
RootedObject obj(cx, &args.callee());
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "FunctionType.prototype.call",
args.calleev());
}
RootedObject typeObj(cx, CData::GetCType(obj));
if (CType::GetTypeCode(typeObj) != TYPE_pointer) {
return IncompatibleThisType(cx, "FunctionType.prototype.call",
"non-PointerType CData", args.calleev());
}
typeObj = PointerType::GetBaseType(typeObj);
if (CType::GetTypeCode(typeObj) != TYPE_function) {
return IncompatibleThisType(cx, "FunctionType.prototype.call",
"non-FunctionType pointer", args.calleev());
}
FunctionInfo* fninfo = GetFunctionInfo(typeObj);
uint32_t argcFixed = fninfo->mArgTypes.length();
if ((!fninfo->mIsVariadic && args.length() != argcFixed) ||
(fninfo->mIsVariadic && args.length() < argcFixed)) {
return FunctionArgumentLengthMismatch(cx, argcFixed, args.length(),
obj, typeObj, fninfo->mIsVariadic);
}
// Check if we have a Library object. If we do, make sure it's open.
Value slot = JS_GetReservedSlot(obj, SLOT_REFERENT);
if (!slot.isUndefined() && Library::IsLibrary(&slot.toObject())) {
PRLibrary* library = Library::GetLibrary(&slot.toObject());
if (!library) {
JS_ReportErrorASCII(cx, "library is not open");
return false;
}
}
// prepare the values for each argument
AutoValueAutoArray values;
AutoValueAutoArray strings;
if (!values.resize(args.length())) {
JS_ReportOutOfMemory(cx);
return false;
}
for (unsigned i = 0; i < argcFixed; ++i)
if (!ConvertArgument(cx, obj, i, args[i], fninfo->mArgTypes[i],
&values[i], &strings))
return false;
if (fninfo->mIsVariadic) {
if (!fninfo->mFFITypes.resize(args.length())) {
JS_ReportOutOfMemory(cx);
return false;
}
RootedObject obj(cx); // Could reuse obj instead of declaring a second
RootedObject type(cx); // RootedObject, but readability would suffer.
for (uint32_t i = argcFixed; i < args.length(); ++i) {
if (args[i].isPrimitive() ||
!CData::IsCData(obj = &args[i].toObject())) {
// Since we know nothing about the CTypes of the ... arguments,
// they absolutely must be CData objects already.
return VariadicArgumentTypeError(cx, i, args[i]);
}
type = CData::GetCType(obj);
if (!type) {
// These functions report their own errors.
return false;
}
RootedValue typeVal(cx, ObjectValue(*type));
type = PrepareType(cx, i, typeVal);
if (!type) {
return false;
}
// Relying on ImplicitConvert only for the limited purpose of
// converting one CType to another (e.g., T[] to T*).
if (!ConvertArgument(cx, obj, i, args[i], type, &values[i], &strings)) {
return false;
}
fninfo->mFFITypes[i] = CType::GetFFIType(cx, type);
if (!fninfo->mFFITypes[i]) {
return false;
}
}
if (!PrepareCIF(cx, fninfo))
return false;
}
// initialize a pointer to an appropriate location, for storing the result
AutoValue returnValue;
TypeCode typeCode = CType::GetTypeCode(fninfo->mReturnType);
if (typeCode != TYPE_void_t &&
!returnValue.SizeToType(cx, fninfo->mReturnType)) {
JS_ReportAllocationOverflow(cx);
return false;
}
// Let the runtime callback know that we are about to call into C.
js::AutoCTypesActivityCallback autoCallback(cx, js::CTYPES_CALL_BEGIN, js::CTYPES_CALL_END);
uintptr_t fn = *reinterpret_cast<uintptr_t*>(CData::GetData(obj));
#if defined(XP_WIN)
int32_t lastErrorStatus; // The status as defined by |GetLastError|
int32_t savedLastError = GetLastError();
SetLastError(0);
#endif //defined(XP_WIN)
int errnoStatus; // The status as defined by |errno|
int savedErrno = errno;
errno = 0;
ffi_call(&fninfo->mCIF, FFI_FN(fn), returnValue.mData,
reinterpret_cast<void**>(values.begin()));
// Save error value.
// We need to save it before leaving the scope of |suspend| as destructing
// |suspend| has the side-effect of clearing |GetLastError|
// (see bug 684017).
errnoStatus = errno;
#if defined(XP_WIN)
lastErrorStatus = GetLastError();
SetLastError(savedLastError);
#endif // defined(XP_WIN)
errno = savedErrno;
// We're no longer calling into C.
autoCallback.DoEndCallback();
// Store the error value for later consultation with |ctypes.getStatus|
JSObject* objCTypes = CType::GetGlobalCTypes(cx, typeObj);
if (!objCTypes)
return false;
JS_SetReservedSlot(objCTypes, SLOT_ERRNO, Int32Value(errnoStatus));
#if defined(XP_WIN)
JS_SetReservedSlot(objCTypes, SLOT_LASTERROR, Int32Value(lastErrorStatus));
#endif // defined(XP_WIN)
// Small integer types get returned as a word-sized ffi_arg. Coerce it back
// into the correct size for ConvertToJS.
switch (typeCode) {
#define INTEGRAL_CASE(name, type, ffiType) \
case TYPE_##name: \
if (sizeof(type) < sizeof(ffi_arg)) { \
ffi_arg data = *static_cast<ffi_arg*>(returnValue.mData); \
*static_cast<type*>(returnValue.mData) = static_cast<type>(data); \
} \
break;
CTYPES_FOR_EACH_INT_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_WRAPPED_INT_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_BOOL_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_CHAR_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_CHAR16_TYPE(INTEGRAL_CASE)
#undef INTEGRAL_CASE
default:
break;
}
// prepare a JS object from the result
RootedObject returnType(cx, fninfo->mReturnType);
return ConvertToJS(cx, returnType, nullptr, returnValue.mData, false, true, args.rval());
}
FunctionInfo*
FunctionType::GetFunctionInfo(JSObject* obj)
{
MOZ_ASSERT(CType::IsCType(obj));
MOZ_ASSERT(CType::GetTypeCode(obj) == TYPE_function);
Value slot = JS_GetReservedSlot(obj, SLOT_FNINFO);
MOZ_ASSERT(!slot.isUndefined() && slot.toPrivate());
return static_cast<FunctionInfo*>(slot.toPrivate());
}
bool
FunctionType::IsFunctionType(HandleValue v)
{
if (!v.isObject())
return false;
JSObject* obj = &v.toObject();
return CType::IsCType(obj) && CType::GetTypeCode(obj) == TYPE_function;
}
bool
FunctionType::ArgTypesGetter(JSContext* cx, const JS::CallArgs& args)
{
JS::Rooted<JSObject*> obj(cx, &args.thisv().toObject());
args.rval().set(JS_GetReservedSlot(obj, SLOT_ARGS_T));
if (!args.rval().isUndefined())
return true;
FunctionInfo* fninfo = GetFunctionInfo(obj);
size_t len = fninfo->mArgTypes.length();
// Prepare a new array.
JS::Rooted<JSObject*> argTypes(cx);
{
JS::AutoValueVector vec(cx);
if (!vec.resize(len))
return false;
for (size_t i = 0; i < len; ++i)
vec[i].setObject(*fninfo->mArgTypes[i]);
argTypes = JS_NewArrayObject(cx, vec);
if (!argTypes)
return false;
}
// Seal and cache it.
if (!JS_FreezeObject(cx, argTypes))
return false;
JS_SetReservedSlot(obj, SLOT_ARGS_T, JS::ObjectValue(*argTypes));
args.rval().setObject(*argTypes);
return true;
}
bool
FunctionType::ReturnTypeGetter(JSContext* cx, const JS::CallArgs& args)
{
// Get the returnType object from the FunctionInfo.
args.rval().setObject(*GetFunctionInfo(&args.thisv().toObject())->mReturnType);
return true;
}
bool
FunctionType::ABIGetter(JSContext* cx, const JS::CallArgs& args)
{
// Get the abi object from the FunctionInfo.
args.rval().setObject(*GetFunctionInfo(&args.thisv().toObject())->mABI);
return true;
}
bool
FunctionType::IsVariadicGetter(JSContext* cx, const JS::CallArgs& args)
{
args.rval().setBoolean(GetFunctionInfo(&args.thisv().toObject())->mIsVariadic);
return true;
}
/*******************************************************************************
** CClosure implementation
*******************************************************************************/
JSObject*
CClosure::Create(JSContext* cx,
HandleObject typeObj,
HandleObject fnObj,
HandleObject thisObj,
HandleValue errVal,
PRFuncPtr* fnptr)
{
MOZ_ASSERT(fnObj);
RootedObject result(cx, JS_NewObject(cx, &sCClosureClass));
if (!result)
return nullptr;
// Get the FunctionInfo from the FunctionType.
FunctionInfo* fninfo = FunctionType::GetFunctionInfo(typeObj);
MOZ_ASSERT(!fninfo->mIsVariadic);
MOZ_ASSERT(GetABICode(fninfo->mABI) != ABI_WINAPI);
// Get the prototype of the FunctionType object, of class CTypeProto,
// which stores our JSContext for use with the closure.
RootedObject proto(cx);
if (!JS_GetPrototype(cx, typeObj, &proto))
return nullptr;
MOZ_ASSERT(proto);
MOZ_ASSERT(CType::IsCTypeProto(proto));
// Prepare the error sentinel value. It's important to do this now, because
// we might be unable to convert the value to the proper type. If so, we want
// the caller to know about it _now_, rather than some uncertain time in the
// future when the error sentinel is actually needed.
UniquePtr<uint8_t[], JS::FreePolicy> errResult;
if (!errVal.isUndefined()) {
// Make sure the callback returns something.
if (CType::GetTypeCode(fninfo->mReturnType) == TYPE_void_t) {
JS_ReportErrorASCII(cx, "A void callback can't pass an error sentinel");
return nullptr;
}
// With the exception of void, the FunctionType constructor ensures that
// the return type has a defined size.
MOZ_ASSERT(CType::IsSizeDefined(fninfo->mReturnType));
// Allocate a buffer for the return value.
size_t rvSize = CType::GetSize(fninfo->mReturnType);
errResult = result->zone()->make_pod_array<uint8_t>(rvSize);
if (!errResult)
return nullptr;
// Do the value conversion. This might fail, in which case we throw.
if (!ImplicitConvert(cx, errVal, fninfo->mReturnType, errResult.get(),
ConversionType::Return, nullptr, typeObj))
return nullptr;
}
ClosureInfo* cinfo = cx->new_<ClosureInfo>(cx);
if (!cinfo) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
// Copy the important bits of context into cinfo.
cinfo->errResult = errResult.release();
cinfo->closureObj = result;
cinfo->typeObj = typeObj;
cinfo->thisObj = thisObj;
cinfo->jsfnObj = fnObj;
// Stash the ClosureInfo struct on our new object.
JS_SetReservedSlot(result, SLOT_CLOSUREINFO, PrivateValue(cinfo));
// Create an ffi_closure object and initialize it.
void* code;
cinfo->closure =
static_cast<ffi_closure*>(ffi_closure_alloc(sizeof(ffi_closure), &code));
if (!cinfo->closure || !code) {
JS_ReportErrorASCII(cx, "couldn't create closure - libffi error");
return nullptr;
}
ffi_status status = ffi_prep_closure_loc(cinfo->closure, &fninfo->mCIF,
CClosure::ClosureStub, cinfo, code);
if (status != FFI_OK) {
JS_ReportErrorASCII(cx, "couldn't create closure - libffi error");
return nullptr;
}
// Casting between void* and a function pointer is forbidden in C and C++.
// Do it via an integral type.
*fnptr = reinterpret_cast<PRFuncPtr>(reinterpret_cast<uintptr_t>(code));
return result;
}
void
CClosure::Trace(JSTracer* trc, JSObject* obj)
{
// Make sure our ClosureInfo slot is legit. If it's not, bail.
Value slot = JS_GetReservedSlot(obj, SLOT_CLOSUREINFO);
if (slot.isUndefined())
return;
ClosureInfo* cinfo = static_cast<ClosureInfo*>(slot.toPrivate());
// Identify our objects to the tracer. (There's no need to identify
// 'closureObj', since that's us.)
JS::TraceEdge(trc, &cinfo->typeObj, "typeObj");
JS::TraceEdge(trc, &cinfo->jsfnObj, "jsfnObj");
if (cinfo->thisObj)
JS::TraceEdge(trc, &cinfo->thisObj, "thisObj");
}
void
CClosure::Finalize(JSFreeOp* fop, JSObject* obj)
{
// Make sure our ClosureInfo slot is legit. If it's not, bail.
Value slot = JS_GetReservedSlot(obj, SLOT_CLOSUREINFO);
if (slot.isUndefined())
return;
ClosureInfo* cinfo = static_cast<ClosureInfo*>(slot.toPrivate());
FreeOp::get(fop)->delete_(cinfo);
}
void
CClosure::ClosureStub(ffi_cif* cif, void* result, void** args, void* userData)
{
MOZ_ASSERT(cif);
MOZ_ASSERT(result);
MOZ_ASSERT(args);
MOZ_ASSERT(userData);
// Retrieve the essentials from our closure object.
ArgClosure argClosure(cif, result, args, static_cast<ClosureInfo*>(userData));
JSContext* cx = argClosure.cinfo->cx;
RootedObject fun(cx, argClosure.cinfo->jsfnObj);
js::PrepareScriptEnvironmentAndInvoke(cx, fun, argClosure);
}
bool CClosure::ArgClosure::operator()(JSContext* cx)
{
// Let the runtime callback know that we are about to call into JS again. The end callback will
// fire automatically when we exit this function.
js::AutoCTypesActivityCallback autoCallback(cx, js::CTYPES_CALLBACK_BEGIN,
js::CTYPES_CALLBACK_END);
RootedObject typeObj(cx, cinfo->typeObj);
RootedObject thisObj(cx, cinfo->thisObj);
RootedValue jsfnVal(cx, ObjectValue(*cinfo->jsfnObj));
AssertSameCompartment(cx, cinfo->jsfnObj);
JS_AbortIfWrongThread(cx);
// Assert that our CIFs agree.
FunctionInfo* fninfo = FunctionType::GetFunctionInfo(typeObj);
MOZ_ASSERT(cif == &fninfo->mCIF);
TypeCode typeCode = CType::GetTypeCode(fninfo->mReturnType);
// Initialize the result to zero, in case something fails. Small integer types
// are promoted to a word-sized ffi_arg, so we must be careful to zero the
// whole word.
size_t rvSize = 0;
if (cif->rtype != &ffi_type_void) {
rvSize = cif->rtype->size;
switch (typeCode) {
#define INTEGRAL_CASE(name, type, ffiType) case TYPE_##name:
CTYPES_FOR_EACH_INT_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_WRAPPED_INT_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_BOOL_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_CHAR_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_CHAR16_TYPE(INTEGRAL_CASE)
#undef INTEGRAL_CASE
rvSize = Align(rvSize, sizeof(ffi_arg));
break;
default:
break;
}
memset(result, 0, rvSize);
}
// Set up an array for converted arguments.
JS::AutoValueVector argv(cx);
if (!argv.resize(cif->nargs)) {
JS_ReportOutOfMemory(cx);
return false;
}
for (uint32_t i = 0; i < cif->nargs; ++i) {
// Convert each argument, and have any CData objects created depend on
// the existing buffers.
RootedObject argType(cx, fninfo->mArgTypes[i]);
if (!ConvertToJS(cx, argType, nullptr, args[i], false, false, argv[i]))
return false;
}
// Call the JS function. 'thisObj' may be nullptr, in which case the JS
// engine will find an appropriate object to use.
RootedValue rval(cx);
bool success = JS_CallFunctionValue(cx, thisObj, jsfnVal, argv, &rval);
// Convert the result. Note that we pass 'ConversionType::Return', such that
// ImplicitConvert will *not* autoconvert a JS string into a pointer-to-char
// type, which would require an allocation that we can't track. The JS
// function must perform this conversion itself and return a PointerType
// CData; thusly, the burden of freeing the data is left to the user.
if (success && cif->rtype != &ffi_type_void)
success = ImplicitConvert(cx, rval, fninfo->mReturnType, result,
ConversionType::Return, nullptr, typeObj);
if (!success) {
// Something failed. The callee may have thrown, or it may not have
// returned a value that ImplicitConvert() was happy with. Depending on how
// prudent the consumer has been, we may or may not have a recovery plan.
//
// Note that PrepareScriptEnvironmentAndInvoke should take care of reporting
// the exception.
if (cinfo->errResult) {
// Good case: we have a sentinel that we can return. Copy it in place of
// the actual return value, and then proceed.
// The buffer we're returning might be larger than the size of the return
// type, due to libffi alignment issues (see above). But it should never
// be smaller.
size_t copySize = CType::GetSize(fninfo->mReturnType);
MOZ_ASSERT(copySize <= rvSize);
memcpy(result, cinfo->errResult, copySize);
// We still want to return false here, so that
// PrepareScriptEnvironmentAndInvoke will report the exception.
} else {
// Bad case: not much we can do here. The rv is already zeroed out, so we
// just return and hope for the best.
}
return false;
}
// Small integer types must be returned as a word-sized ffi_arg. Coerce it
// back into the size libffi expects.
switch (typeCode) {
#define INTEGRAL_CASE(name, type, ffiType) \
case TYPE_##name: \
if (sizeof(type) < sizeof(ffi_arg)) { \
ffi_arg data = *static_cast<type*>(result); \
*static_cast<ffi_arg*>(result) = data; \
} \
break;
CTYPES_FOR_EACH_INT_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_WRAPPED_INT_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_BOOL_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_CHAR_TYPE(INTEGRAL_CASE)
CTYPES_FOR_EACH_CHAR16_TYPE(INTEGRAL_CASE)
#undef INTEGRAL_CASE
default:
break;
}
return true;
}
/*******************************************************************************
** CData implementation
*******************************************************************************/
// Create a new CData object of type 'typeObj' containing binary data supplied
// in 'source', optionally with a referent object 'refObj'.
//
// * 'typeObj' must be a CType of defined (but possibly zero) size.
//
// * If an object 'refObj' is supplied, the new CData object stores the
// referent object in a reserved slot for GC safety, such that 'refObj' will
// be held alive by the resulting CData object. 'refObj' may or may not be
// a CData object; merely an object we want to keep alive.
// * If 'refObj' is a CData object, 'ownResult' must be false.
// * Otherwise, 'refObj' is a Library or CClosure object, and 'ownResult'
// may be true or false.
// * Otherwise 'refObj' is nullptr. In this case, 'ownResult' may be true or
// false.
//
// * If 'ownResult' is true, the CData object will allocate an appropriately
// sized buffer, and free it upon finalization. If 'source' data is
// supplied, the data will be copied from 'source' into the buffer;
// otherwise, the entirety of the new buffer will be initialized to zero.
// * If 'ownResult' is false, the new CData's buffer refers to a slice of
// another buffer kept alive by 'refObj'. 'source' data must be provided,
// and the new CData's buffer will refer to 'source'.
JSObject*
CData::Create(JSContext* cx,
HandleObject typeObj,
HandleObject refObj,
void* source,
bool ownResult)
{
MOZ_ASSERT(typeObj);
MOZ_ASSERT(CType::IsCType(typeObj));
MOZ_ASSERT(CType::IsSizeDefined(typeObj));
MOZ_ASSERT(ownResult || source);
MOZ_ASSERT_IF(refObj && CData::IsCData(refObj), !ownResult);
// Get the 'prototype' property from the type.
Value slot = JS_GetReservedSlot(typeObj, SLOT_PROTO);
MOZ_ASSERT(slot.isObject());
RootedObject proto(cx, &slot.toObject());
RootedObject dataObj(cx, JS_NewObjectWithGivenProto(cx, &sCDataClass, proto));
if (!dataObj)
return nullptr;
// set the CData's associated type
JS_SetReservedSlot(dataObj, SLOT_CTYPE, ObjectValue(*typeObj));
// Stash the referent object, if any, for GC safety.
if (refObj)
JS_SetReservedSlot(dataObj, SLOT_REFERENT, ObjectValue(*refObj));
// Set our ownership flag.
JS_SetReservedSlot(dataObj, SLOT_OWNS, BooleanValue(ownResult));
// attach the buffer. since it might not be 2-byte aligned, we need to
// allocate an aligned space for it and store it there. :(
char** buffer = cx->new_<char*>();
if (!buffer) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
char* data;
if (!ownResult) {
data = static_cast<char*>(source);
} else {
// Initialize our own buffer.
size_t size = CType::GetSize(typeObj);
data = dataObj->zone()->pod_malloc<char>(size);
if (!data) {
// Report a catchable allocation error.
JS_ReportAllocationOverflow(cx);
js_free(buffer);
return nullptr;
}
if (!source)
memset(data, 0, size);
else
memcpy(data, source, size);
}
*buffer = data;
JS_SetReservedSlot(dataObj, SLOT_DATA, PrivateValue(buffer));
return dataObj;
}
void
CData::Finalize(JSFreeOp* fop, JSObject* obj)
{
// Delete our buffer, and the data it contains if we own it.
Value slot = JS_GetReservedSlot(obj, SLOT_OWNS);
if (slot.isUndefined())
return;
bool owns = slot.toBoolean();
slot = JS_GetReservedSlot(obj, SLOT_DATA);
if (slot.isUndefined())
return;
char** buffer = static_cast<char**>(slot.toPrivate());
if (owns)
FreeOp::get(fop)->free_(*buffer);
FreeOp::get(fop)->delete_(buffer);
}
JSObject*
CData::GetCType(JSObject* dataObj)
{
MOZ_ASSERT(CData::IsCData(dataObj));
Value slot = JS_GetReservedSlot(dataObj, SLOT_CTYPE);
JSObject* typeObj = slot.toObjectOrNull();
MOZ_ASSERT(CType::IsCType(typeObj));
return typeObj;
}
void*
CData::GetData(JSObject* dataObj)
{
MOZ_ASSERT(CData::IsCData(dataObj));
Value slot = JS_GetReservedSlot(dataObj, SLOT_DATA);
void** buffer = static_cast<void**>(slot.toPrivate());
MOZ_ASSERT(buffer);
MOZ_ASSERT(*buffer);
return *buffer;
}
bool
CData::IsCData(JSObject* obj)
{
return JS_GetClass(obj) == &sCDataClass;
}
bool
CData::IsCData(HandleValue v)
{
return v.isObject() && CData::IsCData(&v.toObject());
}
bool
CData::IsCDataProto(JSObject* obj)
{
return JS_GetClass(obj) == &sCDataProtoClass;
}
bool
CData::ValueGetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
// Convert the value to a primitive; do not create a new CData object.
RootedObject ctype(cx, GetCType(obj));
return ConvertToJS(cx, ctype, nullptr, GetData(obj), true, false, args.rval());
}
bool
CData::ValueSetter(JSContext* cx, const JS::CallArgs& args)
{
RootedObject obj(cx, &args.thisv().toObject());
args.rval().setUndefined();
return ImplicitConvert(cx, args.get(0), GetCType(obj), GetData(obj),
ConversionType::Setter, nullptr);
}
bool
CData::Address(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 0) {
return ArgumentLengthError(cx, "CData.prototype.address", "no", "s");
}
RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
if (!obj)
return false;
if (!IsCData(obj)) {
return IncompatibleThisProto(cx, "CData.prototype.address", args.thisv());
}
RootedObject typeObj(cx, CData::GetCType(obj));
RootedObject pointerType(cx, PointerType::CreateInternal(cx, typeObj));
if (!pointerType)
return false;
// Create a PointerType CData object containing null.
JSObject* result = CData::Create(cx, pointerType, nullptr, nullptr, true);
if (!result)
return false;
args.rval().setObject(*result);
// Manually set the pointer inside the object, so we skip the conversion step.
void** data = static_cast<void**>(GetData(result));
*data = GetData(obj);
return true;
}
bool
CData::Cast(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 2) {
return ArgumentLengthError(cx, "ctypes.cast", "two", "s");
}
if (args[0].isPrimitive() || !CData::IsCData(&args[0].toObject())) {
return ArgumentTypeMismatch(cx, "first ", "ctypes.cast", "a CData");
}
RootedObject sourceData(cx, &args[0].toObject());
RootedObject sourceType(cx, CData::GetCType(sourceData));
if (args[1].isPrimitive() || !CType::IsCType(&args[1].toObject())) {
return ArgumentTypeMismatch(cx, "second ", "ctypes.cast", "a CType");
}
RootedObject targetType(cx, &args[1].toObject());
size_t targetSize;
if (!CType::GetSafeSize(targetType, &targetSize)) {
return UndefinedSizeCastError(cx, targetType);
}
if (targetSize > CType::GetSize(sourceType)) {
return SizeMismatchCastError(cx, sourceType, targetType,
CType::GetSize(sourceType), targetSize);
}
// Construct a new CData object with a type of 'targetType' and a referent
// of 'sourceData'.
void* data = CData::GetData(sourceData);
JSObject* result = CData::Create(cx, targetType, sourceData, data, false);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
bool
CData::GetRuntime(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 1) {
return ArgumentLengthError(cx, "ctypes.getRuntime", "one", "");
}
if (args[0].isPrimitive() || !CType::IsCType(&args[0].toObject())) {
return ArgumentTypeMismatch(cx, "", "ctypes.getRuntime", "a CType");
}
RootedObject targetType(cx, &args[0].toObject());
size_t targetSize;
if (!CType::GetSafeSize(targetType, &targetSize) ||
targetSize != sizeof(void*)) {
JS_ReportErrorASCII(cx, "target CType has non-pointer size");
return false;
}
void* data = static_cast<void*>(cx->runtime());
JSObject* result = CData::Create(cx, targetType, nullptr, &data, true);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
typedef JS::TwoByteCharsZ (*InflateUTF8Method)(JSContext*, const JS::UTF8Chars, size_t*);
static bool
ReadStringCommon(JSContext* cx, InflateUTF8Method inflateUTF8, unsigned argc,
Value* vp, const char* funName)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 0) {
return ArgumentLengthError(cx, funName, "no", "s");
}
RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
if (!obj) {
return IncompatibleThisProto(cx, funName, args.thisv());
}
if (!CData::IsCData(obj)) {
if (!CDataFinalizer::IsCDataFinalizer(obj)) {
return IncompatibleThisProto(cx, funName, args.thisv());
}
CDataFinalizer::Private* p = (CDataFinalizer::Private*)
JS_GetPrivate(obj);
if (!p) {
return EmptyFinalizerCallError(cx, funName);
}
RootedValue dataVal(cx);
if (!CDataFinalizer::GetValue(cx, obj, &dataVal)) {
return IncompatibleThisProto(cx, funName, args.thisv());
}
if (dataVal.isPrimitive()) {
return IncompatibleThisProto(cx, funName, args.thisv());
}
obj = dataVal.toObjectOrNull();
if (!obj || !CData::IsCData(obj)) {
return IncompatibleThisProto(cx, funName, args.thisv());
}
}
// Make sure we are a pointer to, or an array of, an 8-bit or 16-bit
// character or integer type.
JSObject* baseType;
JSObject* typeObj = CData::GetCType(obj);
TypeCode typeCode = CType::GetTypeCode(typeObj);
void* data;
size_t maxLength = -1;
switch (typeCode) {
case TYPE_pointer:
baseType = PointerType::GetBaseType(typeObj);
data = *static_cast<void**>(CData::GetData(obj));
if (data == nullptr) {
return NullPointerError(cx, "read contents of", obj);
}
break;
case TYPE_array:
baseType = ArrayType::GetBaseType(typeObj);
data = CData::GetData(obj);
maxLength = ArrayType::GetLength(typeObj);
break;
default:
return TypeError(cx, "PointerType or ArrayType", args.thisv());
}
// Convert the string buffer, taking care to determine the correct string
// length in the case of arrays (which may contain embedded nulls).
JSString* result;
switch (CType::GetTypeCode(baseType)) {
case TYPE_int8_t:
case TYPE_uint8_t:
case TYPE_char:
case TYPE_signed_char:
case TYPE_unsigned_char: {
char* bytes = static_cast<char*>(data);
size_t length = strnlen(bytes, maxLength);
// Determine the length.
char16_t* dst = inflateUTF8(cx, JS::UTF8Chars(bytes, length), &length).get();
if (!dst)
return false;
result = JS_NewUCString(cx, dst, length);
if (!result) {
js_free(dst);
return false;
}
break;
}
case TYPE_int16_t:
case TYPE_uint16_t:
case TYPE_short:
case TYPE_unsigned_short:
case TYPE_char16_t: {
char16_t* chars = static_cast<char16_t*>(data);
size_t length = strnlen(chars, maxLength);
result = JS_NewUCStringCopyN(cx, chars, length);
break;
}
default:
return NonStringBaseError(cx, args.thisv());
}
if (!result)
return false;
args.rval().setString(result);
return true;
}
bool
CData::ReadString(JSContext* cx, unsigned argc, Value* vp)
{
return ReadStringCommon(cx, JS::UTF8CharsToNewTwoByteCharsZ, argc, vp,
"CData.prototype.readString");
}
bool
CDataFinalizer::Methods::ReadString(JSContext* cx, unsigned argc, Value* vp)
{
return ReadStringCommon(cx, JS::UTF8CharsToNewTwoByteCharsZ, argc, vp,
"CDataFinalizer.prototype.readString");
}
bool
CData::ReadStringReplaceMalformed(JSContext* cx, unsigned argc, Value* vp)
{
return ReadStringCommon(cx, JS::LossyUTF8CharsToNewTwoByteCharsZ, argc, vp,
"CData.prototype.readStringReplaceMalformed");
}
JSString*
CData::GetSourceString(JSContext* cx, HandleObject typeObj, void* data)
{
// Walk the types, building up the toSource() string.
// First, we build up the type expression:
// 't.ptr' for pointers;
// 't.array([n])' for arrays;
// 'n' for structs, where n = t.name, the struct's name. (We assume this is
// bound to a variable in the current scope.)
AutoString source;
BuildTypeSource(cx, typeObj, true, source);
AppendString(source, "(");
if (!BuildDataSource(cx, typeObj, data, false, source))
return nullptr;
AppendString(source, ")");
return NewUCString(cx, source);
}
bool
CData::ToSource(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 0) {
return ArgumentLengthError(cx, "CData.prototype.toSource", "no", "s");
}
JSObject* obj = JS_THIS_OBJECT(cx, vp);
if (!obj)
return false;
if (!CData::IsCData(obj) && !CData::IsCDataProto(obj)) {
return IncompatibleThisProto(cx, "CData.prototype.toSource",
InformalValueTypeName(args.thisv()));
}
JSString* result;
if (CData::IsCData(obj)) {
RootedObject typeObj(cx, CData::GetCType(obj));
void* data = CData::GetData(obj);
result = CData::GetSourceString(cx, typeObj, data);
} else {
result = JS_NewStringCopyZ(cx, "[CData proto object]");
}
if (!result)
return false;
args.rval().setString(result);
return true;
}
bool
CData::ErrnoGetter(JSContext* cx, const JS::CallArgs& args)
{
args.rval().set(JS_GetReservedSlot(&args.thisv().toObject(), SLOT_ERRNO));
return true;
}
#if defined(XP_WIN)
bool
CData::LastErrorGetter(JSContext* cx, const JS::CallArgs& args)
{
args.rval().set(JS_GetReservedSlot(&args.thisv().toObject(), SLOT_LASTERROR));
return true;
}
#endif // defined(XP_WIN)
bool
CDataFinalizer::Methods::ToSource(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject objThis(cx, JS_THIS_OBJECT(cx, vp));
if (!objThis)
return false;
if (!CDataFinalizer::IsCDataFinalizer(objThis)) {
return IncompatibleThisProto(cx, "CDataFinalizer.prototype.toSource",
InformalValueTypeName(args.thisv()));
}
CDataFinalizer::Private* p = (CDataFinalizer::Private*)
JS_GetPrivate(objThis);
JSString* strMessage;
if (!p) {
strMessage = JS_NewStringCopyZ(cx, "ctypes.CDataFinalizer()");
} else {
RootedObject objType(cx, CDataFinalizer::GetCType(cx, objThis));
if (!objType) {
JS_ReportErrorASCII(cx, "CDataFinalizer has no type");
return false;
}
AutoString source;
AppendString(source, "ctypes.CDataFinalizer(");
JSString* srcValue = CData::GetSourceString(cx, objType, p->cargs);
if (!srcValue) {
return false;
}
AppendString(source, srcValue);
AppendString(source, ", ");
Value valCodePtrType = JS_GetReservedSlot(objThis,
SLOT_DATAFINALIZER_CODETYPE);
if (valCodePtrType.isPrimitive()) {
return false;
}
RootedObject typeObj(cx, valCodePtrType.toObjectOrNull());
JSString* srcDispose = CData::GetSourceString(cx, typeObj, &(p->code));
if (!srcDispose) {
return false;
}
AppendString(source, srcDispose);
AppendString(source, ")");
strMessage = NewUCString(cx, source);
}
if (!strMessage) {
// This is a memory issue, no error message
return false;
}
args.rval().setString(strMessage);
return true;
}
bool
CDataFinalizer::Methods::ToString(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSObject* objThis = JS_THIS_OBJECT(cx, vp);
if (!objThis)
return false;
if (!CDataFinalizer::IsCDataFinalizer(objThis)) {
return IncompatibleThisProto(cx, "CDataFinalizer.prototype.toString",
InformalValueTypeName(args.thisv()));
}
JSString* strMessage;
RootedValue value(cx);
if (!JS_GetPrivate(objThis)) {
// Pre-check whether CDataFinalizer::GetValue can fail
// to avoid reporting an error when not appropriate.
strMessage = JS_NewStringCopyZ(cx, "[CDataFinalizer - empty]");
if (!strMessage) {
return false;
}
} else if (!CDataFinalizer::GetValue(cx, objThis, &value)) {
MOZ_CRASH("Could not convert an empty CDataFinalizer");
} else {
strMessage = ToString(cx, value);
if (!strMessage) {
return false;
}
}
args.rval().setString(strMessage);
return true;
}
bool
CDataFinalizer::IsCDataFinalizer(JSObject* obj)
{
return JS_GetClass(obj) == &sCDataFinalizerClass;
}
JSObject*
CDataFinalizer::GetCType(JSContext* cx, JSObject* obj)
{
MOZ_ASSERT(IsCDataFinalizer(obj));
Value valData = JS_GetReservedSlot(obj,
SLOT_DATAFINALIZER_VALTYPE);
if (valData.isUndefined()) {
return nullptr;
}
return valData.toObjectOrNull();
}
bool
CDataFinalizer::GetValue(JSContext* cx, JSObject* obj,
MutableHandleValue aResult)
{
MOZ_ASSERT(IsCDataFinalizer(obj));
CDataFinalizer::Private* p = (CDataFinalizer::Private*)
JS_GetPrivate(obj);
if (!p) {
// We have called |dispose| or |forget| already.
JS_ReportErrorASCII(cx, "Attempting to get the value of an empty CDataFinalizer");
return false;
}
RootedObject ctype(cx, GetCType(cx, obj));
return ConvertToJS(cx, ctype, /*parent*/nullptr, p->cargs, false, true, aResult);
}
/*
* Attach a C function as a finalizer to a JS object.
*
* Pseudo-JS signature:
* function(CData<T>, CData<T -> U>): CDataFinalizer<T>
* value, finalizer
*
* This function attaches strong references to the following values:
* - the CType of |value|
*
* Note: This function takes advantage of the fact that non-variadic
* CData functions are initialized during creation.
*/
bool
CDataFinalizer::Construct(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject objSelf(cx, &args.callee());
RootedObject objProto(cx);
if (!GetObjectProperty(cx, objSelf, "prototype", &objProto)) {
JS_ReportErrorASCII(cx, "CDataFinalizer.prototype does not exist");
return false;
}
// Get arguments
if (args.length() == 0) { // Special case: the empty (already finalized) object
JSObject* objResult = JS_NewObjectWithGivenProto(cx, &sCDataFinalizerClass, objProto);
args.rval().setObject(*objResult);
return true;
}
if (args.length() != 2) {
return ArgumentLengthError(cx, "CDataFinalizer constructor", "two", "s");
}
JS::HandleValue valCodePtr = args[1];
if (!valCodePtr.isObject()) {
return TypeError(cx, "_a CData object_ of a function pointer type",
valCodePtr);
}
JSObject* objCodePtr = &valCodePtr.toObject();
//Note: Using a custom argument formatter here would be awkward (requires
//a destructor just to uninstall the formatter).
// 2. Extract argument type of |objCodePtr|
if (!CData::IsCData(objCodePtr)) {
return TypeError(cx, "a _CData_ object of a function pointer type",
valCodePtr);
}
RootedObject objCodePtrType(cx, CData::GetCType(objCodePtr));
RootedValue valCodePtrType(cx, ObjectValue(*objCodePtrType));
MOZ_ASSERT(objCodePtrType);
TypeCode typCodePtr = CType::GetTypeCode(objCodePtrType);
if (typCodePtr != TYPE_pointer) {
return TypeError(cx, "a CData object of a function _pointer_ type",
valCodePtr);
}
JSObject* objCodeType = PointerType::GetBaseType(objCodePtrType);
MOZ_ASSERT(objCodeType);
TypeCode typCode = CType::GetTypeCode(objCodeType);
if (typCode != TYPE_function) {
return TypeError(cx, "a CData object of a _function_ pointer type",
valCodePtr);
}
uintptr_t code = *reinterpret_cast<uintptr_t*>(CData::GetData(objCodePtr));
if (!code) {
return TypeError(cx, "a CData object of a _non-NULL_ function pointer type",
valCodePtr);
}
FunctionInfo* funInfoFinalizer =
FunctionType::GetFunctionInfo(objCodeType);
MOZ_ASSERT(funInfoFinalizer);
if ((funInfoFinalizer->mArgTypes.length() != 1)
|| (funInfoFinalizer->mIsVariadic)) {
RootedValue valCodeType(cx, ObjectValue(*objCodeType));
return TypeError(cx, "a function accepting exactly one argument",
valCodeType);
}
RootedObject objArgType(cx, funInfoFinalizer->mArgTypes[0]);
RootedObject returnType(cx, funInfoFinalizer->mReturnType);
// Invariant: At this stage, we know that funInfoFinalizer->mIsVariadic
// is |false|. Therefore, funInfoFinalizer->mCIF has already been initialized.
bool freePointer = false;
// 3. Perform dynamic cast of |args[0]| into |objType|, store it in |cargs|
size_t sizeArg;
RootedValue valData(cx, args[0]);
if (!CType::GetSafeSize(objArgType, &sizeArg)) {
RootedValue valCodeType(cx, ObjectValue(*objCodeType));
return TypeError(cx, "a function with one known size argument",
valCodeType);
}
ScopedJSFreePtr<void> cargs(malloc(sizeArg));
if (!ImplicitConvert(cx, valData, objArgType, cargs.get(),
ConversionType::Finalizer, &freePointer,
objCodePtrType, 0)) {
return false;
}
if (freePointer) {
// Note: We could handle that case, if necessary.
JS_ReportErrorASCII(cx, "Internal Error during CDataFinalizer. Object cannot be represented");
return false;
}
// 4. Prepare buffer for holding return value
ScopedJSFreePtr<void> rvalue;
if (CType::GetTypeCode(returnType) != TYPE_void_t) {
rvalue = malloc(Align(CType::GetSize(returnType),
sizeof(ffi_arg)));
} //Otherwise, simply do not allocate
// 5. Create |objResult|
JSObject* objResult = JS_NewObjectWithGivenProto(cx, &sCDataFinalizerClass, objProto);
if (!objResult) {
return false;
}
// If our argument is a CData, it holds a type.
// This is the type that we should capture, not that
// of the function, which may be less precise.
JSObject* objBestArgType = objArgType;
if (valData.isObject()) {
JSObject* objData = &valData.toObject();
if (CData::IsCData(objData)) {
objBestArgType = CData::GetCType(objData);
size_t sizeBestArg;
if (!CType::GetSafeSize(objBestArgType, &sizeBestArg)) {
MOZ_CRASH("object with unknown size");
}
if (sizeBestArg != sizeArg) {
return FinalizerSizeError(cx, objCodePtrType, valData);
}
}
}
// Used by GetCType
JS_SetReservedSlot(objResult,
SLOT_DATAFINALIZER_VALTYPE,
ObjectOrNullValue(objBestArgType));
// Used by ToSource
JS_SetReservedSlot(objResult,
SLOT_DATAFINALIZER_CODETYPE,
ObjectValue(*objCodePtrType));
RootedValue abiType(cx, ObjectOrNullValue(funInfoFinalizer->mABI));
ffi_abi abi;
if (!GetABI(cx, abiType, &abi)) {
JS_ReportErrorASCII(cx, "Internal Error: "
"Invalid ABI specification in CDataFinalizer");
return false;
}
ffi_type* rtype = CType::GetFFIType(cx, funInfoFinalizer->mReturnType);
if (!rtype) {
JS_ReportErrorASCII(cx, "Internal Error: "
"Could not access ffi type of CDataFinalizer");
return false;
}
// 7. Store C information as private
ScopedJSFreePtr<CDataFinalizer::Private>
p((CDataFinalizer::Private*)malloc(sizeof(CDataFinalizer::Private)));
memmove(&p->CIF, &funInfoFinalizer->mCIF, sizeof(ffi_cif));
p->cargs = cargs.forget();
p->rvalue = rvalue.forget();
p->cargs_size = sizeArg;
p->code = code;
JS_SetPrivate(objResult, p.forget());
args.rval().setObject(*objResult);
return true;
}
/*
* Actually call the finalizer. Does not perform any cleanup on the object.
*
* Preconditions: |this| must be a |CDataFinalizer|, |p| must be non-null.
* The function fails if |this| has gone through |Forget|/|Dispose|
* or |Finalize|.
*
* This function does not alter the value of |errno|/|GetLastError|.
*
* If argument |errnoStatus| is non-nullptr, it receives the value of |errno|
* immediately after the call. Under Windows, if argument |lastErrorStatus|
* is non-nullptr, it receives the value of |GetLastError| immediately after
* the call. On other platforms, |lastErrorStatus| is ignored.
*/
void
CDataFinalizer::CallFinalizer(CDataFinalizer::Private* p,
int* errnoStatus,
int32_t* lastErrorStatus)
{
int savedErrno = errno;
errno = 0;
#if defined(XP_WIN)
int32_t savedLastError = GetLastError();
SetLastError(0);
#endif // defined(XP_WIN)
void* args[1] = {p->cargs};
ffi_call(&p->CIF, FFI_FN(p->code), p->rvalue, args);
if (errnoStatus) {
*errnoStatus = errno;
}
errno = savedErrno;
#if defined(XP_WIN)
if (lastErrorStatus) {
*lastErrorStatus = GetLastError();
}
SetLastError(savedLastError);
#endif // defined(XP_WIN)
}
/*
* Forget the value.
*
* Preconditions: |this| must be a |CDataFinalizer|.
* The function fails if |this| has gone through |Forget|/|Dispose|
* or |Finalize|.
*
* Does not call the finalizer. Cleans up the Private memory and releases all
* strong references.
*/
bool
CDataFinalizer::Methods::Forget(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 0) {
return ArgumentLengthError(cx, "CDataFinalizer.prototype.forget", "no",
"s");
}
RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
if (!obj)
return false;
if (!CDataFinalizer::IsCDataFinalizer(obj)) {
return IncompatibleThisProto(cx, "CDataFinalizer.prototype.forget",
args.thisv());
}
CDataFinalizer::Private* p = (CDataFinalizer::Private*)
JS_GetPrivate(obj);
if (!p) {
return EmptyFinalizerCallError(cx, "CDataFinalizer.prototype.forget");
}
RootedValue valJSData(cx);
RootedObject ctype(cx, GetCType(cx, obj));
if (!ConvertToJS(cx, ctype, nullptr, p->cargs, false, true, &valJSData)) {
JS_ReportErrorASCII(cx, "CDataFinalizer value cannot be represented");
return false;
}
CDataFinalizer::Cleanup(p, obj);
args.rval().set(valJSData);
return true;
}
/*
* Clean up the value.
*
* Preconditions: |this| must be a |CDataFinalizer|.
* The function fails if |this| has gone through |Forget|/|Dispose|
* or |Finalize|.
*
* Calls the finalizer, cleans up the Private memory and releases all
* strong references.
*/
bool
CDataFinalizer::Methods::Dispose(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 0) {
return ArgumentLengthError(cx, "CDataFinalizer.prototype.dispose", "no",
"s");
}
RootedObject obj(cx, JS_THIS_OBJECT(cx, vp));
if (!obj)
return false;
if (!CDataFinalizer::IsCDataFinalizer(obj)) {
return IncompatibleThisProto(cx, "CDataFinalizer.prototype.dispose",
args.thisv());
}
CDataFinalizer::Private* p = (CDataFinalizer::Private*)
JS_GetPrivate(obj);
if (!p) {
return EmptyFinalizerCallError(cx, "CDataFinalizer.prototype.dispose");
}
Value valType = JS_GetReservedSlot(obj, SLOT_DATAFINALIZER_VALTYPE);
MOZ_ASSERT(valType.isObject());
RootedObject objCTypes(cx, CType::GetGlobalCTypes(cx, &valType.toObject()));
if (!objCTypes)
return false;
Value valCodePtrType = JS_GetReservedSlot(obj, SLOT_DATAFINALIZER_CODETYPE);
MOZ_ASSERT(valCodePtrType.isObject());
JSObject* objCodePtrType = &valCodePtrType.toObject();
JSObject* objCodeType = PointerType::GetBaseType(objCodePtrType);
MOZ_ASSERT(objCodeType);
MOZ_ASSERT(CType::GetTypeCode(objCodeType) == TYPE_function);
RootedObject resultType(cx, FunctionType::GetFunctionInfo(objCodeType)->mReturnType);
RootedValue result(cx);
int errnoStatus;
#if defined(XP_WIN)
int32_t lastErrorStatus;
CDataFinalizer::CallFinalizer(p, &errnoStatus, &lastErrorStatus);
#else
CDataFinalizer::CallFinalizer(p, &errnoStatus, nullptr);
#endif // defined(XP_WIN)
JS_SetReservedSlot(objCTypes, SLOT_ERRNO, Int32Value(errnoStatus));
#if defined(XP_WIN)
JS_SetReservedSlot(objCTypes, SLOT_LASTERROR, Int32Value(lastErrorStatus));
#endif // defined(XP_WIN)
if (ConvertToJS(cx, resultType, nullptr, p->rvalue, false, true, &result)) {
CDataFinalizer::Cleanup(p, obj);
args.rval().set(result);
return true;
}
CDataFinalizer::Cleanup(p, obj);
return false;
}
/*
* Perform finalization.
*
* Preconditions: |this| must be the result of |CDataFinalizer|.
* It may have gone through |Forget|/|Dispose|.
*
* If |this| has not gone through |Forget|/|Dispose|, calls the
* finalizer, cleans up the Private memory and releases all
* strong references.
*/
void
CDataFinalizer::Finalize(JSFreeOp* fop, JSObject* obj)
{
CDataFinalizer::Private* p = (CDataFinalizer::Private*)
JS_GetPrivate(obj);
if (!p) {
return;
}
CDataFinalizer::CallFinalizer(p, nullptr, nullptr);
CDataFinalizer::Cleanup(p, nullptr);
}
/*
* Perform cleanup of a CDataFinalizer
*
* Release strong references, cleanup |Private|.
*
* Argument |p| contains the private information of the CDataFinalizer. If
* nullptr, this function does nothing.
* Argument |obj| should contain |nullptr| during finalization (or in any
* context in which the object itself should not be cleaned up), or a
* CDataFinalizer object otherwise.
*/
void
CDataFinalizer::Cleanup(CDataFinalizer::Private* p, JSObject* obj)
{
if (!p) {
return; // We have already cleaned up
}
free(p->cargs);
free(p->rvalue);
free(p);
if (!obj) {
return; // No slots to clean up
}
MOZ_ASSERT(CDataFinalizer::IsCDataFinalizer(obj));
JS_SetPrivate(obj, nullptr);
for (int i = 0; i < CDATAFINALIZER_SLOTS; ++i) {
JS_SetReservedSlot(obj, i, JS::NullValue());
}
}
/*******************************************************************************
** Int64 and UInt64 implementation
*******************************************************************************/
JSObject*
Int64Base::Construct(JSContext* cx,
HandleObject proto,
uint64_t data,
bool isUnsigned)
{
const JSClass* clasp = isUnsigned ? &sUInt64Class : &sInt64Class;
RootedObject result(cx, JS_NewObjectWithGivenProto(cx, clasp, proto));
if (!result)
return nullptr;
// attach the Int64's data
uint64_t* buffer = cx->new_<uint64_t>(data);
if (!buffer) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
JS_SetReservedSlot(result, SLOT_INT64, PrivateValue(buffer));
if (!JS_FreezeObject(cx, result))
return nullptr;
return result;
}
void
Int64Base::Finalize(JSFreeOp* fop, JSObject* obj)
{
Value slot = JS_GetReservedSlot(obj, SLOT_INT64);
if (slot.isUndefined())
return;
FreeOp::get(fop)->delete_(static_cast<uint64_t*>(slot.toPrivate()));
}
uint64_t
Int64Base::GetInt(JSObject* obj) {
MOZ_ASSERT(Int64::IsInt64(obj) || UInt64::IsUInt64(obj));
Value slot = JS_GetReservedSlot(obj, SLOT_INT64);
return *static_cast<uint64_t*>(slot.toPrivate());
}
bool
Int64Base::ToString(JSContext* cx,
JSObject* obj,
const CallArgs& args,
bool isUnsigned)
{
if (args.length() > 1) {
if (isUnsigned) {
return ArgumentLengthError(cx, "UInt64.prototype.toString",
"at most one", "");
}
return ArgumentLengthError(cx, "Int64.prototype.toString",
"at most one", "");
}
int radix = 10;
if (args.length() == 1) {
Value arg = args[0];
if (arg.isInt32())
radix = arg.toInt32();
if (!arg.isInt32() || radix < 2 || radix > 36) {
if (isUnsigned) {
return ArgumentRangeMismatch(cx, "UInt64.prototype.toString", "an integer at least 2 and no greater than 36");
}
return ArgumentRangeMismatch(cx, "Int64.prototype.toString", "an integer at least 2 and no greater than 36");
}
}
AutoString intString;
if (isUnsigned) {
IntegerToString(GetInt(obj), radix, intString);
} else {
IntegerToString(static_cast<int64_t>(GetInt(obj)), radix, intString);
}
JSString* result = NewUCString(cx, intString);
if (!result)
return false;
args.rval().setString(result);
return true;
}
bool
Int64Base::ToSource(JSContext* cx,
JSObject* obj,
const CallArgs& args,
bool isUnsigned)
{
if (args.length() != 0) {
if (isUnsigned) {
return ArgumentLengthError(cx, "UInt64.prototype.toSource", "no", "s");
}
return ArgumentLengthError(cx, "Int64.prototype.toSource", "no", "s");
}
// Return a decimal string suitable for constructing the number.
AutoString source;
if (isUnsigned) {
AppendString(source, "ctypes.UInt64(\"");
IntegerToString(GetInt(obj), 10, source);
} else {
AppendString(source, "ctypes.Int64(\"");
IntegerToString(static_cast<int64_t>(GetInt(obj)), 10, source);
}
AppendString(source, "\")");
JSString* result = NewUCString(cx, source);
if (!result)
return false;
args.rval().setString(result);
return true;
}
bool
Int64::Construct(JSContext* cx,
unsigned argc,
Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Construct and return a new Int64 object.
if (args.length() != 1) {
return ArgumentLengthError(cx, "Int64 constructor", "one", "");
}
int64_t i = 0;
bool overflow = false;
if (!jsvalToBigInteger(cx, args[0], true, &i, &overflow)) {
if (overflow) {
return TypeOverflow(cx, "int64", args[0]);
}
return ArgumentConvError(cx, args[0], "Int64", 0);
}
// Get ctypes.Int64.prototype from the 'prototype' property of the ctor.
RootedValue slot(cx);
RootedObject callee(cx, &args.callee());
ASSERT_OK(JS_GetProperty(cx, callee, "prototype", &slot));
RootedObject proto(cx, slot.toObjectOrNull());
MOZ_ASSERT(JS_GetClass(proto) == &sInt64ProtoClass);
JSObject* result = Int64Base::Construct(cx, proto, i, false);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
bool
Int64::IsInt64(JSObject* obj)
{
return JS_GetClass(obj) == &sInt64Class;
}
bool
Int64::ToString(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSObject* obj = JS_THIS_OBJECT(cx, vp);
if (!obj)
return false;
if (!Int64::IsInt64(obj)) {
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "Int64.prototype.toString",
InformalValueTypeName(args.thisv()));
}
return IncompatibleThisType(cx, "Int64.prototype.toString",
"non-Int64 CData");
}
return Int64Base::ToString(cx, obj, args, false);
}
bool
Int64::ToSource(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSObject* obj = JS_THIS_OBJECT(cx, vp);
if (!obj)
return false;
if (!Int64::IsInt64(obj)) {
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "Int64.prototype.toSource",
InformalValueTypeName(args.thisv()));
}
return IncompatibleThisType(cx, "Int64.prototype.toSource",
"non-Int64 CData");
}
return Int64Base::ToSource(cx, obj, args, false);
}
bool
Int64::Compare(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 2) {
return ArgumentLengthError(cx, "Int64.compare", "two", "s");
}
if (args[0].isPrimitive() || !Int64::IsInt64(&args[0].toObject())) {
return ArgumentTypeMismatch(cx, "first ", "Int64.compare", "a Int64");
}
if (args[1].isPrimitive() ||!Int64::IsInt64(&args[1].toObject())) {
return ArgumentTypeMismatch(cx, "second ", "Int64.compare", "a Int64");
}
JSObject* obj1 = &args[0].toObject();
JSObject* obj2 = &args[1].toObject();
int64_t i1 = Int64Base::GetInt(obj1);
int64_t i2 = Int64Base::GetInt(obj2);
if (i1 == i2)
args.rval().setInt32(0);
else if (i1 < i2)
args.rval().setInt32(-1);
else
args.rval().setInt32(1);
return true;
}
#define LO_MASK ((uint64_t(1) << 32) - 1)
#define INT64_LO(i) ((i) & LO_MASK)
#define INT64_HI(i) ((i) >> 32)
bool
Int64::Lo(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 1) {
return ArgumentLengthError(cx, "Int64.lo", "one", "");
}
if (args[0].isPrimitive() || !Int64::IsInt64(&args[0].toObject())) {
return ArgumentTypeMismatch(cx, "", "Int64.lo", "a Int64");
}
JSObject* obj = &args[0].toObject();
int64_t u = Int64Base::GetInt(obj);
double d = uint32_t(INT64_LO(u));
args.rval().setNumber(d);
return true;
}
bool
Int64::Hi(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 1) {
return ArgumentLengthError(cx, "Int64.hi", "one", "");
}
if (args[0].isPrimitive() || !Int64::IsInt64(&args[0].toObject())) {
return ArgumentTypeMismatch(cx, "", "Int64.hi", "a Int64");
}
JSObject* obj = &args[0].toObject();
int64_t u = Int64Base::GetInt(obj);
double d = int32_t(INT64_HI(u));
args.rval().setDouble(d);
return true;
}
bool
Int64::Join(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 2) {
return ArgumentLengthError(cx, "Int64.join", "two", "s");
}
int32_t hi;
uint32_t lo;
if (!jsvalToInteger(cx, args[0], &hi))
return ArgumentConvError(cx, args[0], "Int64.join", 0);
if (!jsvalToInteger(cx, args[1], &lo))
return ArgumentConvError(cx, args[1], "Int64.join", 1);
int64_t i = (int64_t(hi) << 32) + int64_t(lo);
// Get Int64.prototype from the function's reserved slot.
JSObject* callee = &args.callee();
Value slot = js::GetFunctionNativeReserved(callee, SLOT_FN_INT64PROTO);
RootedObject proto(cx, &slot.toObject());
MOZ_ASSERT(JS_GetClass(proto) == &sInt64ProtoClass);
JSObject* result = Int64Base::Construct(cx, proto, i, false);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
bool
UInt64::Construct(JSContext* cx,
unsigned argc,
Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Construct and return a new UInt64 object.
if (args.length() != 1) {
return ArgumentLengthError(cx, "UInt64 constructor", "one", "");
}
uint64_t u = 0;
bool overflow = false;
if (!jsvalToBigInteger(cx, args[0], true, &u, &overflow)) {
if (overflow) {
return TypeOverflow(cx, "uint64", args[0]);
}
return ArgumentConvError(cx, args[0], "UInt64", 0);
}
// Get ctypes.UInt64.prototype from the 'prototype' property of the ctor.
RootedValue slot(cx);
RootedObject callee(cx, &args.callee());
ASSERT_OK(JS_GetProperty(cx, callee, "prototype", &slot));
RootedObject proto(cx, &slot.toObject());
MOZ_ASSERT(JS_GetClass(proto) == &sUInt64ProtoClass);
JSObject* result = Int64Base::Construct(cx, proto, u, true);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
bool
UInt64::IsUInt64(JSObject* obj)
{
return JS_GetClass(obj) == &sUInt64Class;
}
bool
UInt64::ToString(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSObject* obj = JS_THIS_OBJECT(cx, vp);
if (!obj)
return false;
if (!UInt64::IsUInt64(obj)) {
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "UInt64.prototype.toString",
InformalValueTypeName(args.thisv()));
}
return IncompatibleThisType(cx, "UInt64.prototype.toString",
"non-UInt64 CData");
}
return Int64Base::ToString(cx, obj, args, true);
}
bool
UInt64::ToSource(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSObject* obj = JS_THIS_OBJECT(cx, vp);
if (!obj)
return false;
if (!UInt64::IsUInt64(obj)) {
if (!CData::IsCData(obj)) {
return IncompatibleThisProto(cx, "UInt64.prototype.toSource",
InformalValueTypeName(args.thisv()));
}
return IncompatibleThisType(cx, "UInt64.prototype.toSource",
"non-UInt64 CData");
}
return Int64Base::ToSource(cx, obj, args, true);
}
bool
UInt64::Compare(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 2) {
return ArgumentLengthError(cx, "UInt64.compare", "two", "s");
}
if (args[0].isPrimitive() || !UInt64::IsUInt64(&args[0].toObject())) {
return ArgumentTypeMismatch(cx, "first ", "UInt64.compare", "a UInt64");
}
if (args[1].isPrimitive() || !UInt64::IsUInt64(&args[1].toObject())) {
return ArgumentTypeMismatch(cx, "second ", "UInt64.compare", "a UInt64");
}
JSObject* obj1 = &args[0].toObject();
JSObject* obj2 = &args[1].toObject();
uint64_t u1 = Int64Base::GetInt(obj1);
uint64_t u2 = Int64Base::GetInt(obj2);
if (u1 == u2)
args.rval().setInt32(0);
else if (u1 < u2)
args.rval().setInt32(-1);
else
args.rval().setInt32(1);
return true;
}
bool
UInt64::Lo(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 1) {
return ArgumentLengthError(cx, "UInt64.lo", "one", "");
}
if (args[0].isPrimitive() || !UInt64::IsUInt64(&args[0].toObject())) {
return ArgumentTypeMismatch(cx, "", "UInt64.lo", "a UInt64");
}
JSObject* obj = &args[0].toObject();
uint64_t u = Int64Base::GetInt(obj);
double d = uint32_t(INT64_LO(u));
args.rval().setDouble(d);
return true;
}
bool
UInt64::Hi(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 1) {
return ArgumentLengthError(cx, "UInt64.hi", "one", "");
}
if (args[0].isPrimitive() || !UInt64::IsUInt64(&args[0].toObject())) {
return ArgumentTypeMismatch(cx, "", "UInt64.hi", "a UInt64");
}
JSObject* obj = &args[0].toObject();
uint64_t u = Int64Base::GetInt(obj);
double d = uint32_t(INT64_HI(u));
args.rval().setDouble(d);
return true;
}
bool
UInt64::Join(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
if (args.length() != 2) {
return ArgumentLengthError(cx, "UInt64.join", "two", "s");
}
uint32_t hi;
uint32_t lo;
if (!jsvalToInteger(cx, args[0], &hi))
return ArgumentConvError(cx, args[0], "UInt64.join", 0);
if (!jsvalToInteger(cx, args[1], &lo))
return ArgumentConvError(cx, args[1], "UInt64.join", 1);
uint64_t u = (uint64_t(hi) << 32) + uint64_t(lo);
// Get UInt64.prototype from the function's reserved slot.
JSObject* callee = &args.callee();
Value slot = js::GetFunctionNativeReserved(callee, SLOT_FN_INT64PROTO);
RootedObject proto(cx, &slot.toObject());
MOZ_ASSERT(JS_GetClass(proto) == &sUInt64ProtoClass);
JSObject* result = Int64Base::Construct(cx, proto, u, true);
if (!result)
return false;
args.rval().setObject(*result);
return true;
}
} // namespace ctypes
} // namespace js
|