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

#include "config.h"
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <fcntl.h>
#include <string.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif

#if HOST_WIN32
#include <winsock2.h>
#include <windows.h>
#endif

#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif

#include <errno.h>
#include <sys/stat.h>

#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>  /* for WIFEXITED, WEXITSTATUS */
#endif

#include <mono/metadata/tabledefs.h>
#include <mono/metadata/class.h>
#include <mono/metadata/object.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/gc-internal.h>
#include <mono/metadata/monitor.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/mono-endian.h>
#include <mono/utils/mono-logger-internal.h>
#include <mono/utils/mono-mmap.h>
#include "mono/utils/mono-compiler.h"
#include <mono/utils/mono-counters.h>

#include "mini.h"
#include "version.h"

#ifndef DISABLE_AOT

#ifdef TARGET_WIN32
#define SHARED_EXT ".dll"
#elif ((defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__)) || defined(__MACH__)) && !defined(__linux__)
#define SHARED_EXT ".dylib"
#elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
#define SHARED_EXT ".dylib"
#else
#define SHARED_EXT ".so"
#endif

#define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
#define ROUND_DOWN(VALUE,SIZE)	((VALUE) & ~((SIZE) - 1))

typedef struct MonoAotModule {
	char *aot_name;
	/* Pointer to the Global Offset Table */
	gpointer *got;
	GHashTable *name_cache;
	GHashTable *extra_methods;
	/* Maps methods to their code */
	GHashTable *method_to_code;
	/* Maps pointers into the method info to the methods themselves */
	GHashTable *method_ref_to_method;
	MonoAssemblyName *image_names;
	char **image_guids;
	MonoAssembly *assembly;
	MonoImage **image_table;
	guint32 image_table_len;
	gboolean out_of_date;
	gboolean plt_inited;
	guint8 *mem_begin;
	guint8 *mem_end;
	guint8 *code;
	guint8 *code_end;
	guint8 *plt;
	guint8 *plt_end;
	guint8 *blob;
	gint32 *code_offsets;
#ifdef MONOTOUCH
	gpointer *method_addresses;
#endif
	/* This contains <offset, index> pairs sorted by offset */
	/* This is needed because LLVM emitted methods can be in any order */
	gint32 *sorted_code_offsets;
	gint32 sorted_code_offsets_len;
	guint32 *method_info_offsets;
	guint32 *got_info_offsets;
	guint32 *ex_info_offsets;
	guint32 *class_info_offsets;
	guint32 *methods_loaded;
	guint16 *class_name_table;
	guint32 *extra_method_table;
	guint32 *extra_method_info_offsets;
	guint32 *unbox_trampolines;
	guint32 *unbox_trampolines_end;
	guint8 *unwind_info;
	guint8 *thumb_end;

	/* Points to the mono EH data created by LLVM */
	guint8 *mono_eh_frame;

	/* Points to the trampolines */
	guint8 *trampolines [MONO_AOT_TRAMP_NUM];
	/* The first unused trampoline of each kind */
	guint32 trampoline_index [MONO_AOT_TRAMP_NUM];

	gboolean use_page_trampolines;

	MonoAotFileInfo info;

	gpointer *globals;
	MonoDl *sofile;
} MonoAotModule;

typedef struct {
	void *next;
	unsigned char *trampolines;
	unsigned char *trampolines_end;
} TrampolinePage;

static GHashTable *aot_modules;
#define mono_aot_lock() EnterCriticalSection (&aot_mutex)
#define mono_aot_unlock() LeaveCriticalSection (&aot_mutex)
static CRITICAL_SECTION aot_mutex;

/* 
 * Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
 * AOT modules registered by mono_aot_register_module ().
 */
static GHashTable *static_aot_modules;

/*
 * Maps MonoJitInfo* to the aot module they belong to, this can be different
 * from ji->method->klass->image's aot module for generic instances.
 */
static GHashTable *ji_to_amodule;

/*
 * Whenever to AOT compile loaded assemblies on demand and store them in
 * a cache under $HOME/.mono/aot-cache.
 */
static gboolean use_aot_cache = FALSE;

/*
 * Whenever to spawn a new process to AOT a file or do it in-process. Only relevant if
 * use_aot_cache is TRUE.
 */
static gboolean spawn_compiler = TRUE;

/* For debugging */
static gint32 mono_last_aot_method = -1;

static gboolean make_unreadable = FALSE;
static guint32 name_table_accesses = 0;
static guint32 n_pagefaults = 0;

/* Used to speed-up find_aot_module () */
static gsize aot_code_low_addr = (gssize)-1;
static gsize aot_code_high_addr = 0;

static GHashTable *aot_jit_icall_hash;

#ifdef MONOTOUCH
#define USE_PAGE_TRAMPOLINES ((MonoAotModule*)mono_defaults.corlib->aot_module)->use_page_trampolines
#else
#define USE_PAGE_TRAMPOLINES 0
#endif

#define mono_aot_page_lock() EnterCriticalSection (&aot_page_mutex)
#define mono_aot_page_unlock() LeaveCriticalSection (&aot_page_mutex)
static CRITICAL_SECTION aot_page_mutex;

static void
init_plt (MonoAotModule *info);

/*****************************************************/
/*                 AOT RUNTIME                       */
/*****************************************************/

/*
 * load_image:
 *
 *   Load one of the images referenced by AMODULE. Returns NULL if the image is not
 * found, and sets the loader error if SET_ERROR is TRUE.
 */
static MonoImage *
load_image (MonoAotModule *amodule, int index, gboolean set_error)
{
	MonoAssembly *assembly;
	MonoImageOpenStatus status;

	g_assert (index < amodule->image_table_len);

	if (amodule->image_table [index])
		return amodule->image_table [index];
	if (amodule->out_of_date)
		return NULL;

	assembly = mono_assembly_load (&amodule->image_names [index], amodule->assembly->basedir, &status);
	if (!assembly) {
		mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable because dependency %s is not found.\n", amodule->aot_name, amodule->image_names [index].name);
		amodule->out_of_date = TRUE;

		if (set_error) {
			char *full_name = mono_stringify_assembly_name (&amodule->image_names [index]);
			mono_loader_set_error_assembly_load (full_name, FALSE);
			g_free (full_name);
		}
		return NULL;
	}

	if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
		mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s').\n", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
		amodule->out_of_date = TRUE;
		return NULL;
	}

	amodule->image_table [index] = assembly->image;
	return assembly->image;
}

static inline gint32
decode_value (guint8 *ptr, guint8 **rptr)
{
	guint8 b = *ptr;
	gint32 len;
	
	if ((b & 0x80) == 0){
		len = b;
		++ptr;
	} else if ((b & 0x40) == 0){
		len = ((b & 0x3f) << 8 | ptr [1]);
		ptr += 2;
	} else if (b != 0xff) {
		len = ((b & 0x1f) << 24) |
			(ptr [1] << 16) |
			(ptr [2] << 8) |
			ptr [3];
		ptr += 4;
	}
	else {
		len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
		ptr += 5;
	}
	if (rptr)
		*rptr = ptr;

	//printf ("DECODE: %d.\n", len);
	return len;
}

/*
 * mono_aot_get_offset:
 *
 *   Decode an offset table emitted by emit_offset_table (), returning the INDEXth
 * entry.
 */
static guint32
mono_aot_get_offset (guint32 *table, int index)
{
	int i, group, ngroups, index_entry_size;
	int start_offset, offset, noffsets, group_size;
	guint8 *data_start, *p;
	guint32 *index32 = NULL;
	guint16 *index16 = NULL;
	
	noffsets = table [0];
	group_size = table [1];
	ngroups = table [2];
	index_entry_size = table [3];
	group = index / group_size;

	if (index_entry_size == 2) {
		index16 = (guint16*)&table [4];
		data_start = (guint8*)&index16 [ngroups];
		p = data_start + index16 [group];
	} else {
		index32 = (guint32*)&table [4];
		data_start = (guint8*)&index32 [ngroups];
		p = data_start + index32 [group];
	}

	/* offset will contain the value of offsets [group * group_size] */
	offset = start_offset = decode_value (p, &p);
	for (i = group * group_size + 1; i <= index; ++i) {
		offset += decode_value (p, &p);
	}

	//printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);

	return offset;
}

static MonoMethod*
decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);

static MonoClass*
decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf);

static MonoType*
decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf);

static MonoGenericInst*
decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
	int type_argc, i;
	MonoType **type_argv;
	MonoGenericInst *inst;
	guint8 *p = buf;

	type_argc = decode_value (p, &p);
	type_argv = g_new0 (MonoType*, type_argc);

	for (i = 0; i < type_argc; ++i) {
		MonoClass *pclass = decode_klass_ref (module, p, &p);
		if (!pclass) {
			g_free (type_argv);
			return NULL;
		}
		type_argv [i] = &pclass->byval_arg;
	}

	inst = mono_metadata_get_generic_inst (type_argc, type_argv);
	g_free (type_argv);

	*endbuf = p;

	return inst;
}

static gboolean
decode_generic_context (MonoAotModule *module, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf)
{
	guint8 *p = buf;
	guint8 *p2;
	int argc;

	p2 = p;
	argc = decode_value (p, &p);
	if (argc) {
		p = p2;
		ctx->class_inst = decode_generic_inst (module, p, &p);
		if (!ctx->class_inst)
			return FALSE;
	}
	p2 = p;
	argc = decode_value (p, &p);
	if (argc) {
		p = p2;
		ctx->method_inst = decode_generic_inst (module, p, &p);
		if (!ctx->method_inst)
			return FALSE;
	}

	*endbuf = p;
	return TRUE;
}

static MonoClass*
decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
	MonoImage *image;
	MonoClass *klass = NULL, *eklass;
	guint32 token, rank, idx;
	guint8 *p = buf;
	int reftype;

	reftype = decode_value (p, &p);
	if (reftype == 0) {
		*endbuf = p;
		return NULL;
	}

	switch (reftype) {
	case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
		idx = decode_value (p, &p);
		image = load_image (module, 0, TRUE);
		if (!image)
			return NULL;
		klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
		break;
	case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
		idx = decode_value (p, &p);
		image = load_image (module, decode_value (p, &p), TRUE);
		if (!image)
			return NULL;
		klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF + idx);
		break;
	case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
		token = decode_value (p, &p);
		image = module->assembly->image;
		if (!image)
			return NULL;
		klass = mono_class_get (image, token);
		break;
	case MONO_AOT_TYPEREF_GINST: {
		MonoClass *gclass;
		MonoGenericContext ctx;
		MonoType *type;

		gclass = decode_klass_ref (module, p, &p);
		if (!gclass)
			return NULL;
		g_assert (gclass->generic_container);

		memset (&ctx, 0, sizeof (ctx));
		ctx.class_inst = decode_generic_inst (module, p, &p);
		if (!ctx.class_inst)
			return NULL;
		type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
		klass = mono_class_from_mono_type (type);
		mono_metadata_free_type (type);
		break;
	}
	case MONO_AOT_TYPEREF_VAR: {
		MonoType *t;
		MonoGenericContainer *container = NULL;
		int type = decode_value (p, &p);
		int num = decode_value (p, &p);
		gboolean has_container = decode_value (p, &p);
		int serial = 0;

		if (has_container) {
			gboolean is_method = decode_value (p, &p);
			
			if (is_method) {
				MonoMethod *method_def;
				g_assert (type == MONO_TYPE_MVAR);
				method_def = decode_resolve_method_ref (module, p, &p);
				if (!method_def)
					return NULL;

				container = mono_method_get_generic_container (method_def);
			} else {
				MonoClass *class_def;
				g_assert (type == MONO_TYPE_VAR);
				class_def = decode_klass_ref (module, p, &p);
				if (!class_def)
					return NULL;

				container = class_def->generic_container;
			}
		} else {
			serial = decode_value (p, &p);
		}

		// FIXME: Memory management
		t = g_new0 (MonoType, 1);
		t->type = type;
		if (container) {
			t->data.generic_param = mono_generic_container_get_param (container, num);
			g_assert (serial == 0);
		} else {
			/* Anonymous */
			MonoGenericParam *par = (MonoGenericParam*)g_new0 (MonoGenericParamFull, 1);
			par->num = num;
			par->serial = serial;
			// FIXME:
			par->image = mono_defaults.corlib;
			t->data.generic_param = par;
		}

		// FIXME: Maybe use types directly to avoid
		// the overhead of creating MonoClass-es
		klass = mono_class_from_mono_type (t);

		g_free (t);
		break;
	}
	case MONO_AOT_TYPEREF_ARRAY:
		/* Array */
		rank = decode_value (p, &p);
		eklass = decode_klass_ref (module, p, &p);
		klass = mono_array_class_get (eklass, rank);
		break;
	case MONO_AOT_TYPEREF_PTR: {
		MonoType *t;

		t = decode_type (module, p, &p);
		if (!t)
			return NULL;
		klass = mono_class_from_mono_type (t);
		g_free (t);
		break;
	}
	case MONO_AOT_TYPEREF_BLOB_INDEX: {
		guint32 offset = decode_value (p, &p);
		guint8 *p2;

		p2 = module->blob + offset;
		klass = decode_klass_ref (module, p2, &p2);
		break;
	}
	default:
		g_assert_not_reached ();
	}
	g_assert (klass);
	//printf ("BLA: %s\n", mono_type_full_name (&klass->byval_arg));
	*endbuf = p;
	return klass;
}

static MonoClassField*
decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
	MonoClass *klass = decode_klass_ref (module, buf, &buf);
	guint32 token;
	guint8 *p = buf;

	if (!klass)
		return NULL;

	token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);

	*endbuf = p;

	return mono_class_get_field (klass, token);
}

/*
 * Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
 * memory.
 */
static MonoType*
decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
	guint8 *p = buf;
	MonoType *t;

	t = g_malloc0 (sizeof (MonoType));

	while (TRUE) {
		if (*p == MONO_TYPE_PINNED) {
			t->pinned = TRUE;
			++p;
		} else if (*p == MONO_TYPE_BYREF) {
			t->byref = TRUE;
			++p;
		} else {
			break;
		}
	}

	t->type = *p;
	++p;

	switch (t->type) {
	case MONO_TYPE_VOID:
	case MONO_TYPE_BOOLEAN:
	case MONO_TYPE_CHAR:
	case MONO_TYPE_I1:
	case MONO_TYPE_U1:
	case MONO_TYPE_I2:
	case MONO_TYPE_U2:
	case MONO_TYPE_I4:
	case MONO_TYPE_U4:
	case MONO_TYPE_I8:
	case MONO_TYPE_U8:
	case MONO_TYPE_R4:
	case MONO_TYPE_R8:
	case MONO_TYPE_I:
	case MONO_TYPE_U:
	case MONO_TYPE_STRING:
	case MONO_TYPE_OBJECT:
	case MONO_TYPE_TYPEDBYREF:
		break;
	case MONO_TYPE_VALUETYPE:
	case MONO_TYPE_CLASS:
		t->data.klass = decode_klass_ref (module, p, &p);
		break;
	case MONO_TYPE_SZARRAY:
		t->data.klass = decode_klass_ref (module, p, &p);

		if (!t->data.klass)
			return NULL;
		break;
	case MONO_TYPE_PTR:
		t->data.type = decode_type (module, p, &p);
		break;
	case MONO_TYPE_GENERICINST: {
		MonoClass *gclass;
		MonoGenericContext ctx;
		MonoType *type;
		MonoClass *klass;

		gclass = decode_klass_ref (module, p, &p);
		if (!gclass)
			return NULL;
		g_assert (gclass->generic_container);

		memset (&ctx, 0, sizeof (ctx));
		ctx.class_inst = decode_generic_inst (module, p, &p);
		if (!ctx.class_inst)
			return NULL;
		type = mono_class_inflate_generic_type (&gclass->byval_arg, &ctx);
		klass = mono_class_from_mono_type (type);
		t->data.generic_class = klass->generic_class;
		break;
	}
	case MONO_TYPE_ARRAY: {
		MonoArrayType *array;
		int i;

		// FIXME: memory management
		array = g_new0 (MonoArrayType, 1);
		array->eklass = decode_klass_ref (module, p, &p);
		if (!array->eklass)
			return NULL;
		array->rank = decode_value (p, &p);
		array->numsizes = decode_value (p, &p);

		if (array->numsizes)
			array->sizes = g_malloc0 (sizeof (int) * array->numsizes);
		for (i = 0; i < array->numsizes; ++i)
			array->sizes [i] = decode_value (p, &p);

		array->numlobounds = decode_value (p, &p);
		if (array->numlobounds)
			array->lobounds = g_malloc0 (sizeof (int) * array->numlobounds);
		for (i = 0; i < array->numlobounds; ++i)
			array->lobounds [i] = decode_value (p, &p);
		t->data.array = array;
		break;
	}
	case MONO_TYPE_VAR:
	case MONO_TYPE_MVAR: {
		MonoClass *klass = decode_klass_ref (module, p, &p);
		if (!klass)
			return NULL;
		t->data.generic_param = klass->byval_arg.data.generic_param;
		break;
	}
	default:
		g_assert_not_reached ();
	}

	*endbuf = p;

	return t;
}

