xemacs-beta / src / alloc.c

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

This file is part of XEmacs.

XEmacs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

XEmacs is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with XEmacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

/* Synched up with: FSF 19.28, Mule 2.0.  Substantially different from
   FSF. */

/* Authorship:

   FSF: Original version; a long time ago.
   Mly: Significantly rewritten to use new 3-bit tags and
        nicely abstracted object definitions, for 19.8.
   JWZ: Improved code to keep track of purespace usage and
        issue nice purespace and GC stats.
   Ben Wing: Cleaned up frob-block lrecord code, added error-checking
        and various changes for Mule, for 19.12.
        Added bit vectors for 19.13.
	Added lcrecord lists for 19.14.
*/

#include <config.h>
#include "lisp.h"
#include "sysdep.h"

#ifndef standalone
#include "backtrace.h"
#include "buffer.h"
#include "bytecode.h"
#include "chartab.h"
#include "device.h"
#include "elhash.h"
#include "events.h"
#include "extents.h"
#include "frame.h"
#include "glyphs.h"
#include "redisplay.h"
#include "specifier.h"
#include "window.h"
#endif

/* #define GDB_SUCKS */

/* #define VERIFY_STRING_CHARS_INTEGRITY */

/* Define this to see where all that space is going... */
/* But the length of the printout is obnoxious, so limit it to testers */
#ifdef DEBUG_XEMACS
#define PURESTAT
#endif

/* Define this to use malloc/free with no freelist for all datatypes,
   the hope being that some debugging tools may help detect
   freed memory references */
#ifdef USE_DEBUG_MALLOC	/* Taking the above comment at face value -slb */
#include <dmalloc.h>
#define ALLOC_NO_POOLS
#endif

#include "puresize.h"

#ifdef DEBUG_XEMACS
int debug_allocation;

int debug_allocation_backtrace_length;
#endif

/* Number of bytes of consing done since the last gc */
EMACS_INT consing_since_gc;
#ifdef EMACS_BTL
extern void cadillac_record_backtrace ();
#define INCREMENT_CONS_COUNTER_1(size)		\
  do {						\
    EMACS_INT __sz__ = ((EMACS_INT) (size));	\
    consing_since_gc += __sz__;			\
    cadillac_record_backtrace (2, __sz__);	\
  } while (0)
#else
#define INCREMENT_CONS_COUNTER_1(size) (consing_since_gc += (size))
#endif /* EMACS_BTL */

#define debug_allocation_backtrace()				\
do {								\
  if (debug_allocation_backtrace_length > 0)			\
    debug_short_backtrace (debug_allocation_backtrace_length);	\
} while (0)

#ifdef DEBUG_XEMACS
#define INCREMENT_CONS_COUNTER(foosize, type)			\
  do {								\
    if (debug_allocation)					\
      {								\
	stderr_out ("allocating %s (size %ld)\n", type, (long)foosize);	\
	debug_allocation_backtrace ();				\
      }								\
    INCREMENT_CONS_COUNTER_1 (foosize);				\
  } while (0)
#define NOSEEUM_INCREMENT_CONS_COUNTER(foosize, type)		\
  do {								\
    if (debug_allocation > 1)					\
      {								\
	stderr_out ("allocating noseeum %s (size %ld)\n", type, (long)foosize); \
	debug_allocation_backtrace ();				\
      }								\
    INCREMENT_CONS_COUNTER_1 (foosize);				\
  } while (0)
#else
#define INCREMENT_CONS_COUNTER(size, type) INCREMENT_CONS_COUNTER_1 (size)
#define NOSEEUM_INCREMENT_CONS_COUNTER(size, type) \
  INCREMENT_CONS_COUNTER_1 (size)
#endif

#define DECREMENT_CONS_COUNTER(size)		\
  do {						\
    EMACS_INT __sz__ = ((EMACS_INT) (size));	\
    if (consing_since_gc >= __sz__)		\
      consing_since_gc -= __sz__;		\
    else					\
      consing_since_gc = 0;			\
  } while (0)

/* Number of bytes of consing since gc before another gc should be done. */
EMACS_INT gc_cons_threshold;

/* Nonzero during gc */
int gc_in_progress;

/* Number of times GC has happened at this level or below.
 * Level 0 is most volatile, contrary to usual convention.
 *  (Of course, there's only one level at present) */
EMACS_INT gc_generation_number[1];

/* This is just for use by the printer, to allow things to print uniquely */
static int lrecord_uid_counter;

/* Nonzero when calling certain hooks or doing other things where
   a GC would be bad */
int gc_currently_forbidden;

/* Hooks. */
Lisp_Object Vpre_gc_hook, Qpre_gc_hook;
Lisp_Object Vpost_gc_hook, Qpost_gc_hook;

/* "Garbage collecting" */
Lisp_Object Vgc_message;
Lisp_Object Vgc_pointer_glyph;
static CONST char gc_default_message[] = "Garbage collecting";
Lisp_Object Qgarbage_collecting;

#ifndef VIRT_ADDR_VARIES
extern
#endif /* VIRT_ADDR_VARIES */
 EMACS_INT malloc_sbrk_used;

#ifndef VIRT_ADDR_VARIES
extern
#endif /* VIRT_ADDR_VARIES */
 EMACS_INT malloc_sbrk_unused;

/* Non-zero means defun should do purecopy on the function definition */
int purify_flag;

extern Lisp_Object pure[];/* moved to pure.c to speed incremental linking */

#define PUREBEG ((unsigned char *) pure)

/* Index in pure at which next pure object will be allocated. */
static long pureptr;

#define PURIFIED(ptr)							\
   ((uintptr_t) (ptr) <					\
    (uintptr_t) (PUREBEG + get_PURESIZE()) &&			\
    (uintptr_t) (ptr) >=					\
    (uintptr_t) PUREBEG)

/* Non-zero if pureptr > get_PURESIZE(); accounts for excess purespace needs. */
static long pure_lossage;

#ifdef ERROR_CHECK_TYPECHECK

Error_behavior ERROR_ME, ERROR_ME_NOT, ERROR_ME_WARN;

#endif

int
purified (Lisp_Object obj)
{
  return !POINTER_TYPE_P (XGCTYPE (obj)) ? 0 : PURIFIED (XPNTR (obj));
}

int
purespace_usage (void)
{
  return (int) pureptr;
}

static int
check_purespace (EMACS_INT size)
{
  if (pure_lossage)
    {
      pure_lossage += size;
      return 0;
    }
  else if (pureptr + size > get_PURESIZE())
    {
      /* This can cause recursive bad behavior, we'll yell at the end */
      /* when we're done. */
      /* message ("\nERROR:  Pure Lisp storage exhausted!\n"); */
      pure_lossage = size;
      return 0;
    }
  else
    return 1;
}



#ifndef PURESTAT

#define bump_purestat(p,b) do {} while (0) /* Do nothing */

#else /* PURESTAT */

static int purecopying_for_bytecode;

static int pure_sizeof (Lisp_Object /*, int recurse */);

/* Keep statistics on how much of what is in purespace */
static struct purestat
{
  int nobjects;
  int nbytes;
  CONST char *name;
}
  purestat_cons = {0, 0, "cons cells"},
  purestat_float = {0, 0, "float objects"},
  purestat_string_pname = {0, 0, "symbol-name strings"},
  purestat_bytecode = {0, 0, "compiled-function objects"},
  purestat_string_bytecodes = {0, 0, "byte-code strings"},
  purestat_vector_bytecode_constants = {0, 0, "byte-constant vectors"},
  purestat_string_interactive = {0, 0, "interactive strings"},
#ifdef I18N3
  purestat_string_domain = {0, 0, "domain strings"},
#endif
  purestat_string_documentation = {0, 0, "documentation strings"},
  purestat_string_other_function = {0, 0, "other function strings"},
  purestat_vector_other = {0, 0, "other vectors"},
  purestat_string_other = {0, 0, "other strings"},
  purestat_string_all = {0, 0, "all strings"},
  purestat_vector_all = {0, 0, "all vectors"};

static struct purestat *purestats[] =
{
  &purestat_cons,
  &purestat_float,
  &purestat_string_pname,
  &purestat_bytecode,
  &purestat_string_bytecodes,
  &purestat_vector_bytecode_constants,
  &purestat_string_interactive,
#ifdef I18N3
  &purestat_string_domain,
#endif
  &purestat_string_documentation,
  &purestat_string_other_function,
  &purestat_vector_other,
  &purestat_string_other,
  0,
  &purestat_string_all,
  &purestat_vector_all
};

static void
bump_purestat (struct purestat *purestat, int nbytes)
{
  if (pure_lossage) return;
  purestat->nobjects += 1;
  purestat->nbytes += nbytes;
}
#endif /* PURESTAT */


/* Maximum amount of C stack to save when a GC happens.  */

#ifndef MAX_SAVE_STACK
#define MAX_SAVE_STACK 16000
#endif

/* Buffer in which we save a copy of the C stack at each GC.  */

static char *stack_copy;
static int stack_copy_size;

/* Non-zero means ignore malloc warnings.  Set during initialization.  */
int ignore_malloc_warnings;


static void *breathing_space;

void
release_breathing_space (void)
{
  if (breathing_space)
    {
      void *tmp = breathing_space;
      breathing_space = 0;
      xfree (tmp);
    }
}

/* malloc calls this if it finds we are near exhausting storage */
void
malloc_warning (CONST char *str)
{
  if (ignore_malloc_warnings)
    return;

  warn_when_safe
    (Qmemory, Qcritical,
     "%s\n"
     "Killing some buffers may delay running out of memory.\n"
     "However, certainly by the time you receive the 95%% warning,\n"
     "you should clean up, kill this Emacs, and start a new one.",
     str);
}

/* Called if malloc returns zero */
DOESNT_RETURN
memory_full (void)
{
  /* Force a GC next time eval is called.
     It's better to loop garbage-collecting (we might reclaim enough
     to win) than to loop beeping and barfing "Memory exhausted"
   */
  consing_since_gc = gc_cons_threshold + 1;
  release_breathing_space ();

#ifndef standalone
  /* Flush some histories which might conceivably contain
   *  garbalogical inhibitors */
  if (!NILP (Fboundp (Qvalues)))
    Fset (Qvalues, Qnil);
  Vcommand_history = Qnil;
#endif

  error ("Memory exhausted");
}

/* like malloc and realloc but check for no memory left, and block input. */

#ifdef xmalloc
#undef xmalloc
#endif

void *
xmalloc (size_t size)
{
  void *val = (void *) malloc (size);

  if (!val && (size != 0)) memory_full ();
  return val;
}

void *
xmalloc_and_zero (size_t size)
{
  void *val = xmalloc (size);
  memset (val, 0, size);
  return val;
}

#ifdef xrealloc
#undef xrealloc
#endif

void *
xrealloc (void *block, size_t size)
{
  /* We must call malloc explicitly when BLOCK is 0, since some
     reallocs don't do this.  */
  void *val = (void *) (block ? realloc (block, size) : malloc (size));

  if (!val && (size != 0)) memory_full ();
  return val;
}

void
#ifdef ERROR_CHECK_MALLOC
xfree_1 (void *block)
#else
xfree (void *block)
#endif
{
#ifdef ERROR_CHECK_MALLOC
  /* Unbelievably, calling free() on 0xDEADBEEF doesn't cause an
     error until much later on for many system mallocs, such as
     the one that comes with Solaris 2.3.  FMH!! */
  assert (block != (void *) 0xDEADBEEF);
  assert (block);
#endif /* ERROR_CHECK_MALLOC */
  free (block);
}

#if INTBITS == 32
# define FOUR_BYTE_TYPE unsigned int
#elif LONGBITS == 32
# define FOUR_BYTE_TYPE unsigned long
#elif SHORTBITS == 32
# define FOUR_BYTE_TYPE unsigned short
#else
What kind of strange-ass system are we running on?
#endif

#ifdef ERROR_CHECK_GC

#ifdef WORDS_BIGENDIAN
static unsigned char deadbeef_as_char[] = {0xDE, 0xAD, 0xBE, 0xEF};
#else
static unsigned char deadbeef_as_char[] = {0xEF, 0xBE, 0xAD, 0xDE};
#endif

static void
deadbeef_memory (void *ptr, unsigned long size)
{
  unsigned long long_length = size / sizeof (FOUR_BYTE_TYPE);
  unsigned long i;
  unsigned long bytes_left_over = size - sizeof (FOUR_BYTE_TYPE) * long_length;

  for (i = 0; i < long_length; i++)
    ((FOUR_BYTE_TYPE *) ptr)[i] = 0xdeadbeef;
  for (i = i; i < bytes_left_over; i++)
    ((unsigned char *) ptr + long_length)[i] = deadbeef_as_char[i];
}

#else /* !ERROR_CHECK_GC */


#define deadbeef_memory(ptr, size)

#endif /* !ERROR_CHECK_GC */

#ifdef xstrdup
#undef xstrdup
#endif

char *
xstrdup (CONST char *str)
{
  int len = strlen (str) + 1;   /* for stupid terminating 0 */

  void *val = xmalloc (len);
  if (val == 0) return 0;
  memcpy (val, str, len);
  return (char *) val;
}

#ifdef NEED_STRDUP
char *
strdup (CONST char *s)
{
  return xstrdup (s);
}
#endif /* NEED_STRDUP */


static void *
allocate_lisp_storage (int size)
{
  void *p = xmalloc (size);
  char *lim = ((char *) p) + size;
  Lisp_Object val = Qnil;

  XSETOBJ (val, Lisp_Type_Record, lim);
  if ((char *) XPNTR (val) != lim)
    {
      xfree (p);
      memory_full ();
    }
  return p;
}


/* lrecords are chained together through their "next.v" field.
 * After doing the mark phase, the GC will walk this linked
 *  list and free any record which hasn't been marked
 */
static struct lcrecord_header *all_lcrecords;

int lrecord_type_index (CONST struct lrecord_implementation *implementation);

void *
alloc_lcrecord (int size, CONST struct lrecord_implementation *implementation)
{
  struct lcrecord_header *lcheader;

  if (size <= 0) abort ();
  if (implementation->static_size == 0)
    {
      if (!implementation->size_in_bytes_method)
	abort ();
    }
  else if (implementation->static_size != size)
    abort ();

  lcheader = (struct lcrecord_header *) allocate_lisp_storage (size);
  set_lheader_implementation(&(lcheader->lheader), implementation);
  lcheader->next = all_lcrecords;
#if 1                           /* mly prefers to see small ID numbers */
  lcheader->uid = lrecord_uid_counter++;
#else				/* jwz prefers to see real addrs */
  lcheader->uid = (int) &lcheader;
#endif
  lcheader->free = 0;
  all_lcrecords = lcheader;
  INCREMENT_CONS_COUNTER (size, implementation->name);
  return lcheader;
}

#if 0 /* Presently unused */
/* Very, very poor man's EGC?
 * This may be slow and thrash pages all over the place.
 *  Only call it if you really feel you must (and if the
 *  lrecord was fairly recently allocated).
 * Otherwise, just let the GC do its job -- that's what it's there for
 */
void
free_lcrecord (struct lcrecord_header *lcrecord)
{
  if (all_lcrecords == lcrecord)
    {
      all_lcrecords = lcrecord->next;
    }
  else
    {
      struct lrecord_header *header = all_lcrecords;
      for (;;)
	{
	  struct lrecord_header *next = header->next;
	  if (next == lcrecord)
	    {
	      header->next = lrecord->next;
	      break;
	    }
	  else if (next == 0)
	    abort ();
	  else
	    header = next;
	}
    }
  if (lrecord->implementation->finalizer)
    ((lrecord->implementation->finalizer) (lrecord, 0));
  xfree (lrecord);
  return;
}
#endif /* Unused */


static void
disksave_object_finalization_1 (void)
{
  struct lcrecord_header *header;

  for (header = all_lcrecords; header; header = header->next)
    {
      if (LHEADER_IMPLEMENTATION(&header->lheader)->finalizer &&
	  !header->free)
	((LHEADER_IMPLEMENTATION(&header->lheader)->finalizer)
	 (header, 1));
    }
}


/* This must not be called -- it just serves as for EQ test
 *  If lheader->implementation->finalizer is this_marks_a_marked_record,
 *  then lrecord has been marked by the GC sweeper
 * header->implementation is put back to its correct value by
 *  sweep_records */
void
this_marks_a_marked_record (void *dummy0, int dummy1)
{
  abort ();
}

/* Semi-kludge -- lrecord_symbol_value_forward objects get stuck
   in CONST space and you get SEGV's if you attempt to mark them.
   This sits in lheader->implementation->marker. */

Lisp_Object
this_one_is_unmarkable (Lisp_Object obj, void (*markobj) (Lisp_Object))
{
  abort ();
  return Qnil;
}

/* XGCTYPE for records */
int
gc_record_type_p (Lisp_Object frob, CONST struct lrecord_implementation *type)
{
#ifdef USE_INDEXED_LRECORD_IMPLEMENTATION
  return (XGCTYPE (frob) == Lisp_Type_Record
          && XRECORD_LHEADER_IMPLEMENTATION (frob) == type);
#else
  return (XGCTYPE (frob) == Lisp_Type_Record
          && (XRECORD_LHEADER (frob)->implementation == type ||
              XRECORD_LHEADER (frob)->implementation == type + 1));
#endif
}


/**********************************************************************/
/*                        Fixed-size type macros                      */
/**********************************************************************/

