summaryrefslogtreecommitdiffstats
path: root/LibOVRKernel/Src/Kernel/OVR_DebugHelp.cpp
blob: 34fdd5f160b8f2932f5ea0bc93465407cc2aecc6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
/************************************************************************************

Filename    :   ExceptionHandler.cpp
Content     :   Platform-independent exception handling interface
Created     :   October 6, 2014

Copyright   :   Copyright 2014 Oculus VR, LLC. All Rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

************************************************************************************/

#include "OVR_DebugHelp.h"

#if !defined(HEADLESS_APP)

#include "OVR_Types.h"
#include "OVR_UTF8Util.h"
#include "OVR_Atomic.h"
#include "OVR_SysFile.h"
#include "Util/Util_SystemGUI.h"

#include <stdlib.h>
#include <time.h>

#if defined(OVR_OS_WIN32) || defined(OVR_OS_WIN64)
    #pragma warning(push, 0)
    #include "OVR_Win32_IncludeWindows.h"
    #include <ShlObj.h>
    #include <WinNT.h>
    #include <DbgHelp.h>
    #include <WinVer.h>
    #include <share.h>
    #include <Psapi.h>
    #include <TlHelp32.h>
    #include <comutil.h>
    #include <Wbemcli.h>
    #include <Wbemidl.h>
    #include <ObjBase.h>
    #include <process.h>
    #pragma warning(pop)

    #pragma comment(lib, "Psapi.lib")   // To consider: It may be a problem to statically link to these libraries if the application at runtime intends to dynamically
    #pragma comment(lib, "ole32.lib")   // link to a different version of the same library, and we are statically linked into that application instead of being a DLL.
    #pragma comment(lib, "shell32.lib")
    #pragma comment(lib, "Version.lib")

    // NtQueryInformation and THREAD_BASIC_INFORMATION are undocumented but frequently needed for digging into thread information.
    typedef LONG (WINAPI *NtQueryInformationThreadFunc)(HANDLE, int, PVOID, ULONG, PULONG);

    struct THREAD_BASIC_INFORMATION
    {
        LONG  ExitStatus;
        PVOID TebBaseAddress;
        PVOID UniqueProcessId;
        PVOID UniqueThreadId;
        PVOID Priority;
        PVOID BasePriority;
    };

    #ifndef UNW_FLAG_NHANDLER // Older Windows SDKs don't support this.
        #define UNW_FLAG_NHANDLER 0
    #endif

#elif defined(OVR_OS_MAC)
    #include <unistd.h>
    #include <sys/sysctl.h>
    #include <sys/utsname.h>
    #include <sys/types.h>
    #include <sys/mman.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <pthread.h>
    #include <mach/mach.h>
    #include <mach/mach_error.h>
    #include <mach/thread_status.h>
    #include <mach/exception.h>
    #include <mach/task.h>
    #include <mach/thread_act.h>
    #include <mach-o/dyld.h>
    #include <mach-o/dyld_images.h>
    #include <libproc.h>
    #include <libgen.h>
    #include <execinfo.h>
    #include <cxxabi.h>
    #include "OVR_mach_exc_OSX.h"

    #if defined(__LP64__)
        typedef struct mach_header_64     MachHeader;
        typedef struct segment_command_64 SegmentCommand;
        typedef struct section_64         Section;
        #define kLCSegment                LC_SEGMENT_64
    #else
        typedef struct mach_header        MachHeader;
        typedef struct segment_command    SegmentCommand;
        typedef struct section            Section;
        #define kLCSegment                LC_SEGMENT
    #endif

    extern "C" const struct dyld_all_image_infos* _dyld_get_all_image_infos(); // From libdyld.dylib

#elif defined(OVR_OS_UNIX)
    #include <unistd.h>
    #include "sys/stat.h"
#if defined(OVR_OS_ANDROID)
    #include <linux/sysctl.h>
#else
    #include <sys/sysctl.h>
#endif
    #include <sys/utsname.h>
    #include <sys/types.h>
    #include <sys/ptrace.h>
    #include <sys/wait.h>
    #include <sys/mman.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <pthread.h>
    #include <libgen.h>
#if !defined(OVR_OS_ANDROID)
    #include <execinfo.h>
#endif
    #include <cxxabi.h>
  //#include <libunwind.h> // Can't use this until we can ensure that we have an installed version of it.
#endif

#if !defined(MIN)
    #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
    #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
#endif


OVR_DISABLE_MSVC_WARNING(4351) // new behavior: elements of array will be default initialized
OVR_DISABLE_MSVC_WARNING(4996) // This function or variable may be unsafe




#if defined(OVR_OS_APPLE)
    static OVR::ExceptionHandler* sExceptionHandler = nullptr;
    const uint32_t sMachCancelMessageType = 0x0ca9ce11;  // This is a made-up value of our own choice.

    extern "C"
    {
        kern_return_t catch_mach_exception_raise_OVR(mach_port_t /*exceptionPort*/, mach_port_t /*threadSysId*/,
                                        mach_port_t /*machTask*/, exception_type_t /*machExceptionType*/,
                                        mach_exception_data_t /*machExceptionData*/, mach_msg_type_number_t /*machExceptionDataCount*/)
        {
            return KERN_FAILURE;
        }

        kern_return_t catch_mach_exception_raise_state_OVR(mach_port_t /*exceptionPort*/, exception_type_t /*exceptionType*/,
                                        const mach_exception_data_t /*machExceptionData*/, mach_msg_type_number_t /*machExceptionDataCount*/,
                                        int* /*pMachExceptionFlavor*/, const thread_state_t /*threadStatePrev*/, mach_msg_type_number_t /*threaStatePrevCount*/,
                                        thread_state_t /*threadStateNew*/, mach_msg_type_number_t* /*pThreadStateNewCount*/)
        {
            return KERN_FAILURE;
        }

        kern_return_t catch_mach_exception_raise_state_identity_OVR(mach_port_t exceptionPort, mach_port_t threadSysId, mach_port_t machTask,
                                            exception_type_t exceptionType, mach_exception_data_type_t* pMachExceptionData,
                                            mach_msg_type_number_t machExceptionDataCount, int* pMachExceptionFlavor,
                                            thread_state_t threadStatePrev, mach_msg_type_number_t threadStatePrevCount,
                                            thread_state_t threadStateNew, mach_msg_type_number_t* pThreadStateNewCount)
        {
            return sExceptionHandler->HandleMachException(exceptionPort, threadSysId, machTask, exceptionType, pMachExceptionData,
                                                machExceptionDataCount, pMachExceptionFlavor, threadStatePrev, threadStatePrevCount,
                                                threadStateNew, pThreadStateNewCount);
        }

        void* MachHandlerThreadFunctionStatic(void* pExceptionHandlerVoid)
        {
            return static_cast<OVR::ExceptionHandler*>(pExceptionHandlerVoid)->MachHandlerThreadFunction();
        }

    } // extern "C"
#endif


namespace OVR {


void GetInstructionPointer(void*& pInstruction)
{
    #if defined(OVR_CC_MSVC)
        pInstruction = _ReturnAddress();
    #else // GCC, clang
        pInstruction = __builtin_return_address(0);
    #endif
}


// addressStrCapacity should be at least 2+16+1 = 19 characters.
static size_t SprintfAddress(char* addressStr, size_t addressStrCapacity, const void* pAddress)
{
    #if defined(OVR_CC_MSVC)
        #if (OVR_PTR_SIZE >= 8)
            return OVR_snprintf(addressStr, addressStrCapacity, "0x%016I64x", pAddress);  // e.g. 0x0123456789abcdef
        #else
            return OVR_snprintf(addressStr, addressStrCapacity, "0x%08x", pAddress);      // e.g. 0x89abcdef
        #endif
    #else
        #if (OVR_PTR_SIZE >= 8)
            return OVR_snprintf(addressStr, addressStrCapacity, "%016llx", pAddress);     // e.g. 0x0123456789abcdef
        #else
            return OVR_snprintf(addressStr, addressStrCapacity, "%08x", pAddress);        // e.g. 0x89abcdef
        #endif
    #endif
}


// threadHandleStrCapacity should be at least 2+16+1 = 19 characters.
static size_t SprintfThreadHandle(char* threadHandleStr, size_t threadHandleStrCapacity, const ThreadHandle& threadHandle)
{
    return SprintfAddress(threadHandleStr, threadHandleStrCapacity, threadHandle);
}


// threadSysIdStrCapacity should be at least 20+4+16+2 = 42 characters.
static size_t SprintfThreadSysId(char* threadSysIdStr, size_t threadSysIdStrCapacity, const ThreadSysId& threadSysId)
{
    #if defined(OVR_CC_MSVC) // Somebody could conceivably use VC++ with a different standard library that supports %ll. And VS2012+ also support %ll.
        return OVR_snprintf(threadSysIdStr, threadSysIdStrCapacity, "%I64u (0x%I64x)", (uint64_t)threadSysId, (uint64_t)threadSysId); // e.g. 5642 (0x160a)
    #else
        return OVR_snprintf(threadSysIdStr, threadSysIdStrCapacity, "%llu (0x%llx)", (uint64_t)threadSysId, (uint64_t)threadSysId);
    #endif
}





void GetThreadStackBounds(void*& pStackBase, void*& pStackLimit, ThreadHandle threadHandle)
{
    #if defined(OVR_OS_WIN64) || defined(OVR_OS_WIN32)
        ThreadSysId threadSysIdCurrent = (ThreadSysId)GetCurrentThreadId();
        ThreadSysId threadSysId;
        NT_TIB*     pTIB = nullptr;

        if(threadHandle == OVR_THREADHANDLE_INVALID)
            threadSysId = threadSysIdCurrent;
        else
            threadSysId = ConvertThreadHandleToThreadSysId(threadHandle);

        if(threadSysId == threadSysIdCurrent)
        {
            #if (OVR_PTR_SIZE == 4)
                // Need to use __asm__("movl %%fs:0x18, %0" : "=r" (pTIB) : : ); under gcc/clang.
                __asm {
                    mov eax, fs:[18h]
                    mov pTIB, eax
                }
            #else
                pTIB = (NT_TIB*)NtCurrentTeb();
            #endif
        }
        else
        {
            #if (OVR_PTR_SIZE == 4)
                // It turns out we don't need to suspend the thread when getting SegFs/SegGS, as that's
                // constant per thread and doesn't require the thread to be suspended.
                //SuspendThread((HANDLE)threadHandle);
                CONTEXT context;
                memset(&context, 0, sizeof(context));
                context.ContextFlags = CONTEXT_SEGMENTS;
                GetThreadContext((HANDLE)threadHandle, &context); // Requires THREAD_QUERY_INFORMATION privileges.

                LDT_ENTRY ldtEntry;
                if(GetThreadSelectorEntry(threadHandle, context.SegFs, &ldtEntry)) // Requires THREAD_QUERY_INFORMATION
                    pTIB = (NT_TIB*)((ldtEntry.HighWord.Bits.BaseHi << 24 ) | (ldtEntry.HighWord.Bits.BaseMid << 16) | ldtEntry.BaseLow);

                //ResumeThread((HANDLE)threadHandle);
            #else
                // We cannot use GetThreadSelectorEntry or Wow64GetThreadSelectorEntry on Win64.
                // We need to read the SegGs qword at offset 0x30. We can't use pTIB = (NT_TIB*)__readgsqword(0x30) because that reads only the current setGs offset.
                //    mov rax, qword ptr gs:[30h]
                //    mov qword ptr [pTIB],rax
                // In the meantime we rely on the NtQueryInformationThread function.

                static NtQueryInformationThreadFunc spNtQueryInformationThread = nullptr;

                if(!spNtQueryInformationThread)
                {
                    HMODULE hNTDLL = GetModuleHandleA("ntdll.dll");
                    spNtQueryInformationThread = (NtQueryInformationThreadFunc)(uintptr_t)GetProcAddress(hNTDLL, "NtQueryInformationThread");
                }

                if(spNtQueryInformationThread)
                {
                    THREAD_BASIC_INFORMATION tbi;

                    memset(&tbi, 0, sizeof(tbi));
                    LONG result = spNtQueryInformationThread(threadHandle, 0, &tbi, sizeof(tbi), nullptr); // Requires THREAD_QUERY_INFORMATION privileges
                    if(result == 0)
                        pTIB = (NT_TIB*)tbi.TebBaseAddress;
                }
            #endif
        }

        if(pTIB)
        {
            pStackBase  = (void*)pTIB->StackBase;
            pStackLimit = (void*)pTIB->StackLimit;
        }
        else
        {
            pStackBase  = nullptr;
            pStackLimit = nullptr;
        }

    #elif defined(OVR_OS_APPLE)
        if(!threadHandle)
            threadHandle = pthread_self();

        pStackBase = pthread_get_stackaddr_np((pthread_t)threadHandle);
        size_t stackSize = pthread_get_stacksize_np((pthread_t)threadHandle);
        pStackLimit = (void*)((size_t)pStackBase - stackSize);

    #elif defined(OVR_OS_UNIX)
        pStackBase  = nullptr;
        pStackLimit = nullptr;

        pthread_attr_t threadAttr;
        pthread_attr_init(&threadAttr);

        #if defined(OVR_OS_LINUX)
            int result = pthread_getattr_np((pthread_t)threadHandle, &threadAttr);
        #else
            int result = pthread_attr_get_np((pthread_t)threadHandle, &threadAttr);
        #endif

        if(result == 0)
        {
            size_t stackSize = 0;
            result = pthread_attr_getstack(&threadAttr, &pStackLimit, &stackSize);

            if(result == 0)
                pStackBase = (void*)((uintptr_t)pStackLimit + stackSize); // We assume the stack grows downward.
        }

    #endif
}


bool OVRIsDebuggerPresent()
{
    #if defined(OVR_OS_MS)
        return ::IsDebuggerPresent() != 0;

    #elif defined(OVR_OS_APPLE)
        int               mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
        struct kinfo_proc info;
        size_t            size = sizeof(info);

        info.kp_proc.p_flag = 0;
        sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0);

        return ((info.kp_proc.p_flag & P_TRACED) != 0);

    #elif defined(PT_TRACE_ME) && !defined(OVR_OS_ANDROID)
        return (ptrace(PT_TRACE_ME, 0, 1, 0) < 0);

    #elif (defined(OVR_OS_LINUX) || defined(OVR_OS_BSD)) && !defined(OVR_OS_ANDROID)
        // This works better than the PT_TRACE_ME approach, but causes the debugger to get
        // confused when executed under a debugger.
        // It also presents this problem:
        //     http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html
        //     When the application calls fork() from a signal handler and any of the
        //     fork handlers registered by pthread_atfork() calls a function that is
        //     not asynch-signal-safe, the behavior is undefined.
        // We may need to provide two pathways within this function, one of which
        // doesn't fork and instead uses PT_TRACE_ME.
        int  pid = fork();
        int  status;
        bool present = false;

        if (pid == -1) // If fork failed...
        {
            // perror("fork");
        }
        else if (pid == 0) // If we are the child process...
        {
            int ppid = getppid();

          #if defined(OVR_OS_LINUX)
            if (ptrace(PTRACE_ATTACH, ppid, nullptr, nullptr) == 0)
          #else
            if (ptrace(PT_ATTACH, ppid, nullptr, nullptr) == 0)
          #endif
            {
                waitpid(ppid, nullptr, 0);

              #if defined(OVR_OS_LINUX)
                ptrace(PTRACE_CONT, getppid(), nullptr, nullptr);
                ptrace(PTRACE_DETACH, getppid(), nullptr, nullptr);
              #else
                ptrace(PT_CONTINUE, getppid(), nullptr, nullptr);
                ptrace(PT_DETACH, getppid(), nullptr, nullptr);
              #endif
            }
            else
            {
                // ptrace failed so the debugger is present.
                present = true;
            }

            exit(present ? 1 : 0); // The WEXITSTATUS call below will read this exit value.
        }
        else // Else we are the original process.
        {
            waitpid(pid, &status, 0);
            present = WEXITSTATUS(status) ? true : false; // Read the exit value from the child's call to exit.
        }

        return present;

    #else
        return false;
    #endif
}


// Exits the process with the given exit code.
void ExitProcess(intptr_t processReturnValue)
{
    exit((int)processReturnValue);
}


// Note that we can't just return sizeof(void*) == 8, as we may have the case of a
// 32 bit app running on a 64 bit operating system.
static bool Is64BitOS()
{
    #if (OVR_PTR_SIZE >= 8)
        return true;

    #elif defined(OVR_OS_WIN32) || defined(OVR_OS_WIN64)
        BOOL is64BitOS = FALSE;
        bool IsWow64ProcessPresent = (GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "IsWow64Process") != nullptr);
        return (IsWow64ProcessPresent && IsWow64Process(GetCurrentProcess(), &is64BitOS) && is64BitOS);

    #elif defined(OVR_OS_MAC) || defined(OVR_OS_UNIX)
        utsname utsName;
        memset(&utsName, 0, sizeof(utsName));
        return (uname(&utsName) == 0) && (strcmp(utsName.machine, "x86_64") == 0);

    #else
        return false;
    #endif
}


// The output will always be 0-terminated.
// Returns the required strlen of the output.
// Returns (size_t)-1 on failure.
size_t SpawnShellCommand(const char* shellCommand, char* output, size_t outputCapacity)
{
    #if defined(OVR_OS_UNIX) || defined(OVR_OS_APPLE)
        FILE* pFile = popen(shellCommand, "r");

        if(pFile)
        {
            size_t requiredLength = 0;
            char buffer[256];

            while(fgets(buffer, sizeof(buffer), pFile)) // fgets 0-terminates the buffer.
            {
                size_t length = OVR_strlen(buffer);
                requiredLength += length;

                if(outputCapacity)
                {
                    OVR_strlcpy(output, buffer, outputCapacity);
                    length = MIN(outputCapacity, length);
                }

                output         += length;
                outputCapacity -= length;
            }

            pclose(pFile);
            return requiredLength;
        }
    #else
        // To do. Properly solving this on Windows requires a bit of code.
        OVR_UNUSED(shellCommand);
        OVR_UNUSED(output);
        OVR_UNUSED(outputCapacity);
    #endif

    return (size_t)-1;
}

// Retrieves the name of the given thread.
// To do: Move this to OVR_Threads.h
bool GetThreadName(OVR::ThreadHandle threadHandle, char* threadName, size_t threadNameCapacity)
{
    #if (defined(OVR_OS_APPLE) || defined(OVR_OS_LINUX)) && !defined(OVR_OS_ANDROID)
        int result = pthread_getname_np((pthread_t)threadHandle, threadName, threadNameCapacity);
        if(result == 0)
            return true;
    #else
        // This is not currently possible on Windows, as only the debugger stores the thread name. We could potentially use a vectored
        // exception handler to catch all thread name exceptions (0x406d1388) and record them in a static list at runtime. To detect
        // thread exit we could use WMI Win32_ThreadStopTrace. Maintain a list of thread names between these two events.
        OVR_UNUSED(threadHandle);
        OVR_UNUSED(threadNameCapacity);
    #endif

    if(threadNameCapacity)
        threadName[0] = 0;

    return false;
}


OVR::ThreadSysId ConvertThreadHandleToThreadSysId(OVR::ThreadHandle threadHandle)
{
    #if defined(OVR_OS_WIN64)
        return (OVR::ThreadSysId)::GetThreadId(threadHandle); // Requires THREAD_QUERY_INFORMATION privileges.

    #elif defined(OVR_OS_WIN32)
        typedef DWORD (WINAPI *GetThreadIdFunc)(HANDLE);

        static volatile bool sInitialized = false;
        static GetThreadIdFunc spGetThreadIdFunc = nullptr;
        static NtQueryInformationThreadFunc spNtQueryInformationThread = nullptr;

        if(!sInitialized)
        {
            HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
            if(hKernel32)
                spGetThreadIdFunc = (GetThreadIdFunc)(uintptr_t)GetProcAddress(hKernel32, "GetThreadId");

            if(!spGetThreadIdFunc)
            {
                HMODULE hNTDLL = GetModuleHandleA("ntdll.dll");

                if(hNTDLL)
                    spNtQueryInformationThread = (NtQueryInformationThreadFunc)(uintptr_t)GetProcAddress(hNTDLL, "NtQueryInformationThread");
            }

            sInitialized = true;
        }

        if(spGetThreadIdFunc)
            return (OVR::ThreadSysId)spGetThreadIdFunc(threadHandle);

        if(spNtQueryInformationThread)
        {
            THREAD_BASIC_INFORMATION tbi;

            if(spNtQueryInformationThread(threadHandle, 0, &tbi, sizeof(tbi), nullptr) == 0)
                return (OVR::ThreadSysId)tbi.UniqueThreadId;
        }

        return OVR_THREADSYSID_INVALID;

    #elif defined(OVR_OS_APPLE)
        mach_port_t threadSysId = pthread_mach_thread_np((pthread_t)threadHandle);  // OS 10.4 and later.
        return (ThreadSysId)threadSysId;

    #elif defined(OVR_OS_LINUX)

        // I believe we can usually (though not portably) intepret the pthread_t as a pointer to a struct whose first member is a lwp id.
        OVR_UNUSED(threadHandle);
        return OVR_THREADSYSID_INVALID;

    #else
        OVR_UNUSED(threadHandle);
        return OVR_THREADSYSID_INVALID;
    #endif
}


