aboutsummaryrefslogtreecommitdiff
path: root/nx-X11/programs/Xserver/record/record.c
blob: fd5e5db1db7904011d85082dd641de019f6998dd (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
/* $XdotOrg: xc/programs/Xserver/record/record.c,v 1.5 2005/07/03 07:02:08 daniels Exp $ */
/* $Xorg: record.c,v 1.4 2001/02/09 02:05:27 xorgcvs Exp $ */

/*

Copyright 1995, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from The Open Group.

Author: David P. Wiggins, The Open Group

This work benefited from earlier work done by Martha Zimet of NCD
and Jim Haggerty of Metheus.

*/
/* $XFree86: xc/programs/Xserver/record/record.c,v 1.11 2003/11/03 05:12:01 tsi Exp $ */

#define NEED_EVENTS
#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif

#include "dixstruct.h"
#include "extnsionst.h"
#define _XRECORD_SERVER_
#include <X11/extensions/recordstr.h>
#include "set.h"

#ifndef XFree86LOADER
#include <stdio.h>
#include <assert.h>
#else
#include "xf86_ansic.h"
#endif

#ifdef PANORAMIX
#include "globals.h"
#include "panoramiX.h"
#include "panoramiXsrv.h"
#include "cursor.h"
#endif

static RESTYPE RTContext;   /* internal resource type for Record contexts */
static int RecordErrorBase; /* first Record error number */

/* How many bytes of protocol data to buffer in a context. Don't set to less
 * than 32.
 */
#define REPLY_BUF_SIZE 1024

/* Record Context structure */

typedef struct {
    XID		id;		   /* resource id of context */
    ClientPtr	pRecordingClient;  /* client that has context enabled */
    struct _RecordClientsAndProtocolRec *pListOfRCAP; /* all registered info */
    ClientPtr	pBufClient;	   /* client whose protocol is in replyBuffer*/
    unsigned int continuedReply:1; /* recording a reply that is split up? */
    char	elemHeaders;	   /* element header flags (time/seq no.) */
    char	bufCategory;	   /* category of protocol in replyBuffer */
    int		numBufBytes;	   /* number of bytes in replyBuffer */
    char	replyBuffer[REPLY_BUF_SIZE]; /* buffered recorded protocol */
} RecordContextRec, *RecordContextPtr;

/*  RecordMinorOpRec - to hold minor opcode selections for extension requests
 *  and replies
 */

typedef union {
    int count; /* first element of array: how many "major" structs to follow */
    struct {   /* rest of array elements are this */
	short first;		/* first major opcode */
	short last;		/* last major opcode */
	RecordSetPtr pMinOpSet; /*  minor opcode set for above major range */
    } major;
} RecordMinorOpRec, *RecordMinorOpPtr;


/*  RecordClientsAndProtocolRec, nicknamed RCAP - holds all the client and 
 *  protocol selections passed in a single CreateContext or RegisterClients.
 *  Generally, a context will have one of these from the create and an
 *  additional one for each RegisterClients.  RCAPs are freed when all their
 *  clients are unregistered.
 */

typedef struct _RecordClientsAndProtocolRec {
    RecordContextPtr pContext;		 /* context that owns this RCAP */
    struct _RecordClientsAndProtocolRec *pNextRCAP; /* next RCAP on context */
    RecordSetPtr     pRequestMajorOpSet; /* requests to record */
    RecordMinorOpPtr pRequestMinOpInfo;  /* extension requests to record */
    RecordSetPtr     pReplyMajorOpSet;   /* replies to record */
    RecordMinorOpPtr pReplyMinOpInfo;    /* extension replies to record */
    RecordSetPtr     pDeviceEventSet;    /* device events to record */
    RecordSetPtr     pDeliveredEventSet; /* delivered events to record */
    RecordSetPtr     pErrorSet;          /* errors to record */
    XID *	     pClientIDs;	 /* array of clients to record */
    short 	     numClients;	 /* number of clients in pClientIDs */
    short	     sizeClients;	 /* size of pClientIDs array */
    unsigned int     clientStarted:1;	 /* record new client connections? */
    unsigned int     clientDied:1;	 /* record client disconnections? */
    unsigned int     clientIDsSeparatelyAllocated:1; /* pClientIDs malloced? */
} RecordClientsAndProtocolRec, *RecordClientsAndProtocolPtr;

/* how much bigger to make pRCAP->pClientIDs when reallocing */
#define CLIENT_ARRAY_GROWTH_INCREMENT 4

/* counts the total number of RCAPs belonging to enabled contexts. */
static int numEnabledRCAPs;

/*  void VERIFY_CONTEXT(RecordContextPtr, XID, ClientPtr)
 *  In the spirit of the VERIFY_* macros in dix.h, this macro fills in
 *  the context pointer if the given ID is a valid Record Context, else it
 *  returns an error.
 */
#define VERIFY_CONTEXT(_pContext, _contextid, _client) { \
    (_pContext) = (RecordContextPtr)LookupIDByType((_contextid), RTContext); \
    if (!(_pContext)) { \
        (_client)->errorValue = (_contextid); \
	return RecordErrorBase + XRecordBadContext; \
    } \
}

static int RecordDeleteContext(
    pointer /*value*/,
    XID /*id*/
);

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

/* client private stuff */

/*  To make declarations less obfuscated, have a typedef for a pointer to a
 *  Proc function.
 */
typedef int (*ProcFunctionPtr)(
    ClientPtr /*pClient*/
);

/* Record client private.  Generally a client only has one of these if
 * any of its requests are being recorded.
 */
typedef struct {
/* ptr to client's proc vector before Record stuck its nose in */
    ProcFunctionPtr *originalVector;   
					
/* proc vector with pointers for recorded requests redirected to the
 * function RecordARequest
 */
    ProcFunctionPtr recordVector[256]; 
} RecordClientPrivateRec, *RecordClientPrivatePtr;

static int RecordClientPrivateIndex;

/*  RecordClientPrivatePtr RecordClientPrivate(ClientPtr)
 *  gets the client private of the given client.  Syntactic sugar.
 */
#define RecordClientPrivate(_pClient) (RecordClientPrivatePtr) \
    ((_pClient)->devPrivates[RecordClientPrivateIndex].ptr)

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

/* global list of all contexts */

static RecordContextPtr *ppAllContexts;

static int numContexts;/* number of contexts in ppAllContexts */

/* number of currently enabled contexts.  All enabled contexts are bunched
 * up at the front of the ppAllContexts array, from ppAllContexts[0] to
 * ppAllContexts[numEnabledContexts-1], to eliminate time spent skipping
 * past disabled contexts.
 */
static int numEnabledContexts;

/* RecordFindContextOnAllContexts
 *
 * Arguments:
 *	pContext is the context to search for.
 *
 * Returns:
 *	The index into the array ppAllContexts at which pContext is stored.
 *	If pContext is not found in ppAllContexts, returns -1.
 *
 * Side Effects: none.
 */
static int
RecordFindContextOnAllContexts(pContext)
    RecordContextPtr pContext;
{
    int i;

    assert(numContexts >= numEnabledContexts);
    for (i = 0; i < numContexts; i++)
    {
	if (ppAllContexts[i] == pContext)
	    return i;
    }
    return -1;
} /* RecordFindContextOnAllContexts */

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

/* RecordFlushReplyBuffer
 *
 * Arguments:
 *	pContext is the context to flush.
 *	data1 is a pointer to additional data, and len1 is its length in bytes.
 *	data2 is a pointer to additional data, and len2 is its length in bytes.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	If the context is enabled, any buffered (recorded) protocol is written
 *	to the recording client, and the number of buffered bytes is set to
 *	zero.  If len1 is not zero, data1/len1 are then written to the
 *	recording client, and similarly for data2/len2 (written after
 *	data1/len1).
 */
static void
RecordFlushReplyBuffer(
    RecordContextPtr pContext,
    pointer data1,
    int len1,
    pointer data2,
    int len2
)
{
    if (!pContext->pRecordingClient || pContext->pRecordingClient->clientGone) 
	return;
    if (pContext->numBufBytes)
	WriteToClient(pContext->pRecordingClient, pContext->numBufBytes,
		      (char *)pContext->replyBuffer);
    pContext->numBufBytes = 0;
    if (len1)
	WriteToClient(pContext->pRecordingClient, len1, (char *)data1);
    if (len2)
	WriteToClient(pContext->pRecordingClient, len2, (char *)data2);
} /* RecordFlushReplyBuffer */


/* RecordAProtocolElement
 *
 * Arguments:
 *	pContext is the context that is recording a protocol element.
 *	pClient is the client whose protocol is being recorded.  For
 *	  device events and EndOfData, pClient is NULL.
 *	category is the category of the protocol element, as defined
 *	  by the RECORD spec.
 *	data is a pointer to the protocol data, and datalen is its length
 *	  in bytes.
 *	futurelen is the number of bytes that will be sent in subsequent
 *	  calls to this function to complete this protocol element.  
 *	  In those subsequent calls, futurelen will be -1 to indicate
 *	  that the current data is a continuation of the same protocol
 *	  element.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	The context may be flushed.  The new protocol element will be
 *	added to the context's protocol buffer with appropriate element
 *	headers prepended (sequence number and timestamp).  If the data
 *	is continuation data (futurelen == -1), element headers won't
 *	be added.  If the protocol element and headers won't fit in
 *	the context's buffer, it is sent directly to the recording
 *	client (after any buffered data).
 */
static void
RecordAProtocolElement(RecordContextPtr pContext, ClientPtr pClient,
		       int category, pointer data, int datalen, int futurelen)
{
    CARD32 elemHeaderData[2];
    int numElemHeaders = 0;
    Bool recordingClientSwapped = pContext->pRecordingClient->swapped;
    int n;
    CARD32 serverTime = 0;
    Bool gotServerTime = FALSE;
    int replylen;

    if (futurelen >= 0)
    { /* start of new protocol element */
	xRecordEnableContextReply *pRep = (xRecordEnableContextReply *)
							pContext->replyBuffer;
	if (pContext->pBufClient != pClient ||
	    pContext->bufCategory != category)
	{
	    RecordFlushReplyBuffer(pContext, NULL, 0, NULL, 0);
	    pContext->pBufClient = pClient;
	    pContext->bufCategory = category;
	}

	if (!pContext->numBufBytes)
	{
	    serverTime = GetTimeInMillis();
	    gotServerTime = TRUE;
	    pRep->type          = X_Reply;
	    pRep->category      = category;
	    pRep->sequenceNumber = pContext->pRecordingClient->sequence;
	    pRep->length        = 0;
	    pRep->elementHeader = pContext->elemHeaders;
	    pRep->serverTime    = serverTime;
	    if (pClient)
	    {
		pRep->clientSwapped =
				(pClient->swapped != recordingClientSwapped);
		pRep->idBase = pClient->clientAsMask;
		pRep->recordedSequenceNumber = pClient->sequence;
	    }
	    else /* it's a device event, StartOfData, or EndOfData */
	    {
		pRep->clientSwapped = (category != XRecordFromServer) && 
						recordingClientSwapped;
		pRep->idBase = 0;
		pRep->recordedSequenceNumber = 0;
	    }

	    if (recordingClientSwapped)
	    {
		swaps(&pRep->sequenceNumber, n);
		swapl(&pRep->length, n);
		swapl(&pRep->idBase, n);
		swapl(&pRep->serverTime, n);
		swapl(&pRep->recordedSequenceNumber, n);
	    }
	    pContext->numBufBytes = SIZEOF(xRecordEnableContextReply);
	}

	/* generate element headers if needed */

	if ( ( (pContext->elemHeaders & XRecordFromClientTime)
	      && category == XRecordFromClient)
	    ||
	    ( (pContext->elemHeaders & XRecordFromServerTime)
	     && category == XRecordFromServer))
	{
	    if (gotServerTime)
		elemHeaderData[numElemHeaders] = serverTime;
	    else
		elemHeaderData[numElemHeaders] = GetTimeInMillis();
	    if (recordingClientSwapped)
		swapl(&elemHeaderData[numElemHeaders], n);
	    numElemHeaders++;
	}

	if ( (pContext->elemHeaders & XRecordFromClientSequence)
	    &&
	    (category == XRecordFromClient || category == XRecordClientDied))
	{
	    elemHeaderData[numElemHeaders] = pClient->sequence;
	    if (recordingClientSwapped)
		swapl(&elemHeaderData[numElemHeaders], n);
	    numElemHeaders++;
	}

	/* adjust reply length */

	replylen = pRep->length;
	if (recordingClientSwapped) swapl(&replylen, n);
	replylen += numElemHeaders + (datalen >> 2) + (futurelen >> 2);
	if (recordingClientSwapped) swapl(&replylen, n);
	pRep->length = replylen;
    } /* end if not continued reply */

    numElemHeaders *= 4;

    /* if space available >= space needed, buffer the data */

    if (REPLY_BUF_SIZE - pContext->numBufBytes >= datalen + numElemHeaders)
    {
	if (numElemHeaders)
	{
	    memcpy(pContext->replyBuffer + pContext->numBufBytes,
		   elemHeaderData, numElemHeaders);
	    pContext->numBufBytes += numElemHeaders;
	}
	if (datalen)
	{
	    memcpy(pContext->replyBuffer + pContext->numBufBytes,
		   data, datalen);
	    pContext->numBufBytes += datalen;
	}
    }
    else
	RecordFlushReplyBuffer(pContext, (pointer)elemHeaderData,
			       numElemHeaders, (pointer)data, datalen);

} /* RecordAProtocolElement */


