summaryrefslogtreecommitdiff
path: root/erts/emulator/beam/external.c
blob: 6981e14fa882167ebddfec1db7668dfbe9f0d125 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
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
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
/*
 * %CopyrightBegin%
 *
 * Copyright Ericsson AB 1996-2020. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * %CopyrightEnd%
 */

/*  Implementation of the erlang external format 
 *
 *  And a nice cache mechanism which is used just to send a
 *  index indicating a specific atom to a remote node instead of the
 *  entire atom.
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#define ERTS_WANT_EXTERNAL_TAGS

#include "sys.h"
#include "erl_vm.h"
#include "global.h"
#include "erl_process.h"
#include "error.h"
#include "external.h"
#define ERL_WANT_HIPE_BIF_WRAPPER__
#include "bif.h"
#undef ERL_WANT_HIPE_BIF_WRAPPER__
#include "big.h"
#include "dist.h"
#include "erl_binary.h"
#include "erl_bits.h"
#include "erl_zlib.h"
#include "erl_map.h"
#include "erl_proc_sig_queue.h"
#include "erl_trace.h"

#define PASS_THROUGH 'p'

#define in_area(ptr,start,nbytes) ((UWord)((char*)(ptr) - (char*)(start)) < (nbytes))

#define MAX_STRING_LEN 0xffff

/*
 * MAX value for the creation field in pid, port and reference
 * for the old PID_EXT, PORT_EXT, REFERENCE_EXT and NEW_REFERENCE_EXT.
 * Older nodes (OTP 19-22) will send us these so we must be able to decode them.
 *
 * From OTP 23 DFLAG_BIG_CREATION is mandatory so this node will always
 * encode with new big 32-bit creations using NEW_PID_EXT, NEW_PORT_EXT
 * and NEWER_REFERENCE_EXT.
*/
#define ERTS_MAX_TINY_CREATION (3)
#define is_tiny_creation(Cre) ((unsigned)(Cre) <= ERTS_MAX_TINY_CREATION)

/*
 *   When 0 is used as creation, the real creation
 *   is unknown. Creation 0 on data will be changed to current
 *   creation of the node which it belongs to when it enters
 *   that node.
 *       This typically happens when a remote pid is created with
 *   list_to_pid/1 and then sent to the remote node. This behavior
 *   has the undesirable effect that a pid can be passed between nodes,
 *   and as a result of that not being equal to itself (the pid that
 *   comes back isn't equal to the original pid).
 *
 */

#undef ERTS_DEBUG_USE_DIST_SEP
#ifdef DEBUG
#  if 0
/*
 * Enabling ERTS_DEBUG_USE_DIST_SEP can be useful when debugging, but the
 * result refuses to talk to nodes without it!
 */
#    define ERTS_DEBUG_USE_DIST_SEP
#  endif
#  define IF_DEBUG(X) X
#else
#  define IF_DEBUG(X)
#endif

/* Does Sint fit in Sint32?
 */
#define IS_SSMALL32(x) (((Uint) (((x) >> (32-1)) + 1)) < 2)

static Export term_to_binary_trap_export;

static byte* enc_term(ErtsAtomCacheMap *, Eterm, byte*, Uint64, struct erl_off_heap_header** off_heap);
struct TTBEncodeContext_;
static int enc_term_int(struct TTBEncodeContext_*,ErtsAtomCacheMap *acmp, Eterm obj, byte* ep, Uint64 dflags,
			struct erl_off_heap_header** off_heap, Sint *reds, byte **res);
static int is_external_string(Eterm obj, Uint* lenp);
static byte* enc_atom(ErtsAtomCacheMap *, Eterm, byte*, Uint64);
static byte* enc_pid(ErtsAtomCacheMap *, Eterm, byte*, Uint64);
struct B2TContext_t;
static byte* dec_term(ErtsDistExternal*, ErtsHeapFactory*, byte*, Eterm*, struct B2TContext_t*, int);
static byte* dec_atom(ErtsDistExternal *, byte*, Eterm*);
static byte* dec_pid(ErtsDistExternal *, ErtsHeapFactory*, byte*, Eterm*, byte tag);
static Sint decoded_size(byte *ep, byte* endp, int internal_tags, struct B2TContext_t*);
static BIF_RETTYPE term_to_binary_trap_1(BIF_ALIST_1);

static Eterm erts_term_to_binary_int(Process* p, Sint bif_ix, Eterm Term, Eterm opts, int level,
                                     Uint64 dflags, Binary *context_b, int iovec,
                                     Uint fragment_size);

static Uint encode_size_struct2(ErtsAtomCacheMap *, Eterm, Uint64);
static ErtsExtSzRes encode_size_struct_int(TTBSizeContext*, ErtsAtomCacheMap *acmp,
                                           Eterm obj, Uint64 dflags, Sint *reds, Uint *res);

static Export binary_to_term_trap_export;
static BIF_RETTYPE binary_to_term_trap_1(BIF_ALIST_1);
static Sint transcode_dist_obuf(ErtsDistOutputBuf*, DistEntry*, Uint64 dflags, Sint reds);
static byte *hopefull_bit_binary(TTBEncodeContext* ctx, byte **epp, Binary *pb_val, Eterm pb_term,
                                 byte *bytes, byte bitoffs, byte bitsize, Uint sz);
static void hopefull_export(TTBEncodeContext* ctx, byte **epp, Export* exp, Uint32 dflags,
                            struct erl_off_heap_header** off_heap);
static void store_in_vec(TTBEncodeContext *ctx, byte *ep, Binary *ohbin, Eterm ohpb,
                         byte *ohp, Uint ohsz);

void erts_init_external(void) {
    erts_init_trap_export(&term_to_binary_trap_export,
			  am_erts_internal, am_term_to_binary_trap, 1,
			  &term_to_binary_trap_1);

    erts_init_trap_export(&binary_to_term_trap_export,
			  am_erts_internal, am_binary_to_term_trap, 1,
			  &binary_to_term_trap_1);
    return;
}

#define ERTS_MAX_INTERNAL_ATOM_CACHE_ENTRIES 255

#define ERTS_DIST_HDR_ATOM_CACHE_FLAG_BYTE_IX(IIX) \
  (((((Uint32) (IIX)) >> 1) & 0x7fffffff))
#define ERTS_DIST_HDR_ATOM_CACHE_FLAG_BIT_IX(IIX) \
  (((IIX) << 2) & 7)
#define ERTS_DIST_HDR_ATOM_CACHE_FLAG_BYTES(NO_ATOMS) \
  (((((Uint32) (NO_ATOMS)) >> 1) & 0x7fffffff)+1)

#define ERTS_DIST_HDR_LONG_ATOMS_FLG (1 << 0)

/* #define ERTS_ATOM_CACHE_HASH */
#define ERTS_USE_ATOM_CACHE_SIZE 2039
#if ERTS_ATOM_CACHE_SIZE < ERTS_USE_ATOM_CACHE_SIZE
#error "ERTS_USE_ATOM_CACHE_SIZE too large"
#endif

static ERTS_INLINE int
atom2cix(Eterm atom)
{
    Uint val;
    ASSERT(is_atom(atom));
    val = atom_val(atom);
#ifdef ERTS_ATOM_CACHE_HASH
    val = atom_tab(val)->slot.bucket.hvalue;
#endif
#if ERTS_USE_ATOM_CACHE_SIZE == 256
    return (int) (val & ((Uint) 0xff));
#else
    return (int) (val % ERTS_USE_ATOM_CACHE_SIZE);
#endif
}

int erts_debug_max_atom_out_cache_index(void)
{
    return ERTS_USE_ATOM_CACHE_SIZE-1;
}

int
erts_debug_atom_to_out_cache_index(Eterm atom)
{
    return atom2cix(atom);
}

void
erts_init_atom_cache_map(ErtsAtomCacheMap *acmp)
{
    if (acmp) {
	int ix;
	acmp->long_atoms = 0;
	for (ix = 0; ix < ERTS_ATOM_CACHE_SIZE; ix++)
	    acmp->cache[ix].iix = -1;
	acmp->sz = 0;
	acmp->hdr_sz = -1;
    }
}

void
erts_reset_atom_cache_map(ErtsAtomCacheMap *acmp)
{
    if (acmp) {
	int i;
	acmp->long_atoms = 0;
	for (i = 0; i < acmp->sz; i++) {
	    ASSERT(0 <= acmp->cix[i] && acmp->cix[i] < ERTS_ATOM_CACHE_SIZE);
	    acmp->cache[acmp->cix[i]].iix = -1;
	}
	acmp->sz = 0;
	acmp->hdr_sz = -1;
#ifdef DEBUG
	for (i = 0; i < ERTS_ATOM_CACHE_SIZE; i++) {
	    ASSERT(acmp->cache[i].iix < 0);
	}
#endif
    }
}

void
erts_destroy_atom_cache_map(ErtsAtomCacheMap *acmp)
{

}

static ERTS_INLINE void
insert_acache_map(ErtsAtomCacheMap *acmp, Eterm atom, Uint64 dflags)
{
    if (acmp && acmp->sz < ERTS_MAX_INTERNAL_ATOM_CACHE_ENTRIES) {
	int ix;
	ASSERT(acmp->hdr_sz < 0);
        ASSERT(dflags & DFLAG_UTF8_ATOMS);
	ix = atom2cix(atom);
	if (acmp->cache[ix].iix < 0) {
	    acmp->cache[ix].iix = acmp->sz;
	    acmp->cix[acmp->sz++] = ix;
	    acmp->cache[ix].atom = atom;
	}
    }
}

static ERTS_INLINE int
get_iix_acache_map(ErtsAtomCacheMap *acmp, Eterm atom, Uint64 dflags)
{
    if (!acmp)
	return -1;
    else {
	int ix;
	ASSERT(is_atom(atom));
	ix = atom2cix(atom);
	if (acmp->cache[ix].iix < 0) {
	    ASSERT(acmp->sz == ERTS_MAX_INTERNAL_ATOM_CACHE_ENTRIES);
	    return -1;
	}
	else {
	    ASSERT(acmp->cache[ix].iix < ERTS_ATOM_CACHE_SIZE);
	    return acmp->cache[ix].atom == atom ? acmp->cache[ix].iix : -1;
	}
    }
}

void
erts_finalize_atom_cache_map(ErtsAtomCacheMap *acmp, Uint64 dflags)
{
    if (acmp) {
	int long_atoms = 0; /* !0 if one or more atoms are longer than 255. */
	int i;
	int sz = 0;
	int min_sz;
        ASSERT(dflags & DFLAG_UTF8_ATOMS);
	ASSERT(acmp->hdr_sz < 0);
	/* Make sure cache update instructions fit */
	min_sz = (2+4)*acmp->sz;
	for (i = 0; i < acmp->sz; i++) {
	    Atom *a;
	    Eterm atom;
	    int len;
	    atom = acmp->cache[acmp->cix[i]].atom;
	    ASSERT(is_atom(atom));
	    a = atom_tab(atom_val(atom));
	    len = (int) a->len;
	    ASSERT(len >= 0);
	    if (!long_atoms && len > 255)
		long_atoms = 1;
	    /* Enough for a new atom cache value */
	    sz += 1 /* cix */ + 1 /* length */ + len /* text */;
	}
	if (long_atoms) {
	    acmp->long_atoms = 1;
	    sz += acmp->sz; /* we need 2 bytes per atom for length */
	}
	/* Dynamically sized flag field */
	sz += ERTS_DIST_HDR_ATOM_CACHE_FLAG_BYTES(acmp->sz);
	if (sz < min_sz)
	    sz = min_sz;
	acmp->hdr_sz = sz;
    }
}

Uint
erts_encode_ext_dist_header_size(TTBEncodeContext *ctx,
                                 ErtsAtomCacheMap *acmp,
                                 Uint fragments)
{
    if (ctx->dflags & DFLAG_PENDING_CONNECT) {
        /* HOPEFUL_DATA + hopefull flags + hopefull ix + payload ix */
        return 1 + 8 + 4 + 4;
    }
    else if (!acmp && !(ctx->dflags & DFLAG_FRAGMENTS))
	return 1; /* pass through */
    else {
        int fix_sz
            = 1 /* VERSION_MAGIC */
            + 1 /* DIST_HEADER */
            + 1 /* dist header flags */
            + 1 /* number of internal cache entries */
            ;

        if (fragments > 1)
            fix_sz += 8 /* sequence id */
                + 8 /* number of fragments */
                ;
        if (acmp) {
            ASSERT(acmp->hdr_sz >= 0);
            fix_sz += acmp->hdr_sz;
        } else {
            ASSERT(ctx->dflags & DFLAG_FRAGMENTS);
        }

        return fix_sz;
    }
}

byte *erts_encode_ext_dist_header_setup(TTBEncodeContext *ctx,
                                        byte *ctl_ext, ErtsAtomCacheMap *acmp,
                                        Uint fragments, Eterm from)
{
    /* Maximum number of atom must be less than the maximum of a 32 bits
       unsigned integer. Check is done in erl_init.c, erl_start function. */
    if (ctx->dflags & DFLAG_PENDING_CONNECT) {
        byte *ep = ctl_ext;
        ep -= 4;
        ctx->payload_ixp = ep;
        put_int32(0, ep);
        ep -= 4;
        ctx->hopefull_ixp = ep;
        put_int32(ERTS_NO_HIX, ep);
        ep -= 8;
        ctx->hopefull_flagsp = ep;
        put_int64(0, ep);
        *--ep = HOPEFUL_DATA;
        return ep;
    }
    else if (!acmp && !(ctx->dflags & DFLAG_FRAGMENTS)) {
        byte *ep = ctl_ext;
        *--ep = PASS_THROUGH;
	return ep;
    }
    else {
	int i;
	byte *ep = ctl_ext;
	byte dist_hdr_flags = acmp && acmp->long_atoms ? ERTS_DIST_HDR_LONG_ATOMS_FLG : 0;
	ASSERT(!acmp || acmp->hdr_sz >= 0);

        if (acmp) {
            /*
             * Write cache update instructions. Note that this is a purely
             * internal format, never seen on the wire. This section is later
             * rewritten by erts_encode_ext_dist_header_finalize() while updating
             * the cache. We write the header backwards just before the
             * actual term(s).
             */
            for (i = acmp->sz-1; i >= 0; i--) {
                Uint32 aval;
                ASSERT(0 <= acmp->cix[i] && acmp->cix[i] < ERTS_ATOM_CACHE_SIZE);
                ASSERT(i == acmp->cache[acmp->cix[i]].iix);
                ASSERT(is_atom(acmp->cache[acmp->cix[i]].atom));

                aval = (Uint32) atom_val(acmp->cache[acmp->cix[i]].atom);
                ep -= 4;
                put_int32(aval, ep);
                ep -= 2;
                put_int16(acmp->cix[i], ep);
            }
            --ep;
            put_int8(acmp->sz, ep);
        } else {
            ASSERT(ctx->dflags & DFLAG_FRAGMENTS);
            /* If we don't have an atom cache but are using a dist header we just put 0
               in the atom cache size slot */
            --ep;
            put_int8(0, ep);
        }
	--ep;
	put_int8(dist_hdr_flags, ep);
        if (fragments > 1) {
            ASSERT(is_pid(from));
            ep -= 8;
            put_int64(fragments, ep);
            ep -= 8;
            put_int64(from, ep);
            *--ep = DIST_FRAG_HEADER;
        } else {
            *--ep = DIST_HEADER;
        }
        *--ep = VERSION_MAGIC;
	return ep;
    }
}

byte *erts_encode_ext_dist_header_fragment(byte **hdrpp,
                                           Uint fragment,
                                           Eterm from)
{
    byte *ep = *hdrpp, *start = ep;
    ASSERT(is_pid(from));
    *ep++ = VERSION_MAGIC;
    *ep++ = DIST_FRAG_CONT;
    put_int64(from, ep);
    ep += 8;
    put_int64(fragment, ep);
    ep += 8;
    *hdrpp = ep;
    return start;
}


Sint erts_encode_ext_dist_header_finalize(ErtsDistOutputBuf* ob,
                                          DistEntry* dep,
                                          Uint64 dflags,
                                          Sint reds)
{
    byte *ip;
    byte instr_buf[(2+4)*ERTS_ATOM_CACHE_SIZE];
    int ci, sz;
    byte dist_hdr_flags;
    int long_atoms;
    Uint64 seq_id = 0, frag_id = 0;
    register byte *ep = ob->eiov->iov[1].iov_base;
    ASSERT(dflags & DFLAG_UTF8_ATOMS);

    /*
     * The buffer can have different layouts at this point depending on
     * what was known when encoded:
     *
     * Pending connection: HOPEFUL_DATA, HFlgs, HIX, PIX, CtrlTerm [, MsgTerm]
     * With atom cache   : VERSION_MAGIC, DIST_HEADER, ..., CtrlTerm [, MsgTerm]
     * No atom cache     : VERSION_MAGIC, CtrlTerm [, VERSION_MAGIC, MsgTerm]
     */

    if (ep[0] == HOPEFUL_DATA)
        return transcode_dist_obuf(ob, dep, dflags, reds);

    if (ep[0] == PASS_THROUGH) {
        ASSERT(!(dflags & (DFLAG_DIST_HDR_ATOM_CACHE|DFLAG_FRAGMENTS)));
        ASSERT(ob->eiov->iov[1].iov_len == 1);
        return reds;
    }

    if (ep[1] == DIST_FRAG_CONT) {
        ASSERT(ep[0] == VERSION_MAGIC);
        ASSERT(ob->eiov->iov[1].iov_len == 18);
        return reds;
    }

    if (ep[1] == DIST_FRAG_HEADER) {
        /* skip the seq id and frag id */
        seq_id = get_int64(&ep[2]);
        ep += 8;
        frag_id = get_int64(&ep[2]);
        ep += 8;
    }

    dist_hdr_flags = ep[2];
    long_atoms = ERTS_DIST_HDR_LONG_ATOMS_FLG & ((int) dist_hdr_flags);

    /*
     * Update output atom cache and write the external version of
     * the dist header. We write the header backwards just
     * before the actual term(s).
     */
    ep += 3;
    ci = (int) get_int8(ep);
    ASSERT(0 <= ci && ci < ERTS_ATOM_CACHE_SIZE);
    ep += 1;
    sz = (2+4)*ci;
    ip = &instr_buf[0];
    sys_memcpy((void *) ip, (void *) ep, sz);
    ep += sz;
    ASSERT(ep == (byte *) (ob->eiov->iov[1].iov_base + ob->eiov->iov[1].iov_len));
    if (ci > 0) {
	Uint32 flgs_buf[((ERTS_DIST_HDR_ATOM_CACHE_FLAG_BYTES(
			      ERTS_MAX_INTERNAL_ATOM_CACHE_ENTRIES)-1)
			 / sizeof(Uint32))+1];
	register Uint32 flgs;
	int iix, flgs_bytes, flgs_buf_ix, used_half_bytes;
        ErtsAtomCache* cache = dep->cache;
#ifdef DEBUG
	int tot_used_half_bytes;
#endif

	flgs_bytes = ERTS_DIST_HDR_ATOM_CACHE_FLAG_BYTES(ci);

	ASSERT(flgs_bytes <= sizeof(flgs_buf));
	flgs = (Uint32) dist_hdr_flags;
	flgs_buf_ix = 0;
	if ((ci & 1) == 0)
	    used_half_bytes = 2;
	else
	    used_half_bytes = 1;
#ifdef DEBUG
	tot_used_half_bytes = used_half_bytes;
#endif
	iix = ci-1;
	while (iix >= 0) {
	    int cix;
	    Eterm atom;

	    if (used_half_bytes != 8)
		flgs <<= 4;
	    else {
		flgs_buf[flgs_buf_ix++] = flgs;
		flgs = 0;
		used_half_bytes = 0;
	    }

	    ip = &instr_buf[0] + (2+4)*iix;
	    cix = (int) get_int16(&ip[0]);
	    ASSERT(0 <= cix && cix < ERTS_ATOM_CACHE_SIZE);
	    atom = make_atom((Uint) get_int32(&ip[2]));
	    if (cache->out_arr[cix] == atom) {
		--ep;
		put_int8(cix, ep);
		flgs |= ((cix >> 8) & 7);
	    }
	    else {
		Atom *a;
		cache->out_arr[cix] = atom;
		a = atom_tab(atom_val(atom));
                sz = a->len;
                ep -= sz;
                sys_memcpy((void *) ep, (void *) a->name, sz);
		if (long_atoms) {
		    ep -= 2;
		    put_int16(sz, ep);
		}
		else {
		    ASSERT(0 <= sz && sz <= 255);
		    --ep;
		    put_int8(sz, ep);
		}
		--ep;
		put_int8(cix, ep);
		flgs |= (8 | ((cix >> 8) & 7));
	    }
	    iix--;
	    used_half_bytes++;
#ifdef DEBUG
	    tot_used_half_bytes++;
#endif
	}
	ASSERT(tot_used_half_bytes == 2*flgs_bytes);
	flgs_buf[flgs_buf_ix] = flgs;
	flgs_buf_ix = 0;
	while (1) {
	    flgs = flgs_buf[flgs_buf_ix];
	    if (flgs_bytes > 4) {
		*--ep = (byte) ((flgs >> 24) & 0xff);
		*--ep = (byte) ((flgs >> 16) & 0xff);
		*--ep = (byte) ((flgs >> 8) & 0xff);
		*--ep = (byte) (flgs & 0xff);
		flgs_buf_ix++;
		flgs_bytes -= 4;
	    }
	    else {
		switch (flgs_bytes) {
		case 4:
		    *--ep = (byte) ((flgs >> 24) & 0xff);
		case 3:
		    *--ep = (byte) ((flgs >> 16) & 0xff);
		case 2:
		    *--ep = (byte) ((flgs >> 8) & 0xff);
		case 1:
		    *--ep = (byte) (flgs & 0xff);
		}
		break;
	    }
	}
        reds -= 3; /*was ERTS_PORT_REDS_DIST_CMD_FINALIZE*/
    }
    --ep;
    put_int8(ci, ep);
    if (seq_id) {
        ep -= 8;
        put_int64(frag_id, ep);
        ep -= 8;
        put_int64(seq_id, ep);
        *--ep = DIST_FRAG_HEADER;
    } else {
        *--ep = DIST_HEADER;
    }
    *--ep = VERSION_MAGIC;

    sz = ((byte *) ob->eiov->iov[1].iov_base) - ep;
    ob->eiov->size += sz;
    ob->eiov->iov[1].iov_len += sz;
    ob->eiov->iov[1].iov_base = ep;

    return reds < 0 ? 0 : reds;
}

ErtsExtSzRes
erts_encode_dist_ext_size(Eterm term,
                          ErtsAtomCacheMap *acmp,
                          TTBSizeContext* ctx,
                          Uint* szp, Sint *redsp,
                          Sint *vlenp, Uint *fragmentsp)
{
    Uint sz;
    ErtsExtSzRes res;

    ASSERT(ctx);
    ASSERT(szp);
    ASSERT(vlenp);
    ASSERT(fragmentsp);

    sz = *szp;

    if (!ctx->wstack.wstart) {
        /*
         * First call for this 'term'. We might however encode
         * multiple terms and this might not be the first term
         * in the sequence. 'ctx' should contain valid info about
         * about previous terms regarding fragments, and vlen.
         * 'szp' should contain valid info about the total size
         * of previous terms.
         */
        if (ctx->vlen < 0) {
            /* First term as well */
            ctx->vlen = 0;
            if (ctx->dflags & DFLAG_FRAGMENTS)
                ctx->fragment_size = ERTS_DIST_FRAGMENT_SIZE;
        }

#ifndef ERTS_DEBUG_USE_DIST_SEP
	if (!(ctx->dflags & (DFLAG_DIST_HDR_ATOM_CACHE|DFLAG_FRAGMENTS)))
#endif
	    sz++ /* VERSION_MAGIC */;

    }

    res = encode_size_struct_int(ctx, acmp, term, ctx->dflags, redsp, &sz);

    if (res == ERTS_EXT_SZ_OK) {
        Uint total_size, fragments;

        /*
         * Each fragment use
         * - one element for driver header
         * - one element for fragment header
         * - and (at least) one for data
         */
        total_size = sz + ctx->extra_size;
        fragments = (total_size - 1)/ctx->fragment_size + 1;

	*szp = sz;
        *fragmentsp = fragments;
        *vlenp = ctx->vlen + 3*fragments;
    }

    return res;
}

ErtsExtSzRes erts_encode_ext_size_2(Eterm term, unsigned dflags, Uint *szp)
{
    ErtsExtSzRes res;
    *szp = 0;
    res = encode_size_struct_int(NULL, NULL, term, dflags, NULL, szp);
    (*szp)++ /* VERSION_MAGIC */;
    return res;
}

ErtsExtSzRes erts_encode_ext_size(Eterm term, Uint *szp)
{
    return erts_encode_ext_size_2(term, TERM_TO_BINARY_DFLAGS, szp);
}

Uint erts_encode_ext_size_ets(Eterm term)
{
    return encode_size_struct2(NULL, term,
                               TERM_TO_BINARY_DFLAGS|DFLAG_ETS_COMPRESSED);
}