OVR::ThreadHandle ConvertThreadSysIdToThreadHandle(OVR::ThreadSysId threadSysId)
{
    #if defined(OVR_OS_MS)
        // We currently request the given rights because that's what users of this function typically need it for. Ideally there would
        // be a way to specify the requested rights in order to avoid the problem if we need only a subset of them but can't get it.
        // The solution we use below to try opening with successively reduced rights will work for our uses here but isn't a good general solution to this.
        OVR::ThreadHandle threadHandle = ::OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, TRUE, (DWORD)threadSysId);

        if(threadHandle == OVR_THREADHANDLE_INVALID)
        {
            threadHandle = ::OpenThread(THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, TRUE, (DWORD)threadSysId);

            if(threadHandle == OVR_THREADHANDLE_INVALID)
                threadHandle = ::OpenThread(THREAD_QUERY_INFORMATION, TRUE, (DWORD)threadSysId);
        }

        return threadHandle;
    #elif defined(OVR_OS_MAC)
        return (ThreadHandle)pthread_from_mach_thread_np((mach_port_t)threadSysId);
    #else
        return (ThreadHandle)threadSysId;
    #endif
}


void FreeThreadHandle(OVR::ThreadHandle threadHandle)
{
    #if defined(OVR_OS_MS)
        if(threadHandle != OVR_THREADHANDLE_INVALID)
            ::CloseHandle(threadHandle);
    #else
        OVR_UNUSED(threadHandle);
    #endif
}


OVR::ThreadSysId GetCurrentThreadSysId()
{
    #if defined(OVR_OS_MS)
        return ::GetCurrentThreadId();
    #elif defined(OVR_OS_APPLE)
        return (ThreadSysId)mach_thread_self();
    #else
        return (ThreadSysId)pthread_self();
    #endif
}



static void GetCurrentProcessFilePath(char* appPath, size_t appPathCapacity)
{
    appPath[0] = 0;

    #if defined(OVR_OS_MS)
        wchar_t pathW[OVR_MAX_PATH];
        GetModuleFileNameW(0, pathW, (DWORD)OVR_ARRAY_COUNT(pathW));

        size_t requiredUTF8Length = (size_t)OVR::UTF8Util::GetEncodeStringSize(pathW); // Returns required strlen.

        if(requiredUTF8Length < appPathCapacity)
        {
            OVR::UTF8Util::EncodeString(appPath, pathW, -1);
        }
        else
        {
            appPath[0] = 0;
        }

    #elif defined(OVR_OS_APPLE)
        struct BunderFolder
        {
            // Returns true if pStr ends with pFind, case insensitively.
            // To do: Move OVR_striend to OVRKernel/Std.h
            static bool OVR_striend(const char* pStr, const char* pFind, size_t strLength = (size_t)-1, size_t findLength = (size_t)-1)
            {
                if(strLength == (size_t)-1)
                    strLength = OVR_strlen(pStr);
                if(findLength == (size_t)-1)
                    findLength = OVR_strlen(pFind);
                if(strLength >= findLength)
                    return (OVR_stricmp(pStr + strLength - findLength, pFind) == 0);
                return false;
            }

            static bool IsBundleFolder(const char* filePath)
            {
                // https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/AboutBundles/AboutBundles.html#//apple_ref/doc/uid/10000123i-CH100-SW1
                static const char* extensionArray[] = { ".app", ".bundle", ".framework", ".plugin", ".kext" };

                for(size_t i = 0; i < OVR_ARRAY_COUNT(extensionArray); i++)
                {
                    if(OVR_striend(filePath, extensionArray[i]))
                        return true;
                }

                return false;
            }
        };

        char     appPathTemp[PATH_MAX];
        uint32_t appPathTempCapacity32 = PATH_MAX;
        size_t   requiredStrlen = appPathCapacity;

        if(_NSGetExecutablePath(appPathTemp, &appPathTempCapacity32) == 0)
        {
            char appPathTempReal[PATH_MAX];

            if(realpath(appPathTemp, appPathTempReal))  // If the path is a symbolic link, this converts it to the real path.
            {
                // To consider: Enable reading the internal bundle executable path. An application on Mac may in
                // fact be within a file bundle, which is an private file system within a file. With Objective C
                // we could use: [[NSWorkspace sharedWorkspace] isFilePackageAtPath:fullPath];
                bool shouldReadTheBunderPath = false;

                if(shouldReadTheBunderPath)
                {
                    // We recursively call dirname() until we find .app/.bundle/.plugin as a directory name.
                    OVR_strlcpy(appPathTemp, appPathTempReal, OVR_ARRAY_COUNT(appPathTemp));
                    bool found = BunderFolder::IsBundleFolder(appPathTemp);

                    while(!found && OVR_strcmp(appPathTemp, ".") && OVR_strcmp(appPathTemp, "/"))
                    {
                        OVR_strlcpy(appPathTemp, dirname(appPathTemp), OVR_ARRAY_COUNT(appPathTemp));
                        found = BunderFolder::IsBundleFolder(appPathTemp);
                    }

                    if(found) // If somewhere above we found a parent bundle container...
                        requiredStrlen = OVR_strlcpy(appPath, appPathTemp, appPathCapacity);
                    else
                        requiredStrlen = OVR_strlcpy(appPath, appPathTempReal, appPathCapacity);
                }
                else
                {
                    requiredStrlen = OVR_strlcpy(appPath, appPathTempReal, appPathCapacity);
                }
            }
        }

        if(requiredStrlen >= appPathCapacity)
            appPath[0] = '\0';

    #elif defined(OVR_OS_LINUX)
        ssize_t length = readlink("/proc/self/exe", appPath, appPathCapacity);

        if((length != -1) && ((size_t)length < (appPathCapacity - 1)))
        {
            appPath[length] = '\0';
        }
    #endif
}


static const char* GetFileNameFromPath(const char* filePath)
{
    const char* lastPathSeparator = strrchr(filePath, '/');

    #if defined(OVR_OS_MS)
        // Microsoft APIs are inconsistent with respect to allowing / as a path separator.
        const char* candidate = strrchr(filePath, '\\');

        if(candidate > lastPathSeparator)
        {
            lastPathSeparator = candidate;
        }
    #endif

    if(lastPathSeparator)
        return lastPathSeparator + 1;

    return filePath;
}



static void FormatDateTime(char* buffer, size_t bufferCapacity, time_t timeValue, bool getDate, bool getTime, bool localDateTime, bool fileNameSafeCharacters = false)
{
    char      temp[128];
    const tm* pTime = localDateTime ? localtime(&timeValue) : gmtime(&timeValue);

    if(bufferCapacity)
        buffer[0] = 0;

    if(getDate)
    {
        const char* format = fileNameSafeCharacters ? "%Y-%m-%d" : "%Y/%m/%d";
        strftime(temp, OVR_ARRAY_COUNT(temp), format, pTime);
        OVR::OVR_strlcpy(buffer, temp, bufferCapacity);
    }

    if(getTime)
    {
        const char* format = fileNameSafeCharacters ? " %H.%M.%S" : " %H:%M:%S";
        strftime(temp, OVR_ARRAY_COUNT(temp), (getDate ? format : format + 1), pTime);
        OVR::OVR_strlcat(buffer, temp, bufferCapacity);
    }
}


static void GetOSVersionName(char* versionName, size_t versionNameCapacity)
{
    #if defined(OVR_OS_MS)
        const char* name = "unknown";

        OSVERSIONINFOEXW vi;
        memset(&vi, 0, sizeof(vi));
        vi.dwOSVersionInfoSize = sizeof(vi);

        if(GetVersionExW((LPOSVERSIONINFOW)&vi))
        {
            if(vi.dwMajorVersion >= 7)
            {
                // Unknown recent version.
            }
            if(vi.dwMajorVersion >= 6)
            {
                if(vi.dwMinorVersion >= 4)
                    name = "Windows 10";
                else if(vi.dwMinorVersion >= 3)
                {
                    if(vi.wProductType == VER_NT_WORKSTATION)
                        name = "Windows 8.1";
                    else
                        name = "Windows Server 2012 R2";
                }
                else if(vi.dwMinorVersion >= 2)
                {
                    if(vi.wProductType == VER_NT_WORKSTATION)
                        name = "Windows 8";
                    else
                        name = "Windows Server 2012";
                }
                else if(vi.dwMinorVersion >= 1)
                {
                    if(vi.wProductType == VER_NT_WORKSTATION)
                        name = "Windows 7";
                    else
                        name = "Windows Server 2008 R2";
                }
                else
                {
                    if(vi.wProductType == VER_NT_WORKSTATION)
                        name = "Windows Vista";
                    else
                        name = "Windows Server 2008";
                }
            }
            else if(vi.dwMajorVersion >= 5)
            {
                if(vi.dwMinorVersion == 0)
                    name = "Windows 2000";
                else if(vi.dwMinorVersion == 1)
                    name = "Windows XP";
                else // vi.dwMinorVersion == 2
                {
                    if(GetSystemMetrics(SM_SERVERR2) != 0)
                        name = "Windows Server 2003 R2";
                    else if(vi.wSuiteMask & VER_SUITE_WH_SERVER)
                        name = "Windows Home Server";
                    if(GetSystemMetrics(SM_SERVERR2) == 0)
                        name = "Windows Server 2003";
                    else
                        name = "Windows XP Professional x64 Edition";
                }
            }
            else
                name = "Windows 98 or earlier";
        }

        OVR_strlcpy(versionName, name, versionNameCapacity);

    #elif defined(OVR_OS_UNIX) || defined(OVR_OS_APPLE)
        utsname utsName;
        memset(&utsName, 0, sizeof(utsName));

        if(uname(&utsName) == 0)
            OVR_snprintf(versionName, versionNameCapacity, "%s %s %s %s", utsName.sysname, utsName.release, utsName.version, utsName.machine);
        else
            OVR_snprintf(versionName, versionNameCapacity, "Unix");
    #endif
}




void CreateException(CreateExceptionType exceptionType)
{
    char buffer[1024] = {};

    switch(exceptionType)
    {
        case kCETAccessViolation:
        {
            int* pNullPtr = reinterpret_cast<int*>((rand() / 2) / RAND_MAX);
            pNullPtr[0] = 0;    // This line should generate an exception.
            sprintf(buffer, "%p", pNullPtr);
            break;
        }

        case kCETDivideByZero:
        {
            int smallValue = 1;
            int largeValue = (1000 * exceptionType);
            int divByZero = (smallValue / largeValue); // This line should generate a div/0 exception.
            sprintf(buffer, "%d", divByZero);
            break;
        }

        case kCETIllegalInstruction:
        {
            #if defined(OVR_CPU_X86) || (defined(OVR_CPU_X86_64) && !defined(OVR_CC_MSVC)) // (if x86) or (if x64 and any computer but VC++)...
                #if defined(OVR_CC_MSVC)
                    __asm ud2
                #else // e.g. GCC
                    asm volatile("ud2");
                #endif

            #elif defined(OVR_CPU_X86_64) && (defined(OVR_OS_MS) && defined(PAGE_EXECUTE_READWRITE))
                // VC++ for x64 doesn't support inline asm.
                void*   pVoid          = _AddressOfReturnAddress();
                void**  ppVoid         = reinterpret_cast<void**>(pVoid);
                void*   pReturnAddress = *ppVoid;
                DWORD   dwProtectPrev  = 0;

                if(VirtualProtect(pReturnAddress, 2, PAGE_EXECUTE_READWRITE, &dwProtectPrev)) // If we can set the memory to be executable...
                {
                    // Modify the code we return to.
                    uint8_t asm_ud2[] = { 0x0f, 0x0b };
                    memcpy(pReturnAddress, asm_ud2, sizeof(asm_ud2));
                    VirtualProtect(pReturnAddress, 2, dwProtectPrev, &dwProtectPrev);
                }
                else
                {
                    // To do: Fix this.
                }

            #else
                // To do: Fix this.
            #endif

            break;
        }

        case kCETStackCorruption:
        {
            size_t size = (sizeof(buffer) * 16) - (rand() % 16);
            char*  pOutsizeStack = buffer - ((sizeof(buffer) * 16) + (rand() % 16));

            memset(buffer, 0, size);
            memset(pOutsizeStack, 0, size); // This line should generate an exception, or an exception will be generated upon return from this function.
            break;
        }

        case kCETStackOverflow:
        {
            CreateException(exceptionType);             // Call ourselves recursively. This line should generate a div/0 exception.
            sprintf(buffer, "%d", exceptionType);
            break;
        }

        case kCETAlignment:
        {
            // Not all platforms generate alignment exceptions. Some internally handle it.
            void*     pAligned      = malloc(16);
            char*     pMisaligned   = (char*)pAligned + 1;
            uint64_t* pMisaligned64 = reinterpret_cast<uint64_t*>(pMisaligned);

            *pMisaligned64 = 0; // This line should generate an exception.
            free(pAligned);
            break;
        }

        case kCETFPU:
            // Platforms usually have FPU exceptions disabled. In order to test FPU exceptions we will need to at least
            // temporarily disable them before executing code here to generate such exceptions.
            // To do.
            break;

        case kCETTrap:
            // To do. This is hardware-specific.
            break;
    }
}


//-----------------------------------------------------------------------------
// SymbolLookup

#if defined(OVR_OS_MS)
    #if defined(OVR_CC_MSVC)
        // The Lock below is one that we want to keep around as long as possible, as there may be application code that
        // needs to do symbol lookups during process teardown after main has returned. The init_seg(lib) statement
        // below makes it so that this module's globals are initialized right after the C standard library has initialized,
        // and are destroyed right before the C standard library is destroyed (after after all other app globals are destroyed).
        #pragma warning(disable: 4073) // warning C4073: initializers put in library initialization area.
        #pragma warning(disable: 4075) // warning C4075: initializers put in unrecognized initialization area.
        #pragma init_seg(lib)
    #endif

    typedef BOOL    (WINAPI * StackWalk64Type)(DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
    typedef PVOID   (WINAPI * SymFunctionTableAccess64Type)(HANDLE hProcess, DWORD64 dwAddr);
    typedef DWORD64 (WINAPI * SymGetModuleBase64Type)(HANDLE hProcess, DWORD64 dwAddr);
    typedef DWORD   (WINAPI * SymSetOptionsType)(DWORD SymOptions);
    typedef BOOL    (WINAPI * SymInitializeWType)(HANDLE hProcess, PCWSTR UserSearchPath, BOOL fInvadeProcess);
    typedef BOOL    (WINAPI * SymCleanupType)(HANDLE hProcess);
    typedef DWORD64 (WINAPI * SymLoadModule64Type)(HANDLE hProcess, HANDLE hFile, PCSTR ImageName, PCSTR ModuleName, DWORD64 BaseOfDll, DWORD SizeOfDll);
    typedef BOOL    (WINAPI * SymFromAddrType)(HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol);
    typedef BOOL    (WINAPI * SymGetLineFromAddr64Type)(HANDLE hProcess, DWORD64 qwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line64);

    static StackWalk64Type              pStackWalk64 = nullptr;
    static SymFunctionTableAccess64Type pSymFunctionTableAccess64 = nullptr;
    static SymGetModuleBase64Type       pSymGetModuleBase64 = nullptr;
    static SymSetOptionsType            pSymSetOptions = nullptr;
    static SymInitializeWType           pSymInitializeW = nullptr;
    static SymCleanupType               pSymCleanup = nullptr;
    static SymLoadModule64Type          pSymLoadModule64 = nullptr;
    static SymFromAddrType              pSymFromAddr = nullptr;
    static SymGetLineFromAddr64Type     pSymGetLineFromAddr64 = nullptr;
    static int32_t                      sSymUsageCount = 0;
    static HMODULE                      sDbgHelp = nullptr;
    static OVR::Lock                    sDbgHelpLock;

    bool SymbolLookup::Initialize()
    {
        OVR::Lock::Locker autoLock(&sDbgHelpLock);

        if (++sSymUsageCount > 1)
        {
            OVR_ASSERT(pSymInitializeW != nullptr); // If it was already initialized then the pointers should be valid.
            return true;
        }

        // http://msdn.microsoft.com/en-us/library/windows/desktop/ms679294%28v=vs.85%29.aspx
        sDbgHelp = LoadLibraryW(L"DbgHelp.dll"); // It's best if the application supplies a recent version of this.

        if (sDbgHelp)
        {
            pStackWalk64              = (StackWalk64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "StackWalk64");
            pSymFunctionTableAccess64 = (SymFunctionTableAccess64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "SymFunctionTableAccess64");
            pSymGetModuleBase64       = (SymGetModuleBase64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "SymGetModuleBase64");
            pSymSetOptions            = (SymSetOptionsType)(uintptr_t)::GetProcAddress(sDbgHelp, "SymSetOptions");
            pSymInitializeW           = (SymInitializeWType)(uintptr_t)::GetProcAddress(sDbgHelp, "SymInitializeW");
            pSymCleanup               = (SymCleanupType)(uintptr_t)::GetProcAddress(sDbgHelp, "SymCleanup");
            pSymLoadModule64          = (SymLoadModule64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "SymLoadModule64");
            pSymFromAddr              = (SymFromAddrType)(uintptr_t)::GetProcAddress(sDbgHelp, "SymFromAddr");
            pSymGetLineFromAddr64     = (SymGetLineFromAddr64Type)(uintptr_t)::GetProcAddress(sDbgHelp, "SymGetLineFromAddr64");

            // To consider: Use a manually created search path:
            // wchar_t searchPathW[4096]; // Semicolon-separated strings.
            //     The current working directory of the application.
            //     The directory of the application itself (GetModuleFileName).
            //     The _NT_SYMBOL_PATH environment variable.
            //     The _NT_ALTERNATE_SYMBOL_PATH environment variable.

            if (pSymInitializeW)
            {
                if (pSymInitializeW(GetCurrentProcess(), nullptr /*searchPathW*/, FALSE))
                {
                    if (pSymSetOptions)
                    {
                        pSymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS);
                    }

                    return true;
                }
            }
        }

        return false;
    }

    bool SymbolLookup::IsInitialized()
    {
        // Note that it's possible that another thread could change the state of this right after the return.
        OVR::Lock::Locker autoLock(&sDbgHelpLock);
        return (sSymUsageCount != 0);
    }

    void SymbolLookup::Shutdown()
    {
        OVR::Lock::Locker autoLock(&sDbgHelpLock);

        if (sSymUsageCount > 0 &&
            --sSymUsageCount <= 0)
        {
            pSymCleanup(GetCurrentProcess());

            pStackWalk64              = nullptr;
            pSymFunctionTableAccess64 = nullptr;
            pSymGetModuleBase64       = nullptr;
            pSymSetOptions            = nullptr;
            pSymInitializeW           = nullptr;
            pSymCleanup               = nullptr;
            pSymLoadModule64          = nullptr;
            pSymFromAddr              = nullptr;
            pSymGetLineFromAddr64     = nullptr;

            FreeLibrary(sDbgHelp);
            sDbgHelp = nullptr;
        }
    }
#else
    bool SymbolLookup::Initialize()
    {
        return true;
    }

    bool SymbolLookup::IsInitialized()
    {
        return true;
    }

    void SymbolLookup::Shutdown()
    {
    }
#endif

SymbolLookup::SymbolLookup() :
    AllowMemoryAllocation(true),
    ModuleListUpdated(false),
    ModuleInfoArray(),
    ModuleInfoArraySize(0)
{
}

SymbolLookup::~SymbolLookup()
{
}

void SymbolLookup::AddSourceCodeDirectory(const char* pDirectory)
{
    OVR_UNUSED(pDirectory);
}

void SymbolLookup::EnableMemoryAllocation(bool enabled)
{
    AllowMemoryAllocation = enabled;
}


bool SymbolLookup::Refresh()
{
    ModuleListUpdated = false;
    return RefreshModuleList();
}


OVR_DISABLE_MSVC_WARNING(4740) // flow in or out of inline asm code suppresses global optimization
OVR_DISABLE_MSVC_WARNING(4748) // /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function


