summaryrefslogtreecommitdiff
path: root/base/memento.c
blob: aa60999bb5f8f61fd034e27d3665207a84d3c557 (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
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
/* Copyright (C) 2001-2023 Artifex Software, Inc.
   All Rights Reserved.

   This software is provided AS-IS with no warranty, either express or
   implied.

   This software is distributed under license and may not be copied,
   modified or distributed except as expressly authorized under the terms
   of the license contained in the file LICENSE in this distribution.

   Refer to licensing information at http://www.artifex.com or contact
   Artifex Software, Inc.,  39 Mesa Street, Suite 108A, San Francisco,
   CA 94129, USA, for further information.
*/

#ifndef MEMENTO_CPP_EXTRAS_ONLY

/* Inspired by Fortify by Simon P Bullen. */

/* Set the following if we want to do a build specifically for memory
 * squeezing. We sacrifice some features for speed. */
/* #define MEMENTO_SQUEEZEBUILD */

/* Set the following if you're only looking for leaks, not memory overwrites
 * to speed the operation */
/* #define MEMENTO_LEAKONLY */

/* Unset the following if you don't want the speed/memory hit of tracking references. */
#ifndef MEMENTO_SQUEEZEBUILD
#define MEMENTO_TRACKREFS
#endif

/* Set the following to keep extra details about the history of blocks */
#ifndef MEMENTO_SQUEEZEBUILD
#define MEMENTO_DETAILS
#endif

/* Set what volume of memory blocks we keep around after it's been freed
 * to check for overwrites. */
#define MEMENTO_FREELIST_MAX 0x2000000

/* Don't keep blocks around if they'd mean losing more than a quarter of
 * the freelist. */
#define MEMENTO_FREELIST_MAX_SINGLE_BLOCK (MEMENTO_FREELIST_MAX/4)

#define COMPILING_MEMENTO_C

/* SHUT UP, MSVC. I KNOW WHAT I AM DOING. */
#define _CRT_SECURE_NO_WARNINGS

/* We have some GS specific tweaks; more for the GS build environment than
 * anything else. */
#define MEMENTO_GS_HACKS

#ifdef MEMENTO_GS_HACKS
/* For GS we include malloc_.h. Anyone else would just include memento.h */
#include "malloc_.h"
#include "memory_.h"
int atexit(void (*)(void));
#else
#ifdef MEMENTO_MUPDF_HACKS
#include "mupdf/memento.h"
#else
#include "memento.h"
#endif
#include <stdio.h>
#endif
#ifndef _MSC_VER
#include <stdint.h>
#include <limits.h>
#include <unistd.h>
#endif

#include <errno.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

#ifdef __ANDROID__
#define MEMENTO_ANDROID
#include <stdio.h>
#endif

/* Workaround VS2012 (and earlier) missing va_copy. */
#ifdef _MSC_VER
# if _MSC_VER < 1800 /* Prior to 2013 */
#  ifndef va_copy
#   ifdef __va_copy
#    define va_copy(dst,src) __va_copy(dst,src)
#   else
#    define va_copy(dst,src) memcpy(&dst, &src, sizeof(va_list))
#   endif /* __va_copy */
#  endif /* va_copy */
# endif
#endif

/* Hacks to portably print large sizes */
#ifdef _MSC_VER
#define FMTZ "%llu"
#define FMTZ_CAST _int64
#define FMTP "0x%p"
typedef unsigned _int64 mem_uint64_t;
#else
#define FMTZ "%zu"
#define FMTZ_CAST size_t
#define FMTP "%p"
typedef long long mem_uint64_t;
#endif

#define UB(x) ((intptr_t)((x) & 0xFF))
#define B2I(x) (UB(x) | (UB(x)<<8) | (UB(x)<<16) | (UB(x)<<24))
#define B2P(x) ((void *)(B2I(x) | ((B2I(x)<<16)<<16)))
#define MEMENTO_PREFILL_UBYTE ((unsigned char)(MEMENTO_PREFILL))
#define MEMENTO_PREFILL_USHORT (((unsigned short)MEMENTO_PREFILL_UBYTE) | (((unsigned short)MEMENTO_PREFILL_UBYTE)<<8))
#define MEMENTO_PREFILL_UINT (((unsigned int)MEMENTO_PREFILL_USHORT) | (((unsigned int)MEMENTO_PREFILL_USHORT)<<16))
#define MEMENTO_PREFILL_PTR (void *)(((uintptr_t)MEMENTO_PREFILL_UINT) | ((((uintptr_t)MEMENTO_PREFILL_UINT)<<16)<<16))
#define MEMENTO_POSTFILL_UBYTE ((unsigned char)(MEMENTO_POSTFILL))
#define MEMENTO_POSTFILL_USHORT (((unsigned short)MEMENTO_POSTFILL_UBYTE) | (((unsigned short)MEMENTO_POSTFILL_UBYTE)<<8))
#define MEMENTO_POSTFILL_UINT (((unsigned int)MEMENTO_POSTFILL_USHORT) | (((unsigned int)MEMENTO_POSTFILL_USHORT)<<16))
#define MEMENTO_POSTFILL_PTR (void *)(((uintptr_t)MEMENTO_POSTFILL_UINT) | ((((uintptr_t)MEMENTO_POSTFILL_UINT)<<16)<<16))
#define MEMENTO_ALLOCFILL_UBYTE ((unsigned char)(MEMENTO_ALLOCFILL))
#define MEMENTO_ALLOCFILL_USHORT (((unsigned short)MEMENTO_ALLOCFILL_UBYTE) | (((unsigned short)MEMENTO_ALLOCFILL_UBYTE)<<8))
#define MEMENTO_ALLOCFILL_UINT (((unsigned int)MEMENTO_ALLOCFILL_USHORT) | (((unsigned int)MEMENTO_ALLOCFILL_USHORT)<<16))
#define MEMENTO_ALLOCFILL_PTR (void *)(((uintptr_t)MEMENTO_ALLOCFILL_UINT) | ((((uintptr_t)MEMENTO_ALLOCFILL_UINT)<<16)<<16))
#define MEMENTO_FREEFILL_UBYTE ((unsigned char)(MEMENTO_FREEFILL))
#define MEMENTO_FREEFILL_USHORT (((unsigned short)MEMENTO_FREEFILL_UBYTE) | (((unsigned short)MEMENTO_FREEFILL_UBYTE)<<8))
#define MEMENTO_FREEFILL_UINT (((unsigned int)MEMENTO_FREEFILL_USHORT) | (((unsigned int)MEMENTO_FREEFILL_USHORT)<<16))
#define MEMENTO_FREEFILL_PTR (void *)(((uintptr_t)MEMENTO_FREEFILL_UINT) | ((((uintptr_t)MEMENTO_FREEFILL_UINT)<<16)<<16))

#ifdef MEMENTO

#ifdef MEMENTO_ANDROID
#include <android/log.h>

static char log_buffer[4096];
static int log_fill = 0;

static char log_buffer2[4096];

static int
android_fprintf(FILE *file, const char *fmt, ...)
{
    va_list args;
    char *p, *q;

    va_start(args, fmt);
    vsnprintf(log_buffer2, sizeof(log_buffer2)-1, fmt, args);
    va_end(args);

    /* Ensure we are always null terminated */
    log_buffer2[sizeof(log_buffer2)-1] = 0;

    p = log_buffer2;
    q = p;
    do
    {
        /* Find the end of the string, or the next \n */
        while (*p && *p != '\n')
            p++;

        /* We need to output from q to p. Limit ourselves to what
         * will fit in the existing */
        if (p - q >= sizeof(log_buffer)-1 - log_fill)
                p = q + sizeof(log_buffer)-1 - log_fill;

        memcpy(&log_buffer[log_fill], q, p-q);
        log_fill += p-q;
        if (*p == '\n')
        {
            log_buffer[log_fill] = 0;
            __android_log_print(ANDROID_LOG_ERROR, "memento", "%s", log_buffer);
            usleep(1);
            log_fill = 0;
            p++; /* Skip over the \n */
        }
        else if (log_fill >= sizeof(log_buffer)-1)
        {
            log_buffer[sizeof(log_buffer2)-1] = 0;
            __android_log_print(ANDROID_LOG_ERROR, "memento", "%s", log_buffer);
            usleep(1);
            log_fill = 0;
        }
        q = p;
    }
    while (*p);

    return 0;
}

#define fprintf android_fprintf
#define MEMENTO_STACKTRACE_METHOD 3
#endif

/* _WIN64 defined implies _WIN32 will be */
#ifdef _WIN32
#include <windows.h>

static int
windows_fprintf(FILE *file, const char *fmt, ...)
{
    va_list args;
    char text[4096];
    int ret;

    va_start(args, fmt);
    ret = vfprintf(file, fmt, args);
    va_end(args);

    va_start(args, fmt);
    vsnprintf(text, 4096, fmt, args);
    OutputDebugStringA(text);
    va_end(args);

    return ret;
}

#define fprintf windows_fprintf
#endif

#ifndef MEMENTO_STACKTRACE_METHOD
#ifdef __GNUC__
#define MEMENTO_STACKTRACE_METHOD 1
#endif
#ifdef _WIN32
#define MEMENTO_STACKTRACE_METHOD 2
#endif
#endif

#if defined(__linux__) || defined(__OpenBSD__)
#define MEMENTO_HAS_FORK
#elif defined(__APPLE__) && defined(__MACH__)
#define MEMENTO_HAS_FORK
#endif

#if defined(_DLL) && defined(_MSC_VER)
#define MEMENTO_CRT_SPEC __declspec(dllimport)
#else
#define MEMENTO_CRT_SPEC
#endif

/* Define the underlying allocators, just in case */
MEMENTO_CRT_SPEC void *MEMENTO_UNDERLYING_MALLOC(size_t);
MEMENTO_CRT_SPEC void MEMENTO_UNDERLYING_FREE(void *);
MEMENTO_CRT_SPEC void *MEMENTO_UNDERLYING_REALLOC(void *,size_t);
MEMENTO_CRT_SPEC void *MEMENTO_UNDERLYING_CALLOC(size_t,size_t);

/* And some other standard functions we use. We don't include the header
 * files, just in case they pull in unexpected others. */
MEMENTO_CRT_SPEC int atoi(const char *);
MEMENTO_CRT_SPEC char *getenv(const char *);

/* How far to search for pointers in each block when calculating nestings */
/* mupdf needs at least 34000ish (sizeof(fz_shade))/ */
#define MEMENTO_PTRSEARCH 65536

#ifndef MEMENTO_MAXPATTERN
#define MEMENTO_MAXPATTERN 0
#endif

#ifdef MEMENTO_GS_HACKS
#include "valgrind.h"
#else
#ifdef HAVE_VALGRIND
#include "valgrind/memcheck.h"
#else
#define VALGRIND_MAKE_MEM_NOACCESS(p,s)  do { } while (0==1)
#define VALGRIND_MAKE_MEM_UNDEFINED(p,s)  do { } while (0==1)
#define VALGRIND_MAKE_MEM_DEFINED(p,s)  do { } while (0==1)
#endif
#endif

enum {
    Memento_PreSize  = 16,
    Memento_PostSize = 16
};

/* Some compile time checks */
typedef struct
{
    char MEMENTO_PRESIZE_MUST_BE_A_MULTIPLE_OF_4[Memento_PreSize & 3 ? -1 : 1];
    char MEMENTO_POSTSIZE_MUST_BE_A_MULTIPLE_OF_4[Memento_PostSize & 3 ? -1 : 1];
    char MEMENTO_POSTSIZE_MUST_BE_AT_LEAST_4[Memento_PostSize >= 4 ? 1 : -1];
    char MEMENTO_PRESIZE_MUST_BE_AT_LEAST_4[Memento_PreSize >= 4 ? 1 : -1];
} MEMENTO_SANITY_CHECK_STRUCT;

#define MEMENTO_UINT32 unsigned int
#define MEMENTO_UINT16 unsigned short

#define MEMENTO_PREFILL_UINT32  ((MEMENTO_UINT32)(MEMENTO_PREFILL  | (MEMENTO_PREFILL <<8) | (MEMENTO_PREFILL <<16) |(MEMENTO_PREFILL <<24)))
#define MEMENTO_POSTFILL_UINT16 ((MEMENTO_UINT16)(MEMENTO_POSTFILL | (MEMENTO_POSTFILL<<8)))
#define MEMENTO_POSTFILL_UINT32 ((MEMENTO_UINT32)(MEMENTO_POSTFILL | (MEMENTO_POSTFILL<<8) | (MEMENTO_POSTFILL<<16) |(MEMENTO_POSTFILL<<24)))
#define MEMENTO_FREEFILL_UINT16 ((MEMENTO_UINT16)(MEMENTO_FREEFILL | (MEMENTO_FREEFILL<<8)))
#define MEMENTO_FREEFILL_UINT32 ((MEMENTO_UINT32)(MEMENTO_FREEFILL | (MEMENTO_FREEFILL<<8) | (MEMENTO_FREEFILL<<16) |(MEMENTO_FREEFILL<<24)))

enum {
    Memento_Flag_OldBlock = 1,
    Memento_Flag_HasParent = 2,
    Memento_Flag_BreakOnFree = 4,
    Memento_Flag_BreakOnRealloc = 8,
    Memento_Flag_Freed = 16,
    Memento_Flag_KnownLeak = 32,
    Memento_Flag_Reported = 64,
    Memento_Flag_LastPhase = 0x80000000,
    Memento_Flag_PhaseMask = 0xFFFF0000
};

enum {
    Memento_EventType_malloc = 0,
    Memento_EventType_calloc = 1,
    Memento_EventType_realloc = 2,
    Memento_EventType_free = 3,
    Memento_EventType_new = 4,
    Memento_EventType_delete = 5,
    Memento_EventType_newArray = 6,
    Memento_EventType_deleteArray = 7,
    Memento_EventType_takeRef = 8,
    Memento_EventType_dropRef = 9,
    Memento_EventType_reference = 10,
    Memento_EventType_strdup = 11,
    Memento_EventType_asprintf = 12,
    Memento_EventType_vasprintf = 13
};

static const char *eventType[] =
{
    "malloc",
    "calloc",
    "realloc",
    "free",
    "new",
    "delete",
    "new[]",
    "delete[]",
    "takeRef",
    "dropRef",
    "reference",
    "strdup",
    "asprintf",
    "vasprintf"
};

/* When we list leaked blocks at the end of execution, we search for pointers
 * between blocks in order to be able to give a nice nested view.
 * Unfortunately, if you have are running your own allocator (such as
 * postscript's chunk allocator) you can often find that the header of the
 * block always contains pointers to next or previous blocks. This tends to
 * mean the nesting displayed is "uninteresting" at best :)
 *
 * As a hack to get around this, we have a define MEMENTO_SKIP_SEARCH that
 * indicates how many bytes to skip over at the start of the chunk.
 * This may cause us to miss true nestings, but such is life...
 */
#ifndef MEMENTO_SEARCH_SKIP
#ifdef MEMENTO_GS_HACKS
#define MEMENTO_SEARCH_SKIP (2*sizeof(void *))
#else
#define MEMENTO_SEARCH_SKIP 0
#endif
#endif

#define MEMENTO_CHILD_MAGIC   ((Memento_BlkHeader *)('M' | ('3' << 8) | ('m' << 16) | ('3' << 24)))
#define MEMENTO_SIBLING_MAGIC ((Memento_BlkHeader *)('n' | ('t' << 8) | ('0' << 16) | ('!' << 24)))

#ifdef MEMENTO_DETAILS
typedef struct Memento_hashedST Memento_hashedST;

struct Memento_hashedST
{
    Memento_hashedST *next;
    MEMENTO_UINT32    hash;
    int               count;
    void             *trace[1];
};

typedef struct Memento_BlkDetails Memento_BlkDetails;

struct Memento_BlkDetails
{
    Memento_BlkDetails *next;
    char                type;
    int                 sequence;
    Memento_hashedST   *trace;
};
#endif /* MEMENTO_DETAILS */

typedef struct Memento_BlkHeader Memento_BlkHeader;

#ifdef MEMENTO_DETAILS
#define MEMENTO_DETAIL_FIELDS \
    Memento_BlkDetails  *details;\
    Memento_BlkDetails **details_tail;
#else
#define MEMENTO_DETAIL_FIELDS
#endif

#define MEMENTO_BLKHEADER_FIELDS \
    size_t               rawsize;                       \
    int                  sequence;                      \
    int                  lastCheckedOK;                 \
    int                  flags;                         \
                                                        \
    const char          *label;                         \
                                                        \
    /* Blocks are held in a linked list for LRU */      \
    Memento_BlkHeader   *next;                          \
    /* Reused as 'parent' when printing nested list */  \
    Memento_BlkHeader   *prev;                          \
                                                        \
    /* Blocks are held in a splay tree for position. */ \
    Memento_BlkHeader   *parent;                        \
    Memento_BlkHeader   *left;                          \
    Memento_BlkHeader   *right;                         \
                                                        \
    /* Entries for nesting display calculations. Set    \
     * to magic values at all other time.  */           \
    Memento_BlkHeader   *child;                         \
    Memento_BlkHeader   *sibling;                       \
                                                        \
    MEMENTO_DETAIL_FIELDS

typedef struct
{
    MEMENTO_BLKHEADER_FIELDS
} Memento_BlkHeader_unpadded;

#define MEMENTO_BLKHEADER_UNPADDED_SIZE (sizeof(Memento_BlkHeader_unpadded)+Memento_PreSize)

struct Memento_BlkHeader
{
    MEMENTO_BLKHEADER_FIELDS

    /* Ensure that Memento_BlkHeader is a multiple of 32. This is required
     * for setjmp/longjmp etc on many platforms. We want to ensure that
     * we preserve the relative 32byte alignment to the underlying malloc. */
    char alignment_padding[32-(MEMENTO_BLKHEADER_UNPADDED_SIZE & 31)];

    char                 preblk[Memento_PreSize];
};

/* In future this could (should) be a smarter data structure, like, say,
 * splay trees. For now, we use a list.
 */
typedef struct Memento_Blocks
{
    Memento_BlkHeader *head;
    Memento_BlkHeader *tail;
    Memento_BlkHeader *top;
} Memento_Blocks;

/* What sort of Mutex should we use? */
#ifdef MEMENTO_LOCKLESS
typedef int Memento_mutex;

static void Memento_initMutex(Memento_mutex *m)
{
    (void)m;
}

#define MEMENTO_DO_LOCK() do { } while (0)
#define MEMENTO_DO_UNLOCK() do { } while (0)

#else
#if defined(_WIN32) || defined(_WIN64)
/* Windows */
typedef CRITICAL_SECTION Memento_mutex;

static void Memento_initMutex(Memento_mutex *m)
{
    InitializeCriticalSection(m);
}

#define MEMENTO_DO_LOCK() \
    EnterCriticalSection(&memento.mutex)
#define MEMENTO_DO_UNLOCK() \
    LeaveCriticalSection(&memento.mutex)

#else
#include <pthread.h>
typedef pthread_mutex_t Memento_mutex;

static void Memento_initMutex(Memento_mutex *m)
{
    pthread_mutex_init(m, NULL);
}

#define MEMENTO_DO_LOCK() \
    pthread_mutex_lock(&memento.mutex)
#define MEMENTO_DO_UNLOCK() \
    pthread_mutex_unlock(&memento.mutex)

#endif
#endif

typedef struct {
    int begin;
    int end;
} Memento_range;

/* And our global structure */
static struct {
    int            inited;
    Memento_Blocks used;
    Memento_Blocks free;
    size_t         freeListSize;
    int            sequence;
    int            paranoia;
    int            paranoidAt;
    int            countdown;
    int            lastChecked;
    int            breakAt;
    int            failAt;
    int            failing;
    int            nextFailAt;
    int            squeezeAt;
    int            squeezing;
    int            segv;
    int            pattern;
    int            nextPattern;
    int            patternBit;
    int            leaking;
    int            showDetailedBlocks;
    int            hideMultipleReallocs;
    int            abortOnLeak;
    int            abortOnCorruption;
    size_t         maxMemory;
    size_t         alloc;
    size_t         peakAlloc;
    mem_uint64_t   totalAlloc;
    size_t         numMallocs;
    size_t         numFrees;
    size_t         numReallocs;
    Memento_mutex  mutex;
    Memento_range *squeezes;
    int            squeezes_num;
    int            squeezes_pos;
    int            ignoreNewDelete;
    int            phasing;
    int            verbose;
    int            verboseNewlineSuppressed;
    void          *lastVerbosePtr;
#ifdef MEMENTO_DETAILS
    Memento_hashedST *stacktraces[256];
    int            hashCollisions;
#endif
} memento;

#define MEMENTO_EXTRASIZE (sizeof(Memento_BlkHeader) + Memento_PostSize)

/* Round up size S to the next multiple of N (where N is a power of 2) */
#define MEMENTO_ROUNDUP(S,N) ((S + N-1)&~(N-1))

#define MEMBLK_SIZE(s) MEMENTO_ROUNDUP(s + MEMENTO_EXTRASIZE, MEMENTO_MAXALIGN)

#define MEMBLK_FROMBLK(B)   (&((Memento_BlkHeader*)(void *)(B))[-1])
#define MEMBLK_TOBLK(B)     ((void*)(&((Memento_BlkHeader*)(void*)(B))[1]))
#define MEMBLK_POSTPTR(B) \
          (&((unsigned char *)(void *)(B))[(B)->rawsize + sizeof(Memento_BlkHeader)])

enum
{
    SkipStackBackTraceLevels = 4
};

#if defined(MEMENTO_STACKTRACE_METHOD) && MEMENTO_STACKTRACE_METHOD == 1
extern size_t backtrace(void **, int);
extern void backtrace_symbols_fd(void **, size_t, int);
extern char **backtrace_symbols(void **, size_t);

#define MEMENTO_BACKTRACE_MAX 256
static void (*print_stack_value)(void *address);

/* Libbacktrace gubbins - relies on us having libdl to load the .so */
#ifdef HAVE_LIBDL
#include <dlfcn.h>

typedef void (*backtrace_error_callback) (void *data, const char *msg, int errnum);

typedef struct backtrace_state *(*backtrace_create_state_type)(
    const char *filename, int threaded,
    backtrace_error_callback error_callback, void *data);

typedef int (*backtrace_full_callback) (void *data, uintptr_t pc,
                                        const char *filename, int lineno,
                                        const char *function);

typedef int (*backtrace_pcinfo_type)(struct backtrace_state *state,
                                     uintptr_t pc,
                                     backtrace_full_callback callback,
                                     backtrace_error_callback error_callback,
                                     void *data);

typedef void (*backtrace_syminfo_callback) (void *data, uintptr_t pc,
                                            const char *symname,
                                            uintptr_t symval,
                                            uintptr_t symsize);

typedef int (*backtrace_syminfo_type)(struct backtrace_state *state,
                                      uintptr_t addr,
                                      backtrace_syminfo_callback callback,
                                      backtrace_error_callback error_callback,
                                      void *data);

static backtrace_syminfo_type backtrace_syminfo;
static backtrace_create_state_type backtrace_create_state;
static backtrace_pcinfo_type backtrace_pcinfo;
static struct backtrace_state *my_backtrace_state;
static void *libbt;
static char backtrace_exe[4096];
static void *current_addr;

static void error2_cb(void *data, const char *msg, int errnum)
{
    (void)data;
    (void)msg;
    (void)errnum;
}

static void syminfo_cb(void *data, uintptr_t pc, const char *symname, uintptr_t symval, uintptr_t symsize)
{
    (void)data;
    (void)symval;
    (void)symsize;
    if (sizeof(void *) == 4)
        fprintf(stderr, "    0x%08lx %s\n", pc, symname?symname:"?");
    else
        fprintf(stderr, "    0x%016lx %s\n", pc, symname?symname:"?");
}

static void error_cb(void *data, const char *msg, int errnum)
{
    (void)data;
    (void)msg;
    (void)errnum;
    backtrace_syminfo(my_backtrace_state,
                     (uintptr_t)current_addr,
                     syminfo_cb,
                     error2_cb,
                     NULL);
}

static int full_cb(void *data, uintptr_t pc, const char *fname, int line, const char *fn)
{
    (void)data;
    if (sizeof(void *) == 4)
        fprintf(stderr, "    0x%08lx %s(%s:%d)\n", pc, fn?fn:"?", fname?fname:"?", line);
    else
        fprintf(stderr, "    0x%016lx %s(%s:%d)\n", pc, fn?fn:"?", fname?fname:"?", line);
    return 0;
}

static void print_stack_libbt(void *addr)
{
    current_addr = addr;
    backtrace_pcinfo(my_backtrace_state,
                     (uintptr_t)addr,
                     full_cb,
                     error_cb,
                     NULL);
}

static void print_stack_libbt_failed(void *addr)
{
    char **strings;
#if 0
    /* Let's use a hack from Julian Smith to call gdb to extract the information */
    /* Disabled for now, as I can't make this work. */
    static char command[1024];
    int e;
    static int gdb_invocation_failed = 0;

    if (gdb_invocation_failed == 0)
    {
        snprintf(command, sizeof(command),
                 //"gdb -q --batch -p=%i -ex 'info line *%p' -ex quit 2>/dev/null",
                 "gdb -q --batch -p=%i -ex 'info line *%p' -ex quit 2>/dev/null| egrep -v '(Thread debugging using)|(Using host libthread_db library)|(A debugging session is active)|(will be detached)|(Quit anyway)|(No such file or directory)|(^0x)|(^$)'",
                 getpid(), addr);
    printf("%s\n", command);
        e = system(command);
        if (e == 0)
            return; /* That'll do! */
        gdb_invocation_failed = 1; /* If it's failed once, it'll probably keep failing. */
    }
#endif

    /* We couldn't even get gdb! Make do. */
    strings = backtrace_symbols(&addr, 1);

    if (strings == NULL || strings[0] == NULL)
    {
        if (sizeof(void *) == 4)
            fprintf(stderr, "    [0x%08lx]\n", (uintptr_t)addr);
        else
            fprintf(stderr, "    [0x%016lx]\n", (uintptr_t)addr);
    }
    else
    {
        fprintf(stderr, "    %s\n", strings[0]);
    }
    (free)(strings);
}

static int init_libbt(void)
{
    static int libbt_inited = 0;

    if (libbt_inited)
        return 0;
    libbt_inited = 1;

    libbt = dlopen("libbacktrace.so", RTLD_LAZY);
    if (libbt == NULL)
        libbt = dlopen("/opt/lib/libbacktrace.so", RTLD_LAZY);
    if (libbt == NULL)
        libbt = dlopen("/lib/libbacktrace.so", RTLD_LAZY);
    if (libbt == NULL)
        libbt = dlopen("/usr/lib/libbacktrace.so", RTLD_LAZY);
    if (libbt == NULL)
        libbt = dlopen("/usr/local/lib/libbacktrace.so", RTLD_LAZY);
    if (libbt == NULL)
        goto fail;

    backtrace_create_state = dlsym(libbt, "backtrace_create_state");
    backtrace_syminfo      = dlsym(libbt, "backtrace_syminfo");
    backtrace_pcinfo       = dlsym(libbt, "backtrace_pcinfo");

    if (backtrace_create_state == NULL ||
        backtrace_syminfo == NULL ||
        backtrace_pcinfo == NULL)
    {
        goto fail;
    }

    my_backtrace_state = backtrace_create_state(backtrace_exe,
                                                1 /*BACKTRACE_SUPPORTS_THREADS*/,
                                                error_cb,
                                                NULL);
    if (my_backtrace_state == NULL)
        goto fail;

    print_stack_value = print_stack_libbt;

    return 1;

 fail:
    fprintf(stderr,
            "MEMENTO: libbacktrace.so failed to load; backtraces will be sparse.\n"
            "MEMENTO: See memento.h for how to rectify this.\n");
    libbt = NULL;
    backtrace_create_state = NULL;
    backtrace_syminfo = NULL;
    print_stack_value = print_stack_libbt_failed;
    return 0;
}
#endif

static void print_stack_default(void *addr)
{
    char **strings = backtrace_symbols(&addr, 1);

    if (strings == NULL || strings[0] == NULL)
    {
        fprintf(stderr, "    ["FMTP"]\n", addr);
    }
#ifdef HAVE_LIBDL
    else if (strchr(strings[0], ':') == NULL)
    {
        /* Probably a "path [address]" format string */
        char *s = strchr(strings[0], ' ');

        if (s != strings[0])
        {
            memcpy(backtrace_exe, strings[0], s - strings[0]);
            backtrace_exe[s-strings[0]] = 0;
            init_libbt();
            print_stack_value(addr);
        }
    }
#endif
    else
    {
        fprintf(stderr, "    %s\n", strings[0]);
    }
    free(strings);
}

static void Memento_initStacktracer(void)
{
    print_stack_value = print_stack_default;
}

static int Memento_getStacktrace(void **stack, int *skip)
{
    size_t num;

    num = backtrace(&stack[0], MEMENTO_BACKTRACE_MAX);

    *skip = SkipStackBackTraceLevels;
    if (num <= SkipStackBackTraceLevels)
        return 0;
    return (int)(num-SkipStackBackTraceLevels);
}

static void Memento_showStacktrace(void **stack, int numberOfFrames)
{
    int i;

    for (i = 0; i < numberOfFrames; i++)
    {
        print_stack_value(stack[i]);
    }
}
#elif defined(MEMENTO_STACKTRACE_METHOD) && MEMENTO_STACKTRACE_METHOD == 2
#include <Windows.h>

/* We use DbgHelp.dll rather than DbgHelp.lib. This avoids us needing
 * extra link time complications, and enables us to fall back gracefully
 * if the DLL cannot be found.
 *
 * To achieve this we have our own potted versions of the required types
 * inline here.
 */
#ifdef _WIN64
typedef DWORD64 DWORD_NATIVESIZED;
#else
typedef DWORD DWORD_NATIVESIZED;
#endif

#define MEMENTO_BACKTRACE_MAX 64

typedef USHORT (__stdcall *My_CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __out_opt PULONG);

typedef struct MY_IMAGEHLP_LINE {
    DWORD    SizeOfStruct;
    PVOID    Key;
    DWORD    LineNumber;
    PCHAR    FileName;
    DWORD_NATIVESIZED    Address;
} MY_IMAGEHLP_LINE, *MY_PIMAGEHLP_LINE;

typedef BOOL (__stdcall *My_SymGetLineFromAddrType)(HANDLE hProcess, DWORD_NATIVESIZED dwAddr, PDWORD pdwDisplacement, MY_PIMAGEHLP_LINE Line);

typedef struct MY_SYMBOL_INFO {
    ULONG       SizeOfStruct;
    ULONG       TypeIndex;        // Type Index of symbol
    ULONG64     Reserved[2];
    ULONG       info;
    ULONG       Size;
    ULONG64     ModBase;          // Base Address of module containing this symbol
    ULONG       Flags;
    ULONG64     Value;            // Value of symbol, ValuePresent should be 1
    ULONG64     Address;          // Address of symbol including base address of module
    ULONG       Register;         // register holding value or pointer to value
    ULONG       Scope;            // scope of the symbol
    ULONG       Tag;              // pdb classification
    ULONG       NameLen;          // Actual length of name
    ULONG       MaxNameLen;
    CHAR        Name[1];          // Name of symbol
} MY_SYMBOL_INFO, *MY_PSYMBOL_INFO;

typedef BOOL (__stdcall *My_SymFromAddrType)(HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, MY_PSYMBOL_INFO Symbol);
typedef BOOL (__stdcall *My_SymInitializeType)(HANDLE hProcess, PSTR UserSearchPath, BOOL fInvadeProcess);

static My_CaptureStackBackTraceType Memento_CaptureStackBackTrace;
static My_SymGetLineFromAddrType Memento_SymGetLineFromAddr;
static My_SymFromAddrType Memento_SymFromAddr;
static My_SymInitializeType Memento_SymInitialize;
static HANDLE Memento_process;

static void Memento_initStacktracer(void)
{
    HMODULE mod = LoadLibrary("kernel32.dll");

    if (mod == NULL)
        return;
    Memento_CaptureStackBackTrace = (My_CaptureStackBackTraceType)(GetProcAddress(mod, "RtlCaptureStackBackTrace"));
    if (Memento_CaptureStackBackTrace == NULL)
        return;
    mod = LoadLibrary("Dbghelp.dll");
    if (mod == NULL) {
        Memento_CaptureStackBackTrace = NULL;
        return;
    }
    Memento_SymGetLineFromAddr =
            (My_SymGetLineFromAddrType)(GetProcAddress(mod,
#ifdef _WIN64
                                                       "SymGetLineFromAddr64"
#else
                                                       "SymGetLineFromAddr"
#endif
                                        ));
    if (Memento_SymGetLineFromAddr == NULL) {
        Memento_CaptureStackBackTrace = NULL;
        return;
    }
    Memento_SymFromAddr = (My_SymFromAddrType)(GetProcAddress(mod, "SymFromAddr"));
    if (Memento_SymFromAddr == NULL) {
        Memento_CaptureStackBackTrace = NULL;
        return;
    }
    Memento_SymInitialize = (My_SymInitializeType)(GetProcAddress(mod, "SymInitialize"));
    if (Memento_SymInitialize == NULL) {
        Memento_CaptureStackBackTrace = NULL;
        return;
    }
    Memento_process = GetCurrentProcess();
    Memento_SymInitialize(Memento_process, NULL, TRUE);
}

static int Memento_getStacktrace(void **stack, int *skip)
{
    if (Memento_CaptureStackBackTrace == NULL)
        return 0;

    *skip = 0;
    /* Limit us to 63 levels due to windows bug */
    return Memento_CaptureStackBackTrace(SkipStackBackTraceLevels, 63-SkipStackBackTraceLevels, stack, NULL);
}

static void Memento_showStacktrace(void **stack, int numberOfFrames)
{
    MY_IMAGEHLP_LINE line;
    int i, j;
    char symbol_buffer[sizeof(MY_SYMBOL_INFO) + 1024 + 1];
    MY_SYMBOL_INFO *symbol = (MY_SYMBOL_INFO *)symbol_buffer;
    bool ok;
    int prefix = 1; /* Ignore a prefix of 'unknowns' */
    int suppressed = 0; /* How many unknowns we have suppressed. */

    symbol->MaxNameLen = 1024;
    symbol->SizeOfStruct = sizeof(MY_SYMBOL_INFO);
    line.SizeOfStruct = sizeof(MY_IMAGEHLP_LINE);
    for (i = 0; i < numberOfFrames; i++)
    {
        DWORD64 dwDisplacement64;
        DWORD dwDisplacement;
        ok = Memento_SymFromAddr(Memento_process, (DWORD64)(stack[i]), &dwDisplacement64, symbol);
        if (ok == 1)
            ok = Memento_SymGetLineFromAddr(Memento_process, (DWORD_NATIVESIZED)(stack[i]), &dwDisplacement, &line);
        if (ok == 1) {
            for (j = 0; j < suppressed; j++)
                fprintf(stderr, "    unknown\n");
            suppressed = 0;
            fprintf(stderr, "    %s in %s:%d\n", symbol->Name, line.FileName, line.LineNumber);
            prefix = 0;
        } else if (prefix == 0) {
            suppressed++;
        }
    }
}
#elif defined(MEMENTO_STACKTRACE_METHOD) && MEMENTO_STACKTRACE_METHOD == 3

#include <unwind.h>
#include <dlfcn.h>

/* From cxxabi.h */
extern char* __cxa_demangle(const char* mangled_name,
                            char*       output_buffer,
                            size_t*     length,
                            int*        status);

static void Memento_initStacktracer(void)
{
}

#define MEMENTO_BACKTRACE_MAX 256

typedef struct
{
    int count;
    void **addr;
} my_unwind_details;

static _Unwind_Reason_Code unwind_populate_callback(struct _Unwind_Context *context,
                                                    void *arg)
{
    my_unwind_details *uw = (my_unwind_details *)arg;
    int count = uw->count;

    if (count >= MEMENTO_BACKTRACE_MAX)
        return _URC_END_OF_STACK;

    uw->addr[count] = (void *)_Unwind_GetIP(context);
    uw->count++;

    return _URC_NO_REASON;
}

static int Memento_getStacktrace(void **stack, int *skip)
{
    my_unwind_details uw = { 0, stack };

    *skip = 0;

    /* Collect the backtrace. Deliberately only unwind once,
     * and avoid using malloc etc until this completes just
     * in case. */
    _Unwind_Backtrace(unwind_populate_callback, &uw);
    if (uw.count <= SkipStackBackTraceLevels)
        return 0;

    *skip = SkipStackBackTraceLevels;
    return uw.count-SkipStackBackTraceLevels;
}

static void Memento_showStacktrace(void **stack, int numberOfFrames)
{
    int i;

    for (i = 0; i < numberOfFrames; i++)
    {
        Dl_info info;
        if (dladdr(stack[i], &info))
        {
            int status = 0;
            const char *sym = info.dli_sname ? info.dli_sname : "<unknown>";
            char *demangled = __cxa_demangle(sym, NULL, 0, &status);
            int offset = stack[i] - info.dli_saddr;
            fprintf(stderr, "    ["FMTP"]%s(+0x%x)\n", stack[i], demangled && status == 0 ? demangled : sym, offset);
            free(demangled);
        }
        else
        {
            fprintf(stderr, "    ["FMTP"]\n", stack[i]);
        }
    }
}

#else
static void Memento_initStacktracer(void)
{
}

static int Memento_getStacktrace(void **stack, int *skip)
{
    *skip = 0;
    return 0;
}

static void Memento_showStacktrace(void **stack, int numberOfFrames)
{
}
#endif /* MEMENTO_STACKTRACE_METHOD */

#ifndef MEMENTO_BACKTRACE_MAX
#define MEMENTO_BACKTRACE_MAX 1
#endif

#ifdef MEMENTO_DETAILS
static MEMENTO_UINT32
hashStackTrace(void **stack, int count)
{
    int i;
    MEMENTO_UINT32 hash = 0;

    count *= sizeof(void *)/sizeof(unsigned int);
    for (i = 0; i < count; i++)
        hash = (hash>>5) ^ (hash<<27) ^ ((unsigned int *)stack)[i];

    return hash;
}

static Memento_hashedST oom_hashed_st =
{
    NULL, /* next */
    0,    /* hash */
    0,    /* count */
    {NULL}/* trace[0] */
};

static Memento_hashedST *Memento_getHashedStacktrace(void)
{
    void *stack[MEMENTO_BACKTRACE_MAX];
    MEMENTO_UINT32 hash;
    int count, skip;
    Memento_hashedST **h;

#ifdef MEMENTO_STACKTRACE_METHOD
    count = Memento_getStacktrace(stack, &skip);
#else
    skip = 0;
    count = 0;
#endif

    count -= skip;
    hash = hashStackTrace(&stack[skip], count);
    while (1) {
        h = &memento.stacktraces[hash & 0xff];
        while (*h) {
            if ((*h)->hash == hash)
                break;
            h = &(*h)->next;
        }
        if ((*h) == NULL)
            break; /* No match, fall through to make a new one. */
        if (count == (*h)->count &&
            memcmp((*h)->trace, &stack[skip], sizeof(void *) * count) == 0)
            return (*h); /* We match! Reuse this one. */
        /* Hash collision. */
        hash++;
        memento.hashCollisions++;
    }

    (*h) = MEMENTO_UNDERLYING_MALLOC(sizeof(Memento_hashedST) + sizeof(void *) * (count-1));
    if (*h == NULL)
        return &oom_hashed_st;

    (*h)->next = NULL;
    (*h)->hash = hash;
    (*h)->count = count;
    memcpy(&(*h)->trace[0], &stack[skip], count * sizeof(void *));

    return *h;
}

static void Memento_showHashedStacktrace(Memento_hashedST *trace)
{
    if (trace == NULL)
        return;

    Memento_showStacktrace(&trace->trace[0], trace->count);
}

static void Memento_storeDetails(Memento_BlkHeader *head, int type, Memento_hashedST *st)
{
    Memento_BlkDetails *details;

    if (head == NULL)
        return;

    details = MEMENTO_UNDERLYING_MALLOC(sizeof(*details));
    if (details == NULL)
        return;

    details->type = (char)type;
    details->sequence = memento.sequence;
    details->next = NULL;
    details->trace = st;
    VALGRIND_MAKE_MEM_DEFINED(&head->details_tail, sizeof(head->details_tail));
    *head->details_tail = details;
    head->details_tail = &details->next;
    VALGRIND_MAKE_MEM_NOACCESS(&head->details_tail, sizeof(head->details_tail));
}
#endif

void Memento_showHash(MEMENTO_UINT32 hash)
{
#ifdef MEMENTO_DETAILS
    Memento_hashedST *h;

    h = memento.stacktraces[hash & 0xff];
    while (h) {
        if (h->hash == hash)
            break;
        h = h->next;
    }

    Memento_showHashedStacktrace(h);
#endif
}

static void Memento_bt_internal(int skip2)
{
#ifdef MEMENTO_STACKTRACE_METHOD
    void *stack[MEMENTO_BACKTRACE_MAX];
    int count;
    int skip;

    count = Memento_getStacktrace(stack, &skip);
    Memento_showStacktrace(&stack[skip+skip2], count-skip-skip2);
#endif
}

void (Memento_bt)(void)
{
    Memento_bt_internal(0);
}

static int Memento_checkAllMemoryLocked(void);

void Memento_breakpoint(void)
{
    /* A handy externally visible function for breakpointing */
#if 0 /* Enable this to force automatic breakpointing */
#ifndef NDEBUG
#ifdef _MSC_VER
    __asm int 3;
#endif
#endif
#endif
}

static void Memento_init(void);

#define MEMENTO_LOCK() \
do { if (!memento.inited) Memento_init(); MEMENTO_DO_LOCK(); } while (0)

#define MEMENTO_UNLOCK() \
do { MEMENTO_DO_UNLOCK(); } while (0)

/* Do this as a macro to prevent another level in the callstack,
 * which is annoying while stepping. */
#define Memento_breakpointLocked() \
do { MEMENTO_UNLOCK(); Memento_breakpoint(); MEMENTO_LOCK(); } while (0)

/* Move the given node to the root of the tree, by
 * performing a series of the following rotations.
 * The key observation here is that all these
 * rotations preserve the ordering of the tree, and
 * result in 'x' getting higher.
 *
 * Case 1:   z          x           Case 1b:   z                   x
 *          # #        # #                    # #                 # #
 *         y   D      A   y                  A   y               y   D
 *        # #     =>     # #                    # #     =>      # #
 *       x   C          B   z                  B   x           z   C
 *      # #                # #                    # #         # #
 *     A   B              C   D                  C   D       A   B
 *
 * Case 2:   z             x        Case 2b:   z                  x
 *          # #          ## ##                # #               ## ##
 *         y   D        y     z              A   y             z     y
 *        # #     =>   # #   # #                # #     =>    # #   # #
 *       A   x        A   B C   D              x   D         A   B C   D
 *          # #                               # #
 *         B   C                             B   C
 *
 * Case 3:   y          x           Case 3b:  y                  x
 *          # #        # #                   # #                # #
 *         x   C  =>  A   y                 A   x       =>     y   C
 *        # #            # #                   # #            # #
 *       A   B          B   C                 B   C          A   B
 */
static void
move_to_root(Memento_BlkHeader *x)
{
    Memento_BlkHeader *y, *z;

    if (x == NULL)
        return;

    VALGRIND_MAKE_MEM_DEFINED(x, sizeof(*x));
    while ((y = x->parent) != NULL) {
        VALGRIND_MAKE_MEM_DEFINED(y, sizeof(*y));
        if ((z = y->parent) != NULL) {
            VALGRIND_MAKE_MEM_DEFINED(z, sizeof(*z));
            x->parent = z->parent;
            if (x->parent) {
                VALGRIND_MAKE_MEM_DEFINED(x->parent, sizeof(*x->parent));
                if (x->parent->left == z)
                    x->parent->left = x;
                else
                    x->parent->right  = x;
                VALGRIND_MAKE_MEM_NOACCESS(x->parent, sizeof(*x->parent));
            }
            y->parent = x;
            /* Case 1, 1b, 2 or 2b */
            if (y->left == x) {
                /* Case 1 or 2b */
                if (z->left == y) {
                    /* Case 1 */
                    y->left = x->right;
                    if (y->left) {
                        VALGRIND_MAKE_MEM_DEFINED(y->left, sizeof(*y->left));
                        y->left->parent = y;
                        VALGRIND_MAKE_MEM_NOACCESS(y->left, sizeof(*y->left));
                    }
                    z->left = y->right;
                    if (z->left) {
                        VALGRIND_MAKE_MEM_DEFINED(z->left, sizeof(*z->left));
                        z->left->parent = z;
                        VALGRIND_MAKE_MEM_NOACCESS(z->left, sizeof(*z->left));
                    }
                    y->right = z;
                    z->parent = y;
                } else {
                    /* Case 2b */
                    z->right = x->left;
                    if (z->right) {
                        VALGRIND_MAKE_MEM_DEFINED(z->right, sizeof(*z->right));
                        z->right->parent = z;
                        VALGRIND_MAKE_MEM_NOACCESS(z->right, sizeof(*z->right));
                    }
                    y->left = x->right;
                    if (y->left) {
                        VALGRIND_MAKE_MEM_DEFINED(y->left, sizeof(*y->left));
                        y->left->parent = y;
                        VALGRIND_MAKE_MEM_NOACCESS(y->left, sizeof(*y->left));
                    }
                    x->left = z;
                    z->parent = x;
                }
                x->right      = y;
            } else {
                /* Case 2 or 1b */
                if (z->left == y) {
                    /* Case 2 */
                    y->right = x->left;
                    if (y->right) {
                        VALGRIND_MAKE_MEM_DEFINED(y->right, sizeof(*y->right));
                        y->right->parent = y;
                        VALGRIND_MAKE_MEM_NOACCESS(y->right, sizeof(*y->right));
                    }
                    z->left = x->right;
                    if (z->left) {
                        VALGRIND_MAKE_MEM_DEFINED(z->left, sizeof(*z->left));
                        z->left->parent = z;
                        VALGRIND_MAKE_MEM_NOACCESS(z->left, sizeof(*z->left));
                    }
                    x->right = z;
                    z->parent = x;
                } else {
                    /* Case 1b */
                    z->right = y->left;
                    if (z->right) {
                        VALGRIND_MAKE_MEM_DEFINED(z->right, sizeof(*z->right));
                        z->right->parent = z;
                        VALGRIND_MAKE_MEM_NOACCESS(z->right, sizeof(*z->right));
                    }
                    y->right = x->left;
                    if (y->right) {
                        VALGRIND_MAKE_MEM_DEFINED(y->right, sizeof(*y->right));
                        y->right->parent = y;
                        VALGRIND_MAKE_MEM_NOACCESS(y->right, sizeof(*y->right));
                    }
                    y->left = z;
                    z->parent = y;
                }
                x->left = y;
            }
            VALGRIND_MAKE_MEM_NOACCESS(z, sizeof(*z));
        } else {
            /* Case 3 or 3b */
            x->parent = NULL;
            y->parent = x;
            if (y->left == x) {
                /* Case 3 */
                y->left = x->right;
                if (y->left) {
                    VALGRIND_MAKE_MEM_DEFINED(y->left, sizeof(*y->left));
                    y->left->parent = y;
                    VALGRIND_MAKE_MEM_NOACCESS(y->left, sizeof(*y->left));
                }
                x->right = y;
            } else {
                /* Case 3b */
                y->right = x->left;
                if (y->right) {
                    VALGRIND_MAKE_MEM_DEFINED(y->right, sizeof(*y->right));
                    y->right->parent = y;
                    VALGRIND_MAKE_MEM_NOACCESS(y->right, sizeof(*y->right));
                }
                x->left = y;
            }
        }
        VALGRIND_MAKE_MEM_NOACCESS(y, sizeof(*y));
    }
    VALGRIND_MAKE_MEM_NOACCESS(x, sizeof(*x));
}

static void Memento_removeBlockSplay(Memento_Blocks    *blks,
                                     Memento_BlkHeader *b)
{
    Memento_BlkHeader *replacement;

    VALGRIND_MAKE_MEM_DEFINED(b, sizeof(*b));
    if (b->left == NULL)
    {
        /* At most one child - easy */
        replacement = b->right;
    }
    else if (b->right == NULL)
    {
        /* Strictly one child - easy */
        replacement = b->left;
    }
    else
    {
        /* 2 Children - tricky */
        /* Find in-order predecessor to b */
        replacement = b->left;
        VALGRIND_MAKE_MEM_DEFINED(replacement, sizeof(*replacement));
        while (replacement->right)
        {
            Memento_BlkHeader *o = replacement;
            replacement = o->right;
            VALGRIND_MAKE_MEM_DEFINED(replacement, sizeof(*replacement));
            VALGRIND_MAKE_MEM_NOACCESS(o, sizeof(*o));
        }
        /* Remove replacement - easy as just one child */
        (void)Memento_removeBlockSplay(NULL, replacement);
        /* Replace b with replacement */
        VALGRIND_MAKE_MEM_DEFINED(b, sizeof(*b));
        if (b->left) {
            VALGRIND_MAKE_MEM_DEFINED(b->left, sizeof(*b->left));
            b->left->parent = replacement;
            VALGRIND_MAKE_MEM_NOACCESS(b->left, sizeof(*b->left));
        }
        VALGRIND_MAKE_MEM_DEFINED(b->right, sizeof(*b->right));
        b->right->parent = replacement;
        VALGRIND_MAKE_MEM_NOACCESS(b->right, sizeof(*b->right));
        VALGRIND_MAKE_MEM_DEFINED(replacement, sizeof(*replacement));
        replacement->left = b->left;
        replacement->right = b->right;
    }
    if (b->parent)
    {
        VALGRIND_MAKE_MEM_DEFINED(b->parent, sizeof(*b->parent));
        if (b->parent->left == b)
            b->parent->left = replacement;
        else
            b->parent->right = replacement;
            VALGRIND_MAKE_MEM_NOACCESS(b->parent, sizeof(*b->parent));
    } else {
        VALGRIND_MAKE_MEM_DEFINED(&blks->top, sizeof(blks->top));
        blks->top = replacement;
        VALGRIND_MAKE_MEM_NOACCESS(&blks->top, sizeof(blks->top));
    }
    if (replacement)
    {
        VALGRIND_MAKE_MEM_DEFINED(replacement, sizeof(*replacement));
        replacement->parent = b->parent;
        VALGRIND_MAKE_MEM_NOACCESS(replacement, sizeof(*replacement));
    }
    VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(*b));
}

