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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "TelemetryHistogram.h"
#include <limits>
#include "base/histogram.h"
#include "geckoview/streaming/GeckoViewStreamingTelemetry.h"
#include "ipc/TelemetryIPCAccumulator.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "js/Array.h" // JS::GetArrayLength, JS::IsArrayObject, JS::NewArrayObject
#include "js/GCAPI.h"
#include "js/Object.h" // JS::GetClass, JS::GetMaybePtrFromReservedSlot, JS::SetReservedSlot
#include "js/PropertyAndElement.h" // JS_DefineElement, JS_DefineFunction, JS_DefineProperty, JS_DefineUCProperty, JS_Enumerate, JS_GetElement, JS_GetProperty, JS_GetPropertyById
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/gfx/GPUProcessManager.h"
#include "mozilla/Atomics.h"
#include "mozilla/JSONWriter.h"
#include "mozilla/StartupTimeline.h"
#include "mozilla/StaticMutex.h"
#include "mozilla/Unused.h"
#include "nsClassHashtable.h"
#include "nsString.h"
#include "nsHashKeys.h"
#include "nsITelemetry.h"
#include "nsPrintfCString.h"
#include "TelemetryHistogramNameMap.h"
#include "TelemetryScalar.h"
using base::BooleanHistogram;
using base::CountHistogram;
using base::FlagHistogram;
using base::LinearHistogram;
using mozilla::MakeUnique;
using mozilla::StaticMutex;
using mozilla::StaticMutexAutoLock;
using mozilla::UniquePtr;
using mozilla::Telemetry::HistogramAccumulation;
using mozilla::Telemetry::HistogramCount;
using mozilla::Telemetry::HistogramID;
using mozilla::Telemetry::HistogramIDByNameLookup;
using mozilla::Telemetry::KeyedHistogramAccumulation;
using mozilla::Telemetry::ProcessID;
using mozilla::Telemetry::Common::CanRecordDataset;
using mozilla::Telemetry::Common::CanRecordProduct;
using mozilla::Telemetry::Common::GetCurrentProduct;
using mozilla::Telemetry::Common::GetIDForProcessName;
using mozilla::Telemetry::Common::GetNameForProcessID;
using mozilla::Telemetry::Common::IsExpiredVersion;
using mozilla::Telemetry::Common::IsInDataset;
using mozilla::Telemetry::Common::LogToBrowserConsole;
using mozilla::Telemetry::Common::RecordedProcessType;
using mozilla::Telemetry::Common::StringHashSet;
using mozilla::Telemetry::Common::SupportedProduct;
using mozilla::Telemetry::Common::ToJSString;
namespace TelemetryIPCAccumulator = mozilla::TelemetryIPCAccumulator;
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// Naming: there are two kinds of functions in this file:
//
// * Functions named internal_*: these can only be reached via an
// interface function (TelemetryHistogram::*). They mostly expect
// the interface function to have acquired
// |gTelemetryHistogramMutex|, so they do not have to be
// thread-safe. However, those internal_* functions that are
// reachable from internal_WrapAndReturnHistogram and
// internal_WrapAndReturnKeyedHistogram can sometimes be called
// without |gTelemetryHistogramMutex|, and so might be racey.
//
// * Functions named TelemetryHistogram::*. This is the external interface.
// Entries and exits to these functions are serialised using
// |gTelemetryHistogramMutex|, except for GetKeyedHistogramSnapshots and
// CreateHistogramSnapshots.
//
// Avoiding races and deadlocks:
//
// All functions in the external interface (TelemetryHistogram::*) are
// serialised using the mutex |gTelemetryHistogramMutex|. This means
// that the external interface is thread-safe, and many of the
// internal_* functions can ignore thread safety. But it also brings
// a danger of deadlock if any function in the external interface can
// get back to that interface. That is, we will deadlock on any call
// chain like this
//
// TelemetryHistogram::* -> .. any functions .. -> TelemetryHistogram::*
//
// To reduce the danger of that happening, observe the following rules:
//
// * No function in TelemetryHistogram::* may directly call, nor take the
// address of, any other function in TelemetryHistogram::*.
//
// * No internal function internal_* may call, nor take the address
// of, any function in TelemetryHistogram::*.
//
// internal_WrapAndReturnHistogram and
// internal_WrapAndReturnKeyedHistogram are not protected by
// |gTelemetryHistogramMutex| because they make calls to the JS
// engine, but that can in turn call back to Telemetry and hence back
// to a TelemetryHistogram:: function, in order to report GC and other
// statistics. This would lead to deadlock due to attempted double
// acquisition of |gTelemetryHistogramMutex|, if the internal_* functions
// were required to be protected by |gTelemetryHistogramMutex|. To
// break that cycle, we relax that requirement. Unfortunately this
// means that this file is not guaranteed race-free.
// This is a StaticMutex rather than a plain Mutex (1) so that
// it gets initialised in a thread-safe manner the first time
// it is used, and (2) because it is never de-initialised, and
// a normal Mutex would show up as a leak in BloatView. StaticMutex
// also has the "OffTheBooks" property, so it won't show as a leak
// in BloatView.
static StaticMutex gTelemetryHistogramMutex MOZ_UNANNOTATED;
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE TYPES
namespace {
// Hardcoded probes
//
// The order of elements here is important to minimize the memory footprint of a
// HistogramInfo instance.
//
// Any adjustements need to be reflected in gen_histogram_data.py
struct HistogramInfo {
uint32_t min;
uint32_t max;
uint32_t bucketCount;
uint32_t name_offset;
uint32_t expiration_offset;
uint32_t label_count;
uint32_t key_count;
uint32_t store_count;
uint16_t label_index;
uint16_t key_index;
uint16_t store_index;
RecordedProcessType record_in_processes;
bool keyed;
uint8_t histogramType;
uint8_t dataset;
SupportedProduct products;
const char* name() const;
const char* expiration() const;
nsresult label_id(const char* label, uint32_t* labelId) const;
bool allows_key(const nsACString& key) const;
bool is_single_store() const;
};
// Structs used to keep information about the histograms for which a
// snapshot should be created.
struct HistogramSnapshotData {
CopyableTArray<base::Histogram::Sample> mBucketRanges;
CopyableTArray<base::Histogram::Count> mBucketCounts;
int64_t mSampleSum; // Same type as base::Histogram::SampleSet::sum_
};
struct HistogramSnapshotInfo {
HistogramSnapshotData data;
HistogramID histogramID;
};
typedef mozilla::Vector<HistogramSnapshotInfo> HistogramSnapshotsArray;
typedef mozilla::Vector<HistogramSnapshotsArray> HistogramProcessSnapshotsArray;
// The following is used to handle snapshot information for keyed histograms.
typedef nsTHashMap<nsCStringHashKey, HistogramSnapshotData>
KeyedHistogramSnapshotData;
struct KeyedHistogramSnapshotInfo {
KeyedHistogramSnapshotData data;
HistogramID histogramId;
};
typedef mozilla::Vector<KeyedHistogramSnapshotInfo>
KeyedHistogramSnapshotsArray;
typedef mozilla::Vector<KeyedHistogramSnapshotsArray>
KeyedHistogramProcessSnapshotsArray;
/**
* A Histogram storage engine.
*
* Takes care of recording data into multiple stores if necessary.
*/
class Histogram {
public:
/*
* Create a new histogram instance from the given info.
*
* If the histogram is already expired, this does not allocate.
*/
Histogram(HistogramID histogramId, const HistogramInfo& info, bool expired);
~Histogram();
/**
* Add a sample to this histogram in all registered stores.
*/
void Add(uint32_t sample);
/**
* Clear the named store for this histogram.
*/
void Clear(const nsACString& store);
/**
* Get the histogram instance from the named store.
*/
bool GetHistogram(const nsACString& store, base::Histogram** h);
bool IsExpired() const { return mIsExpired; }
size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf);
private:
// String -> Histogram*
typedef nsClassHashtable<nsCStringHashKey, base::Histogram> HistogramStore;
HistogramStore mStorage;
// A valid pointer if this histogram belongs to only the main store
base::Histogram* mSingleStore;
// We don't track stores for expired histograms.
// We just store a single flag and all other operations become a no-op.
bool mIsExpired;
};
class KeyedHistogram {
public:
KeyedHistogram(HistogramID id, const HistogramInfo& info, bool expired);
~KeyedHistogram();
nsresult GetHistogram(const nsCString& aStore, const nsCString& key,
base::Histogram** histogram);
base::Histogram* GetHistogram(const nsCString& aStore, const nsCString& key);
uint32_t GetHistogramType() const { return mHistogramInfo.histogramType; }
nsresult GetKeys(const StaticMutexAutoLock& aLock, const nsCString& store,
nsTArray<nsCString>& aKeys);
// Note: unlike other methods, GetJSSnapshot is thread safe.
nsresult GetJSSnapshot(JSContext* cx, JS::Handle<JSObject*> obj,
const nsACString& aStore, bool clearSubsession);
nsresult GetSnapshot(const StaticMutexAutoLock& aLock,
const nsACString& aStore,
KeyedHistogramSnapshotData& aSnapshot,
bool aClearSubsession);
nsresult Add(const nsCString& key, uint32_t aSample, ProcessID aProcessType);
void Clear(const nsACString& aStore);
HistogramID GetHistogramID() const { return mId; }
bool IsEmpty(const nsACString& aStore) const;
bool IsExpired() const { return mIsExpired; }
size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf);
private:
typedef nsClassHashtable<nsCStringHashKey, base::Histogram>
KeyedHistogramMapType;
typedef nsClassHashtable<nsCStringHashKey, KeyedHistogramMapType>
StoreMapType;
StoreMapType mStorage;
// A valid map if this histogram belongs to only the main store
KeyedHistogramMapType* mSingleStore;
const HistogramID mId;
const HistogramInfo& mHistogramInfo;
bool mIsExpired;
};
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE STATE, SHARED BY ALL THREADS
namespace {
// Set to true once this global state has been initialized
bool gInitDone = false;
// Whether we are collecting the base, opt-out, Histogram data.
bool gCanRecordBase = false;
// Whether we are collecting the extended, opt-in, Histogram data.
bool gCanRecordExtended = false;
// The storage for actual Histogram instances.
// We use separate ones for plain and keyed histograms.
Histogram** gHistogramStorage;
// Keyed histograms internally map string keys to individual Histogram
// instances.
KeyedHistogram** gKeyedHistogramStorage;
// To simplify logic below we use a single histogram instance for all expired
// histograms.
Histogram* gExpiredHistogram = nullptr;
// The single placeholder for expired keyed histograms.
KeyedHistogram* gExpiredKeyedHistogram = nullptr;
// This tracks whether recording is enabled for specific histograms.
// To utilize C++ initialization rules, we invert the meaning to "disabled".
bool gHistogramRecordingDisabled[HistogramCount] = {};
// This is for gHistogramInfos, gHistogramStringTable
#include "TelemetryHistogramData.inc"
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE CONSTANTS
namespace {
// List of histogram IDs which should have recording disabled initially.
const HistogramID kRecordingInitiallyDisabledIDs[] = {
mozilla::Telemetry::FX_REFRESH_DRIVER_SYNC_SCROLL_FRAME_DELAY_MS,
// The array must not be empty. Leave these item here.
mozilla::Telemetry::TELEMETRY_TEST_COUNT_INIT_NO_RECORD,
mozilla::Telemetry::TELEMETRY_TEST_KEYED_COUNT_INIT_NO_RECORD};
const char* TEST_HISTOGRAM_PREFIX = "TELEMETRY_TEST_";
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// The core storage access functions.
// They wrap access to the histogram storage and lookup caches.
namespace {
size_t internal_KeyedHistogramStorageIndex(HistogramID aHistogramId,
ProcessID aProcessId) {
return aHistogramId * size_t(ProcessID::Count) + size_t(aProcessId);
}
size_t internal_HistogramStorageIndex(const StaticMutexAutoLock& aLock,
HistogramID aHistogramId,
ProcessID aProcessId) {
static_assert(HistogramCount < std::numeric_limits<size_t>::max() /
size_t(ProcessID::Count),
"Too many histograms and processes to store in a 1D array.");
return aHistogramId * size_t(ProcessID::Count) + size_t(aProcessId);
}
Histogram* internal_GetHistogramFromStorage(const StaticMutexAutoLock& aLock,
HistogramID aHistogramId,
ProcessID aProcessId) {
size_t index =
internal_HistogramStorageIndex(aLock, aHistogramId, aProcessId);
return gHistogramStorage[index];
}
void internal_SetHistogramInStorage(const StaticMutexAutoLock& aLock,
HistogramID aHistogramId,
ProcessID aProcessId,
Histogram* aHistogram) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Histograms are stored only in the parent process.");
size_t index =
internal_HistogramStorageIndex(aLock, aHistogramId, aProcessId);
MOZ_ASSERT(!gHistogramStorage[index],
"Mustn't overwrite storage without clearing it first.");
gHistogramStorage[index] = aHistogram;
}
KeyedHistogram* internal_GetKeyedHistogramFromStorage(HistogramID aHistogramId,
ProcessID aProcessId) {
size_t index = internal_KeyedHistogramStorageIndex(aHistogramId, aProcessId);
return gKeyedHistogramStorage[index];
}
void internal_SetKeyedHistogramInStorage(HistogramID aHistogramId,
ProcessID aProcessId,
KeyedHistogram* aKeyedHistogram) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Keyed Histograms are stored only in the parent process.");
size_t index = internal_KeyedHistogramStorageIndex(aHistogramId, aProcessId);
MOZ_ASSERT(!gKeyedHistogramStorage[index],
"Mustn't overwrite storage without clearing it first");
gKeyedHistogramStorage[index] = aKeyedHistogram;
}
// Factory function for base::Histogram instances.
base::Histogram* internal_CreateBaseHistogramInstance(const HistogramInfo& info,
int bucketsOffset);
// Factory function for histogram instances.
Histogram* internal_CreateHistogramInstance(HistogramID histogramId);
bool internal_IsHistogramEnumId(HistogramID aID) {
static_assert(((HistogramID)-1 > 0), "ID should be unsigned.");
return aID < HistogramCount;
}
// Look up a plain histogram by id.
Histogram* internal_GetHistogramById(const StaticMutexAutoLock& aLock,
HistogramID histogramId,
ProcessID processId,
bool instantiate = true) {
MOZ_ASSERT(internal_IsHistogramEnumId(histogramId));
MOZ_ASSERT(!gHistogramInfos[histogramId].keyed);
MOZ_ASSERT(processId < ProcessID::Count);
Histogram* h =
internal_GetHistogramFromStorage(aLock, histogramId, processId);
if (h || !instantiate) {
return h;
}
h = internal_CreateHistogramInstance(histogramId);
MOZ_ASSERT(h);
internal_SetHistogramInStorage(aLock, histogramId, processId, h);
return h;
}
// Look up a keyed histogram by id.
KeyedHistogram* internal_GetKeyedHistogramById(HistogramID histogramId,
ProcessID processId,
bool instantiate = true) {
MOZ_ASSERT(internal_IsHistogramEnumId(histogramId));
MOZ_ASSERT(gHistogramInfos[histogramId].keyed);
MOZ_ASSERT(processId < ProcessID::Count);
KeyedHistogram* kh =
internal_GetKeyedHistogramFromStorage(histogramId, processId);
if (kh || !instantiate) {
return kh;
}
const HistogramInfo& info = gHistogramInfos[histogramId];
const bool isExpired = IsExpiredVersion(info.expiration());
// If the keyed histogram is expired, set its storage to the expired
// keyed histogram.
if (isExpired) {
if (!gExpiredKeyedHistogram) {
// If we don't have an expired keyed histogram, create one.
gExpiredKeyedHistogram =
new KeyedHistogram(histogramId, info, true /* expired */);
MOZ_ASSERT(gExpiredKeyedHistogram);
}
kh = gExpiredKeyedHistogram;
} else {
kh = new KeyedHistogram(histogramId, info, false /* expired */);
}
internal_SetKeyedHistogramInStorage(histogramId, processId, kh);
return kh;
}
// Look up a histogram id from a histogram name.
nsresult internal_GetHistogramIdByName(const StaticMutexAutoLock& aLock,
const nsACString& name,
HistogramID* id) {
const uint32_t idx = HistogramIDByNameLookup(name);
MOZ_ASSERT(idx < HistogramCount,
"Intermediate lookup should always give a valid index.");
// The lookup hashes the input and uses it as an index into the value array.
// Hash collisions can still happen for unknown values,
// therefore we check that the name matches.
if (name.Equals(gHistogramInfos[idx].name())) {
*id = HistogramID(idx);
return NS_OK;
}
return NS_ERROR_ILLEGAL_VALUE;
}
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE: Misc small helpers
namespace {
bool internal_CanRecordBase() { return gCanRecordBase; }
bool internal_CanRecordExtended() { return gCanRecordExtended; }
bool internal_AttemptedGPUProcess() {
// Check if it was tried to launch a process.
bool attemptedGPUProcess = false;
if (auto gpm = mozilla::gfx::GPUProcessManager::Get()) {
attemptedGPUProcess = gpm->AttemptedGPUProcess();
}
return attemptedGPUProcess;
}
// Note: this is completely unrelated to mozilla::IsEmpty.
bool internal_IsEmpty(const StaticMutexAutoLock& aLock,
const base::Histogram* h) {
return h->is_empty();
}
void internal_SetHistogramRecordingEnabled(const StaticMutexAutoLock& aLock,
HistogramID id, bool aEnabled) {
MOZ_ASSERT(internal_IsHistogramEnumId(id));
gHistogramRecordingDisabled[id] = !aEnabled;
}
bool internal_IsRecordingEnabled(HistogramID id) {
MOZ_ASSERT(internal_IsHistogramEnumId(id));
return !gHistogramRecordingDisabled[id];
}
const char* HistogramInfo::name() const {
return &gHistogramStringTable[this->name_offset];
}
const char* HistogramInfo::expiration() const {
return &gHistogramStringTable[this->expiration_offset];
}
nsresult HistogramInfo::label_id(const char* label, uint32_t* labelId) const {
MOZ_ASSERT(label);
MOZ_ASSERT(this->histogramType == nsITelemetry::HISTOGRAM_CATEGORICAL);
if (this->histogramType != nsITelemetry::HISTOGRAM_CATEGORICAL) {
return NS_ERROR_FAILURE;
}
for (uint32_t i = 0; i < this->label_count; ++i) {
// gHistogramLabelTable contains the indices of the label strings in the
// gHistogramStringTable.
// They are stored in-order and consecutively, from the offset label_index
// to (label_index + label_count).
uint32_t string_offset = gHistogramLabelTable[this->label_index + i];
const char* const str = &gHistogramStringTable[string_offset];
if (::strcmp(label, str) == 0) {
*labelId = i;
return NS_OK;
}
}
return NS_ERROR_FAILURE;
}
bool HistogramInfo::allows_key(const nsACString& key) const {
MOZ_ASSERT(this->keyed);
// If we didn't specify a list of allowed keys, just return true.
if (this->key_count == 0) {
return true;
}
// Otherwise, check if |key| is in the list of allowed keys.
for (uint32_t i = 0; i < this->key_count; ++i) {
// gHistogramKeyTable contains the indices of the key strings in the
// gHistogramStringTable. They are stored in-order and consecutively,
// from the offset key_index to (key_index + key_count).
uint32_t string_offset = gHistogramKeyTable[this->key_index + i];
const char* const str = &gHistogramStringTable[string_offset];
if (key.EqualsASCII(str)) {
return true;
}
}
// |key| was not found.
return false;
}
bool HistogramInfo::is_single_store() const {
return store_count == 1 && store_index == UINT16_MAX;
}
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE: Histogram Get, Add, Clone, Clear functions
namespace {
nsresult internal_CheckHistogramArguments(const HistogramInfo& info) {
if (info.histogramType != nsITelemetry::HISTOGRAM_BOOLEAN &&
info.histogramType != nsITelemetry::HISTOGRAM_FLAG &&
info.histogramType != nsITelemetry::HISTOGRAM_COUNT) {
// Sanity checks for histogram parameters.
if (info.min >= info.max) {
return NS_ERROR_ILLEGAL_VALUE;
}
if (info.bucketCount <= 2) {
return NS_ERROR_ILLEGAL_VALUE;
}
if (info.min < 1) {
return NS_ERROR_ILLEGAL_VALUE;
}
}
return NS_OK;
}
Histogram* internal_CreateHistogramInstance(HistogramID histogramId) {
const HistogramInfo& info = gHistogramInfos[histogramId];
if (NS_FAILED(internal_CheckHistogramArguments(info))) {
MOZ_ASSERT(false, "Failed histogram argument checks.");
return nullptr;
}
const bool isExpired = IsExpiredVersion(info.expiration());
if (isExpired) {
if (!gExpiredHistogram) {
gExpiredHistogram = new Histogram(histogramId, info, /* expired */ true);
}
return gExpiredHistogram;
}
Histogram* wrapper = new Histogram(histogramId, info, /* expired */ false);
return wrapper;
}
base::Histogram* internal_CreateBaseHistogramInstance(
const HistogramInfo& passedInfo, int bucketsOffset) {
if (NS_FAILED(internal_CheckHistogramArguments(passedInfo))) {
MOZ_ASSERT(false, "Failed histogram argument checks.");
return nullptr;
}
// We don't actually store data for expired histograms at all.
MOZ_ASSERT(!IsExpiredVersion(passedInfo.expiration()));
HistogramInfo info = passedInfo;
const int* buckets = &gHistogramBucketLowerBounds[bucketsOffset];
base::Histogram::Flags flags = base::Histogram::kNoFlags;
base::Histogram* h = nullptr;
switch (info.histogramType) {
case nsITelemetry::HISTOGRAM_EXPONENTIAL:
h = base::Histogram::FactoryGet(info.min, info.max, info.bucketCount,
flags, buckets);
break;
case nsITelemetry::HISTOGRAM_LINEAR:
case nsITelemetry::HISTOGRAM_CATEGORICAL:
h = LinearHistogram::FactoryGet(info.min, info.max, info.bucketCount,
flags, buckets);
break;
case nsITelemetry::HISTOGRAM_BOOLEAN:
h = BooleanHistogram::FactoryGet(flags, buckets);
break;
case nsITelemetry::HISTOGRAM_FLAG:
h = FlagHistogram::FactoryGet(flags, buckets);
break;
case nsITelemetry::HISTOGRAM_COUNT:
h = CountHistogram::FactoryGet(flags, buckets);
break;
default:
MOZ_ASSERT(false, "Invalid histogram type");
return nullptr;
}
return h;
}
nsresult internal_HistogramAdd(const StaticMutexAutoLock& aLock,
Histogram& histogram, const HistogramID id,
uint32_t value, ProcessID aProcessType) {
// Check if we are allowed to record the data.
bool canRecordDataset =
CanRecordDataset(gHistogramInfos[id].dataset, internal_CanRecordBase(),
internal_CanRecordExtended());
// If `histogram` is a non-parent-process histogram, then recording-enabled
// has been checked in its owner process.
if (!canRecordDataset ||
(aProcessType == ProcessID::Parent && !internal_IsRecordingEnabled(id))) {
return NS_OK;
}
// Don't record if the current platform is not enabled
if (!CanRecordProduct(gHistogramInfos[id].products)) {
return NS_OK;
}
if (&histogram != gExpiredHistogram &&
GetCurrentProduct() == SupportedProduct::GeckoviewStreaming) {
const HistogramInfo& info = gHistogramInfos[id];
GeckoViewStreamingTelemetry::HistogramAccumulate(
nsDependentCString(info.name()),
info.histogramType == nsITelemetry::HISTOGRAM_CATEGORICAL, value);
return NS_OK;
}
// The internal representation of a base::Histogram's buckets uses `int`.
// Clamp large values of `value` to be INT_MAX so they continue to be treated
// as large values (instead of negative ones).
if (value > INT_MAX) {
TelemetryScalar::Add(
mozilla::Telemetry::ScalarID::TELEMETRY_ACCUMULATE_CLAMPED_VALUES,
NS_ConvertASCIItoUTF16(gHistogramInfos[id].name()), 1);
value = INT_MAX;
}
histogram.Add(value);
return NS_OK;
}
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE: Histogram reflection helpers
namespace {
/**
* Copy histograms and samples to Mozilla-friendly structures.
* Please note that this version does not make use of JS contexts.
*
* @param {StaticMutexAutoLock} the proof we hold the mutex.
* @param {Histogram} the histogram to reflect.
* @return {nsresult} NS_ERROR_FAILURE if we fail to allocate memory for the
* snapshot.
*/
nsresult internal_GetHistogramAndSamples(const StaticMutexAutoLock& aLock,
const base::Histogram* h,
HistogramSnapshotData& aSnapshot) {
MOZ_ASSERT(h);
// Convert the ranges of the buckets to a nsTArray.
const size_t bucketCount = h->bucket_count();
for (size_t i = 0; i < bucketCount; i++) {
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier, or change the return type to void.
aSnapshot.mBucketRanges.AppendElement(h->ranges(i));
}
// Get a snapshot of the samples.
base::Histogram::SampleSet ss = h->SnapshotSample();
// Get the number of samples in each bucket.
for (size_t i = 0; i < bucketCount; i++) {
// XXX(Bug 1631371) Check if this should use a fallible operation as it
// pretended earlier, or change the return type to void.
aSnapshot.mBucketCounts.AppendElement(ss.counts(i));
}
// Finally, save the |sum|. We don't need to reflect declared_min,
// declared_max and histogram_type as they are in gHistogramInfo.
aSnapshot.mSampleSum = ss.sum();
return NS_OK;
}
/**
* Reflect a histogram snapshot into a JavaScript object.
* The returned histogram object will have the following properties:
*
* bucket_count - Number of buckets of this histogram
* histogram_type - HISTOGRAM_EXPONENTIAL, HISTOGRAM_LINEAR,
* HISTOGRAM_BOOLEAN, HISTOGRAM_FLAG, HISTOGRAM_COUNT, or HISTOGRAM_CATEGORICAL
* sum - sum of the bucket contents
* range - A 2-item array of minimum and maximum bucket size
* values - Map from bucket start to the bucket's count
*/
nsresult internal_ReflectHistogramAndSamples(
JSContext* cx, JS::Handle<JSObject*> obj,
const HistogramInfo& aHistogramInfo,
const HistogramSnapshotData& aSnapshot) {
if (!(JS_DefineProperty(cx, obj, "bucket_count", aHistogramInfo.bucketCount,
JSPROP_ENUMERATE) &&
JS_DefineProperty(cx, obj, "histogram_type",
aHistogramInfo.histogramType, JSPROP_ENUMERATE) &&
JS_DefineProperty(cx, obj, "sum", double(aSnapshot.mSampleSum),
JSPROP_ENUMERATE))) {
return NS_ERROR_FAILURE;
}
// Don't rely on the bucket counts from "aHistogramInfo": it may
// differ from the length of aSnapshot.mBucketCounts due to expired
// histograms.
const size_t count = aSnapshot.mBucketCounts.Length();
MOZ_ASSERT(count == aSnapshot.mBucketRanges.Length(),
"The number of buckets and the number of counts must match.");
// Create the "range" property and add it to the final object.
JS::Rooted<JSObject*> rarray(cx, JS::NewArrayObject(cx, 2));
if (rarray == nullptr ||
!JS_DefineProperty(cx, obj, "range", rarray, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
// Add [min, max] into the range array
if (!JS_DefineElement(cx, rarray, 0, aHistogramInfo.min, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
if (!JS_DefineElement(cx, rarray, 1, aHistogramInfo.max, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
JS::Rooted<JSObject*> values(cx, JS_NewPlainObject(cx));
if (values == nullptr ||
!JS_DefineProperty(cx, obj, "values", values, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
bool first = true;
size_t last = 0;
for (size_t i = 0; i < count; i++) {
auto value = aSnapshot.mBucketCounts[i];
if (value == 0) {
continue;
}
if (i > 0 && first) {
auto range = aSnapshot.mBucketRanges[i - 1];
if (!JS_DefineProperty(cx, values, nsPrintfCString("%d", range).get(), 0,
JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
}
first = false;
last = i + 1;
auto range = aSnapshot.mBucketRanges[i];
if (!JS_DefineProperty(cx, values, nsPrintfCString("%d", range).get(),
value, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
}
if (last > 0 && last < count) {
auto range = aSnapshot.mBucketRanges[last];
if (!JS_DefineProperty(cx, values, nsPrintfCString("%d", range).get(), 0,
JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
}
return NS_OK;
}
bool internal_ShouldReflectHistogram(const StaticMutexAutoLock& aLock,
base::Histogram* h, HistogramID id) {
// Only flag histograms are serialized when they are empty.
// This has historical reasons, changing this will require downstream changes.
// The cheaper path here is to just deprecate flag histograms in favor
// of scalars.
uint32_t type = gHistogramInfos[id].histogramType;
if (internal_IsEmpty(aLock, h) && type != nsITelemetry::HISTOGRAM_FLAG) {
return false;
}
// Don't reflect the histogram if it's not allowed in this product.
if (!CanRecordProduct(gHistogramInfos[id].products)) {
return false;
}
return true;
}
/**
* Helper function to get a snapshot of the histograms.
*
* @param {aLock} the lock proof.
* @param {aStore} the name of the store to snapshot.
* @param {aDataset} the dataset for which the snapshot is being requested.
* @param {aClearSubsession} whether or not to clear the data after
* taking the snapshot.
* @param {aIncludeGPU} whether or not to include data for the GPU.
* @param {aOutSnapshot} the container in which the snapshot data will be
* stored.
* @return {nsresult} NS_OK if the snapshot was successfully taken or
* NS_ERROR_OUT_OF_MEMORY if it failed to allocate memory.
*/
nsresult internal_GetHistogramsSnapshot(
const StaticMutexAutoLock& aLock, const nsACString& aStore,
unsigned int aDataset, bool aClearSubsession, bool aIncludeGPU,
bool aFilterTest, HistogramProcessSnapshotsArray& aOutSnapshot) {
if (!aOutSnapshot.resize(static_cast<uint32_t>(ProcessID::Count))) {
return NS_ERROR_OUT_OF_MEMORY;
}
for (uint32_t process = 0; process < static_cast<uint32_t>(ProcessID::Count);
++process) {
HistogramSnapshotsArray& hArray = aOutSnapshot[process];
for (size_t i = 0; i < HistogramCount; ++i) {
const HistogramInfo& info = gHistogramInfos[i];
if (info.keyed) {
continue;
}
HistogramID id = HistogramID(i);
if (!CanRecordInProcess(info.record_in_processes, ProcessID(process)) ||
((ProcessID(process) == ProcessID::Gpu) && !aIncludeGPU)) {
continue;
}
if (!IsInDataset(info.dataset, aDataset)) {
continue;
}
bool shouldInstantiate =
info.histogramType == nsITelemetry::HISTOGRAM_FLAG;
Histogram* w = internal_GetHistogramById(aLock, id, ProcessID(process),
shouldInstantiate);
if (!w || w->IsExpired()) {
continue;
}
base::Histogram* h = nullptr;
if (!w->GetHistogram(aStore, &h)) {
continue;
}
if (!internal_ShouldReflectHistogram(aLock, h, id)) {
continue;
}
const char* name = info.name();
if (aFilterTest && strncmp(TEST_HISTOGRAM_PREFIX, name,
strlen(TEST_HISTOGRAM_PREFIX)) == 0) {
if (aClearSubsession) {
h->Clear();
}
continue;
}
HistogramSnapshotData snapshotData;
if (NS_FAILED(internal_GetHistogramAndSamples(aLock, h, snapshotData))) {
continue;
}
if (!hArray.emplaceBack(HistogramSnapshotInfo{snapshotData, id})) {
return NS_ERROR_OUT_OF_MEMORY;
}
if (aClearSubsession) {
h->Clear();
}
}
}
return NS_OK;
}
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE: class Histogram
namespace {
Histogram::Histogram(HistogramID histogramId, const HistogramInfo& info,
bool expired)
: mSingleStore(nullptr), mIsExpired(expired) {
if (IsExpired()) {
return;
}
const int bucketsOffset = gHistogramBucketLowerBoundIndex[histogramId];
if (info.is_single_store()) {
mSingleStore = internal_CreateBaseHistogramInstance(info, bucketsOffset);
} else {
for (uint32_t i = 0; i < info.store_count; i++) {
auto store = nsDependentCString(
&gHistogramStringTable[gHistogramStoresTable[info.store_index + i]]);
mStorage.InsertOrUpdate(store, UniquePtr<base::Histogram>(
internal_CreateBaseHistogramInstance(
info, bucketsOffset)));
}
}
}
Histogram::~Histogram() { delete mSingleStore; }
void Histogram::Add(uint32_t sample) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Only add to histograms in the parent process");
if (!XRE_IsParentProcess()) {
return;
}
if (IsExpired()) {
return;
}
if (mSingleStore != nullptr) {
mSingleStore->Add(sample);
} else {
for (auto iter = mStorage.Iter(); !iter.Done(); iter.Next()) {
auto& h = iter.Data();
h->Add(sample);
}
}
}
void Histogram::Clear(const nsACString& store) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Only clear histograms in the parent process");
if (!XRE_IsParentProcess()) {
return;
}
if (mSingleStore != nullptr) {
if (store.EqualsASCII("main")) {
mSingleStore->Clear();
}
} else {
base::Histogram* h = nullptr;
bool found = GetHistogram(store, &h);
if (!found) {
return;
}
MOZ_ASSERT(h, "Should have found a valid histogram in the named store");
h->Clear();
}
}
bool Histogram::GetHistogram(const nsACString& store, base::Histogram** h) {
MOZ_ASSERT(!IsExpired());
if (IsExpired()) {
return false;
}
if (mSingleStore != nullptr) {
if (store.EqualsASCII("main")) {
*h = mSingleStore;
return true;
}
return false;
}
return mStorage.Get(store, h);
}
size_t Histogram::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) {
size_t n = 0;
n += aMallocSizeOf(this);
/*
* In theory mStorage.SizeOfExcludingThis should included the data part of the
* map, but the numbers seemed low, so we are only taking the shallow size and
* do the iteration here.
*/
n += mStorage.ShallowSizeOfExcludingThis(aMallocSizeOf);
for (const auto& h : mStorage.Values()) {
n += h->SizeOfIncludingThis(aMallocSizeOf);
}
if (mSingleStore != nullptr) {
// base::Histogram doesn't have SizeOfExcludingThis, so we are overcounting
// the pointer here.
n += mSingleStore->SizeOfIncludingThis(aMallocSizeOf);
}
return n;
}
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE: class KeyedHistogram and internal_ReflectKeyedHistogram
namespace {
nsresult internal_ReflectKeyedHistogram(
const KeyedHistogramSnapshotData& aSnapshot, const HistogramInfo& info,
JSContext* aCx, JS::Handle<JSObject*> aObj) {
for (const auto& entry : aSnapshot) {
const HistogramSnapshotData& keyData = entry.GetData();
JS::Rooted<JSObject*> histogramSnapshot(aCx, JS_NewPlainObject(aCx));
if (!histogramSnapshot) {
return NS_ERROR_FAILURE;
}
if (NS_FAILED(internal_ReflectHistogramAndSamples(aCx, histogramSnapshot,
info, keyData))) {
return NS_ERROR_FAILURE;
}
const NS_ConvertUTF8toUTF16 key(entry.GetKey());
if (!JS_DefineUCProperty(aCx, aObj, key.Data(), key.Length(),
histogramSnapshot, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
}
return NS_OK;
}
KeyedHistogram::KeyedHistogram(HistogramID id, const HistogramInfo& info,
bool expired)
: mSingleStore(nullptr),
mId(id),
mHistogramInfo(info),
mIsExpired(expired) {
if (IsExpired()) {
return;
}
if (info.is_single_store()) {
mSingleStore = new KeyedHistogramMapType;
} else {
for (uint32_t i = 0; i < info.store_count; i++) {
auto store = nsDependentCString(
&gHistogramStringTable[gHistogramStoresTable[info.store_index + i]]);
mStorage.InsertOrUpdate(store, MakeUnique<KeyedHistogramMapType>());
}
}
}
KeyedHistogram::~KeyedHistogram() { delete mSingleStore; }
nsresult KeyedHistogram::GetHistogram(const nsCString& aStore,
const nsCString& key,
base::Histogram** histogram) {
if (IsExpired()) {
MOZ_ASSERT(false,
"KeyedHistogram::GetHistogram called on an expired histogram.");
return NS_ERROR_FAILURE;
}
KeyedHistogramMapType* histogramMap;
bool found;
if (mSingleStore != nullptr) {
histogramMap = mSingleStore;
} else {
found = mStorage.Get(aStore, &histogramMap);
if (!found) {
return NS_ERROR_FAILURE;
}
}
found = histogramMap->Get(key, histogram);
if (found) {
return NS_OK;
}
int bucketsOffset = gHistogramBucketLowerBoundIndex[mId];
auto h = UniquePtr<base::Histogram>{
internal_CreateBaseHistogramInstance(mHistogramInfo, bucketsOffset)};
if (!h) {
return NS_ERROR_FAILURE;
}
h->ClearFlags(base::Histogram::kUmaTargetedHistogramFlag);
*histogram = h.get();
bool inserted =
histogramMap->InsertOrUpdate(key, std::move(h), mozilla::fallible);
if (MOZ_UNLIKELY(!inserted)) {
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_OK;
}
base::Histogram* KeyedHistogram::GetHistogram(const nsCString& aStore,
const nsCString& key) {
base::Histogram* h = nullptr;
if (NS_FAILED(GetHistogram(aStore, key, &h))) {
return nullptr;
}
return h;
}
nsresult KeyedHistogram::Add(const nsCString& key, uint32_t sample,
ProcessID aProcessType) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Only add to keyed histograms in the parent process");
if (!XRE_IsParentProcess()) {
return NS_ERROR_FAILURE;
}
bool canRecordDataset =
CanRecordDataset(mHistogramInfo.dataset, internal_CanRecordBase(),
internal_CanRecordExtended());
// If `histogram` is a non-parent-process histogram, then recording-enabled
// has been checked in its owner process.
if (!canRecordDataset || (aProcessType == ProcessID::Parent &&
!internal_IsRecordingEnabled(mId))) {
return NS_OK;
}
// Don't record if expired.
if (IsExpired()) {
return NS_OK;
}
// Don't record if the current platform is not enabled
if (!CanRecordProduct(gHistogramInfos[mId].products)) {
return NS_OK;
}
// The internal representation of a base::Histogram's buckets uses `int`.
// Clamp large values of `sample` to be INT_MAX so they continue to be treated
// as large values (instead of negative ones).
if (sample > INT_MAX) {
TelemetryScalar::Add(
mozilla::Telemetry::ScalarID::TELEMETRY_ACCUMULATE_CLAMPED_VALUES,
NS_ConvertASCIItoUTF16(mHistogramInfo.name()), 1);
sample = INT_MAX;
}
base::Histogram* histogram;
if (mSingleStore != nullptr) {
histogram = GetHistogram("main"_ns, key);
if (!histogram) {
MOZ_ASSERT(false, "Missing histogram in single store.");
return NS_ERROR_FAILURE;
}
histogram->Add(sample);
} else {
for (uint32_t i = 0; i < mHistogramInfo.store_count; i++) {
auto store = nsDependentCString(
&gHistogramStringTable
[gHistogramStoresTable[mHistogramInfo.store_index + i]]);
base::Histogram* histogram = GetHistogram(store, key);
MOZ_ASSERT(histogram);
if (histogram) {
histogram->Add(sample);
} else {
return NS_ERROR_FAILURE;
}
}
}
return NS_OK;
}
void KeyedHistogram::Clear(const nsACString& aStore) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Only clear keyed histograms in the parent process");
if (!XRE_IsParentProcess()) {
return;
}
if (IsExpired()) {
return;
}
if (mSingleStore) {
if (aStore.EqualsASCII("main")) {
mSingleStore->Clear();
}
return;
}
KeyedHistogramMapType* histogramMap;
bool found = mStorage.Get(aStore, &histogramMap);
if (!found) {
return;
}
histogramMap->Clear();
}
bool KeyedHistogram::IsEmpty(const nsACString& aStore) const {
if (mSingleStore != nullptr) {
if (aStore.EqualsASCII("main")) {
return mSingleStore->IsEmpty();
}
return true;
}
KeyedHistogramMapType* histogramMap;
bool found = mStorage.Get(aStore, &histogramMap);
if (!found) {
return true;
}
return histogramMap->IsEmpty();
}
size_t KeyedHistogram::SizeOfIncludingThis(
mozilla::MallocSizeOf aMallocSizeOf) {
size_t n = 0;
n += aMallocSizeOf(this);
/*
* In theory mStorage.SizeOfExcludingThis should included the data part of the
* map, but the numbers seemed low, so we are only taking the shallow size and
* do the iteration here.
*/
n += mStorage.ShallowSizeOfExcludingThis(aMallocSizeOf);
for (const auto& h : mStorage.Values()) {
n += h->SizeOfIncludingThis(aMallocSizeOf);
}
if (mSingleStore != nullptr) {
// base::Histogram doesn't have SizeOfExcludingThis, so we are overcounting
// the pointer here.
n += mSingleStore->SizeOfExcludingThis(aMallocSizeOf);
}
return n;
}
nsresult KeyedHistogram::GetKeys(const StaticMutexAutoLock& aLock,
const nsCString& store,
nsTArray<nsCString>& aKeys) {
KeyedHistogramMapType* histogramMap;
if (mSingleStore != nullptr) {
histogramMap = mSingleStore;
} else {
bool found = mStorage.Get(store, &histogramMap);
if (!found) {
return NS_ERROR_FAILURE;
}
}
if (!aKeys.SetCapacity(histogramMap->Count(), mozilla::fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
for (const auto& key : histogramMap->Keys()) {
if (!aKeys.AppendElement(key, mozilla::fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
return NS_OK;
}
nsresult KeyedHistogram::GetJSSnapshot(JSContext* cx, JS::Handle<JSObject*> obj,
const nsACString& aStore,
bool clearSubsession) {
// Get a snapshot of the data.
KeyedHistogramSnapshotData dataSnapshot;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
MOZ_ASSERT(internal_IsHistogramEnumId(mId));
// Take a snapshot of the data here, protected by the lock, and then,
// outside of the lock protection, mirror it to a JS structure.
nsresult rv = GetSnapshot(locker, aStore, dataSnapshot, clearSubsession);
if (NS_FAILED(rv)) {
return rv;
}
}
// Now that we have a copy of the data, mirror it to JS.
return internal_ReflectKeyedHistogram(dataSnapshot, gHistogramInfos[mId], cx,
obj);
}
/**
* Return a histogram snapshot for the named store.
*
* If getting the snapshot succeeds, NS_OK is returned and `aSnapshot` contains
* the snapshot data. If the histogram is not available in the named store,
* NS_ERROR_NO_CONTENT is returned. For other errors, NS_ERROR_FAILURE is
* returned.
*/
nsresult KeyedHistogram::GetSnapshot(const StaticMutexAutoLock& aLock,
const nsACString& aStore,
KeyedHistogramSnapshotData& aSnapshot,
bool aClearSubsession) {
KeyedHistogramMapType* histogramMap;
if (mSingleStore != nullptr) {
if (!aStore.EqualsASCII("main")) {
return NS_ERROR_NO_CONTENT;
}
histogramMap = mSingleStore;
} else {
bool found = mStorage.Get(aStore, &histogramMap);
if (!found) {
// Nothing in the main store is fine, it's just handled as empty
return NS_ERROR_NO_CONTENT;
}
}
// Snapshot every key.
for (const auto& entry : *histogramMap) {
base::Histogram* keyData = entry.GetWeak();
if (!keyData) {
return NS_ERROR_FAILURE;
}
HistogramSnapshotData keySnapshot;
if (NS_FAILED(
internal_GetHistogramAndSamples(aLock, keyData, keySnapshot))) {
return NS_ERROR_FAILURE;
}
// Append to the final snapshot.
aSnapshot.InsertOrUpdate(entry.GetKey(), std::move(keySnapshot));
}
if (aClearSubsession) {
Clear(aStore);
}
return NS_OK;
}
/**
* Helper function to get a snapshot of the keyed histograms.
*
* @param {aLock} the lock proof.
* @param {aDataset} the dataset for which the snapshot is being requested.
* @param {aClearSubsession} whether or not to clear the data after
* taking the snapshot.
* @param {aIncludeGPU} whether or not to include data for the GPU.
* @param {aOutSnapshot} the container in which the snapshot data will be
* stored.
* @return {nsresult} NS_OK if the snapshot was successfully taken or
* NS_ERROR_OUT_OF_MEMORY if it failed to allocate memory.
*/
nsresult internal_GetKeyedHistogramsSnapshot(
const StaticMutexAutoLock& aLock, const nsACString& aStore,
unsigned int aDataset, bool aClearSubsession, bool aIncludeGPU,
bool aFilterTest, KeyedHistogramProcessSnapshotsArray& aOutSnapshot) {
if (!aOutSnapshot.resize(static_cast<uint32_t>(ProcessID::Count))) {
return NS_ERROR_OUT_OF_MEMORY;
}
for (uint32_t process = 0; process < static_cast<uint32_t>(ProcessID::Count);
++process) {
KeyedHistogramSnapshotsArray& hArray = aOutSnapshot[process];
for (size_t i = 0; i < HistogramCount; ++i) {
HistogramID id = HistogramID(i);
const HistogramInfo& info = gHistogramInfos[id];
if (!info.keyed) {
continue;
}
if (!CanRecordInProcess(info.record_in_processes, ProcessID(process)) ||
((ProcessID(process) == ProcessID::Gpu) && !aIncludeGPU)) {
continue;
}
if (!IsInDataset(info.dataset, aDataset)) {
continue;
}
KeyedHistogram* keyed =
internal_GetKeyedHistogramById(id, ProcessID(process),
/* instantiate = */ false);
if (!keyed || keyed->IsEmpty(aStore) || keyed->IsExpired()) {
continue;
}
const char* name = info.name();
if (aFilterTest && strncmp(TEST_HISTOGRAM_PREFIX, name,
strlen(TEST_HISTOGRAM_PREFIX)) == 0) {
if (aClearSubsession) {
keyed->Clear(aStore);
}
continue;
}
// Take a snapshot of the keyed histogram data!
KeyedHistogramSnapshotData snapshot;
if (!NS_SUCCEEDED(
keyed->GetSnapshot(aLock, aStore, snapshot, aClearSubsession))) {
return NS_ERROR_FAILURE;
}
if (!hArray.emplaceBack(
KeyedHistogramSnapshotInfo{std::move(snapshot), id})) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
}
return NS_OK;
}
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE: thread-unsafe helpers for the external interface
namespace {
bool internal_RemoteAccumulate(const StaticMutexAutoLock& aLock,
HistogramID aId, uint32_t aSample) {
if (XRE_IsParentProcess()) {
return false;
}
if (!internal_IsRecordingEnabled(aId)) {
return true;
}
TelemetryIPCAccumulator::AccumulateChildHistogram(aId, aSample);
return true;
}
bool internal_RemoteAccumulate(const StaticMutexAutoLock& aLock,
HistogramID aId, const nsCString& aKey,
uint32_t aSample) {
if (XRE_IsParentProcess()) {
return false;
}
if (!internal_IsRecordingEnabled(aId)) {
return true;
}
TelemetryIPCAccumulator::AccumulateChildKeyedHistogram(aId, aKey, aSample);
return true;
}
void internal_Accumulate(const StaticMutexAutoLock& aLock, HistogramID aId,
uint32_t aSample) {
if (!internal_CanRecordBase() ||
internal_RemoteAccumulate(aLock, aId, aSample)) {
return;
}
Histogram* w = internal_GetHistogramById(aLock, aId, ProcessID::Parent);
MOZ_ASSERT(w);
internal_HistogramAdd(aLock, *w, aId, aSample, ProcessID::Parent);
}
void internal_Accumulate(const StaticMutexAutoLock& aLock, HistogramID aId,
const nsCString& aKey, uint32_t aSample) {
if (!gInitDone || !internal_CanRecordBase() ||
internal_RemoteAccumulate(aLock, aId, aKey, aSample)) {
return;
}
KeyedHistogram* keyed =
internal_GetKeyedHistogramById(aId, ProcessID::Parent);
MOZ_ASSERT(keyed);
keyed->Add(aKey, aSample, ProcessID::Parent);
}
void internal_AccumulateChild(const StaticMutexAutoLock& aLock,
ProcessID aProcessType, HistogramID aId,
uint32_t aSample) {
if (!internal_CanRecordBase()) {
return;
}
Histogram* w = internal_GetHistogramById(aLock, aId, aProcessType);
if (w == nullptr) {
NS_WARNING("Failed GetHistogramById for CHILD");
} else {
internal_HistogramAdd(aLock, *w, aId, aSample, aProcessType);
}
}
void internal_AccumulateChildKeyed(const StaticMutexAutoLock& aLock,
ProcessID aProcessType, HistogramID aId,
const nsCString& aKey, uint32_t aSample) {
if (!gInitDone || !internal_CanRecordBase()) {
return;
}
KeyedHistogram* keyed = internal_GetKeyedHistogramById(aId, aProcessType);
MOZ_ASSERT(keyed);
keyed->Add(aKey, aSample, aProcessType);
}
void internal_ClearHistogram(const StaticMutexAutoLock& aLock, HistogramID id,
const nsACString& aStore) {
MOZ_ASSERT(XRE_IsParentProcess());
if (!XRE_IsParentProcess()) {
return;
}
// Handle keyed histograms.
if (gHistogramInfos[id].keyed) {
for (uint32_t process = 0;
process < static_cast<uint32_t>(ProcessID::Count); ++process) {
KeyedHistogram* kh = internal_GetKeyedHistogramById(
id, static_cast<ProcessID>(process), /* instantiate = */ false);
if (kh) {
kh->Clear(aStore);
}
}
} else {
// Reset the histograms instances for all processes.
for (uint32_t process = 0;
process < static_cast<uint32_t>(ProcessID::Count); ++process) {
Histogram* h =
internal_GetHistogramById(aLock, id, static_cast<ProcessID>(process),
/* instantiate = */ false);
if (h) {
h->Clear(aStore);
}
}
}
}
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE: JSHistogram_* functions
// NOTE: the functions in this section:
//
// internal_JSHistogram_Add
// internal_JSHistogram_Name
// internal_JSHistogram_Snapshot
// internal_JSHistogram_Clear
// internal_WrapAndReturnHistogram
//
// all run without protection from |gTelemetryHistogramMutex|. If they
// held |gTelemetryHistogramMutex|, there would be the possibility of
// deadlock because the JS_ calls that they make may call back into the
// TelemetryHistogram interface, hence trying to re-acquire the mutex.
//
// This means that these functions potentially race against threads, but
// that seems preferable to risking deadlock.
namespace {
static constexpr uint32_t HistogramObjectDataSlot = 0;
static constexpr uint32_t HistogramObjectSlotCount =
HistogramObjectDataSlot + 1;
void internal_JSHistogram_finalize(JS::GCContext*, JSObject*);
static const JSClassOps sJSHistogramClassOps = {nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
internal_JSHistogram_finalize};
static const JSClass sJSHistogramClass = {
"JSHistogram", /* name */
JSCLASS_HAS_RESERVED_SLOTS(HistogramObjectSlotCount) |
JSCLASS_FOREGROUND_FINALIZE, /* flags */
&sJSHistogramClassOps};
struct JSHistogramData {
HistogramID histogramId;
};
bool internal_JSHistogram_CoerceValue(JSContext* aCx,
JS::Handle<JS::Value> aElement,
HistogramID aId, uint32_t aHistogramType,
uint32_t& aValue) {
if (aElement.isString()) {
// Strings only allowed for categorical histograms
if (aHistogramType != nsITelemetry::HISTOGRAM_CATEGORICAL) {
LogToBrowserConsole(
nsIScriptError::errorFlag,
nsLiteralString(
u"String argument only allowed for categorical histogram"));
return false;
}
// Label is given by the string argument
nsAutoJSString label;
if (!label.init(aCx, aElement)) {
LogToBrowserConsole(nsIScriptError::errorFlag,
u"Invalid string parameter"_ns);
return false;
}
// Get the label id for accumulation
nsresult rv = gHistogramInfos[aId].label_id(
NS_ConvertUTF16toUTF8(label).get(), &aValue);
if (NS_FAILED(rv)) {
nsPrintfCString msg("'%s' is an invalid string label",
NS_ConvertUTF16toUTF8(label).get());
LogToBrowserConsole(nsIScriptError::errorFlag,
NS_ConvertUTF8toUTF16(msg));
return false;
}
} else if (!(aElement.isNumber() || aElement.isBoolean())) {
LogToBrowserConsole(nsIScriptError::errorFlag, u"Argument not a number"_ns);
return false;
} else if (aElement.isNumber() && aElement.toNumber() > UINT32_MAX) {
// Clamp large numerical arguments to aValue's acceptable values.
// JS::ToUint32 will take aElement modulo 2^32 before returning it, which
// may result in a smaller final value.
aValue = UINT32_MAX;
#ifdef DEBUG
LogToBrowserConsole(nsIScriptError::errorFlag,
u"Clamped large numeric value"_ns);
#endif
} else if (!JS::ToUint32(aCx, aElement, &aValue)) {
LogToBrowserConsole(nsIScriptError::errorFlag,
u"Failed to convert element to UInt32"_ns);
return false;
}
// If we're here then all type checks have passed and aValue contains the
// coerced integer
return true;
}
bool internal_JSHistogram_GetValueArray(JSContext* aCx, JS::CallArgs& args,
uint32_t aHistogramType,
HistogramID aId, bool isKeyed,
nsTArray<uint32_t>& aArray) {
// This function populates aArray with the values extracted from args. Handles
// keyed and non-keyed histograms, and single and array of values. Also
// performs sanity checks on the arguments. Returns true upon successful
// population, false otherwise.
uint32_t firstArgIndex = 0;
if (isKeyed) {
firstArgIndex = 1;
}
// Special case of no argument (or only key) and count histogram
if (args.length() == firstArgIndex) {
if (!(aHistogramType == nsITelemetry::HISTOGRAM_COUNT)) {
LogToBrowserConsole(
nsIScriptError::errorFlag,
nsLiteralString(
u"Need at least one argument for non count type histogram"));
return false;
}
aArray.AppendElement(1);
return true;
}
if (args[firstArgIndex].isObject() && !args[firstArgIndex].isString()) {
JS::Rooted<JSObject*> arrayObj(aCx, &args[firstArgIndex].toObject());
bool isArray = false;
JS::IsArrayObject(aCx, arrayObj, &isArray);
if (!isArray) {
LogToBrowserConsole(
nsIScriptError::errorFlag,
nsLiteralString(
u"The argument to accumulate can't be a non-array object"));
return false;
}
uint32_t arrayLength = 0;
if (!JS::GetArrayLength(aCx, arrayObj, &arrayLength)) {
LogToBrowserConsole(nsIScriptError::errorFlag,
u"Failed while trying to get array length"_ns);
return false;
}
for (uint32_t arrayIdx = 0; arrayIdx < arrayLength; arrayIdx++) {
JS::Rooted<JS::Value> element(aCx);
if (!JS_GetElement(aCx, arrayObj, arrayIdx, &element)) {
nsPrintfCString msg("Failed while trying to get element at index %d",
arrayIdx);
LogToBrowserConsole(nsIScriptError::errorFlag,
NS_ConvertUTF8toUTF16(msg));
return false;
}
uint32_t value = 0;
if (!internal_JSHistogram_CoerceValue(aCx, element, aId, aHistogramType,
value)) {
nsPrintfCString msg("Element at index %d failed type checks", arrayIdx);
LogToBrowserConsole(nsIScriptError::errorFlag,
NS_ConvertUTF8toUTF16(msg));
return false;
}
aArray.AppendElement(value);
}
return true;
}
uint32_t value = 0;
if (!internal_JSHistogram_CoerceValue(aCx, args[firstArgIndex], aId,
aHistogramType, value)) {
return false;
}
aArray.AppendElement(value);
return true;
}
static JSHistogramData* GetJSHistogramData(JSObject* obj) {
MOZ_ASSERT(JS::GetClass(obj) == &sJSHistogramClass);
return JS::GetMaybePtrFromReservedSlot<JSHistogramData>(
obj, HistogramObjectDataSlot);
}
bool internal_JSHistogram_Add(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = CallArgsFromVp(argc, vp);
if (!args.thisv().isObject() ||
JS::GetClass(&args.thisv().toObject()) != &sJSHistogramClass) {
JS_ReportErrorASCII(cx, "Wrong JS class, expected JSHistogram class");
return false;
}
JSObject* obj = &args.thisv().toObject();
JSHistogramData* data = GetJSHistogramData(obj);
MOZ_ASSERT(data);
HistogramID id = data->histogramId;
MOZ_ASSERT(internal_IsHistogramEnumId(id));
uint32_t type = gHistogramInfos[id].histogramType;
// This function should always return |undefined| and never fail but
// rather report failures using the console.
args.rval().setUndefined();
nsTArray<uint32_t> values;
if (!internal_JSHistogram_GetValueArray(cx, args, type, id, false, values)) {
// Either GetValueArray or CoerceValue utility function will have printed a
// meaningful error message, so we simply return true
return true;
}
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
for (uint32_t aValue : values) {
internal_Accumulate(locker, id, aValue);
}
}
return true;
}
bool internal_JSHistogram_Name(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = CallArgsFromVp(argc, vp);
if (!args.thisv().isObject() ||
JS::GetClass(&args.thisv().toObject()) != &sJSHistogramClass) {
JS_ReportErrorASCII(cx, "Wrong JS class, expected JSHistogram class");
return false;
}
JSObject* obj = &args.thisv().toObject();
JSHistogramData* data = GetJSHistogramData(obj);
MOZ_ASSERT(data);
HistogramID id = data->histogramId;
MOZ_ASSERT(internal_IsHistogramEnumId(id));
const char* name = gHistogramInfos[id].name();
auto cname = NS_ConvertASCIItoUTF16(name);
args.rval().setString(ToJSString(cx, cname));
return true;
}
/**
* Extract the store name from JavaScript function arguments.
* The first and only argument needs to be an object with a "store" property.
* If no arguments are given it defaults to "main".
*/
nsresult internal_JS_StoreFromObjectArgument(JSContext* cx,
const JS::CallArgs& args,
nsAutoString& aStoreName) {
if (args.length() == 0) {
aStoreName.AssignLiteral("main");
} else if (args.length() == 1) {
if (!args[0].isObject()) {
JS_ReportErrorASCII(cx, "Expected object argument.");
return NS_ERROR_FAILURE;
}
JS::Rooted<JS::Value> storeValue(cx);
JS::Rooted<JSObject*> argsObject(cx, &args[0].toObject());
if (!JS_GetProperty(cx, argsObject, "store", &storeValue)) {
JS_ReportErrorASCII(cx,
"Expected object argument to have property 'store'.");
return NS_ERROR_FAILURE;
}
nsAutoJSString store;
if (!storeValue.isString() || !store.init(cx, storeValue)) {
JS_ReportErrorASCII(
cx, "Expected object argument's 'store' property to be a string.");
return NS_ERROR_FAILURE;
}
aStoreName.Assign(store);
} else {
JS_ReportErrorASCII(cx, "Expected at most one argument.");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
bool internal_JSHistogram_Snapshot(JSContext* cx, unsigned argc,
JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (!XRE_IsParentProcess()) {
JS_ReportErrorASCII(
cx, "Histograms can only be snapshotted in the parent process");
return false;
}
if (!args.thisv().isObject() ||
JS::GetClass(&args.thisv().toObject()) != &sJSHistogramClass) {
JS_ReportErrorASCII(cx, "Wrong JS class, expected JSHistogram class");
return false;
}
JSObject* obj = &args.thisv().toObject();
JSHistogramData* data = GetJSHistogramData(obj);
MOZ_ASSERT(data);
HistogramID id = data->histogramId;
nsAutoString storeName;
nsresult rv = internal_JS_StoreFromObjectArgument(cx, args, storeName);
if (NS_FAILED(rv)) {
return false;
}
HistogramSnapshotData dataSnapshot;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
MOZ_ASSERT(internal_IsHistogramEnumId(id));
// This is not good standard behavior given that we have histogram instances
// covering multiple processes.
// However, changing this requires some broader changes to callers.
Histogram* w = internal_GetHistogramById(locker, id, ProcessID::Parent);
base::Histogram* h = nullptr;
if (!w->GetHistogram(NS_ConvertUTF16toUTF8(storeName), &h)) {
// When it's not in the named store, let's skip the snapshot completely,
// but don't fail
args.rval().setUndefined();
return true;
}
// Take a snapshot of the data here, protected by the lock, and then,
// outside of the lock protection, mirror it to a JS structure
if (NS_FAILED(internal_GetHistogramAndSamples(locker, h, dataSnapshot))) {
return false;
}
}
JS::Rooted<JSObject*> snapshot(cx, JS_NewPlainObject(cx));
if (!snapshot) {
return false;
}
if (NS_FAILED(internal_ReflectHistogramAndSamples(
cx, snapshot, gHistogramInfos[id], dataSnapshot))) {
return false;
}
args.rval().setObject(*snapshot);
return true;
}
bool internal_JSHistogram_Clear(JSContext* cx, unsigned argc, JS::Value* vp) {
if (!XRE_IsParentProcess()) {
JS_ReportErrorASCII(cx,
"Histograms can only be cleared in the parent process");
return false;
}
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (!args.thisv().isObject() ||
JS::GetClass(&args.thisv().toObject()) != &sJSHistogramClass) {
JS_ReportErrorASCII(cx, "Wrong JS class, expected JSHistogram class");
return false;
}
JSObject* obj = &args.thisv().toObject();
JSHistogramData* data = GetJSHistogramData(obj);
MOZ_ASSERT(data);
nsAutoString storeName;
nsresult rv = internal_JS_StoreFromObjectArgument(cx, args, storeName);
if (NS_FAILED(rv)) {
return false;
}
// This function should always return |undefined| and never fail but
// rather report failures using the console.
args.rval().setUndefined();
HistogramID id = data->histogramId;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
MOZ_ASSERT(internal_IsHistogramEnumId(id));
internal_ClearHistogram(locker, id, NS_ConvertUTF16toUTF8(storeName));
}
return true;
}
// NOTE: Runs without protection from |gTelemetryHistogramMutex|.
// See comment at the top of this section.
nsresult internal_WrapAndReturnHistogram(HistogramID id, JSContext* cx,
JS::MutableHandle<JS::Value> ret) {
JS::Rooted<JSObject*> obj(cx, JS_NewObject(cx, &sJSHistogramClass));
if (!obj) {
return NS_ERROR_FAILURE;
}
// The 3 functions that are wrapped up here are eventually called
// by the same thread that runs this function.
if (!(JS_DefineFunction(cx, obj, "add", internal_JSHistogram_Add, 1, 0) &&
JS_DefineFunction(cx, obj, "name", internal_JSHistogram_Name, 1, 0) &&
JS_DefineFunction(cx, obj, "snapshot", internal_JSHistogram_Snapshot, 1,
0) &&
JS_DefineFunction(cx, obj, "clear", internal_JSHistogram_Clear, 1,
0))) {
return NS_ERROR_FAILURE;
}
JSHistogramData* data = new JSHistogramData{id};
JS::SetReservedSlot(obj, HistogramObjectDataSlot, JS::PrivateValue(data));
ret.setObject(*obj);
return NS_OK;
}
void internal_JSHistogram_finalize(JS::GCContext* gcx, JSObject* obj) {
if (!obj || JS::GetClass(obj) != &sJSHistogramClass) {
MOZ_ASSERT_UNREACHABLE("Should have the right JS class.");
return;
}
JSHistogramData* data = GetJSHistogramData(obj);
MOZ_ASSERT(data);
delete data;
}
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE: JSKeyedHistogram_* functions
// NOTE: the functions in this section:
//
// internal_JSKeyedHistogram_Add
// internal_JSKeyedHistogram_Name
// internal_JSKeyedHistogram_Keys
// internal_JSKeyedHistogram_Snapshot
// internal_JSKeyedHistogram_Clear
// internal_WrapAndReturnKeyedHistogram
//
// Same comments as above, at the JSHistogram_* section, regarding
// deadlock avoidance, apply.
namespace {
void internal_JSKeyedHistogram_finalize(JS::GCContext*, JSObject*);
static const JSClassOps sJSKeyedHistogramClassOps = {
nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
internal_JSKeyedHistogram_finalize};
static const JSClass sJSKeyedHistogramClass = {
"JSKeyedHistogram", /* name */
JSCLASS_HAS_RESERVED_SLOTS(HistogramObjectSlotCount) |
JSCLASS_FOREGROUND_FINALIZE, /* flags */
&sJSKeyedHistogramClassOps};
static JSHistogramData* GetJSKeyedHistogramData(JSObject* obj) {
MOZ_ASSERT(JS::GetClass(obj) == &sJSKeyedHistogramClass);
return JS::GetMaybePtrFromReservedSlot<JSHistogramData>(
obj, HistogramObjectDataSlot);
}
bool internal_JSKeyedHistogram_Snapshot(JSContext* cx, unsigned argc,
JS::Value* vp) {
if (!XRE_IsParentProcess()) {
JS_ReportErrorASCII(
cx, "Keyed histograms can only be snapshotted in the parent process");
return false;
}
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (!args.thisv().isObject() ||
JS::GetClass(&args.thisv().toObject()) != &sJSKeyedHistogramClass) {
JS_ReportErrorASCII(cx, "Wrong JS class, expected JSKeyedHistogram class");
return false;
}
JSObject* obj = &args.thisv().toObject();
JSHistogramData* data = GetJSKeyedHistogramData(obj);
MOZ_ASSERT(data);
HistogramID id = data->histogramId;
MOZ_ASSERT(internal_IsHistogramEnumId(id));
// This function should always return |undefined| and never fail but
// rather report failures using the console.
args.rval().setUndefined();
// This is not good standard behavior given that we have histogram instances
// covering multiple processes.
// However, changing this requires some broader changes to callers.
KeyedHistogram* keyed = internal_GetKeyedHistogramById(
id, ProcessID::Parent, /* instantiate = */ true);
if (!keyed) {
JS_ReportErrorASCII(cx, "Failed to look up keyed histogram");
return false;
}
nsAutoString storeName;
nsresult rv;
rv = internal_JS_StoreFromObjectArgument(cx, args, storeName);
if (NS_FAILED(rv)) {
return false;
}
JS::Rooted<JSObject*> snapshot(cx, JS_NewPlainObject(cx));
if (!snapshot) {
JS_ReportErrorASCII(cx, "Failed to create object");
return false;
}
rv = keyed->GetJSSnapshot(cx, snapshot, NS_ConvertUTF16toUTF8(storeName),
false);
// If the store is not available, we return nothing and don't fail
if (rv == NS_ERROR_NO_CONTENT) {
args.rval().setUndefined();
return true;
}
if (!NS_SUCCEEDED(rv)) {
JS_ReportErrorASCII(cx, "Failed to reflect keyed histograms");
return false;
}
args.rval().setObject(*snapshot);
return true;
}
bool internal_JSKeyedHistogram_Add(JSContext* cx, unsigned argc,
JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (!args.thisv().isObject() ||
JS::GetClass(&args.thisv().toObject()) != &sJSKeyedHistogramClass) {
JS_ReportErrorASCII(cx, "Wrong JS class, expected JSKeyedHistogram class");
return false;
}
JSObject* obj = &args.thisv().toObject();
JSHistogramData* data = GetJSKeyedHistogramData(obj);
MOZ_ASSERT(data);
HistogramID id = data->histogramId;
MOZ_ASSERT(internal_IsHistogramEnumId(id));
// This function should always return |undefined| and never fail but
// rather report failures using the console.
args.rval().setUndefined();
if (args.length() < 1) {
LogToBrowserConsole(nsIScriptError::errorFlag, u"Expected one argument"_ns);
return true;
}
nsAutoJSString key;
if (!args[0].isString() || !key.init(cx, args[0])) {
LogToBrowserConsole(nsIScriptError::errorFlag, u"Not a string"_ns);
return true;
}
// Check if we're allowed to record in the provided key, for this histogram.
if (!gHistogramInfos[id].allows_key(NS_ConvertUTF16toUTF8(key))) {
nsPrintfCString msg("%s - key '%s' not allowed for this keyed histogram",
gHistogramInfos[id].name(),
NS_ConvertUTF16toUTF8(key).get());
LogToBrowserConsole(nsIScriptError::errorFlag, NS_ConvertUTF8toUTF16(msg));
TelemetryScalar::Add(mozilla::Telemetry::ScalarID::
TELEMETRY_ACCUMULATE_UNKNOWN_HISTOGRAM_KEYS,
NS_ConvertASCIItoUTF16(gHistogramInfos[id].name()), 1);
return true;
}
const uint32_t type = gHistogramInfos[id].histogramType;
nsTArray<uint32_t> values;
if (!internal_JSHistogram_GetValueArray(cx, args, type, id, true, values)) {
// Either GetValueArray or CoerceValue utility function will have printed a
// meaningful error message so we simple return true
return true;
}
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
for (uint32_t aValue : values) {
internal_Accumulate(locker, id, NS_ConvertUTF16toUTF8(key), aValue);
}
}
return true;
}
bool internal_JSKeyedHistogram_Name(JSContext* cx, unsigned argc,
JS::Value* vp) {
JS::CallArgs args = CallArgsFromVp(argc, vp);
if (!args.thisv().isObject() ||
JS::GetClass(&args.thisv().toObject()) != &sJSKeyedHistogramClass) {
JS_ReportErrorASCII(cx, "Wrong JS class, expected JSKeyedHistogram class");
return false;
}
JSObject* obj = &args.thisv().toObject();
JSHistogramData* data = GetJSKeyedHistogramData(obj);
MOZ_ASSERT(data);
HistogramID id = data->histogramId;
MOZ_ASSERT(internal_IsHistogramEnumId(id));
const char* name = gHistogramInfos[id].name();
auto cname = NS_ConvertASCIItoUTF16(name);
args.rval().setString(ToJSString(cx, cname));
return true;
}
bool internal_JSKeyedHistogram_Keys(JSContext* cx, unsigned argc,
JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (!args.thisv().isObject() ||
JS::GetClass(&args.thisv().toObject()) != &sJSKeyedHistogramClass) {
JS_ReportErrorASCII(cx, "Wrong JS class, expected JSKeyedHistogram class");
return false;
}
JSObject* obj = &args.thisv().toObject();
JSHistogramData* data = GetJSKeyedHistogramData(obj);
MOZ_ASSERT(data);
HistogramID id = data->histogramId;
nsAutoString storeName;
nsresult rv = internal_JS_StoreFromObjectArgument(cx, args, storeName);
if (NS_FAILED(rv)) {
return false;
}
nsTArray<nsCString> keys;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
MOZ_ASSERT(internal_IsHistogramEnumId(id));
// This is not good standard behavior given that we have histogram instances
// covering multiple processes.
// However, changing this requires some broader changes to callers.
KeyedHistogram* keyed =
internal_GetKeyedHistogramById(id, ProcessID::Parent);
MOZ_ASSERT(keyed);
if (!keyed) {
return false;
}
if (NS_FAILED(
keyed->GetKeys(locker, NS_ConvertUTF16toUTF8(storeName), keys))) {
return false;
}
}
// Convert keys from nsTArray<nsCString> to JS array.
JS::RootedVector<JS::Value> autoKeys(cx);
if (!autoKeys.reserve(keys.Length())) {
return false;
}
for (const auto& key : keys) {
JS::Rooted<JS::Value> jsKey(cx);
jsKey.setString(ToJSString(cx, key));
if (!autoKeys.append(jsKey)) {
return false;
}
}
JS::Rooted<JSObject*> jsKeys(cx, JS::NewArrayObject(cx, autoKeys));
if (!jsKeys) {
return false;
}
args.rval().setObject(*jsKeys);
return true;
}
bool internal_JSKeyedHistogram_Clear(JSContext* cx, unsigned argc,
JS::Value* vp) {
if (!XRE_IsParentProcess()) {
JS_ReportErrorASCII(
cx, "Keyed histograms can only be cleared in the parent process");
return false;
}
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (!args.thisv().isObject() ||
JS::GetClass(&args.thisv().toObject()) != &sJSKeyedHistogramClass) {
JS_ReportErrorASCII(cx, "Wrong JS class, expected JSKeyedHistogram class");
return false;
}
JSObject* obj = &args.thisv().toObject();
JSHistogramData* data = GetJSKeyedHistogramData(obj);
MOZ_ASSERT(data);
HistogramID id = data->histogramId;
// This function should always return |undefined| and never fail but
// rather report failures using the console.
args.rval().setUndefined();
nsAutoString storeName;
nsresult rv = internal_JS_StoreFromObjectArgument(cx, args, storeName);
if (NS_FAILED(rv)) {
return false;
}
KeyedHistogram* keyed = nullptr;
{
MOZ_ASSERT(internal_IsHistogramEnumId(id));
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
// This is not good standard behavior given that we have histogram instances
// covering multiple processes.
// However, changing this requires some broader changes to callers.
keyed = internal_GetKeyedHistogramById(id, ProcessID::Parent,
/* instantiate = */ false);
if (!keyed) {
return true;
}
keyed->Clear(NS_ConvertUTF16toUTF8(storeName));
}
return true;
}
// NOTE: Runs without protection from |gTelemetryHistogramMutex|.
// See comment at the top of this section.
nsresult internal_WrapAndReturnKeyedHistogram(
HistogramID id, JSContext* cx, JS::MutableHandle<JS::Value> ret) {
JS::Rooted<JSObject*> obj(cx, JS_NewObject(cx, &sJSKeyedHistogramClass));
if (!obj) return NS_ERROR_FAILURE;
// The 6 functions that are wrapped up here are eventually called
// by the same thread that runs this function.
if (!(JS_DefineFunction(cx, obj, "add", internal_JSKeyedHistogram_Add, 2,
0) &&
JS_DefineFunction(cx, obj, "name", internal_JSKeyedHistogram_Name, 1,
0) &&
JS_DefineFunction(cx, obj, "snapshot",
internal_JSKeyedHistogram_Snapshot, 1, 0) &&
JS_DefineFunction(cx, obj, "keys", internal_JSKeyedHistogram_Keys, 1,
0) &&
JS_DefineFunction(cx, obj, "clear", internal_JSKeyedHistogram_Clear, 1,
0))) {
return NS_ERROR_FAILURE;
}
JSHistogramData* data = new JSHistogramData{id};
JS::SetReservedSlot(obj, HistogramObjectDataSlot, JS::PrivateValue(data));
ret.setObject(*obj);
return NS_OK;
}
void internal_JSKeyedHistogram_finalize(JS::GCContext* gcx, JSObject* obj) {
if (!obj || JS::GetClass(obj) != &sJSKeyedHistogramClass) {
MOZ_ASSERT_UNREACHABLE("Should have the right JS class.");
return;
}
JSHistogramData* data = GetJSKeyedHistogramData(obj);
MOZ_ASSERT(data);
delete data;
}
} // namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// EXTERNALLY VISIBLE FUNCTIONS in namespace TelemetryHistogram::
// All of these functions are actually in namespace TelemetryHistogram::,
// but the ::TelemetryHistogram prefix is given explicitly. This is
// because it is critical to see which calls from these functions are
// to another function in this interface. Mis-identifying "inwards
// calls" from "calls to another function in this interface" will lead
// to deadlocking and/or races. See comments at the top of the file
// for further (important!) details.
void TelemetryHistogram::InitializeGlobalState(bool canRecordBase,
bool canRecordExtended) {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
MOZ_ASSERT(!gInitDone,
"TelemetryHistogram::InitializeGlobalState "
"may only be called once");
gCanRecordBase = canRecordBase;
gCanRecordExtended = canRecordExtended;
if (XRE_IsParentProcess()) {
gHistogramStorage =
new Histogram* [HistogramCount * size_t(ProcessID::Count)] {};
gKeyedHistogramStorage =
new KeyedHistogram* [HistogramCount * size_t(ProcessID::Count)] {};
}
// Some Telemetry histograms depend on the value of C++ constants and hardcode
// their values in Histograms.json.
// We add static asserts here for those values to match so that future changes
// don't go unnoticed.
// clang-format off
static_assert((uint32_t(JS::GCReason::NUM_TELEMETRY_REASONS) + 1) ==
gHistogramInfos[mozilla::Telemetry::GC_MINOR_REASON].bucketCount &&
(uint32_t(JS::GCReason::NUM_TELEMETRY_REASONS) + 1) ==
gHistogramInfos[mozilla::Telemetry::GC_MINOR_REASON_LONG].bucketCount &&
(uint32_t(JS::GCReason::NUM_TELEMETRY_REASONS) + 1) ==
gHistogramInfos[mozilla::Telemetry::GC_REASON_2].bucketCount,
"NUM_TELEMETRY_REASONS is assumed to be a fixed value in Histograms.json."
" If this was an intentional change, update the n_values for the "
"following in Histograms.json: GC_MINOR_REASON, GC_MINOR_REASON_LONG, "
"GC_REASON_2");
// clang-format on
gInitDone = true;
}
void TelemetryHistogram::DeInitializeGlobalState() {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
gCanRecordBase = false;
gCanRecordExtended = false;
gInitDone = false;
// FactoryGet `new`s Histograms for us, but requires us to manually delete.
if (XRE_IsParentProcess()) {
for (size_t i = 0; i < HistogramCount * size_t(ProcessID::Count); ++i) {
if (gKeyedHistogramStorage[i] != gExpiredKeyedHistogram) {
delete gKeyedHistogramStorage[i];
}
if (gHistogramStorage[i] != gExpiredHistogram) {
delete gHistogramStorage[i];
}
}
delete[] gHistogramStorage;
delete[] gKeyedHistogramStorage;
}
delete gExpiredHistogram;
gExpiredHistogram = nullptr;
delete gExpiredKeyedHistogram;
gExpiredKeyedHistogram = nullptr;
}
#ifdef DEBUG
bool TelemetryHistogram::GlobalStateHasBeenInitialized() {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
return gInitDone;
}
#endif
bool TelemetryHistogram::CanRecordBase() {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
return internal_CanRecordBase();
}
void TelemetryHistogram::SetCanRecordBase(bool b) {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
gCanRecordBase = b;
}
bool TelemetryHistogram::CanRecordExtended() {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
return internal_CanRecordExtended();
}
void TelemetryHistogram::SetCanRecordExtended(bool b) {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
gCanRecordExtended = b;
}
void TelemetryHistogram::InitHistogramRecordingEnabled() {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
auto processType = XRE_GetProcessType();
for (size_t i = 0; i < HistogramCount; ++i) {
const HistogramInfo& h = gHistogramInfos[i];
mozilla::Telemetry::HistogramID id = mozilla::Telemetry::HistogramID(i);
bool canRecordInProcess =
CanRecordInProcess(h.record_in_processes, processType);
internal_SetHistogramRecordingEnabled(locker, id, canRecordInProcess);
}
for (auto recordingInitiallyDisabledID : kRecordingInitiallyDisabledIDs) {
internal_SetHistogramRecordingEnabled(locker, recordingInitiallyDisabledID,
false);
}
}
void TelemetryHistogram::SetHistogramRecordingEnabled(HistogramID aID,
bool aEnabled) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(aID))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids.");
return;
}
const HistogramInfo& h = gHistogramInfos[aID];
if (!CanRecordInProcess(h.record_in_processes, XRE_GetProcessType())) {
// Don't permit record_in_process-disabled recording to be re-enabled.
return;
}
if (!CanRecordProduct(h.products)) {
// Don't permit products-disabled recording to be re-enabled.
return;
}
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
internal_SetHistogramRecordingEnabled(locker, aID, aEnabled);
}
nsresult TelemetryHistogram::SetHistogramRecordingEnabled(
const nsACString& name, bool aEnabled) {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
HistogramID id;
if (NS_FAILED(internal_GetHistogramIdByName(locker, name, &id))) {
return NS_ERROR_FAILURE;
}
const HistogramInfo& hi = gHistogramInfos[id];
if (CanRecordInProcess(hi.record_in_processes, XRE_GetProcessType())) {
internal_SetHistogramRecordingEnabled(locker, id, aEnabled);
}
return NS_OK;
}
void TelemetryHistogram::Accumulate(HistogramID aID, uint32_t aSample) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(aID))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids.");
return;
}
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
internal_Accumulate(locker, aID, aSample);
}
void TelemetryHistogram::Accumulate(HistogramID aID,
const nsTArray<uint32_t>& aSamples) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(aID))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids.");
return;
}
MOZ_ASSERT(!gHistogramInfos[aID].keyed,
"Cannot accumulate into a keyed histogram. No key given.");
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
for (uint32_t sample : aSamples) {
internal_Accumulate(locker, aID, sample);
}
}
void TelemetryHistogram::Accumulate(HistogramID aID, const nsCString& aKey,
uint32_t aSample) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(aID))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids.");
return;
}
// Check if we're allowed to record in the provided key, for this histogram.
if (!gHistogramInfos[aID].allows_key(aKey)) {
nsPrintfCString msg("%s - key '%s' not allowed for this keyed histogram",
gHistogramInfos[aID].name(), aKey.get());
LogToBrowserConsole(nsIScriptError::errorFlag, NS_ConvertUTF8toUTF16(msg));
TelemetryScalar::Add(mozilla::Telemetry::ScalarID::
TELEMETRY_ACCUMULATE_UNKNOWN_HISTOGRAM_KEYS,
NS_ConvertASCIItoUTF16(gHistogramInfos[aID].name()),
1);
return;
}
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
internal_Accumulate(locker, aID, aKey, aSample);
}
void TelemetryHistogram::Accumulate(HistogramID aID, const nsCString& aKey,
const nsTArray<uint32_t>& aSamples) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(aID))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids");
return;
}
// Check that this histogram is keyed
MOZ_ASSERT(gHistogramInfos[aID].keyed,
"Cannot accumulate into a non-keyed histogram using a key.");
// Check if we're allowed to record in the provided key, for this histogram.
if (!gHistogramInfos[aID].allows_key(aKey)) {
nsPrintfCString msg("%s - key '%s' not allowed for this keyed histogram",
gHistogramInfos[aID].name(), aKey.get());
LogToBrowserConsole(nsIScriptError::errorFlag, NS_ConvertUTF8toUTF16(msg));
TelemetryScalar::Add(mozilla::Telemetry::ScalarID::
TELEMETRY_ACCUMULATE_UNKNOWN_HISTOGRAM_KEYS,
NS_ConvertASCIItoUTF16(gHistogramInfos[aID].name()),
1);
return;
}
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
for (uint32_t sample : aSamples) {
internal_Accumulate(locker, aID, aKey, sample);
}
}
nsresult TelemetryHistogram::Accumulate(const char* name, uint32_t sample) {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
if (!internal_CanRecordBase()) {
return NS_ERROR_NOT_AVAILABLE;
}
HistogramID id;
nsresult rv =
internal_GetHistogramIdByName(locker, nsDependentCString(name), &id);
if (NS_FAILED(rv)) {
return rv;
}
internal_Accumulate(locker, id, sample);
return NS_OK;
}
nsresult TelemetryHistogram::Accumulate(const char* name, const nsCString& key,
uint32_t sample) {
bool keyNotAllowed = false;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
if (!internal_CanRecordBase()) {
return NS_ERROR_NOT_AVAILABLE;
}
HistogramID id;
nsresult rv =
internal_GetHistogramIdByName(locker, nsDependentCString(name), &id);
if (NS_SUCCEEDED(rv)) {
// Check if we're allowed to record in the provided key, for this
// histogram.
if (gHistogramInfos[id].allows_key(key)) {
internal_Accumulate(locker, id, key, sample);
return NS_OK;
}
// We're holding |gTelemetryHistogramMutex|, so we can't print a message
// here.
keyNotAllowed = true;
}
}
if (keyNotAllowed) {
LogToBrowserConsole(nsIScriptError::errorFlag,
u"Key not allowed for this keyed histogram"_ns);
TelemetryScalar::Add(mozilla::Telemetry::ScalarID::
TELEMETRY_ACCUMULATE_UNKNOWN_HISTOGRAM_KEYS,
NS_ConvertASCIItoUTF16(name), 1);
}
return NS_ERROR_FAILURE;
}
void TelemetryHistogram::AccumulateCategorical(HistogramID aId,
const nsCString& label) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(aId))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids.");
return;
}
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
if (!internal_CanRecordBase()) {
return;
}
uint32_t labelId = 0;
if (NS_FAILED(gHistogramInfos[aId].label_id(label.get(), &labelId))) {
return;
}
internal_Accumulate(locker, aId, labelId);
}
void TelemetryHistogram::AccumulateCategorical(
HistogramID aId, const nsTArray<nsCString>& aLabels) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(aId))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids.");
return;
}
if (!internal_CanRecordBase()) {
return;
}
// We use two loops, one for getting label_ids and another one for actually
// accumulating the values. This ensures that in the case of an invalid label
// in the array, no values are accumulated. In any call to this API, either
// all or (in case of error) none of the values will be accumulated.
nsTArray<uint32_t> intSamples(aLabels.Length());
for (const nsCString& label : aLabels) {
uint32_t labelId = 0;
if (NS_FAILED(gHistogramInfos[aId].label_id(label.get(), &labelId))) {
return;
}
intSamples.AppendElement(labelId);
}
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
for (uint32_t sample : intSamples) {
internal_Accumulate(locker, aId, sample);
}
}
void TelemetryHistogram::AccumulateChild(
ProcessID aProcessType,
const nsTArray<HistogramAccumulation>& aAccumulations) {
MOZ_ASSERT(XRE_IsParentProcess());
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
if (!internal_CanRecordBase()) {
return;
}
for (uint32_t i = 0; i < aAccumulations.Length(); ++i) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(aAccumulations[i].mId))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids.");
continue;
}
internal_AccumulateChild(locker, aProcessType, aAccumulations[i].mId,
aAccumulations[i].mSample);
}
}
void TelemetryHistogram::AccumulateChildKeyed(
ProcessID aProcessType,
const nsTArray<KeyedHistogramAccumulation>& aAccumulations) {
MOZ_ASSERT(XRE_IsParentProcess());
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
if (!internal_CanRecordBase()) {
return;
}
for (uint32_t i = 0; i < aAccumulations.Length(); ++i) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(aAccumulations[i].mId))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids.");
continue;
}
internal_AccumulateChildKeyed(locker, aProcessType, aAccumulations[i].mId,
aAccumulations[i].mKey,
aAccumulations[i].mSample);
}
}
nsresult TelemetryHistogram::GetAllStores(StringHashSet& set) {
for (uint32_t storeIdx : gHistogramStoresTable) {
const char* name = &gHistogramStringTable[storeIdx];
nsAutoCString store;
store.AssignASCII(name);
if (!set.Insert(store, mozilla::fallible)) {
return NS_ERROR_FAILURE;
}
}
return NS_OK;
}
nsresult TelemetryHistogram::GetCategoricalHistogramLabels(
JSContext* aCx, JS::MutableHandle<JS::Value> aResult) {
JS::Rooted<JSObject*> root_obj(aCx, JS_NewPlainObject(aCx));
if (!root_obj) {
return NS_ERROR_FAILURE;
}
aResult.setObject(*root_obj);
for (const HistogramInfo& info : gHistogramInfos) {
if (info.histogramType != nsITelemetry::HISTOGRAM_CATEGORICAL) {
continue;
}
const char* name = info.name();
JS::Rooted<JSObject*> labels(aCx,
JS::NewArrayObject(aCx, info.label_count));
if (!labels) {
return NS_ERROR_FAILURE;
}
if (!JS_DefineProperty(aCx, root_obj, name, labels, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
for (uint32_t i = 0; i < info.label_count; ++i) {
uint32_t string_offset = gHistogramLabelTable[info.label_index + i];
const char* const label = &gHistogramStringTable[string_offset];
auto clabel = NS_ConvertASCIItoUTF16(label);
JS::Rooted<JS::Value> value(aCx);
value.setString(ToJSString(aCx, clabel));
if (!JS_DefineElement(aCx, labels, i, value, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
}
}
return NS_OK;
}
nsresult TelemetryHistogram::GetHistogramById(
const nsACString& name, JSContext* cx, JS::MutableHandle<JS::Value> ret) {
HistogramID id;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
nsresult rv = internal_GetHistogramIdByName(locker, name, &id);
if (NS_FAILED(rv)) {
return NS_ERROR_FAILURE;
}
if (gHistogramInfos[id].keyed) {
return NS_ERROR_FAILURE;
}
}
// Runs without protection from |gTelemetryHistogramMutex|
return internal_WrapAndReturnHistogram(id, cx, ret);
}
nsresult TelemetryHistogram::GetKeyedHistogramById(
const nsACString& name, JSContext* cx, JS::MutableHandle<JS::Value> ret) {
HistogramID id;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
nsresult rv = internal_GetHistogramIdByName(locker, name, &id);
if (NS_FAILED(rv)) {
return NS_ERROR_FAILURE;
}
if (!gHistogramInfos[id].keyed) {
return NS_ERROR_FAILURE;
}
}
// Runs without protection from |gTelemetryHistogramMutex|
return internal_WrapAndReturnKeyedHistogram(id, cx, ret);
}
const char* TelemetryHistogram::GetHistogramName(HistogramID id) {
if (NS_WARN_IF(!internal_IsHistogramEnumId(id))) {
MOZ_ASSERT_UNREACHABLE("Histogram usage requires valid ids.");
return nullptr;
}
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
const HistogramInfo& h = gHistogramInfos[id];
return h.name();
}
nsresult TelemetryHistogram::CreateHistogramSnapshots(
JSContext* aCx, JS::MutableHandle<JS::Value> aResult,
const nsACString& aStore, unsigned int aDataset, bool aClearSubsession,
bool aFilterTest) {
if (!XRE_IsParentProcess()) {
return NS_ERROR_FAILURE;
}
// Runs without protection from |gTelemetryHistogramMutex|
JS::Rooted<JSObject*> root_obj(aCx, JS_NewPlainObject(aCx));
if (!root_obj) {
return NS_ERROR_FAILURE;
}
aResult.setObject(*root_obj);
// Include the GPU process in histogram snapshots only if we actually tried
// to launch a process for it.
bool includeGPUProcess = internal_AttemptedGPUProcess();
HistogramProcessSnapshotsArray processHistArray;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
nsresult rv = internal_GetHistogramsSnapshot(
locker, aStore, aDataset, aClearSubsession, includeGPUProcess,
aFilterTest, processHistArray);
if (NS_FAILED(rv)) {
return rv;
}
}
// Make the JS calls on the stashed histograms for every process
for (uint32_t process = 0; process < processHistArray.length(); ++process) {
JS::Rooted<JSObject*> processObject(aCx, JS_NewPlainObject(aCx));
if (!processObject) {
return NS_ERROR_FAILURE;
}
if (!JS_DefineProperty(aCx, root_obj,
GetNameForProcessID(ProcessID(process)),
processObject, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
for (const HistogramSnapshotInfo& hData : processHistArray[process]) {
HistogramID id = hData.histogramID;
JS::Rooted<JSObject*> hobj(aCx, JS_NewPlainObject(aCx));
if (!hobj) {
return NS_ERROR_FAILURE;
}
if (NS_FAILED(internal_ReflectHistogramAndSamples(
aCx, hobj, gHistogramInfos[id], hData.data))) {
return NS_ERROR_FAILURE;
}
if (!JS_DefineProperty(aCx, processObject, gHistogramInfos[id].name(),
hobj, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
}
}
return NS_OK;
}
nsresult TelemetryHistogram::GetKeyedHistogramSnapshots(
JSContext* aCx, JS::MutableHandle<JS::Value> aResult,
const nsACString& aStore, unsigned int aDataset, bool aClearSubsession,
bool aFilterTest) {
if (!XRE_IsParentProcess()) {
return NS_ERROR_FAILURE;
}
// Runs without protection from |gTelemetryHistogramMutex|
JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
if (!obj) {
return NS_ERROR_FAILURE;
}
aResult.setObject(*obj);
// Include the GPU process in histogram snapshots only if we actually tried
// to launch a process for it.
bool includeGPUProcess = internal_AttemptedGPUProcess();
// Get a snapshot of all the data while holding the mutex.
KeyedHistogramProcessSnapshotsArray processHistArray;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
nsresult rv = internal_GetKeyedHistogramsSnapshot(
locker, aStore, aDataset, aClearSubsession, includeGPUProcess,
aFilterTest, processHistArray);
if (NS_FAILED(rv)) {
return rv;
}
}
// Mirror the snapshot data to JS, now that we released the mutex.
for (uint32_t process = 0; process < processHistArray.length(); ++process) {
JS::Rooted<JSObject*> processObject(aCx, JS_NewPlainObject(aCx));
if (!processObject) {
return NS_ERROR_FAILURE;
}
if (!JS_DefineProperty(aCx, obj, GetNameForProcessID(ProcessID(process)),
processObject, JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
for (const KeyedHistogramSnapshotInfo& hData : processHistArray[process]) {
const HistogramInfo& info = gHistogramInfos[hData.histogramId];
JS::Rooted<JSObject*> snapshot(aCx, JS_NewPlainObject(aCx));
if (!snapshot) {
return NS_ERROR_FAILURE;
}
if (!NS_SUCCEEDED(internal_ReflectKeyedHistogram(hData.data, info, aCx,
snapshot))) {
return NS_ERROR_FAILURE;
}
if (!JS_DefineProperty(aCx, processObject, info.name(), snapshot,
JSPROP_ENUMERATE)) {
return NS_ERROR_FAILURE;
}
}
}
return NS_OK;
}
size_t TelemetryHistogram::GetHistogramSizesOfIncludingThis(
mozilla::MallocSizeOf aMallocSizeOf) {
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
size_t n = 0;
// If we allocated the array, let's count the number of pointers in there and
// each entry's size.
if (gKeyedHistogramStorage) {
n += HistogramCount * size_t(ProcessID::Count) * sizeof(KeyedHistogram*);
for (size_t i = 0; i < HistogramCount * size_t(ProcessID::Count); ++i) {
if (gKeyedHistogramStorage[i] &&
gKeyedHistogramStorage[i] != gExpiredKeyedHistogram) {
n += gKeyedHistogramStorage[i]->SizeOfIncludingThis(aMallocSizeOf);
}
}
}
// If we allocated the array, let's count the number of pointers in there.
if (gHistogramStorage) {
n += HistogramCount * size_t(ProcessID::Count) * sizeof(Histogram*);
for (size_t i = 0; i < HistogramCount * size_t(ProcessID::Count); ++i) {
if (gHistogramStorage[i] && gHistogramStorage[i] != gExpiredHistogram) {
n += gHistogramStorage[i]->SizeOfIncludingThis(aMallocSizeOf);
}
}
}
// We only allocate the expired (keyed) histogram once.
if (gExpiredKeyedHistogram) {
n += gExpiredKeyedHistogram->SizeOfIncludingThis(aMallocSizeOf);
}
if (gExpiredHistogram) {
n += gExpiredHistogram->SizeOfIncludingThis(aMallocSizeOf);
}
return n;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PRIVATE: GeckoView specific helpers
namespace base {
class PersistedSampleSet : public base::Histogram::SampleSet {
public:
explicit PersistedSampleSet(const nsTArray<base::Histogram::Count>& aCounts,
int64_t aSampleSum);
};
PersistedSampleSet::PersistedSampleSet(
const nsTArray<base::Histogram::Count>& aCounts, int64_t aSampleSum) {
// Initialize the data in the base class. See Histogram::SampleSet
// for the fields documentation.
const size_t numCounts = aCounts.Length();
counts_.SetLength(numCounts);
for (size_t i = 0; i < numCounts; i++) {
counts_[i] = aCounts[i];
redundant_count_ += aCounts[i];
}
sum_ = aSampleSum;
};
} // namespace base
namespace {
/**
* Helper function to write histogram properties to JSON.
* Please note that this needs to be called between
* StartObjectProperty/EndObject calls that mark the histogram's
* JSON creation.
*/
void internal_ReflectHistogramToJSON(const HistogramSnapshotData& aSnapshot,
mozilla::JSONWriter& aWriter) {
aWriter.IntProperty("sum", aSnapshot.mSampleSum);
// Fill the "counts" property.
aWriter.StartArrayProperty("counts");
for (size_t i = 0; i < aSnapshot.mBucketCounts.Length(); i++) {
aWriter.IntElement(aSnapshot.mBucketCounts[i]);
}
aWriter.EndArray();
}
bool internal_CanRecordHistogram(const HistogramID id, ProcessID aProcessType) {
// Check if we are allowed to record the data.
if (!CanRecordDataset(gHistogramInfos[id].dataset, internal_CanRecordBase(),
internal_CanRecordExtended())) {
return false;
}
// Check if we're allowed to record in the given process.
if (aProcessType == ProcessID::Parent && !internal_IsRecordingEnabled(id)) {
return false;
}
if (aProcessType != ProcessID::Parent &&
!CanRecordInProcess(gHistogramInfos[id].record_in_processes,
aProcessType)) {
return false;
}
// Don't record if the current platform is not enabled
if (!CanRecordProduct(gHistogramInfos[id].products)) {
return false;
}
return true;
}
nsresult internal_ParseHistogramData(
JSContext* aCx, JS::Handle<JS::PropertyKey> aEntryId,
JS::Handle<JSObject*> aContainerObj, nsACString& aOutName,
nsTArray<base::Histogram::Count>& aOutCountArray, int64_t& aOutSum) {
// Get the histogram name.
nsAutoJSString histogramName;
if (!histogramName.init(aCx, aEntryId)) {
JS_ClearPendingException(aCx);
return NS_ERROR_FAILURE;
}
CopyUTF16toUTF8(histogramName, aOutName);
// Get the data for this histogram.
JS::Rooted<JS::Value> histogramData(aCx);
if (!JS_GetPropertyById(aCx, aContainerObj, aEntryId, &histogramData)) {
JS_ClearPendingException(aCx);
return NS_ERROR_FAILURE;
}
if (!histogramData.isObject()) {
// base::Histogram data need to be an object. If that's not the case, skip
// it and try to load the rest of the data.
return NS_ERROR_FAILURE;
}
// Get the "sum" property.
JS::Rooted<JS::Value> sumValue(aCx);
JS::Rooted<JSObject*> histogramObj(aCx, &histogramData.toObject());
if (!JS_GetProperty(aCx, histogramObj, "sum", &sumValue)) {
JS_ClearPendingException(aCx);
return NS_ERROR_FAILURE;
}
if (!JS::ToInt64(aCx, sumValue, &aOutSum)) {
JS_ClearPendingException(aCx);
return NS_ERROR_FAILURE;
}
// Get the "counts" array.
JS::Rooted<JS::Value> countsArray(aCx);
bool countsIsArray = false;
if (!JS_GetProperty(aCx, histogramObj, "counts", &countsArray) ||
!JS::IsArrayObject(aCx, countsArray, &countsIsArray)) {
JS_ClearPendingException(aCx);
return NS_ERROR_FAILURE;
}
if (!countsIsArray) {
// The "counts" property needs to be an array. If this is not the case,
// skip this histogram.
return NS_ERROR_FAILURE;
}
// Get the length of the array.
uint32_t countsLen = 0;
JS::Rooted<JSObject*> countsArrayObj(aCx, &countsArray.toObject());
if (!JS::GetArrayLength(aCx, countsArrayObj, &countsLen)) {
JS_ClearPendingException(aCx);
return NS_ERROR_FAILURE;
}
// Parse the "counts" in the array.
for (uint32_t arrayIdx = 0; arrayIdx < countsLen; arrayIdx++) {
JS::Rooted<JS::Value> elementValue(aCx);
int countAsInt = 0;
if (!JS_GetElement(aCx, countsArrayObj, arrayIdx, &elementValue) ||
!JS::ToInt32(aCx, elementValue, &countAsInt)) {
JS_ClearPendingException(aCx);
return NS_ERROR_FAILURE;
}
aOutCountArray.AppendElement(countAsInt);
}
return NS_OK;
}
} // Anonymous namespace
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// PUBLIC: GeckoView serialization/deserialization functions.
nsresult TelemetryHistogram::SerializeHistograms(mozilla::JSONWriter& aWriter) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Only save histograms in the parent process");
if (!XRE_IsParentProcess()) {
return NS_ERROR_FAILURE;
}
// Include the GPU process in histogram snapshots only if we actually tried
// to launch a process for it.
bool includeGPUProcess = internal_AttemptedGPUProcess();
// Take a snapshot of the histograms.
HistogramProcessSnapshotsArray processHistArray;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
// We always request the "opt-in"/"prerelease" dataset: we internally
// record the right subset, so this will only return "prerelease" if
// it was recorded.
if (NS_FAILED(internal_GetHistogramsSnapshot(
locker, "main"_ns, nsITelemetry::DATASET_PRERELEASE_CHANNELS,
false /* aClearSubsession */, includeGPUProcess,
false /* aFilterTest */, processHistArray))) {
return NS_ERROR_FAILURE;
}
}
// Make the JSON calls on the stashed histograms for every process
for (uint32_t process = 0; process < processHistArray.length(); ++process) {
aWriter.StartObjectProperty(
mozilla::MakeStringSpan(GetNameForProcessID(ProcessID(process))));
for (const HistogramSnapshotInfo& hData : processHistArray[process]) {
HistogramID id = hData.histogramID;
aWriter.StartObjectProperty(
mozilla::MakeStringSpan(gHistogramInfos[id].name()));
internal_ReflectHistogramToJSON(hData.data, aWriter);
aWriter.EndObject();
}
aWriter.EndObject();
}
return NS_OK;
}
nsresult TelemetryHistogram::SerializeKeyedHistograms(
mozilla::JSONWriter& aWriter) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Only save keyed histograms in the parent process");
if (!XRE_IsParentProcess()) {
return NS_ERROR_FAILURE;
}
// Include the GPU process in histogram snapshots only if we actually tried
// to launch a process for it.
bool includeGPUProcess = internal_AttemptedGPUProcess();
// Take a snapshot of the keyed histograms.
KeyedHistogramProcessSnapshotsArray processHistArray;
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
// We always request the "opt-in"/"prerelease" dataset: we internally
// record the right subset, so this will only return "prerelease" if
// it was recorded.
if (NS_FAILED(internal_GetKeyedHistogramsSnapshot(
locker, "main"_ns, nsITelemetry::DATASET_PRERELEASE_CHANNELS,
false /* aClearSubsession */, includeGPUProcess,
false /* aFilterTest */, processHistArray))) {
return NS_ERROR_FAILURE;
}
}
// Serialize the keyed histograms for every process.
for (uint32_t process = 0; process < processHistArray.length(); ++process) {
aWriter.StartObjectProperty(
mozilla::MakeStringSpan(GetNameForProcessID(ProcessID(process))));
const KeyedHistogramSnapshotsArray& hArray = processHistArray[process];
for (size_t i = 0; i < hArray.length(); ++i) {
const KeyedHistogramSnapshotInfo& hData = hArray[i];
HistogramID id = hData.histogramId;
const HistogramInfo& info = gHistogramInfos[id];
aWriter.StartObjectProperty(mozilla::MakeStringSpan(info.name()));
// Each key is a new object with a "sum" and a "counts" property.
for (const auto& entry : hData.data) {
const HistogramSnapshotData& keyData = entry.GetData();
aWriter.StartObjectProperty(PromiseFlatCString(entry.GetKey()));
internal_ReflectHistogramToJSON(keyData, aWriter);
aWriter.EndObject();
}
aWriter.EndObject();
}
aWriter.EndObject();
}
return NS_OK;
}
nsresult TelemetryHistogram::DeserializeHistograms(
JSContext* aCx, JS::Handle<JS::Value> aData) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Only load histograms in the parent process");
if (!XRE_IsParentProcess()) {
return NS_ERROR_FAILURE;
}
// Telemetry is disabled. This should never happen, but let's leave this check
// for consistency with other histogram updates routines.
if (!internal_CanRecordBase()) {
return NS_OK;
}
typedef std::tuple<nsCString, nsTArray<base::Histogram::Count>, int64_t>
PersistedHistogramTuple;
typedef mozilla::Vector<PersistedHistogramTuple> PersistedHistogramArray;
typedef mozilla::Vector<PersistedHistogramArray> PersistedHistogramStorage;
// Before updating the histograms, we need to get the data out of the JS
// wrappers. We can't hold the histogram mutex while handling JS stuff.
// Build a <histogram name, value> map.
JS::Rooted<JSObject*> histogramDataObj(aCx, &aData.toObject());
JS::Rooted<JS::IdVector> processes(aCx, JS::IdVector(aCx));
if (!JS_Enumerate(aCx, histogramDataObj, &processes)) {
// We can't even enumerate the processes in the loaded data, so
// there is nothing we could recover from the persistence file. Bail out.
JS_ClearPendingException(aCx);
return NS_ERROR_FAILURE;
}
// Make sure we have enough storage for all the processes.
PersistedHistogramStorage histogramsToUpdate;
if (!histogramsToUpdate.resize(static_cast<uint32_t>(ProcessID::Count))) {
return NS_ERROR_OUT_OF_MEMORY;
}
// The following block of code attempts to extract as much data as possible
// from the serialized JSON, even in case of light data corruptions: if, for
// example, the data for a single process is corrupted or is in an unexpected
// form, we press on and attempt to load the data for the other processes.
JS::Rooted<JS::PropertyKey> process(aCx);
for (auto& processVal : processes) {
// This is required as JS API calls require an Handle<jsid> and not a
// plain jsid.
process = processVal;
// Get the process name.
nsAutoJSString processNameJS;
if (!processNameJS.init(aCx, process)) {
JS_ClearPendingException(aCx);
continue;
}
// Make sure it's valid. Note that this is safe to call outside
// of a locked section.
NS_ConvertUTF16toUTF8 processName(processNameJS);
ProcessID processID = GetIDForProcessName(processName.get());
if (processID == ProcessID::Count) {
NS_WARNING(
nsPrintfCString("Failed to get process ID for %s", processName.get())
.get());
continue;
}
// And its probes.
JS::Rooted<JS::Value> processData(aCx);
if (!JS_GetPropertyById(aCx, histogramDataObj, process, &processData)) {
JS_ClearPendingException(aCx);
continue;
}
if (!processData.isObject()) {
// |processData| should be an object containing histograms. If this is
// not the case, silently skip and try to load the data for the other
// processes.
continue;
}
// Iterate through each histogram.
JS::Rooted<JSObject*> processDataObj(aCx, &processData.toObject());
JS::Rooted<JS::IdVector> histograms(aCx, JS::IdVector(aCx));
if (!JS_Enumerate(aCx, processDataObj, &histograms)) {
JS_ClearPendingException(aCx);
continue;
}
// Get a reference to the deserialized data for this process.
PersistedHistogramArray& deserializedProcessData =
histogramsToUpdate[static_cast<uint32_t>(processID)];
JS::Rooted<JS::PropertyKey> histogram(aCx);
for (auto& histogramVal : histograms) {
histogram = histogramVal;
int64_t sum = 0;
nsTArray<base::Histogram::Count> deserializedCounts;
nsCString histogramName;
if (NS_FAILED(internal_ParseHistogramData(aCx, histogram, processDataObj,
histogramName,
deserializedCounts, sum))) {
continue;
}
// Finally append the deserialized data to the storage.
if (!deserializedProcessData.emplaceBack(std::make_tuple(
std::move(histogramName), std::move(deserializedCounts), sum))) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
}
// Update the histogram storage.
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
for (uint32_t process = 0; process < histogramsToUpdate.length();
++process) {
PersistedHistogramArray& processArray = histogramsToUpdate[process];
for (auto& histogramData : processArray) {
// Attempt to get the corresponding ID for the deserialized histogram
// name.
HistogramID id;
if (NS_FAILED(internal_GetHistogramIdByName(
locker, std::get<0>(histogramData), &id))) {
continue;
}
ProcessID procID = static_cast<ProcessID>(process);
if (!internal_CanRecordHistogram(id, procID)) {
// We're not allowed to record this, so don't try to restore it.
continue;
}
// Get the Histogram instance: this will instantiate it if it doesn't
// exist.
Histogram* w = internal_GetHistogramById(locker, id, procID);
MOZ_ASSERT(w);
if (!w || w->IsExpired()) {
continue;
}
base::Histogram* h = nullptr;
constexpr auto store = "main"_ns;
if (!w->GetHistogram(store, &h)) {
continue;
}
MOZ_ASSERT(h);
if (!h) {
// Don't restore expired histograms.
continue;
}
// Make sure that histogram counts have matching sizes. If not,
// |AddSampleSet| will fail and crash.
size_t numCounts = std::get<1>(histogramData).Length();
if (h->bucket_count() != numCounts) {
MOZ_ASSERT(false,
"The number of restored buckets does not match with the "
"on in the definition");
continue;
}
// Update the data for the histogram.
h->AddSampleSet(base::PersistedSampleSet(
std::move(std::get<1>(histogramData)), std::get<2>(histogramData)));
}
}
}
return NS_OK;
}
nsresult TelemetryHistogram::DeserializeKeyedHistograms(
JSContext* aCx, JS::Handle<JS::Value> aData) {
MOZ_ASSERT(XRE_IsParentProcess(),
"Only load keyed histograms in the parent process");
if (!XRE_IsParentProcess()) {
return NS_ERROR_FAILURE;
}
// Telemetry is disabled. This should never happen, but let's leave this check
// for consistency with other histogram updates routines.
if (!internal_CanRecordBase()) {
return NS_OK;
}
typedef std::tuple<nsCString, nsCString, nsTArray<base::Histogram::Count>,
int64_t>
PersistedKeyedHistogramTuple;
typedef mozilla::Vector<PersistedKeyedHistogramTuple>
PersistedKeyedHistogramArray;
typedef mozilla::Vector<PersistedKeyedHistogramArray>
PersistedKeyedHistogramStorage;
// Before updating the histograms, we need to get the data out of the JS
// wrappers. We can't hold the histogram mutex while handling JS stuff.
// Build a <histogram name, value> map.
JS::Rooted<JSObject*> histogramDataObj(aCx, &aData.toObject());
JS::Rooted<JS::IdVector> processes(aCx, JS::IdVector(aCx));
if (!JS_Enumerate(aCx, histogramDataObj, &processes)) {
// We can't even enumerate the processes in the loaded data, so
// there is nothing we could recover from the persistence file. Bail out.
JS_ClearPendingException(aCx);
return NS_ERROR_FAILURE;
}
// Make sure we have enough storage for all the processes.
PersistedKeyedHistogramStorage histogramsToUpdate;
if (!histogramsToUpdate.resize(static_cast<uint32_t>(ProcessID::Count))) {
return NS_ERROR_OUT_OF_MEMORY;
}
// The following block of code attempts to extract as much data as possible
// from the serialized JSON, even in case of light data corruptions: if, for
// example, the data for a single process is corrupted or is in an unexpected
// form, we press on and attempt to load the data for the other processes.
JS::Rooted<JS::PropertyKey> process(aCx);
for (auto& processVal : processes) {
// This is required as JS API calls require an Handle<jsid> and not a
// plain jsid.
process = processVal;
// Get the process name.
nsAutoJSString processNameJS;
if (!processNameJS.init(aCx, process)) {
JS_ClearPendingException(aCx);
continue;
}
// Make sure it's valid. Note that this is safe to call outside
// of a locked section.
NS_ConvertUTF16toUTF8 processName(processNameJS);
ProcessID processID = GetIDForProcessName(processName.get());
if (processID == ProcessID::Count) {
NS_WARNING(
nsPrintfCString("Failed to get process ID for %s", processName.get())
.get());
continue;
}
// And its probes.
JS::Rooted<JS::Value> processData(aCx);
if (!JS_GetPropertyById(aCx, histogramDataObj, process, &processData)) {
JS_ClearPendingException(aCx);
continue;
}
if (!processData.isObject()) {
// |processData| should be an object containing histograms. If this is
// not the case, silently skip and try to load the data for the other
// processes.
continue;
}
// Iterate through each keyed histogram.
JS::Rooted<JSObject*> processDataObj(aCx, &processData.toObject());
JS::Rooted<JS::IdVector> histograms(aCx, JS::IdVector(aCx));
if (!JS_Enumerate(aCx, processDataObj, &histograms)) {
JS_ClearPendingException(aCx);
continue;
}
// Get a reference to the deserialized data for this process.
PersistedKeyedHistogramArray& deserializedProcessData =
histogramsToUpdate[static_cast<uint32_t>(processID)];
JS::Rooted<JS::PropertyKey> histogram(aCx);
for (auto& histogramVal : histograms) {
histogram = histogramVal;
// Get the histogram name.
nsAutoJSString histogramName;
if (!histogramName.init(aCx, histogram)) {
JS_ClearPendingException(aCx);
continue;
}
// Get the data for this histogram.
JS::Rooted<JS::Value> histogramData(aCx);
if (!JS_GetPropertyById(aCx, processDataObj, histogram, &histogramData)) {
JS_ClearPendingException(aCx);
continue;
}
// Iterate through each key in the histogram.
JS::Rooted<JSObject*> keysDataObj(aCx, &histogramData.toObject());
JS::Rooted<JS::IdVector> keys(aCx, JS::IdVector(aCx));
if (!JS_Enumerate(aCx, keysDataObj, &keys)) {
JS_ClearPendingException(aCx);
continue;
}
JS::Rooted<JS::PropertyKey> key(aCx);
for (auto& keyVal : keys) {
key = keyVal;
int64_t sum = 0;
nsTArray<base::Histogram::Count> deserializedCounts;
nsCString keyName;
if (NS_FAILED(internal_ParseHistogramData(
aCx, key, keysDataObj, keyName, deserializedCounts, sum))) {
continue;
}
// Finally append the deserialized data to the storage.
if (!deserializedProcessData.emplaceBack(std::make_tuple(
nsCString(NS_ConvertUTF16toUTF8(histogramName)),
std::move(keyName), std::move(deserializedCounts), sum))) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
}
}
// Update the keyed histogram storage.
{
StaticMutexAutoLock locker(gTelemetryHistogramMutex);
for (uint32_t process = 0; process < histogramsToUpdate.length();
++process) {
PersistedKeyedHistogramArray& processArray = histogramsToUpdate[process];
for (auto& histogramData : processArray) {
// Attempt to get the corresponding ID for the deserialized histogram
// name.
HistogramID id;
if (NS_FAILED(internal_GetHistogramIdByName(
locker, std::get<0>(histogramData), &id))) {
continue;
}
ProcessID procID = static_cast<ProcessID>(process);
if (!internal_CanRecordHistogram(id, procID)) {
// We're not allowed to record this, so don't try to restore it.
continue;
}
KeyedHistogram* keyed = internal_GetKeyedHistogramById(id, procID);
MOZ_ASSERT(keyed);
if (!keyed || keyed->IsExpired()) {
// Don't restore if we don't have a destination storage or the
// histogram is expired.
continue;
}
// Get data for the key we're looking for.
base::Histogram* h = nullptr;
if (NS_FAILED(keyed->GetHistogram("main"_ns, std::get<1>(histogramData),
&h))) {
continue;
}
MOZ_ASSERT(h);
if (!h) {
// Don't restore if we don't have a destination storage.
continue;
}
// Make sure that histogram counts have matching sizes. If not,
// |AddSampleSet| will fail and crash.
size_t numCounts = std::get<2>(histogramData).Length();
if (h->bucket_count() != numCounts) {
MOZ_ASSERT(false,
"The number of restored buckets does not match with the "
"on in the definition");
continue;
}
// Update the data for the histogram.
h->AddSampleSet(base::PersistedSampleSet(
std::move(std::get<2>(histogramData)), std::get<3>(histogramData)));
}
}
}
return NS_OK;
}
|