/* RecordFindClientOnContext
 *
 * Arguments:
 *	pContext is the context to search.
 *	clientspec is the resource ID mask identifying the client to search
 *	  for, or XRecordFutureClients.
 *	pposition is a pointer to an int, or NULL.  See Returns.
 *
 * Returns:
 *	The RCAP on which clientspec was found, or NULL if not found on
 *	any RCAP on the given context.
 *	If pposition was not NULL and the returned RCAP is not NULL,
 *	*pposition will be set to the index into the returned the RCAP's
 *	pClientIDs array that holds clientspec.
 *
 * Side Effects: none.
 */
static RecordClientsAndProtocolPtr
RecordFindClientOnContext(
    RecordContextPtr pContext,
    XID clientspec,
    int *pposition
)
{
    RecordClientsAndProtocolPtr pRCAP;

    for (pRCAP = pContext->pListOfRCAP; pRCAP; pRCAP = pRCAP->pNextRCAP)
    {
	int i;
	for (i = 0; i < pRCAP->numClients; i++)
	{
	    if (pRCAP->pClientIDs[i] == clientspec)
	    {
		if (pposition)
		    *pposition = i;
		return pRCAP;
	    }
	}
    }
    return NULL;
} /* RecordFindClientOnContext */


/* RecordABigRequest
 *
 * Arguments:
 *	pContext is the recording context.
 *	client is the client being recorded.
 *	stuff is a pointer to the big request of client (see the Big Requests
 *	extension for details.)
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	The big request is recorded with the correct length field re-inserted.
 *	
 * Note: this function exists mainly to make RecordARequest smaller.
 */
static void
RecordABigRequest(pContext, client, stuff)
    RecordContextPtr pContext;
    ClientPtr client;
    xReq *stuff;
{
    CARD32 bigLength;
    char n;
    int bytesLeft;

    /* note: client->req_len has been frobbed by ReadRequestFromClient
     * (os/io.c) to discount the extra 4 bytes taken by the extended length
     * field in a big request.  The actual request length to record is
     * client->req_len + 1 (measured in CARD32s).
     */

    /* record the request header */
    bytesLeft = client->req_len << 2;
    RecordAProtocolElement(pContext, client, XRecordFromClient,
			   (pointer)stuff, SIZEOF(xReq), bytesLeft);

    /* reinsert the extended length field that was squished out */
    bigLength = client->req_len + (sizeof(bigLength) >> 2);
    if (client->swapped)
	swapl(&bigLength, n);
    RecordAProtocolElement(pContext, client, XRecordFromClient,
		(pointer)&bigLength, sizeof(bigLength), /* continuation */ -1);
    bytesLeft -= sizeof(bigLength);

    /* record the rest of the request after the length */
    RecordAProtocolElement(pContext, client, XRecordFromClient,
		(pointer)(stuff + 1), bytesLeft, /* continuation */ -1);
} /* RecordABigRequest */


/* RecordARequest
 *
 * Arguments:
 *	client is a client that the server has dispatched a request to by
 *	calling client->requestVector[request opcode] .
 *	The request is in client->requestBuffer.
 *
 * Returns:
 *	Whatever is returned by the "real" Proc function for this request.
 *	The "real" Proc function is the function that was in
 *	client->requestVector[request opcode]  before it was replaced by
 *	RecordARequest.  (See the function RecordInstallHooks.)
 *
 * Side Effects:
 *	The request is recorded by all contexts that have registered this
 *	request for this client.  The real Proc function is called.
 */
static int
RecordARequest(client)
    ClientPtr client;
{
    RecordContextPtr pContext;
    RecordClientsAndProtocolPtr pRCAP;
    int i;
    RecordClientPrivatePtr pClientPriv;
    REQUEST(xReq);
    int majorop;

    majorop = stuff->reqType;
    for (i = 0; i < numEnabledContexts; i++)
    {
	pContext = ppAllContexts[i];
	pRCAP = RecordFindClientOnContext(pContext, client->clientAsMask,
					  NULL);
	if (pRCAP && pRCAP->pRequestMajorOpSet &&
	    RecordIsMemberOfSet(pRCAP->pRequestMajorOpSet, majorop))
	{
	    if (majorop <= 127)
	    { /* core request */

		if (stuff->length == 0)
		    RecordABigRequest(pContext, client, stuff);
		else
		    RecordAProtocolElement(pContext, client, XRecordFromClient,
				(pointer)stuff, client->req_len << 2, 0);
	    }
	    else /* extension, check minor opcode */
	    {
		int minorop = MinorOpcodeOfRequest(client);
		int numMinOpInfo;
		RecordMinorOpPtr pMinorOpInfo = pRCAP->pRequestMinOpInfo;

		assert (pMinorOpInfo);
		numMinOpInfo = pMinorOpInfo->count;
		pMinorOpInfo++;
		assert (numMinOpInfo);
		for ( ; numMinOpInfo; numMinOpInfo--, pMinorOpInfo++)
		{
		    if (majorop >= pMinorOpInfo->major.first &&
			majorop <= pMinorOpInfo->major.last &&
			RecordIsMemberOfSet(pMinorOpInfo->major.pMinOpSet,
					    minorop))
		    {
			if (stuff->length == 0)
			    RecordABigRequest(pContext, client, stuff);
			else
			    RecordAProtocolElement(pContext, client, 
					XRecordFromClient, (pointer)stuff,
					client->req_len << 2, 0);
			break;
		    }			    
		} /* end for each minor op info */
	    } /* end extension request */
	} /* end this RCAP wants this major opcode */
    } /* end for each context */
    pClientPriv = RecordClientPrivate(client);
    assert(pClientPriv);
    return (* pClientPriv->originalVector[majorop])(client);
} /* RecordARequest */


/* RecordASkippedRequest
 *
 * Arguments:
 *	pcbl is &SkippedRequestCallback.
 *	nulldata is NULL.
 *	calldata is a pointer to a SkippedRequestInfoRec (include/os.h)
 *	  which provides information about requests that the server is
 *	  skipping.  The client's proc vector won't be called for skipped
 *	  requests, so that's why we have to catch them here.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	The skipped requests are recorded by all contexts that have 
 *	registered those requests for this client.
 *
 * Note: most servers don't skip requests, so calls to this will probably
 *	 be rare.  For more information on skipped requests, search for
 *	 the word skip in ddx.tbl.ms (the porting layer document).
 */
static void
RecordASkippedRequest(pcbl , nulldata, calldata)
    CallbackListPtr *pcbl;
    pointer nulldata;
    pointer calldata;
{
    SkippedRequestInfoRec *psi = (SkippedRequestInfoRec *)calldata;
    RecordContextPtr pContext;
    RecordClientsAndProtocolPtr pRCAP;
    xReqPtr stuff = psi->req;
    ClientPtr client = psi->client;
    int numSkippedRequests = psi->numskipped;
    int reqlen;
    int i;
    int majorop;
    
    while (numSkippedRequests--)
    {
	majorop = stuff->reqType;
	reqlen = ReqLen(stuff, client);
	/* handle big request */
	if (stuff->length == 0)
	    reqlen += 4;
	for (i = 0; i < numEnabledContexts; i++)
	{
	    pContext = ppAllContexts[i];
	    pRCAP = RecordFindClientOnContext(pContext, client->clientAsMask,
					      NULL);
	    if (pRCAP && pRCAP->pRequestMajorOpSet &&
		RecordIsMemberOfSet(pRCAP->pRequestMajorOpSet, majorop))
	    {
		if (majorop <= 127)
		{ /* core request */

		    RecordAProtocolElement(pContext, client, XRecordFromClient,
				(pointer)stuff, reqlen, 0);
		}
		else /* extension, check minor opcode */
		{
		    int minorop = MinorOpcodeOfRequest(client);
		    int numMinOpInfo;
		    RecordMinorOpPtr pMinorOpInfo = pRCAP->pRequestMinOpInfo;

		    assert (pMinorOpInfo);
		    numMinOpInfo = pMinorOpInfo->count;
		    pMinorOpInfo++;
		    assert (numMinOpInfo);
		    for ( ; numMinOpInfo; numMinOpInfo--, pMinorOpInfo++)
		    {
			if (majorop >= pMinorOpInfo->major.first &&
			    majorop <= pMinorOpInfo->major.last &&
			    RecordIsMemberOfSet(pMinorOpInfo->major.pMinOpSet,
						minorop))
			{
			    RecordAProtocolElement(pContext, client, 
				    XRecordFromClient, (pointer)stuff,
				    reqlen, 0);
			    break;
			}			    
		    } /* end for each minor op info */
		} /* end extension request */
	    } /* end this RCAP wants this major opcode */
	} /* end for each context */

	/* go to next request */
	stuff = (xReqPtr)( ((char *)stuff) + reqlen);

    } /* end for each skipped request */
} /* RecordASkippedRequest */


/* RecordAReply
 *
 * Arguments:
 *	pcbl is &ReplyCallback.
 *	nulldata is NULL.
 *	calldata is a pointer to a ReplyInfoRec (include/os.h)
 *	  which provides information about replies that are being sent
 *	  to clients.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	The reply is recorded by all contexts that have registered this
 *	reply type for this client.  If more data belonging to the same
 *	reply is expected, and if the reply is being recorded by any
 *	context, pContext->continuedReply is set to 1.
 *	If pContext->continuedReply was already 1 and this is the last
 *	chunk of data belonging to this reply, it is set to 0.
 */
static void
RecordAReply(pcbl, nulldata, calldata)
    CallbackListPtr *pcbl;
    pointer nulldata;
    pointer calldata;
{
    RecordContextPtr pContext;
    RecordClientsAndProtocolPtr pRCAP;
    int eci;
    int majorop;
    ReplyInfoRec *pri = (ReplyInfoRec *)calldata;
    ClientPtr client = pri->client;
    REQUEST(xReq);

    majorop = stuff->reqType;
    for (eci = 0; eci < numEnabledContexts; eci++)
    {
	pContext = ppAllContexts[eci];
	pRCAP = RecordFindClientOnContext(pContext, client->clientAsMask,
					  NULL);
	if (pRCAP)
	{
	    if (pContext->continuedReply)
	    {
		RecordAProtocolElement(pContext, client, XRecordFromServer,
		    pri->replyData, pri->dataLenBytes, /* continuation */ -1);
		if (!pri->bytesRemaining)
		    pContext->continuedReply = 0;
	    }
	    else if (pri->startOfReply && pRCAP->pReplyMajorOpSet &&
		     RecordIsMemberOfSet(pRCAP->pReplyMajorOpSet, majorop))
	    {
		if (majorop <= 127)
		{ /* core reply */
		    RecordAProtocolElement(pContext, client, XRecordFromServer,
		       pri->replyData, pri->dataLenBytes, pri->bytesRemaining);
		    if (pri->bytesRemaining)
			pContext->continuedReply = 1;
		}
		else /* extension, check minor opcode */
		{
		    int minorop = MinorOpcodeOfRequest(client);
		    int numMinOpInfo;
		    RecordMinorOpPtr pMinorOpInfo = pRCAP->pReplyMinOpInfo;
		    		    assert (pMinorOpInfo);
		    numMinOpInfo = pMinorOpInfo->count;
		    pMinorOpInfo++;
		    assert (numMinOpInfo);
		    for ( ; numMinOpInfo; numMinOpInfo--, pMinorOpInfo++)
		    {
			if (majorop >= pMinorOpInfo->major.first &&
			    majorop <= pMinorOpInfo->major.last &&
			    RecordIsMemberOfSet(pMinorOpInfo->major.pMinOpSet,
						minorop))
			{
			    RecordAProtocolElement(pContext, client, 
				XRecordFromServer, pri->replyData,
				pri->dataLenBytes, pri->bytesRemaining);
			    if (pri->bytesRemaining)
				pContext->continuedReply = 1;
			    break;
			}			    
		    } /* end for each minor op info */
		} /* end extension reply */
	    } /* end continued reply vs. start of reply */
	} /* end client is registered on this context */
    } /* end for each context */
} /* RecordAReply */


