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

	This file is part of the Palm OS Emulator.

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

#include "EmCommon.h"
#include "MetaMemory.h"

#include "DebugMgr.h"			// Debug::GetRoutineName
#include "EmBankSRAM.h"			// gRAMBank_Size
#include "EmCPU68K.h"			// gCPU68K
#include "EmHAL.h"				// EmHAL
#include "EmLowMem.h"			// LowMem_SetGlobal, LowMem_GetGlobal
#include "EmMemory.h"			// CEnableFullAccess, EmMemGetMetaAddress
#include "EmPalmFunction.h"		// InFoo functions
#include "EmPalmOS.h"			// StackRange, GetBootStack
#include "EmPalmStructs.h"		// EmAliasWindowType, EmAliasFormType
#include "EmPatchState.h"		// IsInSysBinarySearch, OSMajorMinorVersion
#include "EmSession.h"			// gSession->ScheduleDeferredError
#include "Logging.h"			// ReportUIMgrDataAccess
#include "Miscellaneous.h"		// FindFunctionName
#include "ROMStubs.h"			// SysKernelInfo
#include "SessionFile.h"		// SessionFile::Write

#include <algorithm>			// find
#include <ctype.h>				// islower

struct EmTaggedPalmChunk : public EmPalmChunk
{
	EmTaggedPalmChunk (void) {}
	EmTaggedPalmChunk (const EmPalmChunk& chunk, Bool isSystemChunk) :
		EmPalmChunk (chunk),
		fIsSystemChunk (isSystemChunk)
		{}

	Bool	fIsSystemChunk;
};

typedef vector<EmTaggedPalmChunk>	EmTaggedPalmChunkList;

static EmTaggedPalmChunkList	gTaggedChunks;
static Bool						gHaveLastChunk;
static EmTaggedPalmChunk		gLastChunk;

static vector<MemHandle>		gBitmapHandleList;
static vector<MemPtr>			gBitmapPointerList;

enum
{
	kUIWindow,
	kUIBitmap
};

typedef Bool (*IterFn) (emuptr object, void* data, int type);
static Bool PrvCheckUIObject (emuptr object, void* data, int type);
static Bool PrvMarkUIObject (emuptr object, void* data, int type);
static Bool PrvUnmarkUIObject (emuptr object, void* data, int type);
static Bool PrvForEachBitmap (IterFn fn, void* data);
static Bool PrvForEachWindow (IterFn fn, void* data);
static Bool PrvForEachUIObject (IterFn fn, void* data);


#pragma mark -

// ---------------------------------------------------------------------------
//		¥ MetaMemory::Initialize
// ---------------------------------------------------------------------------

