File: dispatch.c

package info (click to toggle)
libjna-java 5.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,828 kB
  • sloc: java: 90,222; ansic: 4,994; xml: 3,713; makefile: 433; sh: 299
file content (3676 lines) | stat: -rw-r--r-- 122,646 bytes parent folder | download
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
/*
 * @(#)dispatch.c       1.9 98/03/22
 *
 * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
 * Copyright (c) 2007-2013 Timothy Wall. All Rights Reserved.
 * Copyright (c) 2007 Wayne Meissner. All Rights Reserved.
 *
 * The contents of this file is dual-licensed under 2 
 * alternative Open Source/Free licenses: LGPL 2.1 or later and 
 * Apache License 2.0. (starting with JNA version 4.0.0).
 * 
 * You can freely decide which license you want to apply to 
 * the project.
 * 
 * You may obtain a copy of the LGPL License at:
 * 
 * http://www.gnu.org/licenses/licenses.html
 * 
 * A copy is also included in the downloadable source code package
 * containing JNA, in file "LGPL2.1".
 * 
 * You may obtain a copy of the Apache License at:
 * 
 * http://www.apache.org/licenses/
 * 
 * A copy is also included in the downloadable source code package
 * containing JNA, in file "AL2.0".
 */

#include "dispatch.h"

#include <string.h>
#include <stdlib.h>

#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <psapi.h>
#define STRTYPE wchar_t*
#define NAME2CSTR(ENV,JSTR) newWideCString(ENV,JSTR)
#ifdef _WIN32_WCE
#include <tlhelp32.h>
#define DEFAULT_LOAD_OPTS 0 /* altered search path unsupported on CE */
#undef GetProcAddress
#define GetProcAddress GetProcAddressA
#else
/* See http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx:
 * "Note that the standard search strategy and the alternate search strategy
 * specified by LoadLibraryEx with LOAD_WITH_ALTERED_SEARCH_PATH differ in
 * just one way: The standard search begins in the calling application's
 * directory, and the alternate search begins in the directory of the
 * executable module that LoadLibraryEx is loading."
 */
#define DEFAULT_LOAD_OPTS LOAD_WITH_ALTERED_SEARCH_PATH
#endif
#define LOAD_LIBRARY(NAME,OPTS) (NAME ? LoadLibraryExW(NAME, NULL, OPTS) : GetModuleHandleW(NULL))
#define LOAD_ERROR() w32_format_error(GetLastError())
#define STR_ERROR(CODE) w32_format_error(CODE)
#define FREE_LIBRARY(HANDLE) (((HANDLE)==GetModuleHandleW(NULL) || FreeLibrary(HANDLE))?0:-1)
#define FIND_ENTRY(HANDLE, NAME) w32_find_entry(env, HANDLE, NAME)
#else
#include <dlfcn.h>
#include <errno.h>
#include <assert.h>
#define STRTYPE char*
#ifdef USE_DEFAULT_LIBNAME_ENCODING
#define NAME2CSTR(ENV,JSTR) newCString(ENV,JSTR)
#else
#define NAME2CSTR(ENV,JSTR) newCStringUTF8(ENV,JSTR)
#endif
#define DEFAULT_LOAD_OPTS (RTLD_LAZY|RTLD_GLOBAL)
#define LOAD_LIBRARY(NAME,OPTS) dlopen(NAME, OPTS)
static inline char * LOAD_ERROR() {
    const char* message = dlerror();
    char* buf = (char*) malloc(strlen(message) + 1 /* null */);
    strcpy(buf, message);
    return buf;
}
static inline char * STR_ERROR(int code) {
    int i;
    char* buf = NULL;
    for(i = 256; i < (10 * 1024); i += 256) {
        buf = (char*) malloc(i);
        int res = strerror_r(code, buf, i);
        if(res == 0) {
            break;
        }
        free(buf);
        buf = NULL;
        if(res != ERANGE) {
            break;
        }
    }
    if(buf == NULL) {
        int requiredBuffer = 25 /* static part*/ + 10 /* space for int */ + 1 /* null */;
        buf = (char*) malloc(requiredBuffer);
        snprintf(buf, requiredBuffer, "Failed to convert error: %d", code);
    }
    return buf;
}
#define FREE_LIBRARY(HANDLE) dlclose(HANDLE)
#define FIND_ENTRY(HANDLE, NAME) dlsym(HANDLE, NAME)
#endif

#ifdef _AIX
#undef DEFAULT_LOAD_OPTS
#define DEFAULT_LOAD_OPTS (RTLD_MEMBER| RTLD_LAZY | RTLD_GLOBAL)
#undef LOAD_LIBRARY
#define LOAD_LIBRARY(NAME,OPTS) dlopen(NAME, OPTS)
#endif

#include <stdlib.h>
#include <wchar.h>
#include <jni.h>

#ifndef NO_JAWT
#include <jawt.h>
#include <jawt_md.h>
#endif

#ifdef HAVE_PROTECTION
// When we have SEH, default to protection on
#if defined(_WIN32) && !(defined(_WIN64) && defined(__GNUC__))
static int _protect = 1;
#else
static int _protect;
#endif
#undef PROTECT
#define PROTECT _protect
#endif

#define CHARSET_UTF8 "utf8"

#ifdef __cplusplus
extern "C" {
#else
#include <stdbool.h>
#endif

#define MEMCPY(ENV,D,S,L) do {     \
  PSTART(); memcpy(D,S,L); PEND(ENV); \
} while(0)
#define MEMSET(ENV,D,C,L) do {        \
  PSTART(); memset(D,C,L); PEND(ENV); \
} while(0)

#define MASK_CC           com_sun_jna_Function_MASK_CC
#define THROW_LAST_ERROR  com_sun_jna_Function_THROW_LAST_ERROR
#define USE_VARARGS       com_sun_jna_Function_USE_VARARGS
#define USE_VARARGS_SHIFT com_sun_jna_Function_USE_VARARGS_SHIFT

/* Cached class, field and method IDs */
static jclass classObject;
static jclass classClass;
static jclass classMethod;
static jclass classVoid, classPrimitiveVoid;
static jclass classBoolean, classPrimitiveBoolean;
static jclass classByte, classPrimitiveByte;
static jclass classCharacter, classPrimitiveCharacter;
static jclass classShort, classPrimitiveShort;
static jclass classInteger, classPrimitiveInteger;
static jclass classLong, classPrimitiveLong;
static jclass classFloat, classPrimitiveFloat;
static jclass classDouble, classPrimitiveDouble;
static jclass classString, classWString;
#ifndef NO_NIO_BUFFERS
static jclass classBuffer;
static jclass classByteBuffer;
static jclass classCharBuffer;
static jclass classShortBuffer;
static jclass classIntBuffer;
static jclass classLongBuffer;
static jclass classFloatBuffer;
static jclass classDoubleBuffer;
#endif /* NO_NIO_BUFFERS */

static jclass classPointer;
static jclass classNative;
static jclass classStructure;
static jclass classStructureByValue;
static jclass classCallback;
static jclass classCallbackReference;
static jclass classAttachOptions;
static jclass classNativeMapped;
static jclass classIntegerType;
static jclass classPointerType;
static jclass classJNIEnv;
static jclass class_ffi_callback;
static jclass classFromNativeConverter;

static jmethodID MID_Class_getComponentType;
static jmethodID MID_Object_toString;
static jmethodID MID_String_getBytes;
static jmethodID MID_String_getBytes2;
static jmethodID MID_String_toCharArray;
static jmethodID MID_String_init_bytes;
static jmethodID MID_String_init_bytes2;
static jmethodID MID_Method_getReturnType;
static jmethodID MID_Method_getParameterTypes;
static jmethodID MID_Long_init;
static jmethodID MID_Integer_init;
static jmethodID MID_Short_init;
static jmethodID MID_Character_init;
static jmethodID MID_Byte_init;
static jmethodID MID_Boolean_init;
static jmethodID MID_Float_init;
static jmethodID MID_Double_init;
#ifndef NO_NIO_BUFFERS
static jmethodID MID_Buffer_position;
static jmethodID MID_ByteBuffer_array;
static jmethodID MID_ByteBuffer_arrayOffset;
static jmethodID MID_CharBuffer_array;
static jmethodID MID_CharBuffer_arrayOffset;
static jmethodID MID_ShortBuffer_array;
static jmethodID MID_ShortBuffer_arrayOffset;
static jmethodID MID_IntBuffer_array;
static jmethodID MID_IntBuffer_arrayOffset;
static jmethodID MID_LongBuffer_array;
static jmethodID MID_LongBuffer_arrayOffset;
static jmethodID MID_FloatBuffer_array;
static jmethodID MID_FloatBuffer_arrayOffset;
static jmethodID MID_DoubleBuffer_array;
static jmethodID MID_DoubleBuffer_arrayOffset;
#endif /* NO_NIO_BUFFERS */

static jmethodID MID_Pointer_init;
static jmethodID MID_Native_dispose;
static jmethodID MID_Native_fromNativeCallbackParam;
static jmethodID MID_Native_fromNative;
static jmethodID MID_Native_nativeType;
static jmethodID MID_Native_toNativeTypeMapped;
static jmethodID MID_Native_fromNativeTypeMapped;
static jmethodID MID_Structure_getTypeInfo;
static jmethodID MID_Structure_newInstance;
static jmethodID MID_Structure_read;
static jmethodID MID_Structure_write;
static jmethodID MID_CallbackReference_getCallback;
static jmethodID MID_CallbackReference_getFunctionPointer;
static jmethodID MID_CallbackReference_getNativeString;
static jmethodID MID_CallbackReference_initializeThread;
static jmethodID MID_NativeMapped_toNative;
static jmethodID MID_WString_init;
static jmethodID MID_FromNativeConverter_nativeType;
static jmethodID MID_ffi_callback_invoke;

static jfieldID FID_Boolean_value;
static jfieldID FID_Byte_value;
static jfieldID FID_Short_value;
static jfieldID FID_Character_value;
static jfieldID FID_Integer_value;
static jfieldID FID_Long_value;
static jfieldID FID_Float_value;
static jfieldID FID_Double_value;

static jfieldID FID_Pointer_peer;
static jfieldID FID_Structure_memory;
static jfieldID FID_Structure_typeInfo;
static jfieldID FID_IntegerType_value;
static jfieldID FID_PointerType_pointer;

static int IS_BIG_ENDIAN;

jstring fileEncoding;

/* Forward declarations */
static char* newCString(JNIEnv *env, jstring jstr);
static char* newCStringEncoding(JNIEnv *env, jstring jstr, const char* encoding);
static wchar_t* newWideCString(JNIEnv *env, jstring jstr);

#ifndef NO_NIO_BUFFERS
static void* getBufferArray(JNIEnv*, jobject, jobject*, void **, void **);
static void* getDirectBufferAddress(JNIEnv*, jobject);
#endif
static char getArrayComponentType(JNIEnv *, jobject);
static ffi_type* getStructureType(JNIEnv *, jobject);

typedef void (JNICALL* release_t)(JNIEnv*,jarray,void*,jint);

#ifdef _WIN32
static char*
w32_format_error(int err) {
  wchar_t* wbuf = NULL;
  char* buf = NULL;
  int wlen =
    FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM
                   |FORMAT_MESSAGE_IGNORE_INSERTS
                   |FORMAT_MESSAGE_ALLOCATE_BUFFER,
                   NULL, err, 0, (LPWSTR)&wbuf, 0, NULL);
  if (wlen > 0) {
    int bufSize = WideCharToMultiByte(CP_UTF8, 0, wbuf, -1, NULL, 0, NULL, NULL);
    buf = (char*)malloc(bufSize);
    int result = WideCharToMultiByte(CP_UTF8, 0, wbuf, -1, buf, bufSize, NULL, NULL);
    if (result == 0) {
      fprintf(stderr, "JNA: error converting error message: %d\n", (int)GET_LAST_ERROR());
      free(buf);
      buf = NULL;
    }
  }
  if (wbuf) {
    LocalFree(wbuf);
  }

  return buf;
}
static wchar_t*
w32_short_name(JNIEnv* env, jstring str) {
  wchar_t* wstr = newWideCString(env, str);
  if (wstr && *wstr) {
    DWORD required;
    size_t size = wcslen(wstr) + 5;
    wchar_t* prefixed = (wchar_t*)alloca(sizeof(wchar_t) * size);

    swprintf(prefixed, size, L"\\\\?\\%ls", wstr);

    if ((required = GetShortPathNameW(prefixed, NULL, 0)) != 0) {
      wchar_t* wshort = (wchar_t*)malloc(sizeof(wchar_t) * required);
      if (GetShortPathNameW(prefixed, wshort, required)) {
        free((void *)wstr);
        wstr = wshort;
      }
      else {
        char* buf = LOAD_ERROR();
        throwByName(env, EError, buf);
        free((void *)buf);
        free((void *)wstr);
        free((void *)wshort);
        wstr = NULL;
      }
    }
    else if (GET_LAST_ERROR() != ERROR_FILE_NOT_FOUND) { 
      char* buf = LOAD_ERROR();
      throwByName(env, EError, buf);
      free((void *)buf);
      free((void *)wstr);
      wstr = NULL;
    }
  }
  return wstr;
}

static HANDLE
w32_find_entry(JNIEnv* env, HANDLE handle, const char* funname) {
  void* func = NULL;
  if (handle != GetModuleHandle(NULL)) {
    func = GetProcAddress(handle, funname);
  }
  else {
#if defined(_WIN32_WCE)
    /* CE has no EnumProcessModules, have to use an alternate API */
    HANDLE snapshot;
    if ((snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0)) != INVALID_HANDLE_VALUE) {
      MODULEENTRY32 moduleInfo;
      moduleInfo.dwSize = sizeof(moduleInfo);
      if (Module32First(snapshot, &moduleInfo)) {
        do {
          if ((func = (void *) GetProcAddress(moduleInfo.hModule, funname))) {
            break;
          }
        } while (Module32Next(snapshot, &moduleInfo));
      }
      CloseToolhelp32Snapshot(snapshot);
    }
#else
    HANDLE cur_proc = GetCurrentProcess ();
    HMODULE *modules;
    DWORD needed, i;
    if (!EnumProcessModules (cur_proc, NULL, 0, &needed)) {
    fail:
      throwByName(env, EError, "Unexpected error enumerating modules");
      return 0;
    }
    modules = (HMODULE*) alloca (needed);
    if (!EnumProcessModules (cur_proc, modules, needed, &needed)) {
      goto fail;
    }
    for (i = 0; i < needed / sizeof (HMODULE); i++) {
      if ((func = (void *) GetProcAddress (modules[i], funname))) {
        break;
      }
    }
#endif
  }
  return func;
}
#endif /* _WIN32 */

#if 0
/** Invokes System.err.println (for debugging only). */
void
println(JNIEnv* env, const char* msg) {
  jclass cls = (*env)->FindClass(env, "java/lang/System");
  if (!cls) {
    fprintf(stderr, "JNA: failed to find java.lang.System\n");
    return;
  }
  jfieldID fid = (*env)->GetStaticFieldID(env, cls, "err",
					  "Ljava/io/PrintStream;");
  jobject err = (*env)->GetStaticObjectField(env, cls, fid);
  if (!err) {
    fprintf(stderr, "JNA: failed to find System.err\n");
    return;
  }
  jclass pscls = (*env)->FindClass(env, "java/io/PrintStream");
  if (!pscls) {
    fprintf(stderr, "JNA: failed to find java.io.PrintStream\n");
    return;
  }
  jmethodID mid = (*env)->GetMethodID(env, pscls, "println",
                                      "(Ljava/lang/String;)V");
  jstring str = newJavaString(env, msg, CHARSET_UTF8);
  (*env)->CallObjectMethod(env, err, mid, str);
}
#endif

/** Throw an exception by name */
void
throwByName(JNIEnv *env, const char *name, const char *msg)
{
  jclass cls;

  (*env)->ExceptionClear(env);

  cls = (*env)->FindClass(env, name);

  if (cls != NULL) { /* Otherwise an exception has already been thrown */
    (*env)->ThrowNew(env, cls, msg);

    /* It's a good practice to clean up the local references. */
    (*env)->DeleteLocalRef(env, cls);
  }
}