int erts_encode_dist_ext(Eterm term, byte **ext, Uint64 flags, ErtsAtomCacheMap *acmp,
                         TTBEncodeContext* ctx, Uint *fragmentsp, Sint* reds)
{
    int res;
    ASSERT(ctx);
    
    if (!ctx->wstack.wstart) {
        ctx->cptr = *ext;
#ifndef ERTS_DEBUG_USE_DIST_SEP
	if (!(flags & (DFLAG_DIST_HDR_ATOM_CACHE|DFLAG_PENDING_CONNECT|DFLAG_FRAGMENTS)))
#endif
	    *(*ext)++ = VERSION_MAGIC;
#ifndef ERTS_DEBUG_USE_DIST_SEP
        if (flags & DFLAG_PENDING_CONNECT) {
            Sint payload_ix = ctx->vlen;
            ASSERT(ctx->payload_ixp);
            if (payload_ix) {
                /* we potentially need a version magic on the payload... */
                (*ext)++;
                ctx->cptr = *ext;
                put_int32(payload_ix, ctx->payload_ixp);
            }
        }
#endif
    }
    res = enc_term_int(ctx, acmp, term, *ext, flags, NULL, reds, ext);
    if (fragmentsp)
        *fragmentsp = res == 0 ? ctx->frag_ix + 1 : ctx->frag_ix;
    if (flags & DFLAG_PENDING_CONNECT) {
        ASSERT(ctx->hopefull_flagsp);
        put_int64(ctx->hopefull_flags, ctx->hopefull_flagsp);
    }
    return res;
}

void erts_encode_ext(Eterm term, byte **ext)
{
    byte *ep = *ext;
    *ep++ = VERSION_MAGIC;
    ep = enc_term(NULL, term, ep, TERM_TO_BINARY_DFLAGS, NULL);
    if (!ep)
	erts_exit(ERTS_ABORT_EXIT,
		 "%s:%d:erts_encode_ext(): Internal data structure error\n",
		 __FILE__, __LINE__);
    *ext = ep;
}

byte* erts_encode_ext_ets(Eterm term, byte *ep, struct erl_off_heap_header** off_heap)
{
    return enc_term(NULL, term, ep, TERM_TO_BINARY_DFLAGS|DFLAG_ETS_COMPRESSED,
		    off_heap);
}


static Uint
dist_ext_size(ErtsDistExternal *edep)
{
    Uint sz = sizeof(ErtsDistExternal);

    ASSERT(edep->data->ext_endp && edep->data->extp);
    ASSERT(edep->data->ext_endp >= edep->data->extp);

    if (edep->flags & ERTS_DIST_EXT_ATOM_TRANS_TAB) {
        ASSERT(0 <= edep->attab.size \
               && edep->attab.size <= ERTS_ATOM_CACHE_SIZE);
        sz -= sizeof(Eterm)*(ERTS_ATOM_CACHE_SIZE - edep->attab.size);
    } else {
        sz -= sizeof(ErtsAtomTranslationTable);
    }
    ASSERT(sz % 4 == 0);
    return sz;
}

Uint
erts_dist_ext_size(ErtsDistExternal *edep)
{
    Uint sz = dist_ext_size(edep);
    sz += 4;  /* may need to pad to 8-byte-align ErtsDistExternalData */
    sz += edep->data[0].frag_id * sizeof(ErtsDistExternalData);
    return sz;
}

Uint
erts_dist_ext_data_size(ErtsDistExternal *edep)
{
    Uint sz = 0, i;
    for (i = 0; i < edep->data->frag_id; i++)
        sz += edep->data[i].ext_endp - edep->data[i].extp;
    return sz;
}

void
erts_dist_ext_frag(ErtsDistExternalData *ede_datap, ErtsDistExternal *edep)
{
    ErtsDistExternalData *new_ede_datap = &edep->data[edep->data->frag_id - ede_datap->frag_id];
    sys_memcpy(new_ede_datap, ede_datap, sizeof(ErtsDistExternalData));

    /* If the data is not backed by a binary, we create one here to keep
       things simple. Only custom distribution drivers should use lists. */
    if (new_ede_datap->binp == NULL) {
        size_t ext_sz = ede_datap->ext_endp - ede_datap->extp;
        new_ede_datap->binp = erts_bin_nrml_alloc(ext_sz);
        sys_memcpy(new_ede_datap->binp->orig_bytes, (void *) ede_datap->extp, ext_sz);
        new_ede_datap->extp = (byte*)new_ede_datap->binp->orig_bytes;
        new_ede_datap->ext_endp = (byte*)new_ede_datap->binp->orig_bytes + ext_sz;
    } else {
        erts_refc_inc(&new_ede_datap->binp->intern.refc, 2);
    }
}

void
erts_make_dist_ext_copy(ErtsDistExternal *edep, ErtsDistExternal *new_edep)
{
    size_t dist_ext_sz = dist_ext_size(edep);
    byte *ep;

    ep = (byte *) new_edep;
    sys_memcpy((void *) ep, (void *) edep, dist_ext_sz);
    erts_ref_dist_entry(new_edep->dep);

    ep += dist_ext_sz;
    ep += (UWord)ep & 4; /* 8-byte alignment for ErtsDistExternalData */
    ASSERT((UWord)ep % 8 == 0);

    new_edep->data = (ErtsDistExternalData*)ep;
    sys_memzero(new_edep->data, sizeof(ErtsDistExternalData) * edep->data->frag_id);
    new_edep->data->frag_id = edep->data->frag_id;
    erts_dist_ext_frag(edep->data, new_edep);
}

void
erts_free_dist_ext_copy(ErtsDistExternal *edep)
{
    int i;
    erts_deref_dist_entry(edep->dep);
    for (i = 0; i < edep->data->frag_id; i++)
        if (edep->data[i].binp)
            erts_bin_release(edep->data[i].binp);
}

ErtsPrepDistExtRes
erts_prepare_dist_ext(ErtsDistExternal *edep,
		      byte *ext,
		      Uint size,
                      Binary *binp,
		      DistEntry *dep,
                      Uint32 conn_id,
		      ErtsAtomCache *cache)
{
    register byte *ep;

    ASSERT(dep);
    erts_de_rlock(dep);

    ASSERT(dep->dflags & DFLAG_UTF8_ATOMS);


    if ((dep->state != ERTS_DE_STATE_CONNECTED &&
         dep->state != ERTS_DE_STATE_PENDING)
        || dep->connection_id != conn_id) {
        erts_de_runlock(dep);
        return ERTS_PREP_DIST_EXT_CLOSED;
    }

    if (!(dep->dflags & (DFLAG_DIST_HDR_ATOM_CACHE|DFLAG_FRAGMENTS))) {
        /* Skip PASS_THROUGH */
        ext++;
        size--;
    }

    ep = ext;

    if (size < 2)
        goto fail;

    if (ep[0] != VERSION_MAGIC) {
	erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf();
        erts_dsprintf(dsbufp,
                      "** Got message from incompatible erlang on "
                      "channel %d\n",
                      dist_entry_channel_no(dep));
	erts_send_error_to_logger_nogl(dsbufp);
	goto fail;
    }

    edep->heap_size = -1;
    edep->flags = 0;
    edep->dep = dep;
    edep->connection_id = conn_id;
    edep->data->ext_endp = ext+size;
    edep->data->binp = binp;
    edep->data->seq_id = 0;
    edep->data->frag_id = 1;

    if (dep->dflags & (DFLAG_DIST_HDR_ATOM_CACHE|DFLAG_FRAGMENTS))
        edep->flags |= ERTS_DIST_EXT_DFLAG_HDR;

    if (ep[1] != DIST_HEADER && ep[1] != DIST_FRAG_HEADER && ep[1] != DIST_FRAG_CONT) {
	if (edep->flags & ERTS_DIST_EXT_DFLAG_HDR)
	    goto bad_hdr;
	edep->attab.size = 0;
	edep->data->extp = ext;
    }
    else if (ep[1] == DIST_FRAG_CONT) {
        if (!(dep->dflags & DFLAG_FRAGMENTS))
            goto bad_hdr;
        edep->attab.size = 0;
	edep->data->extp = ext + 1 + 1 + 8 + 8;
        edep->data->seq_id = get_int64(&ep[2]);
        edep->data->frag_id = get_int64(&ep[2+8]);
        erts_de_runlock(dep);
        return ERTS_PREP_DIST_EXT_FRAG_CONT;
    }
    else {
	int tix;
	int no_atoms;

	if (!(edep->flags & ERTS_DIST_EXT_DFLAG_HDR))
	    goto bad_hdr;

        if (ep[1] == DIST_FRAG_HEADER) {
            if (!(dep->dflags & DFLAG_FRAGMENTS))
                goto bad_hdr;
            edep->data->seq_id = get_int64(&ep[2]);
            edep->data->frag_id = get_int64(&ep[2+8]);
            ep += 16;
        }

#undef CHKSIZE
#define CHKSIZE(SZ) \
	do { if ((SZ) > edep->data->ext_endp - ep) goto bad_hdr; } while(0)

	CHKSIZE(1+1+1);
	ep += 2;
	no_atoms = (int) get_int8(ep);
	if (no_atoms < 0 || ERTS_ATOM_CACHE_SIZE < no_atoms)
	    goto bad_hdr;
	ep++;
	if (no_atoms) {
	    int long_atoms = 0;
#ifdef DEBUG
	    byte *flgs_buf = ep;
#endif
	    byte *flgsp = ep;
	    int flgs_size = ERTS_DIST_HDR_ATOM_CACHE_FLAG_BYTES(no_atoms);
	    int byte_ix;
	    int bit_ix;
	    int got_flgs;
	    register Uint32 flgs = 0;

	    CHKSIZE(flgs_size);
	    ep += flgs_size;

	    /*
	     * Check long atoms flag
	     */
	    byte_ix = ERTS_DIST_HDR_ATOM_CACHE_FLAG_BYTE_IX(no_atoms);
	    bit_ix = ERTS_DIST_HDR_ATOM_CACHE_FLAG_BIT_IX(no_atoms);
	    if (flgsp[byte_ix] & (((byte) ERTS_DIST_HDR_LONG_ATOMS_FLG) << bit_ix))
		long_atoms = 1;

#ifdef DEBUG
	    byte_ix = 0;
	    bit_ix = 0;
#endif
	    got_flgs = 0;
	    /*
	     * Setup the atom translation table.
	     */
	    edep->flags |= ERTS_DIST_EXT_ATOM_TRANS_TAB;
	    edep->attab.size = no_atoms;
	    for (tix = 0; tix < no_atoms; tix++) {
		Eterm atom;
		int cix;
		int len;

		if (!got_flgs) {
		    int left = no_atoms - tix;
		    if (left > 6) {
			flgs = ((((Uint32) flgsp[3]) << 24)
		        	| (((Uint32) flgsp[2]) << 16)
				| (((Uint32) flgsp[1]) << 8)
				| ((Uint32) flgsp[0]));
			flgsp += 4;
		    }
		    else {
			flgs = 0;
			switch (left) {
			case 6:
			case 5:
			    flgs |= (((Uint32) flgsp[2]) << 16);
			case 4:
			case 3:
			    flgs |= (((Uint32) flgsp[1]) << 8);
			case 2:
			case 1:
			    flgs |= ((Uint32) flgsp[0]);
			}
		    }
		    got_flgs = 8;
		}

		ASSERT(byte_ix == ERTS_DIST_HDR_ATOM_CACHE_FLAG_BYTE_IX(tix));
		ASSERT(bit_ix == ERTS_DIST_HDR_ATOM_CACHE_FLAG_BIT_IX(tix));
		ASSERT((flgs & 3)
		       == (((flgs_buf[byte_ix]
			     & (((byte) 3) << bit_ix)) >> bit_ix) & 3));

		CHKSIZE(1);
		cix = (int) ((flgs & 7) << 8);
		if ((flgs & 8) == 0) {
		    /* atom already cached */
		    cix += (int) get_int8(ep);
		    if (cix >= ERTS_ATOM_CACHE_SIZE)
			goto bad_hdr;
		    ep++;
		    atom = cache->in_arr[cix];
		    if (!is_atom(atom))
			goto bad_hdr;
		    edep->attab.atom[tix] = atom;
		}
		else {
		    /* new cached atom */
		    cix += (int) get_int8(ep);
		    if (cix >= ERTS_ATOM_CACHE_SIZE)
			goto bad_hdr;
		    ep++;
		    if (long_atoms) {
			CHKSIZE(2);
			len = get_int16(ep);
			ep += 2;
		    }
		    else {
			CHKSIZE(1);
			len = get_int8(ep);
			ep++;
		    }
		    CHKSIZE(len);
		    atom = erts_atom_put((byte *) ep,
					 len,
                                         ERTS_ATOM_ENC_UTF8,
					 0);
		    if (is_non_value(atom))
			goto bad_hdr;
		    ep += len;
		    cache->in_arr[cix] = atom;
		    edep->attab.atom[tix] = atom;
		}
		flgs >>= 4;
		got_flgs--;
#ifdef DEBUG
		bit_ix += 4;
		if (bit_ix >= 8) {
		    bit_ix = 0;
		    flgs = (int) flgs_buf[++byte_ix];
		    ASSERT(byte_ix < flgs_size);
		}
#endif
	    }
	}
	edep->data->extp = ep;
#ifdef ERTS_DEBUG_USE_DIST_SEP
	if (*ep != VERSION_MAGIC)
	    goto bad_hdr;
#endif
    }
#ifdef ERTS_DEBUG_USE_DIST_SEP
    if (*ep != VERSION_MAGIC)
	goto fail;
#endif

    erts_de_runlock(dep);

    return ERTS_PREP_DIST_EXT_SUCCESS;

#undef CHKSIZE

 bad_hdr: {
	erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf();
	erts_dsprintf(dsbufp,
		      "%T got a corrupted distribution header from %T "
		      "on distribution channel %d\n",
		      erts_this_node->sysname,
		      edep->dep->sysname,
		      dist_entry_channel_no(edep->dep));
	for (ep = ext; ep < edep->data->ext_endp; ep++)
	    erts_dsprintf(dsbufp, ep != ext ? ",%b8u" : "<<%b8u", *ep);
	erts_dsprintf(dsbufp, ">>");
	erts_send_warning_to_logger_nogl(dsbufp);
    }
 fail: {
	erts_de_runlock(dep);
	erts_kill_dist_connection(dep, conn_id);
    }
    return ERTS_PREP_DIST_EXT_FAILED;
}

static void
bad_dist_ext(ErtsDistExternal *edep)
{
    if (edep->dep) {
	DistEntry *dep = edep->dep;
	erts_dsprintf_buf_t *dsbufp = erts_create_logger_dsbuf();
	byte *ep;
	erts_dsprintf(dsbufp,
		      "%T got a corrupted external term from %T "
		      "on distribution channel %d\n",
		      erts_this_node->sysname,
		      dep->sysname,
		      dist_entry_channel_no(dep));
	for (ep = edep->data->extp; ep < edep->data->ext_endp; ep++)
	    erts_dsprintf(dsbufp,
			  ep != edep->data->extp ? ",%b8u" : "<<...,%b8u",
			  *ep);
	erts_dsprintf(dsbufp, ">>\n");
	erts_dsprintf(dsbufp, "ATOM_CACHE_REF translations: ");
	if (!(edep->flags & ERTS_DIST_EXT_ATOM_TRANS_TAB) || !edep->attab.size)
	    erts_dsprintf(dsbufp, "none");
	else {
	    int i;
	    erts_dsprintf(dsbufp, "0=%T", edep->attab.atom[0]);
	    for (i = 1; i < edep->attab.size; i++)
		erts_dsprintf(dsbufp, ", %d=%T", i, edep->attab.atom[i]);
	}
	erts_send_warning_to_logger_nogl(dsbufp);
	erts_kill_dist_connection(dep, edep->connection_id);
    }
}

Sint
erts_decode_dist_ext_size(ErtsDistExternal *edep, int kill_connection, int payload)
{
    Sint res;
    byte *ep;

    if (edep->data->frag_id > 1 && payload) {
        Uint sz = 0;
        Binary *bin;
        int i;
        byte *ep;

        for (i = 0; i < edep->data->frag_id; i++)
            sz += edep->data[i].ext_endp - edep->data[i].extp;

        bin = erts_bin_nrml_alloc(sz);
        ep = (byte*)bin->orig_bytes;

        for (i = 0; i < edep->data->frag_id; i++) {
            sys_memcpy(ep, edep->data[i].extp, edep->data[i].ext_endp - edep->data[i].extp);
            ep += edep->data[i].ext_endp - edep->data[i].extp;
            erts_bin_release(edep->data[i].binp);
            edep->data[i].binp = NULL;
            edep->data[i].extp = NULL;
            edep->data[i].ext_endp = NULL;
        }

        edep->data->frag_id = 1;
        edep->data->extp = (byte*)bin->orig_bytes;
        edep->data->ext_endp = ep;
        edep->data->binp = bin;
    }

    if (edep->data->extp >= edep->data->ext_endp)
	goto fail;
#ifndef ERTS_DEBUG_USE_DIST_SEP
    if (edep->flags & ERTS_DIST_EXT_DFLAG_HDR) {
	if (*edep->data->extp == VERSION_MAGIC)
	    goto fail;
	ep = edep->data->extp;
    }
    else
#endif
    {
	if (*edep->data->extp != VERSION_MAGIC)
	    goto fail;
	ep = edep->data->extp+1;
    }
    res = decoded_size(ep, edep->data->ext_endp, 0, NULL);
    if (res >= 0)
	return res;
 fail:
    if (kill_connection)
        bad_dist_ext(edep);
    return -1;
}

Sint erts_decode_ext_size(byte *ext, Uint size)
{
    if (size == 0 || *ext != VERSION_MAGIC)
	return -1;
    return decoded_size(ext+1, ext+size, 0, NULL);
}

Sint erts_decode_ext_size_ets(byte *ext, Uint size)
{
    Sint sz = decoded_size(ext, ext+size, 1, NULL);
    ASSERT(sz >= 0);
    return sz;
}


/*
** hpp is set to either a &p->htop or
** a pointer to a memory pointer (form message buffers)
** on return hpp is updated to point after allocated data
*/
Eterm
erts_decode_dist_ext(ErtsHeapFactory* factory,
		     ErtsDistExternal *edep,
                     int kill_connection)
{
    Eterm obj;
    byte* ep;

    ep = edep->data->extp;

    if (ep >= edep->data->ext_endp)
	goto error;
#ifndef ERTS_DEBUG_USE_DIST_SEP
    if (edep->flags & ERTS_DIST_EXT_DFLAG_HDR) {
	if (*ep == VERSION_MAGIC)
	    goto error;
    }
    else
#endif
    {
	if (*ep != VERSION_MAGIC)
	    goto error;
	ep++;
    }
    ep = dec_term(edep, factory, ep, &obj, NULL, 0);
    if (!ep)
	goto error;

    edep->data->extp = ep;

    return obj;

 error:
    erts_factory_undo(factory);

    if (kill_connection)
        bad_dist_ext(edep);

    return THE_NON_VALUE;
}

Eterm erts_decode_ext(ErtsHeapFactory* factory, byte **ext, Uint32 flags)
{
    ErtsDistExternal ede, *edep;
    Eterm obj;
    byte *ep = *ext;
    if (*ep++ != VERSION_MAGIC) {
        erts_factory_undo(factory);
	return THE_NON_VALUE;
    }
    if (flags) {
        ASSERT(flags == ERTS_DIST_EXT_BTT_SAFE);
        ede.flags = flags; /* a dummy struct just for the flags */
        ede.data = NULL;
        edep = &ede;
    } else {
        edep = NULL;
    }
    ep = dec_term(edep, factory, ep, &obj, NULL, 0);
    if (!ep) {
	return THE_NON_VALUE;
    }
    *ext = ep;
    return obj;
}

Eterm erts_decode_ext_ets(ErtsHeapFactory* factory, byte *ext)
{
    Eterm obj;
    ext = dec_term(NULL, factory, ext, &obj, NULL, 1);
    ASSERT(ext);
    return obj;
}

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

BIF_RETTYPE erts_debug_dist_ext_to_term_2(BIF_ALIST_2)
{
    ErtsHeapFactory factory;
    Eterm res;
    Sint hsz;
    ErtsDistExternal ede;
    ErtsDistExternalData ede_data;
    Eterm *tp;
    Eterm real_bin;
    Uint offset;
    Uint size;
    Uint bitsize;
    Uint bitoffs;
    Uint arity;
    int i;

    ede.flags = ERTS_DIST_EXT_ATOM_TRANS_TAB;
    ede.dep = NULL;
    ede.heap_size = -1;
    ede.data = &ede_data;

    if (is_not_tuple(BIF_ARG_1))
	goto badarg;
    tp = tuple_val(BIF_ARG_1);
    arity = arityval(tp[0]);
    if (arity > ERTS_MAX_INTERNAL_ATOM_CACHE_ENTRIES)
	goto badarg;

    ede.attab.size = arity;
    for (i = 1; i <= arity; i++) {
	if (is_not_atom(tp[i]))
	    goto badarg;
	ede.attab.atom[i-1] = tp[i];
    }

    if (is_not_binary(BIF_ARG_2))
	goto badarg;

    size = binary_size(BIF_ARG_2);
    if (size == 0)
	goto badarg;
    ERTS_GET_REAL_BIN(BIF_ARG_2, real_bin, offset, bitoffs, bitsize);
    if (bitsize != 0)
	goto badarg;

    ede.data->extp = binary_bytes(real_bin)+offset;
    ede.data->ext_endp = ede.data->extp + size;
    ede.data->frag_id = 1;
    ede.data->binp = NULL;

    hsz = erts_decode_dist_ext_size(&ede, 1, 1);
    if (hsz < 0)
	goto badarg;

    erts_factory_proc_prealloc_init(&factory, BIF_P, hsz);
    res = erts_decode_dist_ext(&factory, &ede, 1);
    erts_factory_close(&factory);

    if (is_value(res))
	BIF_RET(res);

 badarg:

    BIF_ERROR(BIF_P, BADARG);
}

static BIF_RETTYPE term_to_binary_trap_1(BIF_ALIST_1)
{
    Eterm *tp = tuple_val(BIF_ARG_1);
    Eterm Term = tp[1];
    Eterm Opts = tp[2];
    Eterm bt = tp[3];
    Eterm bix = tp[4];
    Sint bif_ix = signed_val(bix);
    Binary *bin = erts_magic_ref2bin(bt);
    Eterm res = erts_term_to_binary_int(BIF_P, bif_ix, Term, Opts,
                                        0, 0,bin, 0, ~((Uint) 0));
    if (is_non_value(res)) {
        if (erts_set_gc_state(BIF_P, 1)
            || MSO(BIF_P).overhead > BIN_VHEAP_SZ(BIF_P)) {
            ERTS_VBUMP_ALL_REDS(BIF_P);
        }
        if (Opts == am_undefined)
            ERTS_BIF_ERROR_TRAPPED1(BIF_P, SYSTEM_LIMIT,
                                    &bif_trap_export[bif_ix], Term);
        else
            ERTS_BIF_ERROR_TRAPPED2(BIF_P, SYSTEM_LIMIT,
                                    &bif_trap_export[bif_ix], Term, Opts);
    }
    if (is_tuple(res)) {
	ASSERT(BIF_P->flags & F_DISABLE_GC);
	BIF_TRAP1(&term_to_binary_trap_export,BIF_P,res);
    } else {
        if (erts_set_gc_state(BIF_P, 1)
            || MSO(BIF_P).overhead > BIN_VHEAP_SZ(BIF_P))
            ERTS_BIF_YIELD_RETURN(BIF_P, res);
        else
            BIF_RET(res);
    }
}

HIPE_WRAPPER_BIF_DISABLE_GC(term_to_binary, 1)

BIF_RETTYPE term_to_binary_1(BIF_ALIST_1)
{
    Eterm res = erts_term_to_binary_int(BIF_P, BIF_term_to_binary_1,
                                        BIF_ARG_1, am_undefined,
                                        0, TERM_TO_BINARY_DFLAGS, NULL, 0,
                                        ~((Uint) 0));
    if (is_non_value(res)) {
	ASSERT(!(BIF_P->flags & F_DISABLE_GC));
        BIF_ERROR(BIF_P, SYSTEM_LIMIT);
    }
    if (is_tuple(res)) {
	erts_set_gc_state(BIF_P, 0);
	BIF_TRAP1(&term_to_binary_trap_export,BIF_P,res);
    } else {
	ASSERT(!(BIF_P->flags & F_DISABLE_GC));
	BIF_RET(res);
    }
}

HIPE_WRAPPER_BIF_DISABLE_GC(term_to_iovec, 1)

BIF_RETTYPE term_to_iovec_1(BIF_ALIST_1)
{
    Eterm res = erts_term_to_binary_int(BIF_P, BIF_term_to_iovec_1,
                                        BIF_ARG_1, am_undefined,
                                        0, TERM_TO_BINARY_DFLAGS, NULL, !0,
                                        ~((Uint) 0));
    if (is_non_value(res)) {
	ASSERT(!(BIF_P->flags & F_DISABLE_GC));
        BIF_ERROR(BIF_P, SYSTEM_LIMIT);
    }
    if (is_tuple(res)) {
	erts_set_gc_state(BIF_P, 0);
	BIF_TRAP1(&term_to_binary_trap_export,BIF_P,res);
    } else {
	ASSERT(!(BIF_P->flags & F_DISABLE_GC));
	BIF_RET(res);
    }
}