size_t SymbolLookup::GetBacktrace(void* addressArray[], size_t addressArrayCapacity, size_t skipCount, void* platformThreadContext, OVR::ThreadSysId threadSysIdHelp)
{
    #if defined(OVR_OS_WIN64)
        OVR_UNUSED(threadSysIdHelp);

        // The DbgHelp library must be loaded already.
        OVR_ASSERT(sSymUsageCount > 0);

        if(platformThreadContext == nullptr)
            return RtlCaptureStackBackTrace((DWORD)skipCount, (ULONG)addressArrayCapacity, addressArray, nullptr);

        // We need to get the call stack of another thread.
        size_t            frameIndex = 0;
        CONTEXT           context;
        PRUNTIME_FUNCTION pRuntimeFunction;
        ULONG64           imageBase = 0;
        ULONG64           imageBasePrev = 0;

        memcpy(&context, (CONTEXT*)platformThreadContext, sizeof(CONTEXT));
        context.ContextFlags = CONTEXT_CONTROL;

        if(context.Rip && (frameIndex < addressArrayCapacity))
            addressArray[frameIndex++] = (void*)(uintptr_t)context.Rip;

        while(context.Rip && (frameIndex < addressArrayCapacity))
        {
            imageBasePrev = imageBase;
            pRuntimeFunction = (PRUNTIME_FUNCTION)RtlLookupFunctionEntry(context.Rip, &imageBase, nullptr);

            if(pRuntimeFunction)
            {
                VOID*   handlerData = nullptr;
                ULONG64 establisherFramePointers[2] = { 0, 0 };
                RtlVirtualUnwind(UNW_FLAG_NHANDLER, imageBase, context.Rip, pRuntimeFunction, &context, &handlerData,  establisherFramePointers, nullptr);
            }
            else
            {
                context.Rip  = (ULONG64)(*(PULONG64)context.Rsp);
                context.Rsp += 8;
            }

            if(context.Rip && (frameIndex < addressArrayCapacity))
            {
                if(skipCount)
                    --skipCount;
                else
                    addressArray[frameIndex++] = (void*)(uintptr_t)context.Rip;
            }
        }

        return frameIndex;

    #elif defined(OVR_OS_WIN32)
        OVR_UNUSED(threadSysIdHelp);

        OVR::Lock::Locker autoLock(&sDbgHelpLock);
        size_t frameIndex = 0;

        if(pStackWalk64)
        {
            CONTEXT context;

            if(platformThreadContext)
            {
                memcpy(&context, platformThreadContext, sizeof(context));
                context.ContextFlags = CONTEXT_CONTROL;
            }
            else
            {
                memset(&context, 0, sizeof(context));
                context.ContextFlags = CONTEXT_CONTROL;

                __asm {
                    mov context.Ebp, EBP
                    mov context.Esp, ESP
                    call GetEIP
                    GetEIP:
                    pop context.Eip
                }
            }

            STACKFRAME64 sf;
            memset(&sf, 0, sizeof(sf));
            sf.AddrPC.Offset     = context.Eip;
            sf.AddrPC.Mode       = AddrModeFlat;
            sf.AddrStack.Offset  = context.Esp;
            sf.AddrStack.Mode    = AddrModeFlat;
            sf.AddrFrame.Offset  = context.Ebp;
            sf.AddrFrame.Mode    = AddrModeFlat;

            const HANDLE hCurrentProcess = ::GetCurrentProcess();
            const HANDLE hCurrentThread  = ::GetCurrentThread();

            if(!platformThreadContext) // If we are reading the current thread's call stack then we ignore this current function.
                skipCount++;

            while(frameIndex < addressArrayCapacity)
            {
                if(!pStackWalk64(IMAGE_FILE_MACHINE_I386, hCurrentProcess, hCurrentThread, &sf, &context, nullptr, pSymFunctionTableAccess64, pSymGetModuleBase64, nullptr))
                    break;

                if(sf.AddrFrame.Offset == 0)
                    break;

                if(skipCount)
                    --skipCount;
                else
                    addressArray[frameIndex++] = ((void*)(uintptr_t)sf.AddrPC.Offset);
            }
        }

        return frameIndex;

    #elif defined(OVR_OS_APPLE)
        struct StackFrame
        {
            StackFrame* pParentStackFrame;
            void*       pReturnPC;
        };

        void*       pInstruction;
        StackFrame* pStackFrame;
        size_t      frameIndex = 0;

        if(platformThreadContext)
        {
            #if defined(OVR_CPU_ARM)
                arm_thread_state_t* pThreadState = (arm_thread_state_t*)platformThreadContext;
                pStackFrame  = (StackFrame*)pThreadState->__fp;
                pInstruction = (void*)      pThreadState->__pc;
                #define FrameIsAligned(pStackFrame) ((((uintptr_t)pStackFrame) & 0x1) == 0)
            #elif defined(OVR_CPU_X86_64)
                x86_thread_state_t* pThreadState = (x86_thread_state_t*)platformThreadContext;
                pInstruction = (void*)      pThreadState->uts.ts64.__rip;
                pStackFrame  = (StackFrame*)pThreadState->uts.ts64.__rbp;
                #define FrameIsAligned(pStackFrame) ((((uintptr_t)pStackFrame) & 0xf) == 0)
            #elif defined(OVR_CPU_X86)
                x86_thread_state_t* pThreadState = (x86_thread_state_t*)platformThreadContext;
                pInstruction = (void*)      pThreadState->uts.ts32.__eip;
                pStackFrame  = (StackFrame*)pThreadState->uts.ts32.__ebp;
                #define FrameIsAligned(pStackFrame) ((((uintptr_t)pStackFrame) & 0xf) == 8)
            #endif

            if(frameIndex < addressArrayCapacity)
                addressArray[frameIndex++] = pInstruction;
        }
        else // Else get the current values...
        {
            pStackFrame = (StackFrame*)__builtin_frame_address(0);
            GetInstructionPointer(pInstruction);
        }

        pthread_t   threadSelf         = pthread_self();
        void*       pCurrentStackBase  = pthread_get_stackaddr_np(threadSelf);
        void*       pCurrentStackLimit = (void*)((uintptr_t)pCurrentStackBase - pthread_get_stacksize_np(threadSelf));
        bool        threadIsCurrent    = (platformThreadContext == nullptr) || (((void*)pStackFrame > pCurrentStackLimit) && ((void*)pStackFrame <= pCurrentStackBase));
        StackFrame* pStackBase;
        StackFrame* pStackLimit;

        if(threadIsCurrent)
        {
            pStackBase  = (StackFrame*)pCurrentStackBase;
            pStackLimit = (StackFrame*)pCurrentStackLimit;
        }
        else if(threadSysIdHelp)
        {
            pthread_t threadHandle = pthread_from_mach_thread_np((mach_port_t)threadSysIdHelp);
            pStackBase  = (StackFrame*)pthread_get_stackaddr_np(threadHandle);
            pStackLimit = (StackFrame*)((uintptr_t)pStackBase - pthread_get_stacksize_np(threadHandle));
        }
        else
        {   // We guess what the limits are.
            pStackBase  = pStackFrame + ((384 * 1024) / sizeof(StackFrame));
            pStackLimit = pStackFrame - ((384 * 1024) / sizeof(StackFrame));
        }

        if((frameIndex < addressArrayCapacity) && pStackFrame && FrameIsAligned(pStackFrame))
        {
            addressArray[frameIndex++] = pStackFrame->pReturnPC;

            while(pStackFrame && pStackFrame->pReturnPC && (frameIndex < addressArrayCapacity))
            {
                pStackFrame = pStackFrame->pParentStackFrame;

                if(pStackFrame && FrameIsAligned(pStackFrame) && pStackFrame->pReturnPC && (pStackFrame > pStackLimit) && (pStackFrame < pStackBase))
                {
                    if(skipCount)
                        --skipCount;
                    else
                        addressArray[frameIndex++] = pStackFrame->pReturnPC;
                }
                else
                    break;
            }
        }

        return frameIndex;

    #elif defined(OVR_OS_LINUX) && (defined( __LIBUNWIND__) || defined(LIBUNWIND_AVAIL))
        // Libunwind-based solution. Requires installation of libunwind package.
        // Libunwind isn't always safe for threads that are in signal handlers.
        // An approach to get the callstack of another thread is to use signal injection into the target thread.

        OVR_UNUSED(platformThreadContext);
        OVR_UNUSED(threadSysIdHelp);

        size_t        frameIndex = 0;
        unw_cursor_t  cursor;
        unw_context_t uc;
        unw_word_t    ip, sp;

        unw_getcontext(&uc);            // This gets the current thread's context. We could alternatively initialize another thread's context with it.
        unw_init_local(&cursor, &uc);

        while((unw_step(&cursor) > 0) && (frameIndex < addressArrayCapacity))
        {
            // We can get the function name here too on some platforms with unw_get_proc_info() and unw_get_proc_name().

            if(skipCount)
                --skipCount;
            else
            {
                unw_get_reg(&cursor, UNW_REG_IP, &ip);
                addressArray[frameIndex++] = (void*)ip;
            }
        }

        return frameIndex;
    #else
        OVR_UNUSED(addressArray);
        OVR_UNUSED(addressArrayCapacity);
        OVR_UNUSED(skipCount);
        OVR_UNUSED(platformThreadContext);
        OVR_UNUSED(threadSysIdHelp);

        return 0;
    #endif
}


size_t SymbolLookup::GetBacktraceFromThreadHandle(void* addressArray[], size_t addressArrayCapacity, size_t skipCount, OVR::ThreadHandle threadHandle)
{
    #if defined(OVR_OS_MS)
        size_t count = 0;
        DWORD  threadSysId = (DWORD)ConvertThreadHandleToThreadSysId(threadHandle);

        // Compare to 0, compare to the self 'pseudohandle' and compare to the self id.
        if((threadHandle == OVR_THREADHANDLE_INVALID) || (threadHandle == ::GetCurrentThread()) || (threadSysId == ::GetCurrentThreadId())) // If threadSysId refers to the current thread...
            return GetBacktrace(addressArray, addressArrayCapacity, skipCount, nullptr);

        // We are working with another thread. We need to suspend it and get its CONTEXT.
        // Suspending other threads is risky, as they may be in some state that cannot be safely blocked.
        BOOL  result = false;
        DWORD suspendResult = ::SuspendThread(threadHandle); // Requires that the handle have THREAD_SUSPEND_RESUME rights.

        if(suspendResult != (DWORD)-1) // Returns previous suspend count, or -1 if failed.
        {
            CONTEXT context;
            context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER; // Requires that the handle have THREAD_GET_CONTEXT rights.
            result = ::GetThreadContext(threadHandle, &context);
            count = GetBacktrace(addressArray, addressArrayCapacity, skipCount, &context);
            suspendResult = ::ResumeThread(threadHandle);
            OVR_ASSERT_AND_UNUSED(suspendResult != (DWORD)-1, suspendResult);
        }

        return count;

    #elif defined(OVR_OS_APPLE)
        mach_port_t threadSysID = pthread_mach_thread_np((pthread_t)threadHandle); // Convert pthread_t to mach thread id.
        return GetBacktraceFromThreadSysId(addressArray, addressArrayCapacity, skipCount, (OVR::ThreadSysId)threadSysID);

    #elif defined(OVR_OS_LINUX)
        // To do.
        OVR_UNUSED(addressArray);
        OVR_UNUSED(addressArrayCapacity);
        OVR_UNUSED(skipCount);
        OVR_UNUSED(threadHandle);
        return 0;
    #endif
}


size_t SymbolLookup::GetBacktraceFromThreadSysId(void* addressArray[], size_t addressArrayCapacity, size_t skipCount, OVR::ThreadSysId threadSysId)
{
    #if defined(OVR_OS_MS)
        OVR::ThreadHandle threadHandle = ConvertThreadSysIdToThreadHandle(threadSysId);
        if(threadHandle)
        {
            size_t count = GetBacktraceFromThreadHandle(addressArray, addressArrayCapacity, skipCount, threadHandle);
            FreeThreadHandle(threadHandle);
            return count;
        }
        return 0;

    #elif defined(OVR_OS_APPLE)
        mach_port_t threadCurrent = pthread_mach_thread_np(pthread_self());
        mach_port_t thread = (mach_port_t)threadSysId;

        if(thread == threadCurrent)
        {
            return GetBacktrace(addressArray, addressArrayCapacity, skipCount, nullptr);
        }
        else
        {
            kern_return_t result = thread_suspend(thread);    // Do we need to do this if it's an thread who exception is being handled?
            size_t        count  = 0;

            if(result == KERN_SUCCESS)
            {
                #if defined(OVR_CPU_X86) || defined(OVR_CPU_X86_64)
                    x86_thread_state_t threadState;
                #elif defined(OVR_CPU_ARM)
                    arm_thread_state_t threadState;
                #endif
                mach_msg_type_number_t stateCount = MACHINE_THREAD_STATE_COUNT;

                result = thread_get_state(thread, MACHINE_THREAD_STATE, (natural_t*)(uintptr_t)&threadState, &stateCount);

                if(result == KERN_SUCCESS)
                    count = GetBacktrace(addressArray, addressArrayCapacity, skipCount, &threadState, threadSysId);

                thread_resume(thread);

                return count;
            }
        }

        return 0;

    #elif defined(OVR_OS_LINUX)
        // To do.
        OVR_UNUSED(addressArray);
        OVR_UNUSED(addressArrayCapacity);
        OVR_UNUSED(skipCount);
        OVR_UNUSED(threadSysId);
        return 0;
    #endif
}


// We need to return the required moduleInfoArrayCapacity.
size_t SymbolLookup::GetModuleInfoArray(ModuleInfo* pModuleInfoArray, size_t moduleInfoArrayCapacity)
{
    #if defined(OVR_OS_MS)
        size_t       moduleCountRequired = 0;         // The count we would copy to pModuleInfoArray if moduleInfoArrayCapacity was enough.
        size_t       moduleCount = 0;                 // The count we actually copy to pModuleInfoArray. Will be <= moduleInfoArrayCapacity.
        HANDLE       hProcess = GetCurrentProcess();
        HMODULE      hModuleArray[200];
        DWORD        cbNeeded = 0;
        MODULEINFO   mi;

        if(EnumProcessModules(hProcess, hModuleArray, sizeof(hModuleArray), &cbNeeded))
        {
            moduleCountRequired = ((cbNeeded / sizeof(HMODULE)) < OVR_ARRAY_COUNT(hModuleArray)) ? (cbNeeded / sizeof(HMODULE)) : OVR_ARRAY_COUNT(hModuleArray);
            moduleCount         = MIN(moduleCountRequired, OVR_ARRAY_COUNT(hModuleArray));
            moduleCount         = MIN(moduleCount, moduleInfoArrayCapacity);

            for(size_t i = 0; i < moduleCount; i++)
            {
                ModuleInfo& moduleInfo = pModuleInfoArray[i];

                memset(&mi, 0, sizeof(mi));
                BOOL result = GetModuleInformation(hProcess, hModuleArray[i], &mi, sizeof(mi));

                if(result)
                {
                    wchar_t pathW[OVR_MAX_PATH];
                    char    pathA[OVR_MAX_PATH * 3]; // *3 to handle UTF8 multibyte encoding.

                    moduleInfo.handle      = hModuleArray[i];
                    moduleInfo.baseAddress = (uintptr_t)mi.lpBaseOfDll;
                    moduleInfo.size        = mi.SizeOfImage;

                    GetModuleFileNameW(hModuleArray[i], pathW, OVR_ARRAY_COUNT(pathW));
                    OVR::UTF8Util::EncodeString(pathA, pathW, -1); // Problem: DecodeString provides no way to specify the destination capacity.
                    OVR::OVR_strlcpy(moduleInfo.filePath, pathA, OVR_ARRAY_COUNT(moduleInfo.filePath));

                    const char* fileName = GetFileNameFromPath(pathA);
                    OVR::OVR_strlcpy(moduleInfo.name, fileName, OVR_ARRAY_COUNT(moduleInfo.name));
                }
                else
                {
                    moduleInfo.handle = 0;
                    moduleInfo.baseAddress = 0;
                    moduleInfo.size = 0;
                    moduleInfo.filePath[0] = 0;
                    moduleInfo.name[0] = 0;
                }
            }
        }

        return moduleCountRequired;

    #elif defined(OVR_OS_MAC)
        size_t moduleCountRequired = 0;
        size_t moduleCount = 0;

        struct MacModuleInfo // This struct exists solely so we can have a local function within this function..
        {
            static void AddMacModuleInfo(ModuleInfo* pModuleInfoArrayL, size_t& moduleCountRequiredL, size_t& moduleCountL, size_t moduleInfoArrayCapacityL,
                                        const char* pTypeFilterL, const char* pModulePath, uintptr_t currentSegmentPos, const MachHeader* pMachHeader, uint64_t offset)
            {
                for(size_t i = 0; i < pMachHeader->ncmds; i++)
                {
                    const SegmentCommand* pSegmentCommand = reinterpret_cast<const SegmentCommand*>(currentSegmentPos);

                    if(pSegmentCommand->cmd == kLCSegment)
                    {
                        const size_t segnameSize = (sizeof(pSegmentCommand->segname) + 1); // +1 so we can have a trailing '\0'.
                        char segname[segnameSize];

                        memcpy(segname, pSegmentCommand->segname, sizeof(pSegmentCommand->segname));
                        segname[segnameSize - 1] = '\0';

                        if(!pTypeFilterL || OVR_strncmp(segname, pTypeFilterL, sizeof(segname)))
                        {
                            moduleCountRequiredL++;

                            if(moduleCountL < moduleInfoArrayCapacityL)
                            {
                                ModuleInfo& info = pModuleInfoArrayL[moduleCountL++];

                                info.baseAddress = (uint64_t)(pSegmentCommand->vmaddr + offset);
                                info.handle      = reinterpret_cast<ModuleHandle>((uintptr_t)info.baseAddress);
                                info.size        = (uint64_t)pSegmentCommand->vmsize;
                                OVR_strlcpy(info.filePath, pModulePath, OVR_ARRAY_COUNT(info.filePath));
                                OVR_strlcpy(info.name, GetFileNameFromPath(pModulePath), OVR_ARRAY_COUNT(info.name));

                                info.permissions[0] = (pSegmentCommand->initprot & VM_PROT_READ)    ? 'r' : '-';
                                info.permissions[1] = (pSegmentCommand->initprot & VM_PROT_WRITE)   ? 'w' : '-';
                                info.permissions[2] = (pSegmentCommand->initprot & VM_PROT_EXECUTE) ? 'x' : '-';
                                info.permissions[3] = '/';
                                info.permissions[4] = (pSegmentCommand->maxprot  & VM_PROT_READ)    ? 'r' : '-';
                                info.permissions[5] = (pSegmentCommand->maxprot  & VM_PROT_WRITE)   ? 'w' : '-';
                                info.permissions[6] = (pSegmentCommand->maxprot  & VM_PROT_EXECUTE) ? 'x' : '-';
                                info.permissions[7] = '\0';

                                OVR_strlcpy(info.type, pSegmentCommand->segname, OVR_ARRAY_COUNT(info.type));
                            }
                        }
                    }

                    currentSegmentPos += pSegmentCommand->cmdsize;
                }
            }
        };

        // Iterate dyld_all_image_infos->infoArray
        const struct dyld_all_image_infos* pAllImageInfos = _dyld_get_all_image_infos();

        for(uint32_t i = 0; i < pAllImageInfos->infoArrayCount; i++)
        {
            const char* pModulePath = pAllImageInfos->infoArray[i].imageFilePath;

            if(pModulePath && *pModulePath)
            {
                uintptr_t         currentSegmentPos = (uintptr_t)pAllImageInfos->infoArray[i].imageLoadAddress;
                const MachHeader* pMachHeader       = reinterpret_cast<const MachHeader*>(currentSegmentPos);
                uint64_t          offset            = (uint64_t)_dyld_get_image_vmaddr_slide(i);

                currentSegmentPos += sizeof(*pMachHeader);

                MacModuleInfo::AddMacModuleInfo(pModuleInfoArray, moduleCountRequired, moduleCount, moduleInfoArrayCapacity,
                                                nullptr /*"__TEXT"*/, pModulePath, currentSegmentPos, pMachHeader, offset);
            }
        }

        // In addition to iterating dyld_all_image_infos->infoArray we need to also iterate /usr/lib/dyld entries.
        const MachHeader* pMachHeader = (const MachHeader*)pAllImageInfos->dyldImageLoadAddress;
        uintptr_t         currentSegmentPos = (uintptr_t)pMachHeader + sizeof(*pMachHeader);
        char              modulePath[OVR_MAX_PATH] = "";
        pid_t             pid = getpid();
        int               filenameLen = proc_regionfilename((int)pid, currentSegmentPos, modulePath, (uint32_t)sizeof(modulePath));

        if(filenameLen > 0)
            MacModuleInfo::AddMacModuleInfo(pModuleInfoArray, moduleCountRequired, moduleCount, moduleInfoArrayCapacity,
                                                "__TEXT", modulePath, currentSegmentPos, pMachHeader, 0);

        return moduleCountRequired;

    #elif defined(OVR_OS_LINUX)
        // One approach is to read /proc/self/maps, which is supported by Linux (though not BSD).
        // Linux glibc dladdr() can tell us what module an arbitrary function address comes from, but can't tell us the list of modules.
        OVR_UNUSED(pModuleInfoArray);
        OVR_UNUSED(moduleInfoArrayCapacity);
        return 0;

    #else
        OVR_UNUSED(pModuleInfoArray);
        OVR_UNUSED(moduleInfoArrayCapacity);
        return 0;
    #endif
}


size_t SymbolLookup::GetThreadList(ThreadHandle* threadHandleArray, ThreadSysId* threadSysIdArray, size_t threadArrayCapacity)
{
    size_t countRequired = 0;
    size_t count = 0;

    #if defined(OVR_OS_MS)
        // Print a list of threads.
        DWORD  currentProcessId = GetCurrentProcessId();
        HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, currentProcessId); // ICreateToolhelp32Snapshot actually ignores currentProcessId.

        if(hThreadSnap != INVALID_HANDLE_VALUE)
        {
            THREADENTRY32 te32;
            te32.dwSize = sizeof(THREADENTRY32);

            if(Thread32First(hThreadSnap, &te32))
            {
                do
                {
                    if(te32.th32OwnerProcessID == currentProcessId)
                    {
                        HANDLE hThread = ConvertThreadSysIdToThreadHandle(te32.th32ThreadID);

                        if(hThread)
                        {
                            ++countRequired;

                            if((threadHandleArray || threadSysIdArray) && (count < threadArrayCapacity))
                            {
                                if(threadHandleArray)
                                    threadHandleArray[count] = hThread; // The caller must call CloseHandle on this thread, or call DoneThreadList on the returned array.
                                if(threadSysIdArray)
                                    threadSysIdArray[count] = ConvertThreadHandleToThreadSysId(hThread);
                                ++count;
                            }

                            if(!threadHandleArray) // If we aren't giving this back to the user...
                                FreeThreadHandle(hThread);
                        }
                    }
                } while(Thread32Next(hThreadSnap, &te32));
            }

            CloseHandle(hThreadSnap);
        }

    #elif defined(OVR_OS_APPLE)
        mach_port_t             taskSelf   = mach_task_self();
        thread_act_port_array_t threadArray;
        mach_msg_type_number_t  threadCount;

        kern_return_t result = task_threads(taskSelf, &threadArray, &threadCount);

        if(result == KERN_SUCCESS)
        {
            for(mach_msg_type_number_t i = 0; i < threadCount; i++)
            {
                ++countRequired;

                if((threadHandleArray || threadSysIdArray) && (count < threadArrayCapacity))
                {
                    if(threadHandleArray)
                        threadHandleArray[count] = pthread_from_mach_thread_np(threadArray[i]);
                    if(threadSysIdArray)
                        threadSysIdArray[count] = threadArray[i];
                    ++count;
                }
            }

            vm_deallocate(taskSelf, (vm_address_t)threadArray, threadCount * sizeof(thread_act_t));
        }

    #elif defined(OVR_OS_LINUX)
        // To do.
        OVR_UNUSED(count);
        OVR_UNUSED(threadHandleArray);
        OVR_UNUSED(threadSysIdArray);
        OVR_UNUSED(threadArrayCapacity);
    #endif

    return countRequired;
}