// FIXME: Error handling, memory management

static MonoMethodSignature*
decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
{
	MonoMethodSignature *sig;
	guint32 flags;
	int i, param_count, call_conv, gen_param_count = 0;
	guint8 *p = buf;
	gboolean hasthis, explicit_this, has_gen_params;

	flags = *p;
	p ++;
	has_gen_params = (flags & 0x10) != 0;
	hasthis = (flags & 0x20) != 0;
	explicit_this = (flags & 0x40) != 0;
	call_conv = flags & 0x0F;

	if (has_gen_params)
		gen_param_count = decode_value (p, &p);
	param_count = decode_value (p, &p);
	if (target && param_count != target->param_count)
		return NULL;
	sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
	sig->param_count = param_count;
	sig->sentinelpos = -1;
	sig->hasthis = hasthis;
	sig->explicit_this = explicit_this;
	sig->call_convention = call_conv;
	sig->param_count = param_count;
	sig->ret = decode_type (module, p, &p);
	for (i = 0; i < param_count; ++i) {
		if (*p == MONO_TYPE_SENTINEL) {
			g_assert (sig->call_convention == MONO_CALL_VARARG);
			sig->sentinelpos = i;
			p ++;
		}
		sig->params [i] = decode_type (module, p, &p);
	}

	if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
		sig->sentinelpos = sig->param_count;

	*endbuf = p;

	return sig;
}

static MonoMethodSignature*
decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
	return decode_signature_with_target (module, NULL, buf, endbuf);
}

static gboolean
sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
{
	MonoMethodSignature *sig;
	gboolean res;
	guint8 *p = buf;
	
	sig = decode_signature_with_target (module, mono_method_signature (target), p, &p);
	res = sig && mono_metadata_signature_equal (mono_method_signature (target), sig);
	g_free (sig);
	*endbuf = p;
	return res;
}

/* Stores information returned by decode_method_ref () */
typedef struct {
	MonoImage *image;
	guint32 token;
	MonoMethod *method;
	gboolean no_aot_trampoline;
} MethodRef;

/*
 * decode_method_ref_with_target:
 *
 *   Decode a method reference, storing the image/token into a MethodRef structure.
 * This avoids loading metadata for the method if the caller does not need it. If the method has
 * no token, then it is loaded from metadata and ref->method is set to the method instance.
 * If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
 *  couldn't resolve to TARGET, and return FALSE.
 * There are some kinds of method references which only support a non-null TARGET.
 * This means that its not possible to decode this into a method, only to check
 * that the method reference matches a given method. This is normally not a problem
 * as these wrappers only occur in the extra_methods table, where we already have
 * a method we want to lookup.
 */
static gboolean
decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf)
{
	guint32 image_index, value;
	MonoImage *image = NULL;
	guint8 *p = buf;

	memset (ref, 0, sizeof (MethodRef));

	value = decode_value (p, &p);
	image_index = value >> 24;

	if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
		ref->no_aot_trampoline = TRUE;
		value = decode_value (p, &p);
		image_index = value >> 24;
	}

	if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC || image_index == MONO_AOT_METHODREF_GINST) {
		if (target && target->wrapper_type)
			return FALSE;
	}

	if (image_index == MONO_AOT_METHODREF_WRAPPER) {
		guint32 wrapper_type;

		wrapper_type = decode_value (p, &p);

		if (target && target->wrapper_type != wrapper_type)
			return FALSE;

		/* Doesn't matter */
		image = mono_defaults.corlib;

		switch (wrapper_type) {
#ifndef DISABLE_REMOTING
		case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: {
			MonoMethod *m = decode_resolve_method_ref (module, p, &p);

			if (!m)
				return FALSE;
			mono_class_init (m->klass);
			ref->method = mono_marshal_get_remoting_invoke_with_check (m);
			break;
		}
		case MONO_WRAPPER_PROXY_ISINST: {
			MonoClass *klass = decode_klass_ref (module, p, &p);
			if (!klass)
				return FALSE;
			ref->method = mono_marshal_get_proxy_cancast (klass);
			break;
		}
		case MONO_WRAPPER_LDFLD:
		case MONO_WRAPPER_LDFLDA:
		case MONO_WRAPPER_STFLD:
		case MONO_WRAPPER_ISINST: {
			MonoClass *klass = decode_klass_ref (module, p, &p);
			if (!klass)
				return FALSE;
			if (wrapper_type == MONO_WRAPPER_LDFLD)
				ref->method = mono_marshal_get_ldfld_wrapper (&klass->byval_arg);
			else if (wrapper_type == MONO_WRAPPER_LDFLDA)
				ref->method = mono_marshal_get_ldflda_wrapper (&klass->byval_arg);
			else if (wrapper_type == MONO_WRAPPER_STFLD)
				ref->method = mono_marshal_get_stfld_wrapper (&klass->byval_arg);
			else if (wrapper_type == MONO_WRAPPER_ISINST)
				ref->method = mono_marshal_get_isinst (klass);
			else
				g_assert_not_reached ();
			break;
		}
		case MONO_WRAPPER_LDFLD_REMOTE:
			ref->method = mono_marshal_get_ldfld_remote_wrapper (NULL);
			break;
		case MONO_WRAPPER_STFLD_REMOTE:
			ref->method = mono_marshal_get_stfld_remote_wrapper (NULL);
			break;
#endif
		case MONO_WRAPPER_ALLOC: {
			int atype = decode_value (p, &p);

			ref->method = mono_gc_get_managed_allocator_by_type (atype);
			g_assert (ref->method);
			break;
		}
		case MONO_WRAPPER_WRITE_BARRIER:
			ref->method = mono_gc_get_write_barrier ();
			break;
		case MONO_WRAPPER_STELEMREF: {
			int subtype = decode_value (p, &p);

			if (subtype == WRAPPER_SUBTYPE_NONE) {
				ref->method = mono_marshal_get_stelemref ();
			} else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
				int kind;
				WrapperInfo *info;
				
				kind = decode_value (p, &p);

				/* Can't decode this */
				if (!target)
					return FALSE;
				if (target->wrapper_type == MONO_WRAPPER_STELEMREF) {
					info = mono_marshal_get_wrapper_info (target);

					g_assert (info);
					if (info->subtype == subtype && info->d.virtual_stelemref.kind == kind)
						ref->method = target;
					else
						return FALSE;
				} else {
					return FALSE;
				}
			} else {
				g_assert_not_reached ();
			}
			break;
		}
		case MONO_WRAPPER_SYNCHRONIZED: {
			MonoMethod *m = decode_resolve_method_ref (module, p, &p);

			if (!m)
				return FALSE;
			ref->method = mono_marshal_get_synchronized_wrapper (m);
			break;
		}
		case MONO_WRAPPER_UNKNOWN: {
			MonoMethodDesc *desc;
			MonoMethod *orig_method;
			int subtype = decode_value (p, &p);

			if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
				MonoClass *klass = decode_klass_ref (module, p, &p);
				
				if (!klass)
					return FALSE;

				if (!target)
					return FALSE;
				if (klass != target->klass)
					return FALSE;

				if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
					if (strcmp (target->name, "PtrToStructure"))
						return FALSE;
					ref->method = mono_marshal_get_ptr_to_struct (klass);
				} else {
					if (strcmp (target->name, "StructureToPtr"))
						return FALSE;
					ref->method = mono_marshal_get_struct_to_ptr (klass);
				}
			} else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
				MonoMethod *m = decode_resolve_method_ref (module, p, &p);

				if (!m)
					return FALSE;
				ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
			} else if (subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
				MonoMethod *m = decode_resolve_method_ref (module, p, &p);

				if (!m)
					return FALSE;
				ref->method = mono_marshal_get_array_accessor_wrapper (m);
			} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN) {
				ref->method = mono_marshal_get_gsharedvt_in_wrapper ();
			} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
				ref->method = mono_marshal_get_gsharedvt_out_wrapper ();
			} else {
				if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER)
					desc = mono_method_desc_new ("Monitor:Enter", FALSE);
				else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_EXIT)
					desc = mono_method_desc_new ("Monitor:Exit", FALSE);
				else if (subtype == WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4)
					desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
				else
					g_assert_not_reached ();
				orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
				g_assert (orig_method);
				mono_method_desc_free (desc);
				ref->method = mono_monitor_get_fast_path (orig_method);
			}
			break;
		}
		case MONO_WRAPPER_MANAGED_TO_MANAGED: {
			int subtype = decode_value (p, &p);

			if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
				int rank = decode_value (p, &p);
				int elem_size = decode_value (p, &p);

				ref->method = mono_marshal_get_array_address (rank, elem_size);
			} else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
				WrapperInfo *info;
				MonoMethod *m;

				m = decode_resolve_method_ref (module, p, &p);
				if (!m)
					return FALSE;

				if (!target)
					return FALSE;
				g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);

				info = mono_marshal_get_wrapper_info (target);
				if (info && info->subtype == subtype && info->d.string_ctor.method == m)
					ref->method = target;
				else
					return FALSE;
			}
			break;
		}
		case MONO_WRAPPER_MANAGED_TO_NATIVE: {
			MonoMethod *m;
			int subtype = decode_value (p, &p);
			char *name;

			if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
				if (!target)
					return FALSE;

				name = (char*)p;
				if (strcmp (target->name, name) != 0)
					return FALSE;
				ref->method = target;
			} else {
				m = decode_resolve_method_ref (module, p, &p);

				if (!m)
					return FALSE;

				/* This should only happen when looking for an extra method */
				if (!target)
					return FALSE;
				if (mono_marshal_method_from_wrapper (target) == m)
					ref->method = target;
				else
					return FALSE;
			}
			break;
		}
		case MONO_WRAPPER_CASTCLASS: {
			int subtype = decode_value (p, &p);

			if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
				ref->method = mono_marshal_get_castclass_with_cache ();
			else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
				ref->method = mono_marshal_get_isinst_with_cache ();
			else
				g_assert_not_reached ();
			break;
		}
		case MONO_WRAPPER_RUNTIME_INVOKE: {
			int subtype = decode_value (p, &p);

			if (!target)
				return FALSE;

			if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
				if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
					return FALSE;
				ref->method = target;
			} else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
				/* Direct wrapper */
				MonoMethod *m = decode_resolve_method_ref (module, p, &p);

				if (!m)
					return FALSE;
				ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
			} else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
				/* Virtual direct wrapper */
				MonoMethod *m = decode_resolve_method_ref (module, p, &p);

				if (!m)
					return FALSE;
				ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
			} else {
				MonoMethodSignature *sig;
				WrapperInfo *info;

				sig = decode_signature_with_target (module, NULL, p, &p);
				info = mono_marshal_get_wrapper_info (target);
				g_assert (info);

				if (info->subtype != subtype)
					return FALSE;
				g_assert (info->d.runtime_invoke.sig);
				if (mono_metadata_signature_equal (sig, info->d.runtime_invoke.sig))
					ref->method = target;
				else
					return FALSE;
			}
			break;
		}
		case MONO_WRAPPER_DELEGATE_INVOKE:
		case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
		case MONO_WRAPPER_DELEGATE_END_INVOKE: {
			gboolean is_inflated = decode_value (p, &p);
			WrapperSubtype subtype;

			if (is_inflated) {
				MonoClass *klass;
				MonoMethod *invoke, *wrapper;

				klass = decode_klass_ref (module, p, &p);
				if (!klass)
					return FALSE;

				switch (wrapper_type) {
				case MONO_WRAPPER_DELEGATE_INVOKE:
					invoke = mono_get_delegate_invoke (klass);
					wrapper = mono_marshal_get_delegate_invoke (invoke, NULL);
					break;
				case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
					invoke = mono_get_delegate_begin_invoke (klass);
					wrapper = mono_marshal_get_delegate_begin_invoke (invoke);
					break;
				case MONO_WRAPPER_DELEGATE_END_INVOKE:
					invoke = mono_get_delegate_end_invoke (klass);
					wrapper = mono_marshal_get_delegate_end_invoke (invoke);
					break;
				default:
					g_assert_not_reached ();
					break;
				}
				if (target && wrapper != target)
					return FALSE;
				ref->method = wrapper;
			} else {
				/*
				 * These wrappers are associated with a signature, not with a method.
				 * Since we can't decode them into methods, they need a target method.
				 */
				if (!target)
					return FALSE;

				if (wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
					WrapperInfo *info;

					subtype = decode_value (p, &p);
					info = mono_marshal_get_wrapper_info (target);
					if (info) {
						if (info->subtype != subtype)
							return FALSE;
					} else {
						if (subtype != WRAPPER_SUBTYPE_NONE)
							return FALSE;
					}
				}
				if (sig_matches_target (module, target, p, &p))
					ref->method = target;
				else
					return FALSE;
			}
			break;
		}
		case MONO_WRAPPER_NATIVE_TO_MANAGED: {
			MonoMethod *m;
			MonoClass *klass;

			m = decode_resolve_method_ref (module, p, &p);
			if (!m)
				return FALSE;
			klass = decode_klass_ref (module, p, &p);
			if (!klass)
				return FALSE;
			ref->method = mono_marshal_get_managed_wrapper (m, klass, 0);
			break;
		}
		default:
			g_assert_not_reached ();
		}
	} else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
		image_index = decode_value (p, &p);
		ref->token = decode_value (p, &p);

		image = load_image (module, image_index, TRUE);
		if (!image)
			return FALSE;
	} else if (image_index == MONO_AOT_METHODREF_GINST) {
		MonoClass *klass;
		MonoGenericContext ctx;

		/* 
		 * These methods do not have a token which resolves them, so we 
		 * resolve them immediately.
		 */
		klass = decode_klass_ref (module, p, &p);
		if (!klass)
			return FALSE;

		if (target && target->klass != klass)
			return FALSE;

		image_index = decode_value (p, &p);
		ref->token = decode_value (p, &p);

		image = load_image (module, image_index, TRUE);
		if (!image)
			return FALSE;

		ref->method = mono_get_method_full (image, ref->token, NULL, NULL);
		if (!ref->method)
			return FALSE;

		memset (&ctx, 0, sizeof (ctx));

		if (FALSE && klass->generic_class) {
			ctx.class_inst = klass->generic_class->context.class_inst;
			ctx.method_inst = NULL;
 
			ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
		}			

		memset (&ctx, 0, sizeof (ctx));

		if (!decode_generic_context (module, &ctx, p, &p))
			return FALSE;

		ref->method = mono_class_inflate_generic_method_full (ref->method, klass, &ctx);
	} else if (image_index == MONO_AOT_METHODREF_ARRAY) {
		MonoClass *klass;
		int method_type;

		klass = decode_klass_ref (module, p, &p);
		if (!klass)
			return FALSE;
		method_type = decode_value (p, &p);
		switch (method_type) {
		case 0:
			ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank);
			break;
		case 1:
			ref->method = mono_class_get_method_from_name (klass, ".ctor", klass->rank * 2);
			break;
		case 2:
			ref->method = mono_class_get_method_from_name (klass, "Get", -1);
			break;
		case 3:
			ref->method = mono_class_get_method_from_name (klass, "Address", -1);
			break;
		case 4:
			ref->method = mono_class_get_method_from_name (klass, "Set", -1);
			break;
		default:
			g_assert_not_reached ();
		}
	} else {
		if (image_index == MONO_AOT_METHODREF_LARGE_IMAGE_INDEX) {
			image_index = decode_value (p, &p);
			value = decode_value (p, &p);
		}

		ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);

		image = load_image (module, image_index, TRUE);
		if (!image)
			return FALSE;
	}

	*endbuf = p;

	ref->image = image;

	return TRUE;
}

static gboolean
decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf)
{
	return decode_method_ref_with_target (module, ref, NULL, buf, endbuf);
}

/*
 * decode_resolve_method_ref_with_target:
 *
 *   Similar to decode_method_ref, but resolve and return the method itself.
 */