/* RecordADeliveredEventOrError
 *
 * Arguments:
 *	pcbl is &EventCallback.
 *	nulldata is NULL.
 *	calldata is a pointer to a EventInfoRec (include/dix.h)
 *	  which provides information about events that are being sent
 *	  to clients.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	The event or error is recorded by all contexts that have registered
 *	it for this client.
 */
static void
RecordADeliveredEventOrError(pcbl, nulldata, calldata)
    CallbackListPtr *pcbl;
    pointer nulldata;
    pointer calldata;
{
    EventInfoRec *pei = (EventInfoRec *)calldata;
    RecordContextPtr pContext;
    RecordClientsAndProtocolPtr pRCAP;
    int eci; /* enabled context index */
    ClientPtr pClient = pei->client;

    for (eci = 0; eci < numEnabledContexts; eci++)
    {
	pContext = ppAllContexts[eci];
	pRCAP = RecordFindClientOnContext(pContext, pClient->clientAsMask,
					  NULL);
	if (pRCAP && (pRCAP->pDeliveredEventSet || pRCAP->pErrorSet))
	{
	    int ev; /* event index */
	    xEvent *pev = pei->events;
	    for (ev = 0; ev < pei->count; ev++, pev++)
	    {
		int recordit;
		if (pev->u.u.type == X_Error)
		{
		    recordit = RecordIsMemberOfSet(pRCAP->pErrorSet,
						((xError *)(pev))->errorCode);
		}
		else
		{
		    recordit = RecordIsMemberOfSet(pRCAP->pDeliveredEventSet,
						   pev->u.u.type & 0177);
		}
		if (recordit)
		{
		    xEvent swappedEvent;
		    xEvent *pEvToRecord = pev;

		    if (pClient->swapped)
		    {
			(*EventSwapVector[pev->u.u.type & 0177])
			    (pev, &swappedEvent);
			pEvToRecord = &swappedEvent;
			
		    }
		    RecordAProtocolElement(pContext, pClient,
			XRecordFromServer, pEvToRecord, SIZEOF(xEvent), 0);
		}
	    } /* end for each event */
	} /* end this client is on this context */
    } /* end for each enabled context */
} /* RecordADeliveredEventOrError */


/* RecordADeviceEvent
 *
 * Arguments:
 *	pcbl is &DeviceEventCallback.
 *	nulldata is NULL.
 *	calldata is a pointer to a DeviceEventInfoRec (include/dix.h)
 *	  which provides information about device events that occur.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	The device event is recorded by all contexts that have registered
 *	it for this client.
 */
static void
RecordADeviceEvent(pcbl, nulldata, calldata)
    CallbackListPtr *pcbl;
    pointer nulldata;
    pointer calldata;
{
    DeviceEventInfoRec *pei = (DeviceEventInfoRec *)calldata;
    RecordContextPtr pContext;
    RecordClientsAndProtocolPtr pRCAP;
    int eci; /* enabled context index */

    for (eci = 0; eci < numEnabledContexts; eci++)
    {
	pContext = ppAllContexts[eci];
	for (pRCAP = pContext->pListOfRCAP; pRCAP; pRCAP = pRCAP->pNextRCAP)
	{
	    if (pRCAP->pDeviceEventSet)
	    {
		int ev; /* event index */
		xEvent *pev = pei->events;
		for (ev = 0; ev < pei->count; ev++, pev++)
		{
		    if (RecordIsMemberOfSet(pRCAP->pDeviceEventSet,
					    pev->u.u.type & 0177))
		    {
		        xEvent swappedEvent;
		        xEvent *pEvToRecord = pev;
#ifdef PANORAMIX
		        xEvent shiftedEvent;

			if (!noPanoramiXExtension &&
			    (pev->u.u.type == MotionNotify ||
			     pev->u.u.type == ButtonPress ||
			     pev->u.u.type == ButtonRelease ||
			     pev->u.u.type == KeyPress ||
			     pev->u.u.type == KeyRelease)) {
				int scr = XineramaGetCursorScreen();
				memcpy(&shiftedEvent, pev, sizeof(xEvent));
				shiftedEvent.u.keyButtonPointer.rootX +=
				    panoramiXdataPtr[scr].x - 
					panoramiXdataPtr[0].x;
				shiftedEvent.u.keyButtonPointer.rootY +=
				    panoramiXdataPtr[scr].y -
					panoramiXdataPtr[0].y;
				pEvToRecord = &shiftedEvent;
			}
#endif /* PANORAMIX */

			if (pContext->pRecordingClient->swapped)
			{
			    (*EventSwapVector[pEvToRecord->u.u.type & 0177])
				(pEvToRecord, &swappedEvent);
			    pEvToRecord = &swappedEvent;
			}

			RecordAProtocolElement(pContext, NULL,
			   XRecordFromServer,  pEvToRecord, SIZEOF(xEvent), 0);
			/* make sure device events get flushed in the absence
			 * of other client activity
			 */
			SetCriticalOutputPending();
		    }
		} /* end for each event */
	    } /* end this RCAP selects device events */
	} /* end for each RCAP on this context */
    } /* end for each enabled context */
} /* RecordADeviceEvent */


/* RecordFlushAllContexts
 *
 * Arguments:
 *	pcbl is &FlushCallback.
 *	nulldata and calldata are NULL.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	All buffered reply data of all enabled contexts is written to
 *	the recording clients.
 */
static void
RecordFlushAllContexts(
    CallbackListPtr *pcbl,
    pointer nulldata,
    pointer calldata
)
{
    int eci; /* enabled context index */
    RecordContextPtr pContext;

    for (eci = 0; eci < numEnabledContexts; eci++)
    {
	pContext = ppAllContexts[eci];

	/* In most cases we leave it to RecordFlushReplyBuffer to make
	 * this check, but this function could be called very often, so we
	 * check before calling hoping to save the function call cost
	 * most of the time.
	 */
	if (pContext->numBufBytes)
	    RecordFlushReplyBuffer(ppAllContexts[eci], NULL, 0, NULL, 0);
    }
} /* RecordFlushAllContexts */


/* RecordInstallHooks
 *
 * Arguments:
 *	pRCAP is an RCAP on an enabled or being-enabled context.
 *	oneclient can be zero or the resource ID mask identifying a client.
 *
 * Returns: BadAlloc if a memory allocation error occurred, else Success.
 *
 * Side Effects:
 *	Recording hooks needed by RCAP are installed.
 *	If oneclient is zero, recording hooks needed for all clients and
 *	protocol on the RCAP are installed.  If oneclient is non-zero,
 *	only those hooks needed for the specified client are installed.
 *	
 *	Client requestVectors may be altered.  numEnabledRCAPs will be
 *	incremented if oneclient == 0.  Callbacks may be added to
 *	various callback lists.
 */
static int
RecordInstallHooks(pRCAP, oneclient)
    RecordClientsAndProtocolPtr pRCAP;
    XID oneclient;
{
    int i = 0;
    XID client;

    if (oneclient)
	client = oneclient;
    else
	client = pRCAP->numClients ? pRCAP->pClientIDs[i++] : 0;

    while (client)
    {
	if (client != XRecordFutureClients)
	{
	    if (pRCAP->pRequestMajorOpSet)
	    {
		RecordSetIteratePtr pIter = NULL;
		RecordSetInterval interval;
		ClientPtr pClient = clients[CLIENT_ID(client)];

		if (pClient && !RecordClientPrivate(pClient))
		{
		    RecordClientPrivatePtr pClientPriv;
		    /* no Record proc vector; allocate one */
		    pClientPriv = (RecordClientPrivatePtr)
				xalloc(sizeof(RecordClientPrivateRec));
		    if (!pClientPriv)
			return BadAlloc;
		    /* copy old proc vector to new */
		    memcpy(pClientPriv->recordVector, pClient->requestVector, 
			   sizeof (pClientPriv->recordVector));
		    pClientPriv->originalVector = pClient->requestVector;
		    pClient->devPrivates[RecordClientPrivateIndex].ptr =
			(pointer)pClientPriv;
		    pClient->requestVector = pClientPriv->recordVector;
		}
		while ((pIter = RecordIterateSet(pRCAP->pRequestMajorOpSet,
						pIter, &interval)))
		{
		    unsigned int j;
		    for (j = interval.first; j <= interval.last; j++)
			pClient->requestVector[j] = RecordARequest;
		}
	    }
	}
	if (oneclient)
	    client = 0;
	else
	    client = (i < pRCAP->numClients) ? pRCAP->pClientIDs[i++] : 0;
    }

    assert(numEnabledRCAPs >= 0);
    if (!oneclient && ++numEnabledRCAPs == 1)
    { /* we're enabling the first context */
	if (!AddCallback(&EventCallback, RecordADeliveredEventOrError, NULL))
	    return BadAlloc;
	if (!AddCallback(&DeviceEventCallback, RecordADeviceEvent, NULL))
	    return BadAlloc;
	if (!AddCallback(&ReplyCallback, RecordAReply, NULL))
	    return BadAlloc;
	if (!AddCallback(&SkippedRequestsCallback, RecordASkippedRequest,
			 NULL))
	    return BadAlloc;
	if (!AddCallback(&FlushCallback, RecordFlushAllContexts, NULL))
	    return BadAlloc;
	/* Alternate context flushing scheme: delete the line above
	 * and call RegisterBlockAndWakeupHandlers here passing
	 * RecordFlushAllContexts.  Is this any better?
	 */
    }
    return Success;
} /* RecordInstallHooks */


/* RecordUninstallHooks
 *
 * Arguments:
 *	pRCAP is an RCAP on an enabled or being-disabled context.
 *	oneclient can be zero or the resource ID mask identifying a client.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	Recording hooks needed by RCAP may be uninstalled.
 *	If oneclient is zero, recording hooks needed for all clients and
 *	protocol on the RCAP may be uninstalled.  If oneclient is non-zero,
 *	only those hooks needed for the specified client may be uninstalled.
 *	
 *	Client requestVectors may be altered.  numEnabledRCAPs will be
 *	decremented if oneclient == 0.  Callbacks may be deleted from
 *	various callback lists.
 */
static void
RecordUninstallHooks(pRCAP, oneclient)
    RecordClientsAndProtocolPtr pRCAP;
    XID oneclient;
{
    int i = 0;
    XID client;

    if (oneclient)
	client = oneclient;
    else
	client = pRCAP->numClients ? pRCAP->pClientIDs[i++] : 0;

    while (client)
    {
	if (client != XRecordFutureClients)
	{
	    if (pRCAP->pRequestMajorOpSet)
	    {
		ClientPtr pClient = clients[CLIENT_ID(client)];
		int c;
		Bool otherRCAPwantsProcVector = FALSE;
		RecordClientPrivatePtr pClientPriv =
						RecordClientPrivate(pClient);

		assert (pClient && RecordClientPrivate(pClient));
		memcpy(pClientPriv->recordVector, pClientPriv->originalVector,
		       sizeof (pClientPriv->recordVector));

		for (c = 0; c < numEnabledContexts; c++)
		{
		    RecordClientsAndProtocolPtr pOtherRCAP;
		    RecordContextPtr pContext = ppAllContexts[c];

		    if (pContext == pRCAP->pContext) continue;
		    pOtherRCAP = RecordFindClientOnContext(pContext, client,
							   NULL);
		    if (pOtherRCAP && pOtherRCAP->pRequestMajorOpSet)
		    {
			RecordSetIteratePtr pIter = NULL;
			RecordSetInterval interval;

			otherRCAPwantsProcVector = TRUE;
			while ((pIter = RecordIterateSet(
						pOtherRCAP->pRequestMajorOpSet,
						pIter, &interval)))
			{
			    unsigned int j;
			    for (j = interval.first; j <= interval.last; j++)
				pClient->requestVector[j] = RecordARequest;
			}
		    }
		}
		if (!otherRCAPwantsProcVector)
		{ /* nobody needs it, so free it */
		    pClient->requestVector = pClientPriv->originalVector;
		    pClient->devPrivates[RecordClientPrivateIndex].ptr = NULL;
		    xfree(pClientPriv);
		}
	    } /* end if this RCAP specifies any requests */
	} /* end if not future clients */
	if (oneclient)
	    client = 0;
	else
	    client = (i < pRCAP->numClients) ? pRCAP->pClientIDs[i++] : 0;
    }

    assert(numEnabledRCAPs >= 1);
    if (!oneclient && --numEnabledRCAPs == 0)
    { /* we're disabling the last context */
	DeleteCallback(&EventCallback, RecordADeliveredEventOrError, NULL);
	DeleteCallback(&DeviceEventCallback, RecordADeviceEvent, NULL);
	DeleteCallback(&ReplyCallback, RecordAReply, NULL);
	DeleteCallback(&SkippedRequestsCallback, RecordASkippedRequest, NULL);
	DeleteCallback(&FlushCallback, RecordFlushAllContexts, NULL);
	/* Alternate context flushing scheme: delete the line above
	 * and call RemoveBlockAndWakeupHandlers here passing
	 * RecordFlushAllContexts.  Is this any better?
	 */
	/* Having deleted the callback, call it one last time. -gildea */
	RecordFlushAllContexts(&FlushCallback, NULL, NULL);
    }
} /* RecordUninstallHooks */