static ERTS_INLINE int
parse_t2b_opts(Eterm opts, Uint *flagsp, int *levelp, int *iovecp, Uint *fsizep)
{
    int level = 0;
    int iovec = 0;
    Uint flags = TERM_TO_BINARY_DFLAGS;
    Uint fsize = ~((Uint) 0); /* one fragment */

    while (is_list(opts)) {
	Eterm arg = CAR(list_val(opts));
	Eterm* tp;
	if (arg == am_compressed) {
	    level = Z_DEFAULT_COMPRESSION;
        }
        else if (iovecp && arg == am_iovec) {
            iovec = !0;
	} else if (is_tuple(arg) && *(tp = tuple_val(arg)) == make_arityval(2)) {
	    if (tp[1] == am_minor_version && is_small(tp[2])) {
		switch (signed_val(tp[2])) {
		case 0:
		    flags = TERM_TO_BINARY_DFLAGS & ~DFLAG_NEW_FLOATS;
		    break;
		case 1: /* Current default... */
		    flags = TERM_TO_BINARY_DFLAGS;
                    break;
                case 2:
                    flags = TERM_TO_BINARY_DFLAGS | DFLAG_UTF8_ATOMS;
		    break;
		default:
                    return 0; /* badarg */
		}
	    } else if (tp[1] == am_compressed && is_small(tp[2])) {
		level = signed_val(tp[2]);
		if (!(0 <= level && level < 10)) {
                    return 0; /* badarg */
		}
	    } else if (fsizep) {
                if (ERTS_IS_ATOM_STR("fragment", tp[1])) {
                    if (!term_to_Uint(tp[2], &fsize))
                        return 0; /* badarg */
                }
                else {
                    return 0; /* badarg */
                }
            }
            else {
                return 0; /* badarg */
	    }
	} else {
            return 0; /* badarg */
	}
	opts = CDR(list_val(opts));
    }
    if (is_not_nil(opts)) {
        return 0; /* badarg */
    }

    *flagsp = flags;
    *levelp = level;
    if (iovecp)
        *iovecp = iovec;
    if (fsizep)
        *fsizep = fsize;

    return !0; /* ok */
}

HIPE_WRAPPER_BIF_DISABLE_GC(term_to_binary, 2)

BIF_RETTYPE term_to_binary_2(BIF_ALIST_2)
{
    int level;
    Uint flags;
    Eterm res;

    if (!parse_t2b_opts(BIF_ARG_2, &flags, &level, NULL, NULL)) {
        BIF_ERROR(BIF_P, BADARG);
    }

    res = erts_term_to_binary_int(BIF_P, BIF_term_to_binary_2,
                                  BIF_ARG_1, BIF_ARG_2,
                                  level, flags, NULL, 0,
                                  ~((Uint) 0));
    if (is_non_value(res)) {
	ASSERT(!(BIF_P->flags & F_DISABLE_GC));
        BIF_ERROR(BIF_P, SYSTEM_LIMIT);
    }
    if (is_tuple(res)) {
	erts_set_gc_state(BIF_P, 0);
	BIF_TRAP1(&term_to_binary_trap_export,BIF_P,res);
    } else {
	ASSERT(!(BIF_P->flags & F_DISABLE_GC));
	BIF_RET(res);
    }
}

HIPE_WRAPPER_BIF_DISABLE_GC(term_to_iovec, 2)

BIF_RETTYPE term_to_iovec_2(BIF_ALIST_2)
{
    int level;
    Uint flags;
    Eterm res;

    if (!parse_t2b_opts(BIF_ARG_2, &flags, &level, NULL, NULL)) {
        BIF_ERROR(BIF_P, BADARG);
    }
    
    res = erts_term_to_binary_int(BIF_P, BIF_term_to_iovec_2,
                                  BIF_ARG_1, BIF_ARG_2,
                                  level, flags, NULL, !0,
                                  ~((Uint) 0));
    if (is_non_value(res)) {
	ASSERT(!(BIF_P->flags & F_DISABLE_GC));
        BIF_ERROR(BIF_P, SYSTEM_LIMIT);
    }
    if (is_tuple(res)) {
	erts_set_gc_state(BIF_P, 0);
	BIF_TRAP1(&term_to_binary_trap_export,BIF_P,res);
    } else {
	ASSERT(!(BIF_P->flags & F_DISABLE_GC));
	BIF_RET(res);
    }
}

Eterm
erts_debug_term_to_binary(Process *p, Eterm term, Eterm opts)
{
    Eterm ret;
    int level, iovec;
    Uint flags;
    Uint fsize;
    
    if (!parse_t2b_opts(opts, &flags, &level, &iovec, &fsize)) {
        ERTS_BIF_PREP_ERROR(ret, p, BADARG);
    }
    else {
        Eterm res = erts_term_to_binary_int(p, BIF_term_to_binary_2,
                                            term, opts, level, flags,
                                            NULL, iovec, fsize);
    
        if (is_non_value(res)) {
            ASSERT(!(p->flags & F_DISABLE_GC));
            ERTS_BIF_PREP_ERROR(ret, p, SYSTEM_LIMIT);
        }
        else if (is_tuple(res)) {
            erts_set_gc_state(p, 0);
            ERTS_BIF_PREP_TRAP1(ret, &term_to_binary_trap_export,p,res);
        }
        else {
            ASSERT(!(p->flags & F_DISABLE_GC));
            ERTS_BIF_PREP_RET(ret, res);
        }
    }
    return ret;
}


enum B2TState { /* order is somewhat significant */
    B2TPrepare,
    B2TUncompressChunk,
    B2TSizeInit,
    B2TSize,
    B2TDecodeInit,
    B2TDecode,
    B2TDecodeList,
    B2TDecodeTuple,
    B2TDecodeString,
    B2TDecodeBinary,

    B2TDone,
    B2TDecodeFail,
    B2TBadArg
};

typedef struct {
    Sint heap_size;
    int terms;
    byte* ep;
    int atom_extra_skip;
} B2TSizeContext;

typedef struct {
    byte*  ep;
    Eterm  res;
    Eterm* next;
    ErtsHeapFactory factory;
    int remaining_n;
    char* remaining_bytes;
    ErtsWStack flat_maps;
    ErtsPStack hamt_array;
} B2TDecodeContext;

typedef struct {
    z_stream stream;
    byte* dbytes;
    Uint dleft;
} B2TUncompressContext;

typedef struct B2TContext_t {
    Sint heap_size;
    byte* aligned_alloc;
    ErtsBinary2TermState b2ts;
    Uint32 flags;
    SWord reds;
    Uint used_bytes; /* In: boolean, Out: bytes */
    Eterm trap_bin;  /* THE_NON_VALUE if not exported */
    Export *bif;
    Eterm arg[2];
    enum B2TState state;
    union {
	B2TSizeContext sc;
	B2TDecodeContext dc;
	B2TUncompressContext uc;
    } u;
} B2TContext;

static B2TContext* b2t_export_context(Process*, B2TContext* src);

static uLongf binary2term_uncomp_size(byte* data, Sint size)
{
    z_stream stream;
    int err;
    const uInt chunk_size = 64*1024;  /* Ask tmp-alloc about a suitable size? */
    void* tmp_buf = erts_alloc(ERTS_ALC_T_TMP, chunk_size);
    uLongf uncomp_size = 0;

    stream.next_in = (Bytef*)data;
    stream.avail_in = (uInt)size;
    stream.next_out = tmp_buf;
    stream.avail_out = (uInt)chunk_size;

    erl_zlib_alloc_init(&stream);

    err = inflateInit(&stream);
    if (err == Z_OK) {
	do {
	    stream.next_out = tmp_buf;
	    stream.avail_out = chunk_size;	   
	    err = inflate(&stream, Z_NO_FLUSH);
	    uncomp_size += chunk_size - stream.avail_out;
	}while (err == Z_OK);
	inflateEnd(&stream);
    }
    erts_free(ERTS_ALC_T_TMP, tmp_buf);
    return err == Z_STREAM_END ? uncomp_size : 0;
}

static ERTS_INLINE int
binary2term_prepare(ErtsBinary2TermState *state, byte *data, Sint data_size,
		    B2TContext** ctxp, Process* p)
{
    byte *bytes = data;
    Sint size = data_size;

    state->exttmp = 0;

    if (size < 1 || *bytes != VERSION_MAGIC) {
	return -1;
    }
    bytes++;
    size--;
    if (size < 5 || *bytes != COMPRESSED) {
	state->extp = bytes;
        if (ctxp)
	    (*ctxp)->state = B2TSizeInit;
    }
    else  {
	uLongf dest_len = (Uint32) get_int32(bytes+1);
	bytes += 5;
	size -= 5;	
	if (dest_len > 32*1024*1024
	    || (state->extp = erts_alloc_fnf(ERTS_ALC_T_EXT_TERM_DATA, dest_len)) == NULL) {
            /*
             * Try avoid out-of-memory crash due to corrupted 'dest_len'
             * by checking the actual length of the uncompressed data.
             * The only way to do that is to uncompress it. Sad but true.
             */
	    if (dest_len != binary2term_uncomp_size(bytes, size)) {
                return -1;
	    }
	    state->extp = erts_alloc(ERTS_ALC_T_EXT_TERM_DATA, dest_len);
            if (ctxp)
                (*ctxp)->reds -= dest_len;
	}
	state->exttmp = 1;
        if (ctxp) {
            /*
             * Start decompression by exporting trap context
             * so we don't have to deal with deep-copying z_stream.
             */
            B2TContext* ctx = b2t_export_context(p, *ctxp);
            ASSERT(state = &(*ctxp)->b2ts);
            state = &ctx->b2ts;

	    if (erl_zlib_inflate_start(&ctx->u.uc.stream, bytes, size) != Z_OK)
		return -1;

	    ctx->u.uc.dbytes = state->extp;
	    ctx->u.uc.dleft = dest_len;
            if (ctx->used_bytes) {
                ASSERT(ctx->used_bytes == 1);
                 /* to be subtracted by stream.avail_in when done */
                ctx->used_bytes = data_size;
            }
	    ctx->state = B2TUncompressChunk;
            *ctxp = ctx;
        }
	else {
	    uLongf dlen = dest_len;
	    if (erl_zlib_uncompress(state->extp, &dlen, bytes, size) != Z_OK
		|| dlen != dest_len) {
		return -1;
	    }
        }
	size = (Sint) dest_len;
    }
    state->extsize = size;
    return 0;
}

static ERTS_INLINE void
binary2term_abort(ErtsBinary2TermState *state)
{
    if (state->exttmp) {
	state->exttmp = 0;
	erts_free(ERTS_ALC_T_EXT_TERM_DATA, state->extp);
    }
}

static ERTS_INLINE Eterm
binary2term_create(ErtsDistExternal *edep, ErtsBinary2TermState *state,
		   ErtsHeapFactory* factory)
{
    Eterm res;

    if (!dec_term(edep, factory, state->extp, &res, NULL, 0))
	res = THE_NON_VALUE;
    if (state->exttmp) {
	state->exttmp = 0;
	erts_free(ERTS_ALC_T_EXT_TERM_DATA, state->extp);
    }
    return res;
}

Sint
erts_binary2term_prepare(ErtsBinary2TermState *state, byte *data, Sint data_size)
{
    Sint res;

    if (binary2term_prepare(state, data, data_size, NULL, NULL) < 0 ||
        (res=decoded_size(state->extp, state->extp + state->extsize, 0, NULL)) < 0) {

        if (state->exttmp)
            erts_free(ERTS_ALC_T_EXT_TERM_DATA, state->extp);
        state->extp = NULL;
	state->exttmp = 0;
	return -1;
    }
    return res;
}

void
erts_binary2term_abort(ErtsBinary2TermState *state)
{
    binary2term_abort(state);
}

Eterm
erts_binary2term_create(ErtsBinary2TermState *state, ErtsHeapFactory* factory)
{
    return binary2term_create(NULL,state, factory);
}

static void b2t_destroy_context(B2TContext* context)
{
    erts_free_aligned_binary_bytes_extra(context->aligned_alloc,
                                         ERTS_ALC_T_EXT_TERM_DATA);
    context->aligned_alloc = NULL;
    binary2term_abort(&context->b2ts);
    switch (context->state) {
    case B2TUncompressChunk:
	erl_zlib_inflate_finish(&context->u.uc.stream);
	break;
    case B2TDecode:
    case B2TDecodeList:
    case B2TDecodeTuple:
    case B2TDecodeString:
    case B2TDecodeBinary:
	if (context->u.dc.hamt_array.pstart) {
	    erts_free(context->u.dc.hamt_array.alloc_type,
		      context->u.dc.hamt_array.pstart);
	}
	break;
    default:;
    }
}

static int b2t_context_destructor(Binary *context_bin)
{
    B2TContext* ctx = (B2TContext*) ERTS_MAGIC_BIN_DATA(context_bin);
    ASSERT(ERTS_MAGIC_BIN_DESTRUCTOR(context_bin) == b2t_context_destructor);

    b2t_destroy_context(ctx);
    return 1;
}

static BIF_RETTYPE binary_to_term_int(Process*, Eterm bin, B2TContext*);


static BIF_RETTYPE binary_to_term_trap_1(BIF_ALIST_1)
{
    Binary *context_bin = erts_magic_ref2bin(BIF_ARG_1);
    ASSERT(ERTS_MAGIC_BIN_DESTRUCTOR(context_bin) == b2t_context_destructor);

    return binary_to_term_int(BIF_P, THE_NON_VALUE, ERTS_MAGIC_BIN_DATA(context_bin));
}


#define B2T_BYTES_PER_REDUCTION 128
#define B2T_MEMCPY_FACTOR 8

/* Define for testing */
/*#define EXTREME_B2T_TRAPPING 1*/

#ifdef EXTREME_B2T_TRAPPING
static unsigned b2t_rand(void)
{
    static unsigned prev = 17;
    prev = (prev * 214013 + 2531011);
    return prev;
}
#endif


static B2TContext* b2t_export_context(Process* p, B2TContext* src)
{
    Binary* context_b = erts_create_magic_binary(sizeof(B2TContext),
                                                 b2t_context_destructor);
    B2TContext* ctx = ERTS_MAGIC_BIN_DATA(context_b);
    Eterm* hp;

    ASSERT(is_non_value(src->trap_bin));
    sys_memcpy(ctx, src, sizeof(B2TContext));
    if (ctx->state >= B2TDecode && ctx->u.dc.next == &src->u.dc.res) {
        ctx->u.dc.next = &ctx->u.dc.res;
    }
    hp = HAlloc(p, ERTS_MAGIC_REF_THING_SIZE);
    ctx->trap_bin = erts_mk_magic_ref(&hp, &MSO(p), context_b);
    return ctx;
}

static BIF_RETTYPE binary_to_term_int(Process* p, Eterm bin, B2TContext *ctx)
{
    BIF_RETTYPE ret_val;
#ifdef EXTREME_B2T_TRAPPING
    SWord initial_reds = 1 + b2t_rand() % 4;
#else
    SWord initial_reds = (Uint)(ERTS_BIF_REDS_LEFT(p) * B2T_BYTES_PER_REDUCTION);
#endif
    int is_first_call;

    if (is_value(bin)) {
	/* Setup enough to get started */
        is_first_call = 1;
	ctx->state = B2TPrepare;
        ctx->aligned_alloc = NULL;
    } else {
        ASSERT(is_value(ctx->trap_bin));
        ASSERT(ctx->state != B2TPrepare);
        is_first_call = 0;
    }
    ctx->reds = initial_reds;

    do {
        switch (ctx->state) {
        case B2TPrepare: {
	    byte* bytes;
            Uint bin_size;
            bytes = erts_get_aligned_binary_bytes_extra(bin,
                                                        &ctx->aligned_alloc,
                                                        ERTS_ALC_T_EXT_TERM_DATA,
                                                        0);
            if (bytes == NULL) {
                ctx->b2ts.exttmp = 0;
                ctx->state = B2TBadArg;
                break;
            }
            bin_size = binary_size(bin);
            if (ctx->aligned_alloc) {
                ctx->reds -= bin_size / 8;
            }
            if (binary2term_prepare(&ctx->b2ts, bytes, bin_size, &ctx, p) < 0) {
		ctx->state = B2TBadArg;
	    }
            break;
        }
	case B2TUncompressChunk: {
            uLongf chunk = ctx->reds;
            int zret;

            if (chunk > ctx->u.uc.dleft)
                chunk = ctx->u.uc.dleft;
            zret = erl_zlib_inflate_chunk(&ctx->u.uc.stream,
                                          ctx->u.uc.dbytes, &chunk);
            ctx->u.uc.dbytes += chunk;
            ctx->u.uc.dleft  -= chunk;
            if (zret == Z_OK && ctx->u.uc.dleft > 0) {
                ctx->reds = 0;
            }
            else if (erl_zlib_inflate_finish(&ctx->u.uc.stream) == Z_OK
                     && zret == Z_STREAM_END
                     && ctx->u.uc.dleft == 0) {
                ctx->reds -= chunk;
                if (ctx->used_bytes) {
                    ASSERT(ctx->used_bytes > 5 + ctx->u.uc.stream.avail_in);
                    ctx->used_bytes -= ctx->u.uc.stream.avail_in;
                }
                ctx->state = B2TSizeInit;
            }
            else {
                ctx->state = B2TBadArg;
            }
            break;
        }
	case B2TSizeInit:
	    ctx->u.sc.ep = NULL;
	    ctx->state = B2TSize;
	    /*fall through*/
        case B2TSize:
            ctx->heap_size = decoded_size(ctx->b2ts.extp,
					  ctx->b2ts.extp + ctx->b2ts.extsize,
                                          0, ctx);
            break;

        case B2TDecodeInit:
            if (is_non_value(ctx->trap_bin) && ctx->b2ts.extsize > ctx->reds) {
                /* dec_term will maybe trap, allocate space for magic bin
                   before result term to make it easy to trim with HRelease.
                 */
                ctx = b2t_export_context(p, ctx);
            }
            ctx->u.dc.ep = ctx->b2ts.extp;
            ctx->u.dc.res = (Eterm) (UWord) NULL;
            ctx->u.dc.next = &ctx->u.dc.res;
	    erts_factory_proc_prealloc_init(&ctx->u.dc.factory, p, ctx->heap_size);
	    ctx->u.dc.flat_maps.wstart = NULL;
	    ctx->u.dc.hamt_array.pstart = NULL;
            ctx->state = B2TDecode;
            /*fall through*/
	case B2TDecode:
        case B2TDecodeList:
        case B2TDecodeTuple:
        case B2TDecodeString:
        case B2TDecodeBinary: {
	    ErtsDistExternal fakedep;
            fakedep.flags = ctx->flags;
            fakedep.data = NULL;
            dec_term(&fakedep, NULL, NULL, NULL, ctx, 0);
            break;
	}
        case B2TDecodeFail:
            /*fall through*/
        case B2TBadArg:
            BUMP_REDS(p, (initial_reds - ctx->reds) / B2T_BYTES_PER_REDUCTION);

	    ASSERT(ctx->bif == &bif_trap_export[BIF_binary_to_term_1]
		   || ctx->bif == &bif_trap_export[BIF_binary_to_term_2]);

	    if (is_first_call)
		ERTS_BIF_PREP_ERROR(ret_val, p, BADARG);
	    else {
                erts_set_gc_state(p, 1);
		if (is_non_value(ctx->arg[1]))
		    ERTS_BIF_PREP_ERROR_TRAPPED1(ret_val, p, BADARG, ctx->bif,
						 ctx->arg[0]);
		else
		    ERTS_BIF_PREP_ERROR_TRAPPED2(ret_val, p, BADARG, ctx->bif,
						 ctx->arg[0], ctx->arg[1]);
	    }
            b2t_destroy_context(ctx);
	    return ret_val;

        case B2TDone:
            if (ctx->used_bytes) {
                Eterm *hp;
                Eterm used;
                if (!ctx->b2ts.exttmp) {
                    ASSERT(ctx->used_bytes == 1);
                    ctx->used_bytes = (ctx->u.dc.ep - ctx->b2ts.extp
                                       +1); /* VERSION_MAGIC */
                }
                if (IS_USMALL(0, ctx->used_bytes)) {
                    hp = erts_produce_heap(&ctx->u.dc.factory, 3, 0);
                    used = make_small(ctx->used_bytes);
                }
                else {
                    hp = erts_produce_heap(&ctx->u.dc.factory, 3+BIG_UINT_HEAP_SIZE, 0);
                    used = uint_to_big(ctx->used_bytes, hp);
                    hp += BIG_UINT_HEAP_SIZE;
                }
                ctx->u.dc.res = TUPLE2(hp, ctx->u.dc.res, used);
            }
            b2t_destroy_context(ctx);

            if (ctx->u.dc.factory.hp > ctx->u.dc.factory.hp_end) {
                erts_exit(ERTS_ERROR_EXIT, ":%s, line %d: heap overrun by %d words(s)\n",
                         __FILE__, __LINE__, ctx->u.dc.factory.hp - ctx->u.dc.factory.hp_end);
            }
	    erts_factory_close(&ctx->u.dc.factory);

            if (!is_first_call) {
                erts_set_gc_state(p, 1);
            }
            BUMP_REDS(p, (initial_reds - ctx->reds) / B2T_BYTES_PER_REDUCTION);
	    ERTS_BIF_PREP_RET(ret_val, ctx->u.dc.res);
	    return ret_val;

        default:
            ASSERT(!"Unknown state in binary_to_term");
        }
    }while (ctx->reds > 0 || ctx->state >= B2TDone);

    if (is_non_value(ctx->trap_bin)) {
        ctx = b2t_export_context(p, ctx);
        ASSERT(is_value(ctx->trap_bin));
    }

    if (is_first_call) {
        erts_set_gc_state(p, 0);
    }
    BUMP_ALL_REDS(p);

    ERTS_BIF_PREP_TRAP1(ret_val, &binary_to_term_trap_export,
			p, ctx->trap_bin);

    return ret_val;
}

HIPE_WRAPPER_BIF_DISABLE_GC(binary_to_term, 1)

BIF_RETTYPE binary_to_term_1(BIF_ALIST_1)
{
    B2TContext ctx;

    ctx.flags = 0;
    ctx.used_bytes = 0;
    ctx.trap_bin = THE_NON_VALUE;
    ctx.bif = &bif_trap_export[BIF_binary_to_term_1];
    ctx.arg[0] = BIF_ARG_1;
    ctx.arg[1] = THE_NON_VALUE;
    return binary_to_term_int(BIF_P, BIF_ARG_1, &ctx);
}

HIPE_WRAPPER_BIF_DISABLE_GC(binary_to_term, 2)

BIF_RETTYPE binary_to_term_2(BIF_ALIST_2)
{
    B2TContext ctx;
    Eterm opts;
    Eterm opt;

    ctx.flags = 0;
    ctx.used_bytes = 0;
    opts = BIF_ARG_2;
    while (is_list(opts)) {
        opt = CAR(list_val(opts));
        if (opt == am_safe) {
            ctx.flags |= ERTS_DIST_EXT_BTT_SAFE;
        }
        else if (opt == am_used) {
            ctx.used_bytes = 1;
        }
	else {
            goto error;
        }
        opts = CDR(list_val(opts));
    }

    if (is_not_nil(opts))
        goto error;

    ctx.trap_bin = THE_NON_VALUE;
    ctx.bif = &bif_trap_export[BIF_binary_to_term_2];
    ctx.arg[0] = BIF_ARG_1;
    ctx.arg[1] = BIF_ARG_2;
    return binary_to_term_int(BIF_P, BIF_ARG_1, &ctx);

error:
    BIF_ERROR(BIF_P, BADARG);
}

Eterm
external_size_1(BIF_ALIST_1)
{
    Process* p = BIF_P;
    Eterm Term = BIF_ARG_1;
    Uint size = 0;

    switch (erts_encode_ext_size(Term, &size)) {
    case ERTS_EXT_SZ_SYSTEM_LIMIT:
        BIF_ERROR(BIF_P, SYSTEM_LIMIT);
    case ERTS_EXT_SZ_YIELD:
        ERTS_INTERNAL_ERROR("Unexpected yield");
    case ERTS_EXT_SZ_OK:
        break;
    }

    if (IS_USMALL(0, size)) {
	BIF_RET(make_small(size));
    } else {
	Eterm* hp = HAlloc(p, BIG_UINT_HEAP_SIZE);
	BIF_RET(uint_to_big(size, hp));
    }
}

Eterm
external_size_2(BIF_ALIST_2)
{
    Uint size = 0;
    Uint flags = TERM_TO_BINARY_DFLAGS;

    while (is_list(BIF_ARG_2)) {
        Eterm arg = CAR(list_val(BIF_ARG_2));
        Eterm* tp;

        if (is_tuple(arg) && *(tp = tuple_val(arg)) == make_arityval(2)) {
            if (tp[1] == am_minor_version && is_small(tp[2])) {
                switch (signed_val(tp[2])) {
                case 0:
                    flags &= ~DFLAG_NEW_FLOATS;
                    break;
                case 1:
                    break;
                default:
                    goto error;
                }
            } else {
                goto error;
            }
        } else {
        error:
            BIF_ERROR(BIF_P, BADARG);
        }
        BIF_ARG_2 = CDR(list_val(BIF_ARG_2));
    }
    if (is_not_nil(BIF_ARG_2)) {
        goto error;
    }

    switch (erts_encode_ext_size_2(BIF_ARG_1, flags, &size)) {
    case ERTS_EXT_SZ_SYSTEM_LIMIT:
        BIF_ERROR(BIF_P, SYSTEM_LIMIT);
    case ERTS_EXT_SZ_YIELD:
        ERTS_INTERNAL_ERROR("Unexpected yield");
    case ERTS_EXT_SZ_OK:
        break;
    }

    if (IS_USMALL(0, size)) {
        BIF_RET(make_small(size));
    } else {
        Eterm* hp = HAlloc(BIF_P, BIG_UINT_HEAP_SIZE);
        BIF_RET(uint_to_big(size, hp));
    }
}