static MonoMethod*
decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
{
	MethodRef ref;
	gboolean res;

	res = decode_method_ref_with_target (module, &ref, target, buf, endbuf);
	if (!res)
		return NULL;
	if (ref.method)
		return ref.method;
	if (!ref.image)
		return NULL;
	return mono_get_method (ref.image, ref.token, NULL);
}

static MonoMethod*
decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
	return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf);
}

static void
create_cache_structure (void)
{
	const char *home;
	char *tmp;
	int err;

	home = g_get_home_dir ();
	if (!home)
		return;

	tmp = g_build_filename (home, ".mono", NULL);
	if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
		mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
#ifdef HOST_WIN32
		err = mkdir (tmp);
#else
		err = mkdir (tmp, 0777);
#endif
		if (err) {
			mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
			g_free (tmp);
			return;
		}
	}
	g_free (tmp);
	tmp = g_build_filename (home, ".mono", "aot-cache", NULL);
	if (!g_file_test (tmp, G_FILE_TEST_IS_DIR)) {
		mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT creating directory %s", tmp);
#ifdef HOST_WIN32
		err = mkdir (tmp);
#else
		err = mkdir (tmp, 0777);
#endif
		if (err) {
			mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed: %s", g_strerror (errno));
			g_free (tmp);
			return;
		}
	}
	g_free (tmp);
}

/*
 * load_aot_module_from_cache:
 *
 *  Experimental code to AOT compile loaded assemblies on demand. 
 *
 * FIXME: 
 * - Add environment variable MONO_AOT_CACHE_OPTIONS
 * - Add options for controlling the cache size
 * - Handle full cache by deleting old assemblies lru style
 * - Add options for excluding assemblies during development
 * - Maybe add a threshold after an assembly is AOT compiled
 * - invoking a new mono process is a security risk
 * - recompile the AOT module if one of its dependencies changes
 */
static MonoDl*
load_aot_module_from_cache (MonoAssembly *assembly, char **aot_name)
{
	char *fname, *cmd, *tmp2, *aot_options;
	const char *home;
	MonoDl *module;
	gboolean res;
	gchar *out, *err;
	gint exit_status;

	*aot_name = NULL;

	if (assembly->image->dynamic)
		return NULL;

	create_cache_structure ();

	home = g_get_home_dir ();

	tmp2 = g_strdup_printf ("%s-%s%s", assembly->image->assembly_name, assembly->image->guid, SHARED_EXT);
	fname = g_build_filename (home, ".mono", "aot-cache", tmp2, NULL);
	*aot_name = fname;
	g_free (tmp2);

	mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT trying to load from cache: '%s'.", fname);
	module = mono_dl_open (fname, MONO_DL_LAZY, NULL);

	if (!module) {
		mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT not found.");

		mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT precompiling assembly '%s'... ", assembly->image->name);

		aot_options = g_strdup_printf ("outfile=%s", fname);

		if (spawn_compiler) {
			/* FIXME: security */
			/* FIXME: Has to pass the assembly loading path to the child process */
			cmd = g_strdup_printf ("mono -O=all --aot=%s %s", aot_options, assembly->image->name);

			res = g_spawn_command_line_sync (cmd, &out, &err, &exit_status, NULL);

#if !defined(HOST_WIN32) && !defined(__ppc__) && !defined(__ppc64__) && !defined(__powerpc__)
			if (res) {
				if (!WIFEXITED (exit_status) && (WEXITSTATUS (exit_status) == 0))
					mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed: %s.", err);
				else
					mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
				g_free (out);
				g_free (err);
			}
#endif
			g_free (cmd);
		} else {
			res = mono_compile_assembly (assembly, mono_parse_default_optimizations (NULL), aot_options);
			if (!res) {
				mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT failed.");
			} else {
				mono_trace (G_LOG_LEVEL_MESSAGE, MONO_TRACE_AOT, "AOT succeeded.");
			}
		}

		module = mono_dl_open (fname, MONO_DL_LAZY, NULL);

		g_free (aot_options);
	}

	return module;
}

static void
find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
{
	if (globals) {
		int global_index;
		guint16 *table, *entry;
		guint16 table_size;
		guint32 hash;		
		char *symbol = (char*)name;

#ifdef TARGET_MACH
		symbol = g_strdup_printf ("_%s", name);
#endif

		/* The first entry points to the hash */
		table = globals [0];
		globals ++;

		table_size = table [0];
		table ++;

		hash = mono_metadata_str_hash (symbol) % table_size;

		entry = &table [hash * 2];

		/* Search the hash for the index into the globals table */
		global_index = -1;
		while (entry [0] != 0) {
			guint32 index = entry [0] - 1;
			guint32 next = entry [1];

			//printf ("X: %s %s\n", (char*)globals [index * 2], name);

			if (!strcmp (globals [index * 2], symbol)) {
				global_index = index;
				break;
			}

			if (next != 0) {
				entry = &table [next * 2];
			} else {
				break;
			}
		}

		if (global_index != -1)
			*value = globals [global_index * 2 + 1];
		else
			*value = NULL;

		if (symbol != name)
			g_free (symbol);
	} else {
		char *err = mono_dl_symbol (module, name, value);

		if (err)
			g_free (err);
	}
}

static gboolean
check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, char **out_msg)
{
	char *build_info;
	char *msg = NULL;
	gboolean usable = TRUE;
	gboolean full_aot;
	guint8 *blob;
	guint32 excluded_cpu_optimizations;

	if (strcmp (assembly->image->guid, info->assembly_guid)) {
		msg = g_strdup_printf ("doesn't match assembly");
		usable = FALSE;
	}

	build_info = mono_get_runtime_build_info ();
	if (strlen (info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
		msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
		usable = FALSE;
	}
	g_free (build_info);

	full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;

	if (mono_aot_only && !full_aot) {
		msg = g_strdup_printf ("not compiled with --aot=full");
		usable = FALSE;
	}
	if (!mono_aot_only && full_aot) {
		msg = g_strdup_printf ("compiled with --aot=full");
		usable = FALSE;
	}
#ifdef TARGET_ARM
	/* mono_arch_find_imt_method () requires this */
	if ((info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && !mono_use_llvm) {
		msg = g_strdup_printf ("compiled against LLVM");
		usable = FALSE;
	}
	if (!(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM) && mono_use_llvm) {
		msg = g_strdup_printf ("not compiled against LLVM");
		usable = FALSE;
	}
#endif
	if (mini_get_debug_options ()->mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot) {
		msg = g_strdup_printf ("not compiled for debugging");
		usable = FALSE;
	}

	mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
	if (info->opts & excluded_cpu_optimizations) {
		msg = g_strdup_printf ("compiled with unsupported CPU optimizations");
		usable = FALSE;
	}

	if (!mono_aot_only && (info->simd_opts & ~mono_arch_cpu_enumerate_simd_versions ())) {
		msg = g_strdup_printf ("compiled with unsupported SIMD extensions");
		usable = FALSE;
	}

	blob = info->blob;

	if (info->gc_name_index != -1) {
		char *gc_name = (char*)&blob [info->gc_name_index];
		const char *current_gc_name = mono_gc_get_gc_name ();

		if (strcmp (current_gc_name, gc_name) != 0) {
			msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
			usable = FALSE;
		}
	}

	*out_msg = msg;
	return usable;
}

/* This returns an interop address */
static void*
get_arm_bl_target (guint32 *ins_addr)
{
#ifdef TARGET_ARM
	guint32 ins = *ins_addr;
	gint32 offset;

	if ((ins >> ARMCOND_SHIFT) == ARMCOND_NV) {
		/* blx */
		offset = (((int)(((ins & 0xffffff) << 1) | ((ins >> 24) & 0x1))) << 7) >> 7;
		return (char*)ins_addr + (offset * 2) + 8 + 1;
	} else {
		offset = (((int)ins & 0xffffff) << 8) >> 8;
		return (char*)ins_addr + (offset * 4) + 8;
	}
#else
	g_assert_not_reached ();
	return NULL;
#endif
}

static void
load_aot_module (MonoAssembly *assembly, gpointer user_data)
{
	char *aot_name;
	MonoAotModule *amodule;
	MonoDl *sofile;
	gboolean usable = TRUE;
	char *version_symbol = NULL;
	char *msg = NULL;
	gpointer *globals = NULL;
	MonoAotFileInfo *info = NULL;
	int i, version;
	guint8 *blob;
	gboolean do_load_image = TRUE;
	int align_double, align_int64;

	if (mono_compile_aot)
		return;

	if (assembly->image->aot_module)
		/* 
		 * Already loaded. This can happen because the assembly loading code might invoke
		 * the assembly load hooks multiple times for the same assembly.
		 */
		return;

	if (assembly->image->dynamic || assembly->ref_only)
		return;

	if (mono_security_cas_enabled ())
		return;

	mono_aot_lock ();
	if (static_aot_modules)
		info = g_hash_table_lookup (static_aot_modules, assembly->aname.name);
	else
		info = NULL;
	mono_aot_unlock ();

	if (info) {
		/* Statically linked AOT module */
		sofile = NULL;
		aot_name = g_strdup_printf ("%s", assembly->aname.name);
		mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.\n", aot_name);
		globals = info->globals;
	} else {
		if (use_aot_cache)
			sofile = load_aot_module_from_cache (assembly, &aot_name);
		else {
			char *err;
			aot_name = g_strdup_printf ("%s%s", assembly->image->name, SHARED_EXT);

			sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);

			if (!sofile) {
				mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT failed to load AOT module %s: %s\n", aot_name, err);
				g_free (err);
			}
		}
	}

	if (!sofile && !globals) {
		if (mono_aot_only && assembly->image->tables [MONO_TABLE_METHOD].rows) {
			fprintf (stderr, "Failed to load AOT module '%s' in aot-only mode.\n", aot_name);
			exit (1);
		}
		g_free (aot_name);
		return;
	}

	if (!info) {
		find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
		find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
	}

	if (version_symbol) {
		/* Old file format */
		version = atoi (version_symbol);
	} else {
		g_assert (info);
		version = info->version;
	}

	if (version != MONO_AOT_FILE_VERSION) {
		msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
		usable = FALSE;
	} else {
		usable = check_usable (assembly, info, &msg);
	}

	if (!usable) {
		if (mono_aot_only) {
			fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode: %s.\n", aot_name, msg);
			exit (1);
		} else {
			mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT module %s is unusable: %s.\n", aot_name, msg);
		}
		g_free (msg);
		g_free (aot_name);
		if (sofile)
			mono_dl_close (sofile);
		assembly->image->aot_module = NULL;
		return;
	}

#if defined (TARGET_ARM) && defined (TARGET_MACH)
	{
		MonoType t;
		int align = 0;

		memset (&t, 0, sizeof (MonoType));
		t.type = MONO_TYPE_R8;
		mono_type_size (&t, &align);
		align_double = align;

		memset (&t, 0, sizeof (MonoType));
		t.type = MONO_TYPE_I8;
		align_int64 = align;
	}
#else
	align_double = __alignof__ (double);
	align_int64 = __alignof__ (gint64);
#endif

	/* Sanity check */
	g_assert (info->double_align == align_double);
	g_assert (info->long_align == align_int64);
	g_assert (info->generic_tramp_num == MONO_TRAMPOLINE_NUM);

	blob = info->blob;

	amodule = g_new0 (MonoAotModule, 1);
	amodule->aot_name = aot_name;
	amodule->assembly = assembly;

	memcpy (&amodule->info, info, sizeof (*info));

	amodule->got = amodule->info.got;
	amodule->got [0] = assembly->image;
	amodule->globals = globals;
	amodule->sofile = sofile;
	amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
	amodule->blob = blob;

	/* Read image table */
	{
		guint32 table_len, i;
		char *table = NULL;

		table = info->image_table;
		g_assert (table);

		table_len = *(guint32*)table;
		table += sizeof (guint32);
		amodule->image_table = g_new0 (MonoImage*, table_len);
		amodule->image_names = g_new0 (MonoAssemblyName, table_len);
		amodule->image_guids = g_new0 (char*, table_len);
		amodule->image_table_len = table_len;
		for (i = 0; i < table_len; ++i) {
			MonoAssemblyName *aname = &(amodule->image_names [i]);

			aname->name = g_strdup (table);
			table += strlen (table) + 1;
			amodule->image_guids [i] = g_strdup (table);
			table += strlen (table) + 1;
			if (table [0] != 0)
				aname->culture = g_strdup (table);
			table += strlen (table) + 1;
			memcpy (aname->public_key_token, table, strlen (table) + 1);
			table += strlen (table) + 1;			

			table = ALIGN_PTR_TO (table, 8);
			aname->flags = *(guint32*)table;
			table += 4;
			aname->major = *(guint32*)table;
			table += 4;
			aname->minor = *(guint32*)table;
			table += 4;
			aname->build = *(guint32*)table;
			table += 4;
			aname->revision = *(guint32*)table;
			table += 4;
		}
	}

	amodule->code_offsets = info->code_offsets;
#ifdef MONOTOUCH
	amodule->method_addresses = info->method_addresses;
#endif
	amodule->code = info->methods;
#ifdef TARGET_ARM
	/* Mask out thumb interop bit */
	amodule->code = (void*)((mgreg_t)amodule->code & ~1);
#endif
	amodule->code_end = info->methods_end;
	amodule->method_info_offsets = info->method_info_offsets;
	amodule->ex_info_offsets = info->ex_info_offsets;
	amodule->class_info_offsets = info->class_info_offsets;
	amodule->class_name_table = info->class_name_table;
	amodule->extra_method_table = info->extra_method_table;
	amodule->extra_method_info_offsets = info->extra_method_info_offsets;
	amodule->unbox_trampolines = info->unbox_trampolines;
	amodule->unbox_trampolines_end = info->unbox_trampolines_end;
	amodule->got_info_offsets = info->got_info_offsets;
	amodule->unwind_info = info->unwind_info;
	amodule->mem_end = info->mem_end;
	amodule->mem_begin = amodule->code;
	amodule->plt = info->plt;
	amodule->plt_end = info->plt_end;
	amodule->mono_eh_frame = info->mono_eh_frame;
	amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = info->specific_trampolines;
	amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = info->static_rgctx_trampolines;
	amodule->trampolines [MONO_AOT_TRAMP_IMT_THUNK] = info->imt_thunks;
	amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = info->gsharedvt_arg_trampolines;
	amodule->thumb_end = info->thumb_end;

#ifdef MONOTOUCH
	if (info->flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) {
		/* Compute code_offsets from the method addresses */
		amodule->code_offsets = g_malloc0 (amodule->info.nmethods * sizeof (gint32));
		for (i = 0; i < amodule->info.nmethods; ++i) {
			/* method_addresses () contains a table of branches, since the ios linker can update those correctly */
			void *addr = get_arm_bl_target ((guint32*)(amodule->method_addresses + i));

			if (addr == amodule->method_addresses)
				amodule->code_offsets [i] = 0xffffffff;
			else
				amodule->code_offsets [i] = (char*)addr - (char*)amodule->code;
		}
	}
#endif

	if (make_unreadable) {
#ifndef TARGET_WIN32
		guint8 *addr;
		guint8 *page_start, *page_end;
		int err, len;

		addr = amodule->mem_begin;
		len = amodule->mem_end - amodule->mem_begin;

		/* Round down in both directions to avoid modifying data which is not ours */
		page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
		page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
		if (page_end > page_start) {
			err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
			g_assert (err == 0);
		}
#endif
	}

	mono_aot_lock ();

	aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->code);
	aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->code_end);

	g_hash_table_insert (aot_modules, assembly, amodule);
	mono_aot_unlock ();

	mono_jit_info_add_aot_module (assembly->image, amodule->code, amodule->code_end);

	assembly->image->aot_module = amodule;

	if (mono_aot_only) {
		char *code;
		find_symbol (amodule->sofile, amodule->globals, "specific_trampolines_page", (gpointer *)&code);
		amodule->use_page_trampolines = code != NULL;
		/*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
		if (mono_defaults.corlib) {
			/* The second got slot contains the mscorlib got addr */
			MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;

			amodule->got [1] = mscorlib_amodule->got;
		} else {
			amodule->got [1] = amodule->got;
		}
	}

	if (mono_gc_is_moving ()) {
		MonoJumpInfo ji;

		memset (&ji, 0, sizeof (ji));
		ji.type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;

		amodule->got [2] = mono_resolve_patch_target (NULL, mono_get_root_domain (), NULL, &ji, FALSE);
	}

	/*
	 * Since we store methoddef and classdef tokens when referring to methods/classes in
	 * referenced assemblies, we depend on the exact versions of the referenced assemblies.
	 * MS calls this 'hard binding'. This means we have to load all referenced assemblies
	 * non-lazily, since we can't handle out-of-date errors later.
	 * The cached class info also depends on the exact assemblies.
	 */