/** Translate FFI errors into exceptions. */
jboolean
ffi_error(JNIEnv* env, const char* op, ffi_status status) {
  char msg[MSG_SIZE];
  switch(status) {
  case FFI_BAD_ABI:
    snprintf(msg, sizeof(msg), "%s: Invalid calling convention (FFI_BAD_ABI)", op);
    throwByName(env, EIllegalArgument, msg);
    return JNI_TRUE;
  case FFI_BAD_TYPEDEF:
    snprintf(msg, sizeof(msg),
             "%s: Invalid structure definition (native typedef error, FFI_BAD_TYPEDEF)", op);
    throwByName(env, EIllegalArgument, msg);
    return JNI_TRUE;
  case FFI_BAD_ARGTYPE:
    snprintf(msg, sizeof(msg),
             "%s: Invalid argument type (FFI_BAD_ARGTYPE)", op);
    throwByName(env, EIllegalArgument, msg);
    return JNI_TRUE;
  default:
    snprintf(msg, sizeof(msg), "%s failed (%d)", op, status);
    throwByName(env, EError, msg);
    return JNI_TRUE;
  case FFI_OK:
    return JNI_FALSE;
  }
}

/* invoke the real native function */
static void
dispatch(JNIEnv *env, void* func, jint flags, jobjectArray args,
         ffi_type *return_type, void *presult)
{
  int i, nargs;
  jvalue* c_args;
  char array_pt;
  struct _array_elements {
    jobject array;
    void *elems;
    release_t release;
  } *array_elements;
  volatile int array_count = 0;
  ffi_cif cif;
  ffi_type** arg_types;
  void** arg_values;
  ffi_abi abi;
  ffi_status status;
  char msg[MSG_SIZE];
  callconv_t callconv = flags & MASK_CC;
  const char* volatile throw_type = NULL;
  const char* volatile throw_msg = NULL;
  int fixed_args = (flags >> USE_VARARGS_SHIFT) & USE_VARARGS;

  nargs = (*env)->GetArrayLength(env, args);

  if (nargs > MAX_NARGS) {
    snprintf(msg, sizeof(msg), "Too many arguments (max %ld)", MAX_NARGS);
    throwByName(env, EUnsupportedOperation, msg);
    return;
  }

  c_args = (jvalue*)alloca(nargs * sizeof(jvalue));
  array_elements = (struct _array_elements*)
    alloca(nargs * sizeof(struct _array_elements));
  arg_types = (ffi_type**)alloca(nargs * sizeof(ffi_type*));
  arg_values = (void**)alloca(nargs * sizeof(void*));

  for (i = 0; i < nargs; i++) {
    jobject arg = (*env)->GetObjectArrayElement(env, args, i);

    if (arg == NULL) {
      c_args[i].l = NULL;
      arg_types[i] = &ffi_type_pointer;
      arg_values[i] = &c_args[i].l;
    }
    else if ((*env)->IsInstanceOf(env, arg, classBoolean)) {
      c_args[i].i = (*env)->GetBooleanField(env, arg, FID_Boolean_value);
      arg_types[i] = &ffi_type_uint32;
      arg_values[i] = &c_args[i].i;
    }
    else if ((*env)->IsInstanceOf(env, arg, classByte)) {
      c_args[i].b = (*env)->GetByteField(env, arg, FID_Byte_value);
      // Promote char to int if we prepare a varargs call
      if(fixed_args && i >= fixed_args && sizeof(char) < sizeof(int)) {
        arg_types[i] = &ffi_type_uint32;
        arg_values[i] = alloca(sizeof(int));
        *(int*)arg_values[i] = (int) c_args[i].b;
      } else {
        arg_types[i] = &ffi_type_sint8;
        arg_values[i] = &c_args[i].b;
      }
    }
    else if ((*env)->IsInstanceOf(env, arg, classShort)) {
      c_args[i].s = (*env)->GetShortField(env, arg, FID_Short_value);
      // Promote short to int if we prepare a varargs call
      if(fixed_args && i >= fixed_args && sizeof(short) < sizeof(int)) {
        arg_types[i] = &ffi_type_uint32;
        arg_values[i] = alloca(sizeof(int));
        *(int*)arg_values[i] = (int) c_args[i].s;
      } else {
        arg_types[i] = &ffi_type_sint16;
        arg_values[i] = &c_args[i].s;
      }
    }
    else if ((*env)->IsInstanceOf(env, arg, classCharacter)) {
      if (sizeof(wchar_t) == 2) {
        c_args[i].c = (*env)->GetCharField(env, arg, FID_Character_value);
        if(fixed_args && i >= fixed_args && sizeof(short) < sizeof(int)) {
          arg_types[i] = &ffi_type_uint32;
          arg_values[i] = alloca(sizeof(int));
          *(int*)arg_values[i] = (int) c_args[i].c;    
        } else {
          arg_types[i] = &ffi_type_uint16;
          arg_values[i] = &c_args[i].c;
        }
      }
      else if (sizeof(wchar_t) == 4) {
        c_args[i].i = (*env)->GetCharField(env, arg, FID_Character_value);
        arg_types[i] = &ffi_type_uint32;
        arg_values[i] = &c_args[i].i;
      }
      else {
        snprintf(msg, sizeof(msg), "Unsupported wchar_t size (%d)", (int)sizeof(wchar_t));
        throw_type = EUnsupportedOperation;
        throw_msg = msg;
        goto cleanup;
      }
    }
    else if ((*env)->IsInstanceOf(env, arg, classInteger)) {
      c_args[i].i = (*env)->GetIntField(env, arg, FID_Integer_value);
      arg_types[i] = &ffi_type_sint32;
      arg_values[i] = &c_args[i].i;
    }
    else if ((*env)->IsInstanceOf(env, arg, classLong)) {
      c_args[i].j = (*env)->GetLongField(env, arg, FID_Long_value);
      arg_types[i] = &ffi_type_sint64;
      arg_values[i] = &c_args[i].j;
    }
    else if ((*env)->IsInstanceOf(env, arg, classFloat)) {
      c_args[i].f = (*env)->GetFloatField(env, arg, FID_Float_value);
      arg_types[i] = &ffi_type_float;
      arg_values[i] = &c_args[i].f;
    }
    else if ((*env)->IsInstanceOf(env, arg, classDouble)) {
      c_args[i].d = (*env)->GetDoubleField(env, arg, FID_Double_value);
      arg_types[i] = &ffi_type_double;
      arg_values[i] = &c_args[i].d;
    }
    else if ((*env)->IsInstanceOf(env, arg, classPointer)) {
      c_args[i].l = getNativeAddress(env, arg);
      arg_types[i] = &ffi_type_pointer;
      arg_values[i] = &c_args[i].l;
    }
    else if ((*env)->IsInstanceOf(env, arg, classJNIEnv)) {
      c_args[i].l = (void*)env;
      arg_types[i] = &ffi_type_pointer;
      arg_values[i] = &c_args[i].l;
    }
    else if ((*env)->IsInstanceOf(env, arg, classStructure)) {
      c_args[i].l = getStructureAddress(env, arg);
      arg_types[i] = getStructureType(env, arg);
      arg_values[i] = c_args[i].l;
      if (!arg_types[i]) {
        snprintf(msg, sizeof(msg),
                 "Structure type info not initialized at argument %d", i);
        throw_type = EIllegalState;
        throw_msg = msg;
        goto cleanup;
      }
    }
#ifndef NO_NIO_BUFFERS
    else if ((*env)->IsInstanceOf(env, arg, classBuffer)) {
      c_args[i].l = getDirectBufferAddress(env, arg);
      arg_types[i] = &ffi_type_pointer;
      arg_values[i] = &c_args[i].l;
      if (c_args[i].l == NULL) {
        c_args[i].l =
          getBufferArray(env, arg, &array_elements[array_count].array,
                         &array_elements[array_count].elems,
                         (void**)&array_elements[array_count].release);
        if (c_args[i].l == NULL) {
          throw_type = EIllegalArgument;
          throw_msg = "Buffer arguments must be direct or have a primitive backing array";
          goto cleanup;
        }
        ++array_count;
      }
    }
#endif /* NO_NIO_BUFFERS */
    else if ((array_pt = getArrayComponentType(env, arg)) != 0
             && array_pt != 'L') {
      void *ptr = NULL;
      release_t release = NULL;

#define GET_ELEMS(TYPE) do {ptr=(*env)->Get##TYPE##ArrayElements(env,arg,NULL); release=(void*)(*env)->Release##TYPE##ArrayElements; }while(0)
      switch(array_pt) {
      case 'Z': GET_ELEMS(Boolean); break;
      case 'B': GET_ELEMS(Byte); break;
      case 'C': GET_ELEMS(Char); break;
      case 'S': GET_ELEMS(Short); break;
      case 'I': GET_ELEMS(Int); break;
      case 'J': GET_ELEMS(Long); break;
      case 'F': GET_ELEMS(Float); break;
      case 'D': GET_ELEMS(Double); break;
      }
      if (!ptr) {
        throw_type = EOutOfMemory;
        throw_msg = "Could not obtain memory for primitive buffer";
        goto cleanup;
      }
      c_args[i].l = ptr;
      arg_types[i] = &ffi_type_pointer;
      arg_values[i] = &c_args[i].l;
      array_elements[array_count].array = arg;
      array_elements[array_count].elems = ptr;
      array_elements[array_count++].release = release;
    }
    else {
      // Anything else, pass directly as a pointer
      c_args[i].l = (void*)arg;
      arg_types[i] = &ffi_type_pointer;
      arg_values[i] = &c_args[i].l;
    }
  }

  switch (callconv) {
  case CALLCONV_C:
    abi = FFI_DEFAULT_ABI;
    break;
#ifdef _WIN32
  case CALLCONV_STDCALL:
#if defined(_WIN64) || defined(_WIN32_WCE)
    // Ignore requests for stdcall on win64/wince
    abi = FFI_DEFAULT_ABI;
#else
    abi = FFI_STDCALL;
#endif
    break;
#endif // _WIN32
  default:
    abi = (int)callconv;
    if (!(abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI)) {
      snprintf(msg, sizeof(msg),
               "Unrecognized calling convention: %d", abi);
      throw_type = EIllegalArgument;
      throw_msg = msg;
      goto cleanup;
    }
    break;
  }

  status = fixed_args
    ? ffi_prep_cif_var(&cif, abi, fixed_args, nargs, return_type, arg_types)
    : ffi_prep_cif(&cif, abi, nargs, return_type, arg_types);
  if (!ffi_error(env, "Native call setup", status)) {
    PSTART();
    if ((flags & THROW_LAST_ERROR) != 0) {
      SET_LAST_ERROR(0);
    }
    ffi_call(&cif, FFI_FN(func), presult, arg_values);
    {
      int err = GET_LAST_ERROR();
      JNA_set_last_error(env, err);
      if ((flags & THROW_LAST_ERROR) && err) {
        char* emsg = STR_ERROR(err);
        snprintf(msg, MSG_SIZE, "[%d] %s", err, emsg);
        free(emsg);
        throw_type = ELastError;
        throw_msg = msg;
      }
    }

    PROTECTED_END(do { throw_type=EError;throw_msg="Invalid memory access";} while(0));
  }

 cleanup:

  // Release array elements
  for (i=0;i < array_count;i++) {
    array_elements[i].release(env, array_elements[i].array,
                              array_elements[i].elems, 0);
  }

  // Must raise any exception *after* all other JNI operations
  if (throw_type) {
    throwByName(env, throw_type, throw_msg);
  }
}

/** Copy characters from the Java character array into native memory. */
static void
getChars(JNIEnv* env, wchar_t* volatile dst, jcharArray chars, volatile jint off, volatile jint len) {
  PSTART();

  if (sizeof(jchar) == sizeof(wchar_t)) {
    (*env)->GetCharArrayRegion(env, chars, off, len, (jchar*)dst);
  }
  else {
    jchar* buf;
    int count = len > 1000 ? 1000 : len;
    buf = (jchar *)alloca(count * sizeof(jchar));
    if (!buf) {
      throwByName(env, EOutOfMemory, "Can't read characters");
    }
    else {
      while (len > 0) {
        int i;
        (*env)->GetCharArrayRegion(env, chars, off, count, buf);
        for (i=0;i < count;i++) {
          // TODO: ensure proper encoding conversion from jchar to native
          // wchar_t 
          dst[i] = (wchar_t)buf[i];
        }
        dst += count;
        off += count;
        len -= count;
        if (count > len) count = len;
      }
    }
  }
  PEND(env);
}

static void
setChars(JNIEnv* env, wchar_t* src, jcharArray chars, volatile jint off, volatile jint len) {
  jchar* buf = (jchar*)src;
  PSTART();

  if (sizeof(jchar) == sizeof(wchar_t)) {
    (*env)->SetCharArrayRegion(env, chars, off, len, buf);
  }
  else {
    int count = len > 1000 ? 1000 : len;
    buf = (jchar *)alloca(count * sizeof(jchar));
    if (!buf) {
      throwByName(env, EOutOfMemory, "Can't write characters");
    }
    else {
      while (len > 0) {
        int i;
        for (i=0;i < count;i++) {
          buf[i] = (jchar)src[off+i];
        }
        (*env)->SetCharArrayRegion(env, chars, off, count, buf);
        off += count;
        len -= count;
        if (count > len) count = len;
      }
    }
  }
  PEND(env);
}

/* Translates a Java string to a C string using the
 * String.getBytes(byte[],String), using the requested encoding.
 */
static char *
newCString(JNIEnv *env, jstring jstr)
{
    jbyteArray bytes = 0;
    char *result = NULL;

    bytes = (*env)->CallObjectMethod(env, jstr, MID_String_getBytes);
    if (!(*env)->ExceptionCheck(env)) {
        jint len = (*env)->GetArrayLength(env, bytes);
        result = (char *)malloc(len + 1);
        if (result == NULL) {
            (*env)->DeleteLocalRef(env, bytes);
            throwByName(env, EOutOfMemory, "Can't allocate C string");
            return NULL;
        }
        (*env)->GetByteArrayRegion(env, bytes, 0, len, (jbyte *)result);
        result[len] = 0; /* NUL-terminate */
    }
    (*env)->DeleteLocalRef(env, bytes);
    return result;
}

/* Translates a Java string to a C string using the String.getBytes("UTF8")
 * method, which uses UTF8 encoding.
 */
const char *
newCStringUTF8(JNIEnv *env, jstring jstr)
{
  return newCStringEncoding(env, jstr, CHARSET_UTF8);
}

static char*
newCStringEncoding(JNIEnv *env, jstring jstr, const char* encoding)
{
    jbyteArray bytes = 0;
    char *result = NULL;

    if (!encoding) return newCString(env, jstr);

    bytes = (*env)->CallObjectMethod(env, jstr, MID_String_getBytes2,
                                     newJavaString(env, encoding, CHARSET_UTF8));
    if (!(*env)->ExceptionCheck(env)) {
        jint len = (*env)->GetArrayLength(env, bytes);
        result = (char *)malloc(len + 1);
        if (result == NULL) {
            (*env)->DeleteLocalRef(env, bytes);
            throwByName(env, EOutOfMemory, "Can't allocate C string");
            return NULL;
        }
        (*env)->GetByteArrayRegion(env, bytes, 0, len, (jbyte *)result);
        result[len] = 0; /* NUL-terminate */
    }
    (*env)->DeleteLocalRef(env, bytes);
    return result;
}

/* Translates a Java string to a wide C string using the String.toCharArray
 * method.
 */
static wchar_t *
newWideCString(JNIEnv *env, jstring str)
{
    jcharArray chars = 0;
    wchar_t *result = NULL;

    if ((*env)->IsSameObject(env, str, NULL)) {
      return result;
    }

    chars = (*env)->CallObjectMethod(env, str, MID_String_toCharArray);
    if (!(*env)->ExceptionCheck(env)) {
        jint len = (*env)->GetArrayLength(env, chars);
        result = (wchar_t *)malloc(sizeof(wchar_t) * (len + 1));
        if (result == NULL) {
            (*env)->DeleteLocalRef(env, chars);
            throwByName(env, EOutOfMemory, "Can't allocate wide C string");
            return NULL;
        }
        getChars(env, result, chars, 0, len);
        if ((*env)->ExceptionCheck(env)) {
          free((void *)result);
          result = NULL;
        }
        else {
          result[len] = 0; /* NUL-terminate */
        }
    }
    (*env)->DeleteLocalRef(env, chars);
    return result;
}

jobject
newJavaWString(JNIEnv *env, const wchar_t* ptr) {
  if (ptr) {
    jstring s = newJavaString(env, (const char*)ptr, NULL);
    return (*env)->NewObject(env, classWString, MID_WString_init, s);
  }
  return NULL;
}