static Eterm
erts_term_to_binary_simple(Process* p, Eterm Term, Uint size, int level, Uint64 dflags)
{
    Eterm bin;
    size_t real_size;
    byte* endp;

    if (level != 0) {
	byte buf[256];
	byte* bytes = buf;
	byte* out_bytes;
	uLongf dest_len;

	if (sizeof(buf) < size) {
	    bytes = erts_alloc(ERTS_ALC_T_TMP, size);
	}

	if ((endp = enc_term(NULL, Term, bytes, dflags, NULL))
	    == NULL) {
	    erts_exit(ERTS_ERROR_EXIT, "%s, line %d: bad term: %x\n",
		     __FILE__, __LINE__, Term);
	}
	real_size = endp - bytes;
	if (real_size > size) {
	    erts_exit(ERTS_ERROR_EXIT, "%s, line %d: buffer overflow: %d word(s)\n",
		     __FILE__, __LINE__, real_size - size);
	}

	/*
	 * We don't want to compress if compression actually increases the size.
	 * Therefore, don't give zlib more out buffer than the size of the
	 * uncompressed external format (minus the 5 bytes needed for the
	 * COMPRESSED tag). If zlib returns any error, we'll revert to using
	 * the original uncompressed external term format.
	 */

	if (real_size < 5) {
	    dest_len = 0;
	} else {
	    dest_len = real_size - 5;
	}
	bin = new_binary(p, NULL, real_size+1);
	out_bytes = binary_bytes(bin);
	out_bytes[0] = VERSION_MAGIC;
	if (erl_zlib_compress2(out_bytes+6, &dest_len, bytes, real_size, level) != Z_OK) {
	    sys_memcpy(out_bytes+1, bytes, real_size);
	    bin = erts_realloc_binary(bin, real_size+1);
	} else {
	    out_bytes[1] = COMPRESSED;
	    put_int32(real_size, out_bytes+2);
	    bin = erts_realloc_binary(bin, dest_len+6);
	}
	if (bytes != buf) {
	    erts_free(ERTS_ALC_T_TMP, bytes);
	}
	return bin;
    } else {
	byte* bytes;

	bin = new_binary(p, (byte *)NULL, size);
	bytes = binary_bytes(bin);
	bytes[0] = VERSION_MAGIC;
	if ((endp = enc_term(NULL, Term, bytes+1, dflags, NULL))
	    == NULL) {
	    erts_exit(ERTS_ERROR_EXIT, "%s, line %d: bad term: %x\n",
		     __FILE__, __LINE__, Term);
	}
	real_size = endp - bytes;
	if (real_size > size) {
	    erts_exit(ERTS_ERROR_EXIT, "%s, line %d: buffer overflow: %d word(s)\n",
		     __FILE__, __LINE__, endp - (bytes + size));
	}
	return erts_realloc_binary(bin, real_size);
    }
}

Eterm
erts_term_to_binary(Process* p, Eterm Term, int level, Uint64 flags) {
    Uint size = 0;
    switch (encode_size_struct_int(NULL, NULL, Term, flags, NULL, &size)) {
    case ERTS_EXT_SZ_SYSTEM_LIMIT:
        return THE_NON_VALUE;
    case ERTS_EXT_SZ_YIELD:
        ERTS_INTERNAL_ERROR("Unexpected yield");
    case ERTS_EXT_SZ_OK:
        break;
    }
    size++; /* VERSION_MAGIC */;
    return erts_term_to_binary_simple(p, Term, size, level, flags);
}

/* Define EXTREME_TTB_TRAPPING for testing in dist.h */

#ifndef EXTREME_TTB_TRAPPING
#define TERM_TO_BINARY_COMPRESS_CHUNK (1 << 18)
#else
#define TERM_TO_BINARY_COMPRESS_CHUNK 10
#endif
#define TERM_TO_BINARY_MEMCPY_FACTOR 8

static int ttb_context_destructor(Binary *context_bin)
{
    TTBContext *context = ERTS_MAGIC_BIN_DATA(context_bin);
    if (context->alive) {
	context->alive = 0;
	switch (context->state) {
	case TTBSize:
	    DESTROY_SAVED_WSTACK(&context->s.sc.wstack);
	    break;
	case TTBEncode:
	    DESTROY_SAVED_WSTACK(&context->s.ec.wstack);
	    if (context->s.ec.result_bin != NULL) { /* Set to NULL if ever made alive! */
		ASSERT(erts_refc_read(&(context->s.ec.result_bin->intern.refc),1));
		erts_bin_free(context->s.ec.result_bin);
		context->s.ec.result_bin = NULL;
	    }
            if (context->s.ec.iov)
                erts_free(ERTS_ALC_T_T2B_VEC, context->s.ec.iov);
	    break;
	case TTBCompress:
	    erl_zlib_deflate_finish(&(context->s.cc.stream));

	    if (context->s.cc.destination_bin != NULL) { /* Set to NULL if ever made alive! */
		ASSERT(erts_refc_read(&(context->s.cc.destination_bin->intern.refc),1));
		erts_bin_free(context->s.cc.destination_bin);
		context->s.cc.destination_bin = NULL;
	    }
	    
	    if (context->s.cc.result_bin != NULL) { /* Set to NULL if ever made alive! */
		ASSERT(erts_refc_read(&(context->s.cc.result_bin->intern.refc),1));
		erts_bin_free(context->s.cc.result_bin);
		context->s.cc.result_bin = NULL;
	    }
	    break;
	}
    }
    return 1;
}

Uint
erts_ttb_iov_size(int use_termv, Sint vlen, Uint fragments)
{
    Uint sz;
    ASSERT(vlen > 0);
    ASSERT(fragments > 0);
    sz = sizeof(SysIOVec)*vlen;
    sz += sizeof(ErlDrvBinary *)*vlen;
    if (use_termv)
        sz += sizeof(Eterm)*vlen;
    sz += sizeof(ErlIOVec *)*fragments;
    sz += sizeof(ErlIOVec)*fragments;
    ASSERT(sz % sizeof(void*) == 0);
    return sz;
}

void
erts_ttb_iov_init(TTBEncodeContext *ctx, int use_termv, char *ptr,
                  Sint vlen, Uint fragments, Uint fragment_size)
{
    ctx->vlen = 0;
    ctx->size = 0;
    
    ctx->iov = (SysIOVec *) ptr;
    ptr += sizeof(SysIOVec)*vlen;
    ASSERT(((UWord) ptr) % sizeof(void *) == 0);
    
    ctx->binv = (ErlDrvBinary **) ptr;
    ptr += sizeof(ErlDrvBinary *)*vlen;

    if (!use_termv)
        ctx->termv = NULL;
    else {
        ctx->termv = (Eterm *) ptr;
        ptr += sizeof(Eterm)*vlen;
    }
    
    ctx->fragment_eiovs = (ErlIOVec *) ptr;
    ptr += sizeof(ErlIOVec)*fragments;
    ASSERT(((UWord) ptr) % sizeof(void *) == 0);
    
    ctx->frag_ix = -1;
    ctx->fragment_size = fragment_size;

#ifdef DEBUG
    ctx->cptr = NULL;
    ctx->debug_fragments = fragments;
    ctx->debug_vlen = vlen;
#endif
}

static Eterm erts_term_to_binary_int(Process* p, Sint bif_ix, Eterm Term, Eterm opts,
                                     int level, Uint64 dflags, Binary *context_b,
                                     int iovec, Uint fragment_size)
{
    Eterm *hp;
    Eterm res;
    Eterm c_term;
#ifndef EXTREME_TTB_TRAPPING
    Sint reds = (Sint) (ERTS_BIF_REDS_LEFT(p) * TERM_TO_BINARY_LOOP_FACTOR);
#else
    Sint reds = 20; /* For testing */
#endif
    Sint initial_reds = reds; 
    TTBContext c_buff;
    TTBContext *context = &c_buff;

    ASSERT(bif_ix > 0 && IS_USMALL(!0, bif_ix));
    ASSERT(bif_ix == BIF_term_to_binary_1 || bif_ix == BIF_term_to_binary_2
           || bif_ix == BIF_term_to_iovec_1 || bif_ix == BIF_term_to_iovec_2);
    
#define EXPORT_CONTEXT()						\
    do {								\
	if (context_b == NULL) {					\
	    context_b = erts_create_magic_binary(sizeof(TTBContext),    \
                                                 ttb_context_destructor);\
	    context =  ERTS_MAGIC_BIN_DATA(context_b);			\
	    sys_memcpy(context,&c_buff,sizeof(TTBContext));		\
	}								\
    } while (0)

#define RETURN_STATE()							\
    do {								\
	hp = HAlloc(p, ERTS_MAGIC_REF_THING_SIZE + 1 + 4);              \
	c_term = erts_mk_magic_ref(&hp, &MSO(p), context_b);            \
	res = TUPLE4(hp, Term, opts, c_term, make_small(bif_ix));       \
	BUMP_ALL_REDS(p);                                               \
	return res;							\
    } while (0);

    if (context_b == NULL) {
	/* Setup enough to get started */
	context->state = TTBSize;
	context->alive = 1;
        ERTS_INIT_TTBSizeContext(&context->s.sc, dflags);
	context->s.sc.level = level;
        context->s.sc.fragment_size = fragment_size;
        if (!level) {
            context->s.sc.vlen = iovec ? 0 : -1;
            context->s.sc.iovec = iovec;
        }
        else {
            context->s.sc.vlen = -1;
            context->s.sc.iovec = 0;
        }
    } else {
	context = ERTS_MAGIC_BIN_DATA(context_b);
    }

    /* Initialization done, now we will go through the states */
    for (;;) {
	switch (context->state) {
	case TTBSize:
	    {
		Uint size, fragments = 1;
		Binary *result_bin;
		int level = context->s.sc.level;
                Sint vlen;
                iovec = context->s.sc.iovec;
                fragment_size = context->s.sc.fragment_size;
		size = 1; /* VERSION_MAGIC */
                switch (encode_size_struct_int(&context->s.sc, NULL, Term,
                                               context->s.sc.dflags, &reds,
                                               &size)) {
                case ERTS_EXT_SZ_SYSTEM_LIMIT:
                    BUMP_REDS(p, (initial_reds - reds) / TERM_TO_BINARY_LOOP_FACTOR);
                    return THE_NON_VALUE;
                case ERTS_EXT_SZ_YIELD:
		    EXPORT_CONTEXT();
		    /* Same state */
		    RETURN_STATE();
                case ERTS_EXT_SZ_OK:
                    break;
		}
		/* Move these to next state */
		dflags = context->s.sc.dflags;
                vlen = context->s.sc.vlen;
		if (vlen >= 0) {
                    Uint total_size = size + context->s.sc.extra_size;
                    fragments = (total_size - 1)/fragment_size + 1;
                    vlen += 3*fragments;
                    ASSERT(vlen);
                }
                else if (size <= ERL_ONHEAP_BIN_LIMIT) {
		    /* Finish in one go */
		    res = erts_term_to_binary_simple(p, Term, size, 
						     level, dflags);
                    if (iovec) {
                        Eterm *hp = HAlloc(p, 2);
                        res = CONS(hp, res, NIL);
                    }
		    BUMP_REDS(p, 1);
		    return res;
		}

		result_bin = erts_bin_nrml_alloc(size);
		result_bin->orig_bytes[0] = (byte)VERSION_MAGIC;
		/* Next state immediately, no need to export context */
		context->state = TTBEncode;
                ERTS_INIT_TTBEncodeContext(&context->s.ec, dflags);
		context->s.ec.level = level;
		context->s.ec.result_bin = result_bin;
                context->s.ec.iovec = iovec;
                if (vlen >= 0) {
                    Uint sz = erts_ttb_iov_size(!0, vlen, fragments);
                    char *ptr = (char *) erts_alloc(ERTS_ALC_T_T2B_VEC, sz);
                    erts_ttb_iov_init(&context->s.ec, !0, ptr, vlen,
                                      fragments, fragment_size);
                    context->s.ec.cptr = (byte *) &result_bin->orig_bytes[0];
                }
		break;
	    }
	case TTBEncode:
	    {
		byte *endp, *tmp;
		byte *bytes = (byte *) context->s.ec.result_bin->orig_bytes;
		size_t real_size;
		Binary *result_bin;
                Sint realloc_offset;
                Uint fragments;

		dflags = context->s.ec.dflags;
		if (enc_term_int(&context->s.ec, NULL,Term, bytes+1, dflags,
                                 NULL, &reds, &endp) < 0) {
		    EXPORT_CONTEXT();
		    RETURN_STATE();
		}
		real_size = endp - bytes;
                tmp = (byte *) &context->s.ec.result_bin->orig_bytes[0];
		result_bin = erts_bin_realloc(context->s.ec.result_bin,real_size);
                realloc_offset = (byte *) &result_bin->orig_bytes[0] - tmp;
		level = context->s.ec.level;
		BUMP_REDS(p, (initial_reds - reds) / TERM_TO_BINARY_LOOP_FACTOR);
		if (level == 0 || real_size < 6) { /* We are done */
                    Sint cbin_refc_diff;
                    Eterm result, rb_term, *hp, *hp_end;
                    Uint hsz;
                    int ix;
                    SysIOVec *iov;
                    Eterm *termv;
		return_normal:
                    fragments = context->s.ec.frag_ix + 1;
		    context->s.ec.result_bin = NULL;
		    context->alive = 0;
		    if (context_b && erts_refc_read(&context_b->intern.refc,0) == 0) {
			erts_bin_free(context_b);
		    }
                    if (!context->s.ec.iov) {
                        hsz = PROC_BIN_SIZE + (iovec ? 2 : 0);
                        hp = HAlloc(p, hsz);
                        result = erts_build_proc_bin(&MSO(p), hp, result_bin);
                        if (iovec) {
                            hp += PROC_BIN_SIZE;
                            result = CONS(hp, result, NIL);
                        }
                        return result;
                    }
                    iovec = context->s.ec.iovec;
                    ASSERT(iovec);
                    iov = context->s.ec.iov;
                    termv = context->s.ec.termv;
                    ASSERT(context->s.ec.vlen <= context->s.ec.debug_vlen);
                    ASSERT(fragments <= context->s.ec.debug_fragments);                    
                    /* first two elements should be unused */
                    ASSERT(context->s.ec.vlen >= 3*fragments);
                    ASSERT(!iov[0].iov_base && !iov[0].iov_len);
                    ASSERT(!iov[1].iov_base && !iov[1].iov_len);

                    hsz = (2 /* cons */
                           + (PROC_BIN_SIZE > ERL_SUB_BIN_SIZE
                              ? PROC_BIN_SIZE
                              : ERL_SUB_BIN_SIZE)); /* max size per vec */
                    hsz *= context->s.ec.vlen - 2*fragments; /* number of vecs */
                    hp = HAlloc(p, hsz);
                    hp_end = hp + hsz;
                    rb_term = THE_NON_VALUE;
                    result = NIL;
                    ASSERT(erts_refc_read(&result_bin->intern.refc, 1) == 1);
                    cbin_refc_diff = -1;
                    for (ix = context->s.ec.vlen - 1; ix > 1; ix--) {
                        Eterm bin_term, pb_term;
                        Uint pb_size;
                        ProcBin *pb;
                        SysIOVec *iovp = &iov[ix];
                        if (!iovp->iov_base)
                            continue; /* empty slot for header */
                        pb_term = termv[ix];
                        if (is_value(pb_term)) {
                            pb_size = binary_size(pb_term);
                            pb = (ProcBin *) binary_val(pb_term);
                        }
                        else {
                            iovp->iov_base = (void *) (((byte *) iovp->iov_base)
                                                       + realloc_offset);
                            pb_size = result_bin->orig_size;
                            if (is_non_value(rb_term))
                                pb = NULL;
                            else {
                                pb = (ProcBin *) binary_val(rb_term);
                                pb_term = rb_term;
                            }
                        }
                        /*
                         * We intentionally avoid using sub binaries
                         * since the GC might convert those to heap
                         * binaries and by this ruin the nice preparation
                         * for usage of this data as I/O vector in
                         * nifs/drivers.
                         */
                        if (is_value(pb_term) && iovp->iov_len == pb_size)
                            bin_term = pb_term;
                        else {
                            Binary *bin;
                            if (is_value(pb_term)) {
                                bin = ((ProcBin *) binary_val(pb_term))->val;
                                erts_refc_inc(&bin->intern.refc, 2);
                            }
                            else {
                                bin = result_bin;
                                cbin_refc_diff++;
                            }
                            pb = (ProcBin *) (char *) hp;
                            hp += PROC_BIN_SIZE;
                            pb->thing_word = HEADER_PROC_BIN;
                            pb->size = (Uint) iovp->iov_len;
                            pb->next = MSO(p).first;
                            MSO(p).first = (struct erl_off_heap_header*) pb;
                            pb->val = bin;
                            pb->bytes = (byte*) iovp->iov_base;
                            pb->flags = 0;
                            OH_OVERHEAD(&MSO(p), pb->size / sizeof(Eterm));
                            bin_term = make_binary(pb);
                        }
                        result = CONS(hp, bin_term, result);
                        hp += 2;
                    }
                    ASSERT(hp <= hp_end);
                    HRelease(p, hp_end, hp);
                    context->s.ec.iov = NULL;
                    erts_free(ERTS_ALC_T_T2B_VEC, iov);
                    if (cbin_refc_diff) {
                        ASSERT(cbin_refc_diff >= -1);
                        if (cbin_refc_diff > 0)
                            erts_refc_add(&result_bin->intern.refc,
                                          cbin_refc_diff, 1);
                        else
                            erts_bin_free(result_bin);
                    }
                    return result;
		}
		/* Continue with compression... */
		/* To make absolutely sure that zlib does not barf on a reallocated context, 
		   we make sure it's "exported" before doing anything compession-like */
		EXPORT_CONTEXT();
		bytes = (byte *) result_bin->orig_bytes; /* result_bin is reallocated */
		if (erl_zlib_deflate_start(&(context->s.cc.stream),bytes+1,real_size-1,level) 
		    != Z_OK) {
		    goto return_normal;
		}
		context->state = TTBCompress;
		context->s.cc.real_size = real_size;
		context->s.cc.result_bin = result_bin;

		result_bin = erts_bin_nrml_alloc(real_size);
		result_bin->orig_bytes[0] = (byte) VERSION_MAGIC;

		context->s.cc.destination_bin = result_bin;
		context->s.cc.dest_len = 0;
		context->s.cc.dbytes = (byte *) result_bin->orig_bytes+6;
		break;
	    }
	case TTBCompress:
	    {
		uLongf tot_dest_len = context->s.cc.real_size - 6;
		uLongf left = (tot_dest_len - context->s.cc.dest_len);
		uLongf this_time = (left > TERM_TO_BINARY_COMPRESS_CHUNK) ?  
		    TERM_TO_BINARY_COMPRESS_CHUNK : 
		    left;
		Binary *result_bin;
		ProcBin *pb;
		Uint max = (ERTS_BIF_REDS_LEFT(p) *  TERM_TO_BINARY_COMPRESS_CHUNK) / CONTEXT_REDS;

		if (max < this_time) {
		    this_time = max + 1; /* do not set this_time to 0 */
		}

		res = erl_zlib_deflate_chunk(&(context->s.cc.stream), context->s.cc.dbytes, &this_time);
		context->s.cc.dbytes += this_time;
		context->s.cc.dest_len += this_time;
		switch (res) {
		case Z_OK:
		    if (context->s.cc.dest_len >= tot_dest_len) {
			goto no_use_compressing;
		    }
		    RETURN_STATE();
		case Z_STREAM_END:
		    {
			byte *dbytes = (byte *) context->s.cc.destination_bin->orig_bytes + 1;

			dbytes[0] = COMPRESSED;
			put_int32(context->s.cc.real_size-1,dbytes+1);
			erl_zlib_deflate_finish(&(context->s.cc.stream));
			result_bin = erts_bin_realloc(context->s.cc.destination_bin,
						      context->s.cc.dest_len+6);
			context->s.cc.destination_bin = NULL;
			ASSERT(erts_refc_read(&result_bin->intern.refc, 1));
			erts_bin_free(context->s.cc.result_bin);
			context->s.cc.result_bin = NULL;
			context->alive = 0;
			BUMP_REDS(p, (this_time * CONTEXT_REDS) / TERM_TO_BINARY_COMPRESS_CHUNK);
			if (context_b && erts_refc_read(&context_b->intern.refc,0) == 0) {
			    erts_bin_free(context_b);
			}
			return erts_build_proc_bin(&MSO(p),
						   HAlloc(p, PROC_BIN_SIZE),
                                                   result_bin);
		    }
		default: /* Compression error, revert to uncompressed binary (still in 
			    context) */
		no_use_compressing:
		    result_bin = context->s.cc.result_bin;
		    context->s.cc.result_bin = NULL;
		    pb = (ProcBin *) HAlloc(p, PROC_BIN_SIZE);
		    pb->thing_word = HEADER_PROC_BIN;
		    pb->size = context->s.cc.real_size;
		    pb->next = MSO(p).first;
		    MSO(p).first = (struct erl_off_heap_header*)pb;
		    pb->val = result_bin;
		    pb->bytes = (byte*) result_bin->orig_bytes;
		    pb->flags = 0;
		    OH_OVERHEAD(&(MSO(p)), pb->size / sizeof(Eterm));
		    ASSERT(erts_refc_read(&result_bin->intern.refc, 1));
		    erl_zlib_deflate_finish(&(context->s.cc.stream));
		    erts_bin_free(context->s.cc.destination_bin);
		    context->s.cc.destination_bin = NULL;
		    context->alive = 0;
		    BUMP_REDS(p, (this_time * CONTEXT_REDS) / TERM_TO_BINARY_COMPRESS_CHUNK);
		    if (context_b && erts_refc_read(&context_b->intern.refc,0) == 0) {
			erts_bin_free(context_b);
		    }
		    return make_binary(pb);
		}
	    }
	}
    }
#undef EXPORT_CONTEXT
#undef RETURN_STATE
}			








/*
 * This function fills ext with the external format of atom.
 * If it's an old atom we just supply an index, otherwise
 * we insert the index _and_ the entire atom. This way the receiving side
 * does not have to perform an hash on the etom to locate it, and
 * we save a lot of space on the wire.
 */

static byte*
enc_atom(ErtsAtomCacheMap *acmp, Eterm atom, byte *ep, Uint64 dflags)
{
    int iix;
    int len;
    const int utf8_atoms = (int) (dflags & DFLAG_UTF8_ATOMS);

    ASSERT(is_atom(atom));

    if (dflags & DFLAG_ETS_COMPRESSED) {
	Uint aval = atom_val(atom);
	ASSERT(aval < (1<<24));
	if (aval >= (1 << 16)) {
	    *ep++ = ATOM_INTERNAL_REF3;
	    put_int24(aval, ep);
	    ep += 3;
	}
	else {
	    *ep++ = ATOM_INTERNAL_REF2;
	    put_int16(aval, ep);
	    ep += 2;
	}
	return ep;
    }

    /*
     * term_to_binary/1,2 and the initial distribution message
     * don't use the cache.
     */

    iix = get_iix_acache_map(acmp, atom, dflags);
    if (iix < 0) {
	Atom *a = atom_tab(atom_val(atom));
	len = a->len;
	if (utf8_atoms || a->latin1_chars < 0) {
	    if (len > 255) {
		*ep++ = ATOM_UTF8_EXT;
		put_int16(len, ep);
		ep += 2;
	    }
	    else {
		*ep++ = SMALL_ATOM_UTF8_EXT;
		put_int8(len, ep);
		ep += 1;
	    }
	    sys_memcpy((char *) ep, (char *) a->name, len);
	}
	else {
	    if (a->latin1_chars <= 255 && (dflags & DFLAG_SMALL_ATOM_TAGS)) {
		*ep++ = SMALL_ATOM_EXT;
		if (len == a->latin1_chars) {
		    sys_memcpy(ep+1, a->name, len);
		}
		else {
		    len = erts_utf8_to_latin1(ep+1, a->name, len);
		    ASSERT(len == a->latin1_chars);
		}
		put_int8(len, ep);
		ep++;
	    }
	    else {
		*ep++ = ATOM_EXT;
		if (len == a->latin1_chars) {
		    sys_memcpy(ep+2, a->name, len);
		}
		else {
		    len = erts_utf8_to_latin1(ep+2, a->name, len);
		    ASSERT(len == a->latin1_chars);
		}
		put_int16(len, ep);
		ep += 2;
	    }	    
	}
	ep += len;
	return ep;
    }

    /* The atom is referenced in the cache. */
    *ep++ = ATOM_CACHE_REF;
    put_int8(iix, ep);
    ep++;
    return ep;
}

/*
 * We use this atom as sysname in local pid/port/refs
 * for the ETS compressed format
 *
 */
#define INTERNAL_LOCAL_SYSNAME am_ErtsSecretAtom

static byte*
enc_pid(ErtsAtomCacheMap *acmp, Eterm pid, byte* ep, Uint64 dflags)
{
    Uint on, os;
    Eterm sysname = ((is_internal_pid(pid) && (dflags & DFLAG_ETS_COMPRESSED))
		      ? INTERNAL_LOCAL_SYSNAME : pid_node_name(pid));
    Uint32 creation = pid_creation(pid);

    *ep++ = NEW_PID_EXT;

    /* insert  atom here containing host and sysname  */
    ep = enc_atom(acmp, sysname, ep, dflags);

    on = pid_number(pid);
    os = pid_serial(pid);

    put_int32(on, ep);
    ep += 4;
    put_int32(os, ep);
    ep += 4;
    put_int32(creation, ep);
    ep += 4;
    return ep;
}