static void Memento_addBlockSplay(Memento_Blocks    *blks,
                                  Memento_BlkHeader *b)
{
    Memento_BlkHeader *parent = NULL;
    Memento_BlkHeader **n = &blks->top;

    /* Walk down, looking for a place to put b. */
    VALGRIND_MAKE_MEM_DEFINED(&blks->top, sizeof(blks->top));
    while (*n != NULL) {
        Memento_BlkHeader *o = parent;
        VALGRIND_MAKE_MEM_DEFINED(*n, sizeof(**n));
        parent = *n;
        if (o) VALGRIND_MAKE_MEM_NOACCESS(o, sizeof(*o));
        VALGRIND_MAKE_MEM_DEFINED(parent, sizeof(*parent));
        if (b < parent)
            n = &parent->left;
        else
            n = &parent->right;
    }
    /* Place b */
    *n = b;
    if (parent) VALGRIND_MAKE_MEM_NOACCESS(parent, sizeof(*parent));
    b->parent = parent;
    b->left = NULL;
    b->right = NULL;
    /* Now perform the splay magic */
    move_to_root(b);
    /* This always leaves b at the top. */
    blks->top = b;
    VALGRIND_MAKE_MEM_DEFINED(b, sizeof(*b));
    b->parent = NULL;
    VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(*b));
    VALGRIND_MAKE_MEM_NOACCESS(&blks->top, sizeof(blks->top));
}

