summaryrefslogtreecommitdiffstats
path: root/opengl/tools/glgen/src/JniCodeEmitter.java
blob: e79170a28a8b1c1872e01a91a995c15e6d86df04 (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
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

public class JniCodeEmitter {

    static final boolean mUseCPlusPlus = true;
    protected boolean mUseContextPointer = true;
    protected boolean mUseStaticMethods = false;
    protected String mClassPathName;
    protected ParameterChecker mChecker;
    protected List<String> nativeRegistrations = new ArrayList<String>();
    boolean needsExit;
    protected static String indent = "    ";
    HashSet<String> mFunctionsEmitted = new HashSet<String>();

    public static String getJniName(JType jType) {
        String jniName = "";
        if (jType.isClass()) {
            return "L" + jType.getBaseType() + ";";
        } else if (jType.isArray()) {
            jniName = "[";
        }

        String baseType = jType.getBaseType();
        if (baseType.equals("int")) {
            jniName += "I";
        } else if (baseType.equals("float")) {
            jniName += "F";
        } else if (baseType.equals("boolean")) {
            jniName += "Z";
        } else if (baseType.equals("short")) {
            jniName += "S";
        } else if (baseType.equals("long")) {
            jniName += "L";
        } else if (baseType.equals("byte")) {
            jniName += "B";
        } else if (baseType.equals("String")) {
            jniName += "Ljava/lang/String;";
        } else if (baseType.equals("void")) {
            // nothing.
        } else {
            throw new RuntimeException("Uknown primitive basetype " + baseType);
        }
        return jniName;
    }


    public void emitCode(CFunc cfunc, String original,
            PrintStream javaInterfaceStream,
            PrintStream javaImplStream,
            PrintStream cStream) {
        JFunc jfunc;
        String signature;
        boolean duplicate;

        if (cfunc.hasTypedPointerArg()) {
            jfunc = JFunc.convert(cfunc, true);

            // Don't emit duplicate functions
            // These may appear because they are defined in multiple
            // Java interfaces (e.g., GL11/GL11ExtensionPack)
            signature = jfunc.toString();
            duplicate = false;
            if (mFunctionsEmitted.contains(signature)) {
                duplicate = true;
            } else {
                mFunctionsEmitted.add(signature);
            }

            if (!duplicate) {
                emitNativeDeclaration(jfunc, javaImplStream);
                emitJavaCode(jfunc, javaImplStream);
            }
            if (javaInterfaceStream != null) {
                emitJavaInterfaceCode(jfunc, javaInterfaceStream);
            }
            if (!duplicate) {
                emitJniCode(jfunc, cStream);
            }
        }

        jfunc = JFunc.convert(cfunc, false);

        signature = jfunc.toString();
        duplicate = false;
        if (mFunctionsEmitted.contains(signature)) {
            duplicate = true;
        } else {
            mFunctionsEmitted.add(signature);
        }

        if (!duplicate) {
            emitNativeDeclaration(jfunc, javaImplStream);
        }
        if (javaInterfaceStream != null) {
            emitJavaInterfaceCode(jfunc, javaInterfaceStream);
        }
        if (!duplicate) {
            emitJavaCode(jfunc, javaImplStream);
            emitJniCode(jfunc, cStream);
        }
    }

    public void emitNativeDeclaration(JFunc jfunc, PrintStream out) {
        out.println("    // C function " + jfunc.getCFunc().getOriginal());
        out.println();

        emitFunction(jfunc, out, true, false);
    }

    public void emitJavaInterfaceCode(JFunc jfunc, PrintStream out) {
        emitFunction(jfunc, out, false, true);
    }

    public void emitJavaCode(JFunc jfunc, PrintStream out) {
        emitFunction(jfunc, out, false, false);
    }

    boolean isPointerFunc(JFunc jfunc) {
        String name = jfunc.getName();
        return (name.endsWith("Pointer") || name.endsWith("PointerOES"))
            && jfunc.getCFunc().hasPointerArg();
    }

    void emitFunctionCall(JFunc jfunc, PrintStream out, String iii, boolean grabArray) {
        boolean isVoid = jfunc.getType().isVoid();
        boolean isPointerFunc = isPointerFunc(jfunc);

        if (!isVoid) {
            out.println(iii +
                        jfunc.getType() + " _returnValue;");
        }
        out.println(iii +
                    (isVoid ? "" : "_returnValue = ") +
                    jfunc.getName() +
                    (isPointerFunc ? "Bounds" : "" ) +
                    "(");

        int numArgs = jfunc.getNumArgs();
        for (int i = 0; i < numArgs; i++) {
            String argName = jfunc.getArgName(i);
            JType argType = jfunc.getArgType(i);

            if (grabArray && argType.isTypedBuffer()) {
                String typeName = argType.getBaseType();
                typeName = typeName.substring(9, typeName.length() - 6);
                out.println(iii + indent + "get" + typeName + "Array(" + argName + "),");
                out.print(iii + indent + "getOffset(" + argName + ")");
            } else {
                out.print(iii + indent + argName);
            }
            if (i == numArgs - 1) {
                if (isPointerFunc) {
                    out.println(",");
                    out.println(iii + indent + argName + ".remaining()");
                } else {
                    out.println();
                }
            } else {
                out.println(",");
            }
        }

        out.println(iii + ");");
    }

    void printIfcheckPostamble(PrintStream out, boolean isBuffer, boolean emitExceptionCheck,
            String iii) {
                printIfcheckPostamble(out, isBuffer, emitExceptionCheck,
                                      "offset", "_remaining", iii);
            }

    void printIfcheckPostamble(PrintStream out, boolean isBuffer, boolean emitExceptionCheck,
            String offset, String remaining, String iii) {
                out.println(iii + "    default:");
                out.println(iii + "        _needed = 0;");
                out.println(iii + "        break;");
                out.println(iii + "}");

                out.println(iii + "if (" + remaining + " < _needed) {");
                if (emitExceptionCheck) {
                    out.println(iii + indent + "_exception = 1;");
                }
                out.println(iii + indent +
                            (mUseCPlusPlus ? "_env" : "(*_env)") +
                            "->ThrowNew(" +
                            (mUseCPlusPlus ? "" : "_env, ") +
                            "IAEClass, " +
                            "\"" +
                            (isBuffer ?
                             "remaining()" : "length - " + offset) +
                            " < needed\");");
                out.println(iii + indent + "goto exit;");
                needsExit = true;
                out.println(iii + "}");
            }

    boolean isNullAllowed(CFunc cfunc) {
        String[] checks = mChecker.getChecks(cfunc.getName());
        int index = 1;
        if (checks != null) {
            while (index < checks.length) {
                if (checks[index].equals("return")) {
                    index += 2;
                } else if (checks[index].startsWith("check")) {
                    index += 3;
                } else if (checks[index].equals("ifcheck")) {
                    index += 5;
                } else if (checks[index].equals("unsupported")) {
                    index += 1;
                } else if (checks[index].equals("nullAllowed")) {
                    return true;
                } else {
                    System.out.println("Error: unknown keyword \"" +
                                       checks[index] + "\"");
                    System.exit(0);
                }
            }
        }
        return false;
    }

    String getErrorReturnValue(CFunc cfunc) {
        CType returnType = cfunc.getType();
        boolean isVoid = returnType.isVoid();
        if (isVoid) {
            return null;
        }

        String[] checks = mChecker.getChecks(cfunc.getName());

        int index = 1;
        if (checks != null) {
            while (index < checks.length) {
                if (checks[index].equals("return")) {
                    return checks[index + 1];
                } else if (checks[index].startsWith("check")) {
                    index += 3;
                } else if (checks[index].equals("ifcheck")) {
                    index += 5;
                } else if (checks[index].equals("unsupported")) {
                    index += 1;
                } else if (checks[index].equals("nullAllowed")) {
                    index += 1;
                } else {
                    System.out.println("Error: unknown keyword \"" +
                                       checks[index] + "\"");
                    System.exit(0);
                }
            }
        }

        return null;
    }

    boolean isUnsupportedFunc(CFunc cfunc) {
        String[] checks = mChecker.getChecks(cfunc.getName());
        int index = 1;
        if (checks != null) {
            while (index < checks.length) {
                if (checks[index].equals("unsupported")) {
                    return true;
                } else if (checks[index].equals("return")) {
                    index += 2;
                } else if (checks[index].startsWith("check")) {
                    index += 3;
                } else if (checks[index].equals("ifcheck")) {
                    index += 5;
                } else if (checks[index].equals("nullAllowed")) {
                    index += 1;
                } else {
                    System.out.println("Error: unknown keyword \"" +
                                       checks[index] + "\"");
                    System.exit(0);
                }
            }
        }
        return false;
    }

    void emitNativeBoundsChecks(CFunc cfunc, String cname, PrintStream out,
            boolean isBuffer, boolean emitExceptionCheck, String offset, String remaining, String iii) {

                String[] checks = mChecker.getChecks(cfunc.getName());

                boolean lastWasIfcheck = false;

                int index = 1;
                if (checks != null) {
                    while (index < checks.length) {
                        if (checks[index].startsWith("check")) {
                            if (lastWasIfcheck) {
                                printIfcheckPostamble(out, isBuffer, emitExceptionCheck,
                                                      offset, remaining, iii);
                            }
                            lastWasIfcheck = false;
                            if (cname != null && !cname.equals(checks[index + 1])) {
                                index += 3;
                                continue;
                            }
                            out.println(iii + "if (" + remaining + " < " +
                                        checks[index + 2] +
                                        ") {");
                            if (emitExceptionCheck) {
                                out.println(iii + indent + "_exception = 1;");
                            }
                    String exceptionClassName = "IAEClass";
                    // If the "check" keyword was of the form
                    // "check_<class name>", use the class name in the
                    // exception to be thrown
                    int underscore = checks[index].indexOf('_');
                    if (underscore >= 0) {
                    exceptionClassName = checks[index].substring(underscore + 1) + "Class";
                    }
                            out.println(iii + indent +
                                        (mUseCPlusPlus ? "_env" : "(*_env)") +
                                        "->ThrowNew(" +
                                        (mUseCPlusPlus ? "" : "_env, ") +
                        exceptionClassName + ", " +
                                        "\"" +
                                        (isBuffer ?
                                         "remaining()" : "length - " + offset) +
                                        " < " + checks[index + 2] +
                                        "\");");

                            out.println(iii + indent + "goto exit;");
                            needsExit = true;
                            out.println(iii + "}");

                            index += 3;
                        } else if (checks[index].equals("ifcheck")) {
                            String[] matches = checks[index + 4].split(",");

                            if (!lastWasIfcheck) {
                                out.println(iii + "int _needed;");
                                out.println(iii +
                                            "switch (" +
                                            checks[index + 3] +
                                            ") {");
                            }

                            for (int i = 0; i < matches.length; i++) {
                                out.println("#if defined(" + matches[i] + ")");
                                out.println(iii +
                                            "    case " +
                                            matches[i] +
                                            ":");
                                out.println("#endif // defined(" + matches[i] + ")");
                            }
                            out.println(iii +
                                        "        _needed = " +
                                        checks[index + 2] +
                                        ";");
                            out.println(iii +
                                        "        break;");

                            lastWasIfcheck = true;
                            index += 5;
                        } else if (checks[index].equals("return")) {
                            // ignore
                            index += 2;
                        } else if (checks[index].equals("unsupported")) {
                            // ignore
                            index += 1;
                        } else if (checks[index].equals("nullAllowed")) {
                            // ignore
                            index += 1;
                        } else {
                            System.out.println("Error: unknown keyword \"" +
                                               checks[index] + "\"");
                            System.exit(0);
                        }
                    }
                }

                if (lastWasIfcheck) {
                    printIfcheckPostamble(out, isBuffer, emitExceptionCheck, iii);
                }
            }

    boolean hasNonConstArg(JFunc jfunc, CFunc cfunc, List<Integer> nonPrimitiveArgs) {
        if (nonPrimitiveArgs.size() > 0) {
            for (int i = nonPrimitiveArgs.size() - 1; i >= 0; i--) {
                int idx = nonPrimitiveArgs.get(i).intValue();
                int cIndex = jfunc.getArgCIndex(idx);
                if (jfunc.getArgType(idx).isArray()) {
                    if (!cfunc.getArgType(cIndex).isConst()) {
                        return true;
                    }
                } else if (jfunc.getArgType(idx).isBuffer()) {
                    if (!cfunc.getArgType(cIndex).isConst()) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
     * Emit a function in several variants:
     *
     * if nativeDecl: public native <returntype> func(args);
     *
     * if !nativeDecl:
     *   if interfaceDecl:  public <returntype> func(args);
     *   if !interfaceDecl: public <returntype> func(args) { body }
     */
    void emitFunction(JFunc jfunc, PrintStream out, boolean nativeDecl, boolean interfaceDecl) {
        boolean isPointerFunc = isPointerFunc(jfunc);

        if (!nativeDecl && !interfaceDecl && !isPointerFunc) {
            // If it's not a pointer function, we've already emitted it
            // with nativeDecl == true
            return;
        }

        String maybeStatic = mUseStaticMethods ? "static " : "";

        if (isPointerFunc) {
            out.println(indent +
                        (nativeDecl ? "private " + maybeStatic +"native " :
                         (interfaceDecl ? "" : "public ") + maybeStatic) +
                        jfunc.getType() + " " +
                        jfunc.getName() +
                        (nativeDecl ? "Bounds" : "") +
                        "(");
        } else {
            out.println(indent +
                        (nativeDecl ? "public " + maybeStatic +"native " :
                         (interfaceDecl ? "" : "public ") + maybeStatic) +
                        jfunc.getType() + " " +
                        jfunc.getName() +
                        "(");
        }

        int numArgs = jfunc.getNumArgs();
        for (int i = 0; i < numArgs; i++) {
            String argName = jfunc.getArgName(i);
            JType argType = jfunc.getArgType(i);

            out.print(indent + indent + argType + " " + argName);
            if (i == numArgs - 1) {
                if (isPointerFunc && nativeDecl) {
                    out.println(",");
                    out.println(indent + indent + "int remaining");
                } else {
                    out.println();
                }
            } else {
                out.println(",");
            }
        }

        if (nativeDecl || interfaceDecl) {
            out.println(indent + ");");
        } else {
            out.println(indent + ") {");

            String iii = indent + indent;

            // emitBoundsChecks(jfunc, out, iii);
            emitFunctionCall(jfunc, out, iii, false);

            // Set the pointer after we call the native code, so that if
            // the native code throws an exception we don't modify the
            // pointer. We assume that the native code is written so that
            // if an exception is thrown, then the underlying glXXXPointer
            // function will not have been called.

            String fname = jfunc.getName();
            if (isPointerFunc) {
                // TODO - deal with VBO variants
                if (fname.equals("glColorPointer")) {
                    out.println(iii + "if ((size == 4) &&");
                    out.println(iii + "    ((type == GL_FLOAT) ||");
                    out.println(iii + "     (type == GL_UNSIGNED_BYTE) ||");
                    out.println(iii + "     (type == GL_FIXED)) &&");
                    out.println(iii + "    (stride >= 0)) {");
                    out.println(iii + indent + "_colorPointer = pointer;");
                    out.println(iii + "}");
                } else if (fname.equals("glNormalPointer")) {
                    out.println(iii + "if (((type == GL_FLOAT) ||");
                    out.println(iii + "     (type == GL_BYTE) ||");
                    out.println(iii + "     (type == GL_SHORT) ||");
                    out.println(iii + "     (type == GL_FIXED)) &&");
                    out.println(iii + "    (stride >= 0)) {");
                    out.println(iii + indent + "_normalPointer = pointer;");
                    out.println(iii + "}");
                } else if (fname.equals("glTexCoordPointer")) {
                    out.println(iii + "if (((size == 2) ||");
                    out.println(iii + "     (size == 3) ||");
                    out.println(iii + "     (size == 4)) &&");
                    out.println(iii + "    ((type == GL_FLOAT) ||");
                    out.println(iii + "     (type == GL_BYTE) ||");
                    out.println(iii + "     (type == GL_SHORT) ||");
                    out.println(iii + "     (type == GL_FIXED)) &&");
                    out.println(iii + "    (stride >= 0)) {");
                    out.println(iii + indent + "_texCoordPointer = pointer;");
                    out.println(iii + "}");
                } else if (fname.equals("glVertexPointer")) {
                    out.println(iii + "if (((size == 2) ||");
                    out.println(iii + "     (size == 3) ||");
                    out.println(iii + "     (size == 4)) &&");
                    out.println(iii + "    ((type == GL_FLOAT) ||");
                    out.println(iii + "     (type == GL_BYTE) ||");
                    out.println(iii + "     (type == GL_SHORT) ||");
                    out.println(iii + "     (type == GL_FIXED)) &&");
                    out.println(iii + "    (stride >= 0)) {");
                    out.println(iii + indent + "_vertexPointer = pointer;");
                    out.println(iii + "}");
                } else if (fname.equals("glPointSizePointerOES")) {
                    out.println(iii + "if (((type == GL_FLOAT) ||");
                    out.println(iii + "     (type == GL_FIXED)) &&");
                    out.println(iii + "    (stride >= 0)) {");
                    out.println(iii + indent + "_pointSizePointerOES = pointer;");
                    out.println(iii + "}");
                } else if (fname.equals("glMatrixIndexPointerOES")) {
                    out.println(iii + "if (((size == 2) ||");
                    out.println(iii + "     (size == 3) ||");
                    out.println(iii + "     (size == 4)) &&");
                    out.println(iii + "    ((type == GL_FLOAT) ||");
                    out.println(iii + "     (type == GL_BYTE) ||");
                    out.println(iii + "     (type == GL_SHORT) ||");
                    out.println(iii + "     (type == GL_FIXED)) &&");
                    out.println(iii + "    (stride >= 0)) {");
                    out.println(iii + indent + "_matrixIndexPointerOES = pointer;");
                    out.println(iii + "}");
                } else if (fname.equals("glWeightPointer")) {
                    out.println(iii + "if (((size == 2) ||");
                    out.println(iii + "     (size == 3) ||");
                    out.println(iii + "     (size == 4)) &&");
                    out.println(iii + "    ((type == GL_FLOAT) ||");
                    out.println(iii + "     (type == GL_BYTE) ||");
                    out.println(iii + "     (type == GL_SHORT) ||");
                    out.println(iii + "     (type == GL_FIXED)) &&");
                    out.println(iii + "    (stride >= 0)) {");
                    out.println(iii + indent + "_weightPointerOES = pointer;");
                    out.println(iii + "}");
                }
            }

            boolean isVoid = jfunc.getType().isVoid();

            if (!isVoid) {
                out.println(indent + indent + "return _returnValue;");
            }
            out.println(indent + "}");
        }
        out.println();
    }

    public void addNativeRegistration(String s) {
        nativeRegistrations.add(s);
    }

    public void emitNativeRegistration(String registrationFunctionName,
            PrintStream cStream) {
        cStream.println("static const char *classPathName = \"" +
                        mClassPathName +
                        "\";");
        cStream.println();

        cStream.println("static JNINativeMethod methods[] = {");

        cStream.println("{\"_nativeClassInit\", \"()V\", (void*)nativeClassInit },");

        Iterator<String> i = nativeRegistrations.iterator();
        while (i.hasNext()) {
            cStream.println(i.next());
        }

        cStream.println("};");
        cStream.println();


        cStream.println("int " + registrationFunctionName + "(JNIEnv *_env)");
        cStream.println("{");
        cStream.println(indent +
                        "int err;");

        cStream.println(indent +
                        "err = android::AndroidRuntime::registerNativeMethods(_env, classPathName, methods, NELEM(methods));");

        cStream.println(indent + "return err;");
        cStream.println("}");
    }

    public JniCodeEmitter() {
        super();
    }

    String getJniType(JType jType) {
        if (jType.isVoid()) {
            return "void";
        }

        String baseType = jType.getBaseType();
        if (jType.isPrimitive()) {
            if (baseType.equals("String")) {
                return "jstring";
            } else {
                return "j" + baseType;
            }
        } else if (jType.isArray()) {
            return "j" + baseType + "Array";
        } else {
            return "jobject";
        }
    }

    String getJniMangledName(String name) {
        name = name.replaceAll("_", "_1");
        name = name.replaceAll(";", "_2");
        name = name.replaceAll("\\[", "_3");
        return name;
    }

    public void emitJniCode(JFunc jfunc, PrintStream out) {
        CFunc cfunc = jfunc.getCFunc();

        // Emit comment identifying original C function
        //
        // Example:
        //
        // /* void glClipPlanef ( GLenum plane, const GLfloat *equation ) */
        //
        out.println("/* " + cfunc.getOriginal() + " */");

        // Emit JNI signature (name)
        //
        // Example:
        //
        // void
        // android_glClipPlanef__I_3FI
        //

        String outName = "android_" + jfunc.getName();
        boolean isPointerFunc = isPointerFunc(jfunc);
        boolean isVBOPointerFunc = (outName.endsWith("Pointer") ||
                outName.endsWith("PointerOES") ||
            outName.endsWith("DrawElements")) &&
            !jfunc.getCFunc().hasPointerArg();
        if (isPointerFunc) {
            outName += "Bounds";
        }

        out.print("static ");
        out.println(getJniType(jfunc.getType()));
        out.print(outName);

        String rsignature = getJniName(jfunc.getType());

        String signature = "";
        int numArgs = jfunc.getNumArgs();
        for (int i = 0; i < numArgs; i++) {
            JType argType = jfunc.getArgType(i);
            signature += getJniName(argType);
        }
        if (isPointerFunc) {
            signature += "I";
        }

        // Append signature to function name
        String sig = getJniMangledName(signature).replace('.', '_').replace('/', '_');
        out.print("__" + sig);
        outName += "__" + sig;

        signature = signature.replace('.', '/');
        rsignature = rsignature.replace('.', '/');

        out.println();
        if (rsignature.length() == 0) {
            rsignature = "V";
        }

        String s = "{\"" +
            jfunc.getName() +
            (isPointerFunc ? "Bounds" : "") +
            "\", \"(" + signature +")" +
            rsignature +
            "\", (void *) " +
            outName +
            " },";
        nativeRegistrations.add(s);

        List<Integer> nonPrimitiveArgs = new ArrayList<Integer>();
        List<Integer> stringArgs = new ArrayList<Integer>();
        int numBufferArgs = 0;
        List<String> bufferArgNames = new ArrayList<String>();

        // Emit JNI signature (arguments)
        //
        // Example:
        //
        // (JNIEnv *_env, jobject this, jint plane, jfloatArray equation_ref, jint offset) {
        //
        out.print("  (JNIEnv *_env, jobject _this");
        for (int i = 0; i < numArgs; i++) {
            out.print(", ");
            JType argType = jfunc.getArgType(i);
            String suffix;
            if (!argType.isPrimitive()) {
                if (argType.isArray()) {
                    suffix = "_ref";
                } else {
                    suffix = "_buf";
                }
                nonPrimitiveArgs.add(new Integer(i));
                if (jfunc.getArgType(i).isBuffer()) {
                    int cIndex = jfunc.getArgCIndex(i);
                    String cname = cfunc.getArgName(cIndex);
                    bufferArgNames.add(cname);
                    numBufferArgs++;
                }
            } else {
                suffix = "";
            }
            if (argType.isString()) {
                stringArgs.add(new Integer(i));
            }

            out.print(getJniType(argType) + " " + jfunc.getArgName(i) + suffix);
        }
        if (isPointerFunc) {
            out.print(", jint remaining");
        }
        out.println(") {");

        int numArrays = 0;
        int numBuffers = 0;
        int numStrings = 0;
        for (int i = 0; i < nonPrimitiveArgs.size(); i++) {
            int idx = nonPrimitiveArgs.get(i).intValue();
            JType argType = jfunc.getArgType(idx);
            if (argType.isArray()) {
                ++numArrays;
            }
            if (argType.isBuffer()) {
                ++numBuffers;
            }
            if (argType.isString()) {
                ++numStrings;
            }
        }

        // Emit method body

        // Emit local variable declarations for _exception and _returnValue
        //
        // Example:
        //
        // android::gl::ogles_context_t *ctx;
        //
        // jint _exception;
        // GLenum _returnValue;
        //
        CType returnType = cfunc.getType();
        boolean isVoid = returnType.isVoid();

        boolean isUnsupported = isUnsupportedFunc(cfunc);
        if (isUnsupported) {
            out.println(indent +
                        "_env->ThrowNew(UOEClass,");
            out.println(indent +
                        "    \"" + cfunc.getName() + "\");");
            if (!isVoid) {
                String retval = getErrorReturnValue(cfunc);
                out.println(indent + "return " + retval + ";");
            }
            out.println("}");
            out.println();
            return;
        }

        if (mUseContextPointer) {
            out.println(indent +
                "android::gl::ogles_context_t *ctx = getContext(_env, _this);");
        }

        boolean initializeReturnValue = stringArgs.size() > 0;

        boolean emitExceptionCheck = (numArrays > 0 || numBuffers > 0 || numStrings > 0) &&
            hasNonConstArg(jfunc, cfunc, nonPrimitiveArgs);
        // mChecker.getChecks(cfunc.getName()) != null

        // Emit an _exeption variable if there will be error checks
        if (emitExceptionCheck) {
            out.println(indent + "jint _exception = 0;");
        }

        // Emit a single _array or multiple _XXXArray variables
        if (numBufferArgs == 1) {
                out.println(indent + "jarray _array = (jarray) 0;");
        } else {
            for (int i = 0; i < numBufferArgs; i++) {
                out.println(indent + "jarray _" + bufferArgNames.get(i) +
                            "Array = (jarray) 0;");
            }
        }
        if (!isVoid) {
            String retval = getErrorReturnValue(cfunc);
            if (retval != null) {
                out.println(indent + returnType.getDeclaration() +
                            " _returnValue = " + retval + ";");
            } else if (initializeReturnValue) {
                out.println(indent + returnType.getDeclaration() +
                " _returnValue = 0;");
            } else {
                out.println(indent + returnType.getDeclaration() +
                            " _returnValue;");
            }
        }

        // Emit local variable declarations for pointer arguments
        //
        // Example:
        //
        // GLfixed *eqn_base;
        // GLfixed *eqn;
        //
        String offset = "offset";
        String remaining = "_remaining";
        if (nonPrimitiveArgs.size() > 0) {
            for (int i = 0; i < nonPrimitiveArgs.size(); i++) {
                int idx = nonPrimitiveArgs.get(i).intValue();
                int cIndex = jfunc.getArgCIndex(idx);
                String cname = cfunc.getArgName(cIndex);

                CType type = cfunc.getArgType(jfunc.getArgCIndex(idx));
                String decl = type.getDeclaration();
                if (jfunc.getArgType(idx).isArray()) {
                    out.println(indent +
                                decl +
                                (decl.endsWith("*") ? "" : " ") +
                                jfunc.getArgName(idx) +
                                "_base = (" + decl + ") 0;");
                }
                remaining = ((numArrays + numBuffers) <= 1) ? "_remaining" :
                    "_" + cname + "Remaining";
                out.println(indent +
                            "jint " + remaining + ";");
                out.println(indent +
                            decl +
                            (decl.endsWith("*") ? "" : " ") +
                            jfunc.getArgName(idx) +
                            " = (" + decl + ") 0;");
            }

            out.println();
        }

        // Emit local variable declaration for strings
        if (stringArgs.size() > 0) {
            for (int i = 0; i < stringArgs.size(); i++) {
                int idx = stringArgs.get(i).intValue();
                int cIndex = jfunc.getArgCIndex(idx);
                String cname = cfunc.getArgName(cIndex);

                out.println(indent + "const char* _native" + cname + " = 0;");
            }

            out.println();
        }

        // Null pointer checks and GetStringUTFChars
        if (stringArgs.size() > 0) {
            for (int i = 0; i < stringArgs.size(); i++) {
                int idx = stringArgs.get(i).intValue();
                int cIndex = jfunc.getArgCIndex(idx);
                String cname = cfunc.getArgName(cIndex);

                CType type = cfunc.getArgType(jfunc.getArgCIndex(idx));
                String decl = type.getDeclaration();
                out.println(indent + "if (!" + cname + ") {");
                out.println(indent + "    _env->ThrowNew(IAEClass, \"" + cname + " == null\");");
                out.println(indent + "    goto exit;");
                needsExit = true;
                out.println(indent + "}");

                out.println(indent + "_native" + cname + " = _env->GetStringUTFChars(" + cname + ", 0);");
            }

            out.println();
        }

        // Emit 'GetPrimitiveArrayCritical' for arrays
        // Emit 'GetPointer' calls for Buffer pointers
        int bufArgIdx = 0;
        if (nonPrimitiveArgs.size() > 0) {
            for (int i = 0; i < nonPrimitiveArgs.size(); i++) {
                int idx = nonPrimitiveArgs.get(i).intValue();
                int cIndex = jfunc.getArgCIndex(idx);

                String cname = cfunc.getArgName(cIndex);
                offset = numArrays <= 1 ? "offset" :
                    cname + "Offset";
                remaining = ((numArrays + numBuffers) <= 1) ? "_remaining" :
                    "_" + cname + "Remaining";

                if (jfunc.getArgType(idx).isArray()) {
                    out.println(indent +
                                "if (!" +
                                cname +
                                "_ref) {");
                    if (emitExceptionCheck) {
                        out.println(indent + indent + "_exception = 1;");
                    }
                    out.println(indent + "    " +
                                (mUseCPlusPlus ? "_env" : "(*_env)") +
                                "->ThrowNew(" +
                                (mUseCPlusPlus ? "" : "_env, ") +
                                "IAEClass, " +
                                "\"" + cname +
                                " == null\");");
                    out.println(indent + "    goto exit;");
                    needsExit = true;
                    out.println(indent + "}");

                    out.println(indent + "if (" + offset + " < 0) {");
                    if (emitExceptionCheck) {
                        out.println(indent + indent + "_exception = 1;");
                    }
                    out.println(indent + "    " +
                                (mUseCPlusPlus ? "_env" : "(*_env)") +
                                "->ThrowNew(" +
                                (mUseCPlusPlus ? "" : "_env, ") +
                                "IAEClass, " +
                                "\"" + offset + " < 0\");");
                    out.println(indent + "    goto exit;");
                    needsExit = true;
                    out.println(indent + "}");

                    out.println(indent + remaining + " = " +
                                    (mUseCPlusPlus ? "_env" : "(*_env)") +
                                    "->GetArrayLength(" +
                                    (mUseCPlusPlus ? "" : "_env, ") +
                                    cname + "_ref) - " + offset + ";");

                    emitNativeBoundsChecks(cfunc, cname, out, false,
                                           emitExceptionCheck,
                                           offset, remaining, "    ");

                    out.println(indent +
                                cname +
                                "_base = (" +
                                cfunc.getArgType(cIndex).getDeclaration() +
                                ")");
                    out.println(indent + "    " +
                                (mUseCPlusPlus ? "_env" : "(*_env)") +
                                "->GetPrimitiveArrayCritical(" +
                                (mUseCPlusPlus ? "" : "_env, ") +
                                jfunc.getArgName(idx) +
                                "_ref, (jboolean *)0);");
                    out.println(indent +
                                cname + " = " + cname + "_base + " + offset +
                                ";");
                    out.println();
                } else {
                    String array = numBufferArgs <= 1 ? "_array" :
                        "_" + bufferArgNames.get(bufArgIdx++) + "Array";

                    boolean nullAllowed = isNullAllowed(cfunc) || isPointerFunc;
                    if (nullAllowed) {
                        out.println(indent + "if (" + cname + "_buf) {");
                        out.print(indent);
                    }

                    if (isPointerFunc) {
                        out.println(indent +
                                cname +
                                " = (" +
                                cfunc.getArgType(cIndex).getDeclaration() +
                                ") getDirectBufferPointer(_env, " +
                                cname + "_buf);");
                        String iii = "    ";
                        out.println(iii + indent + "if ( ! " + cname + " ) {");
                        out.println(iii + iii + indent + "return;");
                        out.println(iii + indent + "}");
                    } else {
                        out.println(indent +
                                    cname +
                                    " = (" +
                                    cfunc.getArgType(cIndex).getDeclaration() +
                                    ")getPointer(_env, " +
                                    cname +
                                    "_buf, &" + array + ", &" + remaining +
                                    ");");
                    }

                    emitNativeBoundsChecks(cfunc, cname, out, true,
                                           emitExceptionCheck,
                                           offset, remaining, nullAllowed ? "        " : "    ");

                    if (nullAllowed) {
                        out.println(indent + "}");
                    }
                }
            }
        }

        if (!isVoid) {
            out.print(indent + "_returnValue = ");
        } else {
            out.print(indent);
        }
        String name = cfunc.getName();

        if (mUseContextPointer) {
            name = name.substring(2, name.length()); // Strip off 'gl' prefix
            name = name.substring(0, 1).toLowerCase() +
                name.substring(1, name.length());
            out.print("ctx->procs.");
        }

        out.print(name + (isPointerFunc ? "Bounds" : "") + "(");

        numArgs = cfunc.getNumArgs();
        if (numArgs == 0) {
            if (mUseContextPointer) {
                out.println("ctx);");
            } else {
                out.println(");");
            }
        } else {
            if (mUseContextPointer) {
                out.println("ctx,");
            } else {
                out.println();
            }
            for (int i = 0; i < numArgs; i++) {
                String typecast;
                if (i == numArgs - 1 && isVBOPointerFunc) {
                    typecast = "const GLvoid *";
                } else {
                    typecast = cfunc.getArgType(i).getDeclaration();
                }
                out.print(indent + indent +
                          "(" +
                          typecast +
                          ")");
                if (cfunc.getArgType(i).isConstCharPointer()) {
                    out.print("_native");
                }
                out.print(cfunc.getArgName(i));

                if (i == numArgs - 1) {
                    if (isPointerFunc) {
                        out.println(",");
                        out.println(indent + indent + "(GLsizei)remaining");
                    } else {
                        out.println();
                    }
                } else {
                    out.println(",");
                }
            }
            out.println(indent + ");");
        }

        if (needsExit) {
            out.println();
            out.println("exit:");
            needsExit = false;
        }

        bufArgIdx = 0;
        if (nonPrimitiveArgs.size() > 0) {
            for (int i = nonPrimitiveArgs.size() - 1; i >= 0; i--) {
                int idx = nonPrimitiveArgs.get(i).intValue();

                int cIndex = jfunc.getArgCIndex(idx);
                if (jfunc.getArgType(idx).isArray()) {

                    // If the argument is 'const', GL will not write to it.
                    // In this case, we can use the 'JNI_ABORT' flag to avoid
                    // the need to write back to the Java array
                    out.println(indent +
                                "if (" + jfunc.getArgName(idx) + "_base) {");
                    out.println(indent + indent +
                                (mUseCPlusPlus ? "_env" : "(*_env)") +
                                "->ReleasePrimitiveArrayCritical(" +
                                (mUseCPlusPlus ? "" : "_env, ") +
                                jfunc.getArgName(idx) + "_ref, " +
                                cfunc.getArgName(cIndex) +
                                "_base,");
                    out.println(indent + indent + indent +
                                (cfunc.getArgType(cIndex).isConst() ?
                                 "JNI_ABORT" :
                                 "_exception ? JNI_ABORT: 0") +
                                ");");
                    out.println(indent + "}");
                } else if (jfunc.getArgType(idx).isBuffer()) {
                    if (! isPointerFunc) {
                        String array = numBufferArgs <= 1 ? "_array" :
                            "_" + bufferArgNames.get(bufArgIdx++) + "Array";
                        out.println(indent + "if (" + array + ") {");
                        out.println(indent + indent +
                                    "releasePointer(_env, " + array + ", " +
                                    cfunc.getArgName(cIndex) +
                                    ", " +
                                    (cfunc.getArgType(cIndex).isConst() ?
                                     "JNI_FALSE" : "_exception ? JNI_FALSE :" +
                                             " JNI_TRUE") +
                                    ");");
                        out.println(indent + "}");
                    }
                }
            }
        }

        // Emit local variable declaration for strings
        if (stringArgs.size() > 0) {
            for (int i = 0; i < stringArgs.size(); i++) {
                int idx = stringArgs.get(i).intValue();
                int cIndex = jfunc.getArgCIndex(idx);
                String cname = cfunc.getArgName(cIndex);

                out.println(indent + "if (_native" + cname + ") {");
                out.println(indent + "    _env->ReleaseStringUTFChars(" + cname + ", _native" + cname + ");");
                out.println(indent + "}");
            }

            out.println();
        }


        if (!isVoid) {
            out.println(indent + "return _returnValue;");
        }

        out.println("}");
        out.println();
    }

}