#if defined(__native_client__)
	/* TODO: Don't 'load_image' on mscorlib due to a */
	/* recursive loading problem.  This should be    */
	/* removed if mscorlib is loaded from disk.      */
	if (strncmp(assembly->aname.name, "mscorlib", 8)) {
		do_load_image = TRUE;
	} else {
		do_load_image = FALSE;
	}
#endif
	if (do_load_image) {
		for (i = 0; i < amodule->image_table_len; ++i)
			load_image (amodule, i, FALSE);
	}

	if (amodule->out_of_date) {
		mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT Module %s is unusable because a dependency is out-of-date.\n", assembly->image->name);
		if (mono_aot_only) {
			fprintf (stderr, "Failed to load AOT module '%s' while running in aot-only mode because a dependency cannot be found or it is out of date.\n", aot_name);
			exit (1);
		}
	}
	else
		mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT loaded AOT Module for %s.\n", assembly->image->name);
}

/*
 * mono_aot_register_globals:
 *
 *   This is called by the ctor function in AOT images compiled with the
 * 'no-dlsym' option.
 */
void
mono_aot_register_globals (gpointer *globals)
{
	g_assert_not_reached ();
}

/*
 * mono_aot_register_module:
 *
 *   This should be called by embedding code to register AOT modules statically linked
 * into the executable. AOT_INFO should be the value of the 
 * 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
 */
void
mono_aot_register_module (gpointer *aot_info)
{
	gpointer *globals;
	char *aname;
	MonoAotFileInfo *info = (gpointer)aot_info;

	g_assert (info->version == MONO_AOT_FILE_VERSION);

	globals = info->globals;
	g_assert (globals);

	aname = info->assembly_name;

	/* This could be called before startup */
	if (aot_modules)
		mono_aot_lock ();

	if (!static_aot_modules)
		static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);

	g_hash_table_insert (static_aot_modules, aname, info);

	if (aot_modules)
		mono_aot_unlock ();
}

void
mono_aot_init (void)
{
	InitializeCriticalSection (&aot_mutex);
	InitializeCriticalSection (&aot_page_mutex);
	aot_modules = g_hash_table_new (NULL, NULL);

#ifndef __native_client__
	mono_install_assembly_load_hook (load_aot_module, NULL);
#endif

	if (g_getenv ("MONO_LASTAOT"))
		mono_last_aot_method = atoi (g_getenv ("MONO_LASTAOT"));
	if (g_getenv ("MONO_AOT_CACHE"))
		use_aot_cache = TRUE;
}

void
mono_aot_cleanup (void)
{
	if (aot_jit_icall_hash)
		g_hash_table_destroy (aot_jit_icall_hash);
	if (aot_modules)
		g_hash_table_destroy (aot_modules);
}

static gboolean
decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
{
	guint32 flags;
	MethodRef ref;
	gboolean res;

	info->vtable_size = decode_value (buf, &buf);
	if (info->vtable_size == -1)
		/* Generic type */
		return FALSE;
	flags = decode_value (buf, &buf);
	info->ghcimpl = (flags >> 0) & 0x1;
	info->has_finalize = (flags >> 1) & 0x1;
	info->has_cctor = (flags >> 2) & 0x1;
	info->has_nested_classes = (flags >> 3) & 0x1;
	info->blittable = (flags >> 4) & 0x1;
	info->has_references = (flags >> 5) & 0x1;
	info->has_static_refs = (flags >> 6) & 0x1;
	info->no_special_static_fields = (flags >> 7) & 0x1;
	info->is_generic_container = (flags >> 8) & 0x1;

	if (info->has_cctor) {
		res = decode_method_ref (module, &ref, buf, &buf);
		if (!res)
			return FALSE;
		info->cctor_token = ref.token;
	}
	if (info->has_finalize) {
		res = decode_method_ref (module, &ref, buf, &buf);
		if (!res)
			return FALSE;
		info->finalize_image = ref.image;
		info->finalize_token = ref.token;
	}

	info->instance_size = decode_value (buf, &buf);
	info->class_size = decode_value (buf, &buf);
	info->packing_size = decode_value (buf, &buf);
	info->min_align = decode_value (buf, &buf);

	*endbuf = buf;

	return TRUE;
}	

gpointer
mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
{
	int i;
	MonoClass *klass = vtable->klass;
	MonoAotModule *amodule = klass->image->aot_module;
	guint8 *info, *p;
	MonoCachedClassInfo class_info;
	gboolean err;
	MethodRef ref;
	gboolean res;

	if (MONO_CLASS_IS_INTERFACE (klass) || klass->rank || !amodule)
		return NULL;

	info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];
	p = info;

	err = decode_cached_class_info (amodule, &class_info, p, &p);
	if (!err)
		return NULL;

	for (i = 0; i < slot; ++i)
		decode_method_ref (amodule, &ref, p, &p);

	res = decode_method_ref (amodule, &ref, p, &p);
	if (!res)
		return NULL;
	if (ref.no_aot_trampoline)
		return NULL;

	if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
		return NULL;

	return mono_aot_get_method_from_token (domain, ref.image, ref.token);
}

gboolean
mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
{
	MonoAotModule *amodule = klass->image->aot_module;
	guint8 *p;
	gboolean err;

	if (klass->rank || !amodule)
		return FALSE;

	p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (klass->type_token) - 1)];

	err = decode_cached_class_info (amodule, res, p, &p);
	if (!err)
		return FALSE;

	return TRUE;
}

/**
 * mono_aot_get_class_from_name:
 *
 *  Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
 * using a cache stored in the AOT file.
 * Stores the resulting class in *KLASS if found, stores NULL otherwise.
 *
 * Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was 
 * found.
 */
gboolean
mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
{
	MonoAotModule *amodule = image->aot_module;
	guint16 *table, *entry;
	guint16 table_size;
	guint32 hash;
	char full_name_buf [1024];
	char *full_name;
	const char *name2, *name_space2;
	MonoTableInfo  *t;
	guint32 cols [MONO_TYPEDEF_SIZE];
	GHashTable *nspace_table;

	if (!amodule || !amodule->class_name_table)
		return FALSE;

	mono_aot_lock ();

	*klass = NULL;

	/* First look in the cache */
	if (!amodule->name_cache)
		amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
	nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
	if (nspace_table) {
		*klass = g_hash_table_lookup (nspace_table, name);
		if (*klass) {
			mono_aot_unlock ();
			return TRUE;
		}
	}

	table_size = amodule->class_name_table [0];
	table = amodule->class_name_table + 1;

	if (name_space [0] == '\0')
		full_name = g_strdup_printf ("%s", name);
	else {
		if (strlen (name_space) + strlen (name) < 1000) {
			sprintf (full_name_buf, "%s.%s", name_space, name);
			full_name = full_name_buf;
		} else {
			full_name = g_strdup_printf ("%s.%s", name_space, name);
		}
	}
	hash = mono_metadata_str_hash (full_name) % table_size;
	if (full_name != full_name_buf)
		g_free (full_name);

	entry = &table [hash * 2];

	if (entry [0] != 0) {
		t = &image->tables [MONO_TABLE_TYPEDEF];

		while (TRUE) {
			guint32 index = entry [0];
			guint32 next = entry [1];
			guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);

			name_table_accesses ++;

			mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);

			name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
			name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);

			if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
				mono_aot_unlock ();
				*klass = mono_class_get (image, token);

				/* Add to cache */
				if (*klass) {
					mono_aot_lock ();
					nspace_table = g_hash_table_lookup (amodule->name_cache, name_space);
					if (!nspace_table) {
						nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
						g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
					}
					g_hash_table_insert (nspace_table, (char*)name2, *klass);
					mono_aot_unlock ();
				}
				return TRUE;
			}

			if (next != 0) {
				entry = &table [next * 2];
			} else {
				break;
			}
		}
	}

	mono_aot_unlock ();
	
	return TRUE;
}

/*
 * decode_mono_eh_frame:
 *
 *   Decode the EH information emitted by our modified LLVM compiler and construct a
 * MonoJitInfo structure from it.
 * LOCKING: Acquires the domain lock.
 */
static MonoJitInfo*
decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoDomain *domain, 
						   MonoMethod *method, guint8 *code, 
						   MonoJitExceptionInfo *clauses, int num_clauses,
						   int extra_size, GSList **nesting,
						   int *this_reg, int *this_offset)
{
	guint8 *p;
	guint8 *fde, *cie, *code_start, *code_end;
	int version, fde_count;
	gint32 *table;
	int i, j, pos, left, right, offset, offset1, offset2, code_len, func_encoding;
	MonoJitExceptionInfo *ei;
	guint32 fde_len, ei_len, nested_len, nindex;
	gpointer *type_info;
	MonoJitInfo *jinfo;
	MonoLLVMFDEInfo info;

	g_assert (amodule->mono_eh_frame);

	p = amodule->mono_eh_frame;

	/* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */

	/* Header */
	version = *p;
	g_assert (version == 3);
	p ++;
	func_encoding = *p;
	p ++;
	p = ALIGN_PTR_TO (p, 4);

	fde_count = *(guint32*)p;
	p += 4;
	table = (gint32*)p;

	/* There is +1 entry in the table */
	cie = p + ((fde_count + 1) * 8);

	/* Binary search in the table to find the entry for code */
	offset = code - amodule->code;
	left = 0;
	right = fde_count;
	while (TRUE) {
		pos = (left + right) / 2;

		/* The table contains method index/fde offset pairs */
		g_assert (table [(pos * 2)] != -1);
		offset1 = amodule->code_offsets [table [(pos * 2)]];
		if (pos + 1 == fde_count) {
			offset2 = amodule->code_end - amodule->code;
		} else {
			g_assert (table [(pos + 1) * 2] != -1);
			offset2 = amodule->code_offsets [table [(pos + 1) * 2]];
		}

		if (offset < offset1)
			right = pos;
		else if (offset >= offset2)
			left = pos + 1;
		else
			break;
	}

	code_start = amodule->code + amodule->code_offsets [table [(pos * 2)]];
	if (pos + 1 == fde_count) {
		/* The +1 entry in the table contains the length of the last method */
		int len = table [(pos + 1) * 2];
		code_end = code_start + len;
	} else {
		code_end = amodule->code + amodule->code_offsets [table [(pos + 1) * 2]];
	}
	code_len = code_end - code_start;

	g_assert (code >= code_start && code < code_end);

	if (amodule->thumb_end && (guint8*)code_start < amodule->thumb_end)
		/* Clear thumb flag */
		code_start = (guint8*)(((mgreg_t)code_start) & ~1);

	fde = amodule->mono_eh_frame + table [(pos * 2) + 1];	
	/* This won't overflow because there is +1 entry in the table */
	fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];

	mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info);
	ei = info.ex_info;
	ei_len = info.ex_info_len;
	type_info = info.type_info;
	*this_reg = info.this_reg;
	*this_offset = info.this_offset;

	/* Count number of nested clauses */
	nested_len = 0;
	for (i = 0; i < ei_len; ++i) {
		/* This might be unaligned */
		gint32 cindex1 = read32 (type_info [i]);
		GSList *l;

		for (l = nesting [cindex1]; l; l = l->next) {
			gint32 nesting_cindex = GPOINTER_TO_INT (l->data);

			for (j = 0; j < ei_len; ++j) {
				gint32 cindex2 = read32 (type_info [j]);

				if (cindex2 == nesting_cindex)
					nested_len ++;
			}
		}
	}

	/*
	 * LLVM might represent one IL region with multiple regions, so have to
	 * allocate a new JI.
	 */
	jinfo = 
		mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * (ei_len + nested_len)) + extra_size);

	jinfo->code_size = code_len;
	jinfo->used_regs = mono_cache_unwind_info (info.unw_info, info.unw_info_len);
	jinfo->method = method;
	jinfo->code_start = code;
	jinfo->domain_neutral = 0;
	/* This signals that used_regs points to a normal cached unwind info */
	jinfo->from_aot = 0;
	jinfo->num_clauses = ei_len + nested_len;

	for (i = 0; i < ei_len; ++i) {
		/*
		 * orig_jinfo contains the original IL exception info saved by the AOT
		 * compiler, we have to combine that with the information produced by LLVM
		 */
		/* The type_info entries contain IL clause indexes */
		int clause_index = read32 (type_info [i]);
		MonoJitExceptionInfo *jei = &jinfo->clauses [i];
		MonoJitExceptionInfo *orig_jei = &clauses [clause_index];

		g_assert (clause_index < num_clauses);
		jei->flags = orig_jei->flags;
		jei->data.catch_class = orig_jei->data.catch_class;

		jei->try_start = ei [i].try_start;
		jei->try_end = ei [i].try_end;
		jei->handler_start = ei [i].handler_start;

		/* Make sure we transition to thumb when a handler starts */
		if (amodule->thumb_end && (guint8*)jei->handler_start < amodule->thumb_end)
			jei->handler_start = (void*)((mgreg_t)jei->handler_start + 1);
	}

	/* See exception_cb () in mini-llvm.c as to why this is needed */
	nindex = ei_len;
	for (i = 0; i < ei_len; ++i) {
		gint32 cindex1 = read32 (type_info [i]);
		GSList *l;

		for (l = nesting [cindex1]; l; l = l->next) {
			gint32 nesting_cindex = GPOINTER_TO_INT (l->data);

			for (j = 0; j < ei_len; ++j) {
				gint32 cindex2 = read32 (type_info [j]);

				if (cindex2 == nesting_cindex) {
					/* 
					 * The try interval comes from the nested clause, everything else from the
					 * nesting clause.
					 */
					memcpy (&jinfo->clauses [nindex], &jinfo->clauses [j], sizeof (MonoJitExceptionInfo));
					jinfo->clauses [nindex].try_start = jinfo->clauses [i].try_start;
					jinfo->clauses [nindex].try_end = jinfo->clauses [i].try_end;
					nindex ++;
				}
			}
		}
	}
	g_assert (nindex == ei_len + nested_len);

	return jinfo;
}

/*
 * LOCKING: Acquires the domain lock.
 */