static void Memento_addBlockHead(Memento_Blocks    *blks,
                                 Memento_BlkHeader *b,
                                 int                type)
{
    Memento_addBlockSplay(blks, b);
    if (blks->tail == NULL)
        blks->tail = b;
    VALGRIND_MAKE_MEM_DEFINED(b, sizeof(*b));
    b->next    = blks->head;
    b->prev    = NULL;
    if (blks->head)
    {
        VALGRIND_MAKE_MEM_DEFINED(&blks->head->prev, sizeof(blks->head->prev));
        blks->head->prev = b;
        VALGRIND_MAKE_MEM_NOACCESS(&blks->head->prev, sizeof(blks->head->prev));
    }
    blks->head = b;
#ifndef MEMENTO_LEAKONLY
    memset(b->preblk, MEMENTO_PREFILL, Memento_PreSize);
    memset(MEMBLK_POSTPTR(b), MEMENTO_POSTFILL, Memento_PostSize);
#endif
    VALGRIND_MAKE_MEM_NOACCESS(MEMBLK_POSTPTR(b), Memento_PostSize);
    if (type == 0) { /* malloc */
        VALGRIND_MAKE_MEM_UNDEFINED(MEMBLK_TOBLK(b), b->rawsize);
    } else if (type == 1) { /* free */
      VALGRIND_MAKE_MEM_NOACCESS(MEMBLK_TOBLK(b), b->rawsize);
    }
    VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(Memento_BlkHeader));
}

static void Memento_addBlockTail(Memento_Blocks    *blks,
                                 Memento_BlkHeader *b,
                                 int                type)
{
    Memento_addBlockSplay(blks, b);
    VALGRIND_MAKE_MEM_DEFINED(&blks->tail, sizeof(Memento_BlkHeader *));
    if (blks->head == NULL)
        blks->head = b;
    VALGRIND_MAKE_MEM_DEFINED(b, sizeof(*b));
    b->prev = blks->tail;
    b->next = NULL;
    if (blks->tail) {
        VALGRIND_MAKE_MEM_DEFINED(&blks->tail->next, sizeof(blks->tail->next));
        blks->tail->next = b;
        VALGRIND_MAKE_MEM_NOACCESS(&blks->tail->next, sizeof(blks->tail->next));
    }
    blks->tail = b;
#ifndef MEMENTO_LEAKONLY
    memset(b->preblk, MEMENTO_PREFILL, Memento_PreSize);
    memset(MEMBLK_POSTPTR(b), MEMENTO_POSTFILL, Memento_PostSize);
#endif
    VALGRIND_MAKE_MEM_NOACCESS(MEMBLK_POSTPTR(b), Memento_PostSize);
    if (type == 0) { /* malloc */
        VALGRIND_MAKE_MEM_UNDEFINED(MEMBLK_TOBLK(b), b->rawsize);
    } else if (type == 1) { /* free */
      VALGRIND_MAKE_MEM_NOACCESS(MEMBLK_TOBLK(b), b->rawsize);
    }
    VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(Memento_BlkHeader));
    VALGRIND_MAKE_MEM_NOACCESS(&blks->tail, sizeof(Memento_BlkHeader *));
}

typedef struct BlkCheckData {
    /* found holds some bits:
     * Bit 0 (1) -> At least one block has been checked.
     * Bit 1 (2) -> We have found an "Allocated block".
     * Bit 2 (4) -> We have found a "Freed block".
     * Bit 3 (8) -> Trigger a breakpoint on completion.
     */
    int found;
    int preCorrupt;
    int postCorrupt;
    int freeCorrupt;
    size_t index;
} BlkCheckData;