void MetaMemory::Initialize (void)
{
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::Reset
// ---------------------------------------------------------------------------

void MetaMemory::Reset (void)
{
	gTaggedChunks.clear ();
	gHaveLastChunk = false;

	gBitmapHandleList.clear ();
	gBitmapPointerList.clear ();
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::Save
// ---------------------------------------------------------------------------

void MetaMemory::Save (SessionFile& f)
{
	const long	kCurrentVersion = 1;

	Chunk			chunk;
	EmStreamChunk	s (chunk);

	s << kCurrentVersion;

	gBitmapHandleList.clear ();
	gBitmapPointerList.clear ();

	s << gBitmapHandleList;
	s << gBitmapPointerList;

	f.WriteMetaInfo (chunk);
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::Load
// ---------------------------------------------------------------------------

void MetaMemory::Load (SessionFile& f)
{
	gTaggedChunks.clear ();
	gHaveLastChunk = false;

	Chunk	chunk;
	if (f.ReadMetaInfo (chunk))
	{
		long			version;
		EmStreamChunk	s (chunk);

		s >> version;

		if (version >= 1)
		{
			s >> gBitmapHandleList;
			s >> gBitmapPointerList;

			gBitmapHandleList.clear ();
			gBitmapPointerList.clear ();
		}
	}
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::Dispose
// ---------------------------------------------------------------------------

void MetaMemory::Dispose (void)
{
}


#if FOR_LATER
// ---------------------------------------------------------------------------
//		¥ MetaMemory::MarkUninitialized
// ---------------------------------------------------------------------------

void MetaMemory::MarkUninitialized (emuptr begin, emuptr end)
{
	MarkRange (begin, end, kUninitialized);
}
#endif


#if FOR_LATER
// ---------------------------------------------------------------------------
//		¥ MetaMemory::MoveUninitialized
// ---------------------------------------------------------------------------
//	Transfer the initialized/uninitialized state of a range of bytes to a
//	new location.  Called during MemMove, so that the state of the bytes
//	being moved can be preserved.

void MetaMemory::MoveUninitialized (emuptr source, emuptr dest, uint32 size)
{
	source = MASK (source);
	dest = MASK (dest);

	if (source > fgMetaMemorySize)
		return;

	if (dest > fgMetaMemorySize)
		return;

	uint8*	p0 = fgMetaMemory + source;
	uint8*	p1 = fgMetaMemory + dest;

	while (size--)
	{
		uint8	dValue = *p0;
		uint8	sValue = *p1;

		dValue = (dValue & ~kUninitialized) | (sValue & kUninitialized);

		*p0 = dValue;

		++p0;
		++p1;
	}
}
#endif


#if FOR_LATER
// ---------------------------------------------------------------------------
//		¥ MetaMemory::MarkInitialized
// ---------------------------------------------------------------------------

void MetaMemory::MarkInitialized (emuptr begin, emuptr end)
{
	UnmarkRange (begin, end, kUninitialized);
}
#endif


// ---------------------------------------------------------------------------
//		¥ MetaMemory::SyncHeap
// ---------------------------------------------------------------------------
//	Find chunk headers and mark them as memory manager structures.  Mark
//	unlocked relocatable chunks as "unlocked" and "initialized" (as we don't
//	have any idea any more what their state was before they were moved).
//	Mark free blocks as "uninitialized".

// ---------------------------------------------------------------------------
//		¥ MetaMemory::SyncOneChunk
// ---------------------------------------------------------------------------
//	Mark the chunk header, free chunks, and unlocked chunks.

void MetaMemory::SyncOneChunk (const EmPalmChunk& chunk)
{
	// Set the access for the chunk header.

	MarkChunkHeader (chunk.HeaderStart (), chunk.HeaderEnd ());

	// Set the access for the body of the chunk.

	// Check for free chunks.

	if (chunk.Free ())
	{
		MarkFreeChunk (chunk.BodyStart (), chunk.BodyEnd ());
	}

	// It's not a free chunk; see if it's unlocked.

	else if (chunk.LockCount () == 0)
	{
		MarkUnlockedChunk (chunk.BodyStart (), chunk.BodyEnd ());
	}

	// It's an allocated, locked chunk.

	else
	{
		MarkTotalAccess (chunk.BodyStart (), chunk.BodyEnd ());
	}

	// Set the access for any unallocated trailing bytes.

	if (chunk.TrailerSize () > 0)
	{
		MarkChunkTrailer (chunk.TrailerStart (), chunk.TrailerEnd ());
	}
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::Resync
// ---------------------------------------------------------------------------

void MetaMemory::Resync (const EmPalmChunkList& delta)
{
	if (delta.size () == 0)
		return;

	// Get the heap that was changed. Assume that all chunks in the
	// delta list are in the same heap for now.

	EmPalmChunkList::const_iterator	iter = delta.begin ();
	const EmPalmHeap*	heap = EmPalmHeap::GetHeapByPtr (iter->Start ());
	if (!heap)
		return;

	// Only support syncing with dynamic heap for now.

	if (heap->HeapID () != 0)
		return;

	while (iter != delta.end ())
	{
		SyncOneChunk (*iter);
		++iter;
	}

	// This process has just wiped out any access bits we've set
	// for UI objects.  Re-establish those.

	MetaMemory::MarkUIObjects ();

	// Mark the master pointer tables.  Mark the MPT headers as
	// for use by the Memory Manager.  However, mark the tables
	// themselves as usable by any of the OS; a lot of the OS
	// uses a MemMgr macro to deref handles directly.

	ITERATE_MPTS(*heap, mpt_iter, end)
	{
		MarkMPT (mpt_iter->Start (), mpt_iter->TableStart ());
		MarkMPT (mpt_iter->TableStart (), mpt_iter->End ());
		++mpt_iter;
	}

	// Hack for startup time.  When MemInit is called, it creates
	// a free block spanning the entire dynamic heap.  However,
	// that's where the current stack happens to be.  We still need
	// access to that, so free it up.

	StackRange	range = EmPalmOS::GetBootStack ();
	MarkTotalAccess (range.fBottom, range.fTop);
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::GetWhatHappened
// ---------------------------------------------------------------------------
//	Some memory access violation was detected.  Nail down more closely what
//	it was.  These checks can be expensive, as they only occur when we're
//	pretty sure we're about to report an error in a dialog.

Errors::EAccessType MetaMemory::GetWhatHappened (emuptr address, long size, Bool forRead)
{
	// If  we've whisked away all memory access checking, return now.

	if (CEnableFullAccess::AccessOK ())
		return Errors::kOKAccess;

	CEnableFullAccess	munge;	// Remove blocks on memory access.

	Errors::EAccessType	whatHappened = Errors::kUnknownAccess;

	// Now figure out what just happened.

	if (MetaMemory::IsLowMemory (address, size))
	{
		whatHappened = Errors::kLowMemAccess;
	}

	else if (MetaMemory::IsSystemGlobal (address, size))
	{
		whatHappened = Errors::kGlobalVarAccess;
	}

	else if (MetaMemory::IsScreenBuffer (address, size))
	{
		whatHappened = Errors::kScreenAccess;
	}

	else if (MetaMemory::IsLowStack (address, size))
	{
		whatHappened = Errors::kLowStackAccess;
	}

#if FOR_LATER
	else if (MetaMemory::IsUninitialized (address, size))
	{
		if (MetaMemory::IsStack (address, size))
		{
			whatHappened = Errors::kUninitializedStack;
		}

		else if (MetaMemory::IsAllocatedChunk (address, size))
		{
			whatHappened = Errors::kUninitializedChunk;
		}
	}
#endif

	else
	{
		Bool	inUIObject, butItsOK;
		CheckUIObjectAccess (address, size, forRead, inUIObject, butItsOK);

		if (inUIObject)
		{
			// We don't really need to do anything else (like return an
			// error or check "butItsOK", since if an error occurred,
			// an error object will be scheduled with the EmSession.

			whatHappened = Errors::kOKAccess;
		}
		else
		{
			WhatHappenedData	info;
			info.result			= Errors::kUnknownAccess;
			info.address		= address;
			info.size			= size;
			info.forRead		= forRead;

			const EmPalmHeap*	heap = EmPalmHeap::GetHeapByID (0);

			if (heap)
				GWH_ExamineHeap (*heap, info);

			if (info.result != Errors::kUnknownAccess)
			{
				whatHappened = info.result;
			}
		}
	}

	whatHappened = AllowForBugs (address, size, forRead, whatHappened);

	return whatHappened;
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::AllowForBugs
// ---------------------------------------------------------------------------

Errors::EAccessType MetaMemory::AllowForBugs (emuptr address, long size, Bool forRead, Errors::EAccessType whatHappened)
{
	if (whatHappened == Errors::kOKAccess)
	{
		return whatHappened;
	}

	if (forRead)
	{
		// Let PrvFindMemoryLeaks have the run of the show.

		if (::InPrvFindMemoryLeaks ())
		{
			return Errors::kOKAccess;
		}

		// SecPrvRandomSeed calls Crc16CalcBlock (NULL, 0x1000, 0).

		emuptr	a6 = gCPU68K->GetRegister (e68KRegID_A6);
		if (::IsEven (a6) && EmPalmOS::IsInStack (a6))
		{
			emuptr	rtnAddr = EmMemGet32 (a6 + 4);

			if (address < 0x1000 &&
				::InCrc16CalcBlock () &&
				::InSecPrvRandomSeed (rtnAddr))
			{
				return Errors::kOKAccess;
			}
		}

		if (whatHappened == Errors::kLowMemAccess)
		{
			// See if the the low-memory checksummer is at work.

			if (size == 4 &&
				::InPrvSystemTimerProc ())
			{
				return Errors::kOKAccess;
			}

			// There's a bug in BackspaceChar (pre-3.2) that accesses the word at 0x0000.

			if (EmPatchState::HasBackspaceCharBug () &&
				address == 0x0000 && size == 2 &&
				InBackspaceChar ())
			{
				return Errors::kOKAccess;
			}

			// There's a bug in FldDelete (pre-3.2) that accesses the word at 0x0000.

			if (EmPatchState::HasFldDeleteBug () &&
				address == 0x0000 && size == 2 &&
				::InFldDelete ())
			{
				return Errors::kOKAccess;
			}

			// There's a bug in GrfProcessStroke (pre-3.1) that accesses the word at 0x0002.

			if (EmPatchState::HasGrfProcessStrokeBug () &&
				address == 0x0002 && size == 2 &&
				::InGrfProcessStroke ())
			{
				return Errors::kOKAccess;
			}

			// There's a bug in NetPrvTaskMain (pre-3.2) that accesses low-memory.

			if (EmPatchState::HasNetPrvTaskMainBug () &&
				::InNetPrvTaskMain ())
			{
				return Errors::kOKAccess;
			}
		}

		//	There's a bug in pre-3.0 versions of SysBinarySearch that cause it to
		//	call the user callback function with a pointer just past the array
		//	to search.

		if (EmPatchState::HasSysBinarySearchBug () &&
			EmPatchState::IsInSysBinarySearch ())
		{
			return Errors::kOKAccess;
		}

		// The Certicom Encryption library snags 20 bytes of data from some
		// unspecified place in RAM to help randomize its keys.  Allow this
		// access.  (Note: the test for the function that performs the access
		// is fragile.  An alternative may be to allow full-memory access
		// while SecLibEncryptBegin is active, which appears to be the only
		// place where the Certicom function is called from.

		if (::In_CerticomMemCpy ())
		{
			return Errors::kOKAccess;
		}

		// dns_decode_name appears to walk off the end of an input buffer.
		// I'm not sure why that happens, yet, but let's allow it for now.

		if (::Indns_decode_name () &&
			whatHappened == Errors::kMemMgrAccess)
		{
			return Errors::kOKAccess;
		}
	}

	if (whatHappened == Errors::kLowMemAccess)
	{
		// Visor replaces the exception vector at 0x0008;
		// allow for that.

		if (size == 4 && address == 0x0008 && (::InHsPrvInit () || ::InHsPrvInitCard ()))
		{
			return Errors::kOKAccess;
		}
	}

	if (whatHappened == Errors::kGlobalVarAccess)
	{
		// Let TSM glue routines (linked with applications) access
		// the TSM global vars.


		if ((address == EmLowMem_AddressOf (tsmFepLibStatusP) ||
			 address == EmLowMem_AddressOf (tsmFepLibRefNum)) &&
			 ::InTsmGlueGetFepGlobals ())
		{
			return Errors::kOKAccess;
		}

		// Let locale modules access the Intl Mgr global pointer.
		
		if ((address == EmLowMem_AddressOf (intlMgrGlobalsP)) &&
			(::InPrvGetIntlMgrGlobalsP() ||
			 ::InPrvSetIntlMgrGlobalsP()))
		{
			return Errors::kOKAccess;
		}

		// Always allow access to this for our Test Harness.

		if (address == EmLowMem_AddressOf (testHarnessGlobalsP))
		{
			return Errors::kOKAccess;
		}
	}

	return whatHappened;
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::GetLowMemoryBegin
// ---------------------------------------------------------------------------

emuptr MetaMemory::GetLowMemoryBegin (void)
{
	return 0;
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::GetLowMemoryEnd
// ---------------------------------------------------------------------------

emuptr MetaMemory::GetLowMemoryEnd (void)
{
	return offsetof (LowMemHdrType, globals);
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::GetSysGlobalsBegin
// ---------------------------------------------------------------------------

emuptr MetaMemory::GetSysGlobalsBegin (void)
{
	return offsetof (LowMemHdrType, globals);
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::GetSysGlobalsEnd
// ---------------------------------------------------------------------------

emuptr MetaMemory::GetSysGlobalsEnd (void)
{
	CEnableFullAccess	munge;	// Remove blocks on memory access.

	return EmLowMem_GetGlobal (sysDispatchTableP) + 
			EmLowMem_GetGlobal (sysDispatchTableSize) * (sizeof (void*));
}
// ---------------------------------------------------------------------------
//		¥ MetaMemory::GetHeapHdrBegin
// ---------------------------------------------------------------------------

emuptr MetaMemory::GetHeapHdrBegin (UInt16 heapID)
{
	const EmPalmHeap*	heap = EmPalmHeap::GetHeapByID (heapID);
	if (!heap)
		return EmMemNULL;

	return heap->HeaderStart ();
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::GetHeapHdrEnd
// ---------------------------------------------------------------------------

emuptr MetaMemory::GetHeapHdrEnd (UInt16 heapID)
{
	const EmPalmHeap*	heap = EmPalmHeap::GetHeapByID (heapID);
	if (!heap)
		return EmMemNULL;

	return heap->HeaderEnd ();
}


Bool MetaMemory::IsLowMemory (emuptr testAddress, uint32 size)
{
	return testAddress >= GetLowMemoryBegin () && testAddress + size <= GetLowMemoryEnd ();
}


Bool MetaMemory::IsSystemGlobal (emuptr testAddress, uint32 size)
{
	return testAddress >= GetSysGlobalsBegin () && testAddress + size <= GetSysGlobalsEnd ();
}


Bool MetaMemory::IsScreenBuffer (emuptr testAddress, uint32 size)
{
	return IsScreenBuffer (EmMemGetMetaAddress (testAddress), size);
}


Bool MetaMemory::IsMemMgrData (emuptr testAddress, uint32 size)
{
	const EmPalmHeap*	heap = EmPalmHeap::GetHeapByPtr (testAddress);
	
	if (heap)
	{
		ITERATE_CHUNKS (*heap, iter, end)
		{
			if ((iter->HeaderContains (testAddress) &&
				iter->HeaderContains (testAddress + size)) ||
				(iter->TrailerContains (testAddress) &&
				iter->TrailerContains (testAddress + size)))
			{
				return true;
			}

			++iter;
		}
	}
	
	return false;
}


Bool MetaMemory::IsUnlockedChunk (emuptr testAddress, uint32 size)
{
	const EmPalmHeap*	heap = EmPalmHeap::GetHeapByPtr (testAddress);
	
	if (heap)
	{
		ITERATE_CHUNKS (*heap, iter, end)
		{
			if (iter->BodyContains (testAddress) &&
				iter->BodyContains (testAddress + size) &&
				iter->LockCount () == 0)
			{
				return true;
			}

			++iter;
		}
	}
	
	return false;
}


Bool MetaMemory::IsFreeChunk (emuptr testAddress, uint32 size)
{
	const EmPalmHeap*	heap = EmPalmHeap::GetHeapByPtr (testAddress);
	
	if (heap)
	{
		ITERATE_CHUNKS (*heap, iter, end)
		{
			if (iter->BodyContains (testAddress) &&
				iter->BodyContains (testAddress + size) &&
				iter->Free () == 0)
			{
				return true;
			}

			++iter;
		}
	}
	
	return false;
}


Bool MetaMemory::IsUninitialized (emuptr testAddress, uint32 size)
{
#if FOR_LATER
	return (fgMetaMemory [MASK(testAddress)] & kUninitialized) != 0;
#else
	UNUSED_PARAM(testAddress)
	UNUSED_PARAM(size)

	return false;
#endif
}


Bool MetaMemory::IsStack (emuptr testAddress, uint32 size)
{
	UNUSED_PARAM(testAddress)
	UNUSED_PARAM(size)

	return false;
}


Bool MetaMemory::IsLowStack (emuptr testAddress, uint32 size)
{
	UNUSED_PARAM(testAddress)
	UNUSED_PARAM(size)

	return false;
}


Bool MetaMemory::IsAllocatedChunk (emuptr testAddress, uint32 size)
{
	return !IsFreeChunk (testAddress, size);
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::MarkRange
// ---------------------------------------------------------------------------

void MetaMemory::MarkRange (emuptr start, emuptr end, uint8 v)
{
	// If there's no meta-memory (not needed for dedicated framebuffers)
	// just leave.

	if (EmMemGetBank(start).xlatemetaaddr == NULL)
		return;

	// If the beginning and end of the buffer are not in the same address
	// space, just leave.  This can happen while initializing the Dragonball's
	// LCD -- for a while, the LCD framebuffer range falls off the end
	// of the dynamic heap.

	if (start >= 0 && start < 0 + gRAMBank_Size
		&& end >= 0 + gRAMBank_Size)
	{
		end = gRAMBank_Size - 1;
	}

	if (start >= gMemoryStart && start < gMemoryStart + gRAMBank_Size
		&& end >= gMemoryStart + gRAMBank_Size)
	{
		end = gMemoryStart + gRAMBank_Size - 1;
	}

	uint8*	startP	= EmMemGetMetaAddress (start);
	uint8*	endP	= startP + (end - start);	// EmMemGetMetaAddress (end);
	uint8*	end4P	= (uint8*) (((uint32) endP) & ~3);
	uint8*	p		= startP;

	EmAssert (end >= start);
	EmAssert (endP >= startP);
	EmAssert (endP - startP == (ptrdiff_t) (end - start));

#if 1
	// Optimization: if there are no middle longs to fill, just
	// do everything a byte at a time.

	if (end - start < 12)
	{
		while (p < endP)
		{
			*p++ &= v;
		}
	}
	else
	{
		uint32	longValue = v;
		longValue |= (longValue << 8);
		longValue |= (longValue << 16);

		while (((uint32) p) & 3)		// while there are leading bytes
		{
			*p++ |= v;
		}

		while (p < end4P)				// while there are middle longs
		{
			*(uint32*) p |= longValue;
			p += sizeof (uint32);
		}

		while (p < endP)				// while there are trailing bytes
		{
			*p++ |= v;
		}
	}
#else
	for (p = startP; p < endP; ++p)
	{
		*p |= v;
	}
#endif
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::UnmarkRange
// ---------------------------------------------------------------------------

void MetaMemory::UnmarkRange (emuptr start, emuptr end, uint8 v)
{
	// If there's no meta-memory (not needed for dedicated framebuffers)
	// just leave.

	if (EmMemGetBank(start).xlatemetaaddr == NULL)
		return;

	// If the beginning and end of the buffer are not in the same address
	// space, just leave.  This can happen while initializing the Dragonball's
	// LCD -- for a while, the LCD framebuffer range falls off the end
	// of the dynamic heap.

	if (start >= 0 && start < 0 + gRAMBank_Size
		&& end >= 0 + gRAMBank_Size)
	{
		end = gRAMBank_Size - 1;
	}

	if (start >= gMemoryStart && start < gMemoryStart + gRAMBank_Size
		&& end >= gMemoryStart + gRAMBank_Size)
	{
		end = gMemoryStart + gRAMBank_Size - 1;
	}

	uint8*	startP	= EmMemGetMetaAddress (start);
	uint8*	endP	= startP + (end - start);	// EmMemGetMetaAddress (end);
	uint8*	end4P	= (uint8*) (((uint32) endP) & ~3);
	uint8*	p		= startP;

	EmAssert (end >= start);
	EmAssert (endP >= startP);
	EmAssert (endP - startP == (ptrdiff_t) (end - start));

	v = ~v;

#if 1
	// Optimization: if there are no middle longs to fill, just
	// do everything a byte at a time.

	if (end - start < 12)
	{
		while (p < endP)
		{
			*p++ &= v;
		}
	}
	else
	{
		uint32	longValue = v;
		longValue |= (longValue << 8);
		longValue |= (longValue << 16);

		while (((uint32) p) & 3)		// while there are leading bytes
		{
			*p++ &= v;
		}

		while (p < end4P)				// while there are middle longs
		{
			*(uint32*) p &= longValue;
			p += sizeof (uint32);
		}

		while (p < endP)				// while there are trailing bytes
		{
			*p++ &= v;
		}
	}
#else
	for (p = startP; p < endP; ++p)
	{
		*p &= v;
	}
#endif
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::MarkUnmarkRange
// ---------------------------------------------------------------------------

void MetaMemory::MarkUnmarkRange (emuptr start, emuptr end,
							uint8 andValue, uint8 orValue)
{
	// If there's no meta-memory (not needed for dedicated framebuffers)
	// just leave.

	if (EmMemGetBank(start).xlatemetaaddr == NULL)
		return;

	// If the beginning and end of the buffer are not in the same address
	// space, just leave.  This can happen while initializing the Dragonball's
	// LCD -- for a while, the LCD framebuffer range falls off the end
	// of the dynamic heap.

	if (start >= 0 && start < 0 + gRAMBank_Size
		&& end >= 0 + gRAMBank_Size)
	{
		end = gRAMBank_Size - 1;
	}

	if (start >= gMemoryStart && start < gMemoryStart + gRAMBank_Size
		&& end >= gMemoryStart + gRAMBank_Size)
	{
		end = gMemoryStart + gRAMBank_Size - 1;
	}

	uint8*	startP	= EmMemGetMetaAddress (start);
	uint8*	endP	= startP + (end - start);	// EmMemGetMetaAddress (end);
	uint8*	end4P	= (uint8*) (((uint32) endP) & ~3);
	uint8*	p		= startP;

	EmAssert (end >= start);
	EmAssert (endP >= startP);
	EmAssert (endP - startP == (ptrdiff_t) (end - start));

	if (andValue == 0xFF)
	{
		while (p < endP)
		{
			*p++ |= orValue;
		}
	}
	else if (orValue == 0x00)
	{
		while (p < endP)
		{
			*p++ &= andValue;
		}
	}
	else
	{
#if 1
		// Optimization: if there are no middle longs to fill, just
		// do everything a byte at a time.

		if (end - start < 12)
		{
			while (p < endP)				// while there are trailing bytes
			{
				*p = (*p & andValue) | orValue;
				p += sizeof (char);
			}
		}
		else
		{
			uint32	longAnd = andValue;
			longAnd |= (longAnd << 8);
			longAnd |= (longAnd << 16);

			uint32	longOr = orValue;
			longOr |= (longOr << 8);
			longOr |= (longOr << 16);

			while (((uint32) p) & 3)		// while there are leading bytes
			{
				*p = (*p & andValue) | orValue;
				p += sizeof (char);
			}

			while (p < end4P)				// while there are middle longs
			{
				*(uint32*) p = ((*(uint32*) p) & longAnd) | longOr;
				p += sizeof (long);
			}

			while (p < endP)				// while there are trailing bytes
			{
				*p = (*p & andValue) | orValue;
				p += sizeof (char);
			}
		}
#else
		for (p = startP; p < endP; ++p)
		{
			*p = (*p & andValue) | orValue;
		}
#endif
	}
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::WhatHappenedCallback
// ---------------------------------------------------------------------------
//	Check to see if there was an access to memory manager data, an unlocked
//	block, or a free block.

void MetaMemory::GWH_ExamineHeap (	const EmPalmHeap& heap,
									WhatHappenedData& info)
{
	// Bail out if the address to test is not even in this heap.

	if (!heap.Contains (info.address))
	{
		return;
	}

	// See if we touched a memory manager structure.
	// Let's start with the headers.

	// Is it in the heap header?

	if (heap.HeaderContains (info.address))
	{
		info.result = Errors::kMemMgrAccess;
		return;
	}

	// Is it in any of the master pointer tables?

	{
		ITERATE_MPTS(heap, iter, end)
		{
			if (iter->Contains (info.address))
			{
				info.result = Errors::kMemMgrAccess;
				return;
			}

			++iter;
		}
	}

	// Check against all of the memory manager chunks.

	{
		ITERATE_CHUNKS (heap, iter, end)
		{
			GWH_ExamineChunk (*iter, info);
			if (info.result != Errors::kUnknownAccess)
				return;

			++iter;
		}
	}
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::GWH_ExamineChunk
// ---------------------------------------------------------------------------
//	Check to see if there was an access to memory manager data, an unlocked
//	block, or a free block.

void MetaMemory::GWH_ExamineChunk (	const EmPalmChunk& chunk,
									WhatHappenedData& info)
{
	emuptr	addrStart	= info.address;
	emuptr	addrEnd		= info.address + info.size;

	// Sort out some ranges we'll be comparing against.

	emuptr	hdrStart	= chunk.HeaderStart ();
	emuptr	bodyStart	= chunk.BodyStart ();
	emuptr	trlStart	= chunk.BodyEnd ();
	emuptr	chunkEnd	= chunk.End ();

	/*
		A note on the comparison below (I had to draw this on the whiteboard
		before I could figure it out).  I need to see if one range of memory
		(the test address, extending for 1, 2, or 4 byte) overlaps another
		range of memory (the chunk header, the chunk body, etc.).  I started
		by drawing the second range as follows:

			+---------+---------+---------+
			|    A    |    B    |    C    |
			+---------+---------+---------+

		"B" is the range I'm interested in testing against, "A" is everything
		before it, and "C" is everything after it.

		The range of memory I want to test to see if it overlaps can be thought
		of as starting in region A, B, or C, and ending in A, B, or C.  We can
		identify all possible ranges by labelling each range "xy", where x is
		the starting section and y is the ending section.  Thus, all the possible
		ranges are AA, AB, AC, BB, BC, and CC.  From inspection, we can see that
		only segments AA and CC don't overlap B in any way.  Looking at it
		another way, any segment ending in A or starting in C will not overlap
		B.  All other ranges will.
	*/

	// See if we hit this chunk at all.  If not, leave.

	if (addrEnd > hdrStart && addrStart < chunkEnd)
	{
		// See if the access was to the body of the block.

		if (addrEnd > bodyStart && addrStart < trlStart)
		{
			// See if this is a free (unallocated) block.

			if (chunk.Free ())
			{
				info.result = Errors::kFreeChunkAccess;
			}

			// See if this is an unlocked block.

			else if (chunk.LockCount () == 0)
			{
				info.result = Errors::kUnlockedChunkAccess;
			}
		}

		// See if the access was to the chunk header.

		if (addrEnd > hdrStart && addrStart < bodyStart)
		{
			info.result = Errors::kMemMgrAccess;
		}

		// See if the access was to the chunk trailer.

		if (addrEnd > trlStart && addrStart < chunkEnd)
		{
			info.result = Errors::kMemMgrAccess;
		}


		// ============================== ALLOW FOR BUGS ==============================

		// Allow the screen driver some liberty.  Some BitBlt functions get a running
		// start or come to a skidding halt before or after an allocated chunk.  They
		// read these two bytes, but the logic is such that those bits get masked out
		// or shifted away.

		if (info.result == Errors::kMemMgrAccess &&
			info.forRead &&
		//	info.size == sizeof (UInt16) &&	// Can be 1-byte access in cases
			(::InPrvCompressedInnerBitBlt () ||
			 ::InPrvMisAlignedForwardInnerBitBlt () ||
			 ::InPrvMisAlignedBackwardInnerBitBlt ()))
		{
			goto HideBug;
		}


		if (EmPatchState::HasConvertDepth1To2BWBug () &&
			info.result == Errors::kMemMgrAccess &&
			info.forRead &&
			info.size == sizeof (UInt8) &&
			::InPrvConvertDepth1To2BW ())
		{
			goto HideBug;
		}


		// Similarly, allow NetLibBitMove some liberty.  It will occassionally
		// scoot off the end of the source buffer, but making sure that it
		// masks off the data that it reads.

		if (info.result == Errors::kMemMgrAccess &&
			info.forRead &&
			info.size == sizeof (UInt8) &&
			::InNetLibBitMove ())
		{
			goto HideBug;
		}


		// There's a bug in MenuHandleEvent (pre-3.1 only) that causes it to read a
		// random long (actually, the random location is the result of using a -1 to index
		// into a menu array).

		if (EmPatchState::HasMenuHandleEventBug () &&
			info.forRead &&
			info.size == sizeof (WinHandle) &&	// MenuPullDownType.menuWin
			::InMenuHandleEvent ())
		{
			goto HideBug;
		}


		// There's a bug in NetPrvSettingSet that causes it to read 0x020C bytes
		// from the beginning of its globals buffer when that buffer is only 8 bytes long.

		if (EmPatchState::HasNetPrvSettingSetBug () &&
			info.forRead &&
			info.size == 4 &&
			::InNetPrvSettingSet ())
		{
			goto HideBug;
		}


		// SysAppExit deletes the block of memory containing the current task's stack
		// and TCB before the task has been deleted.  When SysTaskDelete is called,
		// there are many accesses to both the stack (as functions are called) and
		// the TCB (as tasks are scheduled and as the task to be deleted is finally
		// deleted).
		//
		// We need to detect when any of these SysTaskDelete accesses occurs and
		// allow them.  One hueristic that gets most of them is to see if there
		// are any TCBs with a pointer into the deleted memory chunk.  That will
		// work up until the point the TCB is marked as deleted.  This marking
		// occurs in the AMX function cj_kptkdelete.  At that point, we can just
		// check to see if the access occurred in that function and allow it.

		if (info.result == Errors::kFreeChunkAccess &&
			EmPatchState::HasDeletedStackBug ())
		{
			// First see if there is an active TCB with a stack pointer
			// pointing into this deleted memory chunk.

			SysKernelInfoType	taskInfo;

			taskInfo.selector	= sysKernelInfoSelTaskInfo;
			taskInfo.id			= 0;	// Ask for the first task

			// Get the first task.  Remember the task IDs so that we can
			// detect when we've looped through them all.  Remembering *all*
			// the IDs (instead of just the first one) is necessary in case
			// we're called with the linked list of TCBs is inconsistent
			// (that is, it's in the process of being updated -- when that's
			// happening, we may find a loop that doesn't necessarily involve
			// the first TCB).

			vector<UInt32>	taskIDList;
			Err				err = SysKernelInfo (&taskInfo);

			while (err == 0)
			{
				// See if we've seen this task ID before.  If so, leave.

				vector<UInt32>::iterator	iter = taskIDList.begin ();
				while (iter != taskIDList.end ())
				{
					if (*iter++ == taskInfo.param.task.id)
					{
						goto PlanB;	// I'd really like a break(2) here... :-)
					}
				}

				// We haven't looked at this task before; check the stack.
				// Check against "stackStart" instead of stackP, as the
				// latter sometimes contains values outside of the current
				// stack range (such as the faux stacks we set up when
				// doing ATrap calls).

				if (taskInfo.param.task.stackStart >= bodyStart &&
					taskInfo.param.task.stackStart < trlStart)
				{
					goto HideBug;
				}

				// Save this task ID so we can see if we've visited this
				// record before.

				taskIDList.push_back (taskInfo.param.task.id);

				// Get the next TCB.

				taskInfo.selector	= sysKernelInfoSelTaskInfo;
				taskInfo.id			= taskInfo.param.task.nextID;
				err					= SysKernelInfo (&taskInfo);
			}

			// Plan B...
PlanB:
			// If there is no TCB pointing into the deleted chunk, see if the current
			// function is cj_kptkdelete.  If not, see if it looks like we're in a
			// function called by cj_kptkdelete.

			if (	gCPU->GetSP () >= bodyStart &&
					gCPU->GetSP () < trlStart)
			{
				// See if we're currently in cj_kptkdelete.

				if (::Incj_kptkdelete ())
				{
					info.result = Errors::kOKAccess;
				}

				// If not, see if it's in the current call chain.  Normally (!)
				// I'd walk the a6 stack frame links, but there's a lot of
				// assembly stuff going on here, and not all of them set up
				// stack frames.  a6 *should* point to a valid stack frame
				// somewhere up the line, but it may be cj_kptkdelete's
				// stack frame, resulting in our skipping over it.
				//
				// It's important that gcj_kptkdelete.InRange() has returned
				// true at least once before entering this section of code.
				// That's because if it hasn't, the cached range of the
				// function will be empty, causing InRange to look for the
				// beginning and ending of the function containing the address
				// passed to it.  Since we're passing random contents of the
				// stack, it's very unlikely that there is a function range
				// corresponding to the values passed to InRange, sending it
				// on wild goose chases.  Fortunately, "Plan B" goes into effect
				// only after the TCB has been marked as deleted, which occurs
				// in cj_kptkdelete.  The very next thing cj_kptkdelete does is
				// push a parameter on the stack, causing us to get here while
				// the PC is in cj_kptkdelete.  This will cause the call to InRange
				// immediately above to return true, satisfying the precondition
				// we need here.

				else
				{
					// Get the current stack pointer and use it to iterate
					// over the contents of the stack.  We examine every
					// longword on every even boundary to see if it looks
					// like a return address into cj_kptkdelete.

					emuptr	a7 = gCPU->GetSP ();

					while (a7 >= bodyStart && a7 < trlStart)
					{
						if (::Incj_kptkdelete (EmMemGet32 (a7)))
						{
							goto HideBug;
						}

						a7 += 2;
					}
				}	// end: checking the stack for cj_kptkdelete
			}	// end: A7 is in the deleted chunk
		}	// end: accessed a deleted chunk


		// There's a bug in FindShowResults (pre-3.0) that accesses
		// a byte in an unlocked block.

		if (info.result == Errors::kUnlockedChunkAccess &&
			EmPatchState::HasFindShowResultsBug () &&
			info.forRead &&
			info.size == sizeof (Boolean) &&
			addrStart == bodyStart + sizeof (UInt16) * 2 /*offsetof (FindParamsType, more)*/ &&
			::InFindShowResults ())
		{
			goto HideBug;
		}


		// There's a bug in FindSaveFindStr that causes it to possibly read
		// off the end of the source handle.  The invalid access will be
		// generated in MemMove, which is called by DmWrite, which is called
		// by FindSaveFindStr.  So look up the stack a bit to see who's calling us.

		emuptr	a6_0 = gCPU68K->GetRegister (e68KRegID_A6);	// MemMove's A6 (points to caller's A6 and return address to caller)
		if (::IsEven (a6_0) && EmPalmOS::IsInStack (a6_0))
		{
			emuptr	a6_1 = EmMemGet32 (a6_0);				// DmWrite's (points to caller's A6 and return address to caller)

			if (EmPatchState::HasFindSaveFindStrBug () &&
				info.forRead &&
				::InMemMove () &&								// See if we're in MemMove
				::InDmWrite (EmMemGet32 (a6_0 + 4)) &&			// See if DmWrite is MemMove's caller
				::InFindSaveFindStr (EmMemGet32 (a6_1 + 4)))	// See if FindSaveFindStr is DmWrite's caller
			{
				goto HideBug;
			}
		}

		// There's a bug in FntDefineFont that causes it to possibly read
		// off the end of the source handle.  The invalid access will be
		// generated in MemMove, which is called by FntDefineFont.  So look
		// up the stack a bit to see who's calling us.

		if (EmPatchState::HasFntDefineFontBug () &&
			info.forRead &&
			::InMemMove () &&							// See if we're in MemMove
			::InFntDefineFont (EmMemGet32 (a6_0 + 4)))	// See if FntDefineFont is MemMove's caller
		{
			goto HideBug;
		}
	}

	return;

HideBug:
	info.result = Errors::kOKAccess;
}


#pragma mark -

// ---------------------------------------------------------------------------
//		¥ CheckUIObjectAccess
// ---------------------------------------------------------------------------

#define WindowFlagsType_format			0x8000	// window format:  0=screen mode; 1=generic mode
#define WindowFlagsType_offscreen		0x4000	// offscreen flag: 0=onscreen ; 1=offscreen
#define WindowFlagsType_modal			0x2000	// modal flag:     0=modeless window; 1=modal window
#define WindowFlagsType_focusable		0x1000	// focusable flag: 0=non-focusable; 1=focusable
#define WindowFlagsType_enabled			0x0800	// enabled flag:   0=disabled; 1=enabled
#define WindowFlagsType_visible			0x0400	// visible flag:   0-invisible; 1=visible
#define WindowFlagsType_dialog			0x0200	// dialog flag:    0=non-dialog; 1=dialog
#define WindowFlagsType_freeBitmap		0x0100	// free bitmap w/window: 0=don't free, 1=free

#define FormAttrType_usable				0x8000	// Set if part of ui 
#define FormAttrType_enabled			0x4000	// Set if interactable (not grayed out)
#define FormAttrType_visible			0x2000	// Set if drawn, used internally
#define FormAttrType_dirty				0x1000	// Set if dialog has been modified
#define FormAttrType_saveBehind			0x0800	// Set if bits behind form are save when form ids drawn
#define FormAttrType_graffitiShift		0x0400	// Set if graffiti shift indicator is supported
#define FormAttrType_globalsAvailable	0x0200	// Set by Palm OS if globals are available for the form event handler
#define FormAttrType_doingDialog		0x0100	// FrmDoDialog is using for nested event loop
#define FormAttrType_exitDialog			0x0080	// tells FrmDoDialog to bail out and stop using this form

#define ControlAttrType_usable			0x8000	// set if part of ui 
#define ControlAttrType_enabled			0x4000	// set if interactable (not grayed out)
#define ControlAttrType_visible			0x2000	// set if drawn (set internally)
#define ControlAttrType_on				0x1000	// set if on (checked)
#define ControlAttrType_leftAnchor		0x0800	// set if bounds expand to the right, clear if bounds expand to the left
#define ControlAttrType_frame			0x0700
#define ControlAttrType_drawnAsSelected	0x0080	// support for old-style graphic controls where control overlaps a bitmap
#define ControlAttrType_graphical		0x0040	// set if images are used instead of text
#define ControlAttrType_vertical		0x0020	// true for vertical sliders

// Here are some symbols to search for when looking for more things
// to which to prohibit access:
//
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_CLIPBOARDS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_CONTROLS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_FIELDS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_FINDPARAMS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_FORMS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_LISTS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_MENUS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_PROGRESS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_SCROLLBARS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_TABLES
//	
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_BITMAPS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_FONTS
//	#define ALLOW_ACCESS_TO_INTERNALS_OF_WINDOWS

/*
	AccessorGlueTrapsAvailable	TRUE if sysFtrNumROMVersion indicates 4.0 or later
	AccessorGlueEmu68KAccAvail	TRUE if sysFtrNumAccessorTrapPresent feature exists and is non-zero

	The following functions access the following fields directly, as of
	SDK 4.0 Update 1 (DR1):

	Glue function				Field accessed				Under this condition
	---------------------------	---------------------------	--------------------
	TblGlueGetNumberOfColumns	tableP->numColumns			!AccessorGlueTrapsAvailable

	TblGlueGetTopRow			tableP->topRow				!AccessorGlueTrapsAvailable

	TblGlueSetSelection			tableP->numColumns			!AccessorGlueTrapsAvailable
								tableP->numRows
								tableP->attr.visible
								tableP->rowAttrs
								tableP->attr.selected
								tableP->currentRow
								tableP->currentColumn

	TblGlueGetColumnMasked		tableP->numColumns			!AccessorGlueEmu68KAccAvail
								tableP->columnAttrs

	BmpGlueGetDimensions		bitmapP->width				!AccessorGlueTrapsAvailable
								bitmapP->height
								bitmapP->rowBytes

	BmpGlueGetBitDepth			bitmapP->version			!AccessorGlueTrapsAvailable
								bitmapP->pixelSize

	BmpGlueGetNextBitmap		bitmapP->version			!AccessorGlueTrapsAvailable
								bitmapP->nextDepthOffset

	BmpGlueGetTransparentValue	bitmapP->version			!AccessorGlueEmu68KAccAvail
								bitmapP->flags.hasTransparency
								((BitmapTypeV2*)bitmapP)->transparentValue
								bitmapP->transparentIndex

	BmpGlueSetTransparentValue	bitmapP->flags.forScreen	!AccessorGlueEmu68KAccAvail
								bitmapP->version
								bitmapP->pixelSize
								bitmapP->transparentIndex
								bitmapP->flags.hasTransparency

	BmpGlueGetCompressionType	bitmapP->flags.compressed	!AccessorGlueEmu68KAccAvail
								bitmapP->version
								bitmapP->compressionType

	CtlGlueGetControlStyle		ctlP->style					!AccessorGlueEmu68KAccAvail

	CtlGlueGetFont				ctlP->font					!AccessorGlueEmu68KAccAvail

	CtlGlueSetFont				ctlP->font					!AccessorGlueEmu68KAccAvail

	CtlGlueGetGraphics			ctlP->attr.graphical		!AccessorGlueEmu68KAccAvail
								gctlP->bitmapID
								gctlP->selectedBitmapID

	CtlGlueNewSliderControl		sctlP->attr.graphical		!AccessorGlueEmu68KAccAvail

	CtlGlueSetLeftAnchor		ctlP->attr.leftAnchor		!AccessorGlueEmu68KAccAvail

	FldGlueGetLineInfo			fldP->lines					!AccessorGlueEmu68KAccAvail

	FrmGlueGetObjectUsable		obj.control->attr.usable	!AccessorGlueEmu68KAccAvail
								obj.list->attr.usable
								obj.bitmap->attr.usable
								obj.label->attr.usable
								obj.gadget->attr.usable
								obj.scrollBar->attr.usable
								obj.table->attr.usable		AccessorGlueTrapsAvailable

	FrmGlueGetLabelFont			formLabelP->fontID			!AccessorGlueEmu68KAccAvail

	FrmGlueSetLabelFont			formLabelP->fontID			!AccessorGlueEmu68KAccAvail

	FrmGlueGetDefaultButtonID	formP->defaultButton		!AccessorGlueEmu68KAccAvail

	FrmGlueSetDefaultButtonID	formP->defaultButton		!AccessorGlueEmu68KAccAvail

	FrmGlueGetHelpID			formP->helpRscId			!AccessorGlueEmu68KAccAvail

	FrmGlueSetHelpID			formP->helpRscId			!AccessorGlueEmu68KAccAvail

	FrmGlueGetMenuBarID			formP->menuRscId			!AccessorGlueEmu68KAccAvail

	FrmGlueGetEventHandler		formP->handler				!AccessorGlueEmu68KAccAvail

	LstGlueGetFont				listP->font					!AccessorGlueEmu68KAccAvail

	LstGlueGetTopItem			listP->topItem				!AccessorGlueTrapsAvailable

	LstGlueSetFont				listP->font					!AccessorGlueEmu68KAccAvail

	LstGlueGetItemsText			listP->itemsText			!AccessorGlueEmu68KAccAvail

	LstGlueSetIncrementalSearch	listP->attr.search			!AccessorGlueEmu68KAccAvail

	WinGlueGetFrameType			winP->frameType.word		!AccessorGlueEmu68KAccAvail

	WinGlueSetFrameType			winP->frameType.word		!AccessorGlueEmu68KAccAvail
*/
// ---------------------------------------------------------------------------
//		¥ PrvTrapsAvailable
// ---------------------------------------------------------------------------

static Bool PrvTrapsAvailable (void)
{
	// If the OS is 4.0 or later, the API should be used.

	Bool	result = EmPatchState::OSMajorVersion () >= 4;

	return result;
}


// ---------------------------------------------------------------------------
//		¥ PrvAccessorTrapAvailable
// ---------------------------------------------------------------------------

static Bool PrvAccessorTrapAvailable (void)
{
	// Magic Accessor Trap is available.  Defined but not implemented
	// in 4.0, but magically implemented in the Timulator.

	#ifndef sysFtrNumAccessorTrapPresent
	#define	sysFtrNumAccessorTrapPresent	25	// If accessor trap exists (PalmOS 4.0)
	#endif

	UInt32	value;
	Bool	result = (FtrGet (sysFtrCreator, sysFtrNumAccessorTrapPresent, &value) == errNone) && (value != 0);

	return result;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFieldObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFieldObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	/*
		FieldType
			UInt16					id;					// FrmGetObjectId
			RectangleType			rect;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition, FldGetBounds, FldSetBounds
			FieldAttrType			attr;				// FldGetAttributes, FldSetAttributes
										usable			// FrmShowObject, FrmHideObject, FldSetUsable
										visible
										editable
										singleLine
										hasFocus
										dynamicSize
										insPtVisible
										dirty			// FldSetDirty
										underlined
										justification
										autoShift
										hasScrollBar
										numeric
			Char*					text;				// FldGetTextPtr, FldSetTextPtr, FldSetText
			MemHandle				textHandle;			// FldGetTextHandle, FldSetTextHandle, FldSetText
			LineInfoPtr				lines;				// (FldGetScrollPosition, FldSetScrollPosition, FldGetTextHeight, FldGetVisibleLines)
			UInt16					textLen;			// FldGetTextLength, FldSetText
			UInt16					textBlockSize;		// FldGetTextAllocatedSize, FldSetTextAllocatedSize
			UInt16					maxChars;			// FldGetMaxChars, FldSetMaxChars
			UInt16					selFirstPos;		// FldGetSelection, FldSetSelection
			UInt16					selLastPos;			// FldGetSelection, FldSetSelection
			UInt16					insPtXPos;			// FldGetInsPtPosition, FldSetInsPtPosition, FldSetInsertionPoint
			UInt16					insPtYPos;			// FldGetInsPtPosition, FldSetInsPtPosition, FldSetInsertionPoint
			FontID					fontID;				// FldGetFont, FldSetFont
			UInt8					maxVisibleLines;	// FldSetMaxVisibleLines
	*/

	// Allow read access to "lines" if Emu68KAccessorTrapAvailable / AccFldGetLineInfo
	// not available -- FldGlueGetLineInfo needs access to it.

	if (forRead)
	{
		size_t			offset			= address - objectP;
		const size_t	lines_offset	= EmAliasFieldType<PAS>::offsetof_lines ();
		const size_t	lines_size		= EmAliasemuptr<PAS>::GetSize ();

		if (offset >= lines_offset && offset < lines_offset + lines_size)
		{
			return true;
		}
	}

	// Allow read/write access to "attr" before Palm OS 3.3.  Catherine
	// says there's a bug before those versions they need to workaround.

//	if (forRead)
	{
		size_t			offset		= address - objectP;
		const size_t	attr_offset	= EmAliasFieldType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasFieldAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			if (EmPatchState::OSMajorMinorVersion () < 33)
			{
				return true;
			}
		}
	}

	// Don't allow access to any other fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedControlObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedControlObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	/*
		ControlType
			UInt16					id;					// FrmGetObjectId
			RectangleType			bounds;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition
			Char*					text;
			ControlAttrType			attr;
										usable			// FrmShowObject, FrmHideObject, CtlSetUsable
										enabled
										visible
										on				// FrmGetControlValue, CtlGetValue, FrmSetControlValue, CtlSetValue
										leftAnchor
										frame
										drawnAsSelected
										graphical
										vertical
										reserved
			ControlStyleType		style;
			FontID					font;
			UInt8					group;				// FrmGetControlGroupSelection
			UInt8 					reserved;

		GraphicControlType
			UInt16					id;					// FrmGetObjectId
			RectangleType			bounds;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition
			DmResID					bitmapID;
			DmResID					selectedBitmapID;
			ControlAttrType			attr;
			ControlStyleType		style;
			FontID					unused;
			UInt8					group;
			UInt8 					reserved;

		SliderControlType
			UInt16					id;					// FrmGetObjectId
			RectangleType			bounds;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition
			DmResID					thumbID;
			DmResID					backgroundID;
			ControlAttrType			attr;
			ControlStyleType		style;
			UInt8					reserved;		
			Int16					minValue;
			Int16					maxValue;
			Int16					pageSize;
			Int16					value;				// FrmGetControlValue, CtlGetValue, FrmSetControlValue, CtlSetValue
			MemPtr					activeSliderP;
	*/

	// Allow read access to "attr" and "style" if Emu68KAccessorTrapAvailable / AccFrmGetObjectUsable
	// not available -- FrmGlueGetObjectUsable and CtlGlueGetControlStyle need access to them.
	//
	// Allow read access to "attr.graphical", bitmapID, and selectedBitmapID fields
	// for CtlGlueGetGraphics.

	if (forRead)
	{
		size_t			offset		= address - objectP;

		const size_t	attr_offset	= EmAliasControlType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasControlAttrType<PAS>::GetSize ();

		const size_t	style_offset= EmAliasControlType<PAS>::offsetof_style ();
		const size_t	style_size	= EmAliasUInt8<PAS>::GetSize ();

		if ((offset >= attr_offset && offset < attr_offset + attr_size) ||
			(offset >= style_offset && offset < style_offset + style_size))
		{
			return true;
		}

		EmAliasGraphicControlType<PAS>	control (objectP);
		if (((Int16) control.attr.flags) & ControlAttrType_graphical)
		{
			const size_t	bitmapID_offset			= EmAliasGraphicControlType<PAS>::offsetof_bitmapID ();
			const size_t	bitmapID_size			= EmAliasDmResID<PAS>::GetSize ();

			const size_t	selectedBitmapID_offset	= EmAliasGraphicControlType<PAS>::offsetof_selectedBitmapID ();
			const size_t	selectedBitmapID_size	= EmAliasDmResID<PAS>::GetSize ();

			if ((offset >= bitmapID_offset && offset < bitmapID_offset + bitmapID_size) ||
				(offset >= selectedBitmapID_offset && offset < selectedBitmapID_offset + selectedBitmapID_size))
			{
				return true;
			}
		}
	}

	// Allow read/write access to "font" field for CtlGlueGetFont / CtlGlueSetFont.
	//
	// Allow read/write access to "attr.graphical" and "attr.leftAnchor" fields
	// for CtlGlueNewSliderControl and CtlGlueSetLeftAnchor.

	{
		size_t			offset		= address - objectP;

		const size_t	attr_offset	= EmAliasControlType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasControlAttrType<PAS>::GetSize ();

		const size_t	font_offset	= EmAliasControlType<PAS>::offsetof_font ();
		const size_t	font_size	= EmAliasFontID<PAS>::GetSize ();

		if ((offset >= attr_offset && offset < attr_offset + attr_size) ||
			(offset >= font_offset && offset < font_offset + font_size))
		{
			return true;
		}
	}

	// Don't allow access to any other fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedListObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedListObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	UNUSED_PARAM (forRead)

	/*
		ListType
			UInt16					id;					// FrmGetObjectId
			RectangleType			bounds;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition, LstSetHeight, LstSetPosition
			ListAttrType			attr;				// FrmShowObject, FrmHideObject
										usable			// FrmShowObject, FrmHideObject
										enabled			// (not used)
										visible			// LstDrawList, LstEraseList
										poppedUp		// LstPopupList
										hasScrollBar	// (Tested, but what sets it?)
										search			// (Tested, but what sets it?)
			Char**					itemsText;			// LstGetSelectionText, LstSetListChoices
			Int16					numItems;			// LstGetNumberOfItems
			Int16					currentItem;		// LstGetSelection, LstSetSelection
			Int16					topItem;			// LstGetTopItem, LstSetTopItem
			FontID					font;				// ?
			UInt8 					reserved;			//
			WinHandle				popupWin;			// (Used internally)
			ListDrawDataFuncPtr		drawItemsCallback;	// LstSetDrawFunction
	*/

	// Allow read access to "attr" if Emu68KAccessorTrapAvailable / AccFrmGetObjectUsable
	// not available -- FrmGlueGetObjectUsable needs access to it.

	// Actually, always allow full read/write access to attr.  LstGlueSetIncrementalSearch
	// accesses it.

//	if (forRead)
	{
		size_t			offset		= address - objectP;
		const size_t	attr_offset	= EmAliasListType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasListAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			return true;
		}
	}

	// Allow read access to itemsText for LstGlueGetItemsText.

	if (forRead)
	{
		size_t			offset				= address - objectP;
		const size_t	itemsText_offset	= EmAliasListType<PAS>::offsetof_itemsText ();
		const size_t	itemsText_size		= EmAliasemuptr<PAS>::GetSize ();

		if (offset >= itemsText_offset && offset < itemsText_offset + itemsText_size)
		{
			return true;
		}
	}

	// Allow read access to topItem before 4.0.  In 4.0 and later, use LstGetTopItem.

	if (forRead)
	{
		size_t			offset		= address - objectP;
		const size_t	topItem_offset	= EmAliasListType<PAS>::offsetof_topItem ();
		const size_t	topItem_size	= EmAliasUInt16<PAS>::GetSize ();

		if (offset >= topItem_offset && offset < topItem_offset + topItem_size)
		{
			if (!::PrvTrapsAvailable ())
			{
				return true;
			}
		}
	}

	// Allow read/write access to "font" field for LstGlueGetFont / LstGlueSetFont.

	{
		size_t			offset		= address - objectP;

		const size_t	font_offset	= EmAliasListType<PAS>::offsetof_font ();
		const size_t	font_size	= EmAliasFontID<PAS>::GetSize ();

		if ((offset >= font_offset && offset < font_offset + font_size))
		{
			return true;
		}
	}

	// Don't allow access to any other fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedTableObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedTableObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	/*
		TableType
			UInt16					id;
			RectangleType			bounds;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition, TblGetBounds, TblSetBounds
			TableAttrType			attr;
										visible			// TblEraseTable
										editable
										editing			// TblEditing, TblGrabFocus
										selected		// TblEraseTable
										hasScrollBar	// TblHasScrollBar(sets)
										usable			// FrmShowObject, FrmHideObject [Added later]
			Int16					numColumns;			// TblGetNumberOfColumns [4.0]
			Int16					numRows;			// TblGetNumberOfRows
			Int16					currentRow;			// TblGetSelection, TblSelectItem, TblGrabFocus, TblSetSelection [4.0]
			Int16					currentColumn;		// TblGetSelection, TblSelectItem, TblGrabFocus, TblSetSelection [4.0]
			Int16					topRow;				// TblGetTopRow [4.0]
			TableColumnAttrType*	columnAttrs;		// 
										width;					// TblGetColumnWidth, TblSetColumnWidth
										reserved1 		: 5;
										masked			: 1;	// TblSetColumnMasked
										editIndicator	: 1;	// TblSetColumnEditIndicator
										usable 			: 1;	// TblSetColumnUsable
										reserved2		: 8;
										spacing;				// TblGetColumnSpacing, TblSetColumnSpacing
										drawCallback;			// TblSetCustomDrawProcedure
										loadDataCallback;		// TblSetLoadDataProcedure
										saveDataCallback;		// TblSetSaveDataProcedure
			TableRowAttrType*		rowAttrs;			// 
										id;						// TblFindRowID, TblGetRowID, TblSetRowID
										height;					// TblGetRowHeight, TblSetRowHeight
										data;					// TblFindRowData, TblGetRowData, TblSetRowData
										reserved1		: 7;
										usable			: 1;	// TblRowUsable, TblSetRowUsable
										reserved2		: 4;
										masked			: 1;	// TblRowMasked, TblSetRowMasked
										invalid			: 1;	// TblRowInvalid, TblMarkRowInvalid, TblMarkTableInvalid
										staticHeight	: 1;	// TblSetRowStaticHeight
										selectable		: 1;	// TblRowSelectable, TblSetRowSelectable
										reserved3;
			TableItemPtr			items;				// 
										itemType;				// TblSetItemStyle
										fontID;					// TblGetItemFont, TblSetItemFont
										intValue;				// TblGetItemInt, TblSetItemInt
										ptr;					// TblGetItemPtr, TblSetItemPtr
			FieldType				currentField;		// TblGetCurrentField
	*/

	// TblGlueGetNumberOfColumns
	//	Give read access to numColumns before 4.0

	// TblGlueGetTopRow
	//	Give read access to topRow before 4.0

	// TblGlueSetSelection
	//	Give read access to numColumns before 4.0
	//	Give read access to numRows before 4.0
	//	Give r/w access to attr
	//		* need r/w access to "selected" if !TrapsAvailable because of code in TblGlueSetSelection
	//		* need r/w access to "usable" if TrapsAvailable (actually, if Palm OS > 4.0 for now)
	//	Give read access to rowAttrs before 4.0
	//	Give r/w access to currentRow before 4.0
	//	Give r/w access to currentColumn before 4.0
	//
	// TblGlueGetColumnMasked
	//	Give read access to numColumns
	//	Give read access to columnAttrs

	if (forRead)
	{
		size_t			offset				= address - objectP;
		const size_t	numRows_offset		= EmAliasTableType<PAS>::offsetof_numRows ();
		const size_t	numRows_size		= EmAliasUInt16<PAS>::GetSize ();

		const size_t	numColumns_offset	= EmAliasTableType<PAS>::offsetof_numColumns ();
		const size_t	numColumns_size		= EmAliasUInt16<PAS>::GetSize ();

		const size_t	topRow_offset		= EmAliasTableType<PAS>::offsetof_topRow ();
		const size_t	topRow_size			= EmAliasUInt16<PAS>::GetSize ();

		if ((offset >= numRows_offset && offset < numRows_offset + numRows_size) ||
			(offset >= numColumns_offset && offset < numColumns_offset + numColumns_size) ||
			(offset >= topRow_offset && offset < topRow_offset + topRow_size))
		{
			if (!::PrvTrapsAvailable ())
			{
				return true;
			}
		}
	}

	// Allow read access to these fields so that applications can get
	// to sub-fields that have no APIs.

	if (forRead)
	{
		size_t			offset				= address - objectP;

		const size_t	items_offset		= EmAliasTableType<PAS>::offsetof_items ();
		const size_t	items_size			= EmAliasemuptr<PAS>::GetSize ();

		const size_t	numColumns_offset	= EmAliasTableType<PAS>::offsetof_numColumns ();
		const size_t	numColumns_size		= EmAliasUInt16<PAS>::GetSize ();

		const size_t	rowAttrs_offset		= EmAliasTableType<PAS>::offsetof_rowAttrs ();
		const size_t	rowAttrs_size		= EmAliasemuptr<PAS>::GetSize ();

		const size_t	columnAttrs_offset	= EmAliasTableType<PAS>::offsetof_columnAttrs ();
		const size_t	columnAttrs_size	= EmAliasemuptr<PAS>::GetSize ();

		if ((offset >= items_offset && offset < items_offset + items_size) ||
			(offset >= numColumns_offset && offset < numColumns_offset + numColumns_size) ||
			(offset >= rowAttrs_offset && offset < rowAttrs_offset + rowAttrs_size) ||
			(offset >= columnAttrs_offset && offset < columnAttrs_offset + columnAttrs_size))
		{
			return true;
		}
	}

	{
		size_t			offset				= address - objectP;

		const size_t	currentRow_offset	= EmAliasTableType<PAS>::offsetof_currentRow ();
		const size_t	currentRow_size		= EmAliasUInt16<PAS>::GetSize ();

		const size_t	currentColumn_offset= EmAliasTableType<PAS>::offsetof_currentColumn ();
		const size_t	currentColumn_size	= EmAliasUInt16<PAS>::GetSize ();

		if ((offset >= currentRow_offset && offset < currentRow_offset + currentRow_size) ||
			(offset >= currentColumn_offset && offset < currentColumn_offset + currentColumn_size))
		{
			if (!::PrvTrapsAvailable ())
			{
				return true;
			}
		}
	}

	{
		size_t			offset				= address - objectP;
		const size_t	attr_offset			= EmAliasTableType<PAS>::offsetof_attr ();
		const size_t	attr_size			= EmAliasTableAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			return true;
		}
	}

	// Chain to the function that checks FieldType field access.

	return PrvAllowedFieldObjectAccess (
		objectP + EmAliasTableType<PAS>::offsetof_currentField (),
		address, forRead);
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormBitmapObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormBitmapObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	/*
		FormBitmapType
			FormObjAttrType			attr;
										usable			// FrmShowObject, FrmHideObject
			PointType				pos;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition
			UInt16					rscID;				// FrmGetObjectId
	*/

	// Allow read access to "attr" if Emu68KAccessorTrapAvailable / AccFrmGetObjectUsable
	// not available -- FrmGlueGetObjectUsable needs access to it.

	if (forRead)
	{
		size_t			offset		= address - objectP;
		const size_t	attr_offset	= EmAliasFormBitmapType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasFormObjAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			return true;
		}
	}

	// Allow read/write access to "attr" before 3.2 -- FrmHideObject didn't
	// change the usable bit before then.

	{
		size_t			offset		= address - objectP;

		const size_t	attr_offset	= EmAliasFormBitmapType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasFormObjAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			if (EmPatchState::OSMajorMinorVersion () < 32)
			{
				return true;
			}
		}
	}

	// Don't allow access to any other fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormLineObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormLineObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	UNUSED_PARAM (objectP)
	UNUSED_PARAM (address)
	UNUSED_PARAM (forRead)

	/*
		FormLineType
			FormObjAttrType			attr;
			PointType				point1;
			PointType				point2;
	*/

	// No access to any fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormFrameObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormFrameObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	UNUSED_PARAM (objectP)
	UNUSED_PARAM (address)
	UNUSED_PARAM (forRead)

	/*
		FormFrameType
			UInt16					id;
			FormObjAttrType			attr;
			RectangleType			rect;
			UInt16					frameType;
	*/

	// No access to any fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormRectangleObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormRectangleObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	UNUSED_PARAM (objectP)
	UNUSED_PARAM (address)
	UNUSED_PARAM (forRead)

	/*
		FormRectangleType
			FormObjAttrType			attr;
			RectangleType			rect;
	*/
	
	// No access to any fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormLabelObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormLabelObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	/*
		FormLabelType
			UInt16					id;					// FrmGetObjectId
			PointType				pos;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition
			FormObjAttrType			attr;
										usable			// FrmShowObject, FrmHideObject
			FontID					fontID;				//
			UInt8					reserved;			//
			Char*					text;				// FrmGetLabel, FrmCopyLabel
	*/

	// Allow read access to "attr" if Emu68KAccessorTrapAvailable / AccFrmGetObjectUsable
	// not available -- FrmGlueGetObjectUsable needs access to it.

	if (forRead)
	{
		size_t			offset		= address - objectP;
		const size_t	attr_offset	= EmAliasFormLabelType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasFormObjAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			return true;
		}
	}

	// Allow read/write access to "font" field for FrmGlueGetLabelFont / FrmGlueSetLabelFont.

	{
		size_t			offset		= address - objectP;

		const size_t	font_offset	= EmAliasFormLabelType<PAS>::offsetof_fontID ();
		const size_t	font_size	= EmAliasFontID<PAS>::GetSize ();

		if ((offset >= font_offset && offset < font_offset + font_size))
		{
			return true;
		}
	}

	// Don't allow access to any other fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormTitleObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormTitleObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	UNUSED_PARAM (objectP)
	UNUSED_PARAM (address)
	UNUSED_PARAM (forRead)

	/*
		FormTitleType
			RectangleType			rect;				// FrmSetObjectBounds
			Char*					text;				// FrmGetTitle, FrmSetTitle, FrmCopyTitle
	*/

	// No access to any fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormPopupObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormPopupObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	UNUSED_PARAM (objectP)
	UNUSED_PARAM (address)
	UNUSED_PARAM (forRead)

	/*
		FormPopupType
			UInt16					controlID;			//
			UInt16					listID;				//
	*/

	// No access to any fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormGraffitiStateObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormGraffitiStateObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	UNUSED_PARAM (objectP)
	UNUSED_PARAM (address)
	UNUSED_PARAM (forRead)

	/*
		FrmGraffitiStateType
			PointType				pos;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition
	*/

	// No access to any fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormGadgetObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormGadgetObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	/*
		FormGadgetType
			UInt16					id;					// FrmGetObjectId
			FormGadgetAttrType		attr;
										usable			// FrmShowObject, FrmHideObject
										extended		//
										visible			//
			RectangleType			rect;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, FrmSetObjectPosition
			const void*				data;				// FrmGetGadgetData, FrmSetGadgetData
			FormGadgetHandlerType*	handler;			// FrmSetGadgetHandler
	*/

#if 1
	UNUSED_PARAM (objectP);
	UNUSED_PARAM (address);
	UNUSED_PARAM (forRead);

	// Return "true" for all gadget fields.  Gadget callback functions
	// provide just a pointer to the gadget, with no reference to the
	// form through which to make access calls.  So the only way to
	// access fields is directly.

	return true;
#else
	// Allow read access to "attr" if Emu68KAccessorTrapAvailable / AccFrmGetObjectUsable
	// not available -- FrmGlueGetObjectUsable needs access to it.

	if (forRead)
	{
		size_t			offset		= address - objectP;
		const size_t	attr_offset	= EmAliasFormGadgetType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasFormGadgetAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			return true;
		}
	}

	// Allow write access to "attr" before 3.5, as that version added support for
	// showing and hiding gadgets.  And write-access implies read-access.

//	if (!forRead)
	{
		size_t			offset		= address - objectP;
		const size_t	attr_offset	= EmAliasFormGadgetType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasFormGadgetAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			if (EmPatchState::OSMajorMinorVersion () < 35)
			{
				return true;
			}
		}
	}

	// Don't allow access to any other fields.

	return false;
#endif
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedScrollBarObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedScrollBarObjectAccess (emuptr objectP, emuptr address, Bool forRead)
{
	/*
		ScrollBarType
			RectangleType			bounds;				// FrmGetObjectBounds, FrmGetObjectPosition, FrmSetObjectBounds, , FrmSetObjectPosition
			UInt16					id;					// FrmGetObjectId
			ScrollBarAttrType		attr;
										usable			// FrmShowObject, FrmHideObject
										visible			//
										hilighted		//
										shown			//
										activeRegion	//
			Int16					value;				// SclGetScrollBar, SclSetScrollBar
			Int16					minValue;			// SclGetScrollBar, SclSetScrollBar
			Int16					maxValue;			// SclGetScrollBar, SclSetScrollBar
			Int16					pageSize;			// SclGetScrollBar, SclSetScrollBar
			Int16					penPosInCar;		//
			Int16					savePos;			//
	*/

	// Allow read access to "attr" if Emu68KAccessorTrapAvailable / AccFrmGetObjectUsable
	// not available -- FrmGlueGetObjectUsable needs access to it.

	if (forRead)
	{
		size_t			offset		= address - objectP;
		const size_t	attr_offset	= EmAliasScrollBarType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasScrollBarAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			return true;
		}
	}

	// Allow write access to "attr" before 3.5, as that version added support for
	// showing and hiding scrollbars.  And write-access implies read-access.

//	if (!forRead)
	{
		size_t			offset		= address - objectP;
		const size_t	attr_offset	= EmAliasScrollBarType<PAS>::offsetof_attr ();
		const size_t	attr_size	= EmAliasScrollBarAttrType<PAS>::GetSize ();

		if (offset >= attr_offset && offset < attr_offset + attr_size)
		{
			if (EmPatchState::OSMajorMinorVersion () < 35)
			{
				return true;
			}
		}
	}

	// Don't allow access to any other fields.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormObjectAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form object is allowed
// on the current platform.

static Bool PrvAllowedFormObjectAccess (EmAliasFormObjListType<PAS>& formObject,
										emuptr address, Bool forRead)
{
	//
	// No access is allowed if Accessor Functions are available.
	//

	if (::PrvAccessorTrapAvailable ())
		return false;

	FormObjectKind	kind = formObject.objectType;

	Bool (*check_function) (emuptr, emuptr, Bool) = NULL;

	switch (kind)
	{
		case frmFieldObj:			check_function = PrvAllowedFieldObjectAccess;				break;
		case frmControlObj:			check_function = PrvAllowedControlObjectAccess;				break;
		case frmListObj:			check_function = PrvAllowedListObjectAccess;				break;
		case frmTableObj:			check_function = PrvAllowedTableObjectAccess;				break;
		case frmBitmapObj:			check_function = PrvAllowedFormBitmapObjectAccess;			break;
		case frmLineObj:			check_function = PrvAllowedFormLineObjectAccess;			break;
		case frmFrameObj:			check_function = PrvAllowedFormFrameObjectAccess;			break;
		case frmRectangleObj:		check_function = PrvAllowedFormRectangleObjectAccess;		break;
		case frmLabelObj:			check_function = PrvAllowedFormLabelObjectAccess;			break;
		case frmTitleObj:			check_function = PrvAllowedFormTitleObjectAccess;			break;
		case frmPopupObj:			check_function = PrvAllowedFormPopupObjectAccess;			break;
		case frmGraffitiStateObj:	check_function = PrvAllowedFormGraffitiStateObjectAccess;	break;
		case frmGadgetObj:			check_function = PrvAllowedFormGadgetObjectAccess;			break;
		case frmScrollBarObj:		check_function = PrvAllowedScrollBarObjectAccess;			break;
	}

	if (check_function)
	{
		return check_function (formObject.object, address, forRead);
	}

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedWindowAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given window is allowed on
// the current platform.

static Bool PrvAllowedWindowAccess (emuptr windowP, emuptr address, Bool forRead)
{
	//
	// No access is allowed if Accessor Functions are available.
	//

	if (::PrvAccessorTrapAvailable ())
		return false;

	UNUSED_PARAM (forRead)

	size_t					offset = address - windowP;
	EmAliasWindowType<PAS>	window (windowP);

#undef ACCESSED
#define ACCESSED(fieldName)	\
	((offset >= window.offsetof_##fieldName ()) &&	\
	 (offset < window.offsetof_##fieldName () + window.fieldName.GetSize ()))

	// Allow access to the following fields before 2.0:
	//
	//		displayWidthV20
	//		displayHeightV20

	if (forRead && EmPatchState::OSMajorMinorVersion () < 20)
	{
		if (ACCESSED (displayWidthV20) ||
			ACCESSED (displayHeightV20))
		{
			return true;
		}
	}

	// Allow access to the following fields before 3.5:
	//
	//		displayAddrV20
	//		bitmapP

	if (forRead && EmPatchState::OSMajorMinorVersion () < 35)
	{
		if (ACCESSED (displayAddrV20) ||
			ACCESSED (bitmapP))
		{
			return true;
		}
	}

	// Allow access to the following field for WinGlueGetFrameType, WinGlueSetFrameType.

	{
		if (ACCESSED (frameType))
		{
			return true;
		}
	}

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedFormAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given form is allowed on the
// current platform.

static Bool PrvAllowedFormAccess (emuptr formP, emuptr address, Bool forRead)
{
	//
	// No access is allowed if Accessor Functions are available.
	//

	if (::PrvAccessorTrapAvailable ())
		return false;

	UNUSED_PARAM (formP)
	UNUSED_PARAM (address)
	UNUSED_PARAM (forRead)

	/*
		FormType
			WindowType				window;
			UInt16					formId;					// FrmGetFormId
			FormAttrType			attr;
										usable				// 
										enabled				//
										visible				// FrmVisible
										dirty				// FrmGetUserModifiedState, FrmSetNotUserModified
										saveBehind			//
										graffitiShift		//
										globalsAvailable	//
										doingDialog			//
										exitDialog			//
			WinHandle	       		bitsBehindForm;			//
			FormEventHandlerType*	handler;				// FrmSetEventHandler
			UInt16					focus;					// FrmGetFocus, FrmSetFocus
			UInt16					defaultButton;			//
			UInt16					helpRscId;				//
			UInt16					menuRscId;				// FrmSetMenu
			UInt16					numObjects;				// FrmGetNumberOfObjects
			FormObjListType*		objects;				// FrmGetObjectPtr, FrmGetObjectType
	*/

	// Allow read access to "handler" for FrmGlueGetEventHandler.

	if (forRead)
	{
		size_t			offset			= address - formP;
		const size_t	handler_offset	= EmAliasFormType<PAS>::offsetof_handler ();
		const size_t	handler_size	= EmAliasemuptr<PAS>::GetSize ();

		if (offset >= handler_offset && offset < handler_offset + handler_size)
		{
			return true;
		}
	}

	// Allow full access to defaultButton, menuRscId, and helpRscId for FrmGlueGetDefaultButtonID,
	// FrmGlueSetDefaultButtonID, FrmGlueGetHelpID, FrmGlueSetHelpID, and FrmGlueGetMenuBarID.

	{
		size_t			offset					= address - formP;
		const size_t	defaultButton_offset	= EmAliasFormType<PAS>::offsetof_defaultButton ();
		const size_t	defaultButton_size		= EmAliasUInt16<PAS>::GetSize ();
		const size_t	helpRscId_offset		= EmAliasFormType<PAS>::offsetof_helpRscId ();
		const size_t	helpRscId_size			= EmAliasUInt16<PAS>::GetSize ();
		const size_t	menuRscId_offset		= EmAliasFormType<PAS>::offsetof_menuRscId ();
		const size_t	menuRscId_size			= EmAliasUInt16<PAS>::GetSize ();

		if ((offset >= defaultButton_offset && offset < defaultButton_offset + defaultButton_size) ||
			(offset >= helpRscId_offset && offset < helpRscId_offset + helpRscId_size) ||
			(offset >= menuRscId_offset && offset < menuRscId_offset + menuRscId_size))
		{
			return true;
		}
	}

	// Chain to the function that checks WindowType field access.

	return PrvAllowedWindowAccess (formP, address, forRead);
}


// ---------------------------------------------------------------------------
//		¥ PrvAllowedBitmapAccess
// ---------------------------------------------------------------------------
// Return whether or not the given access to the given bitmap is allowed
// on the current platform.

static Bool PrvAllowedBitmapAccess (EmAliasBitmapTypeV2<PAS>& bitmap, emuptr address, Bool forRead)
{
	//
	// No access is allowed if Accessor Functions are available.
	//

	if (::PrvAccessorTrapAvailable ())
		return false;

	/*
		BitmapType
1.0			Int16					width;
1.0			Int16					height;
1.0			UInt16					rowBytes;
1.0			BitmapFlagsType			flags;
1.0				UInt16					compressed:1;  		// Data format:  0=raw; 1=compressed
3.0				UInt16					hasColorTable:1;	// if true, color table stored before bits[]
3.5				UInt16					hasTransparency:1;	// true if transparency is used
3.5				UInt16					indirect:1;			// true if bits are stored indirectly
3.5				UInt16					forScreen:1;		// system use only
3.0			UInt8					pixelSize;			// bits/pixel
3.0			UInt8					version;			// version of bitmap. This is vers 2
3.0			UInt16					nextDepthOffset;	// # of DWords to next BitmapType
														//	from beginnning of this one
3.5			UInt8					transparentIndex;	// v2 only, if flags.hasTransparency is true,
														// index number of transparent color
3.5			UInt8					compressionType;	// v2 only, if flags.compressed is true, this is
														// the type, see BitmapCompressionType

			UInt16					reserved;			// for future use, must be zero!

			// [colorTableType] pixels | pixels*
														// If hasColorTable != 0, we have:
														//	ColorTableType followed by pixels. 
														// If hasColorTable == 0:
														//	this is the start of the pixels
														// if indirect != 0 bits are stored indirectly.
														//	the address of bits is stored here
														//	In some cases the ColorTableType will
														//	have 0 entries and be 2 bytes long.
	*/

	/*
		width				- Needs r/w access before 3.5.  In 3.5, use BmpCreate.
							- Needs read access before 4.0.  In 4.0, use BmpGetDimensions.
							- No access in 4.0 and later.
		height				- Same as width.
		rowBytes			- Same as width.
		flags				- Needs r/w access always. (to get to hasTransparency)
			compressed			- Needs r/w access before 3.5.  In 3.5, use BmpCompress.
								- No access in 3.5 and later.
			hasColorTable		- Needs r/w access before 3.5.  In 3.5, use BmpCreate.
								- No access in 3.5 and later.
			hasTransparency		- Needs r/w access always.
			indirect			- No access -- system use only
			forScreen			- No access -- system use only
		pixelSize			- Needs r/w access before 3.5.  In 3.5, use BmpCreate.
							- Needs read access before 4.0.  In 4.0, use BmpGetBitDepth.
							- No access in 4.0 and later.
		version				- Needs r/w access before 3.5.  In 3.5, use BmpCreate.
							- Needs read access before 4.0.  In 4.0, use BmpGetNextBitmap. 
							- No access in 4.0 and later.
		nextDepthOffset		- Needs r/w access before 3.5.  In 3.5, use BmpCreate.
							- Needs read access before 4.0.  In 4.0, use BmpGetNextBitmap.
							- No access in 4.0 and later.
		transparentIndex	- Needs r/w access always.
		compressionType		- Needs r/w access before 3.5.  In 3.5, use BmpCompress.
							- No access in 3.5 and later.
		reserved			- No access
	*/

	/*
		// 3.5
			#define sysTrapBmpGetBits								0xA376  // was BltGetBitsAddr

			// Bitmap manager functions
			#define sysTrapBmpCreate								0xA3DD	// width, height, depth, colortable.
			#define sysTrapBmpDelete								0xA3DE
			#define sysTrapBmpCompress								0xA3DF	// compressed, compressionType

			// sysTrapBmpGetBits defined in Screen driver traps
			#define sysTrapBmpGetColortable							0xA3E0
			#define sysTrapBmpSize									0xA3E1
			#define sysTrapBmpBitsSize								0xA3E2
			#define sysTrapBmpColortableSize						0xA3E3

		// 4.0
			#define sysTrapBmpGetDimensions							0xA44E
			#define sysTrapBmpGetBitDepth							0xA44F
			#define sysTrapBmpGetNextBitmap							0xA450
			#define sysTrapBmpGetSizes								0xA455
	*/

	// Since the rules are largely dependent on OS version, let's order
	// our first-level checks based on that.

	if (EmPatchState::OSMajorMinorVersion () < 35)
	{
		// Have full access before 3.5, since there's no API.

		return true;
	}
	else if (EmPatchState::OSMajorMinorVersion () < 40)
	{
		// The following functions were added in 3.5:
		//
		//	BmpGetBits
		//	BmpCreate			-- Allows setting of all fields except hasTransparency and transparentIndex.
		//	BmpDelete
		//	BmpCompress			-- Allows changing of compressed, compressionType
		//	BmpGetColortable
		//	BmpSize
		//	BmpBitsSize
		//	BmpColortableSize
		//
		// Therefore, all fields except hasTransparency and transparentIndex
		// now have read-only access.  Those two fields still have read/write access.

		if (forRead)
		{
			return true;
		}
		else
		{
			emuptr			bitmapP					= bitmap.GetPtr ();
			size_t			offset					= address - bitmapP;

			const size_t	flags_offset			= EmAliasBitmapTypeV2<PAS>::offsetof_flags ();
			const size_t	flags_size				= EmAliasUInt16<PAS>::GetSize ();

			const size_t	transparentIndex_offset	= EmAliasBitmapTypeV2<PAS>::offsetof_transparentIndex ();
			const size_t	transparentIndex_size	= EmAliasUInt8<PAS>::GetSize ();

			if (offset >= flags_offset && offset < flags_offset + flags_size)
			{
				return true;
			}

			if (offset >= transparentIndex_offset && offset < transparentIndex_offset + transparentIndex_size)
			{
				return true;
			}
		}
	}
	else
	{
		// The following functions were added in 4.0:
		//
		//	BmpGetDimensions
		//	BmpGetBitDepth
		//	BmpGetNextBitmap
		//	BmpGetSizes
		//
		// With these, complete supported access to all fields is provided
		// except for hasTransparency and transparentIndex.

		emuptr			bitmapP					= bitmap.GetPtr ();
		size_t			offset					= address - bitmapP;

		const size_t	flags_offset			= EmAliasBitmapTypeV2<PAS>::offsetof_flags ();
		const size_t	flags_size				= EmAliasUInt16<PAS>::GetSize ();

		const size_t	transparentIndex_offset	= EmAliasBitmapTypeV2<PAS>::offsetof_transparentIndex ();
		const size_t	transparentIndex_size	= EmAliasUInt8<PAS>::GetSize ();

		if (offset >= flags_offset && offset < flags_offset + flags_size)
		{
			return true;
		}

		if (offset >= transparentIndex_offset && offset < transparentIndex_offset + transparentIndex_size)
		{
			return true;
		}
	}

	// Don't allow access to any other fields.

	return false;
}


static Bool PrvAllowedBitmapAccess (EmAliasBitmapTypeV3<PAS>&, emuptr, Bool)
{
	// Access to all fields is provided by accessor functions in all versions
	// of the OS that support this data structure.

	// Don't allow access to any other fields.

	return false;
}


#pragma mark -

/*
	In order to track Bitmaps, we have to do some pretty fancy footwork.
	We need to be able to tell when Bitmaps are allocated and deallocated
	so that we know which memory blocks to mark as inaccessible.

	One way that a bitmap can be allocated/deallocated is with BmpCreate
	and BmpDelete.  To support this method, we patch those two functions
	and call RegisterBitmapPointer and UnregisterBitmapPointer as
	appropriate.

	The other way that a bitmap can be allocated/deallocated is from a
	resource.  The resource is read in with DmGetResource or DmGet1Resource,
	locked with MemHandleLock, unlocked with MemHandleUnlock or MemPtrUnlock
	(or possibly MemHandleResetLock), and then possibly released with
	DmReleaseResource.  To support this method, we patch DmGetResource
	and DmGet1Resource so that we know which handles contain bitmaps (passing
	them to RegisterBitmapHandle), and MemHandleLock so that we can get the
	pointer to the bitmap and pass it to RegisterBitmapPointer.  We also
	monitor MemHandleUnlock, MemPtrUnlock, and MemHandleResetLock so that we
	can call UnregisterBitmapPointer, and MemHandleFree and MemPtrFree so
	that we can call UnregisterBitmapHandle.

	With all the handles and pointers registered, we now have the information
	we need in order to mark the blocks as inaccessible in PrvForEachBitmap.
*/

// !!! NOTE: bitmap tracking is turned off for now.  The heuristics for
// determining when to stop tracking a memory handle are incomplete
// and need to be rethought out.  In particular, the case of installing
// an application with a color icon, running it, and then trying to
// re-install that application doesn't work.
//
// As well, Poser doesn't handle invalid bitmap families very well.
// It can easily try to use bogus nextDepthOffset values when stepping
// to the next icon in the family.

// ---------------------------------------------------------------------------
//		¥ MetaMemory::RegisterBitmapHandle
// ---------------------------------------------------------------------------

void MetaMemory::RegisterBitmapHandle (MemHandle /*h*/)
{
#if 0
	if (h && !IsBitmapHandle (h))
	{
		MetaMemory::UnmarkUIObjects ();
		gBitmapHandleList.push_back (h);
		MetaMemory::MarkUIObjects ();
	}
#endif
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::RegisterBitmapPointer
// ---------------------------------------------------------------------------

void MetaMemory::RegisterBitmapPointer (MemPtr /*p*/)
{
#if 0
	if (p && !IsBitmapPointer (p))
	{
		MetaMemory::UnmarkUIObjects ();
		gBitmapPointerList.push_back (p);
		MetaMemory::MarkUIObjects ();
	}
#endif
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::IsBitmapHandle
// ---------------------------------------------------------------------------

Bool MetaMemory::IsBitmapHandle (MemHandle h)
{
	return h && find (
		gBitmapHandleList.begin (),
		gBitmapHandleList.end (), h) != gBitmapHandleList.end ();
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::IsBitmapPointer
// ---------------------------------------------------------------------------

Bool MetaMemory::IsBitmapPointer (MemPtr p)
{
	return p && find (
		gBitmapPointerList.begin (),
		gBitmapPointerList.end (), p) != gBitmapPointerList.end ();
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::UnregisterBitmapHandle
// ---------------------------------------------------------------------------

void MetaMemory::UnregisterBitmapHandle (MemHandle h)
{
	if (h)
	{
		vector<MemHandle>::iterator	iter = find (
			gBitmapHandleList.begin (),
			gBitmapHandleList.end (), h);

		if (iter != gBitmapHandleList.end ())
		{
			MetaMemory::UnmarkUIObjects ();
			gBitmapHandleList.erase (iter);
			MetaMemory::MarkUIObjects ();
		}
	}
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::UnregisterBitmapPointer
// ---------------------------------------------------------------------------

void MetaMemory::UnregisterBitmapPointer (MemPtr p)
{
	if (p)
	{
		vector<MemPtr>::iterator	iter = find (
			gBitmapPointerList.begin (),
			gBitmapPointerList.end (), p);

		if (iter != gBitmapPointerList.end ())
		{
			MetaMemory::UnmarkUIObjects ();
			gBitmapPointerList.erase (iter);
			MetaMemory::MarkUIObjects ();
		}
	}
}


#pragma mark -

struct EmCheckIterData
{
	emuptr	address;
	size_t	size;
	Bool	forRead;
	Bool	isInUIObject;
	Bool	butItsOK;
};


// ---------------------------------------------------------------------------
//		¥ PrvGetObjectSize
// ---------------------------------------------------------------------------
// Get and return the size of the object.  A bitmap object's size is based on
// the version number in the bitmap.  A window object's size is the size of
// the memory chunk the window's in.

static int PrvGetObjectSize (emuptr object, int type)
{
	int	result = 0;

	if (type == kUIWindow)
	{
		// Get the heap the window is in.  Use that to get information about
		// the chunk the window is in.

		const EmPalmHeap*	heap = EmPalmHeap::GetHeapByPtr ((MemPtr) object);

		// Can't find the heap?  Aip!

		EmAssert (heap != NULL);

		if (!heap)
			return result;

		// Get information on this chunk so that we can get its size.

		EmPalmChunk	chunk (*heap, object - heap->ChunkHeaderSize ());

		result = chunk.BodySize ();
	}
	else if (type == kUIBitmap)
	{
		EmAliasBitmapTypeV3<PAS>	bitmapV3 (object);

		if (bitmapV3.version <= 2)
		{
			result = EmProxyBitmapTypeV2::GetSize ();
		}
		else
		{
			result = bitmapV3.size;
		}
	}
	else
	{
		EmAssert (false);
	}

	return result;
}


// ---------------------------------------------------------------------------
//		¥ PrvGetNextBitmap
// ---------------------------------------------------------------------------

static emuptr PrvGetNextBitmap (emuptr p)
{
	emuptr	nextBitmap = EmMemNULL;

	EmAliasBitmapTypeV2<PAS>	bitmapV2 (p);

	// If this is a version 3 bitmap, then format the structure as a
	// version 3 structure and extract the nextDepthOffset field.

	if (bitmapV2.version >= 3)
	{
		EmAliasBitmapTypeV3<PAS>	bitmapV3 (p);
		
		if (bitmapV3.nextDepthOffset != 0)
		{
			nextBitmap = p + bitmapV3.nextDepthOffset * sizeof (UInt32);
		}
	}

	// If this is a version 0, 1, or 2 bitmap, extract the
	// nextDepthOffset field.

	else if (bitmapV2.nextDepthOffset != 0)
	{
		nextBitmap = p + bitmapV2.nextDepthOffset * sizeof (UInt32);
	}

	// If that was NULL, then check to see if this looks like a "dummy"
	// bitmap used to hide the existance and format of high density
	// bitmap families from the unprepared application.

	else if (bitmapV2.version == 1 && bitmapV2.pixelSize == 255)
	{
		nextBitmap = p + bitmapV2.GetSize ();
	}

	EmAssert (nextBitmap == EmMemNULL || EmMemCheckAddress (nextBitmap, 0) != false);

	return nextBitmap;
}


// ---------------------------------------------------------------------------
//		¥ PrvCheckFormObject
// ---------------------------------------------------------------------------

static Bool PrvCheckFormObject (EmAliasFormType<PAS>& form,
						 EmAliasFormObjListType<PAS>& formObject,
						 EmCheckIterData* data)
{
	// Get the form object kind, so that we can determine its size.

	emuptr			formP		= form.GetPtr ();
	emuptr			formObjectP	= formObject.GetPtr ();

	FormObjectKind	kind		= formObject.objectType;
	emuptr			objectAddr	= formObject.object;

	static int	kSizeArray[] =
	{
		EmAliasFieldType<PAS>::GetSize (),				// frmFieldObj
		-1,												// frmControlObj
		EmAliasListType<PAS>::GetSize (),				// frmListObj
		EmAliasTableType<PAS>::GetSize (),				// frmTableObj
		EmAliasFormBitmapType<PAS>::GetSize (),			// frmBitmapObj
		EmAliasFormLineType<PAS>::GetSize (),			// frmLineObj
		EmAliasFormFrameType<PAS>::GetSize (),			// frmFrameObj
		EmAliasFormRectangleType<PAS>::GetSize (),		// frmRectangleObj
		EmAliasFormLabelType<PAS>::GetSize (),			// frmLabelObj
		EmAliasFormTitleType<PAS>::GetSize (),			// frmTitleObj
		EmAliasFormPopupType<PAS>::GetSize (),			// frmPopupObj
		EmAliasFrmGraffitiStateType<PAS>::GetSize (),	// frmGraffitiStateObj
		EmAliasFormGadgetType<PAS>::GetSize (),			// frmGadgetObj
		EmAliasScrollBarType<PAS>::GetSize ()			// frmScrollBarObj
	};

	// If the access was to a form object, flag an error.

	int		itsSize	= kSizeArray[kind];

	if (itsSize < 0)	// Special cases
	{
		// Some controls have special sizes.  Determine and use those.

		EmAliasControlType<PAS>	control (objectAddr);
		uint16	attr	= control.attr.flags;
		uint8	style	= control.style;

		itsSize	= control.GetSize ();	// Standard ControlType size
		
		if (attr & ControlAttrType_graphical)
		{
			// It's a GraphicControlType.

			itsSize = EmAliasGraphicControlType<PAS>::GetSize ();
		}
		else if (style == sliderCtl || style == feedbackSliderCtl)
		{
			// It's a SliderControlType.

			itsSize = EmAliasSliderControlType<PAS>::GetSize ();
		}
	}

	// Now check access to the form object.

	if (data->address >= objectAddr && data->address < objectAddr + itsSize)
	{
		data->isInUIObject = true;

		if (!::PrvAllowedFormObjectAccess (formObject, data->address, data->forRead))
		{
			gSession->ScheduleDeferredError (new EmDeferredErrFormObjectAccess (formObjectP, formP, data->address, data->size, data->forRead));
			data->butItsOK = false;
		}

		return true;
	}

#if 0	// There's no good API for altering the text, and so many developers
		// write to it "in place".  Allow this for now, until we come up with
		// a better API.

	// If there's text associated with this object, check access to it, too.
	// Allow read access, since some functions (like CtrlGetLabel) return
	// pointers to the text that the application will expect to access.

	emuptr	textPtr = EmMemNULL;

	switch (kind)
	{
		case frmControlObj:
		{
			EmAliasControlType<PAS>	control (objectAddr);
			uint16	attr	= control.attr.flags;
			uint8	style	= control.style;
			
			if (attr & ControlAttrType_graphical)
			{
				// No text with graphical controls.
			}
			else if (style == sliderCtl || style == feedbackSliderCtl)
			{
				// No text with slider controls.
			}
			else
			{
				textPtr = control.text;
			}

			break;
		}

		case frmLabelObj:
		{
			EmAliasFormLabelType<PAS>	label (objectAddr);
			textPtr = label.text;
			break;
		}

		case frmTitleObj:
		{
			EmAliasFormTitleType<PAS>	title (objectAddr);
			textPtr = title.text;
			break;
		}

		case frmFieldObj:	// Yes, there's text associated with this object,
							// but it's never in the same memory chunk as the
							// form and its objects, and so will not currently
							// get marked as off limits.
		case frmListObj:
		case frmTableObj:
		case frmBitmapObj:
		case frmLineObj:
		case frmFrameObj:
		case frmRectangleObj:
		case frmPopupObj:
		case frmGraffitiStateObj:
		case frmGadgetObj:
		case frmScrollBarObj:
			break;
	}

	if (textPtr && !data->forRead)
	{
		size_t	textSize = EmMem_strlen (textPtr) + 1;

		if (data->address >= textPtr && data->address < textPtr + textSize)
		{
			data->isInUIObject = true;

			if (!::PrvAllowedFormObjectAccess (formObject, data->address, data->forRead))
			{
				gSession->ScheduleDeferredError (new EmDeferredErrFormObjectAccess (formObjectP, formP, data->address, data->size, data->forRead));
				data->butItsOK = false;
			}

			return true;
		}
	}
#endif

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvCheckForm
// ---------------------------------------------------------------------------

static Bool PrvCheckForm (EmAliasFormType<PAS>& form, EmCheckIterData* data)
{
	// If the access was to the form, flag an error.

	emuptr	formP	= form.GetPtr ();
	size_t	size	= form.GetSize ();

	if (data->address >= formP && data->address < formP + size)
	{
		data->isInUIObject = true;

		if (!::PrvAllowedFormAccess (formP, data->address, data->forRead))
		{
			gSession->ScheduleDeferredError (new EmDeferredErrFormAccess (formP, data->address, data->size, data->forRead));
			data->butItsOK = false;
		}

		return true;
	}

	// If the access was to the form item list, flag an error.

	// Get the number of objects in the form.  Use this value to determine
	// the range of memory the form spans.

	uint16	numObjects	= form.numObjects;
	emuptr	firstObject	= form.objects;
	emuptr	lastObject	= firstObject + numObjects * EmAliasFormObjListType<PAS>::GetSize ();

	if (data->address >= firstObject && data->address < lastObject)
	{
		data->isInUIObject = true;

		if (!::PrvAllowedFormAccess (formP, data->address, data->forRead))
		{
			gSession->ScheduleDeferredError (new EmDeferredErrFormAccess (formP, data->address, data->size, data->forRead));
			data->butItsOK = false;
		}

		return true;
	}

	// Walk the objects in the form.  Check each one to see
	// if the access was made to one of them.

	emuptr	thisObject = firstObject;

	for (int ii = 0; ii < numObjects; ++ii)
	{
		EmAliasFormObjListType<PAS>	formObject (thisObject);

		if (::PrvCheckFormObject (form, formObject, data))
			return true;

		// Go to the next form object.

		thisObject += formObject.GetSize ();
	}

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvCheckWindow
// ---------------------------------------------------------------------------

static Bool PrvCheckWindow (EmAliasWindowType<PAS>& window, EmCheckIterData* data)
{
	// Plain old window.  Check the access against the window size.
	// While a couple of the fields of WindowTyp have changed from
	// Palm OS 1.0 to 4.0 (viewOrigin has changed to bitMapP, gstate
	// has changed to drawStateP, and compressed has changed to
	// freeBitmap), the size is still the same.

	emuptr	windowP = window.GetPtr ();
	size_t	size	= window.GetSize ();

	if (data->address >= windowP && data->address < windowP + size)
	{
		data->isInUIObject = true;

		if (!::PrvAllowedWindowAccess (windowP, data->address, data->forRead))
		{
			gSession->ScheduleDeferredError (new EmDeferredErrWindowAccess (windowP, data->address, data->size, data->forRead));
			data->butItsOK = false;
		}

		return true;
	}

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvCheckBitmap
// ---------------------------------------------------------------------------

static Bool PrvCheckBitmap (EmAliasBitmapTypeV2<PAS>& bitmapV2, EmCheckIterData* data)
{
	emuptr	bitmapP	= bitmapV2.GetPtr ();
	size_t	size	= bitmapV2.GetSize ();

	if (data->address >= bitmapP && data->address < bitmapP + size)
	{
		data->isInUIObject = true;

		if (!::PrvAllowedBitmapAccess (bitmapV2, data->address, data->forRead))
		{
			gSession->ScheduleDeferredError (new EmDeferredErrBitmapAccess (bitmapP, data->address, data->size, data->forRead));
			data->butItsOK = false;
		}

		return true;
	}

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvCheckBitmap
// ---------------------------------------------------------------------------

static Bool PrvCheckBitmap (EmAliasBitmapTypeV3<PAS>& bitmapV3, EmCheckIterData* data)
{
	emuptr	bitmapP	= bitmapV3.GetPtr ();
	size_t	size	= bitmapV3.size;

	if (data->address >= bitmapP && data->address < bitmapP + size)
	{
		data->isInUIObject = true;

		if (!::PrvAllowedBitmapAccess (bitmapV3, data->address, data->forRead))
		{
			gSession->ScheduleDeferredError (new EmDeferredErrBitmapAccess (bitmapP, data->address, data->size, data->forRead));
			data->butItsOK = false;
		}

		return true;
	}

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvCheckUIObject
// ---------------------------------------------------------------------------
// Check to see if the given access is in a proscribed area of memory.  Will
// first check to see if:
//
//	* this check is turned off
//	* the system is initialized enough to make this check
//	* the access is made from a RAM-based system component
//	* full memory access is allowed
//
// Only if checking seems indicated is the full-winded check made.  If
// a proscribed access is indeed made, a "deferred error" object is posted
// to the session.

Bool PrvCheckUIObject (emuptr objectP, void* d, int type)
{
	// Walk the window list, looking for windows and forms

	EmAssert (d);
	EmCheckIterData*	data = (EmCheckIterData*) d;

	if (type == kUIWindow)
	{
		// See if this window is a plain window, or a form.

		EmAliasWindowType<PAS>	window (objectP);
		uint16	flags = window.windowFlags.flags;

		if (flags & WindowFlagsType_dialog)
		{
			// It's a form.

			EmAliasFormType<PAS>	form (objectP);

			if (::PrvCheckForm (form, data))
				return true;
		}
		else
		{
			// It's a plain old window.

			if (::PrvCheckWindow (window, data))
				return true;
		}
	}
	else if (type == kUIBitmap)
	{
		EmAliasBitmapTypeV2<PAS>	bitmapV2 (objectP);

		if (bitmapV2.version <= 2)
		{
			if (::PrvCheckBitmap (bitmapV2, data))
				return true;
		}
		else
		{
			EmAliasBitmapTypeV3<PAS>	bitmapV3 (objectP);

			if (::PrvCheckBitmap (bitmapV3, data))
				return true;
		}
	}
	else
	{
		EmAssert (false);
	}

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvMarkUIObject
// ---------------------------------------------------------------------------
// Get the size of the UI object, use it to get the end of the object, and
// mark the whole thing as off-limits.

Bool PrvMarkUIObject (emuptr object, void* /*data*/, int type)
{
	emuptr	begin	= object;
	emuptr	end		= begin + ::PrvGetObjectSize (object, type);

	MetaMemory::MarkUIObject (begin, end);

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvUnmarkUIObject
// ---------------------------------------------------------------------------
// Get the size of the UI object, use it to get the end of the object, and
// mark the whole thing as accessible.

static Bool PrvUnmarkUIObject (emuptr object, void* /*data*/, int type)
{
	emuptr	begin	= object;
	emuptr	end		= begin + ::PrvGetObjectSize (object, type);

	MetaMemory::UnmarkUIObject (begin, end);

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvForEachWindow
// ---------------------------------------------------------------------------
// Iterate over all window objects, calling a generic iteration function for
// each one.  If the iteration function returns true, that means that the
// iteration should stop.  This function returns true or false to indicate if
// the iteration was aborted.

Bool PrvForEachWindow (IterFn fn, void* data)
{
	// If the UI is not initialized for this application, the FirstWindow
	// pointer in uiGlobals will be non-NULL, but invalid (it will point
	// to the FirstWindow for the previous application, which has been
	// disposed of by now).  Wait until UIReset has been called.

	if (!EmPatchState::UIReset ())
		return false;

	// Walk the window list, looking for windows and forms

	emuptr	w = EmLowMem_GetGlobal (uiGlobals.firstWindow);
	while (w)
	{
		if (fn (w, data, kUIWindow))
			return true;

		// Go to the next window.

		EmAliasWindowType<PAS>	window (w);
		w = window.nextWindow;
	}

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvForEachBitmap
// ---------------------------------------------------------------------------
// Iterate over all bitmap objects, calling a generic iteration function for
// each one.  If the iteration function returns true, that means that the
// iteration should stop.  This function returns true or false to indicate if
// the iteration was aborted.

Bool PrvForEachBitmap (IterFn /*fn*/, void* /*data*/)
{
#if 0
	// Iterate over each bitmap in our list.

	vector<MemPtr>::iterator	iter = gBitmapPointerList.begin ();
	while (iter != gBitmapPointerList.end ())
	{
		emuptr	p = (emuptr) *iter;

		// Iterate over each bitmap in the bitmap family.

		while (p)
		{
			if (fn (p, data, kUIBitmap))
				return true;

			p = ::PrvGetNextBitmap (p);
		}

		++iter;
	}
#endif

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvForEachUIObject
// ---------------------------------------------------------------------------
// Iterate over all UI objects, calling a generic iteration function for each
// one.  If the iteration function returns true, that means that the iteration
// should stop.  This function returns true or false to indicate if the
// iteration was aborted.

Bool PrvForEachUIObject (IterFn fn, void* data)
{
	// Give us full access to memory.

	CEnableFullAccess	munge;

	// Check windows and forms.

	if (::PrvForEachWindow (fn, data))
		return true;

	// Check bitmaps.

	if (::PrvForEachBitmap (fn, data))
		return true;

	return false;
}


// ---------------------------------------------------------------------------
//		¥ CheckUIObjectAccess
// ---------------------------------------------------------------------------
// Iterate over all UI objects, calling a function that will check to see
// which -- if any -- object was accessed and if that access was OK.

void MetaMemory::CheckUIObjectAccess (emuptr address, size_t size, Bool forRead,
									  Bool& isInUIObject, Bool& butItsOK)
{
	EmCheckIterData	data;

	data.address		= address;
	data.size			= size;
	data.forRead		= forRead;
	data.isInUIObject	= false;
	data.butItsOK		= true;

	::PrvForEachUIObject (&::PrvCheckUIObject, &data);

	isInUIObject		= data.isInUIObject;
	butItsOK			= data.butItsOK;
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::MarkUIObjects
// ---------------------------------------------------------------------------
// Iterate over all UI objects, calling a function that will mark each one
// as off limits to applications.

void MetaMemory::MarkUIObjects (void)
{
	::PrvForEachUIObject (&::PrvMarkUIObject, NULL);
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::UnmarkUIObjects
// ---------------------------------------------------------------------------
// Iterate over all UI objects, calling a function that will mark each one
// as accessible to applications.

void MetaMemory::UnmarkUIObjects (void)
{
	::PrvForEachUIObject (&::PrvUnmarkUIObject, NULL);
}


#pragma mark -

// ---------------------------------------------------------------------------
//		¥ PrvLocalIDToPtr
// ---------------------------------------------------------------------------
// Local/native version of MemLocalIDToPtr.  Implemented natively instead
// of calling emulated version for speed.

static emuptr PrvLocalIDToPtr (LocalID local)
{
	emuptr						memCardInfoP = EmLowMem_GetGlobal (memCardInfoP);
	EmAliasCardInfoType<PAS>	cardInfo (memCardInfoP);
	emuptr						p = (local & 0xFFFFFFFE) + cardInfo.baseP;

	// If it's a handle, dereference it

	if (local & 0x01) 
		p = EmMemGet32 (p);

	return p;
}


// ---------------------------------------------------------------------------
//		¥ PrvGetRAMDatabaseDirectory
// ---------------------------------------------------------------------------
// Return a pointer to the database directory for RAM-based databases.

static emuptr PrvGetRAMDatabaseDirectory(void)
{
	emuptr							memCardInfoP = EmLowMem_GetGlobal (memCardInfoP);
	EmAliasCardInfoType<PAS>		cardInfo (memCardInfoP);
	emuptr							storeP = cardInfo.ramStoreP;

	EmAliasStorageHeaderType<PAS>	store (storeP);
	LocalID							databaseDirID = store.databaseDirID;

	return ::PrvLocalIDToPtr (databaseDirID);
}


// ---------------------------------------------------------------------------
//		¥ PrvIsOKCharacter
// ---------------------------------------------------------------------------

static inline Bool PrvIsOKCharacter (char ch)
{
	return islower (ch);
}


// ---------------------------------------------------------------------------
//		¥ PrvIsLowerCaseCreator
// ---------------------------------------------------------------------------
// Return whether or not the given creator is composed of all lower-case
// letters (as defined by the islower macro in ctypes.h).

static inline Bool PrvIsLowerCaseCreator (UInt32 creator)
{
	const char*	p = (const char*) &creator;

	return	PrvIsOKCharacter (p[0]) &&
			PrvIsOKCharacter (p[1]) &&
			PrvIsOKCharacter (p[2]) &&
			PrvIsOKCharacter (p[3]);
}


// ---------------------------------------------------------------------------
//		¥ PrvIsPalmCreator
// ---------------------------------------------------------------------------

static Bool PrvIsPalmCreator (UInt32 creator)
{
	// Creator IDs consisting of all lowercase letters are reserved for use
	// by Palm Inc.  Additionally, it has reserved the following creator
	// IDs, as of 8/17/01.

	static const UInt32 kNonStandardCreators[] =
	{
		'a68k',
		'mfx1',
		'u328',
		'u650',
		'u8EZ'
	};

	// Check to see if the creator ID follows the Palm standard.  If so,
	// return TRUE.

	if (::PrvIsLowerCaseCreator (creator))
	{
		return true;
	}

	// See if the creator is in the list of creators registered by
	// Palm that don't follow the Palm standard.  If so, return TRUE.

	for (size_t ii = 0; ii < countof (kNonStandardCreators); ++ii)
	{
		if (creator == kNonStandardCreators[ii])
		{
			return true;
		}
	}

	// It's not a Palm creator.  Return FALSE.

	return false;
}


// ---------------------------------------------------------------------------
//		¥ PrvIsRegisteredPalmCreator
// ---------------------------------------------------------------------------

static Bool PrvIsRegisteredPalmCreator (UInt32 creator)
{
	// Registered Palm applications as of 8/17/01.

	static const UInt32 kPalmRegisteredCreators[] =
	{
		'a68k',		'actv',		'addr',		'blth',		'btcp',
		'btex',		'bttn',		'bttx',		'calc',		'cinf',
		'clpr',		'date',		'dbmn',		'dial',		'dict',
		'digi',		'dmfx',		'dttm',		'econ',		'expn',
		'exps',		'fatf',		'fins',		'flsh',		'fone',
		'frmt',		'gafd',		'gdem',		'gnrl',		'graf',
		'gsmf',		'hidd',		'hpad',		'hrel',		'hssu',
		'htcp',		'inet',		'ircm',		'irda',		'iwrp',
		'lnch',		'locl',		'lpkr',		'mail',		'mdem',
		'memo',		'memr',		'mfgc',		'mfgf',		'mfx1',
		'mine',		'mmfx',		'modm',		'msgs',		'netl',
		'netp',		'nett',		'netw',		'olbi',		'ownr',
		'patd',		'pdil',		'pdvc',		'phop',		'ping',
		'pnps',		'poem',		'port',		'pref',		'psys',
		'ptch',		'pusb',		'puzl',		'rfcm',		'rfdg',
		'sdsd',		'secl',		'secr',		'setp',		'shct',
		'smgr',		'smsl',		'smsm',		'spht',		'srvr',
		'stgd',		'swrp',		'sync',		'tmgr',		'todo',
		'tsml',		'u328',		'u650',		'u8EZ',		'udic',
		'usbc',		'usbd',		'usbp',		'vfsm',		'wclp',
		'webl',		'wwww'
	};

	const UInt32*	begin	= &kPalmRegisteredCreators[0];
	const UInt32*	end		= &kPalmRegisteredCreators[countof (kPalmRegisteredCreators)];

	return binary_search (begin, end, creator);
}


// ---------------------------------------------------------------------------
//		¥ PrvAddTaggedChunk
// ---------------------------------------------------------------------------

static void PrvAddTaggedChunk (const EmTaggedPalmChunk& chunk)
{
	gTaggedChunks.push_back (chunk);
}


// ---------------------------------------------------------------------------
//		¥ PrvLoadTaggedChunk
// ---------------------------------------------------------------------------
// Return whether or not the given memory address is in a chunk on our cache
// of RAM-based system components.

static void PrvLoadTaggedChunk (emuptr pc)
{
	EmTaggedPalmChunkList::iterator	iter = gTaggedChunks.begin ();
	while (iter != gTaggedChunks.end ())
	{
		if (iter->BodyContains (pc))
		{
			gHaveLastChunk = true;
			gLastChunk = *iter;
			return;
		}

		++iter;
	}
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::ChunkUnlocked
// ---------------------------------------------------------------------------
// If a chunk is unlocked, see if that chunk is on our cache of RAM-based
// system components.  If so, remove that chunk from our cache.

void MetaMemory::ChunkUnlocked (emuptr addr)
{
	EmTaggedPalmChunkList::iterator	iter = gTaggedChunks.begin ();
	while (iter != gTaggedChunks.end ())
	{
		if (iter->BodyContains (addr))
		{
			gTaggedChunks.erase (iter);

			if (gLastChunk.BodyContains (addr))
			{
				gHaveLastChunk = false;
			}

			return;
		}

		++iter;
	}
}


#pragma mark -

// ---------------------------------------------------------------------------
//		¥ PrvIsSystemDatabase
// ---------------------------------------------------------------------------
// See if the database is one that we want to treat as a RAM-based system
// component.

static Bool PrvIsSystemDatabase (UInt32 type, UInt32 creator)
{
	Bool	isSystemDatabase = false;

	if ((type == sysFileTExtension) ||
		(type == sysFileTLibrary) ||
		(type == sysFileTPanel) ||
		(type == sysFileTSystemPatch) ||
		(type == sysFileTHtalLib) ||	// NetSync.prc if is of this type (creator == sysFileCTCPHtal)
		(type == 'bttx'))				// Bluetooth Extension
	{
		isSystemDatabase = ::PrvIsPalmCreator (creator);
	}
	else if (type == sysFileTApplication)
	{
		// I'd just check for all-lower-case letters here, but I'm
		// dubious as to how strictly 3rd party applications adhere
		// to that requirement.  Checking a directory full of 3rd
		// party applications on our server, 9 of the 250 or so
		// application had all-lower-case creators (and more than
		// one of those was 'memo'!).

		isSystemDatabase = ::PrvIsRegisteredPalmCreator (creator);
	}

	// Handspring has RAM-based extensions that access system globals
	// low-memory, and hardware registers.  From Bob Petersen:
	//
	//		HsHal.prc and HsExtensions.prc are the only Handspring
	//		databases that are allowed to perform "system-only" functions
	//		like accessing low memory or touching the Dragonball.  On
	//		Prism, we copy HsExtensions.prc to RAM.  Potentially either
	//		PRC could be run from RAM.
	//
	// From James Phillips:
	//
	//		The HsExtensions.prc is type 'HsPt' creator 'HsEx' and
	//		the Hal.prc is type 'HwAl' creator 'HsEx'.

	else if (creator == 'HsEx' && (type == 'HsPt' || type == 'HwAl'))
	{
		isSystemDatabase = true;
	}

	return isSystemDatabase;
}


// ---------------------------------------------------------------------------
//		¥ PrvSearchForCodeChunk
// ---------------------------------------------------------------------------

static void PrvSearchForCodeChunk (emuptr pc)
{
	// We don't already know about the code chunk containing the given PC.
	// Iterate over the RAM-based databases, looking for one containing a
	// resource containing the given PC.  When we find it, cache it for
	// subsequent searches.

	// Give us full access to memory.

	CEnableFullAccess			munge;

	// Get the directory for the RAM store.  Assumes Card 0.

	emuptr						dirP = ::PrvGetRAMDatabaseDirectory ();
	EmAliasDatabaseDirType<PAS>	dir (dirP);

	// Iterate over all the entries.

	UInt16	numDatabases = dir.numDatabases;
	for (UInt16 ii = 0; ii < numDatabases; ++ii)
	{
		// Get the database header for the current entry.

		LocalID						dbID = dir.databaseID[ii].baseID;
		emuptr						hdrP = ::PrvLocalIDToPtr (dbID);
		EmAliasDatabaseHdrType<PAS>	hdr (hdrP);

		// Skip this if it's a record database, not a resource database.

		if ((hdr.attributes & dmHdrAttrResDB) == 0)
			continue;

		// Get a reference to the list of resources in the database.

		EmAliasRecordListType<PAS>	recList (hdr.recordList);

		// Grovel over all of the resources.

		UInt16	numRecords = recList.numRecords;
		for (UInt16 jj = 0; jj < numRecords; ++jj)
		{
			EmAliasRsrcEntryType<PAS>	entry (recList.resources[jj]);

			// Convert the resource's LocalID into a pointer to the resource data.

			LocalID	entryLocalID = entry.localChunkID;
			emuptr	resourceP = ::PrvLocalIDToPtr (entryLocalID);

			// Get the heap the resource is in.  Use that to get information about
			// the chunk the resource is in.

			const EmPalmHeap*	heap = EmPalmHeap::GetHeapByPtr ((MemPtr) resourceP);

			// Can't find the heap?  Aip!

			EmAssert (heap != NULL);

			if (!heap)
				continue;

			// If not in this resource, move to the next one.

			EmPalmChunk	chunk (*heap, resourceP - heap->ChunkHeaderSize ());

			if (!chunk.BodyContains (pc))
				continue;

			// The PC is in this resource.  Tag it as a system resource
			// or not and add it to our cache of tagged resources.

			UInt32	type	= hdr.type;
			UInt32	creator	= hdr.creator;
			Bool	okType	= ::PrvIsSystemDatabase (type, creator);

			gHaveLastChunk	= true;
			gLastChunk		= EmTaggedPalmChunk (chunk, okType);

			::PrvAddTaggedChunk (gLastChunk);

			// We found what we were looking for, so we can leave now.

			return;
		}
	}
}


// ---------------------------------------------------------------------------
//		¥ MetaMemory::InRAMOSComponent
// ---------------------------------------------------------------------------
// Determine if the given memory address is in a RAM-based system component.

Bool MetaMemory::InRAMOSComponent (emuptr pc)
{
	// If any access is OK, return true.

	if (CEnableFullAccess::AccessOK ())
		return true;

	// See if we have cached the last known code chunk.  If so, see if it
	// contains the given pc.

	if (!(gHaveLastChunk && gLastChunk.BodyContains (pc)))
	{
		// No, either there's no cached chunk or it doesn't contain the pc.
		// Check our cache of known code chunks.

		::PrvLoadTaggedChunk (pc);

		if (!(gHaveLastChunk && gLastChunk.BodyContains (pc)))
		{
			// No, it's not in our cached list of chunks.  Walk the databases
			// looking for a new code chunk to add to our list.

			::PrvSearchForCodeChunk (pc);

			// If we don't have it by now, it means that the PC is not in
			// a database code resource!  That can happen with some system
			// function patch stubs.  If it does, assume it's not system code.

			if (!(gHaveLastChunk && gLastChunk.BodyContains (pc)))
			{
				return false;
			}
		}
	}

	// Return whether or not it's a system code chunk.

	return gLastChunk.fIsSystemChunk;
}