/* RecordDeleteClientFromRCAP
 *
 * Arguments:
 *	pRCAP is an RCAP to delete the client from.
 *	position is the index into the array pRCAP->pClientIDs of the
 *	client to delete.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	Recording hooks needed by client will be uninstalled if the context
 *	is enabled.  The designated client will be removed from the 
 *	pRCAP->pClientIDs array.  If it was the only client on the RCAP, 
 *	the RCAP is removed from the context and freed.  (Invariant: RCAPs
 *	have at least one client.)
 */
static void
RecordDeleteClientFromRCAP(pRCAP, position)
    RecordClientsAndProtocolPtr pRCAP;
    int position;
{
    if (pRCAP->pContext->pRecordingClient)
	RecordUninstallHooks(pRCAP, pRCAP->pClientIDs[position]);
    if (position != pRCAP->numClients - 1)
	pRCAP->pClientIDs[position] = pRCAP->pClientIDs[pRCAP->numClients - 1];
    if (--pRCAP->numClients == 0)
    {	/* no more clients; remove RCAP from context's list */
	RecordContextPtr pContext = pRCAP->pContext;
	if (pContext->pRecordingClient)
	    RecordUninstallHooks(pRCAP, 0);
	if (pContext->pListOfRCAP == pRCAP)
	    pContext->pListOfRCAP = pRCAP->pNextRCAP;
	else
	{
	    RecordClientsAndProtocolPtr prevRCAP;
	    for (prevRCAP = pContext->pListOfRCAP;
		 prevRCAP->pNextRCAP != pRCAP;
		 prevRCAP = prevRCAP->pNextRCAP)
		;
	    prevRCAP->pNextRCAP = pRCAP->pNextRCAP;
	}
	/* free the RCAP */
	if (pRCAP->clientIDsSeparatelyAllocated)
	    xfree(pRCAP->pClientIDs);
	xfree(pRCAP);
    }
} /* RecordDeleteClientFromRCAP */


/* RecordAddClientToRCAP
 *
 * Arguments:
 *	pRCAP is an RCAP to add the client to.
 *	clientspec is the resource ID mask identifying a client, or
 *	  XRecordFutureClients.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	Recording hooks needed by client will be installed if the context
 *	is enabled.  The designated client will be added to the 
 *	pRCAP->pClientIDs array, which may be realloced.
 *	pRCAP->clientIDsSeparatelyAllocated may be set to 1 if there
 *	is no more room to hold clients internal to the RCAP.
 */
static void
RecordAddClientToRCAP(pRCAP, clientspec)
    RecordClientsAndProtocolPtr pRCAP;
    XID clientspec;
{
    if (pRCAP->numClients == pRCAP->sizeClients)
    {
	if (pRCAP->clientIDsSeparatelyAllocated)
	{
	    XID *pNewIDs = (XID *)xrealloc(pRCAP->pClientIDs,
			(pRCAP->sizeClients + CLIENT_ARRAY_GROWTH_INCREMENT) *
								sizeof(XID));
	    if (!pNewIDs)
		return;
	    pRCAP->pClientIDs = pNewIDs;
	    pRCAP->sizeClients += CLIENT_ARRAY_GROWTH_INCREMENT;
	}
	else
	{
	    XID *pNewIDs = (XID *)xalloc((pRCAP->sizeClients +
				CLIENT_ARRAY_GROWTH_INCREMENT) * sizeof(XID));
	    if (!pNewIDs)
		return;
	    memcpy(pNewIDs, pRCAP->pClientIDs, pRCAP->numClients *sizeof(XID));
	    pRCAP->pClientIDs = pNewIDs;
	    pRCAP->sizeClients += CLIENT_ARRAY_GROWTH_INCREMENT;
	    pRCAP->clientIDsSeparatelyAllocated = 1;
	}
    }
    pRCAP->pClientIDs[pRCAP->numClients++] = clientspec;
    if (pRCAP->pContext->pRecordingClient)
	RecordInstallHooks(pRCAP, clientspec);
} /* RecordDeleteClientFromRCAP */


/* RecordDeleteClientFromContext
 *
 * Arguments:
 *	pContext is the context to delete from.
 *	clientspec is the resource ID mask identifying a client, or
 *	  XRecordFutureClients.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	If clientspec is on any RCAP of the context, it is deleted from that
 *	RCAP.  (A given clientspec can only be on one RCAP of a context.)
 */
static void
RecordDeleteClientFromContext(pContext, clientspec)
    RecordContextPtr pContext;
    XID clientspec;
{
    RecordClientsAndProtocolPtr pRCAP;
    int position;

    if ((pRCAP = RecordFindClientOnContext(pContext, clientspec, &position)))
	RecordDeleteClientFromRCAP(pRCAP, position);
} /* RecordDeleteClientFromContext */


/* RecordSanityCheckClientSpecifiers
 *
 * Arguments:
 *	clientspecs is an array of alleged CLIENTSPECs passed by the client.
 *	nspecs is the number of elements in clientspecs.
 *	errorspec, if non-zero, is the resource id base of a client that
 *	  must not appear in clienspecs.
 *
 * Returns: BadMatch if any of the clientspecs are invalid, else Success.
 *
 * Side Effects: none.
 */
static int
RecordSanityCheckClientSpecifiers(clientspecs, nspecs, errorspec)
    XID *clientspecs;
    int nspecs;
    XID errorspec;
{
    int i;
    int clientIndex;

    for (i = 0; i < nspecs; i++)
    {
	if (clientspecs[i] == XRecordCurrentClients ||
	    clientspecs[i] == XRecordFutureClients ||
	    clientspecs[i] == XRecordAllClients)
	    continue;
	if (errorspec && (CLIENT_BITS(clientspecs[i]) == errorspec) )
	    return BadMatch;
	clientIndex = CLIENT_ID(clientspecs[i]);
	if (clientIndex && clients[clientIndex] &&
	    clients[clientIndex]->clientState == ClientStateRunning)
	{
	    if (clientspecs[i] == clients[clientIndex]->clientAsMask)
		continue;
	    if (!LookupIDByClass(clientspecs[i], RC_ANY))
		return BadMatch;
	}
	else
	    return BadMatch;
    }
    return Success;
} /* RecordSanityCheckClientSpecifiers */


/* RecordCanonicalizeClientSpecifiers
 *
 * Arguments:
 *	pClientspecs is an array of CLIENTSPECs that have been sanity
 *	  checked.
 *	pNumClientspecs is a pointer to the number of elements in pClientspecs.
 *	excludespec, if non-zero, is the resource id base of a client that 
 *	  should not be included in the expansion of XRecordAllClients or 
 *	  XRecordCurrentClients.
 *
 * Returns:
 *	A pointer to an array of CLIENTSPECs that is the same as the
 *	passed array with the following modifications:
 *	  - all but the client id bits of resource IDs are stripped off.
 *	  - duplicates removed.
 *	  - XRecordAllClients expanded to a list of all currently connected
 *	    clients + XRecordFutureClients - excludespec (if non-zero)
 *	  - XRecordCurrentClients expanded to a list of all currently
 *	    connected clients - excludespec (if non-zero)
 *	The returned array may be the passed array modified in place, or
 *	it may be an Xalloc'ed array.  The caller should keep a pointer to the
 *	original array and free the returned array if it is different.
 *
 *	*pNumClientspecs is set to the number of elements in the returned
 *	array.
 *
 * Side Effects:
 *	pClientspecs may be modified in place.
 */
static XID *
RecordCanonicalizeClientSpecifiers(pClientspecs, pNumClientspecs, excludespec)
    XID *pClientspecs;
    int *pNumClientspecs;
    XID excludespec;
{
    int i;
    int numClients = *pNumClientspecs;

    /*  first pass strips off the resource index bits, leaving just the
     *  client id bits.  This makes searching for a particular client simpler
     *  (and faster.)
     */
    for (i = 0; i < numClients; i++)
    {
	XID cs = pClientspecs[i];
	if (cs > XRecordAllClients)
	    pClientspecs[i] = CLIENT_BITS(cs);
    }

    for (i = 0; i < numClients; i++)
    {
	if (pClientspecs[i] == XRecordAllClients ||
	    pClientspecs[i] == XRecordCurrentClients)
	{ /* expand All/Current */
	    int j, nc;
	    XID *pCanon = (XID *)xalloc(sizeof(XID) * (currentMaxClients + 1));
	    if (!pCanon) return NULL;
	    for (nc = 0, j = 1; j < currentMaxClients; j++)
	    {
		ClientPtr client = clients[j];
		if (client != NullClient &&
		    client->clientState == ClientStateRunning &&
		    client->clientAsMask != excludespec)
		{
		    pCanon[nc++] = client->clientAsMask;
		}
	    }
	    if (pClientspecs[i] == XRecordAllClients)
		pCanon[nc++] = XRecordFutureClients;
	    *pNumClientspecs = nc;
	    return pCanon;
	}
	else /* not All or Current */
	{
	    int j;
	    for (j = i + 1; j < numClients; )
	    {
		if (pClientspecs[i] == pClientspecs[j])
		{
		    pClientspecs[j] = pClientspecs[--numClients];
		}
		else
		    j++;
	    }
	}
    } /* end for each clientspec */
    *pNumClientspecs = numClients;
    return pClientspecs;
} /* RecordCanonicalizeClientSpecifiers */

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

/* stuff for RegisterClients */

/* RecordPadAlign
 *
 * Arguments:
 *	size is the number of bytes taken by an object.
 *	align is a byte boundary (e.g. 4, 8)
 *
 * Returns:
 *	the number of pad bytes to add at the end of an object of the
 *	given size so that an object placed immediately behind it will
 *	begin on an <align>-byte boundary.
 *
 * Side Effects: none.
 */
static int
RecordPadAlign(int size, int align)
{
    return (align - (size & (align - 1))) & (align - 1);
} /* RecordPadAlign */


/* RecordSanityCheckRegisterClients
 *
 * Arguments:
 *	pContext is the context being registered on.
 *	client is the client that issued a RecordCreateContext or
 *	  RecordRegisterClients request.
 *	stuff is a pointer to the request.
 *
 * Returns:
 *	Any one of several possible error values if any of the request
 *	arguments are invalid.  Success if everything is OK.
 *
 * Side Effects: none.
 */
static int
RecordSanityCheckRegisterClients(pContext, client, stuff)
    RecordContextPtr pContext;
    ClientPtr client;
    xRecordRegisterClientsReq *stuff;
{
    int err;
    xRecordRange *pRange;
    int i;
    XID recordingClient;

    if (((client->req_len << 2) - SIZEOF(xRecordRegisterClientsReq)) !=
	4 * stuff->nClients + SIZEOF(xRecordRange) * stuff->nRanges)
	return BadLength;

    if (stuff->elementHeader &
     ~(XRecordFromClientSequence|XRecordFromClientTime|XRecordFromServerTime))
    {
	client->errorValue = stuff->elementHeader;
	return BadValue;
    }

    recordingClient = pContext->pRecordingClient ?
		      pContext->pRecordingClient->clientAsMask : 0;
    err = RecordSanityCheckClientSpecifiers((XID *)&stuff[1], stuff->nClients,
					    recordingClient);
    if (err != Success) return err;

    pRange = (xRecordRange *)(((XID *)&stuff[1]) + stuff->nClients);
    for (i = 0; i < stuff->nRanges; i++, pRange++)
    {
	if (pRange->coreRequestsFirst > pRange->coreRequestsLast)
	{
	    client->errorValue = pRange->coreRequestsFirst;
	    return BadValue;
	}
	if (pRange->coreRepliesFirst > pRange->coreRepliesLast)
	{
	    client->errorValue = pRange->coreRepliesFirst;
	    return BadValue;
	}
	if ((pRange->extRequestsMajorFirst || pRange->extRequestsMajorLast) &&
	    (pRange->extRequestsMajorFirst < 128 ||
	     pRange->extRequestsMajorLast < 128 ||
	     pRange->extRequestsMajorFirst > pRange->extRequestsMajorLast))
	{
	    client->errorValue = pRange->extRequestsMajorFirst;
	    return BadValue;
	}
	if (pRange->extRequestsMinorFirst > pRange->extRequestsMinorLast)
	{
	    client->errorValue = pRange->extRequestsMinorFirst;
	    return BadValue;
	}
	if ((pRange->extRepliesMajorFirst || pRange->extRepliesMajorLast) &&
	    (pRange->extRepliesMajorFirst < 128 ||
	     pRange->extRepliesMajorLast < 128 ||
	     pRange->extRepliesMajorFirst > pRange->extRepliesMajorLast))
	{
	    client->errorValue = pRange->extRepliesMajorFirst;
	    return BadValue;
	}
	if (pRange->extRepliesMinorFirst > pRange->extRepliesMinorLast)
	{
	    client->errorValue = pRange->extRepliesMinorFirst;
	    return BadValue;
	}
	if ((pRange->deliveredEventsFirst || pRange->deliveredEventsLast) &&
	    (pRange->deliveredEventsFirst < 2 ||
	     pRange->deliveredEventsLast < 2 ||
	     pRange->deliveredEventsFirst > pRange->deliveredEventsLast))
	{
	    client->errorValue = pRange->deliveredEventsFirst;
	    return BadValue;
	}
	if ((pRange->deviceEventsFirst || pRange->deviceEventsLast) &&
	    (pRange->deviceEventsFirst < 2 ||
	     pRange->deviceEventsLast < 2 ||
	     pRange->deviceEventsFirst > pRange->deviceEventsLast))
	{
	    client->errorValue = pRange->deviceEventsFirst;
	    return BadValue;
	}
	if (pRange->errorsFirst > pRange->errorsLast)
	{
	    client->errorValue = pRange->errorsFirst;
	    return BadValue;
	}
	if (pRange->clientStarted != xFalse && pRange->clientStarted != xTrue)
	{
	    client->errorValue = pRange->clientStarted;
	    return BadValue;
	}
	if (pRange->clientDied != xFalse && pRange->clientDied != xTrue)
	{
	    client->errorValue = pRange->clientDied;
	    return BadValue;
	}
    } /* end for each range */
    return Success;
} /* end RecordSanityCheckRegisterClients */