#ifndef MEMENTO_LEAKONLY
static int Memento_Internal_checkAllocedBlock(Memento_BlkHeader *b, void *arg)
{
    int             i;
    MEMENTO_UINT32 *ip;
    unsigned char  *p;
    BlkCheckData   *data = (BlkCheckData *)arg;

    ip = (MEMENTO_UINT32 *)(void *)(b->preblk);
    i = Memento_PreSize>>2;
    do {
        if (*ip++ != MEMENTO_PREFILL_UINT32)
            goto pre_corrupt;
    } while (--i);
    if (0) {
pre_corrupt:
        data->preCorrupt = 1;
    }
    /* Postfill may not be aligned, so have to be slower */
    p = MEMBLK_POSTPTR(b);
    i = Memento_PostSize-4;
    if ((intptr_t)p & 1)
    {
        if (*p++ != MEMENTO_POSTFILL)
            goto post_corrupt;
        i--;
    }
    if ((intptr_t)p & 2)
    {
        if (*(MEMENTO_UINT16 *)p != MEMENTO_POSTFILL_UINT16)
            goto post_corrupt;
        p += 2;
        i -= 2;
    }
    do {
        if (*(MEMENTO_UINT32 *)p != MEMENTO_POSTFILL_UINT32)
            goto post_corrupt;
        p += 4;
        i -= 4;
    } while (i >= 0);
    if (i & 2)
    {
        if (*(MEMENTO_UINT16 *)p != MEMENTO_POSTFILL_UINT16)
            goto post_corrupt;
        p += 2;
    }
    if (i & 1)
    {
        if (*p != MEMENTO_POSTFILL)
            goto post_corrupt;
    }
    if (0) {
post_corrupt:
        data->postCorrupt = 1;
    }
    if ((data->freeCorrupt | data->preCorrupt | data->postCorrupt) == 0) {
        b->lastCheckedOK = memento.sequence;
    }
    data->found |= 1;
    return 0;
}

static int Memento_Internal_checkFreedBlock(Memento_BlkHeader *b, void *arg)
{
    size_t         i;
    unsigned char *p;
    BlkCheckData  *data = (BlkCheckData *)arg;

    p = MEMBLK_TOBLK(b); /* p will always be aligned */
    i = b->rawsize;
    /* Attempt to speed this up by checking an (aligned) int at a time */
    if (i >= 4) {
        i -= 4;
        do {
            if (*(MEMENTO_UINT32 *)p != MEMENTO_FREEFILL_UINT32)
                goto mismatch4;
            p += 4;
            i -= 4;
        } while (i > 0);
        i += 4;
    }
    if (i & 2) {
        if (*(MEMENTO_UINT16 *)p != MEMENTO_FREEFILL_UINT16)
            goto mismatch;
        p += 2;
        i -= 2;
    }
    if (0) {
mismatch4:
        i += 4;
    }
mismatch:
    while (i) {
        if (*p++ != (unsigned char)MEMENTO_FREEFILL)
            break;
        i--;
    }
    if (i) {
        data->freeCorrupt = 1;
        data->index       = b->rawsize-i;
    }
    return Memento_Internal_checkAllocedBlock(b, arg);
}
#endif /* MEMENTO_LEAKONLY */

static void Memento_removeBlock(Memento_Blocks    *blks,
                                Memento_BlkHeader *b)
{
    Memento_removeBlockSplay(blks, b);
    VALGRIND_MAKE_MEM_DEFINED(b, sizeof(*b));
    if (b->next) {
        VALGRIND_MAKE_MEM_DEFINED(&b->next->prev, sizeof(b->next->prev));
        b->next->prev = b->prev;
        VALGRIND_MAKE_MEM_NOACCESS(&b->next->prev, sizeof(b->next->prev));
    }
    if (b->prev) {
        VALGRIND_MAKE_MEM_DEFINED(&b->prev->next, sizeof(b->prev->next));
        b->prev->next = b->next;
        VALGRIND_MAKE_MEM_NOACCESS(&b->prev->next, sizeof(b->prev->next));
    }
    if (blks->tail == b)
        blks->tail = b->prev;
    if (blks->head == b)
        blks->head = b->next;
    VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(*b));
}

static void free_block(Memento_BlkHeader *head)
{
#ifdef MEMENTO_DETAILS
    Memento_BlkDetails *details = head->details;

    while (details)
    {
        Memento_BlkDetails *next = details->next;
        MEMENTO_UNDERLYING_FREE(details);
        details = next;
    }
#endif
    MEMENTO_UNDERLYING_FREE(head);
}

static int Memento_Internal_makeSpace(size_t space)
{
    /* If too big, it can never go on the freelist */
    if (space > MEMENTO_FREELIST_MAX_SINGLE_BLOCK)
        return 0;
    /* Pretend we added it on. */
    memento.freeListSize += space;
    /* Ditch blocks until it fits within our limit */
    while (memento.freeListSize > MEMENTO_FREELIST_MAX) {
        Memento_BlkHeader *head = memento.free.head;
        VALGRIND_MAKE_MEM_DEFINED(head, sizeof(*head));
        memento.free.head = head->next;
        memento.freeListSize -= MEMBLK_SIZE(head->rawsize);
        Memento_removeBlockSplay(&memento.free, head);
        VALGRIND_MAKE_MEM_DEFINED(head, sizeof(*head));
        free_block(head);
    }
    /* Make sure we haven't just completely emptied the free list */
    /* (This should never happen, but belt and braces... */
    if (memento.free.head == NULL)
        memento.free.tail = NULL;
    return 1;
}

static int Memento_appBlocks(Memento_Blocks *blks,
                             int             (*app)(Memento_BlkHeader *,
                                                    void *),
                             void           *arg)
{
    Memento_BlkHeader *head = blks->head;
    Memento_BlkHeader *next;
    int                result;
    while (head) {
        VALGRIND_MAKE_MEM_DEFINED(head, sizeof(Memento_BlkHeader));
        VALGRIND_MAKE_MEM_DEFINED(MEMBLK_TOBLK(head),
                                  head->rawsize + Memento_PostSize);
        result = app(head, arg);
        next = head->next;
        VALGRIND_MAKE_MEM_NOACCESS(MEMBLK_POSTPTR(head), Memento_PostSize);
        VALGRIND_MAKE_MEM_NOACCESS(head, sizeof(Memento_BlkHeader));
        if (result)
            return result;
        head = next;
    }
    return 0;
}

static Memento_BlkHeader *
find_enclosing_block(Memento_Blocks *blks,
                     void *addr,
                     int *flags)
{
    Memento_BlkHeader *blk;

    VALGRIND_MAKE_MEM_DEFINED(&blks->top, sizeof(blks->top));
    blk = blks->top;
    while (blk)
    {
        Memento_BlkHeader *oblk = blk;
        char *blkstart;
        char *blkend;
        VALGRIND_MAKE_MEM_DEFINED(blk, sizeof(Memento_BlkHeader));
        if (addr < (void *)oblk) {
            blk = blk->left;
            VALGRIND_MAKE_MEM_UNDEFINED(oblk, sizeof(Memento_BlkHeader));
            continue;
        }
        blkstart = (char *)MEMBLK_TOBLK(blk);
        blkend = &blkstart[blk->rawsize];
        if (addr >= (void *)(blkend + Memento_PostSize)) {
            blk = blk->right;
            VALGRIND_MAKE_MEM_UNDEFINED(oblk, sizeof(Memento_BlkHeader));
            continue;
        }
        if (flags) {
            if (((void *)blkstart <= addr) && (addr < (void *)blkend))
                *flags = 1;
            else if (((void *)blk <= addr) && (addr < (void *)blkstart))
                *flags = 2;
            else
                *flags = 3;
        }
        VALGRIND_MAKE_MEM_UNDEFINED(oblk, sizeof(Memento_BlkHeader));
        return blk;
    }
    return NULL;
}

#ifndef MEMENTO_LEAKONLY
/* Distrustful - check the block is a real one */
static int Memento_appBlockUser(Memento_Blocks    *blks,
                                int                (*app)(Memento_BlkHeader *,
                                                          void *),
                                void              *arg,
                                Memento_BlkHeader *b)
{
    int result;
    Memento_BlkHeader *head = find_enclosing_block(blks, b, NULL);
    if (head == NULL)
        return 0;

    VALGRIND_MAKE_MEM_DEFINED(head, sizeof(Memento_BlkHeader));
    VALGRIND_MAKE_MEM_DEFINED(MEMBLK_TOBLK(head),
                              head->rawsize + Memento_PostSize);
    result = app(head, arg);
    VALGRIND_MAKE_MEM_NOACCESS(MEMBLK_POSTPTR(head), Memento_PostSize);
    VALGRIND_MAKE_MEM_NOACCESS(head, sizeof(Memento_BlkHeader));
    return result;
}

static int Memento_appBlock(Memento_Blocks    *blks,
                            int                (*app)(Memento_BlkHeader *,
                                                      void *),
                            void              *arg,
                            Memento_BlkHeader *b)
{
    int result;
    (void)blks;
    VALGRIND_MAKE_MEM_DEFINED(b, sizeof(Memento_BlkHeader));
    VALGRIND_MAKE_MEM_DEFINED(MEMBLK_TOBLK(b),
                              b->rawsize + Memento_PostSize);
    result = app(b, arg);
    VALGRIND_MAKE_MEM_NOACCESS(MEMBLK_POSTPTR(b), Memento_PostSize);
    VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(Memento_BlkHeader));
    return result;
}
#endif /* MEMENTO_LEAKONLY */

static int showBlock(Memento_BlkHeader *b, int space)
{
    int seq;
    VALGRIND_MAKE_MEM_DEFINED(b, sizeof(Memento_BlkHeader));
    fprintf(stderr, FMTP":(size=" FMTZ ",num=%d)",
            MEMBLK_TOBLK(b), (FMTZ_CAST)b->rawsize, b->sequence);
    if (b->label)
        fprintf(stderr, "%c(%s)", space, b->label);
    if (b->flags & Memento_Flag_KnownLeak)
        fprintf(stderr, "(Known Leak)");
    seq = b->sequence;
    VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(Memento_BlkHeader));
    return seq;
}

static void blockDisplay(Memento_BlkHeader *b, int n)
{
    n++;
    while (n > 40)
    {
            fprintf(stderr, "*");
            n -= 40;
    }
    while(n > 0)
    {
        int i = n;
        if (i > 32)
            i = 32;
        n -= i;
        fprintf(stderr, "%s", &"                                "[32-i]);
    }
    showBlock(b, '\t');
    fprintf(stderr, "\n");
}

static int Memento_listBlock(Memento_BlkHeader *b,
                             void              *arg)
{
    size_t *counts = (size_t *)arg;
    blockDisplay(b, 0);
    counts[0]++;
    VALGRIND_MAKE_MEM_DEFINED(b, sizeof(Memento_BlkHeader));
    counts[1]+= b->rawsize;
    VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(Memento_BlkHeader));
    return 0;
}

static void doNestedDisplay(Memento_BlkHeader *b,
                            int depth)
{
    /* Try and avoid recursion if we can help it */
    do {
        Memento_BlkHeader *c = NULL;
        blockDisplay(b, depth);
        VALGRIND_MAKE_MEM_DEFINED(b, sizeof(Memento_BlkHeader));
        if (b->sibling) {
            c = b->child;
            b = b->sibling;
        } else {
            b = b->child;
            depth++;
        }
        VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(Memento_BlkHeader));
        if (c)
            doNestedDisplay(c, depth+1);
    } while (b);
}

static int ptrcmp(const void *a_, const void *b_)
{
    const char **a = (const char **)a_;
    const char **b = (const char **)b_;
    return (int)(*a-*b);
}

static
int Memento_listBlocksNested(void)
{
    int count, i;
    size_t size;
    Memento_BlkHeader *b, *prev;
    void **blocks, *minptr, *maxptr;
    intptr_t mask;

    /* Count the blocks */
    count = 0;
    size = 0;
    for (b = memento.used.head; b; b = b->next) {
        VALGRIND_MAKE_MEM_DEFINED(b, sizeof(*b));
        size += b->rawsize;
        count++;
    }

    if (memento.showDetailedBlocks)
    {
        /* Make our block list */
        blocks = MEMENTO_UNDERLYING_MALLOC(sizeof(void *) * count);
        if (blocks == NULL)
            return 1;

        /* Populate our block list */
        b = memento.used.head;
        minptr = maxptr = MEMBLK_TOBLK(b);
        mask = (intptr_t)minptr;
        for (i = 0; b; b = b->next, i++) {
            void *p = MEMBLK_TOBLK(b);
            mask &= (intptr_t)p;
            if (p < minptr)
                minptr = p;
            if (p > maxptr)
                maxptr = p;
            blocks[i] = p;
            b->flags &= ~Memento_Flag_HasParent;
            b->child   = NULL;
            b->sibling = NULL;
            b->prev    = NULL; /* parent */
        }
        qsort(blocks, count, sizeof(void *), ptrcmp);

        /* Now, calculate tree */
        for (b = memento.used.head; b; b = b->next) {
            char *p = MEMBLK_TOBLK(b);
            size_t end = (b->rawsize < MEMENTO_PTRSEARCH ? b->rawsize : MEMENTO_PTRSEARCH);
            size_t z;
            VALGRIND_MAKE_MEM_DEFINED(p, end);
            if (end > sizeof(void *)-1)
                end -= sizeof(void *)-1;
            else
                end = 0;
            for (z = MEMENTO_SEARCH_SKIP; z < end; z += sizeof(void *)) {
                void *q = *(void **)(&p[z]);
                void **r;

                /* Do trivial checks on pointer */
                if ((mask & (intptr_t)q) != mask || q < minptr || q > maxptr)
                    continue;

                /* Search for pointer */
                r = bsearch(&q, blocks, count, sizeof(void *), ptrcmp);
                if (r) {
                    /* Found child */
                    Memento_BlkHeader *child = MEMBLK_FROMBLK(*r);
                    Memento_BlkHeader *parent;

                    /* We're assuming tree structure, not graph - ignore second
                     * and subsequent pointers. */
                    if (child->prev != NULL) /* parent */
                        continue;
                    if (child->flags & Memento_Flag_HasParent)
                        continue;

                    /* Not interested in pointers to ourself! */
                    if (child == b)
                        continue;

                    /* We're also assuming acyclicness here. If this is one of
                     * our parents, ignore it. */
                    parent = b->prev; /* parent */
                    while (parent != NULL && parent != child)
                        parent = parent->prev; /* parent */
                    if (parent == child)
                        continue;

                    child->sibling = b->child;
                    b->child = child;
                    child->prev = b; /* parent */
                    child->flags |= Memento_Flag_HasParent;
                }
            }
        }

        /* Now display with nesting */
        for (b = memento.used.head; b; b = b->next) {
            if ((b->flags & Memento_Flag_HasParent) == 0)
            doNestedDisplay(b, 0);
        }

        MEMENTO_UNDERLYING_FREE(blocks);

        /* Now put the blocks back for valgrind, and restore the prev
         * and magic values. */
        prev = NULL;
        for (b = memento.used.head; b;) {
            Memento_BlkHeader *next = b->next;
            b->prev = prev;
            b->child = MEMENTO_CHILD_MAGIC;
            b->sibling = MEMENTO_SIBLING_MAGIC;
            prev = b;
            VALGRIND_MAKE_MEM_NOACCESS(b, sizeof(*b));
            b = next;
        }
    }

    fprintf(stderr, " Total number of blocks = %d\n", count);
    fprintf(stderr, " Total size of blocks = "FMTZ"\n", (FMTZ_CAST)size);

    return 0;
}

void Memento_listBlocks(void)
{
    MEMENTO_LOCK();
    fprintf(stderr, "Allocated blocks:\n");
    if (Memento_listBlocksNested())
    {
        size_t counts[2];
        counts[0] = 0;
        counts[1] = 0;
        Memento_appBlocks(&memento.used, Memento_listBlock, &counts[0]);
        fprintf(stderr, " Total number of blocks = "FMTZ"\n", (FMTZ_CAST)counts[0]);
        fprintf(stderr, " Total size of blocks = "FMTZ"\n", (FMTZ_CAST)counts[1]);
    }
    MEMENTO_UNLOCK();
}

static int Memento_listNewBlock(Memento_BlkHeader *b,
                                void              *arg)
{
    if (b->flags & Memento_Flag_OldBlock)
        return 0;
    b->flags |= Memento_Flag_OldBlock;
    return Memento_listBlock(b, arg);
}

void Memento_listNewBlocks(void)
{
    size_t counts[2];
    MEMENTO_LOCK();
    counts[0] = 0;
    counts[1] = 0;
    fprintf(stderr, "Blocks allocated and still extant since last list:\n");
    Memento_appBlocks(&memento.used, Memento_listNewBlock, &counts[0]);
    fprintf(stderr, "  Total number of blocks = "FMTZ"\n", (FMTZ_CAST)counts[0]);
    fprintf(stderr, "  Total size of blocks = "FMTZ"\n", (FMTZ_CAST)counts[1]);
    MEMENTO_UNLOCK();
}

typedef struct
{
    size_t counts[2];
    unsigned int phase;
} phased_t;

static int Memento_listPhasedBlock(Memento_BlkHeader *b,
                                   void              *arg)
{
    phased_t *phase = (phased_t *)arg;
    if ((b->flags & phase->phase) == 0)
        return 0;
    b->flags = (b->flags & ~Memento_Flag_PhaseMask) | ((b->flags >> 1) & Memento_Flag_PhaseMask);
    return Memento_listBlock(b, arg);
}

static int Memento_listNewPhasedBlock(Memento_BlkHeader *b,
                                      void              *arg)
{
    if ((b->flags & Memento_Flag_PhaseMask) != 0)
        return 0;
    b->flags |= Memento_Flag_LastPhase;
    return Memento_listBlock(b, arg);
}

static int Memento_startPhasing(Memento_BlkHeader *b,
                                void              *arg)
{
    b->flags |= *(int *)arg;
    return 0;
}

/* On the first call to this, we mark all blocks with the
 * lowest 'phase' bit, (call this phase m) so they will
 * never be reported.
 *
 * On subsequent calls, we:
 *   for (n = m-1; n > 0; n--)
 *     report all blocks in phase n, moving them to n+1.
 *   report all new blocks, and place them in phase 0.
 *
 * The upshot of this is that if you call Memento_listPhasedBlocks()
 * at a given point in the code, then you can watch for how long blocks
 * live between each time the code reaches that point.
 *
 * This is basically like Memento_listNewBlocks(), but allows for
 * the fact that sometimes blocks are freed just after the call.
 */
