summaryrefslogtreecommitdiffstats
path: root/src/java/com/jogamp/gluegen/JavaEmitter.java
blob: 9a5c2afb30f99707ded047c67014007c629a6c8c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
/*
 * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
 * Copyright (c) 2010 JogAmp Community. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * - Redistribution of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
 * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
 * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
 * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
 * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed or intended for use
 * in the design, construction, operation or maintenance of any nuclear
 * facility.
 *
 * Sun gratefully acknowledges that this software was originally authored
 * and developed by Kenneth Bradley Russell and Christopher John Kline.
 */

package com.jogamp.gluegen;

import com.jogamp.common.nio.Buffers;
import com.jogamp.common.os.DynamicLookupHelper;
import com.jogamp.common.os.MachineDescription;

import java.io.*;
import java.util.*;
import java.text.MessageFormat;

import com.jogamp.gluegen.cgram.types.*;

import java.nio.Buffer;
import java.util.logging.Logger;

import jogamp.common.os.MachineDescriptionRuntime;
import static java.util.logging.Level.*;
import static com.jogamp.gluegen.JavaEmitter.MethodAccess.*;

// PROBLEMS:
//  - what if something returns 'const int *'? Could we
//    return an IntBuffer that has read-only behavior? Or do we copy the array
//    (but we don't know its size!). What do we do if it returns a non-const
//    int*? Should the user be allowed to write back to the returned pointer?
//
//  - Non-const array types must be properly released with JNI_COMMIT
//    in order to see side effects if the array was copied.


public class JavaEmitter implements GlueEmitter {

  private StructLayout layout;
  private TypeDictionary typedefDictionary;
  private Map<Type, Type> canonMap;
  protected JavaConfiguration cfg;

  /**
   * Style of code emission. Can emit everything into one class
   * (AllStatic), separate interface and implementing classes
   * (InterfaceAndImpl), only the interface (InterfaceOnly), or only
   * the implementation (ImplOnly).
   */
  public enum EmissionStyle {AllStatic, InterfaceAndImpl, InterfaceOnly, ImplOnly};

  /**
   * Access control for emitted Java methods.
   */
  public enum MethodAccess {
      PUBLIC("public"), PROTECTED("protected"), PRIVATE("private"), PACKAGE_PRIVATE("/* pp */"), PUBLIC_ABSTRACT("abstract");

      public final String getJavaName() { return javaName; }

      MethodAccess(String javaName) {
          this.javaName = javaName;
      }
      private final String javaName;
  }

  private PrintWriter javaWriter; // Emits either interface or, in AllStatic mode, everything
  private PrintWriter javaImplWriter; // Only used in non-AllStatic modes for impl class
  private PrintWriter cWriter;
  private final MachineDescription machDescJava = MachineDescription.StaticConfig.X86_64_UNIX.md;
  private final MachineDescription.StaticConfig[] machDescTargetConfigs = MachineDescription.StaticConfig.values();

  protected final static Logger LOG = Logger.getLogger(JavaEmitter.class.getPackage().getName());

  @Override
  public void readConfigurationFile(String filename) throws Exception {
    cfg = createConfig();
    cfg.read(filename);
  }

  class ConstantRenamer implements SymbolFilter {

    private List<ConstantDefinition> constants;

    @Override
    public void filterSymbols(List<ConstantDefinition> constants, List<FunctionSymbol> functions) {
      this.constants = constants;
      doWork();
    }

    @Override
    public List<ConstantDefinition> getConstants() {
      return constants;
    }

    @Override
    public List<FunctionSymbol> getFunctions() {
      return null;
    }

    private void doWork() {
      List<ConstantDefinition> newConstants = new ArrayList<ConstantDefinition>();
      JavaConfiguration cfg = getConfig();
      for (ConstantDefinition def : constants) {
        def.rename(cfg.getJavaSymbolRename(def.getName()));
        newConstants.add(def);
      }
      constants = newConstants;
    }
  }

    @Override
    public void beginEmission(GlueEmitterControls controls) throws IOException {

        // Request emission of any structs requested
        for (String structs : cfg.forcedStructs()) {
            controls.forceStructEmission(structs);
        }

        if (!cfg.structsOnly()) {
            try {
                openWriters();
            } catch (Exception e) {
                throw new RuntimeException("Unable to open files for writing", e);
            }
            emitAllFileHeaders();

            // Handle renaming of constants
            controls.runSymbolFilter(new ConstantRenamer());
        }
    }

    @Override
    public void endEmission() {
        if (!cfg.structsOnly()) {
            emitAllFileFooters();

            try {
                closeWriters();
            } catch (Exception e) {
                throw new RuntimeException("Unable to close open files", e);
            }
        }
    }

  @Override
  public void beginDefines() throws Exception {
    if ((cfg.allStatic() || cfg.emitInterface()) && !cfg.structsOnly()) {
      javaWriter().println();
    }
  }

  protected static int getJavaRadix(String name, String value)  {
    // FIXME: need to handle when type specifier is in last char (e.g.,
    // "1.0d or 2759L", because parseXXX() methods don't allow the type
    // specifier character in the string.
    //
    //char lastChar = value.charAt(value.length()-1);

    try {
      // see if it's a long or int
      int radix;
      String parseValue;
      // FIXME: are you allowed to specify hex/octal constants with
      // negation, e.g. "-0xFF" or "-056"? If so, need to modify the
      // following "if(..)" checks and parseValue computation
      if (value.startsWith("0x") || value.startsWith("0X")) {
        radix = 16;
        parseValue = value.substring(2);
      }
      else if (value.startsWith("0") && value.length() > 1) {
        // TODO: is "0" the prefix in C to indicate octal???
        radix = 8;
        parseValue = value.substring(1);
      }
      else {
        radix = 10;
        parseValue = value;
      }
      //System.err.println("parsing " + value + " as long w/ radix " + radix);
      Long.parseLong(parseValue, radix);
      return radix;
    } catch (NumberFormatException e) {
      try {
        // see if it's a double or float
        Double.parseDouble(value);
        return 10;
      } catch (NumberFormatException e2) {
        throw new RuntimeException(
          "Cannot emit define \""+name+"\": value \""+value+
          "\" cannot be assigned to a int, long, float, or double", e2);
      }
    }
  }

  protected static Object getJavaValue(String name, String value) {

    // "calculates" the result type of a simple expression
    // example: (2+3)-(2.0f-3.0) -> Double
    // example: (1 << 2) -> Integer

    Scanner scanner = new Scanner(value).useDelimiter("[+-/*/></(/)]");

    Object resultType = null;

    while (scanner.hasNext()) {

        String t = scanner.next().trim();

        if(0<t.length()) {
            Object type = getJavaValue2(name, t);

            //fast path
            if(type instanceof Double)
                return type;

            if(resultType != null) {

                if(resultType instanceof Integer) {
                    if(type instanceof Long || type instanceof Float || type instanceof Double)
                        resultType = type;
                }else if(resultType instanceof Long) {
                    if(type instanceof Float || type instanceof Double)
                        resultType = type;
                }else if(resultType instanceof Float) {
                    if(type instanceof Float)
                        resultType = type;
                }
            }else{
                resultType = type;
            }

            //fast path
            if(resultType instanceof Double)
                return type;
        }
    }

    return resultType;
  }

  private static Object getJavaValue2(String name, String value) {
    // FIXME: need to handle when type specifier is in last char (e.g.,
    // "1.0d or 2759L", because parseXXX() methods don't allow the type
    // specifier character in the string.
    //
    char lastChar = value.charAt(value.length()-1);

    try {
      // see if it's a long or int
      int radix;
      String parseValue;
      // FIXME: are you allowed to specify hex/octal constants with
      // negation, e.g. "-0xFF" or "-056"? If so, need to modify the
      // following "if(..)" checks and parseValue computation
      if (value.startsWith("0x") || value.startsWith("0X")) {
        radix = 16;
        parseValue = value.substring(2);
      } else if (value.startsWith("0") && value.length() > 1) {
        // TODO: is "0" the prefix in C to indicate octal???
        radix = 8;
        parseValue = value.substring(1);
      } else {
        radix = 10;
        parseValue = value;
      }
      if(lastChar == 'u' || lastChar == 'U') {
          parseValue = parseValue.substring(0, parseValue.length()-1);
      }

      //System.err.println("parsing " + value + " as long w/ radix " + radix);
      long longVal = Long.parseLong(parseValue, radix);
      // if constant is small enough, store it as an int instead of a long
      if (longVal > Integer.MIN_VALUE && longVal < Integer.MAX_VALUE) {
        return (int)longVal;
      }
      return longVal;

    } catch (NumberFormatException e) {
      try {
        // see if it's a double or float
        double dVal = Double.parseDouble(value);
        double absVal = Math.abs(dVal);
        // if constant is small enough, store it as a float instead of a double
        if (absVal < Float.MIN_VALUE || absVal > Float.MAX_VALUE) {
            return new Double(dVal);
        }
        return new Float((float) dVal);
      } catch (NumberFormatException e2) {
        throw new RuntimeException(
          "Cannot emit define \""+name+"\": value \""+value+
          "\" cannot be assigned to a int, long, float, or double", e2);
      }
    }
  }


  protected static String getJavaType(String name, String value) {
    Object oval = getJavaValue(name, value);
    return getJavaType(name, oval);
  }

  protected static String getJavaType(String name, Object oval) {
    if(oval instanceof Integer) {
        return "int";
    } else if(oval instanceof Long) {
        return "long";
    } else if(oval instanceof Float) {
        return "float";
    } else if(oval instanceof Double) {
        return "double";
    }

    throw new RuntimeException(
      "Cannot emit define (2) \""+name+"\": value \""+oval+
      "\" cannot be assigned to a int, long, float, or double");
  }