jstring
encodingString(JNIEnv *env, const char* ptr) {
  jstring result = NULL;
  jbyteArray bytes = 0;
  int len = (int)strlen((const char*)ptr);
  
  bytes = (*env)->NewByteArray(env, len);
  if (bytes != NULL) {
    (*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte *)ptr);
    result = (*env)->NewObject(env, classString,
                               MID_String_init_bytes, bytes);
    (*env)->DeleteLocalRef(env, bytes);
  }
  return result;
}

/* Constructs a Java string from a char array (using the String(byte[],String)
 * constructor) or a short array (using the
 * String(char[]) ctor, which uses the character values unmodified).
 */
jstring
newJavaString(JNIEnv *env, const char *ptr, const char* charset)
{
    volatile jstring result = 0;
    PSTART();

    if (ptr) {
      if (charset == NULL) {
        // TODO: proper conversion from native wchar_t to jchar, if any
        jsize len = (int)wcslen((const wchar_t*)ptr);
        if (sizeof(jchar) != sizeof(wchar_t)) {
          // NOTE: while alloca may succeed here, writing to the stack
          // memory may fail with really large buffers
          jchar* buf = (jchar*)malloc(len * sizeof(jchar));
          if (!buf) {
            throwByName(env, EOutOfMemory, "Can't allocate space for conversion to Java String");
          }
          else {
            int i;
            for (i=0;i < len;i++) {
              buf[i] = *((const wchar_t*)ptr + i);
            }
            result = (*env)->NewString(env, buf, len);
            free((void*)buf);
          }
        }
        else {
          result = (*env)->NewString(env, (const jchar*)ptr, len);
        }
      }
      else {
        jbyteArray bytes = 0;
        int len = (int)strlen((const char*)ptr);

        bytes = (*env)->NewByteArray(env, len);
        if (bytes != NULL) {
          (*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte *)ptr);
          result = (*env)->NewObject(env, classString,
                                     MID_String_init_bytes2, bytes, 
                                     encodingString(env, charset));
          (*env)->DeleteLocalRef(env, bytes);
        }
      }
    }
    PEND(env);

    return result;
}

jobject
newJavaPointer(JNIEnv *env, void *p)
{
    jobject obj = NULL;
    if (p != NULL) {
      obj = (*env)->NewObject(env, classPointer, MID_Pointer_init, A2L(p));
    }
    return obj;
}

jobject
newJavaStructure(JNIEnv *env, void *data, jclass type)
{
  if (data != NULL) {
    volatile jobject obj = (*env)->CallStaticObjectMethod(env, classStructure, MID_Structure_newInstance, type, A2L(data));
    if (obj == NULL) {
      fprintf(stderr, "JNA: failed to create structure\n");
    }
    return obj;
  }
  return NULL;
}

jobject
newJavaCallback(JNIEnv* env, void* fptr, jclass type)
{
  if (fptr != NULL) {
    jobject ptr = newJavaPointer(env, fptr);
    return (*env)->CallStaticObjectMethod(env, classCallbackReference,
                                          MID_CallbackReference_getCallback,
                                          type, ptr, JNI_TRUE);
  }
  return NULL;
}

void*
getNativeString(JNIEnv* env, jstring s, jboolean wide) {
  if (s != NULL) {
    jobject ptr = (*env)->CallStaticObjectMethod(env, classCallbackReference,
                                                 MID_CallbackReference_getNativeString,
                                                 s, wide);
    if (!(*env)->ExceptionCheck(env)) {
      return getNativeAddress(env, ptr);
    }
  }
  return NULL;
}

int
get_conversion_flag(JNIEnv* env, jclass cls) {
  int type = get_java_type(env, cls);
  if (type == 's') {
    return CVT_STRUCTURE_BYVAL;
  }
  if (type == '*') {
    if ((*env)->IsAssignableFrom(env, cls, classPointer)) {
      return CVT_POINTER;
    }
    if ((*env)->IsAssignableFrom(env, cls, classStructure)) {
      return CVT_STRUCTURE;
    }
    if ((*env)->IsAssignableFrom(env, cls, classString)) {
      return CVT_STRING;
    }
    if ((*env)->IsAssignableFrom(env, cls, classWString)) {
      return CVT_WSTRING;
    }
    if ((*env)->IsAssignableFrom(env, cls, classCallback)) {
      return CVT_CALLBACK;
    }
    if ((*env)->IsAssignableFrom(env, cls, classIntegerType)) {
      return CVT_INTEGER_TYPE;
    }
    if ((*env)->IsAssignableFrom(env, cls, classPointerType)) {
      return CVT_POINTER_TYPE;
    }
    if ((*env)->IsAssignableFrom(env, cls, classNativeMapped)) {
      return CVT_NATIVE_MAPPED;
    }
  }
  return CVT_DEFAULT;
}

int
get_java_type_from_ffi_type(ffi_type* type) {
  switch(type->type) {
    // NOTE 'Z' aliases 'C' on *nix and platforms where sizeof(wchar_t) is 4;
    // this will cause problems if anyone ever installs a type mapper for 
    // char/Character (not a common arg type)
  case FFI_TYPE_UINT32: return 'Z';
  case FFI_TYPE_SINT8: return 'B';
  case FFI_TYPE_SINT16: return 'S';
  case FFI_TYPE_UINT16: return 'C';
  case FFI_TYPE_SINT32: return 'I';
  case FFI_TYPE_SINT64: return 'J';
  case FFI_TYPE_FLOAT: return 'F';
  case FFI_TYPE_DOUBLE: return 'D';
  default: return '*';
  }
}

int
get_java_type(JNIEnv* env, jclass cls) {

  if ((*env)->IsSameObject(env, classVoid, cls)
      || (*env)->IsSameObject(env, classPrimitiveVoid, cls))
    return 'V';
  if ((*env)->IsSameObject(env, classBoolean, cls)
      || (*env)->IsSameObject(env, classPrimitiveBoolean, cls))
    return 'Z';
  if ((*env)->IsSameObject(env, classByte, cls)
      || (*env)->IsSameObject(env, classPrimitiveByte, cls))
    return 'B';
  if ((*env)->IsSameObject(env, classCharacter, cls)
      || (*env)->IsSameObject(env, classPrimitiveCharacter, cls))
    return 'C';
  if ((*env)->IsSameObject(env,classShort, cls)
      || (*env)->IsSameObject(env, classPrimitiveShort, cls))
    return 'S';
  if ((*env)->IsSameObject(env, classInteger, cls)
      || (*env)->IsSameObject(env, classPrimitiveInteger, cls))
    return 'I';
  if ((*env)->IsSameObject(env, classLong, cls)
      || (*env)->IsSameObject(env, classPrimitiveLong, cls))
    return 'J';
  if ((*env)->IsSameObject(env, classFloat, cls)
      || (*env)->IsSameObject(env, classPrimitiveFloat, cls))
    return 'F';
  if ((*env)->IsSameObject(env, classDouble, cls)
      || (*env)->IsSameObject(env, classPrimitiveDouble, cls))
    return 'D';
  if ((*env)->IsAssignableFrom(env, cls, classStructure)) {
    if ((*env)->IsAssignableFrom(env, cls, classStructureByValue))
      return 's';
    return '*';
  }
  if ((*env)->IsAssignableFrom(env, cls, classPointer)
      || (*env)->IsAssignableFrom(env, cls, classCallback)
      || (*env)->IsAssignableFrom(env, cls, classNativeMapped)
      || (*env)->IsAssignableFrom(env, cls, classWString)
      || (*env)->IsAssignableFrom(env, cls, classString))
    return '*';
  return -1;
}

jlong
getIntegerTypeValue(JNIEnv* env, jobject obj) {
  if(obj == NULL) {
    return 0;
  } else {
    return (*env)->GetLongField(env, obj, FID_IntegerType_value);
  }
}

void*
getPointerTypeAddress(JNIEnv* env, jobject obj) {
  return getNativeAddress(env, (*env)->GetObjectField(env, obj, FID_PointerType_pointer));
}

void *
getStructureAddress(JNIEnv *env, jobject obj) {
  if (obj != NULL) {
    jobject ptr = (*env)->GetObjectField(env, obj, FID_Structure_memory);
    if (!(*env)->ExceptionCheck(env)) {
      return getNativeAddress(env, ptr);
    }
  }
  return NULL;
}

void
writeStructure(JNIEnv *env, jobject s) {
  if (s != NULL) {
    (*env)->CallVoidMethod(env, s, MID_Structure_write);
  }
}

void *
getCallbackAddress(JNIEnv *env, jobject obj) {
  if (obj != NULL) {
    jobject ptr = (*env)->CallStaticObjectMethod(env, classCallbackReference, MID_CallbackReference_getFunctionPointer, obj, JNI_TRUE);
    if (!(*env)->ExceptionCheck(env)) {
      return getNativeAddress(env, ptr);
    }
  }
  return NULL;
}

jobject
initializeThread(callback* cb, AttachOptions* args) {
  JavaVM* jvm = cb->vm;
  JNIEnv* env;
  jobject group = NULL;
  int attached = (*jvm)->GetEnv(jvm, (void *)&env, JNI_VERSION_1_4) == JNI_OK;

  if (!attached) {
    if ((*jvm)->AttachCurrentThread(jvm, (void *)&env, NULL) != JNI_OK) {
      fprintf(stderr, "JNA: Can't attach native thread to VM for callback thread initialization\n");
      return NULL;
    }
  }
  (*env)->PushLocalFrame(env, 16);
  {
    jobject cbobj = (*env)->NewLocalRef(env, cb->object);
    if (!(*env)->IsSameObject(env, cbobj, NULL)) {
      jobject argsobj = newJavaStructure(env, args, classAttachOptions);
      group = (*env)->CallStaticObjectMethod(env, classCallbackReference,
                                             MID_CallbackReference_initializeThread,
                                             cbobj, argsobj);
      if (group != NULL) {
        group = (*env)->NewWeakGlobalRef(env, group);
      }
      if (args->name != NULL) {
        // Make a copy, since the Java Structure which owns this native memory
        // will go out of scope and be available for GC
        args->name = STRDUP(args->name);
      }
    }
  }
  (*env)->PopLocalFrame(env, NULL);
  if (!attached) {
    if ((*jvm)->DetachCurrentThread(jvm) != 0) {
      fprintf(stderr, "JNA: could not detach thread after callback init\n");
    }
  }

  return group;
}

jclass
getNativeType(JNIEnv* env, jclass cls) {
  return (*env)->CallStaticObjectMethod(env, classNative,
                                        MID_Native_nativeType, cls);
}

jclass
getNativeTypeMapped(JNIEnv* env, jobject converter) {
  return (*env)->CallObjectMethod(env, converter,
                                          MID_FromNativeConverter_nativeType);
}

void
toNative(JNIEnv* env, jobject obj, void* valuep, size_t size, jboolean promote, const char* encoding) {
  if (obj != NULL) {
    jobject arg = (*env)->CallObjectMethod(env, obj, MID_NativeMapped_toNative);
    if (!(*env)->ExceptionCheck(env)) {
      extract_value(env, arg, valuep, size, promote, encoding);
    }
  }
  else {
    MEMSET(env, valuep, 0, size);
  }
}

static void
toNativeTypeMapped(JNIEnv* env, jobject obj, void* valuep, size_t size, jobject to_native, const char* encoding) {
  if (obj != NULL) {
    jobject arg = (*env)->CallStaticObjectMethod(env, classNative, MID_Native_toNativeTypeMapped, to_native, obj);
    if (!(*env)->ExceptionCheck(env)) {
      extract_value(env, arg, valuep, size, JNI_FALSE, encoding);
    }
  }
  else {
    MEMSET(env, valuep, 0, size);
  }
}

static void
fromNativeTypeMapped(JNIEnv* env, jobject from_native,
                     void* native_return_value,
                     int jtype, size_t size,
                     jobject java_method,
                     void* result_storage,
                     const char* encoding) {
  jobject value = new_object(env, (char)jtype, native_return_value, JNI_TRUE, encoding);
  if (!(*env)->ExceptionCheck(env)) {
    jobject obj = (*env)->CallStaticObjectMethod(env, classNative,
                                                 MID_Native_fromNativeTypeMapped,
                                                 from_native, value, java_method);
    if (!(*env)->ExceptionCheck(env)) {
      // Convert objects into primitive types if the return class demands it
      jclass java_return_class = (*env)->CallObjectMethod(env, java_method, MID_Method_getReturnType);
      if ((*env)->IsSameObject(env, java_return_class, classPrimitiveBoolean)
          || (*env)->IsSameObject(env, java_return_class, classPrimitiveByte)
          || (*env)->IsSameObject(env, java_return_class, classPrimitiveCharacter)
          || (*env)->IsSameObject(env, java_return_class, classPrimitiveShort)
          || (*env)->IsSameObject(env, java_return_class, classPrimitiveInteger)
          || (*env)->IsSameObject(env, java_return_class, classPrimitiveLong)
          || (*env)->IsSameObject(env, java_return_class, classPrimitiveFloat)
          || (*env)->IsSameObject(env, java_return_class, classPrimitiveDouble)) {
        extract_value(env, obj, result_storage, size, JNI_TRUE, encoding);
      }
      else {
        *(jobject*)result_storage = obj;
      }
    }
  }
}

jobject
fromNativeCallbackParam(JNIEnv* env, jclass javaClass, ffi_type* type, void* resp, jboolean promote, const char* encoding) {
  int jtype = get_java_type_from_ffi_type(type);
  jobject value = new_object(env, (char)jtype, resp, promote, encoding);
  if (!(*env)->ExceptionCheck(env)) {
    return (*env)->CallStaticObjectMethod(env, classNative,
                                          MID_Native_fromNativeCallbackParam,
                                          javaClass, value);
  }
  return NULL;
}

jobject
fromNative(JNIEnv* env, jobject javaMethod, ffi_type* type, void* resp, jboolean promote, const char* encoding) {
  int jtype = get_java_type_from_ffi_type(type);
  jobject value = new_object(env, (char)jtype, resp, promote, encoding);
  if (!(*env)->ExceptionCheck(env)) {
    return (*env)->CallStaticObjectMethod(env, classNative,
                                          MID_Native_fromNative,
                                          javaMethod, value);
  }
  return NULL;
}


static ffi_type*
getStructureType(JNIEnv *env, jobject obj) {
  jlong typeInfo = (*env)->GetLongField(env, obj, FID_Structure_typeInfo);
  if (!typeInfo) {
    (*env)->CallObjectMethod(env, obj, MID_Structure_getTypeInfo);
    if (!(*env)->ExceptionCheck(env)) {
      typeInfo = (*env)->GetLongField(env, obj, FID_Structure_typeInfo);
    }
  }
  return (ffi_type*)L2A(typeInfo);
}

void *
getNativeAddress(JNIEnv *env, jobject obj) {
  if (obj != NULL)
    return L2A((*env)->GetLongField(env, obj, FID_Pointer_peer));
  return NULL;
}

static char
getArrayComponentType(JNIEnv *env, jobject obj) {
  jclass cls = (*env)->GetObjectClass(env, obj);
  jclass type = (*env)->CallObjectMethod(env, cls, MID_Class_getComponentType);
  if (type != NULL) {
    return (char)get_java_type(env, type);
  }
  return 0;
}

#ifndef NO_NIO_BUFFERS
/** Get the direct buffer address, accounting for buffer position. */
static void*
getDirectBufferAddress(JNIEnv* env, jobject buf) {
  void *ptr = (*env)->GetDirectBufferAddress(env, buf);
  if (ptr != NULL) {
    int offset = (*env)->CallIntMethod(env, buf, MID_Buffer_position);
    int size = 0;
    if ((*env)->IsInstanceOf(env, buf, classByteBuffer)) {
      size = 1;
    }
    else if ((*env)->IsInstanceOf(env, buf, classCharBuffer)) {
      // WARNING: likely mismatch with sizeof(wchar_t)
      size = 2;
    }
    else if ((*env)->IsInstanceOf(env, buf, classShortBuffer)) {
      size = 2;
    }
    else if ((*env)->IsInstanceOf(env, buf, classIntBuffer)) {
      size = 4;
    }
    else if ((*env)->IsInstanceOf(env, buf, classLongBuffer)) {
      size = 8;
    }
    else if ((*env)->IsInstanceOf(env, buf, classFloatBuffer)) {
      size = 4;
    }
    else if ((*env)->IsInstanceOf(env, buf, classDoubleBuffer)) {
      size = 8;
    }
    else {
      ptr = NULL;
      throwByName(env, EError, "Unrecognized NIO buffer type");
    }
    ptr = (char*)ptr + offset*size;
  }
  return ptr;
}