void Memento_listPhasedBlocks(void)
{
    phased_t phase;
    int num = 0;
    MEMENTO_LOCK();
    phase.phase = Memento_Flag_LastPhase;
    while ((phase.phase>>1) & Memento_Flag_PhaseMask)
        num++, phase.phase >>= 1;
    if (memento.phasing == 0)
    {
        fprintf(stderr, "Commencing Phasing:\n");
        memento.phasing = 1;
        Memento_appBlocks(&memento.used, Memento_startPhasing, &phase.phase);
    } else {
        phase.phase <<= 1;
        do
        {
            phase.counts[0] = 0;
            phase.counts[1] = 0;
            fprintf(stderr, "Blocks allocated and still extant: In phase %d (%x):\n", num, phase.phase);
            Memento_appBlocks(&memento.used, Memento_listPhasedBlock, &phase);
            fprintf(stderr, "  Total number of blocks = "FMTZ"\n", (FMTZ_CAST)phase.counts[0]);
            fprintf(stderr, "  Total size of blocks = "FMTZ"\n", (FMTZ_CAST)phase.counts[1]);
            phase.phase = phase.phase<<1;
            num--;
        }
        while (phase.phase != 0);
        phase.counts[0] = 0;
        phase.counts[1] = 0;
        fprintf(stderr, "Blocks allocated and still extant: In phase 0:\n", num, phase.phase);
        Memento_appBlocks(&memento.used, Memento_listNewPhasedBlock, &phase);
        fprintf(stderr, "  Total number of blocks = "FMTZ"\n", (FMTZ_CAST)phase.counts[0]);
        fprintf(stderr, "  Total size of blocks = "FMTZ"\n", (FMTZ_CAST)phase.counts[1]);
    }
    MEMENTO_UNLOCK();
}

static void Memento_endStats(void)
{
    fprintf(stderr, "Total memory malloced = "FMTZ" bytes\n", (FMTZ_CAST)memento.totalAlloc);
    fprintf(stderr, "Peak memory malloced = "FMTZ" bytes\n", (FMTZ_CAST)memento.peakAlloc);
    fprintf(stderr, FMTZ" mallocs, "FMTZ" frees, "FMTZ" reallocs\n", (FMTZ_CAST)memento.numMallocs,
            (FMTZ_CAST)memento.numFrees, (FMTZ_CAST)memento.numReallocs);
    fprintf(stderr, "Average allocation size "FMTZ" bytes\n", (FMTZ_CAST)
            (memento.numMallocs != 0 ? memento.totalAlloc/memento.numMallocs: 0));
#ifdef MEMENTO_DETAILS
    if (memento.hashCollisions)
        fprintf(stderr, "%d hash collisions\n", memento.hashCollisions);
#endif
}

void Memento_stats(void)
{
    MEMENTO_LOCK();
    fprintf(stderr, "Current memory malloced = "FMTZ" bytes\n", (FMTZ_CAST)memento.alloc);
    Memento_endStats();
    MEMENTO_UNLOCK();
}

#ifdef MEMENTO_DETAILS
static int showInfo(Memento_BlkHeader *b, void *arg)
{
    Memento_BlkDetails *details;

    (void)arg;

    fprintf(stderr, FMTP":(size="FMTZ",num=%d)",
            MEMBLK_TOBLK(b), (FMTZ_CAST)b->rawsize, b->sequence);
    if (b->label)
        fprintf(stderr, " (%s)", b->label);
    if (b->flags & Memento_Flag_KnownLeak)
        fprintf(stderr, "(Known Leak)");
    fprintf(stderr, "\nEvents:\n");

    for (details = b->details; details; details = details->next)
    {
        if (memento.hideMultipleReallocs &&
            details->type == Memento_EventType_realloc &&
            details->next &&
            details->next->type == Memento_EventType_realloc) {
            continue;
        }
        fprintf(stderr, "  Event %d (%s)\n", details->sequence, eventType[(int)details->type]);
        Memento_showHashedStacktrace(details->trace);
        if (memento.showDetailedBlocks > 0) {
            memento.showDetailedBlocks -= 1;
            if (memento.showDetailedBlocks == 0) {
                fprintf(stderr, "Stopping display of block details because memento.showDetailedBlocks is now zero.\n");
                return 1;
            }
        }
    }
    return 0;
}
#endif

void Memento_listBlockInfo(void)
{
#ifdef MEMENTO_DETAILS
    MEMENTO_LOCK();
    fprintf(stderr, "Details of allocated blocks:\n");
    Memento_appBlocks(&memento.used, showInfo, NULL);
    MEMENTO_UNLOCK();
#endif
}

void Memento_blockInfo(void *p)
{
#ifdef MEMENTO_DETAILS
    Memento_BlkHeader *blk;
    MEMENTO_LOCK();
    blk = find_enclosing_block(&memento.used, p, NULL);
    if (blk == NULL)
        blk = find_enclosing_block(&memento.free, p, NULL);
    if (blk)
        showInfo(blk, NULL);
    MEMENTO_UNLOCK();
#endif
}

static int Memento_nonLeakBlocksLeaked(void)
{
    Memento_BlkHeader *blk = memento.used.head;
    while (blk)
    {
        Memento_BlkHeader *next;
        int leaked;
        VALGRIND_MAKE_MEM_DEFINED(blk, sizeof(*blk));
        leaked = ((blk->flags & Memento_Flag_KnownLeak) == 0);
        next = blk->next;
        VALGRIND_MAKE_MEM_DEFINED(blk, sizeof(*blk));
        if (leaked)
            return 1;
        blk = next;
    }
    return 0;
}

static int Memento_checkAllMemoryInternal(void)
{
#ifndef MEMENTO_LEAKONLY
    int ret;

    MEMENTO_LOCK();
    ret = Memento_checkAllMemoryLocked();
    MEMENTO_UNLOCK();
    if (ret & 8) {
        Memento_breakpoint();
        return 1;
    }
#endif
    return 0;
}

void Memento_fin(void)
{
    int leaked = 0;
    Memento_checkAllMemoryInternal();
    if (!memento.segv)
    {
        Memento_endStats();
        if (Memento_nonLeakBlocksLeaked()) {
            Memento_listBlocks();
#ifdef MEMENTO_DETAILS
            fprintf(stderr, "\n");
            if (memento.showDetailedBlocks)
                Memento_listBlockInfo();
#endif
            Memento_breakpoint();
            leaked = 1;
        }
    }
    if (memento.squeezing) {
        if (memento.pattern == 0)
            fprintf(stderr, "Memory squeezing @ %d complete%s\n", memento.squeezeAt, memento.segv ? " (with SEGV)" : (leaked ? " (with leaks)" : ""));
        else
            fprintf(stderr, "Memory squeezing @ %d (%d) complete%s\n", memento.squeezeAt, memento.pattern, memento.segv ? " (with SEGV)" : (leaked ? " (with leaks)" : ""));
    } else if (memento.segv) {
        fprintf(stderr, "Memento completed (with SEGV)\n");
    }
    if (memento.failing)
    {
        fprintf(stderr, "MEMENTO_FAILAT=%d\n", memento.failAt);
        fprintf(stderr, "MEMENTO_PATTERN=%d\n", memento.pattern);
    }
    if (memento.nextFailAt != 0)
    {
        fprintf(stderr, "MEMENTO_NEXTFAILAT=%d\n", memento.nextFailAt);
        fprintf(stderr, "MEMENTO_NEXTPATTERN=%d\n", memento.nextPattern);
    }
    if (Memento_nonLeakBlocksLeaked() && memento.abortOnLeak) {
        fprintf(stderr, "Calling abort() because blocks were leaked and MEMENTO_ABORT_ON_LEAK is set.\n");
        abort();
    }
}

/* Reads number from <text> using strtol().
 *
 * Params:
 *     text:
 *         text to read.
 *     out:
 *         pointer to output value.
 *     relative:
 *         *relative set to 1 if <text> starts with '+' or '-', else set to 0.
 *     end:
 *         *end is set to point to next unread character after number.
 *
 * Returns 0 on success, else -1.
 */
static int read_number(const char *text, int *out, int *relative, char **end)
{
    if (text[0] == '+' || text[0] == '-')
        *relative = 1;
    else
        *relative = 0;
    errno = 0;
    *out = (int)strtol(text, end, 0 /*base*/);
    if (errno || *end == text)
    {
        fprintf(stderr, "Failed to parse number at start of '%s'.\n", text);
        return -1;
    }
    if (0)
         fprintf(stderr, "text='%s': *out=%i *relative=%i\n",
                 text, *out, *relative);
    return 0;
}

/* Reads number plus optional delta value from <text>.
 *
 * Evaluates <number> or <number>[+|-<delta>]. E.g. text='1234+2' sets *out=1236,
 * text='1234-1' sets *out=1233.
 *
 * Params:
 *     text:
 *         text to read.
 *     out:
 *         pointer to output value.
 *     end:
 *         *end is set to point to next unread character after number.
 *
 * Returns 0 on success, else -1.
 */
static int read_number_delta(const char *text, int *out, char **end)
{
    int e;
    int relative;

    e = read_number(text, out, &relative, end);
    if (e)
        return e;
    if (relative) {
        fprintf(stderr, "Base number should not start with '+' or '-' at start of '%s'.\n",
                text);
        return -1;
    }
    if (*end) {
        if (**end == '-' || **end == '+') {
            int delta;
            e = read_number(*end, &delta, &relative, end);
            if (e)
                return e;
            *out += delta;
        }
    }
    if (0) fprintf(stderr, "text='%s': *out=%i\n", text, *out);

    return 0;
}

/* Reads range.
 *
 * E.g.:
 *     text='115867-2' sets *begin=115865 *end=115866.
 *     text='115867-1..+3' sets *begin=115866 *end=115869.
 *
 * Supported patterns for text:
 *     <range>
 *         <value>             - returns *begin=value *end=*begin+1.
 *         <value1>..<value2>  - returns *begin=value1 *end=value2.
 *         <value>..+<number>  - returns *begin=value *end=*begin+number.
 *     <value>
 *         <number>
 *         <number>+<number>
 *         <number>-<number>
 *
 *     <number>: [0-9]+
 *
 * If not specified, *end defaults to *begin+1.
 *
 * Returns 0 on success, else -1, with *string_end pointing to first unused
 * character.
 */
static int read_number_range(const char *text, int *begin, int *end, char **string_end)
{
    int e;
    e = read_number_delta(text, begin, string_end);
    if (e)
        return e;
    if (string_end && (*string_end)[0] == '.' && (*string_end)[1] == '.') {
        int relative;
        e = read_number((*string_end) + 2, end, &relative, string_end);
        if (e)
            return e;
        if (relative)
            *end += *begin;
    } else {
        *end = *begin + 1;
    }
    if (*end < *begin) {
        fprintf(stderr, "Range %i..%i has negative extent, at start of '%s'.\n",
                *begin, *end, text);
        return -1;
    }
    if (0) fprintf(stderr, "text='%s': *begin=%i *end=%i\n", text, *begin, *end);

    return 0;
}

/* Format: <range>[,<range>]+
 *
 * For description of <range>, see read_number_range() above.
 *
 * E.g.:
 *     MEMENTO_SQUEEZES=1234-2..+4,2345,2350..+2
 */
static int Memento_add_squeezes(const char *text)
{
    int e = 0;
    for(;;) {
        int     begin;
        int     end;
        char   *string_end;
        if (!*text)
            break;
        e = read_number_range(text, &begin, &end, &string_end);
        if (e)
            break;
        if (*string_end && *string_end != ',') {
            fprintf(stderr, "Expecting comma at start of '%s'.\n", string_end);
            e = -1;
            break;
        }
        fprintf(stderr, "Adding squeeze range %i..%i.\n",
                begin, end);
        memento.squeezes_num += 1;
        memento.squeezes = MEMENTO_UNDERLYING_REALLOC(
                memento.squeezes,
                memento.squeezes_num * sizeof(*memento.squeezes)
                );
        if (!memento.squeezes) {
            fprintf(stderr, "Failed to allocate memory for memento.squeezes_num=%i\n",
                    memento.squeezes_num);
            e = -1;
            break;
        }
        memento.squeezes[memento.squeezes_num-1].begin = begin;
        memento.squeezes[memento.squeezes_num-1].end = end;

        if (*string_end == 0)
            break;
        text = string_end + 1;
    }

    return e;
}

#if defined(_WIN32) || defined(_WIN64)
static int Memento_fin_win(void)
{
    Memento_fin();
    return 0;
}
#endif

static void Memento_init(void)
{
    char *env;
    memset(&memento, 0, sizeof(memento));
    memento.inited    = 1;
    memento.used.head = NULL;
    memento.used.tail = NULL;
    memento.free.head = NULL;
    memento.free.tail = NULL;
    memento.sequence  = 0;
    memento.countdown = 1024;
    memento.squeezes  = NULL;
    memento.squeezes_num = 0;
    memento.squeezes_pos = 0;

    env = getenv("MEMENTO_FAILAT");
    memento.failAt = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_BREAKAT");
    memento.breakAt = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_PARANOIA");
    memento.paranoia = (env ? atoi(env) : 0);
    if (memento.paranoia == 0)
        memento.paranoia = -1024;

    env = getenv("MEMENTO_PARANOIDAT");
    memento.paranoidAt = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_SQUEEZEAT");
    memento.squeezeAt = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_PATTERN");
    memento.pattern = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_SHOW_DETAILED_BLOCKS");
    memento.showDetailedBlocks = (env ? atoi(env) : -1);

    env = getenv("MEMENTO_HIDE_MULTIPLE_REALLOCS");
    memento.hideMultipleReallocs = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_ABORT_ON_LEAK");
    memento.abortOnLeak = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_ABORT_ON_CORRUPTION");
    memento.abortOnCorruption = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_SQUEEZES");
    if (env) {
        int e;
        fprintf(stderr, "Parsing squeeze ranges in MEMENTO_SQUEEZES=%s\n", env);
        e = Memento_add_squeezes(env);
        if (e) {
            fprintf(stderr, "Failed to parse MEMENTO_SQUEEZES=%s\n", env);
            exit(1);
        }
    }

    env = getenv("MEMENTO_MAXMEMORY");
    memento.maxMemory = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_VERBOSE");
    memento.verbose = (env ? atoi(env) : 0);

    env = getenv("MEMENTO_IGNORENEWDELETE");
    memento.ignoreNewDelete = (env ? atoi(env) : 0);

    /* For Windows, we can _onexit rather than atexit. This is because
     * _onexit registered handlers are called when the DLL that they are
     * in is freed, rather than on complete closedown. This gives us a
     * higher chance of seeing Memento_fin called in a state when the
     * stack backtracing mechanism can still work. */
#if defined(_WIN32) || defined(_WIN64)
    _onexit(Memento_fin_win);
#else
    atexit(Memento_fin);
#endif

    Memento_initMutex(&memento.mutex);

    Memento_initStacktracer();

    Memento_breakpoint();
}

static void Memento_infoLocked(void *addr)
{
#ifdef MEMENTO_DETAILS
    Memento_BlkHeader *blk;

    blk = find_enclosing_block(&memento.used, addr, NULL);
    if (blk == NULL)
        blk = find_enclosing_block(&memento.free, addr, NULL);
    if (blk != NULL)
        showInfo(blk, NULL);
#else
    printf("Memento not compiled with details support\n");
#endif
}

void Memento_info(void *addr)
{
    MEMENTO_LOCK();
    Memento_infoLocked(addr);
    MEMENTO_UNLOCK();
}

#ifdef MEMENTO_HAS_FORK
#include <unistd.h>
#include <sys/wait.h>
#include <time.h>
#ifdef MEMENTO_STACKTRACE_METHOD
#if MEMENTO_STACKTRACE_METHOD == 1
#include <signal.h>
#endif
#endif

/* FIXME: Find some portable way of getting this */
/* MacOSX has 10240, Ubuntu seems to have 256 */
#ifndef OPEN_MAX
#define OPEN_MAX 10240
#endif

/* stashed_map[j] = i means that file descriptor i-1 was duplicated to j */
int stashed_map[OPEN_MAX];

static void Memento_signal(int sig)
{
    (void)sig;
    fprintf(stderr, "SEGV at:\n");
    memento.segv = 1;
    Memento_bt_internal(0);

    exit(1);
}

static int squeeze(void)
{
    pid_t pid;
    int i, status;

    if (memento.patternBit < 0)
        return 1;
    if (memento.squeezing && memento.patternBit >= MEMENTO_MAXPATTERN)
        return 1;

    if (memento.patternBit == 0)
        memento.squeezeAt = memento.sequence;

    if (!memento.squeezing) {
        fprintf(stderr, "Memory squeezing @ %d\n", memento.squeezeAt);
    } else
        fprintf(stderr, "Memory squeezing @ %d (%x,%x)\n", memento.squeezeAt, memento.pattern, memento.patternBit);

    /* When we fork below, the child is going to snaffle all our file pointers
     * and potentially corrupt them. Let's make copies of all of them before
     * we fork, so we can restore them when we restart. */
    for (i = 0; i < OPEN_MAX; i++) {
        if (stashed_map[i] == 0) {
            int j = dup(i);
            if (j >= 0) {
                stashed_map[j] = i+1;
            }
        }
    }

    fprintf(stderr, "Failing at:\n");
    Memento_bt_internal(2);
    pid = fork();
    if (pid == 0) {
        /* Child */
        signal(SIGSEGV, Memento_signal);
        /* Close the dup-licated fds to avoid them getting corrupted by faulty
         * code. */
        for (i = 0; i < OPEN_MAX; i++) {
            if (stashed_map[i] != 0) {
                /* We close duplicated fds, just in case child has some bad
                 * code that modifies/closes random fds. */
                close(i);
            }
        }
        /* In the child, we always fail the next allocation. */
        if (memento.patternBit == 0) {
            memento.patternBit = 1;
        } else
            memento.patternBit <<= 1;
        memento.squeezing = 1;

        /* This is necessary to allow Memento_failThisEventLocked() near the
         * end to do 'return squeeze();'. */
        memento.squeezes_num = 0;

        return 1;
    }

    /* In the parent if we hit another allocation, pass it (and record the
     * fact we passed it in the pattern. */
    memento.pattern |= memento.patternBit;
    memento.patternBit <<= 1;

    /* Wait for pid to finish, with a timeout. */
    {
        struct timespec tm = { 0, 10 * 1000 * 1000 }; /* 10ms = 100th sec */
        int timeout = 30 * 1000 * 1000; /* time out in microseconds! */
        while (waitpid(pid, &status, WNOHANG) == 0) {
            nanosleep(&tm, NULL);
            timeout -= (int)(tm.tv_nsec/1000);
            tm.tv_nsec *= 2;
            if (tm.tv_nsec > 999999999)
                tm.tv_nsec = 999999999;
            if (timeout <= 0) {
                char text[32];
                fprintf(stderr, "Child is taking a long time to die. Killing it.\n");
                sprintf(text, "kill %d", pid);
                system(text);
                break;
            }
        }
    }

    if (status != 0) {
        fprintf(stderr, "Child status=%d\n", status);
    }

    /* Put the files back */
    for (i = 0; i < OPEN_MAX; i++) {
        if (stashed_map[i] != 0) {
            dup2(i, stashed_map[i]-1);
            close(i);
            stashed_map[i] = 0;
        }
    }

    return 0;
}
#else
#include <signal.h>