/* For fixed-size types that are commonly used, we malloc() large blocks
   of memory at a time and subdivide them into chunks of the correct
   size for an object of that type.  This is more efficient than
   malloc()ing each object separately because we save on malloc() time
   and overhead due to the fewer number of malloc()ed blocks, and
   also because we don't need any extra pointers within each object
   to keep them threaded together for GC purposes.  For less common
   (and frequently large-size) types, we use lcrecords, which are
   malloc()ed individually and chained together through a pointer
   in the lcrecord header.  lcrecords do not need to be fixed-size
   (i.e. two objects of the same type need not have the same size;
   however, the size of a particular object cannot vary dynamically).
   It is also much easier to create a new lcrecord type because no
   additional code needs to be added to alloc.c.  Finally, lcrecords
   may be more efficient when there are only a small number of them.

   The types that are stored in these large blocks (or "frob blocks")
   are cons, float, compiled-function, symbol, marker, extent, event,
   and string.

   Note that strings are special in that they are actually stored in
   two parts: a structure containing information about the string, and
   the actual data associated with the string.  The former structure
   (a struct Lisp_String) is a fixed-size structure and is managed the
   same way as all the other such types.  This structure contains a
   pointer to the actual string data, which is stored in structures of
   type struct string_chars_block.  Each string_chars_block consists
   of a pointer to a struct Lisp_String, followed by the data for that
   string, followed by another pointer to a struct Lisp_String,
   followed by the data for that string, etc.  At GC time, the data in
   these blocks is compacted by searching sequentially through all the
   blocks and compressing out any holes created by unmarked strings.
   Strings that are more than a certain size (bigger than the size of
   a string_chars_block, although something like half as big might
   make more sense) are malloc()ed separately and not stored in
   string_chars_blocks.  Furthermore, no one string stretches across
   two string_chars_blocks.

   Vectors are each malloc()ed separately, similar to lcrecords.

   In the following discussion, we use conses, but it applies equally
   well to the other fixed-size types.

   We store cons cells inside of cons_blocks, allocating a new
   cons_block with malloc() whenever necessary.  Cons cells reclaimed
   by GC are put on a free list to be reallocated before allocating
   any new cons cells from the latest cons_block.  Each cons_block is
   just under 2^n - MALLOC_OVERHEAD bytes long, since malloc (at least
   the versions in malloc.c and gmalloc.c) really allocates in units
   of powers of two and uses 4 bytes for its own overhead.

   What GC actually does is to search through all the cons_blocks,
   from the most recently allocated to the oldest, and put all
   cons cells that are not marked (whether or not they're already
   free) on a cons_free_list.  The cons_free_list is a stack, and
   so the cons cells in the oldest-allocated cons_block end up
   at the head of the stack and are the first to be reallocated.
   If any cons_block is entirely free, it is freed with free()
   and its cons cells removed from the cons_free_list.  Because
   the cons_free_list ends up basically in memory order, we have
   a high locality of reference (assuming a reasonable turnover
   of allocating and freeing) and have a reasonable probability
   of entirely freeing up cons_blocks that have been more recently
   allocated.  This stage is called the "sweep stage" of GC, and
   is executed after the "mark stage", which involves starting
   from all places that are known to point to in-use Lisp objects
   (e.g. the obarray, where are all symbols are stored; the
   current catches and condition-cases; the backtrace list of
   currently executing functions; the gcpro list; etc.) and
   recursively marking all objects that are accessible.

   At the beginning of the sweep stage, the conses in the cons
   blocks are in one of three states: in use and marked, in use
   but not marked, and not in use (already freed).  Any conses
   that are marked have been marked in the mark stage just
   executed, because as part of the sweep stage we unmark any
   marked objects.  The way we tell whether or not a cons cell
   is in use is through the FREE_STRUCT_P macro.  This basically
   looks at the first 4 bytes (or however many bytes a pointer
   fits in) to see if all the bits in those bytes are 1.  The
   resulting value (0xFFFFFFFF) is not a valid pointer and is
   not a valid Lisp_Object.  All current fixed-size types have
   a pointer or Lisp_Object as their first element with the
   exception of strings; they have a size value, which can
   never be less than zero, and so 0xFFFFFFFF is invalid for
   strings as well.  Now assuming that a cons cell is in use,
   the way we tell whether or not it is marked is to look at
   the mark bit of its car (each Lisp_Object has one bit
   reserved as a mark bit, in case it's needed).  Note that
   different types of objects use different fields to indicate
   whether the object is marked, but the principle is the same.

   Conses on the free_cons_list are threaded through a pointer
   stored in the bytes directly after the bytes that are set
   to 0xFFFFFFFF (we cannot overwrite these because the cons
   is still in a cons_block and needs to remain marked as
   not in use for the next time that GC happens).  This
   implies that all fixed-size types must be at least big
   enough to store two pointers, which is indeed the case
   for all current fixed-size types.

   Some types of objects need additional "finalization" done
   when an object is converted from in use to not in use;
   this is the purpose of the ADDITIONAL_FREE_type macro.
   For example, markers need to be removed from the chain
   of markers that is kept in each buffer.  This is because
   markers in a buffer automatically disappear if the marker
   is no longer referenced anywhere (the same does not
   apply to extents, however).

   WARNING: Things are in an extremely bizarre state when
   the ADDITIONAL_FREE_type macros are called, so beware!

   When ERROR_CHECK_GC is defined, we do things differently
   so as to maximize our chances of catching places where
   there is insufficient GCPROing.  The thing we want to
   avoid is having an object that we're using but didn't
   GCPRO get freed by GC and then reallocated while we're
   in the process of using it -- this will result in something
   seemingly unrelated getting trashed, and is extremely
   difficult to track down.  If the object gets freed but
   not reallocated, we can usually catch this because we
   set all bytes of a freed object to 0xDEADBEEF. (The
   first four bytes, however, are 0xFFFFFFFF, and the next
   four are a pointer used to chain freed objects together;
   we play some tricks with this pointer to make it more
   bogus, so crashes are more likely to occur right away.)

   We want freed objects to stay free as long as possible,
   so instead of doing what we do above, we maintain the
   free objects in a first-in first-out queue.  We also
   don't recompute the free list each GC, unlike above;
   this ensures that the queue ordering is preserved.
   [This means that we are likely to have worse locality
   of reference, and that we can never free a frob block
   once it's allocated. (Even if we know that all cells
   in it are free, there's no easy way to remove all those
   cells from the free list because the objects on the
   free list are unlikely to be in memory order.)]
   Furthermore, we never take objects off the free list
   unless there's a large number (usually 1000, but
   varies depending on type) of them already on the list.
   This way, we ensure that an object that gets freed will
   remain free for the next 1000 (or whatever) times that
   an object of that type is allocated.
*/

#ifndef MALLOC_OVERHEAD
#ifdef GNU_MALLOC
#define MALLOC_OVERHEAD 0
#elif defined (rcheck)
#define MALLOC_OVERHEAD 20
#else
#define MALLOC_OVERHEAD 8
#endif
#endif /* MALLOC_OVERHEAD */