void SymbolLookup::DoneThreadList(ThreadHandle* threadHandleArray, ThreadSysId* threadSysIdArray, size_t threadArrayCount)
{
    #if defined(OVR_OS_MS)
        for(size_t i = 0; i != threadArrayCount; ++i)
        {
            if(threadHandleArray[i])
            {
                CloseHandle(threadHandleArray[i]);
                threadHandleArray[i] = OVR_THREADHANDLE_INVALID;
            }
        }

        OVR_UNUSED(threadSysIdArray);
    #else
        OVR_UNUSED(threadHandleArray);
        OVR_UNUSED(threadSysIdArray);
        OVR_UNUSED(threadArrayCount);
    #endif
}


// Writes a given thread's callstack wity symbols to the given output.
// It may not be safe to call this from an exception handler, as sOutput allocates memory.
bool SymbolLookup::ReportThreadCallstack(OVR::String& sOutput, size_t skipCount, ThreadSysId threadSysId)
{
    sOutput.Clear();

    if(!threadSysId)
        threadSysId = GetCurrentThreadSysId();

    void*  addressArray[64];
    size_t addressCount = GetBacktraceFromThreadSysId(addressArray, OVR_ARRAY_COUNT(addressArray), skipCount, threadSysId);

    // Print the header
    char         headerBuffer[256];
    char         threadName[32];
    char         threadHandleStr[24];
    char         threadSysIdStr[48];
    char         stackBaseStr[24];
    char         stackLimitStr[24];
    void*        pStackBase;
    void*        pStackLimit;
  //void*        pStackCurrent;  // Current stack pointer. To do: support reporting this.
    ThreadHandle threadHandle = ConvertThreadSysIdToThreadHandle(threadSysId);
    OVR::GetThreadStackBounds(pStackBase, pStackLimit, threadHandle);

    Thread::GetThreadName(threadName, OVR_ARRAY_COUNT(threadName), threadName);
    SprintfThreadHandle(threadHandleStr, OVR_ARRAY_COUNT(threadHandleStr), threadHandle);
    SprintfThreadSysId(threadSysIdStr, OVR_ARRAY_COUNT(threadSysIdStr), threadSysId);
    SprintfAddress(stackBaseStr, OVR_ARRAY_COUNT(stackBaseStr), pStackBase);
    SprintfAddress(stackLimitStr, OVR_ARRAY_COUNT(stackLimitStr), pStackLimit);

    if(threadName[0])
        OVR_snprintf(headerBuffer, OVR_ARRAY_COUNT(headerBuffer), "Thread \"%s\" handle: %s, id: %s, stack base: %s, stack limit: %s\n", threadName, threadHandleStr, threadSysIdStr, stackBaseStr, stackLimitStr);
    else
        OVR_snprintf(headerBuffer, OVR_ARRAY_COUNT(headerBuffer), "Thread handle: %s, id: %s, stack base: %s, stack limit: %s\n", threadHandleStr, threadSysIdStr, stackBaseStr, stackLimitStr);

    sOutput += headerBuffer;

    // Print the backtrace info
    char        backtraceBuffer[1024];  // Sometimes function symbol names are very long.
    SymbolInfo  symbolInfo;
    const char* pModuleName;

    if(addressCount == 0)
    {
        sOutput += "<Unable to read backtrace>\n";
    }
    else
    {
        for(size_t i = 0; i < addressCount; ++i)
        {
            LookupSymbol((uint64_t)addressArray[i], symbolInfo);

            if(symbolInfo.pModuleInfo && symbolInfo.pModuleInfo->name[0])
                pModuleName = symbolInfo.pModuleInfo->name;
            else
                pModuleName = "(unknown module)";

            char addressStr[24];
            SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), addressArray[i]);

            if(symbolInfo.filePath[0])
                OVR_snprintf(backtraceBuffer, OVR_ARRAY_COUNT(backtraceBuffer), "%-2u %-24s %s %s+%d %s:%d\n", (unsigned)i, pModuleName, addressStr, symbolInfo.function, symbolInfo.functionOffset, symbolInfo.filePath, symbolInfo.fileLineNumber);
            else
                OVR_snprintf(backtraceBuffer, OVR_ARRAY_COUNT(backtraceBuffer), "%-2u %-24s %s %s+%d\n", (unsigned)i, pModuleName, addressStr, symbolInfo.function, symbolInfo.functionOffset);

            sOutput += backtraceBuffer;
        }
    }

    FreeThreadHandle(threadHandle);

    return (addressCount > 0);
}


// Writes all thread's callstacks with symbols to the given output.
// It may not be safe to call this from an exception handler, as sOutput allocates memory.
bool SymbolLookup::ReportThreadCallstacks(OVR::String& sOutput, size_t skipCount)
{
    sOutput.Clear();

    ThreadSysId threadSysIdArray[64];
    size_t      threadSysIdCount = GetThreadList(nullptr, threadSysIdArray, OVR_ARRAY_COUNT(threadSysIdArray));

    if (threadSysIdCount > OVR_ARRAY_COUNT(threadSysIdArray))
        threadSysIdCount = OVR_ARRAY_COUNT(threadSysIdArray);

    for (size_t i = 0; i < threadSysIdCount; i++)
    {
        String sTemp;
        ReportThreadCallstack(sTemp, skipCount, threadSysIdArray[i]);
        if(i > 0)
            sOutput += "\n";
        sOutput += sTemp;
    }

    return (threadSysIdCount > 0);
}

bool SymbolLookup::ReportModuleInformation(OVR::String& sOutput)
{
    sOutput.Clear();

    RefreshModuleList();

    char backtraceBuffer[1024];

    for (size_t i = 0; i < ModuleInfoArraySize; ++i)
    {
        OVR_snprintf(backtraceBuffer, OVR_ARRAY_COUNT(backtraceBuffer), "Base: 0x%llx Size: 0x%llx Name: '%s' Path: '%s'\n",
                     ModuleInfoArray[i].baseAddress, ModuleInfoArray[i].size, ModuleInfoArray[i].name, ModuleInfoArray[i].filePath);
        sOutput += backtraceBuffer;
    }

    return true;
}

bool SymbolLookup::RefreshModuleList()
{
    if(!ModuleListUpdated)
    {
        #if defined(OVR_OS_MS)
            OVR::Lock::Locker autoLock(&sDbgHelpLock);

            // We can't rely on SymRefreshModuleList because it's present in DbgHelp 6.5,
            // which doesn't distribute with Windows 7.

            // Currently we support only refreshing the list once ever. With a little effort we could revise this code to
            // support re-refreshing the list at runtime to account for the possibility that modules have recently been
            // added or removed.
            if(pSymLoadModule64)
            {
                const size_t requiredCount = GetModuleInfoArray(ModuleInfoArray, OVR_ARRAY_COUNT(ModuleInfoArray));
                ModuleInfoArraySize = MIN(requiredCount, OVR_ARRAY_COUNT(ModuleInfoArray));

                HANDLE hProcess = GetCurrentProcess();

                for(size_t i = 0; i < ModuleInfoArraySize; i++)
                    pSymLoadModule64(hProcess, nullptr, ModuleInfoArray[i].filePath, nullptr, ModuleInfoArray[i].baseAddress, (DWORD)ModuleInfoArray[i].size);

                ModuleListUpdated = true;
            }
        #else
            const size_t requiredCount = GetModuleInfoArray(ModuleInfoArray, OVR_ARRAY_COUNT(ModuleInfoArray));
            ModuleInfoArraySize = MIN(requiredCount, OVR_ARRAY_COUNT(ModuleInfoArray));
            ModuleListUpdated = true;
        #endif
    }

    return true;
}


bool SymbolLookup::LookupSymbol(uint64_t address, SymbolInfo& symbolInfo)
{
    return LookupSymbols(&address, &symbolInfo, 1);
}


bool SymbolLookup::LookupSymbols(uint64_t* addressArray, SymbolInfo* pSymbolInfoArray, size_t arraySize)
{
    bool success = false;

    if(!ModuleListUpdated)
    {
        RefreshModuleList();
    }

    #if defined(OVR_OS_MS)
        OVR::Lock::Locker autoLock(&sDbgHelpLock);

        union SYMBOL_INFO_UNION
        {
            SYMBOL_INFO msSymbolInfo;
            char        suffixPadding[sizeof(SYMBOL_INFO) + 1024];
        };

        for(size_t i = 0; i < arraySize; i++)
        {
            uint64_t&   address    = addressArray[i];
            SymbolInfo& symbolInfo = pSymbolInfoArray[i];

            // Copy the address and ModuleInfo
            symbolInfo.address     = addressArray[i];
            symbolInfo.pModuleInfo = GetModuleInfoForAddress(address); // We could also use siu.msSymbolInfo.ModBase to get the module slightly faster.

            // Get the function/offset.
            SYMBOL_INFO_UNION siu;
            memset(&siu, 0, sizeof(siu));
            siu.msSymbolInfo.SizeOfStruct = sizeof(siu.msSymbolInfo);
            siu.msSymbolInfo.MaxNameLen   = sizeof(siu.suffixPadding) - sizeof(SYMBOL_INFO) + 1; // +1 because SYMBOL_INFO itself has Name[1].

            HANDLE  hProcess = GetCurrentProcess();
            DWORD64 displacement64 = 0;
            bool    bResult = (pSymFromAddr != nullptr) && (pSymFromAddr(hProcess, address, &displacement64, &siu.msSymbolInfo) != FALSE);

            if(bResult)
            {
                success = true;
                symbolInfo.size = siu.msSymbolInfo.Size;
                OVR_strlcpy(symbolInfo.function, siu.msSymbolInfo.Name, OVR_ARRAY_COUNT(symbolInfo.function));
                symbolInfo.functionOffset = (int32_t)displacement64;
            }
            else
            {
                symbolInfo.size = kMISizeInvalid;
                symbolInfo.function[0] = 0;
                symbolInfo.functionOffset = kMIFunctionOffsetInvalid;
            }

            // Get the file/line
            IMAGEHLP_LINE64 iLine64;
            DWORD displacement = 0;
            memset(&iLine64, 0, sizeof(iLine64));
            iLine64.SizeOfStruct = sizeof(iLine64);

            bResult = (pSymGetLineFromAddr64 != nullptr) && (pSymGetLineFromAddr64(hProcess, address, &displacement, &iLine64) != FALSE);

            if(bResult)
            {
                success = true;
                OVR_strlcpy(symbolInfo.filePath, iLine64.FileName, OVR_ARRAY_COUNT(symbolInfo.filePath));
                symbolInfo.fileLineNumber = (int32_t)iLine64.LineNumber;
            }
            else
            {
                symbolInfo.filePath[0] = 0;
                symbolInfo.fileLineNumber = kMILineNumberInvalid;
            }

            // To do: get the source code when possible. We need to use the user-registered directory paths and the symbolInfo.filePath
            // and find the given file in the tree(s), then open the file and find the symbolInfo.fileLineNumber line (and surrounding lines).
            // symbolInfo.sourceCode[1024]
            symbolInfo.sourceCode[0] = '\0';
        }

    #elif defined(OVR_OS_APPLE)
        // Apple has an internal CoreSymbolication library which could help with this.
        // Third party implementations of the CoreSymbolication header are available and could be used
        // to get file/line info better than other means. It used Objective C, so we'll need a .m or .mm file.

        memset(pSymbolInfoArray, 0, arraySize * sizeof(SymbolInfo));

        for(size_t i = 0; i < arraySize; i++)
        {
            pSymbolInfoArray[i].address = addressArray[i];
            pSymbolInfoArray[i].pModuleInfo = GetModuleInfoForAddress(addressArray[i]);
        }

        // Problem: backtrace_symbols allocates memory from malloc. If you got into a SIGSEGV due to
        // malloc arena corruption (quite common) you will likely fault in backtrace_symbols.
        // To do: Use allowMemoryAllocation here.

        #if (OVR_PTR_SIZE == 4)
            // backtrace_symbols takes a void* array, but we have a uint64_t array. So for 32 bit we
            // need to convert the 64 bit array to 32 bit temporarily for the backtrace_symbols call.
            void* ptr32Array[256]; // To do: Remove this limit.
            for(size_t i = 0, iEnd = MIN(arraySize, OVR_ARRAY_COUNT(ptr32Array)); i < iEnd; i++)
                ptr32Array[i] = reinterpret_cast<void*>(addressArray[i]);
            char** symbolArray = backtrace_symbols(reinterpret_cast<void**>(ptr32Array), (int)arraySize);
        #else
            char** symbolArray = backtrace_symbols(reinterpret_cast<void**>(addressArray), (int)arraySize);
        #endif

        if(symbolArray)
        {
            success = true;

            for(size_t i = 0; i < arraySize; i++)
            {
                // Generates a string like this: "0 OculusWorldDemo 0x000000010000cfd5 _ZN18OculusWorldDemoApp9OnStartupEiPPKc + 213"
                static_assert(OVR_ARRAY_COUNT(pSymbolInfoArray[i].function) == 128, "Need to change the string format size below");

                sscanf(symbolArray[i], "%*d %*s %*x %128s + %d", pSymbolInfoArray[i].function, &pSymbolInfoArray[i].functionOffset);

                if(AllowMemoryAllocation)
                {
                    int   status = 0;
                    char* strDemangled = abi::__cxa_demangle(pSymbolInfoArray[i].function, nullptr, nullptr, &status);

                    if(strDemangled)
                    {
                        OVR_strlcpy(pSymbolInfoArray[i].function, strDemangled, OVR_ARRAY_COUNT(pSymbolInfoArray[i].function));
                        free(strDemangled);
                    }
                }
            }

            free(symbolArray);
        }

        // To consider: use CoreSybolication to get file/line info instead. atos is a bit slow and cumbersome.
        // https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/atos.1.html
        // atos -p <pid> <addr> <addr> ...
        // atos -o <binary image path> -l <load-address> <addr> <addr> ...
        // Generates output like this: "OVR::CreateException(OVR::CreateExceptionType) (in OculusWorldDemo) (ExceptionHandler.cpp:598)"
        for(size_t i = 0; i < arraySize; i++)
        {
            struct stat statStruct;

            if(pSymbolInfoArray[i].pModuleInfo && pSymbolInfoArray[i].pModuleInfo->filePath[0] && (stat(pSymbolInfoArray[i].pModuleInfo->filePath, &statStruct) == 0))
            {
                char command[PATH_MAX * 2];   // Problem: We can't unilaterally use pSymbolInfoArray[0] for all addresses. We need to match addresses to the corresponding modules.
                OVR_snprintf(command, OVR_ARRAY_COUNT(command), "atos -o %s -l 0x%llx 0x%llx",
                            pSymbolInfoArray[i].pModuleInfo->filePath, (int64_t)pSymbolInfoArray[i].pModuleInfo->baseAddress, (int64_t)pSymbolInfoArray[i].address);

                char output[512];
                if(SpawnShellCommand(command, output, OVR_ARRAY_COUNT(output)) != (size_t)-1)
                {
                    char* pLastOpenParen = strrchr(output, '(');
                    char* pColon = strrchr(output, ':');

                    if(pLastOpenParen && (pColon > pLastOpenParen))
                    {
                        *pColon = '\0';
                        OVR_strlcpy(pSymbolInfoArray[i].filePath, pLastOpenParen + 1, OVR_ARRAY_COUNT(pSymbolInfoArray[i].filePath));
                    }
                }
            }
        }

    #elif defined(OVR_OS_LINUX)
        // We can use libunwind's unw_get_proc_name to try to get function name info. It can work regardless of relocation.
        // Use backtrace_symbols and addr2line. Need to watch out for module load-time relocation.
        // Ned to pass the -rdynamic flag to the linker. It will cause the linker to out in the link
        // tables the name of all the none static functions in your code, not just the exported ones.
        OVR_UNUSED(addressArray);
        OVR_UNUSED(pSymbolInfoArray);
        OVR_UNUSED(arraySize);
    #endif

    return success;
}


const ModuleInfo* SymbolLookup::GetModuleInfoForAddress(uint64_t address)
{
    // This is a linear seach. To consider: it would be significantly faster to search by
    // address if we ordered it by base address and did a binary search.
    for(size_t i = 0; i < ModuleInfoArraySize; ++i)
    {
        const ModuleInfo& mi = ModuleInfoArray[i];

        if((mi.baseAddress <= address) && (address < (mi.baseAddress + mi.size)))
            return &mi;
    }

    return nullptr;
}




ExceptionInfo::ExceptionInfo()
  : time()
  , timeVal(0)
  , backtrace()
  , backtraceCount(0)
  , threadHandle(OVR_THREADHANDLE_INVALID)
  , threadSysId(OVR_THREADSYSID_INVALID)
  , threadName()
  , pExceptionInstructionAddress(nullptr)
  , pExceptionMemoryAddress(nullptr)
  , cpuContext()
  , exceptionDescription()
  , symbolInfo()
 #if defined(OVR_OS_MS)
  , exceptionRecord()
 #elif defined(OVR_OS_APPLE)
  , exceptionType(0)
  , cpuExceptionId(0)
  , cpuExceptionIdError(0)
  , machExceptionData()
  , machExceptionDataCount(0)
 #endif
{
}



ExceptionHandler::ExceptionHandler()
  : enabled(false)
  , pauseCount(0)
  , reportPrivacyEnabled(true)
  , exceptionResponse(kERHandle)
  , exceptionListener(nullptr)
  , exceptionListenerUserValue(0)
  , appDescription()
  , codeBasePathArray()
  , reportFilePath()
  , miniDumpFlags(0)
  , miniDumpFilePath()
  , file(nullptr)
  , scratchBuffer()
  , exceptionOccurred(false)
  , handlingBusy(0)
  , reportFilePathActual()
  , minidumpFilePathActual()
  , terminateReturnValue(0)
  , exceptionInfo()
 #if defined(OVR_OS_MS)
  , vectoredHandle(nullptr)
  , previousFilter(nullptr)
  , pExceptionPointers(nullptr)
 #elif defined(OVR_OS_MAC)
  , machHandlerInitialized(false)
  , machExceptionPort(0)
  , machExceptionPortsSaved()
  , machThreadShouldContinue(false)
  , machThreadExecuting(false)
  , machThread((pthread_t)OVR_THREADHANDLE_INVALID)
 #endif
{
    SetExceptionPaths("default", "default");
}