static MonoJitInfo*
decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain, 
							 MonoMethod *method, guint8* ex_info, guint8 *addr,
							 guint8 *code, guint32 code_len)
{
	int i, buf_len, num_clauses;
	MonoJitInfo *jinfo;
	guint used_int_regs, flags;
	gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
	gboolean from_llvm, has_gc_map;
	guint8 *p;
	int generic_info_size, try_holes_info_size, num_holes, arch_eh_jit_info_size;
	int this_reg = 0, this_offset = 0;

	/* Load the method info from the AOT file */

	p = ex_info;
	flags = decode_value (p, &p);
	has_generic_jit_info = (flags & 1) != 0;
	has_dwarf_unwind_info = (flags & 2) != 0;
	has_clauses = (flags & 4) != 0;
	has_seq_points = (flags & 8) != 0;
	from_llvm = (flags & 16) != 0;
	has_try_block_holes = (flags & 32) != 0;
	has_gc_map = (flags & 64) != 0;
	has_arch_eh_jit_info = (flags & 128) != 0;

	if (has_dwarf_unwind_info) {
		guint32 offset;

		offset = decode_value (p, &p);
		g_assert (offset < (1 << 30));
		used_int_regs = offset;
	} else {
		used_int_regs = decode_value (p, &p);
	}
	if (has_generic_jit_info)
		generic_info_size = sizeof (MonoGenericJitInfo);
	else
		generic_info_size = 0;

	if (has_try_block_holes) {
		num_holes = decode_value (p, &p);
		try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
	} else {
		num_holes = try_holes_info_size = 0;
	}
	/* Exception table */
	if (has_clauses)
		num_clauses = decode_value (p, &p);
	else
		num_clauses = 0;
	if (has_arch_eh_jit_info)
		arch_eh_jit_info_size = sizeof (MonoArchEHJitInfo);
	else
		arch_eh_jit_info_size = 0;

	if (from_llvm) {
		MonoJitExceptionInfo *clauses;
		GSList **nesting;

		/*
		 * Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
		 * section.
		 */
		clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
		nesting = g_new0 (GSList*, num_clauses);

		for (i = 0; i < num_clauses; ++i) {
			MonoJitExceptionInfo *ei = &clauses [i];

			ei->flags = decode_value (p, &p);

			if (decode_value (p, &p))
				ei->data.catch_class = decode_klass_ref (amodule, p, &p);

			/* Read the list of nesting clauses */
			while (TRUE) {
				int nesting_index = decode_value (p, &p);
				if (nesting_index == -1)
					break;
				nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
			}
		}

		jinfo = decode_llvm_mono_eh_frame (amodule, domain, method, code, clauses, num_clauses, generic_info_size + try_holes_info_size + arch_eh_jit_info_size, nesting, &this_reg, &this_offset);
		jinfo->from_llvm = 1;

		g_free (clauses);
		for (i = 0; i < num_clauses; ++i)
			g_slist_free (nesting [i]);
		g_free (nesting);
	} else {
		jinfo = 
			mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size + arch_eh_jit_info_size);
		jinfo->num_clauses = num_clauses;

		for (i = 0; i < jinfo->num_clauses; ++i) {
			MonoJitExceptionInfo *ei = &jinfo->clauses [i];

			ei->flags = decode_value (p, &p);

			ei->exvar_offset = decode_value (p, &p);

			if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
				ei->data.filter = code + decode_value (p, &p);
			else {
				if (decode_value (p, &p))
					ei->data.catch_class = decode_klass_ref (amodule, p, &p);
			}

			ei->try_start = code + decode_value (p, &p);
			ei->try_end = code + decode_value (p, &p);
			ei->handler_start = code + decode_value (p, &p);
		}

		jinfo->code_size = code_len;
		jinfo->used_regs = used_int_regs;
		jinfo->method = method;
		jinfo->code_start = code;
		jinfo->domain_neutral = 0;
		jinfo->from_aot = 1;
	}

	if (has_generic_jit_info) {
		MonoGenericJitInfo *gi;

		jinfo->has_generic_jit_info = 1;

		gi = mono_jit_info_get_generic_jit_info (jinfo);
		g_assert (gi);

		gi->nlocs = decode_value (p, &p);
		if (gi->nlocs) {
			gi->locations = mono_domain_alloc0 (domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
			for (i = 0; i < gi->nlocs; ++i) {
				MonoDwarfLocListEntry *entry = &gi->locations [i];

				entry->is_reg = decode_value (p, &p);
				entry->reg = decode_value (p, &p);
				if (!entry->is_reg)
					entry->offset = decode_value (p, &p);
				if (i > 0)
					entry->from = decode_value (p, &p);
				entry->to = decode_value (p, &p);
			}
		} else {
			if (from_llvm) {
				gi->has_this = this_reg != -1;
				gi->this_reg = this_reg;
				gi->this_offset = this_offset;
			} else {
				gi->has_this = decode_value (p, &p);
				gi->this_reg = decode_value (p, &p);
				gi->this_offset = decode_value (p, &p);
			}
		}

		jinfo->method = decode_resolve_method_ref (amodule, p, &p);

		gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
		if (decode_value (p, &p)) {
			/* gsharedvt */
			int i, n;
			MonoGenericSharingContext *gsctx = gi->generic_sharing_context;

			n = decode_value (p, &p);
			if (n) {
				gsctx->var_is_vt = g_new0 (gboolean, n);
				for (i = 0; i < n; ++i)
					gsctx->var_is_vt [i] = decode_value (p, &p);
			}
			n = decode_value (p, &p);
			if (n) {
				gsctx->mvar_is_vt = g_new0 (gboolean, n);
				for (i = 0; i < n; ++i)
					gsctx->mvar_is_vt [i] = decode_value (p, &p);
			}
		}
	}

	if (has_try_block_holes) {
		MonoTryBlockHoleTableJitInfo *table;

		jinfo->has_try_block_holes = 1;

		table = mono_jit_info_get_try_block_hole_table_info (jinfo);
		g_assert (table);

		table->num_holes = (guint16)num_holes;
		for (i = 0; i < num_holes; ++i) {
			MonoTryBlockHoleJitInfo *hole = &table->holes [i];
			hole->clause = decode_value (p, &p);
			hole->length = decode_value (p, &p);
			hole->offset = decode_value (p, &p);
		}
	}

	if (has_arch_eh_jit_info) {
		MonoArchEHJitInfo *eh_info;

		jinfo->has_arch_eh_info = 1;

		eh_info = mono_jit_info_get_arch_eh_info (jinfo);
		eh_info->stack_size = decode_value (p, &p);
	}

	if (has_seq_points) {
		MonoSeqPointInfo *seq_points;
		int il_offset, native_offset, last_il_offset, last_native_offset, j;

		int len = decode_value (p, &p);

		seq_points = g_malloc0 (sizeof (MonoSeqPointInfo) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
		seq_points->len = len;
		last_il_offset = last_native_offset = 0;
		for (i = 0; i < len; ++i) {
			SeqPoint *sp = &seq_points->seq_points [i];
			il_offset = last_il_offset + decode_value (p, &p);
			native_offset = last_native_offset + decode_value (p, &p);

			sp->il_offset = il_offset;
			sp->native_offset = native_offset;
			
			sp->next_len = decode_value (p, &p);
			sp->next = g_new (int, sp->next_len);
			for (j = 0; j < sp->next_len; ++j)
				sp->next [j] = decode_value (p, &p);

			last_il_offset = il_offset;
			last_native_offset = native_offset;
		}

		mono_domain_lock (domain);
		g_hash_table_insert (domain_jit_info (domain)->seq_points, method, seq_points);
		mono_domain_unlock (domain);
	}

	/* Load debug info */
	buf_len = decode_value (p, &p);
	mono_debug_add_aot_method (domain, method, code, p, buf_len);
	p += buf_len;

	if (has_gc_map) {
		int map_size = decode_value (p, &p);
		/* The GC map requires 4 bytes of alignment */
		while ((guint64)(gsize)p % 4)
			p ++;		
		jinfo->gc_info = p;
		p += map_size;
	}

	if (amodule != jinfo->method->klass->image->aot_module) {
		mono_aot_lock ();
		if (!ji_to_amodule)
			ji_to_amodule = g_hash_table_new (NULL, NULL);
		g_hash_table_insert (ji_to_amodule, jinfo, amodule);
		mono_aot_unlock ();		
	}

	return jinfo;
}

/*
 * mono_aot_get_unwind_info:
 *
 *   Return a pointer to the DWARF unwind info belonging to JI.
 */
guint8*
mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
{
	MonoAotModule *amodule = ji->method->klass->image->aot_module;
	guint8 *p;
	guint8 *code = ji->code_start;

	g_assert (amodule);
	g_assert (ji->from_aot);

	if (!(code >= amodule->code && code <= amodule->code_end)) {
		/* ji belongs to a different aot module than amodule */
		mono_aot_lock ();
		g_assert (ji_to_amodule);
		amodule = g_hash_table_lookup (ji_to_amodule, ji);
		g_assert (amodule);
		g_assert (code >= amodule->code && code <= amodule->code_end);
		mono_aot_unlock ();
	}

	p = amodule->unwind_info + ji->used_regs;
	*unwind_info_len = decode_value (p, &p);
	return p;
}

static G_GNUC_UNUSED int
compare_ints (const void *a, const void *b)
{
	return *(gint32*)a - *(gint32*)b;
}

static void
msort_code_offsets_internal (gint32 *array, int lo, int hi, gint32 *scratch)
{
	int mid = (lo + hi) / 2;
	int i, t_lo, t_hi;

	if (lo >= hi)
		return;

	if (hi - lo < 32) {
		for (i = lo; i < hi; ++i)
			if (array [(i * 2)] > array [(i * 2) + 2])
				break;
		if (i == hi)
			/* Already sorted */
			return;
	}

	msort_code_offsets_internal (array, lo, mid, scratch);
	msort_code_offsets_internal (array, mid + 1, hi, scratch);

	if (array [mid * 2] < array [(mid + 1) * 2])
		return;

	/* Merge */
	t_lo = lo;
	t_hi = mid + 1;
	for (i = lo; i <= hi; i ++) {
		if (t_lo <= mid && ((t_hi > hi) || array [t_lo * 2] < array [t_hi * 2])) {
			scratch [(i * 2)] = array [t_lo * 2];
			scratch [(i * 2) + 1] = array [(t_lo *2) + 1];
			t_lo ++;
		} else {
			scratch [(i * 2)] = array [t_hi * 2];
			scratch [(i * 2) + 1] = array [(t_hi *2) + 1];
			t_hi ++;
		}
	}
	for (i = lo; i <= hi; ++i) {
		array [(i * 2)] = scratch [i * 2];
		array [(i * 2) + 1] = scratch [(i * 2) + 1];
	}
}

static void
msort_code_offsets (gint32 *array, int len)
{
	gint32 *scratch;

	scratch = g_new (gint32, len * 2);
	msort_code_offsets_internal (array, 0, len - 1, scratch);
	g_free (scratch);
}

MonoJitInfo *
mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
{
	int pos, left, right, offset, offset1, offset2, code_len;
	int method_index, table_len;
	guint32 token;
	MonoAotModule *amodule = image->aot_module;
	MonoMethod *method;
	MonoJitInfo *jinfo;
	guint8 *code, *ex_info, *p;
	guint32 *table;
	int nmethods = amodule->info.nmethods;
	gint32 *code_offsets;
	int offsets_len, i;

	if (!amodule)
		return NULL;

	if (domain != mono_get_root_domain ())
		/* FIXME: */
		return NULL;

	offset = (guint8*)addr - amodule->code;

	/* Compute a sorted table mapping code offsets to method indexes. */
	if (!amodule->sorted_code_offsets) {
		code_offsets = g_new0 (gint32, nmethods * 2);
		offsets_len = 0;
		for (i = 0; i < nmethods; ++i) {
			/* Skip the -1 entries to speed up sorting */
			if (amodule->code_offsets [i] == 0xffffffff)
				continue;
			code_offsets [(offsets_len * 2)] = amodule->code_offsets [i];
			code_offsets [(offsets_len *2) + 1] = i;
			offsets_len ++;
		}
		/* Use a merge sort as this is mostly sorted */
		msort_code_offsets (code_offsets, offsets_len);
		//qsort (code_offsets, offsets_len, sizeof (gint32) * 2, compare_ints);
		for (i = 0; i < offsets_len -1; ++i)
			g_assert (code_offsets [(i * 2)] <= code_offsets [(i + 1) * 2]);

		amodule->sorted_code_offsets_len = offsets_len;
		mono_memory_barrier ();
		if (InterlockedCompareExchangePointer ((gpointer*)&amodule->sorted_code_offsets, code_offsets, NULL) != NULL)
			/* Somebody got in before us */
			g_free (code_offsets);
	}

	code_offsets = amodule->sorted_code_offsets;
	offsets_len = amodule->sorted_code_offsets_len;

	if (offsets_len > 0 && (offset < code_offsets [0] || offset >= (amodule->code_end - amodule->code)))
		return NULL;

	/* Binary search in the sorted_code_offsets table */
	left = 0;
	right = offsets_len;
	while (TRUE) {
		pos = (left + right) / 2;

		offset1 = code_offsets [(pos * 2)];
		if (pos + 1 == offsets_len)
			offset2 = amodule->code_end - amodule->code;
		else
			offset2 = code_offsets [(pos + 1) * 2];

		if (offset < offset1)
			right = pos;
		else if (offset >= offset2)
			left = pos + 1;
		else
			break;
	}

	g_assert (offset >= code_offsets [(pos * 2)]);
	if (pos + 1 < offsets_len)
		g_assert (offset < code_offsets [((pos + 1) * 2)]);
	method_index = code_offsets [(pos * 2) + 1];

	code = &amodule->code [amodule->code_offsets [method_index]];
	ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];

	if (pos == offsets_len - 1)
		code_len = amodule->code_end - code;
	else
		code_len = code_offsets [(pos + 1) * 2] - code_offsets [pos * 2];

	g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);

	/* Might be a wrapper/extra method */
	if (amodule->extra_methods) {
		mono_aot_lock ();
		method = g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
		mono_aot_unlock ();
	} else {
		method = NULL;
	}

	if (!method) {
		if (method_index >= image->tables [MONO_TABLE_METHOD].rows) {
			/* 
			 * This is hit for extra methods which are called directly, so they are
			 * not in amodule->extra_methods.
			 */
			table_len = amodule->extra_method_info_offsets [0];
			table = amodule->extra_method_info_offsets + 1;
			left = 0;
			right = table_len;
			pos = 0;

			/* Binary search */
			while (TRUE) {
				pos = ((left + right) / 2);

				g_assert (pos < table_len);

				if (table [pos * 2] < method_index)
					left = pos + 1;
				else if (table [pos * 2] > method_index)
					right = pos;
				else
					break;
			}

			p = amodule->blob + table [(pos * 2) + 1];
			method = decode_resolve_method_ref (amodule, p, &p);
			if (!method)
				/* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
				return NULL;
		} else {
			token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
			method = mono_get_method (image, token, NULL);
		}
	}

	/* FIXME: */
	g_assert (method);

	//printf ("F: %s\n", mono_method_full_name (method, TRUE));
	
	jinfo = decode_exception_debug_info (amodule, domain, method, ex_info, addr, code, code_len);

	g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
	g_assert ((guint8*)addr < (guint8*)jinfo->code_start + jinfo->code_size);

	/* Add it to the normal JitInfo tables */
	mono_jit_info_table_add (domain, jinfo);
	
	return jinfo;
}

static gboolean
decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
{
	guint8 *p = buf;
	gpointer *table;
	MonoImage *image;
	int i;

	switch (ji->type) {
	case MONO_PATCH_INFO_METHOD:
	case MONO_PATCH_INFO_METHOD_JUMP:
	case MONO_PATCH_INFO_ICALL_ADDR:
	case MONO_PATCH_INFO_METHOD_RGCTX: {
		MethodRef ref;
		gboolean res;

		res = decode_method_ref (aot_module, &ref, p, &p);
		if (!res)
			goto cleanup;

		if (!ref.method && !mono_aot_only && !ref.no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (ref.token) == MONO_TABLE_METHOD)) {
			ji->data.target = mono_create_ftnptr (mono_domain_get (), mono_create_jit_trampoline_from_token (ref.image, ref.token));
			ji->type = MONO_PATCH_INFO_ABS;
		}
		else {
			if (ref.method)
				ji->data.method = ref.method;
			else
				ji->data.method = mono_get_method (ref.image, ref.token, NULL);
			g_assert (ji->data.method);
			mono_class_init (ji->data.method->klass);
		}
		break;
	}
	case MONO_PATCH_INFO_INTERNAL_METHOD:
	case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
		guint32 len = decode_value (p, &p);

		ji->data.name = (char*)p;
		p += len + 1;
		break;
	}
	case MONO_PATCH_INFO_METHODCONST:
		/* Shared */
		ji->data.method = decode_resolve_method_ref (aot_module, p, &p);
		if (!ji->data.method)
			goto cleanup;
		break;
	case MONO_PATCH_INFO_VTABLE:
	case MONO_PATCH_INFO_CLASS:
	case MONO_PATCH_INFO_IID:
	case MONO_PATCH_INFO_ADJUSTED_IID:
		/* Shared */
		ji->data.klass = decode_klass_ref (aot_module, p, &p);
		if (!ji->data.klass)
			goto cleanup;
		break;
	case MONO_PATCH_INFO_CLASS_INIT:
	case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
		ji->data.klass = decode_klass_ref (aot_module, p, &p);
		if (!ji->data.klass)
			goto cleanup;
		break;
	case MONO_PATCH_INFO_IMAGE:
		ji->data.image = load_image (aot_module, decode_value (p, &p), TRUE);
		if (!ji->data.image)
			goto cleanup;
		break;
	case MONO_PATCH_INFO_FIELD:
	case MONO_PATCH_INFO_SFLDA:
		/* Shared */
		ji->data.field = decode_field_info (aot_module, p, &p);
		if (!ji->data.field)
			goto cleanup;
		break;
	case MONO_PATCH_INFO_SWITCH:
		ji->data.table = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
		ji->data.table->table_size = decode_value (p, &p);
		table = mono_domain_alloc (mono_domain_get (), sizeof (gpointer) * ji->data.table->table_size);
		ji->data.table->table = (MonoBasicBlock**)table;
		for (i = 0; i < ji->data.table->table_size; i++)
			table [i] = (gpointer)(gssize)decode_value (p, &p);
		break;
	case MONO_PATCH_INFO_R4: {
		guint32 val;
		
		ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (float));
		val = decode_value (p, &p);
		*(float*)ji->data.target = *(float*)&val;
		break;
	}
	case MONO_PATCH_INFO_R8: {
		guint32 val [2];
		guint64 v;

		ji->data.target = mono_domain_alloc0 (mono_domain_get (), sizeof (double));

		val [0] = decode_value (p, &p);
		val [1] = decode_value (p, &p);
		v = ((guint64)val [1] << 32) | ((guint64)val [0]);
		*(double*)ji->data.target = *(double*)&v;
		break;
	}
	case MONO_PATCH_INFO_LDSTR:
		image = load_image (aot_module, decode_value (p, &p), TRUE);
		if (!image)
			goto cleanup;
		ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
		break;
	case MONO_PATCH_INFO_RVA:
	case MONO_PATCH_INFO_DECLSEC:
	case MONO_PATCH_INFO_LDTOKEN:
	case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
		/* Shared */
		image = load_image (aot_module, decode_value (p, &p), TRUE);
		if (!image)
			goto cleanup;
		ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));

		ji->data.token->has_context = decode_value (p, &p);
		if (ji->data.token->has_context) {
			gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p);
			if (!res)
				goto cleanup;
		}
		break;
	case MONO_PATCH_INFO_EXC_NAME:
		ji->data.klass = decode_klass_ref (aot_module, p, &p);
		if (!ji->data.klass)
			goto cleanup;
		ji->data.name = ji->data.klass->name;
		break;
	case MONO_PATCH_INFO_METHOD_REL:
		ji->data.offset = decode_value (p, &p);
		break;
	case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
	case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
	case MONO_PATCH_INFO_MONITOR_ENTER:
	case MONO_PATCH_INFO_MONITOR_EXIT:
	case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
	case MONO_PATCH_INFO_CASTCLASS_CACHE:
	case MONO_PATCH_INFO_JIT_TLS_ID:
		break;
	case MONO_PATCH_INFO_RGCTX_FETCH: {
		gboolean res;
		MonoJumpInfoRgctxEntry *entry;
		guint32 offset, val;
		guint8 *p2;

		offset = decode_value (p, &p);
		val = decode_value (p, &p);

		entry = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
		p2 = aot_module->blob + offset;
		entry->method = decode_resolve_method_ref (aot_module, p2, &p2);
		entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
		entry->info_type = (val >> 1) & 0xff;
		entry->data = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
		entry->data->type = (val >> 9) & 0xff;
		
		res = decode_patch (aot_module, mp, entry->data, p, &p);
		if (!res)
			goto cleanup;
		ji->data.rgctx_entry = entry;
		break;
	}
	case MONO_PATCH_INFO_SEQ_POINT_INFO:
		break;
	case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE: {
		MonoJumpInfoImtTramp *imt_tramp = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoImtTramp));

		imt_tramp->method = decode_resolve_method_ref (aot_module, p, &p);
		imt_tramp->vt_offset = decode_value (p, &p);
		
		ji->data.imt_tramp = imt_tramp;
		break;
	}
	case MONO_PATCH_INFO_SIGNATURE:
		ji->data.target = decode_signature (aot_module, p, &p);
		break;
	case MONO_PATCH_INFO_TLS_OFFSET:
		ji->data.target = GINT_TO_POINTER (decode_value (p, &p));
		break;
	case MONO_PATCH_INFO_GSHAREDVT_CALL: {
		MonoJumpInfoGSharedVtCall *info = g_new0 (MonoJumpInfoGSharedVtCall, 1);
		info->sig = decode_signature (aot_module, p, &p);
		g_assert (info->sig);
		info->method = decode_resolve_method_ref (aot_module, p, &p);
		g_assert (info->method);

		ji->data.target = info;
		break;
	}
	case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
		MonoGSharedVtMethodInfo *info = g_new0 (MonoGSharedVtMethodInfo, 1);
		int i, nentries;
		
		info->method = decode_resolve_method_ref (aot_module, p, &p);
		g_assert (info->method);
		nentries = decode_value (p, &p);
		info->entries = g_ptr_array_new ();
		for (i = 0; i < nentries; ++i) {
			MonoRuntimeGenericContextInfoTemplate *template = g_new0 (MonoRuntimeGenericContextInfoTemplate, 1);

			template->info_type = decode_value (p, &p);
			switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
			case MONO_PATCH_INFO_CLASS: {
				MonoClass *klass = decode_klass_ref (aot_module, p, &p);
				if (!klass)
					goto cleanup;
				template->data = &klass->byval_arg;
				break;
			}
			case MONO_PATCH_INFO_FIELD:
				template->data = decode_field_info (aot_module, p, &p);
				if (!template->data)
					goto cleanup;
				break;
			default:
				g_assert_not_reached ();
				break;
			}

			g_ptr_array_add (info->entries, template);
		}
		ji->data.target = info;
		break;
	}
	default:
		g_warning ("unhandled type %d", ji->type);
		g_assert_not_reached ();
	}

	*endbuf = p;

	return TRUE;

 cleanup:
	return FALSE;
}

