summaryrefslogtreecommitdiffstats
path: root/private/ntos/rtl/heappage.c
blob: fe89c4082228925f9b961ecc29124d021bf4d991 (plain) (blame)
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

//
//  heappage.c
//
//  Implementation of NT RtlHeap family of APIs for debugging
//  applications with heap usage bugs.  Each allocation returned to
//  the calling app is placed at the end of a virtual page such that
//  the following virtual page is protected (ie, NO_ACCESS).
//  So, when the errant app attempts to reference or modify memory
//  beyond the allocated portion of a heap block, an access violation
//  is immediately caused.  This facilitates debugging the app
//  because the access violation occurs at the exact point in the
//  app where the heap corruption or abuse would occur.  Note that
//  significantly more memory (pagefile) is required to run an app
//  using this heap implementation as opposed to the retail heap
//  manager.
//
//  Author:  Tom McGuire (tommcg)
//    Date:  01/06/1995
//
//  Copyright (C) 1994-1996, Microsoft
//

#include "ntrtlp.h"
#include "heappage.h"       // external interface (hooks) to debug heap manager

int __cdecl sprintf(char *, const char *, ...);

//
//  Remainder of entire file is wrapped with #ifdef DEBUG_PAGE_HEAP so that
//  it will compile away to nothing if DEBUG_PAGE_HEAP is not defined in
//  heappage.h
//

#ifdef DEBUG_PAGE_HEAP

#if defined(_X86_)
    #ifndef PAGE_SIZE
    #define PAGE_SIZE   0x1000
    #endif
    #define USER_ALIGNMENT 8
#elif defined(_MIPS_)
    #ifndef PAGE_SIZE
    #define PAGE_SIZE   0x1000
    #endif
    #define USER_ALIGNMENT 8
#elif defined(_PPC_)
    #ifndef PAGE_SIZE
    #define PAGE_SIZE   0x1000
    #endif
    #define USER_ALIGNMENT 8
#elif defined(_ALPHA_)
    #ifndef PAGE_SIZE
    #define PAGE_SIZE   0x2000
    #endif
    #define USER_ALIGNMENT 8
#else
    #error  // platform not defined
#endif


#define DPH_HEAP_ROOT_SIGNATURE  0xFFEEDDCC
#define FILL_BYTE                0xEE
#define HEAD_FILL_SIZE           0x10
#define RESERVE_SIZE             0x800000
#define VM_UNIT_SIZE             0x10000
#define POOL_SIZE                0x4000
#define INLINE                   __inline
#define LOCAL_FUNCTION           // static   // no coff symbols on static functions
#define MIN_FREE_LIST_LENGTH     8


#define ROUNDUP2( x, n ) ((( x ) + (( n ) - 1 )) & ~(( n ) - 1 ))

#if INTERNAL_DEBUG
    #define DEBUG_CODE( a ) a
#else
    #define DEBUG_CODE( a )
#endif

#define RETAIL_ASSERT( a ) ( (a) ? TRUE : \
            RtlpDebugPageHeapAssert( "PAGEHEAP: ASSERTION FAILED: (" #a ")\n" ))

#define DEBUG_ASSERT( a ) DEBUG_CODE( RETAIL_ASSERT( a ))

#define HEAP_HANDLE_FROM_ROOT( HeapRoot ) \
            ((PVOID)(((PCHAR)(HeapRoot)) - PAGE_SIZE ))

#define IF_GENERATE_EXCEPTION( Flags, Status ) {                \
            if (( Flags ) & HEAP_GENERATE_EXCEPTIONS )          \
                RtlpDebugPageHeapException((ULONG)(Status));    \
            }

#define OUT_OF_VM_BREAK( Flags, szText ) {                      \
            if (( Flags ) & HEAP_BREAK_WHEN_OUT_OF_VM )         \
                RtlpDebugPageHeapBreak(( szText ));             \
            }

#define ENQUEUE_HEAD( Node, Head, Tail ) {          \
            (Node)->pNextAlloc = (Head);            \
            if ((Head) == NULL )                    \
                (Tail) = (Node);                    \
            (Head) = (Node);                        \
            }

#define ENQUEUE_TAIL( Node, Head, Tail ) {          \
            if ((Tail) == NULL )                    \
                (Head) = (Node);                    \
            else                                    \
                (Tail)->pNextAlloc = (Node);        \
            (Tail) = (Node);                        \
            }

#define DEQUEUE_NODE( Node, Prev, Head, Tail ) {    \
            PVOID Next = (Node)->pNextAlloc;        \
            if ((Head) == (Node))                   \
                (Head) = Next;                      \
            if ((Tail) == (Node))                   \
                (Tail) = (Prev);                    \
            if ((Prev) != (NULL))                   \
                (Prev)->pNextAlloc = Next;          \
            }

#define PROTECT_HEAP_STRUCTURES( HeapRoot ) {                           \
            if ((HeapRoot)->HeapFlags & HEAP_PROTECTION_ENABLED )       \
                RtlpDebugPageHeapProtectStructures( (HeapRoot) );       \
            }

#define UNPROTECT_HEAP_STRUCTURES( HeapRoot ) {                         \
            if ((HeapRoot)->HeapFlags & HEAP_PROTECTION_ENABLED )       \
                RtlpDebugPageHeapUnProtectStructures( (HeapRoot) );     \
            }


BOOLEAN              RtlpDebugPageHeap;                         // exported via extern
BOOLEAN              RtlpDebugPageHeapListHasBeenInitialized;
RTL_CRITICAL_SECTION RtlpDebugPageHeapListCritSect;
PDPH_HEAP_ROOT       RtlpDebugPageHeapListHead;
PDPH_HEAP_ROOT       RtlpDebugPageHeapListTail;
ULONG                RtlpDebugPageHeapListCount;

#if DPH_CAPTURE_STACK_TRACE
    PVOID RtlpDebugPageHeapStackTraceBuffer[ DPH_MAX_STACK_LENGTH ];
#endif


//
//  Supporting functions
//

VOID
RtlpDebugPageHeapBreak(
    IN PCH Text
    )
    {
    DbgPrint( Text );
    DbgBreakPoint();
    }