void ExceptionHandler::SetPathsFromNames(const char* organizationName, const char* ApplicationName, const char* exceptionFormat, const char* minidumpFormat)
{
    char exceptionPath[OVR_MAX_PATH];
    char miniDumpPath[OVR_MAX_PATH];
    GetCrashDumpDirectory(exceptionPath, OVR_MAX_PATH);
    OVR_strlcat(exceptionPath, organizationName, OVR_MAX_PATH);

    //make the organization folder if necessary
    #ifdef OVR_OS_MS
        WCHAR wpath[128];
        OVR::UTF8Util::DecodeString(wpath, exceptionPath);
        CreateDirectoryW(wpath,NULL);
    #else
        mkdir(exceptionPath,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    #endif

    #ifdef OVR_OS_MS
      const char* separator = "\\";
    #else
      const char* separator = "/";
    #endif
    OVR_strlcat(exceptionPath, separator, OVR_MAX_PATH);
    OVR_strlcat(exceptionPath, ApplicationName, OVR_MAX_PATH);
    #ifdef OVR_OS_MS
        OVR::UTF8Util::DecodeString(wpath, exceptionPath);
        CreateDirectoryW(wpath, NULL);
    #else
        mkdir(exceptionPath,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    #endif
    OVR_strlcat(exceptionPath, separator, OVR_MAX_PATH);
    OVR_strcpy(miniDumpPath, OVR_MAX_PATH, exceptionPath);

    OVR::OVR_strlcat(exceptionPath, exceptionFormat, OVR_MAX_PATH);
    OVR::OVR_strlcat(miniDumpPath, minidumpFormat, OVR_MAX_PATH);

    SetExceptionPaths(exceptionPath, miniDumpPath);
}

ExceptionHandler::~ExceptionHandler()
{
    if(enabled)
    {
        Enable(false);
    }
}

size_t ExceptionHandler::GetCrashDumpDirectory(char* directoryPath, size_t directoryPathCapacity)
{
    #if defined(OVR_OS_MS)
        wchar_t pathW[OVR_MAX_PATH + 1]; // +1 because we append a path separator.
        HRESULT hr = SHGetFolderPathW(nullptr, CSIDL_APPDATA | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, pathW);

        if (SUCCEEDED(hr))
        {
            intptr_t requiredUTF8Length = OVR::UTF8Util::GetEncodeStringSize(pathW); // Returns required strlen.
            if (requiredUTF8Length < OVR_MAX_PATH) // We need space for a trailing path separator.
            {
                OVR::UTF8Util::EncodeString(directoryPath, pathW, -1);
                OVR::OVR_strlcat(directoryPath, "\\", directoryPathCapacity);
            }

            return (requiredUTF8Length + 1);
        }

    #elif defined(OVR_OS_MAC)
        // This is the same location that Apple puts its OS-generated .crash files.
        const char* home = getenv("HOME");
        size_t requiredStrlen = OVR::OVR_snprintf(directoryPath, directoryPathCapacity, "%s/Library/Logs/DiagnosticReports/", home ? home : "/Users/Shared/Logs/DiagnosticReports/");
        // To do: create the directory if it doesn't already exist.
        return requiredStrlen;

    #elif defined(OVR_OS_UNIX)
        const char* home = getenv("HOME");
        size_t requiredStrlen = OVR::OVR_snprintf(directoryPath, directoryPathCapacity, "%s/Library/", home ? home : "/Users/Shared/");
        // To do: create the directory if it doesn't already exist.
        return requiredStrlen;
    #endif

    return 0;
}


#if defined(OVR_OS_MS)

static ExceptionHandler* sExceptionHandler = nullptr;

    unsigned WINAPI ExceptionHandler::ExceptionHandlerThreadExec(void * callingHandler)
    {
        ExceptionHandler* caller = reinterpret_cast<ExceptionHandler*>(callingHandler);
        if (caller->miniDumpFilePath[0])
            caller->WriteMiniDump();

        if (caller->reportFilePath[0])
            caller->WriteReport();

        if (caller->exceptionListener)
            caller->exceptionListener->HandleException(caller->exceptionListenerUserValue, caller, &caller->exceptionInfo, caller->reportFilePathActual);
        return 1;
    }

    LONG WINAPI Win32ExceptionFilter(LPEXCEPTION_POINTERS pExceptionPointers)
    {
        if(sExceptionHandler)
            return (LONG)sExceptionHandler->ExceptionFilter(pExceptionPointers);
        return EXCEPTION_CONTINUE_SEARCH;
    }

    LONG ExceptionHandler::ExceptionFilter(LPEXCEPTION_POINTERS pExceptionPointers)
    {
        if(pauseCount)
            return EXCEPTION_CONTINUE_SEARCH;

        // Exception codes < 0x80000000 are not true exceptions but rather are debugger notifications. They include DBG_TERMINATE_THREAD,
        // DBG_TERMINATE_PROCESS, DBG_CONTROL_BREAK, DBG_COMMAND_EXCEPTION, DBG_CONTROL_C, DBG_PRINTEXCEPTION_C, DBG_RIPEXCEPTION,
        // and 0x406d1388 (thread named, http://blogs.msdn.com/b/stevejs/archive/2005/12/19/505815.aspx).

        if(pExceptionPointers->ExceptionRecord->ExceptionCode < 0x80000000)
            return EXCEPTION_CONTINUE_SEARCH;

        // VC++ C++ exceptions use code 0xe06d7363 ('Emsc')
        // http://support.microsoft.com/kb/185294
        // http://blogs.msdn.com/b/oldnewthing/archive/2010/07/30/10044061.aspx
        if(pExceptionPointers->ExceptionRecord->ExceptionCode == 0xe06d7363)
            return EXCEPTION_CONTINUE_SEARCH;

        if(handlingBusy.CompareAndSet_Acquire(0, 1)) // If we can successfully change it from 0 to 1.
        {
            exceptionOccurred = true;

            SymbolLookup::Initialize();

            this->pExceptionPointers = pExceptionPointers;

            // Disable the handler while we do this processing.
            ULONG result = RemoveVectoredExceptionHandler(vectoredHandle);
            OVR_ASSERT_AND_UNUSED(result != 0, result);

            // Time
            exceptionInfo.timeVal = time(nullptr);
            exceptionInfo.time = *gmtime(&exceptionInfo.timeVal);

            // Thread id
            // This is the thread id of the current thread and not the exception thread.
            if(!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &exceptionInfo.threadHandle, 0, true, DUPLICATE_SAME_ACCESS))
                exceptionInfo.threadHandle = 0;
            exceptionInfo.threadSysId = ConvertThreadHandleToThreadSysId(exceptionInfo.threadHandle);

            OVR::GetThreadName(exceptionInfo.threadHandle, exceptionInfo.threadName, OVR_ARRAY_COUNT(exceptionInfo.threadName));

            // Backtraces
            exceptionInfo.backtraceCount = symbolLookup.GetBacktrace(exceptionInfo.backtrace, OVR_ARRAY_COUNT(exceptionInfo.backtrace));

            // Context
            exceptionInfo.cpuContext = *pExceptionPointers->ContextRecord;
            exceptionInfo.exceptionRecord = *pExceptionPointers->ExceptionRecord;
            exceptionInfo.pExceptionInstructionAddress  = exceptionInfo.exceptionRecord.ExceptionAddress;
            if((exceptionInfo.exceptionRecord.ExceptionCode == EXCEPTION_ACCESS_VIOLATION) || (exceptionInfo.exceptionRecord.ExceptionCode == EXCEPTION_IN_PAGE_ERROR))
                exceptionInfo.pExceptionMemoryAddress = (void*)exceptionInfo.exceptionRecord.ExceptionInformation[1]; // ExceptionInformation[0] indicates if it was a read (0), write (1), or data execution attempt (8).
            else
                exceptionInfo.pExceptionMemoryAddress = pExceptionPointers->ExceptionRecord->ExceptionAddress;

            WriteExceptionDescription();

            if (pExceptionPointers->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW){
                unsigned int IdValue;

                void* ThreadHandle = (HANDLE)_beginthreadex(0, (unsigned)128 * 1024,
                    ExceptionHandlerThreadExec, this, 0, (unsigned*)&IdValue);
                WaitForSingleObject(ThreadHandle, INFINITE);
                CloseHandle(ThreadHandle);

            }
            else
            {
                if (miniDumpFilePath[0])
                    WriteMiniDump();

                if (reportFilePath[0])
                    WriteReport();

                if (exceptionListener)
                    exceptionListener->HandleException(exceptionListenerUserValue, this, &exceptionInfo, reportFilePathActual);
            }
            if(exceptionInfo.threadHandle)
            {
                CloseHandle(exceptionInfo.threadHandle);
                exceptionInfo.threadHandle = 0;
            }

            SymbolLookup::Shutdown();

            // Restore the handler that we temporarily disabled above.
            vectoredHandle = AddVectoredExceptionHandler(1, Win32ExceptionFilter);

            handlingBusy.Store_Release(0);
        }

        if(exceptionResponse == ExceptionHandler::kERContinue)
            return EXCEPTION_CONTINUE_EXECUTION;
        else if(exceptionResponse == ExceptionHandler::kERHandle)
            return EXCEPTION_EXECUTE_HANDLER;
        else if(exceptionResponse == ExceptionHandler::kERTerminate)
        {
            TerminateProcess(GetCurrentProcess(), (UINT)terminateReturnValue);
            return terminateReturnValue;
        }
        else if(exceptionResponse == ExceptionHandler::kERThrow)
            return EXCEPTION_CONTINUE_SEARCH;

        // kERDefault
        return EXCEPTION_EXECUTE_HANDLER;
    }

#endif // defined(OVR_OS_MS)


#if defined(OVR_OS_APPLE)
    // http://www.opensource.apple.com/source/xnu/xnu-2050.22.13/
    // http://www.opensource.apple.com/source/xnu/xnu-2050.22.13/osfmk/man/
    // http://www.opensource.apple.com/source/Libc/Libc-825.26/
    // https://mikeash.com/pyblog/friday-qa-2013-01-11-mach-exception-handlers.html

    void* ExceptionHandler::MachHandlerThreadFunction()
    {
        __Request__mach_exception_raise_state_identity_t msg;
        __Reply__mach_exception_raise_state_identity_t reply;
        mach_msg_return_t result;

        machThreadExecuting = true;
        pthread_setname_np("ExceptionHandler");

        while(machThreadShouldContinue)
        {
            mach_msg_option_t options = MACH_RCV_MSG | MACH_RCV_LARGE;
            natural_t         timeout = 0; // Would be better to support a non-zero time.

            if(timeout)
                options |= MACH_RCV_TIMEOUT;

            result = mach_msg(&msg.Head, options, 0, sizeof(msg), machExceptionPort, timeout, MACH_PORT_NULL);

            if(msg.Head.msgh_id != sMachCancelMessageType)
            {
                if(result == MACH_MSG_SUCCESS)
                {
                    if(mach_exc_server_OVR(&msg.Head, &reply.Head) == 0)  //This will call our HandleMachException function.
                        result = ~MACH_MSG_SUCCESS;
                }

                // Send the reply
                if(result == MACH_MSG_SUCCESS)
                {
                    result = mach_msg(&reply.Head, MACH_SEND_MSG, reply.Head.msgh_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);

                    if(result != MACH_MSG_SUCCESS)
                    {
                        // Failure.
                    }
                }
            }
        }

        machThreadExecuting = false;

        return nullptr;
    }


    kern_return_t ExceptionHandler::HandleMachException(mach_port_t /*machPort*/, mach_port_t threadSysId, mach_port_t machTask,
                                            exception_type_t machExceptionType, mach_exception_data_type_t* pMachExceptionData,
                                            mach_msg_type_number_t exceptionDataCount, int* /*pMachExceptionFlavor*/, thread_state_t threadStatePrev,
                                            mach_msg_type_number_t /*threadStatePrevCount*/, thread_state_t /*threadStateNew*/,
                                            mach_msg_type_number_t* /*pThreadStateNewCount*/)
    {
        // We don't want to handle exceptions for other processes.
        if(machTask != mach_task_self())
            return ForwardMachException(threadSysId, machTask, machExceptionType, pMachExceptionData, exceptionDataCount);

        if(handlingBusy.CompareAndSet_Acquire(0, 1)) // If we can successfully change it from 0 to 1.
        {
            exceptionOccurred = true;

            // Disable the handler while we do this processing.
            // To do.

            // Time
            exceptionInfo.timeVal = time(nullptr);
            exceptionInfo.time = *gmtime(&exceptionInfo.timeVal);

            // Thread id
            exceptionInfo.threadHandle = pthread_from_mach_thread_np(threadSysId);
            exceptionInfo.threadSysId  = threadSysId;
            pthread_getname_np((pthread_t)exceptionInfo.threadHandle, exceptionInfo.threadName, sizeof(exceptionInfo.threadName));

            // Backtraces
            exceptionInfo.backtraceCount = symbolLookup.GetBacktraceFromThreadSysId(exceptionInfo.backtrace, OVR_ARRAY_COUNT(exceptionInfo.backtrace), 0, threadSysId);

            // Context
            #if defined(OVR_CPU_X86) || defined(OVR_CPU_X86_64)
                // We can read x86_THREAD_STATE directly fromk threadStatePrev.
                exceptionInfo.cpuContext.threadState = *reinterpret_cast<x86_thread_state_t*>(threadStatePrev);

                mach_msg_type_number_t stateCount = x86_FLOAT_STATE_COUNT;
                thread_get_state(threadSysId, x86_FLOAT_STATE, (natural_t*)&exceptionInfo.cpuContext.floatState, &stateCount);

                stateCount = x86_DEBUG_STATE_COUNT;
                thread_get_state(threadSysId, x86_DEBUG_STATE, (natural_t*)&exceptionInfo.cpuContext.debugState, &stateCount);

                stateCount = x86_AVX_STATE_COUNT;
                thread_get_state(threadSysId, x86_AVX_STATE, (natural_t*)&exceptionInfo.cpuContext.avxState, &stateCount);

                stateCount = x86_EXCEPTION_STATE_COUNT;
                thread_get_state(threadSysId, x86_EXCEPTION_STATE, (natural_t*)&exceptionInfo.cpuContext.exceptionState, &stateCount);

                #if defined(OVR_CPU_X86)
                    exceptionInfo.pExceptionInstructionAddress = (void*)exceptionInfo.cpuContext.threadState.uts.ts32.__eip;
                    exceptionInfo.pExceptionMemoryAddress      = (void*)exceptionInfo.cpuContext.exceptionState.ues.es32.__faultvaddr;
                    exceptionInfo.cpuExceptionId               = exceptionInfo.cpuContext.exceptionState.ues.es32.__trapno;
                    exceptionInfo.cpuExceptionIdError          = exceptionInfo.cpuContext.exceptionState.ues.es32.__err;
                #else
                    exceptionInfo.pExceptionInstructionAddress = (void*)exceptionInfo.cpuContext.threadState.uts.ts64.__rip;
                    exceptionInfo.pExceptionMemoryAddress      = (void*)exceptionInfo.cpuContext.exceptionState.ues.es64.__faultvaddr;
                    exceptionInfo.cpuExceptionId               = exceptionInfo.cpuContext.exceptionState.ues.es64.__trapno;
                    exceptionInfo.cpuExceptionIdError          = exceptionInfo.cpuContext.exceptionState.ues.es64.__err;
                #endif
            #endif

            exceptionInfo.exceptionType = machExceptionType;

            exceptionInfo.machExceptionDataCount = MIN(exceptionDataCount, OVR_ARRAY_COUNT(exceptionInfo.machExceptionData));
            for(int i = 0; i < exceptionInfo.machExceptionDataCount; i++)
                exceptionInfo.machExceptionData[i] = pMachExceptionData[i];

            WriteExceptionDescription();

            if(reportFilePath[0])
                WriteReport();

            if(miniDumpFilePath[0])
                WriteMiniDump();

            if(exceptionListener)
                exceptionListener->HandleException(exceptionListenerUserValue, this, &exceptionInfo, reportFilePathActual);

            // Re-restore the handler.
            // To do.

            handlingBusy.Store_Release(0);
        }

        kern_return_t result = KERN_FAILURE; // By default pass on the exception to another handler after we are done here.

        if(exceptionResponse == ExceptionHandler::kERContinue)
            result = KERN_SUCCESS; // This will trigger a re-execution of the function.
        else if(exceptionResponse == ExceptionHandler::kERTerminate)
            ::exit(terminateReturnValue);
        else if(exceptionResponse == ExceptionHandler::kERThrow)
            ForwardMachException(threadSysId, machTask, machExceptionType, pMachExceptionData, exceptionDataCount);
        else if(exceptionResponse == ExceptionHandler::kERDefault)
            ::exit(terminateReturnValue);

        // kERHandle
        return result;
    }


    bool ExceptionHandler::InitMachExceptionHandler()
    {
        if(!machHandlerInitialized)
        {
            mach_port_t      machTaskSelf = mach_task_self();
            kern_return_t    result = MACH_MSG_SUCCESS;
            exception_mask_t mask = EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC | EXC_MASK_CRASH;

            if(machExceptionPort == MACH_PORT_NULL)
            {
                result = mach_port_allocate(machTaskSelf, MACH_PORT_RIGHT_RECEIVE, &machExceptionPort);

                if(result == MACH_MSG_SUCCESS)
                {
                    result = mach_port_insert_right(machTaskSelf, machExceptionPort, machExceptionPort, MACH_MSG_TYPE_MAKE_SEND);

                    if(result == MACH_MSG_SUCCESS)
                        result = task_get_exception_ports(machTaskSelf, mask, machExceptionPortsSaved.masks, &machExceptionPortsSaved.count,
                                                          machExceptionPortsSaved.ports, machExceptionPortsSaved.behaviors, machExceptionPortsSaved.flavors);
                }
            }

            if(result == MACH_MSG_SUCCESS)
            {
                result = task_set_exception_ports(machTaskSelf, mask, machExceptionPort, EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, MACHINE_THREAD_STATE);

                if(result == MACH_MSG_SUCCESS)
                {
                    machThreadShouldContinue = true;

                    pthread_attr_t attr;
                    pthread_attr_init(&attr);

                    result = pthread_create(&machThread, &attr, MachHandlerThreadFunctionStatic, (void*)this);
                    pthread_attr_destroy(&attr);

                    machHandlerInitialized = (result == 0);
                }
            }

            if(!machHandlerInitialized)
                ShutdownMachExceptionHandler();
        }

        return machHandlerInitialized;
    }


    void ExceptionHandler::ShutdownMachExceptionHandler()
    {
        if(machThreadExecuting)
        {
            machThreadShouldContinue = false; // Tell it to stop.

            // Cancel the current exception handler thread (which is probably blocking in a call to mach_msg) by sending it a cencel message.
            struct CancelMessage
            {
                mach_msg_header_t msgHeader;
            };

            CancelMessage msg;
            memset(&msg.msgHeader, 0, sizeof(CancelMessage));
            msg.msgHeader.msgh_id          = sMachCancelMessageType;
            msg.msgHeader.msgh_size        = sizeof(CancelMessage);
            msg.msgHeader.msgh_bits        = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MAKE_SEND);
            msg.msgHeader.msgh_remote_port = machExceptionPort;
            msg.msgHeader.msgh_local_port  = MACH_PORT_NULL;

            mach_msg_return_t result = mach_msg(&msg.msgHeader, MACH_SEND_MSG, msg.msgHeader.msgh_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);

            if(result == MACH_MSG_SUCCESS)
            {
                const time_t secondsLater = time(NULL) + 4;

                while(machThreadExecuting && (time(NULL) < secondsLater))
                {
                    timespec ts = { 0, 1000000000 };
                    nanosleep(&ts, nullptr);
                }
            }

            void* joinResult = nullptr;
            pthread_join(machThread, &joinResult);
            machThread = 0;
        }

        if(machExceptionPort != MACH_PORT_NULL)
        {
            // Restore the previous ports
            kern_return_t result = KERN_SUCCESS;
            mach_port_t   machTaskSelf = mach_task_self();

            for(unsigned i = 0; (i < machExceptionPortsSaved.count) && (result == KERN_SUCCESS); i++)
            {
                result = task_set_exception_ports(machTaskSelf, machExceptionPortsSaved.masks[i], machExceptionPortsSaved.ports[i],
                              machExceptionPortsSaved.behaviors[i], machExceptionPortsSaved.flavors[i]);
            }

            mach_port_deallocate(machTaskSelf, machExceptionPort);
            machExceptionPort = MACH_PORT_NULL;
        }

        machHandlerInitialized = false;
    }


    kern_return_t ExceptionHandler::ForwardMachException(mach_port_t thread, mach_port_t task, exception_type_t exceptionType,
                                                mach_exception_data_t pMachExceptionData, mach_msg_type_number_t exceptionDataCount)
    {
        kern_return_t result = KERN_FAILURE;
        mach_msg_type_number_t i;

        for(i = 0; i < machExceptionPortsSaved.count; i++)
        {
            if(machExceptionPortsSaved.masks[i] & (1 << exceptionType))
                break;
        }

        if(i < machExceptionPortsSaved.count)
        {
            mach_port_t            port             = machExceptionPortsSaved.ports[i];
            exception_behavior_t   behavior         = machExceptionPortsSaved.behaviors[i];
            thread_state_flavor_t  flavor           = machExceptionPortsSaved.flavors[i];
            mach_msg_type_number_t threadStateCount = THREAD_STATE_MAX;
            thread_state_data_t    threadState;

            if(behavior != EXCEPTION_DEFAULT)
                thread_get_state(thread, flavor, threadState, &threadStateCount);

            switch(behavior)
            {
                case EXCEPTION_DEFAULT:
                    result = mach_exception_raise_OVR(port, thread, task, exceptionType, pMachExceptionData, exceptionDataCount);
                    break;

                case EXCEPTION_STATE:
                    result = mach_exception_raise_state_OVR(port, exceptionType, pMachExceptionData, exceptionDataCount,
                                       &flavor, threadState, threadStateCount, threadState, &threadStateCount);
                    break;

                case EXCEPTION_STATE_IDENTITY:
                    result = mach_exception_raise_state_identity_OVR(port, thread, task, exceptionType, pMachExceptionData,
                                    exceptionDataCount, &flavor, threadState, threadStateCount, threadState, &threadStateCount);
                    break;

                default:
                    result = KERN_FAILURE;
                    break;
            }

            if(behavior != EXCEPTION_DEFAULT)
                result = thread_set_state(thread, flavor, threadState, threadStateCount);
        }

        return result;
    }


#endif // OVR_OS_APPLE


bool ExceptionHandler::Enable(bool enable)
{
    #if defined(OVR_OS_MS)
        if(enable && !enabled)
        {
            OVR_ASSERT(vectoredHandle == nullptr);
            vectoredHandle = AddVectoredExceptionHandler(1, Win32ExceptionFilter); // Windows call.
            enabled = (vectoredHandle != nullptr);
            OVR_ASSERT(enabled);
            sExceptionHandler = this;
            return enabled;
        }
        else if(!enable && enabled)
        {
            if(sExceptionHandler == this)
                sExceptionHandler = nullptr;
            OVR_ASSERT(vectoredHandle != nullptr);
            ULONG result = RemoveVectoredExceptionHandler(vectoredHandle); // Windows call.
            OVR_ASSERT_AND_UNUSED(result != 0, result);
            vectoredHandle = nullptr;
            enabled = false;
            return true;
        }

    #elif defined(OVR_OS_APPLE)

        if(enable && !enabled)
        {
            enabled = InitMachExceptionHandler();
            OVR_ASSERT(enabled);
            sExceptionHandler = this;
            return enabled;
        }
        else if(!enable && enabled)
        {
            if(sExceptionHandler == this)
                sExceptionHandler = nullptr;
            ShutdownMachExceptionHandler();
            enabled = false;
            return true;
        }
    #else
        OVR_UNUSED(enable);
    #endif

    return true;
}