/* This is a tactical structure used to gather information about all the sets
 * (RecordSetPtr) that need to be created for an RCAP in the process of 
 * digesting a list of RECORDRANGEs (converting it to the internal
 * representation).
 */
typedef struct
{
    int nintervals;	/* number of intervals in following array */
    RecordSetInterval *intervals;  /* array of intervals for this set */
    int size;		/* size of intevals array; >= nintervals */
    int align;		/* alignment restriction for set */
    int offset;		/* where to store set pointer rel. to start of RCAP */
    short first, last;	/* if for extension, major opcode interval */
} SetInfoRec, *SetInfoPtr;

/* These constant are used to index into an array of SetInfoRec. */
enum {REQ,	/* set info for requests */
      REP,	/* set info for replies */
      ERR,	/* set info for errors */
      DEV,	/* set info for device events */
      DLEV,	/* set info for delivered events */
      PREDEFSETS};  /* number of predefined array entries */


/* RecordAllocIntervals
 *
 * Arguments:
 *	psi is a pointer to a SetInfoRec whose intervals pointer is NULL.
 *	nIntervals is the desired size of the intervals array.
 *
 * Returns: BadAlloc if a memory allocation error occurred, else Success.
 *
 * Side Effects:
 *	If Success is returned, psi->intervals is a pointer to size
 *	RecordSetIntervals, all zeroed, and psi->size is set to size.
 */
static int
RecordAllocIntervals(psi, nIntervals)
    SetInfoPtr psi;
    int nIntervals;
{
    assert(!psi->intervals);
    psi->intervals = (RecordSetInterval *)
			xalloc(nIntervals * sizeof(RecordSetInterval));
    if (!psi->intervals)
	return BadAlloc;
    bzero(psi->intervals, nIntervals * sizeof(RecordSetInterval));
    psi->size = nIntervals;
    return Success;
} /* end RecordAllocIntervals */


/* RecordConvertRangesToIntervals
 *
 * Arguments:
 *	psi is a pointer to the SetInfoRec we are building.
 *	pRanges is an array of xRecordRanges.
 *	nRanges is the number of elements in pRanges.
 *	byteoffset is the offset from the start of an xRecordRange of the
 *	  two bytes (1 for first, 1 for last) we are interested in.
 *	pExtSetInfo, if non-NULL, indicates that the two bytes mentioned
 *	  above are followed by four bytes (2 for first, 2 for last)
 *	  representing a minor opcode range, and this information should be
 *	  stored in one of the SetInfoRecs starting at pExtSetInfo.
 *	pnExtSetInfo is the number of elements in the pExtSetInfo array.
 *
 * Returns:  BadAlloc if a memory allocation error occurred, else Success.
 *
 * Side Effects:
 *	The slice of pRanges indicated by byteoffset is stored in psi.  
 *	If pExtSetInfo is non-NULL, minor opcode intervals are stored
 *	in an existing SetInfoRec if the major opcode interval matches, else
 *	they are stored in a new SetInfoRec, and *pnExtSetInfo is
 *	increased accordingly.
 */
static int
RecordConvertRangesToIntervals(
    SetInfoPtr psi,
    xRecordRange *pRanges,
    int nRanges,
    int byteoffset,
    SetInfoPtr pExtSetInfo,
    int *pnExtSetInfo
)
{
    int i;
    CARD8 *pCARD8;
    int first, last;
    int err;

    for (i = 0; i < nRanges; i++, pRanges++)
    {
	pCARD8 = ((CARD8 *)pRanges) + byteoffset;
	first = pCARD8[0];
	last  = pCARD8[1];
	if (first || last)
	{
	    if (!psi->intervals)
	    {
		err = RecordAllocIntervals(psi, 2 * (nRanges - i));
		if (err != Success)
		    return err;
	    }
	    psi->intervals[psi->nintervals].first = first;
	    psi->intervals[psi->nintervals].last  = last;
	    psi->nintervals++;
	    assert(psi->nintervals <= psi->size);
	    if (pExtSetInfo)
	    {
		SetInfoPtr pesi = pExtSetInfo;
		CARD16 *pCARD16 = (CARD16 *)(pCARD8 + 2);
		int j;

		for (j = 0; j < *pnExtSetInfo; j++, pesi++)
		{
		    if ( (first == pesi->first) && (last == pesi->last) )
			break;
		}
		if (j == *pnExtSetInfo)
		{
		    err = RecordAllocIntervals(pesi, 2 * (nRanges - i));
		    if (err != Success)
			return err;
		    pesi->first = first;
		    pesi->last  = last;
		    (*pnExtSetInfo)++;
		}
		pesi->intervals[pesi->nintervals].first = pCARD16[0];
		pesi->intervals[pesi->nintervals].last  = pCARD16[1];
		pesi->nintervals++;
		assert(pesi->nintervals <= pesi->size);
	    }
	}
    }
    return Success;
}  /* end RecordConvertRangesToIntervals */

#define offset_of(_structure, _field) \
    ((char *)(& (_structure . _field)) - (char *)(&_structure))

/* RecordRegisterClients
 *
 * Arguments:
 *	pContext is the context on which to register the clients.
 *	client is the client that issued the RecordCreateContext or
 *	  RecordRegisterClients request.
 *	stuff is a pointer to the request.
 *
 * Returns:
 *	Any one of several possible error values defined by the protocol.
 *	Success if everything is OK.
 *
 * Side Effects:
 *	If different element headers are specified, the context is flushed.
 *	If any of the specified clients are already registered on the
 *	context, they are first unregistered.  A new RCAP is created to
 *	hold the specified protocol and clients, and it is linked onto the
 *	context.  If the context is enabled, appropriate hooks are installed
 *	to record the new clients and protocol.
 */