static void Memento_signal(int sig)
{
    (void)sig;
    memento.segv = 1;
    /* If we just return from this function the SEGV will be unhandled, and
     * we'll launch into whatever JIT debugging system the OS provides. At
     * least fprintf(stderr, something useful first. If MEMENTO_NOJIT is set, then
     * just exit to avoid the JIT (and get the usual atexit handling). */
    if (getenv("MEMENTO_NOJIT"))
        exit(1);
    else
        Memento_fin();
}

static int squeeze(void)
{
    fprintf(stderr, "Memento memory squeezing disabled as no fork!\n");
    return 0;
}
#endif

static void Memento_startFailing(void)
{
    if (!memento.failing) {
        fprintf(stderr, "Starting to fail...\n");
        Memento_bt();
        fflush(stderr);
        memento.failing = 1;
        memento.failAt = memento.sequence;
        memento.nextFailAt = memento.sequence+1;
        memento.patternBit = 0;
        signal(SIGSEGV, Memento_signal);
        signal(SIGABRT, Memento_signal);
        Memento_breakpointLocked();
    }
}

static int Memento_event(void)
{
    int ret = 0;

    memento.sequence++;
    if ((memento.sequence >= memento.paranoidAt) && (memento.paranoidAt != 0)) {
        memento.paranoia = 1;
        memento.countdown = 1;
    }
    if (--memento.countdown == 0) {
        ret = Memento_checkAllMemoryLocked();
        ret = (ret & 8) != 0;
        if (memento.paranoia > 0)
            memento.countdown = memento.paranoia;
        else
        {
            memento.countdown = -memento.paranoia;
            if (memento.paranoia > INT_MIN/2)
                memento.paranoia *= 2;
        }
    }

    if (memento.sequence == memento.breakAt) {
        fprintf(stderr, "Breaking at event %d\n", memento.breakAt);
        return 1;
    }
    return ret;
}

int Memento_sequence(void)
{
    return memento.sequence;
}

int Memento_breakAt(int event)
{
    MEMENTO_LOCK();
    memento.breakAt = event;
    MEMENTO_UNLOCK();
    return event;
}

static void *safe_find_block(void *ptr)
{
    Memento_BlkHeader *block;
    int valid;

    if (ptr == NULL)
        return NULL;

    block = MEMBLK_FROMBLK(ptr);
    /* Sometimes wrapping allocators can mean Memento_label
     * is called with a value within the block, rather than
     * at the start of the block. If we detect this, find it
     * the slow way. */
    VALGRIND_MAKE_MEM_DEFINED(&block->child, sizeof(block->child));
    VALGRIND_MAKE_MEM_DEFINED(&block->sibling, sizeof(block->sibling));
    valid = (block->child == MEMENTO_CHILD_MAGIC &&
             block->sibling == MEMENTO_SIBLING_MAGIC);
    if (valid) {
        VALGRIND_MAKE_MEM_NOACCESS(&block->child, sizeof(block->child));
        VALGRIND_MAKE_MEM_NOACCESS(&block->sibling, sizeof(block->sibling));
    }
    if (!valid)
    {
        block = find_enclosing_block(&memento.used, ptr, NULL);
    }
    return block;
}

void *Memento_label(void *ptr, const char *label)
{
    Memento_BlkHeader *block;

    if (ptr == NULL)
        return NULL;
    MEMENTO_LOCK();
    block = safe_find_block(ptr);
    if (block != NULL)
    {
        VALGRIND_MAKE_MEM_DEFINED(&block->label, sizeof(block->label));
        block->label = label;
        VALGRIND_MAKE_MEM_NOACCESS(&block->label, sizeof(block->label));
    }
    MEMENTO_UNLOCK();

    if (memento.verboseNewlineSuppressed) {
        if (memento.lastVerbosePtr == block) {
            fprintf(stderr, " (%s)", label);
        }
    }

    return ptr;
}

void Memento_tick(void)
{
    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();
    MEMENTO_UNLOCK();
}

static int Memento_failThisEventLocked(void)
{
    int failThisOne;

    if (Memento_event()) Memento_breakpointLocked();

    if (!memento.squeezing && memento.squeezes_num) {
        /* Move to next relevant squeeze region if appropriate. */
        for ( ; memento.squeezes_pos != memento.squeezes_num; memento.squeezes_pos++) {
            if (memento.sequence < memento.squeezes[memento.squeezes_pos].end)
                break;
        }

        /* See whether memento.sequence is within this squeeze region. */
        if (memento.squeezes_pos < memento.squeezes_num) {
            int begin = memento.squeezes[memento.squeezes_pos].begin;
            int end   = memento.squeezes[memento.squeezes_pos].end;
            if (memento.sequence >= begin && memento.sequence < end) {
                if (1) {
                    fprintf(stderr,
                            "squeezes match memento.sequence=%i: memento.squeezes_pos=%i/%i %i..%i\n",
                            memento.sequence,
                            memento.squeezes_pos,
                            memento.squeezes_num,
                            memento.squeezes[memento.squeezes_pos].begin,
                            memento.squeezes[memento.squeezes_pos].end
                            );
                }
                return squeeze();
            }
        }
    }

    if ((memento.sequence >= memento.failAt) && (memento.failAt != 0))
        Memento_startFailing();
    if ((memento.squeezes_num==0) && (memento.sequence >= memento.squeezeAt) && (memento.squeezeAt != 0))
        return squeeze();

    if (!memento.failing)
        return 0;
    failThisOne = ((memento.patternBit & memento.pattern) == 0);
    /* If we are failing, and we've reached the end of the pattern and we've
     * still got bits available in the pattern word, and we haven't already
     * set a nextPattern, then extend the pattern. */
    if (memento.failing &&
        ((~(memento.patternBit-1) & memento.pattern) == 0) &&
        (memento.patternBit != 0) &&
        memento.nextPattern == 0)
    {
        /* We'll fail this one, and set the 'next' one to pass it. */
        memento.nextFailAt = memento.failAt;
        memento.nextPattern = memento.pattern | memento.patternBit;
    }
    memento.patternBit = (memento.patternBit ? memento.patternBit << 1 : 1);

    return failThisOne;
}

int Memento_failThisEvent(void)
{
    int ret;

    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    ret = Memento_failThisEventLocked();
    MEMENTO_UNLOCK();
    return ret;
}

static void *do_malloc(size_t s, int et)
{
    Memento_BlkHeader *memblk;
    size_t             smem = MEMBLK_SIZE(s);
#ifdef MEMENTO_DETAILS
    Memento_hashedST  *st;
#endif

    if (Memento_failThisEventLocked()) {
        errno = ENOMEM;
        return NULL;
    }

    if (s == 0)
        return NULL;

    memento.numMallocs++;

    if (memento.maxMemory != 0 && memento.alloc + s > memento.maxMemory) {
        errno = ENOMEM;
        return NULL;
    }

#ifdef MEMENTO_DETAILS
    st = Memento_getHashedStacktrace();
#endif

    memblk = MEMENTO_UNDERLYING_MALLOC(smem);
    if (memblk == NULL) {
        switch (memento.verbose) {
        default:
            if (memento.verboseNewlineSuppressed)
                fprintf(stderr, "\n");
            fprintf(stderr, "%s failed (size="FMTZ",num=%d",
                    eventType[et], (FMTZ_CAST)s, memento.sequence);
#ifdef MEMENTO_DETAILS
            fprintf(stderr, ",st=%x", st->hash);
#endif
            fprintf(stderr, ")");
            memento.verboseNewlineSuppressed = 1;
            memento.lastVerbosePtr = memblk;
            break;
        case 2:
            if (memento.verboseNewlineSuppressed)
                fprintf(stderr, "\n");
            fprintf(stderr, "%s failed (size="FMTZ"",
                    eventType[et], (FMTZ_CAST)s);
#ifdef MEMENTO_DETAILS
            fprintf(stderr, ",st=%x", st->hash);
#endif
            fprintf(stderr, ")");
            memento.verboseNewlineSuppressed = 1;
            memento.lastVerbosePtr = memblk;
            break;
        case 0:
            break;
        }
        return NULL;
    }

    memento.alloc      += s;
    memento.totalAlloc += s;
    if (memento.peakAlloc < memento.alloc)
        memento.peakAlloc = memento.alloc;
#ifndef MEMENTO_LEAKONLY
    memset(MEMBLK_TOBLK(memblk), MEMENTO_ALLOCFILL, s);
#endif
    memblk->rawsize       = s;
    memblk->sequence      = memento.sequence;
    memblk->lastCheckedOK = memblk->sequence;
    memblk->flags         = 0;
    memblk->label         = 0;
    memblk->child         = MEMENTO_CHILD_MAGIC;
    memblk->sibling       = MEMENTO_SIBLING_MAGIC;
#ifdef MEMENTO_DETAILS
    memblk->details       = NULL;
    memblk->details_tail  = &memblk->details;
    Memento_storeDetails(memblk, et, st);
#endif /* MEMENTO_DETAILS */
    Memento_addBlockHead(&memento.used, memblk, 0);

    if (memento.leaking > 0)
        memblk->flags |= Memento_Flag_KnownLeak;

    switch (memento.verbose) {
    default:
        if (memento.verboseNewlineSuppressed)
            fprintf(stderr, "\n");
        fprintf(stderr, "%s "FMTP":(size="FMTZ",num=%d",
                eventType[et],
                MEMBLK_TOBLK(memblk), (FMTZ_CAST)memblk->rawsize, memblk->sequence);
#ifdef MEMENTO_DETAILS
        fprintf(stderr, ",st=%x", st->hash);
#endif
        if (memblk->label)
            fprintf(stderr, ") (%s", memblk->label);
        fprintf(stderr, ")");
        memento.verboseNewlineSuppressed = 1;
        memento.lastVerbosePtr = memblk;
        break;
    case 2:
        if (memento.verboseNewlineSuppressed)
            fprintf(stderr, "\n");
        fprintf(stderr, "%s (size="FMTZ"",
                eventType[et],
                (FMTZ_CAST)memblk->rawsize);
#ifdef MEMENTO_DETAILS
        fprintf(stderr, ",st=%x", st->hash);
#endif
        if (memblk->label)
            fprintf(stderr, ") (%s", memblk->label);
        fprintf(stderr, ")");
        memento.verboseNewlineSuppressed = 1;
        memento.lastVerbosePtr = memblk;
        break;
    case 0:
        break;
    }

    return MEMBLK_TOBLK(memblk);
}

char *Memento_strdup(const char *text)
{
    size_t len = strlen(text) + 1;
    char *ret;

    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    ret = do_malloc(len, Memento_EventType_strdup);
    MEMENTO_UNLOCK();

    if (ret != NULL)
        memcpy(ret, text, len);

    return ret;
}

#if !defined(MEMENTO_GS_HACKS) && !defined(MEMENTO_MUPDF_HACKS)
int Memento_asprintf(char **ret, const char *format, ...)
{
    va_list va;
    int n;
    int n2;

    if (!memento.inited)
        Memento_init();

    va_start(va, format);
    n = vsnprintf(NULL, 0, format, va);
    va_end(va);
    if (n < 0)
        return n;

    MEMENTO_LOCK();
    *ret = do_malloc(n+1, Memento_EventType_asprintf);
    MEMENTO_UNLOCK();
    if (*ret == NULL)
        return -1;

    va_start(va, format);
    n2 = vsnprintf(*ret, n + 1, format, va);
    va_end(va);

    return n2;
}

int Memento_vasprintf(char **ret, const char *format, va_list ap)
{
    int n;
    va_list ap2;
    va_copy(ap2, ap);

    if (!memento.inited)
        Memento_init();

    n = vsnprintf(NULL, 0, format, ap);
    if (n < 0) {
        va_end(ap2);
        return n;
    }

    MEMENTO_LOCK();
    *ret = do_malloc(n+1, Memento_EventType_vasprintf);
    MEMENTO_UNLOCK();
    if (*ret == NULL) {
        va_end(ap2);
        return -1;
    }

    n = vsnprintf(*ret, n + 1, format, ap2);
    va_end(ap2);

    return n;
}
#endif

void *Memento_malloc(size_t s)
{
    void *ret;

    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    ret = do_malloc(s, Memento_EventType_malloc);
    MEMENTO_UNLOCK();

    return ret;
}

void *Memento_calloc(size_t n, size_t s)
{
    void *block;

    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    block = do_malloc(n*s, Memento_EventType_calloc);
    MEMENTO_UNLOCK();
    if (block)
        memset(block, 0, n*s);

    return block;
}

#ifdef MEMENTO_TRACKREFS
static void do_reference(Memento_BlkHeader *blk, int event)
{
#ifdef MEMENTO_DETAILS
    Memento_hashedST *st = Memento_getHashedStacktrace();
    Memento_storeDetails(blk, event, st);
#endif /* MEMENTO_DETAILS */
}
#endif

static int checkPointerOrNullLocked(void *blk)
{
    if (blk == NULL)
        return 0;
    if (blk == MEMENTO_PREFILL_PTR)
        fprintf(stderr, "Prefill value found as pointer - buffer underrun?\n");
    else if (blk == MEMENTO_POSTFILL_PTR)
        fprintf(stderr, "Postfill value found as pointer - buffer overrun?\n");
    else if (blk == MEMENTO_ALLOCFILL_PTR)
        fprintf(stderr, "Allocfill value found as pointer - use of uninitialised value?\n");
    else if (blk == MEMENTO_FREEFILL_PTR)
        fprintf(stderr, "Allocfill value found as pointer - use after free?\n");
    else
        return 0;
#ifdef MEMENTO_DETAILS
    fprintf(stderr, "Current backtrace:\n");
    Memento_bt();
    fprintf(stderr, "History:\n");
    Memento_infoLocked(blk);
#endif
    Memento_breakpointLocked();
    return 1;
}

int Memento_checkPointerOrNull(void *blk)
{
    int ret;
    MEMENTO_LOCK();
    ret = checkPointerOrNullLocked(blk);
    MEMENTO_UNLOCK();
    return ret;
}

static int checkBytePointerOrNullLocked(void *blk)
{
    unsigned char i;
    if (blk == NULL)
        return 0;
    checkPointerOrNullLocked(blk);

    i = *(unsigned char *)blk;

    if (i == MEMENTO_PREFILL_UBYTE)
        fprintf(stderr, "Prefill value found - buffer underrun?\n");
    else if (i == MEMENTO_POSTFILL_UBYTE)
        fprintf(stderr, "Postfill value found - buffer overrun?\n");
    else if (i == MEMENTO_ALLOCFILL_UBYTE)
        fprintf(stderr, "Allocfill value found - use of uninitialised value?\n");
    else if (i == MEMENTO_FREEFILL_UBYTE)
        fprintf(stderr, "Allocfill value found - use after free?\n");
    else
        return 0;
#ifdef MEMENTO_DETAILS
    fprintf(stderr, "Current backtrace:\n");
    Memento_bt();
    fprintf(stderr, "History:\n");
    Memento_infoLocked(blk);
#endif
    Memento_breakpointLocked();
    return 1;
}

int Memento_checkBytePointerOrNull(void *blk)
{
    int ret;
    MEMENTO_LOCK();
    ret = checkBytePointerOrNullLocked(blk);
    MEMENTO_UNLOCK();
    return ret;
}

static int checkShortPointerOrNullLocked(void *blk)
{
    unsigned short i;
    if (blk == NULL)
        return 0;
    checkPointerOrNullLocked(blk);

    i = *(unsigned short *)blk;

    if (i == MEMENTO_PREFILL_USHORT)
        fprintf(stderr, "Prefill value found - buffer underrun?\n");
    else if (i == MEMENTO_POSTFILL_USHORT)
        fprintf(stderr, "Postfill value found - buffer overrun?\n");
    else if (i == MEMENTO_ALLOCFILL_USHORT)
        fprintf(stderr, "Allocfill value found - use of uninitialised value?\n");
    else if (i == MEMENTO_FREEFILL_USHORT)
        fprintf(stderr, "Allocfill value found - use after free?\n");
    else
        return 0;
#ifdef MEMENTO_DETAILS
    fprintf(stderr, "Current backtrace:\n");
    Memento_bt();
    fprintf(stderr, "History:\n");
    Memento_infoLocked(blk);
#endif
    Memento_breakpointLocked();
    return 1;
}

int Memento_checkShortPointerOrNull(void *blk)
{
    int ret;
    MEMENTO_LOCK();
    ret = checkShortPointerOrNullLocked(blk);
    MEMENTO_UNLOCK();
    return ret;
}

static int checkIntPointerOrNullLocked(void *blk)
{
    unsigned int i;
    if (blk == NULL)
        return 0;
    checkPointerOrNullLocked(blk);

    i = *(unsigned int *)blk;

    if (i == MEMENTO_PREFILL_UINT)
        fprintf(stderr, "Prefill value found - buffer underrun?\n");
    else if (i == MEMENTO_POSTFILL_UINT)
        fprintf(stderr, "Postfill value found - buffer overrun?\n");
    else if (i == MEMENTO_ALLOCFILL_UINT)
        fprintf(stderr, "Allocfill value found - use of uninitialised value?\n");
    else if (i == MEMENTO_FREEFILL_UINT)
        fprintf(stderr, "Allocfill value found - use after free?\n");
    else
        return 0;
#ifdef MEMENTO_DETAILS
    fprintf(stderr, "Current backtrace:\n");
    Memento_bt();
    fprintf(stderr, "History:\n");
    Memento_infoLocked(blk);
#endif
    Memento_breakpointLocked();
    return 1;
}