int ExceptionHandler::PauseHandling(bool pause)
{
    if(pause)
        return ++pauseCount;

    OVR_ASSERT(pauseCount > 0);
    return --pauseCount;
}

void ExceptionHandler::EnableReportPrivacy(bool enable)
{
    reportPrivacyEnabled = enable;
}

void ExceptionHandler::WriteExceptionDescription()
{
    #if defined(OVR_OS_MS)
        // There is some extra information available for AV exception.
        if(exceptionInfo.exceptionRecord.ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
        {
            const char* error = (exceptionInfo.exceptionRecord.ExceptionInformation[0] == 0) ? "reading" :
                               ((exceptionInfo.exceptionRecord.ExceptionInformation[0] == 1) ? "writing" : "executing");

            char addressStr[24];
            SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), exceptionInfo.pExceptionMemoryAddress);
            OVR::OVR_snprintf(exceptionInfo.exceptionDescription, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription), "ACCESS_VIOLATION %s address %s", error, addressStr);
        }
        else
        {
            exceptionInfo.exceptionDescription[0] = 0;

            // Process "standard" exceptions, other than 'access violation'
            #define FORMAT_EXCEPTION(x)           \
                case EXCEPTION_##x:               \
                    OVR::OVR_strlcpy(exceptionInfo.exceptionDescription, #x, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription)); \
                    break;

            switch(exceptionInfo.exceptionRecord.ExceptionCode)
            {
              //FORMAT_EXCEPTION(ACCESS_VIOLATION) Already handled above.
                FORMAT_EXCEPTION(DATATYPE_MISALIGNMENT)
                FORMAT_EXCEPTION(BREAKPOINT)
                FORMAT_EXCEPTION(SINGLE_STEP)
                FORMAT_EXCEPTION(ARRAY_BOUNDS_EXCEEDED)
                FORMAT_EXCEPTION(FLT_DENORMAL_OPERAND)
                FORMAT_EXCEPTION(FLT_DIVIDE_BY_ZERO)
                FORMAT_EXCEPTION(FLT_INEXACT_RESULT)
                FORMAT_EXCEPTION(FLT_INVALID_OPERATION)
                FORMAT_EXCEPTION(FLT_OVERFLOW)
                FORMAT_EXCEPTION(FLT_STACK_CHECK)
                FORMAT_EXCEPTION(FLT_UNDERFLOW)
                FORMAT_EXCEPTION(INT_DIVIDE_BY_ZERO)
                FORMAT_EXCEPTION(INT_OVERFLOW)
                FORMAT_EXCEPTION(PRIV_INSTRUCTION)
                FORMAT_EXCEPTION(IN_PAGE_ERROR)
                FORMAT_EXCEPTION(ILLEGAL_INSTRUCTION)
                FORMAT_EXCEPTION(NONCONTINUABLE_EXCEPTION)
                FORMAT_EXCEPTION(STACK_OVERFLOW)
                FORMAT_EXCEPTION(INVALID_DISPOSITION)
                FORMAT_EXCEPTION(GUARD_PAGE)
                FORMAT_EXCEPTION(INVALID_HANDLE)
              #if defined(EXCEPTION_POSSIBLE_DEADLOCK) && defined(STATUS_POSSIBLE_DEADLOCK) // This type seems to be non-existant in practice.
                FORMAT_EXCEPTION(POSSIBLE_DEADLOCK)
              #endif
            }

            // If not one of the "known" exceptions, try to get the string from NTDLL.DLL's message table.
            if(exceptionInfo.exceptionDescription[0] == 0)
            {
                char addressStr[24];
                SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), exceptionInfo.pExceptionMemoryAddress);

                char  buffer[384];
                DWORD capacity = OVR_ARRAY_COUNT(buffer);

                const size_t length = (size_t)FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE,
                                                    GetModuleHandleW(L"NTDLL.DLL"), exceptionInfo.exceptionRecord.ExceptionCode, 0, buffer, capacity, nullptr);
                if(length)
                    OVR::OVR_snprintf(exceptionInfo.exceptionDescription, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription),
                                        "%s at instruction %s", buffer, addressStr);

                // If everything else failed just show the hex code.
                if(exceptionInfo.exceptionDescription[0] == 0)
                    OVR::OVR_snprintf(exceptionInfo.exceptionDescription, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription),
                                      "Unknown exception 0x%08x at instruction %s", exceptionInfo.exceptionRecord.ExceptionCode, addressStr);
            }
        }

    #elif defined(OVR_OS_APPLE)
        struct MachExceptionInfo
        {
            static const char* GetCPUExceptionIdString(uint32_t cpuExceptionId)
            {
                const char* id;

                #if defined(OVR_CPU_X86) || defined(OVR_CPU_X86_64)
                    switch (cpuExceptionId)
                    {
                        case  0: id = "integer div/0";               break;
                        case  1: id = "breakpoint fault";            break;
                        case  2: id = "non-maskable interrupt";      break;
                        case  3: id = "int 3";                       break;
                        case  4: id = "overflow";                    break;
                        case  5: id = "bounds check failure";        break;
                        case  6: id = "invalid instruction";         break;
                        case  7: id = "coprocessor unavailable";     break;
                        case  8: id = "exception within exception";  break;
                        case  9: id = "coprocessor segment overrun"; break;
                        case 10: id = "invalid task switch";         break;
                        case 11: id = "segment not present";         break;
                        case 12: id = "stack exception";             break;
                        case 13: id = "general protection fault";    break;
                        case 14: id = "page fault";                  break;
                        case 16: id = "coprocessor error";           break;
                        default: id = "<unknown>";                   break;
                    }
                #else
                    // To do: Support ARM or others.
                #endif

                return id;
            }

            static const char* GetMachExceptionTypeString(uint64_t exceptionCause)
            {
                switch (exceptionCause)
                {
                    case EXC_ARITHMETIC:      return "EXC_ARITHMETIC";
                    case EXC_BAD_ACCESS:      return "EXC_BAD_ACCESS";
                    case EXC_BAD_INSTRUCTION: return "EXC_BAD_INSTRUCTION";
                    case EXC_BREAKPOINT:      return "EXC_BREAKPOINT";
                    case EXC_CRASH:           return "EXC_CRASH";
                    case EXC_EMULATION:       return "EXC_EMULATION";
                    case EXC_MACH_SYSCALL:    return "EXC_MACH_SYSCALL";
                    case EXC_RPC_ALERT:       return "EXC_RPC_ALERT";
                    case EXC_SOFTWARE:        return "EXC_SOFTWARE";
                    case EXC_SYSCALL:         return "EXC_SYSCALL";
                };

                return "EXC_<unknown>";
            }

            static const char* GetMachExceptionIdString(uint64_t machExceptionId, uint64_t code0)
            {
                const char* id = "<unknown>";

                #if defined(OVR_CPU_X86) || defined(OVR_CPU_X86_64)
                    switch (machExceptionId)
                    {
                        case EXC_ARITHMETIC:
                            switch (code0)
                            {
                                case EXC_I386_BOUND:     id = "EXC_I386_BOUND";     break;
                                case EXC_I386_DIV:       id = "EXC_I386_DIV";       break;
                                case EXC_I386_EMERR:     id = "EXC_I386_EMERR";     break;
                                case EXC_I386_EXTERR:    id = "EXC_I386_EXTERR";    break;
                                case EXC_I386_EXTOVR:    id = "EXC_I386_EXTOVR";    break;
                                case EXC_I386_INTO:      id = "EXC_I386_INTO";      break;
                                case EXC_I386_NOEXT:     id = "EXC_I386_NOEXT";     break;
                                case EXC_I386_SSEEXTERR: id = "EXC_I386_SSEEXTERR"; break;
                            }
                            break;

                        case EXC_BAD_INSTRUCTION:
                            if(code0 == EXC_I386_INVOP)
                                id = "EXC_I386_INVOP";
                            break;

                        case EXC_BREAKPOINT:
                            if(code0 == EXC_I386_BPT)
                                id = "EXC_I386_BPT";
                            else if(code0 == EXC_I386_SGL)
                                id = "EXC_I386_SGL";
                            break;
                    };
                #else
                    // To do.
                #endif

                return id;
            }
        };

        OVR::OVR_snprintf(exceptionInfo.exceptionDescription, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription),
                            "Mach exception type: %llu (%s)\n", exceptionInfo.exceptionType, MachExceptionInfo::GetMachExceptionTypeString(exceptionInfo.exceptionType));

        OVR::OVR_snprintf(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), "CPU exception info: exception id: %u (%s), exception id error: %u, fault memory address: %p\n",
                            exceptionInfo.cpuExceptionId, MachExceptionInfo::GetCPUExceptionIdString(exceptionInfo.cpuExceptionId), exceptionInfo.cpuExceptionIdError, exceptionInfo.pExceptionMemoryAddress);
        OVR::OVR_strlcat(exceptionInfo.exceptionDescription, scratchBuffer, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription));


        OVR::OVR_snprintf(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), "Mach exception info: exception id: %llu (%s), 0x%llx (%llu)\n", (uint64_t)exceptionInfo.machExceptionData[0],
                           MachExceptionInfo::GetMachExceptionIdString(exceptionInfo.exceptionType, exceptionInfo.machExceptionData[0]),
                           (uint64_t)exceptionInfo.machExceptionData[1], (uint64_t)exceptionInfo.machExceptionData[1]);
        OVR::OVR_strlcat(exceptionInfo.exceptionDescription, scratchBuffer, OVR_ARRAY_COUNT(exceptionInfo.exceptionDescription));
    #else
        // To do.
        exceptionInfo.exceptionDescription[0] = 0;
    #endif
}


void ExceptionHandler::WriteReportLine(const char* pLine)
{
    fwrite(pLine, strlen(pLine), 1, file);
}


void ExceptionHandler::WriteReportLineF(const char* format, ...)
{
    va_list args;
    va_start(args, format);
    int length = OVR_vsnprintf(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), format, args);
    if(length >= (int)OVR_ARRAY_COUNT(scratchBuffer))     // If we didn't have enough space...
        length = (OVR_ARRAY_COUNT(scratchBuffer) - 1);    // ... use what we have.
    va_end(args);

    fwrite(scratchBuffer, length, 1, file);
}


// Thread <name> <handle> <id>
// 0   <module> <address> <function> <file>:<line>
// 1   <module> <address> <function> <file>:<line>
// . . .
//
void ExceptionHandler::WriteThreadCallstack(ThreadHandle threadHandle, ThreadSysId threadSysId, const char* additionalInfo)
{
    // We intentionally do not directly use the SymbolInfo::ReportThreadCallstack function because that function allocates memory,
    // which we cannot do due to possibly being within an exception handler.

    // Print the header
    char    threadName[32];
    char    threadHandleStr[32];
    char    threadSysIdStr[32];
    char    stackBaseStr[24];
    char    stackLimitStr[24];
    char    stackCurrentStr[24];
    void*   pStackBase;
    void*   pStackLimit;
    bool    isExceptionThread = (threadSysId == exceptionInfo.threadSysId);

    #if defined(OVR_OS_MS) && (OVR_PTR_SIZE == 8)
      void* pStackCurrent = (threadSysId == exceptionInfo.threadSysId) ? (void*)exceptionInfo.cpuContext.Rsp : nullptr; // We would need to suspend the thread, get its context, resume it, then read the rsp register. It turns out we are already doing that suspend/resume below in the backtrace call.
    #elif defined(OVR_OS_MS)
      void* pStackCurrent = (threadSysId == exceptionInfo.threadSysId) ? (void*)exceptionInfo.cpuContext.Esp : nullptr;
    #elif defined(OVR_OS_MAC) && (OVR_PTR_SIZE == 8)
      void* pStackCurrent = (threadSysId == exceptionInfo.threadSysId) ? (void*)exceptionInfo.cpuContext.threadState.uts.ts64.__rsp : nullptr;
    #elif defined(OVR_OS_MAC)
      void* pStackCurrent = (threadSysId == exceptionInfo.threadSysId) ? (void*)exceptionInfo.cpuContext.threadState.uts.ts32.__esp : nullptr;
    #elif defined(OVR_OS_LINUX)
      void* pStackCurrent = nullptr; // To do.
    #endif

    OVR::GetThreadStackBounds(pStackBase, pStackLimit, threadHandle);

    OVR::Thread::GetThreadName(threadName, OVR_ARRAY_COUNT(threadName), threadName);
    SprintfThreadHandle(threadHandleStr,  OVR_ARRAY_COUNT(threadHandleStr), threadHandle);
    SprintfThreadSysId(threadSysIdStr, OVR_ARRAY_COUNT(threadSysIdStr), threadSysId);
    SprintfAddress(stackBaseStr, OVR_ARRAY_COUNT(stackBaseStr), pStackBase);
    SprintfAddress(stackLimitStr, OVR_ARRAY_COUNT(stackLimitStr), pStackLimit);
    SprintfAddress(stackCurrentStr, OVR_ARRAY_COUNT(stackCurrentStr), pStackCurrent);

    if(threadName[0])
        WriteReportLineF("Thread \"%s\" handle: %s, id: %s, stack base: %s, stack limit: %s, stack current: %s, %s\n", threadName, threadHandleStr, threadSysIdStr, stackBaseStr, stackLimitStr, stackCurrentStr, additionalInfo ? additionalInfo : "");
    else
        WriteReportLineF("Thread handle: %s, id: %s, stack base: %s, stack limit: %s, stack current: %s, %s\n", threadHandleStr, threadSysIdStr, stackBaseStr, stackLimitStr, stackCurrentStr, additionalInfo ? additionalInfo : "");

    // Print the backtrace info
    void*       addressArray[64];
    size_t      addressCount = symbolLookup.GetBacktraceFromThreadSysId(addressArray, OVR_ARRAY_COUNT(addressArray), 0, threadSysId);
    SymbolInfo  symbolInfo;
    const char* pModuleName;
    size_t      backtraceSkipCount = 0;

    if(isExceptionThread)
    {
        // If this thread is the exception thread, skip some frames.
        #if defined(OVR_OS_MS)
            size_t i, iEnd = MIN(16, addressCount);

            for(i = 0; i < iEnd; i++)
            {
                symbolLookup.LookupSymbol((uint64_t)addressArray[i], symbolInfo);
                if(strstr(symbolInfo.function, "UserExceptionDispatcher") != nullptr)
                    break;
            }

            if(i < iEnd) // If found...
                backtraceSkipCount = i;
            else if(addressCount >= 9)      // Else default to 9, which is coincidentally what works.
                backtraceSkipCount = 9;
            else
                backtraceSkipCount = 0;

            addressArray[backtraceSkipCount] = exceptionInfo.pExceptionInstructionAddress;
        #endif
    }

    if(addressCount == 0)
    {
        WriteReportLine("<Unable to read backtrace>\n\n");
    }
    else
    {
        for(size_t i = backtraceSkipCount; i < addressCount; ++i)
        {
            symbolLookup.LookupSymbol((uint64_t)addressArray[i], symbolInfo);

            if(symbolInfo.pModuleInfo && symbolInfo.pModuleInfo->name[0])
                pModuleName = symbolInfo.pModuleInfo->name;
            else
                pModuleName = "(unknown module)";

            char addressStr[24];
            SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), addressArray[i]);

            if(symbolInfo.filePath[0])
                WriteReportLineF("%-2u %-24s %s %s+%d %s:%d\n%s", (unsigned)i, pModuleName, addressStr,
                                    symbolInfo.function, symbolInfo.functionOffset, symbolInfo.filePath,
                                    symbolInfo.fileLineNumber, (i + 1) == addressCount ? "\n" : "");
            else
                WriteReportLineF("%-2u %-24s %s %s+%d\n%s", (unsigned)i, pModuleName, addressStr,
                                    symbolInfo.function, symbolInfo.functionOffset, (i + 1) == addressCount ? "\n" : ""); // If this is the last line, append another \n.
        }
    }
}