static int
RecordRegisterClients(pContext, client, stuff)
    RecordContextPtr pContext;
    ClientPtr client;
    xRecordRegisterClientsReq *stuff;
{
    int err;
    int i;
    SetInfoPtr si;
    int maxSets;
    int nExtReqSets = 0;
    int nExtRepSets = 0;
    int extReqSetsOffset = 0;
    int extRepSetsOffset = 0;
    SetInfoPtr pExtReqSets, pExtRepSets;
    int clientListOffset;
    XID *pCanonClients;
    int clientStarted = 0, clientDied = 0;
    xRecordRange *pRanges, rr;
    int nClients;
    int sizeClients;
    int totRCAPsize;
    RecordClientsAndProtocolPtr pRCAP;
    int pad;
    XID recordingClient;

    /* do all sanity checking up front */

    err = RecordSanityCheckRegisterClients(pContext, client, stuff);
    if (err != Success)
	return err;

    /* if element headers changed, flush buffer */
	
    if (pContext->elemHeaders != stuff->elementHeader)
    {
	RecordFlushReplyBuffer(pContext, NULL, 0, NULL, 0);
	pContext->elemHeaders = stuff->elementHeader;
    }

    nClients = stuff->nClients;
    if (!nClients)
	/* if empty clients list, we're done. */
	return Success;

    recordingClient = pContext->pRecordingClient ?
		      pContext->pRecordingClient->clientAsMask : 0;
    pCanonClients = RecordCanonicalizeClientSpecifiers((XID *)&stuff[1],
						 &nClients, recordingClient);
    if (!pCanonClients)
	return BadAlloc;

    /* We may have to create as many as one set for each "predefined"
     * protocol types, plus one per range for extension reuests, plus one per
     * range for extension replies.
     */
    maxSets = PREDEFSETS + 2 * stuff->nRanges;
    si = (SetInfoPtr)ALLOCATE_LOCAL(sizeof(SetInfoRec) * maxSets);
    if (!si)
    {
	err = BadAlloc;
	goto bailout;
    }
    bzero(si, sizeof(SetInfoRec) * maxSets);

    /* theoretically you must do this because NULL may not be all-bits-zero */
    for (i = 0; i < maxSets; i++)
	si[i].intervals = NULL;

    pExtReqSets = si + PREDEFSETS;
    pExtRepSets = pExtReqSets + stuff->nRanges;

    pRanges = (xRecordRange *)(((XID *)&stuff[1]) + stuff->nClients);

    err = RecordConvertRangesToIntervals(&si[REQ], pRanges, stuff->nRanges,
			offset_of(rr, coreRequestsFirst), NULL, NULL);
    if (err != Success) goto bailout;

    err = RecordConvertRangesToIntervals(&si[REQ], pRanges, stuff->nRanges,
	   offset_of(rr, extRequestsMajorFirst), pExtReqSets, &nExtReqSets);
    if (err != Success) goto bailout;

    err = RecordConvertRangesToIntervals(&si[REP], pRanges, stuff->nRanges,
			offset_of(rr, coreRepliesFirst), NULL, NULL);
    if (err != Success) goto bailout;

    err = RecordConvertRangesToIntervals(&si[REP], pRanges, stuff->nRanges,
	   offset_of(rr, extRepliesMajorFirst), pExtRepSets, &nExtRepSets);
    if (err != Success) goto bailout;

    err = RecordConvertRangesToIntervals(&si[ERR], pRanges, stuff->nRanges,
			offset_of(rr, errorsFirst), NULL, NULL);
    if (err != Success) goto bailout;

    err = RecordConvertRangesToIntervals(&si[DLEV], pRanges, stuff->nRanges,
			offset_of(rr, deliveredEventsFirst), NULL, NULL);
    if (err != Success) goto bailout;

    err = RecordConvertRangesToIntervals(&si[DEV], pRanges, stuff->nRanges,
			offset_of(rr, deviceEventsFirst), NULL, NULL);
    if (err != Success) goto bailout;

    /* collect client-started and client-died */

    for (i = 0; i < stuff->nRanges; i++)
    {
	if (pRanges[i].clientStarted) clientStarted = TRUE;
	if (pRanges[i].clientDied)    clientDied    = TRUE;
    }

    /*  We now have all the information collected to create all the sets,
     * and we can compute the total memory required for the RCAP.
     */

    totRCAPsize = sizeof(RecordClientsAndProtocolRec);

    /* leave a little room to grow before forcing a separate allocation */
    sizeClients = nClients + CLIENT_ARRAY_GROWTH_INCREMENT;
    pad = RecordPadAlign(totRCAPsize, sizeof(XID));
    clientListOffset = totRCAPsize + pad;
    totRCAPsize += pad + sizeClients * sizeof(XID);

    if (nExtReqSets)
    {
	pad = RecordPadAlign(totRCAPsize, sizeof(RecordSetPtr));
	extReqSetsOffset = totRCAPsize + pad;
	totRCAPsize += pad + (nExtReqSets + 1) * sizeof(RecordMinorOpRec);
    }
    if (nExtRepSets)
    {
	pad = RecordPadAlign(totRCAPsize, sizeof(RecordSetPtr));
	extRepSetsOffset = totRCAPsize + pad;
	totRCAPsize += pad + (nExtRepSets + 1) * sizeof(RecordMinorOpRec);
    }

    for (i = 0; i < maxSets; i++)
    {
	if (si[i].nintervals)
	{
	    si[i].size = RecordSetMemoryRequirements(
				si[i].intervals, si[i].nintervals, &si[i].align);
	    pad = RecordPadAlign(totRCAPsize, si[i].align);
	    si[i].offset = pad + totRCAPsize;
	    totRCAPsize += pad + si[i].size;
	}
    }

    /* allocate memory for the whole RCAP */

    pRCAP = (RecordClientsAndProtocolPtr)xalloc(totRCAPsize);
    if (!pRCAP) 
    {
	err = BadAlloc;
	goto bailout;
    }

    /* fill in the RCAP */

    pRCAP->pContext = pContext;
    pRCAP->pClientIDs = (XID *)((char *)pRCAP + clientListOffset);
    pRCAP->numClients  = nClients;
    pRCAP->sizeClients = sizeClients;
    pRCAP->clientIDsSeparatelyAllocated = 0;
    for (i = 0; i < nClients; i++)
    {
	RecordDeleteClientFromContext(pContext, pCanonClients[i]);
	pRCAP->pClientIDs[i] = pCanonClients[i];
    }

    /* create all the sets */

    if (si[REQ].intervals)
    {
	pRCAP->pRequestMajorOpSet =
	    RecordCreateSet(si[REQ].intervals, si[REQ].nintervals,
		(RecordSetPtr)((char *)pRCAP + si[REQ].offset), si[REQ].size);
    }
    else pRCAP->pRequestMajorOpSet = NULL;

    if (si[REP].intervals)
    {
	pRCAP->pReplyMajorOpSet =
	    RecordCreateSet(si[REP].intervals, si[REP].nintervals,
		(RecordSetPtr)((char *)pRCAP + si[REP].offset), si[REP].size);
    }
    else pRCAP->pReplyMajorOpSet = NULL;

    if (si[ERR].intervals)
    {
	pRCAP->pErrorSet =
	    RecordCreateSet(si[ERR].intervals, si[ERR].nintervals,
		(RecordSetPtr)((char *)pRCAP + si[ERR].offset), si[ERR].size);
    }
    else pRCAP->pErrorSet = NULL;

    if (si[DEV].intervals)
    {
	pRCAP->pDeviceEventSet =
	    RecordCreateSet(si[DEV].intervals, si[DEV].nintervals,
		(RecordSetPtr)((char *)pRCAP + si[DEV].offset), si[DEV].size);
    }
    else pRCAP->pDeviceEventSet = NULL;

    if (si[DLEV].intervals)
    {
	pRCAP->pDeliveredEventSet =
	    RecordCreateSet(si[DLEV].intervals, si[DLEV].nintervals,
	      (RecordSetPtr)((char *)pRCAP + si[DLEV].offset), si[DLEV].size);
    }
    else pRCAP->pDeliveredEventSet = NULL;

    if (nExtReqSets)
    {
	pRCAP->pRequestMinOpInfo = (RecordMinorOpPtr)
					((char *)pRCAP + extReqSetsOffset);
	pRCAP->pRequestMinOpInfo[0].count = nExtReqSets;
	for (i = 0; i < nExtReqSets; i++, pExtReqSets++)
	{
	    pRCAP->pRequestMinOpInfo[i+1].major.first = pExtReqSets->first;
	    pRCAP->pRequestMinOpInfo[i+1].major.last  = pExtReqSets->last;
	    pRCAP->pRequestMinOpInfo[i+1].major.pMinOpSet =
		RecordCreateSet(pExtReqSets->intervals,
				pExtReqSets->nintervals, 
		  (RecordSetPtr)((char *)pRCAP + pExtReqSets->offset),
				pExtReqSets->size);
	}
    }
    else pRCAP->pRequestMinOpInfo = NULL;

    if (nExtRepSets)
    {
	pRCAP->pReplyMinOpInfo = (RecordMinorOpPtr)
					((char *)pRCAP + extRepSetsOffset);
	pRCAP->pReplyMinOpInfo[0].count = nExtRepSets;
	for (i = 0; i < nExtRepSets; i++, pExtRepSets++)
	{
	    pRCAP->pReplyMinOpInfo[i+1].major.first = pExtRepSets->first;
	    pRCAP->pReplyMinOpInfo[i+1].major.last  = pExtRepSets->last;
	    pRCAP->pReplyMinOpInfo[i+1].major.pMinOpSet =
		RecordCreateSet(pExtRepSets->intervals,
				pExtRepSets->nintervals, 
		  (RecordSetPtr)((char *)pRCAP + pExtRepSets->offset),
				pExtRepSets->size);
	}
    }
    else pRCAP->pReplyMinOpInfo = NULL;

    pRCAP->clientStarted = clientStarted;
    pRCAP->clientDied    = clientDied;

    /* link the RCAP onto the context */

    pRCAP->pNextRCAP = pContext->pListOfRCAP;
    pContext->pListOfRCAP = pRCAP;

    if (pContext->pRecordingClient) /* context enabled */
	RecordInstallHooks(pRCAP, 0);

bailout:
    if (si)
    {
	for (i = 0; i < maxSets; i++)
	    if (si[i].intervals)
		xfree(si[i].intervals);
	DEALLOCATE_LOCAL(si);
    }
    if (pCanonClients && pCanonClients != (XID *)&stuff[1])
	xfree(pCanonClients);
    return err;
} /* RecordRegisterClients */


/* Proc functions all take a client argument, execute the request in
 * client->requestBuffer, and return a protocol error status.
 */

static int
ProcRecordQueryVersion(client)
    ClientPtr client;
{
    /* REQUEST(xRecordQueryVersionReq); */
    xRecordQueryVersionReply 	rep;
    int 		n;

    REQUEST_SIZE_MATCH(xRecordQueryVersionReq);
    rep.type        	= X_Reply;
    rep.sequenceNumber 	= client->sequence;
    rep.length         	= 0;
    rep.majorVersion  	= RECORD_MAJOR_VERSION;
    rep.minorVersion  	= RECORD_MINOR_VERSION;
    if(client->swapped)
    {
    	swaps(&rep.sequenceNumber, n);
	swaps(&rep.majorVersion, n);
	swaps(&rep.minorVersion, n);
    }
    (void)WriteToClient(client, sizeof(xRecordQueryVersionReply),
			(char *)&rep);
    return (client->noClientException);
} /* ProcRecordQueryVersion */


static int
ProcRecordCreateContext(client)
    ClientPtr client;
{
    REQUEST(xRecordCreateContextReq);
    RecordContextPtr pContext;
    RecordContextPtr *ppNewAllContexts = NULL;
    int err = BadAlloc;

    REQUEST_AT_LEAST_SIZE(xRecordCreateContextReq);
    LEGAL_NEW_RESOURCE(stuff->context, client);

    pContext = (RecordContextPtr)xalloc(sizeof(RecordContextRec));
    if (!pContext)
	goto bailout;

    /* make sure there is room in ppAllContexts to store the new context */

    ppNewAllContexts = (RecordContextPtr *)
	xrealloc(ppAllContexts, sizeof(RecordContextPtr) * (numContexts + 1));
    if (!ppNewAllContexts)
	goto bailout;
    ppAllContexts = ppNewAllContexts;

    pContext->id = stuff->context;
    pContext->pRecordingClient = NULL;
    pContext->pListOfRCAP = NULL;
    pContext->elemHeaders = 0;
    pContext->bufCategory = 0;
    pContext->numBufBytes = 0;
    pContext->pBufClient = NULL;
    pContext->continuedReply = 0;

    err = RecordRegisterClients(pContext, client,
				(xRecordRegisterClientsReq *)stuff);
    if (err != Success)
	goto bailout;

    if (AddResource(pContext->id, RTContext, pContext))
    {
	ppAllContexts[numContexts++] = pContext;
	return Success;
    }
    else
    {
	RecordDeleteContext((pointer)pContext, pContext->id);
	err = BadAlloc;
    }
bailout:
    if (pContext)
	xfree(pContext);
    return err;
} /* ProcRecordCreateContext */


static int
ProcRecordRegisterClients(client)
    ClientPtr client;
{
    RecordContextPtr pContext;
    REQUEST(xRecordRegisterClientsReq);

    REQUEST_AT_LEAST_SIZE(xRecordRegisterClientsReq);
    VERIFY_CONTEXT(pContext, stuff->context, client);

    return RecordRegisterClients(pContext, client, stuff);
} /* ProcRecordRegisterClients */


static int
ProcRecordUnregisterClients(client)
    ClientPtr client;
{
    RecordContextPtr pContext;
    int err;
    REQUEST(xRecordUnregisterClientsReq);
    XID *pCanonClients;
    int nClients;
    int i;

    REQUEST_AT_LEAST_SIZE(xRecordUnregisterClientsReq);
    if ((client->req_len << 2) - SIZEOF(xRecordUnregisterClientsReq) !=
	4 * stuff->nClients)
	return BadLength;
    VERIFY_CONTEXT(pContext, stuff->context, client);
    err = RecordSanityCheckClientSpecifiers((XID *)&stuff[1],
					    stuff->nClients, 0);
    if (err != Success)
	return err;

    nClients = stuff->nClients;
    pCanonClients = RecordCanonicalizeClientSpecifiers((XID *)&stuff[1],
						 &nClients, 0);
    if (!pCanonClients)
	return BadAlloc;

    for (i = 0; i < nClients; i++)
    {
	RecordDeleteClientFromContext(pContext, pCanonClients[i]);
    }
    if (pCanonClients != (XID *)&stuff[1])
	xfree(pCanonClients);
    return Success;
} /* ProcRecordUnregisterClients */

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

/* stuff for GetContext */

/* This is a tactical structure used to hold the xRecordRanges as they are
 * being reconstituted from the sets in the RCAPs.
 */

typedef struct {
    xRecordRange *pRanges;  /* array of xRecordRanges for one RCAP */
    int size;		/* number of elements in pRanges, >= nRanges */
    int nRanges;	/* number of occupied element of pRanges */
} GetContextRangeInfoRec, *GetContextRangeInfoPtr;


/* RecordAllocRanges
 *
 * Arguments:
 *	pri is a pointer to a GetContextRangeInfoRec to allocate for.
 *	nRanges is the number of xRecordRanges desired for pri.
 *
 * Returns: BadAlloc if a memory allocation error occurred, else Success.
 *
 * Side Effects:
 *	If Success is returned, pri->pRanges points to at least nRanges
 *	ranges.  pri->nRanges is set to nRanges.  pri->size is the actual
 *	number of ranges.  Newly allocated ranges are zeroed.
 */
static int
RecordAllocRanges(pri, nRanges)
    GetContextRangeInfoPtr pri;
    int nRanges;
{
    int newsize;
    xRecordRange *pNewRange;
#define SZINCR 8

    newsize = max(pri->size + SZINCR, nRanges);
    pNewRange = (xRecordRange *)xrealloc(pri->pRanges,
			 newsize * sizeof(xRecordRange));
    if (!pNewRange)
	return BadAlloc;

    pri->pRanges = pNewRange;
    pri->size = newsize;
    bzero(&pri->pRanges[pri->size - SZINCR], SZINCR * sizeof(xRecordRange));
    if (pri->nRanges < nRanges)
	pri->nRanges = nRanges;
    return Success;
} /* RecordAllocRanges */


/* RecordConvertSetToRanges
 *
 * Arguments:
 *	pSet is the set to be converted.
 *	pri is where the result should be stored.
 *	byteoffset is the offset from the start of an xRecordRange of the
 *	  two vales (first, last) we are interested in.
 *	card8 is TRUE if the vales are one byte each and FALSE if two bytes
 *	  each.
 *	imax is the largest set value to store in pri->pRanges.
 *	pStartIndex, if non-NULL, is the index of the first range in
 *	  pri->pRanges that should be stored to.  If NULL,
 *	  start at index 0.
 *
 * Returns: BadAlloc if a memory allocation error occurred, else Success.
 *
 * Side Effects:
 *	If Success is returned, the slice of pri->pRanges indicated by
 *	byteoffset and card8 is filled in with the intervals from pSet.
 *	if pStartIndex was non-NULL, *pStartIndex is filled in with one
 *	more than the index of the last xRecordRange that was touched.
 */