#ifdef ALLOC_NO_POOLS
# define TYPE_ALLOC_SIZE(type, structtype) 1
#else
# define TYPE_ALLOC_SIZE(type, structtype)			\
    ((2048 - MALLOC_OVERHEAD - sizeof (struct type##_block *))	\
     / sizeof (structtype))
#endif /* ALLOC_NO_POOLS */

#define DECLARE_FIXED_TYPE_ALLOC(type, structtype)			  \
									  \
struct type##_block							  \
{									  \
  struct type##_block *prev;						  \
  structtype block[TYPE_ALLOC_SIZE (type, structtype)];			  \
};									  \
									  \
static struct type##_block *current_##type##_block;			  \
static int current_##type##_block_index;				  \
									  \
static structtype *type##_free_list;					  \
static structtype *type##_free_list_tail;				  \
									  \
static void								  \
init_##type##_alloc (void)						  \
{									  \
  current_##type##_block = 0;						  \
  current_##type##_block_index = countof (current_##type##_block->block); \
  type##_free_list = 0;							  \
  type##_free_list_tail = 0;						  \
}									  \
									  \
static int gc_count_num_##type##_in_use, gc_count_num_##type##_freelist

#define ALLOCATE_FIXED_TYPE_FROM_BLOCK(type, result)			\
  do {									\
    if (current_##type##_block_index					\
	== countof (current_##type##_block->block))			\
    {									\
      struct type##_block *__new__ = (struct type##_block *)		\
         allocate_lisp_storage (sizeof (struct type##_block));		\
      __new__->prev = current_##type##_block;				\
      current_##type##_block = __new__;					\
      current_##type##_block_index = 0;					\
    }									\
    (result) =								\
      &(current_##type##_block->block[current_##type##_block_index++]);	\
  } while (0)

/* Allocate an instance of a type that is stored in blocks.
   TYPE is the "name" of the type, STRUCTTYPE is the corresponding
   structure type. */

#ifdef ERROR_CHECK_GC

/* Note: if you get crashes in this function, suspect incorrect calls
   to free_cons() and friends.  This happened once because the cons
   cell was not GC-protected and was getting collected before
   free_cons() was called. */

#define ALLOCATE_FIXED_TYPE_1(type, structtype, result)			 \
do									 \
{									 \
  if (gc_count_num_##type##_freelist >					 \
      MINIMUM_ALLOWED_FIXED_TYPE_CELLS_##type) 				 \
    {									 \
      result = type##_free_list;					 \
      /* Before actually using the chain pointer, we complement all its	 \
         bits; see FREE_FIXED_TYPE(). */				 \
      type##_free_list =						 \
        (structtype *) ~(unsigned long)					 \
          (* (structtype **) ((char *) result + sizeof (void *)));	 \
      gc_count_num_##type##_freelist--;					 \
    }									 \
  else									 \
    ALLOCATE_FIXED_TYPE_FROM_BLOCK (type, result);			 \
  MARK_STRUCT_AS_NOT_FREE (result);					 \
} while (0)

#else /* !ERROR_CHECK_GC */

#define ALLOCATE_FIXED_TYPE_1(type, structtype, result)		\
do								\
{								\
  if (type##_free_list)						\
    {								\
      result = type##_free_list;				\
      type##_free_list =					\
        * (structtype **) ((char *) result + sizeof (void *));	\
    }								\
  else								\
    ALLOCATE_FIXED_TYPE_FROM_BLOCK (type, result);		\
  MARK_STRUCT_AS_NOT_FREE (result);				\
} while (0)

#endif /* !ERROR_CHECK_GC */

#define ALLOCATE_FIXED_TYPE(type, structtype, result)	\
do							\
{							\
  ALLOCATE_FIXED_TYPE_1 (type, structtype, result);	\
  INCREMENT_CONS_COUNTER (sizeof (structtype), #type);	\
} while (0)

#define NOSEEUM_ALLOCATE_FIXED_TYPE(type, structtype, result)	\
do								\
{								\
  ALLOCATE_FIXED_TYPE_1 (type, structtype, result);		\
  NOSEEUM_INCREMENT_CONS_COUNTER (sizeof (structtype), #type);	\
} while (0)

/* INVALID_POINTER_VALUE should be a value that is invalid as a pointer
   to a Lisp object and invalid as an actual Lisp_Object value.  We have
   to make sure that this value cannot be an integer in Lisp_Object form.
   0xFFFFFFFF could be so on a 64-bit system, so we extend it to 64 bits.
   On a 32-bit system, the type bits will be non-zero, making the value
   be a pointer, and the pointer will be misaligned.

   Even if Emacs is run on some weirdo system that allows and allocates
   byte-aligned pointers, this pointer is at the very top of the address
   space and so it's almost inconceivable that it could ever be valid. */

#if INTBITS == 32
# define INVALID_POINTER_VALUE 0xFFFFFFFF
#elif INTBITS == 48
# define INVALID_POINTER_VALUE 0xFFFFFFFFFFFF
#elif INTBITS == 64
# define INVALID_POINTER_VALUE 0xFFFFFFFFFFFFFFFF
#else
You have some weird system and need to supply a reasonable value here.
#endif

#define FREE_STRUCT_P(ptr) \
  (* (void **) ptr == (void *) INVALID_POINTER_VALUE)
#define MARK_STRUCT_AS_FREE(ptr) \
  (* (void **) ptr = (void *) INVALID_POINTER_VALUE)
#define MARK_STRUCT_AS_NOT_FREE(ptr) \
  (* (void **) ptr = 0)

#ifdef ERROR_CHECK_GC

#define PUT_FIXED_TYPE_ON_FREE_LIST(type, structtype, ptr)		\
do { if (type##_free_list_tail)						\
       {								\
	 /* When we store the chain pointer, we complement all		\
	    its bits; this should significantly increase its		\
	    bogosity in case someone tries to use the value, and	\
	    should make us dump faster if someone stores something	\
	    over the pointer because when it gets un-complemented in	\
	    ALLOCATED_FIXED_TYPE(), the resulting pointer will be	\
	    extremely bogus. */						\
	 * (structtype **)						\
	   ((char *) type##_free_list_tail + sizeof (void *)) =		\
	     (structtype *) ~(unsigned long) ptr;			\
       }								\
     else								\
       type##_free_list = ptr;						\
     type##_free_list_tail = ptr;					\
   } while (0)

#else /* !ERROR_CHECK_GC */

#define PUT_FIXED_TYPE_ON_FREE_LIST(type, structtype, ptr)	\
do { * (structtype **) ((char *) ptr + sizeof (void *)) =	\
       type##_free_list;					\
     type##_free_list = ptr;					\
   } while (0)

#endif /* !ERROR_CHECK_GC */

/* TYPE and STRUCTTYPE are the same as in ALLOCATE_FIXED_TYPE(). */

#define FREE_FIXED_TYPE(type, structtype, ptr)			\
do { structtype *_weird_ = (ptr);				\
     ADDITIONAL_FREE_##type (_weird_);				\
     deadbeef_memory (ptr, sizeof (structtype));		\
     PUT_FIXED_TYPE_ON_FREE_LIST (type, structtype, ptr);	\
     MARK_STRUCT_AS_FREE (_weird_);				\
   } while (0)

/* Like FREE_FIXED_TYPE() but used when we are explicitly
   freeing a structure through free_cons(), free_marker(), etc.
   rather than through the normal process of sweeping.
   We attempt to undo the changes made to the allocation counters
   as a result of this structure being allocated.  This is not
   completely necessary but helps keep things saner: e.g. this way,
   repeatedly allocating and freeing a cons will not result in
   the consing-since-gc counter advancing, which would cause a GC
   and somewhat defeat the purpose of explicitly freeing. */

#define FREE_FIXED_TYPE_WHEN_NOT_IN_GC(type, structtype, ptr)	\
do { FREE_FIXED_TYPE (type, structtype, ptr);			\
     DECREMENT_CONS_COUNTER (sizeof (structtype));		\
     gc_count_num_##type##_freelist++;				\
   } while (0)



/**********************************************************************/
/*                         Cons allocation                            */
/**********************************************************************/

DECLARE_FIXED_TYPE_ALLOC (cons, struct Lisp_Cons);
/* conses are used and freed so often that we set this really high */
/* #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_cons 20000 */
#define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_cons 2000

#ifdef LRECORD_CONS
static Lisp_Object mark_cons (Lisp_Object, void (*) (Lisp_Object));
static int cons_equal(Lisp_Object, Lisp_Object, int);
extern void print_cons (Lisp_Object, Lisp_Object, int);
DEFINE_BASIC_LRECORD_IMPLEMENTATION ("cons", cons,
				     mark_cons, print_cons, 0,
				     cons_equal, 
				     /*
				      * No `hash' method needed.
				      * internal_hash knows how to
				      * handle conses.
				      */
				     0,
				     struct Lisp_Cons);
static Lisp_Object
mark_cons (Lisp_Object obj, void (*markobj) (Lisp_Object))
{
  if (NILP (XCDR (obj)))
    return XCAR (obj);
  else
    (markobj) (XCAR (obj));
  return XCDR (obj);
}

static int
cons_equal (Lisp_Object ob1, Lisp_Object ob2, int depth)
{
  while (internal_equal (XCAR (ob1), XCAR (ob2), depth + 1))
    {
      ob1 = XCDR(ob1);
      ob2 = XCDR(ob2);
      if (! CONSP (ob1) || ! CONSP (ob2))
	return internal_equal (ob1, ob2, depth + 1);
    }
  return 0;
}
#endif /* LRECORD_CONS */

DEFUN ("cons", Fcons, 2, 2, 0, /*
Create a new cons, give it CAR and CDR as components, and return it.
*/
       (car, cdr))
{
  /* This cannot GC. */
  Lisp_Object val = Qnil;
  struct Lisp_Cons *c;

  ALLOCATE_FIXED_TYPE (cons, struct Lisp_Cons, c);
#ifdef LRECORD_CONS
  set_lheader_implementation (&(c->lheader), lrecord_cons);
#endif
  XSETCONS (val, c);
  c->car = car;
  c->cdr = cdr;
  return val;
}

/* This is identical to Fcons() but it used for conses that we're
   going to free later, and is useful when trying to track down
   "real" consing. */
Lisp_Object
noseeum_cons (Lisp_Object car, Lisp_Object cdr)
{
  Lisp_Object val = Qnil;
  struct Lisp_Cons *c;

  NOSEEUM_ALLOCATE_FIXED_TYPE (cons, struct Lisp_Cons, c);
#ifdef LRECORD_CONS
  set_lheader_implementation (&(c->lheader), lrecord_cons);
#endif
  XSETCONS (val, c);
  XCAR (val) = car;
  XCDR (val) = cdr;
  return val;
}

DEFUN ("list", Flist, 0, MANY, 0, /*
Return a newly created list with specified arguments as elements.
Any number of arguments, even zero arguments, are allowed.
*/
       (int nargs, Lisp_Object *args))
{
  Lisp_Object val = Qnil;
  Lisp_Object *argp = args + nargs;

  while (nargs-- > 0)
    val = Fcons (*--argp, val);
  return val;
}

Lisp_Object
list1 (Lisp_Object obj0)
{
  /* This cannot GC. */
  return Fcons (obj0, Qnil);
}

Lisp_Object
list2 (Lisp_Object obj0, Lisp_Object obj1)
{
  /* This cannot GC. */
  return Fcons (obj0, list1 (obj1));
}

Lisp_Object
list3 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2)
{
  /* This cannot GC. */
  return Fcons (obj0, list2 (obj1, obj2));
}

static Lisp_Object
cons3 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2)
{
  /* This cannot GC. */
  return Fcons (obj0, Fcons (obj1, obj2));
}

Lisp_Object
list4 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2, Lisp_Object obj3)
{
  /* This cannot GC. */
  return Fcons (obj0, list3 (obj1, obj2, obj3));
}

Lisp_Object
list5 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2, Lisp_Object obj3,
       Lisp_Object obj4)
{
  /* This cannot GC. */
  return Fcons (obj0, list4 (obj1, obj2, obj3, obj4));
}

Lisp_Object
list6 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2, Lisp_Object obj3,
       Lisp_Object obj4, Lisp_Object obj5)
{
  /* This cannot GC. */
  return Fcons (obj0, list5 (obj1, obj2, obj3, obj4, obj5));
}

DEFUN ("make-list", Fmake_list, 2, 2, 0, /*
Return a newly created list of length LENGTH, with each element being INIT.
*/
       (length, init))
{
  Lisp_Object val;
  int size;

  CHECK_NATNUM (length);
  size = XINT (length);

  val = Qnil;
  while (size-- > 0)
    val = Fcons (init, val);
  return val;
}


/**********************************************************************/
/*                        Float allocation                            */
/**********************************************************************/

#ifdef LISP_FLOAT_TYPE

DECLARE_FIXED_TYPE_ALLOC (float, struct Lisp_Float);
#define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_float 1000

Lisp_Object
make_float (double float_value)
{
  Lisp_Object val;
  struct Lisp_Float *f;

  ALLOCATE_FIXED_TYPE (float, struct Lisp_Float, f);
  set_lheader_implementation (&(f->lheader), lrecord_float);
  float_next (f) = ((struct Lisp_Float *) -1);
  float_data (f) = float_value;
  XSETFLOAT (val, f);
  return val;
}

#endif /* LISP_FLOAT_TYPE */


/**********************************************************************/
/*                         Vector allocation                          */
/**********************************************************************/

#ifdef LRECORD_VECTOR
static Lisp_Object mark_vector (Lisp_Object, void (*) (Lisp_Object));
static unsigned int size_vector (CONST void *);
static int vector_equal(Lisp_Object, Lisp_Object, int);
extern void print_vector (Lisp_Object, Lisp_Object, int);
DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION("vector", vector,
				       mark_vector, print_vector, 0,
				       vector_equal,
				       /*
				        * No `hash' method needed for
				        * vectors.  internal_hash
				        * knows how to handle vectors.
				        */
				       0,
				       size_vector, struct Lisp_Vector);
static Lisp_Object
mark_vector (Lisp_Object obj, void (*markobj) (Lisp_Object))
{
  struct Lisp_Vector *ptr = XVECTOR (obj);
  int len = vector_length (ptr);
  int i;

  for (i = 0; i < len - 1; i++)
    (markobj) (ptr->contents[i]);
  return (len > 0) ? ptr->contents[len - 1] : Qnil;
}

static unsigned int
size_vector (CONST void *lheader)
{
  struct Lisp_Vector *p = lheader;
  /*
   * -1 because struct Lisp_Vector includes 1 slot
   */
  return sizeof (struct Lisp_Vector) +
    ((p->size - 1) * sizeof (Lisp_Object)) ;
}

static int
vector_equal (Lisp_Object o1, Lisp_Object o2, int depth)
{
  int indice;
  int len = XVECTOR_LENGTH (o1);
  if (len != XVECTOR_LENGTH (o2))
    return 0;
  for (indice = 0; indice < len; indice++)
    {
      if (!internal_equal (XVECTOR_DATA (o1) [indice],
			   XVECTOR_DATA (o2) [indice],
			   depth + 1))
	return 0;
    }
  return 1;
}

/* #### should allocate `small' vectors from a frob-block */
static struct Lisp_Vector *
make_vector_internal (EMACS_INT sizei)
{
  EMACS_INT sizem = (sizeof (struct Lisp_Vector)
               /* -1 because struct Lisp_Vector includes 1 slot */
               + (sizei - 1) * sizeof (Lisp_Object)
               );
  struct Lisp_Vector *p = alloc_lcrecord (sizem, lrecord_vector);

  p->size = sizei;
  return p;
}

#else /* ! LRECORD_VECTOR */

static Lisp_Object all_vectors;

/* #### should allocate `small' vectors from a frob-block */
static struct Lisp_Vector *
make_vector_internal (EMACS_INT sizei)
{
  EMACS_INT sizem = (sizeof (struct Lisp_Vector)
               /* -1 because struct Lisp_Vector includes 1 slot,
                * +1 to account for vector_next */
               + (sizei - 1 + 1) * sizeof (Lisp_Object)
               );
  struct Lisp_Vector *p = (struct Lisp_Vector *) allocate_lisp_storage (sizem);

  INCREMENT_CONS_COUNTER (sizem, "vector");

  p->size = sizei;
  vector_next (p) = all_vectors;
  XSETVECTOR (all_vectors, p);
  return p;
}

#endif

Lisp_Object
make_vector (EMACS_INT length, Lisp_Object init)
{
  EMACS_INT elt;
  Lisp_Object vector = Qnil;
  struct Lisp_Vector *p;

  if (length < 0)
    length = XINT (wrong_type_argument (Qnatnump, make_int (length)));

  p = make_vector_internal (length);
  XSETVECTOR (vector, p);

#if 0
  /* Initialize big arrays full of 0's quickly, for what that's worth */
  {
    char *travesty = (char *) &init;
    for (i = 1; i < sizeof (Lisp_Object); i++)
    {
      if (travesty[i] != travesty[0])
        goto fill;
    }
    memset (vector_data (p), travesty[0], length * sizeof (Lisp_Object));
    return vector;
  }
 fill:
#endif
  for (elt = 0; elt < length; elt++)
    vector_data(p)[elt] = init;

  return vector;
}

DEFUN ("make-vector", Fmake_vector, 2, 2, 0, /*
Return a newly created vector of length LENGTH, with each element being INIT.
See also the function `vector'.
*/
       (length, init))
{
  if (!INTP (length) || XINT (length) < 0)
    length = wrong_type_argument (Qnatnump, length);

  return make_vector (XINT (length), init);
}

DEFUN ("vector", Fvector, 0, MANY, 0, /*
Return a newly created vector with specified arguments as elements.
Any number of arguments, even zero arguments, are allowed.
*/
       (int nargs, Lisp_Object *args))
{
  Lisp_Object vector = Qnil;
  int elt;
  struct Lisp_Vector *p;

  p = make_vector_internal (nargs);
  XSETVECTOR (vector, p);

  for (elt = 0; elt < nargs; elt++)
    vector_data(p)[elt] = args[elt];

  return vector;
}

Lisp_Object
vector1 (Lisp_Object obj0)
{
  return Fvector (1, &obj0);
}

Lisp_Object
vector2 (Lisp_Object obj0, Lisp_Object obj1)
{
  Lisp_Object args[2];
  args[0] = obj0;
  args[1] = obj1;
  return Fvector (2, args);
}

Lisp_Object
vector3 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2)
{
  Lisp_Object args[3];
  args[0] = obj0;
  args[1] = obj1;
  args[2] = obj2;
  return Fvector (3, args);
}

Lisp_Object
vector4 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
	 Lisp_Object obj3)
{
  Lisp_Object args[4];
  args[0] = obj0;
  args[1] = obj1;
  args[2] = obj2;
  args[3] = obj3;
  return Fvector (4, args);
}

Lisp_Object
vector5 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
	 Lisp_Object obj3, Lisp_Object obj4)
{
  Lisp_Object args[5];
  args[0] = obj0;
  args[1] = obj1;
  args[2] = obj2;
  args[3] = obj3;
  args[4] = obj4;
  return Fvector (5, args);
}

Lisp_Object
vector6 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
	 Lisp_Object obj3, Lisp_Object obj4, Lisp_Object obj5)
{
  Lisp_Object args[6];
  args[0] = obj0;
  args[1] = obj1;
  args[2] = obj2;
  args[3] = obj3;
  args[4] = obj4;
  args[5] = obj5;
  return Fvector (6, args);
}

Lisp_Object
vector7 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
	 Lisp_Object obj3, Lisp_Object obj4, Lisp_Object obj5,
	 Lisp_Object obj6)
{
  Lisp_Object args[7];
  args[0] = obj0;
  args[1] = obj1;
  args[2] = obj2;
  args[3] = obj3;
  args[4] = obj4;
  args[5] = obj5;
  args[6] = obj6;
  return Fvector (7, args);
}

Lisp_Object
vector8 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
	 Lisp_Object obj3, Lisp_Object obj4, Lisp_Object obj5,
	 Lisp_Object obj6, Lisp_Object obj7)
{
  Lisp_Object args[8];
  args[0] = obj0;
  args[1] = obj1;
  args[2] = obj2;
  args[3] = obj3;
  args[4] = obj4;
  args[5] = obj5;
  args[6] = obj6;
  args[7] = obj7;
  return Fvector (8, args);
}

/**********************************************************************/
/*                       Bit Vector allocation                        */
/**********************************************************************/

static Lisp_Object all_bit_vectors;

/* #### should allocate `small' bit vectors from a frob-block */
static struct Lisp_Bit_Vector *
make_bit_vector_internal (EMACS_INT sizei)
{
  EMACS_INT sizem = (sizeof (struct Lisp_Bit_Vector) +
               /* -1 because struct Lisp_Bit_Vector includes 1 slot */
	       sizeof (long) * (BIT_VECTOR_LONG_STORAGE (sizei) - 1));
  struct Lisp_Bit_Vector *p =
    (struct Lisp_Bit_Vector *) allocate_lisp_storage (sizem);
  set_lheader_implementation (&(p->lheader), lrecord_bit_vector);

  INCREMENT_CONS_COUNTER (sizem, "bit-vector");

  bit_vector_length (p) = sizei;
  bit_vector_next (p) = all_bit_vectors;
  /* make sure the extra bits in the last long are 0; the calling
     functions might not set them. */
  p->bits[BIT_VECTOR_LONG_STORAGE (sizei) - 1] = 0;
  XSETBIT_VECTOR (all_bit_vectors, p);
  return p;
}

Lisp_Object
make_bit_vector (EMACS_INT length, Lisp_Object init)
{
  Lisp_Object bit_vector = Qnil;
  struct Lisp_Bit_Vector *p;
  EMACS_INT num_longs;

  if (length < 0)
    length = XINT (wrong_type_argument (Qnatnump, make_int (length)));

  CHECK_BIT (init);

  num_longs = BIT_VECTOR_LONG_STORAGE (length);
  p = make_bit_vector_internal (length);
  XSETBIT_VECTOR (bit_vector, p);

  if (ZEROP (init))
    memset (p->bits, 0, num_longs * sizeof (long));
  else
    {
      EMACS_INT bits_in_last = length & (LONGBITS_POWER_OF_2 - 1);
      memset (p->bits, ~0, num_longs * sizeof (long));
      /* But we have to make sure that the unused bits in the
	 last integer are 0, so that equal/hash is easy. */
      if (bits_in_last)
	p->bits[num_longs - 1] &= (1 << bits_in_last) - 1;
    }

  return bit_vector;
}

Lisp_Object
make_bit_vector_from_byte_vector (unsigned char *bytevec, EMACS_INT length)
{
  Lisp_Object bit_vector = Qnil;
  struct Lisp_Bit_Vector *p;
  EMACS_INT i;

  if (length < 0)
    length = XINT (wrong_type_argument (Qnatnump, make_int (length)));

  p = make_bit_vector_internal (length);
  XSETBIT_VECTOR (bit_vector, p);

  for (i = 0; i < length; i++)
    set_bit_vector_bit (p, i, bytevec[i]);

  return bit_vector;
}

DEFUN ("make-bit-vector", Fmake_bit_vector, 2, 2, 0, /*
Return a newly created bit vector of length LENGTH.
Each element is set to INIT.  See also the function `bit-vector'.
*/
       (length, init))
{
  if (!INTP (length) || XINT (length) < 0)
    length = wrong_type_argument (Qnatnump, length);

  return make_bit_vector (XINT (length), init);
}

DEFUN ("bit-vector", Fbit_vector, 0, MANY, 0, /*
Return a newly created bit vector with specified arguments as elements.
Any number of arguments, even zero arguments, are allowed.
*/
       (int nargs, Lisp_Object *args))
{
  Lisp_Object bit_vector = Qnil;
  int elt;
  struct Lisp_Bit_Vector *p;

  for (elt = 0; elt < nargs; elt++)
    CHECK_BIT (args[elt]);

  p = make_bit_vector_internal (nargs);
  XSETBIT_VECTOR (bit_vector, p);

  for (elt = 0; elt < nargs; elt++)
    set_bit_vector_bit (p, elt, !ZEROP (args[elt]));

  return bit_vector;
}


/**********************************************************************/
/*                   Compiled-function allocation                     */
/**********************************************************************/

DECLARE_FIXED_TYPE_ALLOC (compiled_function, struct Lisp_Compiled_Function);
#define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_compiled_function 1000

static Lisp_Object
make_compiled_function (int make_pure)
{
  struct Lisp_Compiled_Function *b;
  Lisp_Object new;
  int size = sizeof (struct Lisp_Compiled_Function);

  if (make_pure && check_purespace (size))
    {
      b = (struct Lisp_Compiled_Function *) (PUREBEG + pureptr);
      set_lheader_implementation (&(b->lheader), lrecord_compiled_function);
#ifdef USE_INDEXED_LRECORD_IMPLEMENTATION
      b->lheader.pure = 1;
#endif
      pureptr += size;
      bump_purestat (&purestat_bytecode, size);
    }
  else
    {
      ALLOCATE_FIXED_TYPE (compiled_function, struct Lisp_Compiled_Function,
			   b);
      set_lheader_implementation (&(b->lheader), lrecord_compiled_function);
    }
  b->maxdepth = 0;
  b->flags.documentationp = 0;
  b->flags.interactivep = 0;
  b->flags.domainp = 0; /* I18N3 */
  b->bytecodes = Qzero;
  b->constants = Qzero;
  b->arglist = Qnil;
  b->doc_and_interactive = Qnil;
#ifdef COMPILED_FUNCTION_ANNOTATION_HACK
  b->annotated = Qnil;
#endif
  XSETCOMPILED_FUNCTION (new, b);
  return new;
}

DEFUN ("make-byte-code", Fmake_byte_code, 4, MANY, 0, /*
Create a compiled-function object.
Usage: (arglist instructions constants stack-size
	&optional doc-string interactive-spec)
Note that, unlike all other emacs-lisp functions, calling this with five
arguments is NOT the same as calling it with six arguments, the last of
which is nil.  If the INTERACTIVE arg is specified as nil, then that means
that this function was defined with `(interactive)'.  If the arg is not
specified, then that means the function is not interactive.
This is terrible behavior which is retained for compatibility with old
`.elc' files which expected these semantics.
*/
       (int nargs, Lisp_Object *args))
{
/*   In a non-insane world this function would have this arglist...
     (arglist, instructions, constants, stack_size, doc_string, interactive)
     Lisp_Object arglist, instructions, constants, stack_size, doc_string,
	interactive;
 */
  Lisp_Object arglist      = args[0];
  Lisp_Object instructions = args[1];
  Lisp_Object constants    = args[2];
  Lisp_Object stack_size   = args[3];
  Lisp_Object doc_string   = ((nargs > 4) ? args[4] : Qnil);
  Lisp_Object interactive  = ((nargs > 5) ? args[5] : Qunbound);
  /* Don't purecopy the doc references in instructions because it's
     wasteful; they will get fixed up later.

     #### If something goes wrong and they don't get fixed up,
     we're screwed, because pure stuff isn't marked and thus the
     cons references won't be marked and will get reused.

     Note: there will be a window after the byte code is created and
     before the doc references are fixed up in which there will be
     impure objects inside a pure object, which apparently won't
     get marked, leading the trouble.  But during that entire window,
     the objects are sitting on Vload_force_doc_string_list, which
     is staticpro'd, so we're OK. */
  int purecopy_instructions = 1;

  if (nargs > 6)
    return Fsignal (Qwrong_number_of_arguments,
		    list2 (intern ("make-byte-code"), make_int (nargs)));

  CHECK_LIST (arglist);
  /* instructions is a string or a cons (string . int) for a
     lazy-loaded function. */
  if (CONSP (instructions))
    {
      CHECK_STRING (XCAR (instructions));
      CHECK_INT (XCDR (instructions));
      if (!NILP (constants))
	CHECK_VECTOR (constants);
      purecopy_instructions = 0;
    }
  else
    {
      CHECK_STRING (instructions);
      CHECK_VECTOR (constants);
    }
  CHECK_NATNUM (stack_size);
  /* doc_string may be nil, string, int, or a cons (string . int). */

  /* interactive may be list or string (or unbound). */

  if (purify_flag)
    {
      if (!purified (arglist))
	arglist = Fpurecopy (arglist);
      if (purecopy_instructions && !purified (instructions))
	instructions = Fpurecopy (instructions);
      if (!purified (doc_string))
	doc_string = Fpurecopy (doc_string);
      if (!purified (interactive) && !UNBOUNDP (interactive))
	interactive = Fpurecopy (interactive);

      /* Statistics are kept differently for the constants */
      if (!purified (constants))
#ifdef PURESTAT
	{
	  int old = purecopying_for_bytecode;
	  purecopying_for_bytecode = 1;
	  constants = Fpurecopy (constants);
	  purecopying_for_bytecode = old;
	}
#else
        constants = Fpurecopy (constants);
#endif /* PURESTAT */

#ifdef PURESTAT
      if (STRINGP (instructions))
	bump_purestat (&purestat_string_bytecodes, pure_sizeof (instructions));
      if (VECTORP (constants))
	bump_purestat (&purestat_vector_bytecode_constants,
		       pure_sizeof (constants));
      if (STRINGP (doc_string))
	/* These should be have been snagged by make-docfile... */
	bump_purestat (&purestat_string_documentation,
		       pure_sizeof (doc_string));
      if (STRINGP (interactive))
	bump_purestat (&purestat_string_interactive,
		       pure_sizeof (interactive));
#endif /* PURESTAT */
    }

  {
    int docp = !NILP (doc_string);
    int intp = !UNBOUNDP (interactive);
#ifdef I18N3
    int domp = !NILP (Vfile_domain);
#endif
    Lisp_Object val = make_compiled_function (purify_flag);
    struct Lisp_Compiled_Function *b = XCOMPILED_FUNCTION (val);
    b->flags.documentationp = docp;
    b->flags.interactivep   = intp;
#ifdef I18N3
    b->flags.domainp        = domp;
#endif
    b->maxdepth  = XINT (stack_size);
    b->bytecodes = instructions;
    b->constants = constants;
    b->arglist   = arglist;
#ifdef COMPILED_FUNCTION_ANNOTATION_HACK
    if (!NILP (Vcurrent_compiled_function_annotation))
      b->annotated = Fpurecopy (Vcurrent_compiled_function_annotation);
    else if (!NILP (Vload_file_name_internal_the_purecopy))
      b->annotated = Vload_file_name_internal_the_purecopy;
    else if (!NILP (Vload_file_name_internal))
      {
	struct gcpro gcpro1;
	GCPRO1(val);		/* don't let val or b get reaped */
	Vload_file_name_internal_the_purecopy =
	  Fpurecopy (Ffile_name_nondirectory (Vload_file_name_internal));
	b->annotated = Vload_file_name_internal_the_purecopy;
	UNGCPRO;
      }
#endif /* COMPILED_FUNCTION_ANNOTATION_HACK */

#ifdef I18N3
    if (docp && intp && domp)
      b->doc_and_interactive = (((purify_flag) ? pure_cons : Fcons)
				(doc_string,
				 (((purify_flag) ? pure_cons : Fcons)
				  (interactive, Vfile_domain))));
    else if (docp && domp)
      b->doc_and_interactive = (((purify_flag) ? pure_cons : Fcons)
				(doc_string, Vfile_domain));
    else if (intp && domp)
      b->doc_and_interactive = (((purify_flag) ? pure_cons : Fcons)
				(interactive, Vfile_domain));
    else
#endif
    if (docp && intp)
      b->doc_and_interactive = (((purify_flag) ? pure_cons : Fcons)
				(doc_string, interactive));
    else if (intp)
      b->doc_and_interactive = interactive;
#ifdef I18N3
    else if (domp)
      b->doc_and_interactive = Vfile_domain;
#endif
    else
      b->doc_and_interactive = doc_string;

    return val;
  }
}


/**********************************************************************/
/*                          Symbol allocation                         */
/**********************************************************************/

DECLARE_FIXED_TYPE_ALLOC (symbol, struct Lisp_Symbol);
#define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_symbol 1000

DEFUN ("make-symbol", Fmake_symbol, 1, 1, 0, /*
Return a newly allocated uninterned symbol whose name is NAME.
Its value and function definition are void, and its property list is nil.
*/
       (str))
{
  Lisp_Object val;
  struct Lisp_Symbol *p;

  CHECK_STRING (str);

  ALLOCATE_FIXED_TYPE (symbol, struct Lisp_Symbol, p);
#ifdef LRECORD_SYMBOL
  set_lheader_implementation (&(p->lheader), lrecord_symbol);
#endif
  p->name = XSTRING (str);
  p->plist = Qnil;
  p->value = Qunbound;
  p->function = Qunbound;
  symbol_next (p) = 0;
  XSETSYMBOL (val, p);
  return val;
}


/**********************************************************************/
/*                         Extent allocation                          */
/**********************************************************************/

DECLARE_FIXED_TYPE_ALLOC (extent, struct extent);
#define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_extent 1000

struct extent *
allocate_extent (void)
{
  struct extent *e;

  ALLOCATE_FIXED_TYPE (extent, struct extent, e);
  /* memset (e, 0, sizeof (struct extent)); */
  set_lheader_implementation (&(e->lheader), lrecord_extent);
  extent_object (e) = Qnil;
  set_extent_start (e, -1);
  set_extent_end (e, -1);
  e->plist = Qnil;

  memset (&e->flags, 0, sizeof (e->flags));

  extent_face (e) = Qnil;
  e->flags.end_open = 1;  /* default is for endpoints to behave like markers */
  e->flags.detachable = 1;

  return e;
}


/**********************************************************************/
/*                         Event allocation                           */
/**********************************************************************/

DECLARE_FIXED_TYPE_ALLOC (event, struct Lisp_Event);
#define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_event 1000

Lisp_Object
allocate_event (void)
{
  Lisp_Object val;
  struct Lisp_Event *e;

  ALLOCATE_FIXED_TYPE (event, struct Lisp_Event, e);
  set_lheader_implementation (&(e->lheader), lrecord_event);

  XSETEVENT (val, e);
  return val;
}


/**********************************************************************/
/*                       Marker allocation                            */
/**********************************************************************/

DECLARE_FIXED_TYPE_ALLOC (marker, struct Lisp_Marker);
#define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_marker 1000

DEFUN ("make-marker", Fmake_marker, 0, 0, 0, /*
Return a newly allocated marker which does not point at any place.
*/
       ())
{
  Lisp_Object val;
  struct Lisp_Marker *p;

  ALLOCATE_FIXED_TYPE (marker, struct Lisp_Marker, p);
  set_lheader_implementation (&(p->lheader), lrecord_marker);
  p->buffer = 0;
  p->memind = 0;
  marker_next (p) = 0;
  marker_prev (p) = 0;
  p->insertion_type = 0;
  XSETMARKER (val, p);
  return val;
}

Lisp_Object
noseeum_make_marker (void)
{
  Lisp_Object val;
  struct Lisp_Marker *p;

  NOSEEUM_ALLOCATE_FIXED_TYPE (marker, struct Lisp_Marker, p);
  set_lheader_implementation (&(p->lheader), lrecord_marker);
  p->buffer = 0;
  p->memind = 0;
  marker_next (p) = 0;
  marker_prev (p) = 0;
  p->insertion_type = 0;
  XSETMARKER (val, p);
  return val;
}


/**********************************************************************/
/*                        String allocation                           */
/**********************************************************************/

/* The data for "short" strings generally resides inside of structs of type
   string_chars_block. The Lisp_String structure is allocated just like any
   other Lisp object (except for vectors), and these are freelisted when
   they get garbage collected. The data for short strings get compacted,
   but the data for large strings do not.

   Previously Lisp_String structures were relocated, but this caused a lot
   of bus-errors because the C code didn't include enough GCPRO's for
   strings (since EVERY REFERENCE to a short string needed to be GCPRO'd so
   that the reference would get relocated).

   This new method makes things somewhat bigger, but it is MUCH safer.  */

DECLARE_FIXED_TYPE_ALLOC (string, struct Lisp_String);
/* strings are used and freed quite often */
/* #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_string 10000 */
#define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_string 1000

#ifdef LRECORD_STRING
static Lisp_Object mark_string (Lisp_Object, void (*) (Lisp_Object));
static int string_equal (Lisp_Object, Lisp_Object, int);
extern void print_string (Lisp_Object, Lisp_Object, int);
DEFINE_BASIC_LRECORD_IMPLEMENTATION ("string", string,
				     mark_string, print_string,
				     /*
				      * No `finalize', or `hash' methods.
				      * internal_hash already knows how
				      * to hash strings and finalization
				      * is done with the
				      * ADDITIONAL_FREE_string macro,
				      * which is the standard way to do
				      * finalization when using
				      * SWEEP_FIXED_TYPE_BLOCK().
				      */
				     0, string_equal, 0,
				     struct Lisp_String);
static Lisp_Object
mark_string (Lisp_Object obj, void (*markobj) (Lisp_Object))
{
  struct Lisp_String *ptr = XSTRING (obj);

  if (GC_CONSP (ptr->plist) && GC_EXTENT_INFOP (XCAR (ptr->plist)))
    flush_cached_extent_info (XCAR (ptr->plist));
  return ptr->plist;
}

static int
string_equal (Lisp_Object o1, Lisp_Object o2, int depth)
{
  Bytecount len = XSTRING_LENGTH (o1);
  if (len != XSTRING_LENGTH (o2))
    return 0;
  if (memcmp (XSTRING_DATA (o1), XSTRING_DATA (o2), len))
    return 0;
  return 1;
}
#endif /* LRECORD_STRING */

/* String blocks contain this many useful bytes. */
#define STRING_CHARS_BLOCK_SIZE \
  (8192 - MALLOC_OVERHEAD - ((2 * sizeof (struct string_chars_block *)) \
                             + sizeof (EMACS_INT)))
/* Block header for small strings. */
struct string_chars_block
{
  EMACS_INT pos;
  struct string_chars_block *next;
  struct string_chars_block *prev;
  /* Contents of string_chars_block->string_chars are interleaved
     string_chars structures (see below) and the actual string data */
  unsigned char string_chars[STRING_CHARS_BLOCK_SIZE];
};

struct string_chars_block *first_string_chars_block;
struct string_chars_block *current_string_chars_block;

/* If SIZE is the length of a string, this returns how many bytes
 *  the string occupies in string_chars_block->string_chars
 *  (including alignment padding).
 */
#define STRING_FULLSIZE(s) \
   ALIGN_SIZE (((s) + 1 + sizeof (struct Lisp_String *)),\
               ALIGNOF (struct Lisp_String *))

#define BIG_STRING_FULLSIZE_P(fullsize) ((fullsize) >= STRING_CHARS_BLOCK_SIZE)
#define BIG_STRING_SIZE_P(size) (BIG_STRING_FULLSIZE_P (STRING_FULLSIZE(size)))

#define CHARS_TO_STRING_CHAR(x) \
  ((struct string_chars *) \
   (((char *) (x)) - (slot_offset (struct string_chars, chars[0]))))


struct string_chars
{
  struct Lisp_String *string;
  unsigned char chars[1];
};

struct unused_string_chars
{
  struct Lisp_String *string;
  EMACS_INT fullsize;
};

static void
init_string_chars_alloc (void)
{
  first_string_chars_block = xnew (struct string_chars_block);
  first_string_chars_block->prev = 0;
  first_string_chars_block->next = 0;
  first_string_chars_block->pos = 0;
  current_string_chars_block = first_string_chars_block;
}

static struct string_chars *
allocate_string_chars_struct (struct Lisp_String *string_it_goes_with,
			      EMACS_INT fullsize)
{
  struct string_chars *s_chars;

  /* Allocate the string's actual data */
  if (BIG_STRING_FULLSIZE_P (fullsize))
    {
      s_chars = (struct string_chars *) xmalloc (fullsize);
    }
  else if (fullsize <=
           (countof (current_string_chars_block->string_chars)
            - current_string_chars_block->pos))
    {
      /* This string can fit in the current string chars block */
      s_chars = (struct string_chars *)
	(current_string_chars_block->string_chars
	 + current_string_chars_block->pos);
      current_string_chars_block->pos += fullsize;
    }
  else
    {
      /* Make a new current string chars block */
      struct string_chars_block *new = xnew (struct string_chars_block);

      current_string_chars_block->next = new;
      new->prev = current_string_chars_block;
      new->next = 0;
      current_string_chars_block = new;
      new->pos = fullsize;
      s_chars = (struct string_chars *)
	current_string_chars_block->string_chars;
    }

  s_chars->string = string_it_goes_with;

  INCREMENT_CONS_COUNTER (fullsize, "string chars");

  return s_chars;
}

Lisp_Object
make_uninit_string (Bytecount length)
{
  struct Lisp_String *s;
  struct string_chars *s_chars;
  EMACS_INT fullsize = STRING_FULLSIZE (length);
  Lisp_Object val;

  if ((length < 0) || (fullsize <= 0))
    abort ();

  /* Allocate the string header */
  ALLOCATE_FIXED_TYPE (string, struct Lisp_String, s);
#ifdef LRECORD_STRING
  set_lheader_implementation (&(s->lheader), lrecord_string);
#endif

  s_chars = allocate_string_chars_struct (s, fullsize);

  set_string_data (s, &(s_chars->chars[0]));
  set_string_length (s, length);
  s->plist = Qnil;

  set_string_byte (s, length, 0);

  XSETSTRING (val, s);
  return val;
}

#ifdef VERIFY_STRING_CHARS_INTEGRITY
static void verify_string_chars_integrity (void);
#endif

/* Resize the string S so that DELTA bytes can be inserted starting
   at POS.  If DELTA < 0, it means deletion starting at POS.  If
   POS < 0, resize the string but don't copy any characters.  Use
   this if you're planning on completely overwriting the string.
*/

void
resize_string (struct Lisp_String *s, Bytecount pos, Bytecount delta)
{
#ifdef VERIFY_STRING_CHARS_INTEGRITY
  verify_string_chars_integrity ();
#endif

#ifdef ERROR_CHECK_BUFPOS
  if (pos >= 0)
    {
      assert (pos <= string_length (s));
      if (delta < 0)
	assert (pos + (-delta) <= string_length (s));
    }
  else
    {
      if (delta < 0)
	assert ((-delta) <= string_length (s));
    }
#endif /* ERROR_CHECK_BUFPOS */

  if (pos >= 0 && delta < 0)
  /* If DELTA < 0, the functions below will delete the characters
     before POS.  We want to delete characters *after* POS, however,
     so convert this to the appropriate form. */
    pos += -delta;

  if (delta == 0)
    /* simplest case: no size change. */
    return;
  else
    {
      EMACS_INT oldfullsize = STRING_FULLSIZE (string_length (s));
      EMACS_INT newfullsize = STRING_FULLSIZE (string_length (s) + delta);

      if (oldfullsize == newfullsize)
	{
	  /* next simplest case; size change but the necessary
	     allocation size won't change (up or down; code somewhere
	     depends on there not being any unused allocation space,
	     modulo any alignment constraints). */
	  if (pos >= 0)
	    {
	      Bufbyte *addroff = pos + string_data (s);

	      memmove (addroff + delta, addroff,
		       /* +1 due to zero-termination. */
		       string_length (s) + 1 - pos);
	    }
	}
      else if (BIG_STRING_FULLSIZE_P (oldfullsize) &&
	       BIG_STRING_FULLSIZE_P (newfullsize))
	{
	  /* next simplest case; the string is big enough to be malloc()ed
	     itself, so we just realloc.

	     It's important not to let the string get below the threshold
	     for making big strings and still remain malloc()ed; if that
	     were the case, repeated calls to this function on the same
	     string could result in memory leakage. */
	  set_string_data (s, (Bufbyte *) xrealloc (string_data (s),
						    newfullsize));
	  if (pos >= 0)
	    {
	      Bufbyte *addroff = pos + string_data (s);

	      memmove (addroff + delta, addroff,
		       /* +1 due to zero-termination. */
		       string_length (s) + 1 - pos);
	    }
	}
      else
	{
	  /* worst case.  We make a new string_chars struct and copy
	     the string's data into it, inserting/deleting the delta
	     in the process.  The old string data will either get
	     freed by us (if it was malloc()ed) or will be reclaimed
	     in the normal course of garbage collection. */
	  struct string_chars *s_chars =
	    allocate_string_chars_struct (s, newfullsize);
	  Bufbyte *new_addr = &(s_chars->chars[0]);
	  Bufbyte *old_addr = string_data (s);
	  if (pos >= 0)
	    {
	      memcpy (new_addr, old_addr, pos);
	      memcpy (new_addr + pos + delta, old_addr + pos,
		      string_length (s) + 1 - pos);
	    }
	  set_string_data (s, new_addr);
	  if (BIG_STRING_FULLSIZE_P (oldfullsize))
	    xfree (old_addr);
	  else
	    {
	      /* We need to mark this chunk of the string_chars_block
		 as unused so that compact_string_chars() doesn't
		 freak. */
	      struct string_chars *old_s_chars =
		(struct string_chars *) ((char *) old_addr -
					 sizeof (struct Lisp_String *));
	      /* Sanity check to make sure we aren't hosed by strange
	         alignment/padding. */
	      assert (old_s_chars->string == s);
	      MARK_STRUCT_AS_FREE (old_s_chars);
	      ((struct unused_string_chars *) old_s_chars)->fullsize =
		oldfullsize;
	    }
	}

      set_string_length (s, string_length (s) + delta);
      /* If pos < 0, the string won't be zero-terminated.
	 Terminate now just to make sure. */
      string_data (s)[string_length (s)] = '\0';

      if (pos >= 0)
	{
	  Lisp_Object string = Qnil;

	  XSETSTRING (string, s);
	  /* We also have to adjust all of the extent indices after the
	     place we did the change.  We say "pos - 1" because
	     adjust_extents() is exclusive of the starting position
	     passed to it. */
	  adjust_extents (string, pos - 1, string_length (s),
			  delta);
	}
    }

#ifdef VERIFY_STRING_CHARS_INTEGRITY
  verify_string_chars_integrity ();
#endif
}

#ifdef MULE

void
set_string_char (struct Lisp_String *s, Charcount i, Emchar c)
{
  Bytecount oldlen, newlen;
  Bufbyte newstr[MAX_EMCHAR_LEN];
  Bytecount bytoff = charcount_to_bytecount (string_data (s), i);

  oldlen = charcount_to_bytecount (string_data (s) + bytoff, 1);
  newlen = set_charptr_emchar (newstr, c);

  if (oldlen != newlen)
    resize_string (s, bytoff, newlen - oldlen);
  /* Remember, string_data (s) might have changed so we can't cache it. */
  memcpy (string_data (s) + bytoff, newstr, newlen);
}

#endif /* MULE */

DEFUN ("make-string", Fmake_string, 2, 2, 0, /*
Return a newly created string of length LENGTH, with each element being INIT.
LENGTH must be an integer and INIT must be a character.
*/
       (length, init))
{
  Lisp_Object val;

  CHECK_NATNUM (length);
  CHECK_CHAR_COERCE_INT (init);
  {
    Bufbyte str[MAX_EMCHAR_LEN];
    int len = set_charptr_emchar (str, XCHAR (init));

    val = make_uninit_string (len * XINT (length));
    if (len == 1)
      /* Optimize the single-byte case */
      memset (XSTRING_DATA (val), XCHAR (init), XSTRING_LENGTH (val));
    else
      {
	int i, j, k;
	Bufbyte *ptr = XSTRING_DATA (val);

	k = 0;
	for (i = 0; i < XINT (length); i++)
	  for (j = 0; j < len; j++)
	    ptr[k++] = str[j];
      }
  }
  return val;
}

/* Take some raw memory, which MUST already be in internal format,
   and package it up it into a Lisp string. */
Lisp_Object
make_string (CONST Bufbyte *contents, Bytecount length)
{
  Lisp_Object val;

  /* Make sure we find out about bad make_string's when they happen */
#if defined (ERROR_CHECK_BUFPOS) && defined (MULE)
  bytecount_to_charcount (contents, length); /* Just for the assertions */
#endif

  val = make_uninit_string (length);
  memcpy (XSTRING_DATA (val), contents, length);
  return val;
}

/* Take some raw memory, encoded in some external data format,
   and convert it into a Lisp string. */
Lisp_Object
make_ext_string (CONST Extbyte *contents, EMACS_INT length,
		 enum external_data_format fmt)
{
  CONST Bufbyte *intstr;
  Bytecount intlen;

  GET_CHARPTR_INT_DATA_ALLOCA (contents, length, fmt, intstr, intlen);
  return make_string (intstr, intlen);
}

Lisp_Object
build_string (CONST char *str)
{
  /* Some strlen's crash and burn if passed null. */
  return make_string ((CONST Bufbyte *) str, (str ? strlen(str) : 0));
}

Lisp_Object
build_ext_string (CONST char *str, enum external_data_format fmt)
{
  /* Some strlen's crash and burn if passed null. */
  return make_ext_string ((Extbyte *) str, (str ? strlen(str) : 0), fmt);
}

Lisp_Object
build_translated_string (CONST char *str)
{
  return build_string (GETTEXT (str));
}


/************************************************************************/
/*                           lcrecord lists                             */
/************************************************************************/

/* Lcrecord lists are used to manage the allocation of particular
   sorts of lcrecords, to avoid calling alloc_lcrecord() (and thus
   malloc() and garbage-collection junk) as much as possible.
   It is similar to the Blocktype class.

   It works like this:

   1) Create an lcrecord-list object using make_lcrecord_list().
      This is often done at initialization.  Remember to staticpro
      this object!  The arguments to make_lcrecord_list() are the
      same as would be passed to alloc_lcrecord().
   2) Instead of calling alloc_lcrecord(), call allocate_managed_lcrecord()
      and pass the lcrecord-list earlier created.
   3) When done with the lcrecord, call free_managed_lcrecord().
      The standard freeing caveats apply: ** make sure there are no
      pointers to the object anywhere! **
   4) Calling free_managed_lcrecord() is just like kissing the
      lcrecord goodbye as if it were garbage-collected.  This means:
      -- the contents of the freed lcrecord are undefined, and the
         contents of something produced by allocate_managed_lcrecord()
	 are undefined, just like for alloc_lcrecord().
      -- the mark method for the lcrecord's type will *NEVER* be called
         on freed lcrecords.
      -- the finalize method for the lcrecord's type will be called
         at the time that free_managed_lcrecord() is called.

   */

static Lisp_Object mark_lcrecord_list (Lisp_Object, void (*) (Lisp_Object));
DEFINE_LRECORD_IMPLEMENTATION ("lcrecord-list", lcrecord_list,
			       mark_lcrecord_list, internal_object_printer,
			       0, 0, 0, struct lcrecord_list);

static Lisp_Object
mark_lcrecord_list (Lisp_Object obj, void (*markobj) (Lisp_Object))
{
  struct lcrecord_list *list = XLCRECORD_LIST (obj);
  Lisp_Object chain = list->free;

  while (!NILP (chain))
    {
      struct lrecord_header *lheader = XRECORD_LHEADER (chain);
      struct free_lcrecord_header *free_header =
	(struct free_lcrecord_header *) lheader;

#ifdef ERROR_CHECK_GC
      CONST struct lrecord_implementation *implementation
	= LHEADER_IMPLEMENTATION(lheader);

      /* There should be no other pointers to the free list. */
      assert (!MARKED_RECORD_HEADER_P (lheader));
      /* Only lcrecords should be here. */
      assert (!implementation->basic_p);
      /* Only free lcrecords should be here. */
      assert (free_header->lcheader.free);
      /* The type of the lcrecord must be right. */
      assert (implementation == list->implementation);
      /* So must the size. */
      assert (implementation->static_size == 0
	      || implementation->static_size == list->size);
#endif /* ERROR_CHECK_GC */

      MARK_RECORD_HEADER (lheader);
      chain = free_header->chain;
    }

  return Qnil;
}

Lisp_Object
make_lcrecord_list (int size,
		    CONST struct lrecord_implementation *implementation)
{
  struct lcrecord_list *p = alloc_lcrecord_type (struct lcrecord_list,
						 lrecord_lcrecord_list);
  Lisp_Object val = Qnil;

  p->implementation = implementation;
  p->size = size;
  p->free = Qnil;
  XSETLCRECORD_LIST (val, p);
  return val;
}

Lisp_Object
allocate_managed_lcrecord (Lisp_Object lcrecord_list)
{
  struct lcrecord_list *list = XLCRECORD_LIST (lcrecord_list);
  if (!NILP (list->free))
    {
      Lisp_Object val = list->free;
      struct free_lcrecord_header *free_header =
	(struct free_lcrecord_header *) XPNTR (val);

#ifdef ERROR_CHECK_GC
      struct lrecord_header *lheader =
	(struct lrecord_header *) free_header;
      CONST struct lrecord_implementation *implementation
	= LHEADER_IMPLEMENTATION (lheader);

      /* There should be no other pointers to the free list. */
      assert (!MARKED_RECORD_HEADER_P (lheader));
      /* Only lcrecords should be here. */
      assert (!implementation->basic_p);
      /* Only free lcrecords should be here. */
      assert (free_header->lcheader.free);
      /* The type of the lcrecord must be right. */
      assert (implementation == list->implementation);
      /* So must the size. */
      assert (implementation->static_size == 0
	      || implementation->static_size == list->size);
#endif /* ERROR_CHECK_GC */
      list->free = free_header->chain;
      free_header->lcheader.free = 0;
      return val;
    }
  else
    {
      Lisp_Object val = Qnil;

      XSETOBJ (val, Lisp_Type_Record,
	       alloc_lcrecord (list->size, list->implementation));
      return val;
    }
}

void
free_managed_lcrecord (Lisp_Object lcrecord_list, Lisp_Object lcrecord)
{
  struct lcrecord_list *list = XLCRECORD_LIST (lcrecord_list);
  struct free_lcrecord_header *free_header =
    (struct free_lcrecord_header *) XPNTR (lcrecord);
  struct lrecord_header *lheader =
    (struct lrecord_header *) free_header;
  CONST struct lrecord_implementation *implementation
    = LHEADER_IMPLEMENTATION (lheader);

#ifdef ERROR_CHECK_GC
  /* Make sure the size is correct.  This will catch, for example,
     putting a window configuration on the wrong free list. */
  if (implementation->size_in_bytes_method)
    assert (((implementation->size_in_bytes_method) (lheader))
	    == list->size);
  else
    assert (implementation->static_size == list->size);
#endif /* ERROR_CHECK_GC */

  if (implementation->finalizer)
    ((implementation->finalizer) (lheader, 0));
  free_header->chain = list->free;
  free_header->lcheader.free = 1;
  list->free = lcrecord;
}


/**********************************************************************/
/*                 Purity of essence, peace on earth                  */
/**********************************************************************/

static int symbols_initialized;

Lisp_Object
make_pure_string (CONST Bufbyte *data, Bytecount length,
		  Lisp_Object plist, int no_need_to_copy_data)
{
  Lisp_Object new;
  struct Lisp_String *s;
  int size = (sizeof (struct Lisp_String) + ((no_need_to_copy_data)
                                             ? 0
                                             /* + 1 for terminating 0 */
                                             : (length + 1)));
  size = ALIGN_SIZE (size, ALIGNOF (Lisp_Object));

  if (symbols_initialized && !pure_lossage)
    {
      /* Try to share some names.  Saves a few kbytes. */
      Lisp_Object tem = oblookup (Vobarray, data, length);
      if (SYMBOLP (tem))
	{
	  s = XSYMBOL (tem)->name;
	  if (!PURIFIED (s)) abort ();
	  XSETSTRING (new, s);
	  return new;
	}
    }

  if (!check_purespace (size))
    return make_string (data, length);

  s = (struct Lisp_String *) (PUREBEG + pureptr);
#ifdef LRECORD_STRING
  set_lheader_implementation (&(s->lheader), lrecord_string);
#ifdef USE_INDEXED_LRECORD_IMPLEMENTATION
  s->lheader.pure = 1;
#endif
#endif
  set_string_length (s, length);
  if (no_need_to_copy_data)
    {
      set_string_data (s, (Bufbyte *) data);
    }
  else
    {
      set_string_data (s, (Bufbyte *) s + sizeof (struct Lisp_String));
      memcpy (string_data (s), data, length);
      set_string_byte (s, length, 0);
    }
  s->plist = Qnil;
  pureptr += size;

#ifdef PURESTAT
  bump_purestat (&purestat_string_all, size);
  if (purecopying_for_bytecode)
    bump_purestat (&purestat_string_other_function, size);
#endif /* PURESTAT */

  /* Do this after the official "completion" of the purecopying. */
  s->plist = Fpurecopy (plist);

  XSETSTRING (new, s);
  return new;
}


Lisp_Object
make_pure_pname (CONST Bufbyte *data, Bytecount length,
		 int no_need_to_copy_data)
{
  Lisp_Object name = make_pure_string (data, length, Qnil,
				       no_need_to_copy_data);
  bump_purestat (&purestat_string_pname, pure_sizeof (name));

  /* We've made (at least) Qnil now, and Vobarray will soon be set up. */
  symbols_initialized = 1;

  return name;
}


Lisp_Object
pure_cons (Lisp_Object car, Lisp_Object cdr)
{
  Lisp_Object new;
  struct Lisp_Cons *c;

  if (!check_purespace (sizeof (struct Lisp_Cons)))
    return Fcons (Fpurecopy (car), Fpurecopy (cdr));

  c = (struct Lisp_Cons *) (PUREBEG + pureptr);
#ifdef LRECORD_CONS
  set_lheader_implementation (&(c->lheader), lrecord_cons);
#ifdef USE_INDEXED_LRECORD_IMPLEMENTATION
  c->lheader.pure = 1;
#endif
#endif
  pureptr += sizeof (struct Lisp_Cons);
  bump_purestat (&purestat_cons, sizeof (struct Lisp_Cons));

  c->car = Fpurecopy (car);
  c->cdr = Fpurecopy (cdr);
  XSETCONS (new, c);
  return new;
}

Lisp_Object
pure_list (int nargs, Lisp_Object *args)
{
  Lisp_Object foo = Qnil;

  for (--nargs; nargs >= 0; nargs--)
    foo = pure_cons (args[nargs], foo);

  return foo;
}

#ifdef LISP_FLOAT_TYPE

Lisp_Object
make_pure_float (double num)
{
  struct Lisp_Float *f;
  Lisp_Object val;

  /* Make sure that PUREBEG + pureptr is aligned on at least a sizeof
     (double) boundary.  Some architectures (like the sparc) require
     this, and I suspect that floats are rare enough that it's no
     tragedy for those that don't. */
  {
#if defined (__GNUC__) && (__GNUC__ >= 2)
    /* In gcc, we can directly ask what the alignment constraints of a
       structure are, but in general, that's not possible...  Arrgh!!
     */
    int alignment = __alignof (struct Lisp_Float);
#else /* !GNUC */
    /* Best guess is to make the `double' slot be aligned to the size
       of double (which is probably 8 bytes).  This assumes that it's
       ok to align the beginning of the structure to the same boundary
       that the `double' slot in it is supposed to be aligned to; this
       should be ok because presumably there is padding in the layout
       of the struct to account for this.
     */
    int alignment = sizeof (float_data (f));
#endif /* !GNUC */
    char *p = ((char *) PUREBEG + pureptr);

    p = (char *) (((unsigned EMACS_INT) p + alignment - 1) & - alignment);
    pureptr = p - (char *) PUREBEG;
  }

  if (!check_purespace (sizeof (struct Lisp_Float)))
    return make_float (num);

  f = (struct Lisp_Float *) (PUREBEG + pureptr);
  set_lheader_implementation (&(f->lheader), lrecord_float);
#ifdef USE_INDEXED_LRECORD_IMPLEMENTATION
  f->lheader.pure = 1;
#endif
  pureptr += sizeof (struct Lisp_Float);
  bump_purestat (&purestat_float, sizeof (struct Lisp_Float));

  float_next (f) = ((struct Lisp_Float *) -1);
  float_data (f) = num;
  XSETFLOAT (val, f);
  return val;
}

#endif /* LISP_FLOAT_TYPE */

Lisp_Object
make_pure_vector (EMACS_INT len, Lisp_Object init)
{
  Lisp_Object new;
  struct Lisp_Vector *v;
  EMACS_INT size = (sizeof (struct Lisp_Vector)
              + (len - 1) * sizeof (Lisp_Object));

  init = Fpurecopy (init);

  if (!check_purespace (size))
    return make_vector (len, init);

  v = (struct Lisp_Vector *) (PUREBEG + pureptr);
#ifdef LRECORD_VECTOR
  set_lheader_implementation (&(v->header.lheader), lrecord_vector);
#ifdef USE_INDEXED_LRECORD_IMPLEMENTATION
  v->header.lheader.pure = 1;
#endif
#endif
  pureptr += size;
  bump_purestat (&purestat_vector_all, size);

  v->size = len;

  for (size = 0; size < len; size++)
    v->contents[size] = init;

  XSETVECTOR (new, v); 
  return new;
}

#if 0
/* Presently unused */
void *
alloc_pure_lrecord (int size, struct lrecord_implementation *implementation)
{
  struct lrecord_header *header = (void *) (PUREBEG + pureptr);

  if (pureptr + size > get_PURESIZE())
    pure_storage_exhausted ();

  set_lheader_implementation (header, implementation);
  header->next = 0;
  return header;
}
#endif /* unused */



DEFUN ("purecopy", Fpurecopy, 1, 1, 0, /*
Make a copy of OBJECT in pure storage.
Recursively copies contents of vectors and cons cells.
Does not copy symbols.
*/
       (obj))
{
  int i;
  if (!purify_flag)
    return obj;

  if (!POINTER_TYPE_P (XTYPE (obj))
      || PURIFIED (XPNTR (obj))
      /* happens when bootstrapping Qnil */
      || EQ (obj, Qnull_pointer))
    return obj;

  switch (XTYPE (obj))
    {
#ifndef LRECORD_CONS
    case Lisp_Type_Cons:
      return pure_cons (XCAR (obj), XCDR (obj));
#endif

#ifndef LRECORD_STRING
    case Lisp_Type_String:
      return make_pure_string (XSTRING_DATA (obj),
			       XSTRING_LENGTH (obj),
			       XSTRING (obj)->plist,
                               0);
#endif /* ! LRECORD_STRING */

#ifndef LRECORD_VECTOR
    case Lisp_Type_Vector:
      {
        struct Lisp_Vector *o = XVECTOR (obj);
        Lisp_Object new = make_pure_vector (vector_length (o), Qnil);
        for (i = 0; i < vector_length (o); i++)
	  XVECTOR_DATA (new)[i] = Fpurecopy (o->contents[i]);
        return new;
      }
#endif /* !LRECORD_VECTOR */

    default:
      {
        if (COMPILED_FUNCTIONP (obj))
          {
            struct Lisp_Compiled_Function *o = XCOMPILED_FUNCTION (obj);
            Lisp_Object new = make_compiled_function (1);
	    /* How on earth could this code have worked before?  -sb */
            struct Lisp_Compiled_Function *n = XCOMPILED_FUNCTION (new);
            n->flags = o->flags;
            n->bytecodes = Fpurecopy (o->bytecodes);
            n->constants = Fpurecopy (o->constants);
            n->arglist = Fpurecopy (o->arglist);
            n->doc_and_interactive = Fpurecopy (o->doc_and_interactive);
	    n->maxdepth = o->maxdepth;
            return new;
          }
#ifdef LRECORD_CONS
      else if (CONSP (obj))
	return pure_cons (XCAR (obj), XCDR (obj));
#endif /* LRECORD_CONS */
#ifdef LRECORD_VECTOR
      else if (VECTORP (obj))
	{
	  struct Lisp_Vector *o = XVECTOR (obj);
	  Lisp_Object new = make_pure_vector (vector_length (o), Qnil);
	  for (i = 0; i < vector_length (o); i++)
	    XVECTOR_DATA (new)[i] = Fpurecopy (o->contents[i]);
	  return new;
	}
#endif /* LRECORD_VECTOR */
#ifdef LRECORD_STRING
      else if (STRINGP (obj))
	{
	  return make_pure_string (XSTRING_DATA (obj),
				   XSTRING_LENGTH (obj),
				   XSTRING (obj)->plist,
				   0);
	}
#endif /* LRECORD_STRING */
#ifdef LISP_FLOAT_TYPE
        else if (FLOATP (obj))
          return make_pure_float (float_data (XFLOAT (obj)));
#endif /* LISP_FLOAT_TYPE */
	else if (!SYMBOLP (obj))
          signal_simple_error ("Can't purecopy %S", obj);
      }
    }
  return obj;
}



static void
puresize_adjust_h (long int puresize)
{
  FILE *stream = fopen ("puresize-adjust.h", "w");

  if (stream == NULL)
    report_file_error ("Opening puresize adjustment file",
		       Fcons (build_string ("puresize-adjust.h"), Qnil));

  fprintf (stream,
	   "/*\tDo not edit this file!\n"
	   "\tAutomatically generated by XEmacs */\n"
	   "# define PURESIZE_ADJUSTMENT (%ld)\n",
	   puresize - RAW_PURESIZE);
  fclose (stream);
}

void
report_pure_usage (int report_impurities,
                   int die_if_pure_storage_exceeded)
{
  int rc = 0;

  if (pure_lossage)
    {
      message ("\n****\tPure Lisp storage exhausted!\n"
	       "\tPurespace usage: %ld of %ld\n"
	       "****",
               get_PURESIZE()+pure_lossage, (long) get_PURESIZE());
      if (die_if_pure_storage_exceeded) {
	puresize_adjust_h (get_PURESIZE() + pure_lossage);
	rc = -1;
      }
    }
  else
    {
      int lost = (get_PURESIZE() - pureptr) / 1024;
      char buf[200];
      extern Lisp_Object Vemacs_beta_version;
      int slop = NILP(Vemacs_beta_version) ? 512 : 4;

      sprintf (buf, "Purespace usage: %ld of %ld (%d%%",
               pureptr, (long) get_PURESIZE(),
               (int) (pureptr / (get_PURESIZE() / 100.0) + 0.5));
      if (lost > 2) {
        sprintf (buf + strlen (buf), " -- %dk wasted", lost);
	if (die_if_pure_storage_exceeded) {
	  puresize_adjust_h (pureptr + slop);
	  rc = -1;
	}
      }

      strcat (buf, ").");
      message ("%s", buf);
    }

#ifdef PURESTAT

  purestat_vector_other.nbytes =
    purestat_vector_all.nbytes -
    purestat_vector_bytecode_constants.nbytes;
  purestat_vector_other.nobjects =
    purestat_vector_all.nobjects -
    purestat_vector_bytecode_constants.nobjects;

  purestat_string_other.nbytes =
    purestat_string_all.nbytes -
    (purestat_string_pname.nbytes +
     purestat_string_bytecodes.nbytes +
     purestat_string_interactive.nbytes +
     purestat_string_documentation.nbytes +
#ifdef I18N3
     purestat_string_domain.nbytes +
#endif
     purestat_string_other_function.nbytes);

  purestat_string_other.nobjects =
    purestat_string_all.nobjects -
    (purestat_string_pname.nobjects +
     purestat_string_bytecodes.nobjects +
     purestat_string_interactive.nobjects +
     purestat_string_documentation.nobjects +
#ifdef I18N3
     purestat_string_domain.nobjects +
#endif
     purestat_string_other_function.nobjects);

  message ("   %-26s Total    Bytes", "");

  {
    int j;

    for (j = 0; j < countof (purestats); j++)
      if (!purestats[j])
        clear_message ();
      else
	{
	  char buf [100];
	  sprintf(buf, "%s:", purestats[j]->name);
	  message ("   %-26s %5d  %7d  %2d%%",
		   buf,
		   purestats[j]->nobjects,
		   purestats[j]->nbytes,
		   (int) (purestats[j]->nbytes / (pureptr / 100.0) + 0.5));
	}
  }
#endif /* PURESTAT */


  if (report_impurities)
    {
      Lisp_Object tem = Felt (Fgarbage_collect (), make_int (5));
      struct gcpro gcpro1;
      GCPRO1 (tem);
      message ("\nImpurities:");
      while (!NILP (tem))
	{
	  if (CONSP (tem) && SYMBOLP (Fcar (tem)) && CONSP (Fcdr (tem)))
	    {
	      int total = XINT (Fcar (Fcdr (tem)));
	      if (total > 0)
		{
		  char buf [100];
		  char *s = buf;
		  memcpy (buf, string_data (XSYMBOL (Fcar (tem))->name),
			  string_length (XSYMBOL (Fcar (tem))->name) + 1);
		  while (*s++) if (*s == '-') *s = ' ';
		  s--; *s++ = ':'; *s = 0;
		  message ("   %-33s %6d", buf, total);
		}
	      tem = Fcdr (Fcdr (tem));
	    }
	  else			/* WTF?! */
	    {
	      Fprin1 (tem, Qexternal_debugging_output);
	      tem = Qnil;
	    }
	}
      UNGCPRO;
      garbage_collect_1 ();         /* GC garbage_collect's garbage */
    }
  clear_message ();

  if (rc < 0) {
    unlink("SATISFIED");
				/* Current build process on NT does */
				/* not know how to restart itself. */
				/* --marcpa */
#ifndef WINDOWSNT
    fatal ("Pure size adjusted, Don't Panic!  I will restart the `make'");
#endif
  } else if (pure_lossage && die_if_pure_storage_exceeded) {
    fatal ("Pure storage exhausted");
  }
}


/**********************************************************************/
/*                            staticpro                               */
/**********************************************************************/

struct gcpro *gcprolist;

/* 415 used Mly 29-Jun-93 */
#define NSTATICS 1500
/* Not "static" because of linker lossage on some systems */
Lisp_Object *staticvec[NSTATICS]
     /* Force it into data space! */
     = {0};
static int staticidx;

/* Put an entry in staticvec, pointing at the variable whose address is given
 */
void
staticpro (Lisp_Object *varaddress)
{
  if (staticidx >= countof (staticvec))
    abort ();
  staticvec[staticidx++] = varaddress;
}


/* Mark reference to a Lisp_Object.  If the object referred to has not been
   seen yet, recursively mark all the references contained in it. */

static void
mark_object (Lisp_Object obj)
{
 tail_recurse:

  if (EQ (obj, Qnull_pointer))
    return;
  if (!POINTER_TYPE_P (XGCTYPE (obj)))
    return;
  if (PURIFIED (XPNTR (obj)))
    return;
  switch (XGCTYPE (obj))
    {
#ifndef LRECORD_CONS
    case Lisp_Type_Cons:
      {
	struct Lisp_Cons *ptr = XCONS (obj);
	if (CONS_MARKED_P (ptr))
	  break;
	MARK_CONS (ptr);
	/* If the cdr is nil, tail-recurse on the car.  */
	if (NILP (ptr->cdr))
	  {
	    obj = ptr->car;
	  }
	else
	  {
	    mark_object (ptr->car);
	    obj = ptr->cdr;
	  }
	goto tail_recurse;
      }
#endif

    case Lisp_Type_Record:
    /* case Lisp_Symbol_Value_Magic: */
      {
	struct lrecord_header *lheader = XRECORD_LHEADER (obj);
	CONST struct lrecord_implementation *implementation
	  = LHEADER_IMPLEMENTATION (lheader);

	if (! MARKED_RECORD_HEADER_P (lheader) &&
	    ! UNMARKABLE_RECORD_HEADER_P (lheader))
	  {
	    MARK_RECORD_HEADER (lheader);
#ifdef ERROR_CHECK_GC
	    if (!implementation->basic_p)
	      assert (! ((struct lcrecord_header *) lheader)->free);
#endif
	    if (implementation->marker != 0)
	      {
		obj = ((implementation->marker) (obj, mark_object));
		if (!NILP (obj)) goto tail_recurse;
	      }
	  }
      }
      break;

#ifndef LRECORD_STRING
    case Lisp_Type_String:
      {
	struct Lisp_String *ptr = XSTRING (obj);

	if (!XMARKBIT (ptr->plist))
	  {
	    if (CONSP (ptr->plist) &&
		EXTENT_INFOP (XCAR (ptr->plist)))
	      flush_cached_extent_info (XCAR (ptr->plist));
	    XMARK (ptr->plist);
	    obj = ptr->plist;
	    goto tail_recurse;
	  }
      }
      break;
#endif /* ! LRECORD_STRING */

#ifndef LRECORD_VECTOR
    case Lisp_Type_Vector:
      {
	struct Lisp_Vector *ptr = XVECTOR (obj);
	int len = vector_length (ptr);
	int i;

	if (len < 0)
	  break;		/* Already marked */
	ptr->size = -1 - len;	/* Else mark it */
	for (i = 0; i < len - 1; i++) /* and then mark its elements */
	  mark_object (ptr->contents[i]);
        if (len > 0)
        {
          obj = ptr->contents[len - 1];
          goto tail_recurse;
        }
      }
      break;
#endif /* !LRECORD_VECTOR */

#ifndef LRECORD_SYMBOL
    case Lisp_Type_Symbol:
      {
	struct Lisp_Symbol *sym = XSYMBOL (obj);

	while (!XMARKBIT (sym->plist))
	  {
	    XMARK (sym->plist);
	    mark_object (sym->value);
	    mark_object (sym->function);
	    {
	      /*
	       * symbol->name is a struct Lisp_String *, not a
	       * Lisp_Object.  Fix it up and pass to mark_object.
	       */
	      Lisp_Object symname;
	      XSETSTRING(symname, sym->name);
	      mark_object(symname);
	    }
	    if (!symbol_next (sym))
	      {
		obj = sym->plist;
		goto tail_recurse;
	      }
	    mark_object (sym->plist);
	    /* Mark the rest of the symbols in the hash-chain */
	    sym = symbol_next (sym);
	  }
      }
      break;
#endif /* !LRECORD_SYMBOL */

    default:
      abort ();
    }
}

/* mark all of the conses in a list and mark the final cdr; but
   DO NOT mark the cars.

   Use only for internal lists!  There should never be other pointers
   to the cons cells, because if so, the cars will remain unmarked
   even when they maybe should be marked. */
void
mark_conses_in_list (Lisp_Object obj)
{
  Lisp_Object rest;

  for (rest = obj; CONSP (rest); rest = XCDR (rest))
    {
      if (CONS_MARKED_P (XCONS (rest)))
	return;
      MARK_CONS (XCONS (rest));
    }

  mark_object (rest);
}


#ifdef PURESTAT
/* Simpler than mark-object, because pure structure can't
   have any circularities */

#if 0 /* unused */
static int idiot_c_doesnt_have_closures;
static void
idiot_c (Lisp_Object obj)
{
  idiot_c_doesnt_have_closures += pure_sizeof (obj, 1);
}
#endif /* unused */

static int
pure_string_sizeof(Lisp_Object obj)
{
  struct Lisp_String *ptr = XSTRING (obj);
  int size = string_length (ptr);

  if (string_data (ptr) !=
      (unsigned char *) ptr + sizeof (struct Lisp_String))
    {
      /* string-data not allocated contiguously.
	 Probably (better be!!) a pointer constant "C" data. */
      size = sizeof (struct Lisp_String);
    }
  else
    {
      size = sizeof (struct Lisp_String) + size + 1;
      size = ALIGN_SIZE (size, sizeof (Lisp_Object));
    }
  return size;
}

/* recurse arg isn't actually used */
static int
pure_sizeof (Lisp_Object obj /*, int recurse */)
{
  int total = 0;

  /*tail_recurse: */
  if (!POINTER_TYPE_P (XTYPE (obj))
      || !PURIFIED (XPNTR (obj)))
    return total;

  /* symbol's sizes are accounted for separately */
  if (SYMBOLP (obj))
    return total;

  switch (XTYPE (obj))
    {

#ifndef LRECORD_STRING
    case Lisp_Type_String:
      {
	total += pure_string_sizeof (obj);
      }
      break;
#endif /* ! LRECORD_STRING */

#ifndef LRECORD_VECTOR
    case Lisp_Type_Vector:
      {
        struct Lisp_Vector *ptr = XVECTOR (obj);
        int len = vector_length (ptr);

        total += (sizeof (struct Lisp_Vector)
                  + (len - 1) * sizeof (Lisp_Object));
#if 0 /* unused */
        if (!recurse)
          break;
        {
          int i;
	  for (i = 0; i < len - 1; i++)
	    total += pure_sizeof (ptr->contents[i], 1);
	}
        if (len > 0)
	  {
	    obj = ptr->contents[len - 1];
	    goto tail_recurse;
	  }
#endif /* unused */
      }
      break;
#endif /* !LRECORD_VECTOR */

    case Lisp_Type_Record:
      {
	struct lrecord_header *lheader = XRECORD_LHEADER (obj);
	CONST struct lrecord_implementation *implementation
	  = LHEADER_IMPLEMENTATION (lheader);

#ifdef LRECORD_STRING
	if (STRINGP (obj))
	  total += pure_string_sizeof (obj);
	else
#endif
        if (implementation->size_in_bytes_method)
          total += ((implementation->size_in_bytes_method) (lheader));
	else
          total += implementation->static_size;

#if 0 /* unused */
        if (!recurse)
          break;

	if (implementation->marker != 0)
	  {
	    int old = idiot_c_doesnt_have_closures;

	    idiot_c_doesnt_have_closures = 0;
	    obj = ((implementation->marker) (obj, idiot_c));
	    total += idiot_c_doesnt_have_closures;
	    idiot_c_doesnt_have_closures = old;

	    if (!NILP (obj)) goto tail_recurse;
	  }
#endif /* unused */
      }
      break;

#ifndef LRECORD_CONS
    case Lisp_Type_Cons:
      {
        struct Lisp_Cons *ptr = XCONS (obj);
        total += sizeof (*ptr);
#if 0 /* unused */
        if (!recurse)
          break;
	/* If the cdr is nil, tail-recurse on the car.  */
	if (NILP (ptr->cdr))
	  {
	    obj = ptr->car;
	  }
	else
	  {
	    total += pure_sizeof (ptr->car, 1);
	    obj = ptr->cdr;
	  }
	goto tail_recurse;
#endif /* unused */
      }
      break;
#endif

      /* Others can't be purified */
    default:
      abort ();
    }
  return total;
}
#endif /* PURESTAT */




/* Find all structures not marked, and free them. */

#ifndef LRECORD_VECTOR
static int gc_count_num_vector_used, gc_count_vector_total_size;
static int gc_count_vector_storage;
#endif
static int gc_count_num_bit_vector_used, gc_count_bit_vector_total_size;
static int gc_count_bit_vector_storage;
static int gc_count_num_short_string_in_use;
static int gc_count_string_total_size;
static int gc_count_short_string_total_size;

/* static int gc_count_total_records_used, gc_count_records_total_size; */


/* This will be used more extensively In The Future */
static int last_lrecord_type_index_assigned;

CONST struct lrecord_implementation *lrecord_implementations_table[128];
#define max_lrecord_type (countof (lrecord_implementations_table) - 1)

int
lrecord_type_index (CONST struct lrecord_implementation *implementation)
{
  int type_index = *(implementation->lrecord_type_index);
  /* Have to do this circuitous and validation test because of problems
     dumping out initialized variables (ie can't set xxx_type_index to -1
     because that would make xxx_type_index read-only in a dumped emacs. */
  if (type_index < 0 || type_index > max_lrecord_type
      || lrecord_implementations_table[type_index] != implementation)
    {
      if (last_lrecord_type_index_assigned == max_lrecord_type)
        abort ();
      type_index = ++last_lrecord_type_index_assigned;
      lrecord_implementations_table[type_index] = implementation;
      *(implementation->lrecord_type_index) = type_index;
    }
  return type_index;
}

/* stats on lcrecords in use - kinda kludgy */

static struct
{
  int instances_in_use;
  int bytes_in_use;
  int instances_freed;
  int bytes_freed;
  int instances_on_free_list;
} lcrecord_stats [countof (lrecord_implementations_table)];


static void
reset_lcrecord_stats (void)
{
  int i;
  for (i = 0; i < countof (lcrecord_stats); i++)
    {
      lcrecord_stats[i].instances_in_use = 0;
      lcrecord_stats[i].bytes_in_use = 0;
      lcrecord_stats[i].instances_freed = 0;
      lcrecord_stats[i].bytes_freed = 0;
      lcrecord_stats[i].instances_on_free_list = 0;
    }
}

static void
tick_lcrecord_stats (CONST struct lrecord_header *h, int free_p)
{
  CONST struct lrecord_implementation *implementation =
    LHEADER_IMPLEMENTATION (h);
  int type_index = lrecord_type_index (implementation);

  if (((struct lcrecord_header *) h)->free)
    {
      assert (!free_p);
      lcrecord_stats[type_index].instances_on_free_list++;
    }
  else
    {
      unsigned int sz = (implementation->size_in_bytes_method
			 ? ((implementation->size_in_bytes_method) (h))
			 : implementation->static_size);

      if (free_p)
	{
	  lcrecord_stats[type_index].instances_freed++;
	  lcrecord_stats[type_index].bytes_freed += sz;
	}
      else
	{
	  lcrecord_stats[type_index].instances_in_use++;
	  lcrecord_stats[type_index].bytes_in_use += sz;
	}
    }
}


/* Free all unmarked records */
static void
sweep_lcrecords_1 (struct lcrecord_header **prev, int *used)
{
  struct lcrecord_header *header;
  int num_used = 0;
  /* int total_size = 0; */
  reset_lcrecord_stats ();

  /* First go through and call all the finalize methods.
     Then go through and free the objects.  There used to
     be only one loop here, with the call to the finalizer
     occurring directly before the xfree() below.  That
     is marginally faster but much less safe -- if the
     finalize method for an object needs to reference any
     other objects contained within it (and many do),
     we could easily be screwed by having already freed that
     other object. */

  for (header = *prev; header; header = header->next)
    {
      struct lrecord_header *h = &(header->lheader);
      if (!MARKED_RECORD_HEADER_P (h) && ! (header->free))
	{
	  if (LHEADER_IMPLEMENTATION (h)->finalizer)
	    ((LHEADER_IMPLEMENTATION (h)->finalizer) (h, 0));
	}
    }

  for (header = *prev; header; )
    {
      struct lrecord_header *h = &(header->lheader);
      if (MARKED_RECORD_HEADER_P (h))
	{
	  UNMARK_RECORD_HEADER (h);
	  num_used++;
	  /* total_size += ((n->implementation->size_in_bytes) (h));*/
	  prev = &(header->next);
	  header = *prev;
	  tick_lcrecord_stats (h, 0);
	}
      else
	{
	  struct lcrecord_header *next = header->next;
          *prev = next;
	  tick_lcrecord_stats (h, 1);
	  /* used to call finalizer right here. */
	  xfree (header);
	  header = next;
	}
    }
  *used = num_used;
  /* *total = total_size; */
}

#ifndef LRECORD_VECTOR

static void
sweep_vectors_1 (Lisp_Object *prev,
                 int *used, int *total, int *storage)
{
  Lisp_Object vector;
  int num_used = 0;
  int total_size = 0;
  int total_storage = 0;

  for (vector = *prev; VECTORP (vector); )
    {
      struct Lisp_Vector *v = XVECTOR (vector);
      int len = v->size;
      if (len < 0)     /* marked */
	{
          len = - (len + 1);
	  v->size = len;
	  total_size += len;
          total_storage += (MALLOC_OVERHEAD
                            + sizeof (struct Lisp_Vector)
                            + (len - 1 + 1) * sizeof (Lisp_Object));
	  num_used++;
	  prev = &(vector_next (v));
	  vector = *prev;
	}
      else
	{
          Lisp_Object next = vector_next (v);
          *prev = next;
	  xfree (v);
	  vector = next;
	}
    }
  *used = num_used;
  *total = total_size;
  *storage = total_storage;
}

#endif /* ! LRECORD_VECTOR */

static void
sweep_bit_vectors_1 (Lisp_Object *prev,
		     int *used, int *total, int *storage)
{
  Lisp_Object bit_vector;
  int num_used = 0;
  int total_size = 0;
  int total_storage = 0;

  /* BIT_VECTORP fails because the objects are marked, which changes
     their implementation */
  for (bit_vector = *prev; !EQ (bit_vector, Qzero); )
    {
      struct Lisp_Bit_Vector *v = XBIT_VECTOR (bit_vector);
      int len = v->size;
      if (MARKED_RECORD_P (bit_vector))
	{
	  UNMARK_RECORD_HEADER (&(v->lheader));
	  total_size += len;
          total_storage += (MALLOC_OVERHEAD
                            + sizeof (struct Lisp_Bit_Vector)
                            + (BIT_VECTOR_LONG_STORAGE (len) - 1)
			    * sizeof (long));
	  num_used++;
	  prev = &(bit_vector_next (v));
	  bit_vector = *prev;
	}
      else
	{
          Lisp_Object next = bit_vector_next (v);
          *prev = next;
	  xfree (v);
	  bit_vector = next;
	}
    }
  *used = num_used;
  *total = total_size;
  *storage = total_storage;
}

/* And the Lord said: Thou shalt use the `c-backslash-region' command
   to make macros prettier. */

#ifdef ERROR_CHECK_GC

#define SWEEP_FIXED_TYPE_BLOCK(typename, obj_type)			\
do {									\
  struct typename##_block *_frob_current;				\
  struct typename##_block **_frob_prev;					\
  int _frob_limit;							\
  int num_free = 0, num_used = 0;					\
									\
  for (_frob_prev = &current_##typename##_block,			\
       _frob_current = current_##typename##_block,			\
       _frob_limit = current_##typename##_block_index;			\
       _frob_current;							\
       )								\
    {									\
      int _frob_iii;							\
									\
      for (_frob_iii = 0; _frob_iii < _frob_limit; _frob_iii++)		\
	{								\
	  obj_type *_frob_victim = &(_frob_current->block[_frob_iii]);	\
									\
	  if (FREE_STRUCT_P (_frob_victim))				\
	    {								\
	      num_free++;						\
	    }								\
	  else if (!MARKED_##typename##_P (_frob_victim))		\
	    {								\
	      num_free++;						\
	      FREE_FIXED_TYPE (typename, obj_type, _frob_victim);	\
	    }								\
	  else								\
	    {								\
	      num_used++;						\
	      UNMARK_##typename (_frob_victim);				\
	    }								\
	}								\
      _frob_prev = &(_frob_current->prev);				\
      _frob_current = _frob_current->prev;				\
      _frob_limit = countof (current_##typename##_block->block);	\
    }									\
									\
  gc_count_num_##typename##_in_use = num_used;				\
  gc_count_num_##typename##_freelist = num_free;			\
} while (0)

#else /* !ERROR_CHECK_GC */

#define SWEEP_FIXED_TYPE_BLOCK(typename, obj_type)			      \
do {									      \
  struct typename##_block *_frob_current;				      \
  struct typename##_block **_frob_prev;					      \
  int _frob_limit;							      \
  int num_free = 0, num_used = 0;					      \
									      \
  typename##_free_list = 0;						      \
									      \
  for (_frob_prev = &current_##typename##_block,			      \
       _frob_current = current_##typename##_block,			      \
       _frob_limit = current_##typename##_block_index;			      \
       _frob_current;							      \
       )								      \
    {									      \
      int _frob_iii;							      \
      int _frob_empty = 1;						      \
      obj_type *_frob_old_free_list = typename##_free_list;		      \
									      \
      for (_frob_iii = 0; _frob_iii < _frob_limit; _frob_iii++)		      \
	{								      \
	  obj_type *_frob_victim = &(_frob_current->block[_frob_iii]);	      \
									      \
	  if (FREE_STRUCT_P (_frob_victim))				      \
	    {								      \
	      num_free++;						      \
	      PUT_FIXED_TYPE_ON_FREE_LIST (typename, obj_type, _frob_victim); \
	    }								      \
	  else if (!MARKED_##typename##_P (_frob_victim))		      \
	    {								      \
	      num_free++;						      \
	      FREE_FIXED_TYPE (typename, obj_type, _frob_victim);	      \
	    }								      \
	  else								      \
	    {								      \
	      _frob_empty = 0;						      \
	      num_used++;						      \
	      UNMARK_##typename (_frob_victim);				      \
	    }								      \
	}								      \
      if (!_frob_empty)							      \
	{								      \
	  _frob_prev = &(_frob_current->prev);				      \
	  _frob_current = _frob_current->prev;				      \
	}								      \
      else if (_frob_current == current_##typename##_block		      \
	       && !_frob_current->prev)					      \
	{								      \
	  /* No real point in freeing sole allocation block */		      \
	  break;							      \
	}								      \
      else								      \
	{								      \
	  struct typename##_block *_frob_victim_block = _frob_current;	      \
	  if (_frob_victim_block == current_##typename##_block)		      \
	    current_##typename##_block_index				      \
	      = countof (current_##typename##_block->block);		      \
	  _frob_current = _frob_current->prev;				      \
	  {								      \
	    *_frob_prev = _frob_current;				      \
	    xfree (_frob_victim_block);					      \
	    /* Restore free list to what it was before victim was swept */    \
	    typename##_free_list = _frob_old_free_list;			      \
	    num_free -= _frob_limit;					      \
	  }								      \
	}								      \
      _frob_limit = countof (current_##typename##_block->block);	      \
    }									      \
									      \
  gc_count_num_##typename##_in_use = num_used;				      \
  gc_count_num_##typename##_freelist = num_free;			      \
} while (0)

#endif /* !ERROR_CHECK_GC */




static void
sweep_conses (void)
{
#ifndef LRECORD_CONS
# define MARKED_cons_P(ptr) XMARKBIT ((ptr)->car)
# define UNMARK_cons(ptr) do { XUNMARK ((ptr)->car); } while (0)
#else /* LRECORD_CONS */
# define MARKED_cons_P(ptr) MARKED_RECORD_HEADER_P (&((ptr)->lheader))
# define UNMARK_cons(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
#endif /* LRECORD_CONS */
#define ADDITIONAL_FREE_cons(ptr)

  SWEEP_FIXED_TYPE_BLOCK (cons, struct Lisp_Cons);
}

/* Explicitly free a cons cell.  */
void
free_cons (struct Lisp_Cons *ptr)
{
#ifdef ERROR_CHECK_GC
  /* If the CAR is not an int, then it will be a pointer, which will
     always be four-byte aligned.  If this cons cell has already been
     placed on the free list, however, its car will probably contain
     a chain pointer to the next cons on the list, which has cleverly
     had all its 0's and 1's inverted.  This allows for a quick
     check to make sure we're not freeing something already freed. */
  if (POINTER_TYPE_P (XTYPE (ptr->car)))
    ASSERT_VALID_POINTER (XPNTR (ptr->car));
#endif /* ERROR_CHECK_GC */

#ifndef ALLOC_NO_POOLS
  FREE_FIXED_TYPE_WHEN_NOT_IN_GC (cons, struct Lisp_Cons, ptr);
#endif /* ALLOC_NO_POOLS */
}

/* explicitly free a list.  You **must make sure** that you have
   created all the cons cells that make up this list and that there
   are no pointers to any of these cons cells anywhere else.  If there
   are, you will lose. */

void
free_list (Lisp_Object list)
{
  Lisp_Object rest, next;

  for (rest = list; !NILP (rest); rest = next)
    {
      next = XCDR (rest);
      free_cons (XCONS (rest));
    }
}

/* explicitly free an alist.  You **must make sure** that you have
   created all the cons cells that make up this alist and that there
   are no pointers to any of these cons cells anywhere else.  If there
   are, you will lose. */

void
free_alist (Lisp_Object alist)
{
  Lisp_Object rest, next;

  for (rest = alist; !NILP (rest); rest = next)
    {
      next = XCDR (rest);
      free_cons (XCONS (XCAR (rest)));
      free_cons (XCONS (rest));
    }
}

static void
sweep_compiled_functions (void)
{
#define MARKED_compiled_function_P(ptr) \
  MARKED_RECORD_HEADER_P (&((ptr)->lheader))
#define UNMARK_compiled_function(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
#define ADDITIONAL_FREE_compiled_function(ptr)

  SWEEP_FIXED_TYPE_BLOCK (compiled_function, struct Lisp_Compiled_Function);
}


#ifdef LISP_FLOAT_TYPE
static void
sweep_floats (void)
{
#define MARKED_float_P(ptr) MARKED_RECORD_HEADER_P (&((ptr)->lheader))
#define UNMARK_float(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
#define ADDITIONAL_FREE_float(ptr)

  SWEEP_FIXED_TYPE_BLOCK (float, struct Lisp_Float);
}
#endif /* LISP_FLOAT_TYPE */

static void
sweep_symbols (void)
{
#ifndef LRECORD_SYMBOL
# define MARKED_symbol_P(ptr) XMARKBIT ((ptr)->plist)
# define UNMARK_symbol(ptr) do { XUNMARK ((ptr)->plist); } while (0)
#else
# define MARKED_symbol_P(ptr) MARKED_RECORD_HEADER_P (&((ptr)->lheader))
# define UNMARK_symbol(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
#endif /* !LRECORD_SYMBOL */
#define ADDITIONAL_FREE_symbol(ptr)

  SWEEP_FIXED_TYPE_BLOCK (symbol, struct Lisp_Symbol);
}


#ifndef standalone

static void
sweep_extents (void)
{
#define MARKED_extent_P(ptr) MARKED_RECORD_HEADER_P (&((ptr)->lheader))
#define UNMARK_extent(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
#define ADDITIONAL_FREE_extent(ptr)

  SWEEP_FIXED_TYPE_BLOCK (extent, struct extent);
}

static void
sweep_events (void)
{
#define MARKED_event_P(ptr) MARKED_RECORD_HEADER_P (&((ptr)->lheader))
#define UNMARK_event(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
#define ADDITIONAL_FREE_event(ptr)

  SWEEP_FIXED_TYPE_BLOCK (event, struct Lisp_Event);
}

static void
sweep_markers (void)
{
#define MARKED_marker_P(ptr) MARKED_RECORD_HEADER_P (&((ptr)->lheader))
#define UNMARK_marker(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
#define ADDITIONAL_FREE_marker(ptr)					\
  do { Lisp_Object tem;							\
       XSETMARKER (tem, ptr);						\
       unchain_marker (tem);						\
     } while (0)

  SWEEP_FIXED_TYPE_BLOCK (marker, struct Lisp_Marker);
}

/* Explicitly free a marker.  */
void
free_marker (struct Lisp_Marker *ptr)
{
#ifdef ERROR_CHECK_GC
  /* Perhaps this will catch freeing an already-freed marker. */
  Lisp_Object temmy;
  XSETMARKER (temmy, ptr);
  assert (GC_MARKERP (temmy));
#endif /* ERROR_CHECK_GC */

#ifndef ALLOC_NO_POOLS
  FREE_FIXED_TYPE_WHEN_NOT_IN_GC (marker, struct Lisp_Marker, ptr);
#endif /* ALLOC_NO_POOLS */
}

#endif /* not standalone */



#if defined (MULE) && defined (VERIFY_STRING_CHARS_INTEGRITY)

static void
verify_string_chars_integrity (void)
{
  struct string_chars_block *sb;

  /* Scan each existing string block sequentially, string by string.  */
  for (sb = first_string_chars_block; sb; sb = sb->next)
    {
      int pos = 0;
      /* POS is the index of the next string in the block.  */
      while (pos < sb->pos)
        {
          struct string_chars *s_chars =
            (struct string_chars *) &(sb->string_chars[pos]);
          struct Lisp_String *string;
	  int size;
	  int fullsize;

	  /* If the string_chars struct is marked as free (i.e. the STRING
	     pointer is 0xFFFFFFFF) then this is an unused chunk of string
             storage. (See below.) */

	  if (FREE_STRUCT_P (s_chars))
	    {
	      fullsize = ((struct unused_string_chars *) s_chars)->fullsize;
	      pos += fullsize;
	      continue;
            }

          string = s_chars->string;
	  /* Must be 32-bit aligned. */
	  assert ((((int) string) & 3) == 0);

          size = string_length (string);
          fullsize = STRING_FULLSIZE (size);

          assert (!BIG_STRING_FULLSIZE_P (fullsize));
	  assert (string_data (string) == s_chars->chars);
	  pos += fullsize;
        }
      assert (pos == sb->pos);
    }
}

#endif /* MULE && ERROR_CHECK_GC */

/* Compactify string chars, relocating the reference to each --
   free any empty string_chars_block we see. */
static void
compact_string_chars (void)
{
  struct string_chars_block *to_sb = first_string_chars_block;
  int to_pos = 0;
  struct string_chars_block *from_sb;

  /* Scan each existing string block sequentially, string by string.  */
  for (from_sb = first_string_chars_block; from_sb; from_sb = from_sb->next)
    {
      int from_pos = 0;
      /* FROM_POS is the index of the next string in the block.  */
      while (from_pos < from_sb->pos)
        {
          struct string_chars *from_s_chars =
            (struct string_chars *) &(from_sb->string_chars[from_pos]);
          struct string_chars *to_s_chars;
          struct Lisp_String *string;
	  int size;
	  int fullsize;

	  /* If the string_chars struct is marked as free (i.e. the STRING
	     pointer is 0xFFFFFFFF) then this is an unused chunk of string
             storage.  This happens under Mule when a string's size changes
	     in such a way that its fullsize changes. (Strings can change
	     size because a different-length character can be substituted
	     for another character.) In this case, after the bogus string
	     pointer is the "fullsize" of this entry, i.e. how many bytes
	     to skip. */

	  if (FREE_STRUCT_P (from_s_chars))
	    {
	      fullsize = ((struct unused_string_chars *) from_s_chars)->fullsize;
	      from_pos += fullsize;
	      continue;
            }

          string = from_s_chars->string;
	  assert (!(FREE_STRUCT_P (string)));

          size = string_length (string);
          fullsize = STRING_FULLSIZE (size);

          if (BIG_STRING_FULLSIZE_P (fullsize))
            abort ();

          /* Just skip it if it isn't marked.  */
#ifdef LRECORD_STRING
	  if (! MARKED_RECORD_HEADER_P (&(string->lheader)))
#else
          if (!XMARKBIT (string->plist))
#endif
            {
              from_pos += fullsize;
              continue;
            }

          /* If it won't fit in what's left of TO_SB, close TO_SB out
             and go on to the next string_chars_block.  We know that TO_SB
             cannot advance past FROM_SB here since FROM_SB is large enough
             to currently contain this string. */
          if ((to_pos + fullsize) > countof (to_sb->string_chars))
            {
              to_sb->pos = to_pos;
              to_sb = to_sb->next;
              to_pos = 0;
            }

          /* Compute new address of this string
             and update TO_POS for the space being used.  */
          to_s_chars = (struct string_chars *) &(to_sb->string_chars[to_pos]);

          /* Copy the string_chars to the new place.  */
          if (from_s_chars != to_s_chars)
            memmove (to_s_chars, from_s_chars, fullsize);

          /* Relocate FROM_S_CHARS's reference */
          set_string_data (string, &(to_s_chars->chars[0]));

          from_pos += fullsize;
          to_pos += fullsize;
        }
    }

  /* Set current to the last string chars block still used and
     free any that follow. */
  {
    struct string_chars_block *victim;

    for (victim = to_sb->next; victim; )
      {
	struct string_chars_block *next = victim->next;
	xfree (victim);
	victim = next;
      }

    current_string_chars_block = to_sb;
    current_string_chars_block->pos = to_pos;
    current_string_chars_block->next = 0;
  }
}

#if 1 /* Hack to debug missing purecopy's */
static int debug_string_purity;

static void
debug_string_purity_print (struct Lisp_String *p)
{
  Charcount i;
  Charcount s = string_char_length (p);
  putc ('\"', stderr);
  for (i = 0; i < s; i++)
  {
    Emchar ch = string_char (p, i);
    if (ch < 32 || ch >= 126)
      stderr_out ("\\%03o", ch);
    else if (ch == '\\' || ch == '\"')
      stderr_out ("\\%c", ch);
    else
      stderr_out ("%c", ch);
  }
  stderr_out ("\"\n");
}
#endif /* 1 */


static void
sweep_strings (void)
{
  int num_small_used = 0, num_small_bytes = 0, num_bytes = 0;
  int debug = debug_string_purity;

#ifdef LRECORD_STRING

# define MARKED_string_P(ptr) MARKED_RECORD_HEADER_P (&((ptr)->lheader))
# define UNMARK_string(ptr)				\
  do { struct Lisp_String *p = (ptr);			\
       int size = string_length (p);			\
       UNMARK_RECORD_HEADER (&(p->lheader));		\
       num_bytes += size;				\
       if (!BIG_STRING_SIZE_P (size))			\
	 { num_small_bytes += size;			\
	   num_small_used++;				\
	 }						\
       if (debug) debug_string_purity_print (p);	\
     } while (0)
# define ADDITIONAL_FREE_string(p)				\
  do { int size = string_length (p);				\
       if (BIG_STRING_SIZE_P (size))				\
	 xfree_1 (CHARS_TO_STRING_CHAR (string_data (p)));	\
     } while (0)

#else

# define MARKED_string_P(ptr) XMARKBIT ((ptr)->plist)
# define UNMARK_string(ptr)				\
  do { struct Lisp_String *p = (ptr);			\
       int size = string_length (p);			\
       XUNMARK (p->plist);				\
       num_bytes += size;				\
       if (!BIG_STRING_SIZE_P (size))			\
	 { num_small_bytes += size;			\
	   num_small_used++;				\
	 }						\
       if (debug) debug_string_purity_print (p);	\
     } while (0)
# define ADDITIONAL_FREE_string(p)				\
  do { int size = string_length (p);				\
       if (BIG_STRING_SIZE_P (size))				\
	 xfree_1 (CHARS_TO_STRING_CHAR (string_data (p)));	\
     } while (0)

#endif /* ! LRECORD_STRING */

  SWEEP_FIXED_TYPE_BLOCK (string, struct Lisp_String);

  gc_count_num_short_string_in_use = num_small_used;
  gc_count_string_total_size = num_bytes;
  gc_count_short_string_total_size = num_small_bytes;
}


/* I hate duplicating all this crap! */
static int
marked_p (Lisp_Object obj)
{
  if (EQ (obj, Qnull_pointer)) return 1;
  if (!POINTER_TYPE_P (XGCTYPE (obj))) return 1;
  if (PURIFIED (XPNTR (obj))) return 1;
  switch (XGCTYPE (obj))
    {
#ifndef LRECORD_CONS
    case Lisp_Type_Cons:
      return XMARKBIT (XCAR (obj));
#endif
    case Lisp_Type_Record:
      return MARKED_RECORD_HEADER_P (XRECORD_LHEADER (obj));
#ifndef LRECORD_STRING
    case Lisp_Type_String:
      return XMARKBIT (XSTRING (obj)->plist);
#endif /* ! LRECORD_STRING */
#ifndef LRECORD_VECTOR
    case Lisp_Type_Vector:
      return XVECTOR_LENGTH (obj) < 0;
#endif /* !LRECORD_VECTOR */
#ifndef LRECORD_SYMBOL
    case Lisp_Type_Symbol:
      return XMARKBIT (XSYMBOL (obj)->plist);
#endif
    default:
      abort ();
    }
  return 0;	/* suppress compiler warning */
}

static void
gc_sweep (void)
{
  /* Free all unmarked records.  Do this at the very beginning,
     before anything else, so that the finalize methods can safely
     examine items in the objects.  sweep_lcrecords_1() makes
     sure to call all the finalize methods *before* freeing anything,
     to complete the safety. */
  {
    int ignored;
    sweep_lcrecords_1 (&all_lcrecords, &ignored);
  }

  compact_string_chars ();

  /* Finalize methods below (called through the ADDITIONAL_FREE_foo
     macros) must be *extremely* careful to make sure they're not
     referencing freed objects.  The only two existing finalize
     methods (for strings and markers) pass muster -- the string
     finalizer doesn't look at anything but its own specially-
     created block, and the marker finalizer only looks at live
     buffers (which will never be freed) and at the markers before
     and after it in the chain (which, by induction, will never be
     freed because if so, they would have already removed themselves
     from the chain). */

  /* Put all unmarked strings on free list, free'ing the string chars
     of large unmarked strings */
  sweep_strings ();

  /* Put all unmarked conses on free list */
  sweep_conses ();

#ifndef LRECORD_VECTOR
  /* Free all unmarked vectors */
  sweep_vectors_1 (&all_vectors,
                   &gc_count_num_vector_used, &gc_count_vector_total_size,
                   &gc_count_vector_storage);
#endif

  /* Free all unmarked bit vectors */
  sweep_bit_vectors_1 (&all_bit_vectors,
		       &gc_count_num_bit_vector_used,
		       &gc_count_bit_vector_total_size,
		       &gc_count_bit_vector_storage);

  /* Free all unmarked compiled-function objects */
  sweep_compiled_functions ();

#ifdef LISP_FLOAT_TYPE
  /* Put all unmarked floats on free list */
  sweep_floats ();
#endif

  /* Put all unmarked symbols on free list */
  sweep_symbols ();

  /* Put all unmarked extents on free list */
  sweep_extents ();

  /* Put all unmarked markers on free list.
     Dechain each one first from the buffer into which it points. */
  sweep_markers ();

  sweep_events ();

}

/* Clearing for disksave. */

extern Lisp_Object Vprocess_environment;
extern Lisp_Object Vdoc_directory;
extern Lisp_Object Vconfigure_info_directory;
extern Lisp_Object Vload_path;
extern Lisp_Object Vload_history;
extern Lisp_Object Vshell_file_name;

void
disksave_object_finalization (void)
{
  /* It's important that certain information from the environment not get
     dumped with the executable (pathnames, environment variables, etc.).
     To make it easier to tell when this has happend with strings(1) we
     clear some known-to-be-garbage blocks of memory, so that leftover
     results of old evaluation don't look like potential problems.
     But first we set some notable variables to nil and do one more GC,
     to turn those strings into garbage.
   */

  /* Yeah, this list is pretty ad-hoc... */
  Vprocess_environment = Qnil;
  Vexec_directory = Qnil;
  Vdata_directory = Qnil;
  Vsite_directory = Qnil;
  Vdoc_directory = Qnil;
  Vconfigure_info_directory = Qnil;
  Vexec_path = Qnil;
  Vload_path = Qnil;
  /* Vdump_load_path = Qnil; */
  Vload_history = Qnil;
  Vshell_file_name = Qnil;

  garbage_collect_1 ();

  /* Run the disksave finalization methods of all live objects. */
  disksave_object_finalization_1 ();

  /* Zero out the unused portion of purespace */
  if (!pure_lossage)
    memset (  (char *) (PUREBEG + pureptr), 0,
	    (((char *) (PUREBEG + get_PURESIZE())) -
	     ((char *) (PUREBEG + pureptr))));

  /* Zero out the uninitialized (really, unused) part of the containers
     for the live strings. */
  {
    struct string_chars_block *scb;
    for (scb = first_string_chars_block; scb; scb = scb->next)
      /* from the block's fill ptr to the end */
      memset ((scb->string_chars + scb->pos), 0,
              sizeof (scb->string_chars) - scb->pos);
  }

  /* There, that ought to be enough... */

}


Lisp_Object
restore_gc_inhibit (Lisp_Object val)
{
  gc_currently_forbidden = XINT (val);
  return val;
}

/* Maybe we want to use this when doing a "panic" gc after memory_full()? */
static int gc_hooks_inhibited;


void
garbage_collect_1 (void)
{
  char stack_top_variable;
  extern char *stack_bottom;
  int i;
  struct frame *f = selected_frame ();
  int speccount = specpdl_depth ();
  Lisp_Object pre_gc_cursor = Qnil;
  struct gcpro gcpro1;

  int cursor_changed = 0;

  if (gc_in_progress != 0)
    return;

  if (gc_currently_forbidden || in_display)
    return;

  if (preparing_for_armageddon)
    return;

  GCPRO1 (pre_gc_cursor);

  /* Very important to prevent GC during any of the following
     stuff that might run Lisp code; otherwise, we'll likely
     have infinite GC recursion. */
  record_unwind_protect (restore_gc_inhibit,
                         make_int (gc_currently_forbidden));
  gc_currently_forbidden = 1;

  if (!gc_hooks_inhibited)
    run_hook_trapping_errors ("Error in pre-gc-hook", Qpre_gc_hook);

  /* Now show the GC cursor/message. */
  if (!noninteractive)
    {
      if (FRAME_WIN_P (f))
	{
	  Lisp_Object frame = make_frame (f);
	  Lisp_Object cursor = glyph_image_instance (Vgc_pointer_glyph,
						     FRAME_SELECTED_WINDOW (f),
						     ERROR_ME_NOT, 1);
	  pre_gc_cursor = f->pointer;
	  if (POINTER_IMAGE_INSTANCEP (cursor)
	      /* don't change if we don't know how to change back. */
	      && POINTER_IMAGE_INSTANCEP (pre_gc_cursor))
	    {
	      cursor_changed = 1;
	      Fset_frame_pointer (frame, cursor);
	    }
	}

      /* Don't print messages to the stream device. */
      if (!cursor_changed && !FRAME_STREAM_P (f))
	{
	  char *msg = (STRINGP (Vgc_message)
		       ? GETTEXT ((char *) XSTRING_DATA (Vgc_message))
		       : 0);
	  Lisp_Object args[2], whole_msg;
	  args[0] = build_string (msg ? msg :
				  GETTEXT ((CONST char *) gc_default_message));
	  args[1] = build_string ("...");
	  whole_msg = Fconcat (2, args);
	  echo_area_message (f, (Bufbyte *) 0, whole_msg, 0, -1,
			     Qgarbage_collecting);
	}
    }

  /***** Now we actually start the garbage collection. */

  gc_in_progress = 1;

  gc_generation_number[0]++;

#if MAX_SAVE_STACK > 0

  /* Save a copy of the contents of the stack, for debugging.  */
  if (!purify_flag)
    {
      i = &stack_top_variable - stack_bottom;
      if (i < 0) i = -i;
      if (i < MAX_SAVE_STACK)
	{
	  if (stack_copy == 0)
	    stack_copy = (char *) malloc (stack_copy_size = i);
	  else if (stack_copy_size < i)
	    stack_copy = (char *) realloc (stack_copy, (stack_copy_size = i));
	  if (stack_copy)
	    {
	      if ((int) (&stack_top_variable - stack_bottom) > 0)
		memcpy (stack_copy, stack_bottom, i);
	      else
		memcpy (stack_copy, &stack_top_variable, i);
	    }
	}
    }
#endif /* MAX_SAVE_STACK > 0 */

  /* Do some totally ad-hoc resource clearing. */
  /* #### generalize this? */
  clear_event_resource ();
  cleanup_specifiers ();

  /* Mark all the special slots that serve as the roots of accessibility. */
  {
    struct gcpro *tail;
    struct catchtag *catch;
    struct backtrace *backlist;
    struct specbinding *bind;

    for (i = 0; i < staticidx; i++)
      {
#ifdef GDB_SUCKS
	printf ("%d\n", i);
	debug_print (*staticvec[i]);
#endif
        mark_object (*(staticvec[i]));
      }

    for (tail = gcprolist; tail; tail = tail->next)
      {
	for (i = 0; i < tail->nvars; i++)
	  mark_object (tail->var[i]);
      }

    for (bind = specpdl; bind != specpdl_ptr; bind++)
      {
	mark_object (bind->symbol);
	mark_object (bind->old_value);
      }

    for (catch = catchlist; catch; catch = catch->next)
      {
	mark_object (catch->tag);
	mark_object (catch->val);
      }

    for (backlist = backtrace_list; backlist; backlist = backlist->next)
      {
	int nargs = backlist->nargs;

	mark_object (*backlist->function);
	if (nargs == UNEVALLED || nargs == MANY)
	  mark_object (backlist->args[0]);
	else
	  for (i = 0; i < nargs; i++)
	    mark_object (backlist->args[i]);
      }

    mark_redisplay (mark_object);
#ifndef WINDOWSNT
    mark_profiling_info (mark_object);
#endif
  }

  /* OK, now do the after-mark stuff.  This is for things that
     are only marked when something else is marked (e.g. weak hashtables).
     There may be complex dependencies between such objects -- e.g.
     a weak hashtable might be unmarked, but after processing a later
     weak hashtable, the former one might get marked.  So we have to
     iterate until nothing more gets marked. */
  {
    int did_mark;
    /* Need to iterate until there's nothing more to mark, in case
       of chains of mark dependencies. */
    do
      {
        did_mark = 0;
	did_mark += !!finish_marking_weak_hashtables (marked_p, mark_object);
	did_mark += !!finish_marking_weak_lists (marked_p, mark_object);
      }
    while (did_mark);
  }

  /* And prune (this needs to be called after everything else has been
     marked and before we do any sweeping). */
  /* #### this is somewhat ad-hoc and should probably be an object
     method */
  prune_weak_hashtables (marked_p);
  prune_weak_lists (marked_p);
  prune_specifiers (marked_p);
  prune_syntax_tables (marked_p);

  gc_sweep ();

  consing_since_gc = 0;
#ifndef DEBUG_XEMACS
  /* Allow you to set it really fucking low if you really want ... */
  if (gc_cons_threshold < 10000)
    gc_cons_threshold = 10000;
#endif

  gc_in_progress = 0;

  /******* End of garbage collection ********/

  run_hook_trapping_errors ("Error in post-gc-hook", Qpost_gc_hook);

  /* Now remove the GC cursor/message */
  if (!noninteractive)
    {
      if (cursor_changed)
	Fset_frame_pointer (make_frame (f), pre_gc_cursor);
      else if (!FRAME_STREAM_P (f))
	{
	  char *msg = (STRINGP (Vgc_message)
		       ? GETTEXT ((char *) XSTRING_DATA (Vgc_message))
		       : 0);

	  /* Show "...done" only if the echo area would otherwise be empty. */
	  if (NILP (clear_echo_area (selected_frame (),
				     Qgarbage_collecting, 0)))
	    {
	      Lisp_Object args[2], whole_msg;
	      args[0] = build_string (msg ? msg :
				      GETTEXT ((CONST char *)
					       gc_default_message));
	      args[1] = build_string ("... done");
	      whole_msg = Fconcat (2, args);
	      echo_area_message (selected_frame (), (Bufbyte *) 0,
				 whole_msg, 0, -1,
				 Qgarbage_collecting);
	    }
	}
    }

  /* now stop inhibiting GC */
  unbind_to (speccount, Qnil);

  if (!breathing_space)
    {
      breathing_space = (void *) malloc (4096 - MALLOC_OVERHEAD);
    }

  UNGCPRO;
  return;
}

#ifdef EMACS_BTL
 /* This isn't actually called.  BTL recognizes the stack frame of the top
    of the garbage collector by noting that PC is between &garbage_collect_1
    and &BTL_after_garbage_collect_1_stub.  So this fn must be right here.
    There's not any other way to know the address of the end of a function.
  */
void BTL_after_garbage_collect_1_stub () { abort (); }
#endif /* EMACS_BTL */

/* Debugging aids.  */

static Lisp_Object
gc_plist_hack (CONST char *name, int value, Lisp_Object tail)
{
  /* C doesn't have local functions (or closures, or GC, or readable syntax,
     or portable numeric datatypes, or bit-vectors, or characters, or
     arrays, or exceptions, or ...) */
  return cons3 (intern (name), make_int (value), tail);
}

#define HACK_O_MATIC(type, name, pl)					\
  {									\
    int s = 0;								\
    struct type##_block *x = current_##type##_block;			\
    while (x) { s += sizeof (*x) + MALLOC_OVERHEAD; x = x->prev; }	\
    (pl) = gc_plist_hack ((name), s, (pl));				\
  }

DEFUN ("garbage-collect", Fgarbage_collect, 0, 0, "", /*
Reclaim storage for Lisp objects no longer needed.
Returns info on amount of space in use:
 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
  (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
  PLIST)
  where `PLIST' is a list of alternating keyword/value pairs providing
  more detailed information.
Garbage collection happens automatically if you cons more than
`gc-cons-threshold' bytes of Lisp data since previous garbage collection.
*/
       ())
{
  Lisp_Object pl = Qnil;
  Lisp_Object ret[6];
  int i;
#ifdef LRECORD_VECTOR
  int gc_count_vector_total_size;
#endif

  if (purify_flag && pure_lossage)
    {
      return Qnil;
    }

  garbage_collect_1 ();

  for (i = 0; i < last_lrecord_type_index_assigned; i++)
    {
      if (lcrecord_stats[i].bytes_in_use != 0
          || lcrecord_stats[i].bytes_freed != 0
	  || lcrecord_stats[i].instances_on_free_list != 0)
        {
          char buf [255];
          CONST char *name = lrecord_implementations_table[i]->name;
	  int len = strlen (name);
#ifdef LRECORD_VECTOR
	  /* save this for the FSFmacs-compatible part of the summary */
	  if (i == *lrecord_vector[0].lrecord_type_index)
	    gc_count_vector_total_size =
	      lcrecord_stats[i].bytes_in_use + lcrecord_stats[i].bytes_freed;
#endif
          sprintf (buf, "%s-storage", name);
          pl = gc_plist_hack (buf, lcrecord_stats[i].bytes_in_use, pl);
	  /* Okay, simple pluralization check for `symbol-value-varalias' */
	  if (name[len-1] == 's')
	    sprintf (buf, "%ses-freed", name);
	  else
	    sprintf (buf, "%ss-freed", name);
          if (lcrecord_stats[i].instances_freed != 0)
            pl = gc_plist_hack (buf, lcrecord_stats[i].instances_freed, pl);
	  if (name[len-1] == 's')
	    sprintf (buf, "%ses-on-free-list", name);
	  else
	    sprintf (buf, "%ss-on-free-list", name);
          if (lcrecord_stats[i].instances_on_free_list != 0)
            pl = gc_plist_hack (buf, lcrecord_stats[i].instances_on_free_list,
				pl);
	  if (name[len-1] == 's')
	    sprintf (buf, "%ses-used", name);
	  else
	    sprintf (buf, "%ss-used", name);
          pl = gc_plist_hack (buf, lcrecord_stats[i].instances_in_use, pl);
        }
    }

  HACK_O_MATIC (extent, "extent-storage", pl);
  pl = gc_plist_hack ("extents-free", gc_count_num_extent_freelist, pl);
  pl = gc_plist_hack ("extents-used", gc_count_num_extent_in_use, pl);
  HACK_O_MATIC (event, "event-storage", pl);
  pl = gc_plist_hack ("events-free", gc_count_num_event_freelist, pl);
  pl = gc_plist_hack ("events-used", gc_count_num_event_in_use, pl);
  HACK_O_MATIC (marker, "marker-storage", pl);
  pl = gc_plist_hack ("markers-free", gc_count_num_marker_freelist, pl);
  pl = gc_plist_hack ("markers-used", gc_count_num_marker_in_use, pl);
#ifdef LISP_FLOAT_TYPE
  HACK_O_MATIC (float, "float-storage", pl);
  pl = gc_plist_hack ("floats-free", gc_count_num_float_freelist, pl);
  pl = gc_plist_hack ("floats-used", gc_count_num_float_in_use, pl);
#endif /* LISP_FLOAT_TYPE */
  HACK_O_MATIC (string, "string-header-storage", pl);
  pl = gc_plist_hack ("long-strings-total-length",
                      gc_count_string_total_size
		      - gc_count_short_string_total_size, pl);
  HACK_O_MATIC (string_chars, "short-string-storage", pl);
  pl = gc_plist_hack ("short-strings-total-length",
                      gc_count_short_string_total_size, pl);
  pl = gc_plist_hack ("strings-free", gc_count_num_string_freelist, pl);
  pl = gc_plist_hack ("long-strings-used",
                      gc_count_num_string_in_use
		      - gc_count_num_short_string_in_use, pl);
  pl = gc_plist_hack ("short-strings-used",
                      gc_count_num_short_string_in_use, pl);

  HACK_O_MATIC (compiled_function, "compiled-function-storage", pl);
  pl = gc_plist_hack ("compiled-functions-free",
		      gc_count_num_compiled_function_freelist, pl);
  pl = gc_plist_hack ("compiled-functions-used",
		      gc_count_num_compiled_function_in_use, pl);

#ifndef LRECORD_VECTOR
  pl = gc_plist_hack ("vector-storage", gc_count_vector_storage, pl);
  pl = gc_plist_hack ("vectors-total-length",
                      gc_count_vector_total_size, pl);
  pl = gc_plist_hack ("vectors-used", gc_count_num_vector_used, pl);
#endif

  pl = gc_plist_hack ("bit-vector-storage", gc_count_bit_vector_storage, pl);
  pl = gc_plist_hack ("bit-vectors-total-length",
                      gc_count_bit_vector_total_size, pl);
  pl = gc_plist_hack ("bit-vectors-used", gc_count_num_bit_vector_used, pl);

  HACK_O_MATIC (symbol, "symbol-storage", pl);
  pl = gc_plist_hack ("symbols-free", gc_count_num_symbol_freelist, pl);
  pl = gc_plist_hack ("symbols-used", gc_count_num_symbol_in_use, pl);

  HACK_O_MATIC (cons, "cons-storage", pl);
  pl = gc_plist_hack ("conses-free", gc_count_num_cons_freelist, pl);
  pl = gc_plist_hack ("conses-used", gc_count_num_cons_in_use, pl);

  /* The things we do for backwards-compatibility */
  ret[0] = Fcons (make_int (gc_count_num_cons_in_use),
                  make_int (gc_count_num_cons_freelist));
  ret[1] = Fcons (make_int (gc_count_num_symbol_in_use),
                  make_int (gc_count_num_symbol_freelist));
  ret[2] = Fcons (make_int (gc_count_num_marker_in_use),
                  make_int (gc_count_num_marker_freelist));
  ret[3] = make_int (gc_count_string_total_size);
  ret[4] = make_int (gc_count_vector_total_size);
  ret[5] = pl;
  return Flist (6, ret);
}
#undef HACK_O_MATIC

DEFUN ("consing-since-gc", Fconsing_since_gc, 0, 0, "", /*
Return the number of bytes consed since the last garbage collection.
\"Consed\" is a misnomer in that this actually counts allocation
of all different kinds of objects, not just conses.

If this value exceeds `gc-cons-threshold', a garbage collection happens.
*/
       ())
{
  return make_int (consing_since_gc);
}

DEFUN ("memory-limit", Fmemory_limit, 0, 0, "", /*
Return the address of the last byte Emacs has allocated, divided by 1024.
This may be helpful in debugging Emacs's memory usage.
The value is divided by 1024 to make sure it will fit in a lisp integer.
*/
       ())
{
  return make_int ((EMACS_INT) sbrk (0) / 1024);
}



int
object_dead_p (Lisp_Object obj)
{
  return ((BUFFERP  (obj) && !BUFFER_LIVE_P  (XBUFFER  (obj))) ||
	  (FRAMEP   (obj) && !FRAME_LIVE_P   (XFRAME   (obj))) ||
	  (WINDOWP  (obj) && !WINDOW_LIVE_P  (XWINDOW  (obj))) ||
	  (DEVICEP  (obj) && !DEVICE_LIVE_P  (XDEVICE  (obj))) ||
	  (CONSOLEP (obj) && !CONSOLE_LIVE_P (XCONSOLE (obj))) ||
	  (EVENTP   (obj) && !EVENT_LIVE_P   (XEVENT   (obj))) ||
	  (EXTENTP  (obj) && !EXTENT_LIVE_P  (XEXTENT  (obj))));

}

#ifdef MEMORY_USAGE_STATS

/* Attempt to determine the actual amount of space that is used for
   the block allocated starting at PTR, supposedly of size "CLAIMED_SIZE".

   It seems that the following holds:

   1. When using the old allocator (malloc.c):

      -- blocks are always allocated in chunks of powers of two.  For
	 each block, there is an overhead of 8 bytes if rcheck is not
	 defined, 20 bytes if it is defined.  In other words, a
	 one-byte allocation needs 8 bytes of overhead for a total of
	 9 bytes, and needs to have 16 bytes of memory chunked out for
	 it.

   2. When using the new allocator (gmalloc.c):

      -- blocks are always allocated in chunks of powers of two up
         to 4096 bytes.  Larger blocks are allocated in chunks of
	 an integral multiple of 4096 bytes.  The minimum block
         size is 2*sizeof (void *), or 16 bytes if SUNOS_LOCALTIME_BUG
	 is defined.  There is no per-block overhead, but there
	 is an overhead of 3*sizeof (size_t) for each 4096 bytes
	 allocated.

    3. When using the system malloc, anything goes, but they are
       generally slower and more space-efficient than the GNU
       allocators.  One possibly reasonable assumption to make
       for want of better data is that sizeof (void *), or maybe
       2 * sizeof (void *), is required as overhead and that
       blocks are allocated in the minimum required size except
       that some minimum block size is imposed (e.g. 16 bytes). */

int
malloced_storage_size (void *ptr, int claimed_size,
		       struct overhead_stats *stats)
{
  int orig_claimed_size = claimed_size;

#ifdef GNU_MALLOC

  if (claimed_size < 2 * sizeof (void *))
    claimed_size = 2 * sizeof (void *);
# ifdef SUNOS_LOCALTIME_BUG
  if (claimed_size < 16)
    claimed_size = 16;
# endif
  if (claimed_size < 4096)
    {
      int log = 1;

      /* compute the log base two, more or less, then use it to compute
	 the block size needed. */
      claimed_size--;
      /* It's big, it's heavy, it's wood! */
      while ((claimed_size /= 2) != 0)
	++log;
      claimed_size = 1;
      /* It's better than bad, it's good! */
      while (log > 0)
        {
	  claimed_size *= 2;
          log--;
        }
      /* We have to come up with some average about the amount of
	 blocks used. */
      if ((rand () & 4095) < claimed_size)
	claimed_size += 3 * sizeof (void *);
    }
  else
    {
      claimed_size += 4095;
      claimed_size &= ~4095;
      claimed_size += (claimed_size / 4096) * 3 * sizeof (size_t);
    }

#elif defined (SYSTEM_MALLOC)

  if (claimed_size < 16)
    claimed_size = 16;
  claimed_size += 2 * sizeof (void *);

#else /* old GNU allocator */

# ifdef rcheck /* #### may not be defined here */
  claimed_size += 20;
# else
  claimed_size += 8;
# endif
  {
    int log = 1;

    /* compute the log base two, more or less, then use it to compute
       the block size needed. */
    claimed_size--;
    /* It's big, it's heavy, it's wood! */
    while ((claimed_size /= 2) != 0)
      ++log;
    claimed_size = 1;
    /* It's better than bad, it's good! */
    while (log > 0)
      {
	claimed_size *= 2;
        log--;
      }
  }

#endif /* old GNU allocator */

  if (stats)
    {
      stats->was_requested += orig_claimed_size;
      stats->malloc_overhead += claimed_size - orig_claimed_size;
    }
  return claimed_size;
}

int
fixed_type_block_overhead (int size)
{
  int per_block = TYPE_ALLOC_SIZE (cons, unsigned char);
  int overhead = 0;
  int storage_size = malloced_storage_size (0, per_block, 0);
  while (size >= per_block)
    {
      size -= per_block;
      overhead += sizeof (void *) + per_block - storage_size;

    }
  if (rand () % per_block < size)
    overhead += sizeof (void *) + per_block - storage_size;
  return overhead;
}

#endif /* MEMORY_USAGE_STATS */


/* Initialization */
void
init_alloc_once_early (void)
{
  int iii;

#ifdef PURESTAT
  for (iii = 0; iii < countof (purestats); iii++)
    {
      if (! purestats[iii]) continue;
      purestats[iii]->nobjects = 0;
      purestats[iii]->nbytes = 0;
    }
  purecopying_for_bytecode = 0;
#endif /* PURESTAT */

  last_lrecord_type_index_assigned = -1;
  for (iii = 0; iii < countof (lrecord_implementations_table); iii++)
    {
      lrecord_implementations_table[iii] = 0;
    }

#ifdef USE_INDEXED_LRECORD_IMPLEMENTATION
  /*
   * If USE_INDEXED_LRECORD_IMPLEMENTATION is defined, all the staticly
   * defined subr lrecords were initialized with lheader->type == 0.
   * See subr_lheader_initializer in lisp.h.  Force type index 0 to be
   * assigned to lrecord_subr so that those predefined indexes match
   * reality.
   */
  (void) lrecord_type_index (lrecord_subr);
  assert (*(lrecord_subr[0].lrecord_type_index) == 0);
  /*
   * The same is true for symbol_value_forward objects, except the
   * type is 1.
   */
  (void) lrecord_type_index (lrecord_symbol_value_forward);
  assert (*(lrecord_symbol_value_forward[0].lrecord_type_index) == 1);
#endif

  symbols_initialized = 0;

  gc_generation_number[0] = 0;
  /* purify_flag 1 is correct even if CANNOT_DUMP.
   * loadup.el will set to nil at end. */
  purify_flag = 1;
  pureptr = 0;
  pure_lossage = 0;
  breathing_space = 0;
#ifndef LRECORD_VECTOR
  XSETINT (all_vectors, 0); /* Qzero may not be set yet. */
#endif
  XSETINT (all_bit_vectors, 0); /* Qzero may not be set yet. */
  XSETINT (Vgc_message, 0);
  all_lcrecords = 0;
  ignore_malloc_warnings = 1;
  init_string_alloc ();
  init_string_chars_alloc ();
  init_cons_alloc ();
  init_symbol_alloc ();
  init_compiled_function_alloc ();
#ifdef LISP_FLOAT_TYPE
  init_float_alloc ();
#endif /* LISP_FLOAT_TYPE */
#ifndef standalone
  init_marker_alloc ();
  init_extent_alloc ();
  init_event_alloc ();
#endif
  ignore_malloc_warnings = 0;
  staticidx = 0;
  consing_since_gc = 0;
#if 1
  gc_cons_threshold = 500000; /* XEmacs change */
#else
  gc_cons_threshold = 15000; /* debugging */
#endif
#ifdef VIRT_ADDR_VARIES
  malloc_sbrk_unused = 1<<22;	/* A large number */
  malloc_sbrk_used = 100000;	/* as reasonable as any number */
#endif /* VIRT_ADDR_VARIES */
  lrecord_uid_counter = 259;
  debug_string_purity = 0;
  gcprolist = 0;

  gc_currently_forbidden = 0;
  gc_hooks_inhibited = 0;

#ifdef ERROR_CHECK_TYPECHECK
  ERROR_ME.really_unlikely_name_to_have_accidentally_in_a_non_errb_structure =
    666;
  ERROR_ME_NOT.
    really_unlikely_name_to_have_accidentally_in_a_non_errb_structure = 42;
  ERROR_ME_WARN.
    really_unlikely_name_to_have_accidentally_in_a_non_errb_structure =
      3333632;
#endif /* ERROR_CHECK_TYPECHECK */
}

void
reinit_alloc (void)
{
  gcprolist = 0;
}

void
syms_of_alloc (void)
{
  defsymbol (&Qpre_gc_hook, "pre-gc-hook");
  defsymbol (&Qpost_gc_hook, "post-gc-hook");
  defsymbol (&Qgarbage_collecting, "garbage-collecting");

  DEFSUBR (Fcons);
  DEFSUBR (Flist);
  DEFSUBR (Fvector);
  DEFSUBR (Fbit_vector);
  DEFSUBR (Fmake_byte_code);
  DEFSUBR (Fmake_list);
  DEFSUBR (Fmake_vector);
  DEFSUBR (Fmake_bit_vector);
  DEFSUBR (Fmake_string);
  DEFSUBR (Fmake_symbol);
  DEFSUBR (Fmake_marker);
  DEFSUBR (Fpurecopy);
  DEFSUBR (Fgarbage_collect);
  DEFSUBR (Fmemory_limit);
  DEFSUBR (Fconsing_since_gc);
}

void
vars_of_alloc (void)
{
  DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold /*
*Number of bytes of consing between garbage collections.
\"Consing\" is a misnomer in that this actually counts allocation
of all different kinds of objects, not just conses.
Garbage collection can happen automatically once this many bytes have been
allocated since the last garbage collection.  All data types count.

Garbage collection happens automatically when `eval' or `funcall' are
called.  (Note that `funcall' is called implicitly as part of evaluation.)
By binding this temporarily to a large number, you can effectively
prevent garbage collection during a part of the program.

See also `consing-since-gc'.
*/ );

  DEFVAR_INT ("pure-bytes-used", &pureptr /*
Number of bytes of sharable Lisp data allocated so far.
*/ );

#if 0
  DEFVAR_INT ("data-bytes-used", &malloc_sbrk_used /*
Number of bytes of unshared memory allocated in this session.
*/ );

  DEFVAR_INT ("data-bytes-free", &malloc_sbrk_unused /*
Number of bytes of unshared memory remaining available in this session.
*/ );
#endif

#ifdef DEBUG_XEMACS
  DEFVAR_INT ("debug-allocation", &debug_allocation /*
If non-zero, print out information to stderr about all objects allocated.
See also `debug-allocation-backtrace-length'.
*/ );
  debug_allocation = 0;

  DEFVAR_INT ("debug-allocation-backtrace-length",
	      &debug_allocation_backtrace_length /*
Length (in stack frames) of short backtrace printed out by `debug-allocation'.
*/ );
  debug_allocation_backtrace_length = 2;
#endif

  DEFVAR_BOOL ("purify-flag", &purify_flag /*
Non-nil means loading Lisp code in order to dump an executable.
This means that certain objects should be allocated in shared (pure) space.
*/ );

  DEFVAR_LISP ("pre-gc-hook", &Vpre_gc_hook /*
Function or functions to be run just before each garbage collection.
Interrupts, garbage collection, and errors are inhibited while this hook
runs, so be extremely careful in what you add here.  In particular, avoid
consing, and do not interact with the user.
*/ );
  Vpre_gc_hook = Qnil;

  DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook /*
Function or functions to be run just after each garbage collection.
Interrupts, garbage collection, and errors are inhibited while this hook
runs, so be extremely careful in what you add here.  In particular, avoid
consing, and do not interact with the user.
*/ );
  Vpost_gc_hook = Qnil;

  DEFVAR_LISP ("gc-message", &Vgc_message /*
String to print to indicate that a garbage collection is in progress.
This is printed in the echo area.  If the selected frame is on a
window system and `gc-pointer-glyph' specifies a value (i.e. a pointer
image instance) in the domain of the selected frame, the mouse pointer
will change instead of this message being printed.
*/ );
  Vgc_message = make_pure_string ((CONST Bufbyte *) gc_default_message,
				  countof (gc_default_message) - 1,
				  Qnil, 1);

  DEFVAR_LISP ("gc-pointer-glyph", &Vgc_pointer_glyph /*
Pointer glyph used to indicate that a garbage collection is in progress.
If the selected window is on a window system and this glyph specifies a
value (i.e. a pointer image instance) in the domain of the selected
window, the pointer will be changed as specified during garbage collection.
Otherwise, a message will be printed in the echo area, as controlled
by `gc-message'.
*/ );
}

void
complex_vars_of_alloc (void)
{
  Vgc_pointer_glyph = Fmake_glyph_internal (Qpointer);
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.