LOCAL_FUNCTION
BOOLEAN
RtlpDebugPageHeapAssert(
    IN PCH Text
    )
    {
    RtlpDebugPageHeapBreak( Text );
    return FALSE;
    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapEnterCritSect(
    IN PDPH_HEAP_ROOT HeapRoot,
    IN ULONG          Flags
    )
    {
    if ( Flags & HEAP_NO_SERIALIZE ) {

        if ( ! RtlTryEnterCriticalSection( HeapRoot->HeapCritSect )) {

            if ( HeapRoot->nRemoteLockAcquired == 0 ) {

                //
                //  Another thread owns the CritSect.  This is an application
                //  bug since multithreaded access to heap was attempted with
                //  the HEAP_NO_SERIALIZE flag specified.
                //

                RtlpDebugPageHeapBreak( "PAGEHEAP: Multithreaded access with HEAP_NO_SERIALIZE\n" );

                //
                //  In the interest of allowing the errant app to continue,
                //  we'll force serialization and continue.
                //

                HeapRoot->HeapFlags &= ~HEAP_NO_SERIALIZE;

                }

            RtlEnterCriticalSection( HeapRoot->HeapCritSect );

            }
        }
    else {
        RtlEnterCriticalSection( HeapRoot->HeapCritSect );
        }
    }


LOCAL_FUNCTION
INLINE
VOID
RtlpDebugPageHeapLeaveCritSect(
    IN PDPH_HEAP_ROOT HeapRoot
    )
    {
    RtlLeaveCriticalSection( HeapRoot->HeapCritSect );
    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapException(
    IN ULONG ExceptionCode
    )
    {
    EXCEPTION_RECORD ER;

    ER.ExceptionCode    = ExceptionCode;
    ER.ExceptionFlags   = 0;
    ER.ExceptionRecord  = NULL;
    ER.ExceptionAddress = RtlpDebugPageHeapException;
    ER.NumberParameters = 0;
    RtlRaiseException( &ER );

    }


LOCAL_FUNCTION
PVOID
RtlpDebugPageHeapPointerFromHandle(
    IN PVOID HeapHandle
    )
    {
    try {
        if (((PHEAP)(HeapHandle))->ForceFlags & HEAP_FLAG_PAGE_ALLOCS ) {

            PDPH_HEAP_ROOT HeapRoot = (PVOID)(((PCHAR)(HeapHandle)) + PAGE_SIZE );

            if ( HeapRoot->Signature == DPH_HEAP_ROOT_SIGNATURE ) {
                return HeapRoot;
                }
            }
        }
    except( EXCEPTION_EXECUTE_HANDLER ) {
        }

    RtlpDebugPageHeapBreak( "PAGEHEAP: Bad heap handle\n" );
    return NULL;
    }


LOCAL_FUNCTION
PCCH
RtlpDebugPageHeapProtectionText(
    IN     ULONG Access,
    IN OUT PCHAR Buffer
    )
    {
    switch ( Access ) {
        case PAGE_NOACCESS:          return "PAGE_NOACCESS";
        case PAGE_READONLY:          return "PAGE_READONLY";
        case PAGE_READWRITE:         return "PAGE_READWRITE";
        case PAGE_WRITECOPY:         return "PAGE_WRITECOPY";
        case PAGE_EXECUTE:           return "PAGE_EXECUTE";
        case PAGE_EXECUTE_READ:      return "PAGE_EXECUTE_READ";
        case PAGE_EXECUTE_READWRITE: return "PAGE_EXECUTE_READWRITE";
        case PAGE_EXECUTE_WRITECOPY: return "PAGE_EXECUTE_WRITECOPY";
        case PAGE_GUARD:             return "PAGE_GUARD";
        case 0:                      return "UNKNOWN";
        default:                     sprintf( Buffer, "0x%08X", Access );
                                     return Buffer;
        }
    }


LOCAL_FUNCTION
BOOLEAN
RtlpDebugPageHeapRobustProtectVM(
    IN PVOID   VirtualBase,
    IN ULONG   VirtualSize,
    IN ULONG   NewAccess,
    IN BOOLEAN Recursion
    )
    {
    NTSTATUS Status;
    ULONG    OldAccess = 0;

    Status = ZwProtectVirtualMemory(
                 NtCurrentProcess(),
                 &VirtualBase,
                 &VirtualSize,
                 NewAccess,
                 &OldAccess
                 );

    if ( NT_SUCCESS( Status ))
        return TRUE;

    if (( Status == STATUS_CONFLICTING_ADDRESSES ) && ( ! Recursion )) {

        //
        //  ZwProtectVirtualMemory will not work spanning adjacent
        //  blocks allocated from separate ZwAllocateVirtualMemory
        //  requests.  The status returned in such a case is
        //  STATUS_CONFLICTING_ADDRESSES (0xC0000018).  We encounter
        //  this case rarely, so we'll special-case it here by breaking
        //  up request into VM_UNIT_SIZE (64K-aligned) requests.
        //  Note if the first unit succeeds but a subsequent unit fails,
        //  we are left with a partially-changed range of VM, so we'll
        //  likely fail again later on the same VM.
        //

        ULONG   RemainingSize = VirtualSize;
        ULONG   UnitBase      = (ULONG) VirtualBase;
        PVOID   UnitBasePtr;
        ULONG   UnitSize;
        BOOLEAN Success;

        do  {

            UnitSize = (( UnitBase + VM_UNIT_SIZE ) & ~( VM_UNIT_SIZE - 1 ))
                        - UnitBase;

            if ( UnitSize > RemainingSize )
                 UnitSize = RemainingSize;

            UnitBasePtr    = (PVOID)UnitBase;
            UnitBase      += UnitSize;
            RemainingSize -= UnitSize;

            Success = RtlpDebugPageHeapRobustProtectVM(
                          UnitBasePtr,
                          UnitSize,
                          NewAccess,
                          TRUE
                          );

            }

        while (( Success ) && ( RemainingSize ));

        return Success;
        }

    else {

        CHAR OldProtectionText[ 12 ];     // big enough for "0x12345678"
        CHAR NewProtectionText[ 12 ];     // big enough for "0x12345678"

        DbgPrint(
            "PAGEHEAP: Failed changing VM %s at %08X size 0x%X\n"
            "          from %s to %s (Status %08X)\n",
            Recursion ? "fragment" : "protection",
            VirtualBase,
            VirtualSize,
            RtlpDebugPageHeapProtectionText( OldAccess, OldProtectionText ),
            RtlpDebugPageHeapProtectionText( NewAccess, NewProtectionText ),
            Status
            );

        RtlpDebugPageHeapBreak( "" );
        }

    return FALSE;
    }


LOCAL_FUNCTION
INLINE
BOOLEAN
RtlpDebugPageHeapProtectVM(
    IN PVOID   VirtualBase,
    IN ULONG   VirtualSize,
    IN ULONG   NewAccess
    )
    {
    return RtlpDebugPageHeapRobustProtectVM( VirtualBase, VirtualSize, NewAccess, FALSE );
    }


LOCAL_FUNCTION
INLINE
PVOID
RtlpDebugPageHeapAllocateVM(
    IN ULONG nSize
    )
    {
    NTSTATUS Status;
    PVOID pVirtual;

    pVirtual = NULL;

    Status = ZwAllocateVirtualMemory( NtCurrentProcess(),
                                      &pVirtual,
                                      0,
                                      &nSize,
                                      MEM_COMMIT,
                                      PAGE_NOACCESS );

    return NT_SUCCESS( Status ) ? pVirtual : NULL;
    }


LOCAL_FUNCTION
INLINE
BOOLEAN
RtlpDebugPageHeapReleaseVM(
    IN PVOID pVirtual
    )
    {
    ULONG nSize = 0;

    return NT_SUCCESS( ZwFreeVirtualMemory( NtCurrentProcess(),
                                            &pVirtual,
                                            &nSize,
                                            MEM_RELEASE ));
    }


LOCAL_FUNCTION
PDPH_HEAP_ALLOCATION
RtlpDebugPageHeapTakeNodeFromUnusedList(
    IN PDPH_HEAP_ROOT pHeap
    )
    {
    PDPH_HEAP_ALLOCATION pNode = pHeap->pUnusedNodeListHead;
    PDPH_HEAP_ALLOCATION pPrev = NULL;

    //
    //  UnusedNodeList is LIFO with most recent entry at head of list.
    //

    if ( pNode ) {

        DEQUEUE_NODE( pNode, pPrev, pHeap->pUnusedNodeListHead, pHeap->pUnusedNodeListTail );

        --pHeap->nUnusedNodes;

        }

    return pNode;
    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapReturnNodeToUnusedList(
    IN PDPH_HEAP_ROOT       pHeap,
    IN PDPH_HEAP_ALLOCATION pNode
    )
    {

    //
    //  UnusedNodeList is LIFO with most recent entry at head of list.
    //

    ENQUEUE_HEAD( pNode, pHeap->pUnusedNodeListHead, pHeap->pUnusedNodeListTail );

    ++pHeap->nUnusedNodes;

    }


LOCAL_FUNCTION
PDPH_HEAP_ALLOCATION
RtlpDebugPageHeapFindBusyMem(
    IN  PDPH_HEAP_ROOT        pHeap,
    IN  PVOID                 pUserMem,
    OUT PDPH_HEAP_ALLOCATION *pPrevAlloc
    )
    {
    PDPH_HEAP_ALLOCATION pNode = pHeap->pBusyAllocationListHead;
    PDPH_HEAP_ALLOCATION pPrev = NULL;

    while ( pNode != NULL ) {

        if ( pNode->pUserAllocation == pUserMem ) {

            if ( pPrevAlloc )
                *pPrevAlloc = pPrev;

            return pNode;
            }

        pPrev = pNode;
        pNode = pNode->pNextAlloc;
        }

    return NULL;
    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapRemoveFromAvailableList(
    IN PDPH_HEAP_ROOT       pHeap,
    IN PDPH_HEAP_ALLOCATION pNode,
    IN PDPH_HEAP_ALLOCATION pPrev
    )
    {

    DEQUEUE_NODE( pNode, pPrev, pHeap->pAvailableAllocationListHead, pHeap->pAvailableAllocationListTail );

    pHeap->nAvailableAllocations--;
    pHeap->nAvailableAllocationBytesCommitted -= pNode->nVirtualBlockSize;

    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapPlaceOnFreeList(
    IN PDPH_HEAP_ROOT       pHeap,
    IN PDPH_HEAP_ALLOCATION pAlloc
    )
    {

    //
    //  FreeAllocationList is stored FIFO to enhance finding
    //  reference-after-freed bugs by keeping previously freed
    //  allocations on the free list as long as possible.
    //

    pAlloc->pNextAlloc = NULL;

    ENQUEUE_TAIL( pAlloc, pHeap->pFreeAllocationListHead, pHeap->pFreeAllocationListTail );

    pHeap->nFreeAllocations++;
    pHeap->nFreeAllocationBytesCommitted += pAlloc->nVirtualBlockSize;

    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapRemoveFromFreeList(
    IN PDPH_HEAP_ROOT       pHeap,
    IN PDPH_HEAP_ALLOCATION pNode,
    IN PDPH_HEAP_ALLOCATION pPrev
    )
    {

    DEQUEUE_NODE( pNode, pPrev, pHeap->pFreeAllocationListHead, pHeap->pFreeAllocationListTail );

    pHeap->nFreeAllocations--;
    pHeap->nFreeAllocationBytesCommitted -= pNode->nVirtualBlockSize;

#if DPH_CAPTURE_STACK_TRACE

    pNode->pStackTrace = NULL;

#endif // DPH_CAPTURE_STACK_TRACE

    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapPlaceOnVirtualList(
    IN PDPH_HEAP_ROOT       pHeap,
    IN PDPH_HEAP_ALLOCATION pNode
    )
    {

    //
    //  VirtualStorageList is LIFO so that releasing VM blocks will
    //  occur in exact reverse order.
    //

    ENQUEUE_HEAD( pNode, pHeap->pVirtualStorageListHead, pHeap->pVirtualStorageListTail );

    pHeap->nVirtualStorageRanges++;
    pHeap->nVirtualStorageBytes += pNode->nVirtualBlockSize;

    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapPlaceOnBusyList(
    IN PDPH_HEAP_ROOT       pHeap,
    IN PDPH_HEAP_ALLOCATION pNode
    )
    {

    //
    //  BusyAllocationList is LIFO to achieve better temporal locality
    //  of reference (older allocations are farther down the list).
    //

    ENQUEUE_HEAD( pNode, pHeap->pBusyAllocationListHead, pHeap->pBusyAllocationListTail );

    pHeap->nBusyAllocations++;
    pHeap->nBusyAllocationBytesCommitted  += pNode->nVirtualBlockSize;
    pHeap->nBusyAllocationBytesAccessible += pNode->nVirtualAccessSize;

    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapRemoveFromBusyList(
    IN PDPH_HEAP_ROOT       pHeap,
    IN PDPH_HEAP_ALLOCATION pNode,
    IN PDPH_HEAP_ALLOCATION pPrev
    )
    {

    DEQUEUE_NODE( pNode, pPrev, pHeap->pBusyAllocationListHead, pHeap->pBusyAllocationListTail );

    pHeap->nBusyAllocations--;
    pHeap->nBusyAllocationBytesCommitted  -= pNode->nVirtualBlockSize;
    pHeap->nBusyAllocationBytesAccessible -= pNode->nVirtualAccessSize;

    }


LOCAL_FUNCTION
PDPH_HEAP_ALLOCATION
RtlpDebugPageHeapSearchAvailableMemListForBestFit(
    IN  PDPH_HEAP_ROOT        pHeap,
    IN  ULONG                 nSize,
    OUT PDPH_HEAP_ALLOCATION *pPrevAvailNode
    )
    {
    PDPH_HEAP_ALLOCATION pAvail, pFound, pAvailPrev, pFoundPrev;
    ULONG                nAvail, nFound;

    nFound     = 0x7FFFFFFF;
    pFound     = NULL;
    pFoundPrev = NULL;
    pAvailPrev = NULL;
    pAvail     = pHeap->pAvailableAllocationListHead;

    while (( pAvail != NULL ) && ( nFound > nSize )) {

        nAvail = pAvail->nVirtualBlockSize;

        if (( nAvail >= nSize ) && ( nAvail < nFound )) {
            nFound     = nAvail;
            pFound     = pAvail;
            pFoundPrev = pAvailPrev;
            }

        pAvailPrev = pAvail;
        pAvail     = pAvail->pNextAlloc;
        }

    *pPrevAvailNode = pFoundPrev;
    return pFound;
    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapCoalesceNodeIntoAvailable(
    IN PDPH_HEAP_ROOT       pHeap,
    IN PDPH_HEAP_ALLOCATION pNode
    )
    {
    PDPH_HEAP_ALLOCATION pPrev    = NULL;
    PDPH_HEAP_ALLOCATION pNext    = pHeap->pAvailableAllocationListHead;
    PUCHAR               pVirtual = pNode->pVirtualBlock;
    ULONG                nVirtual = pNode->nVirtualBlockSize;

    pHeap->nAvailableAllocationBytesCommitted += nVirtual;
    pHeap->nAvailableAllocations++;

    //
    //  Walk list to insertion point.
    //

    while (( pNext ) && ( pNext->pVirtualBlock < pVirtual )) {
        pPrev = pNext;
        pNext = pNext->pNextAlloc;
        }

    if ( pPrev ) {

        if (( pPrev->pVirtualBlock + pPrev->nVirtualBlockSize ) == pVirtual ) {

            //
            //  pPrev and pNode are adjacent, so simply add size of
            //  pNode entry to pPrev entry.
            //

            pPrev->nVirtualBlockSize += nVirtual;

            RtlpDebugPageHeapReturnNodeToUnusedList( pHeap, pNode );

            pHeap->nAvailableAllocations--;

            pNode    = pPrev;
            pVirtual = pPrev->pVirtualBlock;
            nVirtual = pPrev->nVirtualBlockSize;

            }

        else {

            //
            //  pPrev and pNode are not adjacent, so insert the pNode
            //  block into the list after pPrev.
            //

            pNode->pNextAlloc = pPrev->pNextAlloc;
            pPrev->pNextAlloc = pNode;

            }
        }

    else {

        //
        //  pNode should be inserted at head of list.
        //

        pNode->pNextAlloc = pHeap->pAvailableAllocationListHead;
        pHeap->pAvailableAllocationListHead = pNode;

        }


    if ( pNext ) {

        if (( pVirtual + nVirtual ) == pNext->pVirtualBlock ) {

            //
            //  pNode and pNext are adjacent, so simply add size of
            //  pNext entry to pNode entry and remove pNext entry
            //  from the list.
            //

            pNode->nVirtualBlockSize += pNext->nVirtualBlockSize;

            pNode->pNextAlloc = pNext->pNextAlloc;

            if ( pHeap->pAvailableAllocationListTail == pNext )
                 pHeap->pAvailableAllocationListTail = pNode;

            RtlpDebugPageHeapReturnNodeToUnusedList( pHeap, pNext );

            pHeap->nAvailableAllocations--;

            }
        }

    else {

        //
        //  pNode is tail of list.
        //

        pHeap->pAvailableAllocationListTail = pNode;

        }
    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapCoalesceFreeIntoAvailable(
    IN PDPH_HEAP_ROOT pHeap,
    IN ULONG          nLeaveOnFreeList
    )
    {
    PDPH_HEAP_ALLOCATION pNode = pHeap->pFreeAllocationListHead;
    ULONG                nFree = pHeap->nFreeAllocations;
    PDPH_HEAP_ALLOCATION pNext;

    DEBUG_ASSERT( nFree >= nLeaveOnFreeList );

    while (( pNode ) && ( nFree-- > nLeaveOnFreeList )) {

        pNext = pNode->pNextAlloc;  // preserve next pointer across shuffling

        RtlpDebugPageHeapRemoveFromFreeList( pHeap, pNode, NULL );

        RtlpDebugPageHeapCoalesceNodeIntoAvailable( pHeap, pNode );

        pNode = pNext;

        }

    DEBUG_ASSERT(( nFree = (volatile ULONG)( pHeap->nFreeAllocations )) >= nLeaveOnFreeList );
    DEBUG_ASSERT(( pNode != NULL ) || ( nFree == 0 ));

    }


LOCAL_FUNCTION
BOOLEAN
RtlpDebugPageHeapGrowVirtual(
    IN PDPH_HEAP_ROOT pHeap,
    IN ULONG          nSize
    );


LOCAL_FUNCTION
PDPH_HEAP_ALLOCATION
RtlpDebugPageHeapFindAvailableMem(
    IN  PDPH_HEAP_ROOT        pHeap,
    IN  ULONG                 nSize,
    OUT PDPH_HEAP_ALLOCATION *pPrevAvailNode,
    IN  BOOLEAN               bGrowVirtual
    )
    {
    PDPH_HEAP_ALLOCATION pAvail;
    ULONG                nLeaveOnFreeList;

    //
    //  First search existing AvailableList for a "best-fit" block
    //  (the smallest block that will satisfy the request).
    //

    pAvail = RtlpDebugPageHeapSearchAvailableMemListForBestFit(
                 pHeap,
                 nSize,
                 pPrevAvailNode
                 );

    while (( pAvail == NULL ) && ( pHeap->nFreeAllocations > MIN_FREE_LIST_LENGTH )) {

        //
        //  Failed to find sufficient memory on AvailableList.  Coalesce
        //  3/4 of the FreeList memory to the AvailableList and try again.
        //  Continue this until we have sufficient memory in AvailableList,
        //  or the FreeList length is reduced to MIN_FREE_LIST_LENGTH entries.
        //  We don't shrink the FreeList length below MIN_FREE_LIST_LENGTH
        //  entries to preserve the most recent MIN_FREE_LIST_LENGTH entries
        //  for reference-after-freed purposes.
        //

        nLeaveOnFreeList = pHeap->nFreeAllocations / 4;

        if ( nLeaveOnFreeList < MIN_FREE_LIST_LENGTH )
             nLeaveOnFreeList = MIN_FREE_LIST_LENGTH;

        RtlpDebugPageHeapCoalesceFreeIntoAvailable( pHeap, nLeaveOnFreeList );

        pAvail = RtlpDebugPageHeapSearchAvailableMemListForBestFit(
                     pHeap,
                     nSize,
                     pPrevAvailNode
                     );

        }


    if (( pAvail == NULL ) && ( bGrowVirtual )) {

        //
        //  After coalescing FreeList into AvailableList, still don't have
        //  enough memory (large enough block) to satisfy request, so we
        //  need to allocate more VM.
        //

        if ( RtlpDebugPageHeapGrowVirtual( pHeap, nSize )) {

            pAvail = RtlpDebugPageHeapSearchAvailableMemListForBestFit(
                         pHeap,
                         nSize,
                         pPrevAvailNode
                         );

            if ( pAvail == NULL ) {

                //
                //  Failed to satisfy request with more VM.  If remainder
                //  of free list combined with available list is larger
                //  than the request, we might still be able to satisfy
                //  the request by merging all of the free list onto the
                //  available list.  Note we lose our MIN_FREE_LIST_LENGTH
                //  reference-after-freed insurance in this case, but it
                //  is a rare case, and we'd prefer to satisfy the allocation.
                //

                if (( pHeap->nFreeAllocationBytesCommitted +
                      pHeap->nAvailableAllocationBytesCommitted ) >= nSize ) {

                    RtlpDebugPageHeapCoalesceFreeIntoAvailable( pHeap, 0 );

                    pAvail = RtlpDebugPageHeapSearchAvailableMemListForBestFit(
                                 pHeap,
                                 nSize,
                                 pPrevAvailNode
                                 );
                    }
                }
            }
        }

    return pAvail;
    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapPlaceOnPoolList(
    IN PDPH_HEAP_ROOT       pHeap,
    IN PDPH_HEAP_ALLOCATION pNode
    )
    {

    //
    //  NodePoolList is FIFO.
    //

    pNode->pNextAlloc = NULL;

    ENQUEUE_TAIL( pNode, pHeap->pNodePoolListHead, pHeap->pNodePoolListTail );

    pHeap->nNodePoolBytes += pNode->nVirtualBlockSize;
    pHeap->nNodePools     += 1;

    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapAddNewPool(
    IN PDPH_HEAP_ROOT pHeap,
    IN PVOID          pVirtual,
    IN ULONG          nSize,
    IN BOOLEAN        bAddToPoolList
    )
    {
    PDPH_HEAP_ALLOCATION pNode, pFirst;
    ULONG n, nCount;

    //
    //  Assume pVirtual points to committed block of nSize bytes.
    //

    pFirst = pVirtual;
    nCount = nSize  / sizeof( DPH_HEAP_ALLOCATION );

    for ( n = nCount - 1, pNode = pFirst; n > 0; pNode++, n-- )
        pNode->pNextAlloc = pNode + 1;

    pNode->pNextAlloc = NULL;

    //
    //  Now link this list into the tail of the UnusedNodeList
    //

    ENQUEUE_TAIL( pFirst, pHeap->pUnusedNodeListHead, pHeap->pUnusedNodeListTail );

    pHeap->pUnusedNodeListTail = pNode;

    pHeap->nUnusedNodes += nCount;

    if ( bAddToPoolList ) {

        //
        //  Now add an entry on the PoolList by taking a node from the
        //  UnusedNodeList, which should be guaranteed to be non-empty
        //  since we just added new nodes to it.
        //

        pNode = RtlpDebugPageHeapTakeNodeFromUnusedList( pHeap );

        DEBUG_ASSERT( pNode != NULL );

        pNode->pVirtualBlock     = pVirtual;
        pNode->nVirtualBlockSize = nSize;

        RtlpDebugPageHeapPlaceOnPoolList( pHeap, pNode );

        }

    }


LOCAL_FUNCTION
PDPH_HEAP_ALLOCATION
RtlpDebugPageHeapAllocateNode(
    IN PDPH_HEAP_ROOT pHeap
    )
    {
    PDPH_HEAP_ALLOCATION pNode, pPrev, pReturn;
    PUCHAR pVirtual;
    ULONG  nVirtual;
    ULONG  nRequest;

    DEBUG_ASSERT( ! pHeap->InsideAllocateNode );
    DEBUG_CODE( pHeap->InsideAllocateNode = TRUE );

    pReturn = NULL;

    if ( pHeap->pUnusedNodeListHead == NULL ) {

        //
        //  We're out of nodes -- allocate new node pool
        //  from AvailableList.  Set bGrowVirtual to FALSE
        //  since growing virtual will require new nodes, causing
        //  recursion.  Note that simply calling FindAvailableMem
        //  might return some nodes to the pUnusedNodeList, even if
        //  the call fails, so we'll check that the UnusedNodeList
        //  is still empty before we try to use or allocate more
        //  memory.
        //

        nRequest = POOL_SIZE;

        pNode = RtlpDebugPageHeapFindAvailableMem(
                    pHeap,
                    nRequest,
                    &pPrev,
                    FALSE
                    );

        if (( pHeap->pUnusedNodeListHead == NULL ) && ( pNode == NULL )) {

            //
            //  Reduce request size to PAGE_SIZE and see if
            //  we can find at least a page on the available
            //  list.
            //

            nRequest = PAGE_SIZE;

            pNode = RtlpDebugPageHeapFindAvailableMem(
                        pHeap,
                        nRequest,
                        &pPrev,
                        FALSE
                        );

            }

        if ( pHeap->pUnusedNodeListHead == NULL ) {

            if ( pNode == NULL ) {

                //
                //  Insufficient memory on Available list.  Try allocating a
                //  new virtual block.
                //

                nRequest = POOL_SIZE;
                nVirtual = RESERVE_SIZE;
                pVirtual = RtlpDebugPageHeapAllocateVM( nVirtual );

                if ( pVirtual == NULL ) {

                    //
                    //  Unable to allocate full RESERVE_SIZE block,
                    //  so reduce request to single VM unit (64K)
                    //  and try again.
                    //

                    nVirtual = VM_UNIT_SIZE;
                    pVirtual = RtlpDebugPageHeapAllocateVM( nVirtual );

                    if ( pVirtual == NULL ) {

                        //
                        //  Can't allocate any VM.
                        //

                        goto EXIT;
                        }
                    }
                }

            else {

                RtlpDebugPageHeapRemoveFromAvailableList( pHeap, pNode, pPrev );

                pVirtual = pNode->pVirtualBlock;
                nVirtual = pNode->nVirtualBlockSize;

                }

            //
            //  We now have allocated VM referenced by pVirtual,nVirtual.
            //  Make nRequest portion of VM accessible for new node pool.
            //

            if ( ! RtlpDebugPageHeapProtectVM( pVirtual, nRequest, PAGE_READWRITE )) {

                if ( pNode == NULL ) {
                    RtlpDebugPageHeapReleaseVM( pVirtual );
                    }
                else {
                    RtlpDebugPageHeapCoalesceNodeIntoAvailable( pHeap, pNode );
                    }

                goto EXIT;
                }

            //
            //  Now we have accessible memory for new pool.  Add the
            //  new memory to the pool.  If the new memory came from
            //  AvailableList versus fresh VM, zero the memory first.
            //

            if ( pNode != NULL )
                RtlZeroMemory( pVirtual, nRequest );

            RtlpDebugPageHeapAddNewPool( pHeap, pVirtual, nRequest, TRUE );

            //
            //  If any memory remaining, put it on available list.
            //

            if ( pNode == NULL ) {

                //
                //  Memory came from new VM -- add appropriate list entries
                //  for new VM and add remainder of VM to free list.
                //

                pNode = RtlpDebugPageHeapTakeNodeFromUnusedList( pHeap );
                DEBUG_ASSERT( pNode != NULL );
                pNode->pVirtualBlock     = pVirtual;
                pNode->nVirtualBlockSize = nVirtual;
                RtlpDebugPageHeapPlaceOnVirtualList( pHeap, pNode );

                pNode = RtlpDebugPageHeapTakeNodeFromUnusedList( pHeap );
                DEBUG_ASSERT( pNode != NULL );
                pNode->pVirtualBlock     = pVirtual + nRequest;
                pNode->nVirtualBlockSize = nVirtual - nRequest;

                RtlpDebugPageHeapCoalesceNodeIntoAvailable( pHeap, pNode );

                }

            else {

                if ( pNode->nVirtualBlockSize > nRequest ) {

                    pNode->pVirtualBlock     += nRequest;
                    pNode->nVirtualBlockSize -= nRequest;

                    RtlpDebugPageHeapCoalesceNodeIntoAvailable( pHeap, pNode );
                    }

                else {

                    //
                    //  Used up entire available block -- return node to
                    //  unused list.
                    //

                    RtlpDebugPageHeapReturnNodeToUnusedList( pHeap, pNode );

                    }
                }
            }
        }

    pReturn = RtlpDebugPageHeapTakeNodeFromUnusedList( pHeap );
    DEBUG_ASSERT( pReturn != NULL );

EXIT:

    DEBUG_CODE( pHeap->InsideAllocateNode = FALSE );
    return pReturn;
    }


LOCAL_FUNCTION
BOOLEAN
RtlpDebugPageHeapGrowVirtual(
    IN PDPH_HEAP_ROOT pHeap,
    IN ULONG          nSize
    )
    {
    PDPH_HEAP_ALLOCATION pVirtualNode;
    PDPH_HEAP_ALLOCATION pAvailNode;
    PVOID pVirtual;
    ULONG nVirtual;

    pVirtualNode = RtlpDebugPageHeapAllocateNode( pHeap );

    if ( pVirtualNode == NULL ) {
        return FALSE;
        }

    pAvailNode = RtlpDebugPageHeapAllocateNode( pHeap );

    if ( pAvailNode == NULL ) {
        RtlpDebugPageHeapReturnNodeToUnusedList( pHeap, pVirtualNode );
        return FALSE;
        }

    nSize    = ROUNDUP2( nSize, VM_UNIT_SIZE );
    nVirtual = ( nSize > RESERVE_SIZE ) ? nSize : RESERVE_SIZE;
    pVirtual = RtlpDebugPageHeapAllocateVM( nVirtual );

    if (( pVirtual == NULL ) && ( nSize < RESERVE_SIZE )) {
        nVirtual = nSize;
        pVirtual = RtlpDebugPageHeapAllocateVM( nVirtual );
        }

    if ( pVirtual == NULL ) {
        RtlpDebugPageHeapReturnNodeToUnusedList( pHeap, pVirtualNode );
        RtlpDebugPageHeapReturnNodeToUnusedList( pHeap, pAvailNode );
        return FALSE;
        }

    pVirtualNode->pVirtualBlock     = pVirtual;
    pVirtualNode->nVirtualBlockSize = nVirtual;
    RtlpDebugPageHeapPlaceOnVirtualList( pHeap, pVirtualNode );

    pAvailNode->pVirtualBlock     = pVirtual;
    pAvailNode->nVirtualBlockSize = nVirtual;
    RtlpDebugPageHeapCoalesceNodeIntoAvailable( pHeap, pAvailNode );

    return TRUE;
    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapProtectStructures(
    IN PDPH_HEAP_ROOT pHeap
    )
    {
    PDPH_HEAP_ALLOCATION pNode;

    //
    //  Assume CritSect is owned so we're the only thread twiddling
    //  the protection.
    //

    DEBUG_ASSERT( pHeap->HeapFlags & HEAP_PROTECTION_ENABLED );

    if ( --pHeap->nUnProtectionReferenceCount == 0 ) {

        pNode = pHeap->pNodePoolListHead;

        while ( pNode != NULL ) {

            RtlpDebugPageHeapProtectVM( pNode->pVirtualBlock,
                                        pNode->nVirtualBlockSize,
                                        PAGE_READONLY );

            pNode = pNode->pNextAlloc;

            }
        }
    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapUnProtectStructures(
    IN PDPH_HEAP_ROOT pHeap
    )
    {
    PDPH_HEAP_ALLOCATION pNode;

    DEBUG_ASSERT( pHeap->HeapFlags & HEAP_PROTECTION_ENABLED );

    if ( pHeap->nUnProtectionReferenceCount == 0 ) {

        pNode = pHeap->pNodePoolListHead;

        while ( pNode != NULL ) {

            RtlpDebugPageHeapProtectVM( pNode->pVirtualBlock,
                                        pNode->nVirtualBlockSize,
                                        PAGE_READWRITE );

            pNode = pNode->pNextAlloc;

            }
        }

    ++pHeap->nUnProtectionReferenceCount;

    }


LOCAL_FUNCTION
INLINE
PUCHAR
RtlpDebugPageHeapScanForFillCorruption(
    IN PUCHAR Address,
    IN UCHAR  ExpectedValue,
    IN ULONG  Length
    )
    {
    PUCHAR End;

    for ( End = Address + Length; Address < End; Address++ ) {
        if ( *Address != ExpectedValue )
            return Address;
        }

    return NULL;
    }


LOCAL_FUNCTION
BOOLEAN
RtlpDebugPageHeapDetectFillCorruption(
    IN PDPH_HEAP_ALLOCATION pNode
    )
    {
    PUCHAR p;

    p = RtlpDebugPageHeapScanForFillCorruption(
            pNode->pUserAllocation + pNode->nUserRequestedSize,
            FILL_BYTE,
            pNode->nUserActualSize - pNode->nUserRequestedSize );

    if ( p != NULL ) {

        DbgPrint( "PAGEHEAP: Tail fill corruption detected:\n"
                  "          Allocation at  0x%08X\n"
                  "          Requested size 0x%08X\n"
                  "          Allocated size 0x%08X\n"
                  "          Corruption at  0x%08X\n",
                  pNode->pUserAllocation,
                  pNode->nUserRequestedSize,
                  pNode->nUserActualSize,
                  p );

        RtlpDebugPageHeapBreak( "" );
        return TRUE;
        }

    return FALSE;
    }


#if INTERNAL_DEBUG

LOCAL_FUNCTION
VOID
RtlpDebugPageHeapVerifyList(
    IN PDPH_HEAP_ALLOCATION pListHead,
    IN PDPH_HEAP_ALLOCATION pListTail,
    IN ULONG                nExpectedLength,
    IN ULONG                nExpectedVirtual,
    IN PCCH                 pListName
    )
    {
    PDPH_HEAP_ALLOCATION pPrev = NULL;
    PDPH_HEAP_ALLOCATION pNode = pListHead;
    PDPH_HEAP_ALLOCATION pTest = pListHead ? pListHead->pNextAlloc : NULL;
    ULONG                nNode = 0;
    ULONG                nSize = 0;

    while ( pNode ) {

        if ( pNode == pTest ) {
            DbgPrint( "PAGEHEAP: Internal %s list is circular\n", pListName );
            RtlpDebugPageHeapBreak( "" );
            return;
            }

        nNode++;
        nSize += pNode->nVirtualBlockSize;

        if ( pTest ) {
            pTest = pTest->pNextAlloc;
            if ( pTest ) {
                pTest = pTest->pNextAlloc;
                }
            }

        pPrev = pNode;
        pNode = pNode->pNextAlloc;

        }

    if ( pPrev != pListTail ) {
        DbgPrint( "PAGEHEAP: Internal %s list has incorrect tail pointer\n", pListName );
        RtlpDebugPageHeapBreak( "" );
        }

    if (( nExpectedLength != 0xFFFFFFFF ) && ( nExpectedLength != nNode )) {
        DbgPrint( "PAGEHEAP: Internal %s list has incorrect length\n", pListName );
        RtlpDebugPageHeapBreak( "" );
        }

    if (( nExpectedVirtual != 0xFFFFFFFF ) && ( nExpectedVirtual != nSize )) {
        DbgPrint( "PAGEHEAP: Internal %s list has incorrect virtual size\n", pListName );
        RtlpDebugPageHeapBreak( "" );
        }

    }


LOCAL_FUNCTION
VOID
RtlpDebugPageHeapVerifyIntegrity(
    IN PDPH_HEAP_ROOT pHeap
    )
    {

    RtlpDebugPageHeapVerifyList(
        pHeap->pVirtualStorageListHead,
        pHeap->pVirtualStorageListTail,
        pHeap->nVirtualStorageRanges,
        pHeap->nVirtualStorageBytes,
        "VIRTUAL"
        );

    RtlpDebugPageHeapVerifyList(
        pHeap->pBusyAllocationListHead,
        pHeap->pBusyAllocationListTail,
        pHeap->nBusyAllocations,
        pHeap->nBusyAllocationBytesCommitted,
        "BUSY"
        );

    RtlpDebugPageHeapVerifyList(
        pHeap->pFreeAllocationListHead,
        pHeap->pFreeAllocationListTail,
        pHeap->nFreeAllocations,
        pHeap->nFreeAllocationBytesCommitted,
        "FREE"
        );

    RtlpDebugPageHeapVerifyList(
        pHeap->pAvailableAllocationListHead,
        pHeap->pAvailableAllocationListTail,
        pHeap->nAvailableAllocations,
        pHeap->nAvailableAllocationBytesCommitted,
        "AVAILABLE"
        );

    RtlpDebugPageHeapVerifyList(
        pHeap->pUnusedNodeListHead,
        pHeap->pUnusedNodeListTail,
        pHeap->nUnusedNodes,
        0xFFFFFFFF,
        "FREENODE"
        );

    RtlpDebugPageHeapVerifyList(
        pHeap->pNodePoolListHead,
        pHeap->pNodePoolListTail,
        pHeap->nNodePools,
        pHeap->nNodePoolBytes,
        "NODEPOOL"
        );

    }

#endif // INTERNAL_DEBUG


#if DPH_CAPTURE_STACK_TRACE


VOID
RtlpDebugPageHeapRemoteThreadLock(
    IN PVOID HeapBaseAddress
    )
    {
    PDPH_HEAP_ROOT HeapRoot;
    LARGE_INTEGER  Delay;

    try {

        HeapRoot = HeapBaseAddress;

        if ( HeapRoot->Signature == DPH_HEAP_ROOT_SIGNATURE ) {

            RtlpDebugPageHeapEnterCritSect( HeapRoot, 0 );

            (volatile ULONG)( HeapRoot->nRemoteLockAcquired ) = 1;

            Delay.QuadPart = -1000000;  // 100ms, relative to now

            do  {
                ZwDelayExecution( FALSE, &Delay );
                }
            while ((volatile ULONG)( HeapRoot->nRemoteLockAcquired ) == 1 );

            RtlpDebugPageHeapLeaveCritSect( HeapRoot );

            }
        }
    except( EXCEPTION_EXECUTE_HANDLER ) {
        }

    //
    //  Note that TerminateThread will not free thread's stack --
    //  that will be done by remote caller after thread wait is
    //  satisfied by this termination call.
    //

    ZwTerminateThread( NtCurrentThread(), 0 );
    }

//
//  Since RtlpDebugPageHeapRemoteThreadLock is not called from any code in
//  ntdll, the linker will discard it unless we create a reference to it.
//

PVOID RtlpDebugPageHeapRemoteThreadLockAddress = RtlpDebugPageHeapRemoteThreadLock;


LOCAL_FUNCTION
PDPH_STACK_TRACE_NODE
RtlpDebugPageHeapNewStackTraceStorage(
    IN PDPH_HEAP_ROOT HeapRoot,
    IN ULONG          Length
    )
    {
    PDPH_HEAP_ALLOCATION  pAvailNode, pPrevNode, pStackNode;
    PDPH_STACK_TRACE_NODE Return;
    PUCHAR                pVirtual;
    ULONG                 nRequest;
    ULONG                 Size;

    Size = sizeof( DPH_STACK_TRACE_NODE ) + ( Length * sizeof( PVOID ));

    if ( Size > HeapRoot->nStackTraceStorage ) {

        nRequest = POOL_SIZE;

        pAvailNode = RtlpDebugPageHeapFindAvailableMem(
                         HeapRoot,
                         nRequest,
                         &pPrevNode,
                         TRUE
                         );

        if ( pAvailNode == NULL ) {

            //
            //  Reduce request size to PAGE_SIZE and see if
            //  we can find at least a page on the available
            //  list.
            //

            nRequest = PAGE_SIZE;

            pAvailNode = RtlpDebugPageHeapFindAvailableMem(
                             HeapRoot,
                             nRequest,
                             &pPrevNode,
                             TRUE
                             );

            }

        if ( pAvailNode == NULL )
            return NULL;

        pVirtual = pAvailNode->pVirtualBlock;

        if ( ! RtlpDebugPageHeapProtectVM( pVirtual, nRequest, PAGE_READWRITE )) {
            return NULL;
            }

        //
        //  pAvailNode (still on avail list) points to block large enough
        //  to satisfy request, but it might be large enough to split
        //  into two blocks -- one for request, remainder leave on
        //  avail list.
        //

        if ( pAvailNode->nVirtualBlockSize > nRequest ) {

            //
            //  Adjust pVirtualBlock and nVirtualBlock size of existing
            //  node in avail list.  The node will still be in correct
            //  address space order on the avail list.  This saves having
            //  to remove and then re-add node to avail list.  Note since
            //  we're changing sizes directly, we need to adjust the
            //  avail list counters manually.
            //
            //  Note: since we're leaving at least one page on the
            //  available list, we are guaranteed that AllocateNode
            //  will not fail.
            //

            pAvailNode->pVirtualBlock                    += nRequest;
            pAvailNode->nVirtualBlockSize                -= nRequest;
            HeapRoot->nAvailableAllocationBytesCommitted -= nRequest;

            pStackNode = RtlpDebugPageHeapAllocateNode( HeapRoot );

            DEBUG_ASSERT( pStackNode != NULL );

            pStackNode->pVirtualBlock     = pVirtual;
            pStackNode->nVirtualBlockSize = nRequest;

            }

        else {

            //
            //  Entire avail block is needed, so simply remove it from avail list.
            //

            RtlpDebugPageHeapRemoveFromAvailableList( HeapRoot, pAvailNode, pPrevNode );

            pStackNode = pAvailNode;

            }

        HeapRoot->nStackTraceBytesWasted    += HeapRoot->nStackTraceStorage;
        HeapRoot->nStackTraceBytesCommitted += nRequest;

        //
        //  Note: we're wasting the remaining HeapRoot->nStackTraceStorage
        //  bytes here.
        //

        HeapRoot->pStackTraceStorage = pVirtual;
        HeapRoot->nStackTraceStorage = nRequest;

        RtlpDebugPageHeapPlaceOnPoolList( HeapRoot, pStackNode );

        }

    Return = (PVOID) HeapRoot->pStackTraceStorage;

    HeapRoot->pStackTraceStorage += Size;
    HeapRoot->nStackTraceStorage -= Size;
    HeapRoot->nStackTraceBNodes++;

    return Return;
    }


LOCAL_FUNCTION
PDPH_STACK_TRACE_NODE
RtlpDebugPageHeapFindOrAddStackTrace(
    IN PDPH_HEAP_ROOT HeapRoot,
    IN ULONG          HashValue,
    IN ULONG          Length,
    IN PVOID*         Address
    )
    {
    PDPH_STACK_TRACE_NODE Node;
    PDPH_STACK_TRACE_NODE NewNode;
    ULONG                 Depth;

    Node    = HeapRoot->pStackTraceRoot;        // assume non-NULL
    NewNode = NULL;
    Depth   = 0;

    for (;;) {

        Depth++;

        if ( Node->Hash > HashValue ) {         // go left
            if ( Node->Left ) {
                Node = Node->Left;
                }
            else {

                NewNode = RtlpDebugPageHeapNewStackTraceStorage(
                              HeapRoot,
                              Length
                              );

                Node->Left = NewNode;
                break;
                }
            }

        else if ( Node->Hash < HashValue ) {    // go right
            if ( Node->Right ) {
                Node = Node->Right;
                }
            else {

                NewNode = RtlpDebugPageHeapNewStackTraceStorage(
                              HeapRoot,
                              Length
                              );

                Node->Right = NewNode;
                break;
                }
            }
        else {  // ( Node->Hash == HashValue ), verify matching data or rehash

            if (( Node->Length == Length ) &&
                ( RtlCompareMemory( Node->Address, Address, Length ) == Length )) {

                //
                //  Complete match, return this Node.
                //

                return Node;
                }

            else {

                //
                //  Not a match, increment hash value by one and search again
                //  (slow linear-rehashing, but don't expect many collisions).
                //

                HashValue++;
                Node  = HeapRoot->pStackTraceRoot;
                Depth = 0;

                HeapRoot->nStackTraceBHashCollisions++;

                }
            }
        }

    if ( NewNode != NULL ) {

        NewNode->Left      = NULL;
        NewNode->Right     = NULL;
        NewNode->Hash      = HashValue;
        NewNode->Length    = Length;
        NewNode->BusyCount = 0;
        NewNode->BusyBytes = 0;

        RtlCopyMemory( NewNode->Address, Address, Length * sizeof( PVOID ));

        if ( ++Depth > HeapRoot->nStackTraceBDepth ) {
            HeapRoot->nStackTraceBDepth = Depth;
            }
        }

    return NewNode;
    }


#if (( i386 ) && ( FPO ))
#pragma optimize( "y", off )    // disable FPO for consistent stack traces
#endif

LOCAL_FUNCTION
UCHAR
RtlpDebugPageHeapCaptureStackTrace(
    IN  UCHAR  FramesToSkip,
    IN  UCHAR  FramesToCapture,
    OUT PVOID* TraceBuffer,
    OUT PULONG HashValue
    )
    {
    UCHAR FramesCaptured;

    RtlZeroMemory( TraceBuffer, FramesToCapture * sizeof( PVOID ));

    *HashValue = 0;

    try {

        FramesCaptured = (UCHAR) RtlCaptureStackBackTrace(
                                    (UCHAR)( FramesToSkip + 1 ),
                                    FramesToCapture,
                                    TraceBuffer,
                                    HashValue
                                    );

        //
        //  Sometimes the final frame is NULL: if so, we'll strip it
        //  for smaller storage.
        //

        if (( FramesCaptured ) && ( ! TraceBuffer[ FramesCaptured - 1 ] )) {
            --FramesCaptured;
            }

        }

    except( EXCEPTION_EXECUTE_HANDLER ) {

        FramesCaptured = 0;

        while (( FramesCaptured < FramesToCapture ) &&
               ( TraceBuffer[ FramesCaptured ] != NULL )) {

            FramesCaptured++;

            }
        }

    return FramesCaptured;

    }


LOCAL_FUNCTION
PDPH_STACK_TRACE_NODE
RtlpDebugPageHeapCaptureAndStoreStackTrace(
    IN PDPH_HEAP_ROOT HeapRoot,
    IN UCHAR          FramesToSkip
    )
    {
    ULONG HashValue;
    ULONG FramesCaptured;

    FramesCaptured = RtlpDebugPageHeapCaptureStackTrace(
                         (UCHAR)( FramesToSkip + 1 ),
                         (UCHAR)( DPH_MAX_STACK_LENGTH ),
                         RtlpDebugPageHeapStackTraceBuffer,
                         &HashValue
                         );

    if ( FramesCaptured ) {

        return RtlpDebugPageHeapFindOrAddStackTrace(
                   HeapRoot,
                   HashValue,
                   FramesCaptured,
                   RtlpDebugPageHeapStackTraceBuffer
                   );
        }

    return NULL;

    }


#if (( i386 ) && ( FPO ))
#pragma optimize( "", on )      // restore original optimizations
#endif

#endif // DPH_CAPTURE_STACK_TRACE


///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////



//
//  Here's where the exported interface functions are defined.
//

#if (( DPH_CAPTURE_STACK_TRACE ) && ( i386 ) && ( FPO ))
#pragma optimize( "y", off )    // disable FPO for consistent stack traces
#endif


PVOID
RtlpDebugPageHeapCreate(
    IN ULONG Flags,
    IN PVOID HeapBase OPTIONAL,
    IN ULONG ReserveSize OPTIONAL,
    IN ULONG CommitSize OPTIONAL,
    IN PVOID Lock OPTIONAL,
    IN PRTL_HEAP_PARAMETERS Parameters OPTIONAL
    )
    {
    SYSTEM_BASIC_INFORMATION    SystemInfo;
    PDPH_HEAP_ALLOCATION        Node;
    PDPH_HEAP_ROOT              HeapRoot;
    PVOID                       HeapHandle;
    PUCHAR                      pVirtual;
    ULONG                       nVirtual;
    ULONG                       Size;
    NTSTATUS                    Status;

    //
    //  We don't handle heaps where HeapBase is already allocated
    //  from user or where Lock is provided by user.
    //

    DEBUG_ASSERT( HeapBase == NULL );
    DEBUG_ASSERT( Lock == NULL );

    if (( HeapBase != NULL ) || ( Lock != NULL ))
        return NULL;

    //
    //  Note that we simply ignore ReserveSize, CommitSize, and
    //  Parameters as we always have a growable heap with our
    //  own thresholds, etc.
    //

    ZwQuerySystemInformation( SystemBasicInformation,
                              &SystemInfo,
                              sizeof( SystemInfo ),
                              NULL );

    RETAIL_ASSERT( SystemInfo.PageSize == PAGE_SIZE );
    RETAIL_ASSERT( SystemInfo.AllocationGranularity == VM_UNIT_SIZE );
    DEBUG_ASSERT(( PAGE_SIZE + POOL_SIZE + PAGE_SIZE ) < VM_UNIT_SIZE );

    nVirtual = RESERVE_SIZE;
    pVirtual = RtlpDebugPageHeapAllocateVM( nVirtual );

    if ( pVirtual == NULL ) {

        nVirtual = VM_UNIT_SIZE;
        pVirtual = RtlpDebugPageHeapAllocateVM( nVirtual );

        if ( pVirtual == NULL ) {
            OUT_OF_VM_BREAK( Flags, "PAGEHEAP: Insufficient memory to create heap\n" );
            IF_GENERATE_EXCEPTION( Flags, STATUS_NO_MEMORY );
            return NULL;
            }
        }

    if ( ! RtlpDebugPageHeapProtectVM( pVirtual, PAGE_SIZE + POOL_SIZE + PAGE_SIZE, PAGE_READWRITE )) {
        RtlpDebugPageHeapReleaseVM( pVirtual );
        IF_GENERATE_EXCEPTION( Flags, STATUS_NO_MEMORY );
        return NULL;
        }

    //
    //  Out of our initial allocation, the initial page is the fake
    //  retail HEAP structure.  The second page begins our DPH_HEAP_ROOT
    //  structure followed by (POOL_SIZE-sizeof(DPH_HEAP_ROOT)) bytes for
    //  the initial pool.  The next page contains out CRIT_SECT
    //  variable, which must always be READWRITE.  Beyond that, the
    //  remainder of the virtual allocation is placed on the available
    //  list.
    //
    //  |_____|___________________|_____|__ _ _ _ _ _ _ _ _ _ _ _ _ __|
    //
    //  ^pVirtual
    //
    //  ^FakeRetailHEAP
    //
    //        ^HeapRoot
    //
    //            ^InitialNodePool
    //
    //                            ^CRITICAL_SECTION
    //
    //                                  ^AvailableSpace
    //
    //
    //
    //  Our DPH_HEAP_ROOT structure starts at the page following the
    //  fake retail HEAP structure pointed to by the "heap handle".
    //  For the fake HEAP structure, we'll fill it with 0xEEEEEEEE
    //  except for the Heap->Flags and Heap->ForceFlags fields,
    //  which we must set to include our HEAP_FLAG_PAGE_ALLOCS flag,
    //  and then we'll make the whole page read-only.
    //

    RtlFillMemory( pVirtual, PAGE_SIZE, FILL_BYTE );

    ((PHEAP)pVirtual)->Flags      = Flags | HEAP_FLAG_PAGE_ALLOCS;
    ((PHEAP)pVirtual)->ForceFlags = Flags | HEAP_FLAG_PAGE_ALLOCS;

    if ( ! RtlpDebugPageHeapProtectVM( pVirtual, PAGE_SIZE, PAGE_READONLY )) {
        RtlpDebugPageHeapReleaseVM( pVirtual );
        IF_GENERATE_EXCEPTION( Flags, STATUS_NO_MEMORY );
        return NULL;
        }

    HeapRoot = (PDPH_HEAP_ROOT)( pVirtual + PAGE_SIZE );

    HeapRoot->Signature    = DPH_HEAP_ROOT_SIGNATURE;
    HeapRoot->HeapFlags    = Flags;
    HeapRoot->HeapCritSect = (PVOID)((PCHAR)HeapRoot + POOL_SIZE );

    RtlInitializeCriticalSection( HeapRoot->HeapCritSect );

    //
    //  On the page that contains our DPH_HEAP_ROOT structure, use
    //  the remaining memory beyond the DPH_HEAP_ROOT structure as
    //  pool for allocating heap nodes.
    //

    RtlpDebugPageHeapAddNewPool( HeapRoot,
                                 HeapRoot + 1,
                                 POOL_SIZE - sizeof( DPH_HEAP_ROOT ),
                                 FALSE
                               );

    //
    //  Make initial PoolList entry by taking a node from the
    //  UnusedNodeList, which should be guaranteed to be non-empty
    //  since we just added new nodes to it.
    //

    Node = RtlpDebugPageHeapAllocateNode( HeapRoot );
    DEBUG_ASSERT( Node != NULL );
    Node->pVirtualBlock     = (PVOID)HeapRoot;
    Node->nVirtualBlockSize = POOL_SIZE;
    RtlpDebugPageHeapPlaceOnPoolList( HeapRoot, Node );

    //
    //  Make VirtualStorageList entry for initial VM allocation
    //

    Node = RtlpDebugPageHeapAllocateNode( HeapRoot );
    DEBUG_ASSERT( Node != NULL );
    Node->pVirtualBlock     = pVirtual;
    Node->nVirtualBlockSize = nVirtual;
    RtlpDebugPageHeapPlaceOnVirtualList( HeapRoot, Node );

    //
    //  Make AvailableList entry containing remainder of initial VM
    //  and add to (create) the AvailableList.
    //

    Node = RtlpDebugPageHeapAllocateNode( HeapRoot );
    DEBUG_ASSERT( Node != NULL );
    Node->pVirtualBlock     = pVirtual + ( PAGE_SIZE + POOL_SIZE + PAGE_SIZE );
    Node->nVirtualBlockSize = nVirtual - ( PAGE_SIZE + POOL_SIZE + PAGE_SIZE );
    RtlpDebugPageHeapCoalesceNodeIntoAvailable( HeapRoot, Node );

#if DPH_CAPTURE_STACK_TRACE

    HeapRoot->pStackTraceRoot = RtlpDebugPageHeapNewStackTraceStorage( HeapRoot, 0 );
    DEBUG_ASSERT( HeapRoot->pStackTraceRoot != NULL );
    HeapRoot->pStackTraceRoot->Left      = NULL;
    HeapRoot->pStackTraceRoot->Right     = NULL;
    HeapRoot->pStackTraceRoot->Hash      = 0;
    HeapRoot->pStackTraceRoot->BusyCount = 0;
    HeapRoot->pStackTraceRoot->BusyBytes = 0;
    HeapRoot->pStackTraceCreator = RtlpDebugPageHeapCaptureAndStoreStackTrace( HeapRoot, 1 );

#endif // DPH_CAPTURE_STACK_TRACE

    //
    //  Initialize heap internal structure protection.
    //

    HeapRoot->nUnProtectionReferenceCount = 1;          // initialize
    PROTECT_HEAP_STRUCTURES( HeapRoot );                // now protected

    //
    //  If this is the first heap creation in this process, then we
    //  need to initialize the process heap list critical section.
    //

    if ( ! RtlpDebugPageHeapListHasBeenInitialized ) {
        RtlpDebugPageHeapListHasBeenInitialized = TRUE;
        RtlInitializeCriticalSection( &RtlpDebugPageHeapListCritSect );
        }

    //
    //  Add this heap entry to the process heap linked list.
    //

    RtlEnterCriticalSection( &RtlpDebugPageHeapListCritSect );

    if ( RtlpDebugPageHeapListHead == NULL ) {
        RtlpDebugPageHeapListHead = HeapRoot;
        RtlpDebugPageHeapListTail = HeapRoot;
        }
    else {
        HeapRoot->pPrevHeapRoot = RtlpDebugPageHeapListTail;
        RtlpDebugPageHeapListTail->pNextHeapRoot = HeapRoot;
        RtlpDebugPageHeapListTail                = HeapRoot;
        }

    RtlpDebugPageHeapListCount++;

    RtlLeaveCriticalSection( &RtlpDebugPageHeapListCritSect );

    DEBUG_CODE( RtlpDebugPageHeapVerifyIntegrity( HeapRoot ));

    DbgPrint( "PAGEHEAP: process 0x%X created debug heap %08X\n",
              NtCurrentTeb()->ClientId.UniqueProcess,
              HEAP_HANDLE_FROM_ROOT( HeapRoot ));

    return HEAP_HANDLE_FROM_ROOT( HeapRoot );       // same as pVirtual
    }


PVOID
RtlpDebugPageHeapAllocate(
    IN PVOID HeapHandle,
    IN ULONG Flags,
    IN ULONG Size
    )
    {
    PDPH_HEAP_ROOT       HeapRoot;
    PDPH_HEAP_ALLOCATION pAvailNode;
    PDPH_HEAP_ALLOCATION pPrevAvailNode;
    PDPH_HEAP_ALLOCATION pBusyNode;
    ULONG                nBytesAllocate;
    ULONG                nBytesAccess;
    ULONG                nActual;
    PVOID                pVirtual;
    PVOID                pReturn;
    PUCHAR               pBlockHeader;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return NULL;

    Flags |= HeapRoot->HeapFlags;

    //
    //  Acquire the heap CritSect and unprotect the structures
    //

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );
    DEBUG_CODE( RtlpDebugPageHeapVerifyIntegrity( HeapRoot ));
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    pReturn = NULL;

    //
    //  Validate requested size so we don't overflow
    //  while rounding up size computations.  We do this
    //  after we've acquired the critsect so we can still
    //  catch serialization problems.
    //

    if ( Size > 0x7FFF0000 ) {
        OUT_OF_VM_BREAK( Flags, "PAGEHEAP: Invalid allocation size\n" );
        goto EXIT;
        }

    //
    //  Determine number of pages needed for READWRITE portion
    //  of allocation and add an extra page for the NO_ACCESS
    //  memory beyond the READWRITE page(s).
    //

    nBytesAccess  = ROUNDUP2( Size, PAGE_SIZE );
    nBytesAllocate = nBytesAccess + PAGE_SIZE;

    //
    //  RtlpDebugPageHeapFindAvailableMem will first attempt to satisfy
    //  the request from memory on the Available list.  If that fails,
    //  it will coalesce some of the Free list memory into the Available
    //  list and try again.  If that still fails, new VM is allocated and
    //  added to the Available list.  If that fails, the function will
    //  finally give up and return NULL.
    //

    pAvailNode = RtlpDebugPageHeapFindAvailableMem(
                     HeapRoot,
                     nBytesAllocate,
                     &pPrevAvailNode,
                     TRUE
                     );

    if ( pAvailNode == NULL ) {
        OUT_OF_VM_BREAK( Flags, "PAGEHEAP: Unable to allocate virtual memory\n" );
        goto EXIT;
        }

    //
    //  Now can't call AllocateNode until pAvailNode is
    //  adjusted and/or removed from Avail list since AllocateNode
    //  might adjust the Avail list.
    //

    pVirtual = pAvailNode->pVirtualBlock;

    if ( nBytesAccess > 0 ) {
        if ( ! RtlpDebugPageHeapProtectVM( pVirtual, nBytesAccess, PAGE_READWRITE )) {
            goto EXIT;
            }
        }

    //
    //  pAvailNode (still on avail list) points to block large enough
    //  to satisfy request, but it might be large enough to split
    //  into two blocks -- one for request, remainder leave on
    //  avail list.
    //

    if ( pAvailNode->nVirtualBlockSize > nBytesAllocate ) {

        //
        //  Adjust pVirtualBlock and nVirtualBlock size of existing
        //  node in avail list.  The node will still be in correct
        //  address space order on the avail list.  This saves having
        //  to remove and then re-add node to avail list.  Note since
        //  we're changing sizes directly, we need to adjust the
        //  avail and busy list counters manually.
        //
        //  Note: since we're leaving at least one page on the
        //  available list, we are guaranteed that AllocateNode
        //  will not fail.
        //

        pAvailNode->pVirtualBlock                    += nBytesAllocate;
        pAvailNode->nVirtualBlockSize                -= nBytesAllocate;
        HeapRoot->nAvailableAllocationBytesCommitted -= nBytesAllocate;

        pBusyNode = RtlpDebugPageHeapAllocateNode( HeapRoot );

        DEBUG_ASSERT( pBusyNode != NULL );

        pBusyNode->pVirtualBlock     = pVirtual;
        pBusyNode->nVirtualBlockSize = nBytesAllocate;

        }

    else {

        //
        //  Entire avail block is needed, so simply remove it from avail list.
        //

        RtlpDebugPageHeapRemoveFromAvailableList( HeapRoot, pAvailNode, pPrevAvailNode );

        pBusyNode = pAvailNode;

        }

    //
    //  Now pBusyNode points to our committed virtual block.
    //

    if ( HeapRoot->HeapFlags & HEAP_NO_ALIGNMENT )
        nActual = Size;
    else
        nActual = ROUNDUP2( Size, USER_ALIGNMENT );

    pBusyNode->nVirtualAccessSize = nBytesAccess;
    pBusyNode->nUserRequestedSize = Size;
    pBusyNode->nUserActualSize    = nActual;
    pBusyNode->pUserAllocation    = pBusyNode->pVirtualBlock
                                  + pBusyNode->nVirtualAccessSize
                                  - nActual;
    pBusyNode->UserValue          = NULL;
    pBusyNode->UserFlags          = Flags & HEAP_SETTABLE_USER_FLAGS;

#if DPH_CAPTURE_STACK_TRACE

    //
    //  RtlpDebugPageHeapAllocate gets called from RtlDebugAllocateHeap,
    //  which gets called from RtlAllocateHeapSlowly, which gets called
    //  from RtlAllocateHeap.  To keep from wasting lots of stack trace
    //  storage, we'll skip the bottom 3 entries, leaving RtlAllocateHeap
    //  as the first recorded entry.
    //

    pBusyNode->pStackTrace = RtlpDebugPageHeapCaptureAndStoreStackTrace( HeapRoot, 3 );

    if ( pBusyNode->pStackTrace ) {
         pBusyNode->pStackTrace->BusyCount += 1;
         pBusyNode->pStackTrace->BusyBytes += pBusyNode->nUserRequestedSize;
         }

#endif

    RtlpDebugPageHeapPlaceOnBusyList( HeapRoot, pBusyNode );

    pReturn = pBusyNode->pUserAllocation;

    //
    //  For requests the specify HEAP_ZERO_MEMORY, we'll fill the
    //  user-requested portion of the block with zeros, but the
    //  16 bytes (HEAD_FILL_SIZE) before the block and the odd
    //  alignment bytes beyond the requested size up to the end of
    //  the page are filled with 0xEEEEEEEE.  For requests that
    //  don't specify HEAP_ZERO_MEMORY, we fill the whole request
    //  including the 16 bytes before the block and the alignment
    //  bytes beyond the block with 0xEEEEEEEE.
    //

    pBlockHeader = pBusyNode->pUserAllocation - HEAD_FILL_SIZE;

    if ( pBlockHeader < pBusyNode->pVirtualBlock )
        pBlockHeader = pBusyNode->pVirtualBlock;

    if ( Flags & HEAP_ZERO_MEMORY ) {

        RtlFillMemory( pBlockHeader,
                       pBusyNode->pUserAllocation - pBlockHeader,
                       FILL_BYTE );

        RtlZeroMemory( pBusyNode->pUserAllocation, Size );

        RtlFillMemory( pBusyNode->pUserAllocation + Size,
                       nActual - Size,
                       FILL_BYTE );
        }
    else {

        RtlFillMemory( pBlockHeader,
                       pBusyNode->pUserAllocation + nActual - pBlockHeader,
                       FILL_BYTE );

        }

EXIT:

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    DEBUG_CODE( RtlpDebugPageHeapVerifyIntegrity( HeapRoot ));
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    if ( pReturn == NULL ) {
        IF_GENERATE_EXCEPTION( Flags, STATUS_NO_MEMORY );
        }

    return pReturn;

    }


BOOLEAN
RtlpDebugPageHeapFree(
    IN PVOID HeapHandle,
    IN ULONG Flags,
    IN PVOID Address
    )
    {

    PDPH_HEAP_ROOT       HeapRoot;
    PDPH_HEAP_ALLOCATION Node, Prev;
    BOOLEAN              Success;
    PCH                  p;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return FALSE;

    if ( Address == NULL )
        return TRUE;            // for C++ apps that delete NULL

    Flags |= HeapRoot->HeapFlags;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );
    DEBUG_CODE( RtlpDebugPageHeapVerifyIntegrity( HeapRoot ));
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    Success = FALSE;

    Node = RtlpDebugPageHeapFindBusyMem( HeapRoot, Address, &Prev );

    if ( Node == NULL ) {
        RtlpDebugPageHeapBreak( "PAGEHEAP: Attempt to reference block which is not allocated\n" );
        goto EXIT;
        }

    //
    //  If tail was allocated, make sure filler not overwritten
    //

    if ( Node->nUserActualSize > Node->nUserRequestedSize ) {
        RtlpDebugPageHeapDetectFillCorruption( Node );
        }

    if ( Node->nVirtualAccessSize > 0 ) {
        RtlpDebugPageHeapProtectVM( Node->pVirtualBlock,
                                    Node->nVirtualAccessSize,
                                    PAGE_NOACCESS );
        }

    RtlpDebugPageHeapRemoveFromBusyList( HeapRoot, Node, Prev );

    RtlpDebugPageHeapPlaceOnFreeList( HeapRoot, Node );

#if DPH_CAPTURE_STACK_TRACE

    //
    //  RtlpDebugPageHeapFree gets called from RtlDebugFreeHeap, which
    //  gets called from RtlFreeHeapSlowly, which gets called from
    //  RtlFreeHeap.  To keep from wasting lots of stack trace storage,
    //  we'll skip the bottom 3 entries, leaving RtlFreeHeap as the
    //  first recorded entry.
    //

    if ( Node->pStackTrace ) {
         if ( Node->pStackTrace->BusyCount > 0 ) {
              Node->pStackTrace->BusyCount -= 1;
              Node->pStackTrace->BusyBytes -= Node->nUserRequestedSize;
              }
         }

    Node->pStackTrace = RtlpDebugPageHeapCaptureAndStoreStackTrace( HeapRoot, 3 );

#endif

    Success = TRUE;

EXIT:

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    DEBUG_CODE( RtlpDebugPageHeapVerifyIntegrity( HeapRoot ));
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    if ( ! Success ) {
        IF_GENERATE_EXCEPTION( Flags, STATUS_ACCESS_VIOLATION );
        }

    return Success;
    }


PVOID
RtlpDebugPageHeapReAllocate(
    IN PVOID HeapHandle,
    IN ULONG Flags,
    IN PVOID Address,
    IN ULONG Size
    )
    {
    PDPH_HEAP_ROOT       HeapRoot;
    PDPH_HEAP_ALLOCATION OldNode, OldPrev, NewNode;
    PVOID                NewAddress;
    PUCHAR               p;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return NULL;

    Flags |= HeapRoot->HeapFlags;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );
    DEBUG_CODE( RtlpDebugPageHeapVerifyIntegrity( HeapRoot ));
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    NewAddress = NULL;

    //
    //  Check Flags for non-moveable reallocation and fail it
    //  unconditionally.  Apps that specify this flag should be
    //  prepared to deal with failure anyway.
    //

    if ( Flags & HEAP_REALLOC_IN_PLACE_ONLY ) {
        goto EXIT;
        }

    //
    //  Validate requested size so we don't overflow
    //  while rounding up size computations.  We do this
    //  after we've acquired the critsect so we can still
    //  catch serialization problems.
    //

    if ( Size > 0x7FFF0000 ) {
        OUT_OF_VM_BREAK( Flags, "PAGEHEAP: Invalid allocation size\n" );
        goto EXIT;
        }

    OldNode = RtlpDebugPageHeapFindBusyMem( HeapRoot, Address, &OldPrev );

    if ( OldNode == NULL ) {
        RtlpDebugPageHeapBreak( "PAGEHEAP: Attempt to reference block which is not allocated\n" );
        goto EXIT;
        }

    //
    //  If tail was allocated, make sure filler not overwritten
    //

    if ( OldNode->nUserActualSize > OldNode->nUserRequestedSize ) {
        RtlpDebugPageHeapDetectFillCorruption( OldNode );
        }

    //
    //  Before allocating a new block, remove the old block from
    //  the busy list.  When we allocate the new block, the busy
    //  list pointers will change, possibly leaving our acquired
    //  Prev pointer invalid.
    //

    RtlpDebugPageHeapRemoveFromBusyList( HeapRoot, OldNode, OldPrev );

    //
    //  Allocate new memory for new requested size.  Use try/except
    //  to trap exception if Flags caused out-of-memory exception.
    //

    try {
        NewAddress = RtlpDebugPageHeapAllocate( HeapHandle, Flags, Size );
        }
    except( EXCEPTION_EXECUTE_HANDLER ) {
        }

    if ( NewAddress ) {

        RtlCopyMemory(
            NewAddress,
            Address,
            ( OldNode->nUserActualSize < Size ) ?
              OldNode->nUserActualSize : Size
            );

        NewNode = RtlpDebugPageHeapFindBusyMem( HeapRoot, NewAddress, NULL );

        DEBUG_ASSERT( NewNode != NULL );

        NewNode->UserValue = OldNode->UserValue;
        NewNode->UserFlags = ( Flags & HEAP_SETTABLE_USER_FLAGS ) ?
                             ( Flags & HEAP_SETTABLE_USER_FLAGS ) :
                             OldNode->UserFlags;

        if ( OldNode->nVirtualAccessSize > 0 ) {
            RtlpDebugPageHeapProtectVM( OldNode->pVirtualBlock,
                                        OldNode->nVirtualAccessSize,
                                        PAGE_NOACCESS );
            }

        RtlpDebugPageHeapPlaceOnFreeList( HeapRoot, OldNode );

#if DPH_CAPTURE_STACK_TRACE

        //
        //  RtlpDebugPageHeapReAllocate gets called from RtlDebugReAllocateHeap,
        //  which gets called from RtlReAllocateHeap.  To keep from wasting
        //  lots of stack trace storage, we'll skip the bottom 2 entries,
        //  leaving RtlReAllocateHeap as the first recorded entry in the
        //  freed stack trace.
        //

        if ( OldNode->pStackTrace ) {
            if ( OldNode->pStackTrace->BusyCount > 0 ) {
                 OldNode->pStackTrace->BusyCount -= 1;
                 OldNode->pStackTrace->BusyBytes -= OldNode->nUserRequestedSize;
                 }
            }

        OldNode->pStackTrace = RtlpDebugPageHeapCaptureAndStoreStackTrace( HeapRoot, 2 );

#endif
        }

    else {

        //
        //  Failed to allocate a new block.  Return old block to busy list.
        //

        RtlpDebugPageHeapPlaceOnBusyList( HeapRoot, OldNode );

        }

EXIT:

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    DEBUG_CODE( RtlpDebugPageHeapVerifyIntegrity( HeapRoot ));
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    if ( NewAddress == NULL ) {
        IF_GENERATE_EXCEPTION( Flags, STATUS_NO_MEMORY );
        }

    return NewAddress;
    }


#if (( DPH_CAPTURE_STACK_TRACE ) && ( i386 ) && ( FPO ))
#pragma optimize( "", on )      // restore original optimizations
#endif


PVOID
RtlpDebugPageHeapDestroy(
    IN PVOID HeapHandle
    )
    {
    PDPH_HEAP_ROOT       HeapRoot;
    PDPH_HEAP_ROOT       PrevHeapRoot;
    PDPH_HEAP_ROOT       NextHeapRoot;
    PDPH_HEAP_ALLOCATION Node;
    PDPH_HEAP_ALLOCATION Next;
    ULONG                Flags;
    PUCHAR               p;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return NULL;

    Flags = HeapRoot->HeapFlags | HEAP_NO_SERIALIZE;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );
    DEBUG_CODE( RtlpDebugPageHeapVerifyIntegrity( HeapRoot ));
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    //
    //  Walk all busy allocations and check for tail fill corruption
    //

    Node = HeapRoot->pBusyAllocationListHead;

    while ( Node ) {

        if ( Node->nUserActualSize > Node->nUserRequestedSize ) {
            RtlpDebugPageHeapDetectFillCorruption( Node );
            }

        Node = Node->pNextAlloc;
        }

    //
    //  Remove this heap entry from the process heap linked list.
    //

    RtlEnterCriticalSection( &RtlpDebugPageHeapListCritSect );

    if ( HeapRoot->pPrevHeapRoot ) {
         HeapRoot->pPrevHeapRoot->pNextHeapRoot = HeapRoot->pNextHeapRoot;
         }
    else {
         RtlpDebugPageHeapListHead = HeapRoot->pNextHeapRoot;
         }

    if ( HeapRoot->pNextHeapRoot ) {
         HeapRoot->pNextHeapRoot->pPrevHeapRoot = HeapRoot->pPrevHeapRoot;
         }
    else {
         RtlpDebugPageHeapListTail = HeapRoot->pPrevHeapRoot;
         }

    RtlpDebugPageHeapListCount--;

    RtlLeaveCriticalSection( &RtlpDebugPageHeapListCritSect );


    //
    //  Must release critical section before deleting it; otherwise,
    //  checked build Teb->CountOfOwnedCriticalSections gets out of sync.
    //

    RtlLeaveCriticalSection( HeapRoot->HeapCritSect );
    RtlDeleteCriticalSection( HeapRoot->HeapCritSect );

    //
    //  This is weird.  A virtual block might contain storage for
    //  one of the nodes necessary to walk this list.  In fact,
    //  we're guaranteed that the root node contains at least one
    //  virtual alloc node.
    //
    //  Each time we alloc new VM, we make that the head of the
    //  of the VM list, like a LIFO structure.  I think we're ok
    //  because no VM list node should be on a subsequently alloc'd
    //  VM -- only a VM list entry might be on its own memory (as
    //  is the case for the root node).  We read pNode->pNextAlloc
    //  before releasing the VM in case pNode existed on that VM.
    //  I think this is safe -- as long as the VM list is LIFO and
    //  we don't do any list reorganization.
    //

    Node = HeapRoot->pVirtualStorageListHead;

    while ( Node ) {
        Next = Node->pNextAlloc;
        if ( ! RtlpDebugPageHeapReleaseVM( Node->pVirtualBlock )) {
            RtlpDebugPageHeapBreak( "PAGEHEAP: Unable to release virtual memory\n" );
            }
        Node = Next;
        }

    //
    //  That's it.  All the VM, including the root node, should now
    //  be released.  RtlDestroyHeap always returns NULL.
    //

    return NULL;

    }


ULONG
RtlpDebugPageHeapSize(
    IN PVOID HeapHandle,
    IN ULONG Flags,
    IN PVOID Address
    )
    {
    PDPH_HEAP_ROOT       HeapRoot;
    PDPH_HEAP_ALLOCATION Node;
    ULONG                Size;

    Size = 0xFFFFFFFF;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL ) {
        return Size;
        }

    Flags |= HeapRoot->HeapFlags;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    Node = RtlpDebugPageHeapFindBusyMem( HeapRoot, Address, NULL );

    if ( Node == NULL ) {
        RtlpDebugPageHeapBreak( "PAGEHEAP: Attempt to reference block which is not allocated\n" );
        }
    else {
        Size = Node->nUserRequestedSize;
        }

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    if ( Size == 0xFFFFFFFF ) {
        IF_GENERATE_EXCEPTION( Flags, STATUS_ACCESS_VIOLATION );
        }

    return Size;
    }


ULONG
RtlpDebugPageHeapGetProcessHeaps(
    ULONG NumberOfHeaps,
    PVOID *ProcessHeaps
    )
    {
    PDPH_HEAP_ROOT HeapRoot;
    ULONG          Count;

    //
    //  Although we'd expect GetProcessHeaps never to be called
    //  before at least the very first heap creation, we should
    //  still be safe and initialize the critical section if
    //  necessary.
    //

    if ( ! RtlpDebugPageHeapListHasBeenInitialized ) {
        RtlpDebugPageHeapListHasBeenInitialized = TRUE;
        RtlInitializeCriticalSection( &RtlpDebugPageHeapListCritSect );
        }

    RtlEnterCriticalSection( &RtlpDebugPageHeapListCritSect );

    if ( RtlpDebugPageHeapListCount <= NumberOfHeaps ) {

        for ( HeapRoot  = RtlpDebugPageHeapListHead, Count = 0;
              HeapRoot != NULL;
              HeapRoot  = HeapRoot->pNextHeapRoot, Count++ ) {

            *ProcessHeaps++ = HEAP_HANDLE_FROM_ROOT( HeapRoot );
            }

        if ( Count != RtlpDebugPageHeapListCount ) {
            RtlpDebugPageHeapBreak( "PAGEHEAP: BUG: process heap list count wrong\n" );
            }

        }
    else {

        //
        //  User's buffer is too small.  Return number of entries
        //  necessary for subsequent call to succeed.  Buffer
        //  remains untouched.
        //

        Count = RtlpDebugPageHeapListCount;

        }

    RtlLeaveCriticalSection( &RtlpDebugPageHeapListCritSect );

    return Count;
    }


ULONG
RtlpDebugPageHeapCompact(
    IN PVOID HeapHandle,
    IN ULONG Flags
    )
    {
    PDPH_HEAP_ROOT HeapRoot;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return 0;

    Flags |= HeapRoot->HeapFlags;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );

    //
    //  Don't do anything, but we did want to acquire the critsect
    //  in case this was called with HEAP_NO_SERIALIZE while another
    //  thread is in the heap code.
    //

    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    return 0;

    }



BOOLEAN
RtlpDebugPageHeapValidate(
    IN PVOID HeapHandle,
    IN ULONG Flags,
    IN PVOID Address
    )
    {
    PDPH_HEAP_ROOT       HeapRoot;
    PDPH_HEAP_ALLOCATION Node;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return FALSE;

    Flags |= HeapRoot->HeapFlags;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );
    DEBUG_CODE( RtlpDebugPageHeapVerifyIntegrity( HeapRoot ));
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    Node = Address ? RtlpDebugPageHeapFindBusyMem( HeapRoot, Address, NULL ) : NULL;

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    return ( Address ? ( Node != NULL ) : TRUE );
    }


NTSTATUS
RtlpDebugPageHeapWalk(
    IN PVOID HeapHandle,
    IN OUT PRTL_HEAP_WALK_ENTRY Entry
    )
    {
    RtlpDebugPageHeapBreak( "PAGEHEAP: Not implemented\n" );
    return STATUS_UNSUCCESSFUL;
    }


BOOLEAN
RtlpDebugPageHeapLock(
    IN PVOID HeapHandle
    )
    {
    PDPH_HEAP_ROOT HeapRoot;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return FALSE;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, HeapRoot->HeapFlags );

    return TRUE;
    }


BOOLEAN
RtlpDebugPageHeapUnlock(
    IN PVOID HeapHandle
    )
    {
    PDPH_HEAP_ROOT HeapRoot;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return FALSE;

    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    return TRUE;
    }


BOOLEAN
RtlpDebugPageHeapSetUserValue(
    IN PVOID HeapHandle,
    IN ULONG Flags,
    IN PVOID Address,
    IN PVOID UserValue
    )
    {
    PDPH_HEAP_ROOT       HeapRoot;
    PDPH_HEAP_ALLOCATION Node;
    BOOLEAN              Success;

    Success = FALSE;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return Success;

    Flags |= HeapRoot->HeapFlags;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    Node = RtlpDebugPageHeapFindBusyMem( HeapRoot, Address, NULL );

    if ( Node == NULL ) {
        RtlpDebugPageHeapBreak( "PAGEHEAP: Attempt to reference block which is not allocated\n" );
        }
    else {
        Node->UserValue = UserValue;
        Success = TRUE;
        }

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    return Success;
    }


BOOLEAN
RtlpDebugPageHeapGetUserInfo(
    IN  PVOID  HeapHandle,
    IN  ULONG  Flags,
    IN  PVOID  Address,
    OUT PVOID* UserValue,
    OUT PULONG UserFlags
    )
    {
    PDPH_HEAP_ROOT       HeapRoot;
    PDPH_HEAP_ALLOCATION Node;
    BOOLEAN              Success;

    Success = FALSE;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return Success;

    Flags |= HeapRoot->HeapFlags;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    Node = RtlpDebugPageHeapFindBusyMem( HeapRoot, Address, NULL );

    if ( Node == NULL ) {
        RtlpDebugPageHeapBreak( "PAGEHEAP: Attempt to reference block which is not allocated\n" );
        }
    else {
        if ( UserValue != NULL )
            *UserValue = Node->UserValue;
        if ( UserFlags != NULL )
            *UserFlags = Node->UserFlags;
        Success = TRUE;
        }

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    return Success;
    }


BOOLEAN
RtlpDebugPageHeapSetUserFlags(
    IN PVOID HeapHandle,
    IN ULONG Flags,
    IN PVOID Address,
    IN ULONG UserFlagsReset,
    IN ULONG UserFlagsSet
    )
    {
    PDPH_HEAP_ROOT       HeapRoot;
    PDPH_HEAP_ALLOCATION Node;
    BOOLEAN              Success;

    Success = FALSE;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return Success;

    Flags |= HeapRoot->HeapFlags;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, Flags );
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    Node = RtlpDebugPageHeapFindBusyMem( HeapRoot, Address, NULL );

    if ( Node == NULL ) {
        RtlpDebugPageHeapBreak( "PAGEHEAP: Attempt to reference block which is not allocated\n" );
        }
    else {
        Node->UserFlags &= ~( UserFlagsReset );
        Node->UserFlags |=    UserFlagsSet;
        Success = TRUE;
        }

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    return Success;
    }


BOOLEAN
RtlpDebugPageHeapSerialize(
    IN PVOID HeapHandle
    )
    {
    PDPH_HEAP_ROOT HeapRoot;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return FALSE;

    RtlpDebugPageHeapEnterCritSect( HeapRoot, 0 );
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    HeapRoot->HeapFlags &= ~HEAP_NO_SERIALIZE;

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    return TRUE;
    }


NTSTATUS
RtlpDebugPageHeapExtend(
    IN PVOID HeapHandle,
    IN ULONG Flags,
    IN PVOID Base,
    IN ULONG Size
    )
    {
    return STATUS_SUCCESS;
    }


NTSTATUS
RtlpDebugPageHeapZero(
    IN PVOID HeapHandle,
    IN ULONG Flags
    )
    {
    return STATUS_SUCCESS;
    }


NTSTATUS
RtlpDebugPageHeapUsage(
    IN PVOID HeapHandle,
    IN ULONG Flags,
    IN OUT PRTL_HEAP_USAGE Usage
    )
    {
    PDPH_HEAP_ROOT HeapRoot;

    //
    //  Partial implementation since this information is kind of meaningless.
    //

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return STATUS_INVALID_PARAMETER;

    if ( Usage->Length != sizeof( RTL_HEAP_USAGE ))
        return STATUS_INFO_LENGTH_MISMATCH;

    memset( Usage, 0, sizeof( RTL_HEAP_USAGE ));
    Usage->Length = sizeof( RTL_HEAP_USAGE );

    RtlpDebugPageHeapEnterCritSect( HeapRoot, 0 );
    UNPROTECT_HEAP_STRUCTURES( HeapRoot );

    Usage->BytesAllocated       = HeapRoot->nBusyAllocationBytesAccessible;
    Usage->BytesCommitted       = HeapRoot->nVirtualStorageBytes;
    Usage->BytesReserved        = HeapRoot->nVirtualStorageBytes;
    Usage->BytesReservedMaximum = HeapRoot->nVirtualStorageBytes;

    PROTECT_HEAP_STRUCTURES( HeapRoot );
    RtlpDebugPageHeapLeaveCritSect( HeapRoot );

    return STATUS_SUCCESS;
    }


BOOLEAN
RtlpDebugPageHeapIsLocked(
    IN PVOID HeapHandle
    )
    {
    PDPH_HEAP_ROOT HeapRoot;

    HeapRoot = RtlpDebugPageHeapPointerFromHandle( HeapHandle );
    if ( HeapRoot == NULL )
        return FALSE;

    if ( RtlTryEnterCriticalSection( HeapRoot->HeapCritSect )) {
        RtlLeaveCriticalSection( HeapRoot->HeapCritSect );
        return FALSE;
        }
    else {
        return TRUE;
        }
    }


#endif // DEBUG_PAGE_HEAP