/* Expect an atom in plain text or cached */
static byte*
dec_atom(ErtsDistExternal *edep, byte* ep, Eterm* objp)
{
    Uint len;
    int n;
    ErtsAtomEncoding char_enc;

    switch (*ep++) {
    case ATOM_CACHE_REF:
	if (!(edep && (edep->flags & ERTS_DIST_EXT_ATOM_TRANS_TAB)))
	    goto error;
	n = get_int8(ep);
	ep++;
	if (n >= edep->attab.size)
	    goto error;
	ASSERT(is_atom(edep->attab.atom[n]));
	*objp = edep->attab.atom[n];
	break;
    case ATOM_EXT:
	len = get_int16(ep),
	ep += 2;
	char_enc = ERTS_ATOM_ENC_LATIN1;
        goto dec_atom_common;
    case SMALL_ATOM_EXT:
	len = get_int8(ep);
	ep++;
	char_enc = ERTS_ATOM_ENC_LATIN1;
	goto dec_atom_common;
    case ATOM_UTF8_EXT:
	len = get_int16(ep),
	ep += 2;
	char_enc = ERTS_ATOM_ENC_UTF8;
	goto dec_atom_common;
    case SMALL_ATOM_UTF8_EXT:
	len = get_int8(ep),
	ep++;
	char_enc = ERTS_ATOM_ENC_UTF8;
    dec_atom_common:
        if (edep && (edep->flags & ERTS_DIST_EXT_BTT_SAFE)) {
	    if (!erts_atom_get((char*)ep, len, objp, char_enc)) {
                goto error;
	    }
        } else {
	    Eterm atom = erts_atom_put(ep, len, char_enc, 0);
	    if (is_non_value(atom))
		goto error;
            *objp = atom;
        }
	ep += len;
	break;
    case ATOM_INTERNAL_REF2:
	n = get_int16(ep);
	ep += 2;
	if (n >= atom_table_size()) {
	    goto error;
	}
	*objp = make_atom(n);
	break;
    case ATOM_INTERNAL_REF3:
	n = get_int24(ep);
	ep += 3;
	if (n >= atom_table_size()) {
	    goto error;
	}
	*objp = make_atom(n);
	break;

    default:
    error:
	*objp = NIL;	/* Don't leave a hole in the heap */
	return NULL;
    }
    return ep;
}

static ERTS_INLINE ErlNode* dec_get_node(Eterm sysname, Uint32 creation, Eterm book)
{
    if (sysname == INTERNAL_LOCAL_SYSNAME)  /* && DFLAG_INTERNAL_TAGS */
	return erts_this_node;

    if (sysname == erts_this_node->sysname
	&& (creation == erts_this_node->creation || creation == ORIG_CREATION))
	return erts_this_node;

    return erts_find_or_insert_node(sysname,creation,book);
}

static byte*
dec_pid(ErtsDistExternal *edep, ErtsHeapFactory* factory, byte* ep,
        Eterm* objp, byte tag)
{
    Eterm sysname;
    Uint data;
    Uint num;
    Uint ser;
    Uint32 cre;
    ErlNode *node;

    *objp = NIL;		/* In case we fail, don't leave a hole in the heap */

    /* eat first atom */
    if ((ep = dec_atom(edep, ep, &sysname)) == NULL)
	return NULL;
    num = get_int32(ep);
    ep += 4;
    if (num > ERTS_MAX_PID_NUMBER)
	return NULL;
    ser = get_int32(ep);
    ep += 4;
    if (ser > ERTS_MAX_PID_SERIAL)
	return NULL;

    if (tag == PID_EXT) {
        cre = get_int8(ep);
        ep += 1;
        if (!is_tiny_creation(cre)) {
            return NULL;
        }
    } else {
        ASSERT(tag == NEW_PID_EXT);
        cre = get_int32(ep);
        ep += 4;
    }

    data = make_pid_data(ser, num);

    /*
     * We are careful to create the node entry only after all
     * validity tests are done.
     */
    node = dec_get_node(sysname, cre, make_boxed(factory->hp));

    if(node == erts_this_node) {
	*objp = make_internal_pid(data);
    } else {
	ExternalThing *etp = (ExternalThing *) factory->hp;
	factory->hp += EXTERNAL_THING_HEAD_SIZE + 1;

	etp->header = make_external_pid_header(1);
	etp->next = factory->off_heap->first;
	etp->node = node;
	etp->data.ui[0] = data;

	factory->off_heap->first = (struct erl_off_heap_header*) etp;
	*objp = make_external_pid(etp);
    }
    return ep;
}


#define ENC_TERM ((Eterm) 0)
#define ENC_ONE_CONS ((Eterm) 1)
#define ENC_PATCH_FUN_SIZE ((Eterm) 2)
#define ENC_BIN_COPY ((Eterm) 3)
#define ENC_MAP_PAIR ((Eterm) 4)
#define ENC_HASHMAP_NODE ((Eterm) 5)
#define ENC_LAST_ARRAY_ELEMENT ((Eterm) 6)

static byte*
enc_term(ErtsAtomCacheMap *acmp, Eterm obj, byte* ep, Uint64 dflags,
	 struct erl_off_heap_header** off_heap)
{
    byte *res;
    (void) enc_term_int(NULL, acmp, obj, ep, dflags, off_heap, NULL, &res);
    return res;
}

static int
enc_term_int(TTBEncodeContext* ctx, ErtsAtomCacheMap *acmp, Eterm obj, byte* ep,
             Uint64 dflags,
	     struct erl_off_heap_header** off_heap, Sint *reds, byte **res)
{
    DECLARE_WSTACK(s);
    Uint n;
    Uint i;
    Uint j;
    Uint* ptr;
    Eterm val;
    FloatDef f;
    Sint r = 0;
    int use_iov = 0;

    if (ctx) {
	WSTACK_CHANGE_ALLOCATOR(s, ERTS_ALC_T_SAVED_ESTACK);
	r = *reds;
        use_iov = !!ctx->iov;

	if (ctx->wstack.wstart) { /* restore saved stacks and byte pointer */
	    WSTACK_RESTORE(s, &ctx->wstack);
	    ep = ctx->ep;
	    obj = ctx->obj;
	    if (is_non_value(obj)) {
		goto outer_loop;
	    }
	}
    }

    goto L_jump_start;

 outer_loop:
    while (!WSTACK_ISEMPTY(s)) {
	obj = WSTACK_POP(s);

	switch (val = WSTACK_POP(s)) {
	case ENC_TERM:
	    break;
	case ENC_ONE_CONS:
	encode_one_cons:
	    {
		Eterm* cons = list_val(obj);
		Eterm tl;
                Uint len_cnt = WSTACK_POP(s);

		obj = CAR(cons);
		tl = CDR(cons);
                if (is_list(tl)) {
                    len_cnt++;
                    WSTACK_PUSH3(s, len_cnt, ENC_ONE_CONS, tl);
                }
                else {
                    byte* list_lenp = (byte*) WSTACK_POP(s);
		    ASSERT(list_lenp[-1] == LIST_EXT);
                    put_int32(len_cnt, list_lenp);

                    WSTACK_PUSH2(s, ENC_TERM, tl);
                }
	    }
	    break;
	case ENC_PATCH_FUN_SIZE:
	    {
		byte* size_p = (byte *) obj;
		put_int32(ep - size_p, size_p);
	    }
	    goto outer_loop;
	case ENC_BIN_COPY: {
	    Uint bits = (Uint)obj;
	    Uint bitoffs = WSTACK_POP(s);
	    byte* bytes = (byte*) WSTACK_POP(s);
	    byte* dst = (byte*) WSTACK_POP(s);
	    if (bits > r * (TERM_TO_BINARY_MEMCPY_FACTOR * 8)) {
		Uint n = r * TERM_TO_BINARY_MEMCPY_FACTOR;
		WSTACK_PUSH5(s, (UWord)(dst + n), (UWord)(bytes + n), bitoffs,
			     ENC_BIN_COPY, bits - 8*n);
		bits = 8*n;
		copy_binary_to_buffer(dst, 0, bytes, bitoffs, bits);
		obj = THE_NON_VALUE;
		r = 0; /* yield */
		break;
	    } else {
		copy_binary_to_buffer(dst, 0, bytes, bitoffs, bits);
		r -= bits / (TERM_TO_BINARY_MEMCPY_FACTOR * 8);
		goto outer_loop;
	    }
	}
	case ENC_MAP_PAIR: {
	    Uint pairs_left = obj;
	    Eterm *vptr = (Eterm*) WSTACK_POP(s);
	    Eterm *kptr = (Eterm*) WSTACK_POP(s);

	    obj = *kptr;
	    if (--pairs_left > 0) {
		WSTACK_PUSH4(s, (UWord)(kptr+1), (UWord)(vptr+1),
			     ENC_MAP_PAIR, pairs_left);
	    }
	    WSTACK_PUSH2(s, ENC_TERM, *vptr);
	    break;
	}
	case ENC_HASHMAP_NODE:
	    if (is_list(obj)) { /* leaf node [K|V] */
		ptr = list_val(obj);
		WSTACK_PUSH2(s, ENC_TERM, CDR(ptr));
		obj = CAR(ptr);
	    }
	    break;
	case ENC_LAST_ARRAY_ELEMENT:
	    /* obj is the tuple */
	    {
		Eterm* ptr = (Eterm *) obj;
		obj = *ptr;
	    }
	    break;
	default:		/* ENC_LAST_ARRAY_ELEMENT+1 and upwards */
	    {
		Eterm* ptr = (Eterm *) obj;
		obj = *ptr++;
		WSTACK_PUSH2(s, val-1, (UWord)ptr);
	    }
	    break;
	}

	if (ctx && --r <= 0) {
	    *reds = 0;
	    ctx->obj = obj;
	    ctx->ep = ep;
	    WSTACK_SAVE(s, &ctx->wstack);
	    return -1;
	}

    L_jump_start:
	switch(tag_val_def(obj)) {
	case NIL_DEF:
	    *ep++ = NIL_EXT;
	    break;

	case ATOM_DEF:
	    ep = enc_atom(acmp,obj,ep,dflags);
	    break;

	case SMALL_DEF:
	    {
		/* From R14B we no longer restrict INTEGER_EXT to 28 bits,
		 * as done earlier for backward compatibility reasons. */
		Sint val = signed_val(obj);

		if ((Uint)val < 256) {
		    *ep++ = SMALL_INTEGER_EXT;
		    put_int8(val, ep);
		    ep++;
		} else if (sizeof(Sint) == 4 || IS_SSMALL32(val)) {
		    *ep++ = INTEGER_EXT;
		    put_int32(val, ep);
		    ep += 4;
		} else {
		    DeclareTmpHeapNoproc(tmp_big,2);
		    Eterm big;
		    UseTmpHeapNoproc(2);
		    big = small_to_big(val, tmp_big);
		    *ep++ = SMALL_BIG_EXT;
		    n = big_bytes(big);
		    ASSERT(n < 256);
		    put_int8(n, ep);
		    ep += 1;
		    *ep++ = big_sign(big);
		    ep = big_to_bytes(big, ep);
		    UnUseTmpHeapNoproc(2);
		}
	    }
	    break;

	case BIG_DEF:
	    {
		int sign = big_sign(obj);
		n = big_bytes(obj);
		if (sizeof(Sint)==4 && n<=4) {
		    Uint dig = big_digit(obj,0);		   
		    Sint val = sign ? -dig : dig;
		    if ((val<0) == sign) {
			*ep++ = INTEGER_EXT;
			put_int32(val, ep);
			ep += 4;
			break;
		    }
		}
		if (n < 256) {
		    *ep++ = SMALL_BIG_EXT;
		    put_int8(n, ep);
		    ep += 1;
		}
		else {
		    *ep++ = LARGE_BIG_EXT;
		    put_int32(n, ep);
		    ep += 4;
		}
		*ep++ = sign;
		ep = big_to_bytes(obj, ep);
	    }
	    break;

	case PID_DEF:
	case EXTERNAL_PID_DEF:
	    ep = enc_pid(acmp, obj, ep, dflags);
	    break;

	case REF_DEF:
	case EXTERNAL_REF_DEF: {
	    Uint32 *ref_num;
	    Eterm sysname = (((dflags & DFLAG_ETS_COMPRESSED) && is_internal_ref(obj))
			     ? INTERNAL_LOCAL_SYSNAME : ref_node_name(obj));
            Uint32 creation = ref_creation(obj);

	    ASSERT(dflags & DFLAG_EXTENDED_REFERENCES);

	    erts_magic_ref_save_bin(obj);

            *ep++ = NEWER_REFERENCE_EXT;
	    i = ref_no_numbers(obj);
	    put_int16(i, ep);
	    ep += 2;
	    ep = enc_atom(acmp, sysname, ep, dflags);
            put_int32(creation, ep);
            ep += 4;
	    ref_num = ref_numbers(obj);
	    for (j = 0; j < i; j++) {
		put_int32(ref_num[j], ep);
		ep += 4;
	    }
	    break;
	}
	case PORT_DEF:
	case EXTERNAL_PORT_DEF: {
	    Eterm sysname = (((dflags & DFLAG_ETS_COMPRESSED) && is_internal_port(obj))
			     ? INTERNAL_LOCAL_SYSNAME : port_node_name(obj));
            Uint32 creation = port_creation(obj);

            *ep++ = NEW_PORT_EXT;
	    ep = enc_atom(acmp, sysname, ep, dflags);
	    j = port_number(obj);
	    put_int32(j, ep);
	    ep += 4;
            put_int32(creation, ep);
            ep += 4;
	    break;
	}
	case LIST_DEF:
	    {
		if (is_external_string(obj, &i)) {
		    *ep++ = STRING_EXT;
		    put_int16(i, ep);
		    ep += 2;
		    while (is_list(obj)) {
			Eterm* cons = list_val(obj);
			*ep++ = unsigned_val(CAR(cons));
			obj = CDR(cons);
		    }
		    r -= i;
		} else {
		    r -= i/2;
		    *ep++ = LIST_EXT;
                    /* Patch list length when we find end of list */
                    WSTACK_PUSH2(s, (UWord)ep, 1);
		    ep += 4;
		    goto encode_one_cons;
		}
	    }
	    break;

	case TUPLE_DEF:
	    ptr = tuple_val(obj);
	    i = arityval(*ptr);
	    ptr++;
	    if (i <= 0xff) {
		*ep++ = SMALL_TUPLE_EXT;
		put_int8(i, ep);
		ep += 1;
	    } else  {
		*ep++ = LARGE_TUPLE_EXT;
		put_int32(i, ep);
		ep += 4;
	    }
	    if (i > 0) {
		WSTACK_PUSH2(s, ENC_LAST_ARRAY_ELEMENT+i-1, (UWord)ptr);
	    }
	    break;

	case MAP_DEF:
	    if (is_flatmap(obj)) {
		flatmap_t *mp = (flatmap_t*)flatmap_val(obj);
		Uint size = flatmap_get_size(mp);

		*ep++ = MAP_EXT;
		put_int32(size, ep); ep += 4;

		if (size > 0) {
		    Eterm *kptr = flatmap_get_keys(mp);
		    Eterm *vptr = flatmap_get_values(mp);

		    WSTACK_PUSH4(s, (UWord)kptr, (UWord)vptr,
				 ENC_MAP_PAIR, size);
		}
	    } else {
		Eterm hdr;
		Uint node_sz;
		ptr = boxed_val(obj);
		hdr = *ptr;
		ASSERT(is_header(hdr));
		switch(hdr & _HEADER_MAP_SUBTAG_MASK) {
		case HAMT_SUBTAG_HEAD_ARRAY:
		    *ep++ = MAP_EXT;
		    ptr++;
		    put_int32(*ptr, ep); ep += 4;
		    node_sz = 16;
		    break;
		case HAMT_SUBTAG_HEAD_BITMAP:
		    *ep++ = MAP_EXT;
		    ptr++;
		    put_int32(*ptr, ep); ep += 4;
		    /*fall through*/
		case HAMT_SUBTAG_NODE_BITMAP:
		    node_sz = hashmap_bitcount(MAP_HEADER_VAL(hdr));
		    ASSERT(node_sz < 17);
		    break;
		default:
		    erts_exit(ERTS_ERROR_EXIT, "bad header\r\n");
		}

		ptr++;
		WSTACK_RESERVE(s, node_sz*2);
		while(node_sz--) {
		    WSTACK_FAST_PUSH(s, ENC_HASHMAP_NODE);
		    WSTACK_FAST_PUSH(s, *ptr++);
		}
	    }
	    break;
	case FLOAT_DEF:
	    GET_DOUBLE(obj, f);
	    if (dflags & DFLAG_NEW_FLOATS) {
		*ep++ = NEW_FLOAT_EXT;
#if defined(WORDS_BIGENDIAN) || defined(DOUBLE_MIDDLE_ENDIAN)
		put_int32(f.fw[0], ep);
		ep += 4;
		put_int32(f.fw[1], ep);
#else
		put_int32(f.fw[1], ep);
		ep += 4;
		put_int32(f.fw[0], ep);
#endif		
		ep += 4;
	    } else {
		*ep++ = FLOAT_EXT;

		/* now the erts_snprintf which does the work */
		i = sys_double_to_chars(f.fd, (char*) ep, (size_t)31);

		/* Don't leave garbage after the float!  (Bad practice in general,
		 * and Purify complains.)
		 */
		sys_memset(ep+i, 0, 31-i);
		ep += 31;
	    }
	    break;

	case BINARY_DEF:
	    {
		Uint bitoffs;
		Uint bitsize;
		byte* bytes;
		byte* data_dst;
                Uint off_heap_bytesize = 0;
                Uint off_heap_tail;
                Eterm pb_term;
                Binary *pb_val;

                ASSERT(!(dflags & DFLAG_PENDING_CONNECT) || (ctx && ctx->iov));
    
		ERTS_GET_BINARY_BYTES(obj, bytes, bitoffs, bitsize);
                if (use_iov) {
                    if (bitoffs == 0) {
                        ProcBin* pb = (ProcBin*) binary_val(obj);
                        off_heap_bytesize = pb->size;
                        if (off_heap_bytesize <= ERL_ONHEAP_BIN_LIMIT)
                            off_heap_bytesize = 0;
                        else {
                            pb_term = obj;
                            if (pb->thing_word == HEADER_SUB_BIN) {
                                ErlSubBin* sub = (ErlSubBin*)pb;
                                pb_term = sub->orig;
                                pb = (ProcBin*) binary_val(pb_term);
                            }
                            if (pb->thing_word != HEADER_PROC_BIN)
                                off_heap_bytesize = 0;
                            else {
                                if (pb->flags) {
                                    char* before_realloc = pb->val->orig_bytes; 
                                    erts_emasculate_writable_binary(pb);
                                    bytes += (pb->val->orig_bytes - before_realloc);
                                    ASSERT((byte *) &pb->val->orig_bytes[0] <= bytes
                                           && bytes < ((byte *) &pb->val->orig_bytes[0]
                                                       + pb->val->orig_size));
                                }
                                pb_val = pb->val;
                            }
                        }
                    }
                }
		else if (dflags & DFLAG_ETS_COMPRESSED) {
		    ProcBin* pb = (ProcBin*) binary_val(obj);
		    Uint bytesize = pb->size;
		    if (pb->thing_word == HEADER_SUB_BIN) {
			ErlSubBin* sub = (ErlSubBin*)pb;
			pb = (ProcBin*) binary_val(sub->orig);
			ASSERT(bytesize == sub->size);
			bytesize += (bitoffs + bitsize + 7) / 8;
		    }
		    if (pb->thing_word == HEADER_PROC_BIN
			&& heap_bin_size(bytesize) > PROC_BIN_SIZE) {
			ProcBin tmp;
			if (bitoffs || bitsize) {
			    *ep++ = BIT_BINARY_INTERNAL_REF;
			    *ep++ = bitoffs;
			    *ep++ = bitsize;
			}
			else {
			    *ep++ = BINARY_INTERNAL_REF;
			}
			if (pb->flags) {
			    char* before_realloc = pb->val->orig_bytes; 
			    erts_emasculate_writable_binary(pb);
			    bytes += (pb->val->orig_bytes - before_realloc);
			}
			erts_refc_inc(&pb->val->intern.refc, 2);

			sys_memcpy(&tmp, pb, sizeof(ProcBin));
			tmp.next = *off_heap;
			tmp.bytes = bytes;
			tmp.size = bytesize;
			sys_memcpy(ep, &tmp, sizeof(ProcBin));
			*off_heap = (struct erl_off_heap_header*) ep;
			ep += sizeof(ProcBin);
			break;
		    }
		}
		if (bitsize == 0) {
		    /* Plain old byte-sized binary. */
		    *ep++ = BINARY_EXT;
		    j = binary_size(obj);
		    put_int32(j, ep);
		    ep += 4;
                    if (off_heap_bytesize)
                        off_heap_tail = 0;
                    else {
                        data_dst = ep;
                        ep += j;
                    }
		} else if (dflags & DFLAG_BIT_BINARIES) {
		    /* Bit-level binary. */
                    if (dflags & DFLAG_PENDING_CONNECT) {
                        j = off_heap_bytesize;
                        if (!j) {
                            pb_val = NULL;
                            pb_term = THE_NON_VALUE;
                            j = binary_size(obj);
                        }
                        data_dst = hopefull_bit_binary(ctx, &ep, pb_val, pb_term,
                                                       bytes, bitoffs, bitsize, j);
                        if (!data_dst)
                            break; /* off heap binary referred... */
                        ASSERT(!off_heap_bytesize);
                        off_heap_tail = 0;
                        /*
                         * Trailing bits already written by hopefull_bit_binary();
                         * now go copy all whole octets...
                         */
                        bitsize = 0;
                    }
                    else {
                        *ep++ = BIT_BINARY_EXT;
                        j = binary_size(obj);
                        put_int32((j+1), ep);
                        ep += 4;
                        *ep++ = bitsize;
                        if (off_heap_bytesize) {
                            /* trailing bits */
                            ep[0] = 0;
                            copy_binary_to_buffer(ep, 0, bytes + j, 0, bitsize);
                            off_heap_tail = 1;
                        }
                        else {
                            ep[j] = 0;	/* Zero unused bits at end of binary */
                            data_dst = ep;
                            ep += j + 1;
                        }
                    }
		} else {
		    /*
		     * Bit-level binary, but the receiver doesn't support it.
		     * Build a tuple instead.
		     */
		    *ep++ = SMALL_TUPLE_EXT;
		    *ep++ = 2;
		    *ep++ = BINARY_EXT;
		    j = binary_size(obj);
		    put_int32((j+1), ep);
		    ep += 4;
                    
                    if (off_heap_bytesize) {
                        /* trailing bits */
                        ep[0] = 0;
                        copy_binary_to_buffer(ep, 0, bytes + j, 0, bitsize);
                        ep[1] = SMALL_INTEGER_EXT;
                        ep[2] = bitsize;
                        off_heap_tail = 3;
                    }
                    else {
                        ep[j] = 0; /* Zero unused bits at end of binary */
                        data_dst = ep;
                        ep += j+1;
                        *ep++ = SMALL_INTEGER_EXT;
                        *ep++ = bitsize;
                    }
		}
                if (off_heap_bytesize) {
                    ASSERT(pb_val);
                    store_in_vec(ctx, ep, pb_val, pb_term,
                                 bytes, off_heap_bytesize);
                    ep += off_heap_tail;
                }
                else if (ctx && j > r * TERM_TO_BINARY_MEMCPY_FACTOR) {
		    WSTACK_PUSH5(s, (UWord)data_dst, (UWord)bytes, bitoffs,
				 ENC_BIN_COPY, 8*j + bitsize);
		} else {
		    copy_binary_to_buffer(data_dst, 0, bytes, bitoffs,
					  8 * j + bitsize);
		}
	    }
	    break;
	case EXPORT_DEF:
	    {
		Export* exp = *((Export **) (export_val(obj) + 1));
                ASSERT(!(dflags & DFLAG_PENDING_CONNECT) || (ctx && ctx->iov));
                if (dflags & DFLAG_PENDING_CONNECT)
                    hopefull_export(ctx, &ep, exp, dflags, off_heap);
                else if ((dflags & DFLAG_EXPORT_PTR_TAG) != 0) {
		    *ep++ = EXPORT_EXT;
		    ep = enc_atom(acmp, exp->info.mfa.module, ep, dflags);
		    ep = enc_atom(acmp, exp->info.mfa.function, ep, dflags);
		    ep = enc_term(acmp, make_small(exp->info.mfa.arity),
                                  ep, dflags, off_heap);
		} else {
		    /* Tag, arity */
		    *ep++ = SMALL_TUPLE_EXT;
		    put_int8(2, ep);
		    ep += 1;

		    /* Module name */
		    ep = enc_atom(acmp, exp->info.mfa.module, ep, dflags);

		    /* Function name */
		    ep = enc_atom(acmp, exp->info.mfa.function, ep, dflags);
		}
		break;
	    }
	    break;
	case FUN_DEF:
	    {
		ErlFunThing* funp = (ErlFunThing *) fun_val(obj);
		int ei;

		ASSERT(dflags & DFLAG_NEW_FUN_TAGS);
                *ep++ = NEW_FUN_EXT;
                WSTACK_PUSH2(s, ENC_PATCH_FUN_SIZE,
                             (UWord) ep); /* Position for patching in size */
                ep += 4;
                *ep = funp->arity;
                ep += 1;
                sys_memcpy(ep, funp->fe->uniq, 16);
                ep += 16;
                put_int32(funp->fe->index, ep);
                ep += 4;
                put_int32(funp->num_free, ep);
                ep += 4;
                ep = enc_atom(acmp, funp->fe->module, ep, dflags);
                ep = enc_term(acmp, make_small(funp->fe->old_index), ep, dflags, off_heap);
                ep = enc_term(acmp, make_small(funp->fe->old_uniq), ep, dflags, off_heap);
                ep = enc_pid(acmp, funp->creator, ep, dflags);

		for (ei = funp->num_free-1; ei >= 0; ei--) {
		    WSTACK_PUSH2(s, ENC_TERM, (UWord) funp->env[ei]);
		}
	    }
	    break;
	}
    }
    DESTROY_WSTACK(s);
    if (ctx) {
	ASSERT(ctx->wstack.wstart == NULL);
	*reds = r;
        if (use_iov)
            store_in_vec(ctx, ep, NULL, THE_NON_VALUE, NULL, 0);
    }
    *res = ep;
    return 0;
}