static void*
getBufferArray(JNIEnv* env, jobject buf,
               jobject* arrayp, void **basep,
               void **releasep) {
  void *ptr = NULL;
  int offset = 0;
  jobject array = NULL;

#define GET_ARRAY(TYPE, ELEM_SIZE) \
  do {                                                                  \
    array = (*env)->CallObjectMethod(env, buf, MID_##TYPE##Buffer_array); \
    if (array != NULL) {                                                \
      offset =                                                          \
        ((*env)->CallIntMethod(env, buf, MID_##TYPE##Buffer_arrayOffset) \
         + (*env)->CallIntMethod(env, buf, MID_Buffer_position))        \
        * ELEM_SIZE;                                                    \
      ptr = (*env)->Get##TYPE##ArrayElements(env, array, NULL);         \
      if (releasep) *releasep = (void*)(*env)->Release##TYPE##ArrayElements; \
    }                                                                   \
    else if (releasep) *releasep = NULL;                                \
  } while(0)

  if ((*env)->IsInstanceOf(env, buf, classByteBuffer)) {
    GET_ARRAY(Byte, 1);
  }
  else if((*env)->IsInstanceOf(env, buf, classCharBuffer)) {
    // WARNING: likely mismatch with sizeof(wchar_t)
    GET_ARRAY(Char, 2);
  }
  else if((*env)->IsInstanceOf(env, buf, classShortBuffer)) {
    GET_ARRAY(Short, 2);
  }
  else if((*env)->IsInstanceOf(env, buf, classIntBuffer)) {
    GET_ARRAY(Int, 4);
  }
  else if((*env)->IsInstanceOf(env, buf, classLongBuffer)) {
    GET_ARRAY(Long, 8);
  }
  else if((*env)->IsInstanceOf(env, buf, classFloatBuffer)) {
    GET_ARRAY(Float, 4);
  }
  else if((*env)->IsInstanceOf(env, buf, classDoubleBuffer)) {
    GET_ARRAY(Double, 8);
  }
  if (ptr != NULL) {
    if (basep) *basep = ptr;
    if (arrayp) *arrayp = array;
    ptr = (char *)ptr + offset;
  }

  return ptr;
}
#endif /* NO_NIO_BUFFERS */

static jstring
get_system_property(JNIEnv* env, const char* name) {
  jclass classSystem = (*env)->FindClass(env, "java/lang/System");
  if (classSystem != NULL) {
    jmethodID mid = (*env)->GetStaticMethodID(env, classSystem, "getProperty",
                                              "(Ljava/lang/String;)Ljava/lang/String;");
    if (mid != NULL) {
      jstring propname = newJavaString(env, name, CHARSET_UTF8);
      return (*env)->CallStaticObjectMethod(env, classSystem, mid, propname);
    }
  }
  return NULL;
}

static const char*
JNA_init(JNIEnv* env) {
  if (!LOAD_CREF(env, Object, "java/lang/Object")) return "java.lang.Object";
  if (!LOAD_CREF(env, Class, "java/lang/Class")) return "java.lang.Class";
  if (!LOAD_CREF(env, Method, "java/lang/reflect/Method")) return "java.lang.reflect.Method";
  if (!LOAD_CREF(env, String, "java/lang/String")) return "java.lang.String";
#ifndef NO_NIO_BUFFERS
  if (!LOAD_CREF(env, Buffer, "java/nio/Buffer")) return "java.nio.Buffer";
  if (!LOAD_CREF(env, ByteBuffer, "java/nio/ByteBuffer")) return "java.nio.ByteBuffer";
  if (!LOAD_CREF(env, CharBuffer, "java/nio/CharBuffer")) return "java.nio.CharBuffer";
  if (!LOAD_CREF(env, ShortBuffer, "java/nio/ShortBuffer")) return "java.nio.ShortBuffer";
  if (!LOAD_CREF(env, IntBuffer, "java/nio/IntBuffer")) return "java.nio.IntBuffer";
  if (!LOAD_CREF(env, LongBuffer, "java/nio/LongBuffer")) return "java.nio.LongBuffer";
  if (!LOAD_CREF(env, FloatBuffer, "java/nio/FloatBuffer")) return "java.nio.FloatBuffer";
  if (!LOAD_CREF(env, DoubleBuffer, "java/nio/DoubleBuffer")) return "java.nio.DoubleBuffer";
#endif

  if (!LOAD_PCREF(env, Void, "java/lang/Void")) return "java.lang.Void";
  if (!LOAD_PCREF(env, Boolean, "java/lang/Boolean")) return "java.lang.Boolean";
  if (!LOAD_PCREF(env, Byte, "java/lang/Byte")) return "java.lang.Byte";
  if (!LOAD_PCREF(env, Character, "java/lang/Character")) return "java.lang.Character";
  if (!LOAD_PCREF(env, Short, "java/lang/Short")) return "java.lang.Short";
  if (!LOAD_PCREF(env, Integer, "java/lang/Integer")) return "java.lang.Integer";
  if (!LOAD_PCREF(env, Long, "java/lang/Long")) return "java.lang.Long";
  if (!LOAD_PCREF(env, Float, "java/lang/Float")) return "java.lang.Float";
  if (!LOAD_PCREF(env, Double, "java/lang/Double")) return "java.lang.Double";

  if (!LOAD_MID(env, MID_Long_init, classLong,
                "<init>", "(J)V"))
    return "java.lang.Long<init>(J)V";
  if (!LOAD_MID(env, MID_Integer_init, classInteger,
                "<init>", "(I)V"))
    return "java.lang.Integer<init>(I)V";
  if (!LOAD_MID(env, MID_Short_init, classShort,
                "<init>", "(S)V"))
    return "java.lang.Short<init>(S)V";
  if (!LOAD_MID(env, MID_Character_init, classCharacter,
                "<init>", "(C)V"))
    return "java.lang.Character<init>(C)V";
  if (!LOAD_MID(env, MID_Byte_init, classByte,
                "<init>", "(B)V"))
    return "java.lang.Byte<init>(B)V";
  if (!LOAD_MID(env, MID_Boolean_init, classBoolean,
                "<init>", "(Z)V"))
    return "java.lang.Boolean<init>(Z)V";
  if (!LOAD_MID(env, MID_Float_init, classFloat,
                "<init>", "(F)V"))
    return "java.lang.Float<init>(F)V";
  if (!LOAD_MID(env, MID_Double_init, classDouble,
                "<init>", "(D)V"))
    return "java.lang.Double<init>(D)V";
  if (!LOAD_MID(env, MID_Class_getComponentType, classClass,
                "getComponentType", "()Ljava/lang/Class;"))
    return "Class.getComponentType()";
  if (!LOAD_MID(env, MID_Object_toString, classObject,
                "toString", "()Ljava/lang/String;"))
    return "Object.toString()";
  if (!LOAD_MID(env, MID_String_getBytes, classString,
                "getBytes", "()[B"))
    return "String.getBytes()";
  if (!LOAD_MID(env, MID_String_getBytes2, classString,
                "getBytes", "(Ljava/lang/String;)[B"))
    return "String.getBytes(String)";
  if (!LOAD_MID(env, MID_String_toCharArray, classString,
                "toCharArray", "()[C"))
    return "String.toCharArray()";
  if (!LOAD_MID(env, MID_String_init_bytes, classString,
                "<init>", "([B)V"))
    return "String<init>([B)V";
  if (!LOAD_MID(env, MID_String_init_bytes2, classString,
                "<init>", "([BLjava/lang/String;)V"))
    return "String<init>([B)V";
  if (!LOAD_MID(env, MID_Method_getParameterTypes, classMethod,
                "getParameterTypes", "()[Ljava/lang/Class;"))
    return "Method.getParameterTypes()";
  if (!LOAD_MID(env, MID_Method_getReturnType, classMethod,
                "getReturnType", "()Ljava/lang/Class;"))
    return "Method.getReturnType()";

#ifndef NO_NIO_BUFFERS
  if (!LOAD_MID(env, MID_Buffer_position, classBuffer, "position", "()I"))
    return "Buffer.position";
  if (!LOAD_MID(env, MID_ByteBuffer_array, classByteBuffer, "array", "()[B"))
    return "ByteBuffer.array";
  if (!LOAD_MID(env, MID_ByteBuffer_arrayOffset, classByteBuffer, "arrayOffset", "()I"))
    return "ByteBuffer.arrayOffset";
  if (!LOAD_MID(env, MID_CharBuffer_array, classCharBuffer, "array", "()[C"))
    return "CharBuffer.array";
  if (!LOAD_MID(env, MID_CharBuffer_arrayOffset, classCharBuffer, "arrayOffset", "()I"))
    return "CharBuffer.arrayOffset";
  if (!LOAD_MID(env, MID_ShortBuffer_array, classShortBuffer, "array", "()[S"))
    return "ShortBuffer.array";
  if (!LOAD_MID(env, MID_ShortBuffer_arrayOffset, classShortBuffer, "arrayOffset", "()I"))
    return "ShortBuffer.arrayOffset";
  if (!LOAD_MID(env, MID_IntBuffer_array, classIntBuffer, "array", "()[I"))
    return "IntBuffer.array";
  if (!LOAD_MID(env, MID_IntBuffer_arrayOffset, classIntBuffer, "arrayOffset", "()I"))
    return "IntBuffer.arrayOffset";
  if (!LOAD_MID(env, MID_LongBuffer_array, classLongBuffer, "array", "()[J"))
    return "LongBuffer.array";
  if (!LOAD_MID(env, MID_LongBuffer_arrayOffset, classLongBuffer, "arrayOffset", "()I"))
    return "LongBuffer.arrayOffset";
  if (!LOAD_MID(env, MID_FloatBuffer_array, classFloatBuffer, "array", "()[F"))
    return "FloatBuffer.array";
  if (!LOAD_MID(env, MID_FloatBuffer_arrayOffset, classFloatBuffer, "arrayOffset", "()I"))
    return "FloatBuffer.arrayOffset";
  if (!LOAD_MID(env, MID_DoubleBuffer_array, classDoubleBuffer, "array", "()[D"))
    return "DoubleBuffer.array";
  if (!LOAD_MID(env, MID_DoubleBuffer_arrayOffset, classDoubleBuffer, "arrayOffset", "()I"))
    return "DoubleBuffer.arrayOffset";
#endif

  if (!LOAD_FID(env, FID_Boolean_value, classBoolean, "value", "Z"))
    return "Boolean.value";
  if (!LOAD_FID(env, FID_Byte_value, classByte, "value", "B"))
    return "Byte.value";
  if (!LOAD_FID(env, FID_Short_value, classShort, "value", "S"))
    return "Short.value";
  if (!LOAD_FID(env, FID_Character_value, classCharacter, "value", "C"))
    return "Character.value";
  if (!LOAD_FID(env, FID_Integer_value, classInteger, "value", "I"))
    return "Integer.value";
  if (!LOAD_FID(env, FID_Long_value, classLong, "value", "J"))
    return "Long.value";
  if (!LOAD_FID(env, FID_Float_value, classFloat, "value", "F"))
    return "Float.value";
  if (!LOAD_FID(env, FID_Double_value, classDouble, "value", "D"))
    return "Double.value";

  fileEncoding = get_system_property(env, "file.encoding");
  if (fileEncoding) {
    fileEncoding = (*env)->NewGlobalRef(env, fileEncoding);
  }

  return NULL;
}

/** Copy value from the given Java object into the given storage buffer.
 * If the value is being extracted from a String or WString, you are
 * responsible for freeing the allocated memory.
 */
void
extract_value(JNIEnv* env, jobject value, void* buffer, size_t size, jboolean promote, const char* encoding) {
  if (value == NULL) {
    *(void **)buffer = NULL;
  }
  else if ((*env)->IsInstanceOf(env, value, classVoid)) {
    // nothing to do
  }
  else if ((*env)->IsInstanceOf(env, value, classBoolean)) {
    jboolean b = (*env)->GetBooleanField(env, value, FID_Boolean_value);
    if (promote) {
      *(ffi_arg*)buffer = b;
    }
    else {
      *(jint*)buffer = b;
    }
  }
  else if ((*env)->IsInstanceOf(env, value, classByte)) {
    jbyte b = (*env)->GetByteField(env, value, FID_Byte_value);
    if (promote) {
      *(ffi_arg*)buffer = b;
    }
    else {
      *(jbyte*)buffer = b;
    }
  }
  else if ((*env)->IsInstanceOf(env, value, classShort)) {
    jshort s = (*env)->GetShortField(env, value, FID_Short_value);
    if (promote) {
      *(ffi_arg*)buffer = s;
    }
    else {
      *(jshort*)buffer = s;
    }
  }
  else if ((*env)->IsInstanceOf(env, value, classCharacter)) {
    jchar c = (*env)->GetCharField(env, value, FID_Character_value);
    if (promote) {
      *(ffi_arg*)buffer = c;
    }
    else {
      *(wchar_t*)buffer = c;
    }
  }
  else if ((*env)->IsInstanceOf(env, value, classInteger)) {
    jint i = (*env)->GetIntField(env, value, FID_Integer_value);
    if (promote) {
      *(ffi_arg*)buffer = i;
    }
    else {
      *(jint*)buffer = i;
    }
  }
  else if ((*env)->IsInstanceOf(env, value, classLong)) {
    *(jlong *)buffer = (*env)->GetLongField(env, value, FID_Long_value);
  }
  else if ((*env)->IsInstanceOf(env, value, classFloat)) {
    *(float *)buffer = (*env)->GetFloatField(env, value, FID_Float_value);
  }
  else if ((*env)->IsInstanceOf(env, value, classDouble)) {
    *(double *)buffer = (*env)->GetDoubleField(env, value, FID_Double_value);
  }
  else if ((*env)->IsInstanceOf(env, value, classStructure)) {
    void* ptr = getStructureAddress(env, value);
    memcpy(buffer, ptr, size);
  }
  else if ((*env)->IsInstanceOf(env, value, classPointer)) {
    *(void **)buffer = getNativeAddress(env, value);
  }
  else if ((*env)->IsInstanceOf(env, value, classString)) {
    *(void **)buffer = newCStringEncoding(env, (jstring)value, encoding);
  }
  else if ((*env)->IsInstanceOf(env, value, classWString)) {
    jstring s = (*env)->CallObjectMethod(env, value, MID_Object_toString);
    *(void **)buffer = newWideCString(env, s);
  }
  else {
    char msg[MSG_SIZE];
    snprintf(msg, sizeof(msg), "Can't convert type to native, native size %d\n", (int)size);
    fprintf(stderr, "JNA: extract_value: %s", msg);
    memset(buffer, 0, size);
    throwByName(env, EError, msg);
  }
}

/** Construct a new Java object from a native value.  */
jobject
new_object(JNIEnv* env, char jtype, void* valuep, jboolean promote, const char* encoding) {
    switch(jtype) {
    case 's':
      return newJavaPointer(env, valuep);
    case 'c':
      return newJavaString(env, *(void**)valuep, encoding);
    case 'w':
      return newJavaString(env, *(void **)valuep, NULL);
    case '*':
      return newJavaPointer(env, *(void**)valuep);
    case 'J':
      return (*env)->NewObject(env, classLong, MID_Long_init,
                               *(jlong *)valuep);
    case 'F':
      return (*env)->NewObject(env, classFloat, MID_Float_init,
                               *(float *)valuep);
    case 'D':
      return (*env)->NewObject(env, classDouble, MID_Double_init,
                               *(double *)valuep);
    case 'Z':
      // Default mapping for boolean is int32_t
      return (*env)->NewObject(env, classBoolean, MID_Boolean_init,
                               (promote
				? (jint)*(ffi_arg*)valuep
				: (*(jint *)valuep)) ? JNI_TRUE : JNI_FALSE);
    case 'B':
      return (*env)->NewObject(env, classByte, MID_Byte_init,
                               promote
			       ? (jbyte)*(ffi_arg*)valuep
			       : (*(jbyte *)valuep));
    case 'C':
      return (*env)->NewObject(env, classCharacter, MID_Character_init,
                               promote
			       ? (jchar)*(ffi_arg*)valuep
			       : (jchar)(*(wchar_t *)valuep));
    case 'S':
      return (*env)->NewObject(env, classShort, MID_Short_init,
                               promote
			       ? (jshort)*(ffi_arg*)valuep
			       : (*(jshort *)valuep));
    case 'I':
      return (*env)->NewObject(env, classInteger, MID_Integer_init,
                               promote
			       ? (jint)*(ffi_arg*)valuep
			       : *(jint *)valuep);
    default:
      return NULL;
    }
}

/** Get the FFI type for the native type which will be converted to the given
    Java class. */
ffi_type*
get_ffi_type(JNIEnv* env, jclass cls, char jtype) {
  switch (jtype) {
  case 'Z':
    return &ffi_type_uint32;
  case 'B':
    return &ffi_type_sint8;
  case 'C':
    return sizeof(wchar_t) == 2 ? &ffi_type_uint16 : &ffi_type_uint32;
  case 'S':
    return &ffi_type_sint16;
  case 'I':
    return &ffi_type_sint32;
  case 'J':
    return &ffi_type_sint64;
  case 'F':
    return &ffi_type_float;
  case 'D':
    return &ffi_type_double;
  case 'V':
    return &ffi_type_void;
  case 's': {
#define PLACEHOLDER_MEMORY ((jlong)0)
    jobject s = (*env)->CallStaticObjectMethod(env, classStructure,
                                               MID_Structure_newInstance, cls, PLACEHOLDER_MEMORY);
    if (s) {
      return getStructureType(env, s);
    }
    return NULL;
  }
  case '*':
  case 'c':
  case 'w':
  default:
    return &ffi_type_pointer;
  }
}

/** Return the FFI type corresponding to the native equivalent of a
    callback function's return value. */
ffi_type*
get_ffi_return_type(JNIEnv* env, jclass cls, char jtype) {
  switch (jtype) {
  case 'Z':
  case 'B':
  case 'C':
  case 'S':
  case 'I':
    /*
     * Always use a return type the size of a cpu register.  This fixes up
     * callbacks on big-endian 64bit machines, and does not break things on
     * i386 or amd64.
     */
    return &ffi_type_slong;
  default:
    return get_ffi_type(env, cls, jtype);
  }
}

typedef struct _method_data {
  ffi_cif cif;
  ffi_cif closure_cif;
  void*   fptr;
  ffi_type** arg_types;
  ffi_type** closure_arg_types;
  int*    flags;
  int     rflag;
  jobject closure_method;
  jobject* to_native;
  jobject  from_native;
  jboolean throw_last_error;
  const char* encoding;
} method_data;

/** Direct invocation glue.  VM vectors to this callback, which in turn calls
    native code
*/
static void
dispatch_direct(ffi_cif* cif, void* volatile resp, void** argp, void *cdata) {
  JNIEnv* env = (JNIEnv*)*(void **)argp[0];
  method_data *data = (method_data*)cdata;

  // ignore first two arguments, which are pointers
  void** volatile args = argp + 2;
  void** volatile objects = NULL;
  release_t* volatile release = NULL;
  void** volatile elems = NULL;
  unsigned i;
  void* oldresp = resp;
  const char* volatile throw_type = NULL;
  const char* volatile throw_msg = NULL;
  char msg[MSG_SIZE];

  if (data->flags) {
    objects = alloca(data->cif.nargs * sizeof(void*));
    memset(objects, 0, data->cif.nargs * sizeof(void*));
    release = alloca(data->cif.nargs * sizeof(release_t));
    memset(release, 0, data->cif.nargs * sizeof(release_t));
    elems = alloca(data->cif.nargs * sizeof(void*));
    for (i=0;i < data->cif.nargs;i++) {
      if (data->flags[i] == CVT_DEFAULT) {
        continue;
      }
      if (data->arg_types[i]->type == FFI_TYPE_POINTER
          && *(void **)args[i] == NULL) {
        continue;
      }
      switch(data->flags[i]) {
      case CVT_INTEGER_TYPE:
        {
          jlong value = getIntegerTypeValue(env, *(void **)args[i]);
          if (cif->arg_types[i+2]->size < data->cif.arg_types[i]->size) {
            args[i] = alloca(data->cif.arg_types[i]->size);
          }
          if (data->cif.arg_types[i]->size > sizeof(ffi_arg)) {
            *(jlong *)args[i] = value;
          }
          else {
            if(IS_BIG_ENDIAN) {
                value = value << ((sizeof(ffi_arg) - data->cif.arg_types[i]->size) * 8);
            }
            *(ffi_arg *)args[i] = (ffi_arg)value;
          }
        }
        break;
      case CVT_POINTER_TYPE:
        *(void **)args[i] = getPointerTypeAddress(env, *(void **)args[i]);
        break;
      case CVT_TYPE_MAPPER:
      case CVT_TYPE_MAPPER_STRING:
      case CVT_TYPE_MAPPER_WSTRING:
        {
          void* valuep = args[i];
          int jtype = get_java_type_from_ffi_type(data->closure_cif.arg_types[i+2]);
          jobject obj = jtype == '*'
            ? *(void **)valuep
            : new_object(env, (char)jtype, valuep, JNI_FALSE, data->encoding);
          if (cif->arg_types[i+2]->size < data->cif.arg_types[i]->size) {
            args[i] = alloca(data->cif.arg_types[i]->size);
          }
          toNativeTypeMapped(env, obj, args[i],
                             data->cif.arg_types[i]->size,
                             data->to_native[i],
                             data->encoding);
        }
        break;
      case CVT_NATIVE_MAPPED:
      case CVT_NATIVE_MAPPED_STRING:
      case CVT_NATIVE_MAPPED_WSTRING:
        toNative(env, *(void **)args[i], args[i], data->cif.arg_types[i]->size, JNI_FALSE, data->encoding);
        break;
      case CVT_POINTER:
        *(void **)args[i] = getNativeAddress(env, *(void **)args[i]);
        break;
      case CVT_JNIENV:
        *(void **)args[i] = (void*)env;
        break;
      case CVT_STRUCTURE:
        objects[i] = *(void **)args[i];
        writeStructure(env, *(void **)args[i]);
        *(void **)args[i] = getStructureAddress(env, *(void **)args[i]);
        break;
      case CVT_STRUCTURE_BYVAL:
        objects[i] = *(void **)args[i];
        writeStructure(env, objects[i]);
        args[i] = getStructureAddress(env, objects[i]);
        break;
      case CVT_STRING:
        *(void **)args[i] = newCStringEncoding(env, (jstring)*(void **)args[i], data->encoding);
        break;
      case CVT_WSTRING:
        {
          jstring s = (*env)->CallObjectMethod(env, *(void **)args[i], MID_Object_toString);
          *(void **)args[i] = newWideCString(env, s);
        }
        break;
      case CVT_CALLBACK:
        *(void **)args[i] = getCallbackAddress(env, *(void **)args[i]);
        break;
#ifndef NO_NIO_BUFFERS
      case CVT_BUFFER:
        {
          void *ptr = getDirectBufferAddress(env, *(void **)args[i]);
          if (ptr != NULL) {
            objects[i] = NULL;
            release[i] = NULL;
          }
          else {
            ptr = getBufferArray(env, *(jobject *)args[i], (jobject *)&objects[i], &elems[i], (void**)&release[i]);
            if (ptr == NULL) {
              throw_type = EIllegalArgument;
              throw_msg = "Buffer arguments must be direct or have a primitive backing array";
              goto cleanup;
            }
          }
          *(void **)args[i] = ptr;
        }
        break;
#endif /* NO_NIO_BUFFERS */
#define ARRAY(Type)                             \
 do { \
   objects[i] = *(void **)args[i];                                      \
   release[i] = (void *)(*env)->Release##Type##ArrayElements;           \
   elems[i] = *(void **)args[i] = (*env)->Get##Type##ArrayElements(env, objects[i], NULL); } while(0)
      case CVT_ARRAY_BOOLEAN: ARRAY(Boolean); break;
      case CVT_ARRAY_BYTE: ARRAY(Byte); break;
      case CVT_ARRAY_SHORT: ARRAY(Short); break;
      case CVT_ARRAY_CHAR: ARRAY(Char); break;
      case CVT_ARRAY_INT: ARRAY(Int); break;
      case CVT_ARRAY_LONG: ARRAY(Long); break;
      case CVT_ARRAY_FLOAT: ARRAY(Float); break;
      case CVT_ARRAY_DOUBLE: ARRAY(Double); break;
      default:
        break;
      }
    }
    if ((*env)->ExceptionCheck(env)) {
      goto cleanup;
    }
  }

  if (data->rflag == CVT_NATIVE_MAPPED) {
    resp = alloca(sizeof(jobject));
  }
  else if (data->rflag == CVT_TYPE_MAPPER) {
    // Ensure enough space for the inner call result, which may differ
    // from the closure result
    resp = alloca(data->cif.rtype->size);
  }
  else if (data->rflag == CVT_STRUCTURE_BYVAL) {
    // In the case of returned structure by value, the inner and
    // outer calls have different return types; we pass the structure memory
    // to the inner call but return a Java object to the outer call.
    resp = alloca(data->cif.rtype->size);
  }

  {
    PSTART();
    if (data->throw_last_error) {
      SET_LAST_ERROR(0);
    }
    ffi_call(&data->cif, FFI_FN(data->fptr), resp, args);
    {
      int err = GET_LAST_ERROR();
      JNA_set_last_error(env, err);
      if (data->throw_last_error && err) {
        char* emsg = STR_ERROR(err);
        snprintf(msg, sizeof(msg), "[%d] %s", err, emsg);
        free(emsg);
        throw_type = ELastError;
        throw_msg = msg;
      }
    }
    PROTECTED_END(do { throw_type=EError;throw_msg="Invalid memory access"; } while(0));
  }

  switch(data->rflag) {
  case CVT_TYPE_MAPPER:
  case CVT_TYPE_MAPPER_STRING:
  case CVT_TYPE_MAPPER_WSTRING:
    {
       int jtype;
       if(data->rflag == CVT_TYPE_MAPPER_STRING) {
           jtype = 'c';
       } else if (data->rflag == CVT_TYPE_MAPPER_WSTRING) {
           jtype = 'w';
       } else {
           jclass returnClass = getNativeTypeMapped(env, data->from_native);
           jtype = get_java_type(env, returnClass);
           if(jtype == -1) {
               jtype = get_java_type_from_ffi_type(data->cif.rtype);
           }
       }
       
       fromNativeTypeMapped(env, data->from_native, resp, jtype, data->cif.rtype->size,
                           data->closure_method, oldresp, data->encoding);
    }
    break;
  case CVT_INTEGER_TYPE:
  case CVT_POINTER_TYPE:
  case CVT_NATIVE_MAPPED:
  case CVT_NATIVE_MAPPED_STRING:
  case CVT_NATIVE_MAPPED_WSTRING:
    *(void **)oldresp = fromNative(env, data->closure_method, data->cif.rtype, resp, JNI_TRUE, data->encoding);
    break;
  case CVT_POINTER:
    *(void **)resp = newJavaPointer(env, *(void **)resp);
    break;
  case CVT_STRING:
    *(void **)resp = newJavaString(env, *(void **)resp, data->encoding);
    break;
  case CVT_WSTRING:
    *(void **)resp = newJavaWString(env, *(void **)resp);
    break;
  case CVT_STRUCTURE:
    {
      jclass return_class = (*env)->CallObjectMethod(env, data->closure_method, MID_Method_getReturnType);
      *(void **)resp = newJavaStructure(env, *(void **)resp, return_class);
    }
    break;
  case CVT_STRUCTURE_BYVAL:
    {
      jclass return_class = (*env)->CallObjectMethod(env, data->closure_method, MID_Method_getReturnType);
      *(void **)oldresp = newJavaStructure(env, resp, return_class);
    }
    break;
  case CVT_CALLBACK:
    {
      jclass return_class = (*env)->CallObjectMethod(env, data->closure_method, MID_Method_getReturnType);
      *(void **)resp = newJavaCallback(env, *(void **)resp, return_class);
    }
    break;
  default:
    break;
  }

  cleanup:
  if (data->flags) {
    for (i=0;i < data->cif.nargs;i++) {
      switch(data->flags[i]) {
      case CVT_STRUCTURE:
        if (objects[i] && !(*env)->ExceptionCheck(env)) {
          (*env)->CallVoidMethod(env, objects[i], MID_Structure_read);
        }
        break;
      case CVT_STRING:
      case CVT_WSTRING:
      case CVT_TYPE_MAPPER_STRING:
      case CVT_TYPE_MAPPER_WSTRING:
      case CVT_NATIVE_MAPPED_STRING:
      case CVT_NATIVE_MAPPED_WSTRING:
        // Free allocated native strings
        free(*(void **)args[i]);
        break;
      case CVT_BUFFER:
      case CVT_ARRAY_BOOLEAN:
      case CVT_ARRAY_BYTE:
      case CVT_ARRAY_SHORT:
      case CVT_ARRAY_CHAR:
      case CVT_ARRAY_INT:
      case CVT_ARRAY_LONG:
      case CVT_ARRAY_FLOAT:
      case CVT_ARRAY_DOUBLE:
        if (*(void **)args[i] && release[i] != NULL) {
          release[i](env, objects[i], elems[i], 0);
        }
        break;
      }
    }
  }

  if (throw_type) {
    throwByName(env, throw_type, throw_msg);
  }
}

static void
closure_handler(ffi_cif* cif, void* resp, void** argp, void *cdata)
{
  callback* cb = (callback *)cdata;
  JavaVM* jvm = cb->vm;
  JNIEnv* env;
  jobject obj;
  int attached = (*jvm)->GetEnv(jvm, (void *)&env, JNI_VERSION_1_4) == JNI_OK;

  if (!attached) {
    if ((*jvm)->AttachCurrentThread(jvm, (void *)&env, NULL) != JNI_OK) {
      fprintf(stderr, "JNA: Can't attach native thread to VM for closure handler\n");
      return;
    }
  }

  // Give the callback its own local frame to ensure all local references
  // are properly disposed
  if ((*env)->PushLocalFrame(env, 16) < 0) {
    fprintf(stderr, "JNA: Out of memory: Can't allocate local frame");
  }
  else {
    obj = (*env)->NewLocalRef(env, cb->object);
    if ((*env)->IsSameObject(env, obj, NULL)) {
      fprintf(stderr, "JNA: callback object has been garbage collected\n");
      if (cif->rtype->type != FFI_TYPE_VOID)
        memset(resp, 0, cif->rtype->size);
    }
    else {
      (*env)->CallVoidMethod(env, obj, MID_ffi_callback_invoke,
                             A2L(cif), A2L(resp), A2L(argp));
    }

    (*env)->PopLocalFrame(env, NULL);
  }

  if (!attached) {
    if ((*jvm)->DetachCurrentThread(jvm) != 0) {
      fprintf(stderr, "JNA: could not detach thread after callback handling\n");
    }
  }
}

////////////////////
// API Methods
////////////////////

/*
 * Class:     com_sun_jna_Native
 * Method:    invokePointer
 * Signature: (Lcom/sun/jna/Function;JI[Ljava/lang/Object;)J
 */
JNIEXPORT jlong JNICALL 
Java_com_sun_jna_Native_invokePointer (JNIEnv *env, jclass UNUSED(cls),
                                       jobject UNUSED(function), jlong fp,
                                       jint callconv, jobjectArray arr)
{
    jvalue result;
    dispatch(env, L2A(fp), callconv, arr, &ffi_type_pointer, &result);
    return A2L(result.l);
}


/*
 * Class:     com_sun_jna_Native
 * Method:    invokeObject
 * Signature: (Lcom/sun/jna/Function;JI[Ljava/lang/Object;)Ljava/lang/Object;
 */
JNIEXPORT jobject 
JNICALL Java_com_sun_jna_Native_invokeObject(JNIEnv *env, jclass UNUSED(cls),
                                             jobject UNUSED(function), jlong fp,
                                             jint callconv, jobjectArray arr)
{
    jvalue result;
    dispatch(env, L2A(fp), callconv, arr, &ffi_type_pointer, &result);
    return result.l;
}


/*
 * Class:     com_sun_jna_Native
 * Method:    invokeStructure
 * Signature: (Lcom/sun/jna/Function;JI[Ljava/lang/Object;JJ)V
 */
JNIEXPORT void JNICALL 
Java_com_sun_jna_Native_invokeStructure(JNIEnv *env, jclass UNUSED(cls), 
                                        jobject UNUSED(function), jlong fp,
                                        jint callconv, jobjectArray arr,
                                        jlong memory, jlong type_info)
{
  ffi_type* rtype = (ffi_type*)L2A(type_info);
  if (!rtype) {
    throwByName(env, EIllegalState, "Return structure type info not initialized");
  }
  else {
    dispatch(env, L2A(fp), callconv, arr, rtype, L2A(memory));
  }
}

/*
 * Class:     com_sun_jna_Native
 * Method:    invokeDouble
 * Signature: (Lcom/sun/jna/Function;JI[Ljava/lang/Object;)D
 */
JNIEXPORT jdouble JNICALL
Java_com_sun_jna_Native_invokeDouble(JNIEnv *env, jclass UNUSED(cls), 
                                     jobject UNUSED(function), jlong fp, 
                                     jint callconv, jobjectArray arr)
{
    jvalue result;
    dispatch(env, L2A(fp), callconv, arr, &ffi_type_double, &result);
    return result.d;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    invokeFloat
 * Signature: (Lcom/sun/jna/Function;JI[Ljava/lang/Object;)F
 */
JNIEXPORT jfloat JNICALL
Java_com_sun_jna_Native_invokeFloat(JNIEnv *env, jclass UNUSED(cls), 
                                    jobject UNUSED(function), jlong fp,
                                    jint callconv, jobjectArray arr)
{
    jvalue result;
    dispatch(env, L2A(fp), callconv, arr, &ffi_type_float, &result);
    return result.f;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    invokeInt
 * Signature: (Lcom/sun/jna/Function;JI[Ljava/lang/Object;)I
 */
JNIEXPORT jint JNICALL
Java_com_sun_jna_Native_invokeInt(JNIEnv *env, jclass UNUSED(cls), 
                                  jobject UNUSED(function), jlong fp, jint callconv,
                                  jobjectArray arr)
{
    ffi_arg result;
    dispatch(env, L2A(fp), callconv, arr, &ffi_type_sint32, &result);
    return (jint)result;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    invokeLong
 * Signature: (Lcom/sun/jna/Function;JI[Ljava/lang/Object;)J
 */
JNIEXPORT jlong JNICALL
Java_com_sun_jna_Native_invokeLong(JNIEnv *env, jclass UNUSED(cls),
                                   jobject UNUSED(function), jlong fp, jint callconv,
                                   jobjectArray arr)
{
    jvalue result;
    dispatch(env, L2A(fp), callconv, arr, &ffi_type_sint64, &result);
    return result.j;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    invokeVoid
 * Signature: (Lcom/sun/jna/Function;JI[Ljava/lang/Object;)V
 */
JNIEXPORT void JNICALL
Java_com_sun_jna_Native_invokeVoid(JNIEnv *env, jclass UNUSED(cls),
                                   jobject UNUSED(function), jlong fp, jint callconv,
                                   jobjectArray arr)
{
    jvalue result;
    dispatch(env, L2A(fp), callconv, arr, &ffi_type_void, &result);
}

JNIEXPORT jlong JNICALL
Java_com_sun_jna_Native_createNativeCallback(JNIEnv *env,
                                             jclass UNUSED(cls),
                                             jobject obj,
                                             jobject method,
                                             jobjectArray arg_types,
                                             jclass return_type,
                                             jint call_conv,
                                             jint options,
                                             jstring encoding) {
  callback* cb =
    create_callback(env, obj, method, arg_types, return_type,
                    call_conv, options, encoding);

  return A2L(cb);
}

JNIEXPORT void JNICALL
Java_com_sun_jna_Native_freeNativeCallback(JNIEnv *env,
                                           jclass UNUSED(cls),
                                           jlong ptr) {
  free_callback(env, (callback*)L2A(ptr));
}

/*
 * Class:     Native
 * Method:    open
 * Signature: (Ljava/lang/String;I)J
 */
JNIEXPORT jlong JNICALL
Java_com_sun_jna_Native_open(JNIEnv *env, jclass UNUSED(cls), jstring lib, jint flags){
    /* dlopen on Unix allows NULL to mean "current process" */
    const STRTYPE libname = NULL;
    void *handle = NULL;

    if (flags == -1) {
      flags = DEFAULT_LOAD_OPTS;
    }

    if (lib != NULL) {
      if ((libname = NAME2CSTR(env, lib)) == NULL) {
        return A2L(NULL);
      }
    }

    handle = (void *)LOAD_LIBRARY(libname, flags);
#if defined(_WIN32)
    /** Reattempt lookup using the short name version */
    if (!handle) {
      const STRTYPE short_libname = NULL;
      if ((short_libname = w32_short_name(env, lib)) != NULL) {
        free((void *)libname);
        libname = short_libname;
        handle = (void *)LOAD_LIBRARY(libname, flags);
      }
    }
#endif
    if (!handle) {
      char* buf = LOAD_ERROR();
      throwByName(env, EUnsatisfiedLink, buf);
      free(buf);
    }
    if (libname != NULL) {
      free((void *)libname);
    }
    return A2L(handle);
}

/*
 * Class:     Native
 * Method:    close
 * Signature: (J)V
 */
JNIEXPORT void JNICALL
Java_com_sun_jna_Native_close(JNIEnv *env, jclass UNUSED(cls), jlong handle)
{
  if (FREE_LIBRARY(L2A(handle))) {
    char* buf = LOAD_ERROR();
    throwByName(env, EError, buf);
    free(buf);
  }
}

/*
 * Class:     Native
 * Method:    findSymbol
 * Signature: (JLjava/lang/String;)J
 */
JNIEXPORT jlong JNICALL
Java_com_sun_jna_Native_findSymbol(JNIEnv *env, jclass UNUSED(cls),
                                   jlong libHandle, jstring fun) {

    void *handle = L2A(libHandle);
    void *func = NULL;
    const char* funname = newCString(env, fun);

    if (funname != NULL) {
      func = (void *)FIND_ENTRY(handle, funname);
      if (!func) {
        char* buf = LOAD_ERROR();
        throwByName(env, EUnsatisfiedLink, buf);
        free(buf);
      }
      free((void *)funname);
    }
    return A2L(func);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    write
 * Signature: (Lcom/sun/jna/Pointer;JJ[BII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3BII
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jbyteArray arr, jint off, jint n)
{
  PSTART();
  (*env)->GetByteArrayRegion(env, arr, off, n, L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    write
 * Signature: (Lcom/sun/jna/Pointer;JJ[CII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3CII
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jcharArray arr, jint off, jint n)
{
  getChars(env, (wchar_t*)L2A(addr + offset), arr, off, n);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    write
 * Signature: (Lcom/sun/jna/Pointer;JJ[DII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3DII
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jdoubleArray arr, jint off, jint n)
{
  PSTART();
  (*env)->GetDoubleArrayRegion(env, arr, off, n, (jdouble*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    write
 * Signature: (Lcom/sun/jna/Pointer;JJ[FII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3FII
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jfloatArray arr, jint off, jint n)
{
  PSTART();
  (*env)->GetFloatArrayRegion(env, arr, off, n, (jfloat*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    write
 * Signature: (Lcom/sun/jna/Pointer;JJ[III)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3III
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jintArray arr, jint off, jint n)
{
  PSTART();
  (*env)->GetIntArrayRegion(env, arr, off, n, (jint*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    write
 * Signature: (Lcom/sun/jna/Pointer;JJ[JII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3JII
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jlongArray arr, jint off, jint n)
{
  PSTART();
  (*env)->GetLongArrayRegion(env, arr, off, n, (jlong*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    write
 * Signature: (Lcom/sun/jna/Pointer;JJ[SII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3SII
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jshortArray arr, jint off, jint n)
{
  PSTART();
  (*env)->GetShortArrayRegion(env, arr, off, n, (jshort*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    indexOf
 * Signature: (Lcom/sun/jna/Pointer;JJB)J
 */
JNIEXPORT jlong JNICALL Java_com_sun_jna_Native_indexOf
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jbyte value)
{
  jbyte *peer = (jbyte *)L2A(addr + offset);
  volatile jlong i = 0;
  volatile jlong result = -1L;
  PSTART();
  while (i >= 0 && result == -1L) {
    if (peer[i] == value)
      result = i;
    ++i;
  }
  PEND(env);

  return result;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    read
 * Signature: (Lcom/sun/jna/Pointer;JJ[BII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3BII
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jbyteArray arr, jint off, jint n)
{
  PSTART();
  (*env)->SetByteArrayRegion(env, arr, off, n, L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    read
 * Signature: (Lcom/sun/jna/Pointer;JJ[CII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3CII
    (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jcharArray arr, jint off, jint n)
{
  setChars(env, (wchar_t*)L2A(addr + offset), arr, off, n);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    read
 * Signature: (Lcom/sun/jna/Pointer;JJ[DII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3DII
    (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jdoubleArray arr, jint off, jint n)
{
  PSTART();
  (*env)->SetDoubleArrayRegion(env, arr, off, n, (jdouble*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    read
 * Signature: (Lcom/sun/jna/Pointer;JJ[FII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3FII
    (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jfloatArray arr, jint off, jint n)
{
  PSTART();
  (*env)->SetFloatArrayRegion(env, arr, off, n, (jfloat*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    read
 * Signature: (Lcom/sun/jna/Pointer;JJ[III)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3III
    (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jintArray arr, jint off, jint n)
{
  PSTART();
  (*env)->SetIntArrayRegion(env, arr, off, n, (jint*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    read
 * Signature: (Lcom/sun/jna/Pointer;JJ[JII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3JII
    (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jlongArray arr, jint off, jint n)
{
  PSTART();
  (*env)->SetLongArrayRegion(env, arr, off, n, (jlong*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    read
 * Signature: (Lcom/sun/jna/Pointer;JJ[SII)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3SII
    (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jshortArray arr, jint off, jint n)
{
  PSTART();
  (*env)->SetShortArrayRegion(env, arr, off, n, (jshort*)L2A(addr + offset));
  PEND(env);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getByte
 * Signature: (Lcom/sun/jna/Pointer;JJ)B
 */
JNIEXPORT jbyte JNICALL Java_com_sun_jna_Native_getByte
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset)
{
    jbyte res = 0;
    MEMCPY(env, &res, L2A(addr + offset), sizeof(res));
    return res;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getChar
 * Signature: (Lcom/sun/jna/Pointer;JJ)C
 */
JNIEXPORT jchar JNICALL Java_com_sun_jna_Native_getChar
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset)
{
    wchar_t res = 0;
    MEMCPY(env, &res, L2A(addr + offset), sizeof(res));
    return (jchar)res;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    _getPointer
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL Java_com_sun_jna_Native__1getPointer
(JNIEnv *UNUSED_ENV(env), jclass UNUSED(cls), jlong addr)
{
    void *ptr = NULL;
    MEMCPY(env, &ptr, L2A(addr), sizeof(ptr));
    return A2L(ptr);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getDirectByteBuffer
 * Signature: (Lcom/sun/jna/Pointer;JJJ)Ljava/nio/ByteBuffer;
 */
JNIEXPORT jobject JNICALL Java_com_sun_jna_Native_getDirectByteBuffer__Lcom_sun_jna_Pointer_2JJJ
    (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jlong length)
{
#ifdef NO_NIO_BUFFERS
    return NULL;
#else
    return (*env)->NewDirectByteBuffer(env, L2A(addr + offset), length);
#endif
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getDouble
 * Signature: (Lcom/sun/jna/Pointer;JJ)D
 */
JNIEXPORT jdouble JNICALL Java_com_sun_jna_Native_getDouble
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset)
{
    jdouble res = 0;
    MEMCPY(env, &res, L2A(addr + offset), sizeof(res));
    return res;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getFloat
 * Signature: (Lcom/sun/jna/Pointer;JJ)F
 */
JNIEXPORT jfloat JNICALL Java_com_sun_jna_Native_getFloat
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset)
{
    jfloat res = 0;
    MEMCPY(env, &res, L2A(addr + offset), sizeof(res));
    return res;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getInt
 * Signature: (Lcom/sun/jna/Pointer;JJ)I
 */
JNIEXPORT jint JNICALL Java_com_sun_jna_Native_getInt
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset)
{
    jint res = 0;
    MEMCPY(env, &res, L2A(addr + offset), sizeof(res));
    return res;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getLong
 * Signature: (Lcom/sun/jna/Pointer;JJ)J
 */
JNIEXPORT jlong JNICALL Java_com_sun_jna_Native_getLong
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset)
{
    jlong res = 0;
    MEMCPY(env, &res, L2A(addr + offset), sizeof(res));
    return res;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getShort
 * Signature: (Lcom/sun/jna/Pointer;JJ)S
 */
JNIEXPORT jshort JNICALL Java_com_sun_jna_Native_getShort
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset)
{
    jshort res = 0;
    MEMCPY(env, &res, L2A(addr + offset), sizeof(res));
    return res;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getWideString
 * Signature: (Lcom/sun/jna/Pointer;JJ)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_sun_jna_Native_getWideString
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset)
{
  return newJavaString(env, L2A(addr + offset), NULL);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    getStringBytes
 * Signature: (Lcom/sun/jna/Pointer;JJ)[B
 */
JNIEXPORT jbyteArray JNICALL Java_com_sun_jna_Native_getStringBytes
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong baseaddr, jlong offset)
{
  volatile jbyteArray bytes = 0;
  PSTART();
  {
    void* addr = L2A(baseaddr + offset);
    int len = (int)strlen(addr);
    bytes = (*env)->NewByteArray(env, len);
    if (bytes != 0) {
      (*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte *)addr);
    }
    else {
      throwByName(env, EOutOfMemory, "Can't allocate byte array");
    }
  }
  PEND(env);
  return bytes;
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setMemory
 * Signature: (Lcom/sun/jna/Pointer;JJJB)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setMemory
(JNIEnv *UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jlong count, jbyte value)
{
  MEMSET(env, L2A(addr + offset), (int)value, (size_t)count);
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setByte
 * Signature: (Lcom/sun/jna/Pointer;JJB)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setByte
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jbyte value)
{
  MEMCPY(env, L2A(addr  + offset), &value, sizeof(value));
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setChar
 * Signature: (Lcom/sun/jna/Pointer;JJC)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setChar
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jchar value)
{
  wchar_t ch = value;
  MEMCPY(env, L2A(addr + offset), &ch, sizeof(ch));
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setPointer
 * Signature: (Lcom/sun/jna/Pointer;JJJ)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setPointer
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jlong value)
{
  void *ptr = L2A(value);
  MEMCPY(env, L2A(addr + offset), &ptr, sizeof(void *));
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setDouble
 * Signature: (Lcom/sun/jna/Pointer;JJD)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setDouble
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jdouble value)
{
  MEMCPY(env, L2A(addr + offset), &value, sizeof(value));
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setFloat
 * Signature: (Lcom/sun/jna/Pointer;JJF)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setFloat
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jfloat value)
{
  MEMCPY(env, L2A(addr + offset), &value, sizeof(value));
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setInt
 * Signature: (Lcom/sun/jna/Pointer;JJI)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setInt
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jint value)
{
  MEMCPY(env, L2A(addr + offset), &value, sizeof(value));
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setLong
 * Signature: (Lcom/sun/jna/Pointer;JJJ)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setLong
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jlong value)
{
  MEMCPY(env, L2A(addr + offset), &value, sizeof(value));
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setShort
 * Signature: (Lcom/sun/jna/Pointer;JJS)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setShort
(JNIEnv * UNUSED_ENV(env), jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jshort value)
{
  MEMCPY(env, L2A(addr + offset), &value, sizeof(value));
}

/*
 * Class:     com_sun_jna_Native
 * Method:    setWideString
 * Signature: (Lcom/sun/jna/Pointer;JJLjava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_setWideString
(JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jstring value)
{
    int len = (*env)->GetStringLength(env, value);
    const void* volatile str;
    volatile int size = (len + 1) * sizeof(wchar_t);

    str = newWideCString(env, value);
    if (str != NULL) {
      MEMCPY(env, L2A(addr + offset), str, size);
      free((void*)str);
    }
}

/*
 * Class:     Native
 * Method:    malloc
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL Java_com_sun_jna_Native_malloc
(JNIEnv *UNUSED(env), jclass UNUSED(cls), jlong size)
{
    return A2L(malloc((size_t)size));
}

/*
 * Class:     Native
 * Method:    free
 * Signature: (J)V
 */
JNIEXPORT void JNICALL Java_com_sun_jna_Native_free
(JNIEnv *UNUSED(env), jclass UNUSED(cls), jlong ptr)
{
    free(L2A(ptr));
}


/*
 * Class:     Native
 * Method:    sizeof
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL
Java_com_sun_jna_Native_sizeof(JNIEnv *env, jclass UNUSED(cls), jint type)
{
  switch(type) {
  case com_sun_jna_Native_TYPE_VOIDP: return sizeof(void*);
  case com_sun_jna_Native_TYPE_LONG: return sizeof(long);
  case com_sun_jna_Native_TYPE_WCHAR_T: return sizeof(wchar_t);
  case com_sun_jna_Native_TYPE_SIZE_T: return sizeof(size_t);
  case com_sun_jna_Native_TYPE_BOOL: return sizeof(bool);
  case com_sun_jna_Native_TYPE_LONG_DOUBLE: return sizeof(long double);
  default:
    {
      char msg[MSG_SIZE];
      snprintf(msg, sizeof(msg), "Invalid sizeof type %d", (int)type);
      throwByName(env, EIllegalArgument, msg);
      return -1;
    }
  }
}

/** Initialize com.sun.jna classes separately from the library load to
 * avoid initialization inconsistencies.
 */
JNIEXPORT void JNICALL
Java_com_sun_jna_Native_initIDs(JNIEnv *env, jclass cls) {
  if (!LOAD_CREF(env, Pointer, "com/sun/jna/Pointer")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.Pointer");
  }
  else if (!LOAD_MID(env, MID_Pointer_init, classPointer,
                     "<init>", "(J)V")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain constructor for class com.sun.jna.Pointer");
  }
  else if (!LOAD_FID(env, FID_Pointer_peer, classPointer, "peer", "J")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain peer field ID for class com.sun.jna.Pointer");
  }
  else if (!(classNative = (*env)->NewWeakGlobalRef(env, cls))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain global reference for class com.sun.jna.Native");
  }
  else if (!(MID_Native_dispose
             = (*env)->GetStaticMethodID(env, classNative,
                                         "dispose", "()V"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method dispose from class com.sun.jna.Native");
  }
  else if (!(MID_Native_fromNativeCallbackParam
             = (*env)->GetStaticMethodID(env, classNative,
                                         "fromNative", "(Ljava/lang/Class;Ljava/lang/Object;)Lcom/sun/jna/NativeMapped;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method fromNative(Class, Object) from class com.sun.jna.Native");
  }
  else if (!(MID_Native_fromNative
             = (*env)->GetStaticMethodID(env, classNative,
                                         "fromNative", "(Ljava/lang/reflect/Method;Ljava/lang/Object;)Lcom/sun/jna/NativeMapped;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method fromNative(Method, Object) from class com.sun.jna.Native");
  }
  else if (!(MID_Native_nativeType
             = (*env)->GetStaticMethodID(env, classNative,
                                         "nativeType", "(Ljava/lang/Class;)Ljava/lang/Class;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method nativeType from class com.sun.jna.Native");
  }
  else if (!(MID_Native_toNativeTypeMapped
             = (*env)->GetStaticMethodID(env, classNative,
                                         "toNative", "(Lcom/sun/jna/ToNativeConverter;Ljava/lang/Object;)Ljava/lang/Object;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method toNative from class com.sun.jna.Native");
  }
  else if (!(MID_Native_fromNativeTypeMapped
             = (*env)->GetStaticMethodID(env, classNative,
                                         "fromNative", "(Lcom/sun/jna/FromNativeConverter;Ljava/lang/Object;Ljava/lang/reflect/Method;)Ljava/lang/Object;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method fromNative(FromNativeConverter, Object, Method) from class com.sun.jna.Native");
  }
  else if (!LOAD_CREF(env, Structure, "com/sun/jna/Structure")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.Structure");
  }
  else if (!LOAD_MID(env, MID_Structure_getTypeInfo, classStructure,
                     "getTypeInfo", "()Lcom/sun/jna/Pointer;")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain getTypeInfo method for class com.sun.jna.Structure");
  }
  else if (!(MID_Structure_newInstance
             = (*env)->GetStaticMethodID(env, classStructure,
                                         "newInstance", "(Ljava/lang/Class;J)Lcom/sun/jna/Structure;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static newInstance method for class com.sun.jna.Structure");
  }
  else if (!LOAD_MID(env, MID_Structure_read, classStructure,
                     "autoRead", "()V")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain read method for class com.sun.jna.Structure");
  }
  else if (!LOAD_MID(env, MID_Structure_write, classStructure,
                     "autoWrite", "()V")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain write method for class com.sun.jna.Structure");
  }
  else if (!LOAD_FID(env, FID_Structure_memory, classStructure, "memory", "Lcom/sun/jna/Pointer;")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain memory field ID for class com.sun.jna.Structure");
  }
  else if (!LOAD_FID(env, FID_Structure_typeInfo, classStructure, "typeInfo", "J")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain typeInfo field ID for class com.sun.jna.Structure");
  }
  else if (!LOAD_CREF(env, StructureByValue, "com/sun/jna/Structure$ByValue")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.Structure.ByValue");
  }
  else if (!LOAD_CREF(env, Callback, "com/sun/jna/Callback")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.Callback");
  }
  else if (!LOAD_CREF(env, AttachOptions, "com/sun/jna/CallbackReference$AttachOptions")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.CallbackReference.AttachOptions");
  }
  else if (!LOAD_CREF(env, CallbackReference, "com/sun/jna/CallbackReference")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.CallbackReference");
  }
  else if (!(MID_CallbackReference_getCallback
             = (*env)->GetStaticMethodID(env, classCallbackReference,
                                         "getCallback", "(Ljava/lang/Class;Lcom/sun/jna/Pointer;Z)Lcom/sun/jna/Callback;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method getCallback from class com.sun.jna.CallbackReference");
  }
  else if (!(MID_CallbackReference_getFunctionPointer
             = (*env)->GetStaticMethodID(env, classCallbackReference,
                                         "getFunctionPointer", "(Lcom/sun/jna/Callback;Z)Lcom/sun/jna/Pointer;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method getFunctionPointer from class com.sun.jna.CallbackReference");
  }
  else if (!(MID_CallbackReference_getNativeString
             = (*env)->GetStaticMethodID(env, classCallbackReference,
                                         "getNativeString", "(Ljava/lang/Object;Z)Lcom/sun/jna/Pointer;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method getNativeString from class com.sun.jna.CallbackReference");
  }
  else if (!(MID_CallbackReference_initializeThread
             = (*env)->GetStaticMethodID(env, classCallbackReference,
                                         "initializeThread", "(Lcom/sun/jna/Callback;Lcom/sun/jna/CallbackReference$AttachOptions;)Ljava/lang/ThreadGroup;"))) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain static method initializeThread from class com.sun.jna.CallbackReference");
  }
  else if (!LOAD_CREF(env, WString, "com/sun/jna/WString")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.WString");
  }
  else if (!LOAD_CREF(env, NativeMapped, "com/sun/jna/NativeMapped")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.NativeMapped");
  }
  else if (!LOAD_MID(env, MID_NativeMapped_toNative, classNativeMapped,
                     "toNative", "()Ljava/lang/Object;")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain toNative method for class com.sun.jna.NativeMapped");
  }
  else if (!LOAD_CREF(env, IntegerType, "com/sun/jna/IntegerType")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.IntegerType");
  }
  else if (!LOAD_FID(env, FID_IntegerType_value, classIntegerType, "value", "J")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain value field ID for class com.sun.jna.IntegerType");
  }
  else if (!LOAD_CREF(env, PointerType, "com/sun/jna/PointerType")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.PointerType");
  }
  else if (!LOAD_FID(env, FID_PointerType_pointer, classPointerType, "pointer", "Lcom/sun/jna/Pointer;")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain typeInfo field ID for class com.sun.jna.Structure");
  }
  else if (!LOAD_MID(env, MID_WString_init, classWString,
                     "<init>", "(Ljava/lang/String;)V")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain constructor for class com.sun.jna.WString");
  }
  else if (!LOAD_CREF(env, JNIEnv, "com/sun/jna/JNIEnv")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.JNIEnv");
  }
  else if (!LOAD_CREF(env, _ffi_callback, "com/sun/jna/Native$ffi_callback")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.Native$ffi_callback");
  }
  else if (!LOAD_MID(env, MID_ffi_callback_invoke, class_ffi_callback,
                     "invoke", "(JJJ)V")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain invoke method from class com.sun.jna.Native$ffi_callback");
  }
  else if (!LOAD_CREF(env, FromNativeConverter, "com/sun/jna/FromNativeConverter")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain class com.sun.jna.FromNativeConverter");
  }
  else if (!LOAD_MID(env, MID_FromNativeConverter_nativeType, classFromNativeConverter, 
                "nativeType", "()Ljava/lang/Class;")) {
    throwByName(env, EUnsatisfiedLink,
                "Can't obtain method nativeType for class com.sun.jna.FromNativeConverter");
  }
  // Initialize type fields within Structure.FFIType
  else {
#define CFFITYPE "com/sun/jna/Structure$FFIType$FFITypes"
    jclass cls = (*env)->FindClass(env, CFFITYPE);
    jfieldID fid;
    unsigned i;
    const char* fields[] = {
      "void",
      "float", "double", "longdouble",
      "uint8", "sint8", "uint16", "sint16",
      "uint32", "sint32", "uint64", "sint64",
      "pointer",
    };
    ffi_type* types[] = {
      &ffi_type_void,
      &ffi_type_float, &ffi_type_double, &ffi_type_longdouble,
      &ffi_type_uint8, &ffi_type_sint8, &ffi_type_uint16, &ffi_type_sint16,
      &ffi_type_uint32, &ffi_type_sint32, &ffi_type_uint64, &ffi_type_sint64,
      &ffi_type_pointer,
    };
    char field[32];
    if (!cls) {
      throwByName(env, EUnsatisfiedLink, "Structure$FFIType missing");
      return;
    }
    for (i=0;i < sizeof(fields)/sizeof(fields[0]);i++) {
      snprintf(field, sizeof(field), "ffi_type_%s", fields[i]);
      fid = (*env)->GetStaticFieldID(env, cls, field, "Lcom/sun/jna/Pointer;");
      if (!fid) {
        throwByName(env, EUnsatisfiedLink, field);
        return;
      }
      (*env)->SetStaticObjectField(env, cls, fid, newJavaPointer(env, types[i]));
    }
    short checkValue = 0x0001;
    IS_BIG_ENDIAN = ((char *) &checkValue)[0] == 1 ? 0 : 1;
  }
}

#ifndef NO_JAWT
    #if !defined(__APPLE__)
        #define JAWT_HEADLESS_HACK
        #ifdef _WIN32
            #if defined(_WIN64)
                #define METHOD_NAME "JAWT_GetAWT"
            #else
                #define METHOD_NAME "_JAWT_GetAWT@8"
            #endif
        #else
            #define METHOD_NAME "JAWT_GetAWT"
        #endif

        static void* jawt_handle = NULL;
        static jboolean (JNICALL *pJAWT_GetAWT)(JNIEnv*,JAWT*);

        #define JAWT_GetAWT (*pJAWT_GetAWT)
    #endif
#endif /* NO_JAWT */

JNIEXPORT jlong JNICALL
Java_com_sun_jna_Native_getWindowHandle0(JNIEnv* UNUSED_JAWT(env), jclass UNUSED(classp), jobject UNUSED_JAWT(w)) {
  jlong handle = 0;
#ifndef NO_JAWT
  JAWT_DrawingSurface* ds;
  JAWT_DrawingSurfaceInfo* dsi;
  jint lock;
  JAWT awt;

  // NOTE: AWT/JAWT must be loaded prior to this code's execution
  // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6539705
  awt.version = JAWT_VERSION_1_4;
#ifdef JAWT_HEADLESS_HACK
  // Java versions 1.5/1.6 throw UnsatisfiedLinkError when run headless
  // Avoid the issue by dynamic linking
  if (!pJAWT_GetAWT) {
#ifdef _WIN32
    // Windows needs the full path to JAWT; calling System.loadLibrary("jawt")
    // from Java adds it to the path so that a simple LoadLibrary("jawt.dll")
    // works, but may cause other attempts to load that library from Java to
    // to get an UnsatisfiedLinkError, reporting that the library is already
    // loaded in a different class loader, since there is no way to force the
    // JAWT library by the system class loader.
    // Use Unicode strings in case the path to the library includes non-ASCII
    // characters.
    wchar_t* path = L"jawt.dll";
    jstring jprop = get_system_property(env, "java.home");
    if (jprop != NULL) {
      const wchar_t* prop = newWideCString(env, jprop);
      const wchar_t* suffix = L"/bin/jawt.dll";
      size_t len = wcslen(prop) + wcslen(suffix) + 1;
      path = (wchar_t*)alloca(len * sizeof(wchar_t));

      swprintf(path, len, L"%s%s", prop, suffix);

      free((void *)prop);
    }
    if ((jawt_handle = LOAD_LIBRARY(path, DEFAULT_LOAD_OPTS)) == NULL) {
      char* msg = LOAD_ERROR();
      throwByName(env, EUnsatisfiedLink, msg);
      free(msg);
      return -1;
    }
#else
    const char* jawtLibraryName = "libjawt.so";

    // Try to load the libjawt.so library first from the the directories listed
    // in the sun.boot.library.path system property. At least Ubuntu builds the
    // JDK with RUNPATH set instead of RPATH. The two differ in their effect on
    // loading transitive dependencies.
    //
    // RPATHs effect also covers libraries loaded as transitive dependencies,
    // while RUNPATH does not. In the case of JNA libjawt is loaded by
    // libdispatch (the native JNA part), which makes it a transtive load.
    //
    // The solution is to load the library with the full path based on the
    // sun.boot.library.path system property, which points to the native library
    // dirs.
    jstring jprop = get_system_property(env, "sun.boot.library.path");
    if (jprop != NULL) {

      char* prop = newCString(env, jprop);
      char* saveptr = NULL;
      char* propToBeTokeninzed = NULL;

      for(propToBeTokeninzed = prop; ; propToBeTokeninzed = NULL) {
          char* pathElement = strtok_r(propToBeTokeninzed, ":", &saveptr);

          if(pathElement == NULL) {
            break;
          }

          size_t len = strlen(pathElement) + strlen(jawtLibraryName) + 2;
          char* path = (char*) alloca(len);

          sprintf(path, "%s/%s", pathElement, jawtLibraryName);

          jawt_handle = LOAD_LIBRARY(path, DEFAULT_LOAD_OPTS);
          if(jawt_handle != NULL) {
            break;
          }
      }

      free((void *)prop);
    }

    if (jawt_handle == NULL) {
      if ((jawt_handle = LOAD_LIBRARY(jawtLibraryName, DEFAULT_LOAD_OPTS)) == NULL) {
        char* msg = LOAD_ERROR();
        throwByName(env, EUnsatisfiedLink, msg);
        free(msg);
        return -1;
      }
    }
#endif
    if ((pJAWT_GetAWT = (void*)FIND_ENTRY(jawt_handle, METHOD_NAME)) == NULL) {
      char* buf = LOAD_ERROR();
      size_t requiredBuffer = strlen(METHOD_NAME) + strlen(buf) + 31 /*static part*/ + 1 /*null*/;
      char* msg = (char*) malloc(requiredBuffer);
      snprintf(msg, requiredBuffer, "Error looking up JAWT method %s: %s", METHOD_NAME, buf);
      throwByName(env, EUnsatisfiedLink, msg);
      free(buf);
      free(msg);
      return -1;
    }
  }
#endif

  if (!JAWT_GetAWT(env, &awt)) {
    throwByName(env, EUnsatisfiedLink, "Can't load JAWT");
    return 0;
  }

  ds = awt.GetDrawingSurface(env, w);
  if (ds == NULL) {
    throwByName(env, EError, "Can't get drawing surface");
  }
  else {
    lock = ds->Lock(ds);
    if ((lock & JAWT_LOCK_ERROR) != 0) {
      awt.FreeDrawingSurface(ds);
      throwByName(env, EError, "Can't get drawing surface lock");
      return 0;
    }
    dsi = ds->GetDrawingSurfaceInfo(ds);
    if (dsi == NULL) {
      throwByName(env, EError, "Can't get drawing surface info");
    }
    else {
#ifdef _WIN32
      JAWT_Win32DrawingSurfaceInfo* wdsi =
        (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;
      if (wdsi != NULL) {
        // FIXME this kills the VM if the window is not realized;
        // if not, wdsi might be a bogus, non-null value
        // TODO: fix JVM (right) or ensure window is realized (done in Java)
        handle = A2L(wdsi->hwnd);
        if (!handle) {
          throwByName(env, EIllegalState, "Can't get HWND");
        }
      }
      else {
        throwByName(env, EError, "Can't get w32 platform info");
      }
#elif __APPLE__
      // WARNING: the view ref is not guaranteed to be stable except during
      // component paint (see jni_md.h)
      JAWT_MacOSXDrawingSurfaceInfo* mdsi =
        (JAWT_MacOSXDrawingSurfaceInfo*)dsi->platformInfo;
      if (mdsi != NULL) {
        handle = (unsigned long)mdsi->cocoaViewRef;
        if (!handle) {
          throwByName(env, EIllegalState, "Can't get Cocoa View");
        }
      }
      else {
        throwByName(env, EError, "Can't get OS X platform info");
      }
#else
      JAWT_X11DrawingSurfaceInfo* xdsi =
        (JAWT_X11DrawingSurfaceInfo*)dsi->platformInfo;
      if (xdsi != NULL) {
        handle = xdsi->drawable;
        if (!handle) {
          throwByName(env, EIllegalState, "Can't get Drawable");
        }
      }
      else {
        throwByName(env, EError, "Can't get X11 platform info");
      }
#endif
      ds->FreeDrawingSurfaceInfo(dsi);
    }
    ds->Unlock(ds);
    awt.FreeDrawingSurface(ds);
  }
#endif /* NO_JAWT */
  return handle;
}

JNIEXPORT jlong JNICALL
Java_com_sun_jna_Native__1getDirectBufferPointer(JNIEnv *env, jclass UNUSED(classp), jobject buffer) {
  void* addr = NULL;
#ifndef NO_NIO_BUFFERS
  addr = (*env)->GetDirectBufferAddress(env, buffer);
#endif
  if (addr == NULL) {
    throwByName(env, EIllegalArgument, "Non-direct Buffer is not supported");
    return 0;
  }
  return A2L(addr);
}

#ifdef HAVE_PROTECTION
JNIEXPORT void JNICALL
Java_com_sun_jna_Native_setProtected(JNIEnv *UNUSED(env), jclass UNUSED(classp), jboolean protect_access) {
  _protect = protect_access;
}
#else
JNIEXPORT void JNICALL
Java_com_sun_jna_Native_setProtected(JNIEnv *UNUSED(env), jclass UNUSED(classp), jboolean UNUSED(protect_access)) {
  /* Unsupported */
}
#endif

jboolean
is_protected() {
#ifdef HAVE_PROTECTION
  if (_protect) return JNI_TRUE;
#endif
  return JNI_FALSE;
}

JNIEXPORT jboolean JNICALL
Java_com_sun_jna_Native_isProtected(JNIEnv *UNUSED(env), jclass UNUSED(classp)) {
  return is_protected();
}

JNIEXPORT void JNICALL
Java_com_sun_jna_Native_setLastError(JNIEnv *env, jclass UNUSED(classp), jint code) {
  JNA_set_last_error(env, code);
  SET_LAST_ERROR(code);
}

JNIEXPORT jint JNICALL
Java_com_sun_jna_Native_getLastError(JNIEnv *env, jclass UNUSED(classp)) {
  return JNA_get_last_error(env);
}

JNIEXPORT jstring JNICALL
Java_com_sun_jna_Native_getNativeVersion(JNIEnv *env, jclass UNUSED(classp)) {
#ifndef JNA_JNI_VERSION
#define JNA_JNI_VERSION "undefined"
#endif
  return newJavaString(env, JNA_JNI_VERSION, CHARSET_UTF8);
}

JNIEXPORT jstring JNICALL
Java_com_sun_jna_Native_getAPIChecksum(JNIEnv *env, jclass UNUSED(classp)) {
#ifndef CHECKSUM
#define CHECKSUM "undefined"
#endif
  return newJavaString(env, CHECKSUM, CHARSET_UTF8);
}

JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *jvm, void *UNUSED(reserved)) {
  JNIEnv* env;
  int result = JNI_VERSION_1_4;
  int attached = (*jvm)->GetEnv(jvm, (void *)&env, JNI_VERSION_1_4) == JNI_OK;
  const char* err;

  if (!attached) {
    if ((*jvm)->AttachCurrentThread(jvm, (void *)&env, NULL) != JNI_OK) {
      fprintf(stderr, "JNA: Can't attach native thread to VM on load\n");
      return 0;
    }
  }

  if ((err = JNA_init(env)) != NULL) {
    fprintf(stderr, "JNA: Problems loading core IDs: %s\n", err);
    result = 0;
  }
  else if ((err = JNA_callback_init(env)) != NULL) {
    fprintf(stderr, "JNA: Problems loading callback IDs: %s\n", err);
    result = 0;
  }
  if (!attached) {
    if ((*jvm)->DetachCurrentThread(jvm) != 0) {
      fprintf(stderr, "JNA: could not detach thread on initial load\n");
    }
  }

  return result;
}

JNIEXPORT void JNICALL
JNI_OnUnload(JavaVM *vm, void *UNUSED(reserved)) {
  jobject* refs[] = {
    &classObject, &classClass, &classMethod,
    &classString,
#ifndef NO_NIO_BUFFERS
    &classBuffer, &classByteBuffer, &classCharBuffer,
    &classShortBuffer, &classIntBuffer, &classLongBuffer,
    &classFloatBuffer, &classDoubleBuffer,
#endif /* NO_NIO_BUFFERS */
    &classVoid, &classPrimitiveVoid,
    &classBoolean, &classPrimitiveBoolean,
    &classByte, &classPrimitiveByte,
    &classCharacter, &classPrimitiveCharacter,
    &classShort, &classPrimitiveShort,
    &classInteger, &classPrimitiveInteger,
    &classLong, &classPrimitiveLong,
    &classFloat, &classPrimitiveFloat,
    &classDouble, &classPrimitiveDouble,
    &classPointer, &classNative, &classWString,
    &classStructure, &classStructureByValue,
    &classCallbackReference, &classAttachOptions, &classNativeMapped,
    &classIntegerType, &classPointerType,
  };
  unsigned i;
  JNIEnv* env;
  int attached = (*vm)->GetEnv(vm, (void*)&env, JNI_VERSION_1_4) == JNI_OK;
  if (!attached) {
    if ((*vm)->AttachCurrentThread(vm, (void*)&env, NULL) != JNI_OK) {
      fprintf(stderr, "JNA: Can't attach native thread to VM on unload\n");
      return;
    }
  }

  // Calls back to the Native class are unsafe at this point
  //(*env)->CallStaticObjectMethod(env, classNative, MID_Native_dispose);

  if (fileEncoding) {
    (*env)->DeleteGlobalRef(env, fileEncoding);
    fileEncoding = NULL;
  }

  for (i=0;i < sizeof(refs)/sizeof(refs[0]);i++) {
    if (*refs[i]) {
      (*env)->DeleteWeakGlobalRef(env, *refs[i]);
      *refs[i] = NULL;
    }
  }

  JNA_callback_dispose(env);

#ifdef JAWT_HEADLESS_HACK
  if (jawt_handle != NULL) {
    FREE_LIBRARY(jawt_handle);
    jawt_handle = NULL;
    pJAWT_GetAWT = NULL;
  }
#endif

  if (!attached) {
    if ((*vm)->DetachCurrentThread(vm) != 0) {
      fprintf(stderr, "JNA: could not detach thread on unload\n");
    }
  }
}

JNIEXPORT void JNICALL
Java_com_sun_jna_Native_unregister(JNIEnv *env, jclass UNUSED(ncls), jclass cls, jlongArray handles) {
  jlong* data = (*env)->GetLongArrayElements(env, handles, NULL);
  int count = (*env)->GetArrayLength(env, handles);

  while (count-- > 0) {
    method_data* md = (method_data*)L2A(data[count]);
    if (md->to_native) {
      unsigned i;
      for (i=0;i < md->cif.nargs;i++) {
        if (md->to_native[i])
          (*env)->DeleteWeakGlobalRef(env, md->to_native[i]);
      }
    }
    if (md->from_native) (*env)->DeleteWeakGlobalRef(env, md->from_native);
    if (md->closure_method) (*env)->DeleteGlobalRef(env, md->closure_method);
    free(md->arg_types);
    free(md->closure_arg_types);
    free(md->flags);
    free((void *)md->encoding);
    free(md);
  }
  (*env)->ReleaseLongArrayElements(env, handles, data, 0);

  // Not required, or recommended for normal code (see description in JNI docs)
  // see http://java.sun.com/j2se/1.4.2/docs/guide/jni/spec/functions.html
  // However, we're not "normal" code
  // This *may* cause issues in some linux code, not completely verified:
  // see http://java.net/jira/browse/JNA-154
  (*env)->UnregisterNatives(env, cls);
}

JNIEXPORT jlong JNICALL
Java_com_sun_jna_Native_registerMethod(JNIEnv *env, jclass UNUSED(ncls),
                                       jclass cls, jstring name,
                                       jstring signature,
                                       jintArray conversions,
                                       jlongArray closure_atypes,
                                       jlongArray atypes,
                                       jint rconversion,
                                       jlong closure_return_type,
                                       jlong return_type,
                                       jobject closure_method,
                                       jlong function, jint cc,
                                       jboolean throw_last_error,
                                       jobjectArray to_native,
                                       jobject from_native,
                                       jstring encoding)
{
  int argc = atypes ? (*env)->GetArrayLength(env, atypes) : 0;
  const char* cname = newCStringUTF8(env, name);
  const char* sig = newCStringUTF8(env, signature);
  void *code;
  void *closure;
  method_data* data = calloc(1, sizeof(method_data));
  ffi_cif* closure_cif = &data->closure_cif;
  int status;
  int i;
  int abi = cc == CALLCONV_C ? FFI_DEFAULT_ABI : cc;
  ffi_type* rtype = (ffi_type*)L2A(return_type);
  ffi_type* closure_rtype = (ffi_type*)L2A(closure_return_type);
  jlong* types = atypes ? (*env)->GetLongArrayElements(env, atypes, NULL) : NULL;
  jlong* closure_types = closure_atypes ? (*env)->GetLongArrayElements(env, closure_atypes, NULL) : NULL;
  jint* cvts = conversions ? (*env)->GetIntArrayElements(env, conversions, NULL) : NULL;
#if defined(_WIN32) && !defined(_WIN64) && !defined(_WIN32_WCE)
  if (cc == CALLCONV_STDCALL) abi = FFI_STDCALL;
#endif
  if (!(abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI)) {
    char msg[MSG_SIZE];
    snprintf(msg, sizeof(msg), "Invalid calling convention %d", abi);
    throwByName(env, EIllegalArgument, msg);
    status = FFI_BAD_ABI;
    goto cleanup;
  }

  data->throw_last_error = throw_last_error;
  data->arg_types = calloc(argc, sizeof(ffi_type*));
  data->closure_arg_types = calloc(argc + 2, sizeof(ffi_type*));
  data->closure_arg_types[0] = &ffi_type_pointer;
  data->closure_arg_types[1] = &ffi_type_pointer;
  data->closure_method = NULL;
  data->flags = cvts ? calloc(argc, sizeof(jint)) : NULL;
  data->rflag = rconversion;
  data->to_native = NULL;
  data->from_native = from_native ? (*env)->NewWeakGlobalRef(env, from_native) : NULL;
  data->encoding = newCStringUTF8(env, encoding);

  for (i=0;i < argc;i++) {
    data->closure_arg_types[i+2] = (ffi_type*)L2A(closure_types[i]);
    data->arg_types[i] = (ffi_type*)L2A(types[i]);
    if (cvts) {
      data->flags[i] = cvts[i];
      // Type mappers only apply to non-primitive arguments
      if (cvts[i] == CVT_TYPE_MAPPER
          || cvts[i] == CVT_TYPE_MAPPER_STRING
          || cvts[i] == CVT_TYPE_MAPPER_WSTRING) {
        if (!data->to_native) {
          data->to_native = calloc(argc, sizeof(jweak));
        }
        data->to_native[i] = (*env)->NewWeakGlobalRef(env, (*env)->GetObjectArrayElement(env, to_native, i));
      }
    }
  }
  if (types) (*env)->ReleaseLongArrayElements(env, atypes, types, 0);
  if (closure_types) (*env)->ReleaseLongArrayElements(env, closure_atypes, closure_types, 0);
  if (cvts) (*env)->ReleaseIntArrayElements(env, conversions, cvts, 0);
  data->fptr = L2A(function);
  data->closure_method = (*env)->NewGlobalRef(env, closure_method);

  status = ffi_prep_cif(closure_cif, abi, argc+2, closure_rtype, data->closure_arg_types);
  if (ffi_error(env, "Native method mapping", status)) {
    goto cleanup;
  }

  status = ffi_prep_cif(&data->cif, abi, argc, rtype, data->arg_types);
  if (ffi_error(env, "Native method setup", status)) {
    goto cleanup;
  }

  closure = ffi_closure_alloc(sizeof(ffi_closure), &code);
  if (closure == NULL) {
    throwByName(env, EUnsupportedOperation, "Failed to allocate closure");
    status = FFI_BAD_ABI;
    goto cleanup;
  }
  status = ffi_prep_closure_loc(closure, closure_cif, dispatch_direct, data, code);
  if (status != FFI_OK) {
    throwByName(env, EError, "Native method linkage failed");
    goto cleanup;
  }

  {
    JNINativeMethod m = { (char*)cname, (char*)sig, code };
    (*env)->RegisterNatives(env, cls, &m, 1);
  }

 cleanup:
  if (status != FFI_OK) {
    free(data->arg_types);
    free(data->flags);
    free(data);
    data = NULL;
  }
  free((void *)cname);
  free((void *)sig);

  return A2L(data);
}

JNIEXPORT void JNICALL
Java_com_sun_jna_Native_ffi_1call(JNIEnv *UNUSED(env), jclass UNUSED(cls), jlong cif, jlong fptr, jlong resp, jlong args)
{
  ffi_call(L2A(cif), FFI_FN(L2A(fptr)), L2A(resp), L2A(args));
}

JNIEXPORT jlong JNICALL
Java_com_sun_jna_Native_ffi_1prep_1cif(JNIEnv *env, jclass UNUSED(cls), jint abi, jint nargs, jlong return_type, jlong arg_types)
{
  ffi_cif* cif = malloc(sizeof(ffi_cif));
  ffi_status s = ffi_prep_cif(L2A(cif), abi ? abi : FFI_DEFAULT_ABI, nargs, L2A(return_type), L2A(arg_types));
  if (ffi_error(env, "ffi_prep_cif", s)) {
    return 0;
  }
  return A2L(cif);
}

JNIEXPORT jlong JNICALL
Java_com_sun_jna_Native_ffi_1prep_1closure(JNIEnv *env, jclass UNUSED(cls), jlong cif, jobject obj)
{
  callback* cb = (callback *)calloc(1, sizeof(callback));
  ffi_status s;

  if ((*env)->GetJavaVM(env, &cb->vm) != JNI_OK) {
    free(cb);
    throwByName(env, EUnsatisfiedLink, "Can't get Java VM");
    return 0;
  }

  cb->object = (*env)->NewWeakGlobalRef(env, obj);
  if (cb->object == NULL) {
    // either obj was null or an OutOfMemoryError has been thrown
    free(cb);
    return 0;
  }
  cb->closure = ffi_closure_alloc(sizeof(ffi_closure), L2A(&cb->x_closure));
  if (cb->closure == NULL) {
    (*env)->DeleteWeakGlobalRef(env, cb->object);
    free(cb);
    throwByName(env, EUnsupportedOperation, "Failed to allocate closure");
    return 0;
  }

  s = ffi_prep_closure_loc(cb->closure, L2A(cif), &closure_handler,
                           cb, cb->x_closure);
  if (ffi_error(env, "ffi_prep_cif", s)) {
    ffi_closure_free(cb->closure);
    (*env)->DeleteWeakGlobalRef(env, cb->object);
    free(cb);
    return 0;
  }
  return A2L(cb);
}

JNIEXPORT void JNICALL
Java_com_sun_jna_Native_ffi_1free_1closure(JNIEnv *env, jclass UNUSED(cls), jlong closure) {
  callback* cb = (callback *)L2A(closure);

  (*env)->DeleteWeakGlobalRef(env, cb->object);
  ffi_closure_free(cb->closure);
  free(cb);
}

JNIEXPORT jint JNICALL
Java_com_sun_jna_Native_initialize_1ffi_1type(JNIEnv *env, jclass UNUSED(cls), jlong type_info) {
  ffi_type* type = L2A(type_info);
  ffi_cif cif;
  ffi_status status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, type, NULL);
  if (ffi_error(env, "ffi_prep_cif", status)) {
    return 0;
  }
  return (jint)type->size;
}

JNIEXPORT void JNICALL
Java_com_sun_jna_Native_setDetachState(JNIEnv* env, jclass UNUSED(cls), jboolean d, jlong flag) {
  JNA_detach(env, d, L2A(flag));
}

#ifdef __cplusplus
}
#endif