int Memento_checkIntPointerOrNull(void *blk)
{
    int ret;
    MEMENTO_LOCK();
    ret = checkIntPointerOrNullLocked(blk);
    MEMENTO_UNLOCK();
    return ret;
}

#ifdef MEMENTO_TRACKREFS
static void *do_takeRef(void *blk)
{
    do_reference(safe_find_block(blk), Memento_EventType_takeRef);
    return blk;
}

static void *do_takeRefAndUnlock(void *blk)
{
    do_reference(safe_find_block(blk), Memento_EventType_takeRef);
    MEMENTO_UNLOCK();
    return blk;
}

static void *do_dropRef(void *blk)
{
    do_reference(safe_find_block(blk), Memento_EventType_dropRef);
    return blk;
}

static void *do_dropRefAndUnlock(void *blk)
{
    do_reference(safe_find_block(blk), Memento_EventType_dropRef);
    MEMENTO_UNLOCK();
    return blk;
}
#endif

void *Memento_takeByteRef(void *blk)
{
#ifdef MEMENTO_TRACKREFS
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();

    if (!blk) {
        MEMENTO_UNLOCK();
        return NULL;
    }

    (void)checkBytePointerOrNullLocked(blk);

    return do_takeRefAndUnlock(blk);
#else
    return blk;
#endif
}

void *Memento_takeShortRef(void *blk)
{
#ifdef MEMENTO_TRACKREFS
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();

    if (!blk) {
        MEMENTO_UNLOCK();
        return NULL;
    }

    (void)checkShortPointerOrNullLocked(blk);

    return do_takeRefAndUnlock(blk);
#else
    return blk;
#endif
}

void *Memento_takeIntRef(void *blk)
{
#ifdef MEMENTO_TRACKREFS
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();

    if (!blk) {
        MEMENTO_UNLOCK();
        return NULL;
    }

    (void)checkIntPointerOrNullLocked(blk);

    return do_takeRefAndUnlock(blk);
#else
    return blk;
#endif
}

void *Memento_takeRef(void *blk)
{
#ifdef MEMENTO_TRACKREFS
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();

    if (!blk) {
        MEMENTO_UNLOCK();
        return NULL;
    }

    return do_takeRefAndUnlock(blk);
#else
    return blk;
#endif
}

void *Memento_dropByteRef(void *blk)
{
#ifdef MEMENTO_TRACKREFS
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();

    if (!blk) {
        MEMENTO_UNLOCK();
        return NULL;
    }

    checkBytePointerOrNullLocked(blk);

    return do_dropRefAndUnlock(blk);
#else
    return blk;
#endif
}

void *Memento_dropShortRef(void *blk)
{
#ifdef MEMENTO_TRACKREFS
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();

    if (!blk) {
        MEMENTO_UNLOCK();
        return NULL;
    }

    checkShortPointerOrNullLocked(blk);

    return do_dropRefAndUnlock(blk);
#else
    return blk;
#endif
}

void *Memento_dropIntRef(void *blk)
{
#ifdef MEMENTO_TRACKREFS
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();

    if (!blk) {
        MEMENTO_UNLOCK();
        return NULL;
    }

    checkIntPointerOrNullLocked(blk);

    return do_dropRefAndUnlock(blk);
#else
    return blk;
#endif
}

void *Memento_dropRef(void *blk)
{
#ifdef MEMENTO_TRACKREFS
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();

    if (!blk) {
        MEMENTO_UNLOCK();
        return NULL;
    }

    return do_dropRefAndUnlock(blk);
#else
    return blk;
#endif
}

void *Memento_adjustRef(void *blk, int adjust)
{
#ifdef MEMENTO_TRACKREFS
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    if (Memento_event()) Memento_breakpointLocked();

    if (blk == NULL) {
        MEMENTO_UNLOCK();
        return NULL;
    }

    while (adjust > 0)
    {
        do_takeRef(blk);
        adjust--;
    }
    while (adjust < 0)
    {
        do_dropRef(blk);
        adjust++;
    }

    MEMENTO_UNLOCK();
#endif
    return blk;
}

void *Memento_reference(void *blk)
{
#ifdef MEMENTO_TRACKREFS
    if (!blk)
        return NULL;

    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    do_reference(safe_find_block(blk), Memento_EventType_reference);
    MEMENTO_UNLOCK();
#endif
    return blk;
}

/* Treat blocks from the user with suspicion, and check them the slow
 * but safe way. */
static int checkBlockUser(Memento_BlkHeader *memblk, const char *action)
{
#ifndef MEMENTO_LEAKONLY
    BlkCheckData data;

    memset(&data, 0, sizeof(data));
    Memento_appBlockUser(&memento.used, Memento_Internal_checkAllocedBlock,
                         &data, memblk);
    if (!data.found) {
        /* Failure! */
        fprintf(stderr, "Attempt to %s block ", action);
        showBlock(memblk, 32);
        fprintf(stderr, "\n");
        Memento_breakpointLocked();
        return 1;
    } else if (data.preCorrupt || data.postCorrupt) {
        fprintf(stderr, "Block ");
        showBlock(memblk, ' ');
        fprintf(stderr, " found to be corrupted on %s!\n", action);
        if (data.preCorrupt) {
            fprintf(stderr, "Preguard corrupted\n");
        }
        if (data.postCorrupt) {
            fprintf(stderr, "Postguard corrupted\n");
        }
        fprintf(stderr, "Block last checked OK at allocation %d. Now %d.\n",
                memblk->lastCheckedOK, memento.sequence);
        if ((memblk->flags & Memento_Flag_Reported) == 0)
        {
            memblk->flags |= Memento_Flag_Reported;
            Memento_breakpointLocked();
        }
        return 1;
    }
#endif
    return 0;
}

static int checkBlock(Memento_BlkHeader *memblk, const char *action)
{
#ifndef MEMENTO_LEAKONLY
    BlkCheckData data;
#endif

    if (memblk->child != MEMENTO_CHILD_MAGIC ||
        memblk->sibling != MEMENTO_SIBLING_MAGIC)
    {
        /* Failure! */
        fprintf(stderr, "Attempt to %s invalid block ", action);
        showBlock(memblk, 32);
        fprintf(stderr, "\n");
        return 2;
    }

#ifndef MEMENTO_LEAKONLY
    memset(&data, 0, sizeof(data));
    Memento_appBlock(&memento.used, Memento_Internal_checkAllocedBlock,
                     &data, memblk);
    if (!data.found) {
        /* Failure! */
        fprintf(stderr, "Attempt to %s block ", action);
        showBlock(memblk, 32);
        fprintf(stderr, "\n");
        return 2;
    } else if (data.preCorrupt || data.postCorrupt) {
        fprintf(stderr, "Block ");
        showBlock(memblk, ' ');
        fprintf(stderr, " found to be corrupted on %s!\n", action);
        if (data.preCorrupt) {
            fprintf(stderr, "Preguard corrupted\n");
        }
        if (data.postCorrupt) {
            fprintf(stderr, "Postguard corrupted\n");
        }
        fprintf(stderr, "Block last checked OK at allocation %d. Now %d.\n",
                memblk->lastCheckedOK, memento.sequence);
        if ((memblk->flags & Memento_Flag_Reported) == 0)
        {
            memblk->flags |= Memento_Flag_Reported;
            return 2;
        }
        return 1;
    }
#endif
    return 0;
}

static void do_free(void *blk, int et)
{
    Memento_BlkHeader *memblk;
    int ret;
#ifdef MEMENTO_DETAILS
    Memento_hashedST *st;
#endif

    if (Memento_event()) Memento_breakpointLocked();

    if (blk == NULL)
        return;

    memblk = MEMBLK_FROMBLK(blk);
    VALGRIND_MAKE_MEM_DEFINED(memblk, sizeof(*memblk));
    ret = checkBlock(memblk, "free");
    if (ret)
    {
        if (ret & 2)
            Memento_breakpoint();
        if (memento.abortOnCorruption) {
            fprintf(stderr, "*** memblk corrupted, calling abort()\n");
            abort();
        }
        return;
    }

#ifdef MEMENTO_DETAILS
    st = Memento_getHashedStacktrace();
#endif

    switch (memento.verbose) {
    default:
        if (memento.verboseNewlineSuppressed) {
            fprintf(stderr, "\n");
            memento.verboseNewlineSuppressed = 0;
        }
        fprintf(stderr, "%s "FMTP":(size="FMTZ",num=%d",
                eventType[et],
                MEMBLK_TOBLK(memblk), (FMTZ_CAST)memblk->rawsize, memblk->sequence);
#ifdef MEMENTO_DETAILS
        fprintf(stderr, ",hash=%x", st->hash);
#endif
        if (memblk->label)
            fprintf(stderr, ") (%s", memblk->label);
        fprintf(stderr, ")\n");
        break;
    case 2:
        if (memento.verboseNewlineSuppressed) {
            fprintf(stderr, "\n");
            memento.verboseNewlineSuppressed = 0;
        }
        fprintf(stderr, "%s (size="FMTZ,
                eventType[et],
                (FMTZ_CAST)memblk->rawsize);
#ifdef MEMENTO_DETAILS
        fprintf(stderr, ",hash=%x", st->hash);
#endif
        if (memblk->label)
            fprintf(stderr, ") (%s", memblk->label);
        fprintf(stderr, ")\n");
        break;
    case 0:
        break;
    }

#ifdef MEMENTO_DETAILS
    Memento_storeDetails(memblk, et, st);
#endif

    VALGRIND_MAKE_MEM_DEFINED(memblk, sizeof(*memblk));
    if (memblk->flags & Memento_Flag_BreakOnFree)
        Memento_breakpointLocked();

    memento.alloc -= memblk->rawsize;
    memento.numFrees++;

    Memento_removeBlock(&memento.used, memblk);

    VALGRIND_MAKE_MEM_DEFINED(memblk, sizeof(*memblk));
    if (Memento_Internal_makeSpace(MEMBLK_SIZE(memblk->rawsize))) {
        VALGRIND_MAKE_MEM_DEFINED(memblk, sizeof(*memblk));
        VALGRIND_MAKE_MEM_DEFINED(MEMBLK_TOBLK(memblk),
                                  memblk->rawsize + Memento_PostSize);
#ifndef MEMENTO_LEAKONLY
        memset(MEMBLK_TOBLK(memblk), MEMENTO_FREEFILL, memblk->rawsize);
#endif
        memblk->flags |= Memento_Flag_Freed;
        Memento_addBlockTail(&memento.free, memblk, 1);
    } else {
        free_block(memblk);
    }
}

void Memento_free(void *blk)
{
    if (!memento.inited)
        Memento_init();

    MEMENTO_LOCK();
    do_free(blk, Memento_EventType_free);
    MEMENTO_UNLOCK();
}

static void *do_realloc(void *blk, size_t newsize, int type)
{
    Memento_BlkHeader *memblk, *newmemblk;
    size_t             newsizemem;
    int                flags, ret;
    size_t             oldsize;
#ifdef MEMENTO_DETAILS
    Memento_hashedST *st;
#endif

    if (Memento_failThisEventLocked()) {
        errno = ENOMEM;
        return NULL;
    }

#ifdef MEMENTO_DETAILS
    st = Memento_getHashedStacktrace();
#endif

    memblk     = MEMBLK_FROMBLK(blk);
    VALGRIND_MAKE_MEM_DEFINED(memblk, sizeof(*memblk));
    ret = checkBlock(memblk, "realloc");
    if (ret) {
        switch (memento.verbose) {
        default:
            if (memento.verboseNewlineSuppressed) {
                fprintf(stderr, "\n");
                memento.verboseNewlineSuppressed = 0;
            }
            fprintf(stderr, "%s bad block "FMTP":(size=?=>"FMTZ", num=?, now=%d",
                eventType[type],
                MEMBLK_TOBLK(memblk),
                (FMTZ_CAST)newsize, memento.sequence);
#ifdef MEMENTO_DETAILS
            fprintf(stderr, ",hash=%x", st->hash);
#endif
            fprintf(stderr, ")\n");
            break;
        case 2:
            if (memento.verboseNewlineSuppressed) {
                fprintf(stderr, "\n");
                memento.verboseNewlineSuppressed = 0;
            }
            fprintf(stderr, "%s bad block (size=?=>"FMTZ,
                eventType[type],
                (FMTZ_CAST)newsize);
#ifdef MEMENTO_DETAILS
            fprintf(stderr, ",hash=%x", st->hash);
#endif
            fprintf(stderr, ")\n");
            break;
        case 0:
            break;
        }
        if (ret == 2)
            Memento_breakpoint();
        errno = ENOMEM;
        return NULL;
    }

#ifdef MEMENTO_DETAILS
    Memento_storeDetails(memblk, type, st);
#endif

    VALGRIND_MAKE_MEM_DEFINED(memblk, sizeof(*memblk));
    if (memblk->flags & Memento_Flag_BreakOnRealloc)
        Memento_breakpointLocked();

    VALGRIND_MAKE_MEM_DEFINED(memblk, sizeof(*memblk));
    oldsize = memblk->rawsize;
    if (memento.maxMemory != 0 && memento.alloc - oldsize + newsize > memento.maxMemory) {
        switch (memento.verbose) {
        default:
            if (memento.verboseNewlineSuppressed) {
                fprintf(stderr, "\n");
                memento.verboseNewlineSuppressed = 0;
            }
            fprintf(stderr, "%s failing (memory limit exceeded) "FMTP":(size="FMTZ"=>"FMTZ", num=%d, now=%d",
                    eventType[type], MEMBLK_TOBLK(memblk),
                    (FMTZ_CAST)oldsize, (FMTZ_CAST)newsize,
                    memblk->sequence, memento.sequence);
#ifdef MEMENTO_DETAILS
            fprintf(stderr, ",hash=%x", st->hash);
#endif
            if (memblk->label)
                fprintf(stderr, ") (%s", memblk->label);
            fprintf(stderr, ")\n");
            break;
        case 2:
            if (memento.verboseNewlineSuppressed) {
                fprintf(stderr, "\n");
                memento.verboseNewlineSuppressed = 0;
            }
            fprintf(stderr, "%s failing (memory limit exceeded) (size="FMTZ"=>"FMTZ,
                    eventType[type], (FMTZ_CAST)oldsize, (FMTZ_CAST)newsize);
#ifdef MEMENTO_DETAILS
            fprintf(stderr, ",hash=%x", st->hash);
#endif
            if (memblk->label)
                fprintf(stderr, ") (%s", memblk->label);
            fprintf(stderr, ")\n");
            break;
        case 0:
            break;
        }
        errno = ENOMEM;
        return NULL;
    }

    newsizemem = MEMBLK_SIZE(newsize);
    Memento_removeBlock(&memento.used, memblk);
    VALGRIND_MAKE_MEM_DEFINED(memblk, sizeof(*memblk));
    flags = memblk->flags;
    newmemblk  = MEMENTO_UNDERLYING_REALLOC(memblk, newsizemem);
    if (newmemblk == NULL)
    {
        switch (memento.verbose) {
        default:
            if (memento.verboseNewlineSuppressed) {
                fprintf(stderr, "\n");
                memento.verboseNewlineSuppressed = 0;
            }
            fprintf(stderr, "%s failed "FMTP":(size="FMTZ"=>"FMTZ", num=%d, now=%d",
                    eventType[type], MEMBLK_TOBLK(memblk),
                    (FMTZ_CAST)oldsize, (FMTZ_CAST)newsize,
                    memblk->sequence, memento.sequence);
#ifdef MEMENTO_DETAILS
            fprintf(stderr, ",hash=%x", st->hash);
#endif
            if (memblk->label)
                fprintf(stderr, ") (%s", newmemblk->label);
            fprintf(stderr, ")\n");
            break;
        case 2:
            if (memento.verboseNewlineSuppressed) {
                fprintf(stderr, "\n");
                memento.verboseNewlineSuppressed = 0;
            }
            fprintf(stderr, "%s failed (size="FMTZ"=>"FMTZ,
                    eventType[type],
                    (FMTZ_CAST)oldsize, (FMTZ_CAST)newsize);
#ifdef MEMENTO_DETAILS
            fprintf(stderr, ",hash=%x", st->hash);
#endif
            if (memblk->label)
                fprintf(stderr, ") (%s", newmemblk->label);
            fprintf(stderr, ")\n");
            break;
        case 0:
            break;
        }
        Memento_addBlockHead(&memento.used, memblk, 2);
        return NULL;
    }
    memento.numReallocs++;
    memento.totalAlloc += newsize;
    memento.alloc      -= newmemblk->rawsize;
    memento.alloc      += newsize;
    if (memento.peakAlloc < memento.alloc)
        memento.peakAlloc = memento.alloc;
    newmemblk->flags = flags;
#ifndef MEMENTO_LEAKONLY
    if (newmemblk->rawsize < newsize) {
        char *newbytes = ((char *)MEMBLK_TOBLK(newmemblk))+newmemblk->rawsize;
        VALGRIND_MAKE_MEM_DEFINED(newbytes, newsize - newmemblk->rawsize);
        memset(newbytes, MEMENTO_ALLOCFILL, newsize - newmemblk->rawsize);
        VALGRIND_MAKE_MEM_UNDEFINED(newbytes, newsize - newmemblk->rawsize);
    }
#endif
    newmemblk->rawsize = newsize;
#ifndef MEMENTO_LEAKONLY
    VALGRIND_MAKE_MEM_DEFINED(newmemblk->preblk, Memento_PreSize);
    memset(newmemblk->preblk, MEMENTO_PREFILL, Memento_PreSize);
    VALGRIND_MAKE_MEM_UNDEFINED(newmemblk->preblk, Memento_PreSize);
    VALGRIND_MAKE_MEM_DEFINED(MEMBLK_POSTPTR(newmemblk), Memento_PostSize);
    memset(MEMBLK_POSTPTR(newmemblk), MEMENTO_POSTFILL, Memento_PostSize);
    VALGRIND_MAKE_MEM_UNDEFINED(MEMBLK_POSTPTR(newmemblk), Memento_PostSize);
#endif

    switch (memento.verbose) {
    default:
        if (memento.verboseNewlineSuppressed) {
            fprintf(stderr, "\n");
            memento.verboseNewlineSuppressed = 0;
        }
        fprintf(stderr, "%s "FMTP"=>"FMTP":(size="FMTZ"=>"FMTZ", num=%d, now=%d",
                eventType[type],
                MEMBLK_TOBLK(memblk), MEMBLK_TOBLK(newmemblk),
                (FMTZ_CAST)oldsize, (FMTZ_CAST)newsize,
                newmemblk->sequence, memento.sequence);
#ifdef MEMENTO_DETAILS
        fprintf(stderr, ",hash=%x", st->hash);
#endif
        if (memblk->label)
            fprintf(stderr, ") (%s", newmemblk->label);
        fprintf(stderr, ")\n");
        break;
    case 2:
        if (memento.verboseNewlineSuppressed) {
            fprintf(stderr, "\n");
            memento.verboseNewlineSuppressed = 0;
        }
        fprintf(stderr, "%s (size="FMTZ"=>"FMTZ,
                eventType[type],
                (FMTZ_CAST)oldsize, (FMTZ_CAST)newsize);
#ifdef MEMENTO_DETAILS
        fprintf(stderr, ",hash=%x", st->hash);
#endif
        if (memblk->label)
            fprintf(stderr, ") (%s", newmemblk->label);
        fprintf(stderr, ")\n");
        break;
    case 0:
        break;
    }

    Memento_addBlockHead(&memento.used, newmemblk, 2);
    return MEMBLK_TOBLK(newmemblk);
}