static ERTS_INLINE void
store_in_vec_aux(TTBEncodeContext *ctx,
                 Binary *bin,
                 Eterm term,
                 byte *ptr,
                 Uint len)
{
    ErlDrvBinary *dbin = Binary2ErlDrvBinary(bin);
    int vlen = ctx->vlen;
    Uint iov_len;
    ErlIOVec *feiovp;

    ASSERT(((byte *) &bin->orig_bytes[0]) <= ptr);
    ASSERT(ptr + len <= ((byte *) &bin->orig_bytes[0]) + bin->orig_size);

    if (ctx->frag_ix >= 0) {
        feiovp = &ctx->fragment_eiovs[ctx->frag_ix];
        ASSERT(0 < feiovp->size);
        ASSERT(feiovp->size <= ctx->fragment_size);
        if (feiovp->size != ctx->fragment_size) {
            /* current fragment not full yet... */
            iov_len = ctx->fragment_size - feiovp->size;
            if (len < iov_len)
                iov_len = len;
            goto store_iov_data;
        }
    }

    while (len) {
        /* Start new fragment... */
        ctx->frag_ix++;
        feiovp = &ctx->fragment_eiovs[ctx->frag_ix];
        ASSERT(ctx->frag_ix >= 0);

        if (ctx->termv) {
            ctx->termv[vlen] = THE_NON_VALUE;
            ctx->termv[vlen+1] = THE_NON_VALUE;
        }

        feiovp->vsize = 2;
        feiovp->size = 0;
        feiovp->iov = &ctx->iov[vlen];
        feiovp->binv = &ctx->binv[vlen];

        /* entry for driver header */
        ctx->iov[vlen].iov_base = NULL;
        ctx->iov[vlen].iov_len = 0;
        ctx->binv[vlen] = NULL;
        vlen++;

        /* entry for dist header */
        ctx->iov[vlen].iov_base = NULL;
        ctx->iov[vlen].iov_len = 0;
        ctx->binv[vlen] = NULL;
        vlen++;

        iov_len = len < ctx->fragment_size ? len : ctx->fragment_size;

    store_iov_data:

        ASSERT(iov_len);
        
        do {
            Uint iov_len_left;
                
            if (iov_len <= MAX_SYSIOVEC_IOVLEN)
                iov_len_left = 0;
            else {
                iov_len_left = iov_len - MAX_SYSIOVEC_IOVLEN;
                iov_len = MAX_SYSIOVEC_IOVLEN;
            }

            ctx->iov[vlen].iov_base = ptr;
            ctx->iov[vlen].iov_len = iov_len;
            ctx->binv[vlen] = dbin;
            if (ctx->termv)
                ctx->termv[vlen] = term;
            else
                erts_refc_inc(&bin->intern.refc, 2);
            ctx->size += iov_len;
            len -= iov_len;
            ptr += iov_len;
            vlen++;
            feiovp->size += iov_len;
            feiovp->vsize++;

            iov_len = iov_len_left;
        } while (iov_len);
    }

    ctx->vlen = vlen;
}

static void
store_in_vec(TTBEncodeContext *ctx,
             byte *ep,
             Binary *ohbin,
             Eterm ohpb,
             byte *ohp,
             Uint ohsz)
{
    byte *cp = ctx->cptr;
    if (cp != ep) {
        /* save data in common binary... */
        store_in_vec_aux(ctx,
                         ctx->result_bin,
                         THE_NON_VALUE,
                         cp,
                         ep - cp);
        ASSERT(ctx->vlen <= ctx->debug_vlen);
        ASSERT(ctx->frag_ix <= ctx->debug_fragments);
        ctx->cptr = ep;
    }
    if (ohbin) {
        /* save off-heap binary... */
        store_in_vec_aux(ctx,
                         ohbin,
                         ohpb,
                         ohp,
                         ohsz);
        ASSERT(ctx->vlen <= ctx->debug_vlen);
        ASSERT(ctx->frag_ix <= ctx->debug_fragments);
    }
}

static byte *
begin_hopefull_data(TTBEncodeContext *ctx, byte *ep)
{
    store_in_vec(ctx, ep, NULL, THE_NON_VALUE, NULL, 0);
    ASSERT(ERTS_NO_HIX == (Uint32) get_int32(ctx->hopefull_ixp));
    put_int32(ctx->vlen, ctx->hopefull_ixp);
    ctx->hopefull_ixp = ep;
    put_int32(ERTS_NO_HIX, ep);
    ep += 4;
    ctx->cptr = ep;
    return ep;
}

static byte *
end_hopefull_data(TTBEncodeContext *ctx, byte *ep, Uint fallback_size)
{
    Uint sz;
    store_in_vec(ctx, ep, NULL, THE_NON_VALUE, NULL, 0);
    /*
     * Reserve extra room for fallback if needed. The four
     * bytes used for hopefull index can be used for
     * fallback encoding...
     */
    sz = ep - ctx->hopefull_ixp;
    if (fallback_size > sz) {
        ep += fallback_size - sz;
        ctx->cptr = ep;
    }
    return ep;
}

static byte *
hopefull_bit_binary(TTBEncodeContext* ctx, byte **epp, Binary *pb_val, Eterm pb_term,
                    byte *bytes, byte bitoffs, byte bitsize, Uint sz)
{
    byte *octets, *ep = *epp;

    ctx->hopefull_flags |= DFLAG_BIT_BINARIES;
    
    /*
     * The fallback:
     *
     *   SMALL_TUPLE_EXT          - 1 byte
     *   2                        - 1 byte
     *   BINARY_EXT               - 1 byte
     *   whole octet size ('sz')  - 4 byte
     *   whole octets             - 'sz' bytes
     *   trailing bits            - 1 byte
     *   SMALL_INTEGER_EXT        - 1 byte
     *   bitsize                  - 1 byte
     */

    /* bit binary prelude in one hopefull data element */
    ep = begin_hopefull_data(ctx, ep);
    *ep++ = BIT_BINARY_EXT;
    put_int32((sz+1), ep);
    ep += 4;
    *ep++ = bitsize;
    ep = end_hopefull_data(ctx, ep, 1+1+1+4);

    /* All whole octets... */
    if (pb_val) {
        octets = NULL;
        store_in_vec(ctx, ep, pb_val, pb_term, bytes, sz);
    }
    else {
        /* ... will be copied here afterwards */
        octets = ep;
        ep += sz;
    }

    /* copy trailing bits into new hopefull data element */
    ep = begin_hopefull_data(ctx, ep);
    *ep = 0;

    copy_binary_to_buffer(ep, 0, bytes + sz, bitoffs, bitsize);
    ep++;

    ep = end_hopefull_data(ctx, ep, 1+1+1);
    *epp = ep;
    
    return octets;
}

static void
hopefull_export(TTBEncodeContext* ctx, byte **epp, Export* exp, Uint32 dflags,
                struct erl_off_heap_header** off_heap)
{
    Uint fallback_sz;
    byte *ep = *epp, *mod_start;

    /*
     * The fallback:
     *
     *   SMALL_TUPLE_EXT        - 1 byte
     *   2                      - 1 byte
     *   module atom...         - M bytes
     *   function atom...       - F bytes
     */

    ctx->hopefull_flags |= DFLAG_EXPORT_PTR_TAG;

    ep = begin_hopefull_data(ctx, ep);
                    
    *ep++ = EXPORT_EXT;
    mod_start = ep;
    ep = enc_atom(NULL, exp->info.mfa.module, ep, dflags);
    ep = enc_atom(NULL, exp->info.mfa.function, ep, dflags);
    fallback_sz = 2 + (ep - mod_start);
    ep = enc_term(NULL, make_small(exp->info.mfa.arity),
                  ep, dflags, off_heap);

    ep = end_hopefull_data(ctx, ep, fallback_sz);

    *epp = ep;
}

/** @brief Is it a list of bytes not longer than MAX_STRING_LEN?
 * @param lenp out: string length or number of list cells traversed
 * @return true/false
 */
static
int
is_external_string(Eterm list, Uint* lenp)
{
    Uint len = 0;

    /*
     * Calculate the length of the list as long as all characters
     * are integers from 0 through 255.
     */
    while (is_list(list)) {
	Eterm* consp = list_val(list);
	Eterm hd = CAR(consp);

	if (!is_byte(hd) || ++len > MAX_STRING_LEN) {
	    *lenp = len;
            return 0;
	}
	list = CDR(consp);
    }

    *lenp = len;
    return is_nil(list);
}


struct dec_term_hamt
{
    Eterm* objp; /* write result here */
    Uint size;   /* nr of leafs */
    Eterm* leaf_array;
};


/* Decode term from external format into *objp.
** On failure calls erts_factory_undo() and returns NULL
*/
static byte*
dec_term(ErtsDistExternal *edep,
	 ErtsHeapFactory* factory,
	 byte* ep,
         Eterm* objp,
	 B2TContext* ctx,
         int ets_decode)
{
#define PSTACK_TYPE struct dec_term_hamt
    PSTACK_DECLARE(hamt_array, 5);
    int n;
    ErtsAtomEncoding char_enc;
    register Eterm* hp;        /* Please don't take the address of hp */
    DECLARE_WSTACK(flat_maps); /* for preprocessing of small maps */
    Eterm* next;
    SWord reds;
#ifdef DEBUG
    Eterm* dbg_resultp = ctx ? &ctx->u.dc.res : objp;
#endif

    if (ctx) {
        reds     = ctx->reds;
        next     = ctx->u.dc.next;
        ep       = ctx->u.dc.ep;
	factory  = &ctx->u.dc.factory;

        if (ctx->state != B2TDecode) {
            int n_limit = reds;

	    n = ctx->u.dc.remaining_n;
            if (ctx->state == B2TDecodeBinary) {
                n_limit *= B2T_MEMCPY_FACTOR;
                ASSERT(n_limit >= reds);
		reds -= n / B2T_MEMCPY_FACTOR;
            }
	    else
		reds -= n;

            if (n > n_limit) {
                ctx->u.dc.remaining_n -= n_limit;
                n = n_limit;
                reds = 0;
            }
            else {
                ctx->u.dc.remaining_n = 0;
            }

            switch (ctx->state) {
            case B2TDecodeList:
                objp = next - 2;
                while (n > 0) {
                    objp[0] = (Eterm) next;
                    objp[1] = make_list(next);
                    next = objp;
                    objp -= 2;
                    n--;
                }
                break;

            case B2TDecodeTuple:
                objp = next - 1;
                while (n-- > 0) {
                    objp[0] = (Eterm) next;
                    next = objp;
                    objp--;
                }
                break;

            case B2TDecodeString:
                hp = factory->hp;
                hp[-1] = make_list(hp);  /* overwrite the premature NIL */
                while (n-- > 0) {
                    hp[0] = make_small(*ep++);
                    hp[1] = make_list(hp+2);
                    hp += 2;
                }
                hp[-1] = NIL;
		factory->hp = hp;
                break;

            case B2TDecodeBinary:
                sys_memcpy(ctx->u.dc.remaining_bytes, ep, n);
                ctx->u.dc.remaining_bytes += n;
                ep += n;
                break;

            default:
                ASSERT(!"Unknown state");
            }
            if (!ctx->u.dc.remaining_n) {
                ctx->state = B2TDecode;
            }
            if (reds <= 0) {
                ctx->u.dc.next = next;
                ctx->u.dc.ep = ep;
                ctx->reds = 0;
                return NULL;
            }
        }
	PSTACK_CHANGE_ALLOCATOR(hamt_array, ERTS_ALC_T_SAVED_ESTACK);
        WSTACK_CHANGE_ALLOCATOR(flat_maps, ERTS_ALC_T_SAVED_ESTACK);
	if (ctx->u.dc.hamt_array.pstart) {
	    PSTACK_RESTORE(hamt_array, &ctx->u.dc.hamt_array);
	}
	if (ctx->u.dc.flat_maps.wstart) {
	    WSTACK_RESTORE(flat_maps, &ctx->u.dc.flat_maps);
	}
    }
    else {
        reds = ERTS_SWORD_MAX;
        next = objp;
        *next = (Eterm) (UWord) NULL;
    }
    hp = factory->hp;

    while (next != NULL) {

	objp = next;
	next = (Eterm *) *objp;

	switch (*ep++) {
	case INTEGER_EXT:
	    {
		Sint sn = get_int32(ep);

		ep += 4;
#if defined(ARCH_64)
		*objp = make_small(sn);
#else
		if (IS_SSMALL(sn)) {
		    *objp = make_small(sn);
		} else {
		    *objp = small_to_big(sn, hp);
		    hp += BIG_UINT_HEAP_SIZE;
		}
#endif
		break;
	    }
	case SMALL_INTEGER_EXT:
	    n = get_int8(ep);
	    ep++;
	    *objp = make_small(n);
	    break;
	case SMALL_BIG_EXT:
	    n = get_int8(ep);
	    ep++;
	    goto big_loop;
	case LARGE_BIG_EXT:
	    n = get_int32(ep);
	    ep += 4;
	big_loop:
	    {
		Eterm big;
		byte* first;
		byte* last;
		Uint neg;

		neg = get_int8(ep); /* Sign bit */
		ep++;

		/*
		 * Strip away leading zeroes to avoid creating illegal bignums.
		 */
		first = ep;
		last = ep + n;
		ep += n;
		do {
		    --last;
		} while (first <= last && *last == 0);

		if ((n = last - first + 1) == 0) {
		    /* Zero width bignum defaults to zero */
		    big = make_small(0);
		} else {
		    big = bytes_to_big(first, n, neg, hp);
		    if (is_nil(big))
			goto error;
		    if (is_big(big)) {
			hp += big_arity(big) + 1;
		    }
		}
		*objp = big;
		break;
	    }
	case ATOM_CACHE_REF:
	    if (edep == 0 || (edep->flags & ERTS_DIST_EXT_ATOM_TRANS_TAB) == 0) {
		goto error;
	    }
	    n = get_int8(ep);
	    ep++;
	    if (n >= edep->attab.size)
		goto error;
	    ASSERT(is_atom(edep->attab.atom[n]));
	    *objp = edep->attab.atom[n];
	    break;
	case ATOM_EXT:
	    n = get_int16(ep);
	    ep += 2;
	    char_enc = ERTS_ATOM_ENC_LATIN1;
	    goto dec_term_atom_common;
	case SMALL_ATOM_EXT:
	    n = get_int8(ep);
	    ep++;
	    char_enc = ERTS_ATOM_ENC_LATIN1;
	    goto dec_term_atom_common;
	case ATOM_UTF8_EXT:
	    n = get_int16(ep);
	    ep += 2;
	    char_enc = ERTS_ATOM_ENC_UTF8;
	    goto dec_term_atom_common;
	case SMALL_ATOM_UTF8_EXT:
	    n = get_int8(ep);
	    ep++;
	    char_enc = ERTS_ATOM_ENC_UTF8;
dec_term_atom_common:
	    if (edep && (edep->flags & ERTS_DIST_EXT_BTT_SAFE)) {
		if (!erts_atom_get((char*)ep, n, objp, char_enc)) {
		    goto error;
		}
	    } else {
		Eterm atom = erts_atom_put(ep, n, char_enc, 0);
		if (is_non_value(atom))
		    goto error;
	        *objp = atom;
	    }
	    ep += n;
	    break;
	case LARGE_TUPLE_EXT:
	    n = get_int32(ep);
	    ep += 4;
	    goto tuple_loop;
	case SMALL_TUPLE_EXT:
	    n = get_int8(ep);
	    ep++;
	tuple_loop:
	    *objp = make_tuple(hp);
	    *hp++ = make_arityval(n);
	    hp += n;
            objp = hp - 1;
            if (ctx) {
                if (reds < n) {
                    ASSERT(reds > 0);
                    ctx->state = B2TDecodeTuple;
                    ctx->u.dc.remaining_n = n - reds;
                    n = reds;
                }
		reds -= n;
	    }
	    while (n-- > 0) {
		objp[0] = (Eterm) next;
		next = objp;
		objp--;
	    }
	    break;
	case NIL_EXT:
	    *objp = NIL;
	    break;
	case LIST_EXT:
	    n = get_int32(ep);
	    ep += 4;
	    if (n == 0) {
		next = objp;
		break;
	    }
	    *objp = make_list(hp);
            hp += 2 * n;
	    objp = hp - 2;
	    objp[0] = (Eterm) (objp+1);
	    objp[1] = (Eterm) next;
	    next = objp;
	    objp -= 2;
            n--;
	    if (ctx) {
                if (reds < n) {
                    ASSERT(reds > 0);
		    ctx->state = B2TDecodeList;
		    ctx->u.dc.remaining_n = n - reds;
		    n = reds;
		}
		reds -= n;
	    }
            while (n > 0) {
		objp[0] = (Eterm) next;
		objp[1] = make_list(next);
		next = objp;
		objp -= 2;
                n--;
	    }
	    break;
	case STRING_EXT:
	    n = get_int16(ep);
	    ep += 2;
	    if (n == 0) {
		*objp = NIL;
		break;
	    }
	    *objp = make_list(hp);
            if (ctx) {
                if (reds < n) {
                    ctx->state = B2TDecodeString;
                    ctx->u.dc.remaining_n = n - reds;
                    n = reds;
		}
                reds -= n;
            }
	    while (n-- > 0) {
		hp[0] = make_small(*ep++);
		hp[1] = make_list(hp+2);
		hp += 2;
	    }
	    hp[-1] = NIL;
	    break;
	case FLOAT_EXT:
	    {
		FloatDef ff;

		if (sys_chars_to_double((char*)ep, &ff.fd) != 0) {
		    goto error;
		}
		ep += 31;
		*objp = make_float(hp);
		PUT_DOUBLE(ff, hp);
		hp += FLOAT_SIZE_OBJECT;
		break;
	    }
	case NEW_FLOAT_EXT:
	    {
		FloatDef ff;
#ifndef NO_FPE_SIGNALS
		volatile unsigned long *fpexnp = erts_get_current_fp_exception();
#endif

#if defined(WORDS_BIGENDIAN) || defined(DOUBLE_MIDDLE_ENDIAN)
		ff.fw[0] = get_int32(ep);
		ep += 4;
		ff.fw[1] = get_int32(ep);
		ep += 4;
#else
		ff.fw[1] = get_int32(ep);
		ep += 4;
		ff.fw[0] = get_int32(ep);
		ep += 4;
#endif		
		__ERTS_FP_CHECK_INIT(fpexnp);
		__ERTS_FP_ERROR_THOROUGH(fpexnp, ff.fd, goto error);
		*objp = make_float(hp);
		PUT_DOUBLE(ff, hp);
		hp += FLOAT_SIZE_OBJECT;
		break;
	    }
        case PID_EXT:
        case NEW_PID_EXT:
	    factory->hp = hp;
	    ep = dec_pid(edep, factory, ep, objp, ep[-1]);
	    hp = factory->hp;
	    if (ep == NULL) {
		goto error;
	    }
	    break;
        case PORT_EXT:
        case NEW_PORT_EXT:
	    {
		Eterm sysname;
		ErlNode *node;
		Uint num;
		Uint32 cre;
                byte tag = ep[-1];

		if ((ep = dec_atom(edep, ep, &sysname)) == NULL) {
		    goto error;
		}
		if ((num = get_int32(ep)) > ERTS_MAX_PORT_NUMBER) {
		    goto error;
		}
		ep += 4;
                if (tag == PORT_EXT) {
                    cre = get_int8(ep);
                    ep++;
                    if (!is_tiny_creation(cre)) {
                        goto error;
                    }
                }
                else {
                    cre = get_int32(ep);
                    ep += 4;
                }
		node = dec_get_node(sysname, cre, make_boxed(hp));
		if(node == erts_this_node) {
		    *objp = make_internal_port(num);
		}
		else {
		    ExternalThing *etp = (ExternalThing *) hp;
		    hp += EXTERNAL_THING_HEAD_SIZE + 1;
		    
		    etp->header = make_external_port_header(1);
		    etp->next = factory->off_heap->first;
		    etp->node = node;
		    etp->data.ui[0] = num;

		    factory->off_heap->first = (struct erl_off_heap_header*)etp;
		    *objp = make_external_port(etp);
		}

		break;
	    }
	case REFERENCE_EXT:
	    {
		Eterm sysname;
		ErlNode *node;
		int i;
		Uint32 cre;
		Uint32 *ref_num;
		Uint32 r0;
		Uint ref_words;

		ref_words = 1;

		if ((ep = dec_atom(edep, ep, &sysname)) == NULL)
		    goto error;
		if ((r0 = get_int32(ep)) >= MAX_REFERENCE )
		    goto error;
		ep += 4;

		cre = get_int8(ep);
		ep += 1;
		if (!is_tiny_creation(cre)) {
		    goto error;
		}
		goto ref_ext_common;

	    case NEW_REFERENCE_EXT:
		ref_words = get_int16(ep);
		ep += 2;

		if ((ep = dec_atom(edep, ep, &sysname)) == NULL)
		    goto error;

		cre = get_int8(ep);
		ep += 1;
		if (!is_tiny_creation(cre)) {
		    goto error;
		}
		r0 = get_int32(ep);
		ep += 4;
		if (r0 >= MAX_REFERENCE)
		    goto error;
		goto ref_ext_common;

            case NEWER_REFERENCE_EXT:
		ref_words = get_int16(ep);
		ep += 2;

		if ((ep = dec_atom(edep, ep, &sysname)) == NULL)
		    goto error;

		cre = get_int32(ep);
		ep += 4;
		r0 = get_int32(ep);
		ep += 4;

	    ref_ext_common: {
		ErtsORefThing *rtp;

		if (ref_words > ERTS_MAX_REF_NUMBERS)
		    goto error;

		node = dec_get_node(sysname, cre, make_boxed(hp));
		if(node == erts_this_node) {
                    if (r0 >= MAX_REFERENCE) {
                          /*
                           * Must reject local refs with more than 18 bits
                           * in first word as magic ref table relies on it.
                           */
                        goto error;
                    }
	
		    rtp = (ErtsORefThing *) hp;
		    ref_num = &rtp->num[0];
		    if (ref_words != ERTS_REF_NUMBERS) {
                        int i;
                        if (ref_words > ERTS_REF_NUMBERS)
                            goto error; /* Not a ref that we created... */
                        for (i = ref_words; i < ERTS_REF_NUMBERS; i++)
                            ref_num[i] = 0;
		    }

#ifdef ERTS_ORDINARY_REF_MARKER
		    rtp->marker = ERTS_ORDINARY_REF_MARKER;
#endif
		    hp += ERTS_REF_THING_SIZE;
		    rtp->header = ERTS_REF_THING_HEADER;
		    *objp = make_internal_ref(rtp);
		}
		else {
		    ExternalThing *etp = (ExternalThing *) hp;
		    rtp = NULL;
#if defined(ARCH_64)
		    hp += EXTERNAL_THING_HEAD_SIZE + ref_words/2 + 1;
#else
		    hp += EXTERNAL_THING_HEAD_SIZE + ref_words;
#endif

#if defined(ARCH_64)
		    etp->header = make_external_ref_header(ref_words/2 + 1);
#else
		    etp->header = make_external_ref_header(ref_words);
#endif
		    etp->next = factory->off_heap->first;
		    etp->node = node;

		    factory->off_heap->first = (struct erl_off_heap_header*)etp;
		    *objp = make_external_ref(etp);
		    ref_num = &(etp->data.ui32[0]);
#if defined(ARCH_64)
		    *(ref_num++) = ref_words /* 32-bit arity */;
#endif
		}

		ref_num[0] = r0;

		for(i = 1; i < ref_words; i++) {
		    ref_num[i] = get_int32(ep);
		    ep += 4;
		}
#if defined(ARCH_64)
		if ((1 + ref_words) % 2)
		    ref_num[ref_words] = 0;
#endif
		if (node == erts_this_node) {
		    /* Check if it was a magic reference... */
		    ErtsMagicBinary *mb = erts_magic_ref_lookup_bin(ref_num);
		    if (mb) {
			/*
			 * Was a magic ref; adjust it...
			 *
			 * Refc on binary was increased by lookup above...
			 */
			ASSERT(rtp);
			hp = (Eterm *) rtp;
			write_magic_ref_thing(hp, factory->off_heap, mb);
                        OH_OVERHEAD(factory->off_heap,
                                    mb->orig_size / sizeof(Eterm));
			hp += ERTS_MAGIC_REF_THING_SIZE;
		    }
		}
		break;
	    }
	    }
	case BINARY_EXT:
	    {
		n = get_int32(ep);
		ep += 4;
	    
		if ((unsigned)n <= ERL_ONHEAP_BIN_LIMIT) {
		    ErlHeapBin* hb = (ErlHeapBin *) hp;

		    hb->thing_word = header_heap_bin(n);
		    hb->size = n;
		    hp += heap_bin_size(n);
		    sys_memcpy(hb->data, ep, n);
		    *objp = make_binary(hb);
		} else if (edep && edep->data && edep->data->binp &&
                           n > (edep->data->binp->orig_size / 4)) {
                    /* If we decode a refc binary from a distribution data
                       entry we know that it is a refc binary to begin with
                       so we just increment it and use the reference. This
                       means that the entire distribution data entry will
                       remain until this binary is de-allocated so we only
                       do it if a substantial part (> 25%) of the data
                       is a binary. */
                    ProcBin* pb = (ProcBin *) hp;
                    Binary* bptr = edep->data->binp;
                    erts_refc_inc(&bptr->intern.refc, 1);
                    pb->thing_word = HEADER_PROC_BIN;
                    pb->size = n;
                    pb->next = factory->off_heap->first;
                    factory->off_heap->first = (struct erl_off_heap_header*)pb;
                    pb->val = bptr;
                    pb->bytes = (byte*) ep;
                    ERTS_ASSERT((byte*)(bptr->orig_bytes) < ep &&
                                ep+n <= (byte*)(bptr->orig_bytes+bptr->orig_size));
                    pb->flags = 0;
                    OH_OVERHEAD(factory->off_heap, pb->size / sizeof(Eterm));
                    hp += PROC_BIN_SIZE;
                    *objp = make_binary(pb);
		} else {
		    Binary* dbin = erts_bin_nrml_alloc(n);

		    *objp = erts_build_proc_bin(factory->off_heap, hp, dbin);
		    hp += PROC_BIN_SIZE;
                    if (ctx) {
                        int n_limit = reds * B2T_MEMCPY_FACTOR;
                        if (n > n_limit) {
                            ctx->state = B2TDecodeBinary;
                            ctx->u.dc.remaining_n = n - n_limit;
                            ctx->u.dc.remaining_bytes = dbin->orig_bytes + n_limit;
                            n = n_limit;
                            reds = 0;
                        }
                        else
                            reds -= n / B2T_MEMCPY_FACTOR;
                    }
                    sys_memcpy(dbin->orig_bytes, ep, n);
                }
		ep += n;
		break;
	    }
	case BIT_BINARY_EXT:
	    {
		Eterm bin;
		ErlSubBin* sb;
		Uint bitsize;

		n = get_int32(ep);
		bitsize = ep[4];
                if (((bitsize==0) != (n==0)) || bitsize > 8)
                    goto error;
                ep += 5;
		if ((unsigned)n <= ERL_ONHEAP_BIN_LIMIT) {
		    ErlHeapBin* hb = (ErlHeapBin *) hp;

		    hb->thing_word = header_heap_bin(n);
		    hb->size = n;
		    sys_memcpy(hb->data, ep, n);
		    bin = make_binary(hb);
		    hp += heap_bin_size(n);
                    ep += n;
		} else {
		    Binary* dbin = erts_bin_nrml_alloc(n);
		    Uint n_copy = n;

		    bin = erts_build_proc_bin(factory->off_heap, hp, dbin);
		    hp += PROC_BIN_SIZE;
                    if (ctx) {
                        int n_limit = reds * B2T_MEMCPY_FACTOR;
                        if (n > n_limit) {
                            ctx->state = B2TDecodeBinary;
                            ctx->u.dc.remaining_n = n - n_limit;
                            ctx->u.dc.remaining_bytes = dbin->orig_bytes + n_limit;
                            n_copy = n_limit;
                            reds = 0;
                        }
                        else {
                            reds -= n / B2T_MEMCPY_FACTOR;
			}
                    }
                    sys_memcpy(dbin->orig_bytes, ep, n_copy);
                    ep += n_copy;
                }

		if (bitsize == 8 || n == 0) {
		    *objp = bin;
		} else {
                    sb = (ErlSubBin *)hp;
		    sb->thing_word = HEADER_SUB_BIN;
		    sb->orig = bin;
		    sb->size = n - 1;
		    sb->bitsize = bitsize;
		    sb->bitoffs = 0;
		    sb->offs = 0;
		    sb->is_writable = 0;
		    *objp = make_binary(sb);
		    hp += ERL_SUB_BIN_SIZE;
		}
		break;
	    }
	case EXPORT_EXT:
	    {
		Eterm mod;
		Eterm name;
		Eterm temp;
		Sint arity;

		if ((ep = dec_atom(edep, ep, &mod)) == NULL) {
		    goto error;
		}
		if ((ep = dec_atom(edep, ep, &name)) == NULL) {
		    goto error;
		}
		factory->hp = hp;
		ep = dec_term(edep, factory, ep, &temp, NULL, 0);
		hp = factory->hp;
		if (ep == NULL) {
		    goto error;
		}
		if (!is_small(temp)) {
		    goto error;
		}
		arity = signed_val(temp);
		if (arity < 0) {
		    goto error;
		}
		if (edep && (edep->flags & ERTS_DIST_EXT_BTT_SAFE)) {
		    if (!erts_active_export_entry(mod, name, arity))
			goto error;
                }
		*objp = make_export(hp);
		*hp++ = HEADER_EXPORT;
		*hp++ = (Eterm) erts_export_get_or_make_stub(mod, name, arity);
		break;
	    }
	    break;
	case MAP_EXT:
	    {
		Uint32 size,n;
		Eterm *kptr,*vptr;
		Eterm keys;

		size = get_int32(ep); ep += 4;

                if (size <= MAP_SMALL_MAP_LIMIT) {
                    flatmap_t *mp;

                    keys  = make_tuple(hp);
                    *hp++ = make_arityval(size);
                    hp   += size;
                    kptr = hp - 1;

                    mp    = (flatmap_t*)hp;
                    hp   += MAP_HEADER_FLATMAP_SZ;
                    hp   += size;
                    vptr = hp - 1;

                    /* kptr, last word for keys
                     * vptr, last word for values
                     */

                    WSTACK_PUSH(flat_maps, (UWord)mp);
                    mp->thing_word = MAP_HEADER_FLATMAP;
                    mp->size       = size;
                    mp->keys       = keys;
                    *objp          = make_flatmap(mp);

                    for (n = size; n; n--) {
                        *vptr = (Eterm) next;
                        *kptr = (Eterm) vptr;
                        next  = kptr;
                        vptr--;
                        kptr--;
                    }
                }
                else {  /* Make hamt */
                    struct dec_term_hamt* hamt = PSTACK_PUSH(hamt_array);

                    hamt->objp = objp;
                    hamt->size = size;
                    hamt->leaf_array = hp;

                    for (n = size; n; n--) {
                        CDR(hp) = (Eterm) next;
                        CAR(hp) = (Eterm) &CDR(hp);
                        next = &CAR(hp);
                        hp += 2;
                    }
                }
	    }
	    break;
	case NEW_FUN_EXT:
	    {
		ErlFunThing* funp = (ErlFunThing *) hp;
		Uint arity;
		Eterm module;
		byte* uniq;
		int index;
		Sint old_uniq;
		Sint old_index;
		unsigned num_free;
		int i;
		Eterm temp;

		ep += 4;	/* Skip total size in bytes */
		arity = *ep++;
		uniq = ep;
		ep += 16;
		index = get_int32(ep);
		ep += 4;
		num_free = get_int32(ep);
		ep += 4;
		hp += ERL_FUN_SIZE;
		hp += num_free;
		funp->thing_word = HEADER_FUN;
		funp->num_free = num_free;
		*objp = make_fun(funp);

		/* Module */
		if ((ep = dec_atom(edep, ep, &module)) == NULL) {
		    goto error;
		}
		factory->hp = hp;
		/* Index */
		if ((ep = dec_term(edep, factory, ep, &temp, NULL, 0)) == NULL) {
		    goto error;
		}
		if (!is_small(temp)) {
		    goto error;
		}
		old_index = unsigned_val(temp);

		/* Uniq */
		if ((ep = dec_term(edep, factory, ep, &temp, NULL, 0)) == NULL) {
		    goto error;
		}
		if (!is_small(temp)) {
		    goto error;
		}
		old_uniq = unsigned_val(temp);

		/*
		 * It is safe to link the fun into the fun list only when
		 * no more validity tests can fail.
		 */
		funp->next = factory->off_heap->first;
		factory->off_heap->first = (struct erl_off_heap_header*)funp;

		funp->fe = erts_put_fun_entry2(module, old_uniq, old_index,
					       uniq, index, arity);
		funp->arity = arity;
#ifdef HIPE
		if (funp->fe->native_address == NULL) {
		    hipe_set_closure_stub(funp->fe);
		}
#endif
		hp = factory->hp;

		/* Environment */
		for (i = num_free-1; i >= 0; i--) {
		    funp->env[i] = (Eterm) next;
		    next = funp->env + i;
		}
		/* Creator */
		funp->creator = (Eterm) next;
		next = &(funp->creator);
		break;
	    }
	case ATOM_INTERNAL_REF2:
	    n = get_int16(ep);
	    ep += 2;
            /* If this is an ets_decode we know that
               the atom is valid, so we can skip the
               validation check */
	    if (!ets_decode && n >= atom_table_size()) {
		goto error;
	    }
	    *objp = make_atom(n);
	    break;
	case ATOM_INTERNAL_REF3:
	    n = get_int24(ep);
	    ep += 3;
            /* If this is an ets_decode we know that
               the atom is valid, so we can skip the
               validation check */
	    if (!ets_decode && n >= atom_table_size()) {
		goto error;
	    }
	    *objp = make_atom(n);
	    break;

	case BINARY_INTERNAL_REF:
	    {
		ProcBin* pb = (ProcBin*) hp;
		sys_memcpy(pb, ep, sizeof(ProcBin));
		ep += sizeof(ProcBin);

		erts_refc_inc(&pb->val->intern.refc, 1);
		hp += PROC_BIN_SIZE;
		pb->next = factory->off_heap->first;
		factory->off_heap->first = (struct erl_off_heap_header*)pb;
		OH_OVERHEAD(factory->off_heap, pb->size / sizeof(Eterm));
		pb->flags = 0;
		*objp = make_binary(pb);
		break;
	    }
	case BIT_BINARY_INTERNAL_REF:
	    {
		Sint bitoffs = *ep++;
		Sint bitsize = *ep++;
		ProcBin* pb = (ProcBin*) hp;
		ErlSubBin* sub;
		sys_memcpy(pb, ep, sizeof(ProcBin));
		ep += sizeof(ProcBin);

		erts_refc_inc(&pb->val->intern.refc, 1);
		hp += PROC_BIN_SIZE;
		pb->next = factory->off_heap->first;
		factory->off_heap->first = (struct erl_off_heap_header*)pb;
                OH_OVERHEAD(factory->off_heap, pb->size / sizeof(Eterm));
		pb->flags = 0;

		sub = (ErlSubBin*)hp;
		sub->thing_word = HEADER_SUB_BIN;
		sub->size = pb->size - (bitoffs + bitsize + 7)/8;
		sub->offs = 0;
		sub->bitoffs = bitoffs;
		sub->bitsize = bitsize;
		sub->is_writable = 0;
		sub->orig = make_binary(pb);

		hp += ERL_SUB_BIN_SIZE;
		*objp = make_binary(sub);
		break;
	    }

	default:
	    goto error;
	}

        if (--reds <= 0) {
            if (ctx) {
                if (next || ctx->state != B2TDecode) {
                    ctx->u.dc.ep = ep;
                    ctx->u.dc.next = next;
                    ctx->u.dc.factory.hp = hp;
		    if (!WSTACK_ISEMPTY(flat_maps)) {
			WSTACK_SAVE(flat_maps, &ctx->u.dc.flat_maps);
		    }
		    if (!PSTACK_IS_EMPTY(hamt_array)) {
			PSTACK_SAVE(hamt_array, &ctx->u.dc.hamt_array);
		    }
                    ctx->reds = 0;
                    return NULL;
                }
            }
            else {
                reds = ERTS_SWORD_MAX;
            }
        }
    }

    ASSERT(hp <= factory->hp_end
           || (factory->mode == FACTORY_CLOSED && is_immed(*dbg_resultp)));
    factory->hp = hp;
    /*
     * From here on factory may produce (more) heap fragments
     */

    if (!PSTACK_IS_EMPTY(hamt_array)) {
        do {
            struct dec_term_hamt* hamt = PSTACK_TOP(hamt_array);

            *hamt->objp = erts_hashmap_from_array(factory,
                                                  hamt->leaf_array,
                                                  hamt->size,
                                                  1);
            if (is_non_value(*hamt->objp))
                goto error_hamt;

            (void) PSTACK_POP(hamt_array);
        } while (!PSTACK_IS_EMPTY(hamt_array));
        PSTACK_DESTROY(hamt_array);
    }

    /* Iterate through all the (flat)maps and check for validity and sort keys
     * - done here for when we know it is complete.
     */

    while(!WSTACK_ISEMPTY(flat_maps)) {
        next = (Eterm *)WSTACK_POP(flat_maps);
        if (!erts_validate_and_sort_flatmap((flatmap_t*)next))
            goto error;
    }
    WSTACK_DESTROY(flat_maps);

    ASSERT((Eterm*)*dbg_resultp != NULL);

    if (ctx) {
        ctx->state = B2TDone;
	ctx->reds = reds;
        ctx->u.dc.ep = ep;
    }

    return ep;

error:
    /* UNDO:
     * Must unlink all off-heap objects that may have been
     * linked into the process. 
     */
    if (factory->mode != FACTORY_CLOSED) {
	if (factory->hp < hp) { /* Sometimes we used hp and sometimes factory->hp */
	    factory->hp = hp;   /* the largest must be the freshest */
	}
    }
    else ASSERT(!factory->hp || factory->hp == hp);

error_hamt:
    erts_factory_undo(factory);
    PSTACK_DESTROY(hamt_array);
    if (ctx) {
	ctx->state = B2TDecodeFail;
	ctx->reds = reds;
    }
    WSTACK_DESTROY(flat_maps);
        
    return NULL;
}