static int
RecordConvertSetToRanges(
    RecordSetPtr pSet,
    GetContextRangeInfoPtr pri,
    int byteoffset,
    Bool card8,
    unsigned int imax,
    int *pStartIndex
)
{
    int nRanges;
    RecordSetIteratePtr pIter = NULL;
    RecordSetInterval interval;
    CARD8 *pCARD8;
    CARD16 *pCARD16;
    int err;

    if (!pSet)
	return Success;

    nRanges = pStartIndex ? *pStartIndex : 0;
    while ((pIter = RecordIterateSet(pSet, pIter, &interval)))
    {
	if (interval.first > imax) break;
	if (interval.last  > imax) interval.last = imax;
	nRanges++;
	if (nRanges > pri->size)
	{
	    err = RecordAllocRanges(pri, nRanges);
	    if (err != Success)
		return err;
	}
	else
	    pri->nRanges = max(pri->nRanges, nRanges);
	if (card8)
	{
	    pCARD8 = ((CARD8 *)&pri->pRanges[nRanges-1]) + byteoffset;
	    *pCARD8++ = interval.first;
	    *pCARD8   = interval.last;
	}
	else
	{
	    pCARD16 = (CARD16 *)
			(((char *)&pri->pRanges[nRanges-1]) + byteoffset);
	    *pCARD16++ = interval.first;
	    *pCARD16   = interval.last;
	}
    }
    if (pStartIndex)
	*pStartIndex = nRanges;
    return Success;
} /* RecordConvertSetToRanges */


/* RecordConvertMinorOpInfoToRanges
 *
 * Arguments:
 *	pMinOpInfo is the minor opcode info to convert to xRecordRanges.
 *	pri is where the result should be stored.
 *	byteoffset is the offset from the start of an xRecordRange of the
 *	  four vales (CARD8 major_first, CARD8 major_last,
 *	  CARD16 minor_first, CARD16 minor_last) we are going to store.
 *
 * Returns: BadAlloc if a memory allocation error occurred, else Success.
 *
 * Side Effects:
 *	If Success is returned, the slice of pri->pRanges indicated by
 *	byteoffset is filled in with the information from pMinOpInfo.
 */
static int
RecordConvertMinorOpInfoToRanges(
    RecordMinorOpPtr pMinOpInfo,
    GetContextRangeInfoPtr pri,
    int byteoffset
)
{
    int nsets;
    int start;
    int i;
    int err;

    if (!pMinOpInfo)
	return Success;

    nsets = pMinOpInfo->count;
    pMinOpInfo++;
    start = 0;
    for (i = 0; i < nsets; i++)
    {
	int j, s;
	s = start;
	err = RecordConvertSetToRanges(pMinOpInfo[i].major.pMinOpSet, pri,
				byteoffset + 2, FALSE, 65535, &start);
	if (err != Success) return err;
	for (j = s; j < start; j++)
	{
	    CARD8 *pCARD8 = ((CARD8 *)&pri->pRanges[j]) + byteoffset;
	    *pCARD8++ = pMinOpInfo[i].major.first;
	    *pCARD8   = pMinOpInfo[i].major.last;
	}
    }
    return Success;
} /* RecordConvertMinorOpInfoToRanges */


/* RecordSwapRanges
 *
 * Arguments:
 *	pRanges is an array of xRecordRanges.
 *	nRanges is the number of elements in pRanges.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	The 16 bit fields of each xRecordRange are byte swapped.
 */
static void
RecordSwapRanges(pRanges, nRanges)
    xRecordRange *pRanges;
    int nRanges;
{
    int i;
    register char n;
    for (i = 0; i < nRanges; i++, pRanges++)
    {
	swaps(&pRanges->extRequestsMinorFirst, n);
	swaps(&pRanges->extRequestsMinorLast, n);
	swaps(&pRanges->extRepliesMinorFirst, n);
	swaps(&pRanges->extRepliesMinorLast, n);
    }
} /* RecordSwapRanges */


static int
ProcRecordGetContext(client)
    ClientPtr client;
{
    RecordContextPtr pContext;
    REQUEST(xRecordGetContextReq);
    xRecordGetContextReply rep;
    int n;
    RecordClientsAndProtocolPtr pRCAP;
    int nRCAPs = 0;
    GetContextRangeInfoPtr pRangeInfo;
    GetContextRangeInfoPtr pri;
    int i;
    int err;

    REQUEST_SIZE_MATCH(xRecordGetContextReq);
    VERIFY_CONTEXT(pContext, stuff->context, client);

    /* how many RCAPs are there on this context? */

    for (pRCAP = pContext->pListOfRCAP; pRCAP; pRCAP = pRCAP->pNextRCAP)
	nRCAPs++;

    /* allocate and initialize space for record range info */

    pRangeInfo = (GetContextRangeInfoPtr)ALLOCATE_LOCAL(
				nRCAPs * sizeof(GetContextRangeInfoRec));
    if (!pRangeInfo && nRCAPs > 0)
	return BadAlloc;
    for (i = 0; i < nRCAPs; i++)
    {
	pRangeInfo[i].pRanges = NULL;
	pRangeInfo[i].size = 0;
	pRangeInfo[i].nRanges = 0;
    }

    /* convert the RCAP (internal) representation of the recorded protocol
     * to the wire protocol (external) representation, storing the information
     * for the ith RCAP in pri[i]
     */

    for (pRCAP = pContext->pListOfRCAP, pri = pRangeInfo;
	 pRCAP;
	 pRCAP = pRCAP->pNextRCAP, pri++)
    {
	xRecordRange rr;

	err = RecordConvertSetToRanges(pRCAP->pRequestMajorOpSet, pri,
			offset_of(rr, coreRequestsFirst), TRUE, 127, NULL);
	if (err != Success) goto bailout;

	err = RecordConvertSetToRanges(pRCAP->pReplyMajorOpSet, pri,
			offset_of(rr, coreRepliesFirst), TRUE, 127, NULL);
	if (err != Success) goto bailout;

	err = RecordConvertSetToRanges(pRCAP->pDeliveredEventSet, pri,
			offset_of(rr, deliveredEventsFirst), TRUE, 255, NULL);
	if (err != Success) goto bailout;

	err = RecordConvertSetToRanges(pRCAP->pDeviceEventSet, pri,
			offset_of(rr, deviceEventsFirst), TRUE, 255, NULL);
	if (err != Success) goto bailout;

	err = RecordConvertSetToRanges(pRCAP->pErrorSet, pri,
			      offset_of(rr, errorsFirst), TRUE, 255, NULL);
	if (err != Success) goto bailout;

	err = RecordConvertMinorOpInfoToRanges(pRCAP->pRequestMinOpInfo,
				pri, offset_of(rr, extRequestsMajorFirst));
	if (err != Success) goto bailout;

	err = RecordConvertMinorOpInfoToRanges(pRCAP->pReplyMinOpInfo,
				pri, offset_of(rr, extRepliesMajorFirst));
	if (err != Success) goto bailout;

	if (pRCAP->clientStarted || pRCAP->clientDied)
	{
	    if (pri->nRanges == 0)
		RecordAllocRanges(pri, 1);
	    pri->pRanges[0].clientStarted = pRCAP->clientStarted;
	    pri->pRanges[0].clientDied    = pRCAP->clientDied;
	}
    }

    /* calculate number of clients and reply length */

    rep.nClients = 0;
    rep.length = 0;
    for (pRCAP = pContext->pListOfRCAP, pri = pRangeInfo;
	 pRCAP;
	 pRCAP = pRCAP->pNextRCAP, pri++)
    {
	rep.nClients += pRCAP->numClients;
	rep.length += pRCAP->numClients *
		( (sizeof(xRecordClientInfo) >> 2) +
		  pri->nRanges * (sizeof(xRecordRange) >> 2));
    }

    /* write the reply header */

    rep.type = X_Reply;
    rep.sequenceNumber 	= client->sequence;
    rep.enabled = pContext->pRecordingClient != NULL;
    rep.elementHeader = pContext->elemHeaders;
    if(client->swapped)
    {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
    	swapl(&rep.nClients, n);
    }
    (void)WriteToClient(client, sizeof(xRecordGetContextReply),
			(char *)&rep);

    /* write all the CLIENT_INFOs */

    for (pRCAP = pContext->pListOfRCAP, pri = pRangeInfo;
	 pRCAP;
	 pRCAP = pRCAP->pNextRCAP, pri++)
    {
	xRecordClientInfo rci;
	rci.nRanges = pri->nRanges;
	if (client->swapped)
	{
	    swapl(&rci.nRanges, n);
	    RecordSwapRanges(pri->pRanges, pri->nRanges);
	}
	for (i = 0; i < pRCAP->numClients; i++)
	{
	    rci.clientResource = pRCAP->pClientIDs[i];
	    if (client->swapped) swapl(&rci.clientResource, n);
	    WriteToClient(client, sizeof(xRecordClientInfo), (char *)&rci);
	    WriteToClient(client, sizeof(xRecordRange) * pri->nRanges,
			  (char *)pri->pRanges);
	}
    }
    err = client->noClientException;

bailout:
    for (i = 0; i < nRCAPs; i++)
    {
	if (pRangeInfo[i].pRanges) xfree(pRangeInfo[i].pRanges);
    }
    DEALLOCATE_LOCAL(pRangeInfo);
    return err;
} /* ProcRecordGetContext */


static int
ProcRecordEnableContext(client)
    ClientPtr client;
{
    RecordContextPtr pContext;
    REQUEST(xRecordEnableContextReq);
    int i;
    RecordClientsAndProtocolPtr pRCAP;

    REQUEST_SIZE_MATCH(xRecordGetContextReq);
    VERIFY_CONTEXT(pContext, stuff->context, client);
    if (pContext->pRecordingClient)
	return BadMatch; /* already enabled */

    /* install record hooks for each RCAP */

    for (pRCAP = pContext->pListOfRCAP; pRCAP; pRCAP = pRCAP->pNextRCAP)
    {
	int err = RecordInstallHooks(pRCAP, 0);
	if (err != Success)
	{ /* undo the previous installs */
	    RecordClientsAndProtocolPtr pUninstallRCAP;
	    for (pUninstallRCAP = pContext->pListOfRCAP;
		 pUninstallRCAP != pRCAP;
		 pUninstallRCAP = pUninstallRCAP->pNextRCAP)
	    {
		RecordUninstallHooks(pUninstallRCAP, 0);
	    }
	    return err;
	}
    }

    /* Disallow further request processing on this connection until
     * the context is disabled.
     */
    IgnoreClient(client);
    pContext->pRecordingClient = client;

    /* Don't allow the data connection to record itself; unregister it. */
    RecordDeleteClientFromContext(pContext,
				  pContext->pRecordingClient->clientAsMask);

    /* move the newly enabled context to the front part of ppAllContexts,
     * where all the enabled contexts are
     */
    i = RecordFindContextOnAllContexts(pContext);
    assert(i >= numEnabledContexts);
    if (i != numEnabledContexts)
    {
	ppAllContexts[i] = ppAllContexts[numEnabledContexts];
	ppAllContexts[numEnabledContexts] = pContext;
    }

    ++numEnabledContexts;
    assert(numEnabledContexts > 0);

    /* send StartOfData */
    RecordAProtocolElement(pContext, NULL, XRecordStartOfData, NULL, 0, 0);
    RecordFlushReplyBuffer(pContext, NULL, 0, NULL, 0);
    return Success;
} /* ProcRecordEnableContext */


/* RecordDisableContext
 *
 * Arguments:
 *	pContext is the context to disable.
 *	nRanges is the number of elements in pRanges.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	If the context was enabled, it is disabled.  An EndOfData
 *	message is sent to the recording client.  Recording hooks for
 *	this context are uninstalled.  The context is moved to the
 *	rear part of the ppAllContexts array.  numEnabledContexts is
 *	decremented.  Request processing for the formerly recording client
 *	is resumed.
 */
static void
RecordDisableContext(pContext)
    RecordContextPtr pContext;
{
    RecordClientsAndProtocolPtr pRCAP;
    int i;

    if (!pContext->pRecordingClient) return;
    if (!pContext->pRecordingClient->clientGone)
    {
	RecordAProtocolElement(pContext, NULL, XRecordEndOfData, NULL, 0, 0);
	RecordFlushReplyBuffer(pContext, NULL, 0, NULL, 0);
	/* Re-enable request processing on this connection. */
	AttendClient(pContext->pRecordingClient);
    }

    for (pRCAP = pContext->pListOfRCAP; pRCAP; pRCAP = pRCAP->pNextRCAP)
    {
	RecordUninstallHooks(pRCAP, 0);
    }

    pContext->pRecordingClient = NULL;

    /* move the newly disabled context to the rear part of ppAllContexts,
     * where all the disabled contexts are
     */
    i = RecordFindContextOnAllContexts(pContext);
    assert( (i != -1) && (i < numEnabledContexts) );
    if (i != (numEnabledContexts - 1) )
    {
	ppAllContexts[i] = ppAllContexts[numEnabledContexts-1];
	ppAllContexts[numEnabledContexts-1] = pContext;
    }
    --numEnabledContexts;
    assert(numEnabledContexts >= 0);
} /* RecordDisableContext */