void *Memento_realloc(void *blk, size_t newsize)
{
    void *ret;

    if (!memento.inited)
        Memento_init();

    if (blk == NULL)
    {
        MEMENTO_LOCK();
        ret = do_malloc(newsize, Memento_EventType_realloc);
        MEMENTO_UNLOCK();
        if (!ret) errno = ENOMEM;
        return ret;
    }
    if (newsize == 0) {
        MEMENTO_LOCK();
        do_free(blk, Memento_EventType_realloc);
        MEMENTO_UNLOCK();
        return NULL;
    }

    MEMENTO_LOCK();
    ret = do_realloc(blk, newsize, Memento_EventType_realloc);
    MEMENTO_UNLOCK();
    if (!ret) errno = ENOMEM;
    return ret;
}

int Memento_checkBlock(void *blk)
{
    Memento_BlkHeader *memblk;
    int ret;

    if (blk == NULL)
        return 0;

    MEMENTO_LOCK();
    memblk = MEMBLK_FROMBLK(blk);
    ret = checkBlockUser(memblk, "check");
    MEMENTO_UNLOCK();
    return ret;
}

#ifndef MEMENTO_LEAKONLY
static int Memento_Internal_checkAllAlloced(Memento_BlkHeader *memblk, void *arg)
{
    BlkCheckData *data = (BlkCheckData *)arg;

    Memento_Internal_checkAllocedBlock(memblk, data);
    if (data->preCorrupt || data->postCorrupt) {
        if ((data->found & 2) == 0) {
            fprintf(stderr, "Allocated blocks:\n");
            data->found |= 2;
        }
        fprintf(stderr, "  Block ");
        showBlock(memblk, ' ');
        if (data->preCorrupt) {
            fprintf(stderr, " Preguard ");
        }
        if (data->postCorrupt) {
            fprintf(stderr, "%s Postguard ",
                    (data->preCorrupt ? "&" : ""));
        }
        fprintf(stderr, "corrupted.\n    "
                "Block last checked OK at allocation %d. Now %d.\n",
                memblk->lastCheckedOK, memento.sequence);
        if (memento.abortOnCorruption) {
            fprintf(stderr, "*** memblk corrupted, calling abort()\n");
            abort();
        }
        data->preCorrupt  = 0;
        data->postCorrupt = 0;
        data->freeCorrupt = 0;
        if ((memblk->flags & Memento_Flag_Reported) == 0)
        {
            memblk->flags |= Memento_Flag_Reported;
            data->found |= 8;
        }
    }
    else
        memblk->lastCheckedOK = memento.sequence;
    return 0;
}

static int Memento_Internal_checkAllFreed(Memento_BlkHeader *memblk, void *arg)
{
    BlkCheckData *data = (BlkCheckData *)arg;

    Memento_Internal_checkFreedBlock(memblk, data);
    if (data->preCorrupt || data->postCorrupt || data->freeCorrupt) {
        if ((data->found & 4) == 0) {
            fprintf(stderr, "Freed blocks:\n");
            data->found |= 4;
        }
        fprintf(stderr, "  ");
        showBlock(memblk, ' ');
        if (data->freeCorrupt) {
            fprintf(stderr, " index %d (address "FMTP") onwards", (int)data->index,
                    &((char *)MEMBLK_TOBLK(memblk))[data->index]);
            if (data->preCorrupt) {
                fprintf(stderr, "+ preguard");
            }
            if (data->postCorrupt) {
                fprintf(stderr, "+ postguard");
            }
        } else {
            if (data->preCorrupt) {
                fprintf(stderr, " preguard");
            }
            if (data->postCorrupt) {
                fprintf(stderr, "%s Postguard",
                        (data->preCorrupt ? "+" : ""));
            }
        }
        VALGRIND_MAKE_MEM_DEFINED(memblk, sizeof(Memento_BlkHeader));
        fprintf(stderr, " corrupted.\n"
                "    Block last checked OK at allocation %d. Now %d.\n",
                memblk->lastCheckedOK, memento.sequence);
        if ((memblk->flags & Memento_Flag_Reported) == 0)
        {
            memblk->flags |= Memento_Flag_Reported;
            data->found |= 8;
        }
        VALGRIND_MAKE_MEM_NOACCESS(memblk, sizeof(Memento_BlkHeader));
        data->preCorrupt  = 0;
        data->postCorrupt = 0;
        data->freeCorrupt = 0;
    }
    else
        memblk->lastCheckedOK = memento.sequence;
    return 0;
}
#endif /* MEMENTO_LEAKONLY */

static int Memento_checkAllMemoryLocked(void)
{
#ifndef MEMENTO_LEAKONLY
    BlkCheckData data;

    memset(&data, 0, sizeof(data));
    Memento_appBlocks(&memento.used, Memento_Internal_checkAllAlloced, &data);
    Memento_appBlocks(&memento.free, Memento_Internal_checkAllFreed, &data);
    return data.found;
#else
    return 0;
#endif
}

int Memento_checkAllMemory(void)
{
#ifndef MEMENTO_LEAKONLY
    int ret;

    MEMENTO_LOCK();
    ret = Memento_checkAllMemoryLocked();
    MEMENTO_UNLOCK();
    if (ret & 8) {
        return 1;
    }
#endif
    return 0;
}

int Memento_setParanoia(int i)
{
    memento.paranoia = i;
    if (memento.paranoia > 0)
        memento.countdown = memento.paranoia;
    else
        memento.countdown = -memento.paranoia;
    return i;
}

int Memento_setIgnoreNewDelete(int ignore)
{
    int ret = memento.ignoreNewDelete;
    memento.ignoreNewDelete = ignore;
    return ret;
}

int Memento_paranoidAt(int i)
{
    memento.paranoidAt = i;
    return i;
}

int Memento_getBlockNum(void *b)
{
    Memento_BlkHeader *memblk;
    if (b == NULL)
        return 0;
    memblk = MEMBLK_FROMBLK(b);
    return (memblk->sequence);
}

int Memento_check(void)
{
    int result;

    fprintf(stderr, "Checking memory\n");
    result = Memento_checkAllMemory();
    fprintf(stderr, "Memory checked!\n");
    return result;
}

int Memento_find(void *a)
{
    Memento_BlkHeader *blk;
    int s;
    int flags;

    MEMENTO_LOCK();
    blk = find_enclosing_block(&memento.used, a, &flags);
    if (blk != NULL) {
        fprintf(stderr, "Address "FMTP" is in %sallocated block ",
                a,
                (flags == 1 ? "" : (flags == 2 ? "preguard of " : "postguard of ")));
        s = showBlock(blk, ' ');
        fprintf(stderr, "\n");
        MEMENTO_UNLOCK();
        return s;
    }
    blk = find_enclosing_block(&memento.free, a, &flags);
    if (blk != NULL) {
        fprintf(stderr, "Address "FMTP" is in %sfreed block ",
                a,
                (flags == 1 ? "" : (flags == 2 ? "preguard of " : "postguard of ")));
        s = showBlock(blk, ' ');
        fprintf(stderr, "\n");
        MEMENTO_UNLOCK();
        return s;
    }
    MEMENTO_UNLOCK();
    return 0;
}

void Memento_breakOnFree(void *a)
{
    Memento_BlkHeader *blk;
    int flags;

    MEMENTO_LOCK();
    blk = find_enclosing_block(&memento.used, a, &flags);
    if (blk != NULL) {
        fprintf(stderr, "Will stop when address "FMTP" (in %sallocated block ",
                a,
                (flags == 1 ? "" : (flags == 2 ? "preguard of " : "postguard of ")));
        showBlock(blk, ' ');
        fprintf(stderr, ") is freed\n");
        VALGRIND_MAKE_MEM_DEFINED(blk, sizeof(Memento_BlkHeader));
        blk->flags |= Memento_Flag_BreakOnFree;
        VALGRIND_MAKE_MEM_NOACCESS(blk, sizeof(Memento_BlkHeader));
        MEMENTO_UNLOCK();
        return;
    }
    blk = find_enclosing_block(&memento.free, a, &flags);
    if (blk != NULL) {
        fprintf(stderr, "Can't stop on free; address "FMTP" is in %sfreed block ",
                a,
                (flags == 1 ? "" : (flags == 2 ? "preguard of " : "postguard of ")));
        showBlock(blk, ' ');
        fprintf(stderr, "\n");
        MEMENTO_UNLOCK();
        return;
    }
    fprintf(stderr, "Can't stop on free; address "FMTP" is not in a known block.\n", a);
    MEMENTO_UNLOCK();
}

void Memento_breakOnRealloc(void *a)
{
    Memento_BlkHeader *blk;
    int flags;

    MEMENTO_LOCK();
    blk = find_enclosing_block(&memento.used, a, &flags);
    if (blk != NULL) {
        fprintf(stderr, "Will stop when address "FMTP" (in %sallocated block ",
                a,
                (flags == 1 ? "" : (flags == 2 ? "preguard of " : "postguard of ")));
        showBlock(blk, ' ');
        fprintf(stderr, ") is freed (or realloced)\n");
        VALGRIND_MAKE_MEM_DEFINED(blk, sizeof(Memento_BlkHeader));
        blk->flags |= Memento_Flag_BreakOnFree | Memento_Flag_BreakOnRealloc;
        VALGRIND_MAKE_MEM_NOACCESS(blk, sizeof(Memento_BlkHeader));
        MEMENTO_UNLOCK();
        return;
    }
    blk = find_enclosing_block(&memento.free, a, &flags);
    if (blk != NULL) {
        fprintf(stderr, "Can't stop on free/realloc; address "FMTP" is in %sfreed block ",
                a,
                (flags == 1 ? "" : (flags == 2 ? "preguard of " : "postguard of ")));
        showBlock(blk, ' ');
        fprintf(stderr, "\n");
        MEMENTO_UNLOCK();
        return;
    }
    fprintf(stderr, "Can't stop on free/realloc; address "FMTP" is not in a known block.\n", a);
    MEMENTO_UNLOCK();
}

int Memento_failAt(int i)
{
    memento.failAt = i;
    if ((memento.sequence > memento.failAt) &&
        (memento.failing != 0))
        Memento_startFailing();
    return i;
}

size_t Memento_setMax(size_t max)
{
    memento.maxMemory = max;
    return max;
}

void Memento_startLeaking(void)
{
    memento.leaking++;
}

void Memento_stopLeaking(void)
{
    memento.leaking--;
}

int Memento_squeezing(void)
{
    return memento.squeezing;
}

int Memento_setVerbose(int x)
{
    memento.verbose = x;
    return x;
}

void *Memento_cpp_new(size_t size)
{
    void *ret;

    if (!memento.inited)
        Memento_init();

    if (memento.ignoreNewDelete)
        return MEMENTO_UNDERLYING_MALLOC(size);

    if (size == 0)
        size = 1;
    MEMENTO_LOCK();
    ret = do_malloc(size, Memento_EventType_new);
    MEMENTO_UNLOCK();
    return ret;
}

void Memento_cpp_delete(void *pointer)
{
    if (!pointer)
        return;

    if (!memento.inited)
        Memento_init();
    if (memento.ignoreNewDelete)
    {
        MEMENTO_UNDERLYING_FREE(pointer);
        return;
    }

    MEMENTO_LOCK();
    do_free(pointer, Memento_EventType_delete);
    MEMENTO_UNLOCK();
}

/* Some C++ systems (apparently) don't provide new[] or delete[]
 * operators. Provide a way to cope with this */
void *Memento_cpp_new_array(size_t size)
{
    void *ret;
    if (!memento.inited)
        Memento_init();

    if (size == 0)
        size = 1;

    if (memento.ignoreNewDelete)
        return MEMENTO_UNDERLYING_MALLOC(size);

    MEMENTO_LOCK();
    ret = do_malloc(size, Memento_EventType_newArray);
    MEMENTO_UNLOCK();
    return ret;
}

void  Memento_cpp_delete_array(void *pointer)
{
    if (memento.ignoreNewDelete)
    {
        MEMENTO_UNDERLYING_FREE(pointer);
        return;
    }

    MEMENTO_LOCK();
    do_free(pointer, Memento_EventType_deleteArray);
    MEMENTO_UNLOCK();
}

#else /* MEMENTO */

/* Just in case anyone has left some debugging code in... */
void (Memento_breakpoint)(void)
{
}

int (Memento_checkBlock)(void *b)
{
    return 0;
}

int (Memento_checkAllMemory)(void)
{
    return 0;
}

int (Memento_check)(void)
{
    return 0;
}

int (Memento_setParanoia)(int i)
{
    return 0;
}

int (Memento_paranoidAt)(int i)
{
    return 0;
}

int (Memento_breakAt)(int i)
{
    return 0;
}

int  (Memento_getBlockNum)(void *i)
{
    return 0;
}

int (Memento_find)(void *a)
{
    return 0;
}

int (Memento_failAt)(int i)
{
    return 0;
}

void (Memento_breakOnFree)(void *a)
{
}

void (Memento_breakOnRealloc)(void *a)
{
}

void *(Memento_takeRef)(void *a)
{
    return a;
}

void *(Memento_dropRef)(void *a)
{
    return a;
}

void *(Memento_adjustRef)(void *a, int adjust)
{
    return a;
}

void *(Memento_reference)(void *a)
{
    return a;
}

#undef Memento_malloc
#undef Memento_free
#undef Memento_realloc
#undef Memento_calloc
#undef Memento_strdup
#undef Memento_asprintf
#undef Memento_vasprintf

void *Memento_malloc(size_t size)
{
    return MEMENTO_UNDERLYING_MALLOC(size);
}

void Memento_free(void *b)
{
    MEMENTO_UNDERLYING_FREE(b);
}

void *Memento_realloc(void *b, size_t s)
{
    return MEMENTO_UNDERLYING_REALLOC(b, s);
}

void *Memento_calloc(size_t n, size_t s)
{
    return MEMENTO_UNDERLYING_CALLOC(n, s);
}

#if !defined(MEMENTO_GS_HACKS) && !defined(MEMENTO_MUPDF_HACKS)
/* Avoid calling strdup, in case our compiler doesn't support it.
 * Yes, I'm looking at you, early Visual Studios. */
char *Memento_strdup(const char *s)
{
    size_t len = strlen(s)+1;
    char *ret = MEMENTO_UNDERLYING_MALLOC(len);
    if (ret != NULL)
        memcpy(ret, s, len);
    return ret;
}

/* Avoid calling asprintf, in case our compiler doesn't support it.
 * Vaguely unhappy about relying on vsnprintf, but... */
int Memento_asprintf(char **ret, const char *format, ...)
{
    va_list va;
    int n;
    int n2;

    va_start(va, format);
    n = vsnprintf(NULL, 0, format, va);
    va_end(va);
    if (n < 0)
        return n;

    *ret = MEMENTO_UNDERLYING_MALLOC(n+1);
    if (*ret == NULL)
        return -1;

    va_start(va, format);
    n2 = vsnprintf(*ret, n + 1, format, va);
    va_end(va);

    return n2;
}

/* Avoid calling vasprintf, in case our compiler doesn't support it.
 * Vaguely unhappy about relying on vsnprintf, but... */
int Memento_vasprintf(char **ret, const char *format, va_list ap)
{
    int n;
    va_list ap2;
    va_copy(ap2, ap);

    n = vsnprintf(NULL, 0, format, ap);
    if (n < 0) {
        va_end(ap2);
        return n;
    }

    *ret = MEMENTO_UNDERLYING_MALLOC(n+1);
    if (*ret == NULL) {
        va_end(ap2);
        return -1;
    }

    n = vsnprintf(*ret, n + 1, format, ap2);
    va_end(ap2);

    return n;
}
#endif

void (Memento_listBlocks)(void)
{
}

void (Memento_listNewBlocks)(void)
{
}

void (Memento_listPhasedBlocks)(void)
{
}

int (Memento_setIgnoreNewDelete)(int ignore)
{
    return 0;
}

size_t (Memento_setMax)(size_t max)
{
    return 0;
}

void (Memento_stats)(void)
{
}

void *(Memento_label)(void *ptr, const char *label)
{
    return ptr;
}

void (Memento_info)(void *addr)
{
}

void (Memento_listBlockInfo)(void)
{
}

void (Memento_blockInfo)(void *ptr)
{
}

void (Memento_startLeaking)(void)
{
}

void (Memento_stopLeaking)(void)
{
}

int (Memento_squeezing)(void)
{
    return 0;
}

int (Memento_setVerbose)(int x)
{
    return x;
}

void Memento_showHash(unsigned int hash)
{
}

#endif /* MEMENTO */

#endif /* MEMENTO_CPP_EXTRAS_ONLY */

/* Everything here is only for C++, and then only if we haven't
 * disabled it. */

#ifndef MEMENTO_NO_CPLUSPLUS
#ifdef __cplusplus

// C++ Operator Veneers - START
void *operator new(size_t size)
{
    return Memento_cpp_new(size);
}
void operator delete(void *pointer)
{
    Memento_cpp_delete(pointer);
}
void *operator new[](size_t size)
{
    return Memento_cpp_new_array(size);
}
void operator delete[](void *pointer)
{
   Memento_cpp_delete_array(pointer);
}

/* Some C++ systems (apparently) don't provide new[] or delete[]
 * operators. Provide a way to cope with this */
#ifndef MEMENTO_CPP_NO_ARRAY_CONSTRUCTORS
void *operator new[](size_t size)
{
    return Memento_cpp_new_array(size);
}

void operator delete[](void *pointer)
{
    Memento_cpp_delete_array(pointer);
}
#endif /* MEMENTO_CPP_NO_ARRAY_CONSTRUCTORS */
// C++ Operator Veneers - END

#endif /* __cplusplus */
#endif /* MEMENTO_NO_CPLUSPLUS */