static MonoJumpInfo*
load_patch_info (MonoAotModule *aot_module, MonoMemPool *mp, int n_patches, 
				 guint32 **got_slots, 
				 guint8 *buf, guint8 **endbuf)
{
	MonoJumpInfo *patches;
	int pindex;
	guint8 *p;

	p = buf;

	patches = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);

	*got_slots = g_malloc (sizeof (guint32) * n_patches);

	for (pindex = 0; pindex < n_patches; ++pindex) {
		MonoJumpInfo *ji = &patches [pindex];
		guint8 *shared_p;
		gboolean res;
		guint32 got_offset;

		got_offset = decode_value (p, &p);

		if (aot_module->got [got_offset]) {
			/* Already loaded */
			//printf ("HIT!\n");
		} else {
			shared_p = aot_module->blob + mono_aot_get_offset (aot_module->got_info_offsets, got_offset);

			ji->type = decode_value (shared_p, &shared_p);

			res = decode_patch (aot_module, mp, ji, shared_p, &shared_p);
			if (!res)
				goto cleanup;
		}

		(*got_slots) [pindex] = got_offset;
	}

	*endbuf = p;
	return patches;

 cleanup:
	g_free (*got_slots);
	*got_slots = NULL;

	return NULL;
}

static void
register_jump_target_got_slot (MonoDomain *domain, MonoMethod *method, gpointer *got_slot)
{
	/*
	 * Jump addresses cannot be patched by the trampoline code since it
	 * does not have access to the caller's address. Instead, we collect
	 * the addresses of the GOT slots pointing to a method, and patch
	 * them after the method has been compiled.
	 */
	MonoJitDomainInfo *info = domain_jit_info (domain);
	GSList *list;
		
	mono_domain_lock (domain);
	if (!info->jump_target_got_slot_hash)
		info->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
	list = g_hash_table_lookup (info->jump_target_got_slot_hash, method);
	list = g_slist_prepend (list, got_slot);
	g_hash_table_insert (info->jump_target_got_slot_hash, method, list);
	mono_domain_unlock (domain);
}

/*
 * load_method:
 *
 *   Load the method identified by METHOD_INDEX from the AOT image. Return a
 * pointer to the native code of the method, or NULL if not found.
 * METHOD might not be set if the caller only has the image/token info.
 */
static gpointer
load_method (MonoDomain *domain, MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index)
{
	MonoClass *klass;
	gboolean from_plt = method == NULL;
	MonoMemPool *mp;
	int i, pindex, n_patches, used_strings;
	gboolean keep_patches = TRUE;
	guint8 *p;
	MonoJitInfo *jinfo = NULL;
	guint8 *code, *info;

	if (mono_profiler_get_events () & MONO_PROFILE_ENTER_LEAVE)
		return NULL;

	if ((domain != mono_get_root_domain ()) && (!(amodule->info.opts & MONO_OPT_SHARED)))
		/* Non shared AOT code can't be used in other appdomains */
		return NULL;

	if (amodule->out_of_date)
		return NULL;

	if (amodule->code_offsets [method_index] == 0xffffffff) {
		if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
			char *full_name;

			if (!method)
				method = mono_get_method (image, token, NULL);
			full_name = mono_method_full_name (method, TRUE);
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
			g_free (full_name);
		}
		return NULL;
	}

	code = &amodule->code [amodule->code_offsets [method_index]];

	info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];

	if (amodule->thumb_end && code < amodule->thumb_end && ((amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES) == 0)) {
		/* Convert this into a thumb address */
		g_assert ((amodule->code_offsets [method_index] & 0x1) == 0);
		code = &amodule->code [amodule->code_offsets [method_index] + 1];
	}

	mono_aot_lock ();
	if (!amodule->methods_loaded)
		amodule->methods_loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
	mono_aot_unlock ();

	if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
		return code;

	if (mono_last_aot_method != -1) {
		if (mono_jit_stats.methods_aot >= mono_last_aot_method)
				return NULL;
		else if (mono_jit_stats.methods_aot == mono_last_aot_method - 1) {
			if (!method)
				method = mono_get_method (image, token, NULL);
			if (method) {
				char *name = mono_method_full_name (method, TRUE);
				printf ("LAST AOT METHOD: %s.\n", name);
				g_free (name);
			} else {
				printf ("LAST AOT METHOD: %p %d\n", code, method_index);
			}
		}
	}

	p = info;

	if (method) {
		klass = method->klass;
		decode_klass_ref (amodule, p, &p);
	} else {
		klass = decode_klass_ref (amodule, p, &p);
	}

	if (amodule->info.opts & MONO_OPT_SHARED)
		used_strings = decode_value (p, &p);
	else
		used_strings = 0;

	for (i = 0; i < used_strings; i++) {
		guint token = decode_value (p, &p);
		mono_ldstr (mono_get_root_domain (), image, mono_metadata_token_index (token));
	}

	if (amodule->info.opts & MONO_OPT_SHARED)	
		keep_patches = FALSE;

	n_patches = decode_value (p, &p);

	keep_patches = FALSE;

	if (n_patches) {
		MonoJumpInfo *patches;
		guint32 *got_slots;

		if (keep_patches)
			mp = domain->mp;
		else
			mp = mono_mempool_new ();

		patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
		if (patches == NULL)
			goto cleanup;

		for (pindex = 0; pindex < n_patches; ++pindex) {
			MonoJumpInfo *ji = &patches [pindex];

			if (!amodule->got [got_slots [pindex]]) {
				amodule->got [got_slots [pindex]] = mono_resolve_patch_target (method, domain, code, ji, TRUE);
				if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
					amodule->got [got_slots [pindex]] = mono_create_ftnptr (domain, amodule->got [got_slots [pindex]]);
				if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
					register_jump_target_got_slot (domain, ji->data.method, &(amodule->got [got_slots [pindex]]));
			}
			ji->type = MONO_PATCH_INFO_NONE;
		}

		g_free (got_slots);

		if (!keep_patches)
			mono_mempool_destroy (mp);
	}

	if (mini_get_debug_options ()->load_aot_jit_info_eagerly)
		jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);

	if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
		char *full_name;

		if (!method)
			method = mono_get_method (image, token, NULL);

		full_name = mono_method_full_name (method, TRUE);

		if (!jinfo)
			jinfo = mono_aot_find_jit_info (domain, amodule->assembly->image, code);

		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
		g_free (full_name);
	}

	mono_aot_lock ();

	InterlockedIncrement (&mono_jit_stats.methods_aot);

	amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);

	init_plt (amodule);

	if (method && method->wrapper_type)
		g_hash_table_insert (amodule->method_to_code, method, code);

	mono_aot_unlock ();

	if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION) {
		MonoJitInfo *jinfo;

		if (!method) {
			method = mono_get_method (image, token, NULL);
			g_assert (method);
		}
		mono_profiler_method_jit (method);
		jinfo = mono_jit_info_table_find (domain, (char*)code);
		g_assert (jinfo);
		mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
	}

	if (from_plt && klass && !klass->generic_container)
		mono_runtime_class_init (mono_class_vtable (domain, klass));

	return code;

 cleanup:
	/* FIXME: The space in domain->mp is wasted */	
	if (amodule->info.opts & MONO_OPT_SHARED)
		/* No need to cache patches */
		mono_mempool_destroy (mp);

	if (jinfo)
		g_free (jinfo);

	return NULL;
}

static guint32
find_extra_method_in_amodule (MonoAotModule *amodule, MonoMethod *method)
{
	guint32 table_size, entry_size, hash;
	guint32 *table, *entry;
	guint32 index;
	static guint32 n_extra_decodes;

	if (!amodule || amodule->out_of_date)
		return 0xffffff;

	table_size = amodule->extra_method_table [0];
	table = amodule->extra_method_table + 1;
	entry_size = 3;

	hash = mono_aot_method_hash (method) % table_size;

	entry = &table [hash * entry_size];

	if (entry [0] == 0)
		return 0xffffff;

	index = 0xffffff;
	while (TRUE) {
		guint32 key = entry [0];
		guint32 value = entry [1];
		guint32 next = entry [entry_size - 1];
		MonoMethod *m;
		guint8 *p, *orig_p;

		p = amodule->blob + key;
		orig_p = p;

		mono_aot_lock ();
		if (!amodule->method_ref_to_method)
			amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
		m = g_hash_table_lookup (amodule->method_ref_to_method, p);
		mono_aot_unlock ();
		if (!m) {
			m = decode_resolve_method_ref_with_target (amodule, method, p, &p);
			if (m) {
				mono_aot_lock ();
				g_hash_table_insert (amodule->method_ref_to_method, orig_p, m);
				mono_aot_unlock ();
			}
		}
		if (m == method) {
			index = value;
			break;
		}

		/* Special case: wrappers of shared generic methods */
		if (m && method->wrapper_type && m->wrapper_type == m->wrapper_type &&
			method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
			MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
			MonoMethod *w2 = mono_marshal_method_from_wrapper (m);

			if (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2) {
				index = value;
				break;
			}
		}

		/* Methods decoded needlessly */
		if (m) {
			//printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
			n_extra_decodes ++;
		}

		if (next != 0)
			entry = &table [next * entry_size];
		else
			break;
	}

	return index;
}

static void
add_module_cb (gpointer key, gpointer value, gpointer user_data)
{
	g_ptr_array_add ((GPtrArray*)user_data, value);
}

/*
 * find_extra_method:
 *
 *   Try finding METHOD in the extra_method table in all AOT images.
 * Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
 * module where the method was found.
 */
static guint32
find_extra_method (MonoMethod *method, MonoAotModule **out_amodule)
{
	guint32 index;
	GPtrArray *modules;
	int i;

	/* Try the method's module first */
	*out_amodule = method->klass->image->aot_module;
	index = find_extra_method_in_amodule (method->klass->image->aot_module, method);
	if (index != 0xffffff)
		return index;

	/* 
	 * Try all other modules.
	 * This is needed because generic instances klass->image points to the image
	 * containing the generic definition, but the native code is generated to the
	 * AOT image which contains the reference.
	 */

	/* Make a copy to avoid doing the search inside the aot lock */
	modules = g_ptr_array_new ();
	mono_aot_lock ();
	g_hash_table_foreach (aot_modules, add_module_cb, modules);
	mono_aot_unlock ();

	index = 0xffffff;
	for (i = 0; i < modules->len; ++i) {
		MonoAotModule *amodule = g_ptr_array_index (modules, i);

		if (amodule != method->klass->image->aot_module)
			index = find_extra_method_in_amodule (amodule, method);
		if (index != 0xffffff) {
			*out_amodule = amodule;
			break;
		}
	}
	
	g_ptr_array_free (modules, TRUE);

	return index;
}

/*
 * mono_aot_get_method:
 *
 *   Return a pointer to the AOTed native code for METHOD if it can be found,
 * NULL otherwise.
 * On platforms with function pointers, this doesn't return a function pointer.
 */