/* returns the number of bytes needed to encode an object
   to a sequence of bytes
   N.B. That this must agree with to_external2() above!!!
   (except for cached atoms) */
static Uint encode_size_struct2(ErtsAtomCacheMap *acmp,
                                Eterm obj,
                                Uint64 dflags) {
    Uint size = 0;
    ErtsExtSzRes res = encode_size_struct_int(NULL, acmp, obj,
                                              dflags, NULL,
                                              &size);
    /*
     * encode_size_struct2() only allowed when
     * we know the result will always be OK!
     */ 
    ASSERT(res == ERTS_EXT_SZ_OK); (void) res;
    return (Uint) size;
}

static ErtsExtSzRes
encode_size_struct_int(TTBSizeContext* ctx, ErtsAtomCacheMap *acmp, Eterm obj,
		       Uint64 dflags, Sint *reds, Uint *res)
{
    DECLARE_WSTACK(s);
    Uint m, i, arity;
    Uint result = *res;
    Sint r = 0;
    int vlen = -1;

    if (ctx) {
	WSTACK_CHANGE_ALLOCATOR(s, ERTS_ALC_T_SAVED_ESTACK);
	r = *reds;

        vlen = ctx->vlen;
        
	if (!ctx->wstack.wstart)
            ctx->last_result = result;
        else { /* restore saved stack */
	    WSTACK_RESTORE(s, &ctx->wstack);
	    result = ctx->result;
	    obj = ctx->obj;
	}
    }

#define LIST_TAIL_OP ((0 << _TAG_PRIMARY_SIZE) | TAG_PRIMARY_HEADER)
#define TERM_ARRAY_OP(N) (((N) << _TAG_PRIMARY_SIZE) | TAG_PRIMARY_HEADER)
#define TERM_ARRAY_OP_DEC(OP) ((OP) - (1 << _TAG_PRIMARY_SIZE))


    for (;;) {
	ASSERT(!is_header(obj));

	if (ctx && --r <= 0) {
	    *reds = 0;
	    ctx->obj = obj;
	    ctx->result = result;
            ctx->vlen = vlen;
	    WSTACK_SAVE(s, &ctx->wstack);
	    return ERTS_EXT_SZ_YIELD;
	}
	switch (tag_val_def(obj)) {
	case NIL_DEF:
	    result++;
	    break;
	case ATOM_DEF:
	    if (dflags & DFLAG_ETS_COMPRESSED) {
		if (atom_val(obj) >= (1<<16)) {
		    result += 1 + 3;
		}
		else {
		    result += 1 + 2;
		}
	    }
	    else {
		Atom *a = atom_tab(atom_val(obj));
		int alen;
		if ((dflags & DFLAG_UTF8_ATOMS) || a->latin1_chars < 0) {
		    alen = a->len;
		    result += 1 + 1 + alen;
		    if (alen > 255) {
			result++; /* ATOM_UTF8_EXT (not small) */
		    }
		}
		else {
		    alen = a->latin1_chars;
		    result += 1 + 1 + alen;
		    if (alen > 255 || !(dflags & DFLAG_SMALL_ATOM_TAGS))
			result++; /* ATOM_EXT (not small) */
		}
		insert_acache_map(acmp, obj, dflags);
	    }
	    break;
	case SMALL_DEF:
	    {
		Sint val = signed_val(obj);

		if ((Uint)val < 256)
		    result += 1 + 1;		/* SMALL_INTEGER_EXT */
		else if (sizeof(Sint) == 4 || IS_SSMALL32(val))
		    result += 1 + 4;		/* INTEGER_EXT */
		else {
		    DeclareTmpHeapNoproc(tmp_big,2);
		    UseTmpHeapNoproc(2);
		    i = big_bytes(small_to_big(val, tmp_big));
		    result += 1 + 1 + 1 + i;	/* SMALL_BIG_EXT */
		    UnUseTmpHeapNoproc(2);
		}
	    }
	    break;
	case BIG_DEF:
	    i = big_bytes(obj);
	    if (sizeof(Sint)==4 && i <= 4 && (big_digit(obj,0)-big_sign(obj)) < (1<<31))
		result += 1 + 4;          /* INTEGER_EXT */
	    else if (i < 256)
		result += 1 + 1 + 1 + i;  /* tag,size,sign,digits */
	    else
		result += 1 + 4 + 1 + i;  /* tag,size,sign,digits */
	    break;
        case EXTERNAL_PID_DEF:
	case PID_DEF:
	    result += (1 + encode_size_struct2(acmp, pid_node_name(obj), dflags) +
		       4 + 4 + 4);
	    break;
        case EXTERNAL_REF_DEF:
	case REF_DEF:
	    ASSERT(dflags & DFLAG_EXTENDED_REFERENCES);
	    i = ref_no_numbers(obj);
	    result += (1 + 2 + encode_size_struct2(acmp, ref_node_name(obj), dflags) +
		       4 + 4*i);
	    break;
        case EXTERNAL_PORT_DEF:
        case PORT_DEF:
	    result += (1 + encode_size_struct2(acmp, port_node_name(obj), dflags) +
		      4 + 4);
	    break;
	case LIST_DEF: {
	    int is_str = is_external_string(obj, &m);
	    r -= m/2;
	    if (is_str) {
		result += m + 2 + 1;
	    } else {
		result += 5;
		WSTACK_PUSH2(s, (UWord)CDR(list_val(obj)), (UWord)LIST_TAIL_OP);
		obj = CAR(list_val(obj));
		continue; /* big loop */
	    }
	    break;
	}
	case TUPLE_DEF:
	    {
		Eterm* ptr = tuple_val(obj);
		arity = arityval(*ptr);
		if (arity <= 0xff) {
		    result += 1 + 1;
		} else {
		    result += 1 + 4;
		}
		if (arity > 1) {
		    WSTACK_PUSH2(s, (UWord) (ptr + 2),
				    (UWord) TERM_ARRAY_OP(arity-1));
		}
                else if (arity == 0) {
		    break;
                }
		obj = ptr[1];
		continue; /* big loop */
	    }
	case MAP_DEF:
	    if (is_flatmap(obj)) {
		flatmap_t *mp = (flatmap_t*)flatmap_val(obj);
		Uint size = flatmap_get_size(mp);

		result += 1 + 4; /* tag + 4 bytes size */

                if (size) {
		    WSTACK_PUSH4(s, (UWord) flatmap_get_values(mp),
				    (UWord) TERM_ARRAY_OP(size),
		                    (UWord) flatmap_get_keys(mp),
				    (UWord) TERM_ARRAY_OP(size));
		}
	    } else {
		Eterm *ptr;
		Eterm hdr;
		Uint node_sz;
		ptr = boxed_val(obj);
		hdr = *ptr;
		ASSERT(is_header(hdr));
		switch(hdr & _HEADER_MAP_SUBTAG_MASK) {
		case HAMT_SUBTAG_HEAD_ARRAY:
		    ptr++;
		    node_sz = 16;
		    result += 1 + 4; /* tag + 4 bytes size */
		    break;
		case HAMT_SUBTAG_HEAD_BITMAP:
		    ptr++;
		    result += 1 + 4; /* tag + 4 bytes size */
		    /*fall through*/
		case HAMT_SUBTAG_NODE_BITMAP:
		    node_sz = hashmap_bitcount(MAP_HEADER_VAL(hdr));
		    ASSERT(node_sz < 17);
		    break;
		default:
		    erts_exit(ERTS_ERROR_EXIT, "bad header\r\n");
		}

		ptr++;
		WSTACK_RESERVE(s, node_sz*2);
		while(node_sz--) {
                    if (is_list(*ptr)) {
			WSTACK_FAST_PUSH(s, CAR(list_val(*ptr)));
			WSTACK_FAST_PUSH(s, CDR(list_val(*ptr)));
                    } else {
			WSTACK_FAST_PUSH(s, *ptr);
		    }
		    ptr++;
		}
	    }
	    break;
	case FLOAT_DEF:
	    if (dflags & DFLAG_NEW_FLOATS) {
		result += 9;
	    } else {
		result += 32;   /* Yes, including the tag */
	    }
	    break;
	case BINARY_DEF: {
            ProcBin* pb = (ProcBin*) binary_val(obj);
            Uint bin_size = pb->size;
            byte bitoffs = 0;
            byte bitsize = 0;
            if (dflags & DFLAG_ETS_COMPRESSED) {
		ProcBin* pb = (ProcBin*) binary_val(obj);
		Uint sub_extra = 0;
		if (pb->thing_word == HEADER_SUB_BIN) {
		    ErlSubBin* sub = (ErlSubBin*) pb;
                    bitoffs = sub->bitoffs;
                    bitsize = sub->bitsize;
		    pb = (ProcBin*) binary_val(sub->orig);
		    sub_extra = 2;  /* bitoffs and bitsize */
		    bin_size += (bitoffs + bitsize + 7) / 8;
		}
		if (pb->thing_word == HEADER_PROC_BIN
		    && heap_bin_size(bin_size) > PROC_BIN_SIZE) {

		    result += 1 + sub_extra + sizeof(ProcBin);
		    break;
		}
            }
            else {
#ifdef ARCH_64
                if (bin_size >= (Uint) 0xffffffff) {
                    if (pb->thing_word == HEADER_SUB_BIN) {
                        ErlSubBin* sub = (ErlSubBin*) pb;
                        bin_size += (sub->bitoffs + sub->bitsize+ 7) / 8;
                    }
                    if (bin_size > (Uint) 0xffffffff) {
                        WSTACK_DESTROY(s);
                        return ERTS_EXT_SZ_SYSTEM_LIMIT;
                    }
                }
#endif
                if (pb->thing_word == HEADER_SUB_BIN) {
                    ErlSubBin* sub = (ErlSubBin*) pb;
                    bitoffs = sub->bitoffs;
                    bitsize = sub->bitsize;
                    pb = (ProcBin*) binary_val(sub->orig);
                }
                if (vlen >= 0) {
                    Uint csz;
                    if (pb->thing_word == HEADER_PROC_BIN
                        && bitoffs == 0
                        && bin_size > ERL_ONHEAP_BIN_LIMIT) {
                        Uint trailing_result;
                        if (bitsize == 0) {
                            result += (1 /* BIT_BINARY_EXT */
                                       + 4 /* size */);
                            trailing_result = 0;
                        }
                        else if (dflags & DFLAG_BIT_BINARIES) {
                            result += (1 /* BIT_BINARY_EXT */
                                       + 4 /* size */
                                       + 1 /* trailing bitsize */);
                            trailing_result = 1 /* trailing bits */;
                        }
                        else {
                            /* sigh... */
                            result += (1 /* SMALL_TUPLE_EXT */
                                       + 1 /* 2 tuple size */
                                       + 1 /* BINARY_EXT */
                                       + 4 /* binary size */);
                            trailing_result = (1 /* SMALL_INTEGER_EXT */
                                               + 1 /* bitsize */);
                        }
                        csz = result - ctx->last_result;
                        ctx->last_result = result;
                        result += trailing_result;
                        vlen += 2; /* data leading up to binary and binary */

                        /* potentially multiple elements leading up to binary */
                        vlen += csz/MAX_SYSIOVEC_IOVLEN;
                        /* potentially multiple elements for binary */
                        vlen += bin_size/MAX_SYSIOVEC_IOVLEN;
                        ctx->extra_size += bin_size;

                        if (dflags & DFLAG_PENDING_CONNECT) {
                            ASSERT(dflags & DFLAG_BIT_BINARIES);
                            vlen += 2; /* for hopefull prolog and epilog */
                            result += (4 /* for hopefull prolog (see below) */
                                       + 4); /* for hopefull epilog (see below) */
                            ctx->last_result = result;
                        }
                        break;
                    }
                }
	    }

            if (bitsize == 0) {
                result += (1 /* BIT_BINARY_EXT */
                           + 4 /* size */
                           + bin_size);
            }
            else if (dflags & DFLAG_PENDING_CONNECT) {
                Uint csz = result - ctx->last_result;
                ASSERT(dflags & DFLAG_BIT_BINARIES);
                /* potentially multiple elements leading up to binary */
                vlen += csz/MAX_SYSIOVEC_IOVLEN;
                vlen++; /* hopefull prolog */
                /*
                 * Size for hopefull prolog is max of
                 * - fallback: 1 + 1 + 1 + 4
                 * - hopfull index + bit binary prolog: 4 + 1 + 4 + 1
                 */
                result += 4 + 1 + 4 + 1;
                /* potentially multiple elements for binary */
                vlen += bin_size/MAX_SYSIOVEC_IOVLEN + 1;
                result += bin_size;
                vlen++; /* hopefull epiolog */
                /*
                 * Size for hopefull epiolog is max of
                 * - fallback: 1 + 1 + 1
                 * - hopfull index + bit binary epilog: 4 + 1
                 */
                result += 4 + 1;
                ctx->last_result = result;
            }
            else if (dflags & DFLAG_BIT_BINARIES) {
                result += 1 + 4 + 1 + bin_size + 1;
            }
            else {
                /* Sigh... */
                result += 1 + 1 + 1 + 4 + bin_size + 1 + 1 + 1;
            }
	    break;
        }
	case FUN_DEF:
	    {
		ErlFunThing* funp = (ErlFunThing *) fun_val(obj);
		
                ASSERT(dflags & DFLAG_NEW_FUN_TAGS);
                result += 20+1+1+4;	/* New ID + Tag */
                result += 4; /* Length field (number of free variables */
                result += encode_size_struct2(acmp, funp->creator, dflags);
                result += encode_size_struct2(acmp, funp->fe->module, dflags);
                result += 2 * (1+4);	/* Index, Uniq */
		if (funp->num_free > 1) {
		    WSTACK_PUSH2(s, (UWord) (funp->env + 1),
				    (UWord) TERM_ARRAY_OP(funp->num_free-1));
		}
		if (funp->num_free != 0) {
		    obj = funp->env[0];
		    continue; /* big loop */
		}
		break;
	    }

	case EXPORT_DEF:
	    {
		Export* ep = *((Export **) (export_val(obj) + 1));
                Uint tmp_result = result;
		result += 1;
		result += encode_size_struct2(acmp, ep->info.mfa.module, dflags);
		result += encode_size_struct2(acmp, ep->info.mfa.function, dflags);
		result += encode_size_struct2(acmp, make_small(ep->info.mfa.arity), dflags);
                if (dflags & DFLAG_PENDING_CONNECT) {
                    Uint csz;
                    /*
                     * Fallback is 1 + 1 + Module size + Function size, that is,
                     * the hopefull index + hopefull encoding is larger...
                     */
                    ASSERT(dflags & DFLAG_EXPORT_PTR_TAG);
                    csz = tmp_result - ctx->last_result;
                    /* potentially multiple elements leading up to hopefull entry */
                    vlen += csz/MAX_SYSIOVEC_IOVLEN;
                    vlen++; /* hopefull entry */
                    result += 4; /* hopefull index */
                    ctx->last_result = result;
                }
	    }
	    break;

	default:
	    erts_exit(ERTS_ERROR_EXIT,"Internal data structure error (in encode_size_struct_int) %x\n",
		     obj);
	}

	if (WSTACK_ISEMPTY(s)) {
	    break;
	}
	obj = (Eterm) WSTACK_POP(s);

        if (is_header(obj)) {
            switch (obj) {
            case LIST_TAIL_OP:
		obj = (Eterm) WSTACK_POP(s);
		if (is_list(obj)) {
		    Eterm* cons = list_val(obj);

		    WSTACK_PUSH2(s, (UWord)CDR(cons), (UWord)LIST_TAIL_OP);
		    obj = CAR(cons);
		}
		break;

	    case TERM_ARRAY_OP(1):
		obj = *(Eterm*)WSTACK_POP(s);
		break;
	    default: { /* TERM_ARRAY_OP(N) when N > 1 */
		Eterm* ptr = (Eterm*) WSTACK_POP(s);
		WSTACK_PUSH2(s, (UWord) (ptr+1),
			        (UWord) TERM_ARRAY_OP_DEC(obj));
		obj = *ptr;
	    }
	    }
	}
    }

    WSTACK_DESTROY(s);
    if (ctx) {
	ASSERT(ctx->wstack.wstart == NULL);
	*reds = r < 0 ? 0 : r;

        if (vlen >= 0) {
            Uint csz;
            csz = result - ctx->last_result;
            if (csz)
                vlen += csz/MAX_SYSIOVEC_IOVLEN + 1;
            ctx->vlen = vlen;
        }
    }
    *res = result;
    return ERTS_EXT_SZ_OK;
}