void ExceptionHandler::WriteReport()
{
    // It's important that we don't allocate any memory here if we can help it.
    using namespace OVR;

    if(strstr(reportFilePath, "%s")) // If the user-specified file path includes a date/time component...
    {
        char dateTimeBuffer[64];
        FormatDateTime(dateTimeBuffer, OVR_ARRAY_COUNT(dateTimeBuffer), exceptionInfo.timeVal, true, true, false, true);
        OVR_snprintf(reportFilePathActual, OVR_ARRAY_COUNT(reportFilePathActual), reportFilePath, dateTimeBuffer);
    }
    else
    {
        OVR_strlcpy(reportFilePathActual, reportFilePath, OVR_ARRAY_COUNT(reportFilePathActual));
    }

    file = fopen(reportFilePathActual, "w");
    OVR_ASSERT(file != nullptr);
    if(!file)
        return;

    SymbolLookup::Initialize();

    {
        // Exception information
        WriteReportLine("Exception Info\n");

        WriteReportLineF("Exception report file: %s\n", reportFilePathActual);

        #if defined(OVR_OS_MS)
            if(miniDumpFilePath[0])
                WriteReportLineF("Exception minidump file: %s\n", minidumpFilePathActual);
        #endif

        char dateTimeBuffer[64];
        FormatDateTime(dateTimeBuffer, OVR_ARRAY_COUNT(dateTimeBuffer), exceptionInfo.timeVal, true, true, false, false);
        WriteReportLineF("Time (GMT): %s\n", dateTimeBuffer);

        FormatDateTime(dateTimeBuffer, OVR_ARRAY_COUNT(scratchBuffer), exceptionInfo.timeVal, true, true, true, false);
        WriteReportLineF("Time (local): %s\n", dateTimeBuffer);
        WriteReportLineF("Thread name: %s\n", exceptionInfo.threadName[0] ? exceptionInfo.threadName : "(not available)"); // It's never possible on Windows to get thread names, as they are stored in the debugger at runtime.

        SprintfThreadHandle(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), exceptionInfo.threadHandle);
        OVR_strlcat(scratchBuffer, "\n", OVR_ARRAY_COUNT(scratchBuffer));
        WriteReportLine("Thread handle: ");
        WriteReportLine(scratchBuffer);

        SprintfThreadSysId(scratchBuffer, OVR_ARRAY_COUNT(scratchBuffer), exceptionInfo.threadSysId);
        OVR_strlcat(scratchBuffer, "\n", OVR_ARRAY_COUNT(scratchBuffer));
        WriteReportLine("Thread sys id: ");
        WriteReportLine(scratchBuffer);

        char addressStr[24];
        SprintfAddress(addressStr, OVR_ARRAY_COUNT(addressStr), exceptionInfo.pExceptionInstructionAddress);
        WriteReportLineF("Exception instruction address: %s (see callstack below)\n", addressStr);
        WriteReportLineF("Exception description: %s\n", exceptionInfo.exceptionDescription);

        if (symbolLookup.LookupSymbol((uint64_t)exceptionInfo.pExceptionInstructionAddress, exceptionInfo.symbolInfo))
        {
            if(exceptionInfo.symbolInfo.filePath[0])
                WriteReportLineF("Exception location: %s (%d)\n", exceptionInfo.symbolInfo.filePath, exceptionInfo.symbolInfo.fileLineNumber);
            else
                WriteReportLineF("Exception location: %s (%d)\n", exceptionInfo.symbolInfo.function, exceptionInfo.symbolInfo.functionOffset);
        }

        // To consider: print exceptionInfo.cpuContext registers
    }

    #if 0 // Disabled while we move this to the Util module or some other location.
    /*
    // OVR information
    WriteReportLine("\nOVR Info\n");
    WriteReportLineF("OVR time: %f\n", ovr_GetTimeInSeconds());
    WriteReportLineF("OVR version: %s\n", ovr_GetVersionString());

    // OVR util information
    // The following would be useful to use if they didn't allocate memory, which we can't do.
    // To do: see if we can have versions of the functions below which don't allocate memory
    // or allocate it safely (e.g. use an alternative heap).
    // String OVR::GetDisplayDriverVersion();
    // String OVR::GetCameraDriverVersion();

    // OVR HMD information
    WriteReportLine("\nOVR HMD Info\n");

    // XXX rewrite this to use EnumerateHMDStateList() with a callback...
    const OVR::List<OVR::CAPI::HMDState>& hmdStateList = OVR::CAPI::HMDState::GetHMDStateList();
    const OVR::CAPI::HMDState* pHMDState = hmdStateList.GetFirst();

    if(hmdStateList.IsNull(pHMDState))
    {
        WriteReportLine("No HMDs found.\n");
    }

    while(!hmdStateList.IsNull(pHMDState))
    {
        if(pHMDState->pProfile)
        {
            const char* user = pHMDState->pProfile->GetValue(OVR_KEY_USER);

            if(user)
                WriteReportLineF("Profile user: %s\n", reportPrivacyEnabled ? "<disabled by report privacy settings>" : user);
            else
                WriteReportLine("Null profile user\n");

            float NeckEyeDistance[2];
            float EyeToNoseDistance[2];
            float MaxEyeToPlateDist[2];
            pHMDState->pProfile->GetFloatValues(OVR_KEY_NECK_TO_EYE_DISTANCE, NeckEyeDistance, 2);
            pHMDState->pProfile->GetFloatValues(OVR_KEY_EYE_TO_NOSE_DISTANCE, EyeToNoseDistance, 2);
            pHMDState->pProfile->GetFloatValues(OVR_KEY_MAX_EYE_TO_PLATE_DISTANCE, MaxEyeToPlateDist, 2);

            WriteReportLineF("Player height: %f, eye height: %f, IPD: %f, Neck eye distance: %f,%f, eye relief dial: %d, eye to nose distance: %f,%f, max eye to plate distance: %f,%f, custom eye render: %s\n",
                        pHMDState->pProfile->GetFloatValue(OVR_KEY_PLAYER_HEIGHT, 0.f),
                        pHMDState->pProfile->GetFloatValue(OVR_KEY_EYE_HEIGHT, 0.f),
                        pHMDState->pProfile->GetFloatValue(OVR_KEY_IPD, 0.f),
                        NeckEyeDistance[0], NeckEyeDistance[1],
                        pHMDState->pProfile->GetIntValue(OVR_KEY_EYE_RELIEF_DIAL, 0),
                        EyeToNoseDistance[0], EyeToNoseDistance[1],
                        MaxEyeToPlateDist[0], MaxEyeToPlateDist[1],
                        pHMDState->pProfile->GetBoolValue(OVR_KEY_CUSTOM_EYE_RENDER, false) ? "yes" : "no");

            // Not currently used:
            // OVR_KEY_NAME
            // OVR_KEY_GENDER
            // OVR_KEY_EYE_CUP
            // OVR_KEY_CAMERA_POSITION
        }
        else
        {
            WriteReportLine("Null HMD profile\n");
        }

        if(pHMDState->pHmdDesc) // This should usually be true.
        {
            WriteReportLineF("HMD %d: Type: %u ProductName: %s, Manufacturer: %s VendorId: %d, ProductId: %d, SerialNumber: %s, FirmwareMajor: %d, FirmwareMinor: %d, Resolution: %dx%d, DisplayDeviceName: %s, DisplayId: %d\n",
                            0, (unsigned)pHMDState->pHmdDesc->Type, pHMDState->pHmdDesc->ProductName, pHMDState->pHmdDesc->Manufacturer, pHMDState->pHmdDesc->VendorId,
                            pHMDState->pHmdDesc->ProductId, pHMDState->pHmdDesc->SerialNumber, pHMDState->pHmdDesc->FirmwareMajor, pHMDState->pHmdDesc->FirmwareMinor,
                            pHMDState->pHmdDesc->Resolution.w, pHMDState->pHmdDesc->Resolution.h, pHMDState->pHmdDesc->DisplayDeviceName, pHMDState->pHmdDesc->DisplayId);

            // HSW display state
            ovrHSWDisplayState hswDS;
            ovrHmd_GetHSWDisplayState(pHMDState->pHmdDesc, &hswDS);
            WriteReportLineF("HSW displayed for hmd: %s\n", hswDS.Displayed ? "yes" : "no");
        }

        char threadIdStr[24];
        SprintfAddress(threadIdStr, OVR_ARRAY_COUNT(threadIdStr), pHMDState->BeginFrameThreadId);

        WriteReportLineF("Hmd Caps: %x, Hmd Service Caps: %x, Latency test active: %s, Last frame time: %f, Last get frame time: %f, Rendering configred: %s, Begin frame called: %s, Begin frame thread id: %s\n",
                    pHMDState->EnabledHmdCaps, pHMDState->EnabledServiceHmdCaps, pHMDState->LatencyTestActive ? "yes" : "no", pHMDState->LastFrameTimeSeconds, pHMDState->LastGetFrameTimeSeconds, pHMDState->RenderingConfigured ? "yes" : "no",
                    pHMDState->BeginFrameCalled ? "yes" : "no", threadIdStr);

        if(pHMDState->pLastError)
        {
            WriteReportLineF("OVR last error for hmd: %s\n", pHMDState->pLastError);
        }

        pHMDState = hmdStateList.GetNext(pHMDState);
    }
    */
    #endif // #if 0

    #if defined(OVR_OS_WIN32)
        {
            WriteReportLine("\nApp Info\n");

            // Print the app path.
            char appPath[OVR_MAX_PATH];
            GetCurrentProcessFilePath(appPath, OVR_ARRAY_COUNT(appPath));
            WriteReportLineF("Process path: %s\n", appPath);

            #if (OVR_PTR_SIZE == 4)
                WriteReportLine("App format: 32 bit\n");
            #else
                WriteReportLine("App format: 64 bit\n");
            #endif

            // Print the app version
            wchar_t pathW[OVR_MAX_PATH] = {};
            GetModuleFileNameW(0, pathW, (DWORD)OVR_ARRAY_COUNT(pathW));
            DWORD dwUnused;
            DWORD dwSize = GetFileVersionInfoSizeW(pathW, &dwUnused);
            scratchBuffer[0] = 0;

            if(dwSize > 0)
            {
                void* const pVersionData = SafeMMapAlloc(dwSize);

                if(pVersionData)
                {
                    if(GetFileVersionInfoW(pathW, 0, dwSize, pVersionData))
                    {
                        VS_FIXEDFILEINFO* pFFI;
                        UINT size;

                        if(VerQueryValueA(pVersionData, "\\", (void**)&pFFI, &size))
                        {
                            WriteReportLineF("App version: %u.%u.%u.%u\n",
                                            HIWORD(pFFI->dwFileVersionMS), LOWORD(pFFI->dwFileVersionMS),
                                            HIWORD(pFFI->dwFileVersionLS), LOWORD(pFFI->dwFileVersionLS));
                        }
                    }

                    SafeMMapFree(pVersionData, dwSize);
                }
            }

            if(!scratchBuffer[0]) // If version info couldn't be found or read...
                WriteReportLine("App version info not present\n");
        }

        {
            WriteReportLine("\nSystem Info\n");

            OSVERSIONINFOEXW vi;
            memset(&vi, 0, sizeof(vi));
            vi.dwOSVersionInfoSize = sizeof(vi);
            GetVersionExW((LPOSVERSIONINFOW)&vi); // Cast to the older type.

            char osVersionName[256];
            GetOSVersionName(osVersionName, OVR_ARRAY_COUNT(osVersionName));
            WriteReportLineF("OS name: %s, version: %u.%u build %u, %s, platform id: %u, service pack: %ls\n",
                            osVersionName, vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber, Is64BitOS() ? "64 bit" : "32 bit",
                            vi.dwPlatformId, vi.szCSDVersion[0] ? vi.szCSDVersion : L"<none>");

            WriteReportLineF("Debugger present: %s\n", OVRIsDebuggerPresent() ? "yes" : "no");

            // System info
            SYSTEM_INFO systemInfo;
            GetNativeSystemInfo(&systemInfo);

            WriteReportLineF("Processor count: %u\n", systemInfo.dwNumberOfProcessors);

            // Windows Vista and later:
            // BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, PDWORD ReturnLength);

            if(systemInfo.wProcessorArchitecture == 0)
                WriteReportLineF("Processor type: x86\n");
            else if(systemInfo.wProcessorArchitecture == 9)
                WriteReportLineF("Processor type: x86-64\n");
            else if(systemInfo.wProcessorArchitecture == 10)
                WriteReportLineF("Processor type: x86 on x86-64\n");

            WriteReportLineF("Processor level: %u\n", systemInfo.wProcessorLevel);
            WriteReportLineF("Processor revision: %u\n", systemInfo.wProcessorRevision);

            // Memory information
            MEMORYSTATUSEX memoryStatusEx;
            memset(&memoryStatusEx, 0, sizeof(memoryStatusEx));
            memoryStatusEx.dwLength = sizeof(memoryStatusEx);
            GlobalMemoryStatusEx(&memoryStatusEx);

            WriteReportLineF("Memory load: %d%%\n", memoryStatusEx.dwMemoryLoad);
            WriteReportLineF("Total physical memory: %I64d MiB\n", memoryStatusEx.ullTotalPhys / (1024 * 1024)); // Or are Mebibytes equal to (1024 * 1000)
            WriteReportLineF("Available physical memory: %I64d MiB\n", memoryStatusEx.ullAvailPhys / (1024 * 1024));
            WriteReportLineF("Total page file memory: %I64d MiB\n", memoryStatusEx.ullTotalPageFile / (1024 * 1024));
            WriteReportLineF("Available page file memory: %I64d MiB\n", memoryStatusEx.ullAvailPageFile / (1024 * 1024));
            WriteReportLineF("Total virtual memory: %I64d MiB\n", memoryStatusEx.ullTotalVirtual / (1024 * 1024));
            WriteReportLineF("Free virtual memory: %I64d MiB\n", memoryStatusEx.ullAvailVirtual / (1024 * 1024));

            DISPLAY_DEVICEW dd;
            memset(&dd, 0, sizeof(DISPLAY_DEVICE));
            dd.cb = sizeof(DISPLAY_DEVICE);

            for(int i = 0; EnumDisplayDevicesW(nullptr, (DWORD)i, &dd, EDD_GET_DEVICE_INTERFACE_NAME); ++i)
            {
                WriteReportLineF("Display Device %d name: %ls, context: %ls, primary: %s, mirroring: %s\n",
                             i, dd.DeviceName, dd.DeviceString, (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) ? "yes" : "no", (dd.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) ? "yes" : "no");
            }
        }

        // Print video card information
        // http://msdn.microsoft.com/en-us/library/aa394512%28v=vs.85%29.aspx
        {
            IWbemLocator*         pIWbemLocator = nullptr;
            BSTR                  bstrServer = nullptr;
            IWbemServices*        pIWbemServices = nullptr;
            BSTR                  bstrWQL  = nullptr;
            BSTR                  bstrPath = nullptr;
            IEnumWbemClassObject* pEnum = nullptr;

            CoInitializeEx(nullptr, COINIT_MULTITHREADED);

            HRESULT hr = CoCreateInstance(__uuidof(WbemLocator), nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID*)&pIWbemLocator);
            if(FAILED(hr))
                goto End;

            bstrServer = SysAllocString(L"\\\\.\\root\\cimv2");
            hr = pIWbemLocator->ConnectServer(bstrServer, nullptr, nullptr, 0L, 0L, nullptr, nullptr, &pIWbemServices);
            if(FAILED(hr))
                goto End;

            hr = CoSetProxyBlanket(pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr, RPC_C_AUTHN_LEVEL_CALL,
                                    RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_DEFAULT);
            if(FAILED(hr))
                goto End;

            bstrWQL  = SysAllocString(L"WQL");
            bstrPath = SysAllocString(L"select * from Win32_VideoController");
            hr = pIWbemServices->ExecQuery(bstrWQL, bstrPath, WBEM_FLAG_FORWARD_ONLY, nullptr, &pEnum);
            if(FAILED(hr))
                goto End;

            ULONG uReturned;
            IWbemClassObject* pObj = nullptr;
            hr = pEnum->Next(WBEM_INFINITE, 1, &pObj, &uReturned);
            if(FAILED(hr))
                goto End;

            WriteReportLine("\nDisplay adapter list\n");

            for(unsigned i = 0; SUCCEEDED(hr) && uReturned; i++)
            {
                char    sString[256];
                VARIANT var;

                if(i > 0)
                    WriteReportLine("\n");

                WriteReportLineF("Info for display adapter %u\n", i);

                hr = pObj->Get(L"Name", 0, &var, nullptr, nullptr);
                if(SUCCEEDED(hr))
                {
                    WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
                    WriteReportLineF("Display Adapter Name: %s\n", sString);
                }

                hr = pObj->Get(L"AdapterRAM", 0, &var, nullptr, nullptr);
                if(SUCCEEDED(hr))
                {
                    WriteReportLineF("Display Adapter RAM: %u %s\n",
                            ((uint32_t)var.lVal > (1024*1024*1024) ? (uint32_t)var.lVal/(1024*1024*1024) : (uint32_t)var.lVal/(1024*1024)), ((uint32_t)var.lVal > (1024*1024*1024) ? "GiB" : "MiB"));
                }

                hr = pObj->Get(L"DeviceID", 0, &var, nullptr, nullptr);
                if(SUCCEEDED(hr))
                {
                    WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
                    WriteReportLineF("Display Adapter DeviceID: %s\n", sString);
                }

                hr = pObj->Get(L"DriverVersion", 0, &var, nullptr, nullptr);
                if(SUCCEEDED(hr))
                {
                    WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
                    WriteReportLineF("Display Adapter DriverVersion: %s\n", sString);
                }

                hr = pObj->Get(L"DriverDate", 0, &var, nullptr, nullptr);
                if(SUCCEEDED(hr))
                {
                    // http://technet.microsoft.com/en-us/library/ee156576.aspx
                    wchar_t year[5] = { var.bstrVal[0], var.bstrVal[1], var.bstrVal[2], var.bstrVal[3], 0 };
                    wchar_t month[3] = { var.bstrVal[4], var.bstrVal[5], 0 };
                    wchar_t monthDay[3] = { var.bstrVal[6], var.bstrVal[7], 0 };

                    WriteReportLineF("Display Adapter DriverDate (US format): %ls/%ls/%ls\n", month, monthDay, year);
                }

                // VideoProcessor
                hr = pObj->Get(L"VideoProcessor", 0, &var, nullptr, nullptr);
                if(SUCCEEDED(hr))
                {
                    WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
                    WriteReportLineF("Display Adapter VideoProcessor %s\n", sString);
                }

                hr = pObj->Get(L"VideoModeDescription", 0, &var, nullptr, nullptr);
                if(SUCCEEDED(hr))
                {
                    WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sString, sizeof(sString), nullptr, nullptr);
                    WriteReportLineF("Display Adapter VideoModeDescription: %s\n", sString);
                }

                pObj->Release();

                hr = pEnum->Next(WBEM_INFINITE, 1, &pObj, &uReturned);
            }

            End:
            if(pEnum)
                pEnum->Release();
            if(bstrPath)
                SysFreeString(bstrPath);
            if(bstrWQL)
                SysFreeString(bstrWQL);
            if(pIWbemServices)
                pIWbemServices->Release();
            if(bstrServer)
                SysFreeString(bstrServer);
            if(pIWbemLocator)
                pIWbemLocator->Release();

            CoUninitialize();
        }

        {
            // Print a list of threads.
            DWORD  currentProcessId = GetCurrentProcessId();
            HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, currentProcessId); // ICreateToolhelp32Snapshot actually ignores currentProcessId.

            if(hThreadSnap != INVALID_HANDLE_VALUE)
            {
                THREADENTRY32 te32;
                te32.dwSize = sizeof(THREADENTRY32);

                if(Thread32First(hThreadSnap, &te32))
                {
                    WriteReportLine("\nThread list\n");

                    do {
                        if(te32.th32OwnerProcessID == currentProcessId)
                        {
                            HANDLE hThread = ConvertThreadSysIdToThreadHandle(te32.th32ThreadID);

                            if(hThread)
                            {
                                char buffer[96]; // Can't use scratchBuffer, because it's used by WriteThreadCallstack.
                                OVR_snprintf(buffer, OVR_ARRAY_COUNT(buffer), "base priority: %ld, delta priority: %ld", te32.tpBasePri, te32.tpDeltaPri);

                                bool threadIsExceptionThread = (te32.th32ThreadID == (DWORD)exceptionInfo.threadSysId);
                                if(threadIsExceptionThread)
                                    OVR_strlcat(buffer, ", exception thread", OVR_ARRAY_COUNT(buffer));

                                WriteThreadCallstack(hThread, (OVR::ThreadSysId)te32.th32ThreadID, buffer);
                                FreeThreadHandle(hThread);
                            }
                        }
                    } while(Thread32Next(hThreadSnap, &te32));
                }

                CloseHandle(hThreadSnap);
            }
        }

        {
            // Print a list of the current modules within this process.
            // DbgHelp.dll also provides a EnumerateLoadedModules64 function.
            // To do: Convert the code below to use the GetModuleInfoArray function which we now have.
            HMODULE hModule = LoadLibraryW(L"psapi.dll");

            if(hModule)
            {
                typedef BOOL  (WINAPI * ENUMPROCESSMODULES)  (HANDLE hProcess, HMODULE* phModule, DWORD cb, LPDWORD lpcbNeeded);
                typedef DWORD (WINAPI * GETMODULEBASENAME)   (HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize);
                typedef DWORD (WINAPI * GETMODULEFILENAMEEX) (HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize);
                typedef BOOL  (WINAPI * GETMODULEINFORMATION)(HANDLE hProcess, HMODULE hModule, MODULEINFO* pmi, DWORD nSize);

                ENUMPROCESSMODULES   pEnumProcessModules   = (ENUMPROCESSMODULES)  (uintptr_t)GetProcAddress(hModule, "EnumProcessModules");
                GETMODULEBASENAME    pGetModuleBaseName    = (GETMODULEBASENAME)   (uintptr_t)GetProcAddress(hModule, "GetModuleBaseNameW");
                GETMODULEFILENAMEEX  pGetModuleFileNameEx  = (GETMODULEFILENAMEEX) (uintptr_t)GetProcAddress(hModule, "GetModuleFileNameExW");
                GETMODULEINFORMATION pGetModuleInformation = (GETMODULEINFORMATION)(uintptr_t)GetProcAddress(hModule, "GetModuleInformation");

                HANDLE  hProcess = GetCurrentProcess();
                HMODULE hModuleArray[200];
                DWORD   cbNeeded;

                if(pEnumProcessModules(hProcess, hModuleArray, sizeof(hModuleArray), &cbNeeded))
                {
                    size_t actualModuleCount = (cbNeeded / sizeof(HMODULE));

                    if(actualModuleCount > OVR_ARRAY_COUNT(hModuleArray))  //If hModuleArray's capacity was not enough...
                        actualModuleCount = OVR_ARRAY_COUNT(hModuleArray);

                    // Print a header
                    WriteReportLine("\nModule list\n");

                    #if (OVR_PTR_SIZE == 4)
                        WriteReportLine("Base        Size       Entrypoint Name                     Path\n");
                    #else
                        WriteReportLine("Base                Size               Entrypoint         Name                     Path\n");
                    #endif

                    // And go through the list one by one
                    for(size_t i = 0; i < actualModuleCount; i++)
                    {
                        MODULEINFO mi;
                        size_t     length;

                        if(!pGetModuleInformation(hProcess, hModuleArray[i], &mi, sizeof(mi)))
                        {
                            mi.EntryPoint  = nullptr;
                            mi.lpBaseOfDll = nullptr;
                            mi.SizeOfImage = 0;
                        }

                        // Write the base name.
                        wchar_t name[OVR_MAX_PATH + 3];
                        name[0] = '"';
                        if(pGetModuleBaseName(hProcess, hModuleArray[i], name + 1, OVR_MAX_PATH))
                            length = wcslen(name);
                        else
                        {
                            wcscpy(name + 1, L"(unknown)");
                            length = 10;
                        }

                        name[length] = '"';
                        name[length + 1] = '\0';

                        // Write the path
                        wchar_t path[OVR_MAX_PATH + 3];
                        path[0] = '"';
                        if(pGetModuleFileNameEx(hProcess, hModuleArray[i], path + 1, OVR_MAX_PATH))
                            length = wcslen(path);
                        else
                        {
                            wcscpy(path + 1, L"(unknown)");
                            length = 10;
                        }
                        path[length]     = '"';
                        path[length + 1] = '\0';

                        #if (OVR_PTR_SIZE == 4)
                            WriteReportLineF("0x%08x, 0x%08x 0x%08x %-24ls %ls\n", (uint32_t)mi.lpBaseOfDll, (uint32_t)mi.SizeOfImage, (uint32_t)mi.EntryPoint, name, path);
                        #else
                            WriteReportLineF("0x%016I64x 0x%016I64x 0x%016I64x %-24ls %ls\n", (uint64_t)mi.lpBaseOfDll, (uint64_t)mi.SizeOfImage, (uint64_t)mi.EntryPoint, name, path);
                        #endif
                    }
                }
            }
        }

        {
            // Print a list of processes.
            // DbgHelp.dll provides a SymEnumProcesses function, but it's available with DbgHelp.dll v6.2 which doesn't ship with Windows until Windows 8.
            WriteReportLine("\nProcess list\n");

            if(reportPrivacyEnabled)
                WriteReportLine("Disabled by report privacy settings\n");
            else
            {
                HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

                if(hProcessSnapshot != INVALID_HANDLE_VALUE)
                {
                    PROCESSENTRY32W pe32;
                    memset(&pe32, 0, sizeof(pe32));
                    pe32.dwSize = sizeof(pe32);

                    if(Process32FirstW(hProcessSnapshot, &pe32))
                    {
                        WriteReportLine("Process Id File\n");

                        do {
                            // Try to get the full path to the process, as pe32.szExeFile holds only the process file name.
                            // This will typically fail with a privilege error unless this process has debug privileges: http://support.microsoft.com/kb/131065/en-us
                            wchar_t filePathW[OVR_MAX_PATH];
                            const wchar_t* pFilePathW = pe32.szExeFile;
                            HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe32.th32ProcessID); // With Windows Vista+ we can use PROCESS_QUERY_LIMITED_INFORMATION.
                            if(hProcess)
                            {
                                if(GetProcessImageFileNameW(hProcess, filePathW, (DWORD)OVR_ARRAY_COUNT(filePathW)))
                                    pFilePathW = filePathW;
                            }

                            WriteReportLineF("0x%08x %ls\n", pe32.th32ProcessID, pFilePathW);
                        } while(Process32NextW(hProcessSnapshot, &pe32));
                    }

                    CloseHandle(hProcessSnapshot);
                }
                else
                {
                    WriteReportLine("Unable to read process list\n");
                }
            }
        }

    #elif defined(OVR_OS_APPLE)

        WriteReportLine("\nApp Info\n");

        // App path
        const pid_t processId = getpid();
        WriteReportLineF("Process id: ", "%lld (0x%llx)\n", (int64_t)processId, (int64_t)processId);

        char appPath[PATH_MAX];
        GetCurrentProcessFilePath(appPath, OVR_ARRAY_COUNT(appPath));
        WriteReportLineF("Process path: %s\n", appPath);

        #if (OVR_PTR_SIZE == 4)
            WriteReportLine("App format: 32 bit\n");
        #else
            WriteReportLine("App format: 64 bit\n");
        #endif

        // App version
        // To do.

        // System Info
        WriteReportLine("\nSystem Info\n");

        char osVersionName[256];
        GetOSVersionName(osVersionName, OVR_ARRAY_COUNT(osVersionName));
        WriteReportLineF("OS name: %s, %s\n", osVersionName, Is64BitOS() ? "64 bit" : "32 bit");

        int     name[2];
        int     intValue;
        size_t  length;
        char    tempBuffer[256];

        name[0] = CTL_KERN;
        name[1] = KERN_OSTYPE;
        length = sizeof(tempBuffer);
        tempBuffer[0] = 0;
        if(sysctl(name, 2, tempBuffer, &length, nullptr, 0) == 0)
        {
            WriteReportLineF("KERN_OSTYPE: %s\n", tempBuffer);
        }

        name[0] = CTL_KERN;
        name[1] = KERN_OSREV;
        length = sizeof(intValue);
        intValue = 0;
        if(sysctl(name, 2, &intValue, &length, nullptr, 0) == 0)
        {
            WriteReportLineF("KERN_OSREV: %d\n", intValue);
        }

        name[0] = CTL_KERN;
        name[1] = KERN_OSRELEASE;
        length = sizeof(tempBuffer);
        tempBuffer[0] = 0;
        if(sysctl(name, 2, tempBuffer, &length, nullptr, 0) == 0)
            WriteReportLineF("KERN_OSRELEASE: %s\n", tempBuffer);

        name[0] = CTL_HW;
        name[1] = HW_MACHINE;
        length = sizeof(tempBuffer);
        tempBuffer[0] = 0;
        if(sysctl(name, 2, tempBuffer, &length, nullptr, 0) == 0)
            WriteReportLineF("HW_MACHINE: %s\n", tempBuffer);

        name[0] = CTL_HW;
        name[1] = HW_MODEL;
        length = sizeof(tempBuffer);
        tempBuffer[0] = 0;
        if(sysctl(name, 2, tempBuffer, &length, nullptr, 0) == 0)
            WriteReportLineF("sHW_MODEL: %s\n", tempBuffer);

        name[0] = CTL_HW;
        name[1] = HW_NCPU;
        length = sizeof(intValue);
        intValue = 0;
        if(sysctl(name, 2, &intValue, &length, nullptr, 0) == 0)
            WriteReportLineF("HW_NCPU: %d\n", intValue);

        length = sizeof(tempBuffer);
        tempBuffer[0] = 0;
        if(sysctlbyname("machdep.cpu.brand_string", &tempBuffer, &length, nullptr, 0) == 0)
            WriteReportLineF("machdep.cpu.brand_string: %s\n", tempBuffer);

        length = sizeof(tempBuffer);
        tempBuffer[0] = 0;
        if(sysctlbyname("hw.acpi.thermal.tz0.temperature", &tempBuffer, &length, nullptr, 0) == 0)
            WriteReportLineF("hw.acpi.thermal.tz0.temperature: %s\n", tempBuffer);

        host_basic_info_data_t hostinfo;
        mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
        kern_return_t          kr = host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostinfo, &count);

        if(kr == KERN_SUCCESS)
        {
            const uint64_t memoryMib = (uint64_t)hostinfo.max_mem / (1024 * 1024);
            WriteReportLineF("System memory: %lld Mib (%.1f Gib)\n", memoryMib, (double)memoryMib / 1024);
        }

        // Video card info
        // To do.

        // Thread list
        mach_port_t             taskSelf   = mach_task_self();
        thread_act_port_array_t threadArray;
        mach_msg_type_number_t  threadCount;

        kern_return_t result = task_threads(taskSelf, &threadArray, &threadCount);

        if(result == KERN_SUCCESS)
        {
            WriteReportLine("\nThread list\n");

            for(mach_msg_type_number_t i = 0; i < threadCount; i++)
            {
                union TBIUnion{
                    natural_t words[THREAD_INFO_MAX];
                    thread_basic_info tbi;
                };

                TBIUnion    tbiUnion;
                mach_port_t thread = threadArray[i];
                pthread_t   pthread = pthread_from_mach_thread_np(thread); // We assume the thread was created through pthreads.

                char threadState[32] = "unknown";
                mach_msg_type_number_t threadInfoCount = THREAD_INFO_MAX;
                result = thread_info(thread, THREAD_BASIC_INFO, (thread_info_t)&tbiUnion, &threadInfoCount);

                if(result == KERN_SUCCESS)
                {
                    const char* state;

                    switch (tbiUnion.tbi.run_state)
                    {
                        case TH_STATE_HALTED:          state = "halted";          break;
                        case TH_STATE_RUNNING:         state = "running";         break;
                        case TH_STATE_STOPPED:         state = "stopped";         break;
                        case TH_STATE_UNINTERRUPTIBLE: state = "uninterruptible"; break;
                        case TH_STATE_WAITING:         state = "waiting";         break;
                        default:                       state = "<unknown>";       break;
                    }

                    OVR_snprintf(threadState, OVR_ARRAY_COUNT(threadState), "%s", state);
                    if(tbiUnion.tbi.flags & TH_FLAGS_IDLE)
                        OVR_strlcat(threadState, ", idle", sizeof(threadState));
                    if(tbiUnion.tbi.flags & TH_FLAGS_SWAPPED)
                        OVR_strlcat(threadState, ", swapped", sizeof(threadState));
                }

                thread_identifier_info threadIdentifierInfo;
                memset(&threadIdentifierInfo, 0, sizeof(threadIdentifierInfo));

                mach_msg_type_number_t threadIdentifierInfoCount = THREAD_IDENTIFIER_INFO_COUNT;
                thread_info(thread, THREAD_IDENTIFIER_INFO, (thread_info_t)&threadIdentifierInfo, &threadIdentifierInfoCount);

                proc_threadinfo procThreadInfo;
                memset(&procThreadInfo, 0, sizeof(procThreadInfo));
                result = proc_pidinfo(processId, PROC_PIDTHREADINFO, threadIdentifierInfo.thread_handle, &procThreadInfo, sizeof(procThreadInfo));
                OVR_UNUSED(result);

                char buffer[256]; // Can't use scratchBuffer, because it's used by WriteThreadCallstack.
                OVR_snprintf(buffer, OVR_ARRAY_COUNT(buffer), "state: %s, suspend count: %d, kernel priority: %d", threadState, (int)tbiUnion.tbi.suspend_count, (int)procThreadInfo.pth_curpri);

                bool threadIsExceptionThread = (thread == exceptionInfo.threadSysId);
                if(threadIsExceptionThread)
                    OVR_strlcat(buffer, ", exception thread", OVR_ARRAY_COUNT(buffer));

                WriteThreadCallstack(pthread, thread, buffer);
            }

            vm_deallocate(taskSelf, (vm_address_t)threadArray, threadCount * sizeof(thread_act_t));
        }


        WriteReportLine("\nModule list\n");

        const size_t mifCapacity  = 256;
        const size_t mifAllocSize = mifCapacity * sizeof(ModuleInfo);
        ModuleInfo* moduleInfoArray = (ModuleInfo*)SafeMMapAlloc(mifAllocSize);

        if(moduleInfoArray)
        {
            #if (OVR_PTR_SIZE == 4)
                WriteReportLine("Base        Size       Name                     Path\n");
            #else
                WriteReportLine("Base                Size               Name                     Path\n");
            #endif

            size_t moduleCount = symbolLookup.GetModuleInfoArray(moduleInfoArray, mifCapacity);
            if(moduleCount > mifCapacity)
                moduleCount = mifCapacity;

            for(size_t i = 0; i < moduleCount; i++)
            {
                const ModuleInfo& mi = moduleInfoArray[i];

                #if (OVR_PTR_SIZE == 4)
                    WriteReportLineF("0x%08x, 0x%08x %-24s %s\n", (uint32_t)mi.baseAddress, (uint32_t)mi.size, mi.name, mi.filePath);
                #else
                    WriteReportLineF("0x%016llx 0x%016llx %-24s %s\n", (uint64_t)mi.baseAddress, (uint64_t)mi.size, mi.name, mi.filePath);
                #endif
            }

            SafeMMapFree(moduleInfoArray, mifAllocSize);
        }


        WriteReportLine("\nProcess list\n");

        if(reportPrivacyEnabled)
            WriteReportLine("Disabled by report privacy settings\n");
        else
        {
            WriteReportLine("Process Id File\n");

            pid_t pidArray[1024];
            int   processCount = proc_listpids(PROC_ALL_PIDS, 0, pidArray, sizeof(pidArray)); // Important that we use sizeof not OVR_ARRAY_COUNT.
            char  processFilePath[PATH_MAX];

            for(int i = 0; i < processCount; i++)
            {
                if(proc_pidpath(pidArray[i], processFilePath, sizeof(processFilePath)) > 0)
                    WriteReportLineF("%-10d %s\n", pidArray[i], processFilePath);
            }

            if(!processCount)
                WriteReportLine("Unable to read process list\n");
        }

    #elif defined(OVR_OS_UNIX)
         Is64BitOS();
         GetCurrentProcessFilePath(nullptr, 0);
         GetFileNameFromPath(nullptr);
         GetOSVersionName(nullptr, 0);

    #endif // OVR_OS_MS

    SymbolLookup::Shutdown();

    fclose(file);
    file = nullptr;
}