gpointer
mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
{
	MonoClass *klass = method->klass;
	guint32 method_index;
	MonoAotModule *amodule = klass->image->aot_module;
	guint8 *code;

	if (!amodule)
		return NULL;

	if (amodule->out_of_date)
		return NULL;

	if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
		(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
		(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
		(method->flags & METHOD_ATTRIBUTE_ABSTRACT))
		return NULL;

	/*
	 * Use the original method instead of its invoke-with-check wrapper.
	 * This is not a problem when using full-aot, since it doesn't support
	 * remoting.
	 */
	if (mono_aot_only && method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
		return mono_aot_get_method (domain, mono_marshal_method_from_wrapper (method));

	g_assert (klass->inited);

	/* Find method index */
	method_index = 0xffffff;
	if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
		/* 
		 * For generic methods, we store the fully shared instance in place of the
		 * original method.
		 */
		method = mono_method_get_declaring_generic_method (method);
		method_index = mono_metadata_token_index (method->token) - 1;
	} else if (method->is_inflated || !method->token) {
		/* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
		mono_aot_lock ();
		code = g_hash_table_lookup (amodule->method_to_code, method);
		mono_aot_unlock ();
		if (code)
			return code;

		method_index = find_extra_method (method, &amodule);
		/*
		 * Special case the ICollection<T> wrappers for arrays, as they cannot
		 * be statically enumerated, and each wrapper ends up calling the same
		 * method in Array.
		 */
		if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && method->klass->rank && strstr (method->name, "System.Collections.Generic")) {
			MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);

			code = mono_aot_get_method (domain, m);
			if (code) {
				if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
					code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
					/* The call above returns an ftnptr */
					code = mono_get_addr_from_ftnptr (code);
				}

				return code;
			}
		}

		/*
		 * Special case Array.GetGenericValueImpl which is a generic icall.
		 * Generic sharing currently can't handle it, but the icall returns data using
		 * an out parameter, so the managed-to-native wrappers can share the same code.
		 */
		if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValueImpl")) {
			MonoMethod *m;
			MonoGenericContext ctx;
			MonoType *args [16];

			if (mono_method_signature (method)->params [1]->type == MONO_TYPE_OBJECT)
				/* Avoid recursion */
				return NULL;

			m = mono_class_get_method_from_name (mono_defaults.array_class, "GetGenericValueImpl", 2);
			g_assert (m);

			memset (&ctx, 0, sizeof (ctx));
			args [0] = &mono_defaults.object_class->byval_arg;
			ctx.method_inst = mono_metadata_get_generic_inst (1, args);

			m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);

			/* 
			 * Get the code for the <object> instantiation which should be emitted into
			 * the mscorlib aot image by the AOT compiler.
			 */
			code = mono_aot_get_method (domain, m);
			if (code)
				return code;
		}

		/* Same for CompareExchange<T> and Exchange<T> */
		/* Same for Volatile.Read<T>/Write<T> */
		if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass->image == mono_defaults.corlib && 
			((!strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Interlocked") && (!strcmp (method->name, "CompareExchange") || !strcmp (method->name, "Exchange")) && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->params [1])) ||
			 (!strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Volatile") && (!strcmp (method->name, "Read") && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->ret))) ||
			 (!strcmp (method->klass->name_space, "System.Threading") && !strcmp (method->klass->name, "Volatile") && (!strcmp (method->name, "Write") && MONO_TYPE_IS_REFERENCE (mono_method_signature (method)->params [1]))))) {
			MonoMethod *m;
			MonoGenericContext ctx;
			MonoType *args [16];
			gpointer iter = NULL;

			while ((m = mono_class_get_methods (method->klass, &iter))) {
				if (mono_method_signature (m)->generic_param_count && !strcmp (m->name, method->name))
					break;
			}
			g_assert (m);

			memset (&ctx, 0, sizeof (ctx));
			args [0] = &mono_defaults.object_class->byval_arg;
			ctx.method_inst = mono_metadata_get_generic_inst (1, args);

			m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE);

			/* Avoid recursion */
			if (method == m)
				return NULL;

			/* 
			 * Get the code for the <object> instantiation which should be emitted into
			 * the mscorlib aot image by the AOT compiler.
			 */
			code = mono_aot_get_method (domain, m);
			if (code)
				return code;
		}

		if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
			/* Partial sharing */
			MonoMethod *shared;

			shared = mini_get_shared_method (method);
			method_index = find_extra_method (shared, &amodule);
			if (method_index != 0xffffff)
				method = shared;
		}

		if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
			/* gsharedvt */
			/* Use the all-vt shared method since this is what was AOTed */
			method_index = find_extra_method (mini_get_shared_method_full (method, TRUE, TRUE), &amodule);
			if (method_index != 0xffffff)
				method = mini_get_shared_method_full (method, TRUE, FALSE);
		}

		if (method_index == 0xffffff) {
			if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
				char *full_name;

				full_name = mono_method_full_name (method, TRUE);
				mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.\n", full_name);
				g_free (full_name);
			}
			return NULL;
		}

		if (method_index == 0xffffff)
			return NULL;

		/* Needed by find_jit_info */
		mono_aot_lock ();
		if (!amodule->extra_methods)
			amodule->extra_methods = g_hash_table_new (NULL, NULL);
		g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
		mono_aot_unlock ();
	} else {
		/* Common case */
		method_index = mono_metadata_token_index (method->token) - 1;
	}

	return load_method (domain, amodule, klass->image, method, method->token, method_index);
}

/**
 * Same as mono_aot_get_method, but we try to avoid loading any metadata from the
 * method.
 */
gpointer
mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
{
	MonoAotModule *aot_module = image->aot_module;
	int method_index;

	if (!aot_module)
		return NULL;

	method_index = mono_metadata_token_index (token) - 1;

	return load_method (domain, aot_module, image, NULL, token, method_index);
}

typedef struct {
	guint8 *addr;
	gboolean res;
} IsGotEntryUserData;

static void
check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
{
	IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
	MonoAotModule *aot_module = (MonoAotModule*)value;

	if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
		data->res = TRUE;
}

gboolean
mono_aot_is_got_entry (guint8 *code, guint8 *addr)
{
	IsGotEntryUserData user_data;

	if (!aot_modules)
		return FALSE;

	user_data.addr = addr;
	user_data.res = FALSE;
	mono_aot_lock ();
	g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
	mono_aot_unlock ();
	
	return user_data.res;
}

typedef struct {
	guint8 *addr;
	MonoAotModule *module;
} FindAotModuleUserData;

static void
find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
{
	FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
	MonoAotModule *aot_module = (MonoAotModule*)value;

	if ((data->addr >= (guint8*)(aot_module->code)) && (data->addr < (guint8*)(aot_module->code_end)))
		data->module = aot_module;
}

static inline MonoAotModule*
find_aot_module (guint8 *code)
{
	FindAotModuleUserData user_data;

	if (!aot_modules)
		return NULL;

	/* Reading these need no locking */
	if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
		return NULL;

	user_data.addr = code;
	user_data.module = NULL;
		
	mono_aot_lock ();
	g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
	mono_aot_unlock ();
	
	return user_data.module;
}

void
mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
{
	/*
	 * Since AOT code is only used in the root domain, 
	 * mono_domain_get () != mono_get_root_domain () means the calling method
	 * is AppDomain:InvokeInDomain, so this is the same check as in 
	 * mono_method_same_domain () but without loading the metadata for the method.
	 */
	if (mono_domain_get () == mono_get_root_domain ())
		mono_arch_patch_plt_entry (code, got, regs, addr);
}

/*
 * mono_aot_plt_resolve:
 *
 *   This function is called by the entries in the PLT to resolve the actual method that
 * needs to be called. It returns a trampoline to the method and patches the PLT entry.
 * Returns NULL if the something cannot be loaded.
 */
gpointer
mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
{
#ifdef MONO_ARCH_AOT_SUPPORTED
	guint8 *p, *target, *plt_entry;
	MonoJumpInfo ji;
	MonoAotModule *module = (MonoAotModule*)aot_module;
	gboolean res, no_ftnptr = FALSE;
	MonoMemPool *mp;
	gboolean using_gsharedvt = FALSE;

	//printf ("DYN: %p %d\n", aot_module, plt_info_offset);

	p = &module->blob [plt_info_offset];

	ji.type = decode_value (p, &p);

	mp = mono_mempool_new_size (512);
	res = decode_patch (module, mp, &ji, p, &p);

	if (!res) {
		mono_mempool_destroy (mp);
		return NULL;
	}

#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
	using_gsharedvt = TRUE;
#endif

	/* 
	 * Avoid calling resolve_patch_target in the full-aot case if possible, since
	 * it would create a trampoline, and we don't need that.
	 * We could do this only if the method does not need the special handling
	 * in mono_magic_trampoline ().
	 */
	if (mono_aot_only && ji.type == MONO_PATCH_INFO_METHOD && !ji.data.method->is_generic && !mono_method_check_context_used (ji.data.method) && !(ji.data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) &&
		!mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
		target = mono_jit_compile_method (ji.data.method);
		no_ftnptr = TRUE;
	} else {
		target = mono_resolve_patch_target (NULL, mono_domain_get (), NULL, &ji, TRUE);
	}

	/*
	 * The trampoline expects us to return a function descriptor on platforms which use
	 * it, but resolve_patch_target returns a direct function pointer for some type of
	 * patches, so have to translate between the two.
	 * FIXME: Clean this up, but how ?
	 */
	if (ji.type == MONO_PATCH_INFO_ABS || ji.type == MONO_PATCH_INFO_INTERNAL_METHOD || ji.type == MONO_PATCH_INFO_CLASS_INIT || ji.type == MONO_PATCH_INFO_ICALL_ADDR || ji.type == MONO_PATCH_INFO_JIT_ICALL_ADDR || ji.type == MONO_PATCH_INFO_RGCTX_FETCH) {
		/* These should already have a function descriptor */
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
		/* Our function descriptors have a 0 environment, gcc created ones don't */
		if (ji.type != MONO_PATCH_INFO_INTERNAL_METHOD && ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR && ji.type != MONO_PATCH_INFO_ICALL_ADDR)
			g_assert (((gpointer*)target) [2] == 0);
#endif
		/* Empty */
	} else if (!no_ftnptr) {
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
		g_assert (((gpointer*)target) [2] != 0);
#endif
		target = mono_create_ftnptr (mono_domain_get (), target);
	}

	mono_mempool_destroy (mp);

	/* Patch the PLT entry with target which might be the actual method not a trampoline */
	plt_entry = mono_aot_get_plt_entry (code);
	g_assert (plt_entry);
	mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);

	return target;
#else
	g_assert_not_reached ();
	return NULL;
#endif
}

/**
 * init_plt:
 *
 *   Initialize the PLT table of the AOT module. Called lazily when the first AOT
 * method in the module is loaded to avoid committing memory by writing to it.
 * LOCKING: Assumes the AOT lock is held.
 */
static void
init_plt (MonoAotModule *amodule)
{
	int i;
	gpointer tramp;

	if (amodule->plt_inited)
		return;

	tramp = mono_create_specific_trampoline (amodule, MONO_TRAMPOLINE_AOT_PLT, mono_get_root_domain (), NULL);

	/*
	 * Initialize the PLT entries in the GOT to point to the default targets.
	 */

	tramp = mono_create_ftnptr (mono_domain_get (), tramp);
	 for (i = 1; i < amodule->info.plt_size; ++i)
		 /* All the default entries point to the AOT trampoline */
		 ((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;

	amodule->plt_inited = TRUE;
}

/*
 * mono_aot_get_plt_entry:
 *
 *   Return the address of the PLT entry called by the code at CODE if exists.
 */
guint8*
mono_aot_get_plt_entry (guint8 *code)
{
	MonoAotModule *amodule = find_aot_module (code);
	guint8 *target = NULL;

	if (!amodule)
		return NULL;

#ifdef TARGET_ARM
	if (amodule->thumb_end && code < amodule->thumb_end) {
		return mono_arm_get_thumb_plt_entry (code);
	}
#endif

#ifdef MONO_ARCH_AOT_SUPPORTED
	target = mono_arch_get_call_target (code);
#else
	g_assert_not_reached ();
#endif

#ifdef MONOTOUCH
	while (target != NULL) {
		if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
			return target;
		
		// Add 4 since mono_arch_get_call_target assumes we're passing
		// the instruction after the actual branch instruction.
		target = mono_arch_get_call_target (target + 4);
	}

	return NULL;
#else
	if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
		return target;
	else
		return NULL;
#endif
}

/*
 * mono_aot_get_plt_info_offset:
 *
 *   Return the PLT info offset belonging to the plt entry called by CODE.
 */
guint32
mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
{
	guint8 *plt_entry = mono_aot_get_plt_entry (code);

	g_assert (plt_entry);

	/* The offset is embedded inside the code after the plt entry */
#ifdef MONO_ARCH_AOT_SUPPORTED
	return mono_arch_get_plt_info_offset (plt_entry, regs, code);
#else
	g_assert_not_reached ();
	return 0;
#endif
}

static gpointer
mono_create_ftnptr_malloc (guint8 *code)
{
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
	MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));

	ftnptr->code = code;
	ftnptr->toc = NULL;
	ftnptr->env = NULL;

	return ftnptr;
#else
	return code;
#endif
}

/*
 * mono_aot_register_jit_icall:
 *
 *   Register a JIT icall which is called by trampolines in full-aot mode. This should
 * be called from mono_arch_init () during startup.
 */
void
mono_aot_register_jit_icall (const char *name, gpointer addr)
{
	/* No need for locking */
	if (!aot_jit_icall_hash)
		aot_jit_icall_hash = g_hash_table_new (g_str_hash, g_str_equal);
	g_hash_table_insert (aot_jit_icall_hash, (char*)name, addr);
}

/*
 * load_function_full:
 *
 *   Load the function named NAME from the aot image. 
 */
static gpointer
load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
{
	char *symbol;
	guint8 *p;
	int n_patches, pindex;
	MonoMemPool *mp;
	gpointer code;
	guint32 info_offset;

	/* Load the code */

	symbol = g_strdup_printf ("%s", name);
	find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&code);
	g_free (symbol);
	if (!code)
		g_error ("Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);

	/* Load info */

	symbol = g_strdup_printf ("%s_p", name);
	find_symbol (amodule->sofile, amodule->globals, symbol, (gpointer *)&p);
	g_free (symbol);
	if (!p)
		/* Nothing to patch */
		return code;

	info_offset = *(guint32*)p;
	if (out_tinfo) {
		MonoTrampInfo *tinfo;
		guint32 code_size, uw_info_len, uw_offset;
		guint8 *uw_info;
		/* Construct a MonoTrampInfo from the data in the AOT image */

		p += sizeof (guint32);
		code_size = *(guint32*)p;
		p += sizeof (guint32);
		uw_offset = *(guint32*)p;
		uw_info = amodule->unwind_info + uw_offset;
		uw_info_len = decode_value (uw_info, &uw_info);

		tinfo = g_new0 (MonoTrampInfo, 1);
		tinfo->code = code;
		tinfo->code_size = code_size;
		tinfo->uw_info = uw_info;
		tinfo->uw_info_len = uw_info_len;

		*out_tinfo = tinfo;
	}

	p = amodule->blob + info_offset;

	/* Similar to mono_aot_load_method () */

	n_patches = decode_value (p, &p);

	if (n_patches) {
		MonoJumpInfo *patches;
		guint32 *got_slots;

		mp = mono_mempool_new ();

		patches = load_patch_info (amodule, mp, n_patches, &got_slots, p, &p);
		g_assert (patches);

		for (pindex = 0; pindex < n_patches; ++pindex) {
			MonoJumpInfo *ji = &patches [pindex];
			gpointer target;

			if (amodule->got [got_slots [pindex]])
				continue;

			/*
			 * When this code is executed, the runtime may not be initalized yet, so
			 * resolve the patch info by hand.
			 */
			if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
				if (!strcmp (ji->data.name, "mono_get_lmf_addr")) {
					target = mono_get_lmf_addr;
				} else if (!strcmp (ji->data.name, "mono_thread_force_interruption_checkpoint")) {
					target = mono_thread_force_interruption_checkpoint;
				} else if (!strcmp (ji->data.name, "mono_exception_from_token")) {
					target = mono_exception_from_token;
				} else if (!strcmp (ji->data.name, "mono_throw_exception")) {
					target = mono_get_throw_exception ();
				} else if (strstr (ji->data.name, "trampoline_func_") == ji->data.name) {
					int tramp_type2 = atoi (ji->data.name + strlen ("trampoline_func_"));
					target = (gpointer)mono_get_trampoline_func (tramp_type2);
				} else if (strstr (ji->data.name, "specific_trampoline_lazy_fetch_") == ji->data.name) {
					/* atoll is needed because the the offset is unsigned */
					guint32 slot;
					int res;

					res = sscanf (ji->data.name, "specific_trampoline_lazy_fetch_%u", &slot);
					g_assert (res == 1);
					target = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
					target = mono_create_ftnptr_malloc (target);
				} else if (!strcmp (ji->data.name, "specific_trampoline_monitor_enter")) {
					target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
					target = mono_create_ftnptr_malloc (target);
				} else if (!strcmp (ji->data.name, "specific_trampoline_monitor_exit")) {
					target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
					target = mono_create_ftnptr_malloc (target);
				} else if (!strcmp (ji->data.name, "specific_trampoline_generic_class_init")) {
					target = mono_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
					target = mono_create_ftnptr_malloc (target);
				} else if (!strcmp (ji->data.name, "mono_thread_get_and_clear_pending_exception")) {
					target = mono_thread_get_and_clear_pending_exception;
				} else if (strstr (ji->data.name, "generic_trampoline_")) {
					target = mono_aot_get_trampoline (ji->data.name);
				} else if (aot_jit_icall_hash && g_hash_table_lookup (aot_jit_icall_hash, ji->data.name)) {
					/* Registered by mono_arch_init () */
					target = g_hash_table_lookup (aot_jit_icall_hash, ji->data.name);
				} else {
					fprintf (stderr, "Unknown relocation '%s'\n", ji->data.name);
					g_assert_not_reached ();
					target = NULL;
				}
			} else {
				/* Hopefully the code doesn't have patches which need method or 
				 * domain to be set.
				 */
				target = mono_resolve_patch_target (NULL, NULL, code, ji, FALSE);
				g_assert (target);
			}

			amodule->got [got_slots [pindex]] = target;
		}

		g_free (got_slots);

		mono_mempool_destroy (mp);
	}

	return code;
}