static int
ProcRecordDisableContext(client)
    ClientPtr client;
{
    RecordContextPtr pContext;
    REQUEST(xRecordDisableContextReq);

    REQUEST_SIZE_MATCH(xRecordDisableContextReq);
    VERIFY_CONTEXT(pContext, stuff->context, client);
    RecordDisableContext(pContext);
    return Success;
} /* ProcRecordDisableContext */


/* RecordDeleteContext
 *
 * Arguments:
 *	value is the context to delete.
 *	id is its resource ID.
 *
 * Returns: Success.
 *
 * Side Effects:
 *	Disables the context, frees all associated memory, and removes
 *	it from the ppAllContexts array.
 */
static int
RecordDeleteContext(value, id)
    pointer value;
    XID id;
{
    int i;
    RecordContextPtr pContext = (RecordContextPtr)value;
    RecordClientsAndProtocolPtr pRCAP;

    RecordDisableContext(pContext);

    /*  Remove all the clients from all the RCAPs.
     *  As a result, the RCAPs will be freed.
     */

    while ((pRCAP = pContext->pListOfRCAP))
    {
	int numClients = pRCAP->numClients;
	/* when the last client is deleted, the RCAP will go away. */
	while(numClients--)
	{
	    RecordDeleteClientFromRCAP(pRCAP, numClients);
	}
    }

    xfree(pContext);

    /* remove context from AllContexts list */

    if (-1 != (i = RecordFindContextOnAllContexts(pContext)))
    {
	ppAllContexts[i] = ppAllContexts[numContexts - 1];
	if (--numContexts == 0)
	{
	    xfree(ppAllContexts);
	    ppAllContexts = NULL;
	}
    }
    return Success;
} /* RecordDeleteContext */


static int
ProcRecordFreeContext(client)
    ClientPtr       client;
{
    RecordContextPtr pContext;
    REQUEST(xRecordFreeContextReq);

    REQUEST_SIZE_MATCH(xRecordFreeContextReq);
    VERIFY_CONTEXT(pContext, stuff->context, client);
    FreeResource(stuff->context, RT_NONE);
    return Success;
} /* ProcRecordFreeContext */


static int
ProcRecordDispatch(client)
    ClientPtr client;
{
    REQUEST(xReq);

    switch (stuff->data)
    {
	case X_RecordQueryVersion:
	    return ProcRecordQueryVersion(client);
	case X_RecordCreateContext:
	    return ProcRecordCreateContext(client);
	case X_RecordRegisterClients:
	    return ProcRecordRegisterClients(client);
	case X_RecordUnregisterClients:
	    return ProcRecordUnregisterClients(client);
	case X_RecordGetContext:
	    return ProcRecordGetContext(client);
	case X_RecordEnableContext:
	    return ProcRecordEnableContext(client);
	case X_RecordDisableContext:
	    return ProcRecordDisableContext(client);
	case X_RecordFreeContext:
	    return ProcRecordFreeContext(client);
       default:
	    return BadRequest;
    }
} /* ProcRecordDispatch */


static int
SProcRecordQueryVersion(client)
    ClientPtr client;
{
    REQUEST(xRecordQueryVersionReq);
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xRecordQueryVersionReq);
    swaps(&stuff->majorVersion, n);
    swaps(&stuff->minorVersion,n);
    return ProcRecordQueryVersion(client);
} /* SProcRecordQueryVersion */


static int
SwapCreateRegister(xRecordRegisterClientsReq *stuff)
{
    register char n;
    int i;
    XID *pClientID;

    swapl(&stuff->context, n);
    swapl(&stuff->nClients, n);
    swapl(&stuff->nRanges, n);
    pClientID = (XID *)&stuff[1];
    if (stuff->nClients > stuff->length - (sz_xRecordRegisterClientsReq >> 2))
	return BadLength;
    for (i = 0; i < stuff->nClients; i++, pClientID++)
    {
	swapl(pClientID, n);
    }
    if (stuff->nRanges > stuff->length - (sz_xRecordRegisterClientsReq >> 2)
	- stuff->nClients)
	return BadLength;
    RecordSwapRanges((xRecordRange *)pClientID, stuff->nRanges);
    return Success;
} /* SwapCreateRegister */


static int
SProcRecordCreateContext(client)
    ClientPtr client;
{
    REQUEST(xRecordCreateContextReq);
    int			status;
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_AT_LEAST_SIZE(xRecordCreateContextReq);
    if ((status = SwapCreateRegister((pointer)stuff)) != Success)
	return status;
    return ProcRecordCreateContext(client);
} /* SProcRecordCreateContext */


static int
SProcRecordRegisterClients(client)
    ClientPtr client;
{
    REQUEST(xRecordRegisterClientsReq);
    int			status;
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_AT_LEAST_SIZE(xRecordRegisterClientsReq);
    if ((status = SwapCreateRegister((pointer)stuff)) != Success)
	return status;
    return ProcRecordRegisterClients(client);
} /* SProcRecordRegisterClients */


static int
SProcRecordUnregisterClients(client)
    ClientPtr client;
{
    REQUEST(xRecordUnregisterClientsReq);
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_AT_LEAST_SIZE(xRecordUnregisterClientsReq);
    swapl(&stuff->context, n);
    swapl(&stuff->nClients, n);
    SwapRestL(stuff);
    return ProcRecordUnregisterClients(client);
} /* SProcRecordUnregisterClients */


static int
SProcRecordGetContext(client)
    ClientPtr client;
{
    REQUEST(xRecordGetContextReq);
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xRecordGetContextReq);
    swapl(&stuff->context, n);
    return ProcRecordGetContext(client);
} /* SProcRecordGetContext */

static int
SProcRecordEnableContext(client)
    ClientPtr client;
{
    REQUEST(xRecordEnableContextReq);
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xRecordEnableContextReq);
    swapl(&stuff->context, n);
    return ProcRecordEnableContext(client);
} /* SProcRecordEnableContext */


static int
SProcRecordDisableContext(client)
    ClientPtr client;
{
    REQUEST(xRecordDisableContextReq);
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xRecordDisableContextReq);
    swapl(&stuff->context, n);
    return ProcRecordDisableContext(client);
} /* SProcRecordDisableContext */


static int
SProcRecordFreeContext(client)
    ClientPtr client;
{
    REQUEST(xRecordFreeContextReq);
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xRecordFreeContextReq);
    swapl(&stuff->context, n);
    return ProcRecordFreeContext(client);
} /* SProcRecordFreeContext */


static int
SProcRecordDispatch(client)
    ClientPtr client;
{
    REQUEST(xReq);

    switch (stuff->data)
    {
	case X_RecordQueryVersion:
	    return SProcRecordQueryVersion(client);
	case X_RecordCreateContext:
	    return SProcRecordCreateContext(client);
	case X_RecordRegisterClients:
	    return SProcRecordRegisterClients(client);
	case X_RecordUnregisterClients:
	    return SProcRecordUnregisterClients(client);
	case X_RecordGetContext:
	    return SProcRecordGetContext(client);
	case X_RecordEnableContext:
	    return SProcRecordEnableContext(client);
	case X_RecordDisableContext:
	    return SProcRecordDisableContext(client);
	case X_RecordFreeContext:
	    return SProcRecordFreeContext(client);
       default:
	    return BadRequest;
    }
} /* SProcRecordDispatch */

/* XXX goes in header file */
extern void SwapConnSetupInfo(), SwapConnSetupPrefix();

/* RecordConnectionSetupInfo
 *
 * Arguments:
 *	pContext is an enabled context that specifies recording of 
 *	  connection setup info.
 *	pci holds the connection setup info.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	The connection setup info is sent to the recording client.
 */
static void
RecordConnectionSetupInfo(pContext, pci)
    RecordContextPtr pContext;
    NewClientInfoRec *pci;
{
    int prefixsize = SIZEOF(xConnSetupPrefix);
    int restsize = pci->prefix->length * 4;

    if (pci->client->swapped)
    {
	char * pConnSetup = (char *)ALLOCATE_LOCAL(prefixsize + restsize);
	if (!pConnSetup)
	    return;
	SwapConnSetupPrefix(pci->prefix, pConnSetup);
	SwapConnSetupInfo(pci->setup, pConnSetup + prefixsize);
	RecordAProtocolElement(pContext, pci->client, XRecordClientStarted,
			       (pointer)pConnSetup, prefixsize + restsize, 0);
	DEALLOCATE_LOCAL(pConnSetup);
    }
    else
    {
	/* don't alloc and copy as in the swapped case; just send the
	 * data in two pieces
	 */
	RecordAProtocolElement(pContext, pci->client, XRecordClientStarted,
			(pointer)pci->prefix, prefixsize, restsize);
	RecordAProtocolElement(pContext, pci->client, XRecordClientStarted,
			(pointer)pci->setup, restsize, /* continuation */ -1);
    }
} /* RecordConnectionSetupInfo */


/* RecordDeleteContext
 *
 * Arguments:
 *	pcbl is &ClientStateCallback.
 *	nullata is NULL.
 *	calldata is a pointer to a NewClientInfoRec (include/dixstruct.h)
 *	which contains information about client state changes.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	If a new client has connected and any contexts have specified
 *	XRecordFutureClients, the new client is registered on those contexts.
 *	If any of those contexts specify recording of the connection setup
 *	info, it is recorded.
 *
 *	If an existing client has disconnected, it is deleted from any
 *	contexts that it was registered on.  If any of those contexts
 *	specified XRecordClientDied, they record a ClientDied protocol element.
 *	If the disconnectiong client happened to be the data connection of an
 *	enabled context, the context is disabled.
 */

static void
RecordAClientStateChange(pcbl, nulldata, calldata)
    CallbackListPtr *pcbl;
    pointer nulldata;
    pointer calldata;
{
    NewClientInfoRec *pci = (NewClientInfoRec *)calldata;
    int i;
    ClientPtr pClient = pci->client;

    switch (pClient->clientState)
    {
    case ClientStateRunning: /* new client */
	for (i = 0; i < numContexts; i++)
	{
	    RecordClientsAndProtocolPtr pRCAP;
	    RecordContextPtr pContext = ppAllContexts[i];

	    if ((pRCAP = RecordFindClientOnContext(pContext,
					    XRecordFutureClients, NULL)))
	    {
		RecordAddClientToRCAP(pRCAP, pClient->clientAsMask);
		if (pContext->pRecordingClient && pRCAP->clientStarted)
		    RecordConnectionSetupInfo(pContext, pci);
	    }
	}
    break;

    case ClientStateGone:
    case ClientStateRetained: /* client disconnected */
	for (i = 0; i < numContexts; i++)
	{
	    RecordClientsAndProtocolPtr pRCAP;
	    RecordContextPtr pContext = ppAllContexts[i];
	    int pos;

	    if (pContext->pRecordingClient == pClient)
		RecordDisableContext(pContext);
	    if ((pRCAP = RecordFindClientOnContext(pContext,
				    pClient->clientAsMask, &pos)))
	    {
		if (pContext->pRecordingClient && pRCAP->clientDied)
		    RecordAProtocolElement(pContext, pClient,
					   XRecordClientDied, NULL, 0, 0);
		RecordDeleteClientFromRCAP(pRCAP, pos);
	    }
	}
    break;

    default:
    break;
    } /* end switch on client state */
} /* RecordAClientStateChange */


/* RecordCloseDown
 *
 * Arguments:
 *	extEntry is the extension information for RECORD.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	Performs any cleanup needed by RECORD at server shutdown time.
 *	
 */
static void
RecordCloseDown(extEntry)
    ExtensionEntry *extEntry;
{
    DeleteCallback(&ClientStateCallback, RecordAClientStateChange, NULL);
} /* RecordCloseDown */


/* RecordExtensionInit
 *
 * Arguments: none.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	Enables the RECORD extension if possible.
 */
void 
RecordExtensionInit()
{
    ExtensionEntry *extentry;

    RTContext = CreateNewResourceType(RecordDeleteContext);
    if (!RTContext)
	return;

    RecordClientPrivateIndex = AllocateClientPrivateIndex();
    if (!AllocateClientPrivate(RecordClientPrivateIndex, 0))
	return;

    ppAllContexts = NULL;
    numContexts = numEnabledContexts = numEnabledRCAPs = 0;

    if (!AddCallback(&ClientStateCallback, RecordAClientStateChange, NULL))
	return;

    extentry = AddExtension(RECORD_NAME, RecordNumEvents, RecordNumErrors,
			    ProcRecordDispatch, SProcRecordDispatch,
			    RecordCloseDown, StandardMinorOpcode);
    if (!extentry)
    {
	DeleteCallback(&ClientStateCallback, RecordAClientStateChange, NULL);
	return;
    }
    RecordErrorBase = extentry->errorBase;

} /* RecordExtensionInit */