void ExceptionHandler::WriteMiniDump()
{
    if(strstr(miniDumpFilePath, "%s")) // If the user-specified file path includes a date/time component...
    {
        char dateTimeBuffer[64];
        FormatDateTime(dateTimeBuffer, OVR_ARRAY_COUNT(dateTimeBuffer), exceptionInfo.timeVal, true, true, false, true);
        OVR_snprintf(minidumpFilePathActual, OVR_ARRAY_COUNT(minidumpFilePathActual), miniDumpFilePath, dateTimeBuffer);
    }
    else
    {
        OVR_strlcpy(minidumpFilePathActual, miniDumpFilePath, OVR_ARRAY_COUNT(minidumpFilePathActual));
    }

    #if defined(OVR_OS_WIN32) || defined(OVR_OS_WIN64)
        typedef BOOL (WINAPI * MINIDUMPWRITEDUMP)(HANDLE hProcess, DWORD ProcessId, HANDLE hFile, MINIDUMP_TYPE dumpType, CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
        HMODULE hModuleDbgHelp = LoadLibraryW(L"DbgHelp.dll");

        MINIDUMPWRITEDUMP pMiniDumpWriteDump = hModuleDbgHelp ? (MINIDUMPWRITEDUMP)(void*)GetProcAddress(hModuleDbgHelp, "MiniDumpWriteDump") : nullptr;

        if(pMiniDumpWriteDump)
        {
            wchar_t miniDumpFilePathW[OVR_MAX_PATH];
            OVR::UTF8Util::DecodeString(miniDumpFilePathW, minidumpFilePathActual, -1); // Problem: DecodeString provides no way to specify the destination capacity.

            HANDLE hFile = CreateFileW(miniDumpFilePathW, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, 0);

            if(hFile != INVALID_HANDLE_VALUE)
            {
                MINIDUMP_EXCEPTION_INFORMATION minidumpExceptionInfo = { ::GetCurrentThreadId(), pExceptionPointers, TRUE };

                BOOL result = pMiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile,
                                                    (MINIDUMP_TYPE)miniDumpFlags, &minidumpExceptionInfo,
                                                    (CONST PMINIDUMP_USER_STREAM_INFORMATION)nullptr, (CONST PMINIDUMP_CALLBACK_INFORMATION)nullptr);

                OVR_ASSERT_AND_UNUSED(result, result);
                CloseHandle(hFile);
                hFile = 0;
            }
            else
            {
                OVR_ASSERT(pMiniDumpWriteDump);  // OVR_FAIL_F(("ExceptionHandler::WriteMiniDump: Failed to create minidump file at %s", minidumpFilePathActual));
            }
        }

        FreeLibrary(hModuleDbgHelp);
    #else
        // Some platforms support various forms or exception reports and core dumps which are automatically generated upon us
        // returning from our own exception handling. We might want to put something here if we are using a custom version of
        // this, such as Google Breakpad.
    #endif
}


void ExceptionHandler::SetExceptionListener(ExceptionListener* pExceptionListener, uintptr_t userValue)
{
    exceptionListener = pExceptionListener;
    exceptionListenerUserValue = userValue;
}


void ExceptionHandler::SetAppDescription(const char* pAppDescription)
{
    appDescription = pAppDescription;
}


void ExceptionHandler::SetExceptionPaths(const char* exceptionReportPath, const char* exceptionMiniDumpFilePath)
{
    char tempPath[OVR_MAX_PATH];

    if(exceptionReportPath)
    {
        if(OVR_stricmp(exceptionReportPath, "default") == 0)
        {
            GetCrashDumpDirectory(tempPath, OVR_ARRAY_COUNT(tempPath));
            OVR::OVR_strlcat(tempPath, "Exception Report (%s).txt", OVR_ARRAY_COUNT(tempPath));
            exceptionReportPath = tempPath;
        }

        OVR_strlcpy(reportFilePath, exceptionReportPath, OVR_ARRAY_COUNT(reportFilePath));
    }
    else
    {
        reportFilePath[0] = '\0';
    }

    if(exceptionMiniDumpFilePath)
    {
        if(OVR_stricmp(exceptionMiniDumpFilePath, "default") == 0)
        {
            GetCrashDumpDirectory(tempPath, OVR_ARRAY_COUNT(tempPath));
            OVR::OVR_strlcat(tempPath, "Exception Minidump (%s).mdmp", OVR_ARRAY_COUNT(tempPath));
            exceptionMiniDumpFilePath = tempPath;
        }

        OVR_strlcpy(miniDumpFilePath, exceptionMiniDumpFilePath, OVR_ARRAY_COUNT(miniDumpFilePath));
    }
    else
    {
        miniDumpFilePath[0] = '\0';
    }
}


void ExceptionHandler::SetCodeBaseDirectoryPaths(const char* codeBaseDirectoryPathArray[], size_t codeBaseDirectoryPathCount)
{
    for(size_t i = 0, iCount = OVR::Alg::Min<size_t>(codeBaseDirectoryPathCount, OVR_ARRAY_COUNT(codeBasePathArray)); i != iCount; ++i)
    {
        codeBasePathArray[i] = codeBaseDirectoryPathArray[i];
    }
}

const char* ExceptionHandler::GetExceptionUIText(const char* exceptionReportPath)
{
    char* uiText = nullptr;
    OVR::SysFile file(exceptionReportPath, SysFile::Open_Read, SysFile::Mode_ReadWrite);

    if(file.IsValid())
    {
        size_t length = (size_t)file.GetLength();
        uiText = (char*)OVR::SafeMMapAlloc(length + 1);

        if(uiText)
        {
            file.Read((uint8_t*)uiText, (int)length);
            uiText[length] = '\0';
            file.Close();

            // Currently on Mac our message box implementation is unable to display arbitrarily large amounts of text.
            // So we reduce its size to a more summary version before presenting.
            #if defined(OVR_OS_MAC)
                struct Find { static char* PreviousChar(char* p, char c){ while(*p != c) p--; return p; } }; // Assumes the given c is present prior to p.

                // Print that the full report is at <file path>
                // Exception Info section
                // Exception thread callstack.
                char  empty[]               = "";
                char* pExceptionInfoBegin   = strstr(uiText, "Exception Info") ? strstr(uiText, "Exception Info") : empty;
                char* pExceptionInfoEnd     = (pExceptionInfoBegin == empty) ? (empty + 1) : strstr(uiText, "\n\n");
                char* pExceptionThreadArea  = strstr(uiText, ", exception thread");
                char* pExceptionThreadBegin = pExceptionThreadArea ? Find::PreviousChar(pExceptionThreadArea, '\n') + 1 : empty;
                char* pExceptionThreadEnd   = (pExceptionThreadBegin == empty) ? (empty + 1) : strstr(pExceptionThreadArea, "\n\n");

                if(!pExceptionInfoEnd)
                    pExceptionInfoEnd = pExceptionInfoBegin;
                *pExceptionInfoEnd = '\0';

                if(!pExceptionThreadEnd)
                    pExceptionThreadEnd = pExceptionThreadBegin;
                *pExceptionThreadEnd = '\0';

                size_t uiTextBriefLength = OVR_snprintf(nullptr, 0, "Full report:%s\n\nSummary report:\n%s\n\n%s", exceptionReportPath, pExceptionInfoBegin, pExceptionThreadBegin);
                char* uiTextBrief = (char*)OVR::SafeMMapAlloc(uiTextBriefLength + 1);

                if(uiTextBrief)
                {
                    OVR_snprintf(uiTextBrief, uiTextBriefLength + 1, "Full report:%s\n\nSummary report:\n%s\n\n%s", exceptionReportPath, pExceptionInfoBegin, pExceptionThreadBegin);
                    OVR::SafeMMapFree(uiText, length);
                    uiText = uiTextBrief;
                }
           #endif
        }
    }

    return uiText;
}

void ExceptionHandler::FreeExceptionUIText(const char* messageBoxText)
{
    OVR::SafeMMapFree(messageBoxText, OVR_strlen(messageBoxText));
}

void ExceptionHandler::ReportDeadlock(const char* threadName,
                                      const char* organizationName,
                                      const char* applicationName)
{
    ExceptionHandler handler;

    if (!organizationName || !organizationName[0] ||
        !applicationName || !applicationName[0])
    {
        char tempPath[OVR_MAX_PATH];
        GetCrashDumpDirectory(tempPath, OVR_ARRAY_COUNT(tempPath));
        OVR_strlcat(tempPath, "Deadlock Report (%s).txt", OVR_ARRAY_COUNT(tempPath));
        handler.SetExceptionPaths(tempPath);
    }
    else
    {
        handler.SetPathsFromNames(organizationName, applicationName, "Deadlock Report (%s).txt");
    }

    OVR_snprintf(handler.exceptionInfo.exceptionDescription,
                 sizeof(handler.exceptionInfo.exceptionDescription),
                 "Deadlock in thread '%s'", threadName ? threadName : "(null)");

    handler.exceptionInfo.timeVal = time(nullptr);
    handler.exceptionInfo.time = *gmtime(&handler.exceptionInfo.timeVal);
    handler.WriteReport();
}


//-----------------------------------------------------------------------------
// GUI Exception Listener

GUIExceptionListener::GUIExceptionListener() :
    Handler()
{
}

int GUIExceptionListener::HandleException(uintptr_t userValue,
                                          ExceptionHandler* pExceptionHandler,
                                          ExceptionInfo* pExceptionInfo,
                                          const char* reportFilePath)
{
    OVR_UNUSED3(userValue, pExceptionHandler, pExceptionInfo);

    // If debugger is not present,
    if (!OVRIsDebuggerPresent())
    {
        const char* uiText = ExceptionHandler::GetExceptionUIText(reportFilePath);
        if (uiText)
        {
            OVR::Util::DisplayMessageBox("Exception occurred", uiText);
            ExceptionHandler::FreeExceptionUIText(uiText);
        }
    }
    return 0;
}


} // namespace OVR


OVR_RESTORE_MSVC_WARNING()

#else /* !defined(HEADLESS_APP) */

namespace OVR {
    // Exits the process with the given exit code.
    void ExitProcess(intptr_t processReturnValue)
    {
        exit((int)processReturnValue);
    }
    bool OVRIsDebuggerPresent()
    {
        return false;
    }
    void ExceptionHandler::ReportDeadlock(const char* threadName,
                                          const char* organizationName,
                                          const char* applicationName)
    {
    }


    bool SymbolLookup::Initialize()
    {
        return true;
    }

    bool SymbolLookup::IsInitialized()
    {
        return true;
    }

    void SymbolLookup::Shutdown()
    {
    }

    bool SymbolLookup::Refresh()
    {
        return true;
    }

    size_t SymbolLookup::GetBacktrace(void* addressArray[], size_t addressArrayCapacity, size_t skipCount, void* platformThreadContext, OVR::ThreadSysId threadSysIdHelp) 
    {
        return 0;
    }
    bool SymbolLookup::LookupSymbol(uint64_t address, SymbolInfo& symbolInfo)
    {
        return false;
    }
    bool SymbolLookup::LookupSymbols(uint64_t* addressArray, SymbolInfo* pSymbolInfoArray, size_t arraySize)
    {
        return false;
    }
    SymbolLookup::SymbolLookup() { }
    SymbolLookup::~SymbolLookup() { }
    bool SymbolLookup::ReportThreadCallstacks(OVR::String& sOutput, size_t skipCount)
    {
        sOutput.Clear();
        return true;
    }
    bool SymbolLookup::ReportModuleInformation(OVR::String& sOutput)
    {
        sOutput.Clear();
        return true;
    }
} // namespace OVR

#endif /* !defined(HEADLESS_APP) */