  /** Mangle a class, package or function name for JNI usage, i.e. replace all '.' w/ '_' */
  protected static String jniMangle(String name) {
    return name.replaceAll("_", "_1").replace('.', '_');
  }
  /** Returns the JNI method prefix consisting our of mangled package- and class-name */
  protected static String getJNIMethodNamePrefix(final String javaPackageName, final String javaClassName) {
      return "Java_"+jniMangle(javaPackageName)+"_"+jniMangle(javaClassName);
  }

  @Override
  public void emitDefine(ConstantDefinition def, String optionalComment) throws Exception  {

    if (cfg.allStatic() || cfg.emitInterface()) {
      // TODO: Some defines (e.g., GL_DOUBLE_EXT in gl.h) are defined in terms
      // of other defines -- should we emit them as references to the original
      // define (not even sure if the lexer supports this)? Right now they're
      // emitted as the numeric value of the original definition. If we decide
      // emit them as references we'll also have to emit them in the correct
      // order. It's probably not an issue right now because the emitter
      // currently only emits only numeric defines -- if it handled #define'd
      // objects it would make a bigger difference.

      String name = def.getName();
      String value = def.getValue();

      if (!cfg.shouldIgnoreInInterface(name)) {
        String type = getJavaType(name, value);
        if (optionalComment != null && optionalComment.length() != 0) {
          javaWriter().println("  /** " + optionalComment + " */");
        }
        String suffix = "";
        if(!value.endsWith(")")) {
            if (type.equals("float") && !value.endsWith("f")) {
                suffix = "f";
            }else if(value.endsWith("u") || value.endsWith("U")) {
                value = value.substring(0, value.length()-1);
            }
        }

        javaWriter().println("  public static final " + type + " " + name + " = " + value + suffix + ";");
      }
    }
  }

  @Override
  public void endDefines() throws Exception {
  }

  @Override
  public void beginFunctions(TypeDictionary typedefDictionary,
                             TypeDictionary structDictionary,
                             Map<Type, Type> canonMap) throws Exception {

    this.typedefDictionary = typedefDictionary;
    this.canonMap          = canonMap;

    if ((cfg.allStatic() || cfg.emitInterface()) && !cfg.structsOnly()) {
      javaWriter().println();
    }
  }