static gpointer
load_function (MonoAotModule *amodule, const char *name)
{
	return load_function_full (amodule, name, NULL);
}

/*
 * Return the trampoline identified by NAME from the mscorlib AOT file.
 * On ppc64, this returns a function descriptor.
 */
gpointer
mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
{
	MonoImage *image;
	MonoAotModule *amodule;

	image = mono_defaults.corlib;
	g_assert (image);

	amodule = image->aot_module;
	g_assert (amodule);

	return mono_create_ftnptr_malloc (load_function_full (amodule, name, out_tinfo));
}

gpointer
mono_aot_get_trampoline (const char *name)
{
	return mono_aot_get_trampoline_full (name, NULL);
}

#ifdef MONOTOUCH
#include <mach/mach.h>

static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
/* these sizes are for ARM code, parametrize if porting to other architectures (see arch_emit_specific_trampoline_pages)
 * trampoline size is assumed to be 8 bytes below as well (8 is the minimum for 32 bit archs, since we need to store
 * two pointers for trampoline in the data page).
 * the minimum for the common code must be at least sizeof(TrampolinePage), since we store the page info at the
 * beginning of the data page.
 */
static const int trampolines_pages_code_offsets [MONO_AOT_TRAMP_NUM] = {16, 16, 72, 16};

static unsigned char*
get_new_trampoline_from_page (int tramp_type)
{
	MonoAotModule *amodule;
	MonoImage *image;
	TrampolinePage *page;
	int count;
	void *tpage;
	vm_address_t addr, taddr;
	kern_return_t ret;
	vm_prot_t prot, max_prot;
	int psize;
	unsigned char *code;

	mono_aot_page_lock ();
	page = trampoline_pages [tramp_type];
	if (page && page->trampolines < page->trampolines_end) {
		code = page->trampolines;
		page->trampolines += 8;
		mono_aot_page_unlock ();
		return code;
	}
	mono_aot_page_unlock ();
	psize = mono_pagesize ();
	/* the trampoline template page is in the mscorlib module */
	image = mono_defaults.corlib;
	g_assert (image);

	amodule = image->aot_module;
	g_assert (amodule);

	if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
		tpage = load_function (amodule, "specific_trampolines_page");
	else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
		tpage = load_function (amodule, "rgctx_trampolines_page");
	else if (tramp_type == MONO_AOT_TRAMP_IMT_THUNK)
		tpage = load_function (amodule, "imt_trampolines_page");
	else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
		tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
	else
		g_error ("Incorrect tramp type for trampolines page");
	g_assert (tpage);
	/*g_warning ("loaded trampolines page at %x", tpage);*/

	/* avoid the unlikely case of looping forever */
	count = 40;
	page = NULL;
	while (page == NULL && count-- > 0) {
		addr = 0;
		/* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
		 * while the second will contain the trampolines.
		 */
		ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
		if (ret != KERN_SUCCESS) {
			g_error ("Cannot allocate memory for trampolines: %d", ret);
			break;
		}
		/*g_warning ("allocated trampoline double page at %x", addr);*/
		/* replace the second page with a remapped trampoline page */
		taddr = addr + psize;
		vm_deallocate (mach_task_self (), taddr, psize);
		ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
		if (ret != KERN_SUCCESS) {
			/* someone else got the page, try again  */
			vm_deallocate (mach_task_self (), addr, psize);
			continue;
		}
		/*g_warning ("remapped trampoline page at %x", taddr);*/

		mono_aot_page_lock ();
		page = trampoline_pages [tramp_type];
		/* some other thread already allocated, so use that to avoid wasting memory */
		if (page && page->trampolines < page->trampolines_end) {
			code = page->trampolines;
			page->trampolines += 8;
			mono_aot_page_unlock ();
			vm_deallocate (mach_task_self (), addr, psize);
			vm_deallocate (mach_task_self (), taddr, psize);
			return code;
		}
		page = (TrampolinePage*)addr;
		page->next = trampoline_pages [tramp_type];
		trampoline_pages [tramp_type] = page;
		page->trampolines = (void*)(taddr + trampolines_pages_code_offsets [tramp_type]);
		page->trampolines_end = (void*)(taddr + psize);
		code = page->trampolines;
		page->trampolines += 8;
		mono_aot_page_unlock ();
		return code;
	}
	g_error ("Cannot allocate more trampoline pages: %d", ret);
	return NULL;
}

#else
static unsigned char*
get_new_trampoline_from_page (int tramp_type)
{
	g_error ("Page trampolines not supported.");
	return NULL;
}
#endif


static gpointer
get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
{
	void *code;
	gpointer *data;

	code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);

	data = (gpointer*)((char*)code - mono_pagesize ());
	data [0] = arg;
	data [1] = tramp;
	/*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
	return code;

}

static gpointer
get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
{
	void *code;
	gpointer *data;

	code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);

	data = (gpointer*)((char*)code - mono_pagesize ());
	data [0] = arg;
	data [1] = tramp;
	/*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
	return code;

}

static gpointer
get_new_imt_trampoline_from_page (gpointer arg)
{
	void *code;
	gpointer *data;

	code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT_THUNK);

	data = (gpointer*)((char*)code - mono_pagesize ());
	data [0] = arg;
	/*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
	return code;

}

static gpointer
get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
{
	void *code;
	gpointer *data;

	code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);

	data = (gpointer*)((char*)code - mono_pagesize ());
	data [0] = arg;
	data [1] = tramp;
	/*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
	return code;
}

/* Return a given kind of trampoline */
static gpointer
get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
{
	MonoAotModule *amodule;
	int index, tramp_size;
	MonoImage *image;

	/* Currently, we keep all trampolines in the mscorlib AOT image */
	image = mono_defaults.corlib;
	g_assert (image);

	mono_aot_lock ();

	amodule = image->aot_module;
	g_assert (amodule);

	*out_amodule = amodule;

#ifdef MONOTOUCH
#define	MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instruction on how to fix this condition"
#else
#define	MONOTOUCH_TRAMPOLINES_ERROR ""
#endif
	if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
		g_error ("Ran out of trampolines of type %d in '%s' (%d)%s\n", 
				 tramp_type, image->name, amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
	}
	index = amodule->trampoline_index [tramp_type] ++;

	mono_aot_unlock ();

	*got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);

	tramp_size = amodule->info.trampoline_size [tramp_type];

	if (out_tramp_size)
		*out_tramp_size = tramp_size;

	return amodule->trampolines [tramp_type] + (index * tramp_size);
}

/*
 * Return a specific trampoline from the AOT file.
 */
gpointer
mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
{
	MonoAotModule *amodule;
	guint32 got_offset, tramp_size;
	guint8 *code, *tramp;
	static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
	static gboolean inited;
	static guint32 num_trampolines;

	if (!inited) {
		mono_aot_lock ();

		if (!inited) {
			mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
			inited = TRUE;
		}

		mono_aot_unlock ();
	}

	num_trampolines ++;

	if (!generic_trampolines [tramp_type]) {
		char *symbol;

		symbol = mono_get_generic_trampoline_name (tramp_type);
		generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
		g_free (symbol);
	}

	tramp = generic_trampolines [tramp_type];
	g_assert (tramp);

	if (USE_PAGE_TRAMPOLINES) {
		code = get_new_specific_trampoline_from_page (tramp, arg1);
		tramp_size = 8;
	} else {
		code = get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);

		amodule->got [got_offset] = tramp;
		amodule->got [got_offset + 1] = arg1;
	}

	if (code_len)
		*code_len = tramp_size;

	return code;
}

gpointer
mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
{
	MonoAotModule *amodule;
	guint8 *code;
	guint32 got_offset;

	if (USE_PAGE_TRAMPOLINES) {
		code = get_new_rgctx_trampoline_from_page (addr, ctx);
	} else {
		code = get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);

		amodule->got [got_offset] = ctx;
		amodule->got [got_offset + 1] = addr; 
	}

	/* The caller expects an ftnptr */
	return mono_create_ftnptr (mono_domain_get (), code);
}

gpointer
mono_aot_get_unbox_trampoline (MonoMethod *method)
{
	guint32 method_index = mono_metadata_token_index (method->token) - 1;
	MonoAotModule *amodule;
	gpointer code;
	guint32 *ut, *ut_end, *entry;
	int low, high, entry_index;

	if (method->is_inflated && !mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
		method_index = find_extra_method (method, &amodule);
		if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
			MonoMethod *shared = mini_get_shared_method_full (method, TRUE, TRUE);
			method_index = find_extra_method (shared, &amodule);
		}
		g_assert (method_index != 0xffffff);
	} else {
		amodule = method->klass->image->aot_module;
		g_assert (amodule);
	}

	ut = amodule->unbox_trampolines;
	ut_end = amodule->unbox_trampolines_end;

	/* Do a binary search in the sorted table */
	code = NULL;
	low = 0;
	high = (ut_end - ut) / 2;
	while (low < high) {
		entry_index = (low + high) / 2;
		entry = &ut [(entry_index * 2)];
		if (entry [0] < method_index) {
			low = entry_index + 1;
		} else if (entry [0] > method_index) {
			high = entry_index;
		} else {
			if (amodule->info.flags & MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES)
				code = get_arm_bl_target (entry + 1);
			else
				code = amodule->code + entry [1];
			break;
		}
	}
	g_assert (code);

	/* The caller expects an ftnptr */
	return mono_create_ftnptr (mono_domain_get (), code);
}

gpointer
mono_aot_get_lazy_fetch_trampoline (guint32 slot)
{
	char *symbol;
	gpointer code;
	MonoAotModule *amodule = mono_defaults.corlib->aot_module;
	guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
	static int count = 0;

	count ++;
	if (index >= amodule->info.num_rgctx_fetch_trampolines) {
		static gpointer addr;
		gpointer *info;

		/*
		 * Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
		 */
		if (!addr)
			addr = load_function (amodule, "rgctx_fetch_trampoline_general");
		info = mono_domain_alloc0 (mono_get_root_domain (), sizeof (gpointer) * 2);
		info [0] = GUINT_TO_POINTER (slot);
		info [1] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
		code = mono_aot_get_static_rgctx_trampoline (info, addr);
		return mono_create_ftnptr (mono_domain_get (), code);
	}

	symbol = mono_get_rgctx_fetch_trampoline_name (slot);
	code = load_function (mono_defaults.corlib->aot_module, symbol);
	g_free (symbol);
	/* The caller expects an ftnptr */
	return mono_create_ftnptr (mono_domain_get (), code);
}

gpointer
mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
{
	guint32 got_offset;
	gpointer code;
	gpointer *buf;
	int i, index, real_count;
	MonoAotModule *amodule;

	real_count = 0;
	for (i = 0; i < count; ++i) {
		MonoIMTCheckItem *item = imt_entries [i];

		if (item->is_equals)
			real_count ++;
	}

	/* Save the entries into an array */
	buf = mono_domain_alloc (domain, (real_count + 1) * 2 * sizeof (gpointer));
	index = 0;
	for (i = 0; i < count; ++i) {
		MonoIMTCheckItem *item = imt_entries [i];		

		if (!item->is_equals)
			continue;

		g_assert (item->key);

		buf [(index * 2)] = item->key;
		if (item->has_target_code) {
			gpointer *p = mono_domain_alloc (domain, sizeof (gpointer));
			*p = item->value.target_code;
			buf [(index * 2) + 1] = p;
		} else {
			buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
		}
		index ++;
	}
	buf [(index * 2)] = NULL;
	buf [(index * 2) + 1] = fail_tramp;
	
	if (USE_PAGE_TRAMPOLINES) {
		code = get_new_imt_trampoline_from_page (buf);
	} else {
		code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT_THUNK, 1, &amodule, &got_offset, NULL);

		amodule->got [got_offset] = buf;
	}

	return code;
}

gpointer
mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
{
	MonoAotModule *amodule;
	guint8 *code;
	guint32 got_offset;

	if (USE_PAGE_TRAMPOLINES) {
		code = get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
	} else {
		code = get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);

		amodule->got [got_offset] = arg;
		amodule->got [got_offset + 1] = addr; 
	}

	/* The caller expects an ftnptr */
	return mono_create_ftnptr (mono_domain_get (), code);
}
 
/*
 * mono_aot_set_make_unreadable:
 *
 *   Set whenever to make all mmaped memory unreadable. In conjuction with a
 * SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
 */
void
mono_aot_set_make_unreadable (gboolean unreadable)
{
	static int inited;

	make_unreadable = unreadable;

	if (make_unreadable && !inited) {
		mono_counters_register ("AOT pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
	}		
}

typedef struct {
	MonoAotModule *module;
	guint8 *ptr;
} FindMapUserData;

static void
find_map (gpointer key, gpointer value, gpointer user_data)
{
	MonoAotModule *module = (MonoAotModule*)value;
	FindMapUserData *data = (FindMapUserData*)user_data;

	if (!data->module)
		if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
			data->module = module;
}

static MonoAotModule*
find_module_for_addr (void *ptr)
{
	FindMapUserData data;

	if (!make_unreadable)
		return NULL;

	data.module = NULL;
	data.ptr = (guint8*)ptr;

	mono_aot_lock ();
	g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
	mono_aot_unlock ();

	return data.module;
}

/*
 * mono_aot_is_pagefault:
 *
 *   Should be called from a SIGSEGV signal handler to find out whenever @ptr is
 * within memory allocated by this module.
 */
gboolean
mono_aot_is_pagefault (void *ptr)
{
	if (!make_unreadable)
		return FALSE;

	/* 
	 * Not signal safe, but SIGSEGV's are synchronous, and
	 * this is only turned on by a MONO_DEBUG option.
	 */
	return find_module_for_addr (ptr) != NULL;
}

/*
 * mono_aot_handle_pagefault:
 *
 *   Handle a pagefault caused by an unreadable page by making it readable again.
 */
void
mono_aot_handle_pagefault (void *ptr)
{
#ifndef PLATFORM_WIN32
	guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
	int res;

	mono_aot_lock ();
	res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
	g_assert (res == 0);

	n_pagefaults ++;
	mono_aot_unlock ();
#endif
}

#else
/* AOT disabled */

void
mono_aot_init (void)
{
}

gpointer
mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
{
	return NULL;
}

gboolean
mono_aot_is_got_entry (guint8 *code, guint8 *addr)
{
	return FALSE;
}

gboolean
mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
{
	return FALSE;
}

gboolean
mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
{
	return FALSE;
}

MonoJitInfo *
mono_aot_find_jit_info (MonoDomain *domain, MonoImage *image, gpointer addr)
{
	return NULL;
}

gpointer
mono_aot_get_method_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
{
	return NULL;
}

guint8*
mono_aot_get_plt_entry (guint8 *code)
{
	return NULL;
}

gpointer
mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code)
{
	return NULL;
}

void
mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
{
}

gpointer
mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
{
	return NULL;
}

guint32
mono_aot_get_plt_info_offset (mgreg_t *regs, guint8 *code)
{
	g_assert_not_reached ();

	return 0;
}

gpointer
mono_aot_create_specific_trampoline (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
{
	g_assert_not_reached ();
	return NULL;
}

gpointer
mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
{
	g_assert_not_reached ();
	return NULL;
}

gpointer
mono_aot_get_trampoline (const char *name)
{
	g_assert_not_reached ();
	return NULL;
}

gpointer
mono_aot_get_unbox_trampoline (MonoMethod *method)
{
	g_assert_not_reached ();
	return NULL;
}

gpointer
mono_aot_get_lazy_fetch_trampoline (guint32 slot)
{
	g_assert_not_reached ();
	return NULL;
}

gpointer
mono_aot_get_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
{
	g_assert_not_reached ();
	return NULL;
}	

guint8*
mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
{
	g_assert_not_reached ();
	return NULL;
}

void
mono_aot_register_jit_icall (const char *name, gpointer addr)
{
}

#endif