static Sint
decoded_size(byte *ep, byte* endp, int internal_tags, B2TContext* ctx)
{
    Sint heap_size;
    int terms;
    int atom_extra_skip;
    Uint n;
    SWord reds;

    if (ctx) {
        reds = ctx->reds;
        if (ctx->u.sc.ep) {
            heap_size = ctx->u.sc.heap_size;
            terms = ctx->u.sc.terms;
            ep = ctx->u.sc.ep;
            atom_extra_skip = ctx->u.sc.atom_extra_skip;
            goto init_done;
        }
    }
    else
        ERTS_UNDEF(reds, 0);

    heap_size = 0;
    terms = 1;
    atom_extra_skip = 0;
init_done:

#define SKIP(sz)				\
    do {					\
	if ((sz) <= endp-ep) {			\
	    ep += (sz);				\
        } else { goto error; };			\
    } while (0)

#define SKIP2(sz1, sz2)				\
    do {					\
	Uint sz = (sz1) + (sz2);		\
	if (sz1 < sz && (sz) <= endp-ep) {	\
	    ep += (sz);				\
        } else { goto error; }			\
    } while (0)

#define CHKSIZE(sz)				\
    do {					\
	 if ((sz) > endp-ep) { goto error; }	\
    } while (0)

#define ADDTERMS(n)				\
    do {					\
        int before = terms;		        \
	terms += (n);                           \
	if (terms < before) goto error;     	\
    } while (0)

    ASSERT(terms > 0);
    do {
        int tag;
	CHKSIZE(1);
	tag = ep++[0];
	switch (tag) {
	case INTEGER_EXT:
	    SKIP(4);
#if !defined(ARCH_64)
	    heap_size += BIG_UINT_HEAP_SIZE;
#endif
	    break;
	case SMALL_INTEGER_EXT:
	    SKIP(1);
	    break;
	case SMALL_BIG_EXT:
	    CHKSIZE(1);
	    n = ep[0];		/* number of bytes */
	    SKIP2(n, 1+1);		/* skip size,sign,digits */
	    heap_size += 1+(n+sizeof(Eterm)-1)/sizeof(Eterm); /* XXX: 1 too much? */
	    break;
	case LARGE_BIG_EXT:
	    CHKSIZE(4);
	    n = get_int32(ep);
	    if (n > BIG_ARITY_MAX*sizeof(ErtsDigit)) {
		goto error;
	    }
	    SKIP2(n,4+1);		/* skip, size,sign,digits */
	    heap_size += 1+1+(n+sizeof(Eterm)-1)/sizeof(Eterm); /* XXX: 1 too much? */
	    break;
	case ATOM_EXT:
	    CHKSIZE(2);
	    n = get_int16(ep);
	    if (n > MAX_ATOM_CHARACTERS) {
		goto error;
	    }
	    SKIP(n+2+atom_extra_skip);
	    atom_extra_skip = 0;
	    break;
	case ATOM_UTF8_EXT:
	    CHKSIZE(2);
	    n = get_int16(ep);
	    ep += 2;
	    if (n > MAX_ATOM_SZ_LIMIT) {
		goto error;
	    }
	    SKIP(n+atom_extra_skip);
	    atom_extra_skip = 0;
	    break;
	case SMALL_ATOM_EXT:
	    CHKSIZE(1);
	    n = get_int8(ep);
	    if (n > MAX_ATOM_CHARACTERS) {
		goto error;
	    }
	    SKIP(n+1+atom_extra_skip);
	    atom_extra_skip = 0;
	    break;
	case SMALL_ATOM_UTF8_EXT:
	    CHKSIZE(1);
	    n = get_int8(ep);
	    ep++;
	    if (n > MAX_ATOM_SZ_LIMIT) {
		goto error;
	    }
	    SKIP(n+atom_extra_skip);
	    atom_extra_skip = 0;
	    break;
	case ATOM_CACHE_REF:
	    SKIP(1+atom_extra_skip);
	    atom_extra_skip = 0;
	    break;
        case NEW_PID_EXT:
	    atom_extra_skip = 12;
	    goto case_PID;
        case PID_EXT:
	    atom_extra_skip = 9;
	case_PID:
	    /* In case it is an external pid */
	    heap_size += EXTERNAL_THING_HEAD_SIZE + 1;
	    terms++;
	    break;
        case NEW_PORT_EXT:
	    atom_extra_skip = 8;
	    goto case_PORT;
        case PORT_EXT:
	    atom_extra_skip = 5;
	case_PORT:
	    /* In case it is an external port */
	    heap_size += EXTERNAL_THING_HEAD_SIZE + 1;
	    terms++;
	    break;
	case NEWER_REFERENCE_EXT:
	    atom_extra_skip = 4;
	    goto case_NEW_REFERENCE;
        case NEW_REFERENCE_EXT:
	    atom_extra_skip = 1;
	case_NEW_REFERENCE:
	    {
		int id_words;

		CHKSIZE(2);
		id_words = get_int16(ep);
		    
		if (id_words > ERTS_MAX_REF_NUMBERS)
		    goto error;

		ep += 2;
		atom_extra_skip += 4*id_words;
		/* In case it is an external ref */
#if defined(ARCH_64)
		heap_size += EXTERNAL_THING_HEAD_SIZE + id_words/2 + 1;
#else
		heap_size += EXTERNAL_THING_HEAD_SIZE + id_words;
#endif
		terms++;
		break;
	    }
	case REFERENCE_EXT:
	    /* In case it is an external ref */
	    heap_size += EXTERNAL_THING_HEAD_SIZE + 1;
	    atom_extra_skip = 5;
	    terms++;
	    break;
	case NIL_EXT:
	    break;
	case LIST_EXT:
	    CHKSIZE(4);
	    n = get_int32(ep);
	    ep += 4;
	    ADDTERMS(n);
	    terms++;
	    heap_size += 2 * n;
	    break;
	case SMALL_TUPLE_EXT:
	    CHKSIZE(1);
	    n = *ep++;
	    terms += n;
	    heap_size += n + 1;
	    break;
	case LARGE_TUPLE_EXT:
	    CHKSIZE(4);
	    n = get_int32(ep);
	    ep += 4;
	    ADDTERMS(n);
	    heap_size += n + 1;
	    break;
	case MAP_EXT:
	    CHKSIZE(4);
	    n = get_int32(ep);
	    ep += 4;
	    ADDTERMS(2*n);
            if (n <= MAP_SMALL_MAP_LIMIT) {
                heap_size += 3 + n + 1 + n;
            } else {
                heap_size += HASHMAP_ESTIMATED_HEAP_SIZE(n);
            }
	    break;
	case STRING_EXT:
	    CHKSIZE(2);
	    n = get_int16(ep);
	    SKIP(n+2);
	    heap_size += 2 * n;
	    break;
	case FLOAT_EXT:
	    SKIP(31);
	    heap_size += FLOAT_SIZE_OBJECT;
	    break;
	case NEW_FLOAT_EXT:
	    SKIP(8);
	    heap_size += FLOAT_SIZE_OBJECT;
	    break;
	case BINARY_EXT:
	    CHKSIZE(4);
	    n = get_int32(ep);
	    SKIP2(n, 4);
	    if (n <= ERL_ONHEAP_BIN_LIMIT) {
		heap_size += heap_bin_size(n);
	    } else {
		heap_size += PROC_BIN_SIZE;
	    }
	    break;
	case BIT_BINARY_EXT:
	    {
		CHKSIZE(5);
		n = get_int32(ep);
		SKIP2(n, 5);
		if (n <= ERL_ONHEAP_BIN_LIMIT) {
		    heap_size += heap_bin_size(n) + ERL_SUB_BIN_SIZE;
		} else {
		    heap_size += PROC_BIN_SIZE + ERL_SUB_BIN_SIZE;
		}
	    }
	    break;
	case EXPORT_EXT:
	    terms += 3;
	    heap_size += 2;
	    break;
	case NEW_FUN_EXT:
	    {
		unsigned num_free;
		Uint total_size;

		CHKSIZE(1+16+4+4);
		total_size = get_int32(ep);
		CHKSIZE(total_size);		
		ep += 1+16+4+4;
		CHKSIZE(4);
		num_free = get_int32(ep);
		ep += 4;
		if (num_free > MAX_ARG) {
		    goto error;
		}
		terms += 4 + num_free;
		heap_size += ERL_FUN_SIZE + num_free;
		break;
	    }
	case FUN_EXT:
            /*
             * OTP 23: No longer support decoding the old fun
             * representation.
             */
            goto error;
	case ATOM_INTERNAL_REF2:
	    SKIP(2+atom_extra_skip);
	    atom_extra_skip = 0;
	    break;
	case ATOM_INTERNAL_REF3:
	    SKIP(3+atom_extra_skip);
	    atom_extra_skip = 0;
	    break;

	case BINARY_INTERNAL_REF:
	    if (!internal_tags) {
		goto error;
	    }
	    SKIP(sizeof(ProcBin));
	    heap_size += PROC_BIN_SIZE;
	    break;
	case BIT_BINARY_INTERNAL_REF:
	    if (!internal_tags) {
		goto error;
	    }
	    SKIP(2+sizeof(ProcBin));
	    heap_size += PROC_BIN_SIZE + ERL_SUB_BIN_SIZE;
	    break;
	default:
	    goto error;
	}
        terms--;

        if (ctx && --reds <= 0 && terms > 0) {
            ctx->u.sc.heap_size = heap_size;
            ctx->u.sc.terms = terms;
            ctx->u.sc.ep = ep;
            ctx->u.sc.atom_extra_skip = atom_extra_skip;
            ctx->reds = 0;
            return 0;
        }
    }while (terms > 0);

    /* 'terms' may be non-zero if it has wrapped around */
    if (terms == 0) {
        if (ctx) {
            ctx->state = B2TDecodeInit;
            ctx->reds = reds;
        }
        return heap_size;
    }

error:
    if (ctx) {
        ctx->state = B2TBadArg;
    }
    return -1;
#undef SKIP
#undef SKIP2
#undef CHKSIZE
}

#define ERTS_TRANSCODE_REDS_FACT 4

Sint transcode_dist_obuf(ErtsDistOutputBuf* ob,
                         DistEntry* dep,
                         Uint64 dflags,
                         Sint reds)
{
    ErlIOVec* eiov = ob->eiov;
    SysIOVec* iov = eiov->iov;
    byte *hdr;
    Uint64 hopefull_flags;
    Uint32 hopefull_ix, payload_ix;
    Sint start_r, r;
    Uint new_len;
    byte *ep;

    if (reds < 0)
        return reds;

    /*
     * HOPEFUL_DATA header always present in io vector
     * element 1:
     *
     * +---+--------------+-----------+----------+
     * |'H'|Hopefull Flags|Hopefull IX|Payload IX|
     * +---+--------------+-----------+----------+
     *   1         8            4          4
     *
     * Hopefull flags: Flags corresponding to actual
     *                 hopefull encodings in this
     *                 buffer.
     * Hopefull IX:    Vector index of first hopefull
     *                 encoding. Each hopefull encoding
     *                 is preceeded by 4 bytes containing
     *                 next vector index of hopefull
     *                 encoding. ERTS_NO_HIX marks the
     *                 end.
     * Payload IX:     Vector index of the beginning
     *                 of the payload if there is
     *                 one; otherwise, zero.
     */
    hdr = (byte *) iov[1].iov_base;

    ASSERT(HOPEFUL_DATA == *((byte *)iov[1].iov_base));
    ASSERT(iov[1].iov_len == 1+8+4+4);
    
    /* Control message always begin in vector element 2 */
    ep = iov[2].iov_base;
    ASSERT(ep[0] == SMALL_TUPLE_EXT || ep[0] == LARGE_TUPLE_EXT);

    if (~dflags & (DFLAG_DIST_MONITOR | DFLAG_DIST_MONITOR_NAME)
        && ep[0] == SMALL_TUPLE_EXT
        && ep[1] == 4
        && ep[2] == SMALL_INTEGER_EXT
        && (ep[3] == DOP_MONITOR_P ||
            ep[3] == DOP_MONITOR_P_EXIT ||
            ep[3] == DOP_DEMONITOR_P)) {
        /*
         * Receiver does not support process monitoring.
         * Suppress monitor control msg (see erts_dsig_send_monitor)
         * by converting it to an empty (tick) packet.
         */
        int i;
        for (i = 1; i < ob->eiov->vsize; i++) {
            if (ob->eiov->binv[i])
                driver_free_binary(ob->eiov->binv[i]);
        }
        ob->eiov->vsize = 1;
        ob->eiov->size = 0;
        return reds;
    }

    hdr++;
    hopefull_flags = get_int64(hdr);

    hdr += 8;
    hopefull_ix = get_int32(hdr);

    if ((~dflags & DFLAG_SPAWN)
        && ep[0] == SMALL_TUPLE_EXT
        && ((ep[1] == 6
             && ep[2] == SMALL_INTEGER_EXT
             && ep[3] == DOP_SPAWN_REQUEST)
            || (ep[1] == 8
                && ep[2] == SMALL_INTEGER_EXT
                && ep[3] == DOP_SPAWN_REQUEST_TT))) {
        /*
         * Receiver does not support distributed spawn. Convert
         * this packet to an empty (tick) packet, and inform
         * spawning process that this is not supported...
         */
        ErtsHeapFactory factory;
        Eterm ctl_msg, ref, pid, token, *tp, *hp;
        Uint buf_sz;
        byte *buf_start, *buf_end;
        byte *ptr;
        Uint hsz;
        int i;

        hdr += 4;
        payload_ix = get_int32(hdr);
        ASSERT(payload_ix >= 3);

        if (payload_ix == 3) {
            /* The whole control message is in iov[2].iov_base */
            buf_sz = (Uint) iov[2].iov_len;
            buf_start = (byte *) iov[2].iov_base;
            buf_end = buf_start + buf_sz;
        }
        else {
            /* Control message over multiple buffers... */
            int ix;
            buf_sz = 0;
            for (ix = 2; ix < payload_ix; ix++)
                buf_sz += iov[ix].iov_len;
            ptr = buf_start = erts_alloc(ERTS_ALC_T_TMP, buf_sz);
            buf_end = buf_start + buf_sz;
            for (ix = 2; ix < payload_ix; ix++) {
                sys_memcpy((void *) ptr,
                           (void *) iov[ix].iov_base,
                           iov[ix].iov_len);
                ptr += iov[ix].iov_len;
            }
        }

        hsz = decoded_size(buf_start, buf_end, 0, NULL);
        hp = erts_alloc(ERTS_ALC_T_TMP, hsz*sizeof(Eterm));
        erts_factory_tmp_init(&factory, hp, hsz, ERTS_ALC_T_TMP);
            
        ptr = dec_term(NULL, &factory, buf_start, &ctl_msg, NULL, 0);
        ASSERT(ptr); (void)ptr;

        ASSERT(is_tuple_arity(ctl_msg, 6)
               || is_tuple_arity(ctl_msg, 8));
        tp = tuple_val(ctl_msg);
        ASSERT(tp[1] == make_small(DOP_SPAWN_REQUEST)
               || tp[1] == make_small(DOP_SPAWN_REQUEST_TT));

        ref = tp[2];
        pid = tp[3];
        if (tp[1] == make_small(DOP_SPAWN_REQUEST))
            token = NIL;
        else {
            token = tp[8];
            erts_seq_trace_update_node_token(token);
        }
        ASSERT(is_internal_ordinary_ref(tp[2]));
        ASSERT(is_internal_pid(tp[3]));
        
        (void) erts_proc_sig_send_dist_spawn_reply(dep->sysname,
                                                   ref, pid,
                                                   NULL, am_notsup,
                                                   token);

        erts_factory_close(&factory);
        erts_free(ERTS_ALC_T_TMP, hp);
        if (buf_start != (byte *) iov[2].iov_base)
            erts_free(ERTS_ALC_T_TMP, buf_start);

        for (i = 1; i < ob->eiov->vsize; i++) {
            if (ob->eiov->binv[i])
                driver_free_binary(ob->eiov->binv[i]);
        }
        ob->eiov->vsize = 1;
        ob->eiov->size = 0;
        
        reds -= 4;
        
        if (reds < 0)
            return 0;
        return reds;
    }
    
    start_r = r = reds*ERTS_TRANSCODE_REDS_FACT;

    if (~dflags & hopefull_flags) {

        while (hopefull_ix != ERTS_NO_HIX) {
            Uint32 new_hopefull_ix;
            
            if (r <= 0) { /* yield... */
                /* save current hopefull_ix... */
                ep = (byte *) iov[1].iov_base;
                ep += 5;
                put_int32(hopefull_ix, ep);
                return -1;
            }

            /* Read next hopefull index */
            ep = (byte *) iov[hopefull_ix].iov_base;
            ep -= 4;
            new_hopefull_ix = get_int32(ep);
            ASSERT(new_hopefull_ix == ERTS_NO_HIX
                   || (hopefull_ix < new_hopefull_ix
                       && new_hopefull_ix < eiov->vsize));
            
            ep = (byte *) iov[hopefull_ix].iov_base;
            switch (*ep) {

            case EXPORT_EXT: {
                byte *start_ep, *end_ep;
                Eterm module, function;
                if (!(hopefull_flags & DFLAG_EXPORT_PTR_TAG))
                    break;
                /* Read original encoding... */
                ep++;
                start_ep = ep;
                ep = dec_atom(NULL, ep, &module);
                ASSERT(ep && is_atom(module));
                ep = dec_atom(NULL, ep, &function);
                ASSERT(ep && is_atom(function));
                end_ep = ep;
                ASSERT(*ep == SMALL_INTEGER_EXT
                       || *ep == INTEGER_EXT
                       || *ep == SMALL_BIG_EXT
                       || *ep == LARGE_BIG_EXT);

                /*
                 * module and function atoms are encoded
                 * between start_ep and end_ep. Prepend a
                 * 2-tuple tag before the atoms and
                 * remove arity at end.
                 */

                /* write fallback */

                ep = start_ep;
                ep--;
                put_int8(2, ep);
                ep--;
                *ep = SMALL_TUPLE_EXT;

                iov[hopefull_ix].iov_base = ep;

                /* Update iov sizes... */
                new_len = end_ep - ep;
                eiov->size -= iov[hopefull_ix].iov_len;
                eiov->size += new_len;
                iov[hopefull_ix].iov_len = new_len;
                r--;
                break;
            }

            case BIT_BINARY_EXT: {
                Uint bin_sz;
                byte bitsize, epilog_byte;
                ASSERT(hopefull_ix != ERTS_NO_HIX);
                if (!(hopefull_flags & DFLAG_BIT_BINARIES)) {
                    /* skip to epilog... */
                    hopefull_ix = new_hopefull_ix;
                    ep = (byte *) iov[hopefull_ix].iov_base;
                    ep -= 4;
                    new_hopefull_ix = get_int32(ep);
                    ASSERT(new_hopefull_ix == ERTS_NO_HIX
                           || (hopefull_ix < new_hopefull_ix
                               && new_hopefull_ix < eiov->vsize));
                    break;
                }

                /* read original encoded prolog... */
                ep++;
                bin_sz = get_int32(ep);
                ep += 4;
                bitsize = *ep++;

                /* write fallback prolog... */
                iov[hopefull_ix].iov_base -= 4;
                ep = (byte *) iov[hopefull_ix].iov_base;

                *ep++ = SMALL_TUPLE_EXT;
                *ep++ = 2;
                *ep++ = BINARY_EXT;
                put_int32(bin_sz, ep);
                ep += 4;

                /* Update iov sizes... */
                new_len = ep - (byte *) iov[hopefull_ix].iov_base;
                eiov->size -= iov[hopefull_ix].iov_len;
                eiov->size += new_len;
                iov[hopefull_ix].iov_len = new_len;
                r--;
#ifdef DEBUG
                /*
                 * The binary data between the prolog and the
                 * epilog should be of size 'bin_sz - 1' and
                 * exists in the iov elements between prolog
                 * and epilog...
                 */
                {
                    Uint ix, debug_bin_sz = 0;
                    for (ix = hopefull_ix+1; ix < new_hopefull_ix; ix++)
                        debug_bin_sz += iov[ix].iov_len;
                    ASSERT(debug_bin_sz == bin_sz - 1);
                }
#endif
                /* jump to epilog... */
                hopefull_ix = new_hopefull_ix;
                ep = (byte *) iov[hopefull_ix].iov_base;

                /* read original encoded epilog... */
                epilog_byte = *ep;

                ASSERT(1 == iov[hopefull_ix].iov_len);

                iov[hopefull_ix].iov_base -= 4;
                ep = (byte *) iov[hopefull_ix].iov_base;
                new_hopefull_ix = get_int32(ep);
                ASSERT(new_hopefull_ix == ERTS_NO_HIX
                       || (hopefull_ix < new_hopefull_ix
                           && new_hopefull_ix < eiov->vsize));
                
                /* write fallback epilog... */

                *ep++ = epilog_byte;
                *ep++ = SMALL_INTEGER_EXT;
                *ep++ = bitsize;

                /* Update iov sizes... */
                new_len = ep - (byte *) iov[hopefull_ix].iov_base;
                eiov->size -= iov[hopefull_ix].iov_len;
                eiov->size += new_len;
                iov[hopefull_ix].iov_len = new_len;
                r--;
                break;
            }

            default:
                ERTS_INTERNAL_ERROR("Unexpected external tag");
                break;
            }

            hopefull_ix = new_hopefull_ix;
            r--;
        }
    }

    /*
     * Replace hopefull data header with actual header...
     */
    ep = (byte *) iov[1].iov_base;
    eiov->size -= iov[1].iov_len;

    if (dflags & (DFLAG_DIST_HDR_ATOM_CACHE|DFLAG_FRAGMENTS)) {
        /*
         * Encoding was done without atom caching but receiver expects
         * a dist header, so we prepend an empty one.
         */
        *ep++ = VERSION_MAGIC;
        *ep++ = DIST_HEADER;
        *ep++ = 0; /* NumberOfAtomCacheRefs */
    }
    else {
        hdr += 4;
        payload_ix = get_int32(hdr);

        if (payload_ix) {
            ASSERT(0 < payload_ix && payload_ix < eiov->vsize);
            /* Prepend version magic on payload. */
            iov[payload_ix].iov_base--;
            *((byte *) iov[payload_ix].iov_base) = VERSION_MAGIC;
            iov[payload_ix].iov_len++;
            eiov->size++;
            r--;
        }

        *ep++ = PASS_THROUGH;
        *ep++ = VERSION_MAGIC;
    }

    iov[1].iov_len = ep - (byte *) iov[1].iov_base;
    eiov->size += iov[1].iov_len;

    r--;

    /* done... */

    reds -= (start_r - r)/ERTS_TRANSCODE_REDS_FACT + 1;
    if (reds < 0)
        return 0;
    return reds;
}