  @Override
  public Iterator<FunctionSymbol> emitFunctions(List<FunctionSymbol> originalCFunctions) throws Exception {

    // Sometimes headers will have the same function prototype twice, once
    // with the argument names and once without. We'll remember the signatures
    // we've already processed we don't generate duplicate bindings.
    //
    // Note: this code assumes that on the equals() method in FunctionSymbol
    // only considers function name and argument types (i.e., it does not
    // consider argument *names*) when comparing FunctionSymbols for equality
    Set<FunctionSymbol> funcsToBindSet = new HashSet<FunctionSymbol>(100);
    for (FunctionSymbol cFunc : originalCFunctions) {
      if (!funcsToBindSet.contains(cFunc)) {
        funcsToBindSet.add(cFunc);
      }
    }

    //    validateFunctionsToBind(funcsToBindSet);

    ArrayList<FunctionSymbol> funcsToBind = new ArrayList<FunctionSymbol>(funcsToBindSet);
    // sort functions to make them easier to find in native code
    Collections.sort(funcsToBind, new Comparator<FunctionSymbol>() {
            @Override
            public int compare(FunctionSymbol o1, FunctionSymbol o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

    // Bind all the C funcs to Java methods
    HashSet<MethodBinding> methodBindingSet = new HashSet<MethodBinding>();
    ArrayList<FunctionEmitter> methodBindingEmitters = new ArrayList<FunctionEmitter>(2*funcsToBind.size());
    for (FunctionSymbol cFunc : funcsToBind) {
      // Check to see whether this function should be ignored
      if (!cfg.shouldIgnoreInImpl(cFunc.getName())) {
          methodBindingEmitters.addAll(generateMethodBindingEmitters(methodBindingSet, cFunc));
      }

    }

    // Emit all the methods
    for (FunctionEmitter emitter : methodBindingEmitters) {
      try {
        if (!emitter.isInterface() || !cfg.shouldIgnoreInInterface(emitter.getName())) {
            emitter.emit();
            emitter.getDefaultOutput().println(); // put newline after method body
        }
      } catch (Exception e) {
        throw new RuntimeException(
            "Error while emitting binding for \"" + emitter.getName() + "\"", e);
      }
    }

    // Return the list of FunctionSymbols that we generated gluecode for
    return funcsToBind.iterator();
  }

  /**
   * Create the object that will read and store configuration information for
   * this JavaEmitter.
   */
  protected JavaConfiguration createConfig() {
    return new JavaConfiguration();
  }

  /**
   * Get the configuration information for this JavaEmitter.
   */
  protected JavaConfiguration getConfig() {
    return cfg;
  }

  /**
   * Generates the public emitters for this MethodBinding which will
   * produce either simply signatures (for the interface class, if
   * any) or function definitions with or without a body (depending on
   * whether or not the implementing function can go directly to
   * native code because it doesn't need any processing of the
   * outgoing arguments).
   */
  protected void generatePublicEmitters(MethodBinding binding,
                                        List<FunctionEmitter> allEmitters,
                                        boolean signatureOnly) {
    if (cfg.manuallyImplement(binding.getName()) && !signatureOnly) {
      // We only generate signatures for manually-implemented methods;
      // user provides the implementation
      return;
    }

    MethodAccess accessControl = cfg.accessControl(binding.getName());
    // We should not emit anything except public APIs into interfaces
    if (signatureOnly && (accessControl != PUBLIC)) {
      return;
    }

    final PrintWriter writer = ((signatureOnly || cfg.allStatic()) ? javaWriter() : javaImplWriter());

    // It's possible we may not need a body even if signatureOnly is
    // set to false; for example, if the routine doesn't take any
    // arrays or buffers as arguments
    boolean isUnimplemented = cfg.isUnimplemented(binding.getName());
    List<String> prologue = cfg.javaPrologueForMethod(binding, false, false);
    List<String> epilogue = cfg.javaEpilogueForMethod(binding, false, false);
    boolean needsBody = (isUnimplemented ||
                         (binding.needsNIOWrappingOrUnwrapping() ||
                          binding.signatureUsesJavaPrimitiveArrays()) ||
                         (prologue != null) ||
                         (epilogue != null));

    JavaMethodBindingEmitter emitter =
      new JavaMethodBindingEmitter(binding,
                                   writer,
                                   cfg.runtimeExceptionType(),
                                   cfg.unsupportedExceptionType(),
                                   !signatureOnly && needsBody,
                                   cfg.tagNativeBinding(),
                                   false, // eraseBufferAndArrayTypes
                                   cfg.useNIOOnly(binding.getName()),
                                   cfg.useNIODirectOnly(binding.getName()),
                                   false,
                                   false,
                                   false,
                                   isUnimplemented,
                                   signatureOnly,
                                   cfg);
    switch (accessControl) {
      case PUBLIC:     emitter.addModifier(JavaMethodBindingEmitter.PUBLIC); break;
      case PROTECTED:  emitter.addModifier(JavaMethodBindingEmitter.PROTECTED); break;
      case PRIVATE:    emitter.addModifier(JavaMethodBindingEmitter.PRIVATE); break;
      default: break; // package-private adds no modifiers
    }
    if (cfg.allStatic()) {
      emitter.addModifier(JavaMethodBindingEmitter.STATIC);
    }
    if (!isUnimplemented && !needsBody && !signatureOnly) {
      emitter.addModifier(JavaMethodBindingEmitter.NATIVE);
    }
    emitter.setReturnedArrayLengthExpression(cfg.returnedArrayLength(binding.getName()));
    emitter.setPrologue(prologue);
    emitter.setEpilogue(epilogue);
    allEmitters.add(emitter);
  }

  /**
   * Generates the private emitters for this MethodBinding. On the
   * Java side these will simply produce signatures for native
   * methods. On the C side these will create the emitters which will
   * write the JNI code to interface to the functions. We need to be
   * careful to make the signatures all match up and not produce too
   * many emitters which would lead to compilation errors from
   * creating duplicated methods / functions.
   */
  protected void generatePrivateEmitters(MethodBinding binding,
                                         List<FunctionEmitter> allEmitters) {
    if (cfg.manuallyImplement(binding.getName())) {
      // Don't produce emitters for the implementation class
      return;
    }

    boolean hasPrologueOrEpilogue =
        ((cfg.javaPrologueForMethod(binding, false, false) != null) ||
         (cfg.javaEpilogueForMethod(binding, false, false) != null));

    // If we already generated a public native entry point for this
    // method, don't emit another one
    if (!cfg.isUnimplemented(binding.getName()) &&
        (binding.needsNIOWrappingOrUnwrapping() ||
         // binding.signatureUsesJavaPrimitiveArrays() /* excluded below */ ||
         hasPrologueOrEpilogue)) {
      PrintWriter writer = (cfg.allStatic() ? javaWriter() : javaImplWriter());

      // If the binding uses primitive arrays, we are going to emit
      // the private native entry point for it along with the version
      // taking only NIO buffers
      if ( !binding.signatureUsesJavaPrimitiveArrays() ) {
        // (Always) emit the entry point taking only direct buffers
        JavaMethodBindingEmitter emitter =
          new JavaMethodBindingEmitter(binding,
                                       writer,
                                       cfg.runtimeExceptionType(),
                                       cfg.unsupportedExceptionType(),
                                       false,
                                       cfg.tagNativeBinding(),
                                       true, // eraseBufferAndArrayTypes
                                       cfg.useNIOOnly(binding.getName()),
                                       cfg.useNIODirectOnly(binding.getName()),
                                       true,
                                       true,
                                       false,
                                       false,
                                       false,
                                       cfg);
        emitter.addModifier(JavaMethodBindingEmitter.PRIVATE);
        if (cfg.allStatic()) {
          emitter.addModifier(JavaMethodBindingEmitter.STATIC);
        }
        emitter.addModifier(JavaMethodBindingEmitter.NATIVE);
        emitter.setReturnedArrayLengthExpression(cfg.returnedArrayLength(binding.getName()));
        allEmitters.add(emitter);
      }
    }

    // Now generate the C emitter(s). We need to produce one for every
    // Java native entry point (public or private). The only
    // situations where we don't produce one are (a) when the method
    // is unimplemented, and (b) when the signature contains primitive
    // arrays, since the latter is handled by the method binding
    // variant taking only NIO Buffers.
    if (!cfg.isUnimplemented(binding.getName()) &&
        !binding.signatureUsesJavaPrimitiveArrays()) {
      CMethodBindingEmitter cEmitter;
      // Generate a binding without mixed access (NIO-direct, -indirect, array)
      cEmitter =
          new CMethodBindingEmitter(binding,
                                    cWriter(),
                                    cfg.implPackageName(),
                                    cfg.implClassName(),
                                    true, // NOTE: we always disambiguate with a suffix now, so this is optional
                                    cfg.allStatic(),
                                    (binding.needsNIOWrappingOrUnwrapping() || hasPrologueOrEpilogue),
                                    !cfg.useNIODirectOnly(binding.getName()),
                                    machDescJava);
      prepCEmitter(binding, cEmitter);
      allEmitters.add(cEmitter);
    }
  }

  protected void prepCEmitter(MethodBinding binding, CMethodBindingEmitter cEmitter)
  {
      // See whether we need an expression to help calculate the
      // length of any return type
      JavaType javaReturnType = binding.getJavaReturnType();
      if (javaReturnType.isNIOBuffer() ||
          javaReturnType.isCompoundTypeWrapper()) {
        // See whether capacity has been specified
        String capacity = cfg.returnValueCapacity(binding.getName());
        if (capacity != null) {
          cEmitter.setReturnValueCapacityExpression( new MessageFormat(capacity) );
        }
      } else if (javaReturnType.isArray() ||
                 javaReturnType.isArrayOfCompoundTypeWrappers()) {
        // NOTE: adding a check here because the CMethodBindingEmitter
        // also doesn't yet handle returning scalar arrays. In order
        // to implement this, return the type as a Buffer instead
        // (i.e., IntBuffer, FloatBuffer) and add code as necessary.
        if (javaReturnType.isPrimitiveArray()) {
          throw new RuntimeException("Primitive array return types not yet supported");
        }

        // See whether length has been specified
        String len = cfg.returnValueLength(binding.getName());
        if (len != null) {
          cEmitter.setReturnValueLengthExpression( new MessageFormat(len) );
        }
      }
      cEmitter.setTemporaryCVariableDeclarations(cfg.temporaryCVariableDeclarations(binding.getName()));
      cEmitter.setTemporaryCVariableAssignments(cfg.temporaryCVariableAssignments(binding.getName()));
  }

  /**
   * Generate all appropriate Java bindings for the specified C function
   * symbols.
   */
  protected List<? extends FunctionEmitter> generateMethodBindingEmitters(Set<MethodBinding> methodBindingSet, FunctionSymbol sym) throws Exception {

    ArrayList<FunctionEmitter> allEmitters = new ArrayList<FunctionEmitter>();

    try {
      // Get Java binding for the function
      MethodBinding mb = bindFunction(sym, null, null, machDescJava);

      // JavaTypes representing C pointers in the initial
      // MethodBinding have not been lowered yet to concrete types
      List<MethodBinding> bindings = expandMethodBinding(mb);

      for (MethodBinding binding : bindings) {

        if(!methodBindingSet.add(binding)) {
            // skip .. already exisiting binding ..
            continue;
        }

        if (cfg.allStatic() && binding.hasContainingType()) {
          // This should not currently happen since structs are emitted using a different mechanism
          throw new IllegalArgumentException("Cannot create binding in AllStatic mode because method has containing type: \"" +
                                             binding + "\"");
        }

        // The structure of the generated glue code looks something like this:
        // Simple method (no arrays, void pointers, etc.):
        //   Interface class:
        //     public void fooMethod();
        //   Implementation class:
        //     public native void fooMethod();
        //
        // Method taking void* argument:
        //   Interface class:
        //     public void fooMethod(Buffer arg);
        //   Implementation class:
        //     public void fooMethod(Buffer arg) {
        //       ... bounds checks, etc. ...
        //
        //       boolean arg_direct = arg != null && Buffers.isDirect(arg);
        //
        //       fooMethod0(arg_direct?arg:Buffers.getArray(arg),
        //                  arg_direct?Buffers.getDirectBufferByteOffset(arg):Buffers.getIndirectBufferByteOffset(arg),
        //                  arg_direct,
        //                  ... );
        //     }
        //     private native void fooMethod1(Object arg, int arg_byte_offset, boolean arg_is_direct, ...);
        //
        // Method taking primitive array argument:
        //   Interface class:
        //     public void fooMethod(int[] arg, int arg_offset);
        //     public void fooMethod(IntBuffer arg);
        //   Implementing class:
        //     public void fooMethod(int[] arg, int arg_offset) {
        //       ... range checks, etc. ...
        //       fooMethod1(arg, SIZEOF_INT * arg_offset);
        //     }
        //     public void fooMethod(IntBuffer arg) {
        //       ... bounds checks, etc. ...
        //
        //       boolean arg_direct = BufferFactory.isDirect(arg);
        //
        //       fooMethod1(arg_direct?arg:BufferFactory.getArray(arg),
        //                  arg_direct?BufferFactory.getDirectBufferByteOffset(arg):BufferFactory.getIndirectBufferByteOffset(arg),
        //                  arg_direct,
        //                  ... );
        //     }
        //     private native void fooMethod1(Object arg, int arg_byte_offset, boolean arg_is_direct, ...);
        //
        // Note in particular that the public entry point taking an
        // array is merely a special case of the indirect buffer case.

        if (cfg.emitInterface()) {
          generatePublicEmitters(binding, allEmitters, true);
        }
        if (cfg.emitImpl()) {
          generatePublicEmitters(binding, allEmitters, false);
          generatePrivateEmitters(binding, allEmitters);
        }
      } // end iteration over expanded bindings
    } catch (Exception e) {
      throw new RuntimeException("Error while generating bindings for \"" + sym + "\"", e);
    }

    return allEmitters;
  }


  @Override
  public void endFunctions() throws Exception {
    if (!cfg.structsOnly()) {
        if (cfg.allStatic() || cfg.emitInterface()) {
            emitCustomJavaCode(javaWriter(), cfg.className());
        }
        if (!cfg.allStatic() && cfg.emitImpl()) {
            emitCustomJavaCode(javaImplWriter(), cfg.implClassName());
        }
    }
  }

  @Override
  public void beginStructLayout() throws Exception {}
  @Override
  public void layoutStruct(CompoundType t) throws Exception {
    getLayout().layout(t);
  }
  @Override
  public void endStructLayout() throws Exception {}

  @Override
  public void beginStructs(TypeDictionary typedefDictionary,
                           TypeDictionary structDictionary,
                           Map<Type, Type> canonMap) throws Exception {
    this.typedefDictionary = typedefDictionary;
    this.canonMap          = canonMap;
  }

  @Override
  public void emitStruct(CompoundType structType, String alternateName) throws Exception {
    String name = structType.getName();
    if (name == null && alternateName != null) {
      name = alternateName;
    }

    if (name == null) {
        final String structName = structType.getStructName();
        if ( null != structName && cfg.shouldIgnoreInInterface(structName) ) {
            return;
        }

        LOG.log(WARNING, "skipping emission of unnamed struct \"{0}\"", structType);
        return;
    }

    if (cfg.shouldIgnoreInInterface(name)) {
      return;
    }

    Type containingCType = canonicalize(new PointerType(SizeThunk.POINTER, structType, 0));
    JavaType containingType = typeToJavaType(containingCType, false, null);
    if (!containingType.isCompoundTypeWrapper()) {
      return;
    }
    String containingTypeName = containingType.getName();

    // machDescJava global MachineDescription is the one used to determine
    // the sizes of the primitive types seen in the public API in Java.
    // For example, if a C long is an element of a struct, it is the size
    // of a Java int on a 32-bit machine but the size of a Java long
    // on a 64-bit machine. To support both of these sizes with the
    // same API, the abstract base class must take and return a Java
    // long from the setter and getter for this field. However the
    // implementation on a 32-bit platform must downcast this to an
    // int and set only an int's worth of data in the struct.
    //
    // The machDescTarget MachineDescription is the one used to determine how
    // much data to set in or get from the struct and exactly from
    // where it comes.
    //
    // Note that machDescJava MachineDescription is always 64bit unix,
    // which complies w/ Java types.

    boolean needsNativeCode = false;
    // Native code for calls through function pointers gets emitted
    // into the abstract base class; Java code which accesses fields
    // gets emitted into the concrete classes
    for (int i = 0; i < structType.getNumFields(); i++) {
      if (structType.getField(i).getType().isFunctionPointer()) {
        needsNativeCode = true;
        break;
      }
    }

    final String structClassPkg = cfg.packageForStruct(name);
    final PrintWriter javaWriter;
    final PrintWriter jniWriter;
    try  {
        javaWriter = openFile(cfg.javaOutputDir() + File.separator +
                              CodeGenUtils.packageAsPath(structClassPkg) +
                              File.separator + containingTypeName + ".java", containingTypeName);
        if( null == javaWriter ) {
            // suppress output if openFile deliberately returns null.
            return;
        }
        CodeGenUtils.emitAutogeneratedWarning(javaWriter, this);
        if (needsNativeCode) {
            String nRoot = cfg.nativeOutputDir();
            if (cfg.nativeOutputUsesJavaHierarchy()) {
                nRoot += File.separator + CodeGenUtils.packageAsPath(cfg.packageName());
            }
            jniWriter = openFile(nRoot + File.separator + containingTypeName + "_JNI.c", containingTypeName);
            CodeGenUtils.emitAutogeneratedWarning(jniWriter, this);
            emitCHeader(jniWriter, structClassPkg, containingTypeName);
        } else {
            jniWriter = null;
        }
    } catch(Exception e)   {
        throw new RuntimeException("Unable to open files for emission of struct class", e);
    }

    javaWriter.println();
    javaWriter.println("package " + structClassPkg + ";");
    javaWriter.println();
    javaWriter.println("import java.nio.*;");
    javaWriter.println();

    javaWriter.println("import " + cfg.gluegenRuntimePackage() + ".*;");
    javaWriter.println("import " + DynamicLookupHelper.class.getPackage().getName() + ".*;");
    javaWriter.println("import " + Buffers.class.getPackage().getName() + ".*;");
    javaWriter.println("import " + MachineDescriptionRuntime.class.getName() + ";");
    javaWriter.println();
    List<String> imports = cfg.imports();
    for (String str : imports) {
      javaWriter.print("import ");
      javaWriter.print(str);
      javaWriter.println(";");
    }
    javaWriter.println();
    List<String> javadoc = cfg.javadocForClass(containingTypeName);
    for (String doc : javadoc) {
      javaWriter.println(doc);
    }
    javaWriter.print("public class " + containingTypeName + " ");
    boolean firstIteration = true;
    List<String> userSpecifiedInterfaces = cfg.implementedInterfaces(containingTypeName);
    for (String userInterface : userSpecifiedInterfaces) {
      if (firstIteration) {
        javaWriter.print("implements ");
      }
      firstIteration = false;
      javaWriter.print(userInterface);
      javaWriter.print(" ");
    }
    javaWriter.println("{");
    javaWriter.println();
    javaWriter.println("  StructAccessor accessor;");
    javaWriter.println();
    javaWriter.println("  private static final int mdIdx = MachineDescriptionRuntime.getStatic().ordinal();");
    javaWriter.println();
    // generate all offset and size arrays
    generateOffsetAndSizeArrays(javaWriter, "  ", containingTypeName, structType, null); /* w/o offset */
    for (int i = 0; i < structType.getNumFields(); i++) {
      final Field field = structType.getField(i);
      final Type fieldType = field.getType();

      if (!cfg.shouldIgnoreInInterface(name + " " + field.getName())) {
        final String renamed = cfg.getJavaSymbolRename(field.getName());
        final String fieldName = renamed==null ? field.getName() : renamed;
        if (fieldType.isFunctionPointer()) {
           // no offset/size for function pointer ..
        } else if (fieldType.isCompound()) {
          // FIXME: will need to support this at least in order to
          // handle the union in jawt_Win32DrawingSurfaceInfo (fabricate
          // a name?)
          if (fieldType.getName() == null) {
            throw new RuntimeException("Anonymous structs as fields not supported yet (field \"" +
                                       field + "\" in type \"" + name + "\")");
          }

          generateOffsetAndSizeArrays(javaWriter, "  ", fieldName, fieldType, field);
        } else if (fieldType.isArray()) {
            Type baseElementType = field.getType().asArray().getBaseElementType();

            if(!baseElementType.isPrimitive())
                break;

            generateOffsetAndSizeArrays(javaWriter, "  ", fieldName, null, field); /* w/o size */
        } else {
          JavaType externalJavaType = null;
          try {
            externalJavaType = typeToJavaType(fieldType, false, machDescJava);
          } catch (Exception e) {
            System.err.println("Error occurred while creating accessor for field \"" +
                               field.getName() + "\" in type \"" + name + "\"");
            throw(e);
          }
          if (externalJavaType.isPrimitive()) {
            // Primitive type
            generateOffsetAndSizeArrays(javaWriter, "  ", fieldName, null, field); /* w/o size */
          } else if (externalJavaType.isCPrimitivePointerType()) {
            // FIXME: Primitive Pointer type
            generateOffsetAndSizeArrays(javaWriter, "//", fieldName, fieldType, field);
          } else {
            // FIXME
            LOG.log(WARNING, "Complicated fields (field \"{0}\" of type \"{1}\") not implemented yet: "+externalJavaType.getDumpString(), new Object[]{field, name});
            //          throw new RuntimeException("Complicated fields (field \"" + field + "\" of type \"" + t +
            //                                     "\") not implemented yet");
          }
        }
      }
    }
    javaWriter.println();
    if (needsNativeCode) {
        emitJavaInitCode(javaWriter, containingTypeName);
        javaWriter.println();
    }
    javaWriter.println("  public static int size() {");
    javaWriter.println("    return "+containingTypeName+"_size[mdIdx];");
    javaWriter.println("  }");
    javaWriter.println();
    javaWriter.println("  public static " + containingTypeName + " create() {");
    javaWriter.println("    return create(Buffers.newDirectByteBuffer(size()));");
    javaWriter.println("  }");
    javaWriter.println();
    javaWriter.println("  public static " + containingTypeName + " create(java.nio.ByteBuffer buf) {");
    javaWriter.println("      return new " + containingTypeName + "(buf);");
    javaWriter.println("  }");
    javaWriter.println();
    javaWriter.println("  " + containingTypeName + "(java.nio.ByteBuffer buf) {");
    javaWriter.println("    accessor = new StructAccessor(buf);");
    javaWriter.println("  }");
    javaWriter.println();
    javaWriter.println("  public java.nio.ByteBuffer getBuffer() {");
    javaWriter.println("    return accessor.getBuffer();");
    javaWriter.println("  }");

    for (int i = 0; i < structType.getNumFields(); i++) {
      final Field field = structType.getField(i);
      final Type fieldType = field.getType();

      if (!cfg.shouldIgnoreInInterface(name + " " + field.getName())) {
        final String renamed = cfg.getJavaSymbolRename(field.getName());
        final String fieldName = renamed==null ? field.getName() : renamed;

        if (fieldType.isFunctionPointer()) {
            try {
              // Emit method call and associated native code
              FunctionType   funcType     = fieldType.asPointer().getTargetType().asFunction();
              FunctionSymbol funcSym      = new FunctionSymbol(fieldName, funcType);
              MethodBinding  binding      = bindFunction(funcSym, containingType, containingCType, machDescJava);
              binding.findThisPointer(); // FIXME: need to provide option to disable this on per-function basis
              javaWriter.println();

              // Emit public Java entry point for calling this function pointer
              JavaMethodBindingEmitter emitter =
                new JavaMethodBindingEmitter(binding,
                                             javaWriter,
                                             cfg.runtimeExceptionType(),
                                             cfg.unsupportedExceptionType(),
                                             true,
                                             cfg.tagNativeBinding(),
                                             false, // eraseBufferAndArrayTypes
                                             true, // FIXME: should unify this with the general emission code
                                             true, // FIXME: should unify this with the general emission code
                                             false,
                                             false, // FIXME: should unify this with the general emission code
                                             false, // FIXME: should unify this with the general emission code
                                             false, // FIXME: should unify this with the general emission code
                                             false,
                                             cfg);
              emitter.addModifier(JavaMethodBindingEmitter.PUBLIC);
              emitter.emit();

              // Emit private native Java entry point for calling this function pointer
              emitter =
                new JavaMethodBindingEmitter(binding,
                                             javaWriter,
                                             cfg.runtimeExceptionType(),
                                             cfg.unsupportedExceptionType(),
                                             false,
                                             cfg.tagNativeBinding(),
                                             true,
                                             true, // FIXME: should unify this with the general emission code
                                             true, // FIXME: should unify this with the general emission code
                                             true,
                                             true, // FIXME: should unify this with the general emission code
                                             false, // FIXME: should unify this with the general emission code
                                             false, // FIXME: should unify this with the general emission code
                                             false,
                                             cfg);
              emitter.addModifier(JavaMethodBindingEmitter.PRIVATE);
              emitter.addModifier(JavaMethodBindingEmitter.NATIVE);
              emitter.emit();

              // Emit (private) C entry point for calling this function pointer
              CMethodBindingEmitter cEmitter =
                new CMethodBindingEmitter(binding,
                                          jniWriter,
                                          structClassPkg,
                                          containingTypeName,
                                          true, // FIXME: this is optional at this point
                                          false,
                                          true,
                                          false, // FIXME: should unify this with the general emission code
                                          machDescJava);
              prepCEmitter(binding, cEmitter);
              cEmitter.emit();
            } catch (Exception e) {
              System.err.println("While processing field " + field + " of type " + name + ":");
              throw(e);
            }
        } else if (fieldType.isCompound()) {
          // FIXME: will need to support this at least in order to
          // handle the union in jawt_Win32DrawingSurfaceInfo (fabricate a name?)
          if (fieldType.getName() == null) {
            throw new RuntimeException("Anonymous structs as fields not supported yet (field \"" +
                                       field + "\" in type \"" + name + "\")");
          }

          javaWriter.println();
          generateGetterSignature(javaWriter, false, fieldType.getName(), capitalizeString(fieldName));
          javaWriter.println(" {");
          javaWriter.println("    return " + fieldType.getName() + ".create( accessor.slice( " +
                           fieldName+"_offset[mdIdx], "+fieldName+"_size[mdIdx] ) );");
          javaWriter.println(" }");

        } else if (fieldType.isArray()) {

            Type baseElementType = field.getType().asArray().getBaseElementType();

            if(!baseElementType.isPrimitive())
                break;

            String paramType = typeToJavaType(baseElementType, false, machDescJava).getName();
            String capitalized = capitalizeString(fieldName);

            // Setter
            javaWriter.println();
            generateSetterSignature(javaWriter, false, containingTypeName, capitalized, paramType+"[]");
            javaWriter.println(" {");
            javaWriter.print  ("    accessor.set" + capitalizeString(paramType) + "sAt(" + fieldName+"_offset[mdIdx], val);");
            javaWriter.println("    return this;");
            javaWriter.println("  }");
            javaWriter.println();
            // Getter
            generateGetterSignature(javaWriter, false, paramType+"[]", capitalized);
            javaWriter.println(" {");
            javaWriter.print  ("    return accessor.get" + capitalizeString(paramType) + "sAt(" + fieldName+"_offset[mdIdx], new " +paramType+"["+fieldType.asArray().getLength()+"]);");
            javaWriter.println(" }");
        } else {
          JavaType javaType = null;

          try {
            javaType = typeToJavaType(fieldType, false, machDescJava);
          } catch (Exception e) {
            System.err.println("Error occurred while creating accessor for field \"" +
                               field.getName() + "\" in type \"" + name + "\"");
            throw(e);
          }
          if (javaType.isPrimitive()) {
            // Primitive type
            final boolean fieldTypeNativeSizeFixed = fieldType.getSize().hasFixedNativeSize();
            final String javaTypeName;
            if ( isOpaque(fieldType) ) {
              javaTypeName = compatiblePrimitiveJavaTypeName(fieldType, javaType, machDescJava);
            } else {
              javaTypeName = javaType.getName();
            }
            final String capJavaTypeName = capitalizeString(javaTypeName);
            final String capFieldName = capitalizeString(fieldName);
            final String sizeDenominator = fieldType.isPointer() ? "pointer" : javaTypeName ;

            if(GlueGen.debug()) {
                System.err.println("Java.StructEmitter.Primitive: "+field.getName()+", "+fieldType.getName(true)+", "+javaTypeName+", "+
                                   ", fixedSize "+fieldTypeNativeSizeFixed+", opaque "+isOpaque(fieldType)+", isPointer "+fieldType.isPointer()+", isCompound "+fieldType.isCompound()+
                                   ", sizeDenominator "+sizeDenominator);
            }

            javaWriter.println();
            // Setter
            generateSetterSignature(javaWriter, false, containingTypeName, capFieldName, javaTypeName);
            javaWriter.println(" {");
            if( fieldTypeNativeSizeFixed ) {
                javaWriter.println("    accessor.set" + capJavaTypeName + "At(" + fieldName+"_offset[mdIdx], val);");
            } else {
                javaWriter.println("    accessor.set" + capJavaTypeName + "At(" + fieldName+"_offset[mdIdx], val, MachineDescriptionRuntime.getStatic().md."+sizeDenominator+"SizeInBytes());");
            }
            javaWriter.println("    return this;");
            javaWriter.println("  }");
            javaWriter.println();

            // Getter
            generateGetterSignature(javaWriter, false, javaTypeName, capFieldName);
            javaWriter.println(" {");
            javaWriter.print  ("    return ");
            if( fieldTypeNativeSizeFixed ) {
                javaWriter.println("accessor.get" + capJavaTypeName + "At(" + fieldName+"_offset[mdIdx]);");
            } else {
                javaWriter.println("accessor.get" + capJavaTypeName + "At(" + fieldName+"_offset[mdIdx], MachineDescriptionRuntime.getStatic().md."+sizeDenominator+"SizeInBytes());");
            }
            javaWriter.println("  }");
          } else if (javaType.isCPrimitivePointerType()) {
            // FIXME: Primitive Pointer type
            javaWriter.println();
            javaWriter.println("  /** "+fieldName +": "+javaType.getDumpString()+" */");
          }
        }
      }
    }
    emitCustomJavaCode(javaWriter, containingTypeName);
    javaWriter.println("}");
    javaWriter.flush();
    javaWriter.close();
    if (needsNativeCode) {
      jniWriter.flush();
      jniWriter.close();
    }
  }
  @Override
  public void endStructs() throws Exception {}

  public static int addStrings2Buffer(StringBuilder buf, String sep, String first, Collection<String> col) {
    int num = 0;
    if(null==buf) {
        buf = new StringBuilder();
    }

    Iterator<String> iter = col.iterator();
    if(null!=first) {
        buf.append(first);
        if( iter.hasNext() ) {
            buf.append(sep);
        }
        num++;
    }
    while( iter.hasNext() ) {
        buf.append(iter.next());
        if( iter.hasNext() ) {
            buf.append(sep);
        }
        num++;
    }
    return num;
  }

  //----------------------------------------------------------------------
  // Internals only below this point
  //

  private void generateGetterSignature(PrintWriter writer, boolean abstractMethod, String returnTypeName, String capitalizedFieldName) {
      writer.print("  public " + (abstractMethod ? "abstract " : "") + returnTypeName + " get" + capitalizedFieldName + "()");
  }

  private void generateSetterSignature(PrintWriter writer, boolean abstractMethod, String returnTypeName, String capitalizedFieldName, String paramTypeName) {
      writer.print("  public " + (abstractMethod ? "abstract " : "") + returnTypeName + " set" + capitalizedFieldName + "(" + paramTypeName + " val)");
  }

  private void generateOffsetAndSizeArrays(PrintWriter writer, String prefix, String fieldName, Type fieldType, Field field) {
      if(null != field) {
          writer.print(prefix+"private static final int[] "+fieldName+"_offset = new int[] { ");
          for( int i=0; i < machDescTargetConfigs.length; i++ ) {
              if(0<i) {
                  writer.print(", ");
              }
              writer.print(field.getOffset(machDescTargetConfigs[i].md) +
                           " /* " + machDescTargetConfigs[i].name() + " */");
          }
          writer.println(" };");
      }
      if(null!=fieldType) {
          writer.print(prefix+"private static final int[] "+fieldName+"_size = new int[] { ");
          for( int i=0; i < machDescTargetConfigs.length; i++ ) {
              if(0<i) {
                  writer.print(", ");
              }
              writer.print(fieldType.getSize(machDescTargetConfigs[i].md) +
                           " /* " + machDescTargetConfigs[i].name() + " */");
          }
          writer.println("  };");
      }
  }

  private JavaType typeToJavaType(Type cType, boolean outgoingArgument, MachineDescription curMachDesc) {
    // Recognize JNIEnv* case up front
    PointerType opt = cType.asPointer();
    if ((opt != null) &&
        (opt.getTargetType().getName() != null) &&
        (opt.getTargetType().getName().equals("JNIEnv"))) {
      return JavaType.createForJNIEnv();
    }
    Type t = cType;

    // Opaque specifications override automatic conversions
    // in case the identity is being used .. not if ptr-ptr
    TypeInfo info = cfg.typeInfo(t, typedefDictionary);
    if (info != null) {
      boolean isPointerPointer = false;
      if (t.pointerDepth() > 0 || t.arrayDimension() > 0) {
        Type targetType; // target type
        if (t.isPointer()) {
          // t is <type>*, we need to get <type>
          targetType = t.asPointer().getTargetType();
        } else {
          // t is <type>[], we need to get <type>
          targetType = t.asArray().getBaseElementType();
        }
        if (t.pointerDepth() == 2 || t.arrayDimension() == 2) {
          // Get the target type of the target type (targetType was computer earlier
          // as to be a pointer to the target type, so now we need to get its
          // target type)
          if (targetType.isPointer()) {
            isPointerPointer = true;

            // t is<type>**, targetType is <type>*, we need to get <type>
            Type bottomType = targetType.asPointer().getTargetType();
            LOG.log(INFO, "Opaque Type: {0}, targetType: {1}, bottomType: {2} is ptr-ptr", new Object[]{t, targetType, bottomType});
          }
        }
      }
      if(!isPointerPointer) {
          return info.javaType();
      }
    }

    if (t.isInt() || t.isEnum()) {
      switch ((int) t.getSize(curMachDesc)) {
       case 1:  return javaType(Byte.TYPE);
       case 2:  return javaType(Short.TYPE);
       case 4:  return javaType(Integer.TYPE);
       case 8:  return javaType(Long.TYPE);
       default: throw new RuntimeException("Unknown integer type of size " +
                                           t.getSize(curMachDesc) + " and name " + t.getName());
      }
    } else if (t.isFloat()) {
      return javaType(Float.TYPE);
    } else if (t.isDouble()) {
      return javaType(Double.TYPE);
    } else if (t.isVoid()) {
      return javaType(Void.TYPE);
    } else if (t.pointerDepth() > 0 || t.arrayDimension() > 0) {
        Type targetType; // target type
        if (t.isPointer()) {
          // t is <type>*, we need to get <type>
          targetType = t.asPointer().getTargetType();
        } else {
          // t is <type>[], we need to get <type>
          targetType = t.asArray().getBaseElementType();
        }

        // Handle Types of form pointer-to-type or array-of-type, like
        // char* or int[]; these are expanded out into Java primitive
        // arrays, NIO buffers, or both in expandMethodBinding
        if (t.pointerDepth() == 1 || t.arrayDimension() == 1) {
          if (targetType.isVoid()) {
            return JavaType.createForCVoidPointer();
          } else if (targetType.isInt()) {
            final SizeThunk targetSizeThunk = targetType.getSize();
            if( null != targetSizeThunk && SizeThunk.POINTER == targetSizeThunk ) {
              // Map intptr_t*, uintptr_t*, ptrdiff_t* and size_t* to PointerBuffer, since referenced memory-size is arch dependent
              return JavaType.forNIOPointerBufferClass();
            }
            switch ((int) targetType.getSize(curMachDesc)) {
              case 1:  return JavaType.createForCCharPointer();
              case 2:  return JavaType.createForCShortPointer();
              case 4:  return JavaType.createForCInt32Pointer();
              case 8:  return JavaType.createForCInt64Pointer();
              default: throw new RuntimeException("Unknown integer array type of size " +
                                                  t.getSize(curMachDesc) + " and name " + t.getName());
            }
          } else if (targetType.isFloat()) {
            return JavaType.createForCFloatPointer();
          } else if (targetType.isDouble()) {
            return JavaType.createForCDoublePointer();
          } else if (targetType.isCompound()) {
            if (t.isArray()) { // FIXME: Compound and Compound-Arrays
              return JavaType.createForCArray(targetType);
            }
            // Special cases for known JNI types (in particular for converting jawt.h)
            if (t.getName() != null &&
                t.getName().equals("jobject")) {
              return javaType(java.lang.Object.class);
            }
            String name = targetType.getName();
            if (name == null) {
              // Try containing pointer type for any typedefs
              name = t.getName();
              if (name == null) {
                throw new RuntimeException("Couldn't find a proper type name for pointer type " + t);
              }
            }

            return JavaType.createForCStruct(cfg.renameJavaType(name));
          } else {
            throw new RuntimeException("Don't know how to convert pointer/array type \"" +
                                       t + "\"");
          }
        }
        // Handle Types of form pointer-to-pointer-to-type or
        // array-of-arrays-of-type, like char** or int[][]
        else if (t.pointerDepth() == 2 || t.arrayDimension() == 2) {
          // Get the target type of the target type (targetType was computer earlier
          // as to be a pointer to the target type, so now we need to get its
          // target type)
          Type bottomType;
          if (targetType.isPointer()) {
            // t is<type>**, targetType is <type>*, we need to get <type>
            bottomType = targetType.asPointer().getTargetType();
            return JavaType.forNIOPointerBufferClass();
          } else {
            // t is<type>[][], targetType is <type>[], we need to get <type>
            bottomType = targetType.asArray().getBaseElementType();
            LOG.log(WARNING, "typeToJavaType(ptr-ptr): {0}, targetType: {1}, bottomType: {2} -> Unhandled!", new Object[]{t, targetType, bottomType});
          }

          // Warning: The below code is not backed up by an implementation,
          //          the only working variant is a ptr-ptr type which results in a PointerBuffer.
          //
          if (bottomType.isPrimitive()) {
            if (bottomType.isInt()) {
              switch ((int) bottomType.getSize(curMachDesc)) {
                case 1: return javaType(ArrayTypes.byteBufferArrayClass);
                case 2: return javaType(ArrayTypes.shortBufferArrayClass);
                case 4: return javaType(ArrayTypes.intBufferArrayClass);
                case 8: return javaType(ArrayTypes.longBufferArrayClass);
                default: throw new RuntimeException("Unknown two-dimensional integer array type of element size " +
                                                    bottomType.getSize(curMachDesc) + " and name " + bottomType.getName());
              }
            } else if (bottomType.isFloat()) {
              return javaType(ArrayTypes.floatBufferArrayClass);
            } else if (bottomType.isDouble()) {
              return javaType(ArrayTypes.doubleBufferArrayClass);
            } else {
              throw new RuntimeException("Unexpected primitive type " + bottomType.getName() +
                                         " in two-dimensional array");
            }
          } else if (bottomType.isVoid()) {
            return javaType(ArrayTypes.bufferArrayClass);
          } else if (targetType.isPointer() && (targetType.pointerDepth() == 1) &&
                     targetType.asPointer().getTargetType().isCompound()) {
            // Array of pointers; convert as array of StructAccessors
            return JavaType.createForCArray(bottomType);
          } else {
            throw new RuntimeException(
              "Could not convert C type \"" + t + "\" " +
              "to appropriate Java type; need to add more support for " +
              "depth=2 pointer/array types [debug info: targetType=\"" +
              targetType + "\"]");
          }
        } else {
          // can't handle this type of pointer/array argument
          throw new RuntimeException(
            "Could not convert C pointer/array \"" + t + "\" to " +
            "appropriate Java type; types with pointer/array depth " +
            "greater than 2 are not yet supported [debug info: " +
            "pointerDepth=" + t.pointerDepth() + " arrayDimension=" +
            t.arrayDimension() + " targetType=\"" + targetType + "\"]");
        }

    } else if(t.isCompound() ) { // FIXME: Compound and Compound-Arrays
        final String name = t.getName();
        if (name == null) {
          throw new RuntimeException("Couldn't find a proper type name for pointer type " + t);
        }
        return JavaType.createForCStruct(cfg.renameJavaType(name));
    } else {
        throw new RuntimeException(
          "Could not convert C type \"" + t + "\" (class " +
          t.getClass().getName() + ") to appropriate Java type");
    }
  }

  private static boolean isIntegerType(Class<?> c) {
    return ((c == Byte.TYPE) ||
            (c == Short.TYPE) ||
            (c == Character.TYPE) ||
            (c == Integer.TYPE) ||
            (c == Long.TYPE));
  }

  private StructLayout getLayout() {
    if (layout == null) {
      layout = StructLayout.create(0);
    }
    return layout;
  }

  /**
   * @param filename the class's full filename to open w/ write access
   * @param simpleClassName the simple class name, i.e. w/o package name
   * @return a {@link PrintWriter} instance to write the class source file or <code>null</code> to suppress output!
   * @throws IOException
   */
  protected PrintWriter openFile(String filename, String simpleClassName) throws IOException {
    //System.out.println("Trying to open: " + filename);
    final File file = new File(filename);
    final String parentDir = file.getParent();
    if (parentDir != null) {
        new File(parentDir).mkdirs();
    }
    return new PrintWriter(new BufferedWriter(new FileWriter(file)));
  }

  private boolean isOpaque(Type type) {
    return (cfg.typeInfo(type, typedefDictionary) != null);
  }

  private String compatiblePrimitiveJavaTypeName(Type fieldType,
                                                 JavaType javaType,
                                                 MachineDescription curMachDesc) {
    Class<?> c = javaType.getJavaClass();
    if (!isIntegerType(c)) {
      // FIXME
      throw new RuntimeException("Can't yet handle opaque definitions of structs' fields to non-integer types (byte, short, int, long, etc.): type: "+fieldType+", javaType "+javaType+", javaClass "+c);
    }
    switch ((int) fieldType.getSize(curMachDesc)) {
      case 1:  return "byte";
      case 2:  return "short";
      case 4:  return "int";
      case 8:  return "long";
      default: throw new RuntimeException("Can't handle opaque definitions if the starting type isn't compatible with integral types");
    }
  }

  private void openWriters() throws IOException {
    String jRoot = null;
    if (cfg.allStatic() || cfg.emitInterface()) {
      jRoot = cfg.javaOutputDir() + File.separator +
        CodeGenUtils.packageAsPath(cfg.packageName());
    }
    String jImplRoot = null;
    if (!cfg.allStatic()) {
      jImplRoot =
        cfg.javaOutputDir() + File.separator +
        CodeGenUtils.packageAsPath(cfg.implPackageName());
    }
    String nRoot = cfg.nativeOutputDir();
    if (cfg.nativeOutputUsesJavaHierarchy())
    {
      nRoot +=
        File.separator + CodeGenUtils.packageAsPath(cfg.packageName());
    }

    if (cfg.allStatic() || cfg.emitInterface()) {
      javaWriter = openFile(jRoot + File.separator + cfg.className() + ".java", cfg.className());
    }
    if (!cfg.allStatic() && cfg.emitImpl()) {
      javaImplWriter = openFile(jImplRoot + File.separator + cfg.implClassName() + ".java", cfg.implClassName());
    }
    if (cfg.emitImpl()) {
      cWriter = openFile(nRoot + File.separator + cfg.implClassName() + "_JNI.c", cfg.implClassName());
    }

    if (javaWriter != null) {
      CodeGenUtils.emitAutogeneratedWarning(javaWriter, this);
    }
    if (javaImplWriter != null) {
      CodeGenUtils.emitAutogeneratedWarning(javaImplWriter, this);
    }
    if (cWriter != null) {
      CodeGenUtils.emitAutogeneratedWarning(cWriter, this);
    }
  }

  protected PrintWriter javaWriter() {
    if (!cfg.allStatic() && !cfg.emitInterface()) {
      throw new InternalError("Should not call this");
    }
    return javaWriter;
  }

  protected PrintWriter javaImplWriter() {
    if (cfg.allStatic() || !cfg.emitImpl()) {
      throw new InternalError("Should not call this");
    }
    return javaImplWriter;
  }

  protected PrintWriter cWriter() {
    if (!cfg.emitImpl()) {
      throw new InternalError("Should not call this");
    }
    return cWriter;
  }

  private void closeWriter(PrintWriter writer) throws IOException {
    writer.flush();
    writer.close();
  }

  private void closeWriters() throws IOException {
    if (javaWriter != null) {
      closeWriter(javaWriter);
    }
    if (javaImplWriter != null) {
      closeWriter(javaImplWriter);
    }
    if (cWriter != null) {
      closeWriter(cWriter);
    }
    javaWriter = null;
    javaImplWriter = null;
    cWriter = null;
  }

  /**
   * Returns the value that was specified by the configuration directive
   * "JavaOutputDir", or the default if none was specified.
   */
  protected String getJavaOutputDir() {
    return cfg.javaOutputDir();
  }

  /**
   * Returns the value that was specified by the configuration directive
   * "Package", or the default if none was specified.
   */
  protected String getJavaPackageName() {
    return cfg.packageName();
  }

  /**
   * Returns the value that was specified by the configuration directive
   * "ImplPackage", or the default if none was specified.
   */
  protected String getImplPackageName() {
    return cfg.implPackageName();
  }

  /**
   * Emit all the strings specified in the "CustomJavaCode" parameters of
   * the configuration file.
   */
  protected void emitCustomJavaCode(PrintWriter writer, String className) throws Exception  {
    List<String> code = cfg.customJavaCodeForClass(className);
    if (code.isEmpty())
      return;

    writer.println();
    writer.println("  // --- Begin CustomJavaCode .cfg declarations");
    for (String line : code) {
      writer.println(line);
    }
    writer.println("  // ---- End CustomJavaCode .cfg declarations");
  }

  /**
   * Write out any header information for the output files (class declaration
   * and opening brace, import statements, etc).
   */
  protected void emitAllFileHeaders() throws IOException {
    try {
        List<String> imports = new ArrayList<String>(cfg.imports());
        imports.add(cfg.gluegenRuntimePackage()+".*");
        imports.add(DynamicLookupHelper.class.getPackage().getName()+".*");
        imports.add(Buffers.class.getPackage().getName()+".*");
        imports.add(Buffer.class.getPackage().getName()+".*");

      if (cfg.allStatic() || cfg.emitInterface()) {

        String[] interfaces;
        List<String> userSpecifiedInterfaces = null;
        if (cfg.emitInterface()) {
          userSpecifiedInterfaces = cfg.extendedInterfaces(cfg.className());
        } else {
          userSpecifiedInterfaces = cfg.implementedInterfaces(cfg.className());
        }
        interfaces = new String[userSpecifiedInterfaces.size()];
        userSpecifiedInterfaces.toArray(interfaces);

        final List<String> intfDocs = cfg.javadocForClass(cfg.className());
        CodeGenUtils.EmissionCallback docEmitter =
          new CodeGenUtils.EmissionCallback() {
            @Override
            public void emit(PrintWriter w) {
              for (Iterator<String> iter = intfDocs.iterator(); iter.hasNext(); ) {
                w.println(iter.next());
              }
            }
          };

        String[] accessModifiers = null;
        if(cfg.accessControl(cfg.className()) == PUBLIC_ABSTRACT) {
            accessModifiers = new String[] { "public", "abstract" };
        } else {
            accessModifiers = new String[] { "public" };
        }

        CodeGenUtils.emitJavaHeaders(
          javaWriter,
          cfg.packageName(),
          cfg.className(),
          cfg.allStatic() ? true : false,
          imports,
          accessModifiers,
          interfaces,
          cfg.extendedParentClass(cfg.className()),
          docEmitter);
      }

      if (!cfg.allStatic() && cfg.emitImpl()) {
        final List<String> implDocs = cfg.javadocForClass(cfg.implClassName());
        CodeGenUtils.EmissionCallback docEmitter =
          new CodeGenUtils.EmissionCallback() {
            @Override
            public void emit(PrintWriter w) {
              for (Iterator<String> iter = implDocs.iterator(); iter.hasNext(); ) {
                w.println(iter.next());
              }
            }
          };

        String[] interfaces;
        List<String> userSpecifiedInterfaces = null;
        userSpecifiedInterfaces = cfg.implementedInterfaces(cfg.implClassName());
        int additionalNum = 0;
        if (cfg.className() != null) {
          additionalNum = 1;
        }
        interfaces = new String[additionalNum + userSpecifiedInterfaces.size()];
        userSpecifiedInterfaces.toArray(interfaces);
        if (additionalNum == 1) {
          interfaces[userSpecifiedInterfaces.size()] = cfg.className();
        }

        String[] accessModifiers = null;
        if(cfg.accessControl(cfg.implClassName()) == PUBLIC_ABSTRACT) {
            accessModifiers = new String[] { "public", "abstract" };
        } else {
            accessModifiers = new String[] { "public" };
        }

        CodeGenUtils.emitJavaHeaders(
          javaImplWriter,
          cfg.implPackageName(),
          cfg.implClassName(),
          true,
          imports,
          accessModifiers,
          interfaces,
          cfg.extendedParentClass(cfg.implClassName()),
          docEmitter);
      }

      if (cfg.emitImpl()) {
        emitJavaInitCode();
        emitCHeader(cWriter(), getImplPackageName(), cfg.implClassName());
      }
    } catch (Exception e) {
      throw new RuntimeException(
        "Error emitting all file headers: cfg.allStatic()=" + cfg.allStatic() +
        " cfg.emitImpl()=" + cfg.emitImpl() + " cfg.emitInterface()=" + cfg.emitInterface(),
        e);
    }

  }

  private static final String initClassAccessCode = "\n"+
         "static const char * clazzNameBuffers = \"com/jogamp/common/nio/Buffers\";\n"+
         "static const char * clazzNameBuffersStaticNewCstrName = \"newDirectByteBuffer\";\n"+
         "static const char * clazzNameBuffersStaticNewCstrSignature = \"(I)Ljava/nio/ByteBuffer;\";\n"+
         "static jclass clazzBuffers = NULL;\n"+
         "static jmethodID cstrBuffersNew = NULL;\n"+
         "\n"+
         "static jboolean _initClazzAccess(JNIEnv *env) {\n"+
         "    jclass c;\n"+
         "\n"+
         "    if(NULL!=cstrBuffersNew) return JNI_TRUE;\n"+
         "\n"+
         "    c = (*env)->FindClass(env, clazzNameBuffers);\n"+
         "    if(NULL==c) {\n"+
         "        fprintf(stderr, \"FatalError: Can't find %s\\n\", clazzNameBuffers);\n"+
         "        (*env)->FatalError(env, clazzNameBuffers);\n"+
         "        return JNI_FALSE;\n"+
         "    }\n"+
         "    clazzBuffers = (jclass)(*env)->NewGlobalRef(env, c);\n"+
         "    if(NULL==clazzBuffers) {\n"+
         "        fprintf(stderr, \"FatalError: Can't use %s\\n\", clazzNameBuffers);\n"+
         "        (*env)->FatalError(env, clazzNameBuffers);\n"+
         "        return JNI_FALSE;\n"+
         "    }\n"+
         "\n"+
         "    cstrBuffersNew = (*env)->GetStaticMethodID(env, clazzBuffers,\n"+
         "                            clazzNameBuffersStaticNewCstrName, clazzNameBuffersStaticNewCstrSignature);\n"+
         "    if(NULL==cstrBuffersNew) {\n"+
         "        fprintf(stderr, \"FatalError: Java_jogamp_common_jvm_JVMUtil:: can't create %s.%s %s\\n\",\n"+
         "            clazzNameBuffers,\n"+
         "            clazzNameBuffersStaticNewCstrName, clazzNameBuffersStaticNewCstrSignature);\n"+
         "        (*env)->FatalError(env, clazzNameBuffersStaticNewCstrName);\n"+
         "        return JNI_FALSE;\n"+
         "    }\n"+
         "    return JNI_TRUE;\n"+
         "}\n"+
         "\n"+
         "static jobject JVMUtil_NewDirectByteBufferCopy(JNIEnv *env, void * source_address, jlong capacity) {\n"+
         "    jobject jbyteBuffer  = (*env)->CallStaticObjectMethod(env, clazzBuffers, cstrBuffersNew, capacity);\n"+
         "    void * byteBufferPtr = (*env)->GetDirectBufferAddress(env, jbyteBuffer);\n"+
         "    memcpy(byteBufferPtr, source_address, capacity);\n"+
         "    return jbyteBuffer;\n"+
         "}\n"+
         "\n";

  private static final String staticClassInitCode = "\n"+
         "  static {\n"+
         "    if( !initializeImpl() ) {\n"+
         "      throw new RuntimeException(\"Initialization failure\");\n"+
         "    }\n"+
         "  }\n"+
         "\n";

  protected void emitCHeader(PrintWriter cWriter, String packageName, String className) {
    cWriter.println("#include <jni.h>");
    cWriter.println("#include <stdlib.h>");
    cWriter.println("#include <string.h>");
    cWriter.println();

    if (getConfig().emitImpl()) {
      cWriter.println("#include <assert.h>");
      cWriter.println();
    }
    emitCInitCode(cWriter, packageName, className);
    for (String code : cfg.customCCode()) {
      cWriter.println(code);
    }
    cWriter.println();
  }

  protected void emitCInitCode(PrintWriter cWriter, String packageName, String className) {
    if (getConfig().emitImpl()) {
      cWriter.println(initClassAccessCode);
      cWriter.println("JNIEXPORT jboolean JNICALL "+JavaEmitter.getJNIMethodNamePrefix(packageName, className)+"_initializeImpl(JNIEnv *env, jclass _unused) {");
      cWriter.println("    return _initClazzAccess(env);");
      cWriter.println("}");
      cWriter.println();
    }
  }
  protected void emitJavaInitCode() {
    if ( cfg.allStatic() ) {
        emitJavaInitCode( javaWriter(), cfg.className() );
    } else if( cfg.emitImpl() ) {
        emitJavaInitCode( javaImplWriter(), cfg.implClassName() );
    }
  }
  protected void emitJavaInitCode(PrintWriter jWriter, String className) {
    if( null != jWriter ) {
        jWriter.println();
        jWriter.println("  private static native boolean initializeImpl();");
        jWriter.println();
        if( !cfg.manualStaticInit(className) ) {
            jWriter.println(staticClassInitCode);
        }
    }
  }

  /**
   * Write out any footer information for the output files (closing brace of
   * class definition, etc).
   */
  protected void emitAllFileFooters(){
    if (cfg.allStatic() || cfg.emitInterface()) {
      javaWriter().println();
      javaWriter().println("} // end of class " + cfg.className());
    }
    if (!cfg.allStatic() && cfg.emitImpl())  {
      javaImplWriter().println();
      javaImplWriter().println("} // end of class " + cfg.implClassName());
    }
  }

  private JavaType javaType(Class<?> c) {
    return JavaType.createForClass(c);
  }

  /** Maps the C types in the specified function to Java types through
      the MethodBinding interface. Note that the JavaTypes in the
      returned MethodBinding are "intermediate" JavaTypes (some
      potentially representing C pointers rather than true Java types)
      and must be lowered to concrete Java types before creating
      emitters for them. */
  private MethodBinding bindFunction(FunctionSymbol sym,
                                     JavaType containingType,
                                     Type containingCType,
                                     MachineDescription curMachDesc) {

    MethodBinding binding = new MethodBinding(sym, containingType, containingCType);

    binding.renameMethodName(cfg.getJavaSymbolRename(sym.getName()));

    // System.out.println("bindFunction(0) "+sym.getReturnType());

    if (cfg.returnsString(binding.getName())) {
      PointerType prt = sym.getReturnType().asPointer();
      if (prt == null ||
          prt.getTargetType().asInt() == null ||
          prt.getTargetType().getSize(curMachDesc) != 1) {
        throw new RuntimeException(
          "Cannot apply ReturnsString configuration directive to \"" + sym +
          "\". ReturnsString requires native method to have return type \"char *\"");
      }
      binding.setJavaReturnType(javaType(java.lang.String.class));
    } else {
      binding.setJavaReturnType(typeToJavaType(sym.getReturnType(), false, curMachDesc));
    }

    // System.out.println("bindFunction(1) "+binding.getJavaReturnType());

    // List of the indices of the arguments in this function that should be
    // converted from byte[] or short[] to String
    List<Integer> stringArgIndices = cfg.stringArguments(binding.getName());

    for (int i = 0; i < sym.getNumArguments(); i++) {
      Type cArgType = sym.getArgumentType(i);
      JavaType mappedType = typeToJavaType(cArgType, true, curMachDesc);
      // System.out.println("C arg type -> \"" + cArgType + "\"" );
      // System.out.println("      Java -> \"" + mappedType + "\"" );

      // Take into account any ArgumentIsString configuration directives that apply
      if (stringArgIndices != null && stringArgIndices.contains(i)) {
        // System.out.println("Forcing conversion of " + binding.getName() + " arg #" + i + " from byte[] to String ");
        if (mappedType.isCVoidPointerType() ||
            mappedType.isCCharPointerType() ||
            mappedType.isCShortPointerType() ||
            mappedType.isNIOPointerBuffer() ||
            (mappedType.isArray() &&
             (mappedType.getJavaClass() == ArrayTypes.byteBufferArrayClass) ||
             (mappedType.getJavaClass() == ArrayTypes.shortBufferArrayClass))) {
          // convert mapped type from:
          //   void*, byte[], and short[] to String
          //   ByteBuffer[] and ShortBuffer[] to String[]
          if (mappedType.isArray() || mappedType.isNIOPointerBuffer()) {
            mappedType = javaType(ArrayTypes.stringArrayClass);
          } else {
            mappedType = javaType(String.class);
          }
        }
        else {
        throw new RuntimeException(
          "Cannot apply ArgumentIsString configuration directive to " +
          "argument " + i + " of \"" + sym + "\": argument type is not " +
          "a \"void*\", \"char *\", \"short *\", \"char**\", or \"short**\" equivalent");
        }
      }
      binding.addJavaArgumentType(mappedType);
      //System.out.println("During binding of [" + sym + "], added mapping from C type: " + cArgType + " to Java type: " + mappedType);
    }

    // System.out.println("---> " + binding);
    // System.out.println("    ---> " + binding.getCSymbol());
    // System.out.println("bindFunction(3) "+binding);
    return binding;
  }

  private MethodBinding lowerMethodBindingPointerTypes(MethodBinding inputBinding,
                                                       boolean convertToArrays,
                                                       boolean[] canProduceArrayVariant) {
    MethodBinding result = inputBinding;
    boolean arrayPossible = false;

    // System.out.println("lowerMethodBindingPointerTypes(0): "+result);

    for (int i = 0; i < inputBinding.getNumArguments(); i++) {
      JavaType t = inputBinding.getJavaArgumentType(i);
      if (t.isCPrimitivePointerType()) {
        if (t.isCVoidPointerType()) {
          // These are always bound to java.nio.Buffer
          result = result.replaceJavaArgumentType(i, JavaType.forNIOBufferClass());
        } else if (t.isCCharPointerType()) {
          arrayPossible = true;
          if (convertToArrays) {
            result = result.replaceJavaArgumentType(i, javaType(ArrayTypes.byteArrayClass));
          } else {
            result = result.replaceJavaArgumentType(i, JavaType.forNIOByteBufferClass());
          }
        } else if (t.isCShortPointerType()) {
          arrayPossible = true;
          if (convertToArrays) {
            result = result.replaceJavaArgumentType(i, javaType(ArrayTypes.shortArrayClass));
          } else {
            result = result.replaceJavaArgumentType(i, JavaType.forNIOShortBufferClass());
          }
        } else if (t.isCInt32PointerType()) {
          arrayPossible = true;
          if (convertToArrays) {
            result = result.replaceJavaArgumentType(i, javaType(ArrayTypes.intArrayClass));
          } else {
            result = result.replaceJavaArgumentType(i, JavaType.forNIOIntBufferClass());
          }
        } else if (t.isCInt64PointerType()) {
          arrayPossible = true;
          if (convertToArrays) {
            result = result.replaceJavaArgumentType(i, javaType(ArrayTypes.longArrayClass));
          } else {
            result = result.replaceJavaArgumentType(i, JavaType.forNIOLongBufferClass());
          }
        } else if (t.isCFloatPointerType()) {
          arrayPossible = true;
          if (convertToArrays) {
            result = result.replaceJavaArgumentType(i, javaType(ArrayTypes.floatArrayClass));
          } else {
            result = result.replaceJavaArgumentType(i, JavaType.forNIOFloatBufferClass());
          }
        } else if (t.isCDoublePointerType()) {
          arrayPossible = true;
          if (convertToArrays) {
            result = result.replaceJavaArgumentType(i, javaType(ArrayTypes.doubleArrayClass));
          } else {
            result = result.replaceJavaArgumentType(i, JavaType.forNIODoubleBufferClass());
          }
        } else {
          throw new RuntimeException("Unknown C pointer type " + t);
        }
      }
    }

    // System.out.println("lowerMethodBindingPointerTypes(1): "+result);

    // Always return primitive pointer types as NIO buffers
    JavaType t = result.getJavaReturnType();
    if (t.isCPrimitivePointerType()) {
      if (t.isCVoidPointerType()) {
        result = result.replaceJavaArgumentType(-1, JavaType.forNIOByteBufferClass());
      } else if (t.isCCharPointerType()) {
        result = result.replaceJavaArgumentType(-1, JavaType.forNIOByteBufferClass());
      } else if (t.isCShortPointerType()) {
        result = result.replaceJavaArgumentType(-1, JavaType.forNIOShortBufferClass());
      } else if (t.isCInt32PointerType()) {
        result = result.replaceJavaArgumentType(-1, JavaType.forNIOIntBufferClass());
      } else if (t.isCInt64PointerType()) {
        result = result.replaceJavaArgumentType(-1, JavaType.forNIOLongBufferClass());
      } else if (t.isCFloatPointerType()) {
        result = result.replaceJavaArgumentType(-1, JavaType.forNIOFloatBufferClass());
      } else if (t.isCDoublePointerType()) {
        result = result.replaceJavaArgumentType(-1, JavaType.forNIODoubleBufferClass());
      } else {
        throw new RuntimeException("Unknown C pointer type " + t);
      }
    }

    // System.out.println("lowerMethodBindingPointerTypes(2): "+result);

    if (canProduceArrayVariant != null) {
      canProduceArrayVariant[0] = arrayPossible;
    }

    return result;
  }

  // Expands a MethodBinding containing C primitive pointer types into
  // multiple variants taking Java primitive arrays and NIO buffers, subject
  // to the per-function "NIO only" rule in the configuration file
  protected List<MethodBinding> expandMethodBinding(MethodBinding binding) {

    List<MethodBinding> result = new ArrayList<MethodBinding>();
    // Indicates whether it is possible to produce an array variant
    // Prevents e.g. char* -> String conversions from emitting two entry points
    boolean[] canProduceArrayVariant = new boolean[1];

    if (binding.signatureUsesCPrimitivePointers() ||
        binding.signatureUsesCVoidPointers() ||
        binding.signatureUsesCArrays()) {

      result.add(lowerMethodBindingPointerTypes(binding, false, canProduceArrayVariant));

      // FIXME: should add new configuration flag for this
      if (canProduceArrayVariant[0] && (binding.signatureUsesCPrimitivePointers() || binding.signatureUsesCArrays()) &&
          !cfg.useNIOOnly(binding.getName()) ) {
        result.add(lowerMethodBindingPointerTypes(binding, true, null));
      }
    } else {
      result.add(binding);
    }

    return result;
  }

  private Type canonicalize(Type t) {
    Type res = canonMap.get(t);
    if (res != null) {
      return res;
    }
    canonMap.put(t, t);
    return t;
  }

  /**
   * Converts first letter to upper case.
   */
  private final String capitalizeString(String string) {
      return Character.toUpperCase(string.charAt(0)) + string.substring(1);
  }

}