aboutsummaryrefslogtreecommitdiff
path: root/src/share/classes/sun/rmi/rmic/RMIGenerator.java
blob: 41e94ff361aa4f35030873d9aef43f3c76f3d2cf (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
/*
 * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

/*****************************************************************************/
/*                    Copyright (c) IBM Corporation 1998                     */
/*                                                                           */
/* (C) Copyright IBM Corp. 1998                                              */
/*                                                                           */
/*****************************************************************************/

package sun.rmi.rmic;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import sun.tools.java.Type;
import sun.tools.java.Identifier;
import sun.tools.java.ClassDefinition;
import sun.tools.java.ClassDeclaration;
import sun.tools.java.ClassNotFound;
import sun.tools.java.ClassFile;
import sun.tools.java.MemberDefinition;
import com.sun.corba.se.impl.util.Utility;

/**
 * A Generator object will generate the Java source code of the stub
 * and skeleton classes for an RMI remote implementation class, using
 * a particular stub protocol version.
 *
 * WARNING: The contents of this source file are not part of any
 * supported API.  Code that depends on them does so at its own risk:
 * they are subject to change or removal without notice.
 *
 * @author      Peter Jones,  Bryan Atsatt
 */
public class RMIGenerator implements RMIConstants, Generator {

    private static final Hashtable versionOptions = new Hashtable();
    static {
        versionOptions.put("-v1.1", new Integer(STUB_VERSION_1_1));
        versionOptions.put("-vcompat", new Integer(STUB_VERSION_FAT));
        versionOptions.put("-v1.2", new Integer(STUB_VERSION_1_2));
    }

    /**
     * Default constructor for Main to use.
     */
    public RMIGenerator() {
        version = STUB_VERSION_1_2;     // default is -v1.2 (see 4638155)
    }

    /**
     * Examine and consume command line arguments.
     * @param argv The command line arguments. Ignore null
     * and unknown arguments. Set each consumed argument to null.
     * @param error Report any errors using the main.error() methods.
     * @return true if no errors, false otherwise.
     */
    public boolean parseArgs(String argv[], Main main) {
        String explicitVersion = null;
        for (int i = 0; i < argv.length; i++) {
            if (argv[i] != null) {
                String arg = argv[i].toLowerCase();
                if (versionOptions.containsKey(arg)) {
                    if (explicitVersion != null &&
                        !explicitVersion.equals(arg))
                    {
                        main.error("rmic.cannot.use.both",
                                   explicitVersion, arg);
                        return false;
                    }
                    explicitVersion = arg;
                    version = ((Integer) versionOptions.get(arg)).intValue();
                    argv[i] = null;
                }
            }
        }
        return true;
    }

    /**
     * Generate the source files for the stub and/or skeleton classes
     * needed by RMI for the given remote implementation class.
     *
     * @param env       compiler environment
     * @param cdef      definition of remote implementation class
     *                  to generate stubs and/or skeletons for
     * @param destDir   directory for the root of the package hierarchy
     *                  for generated files
     */
    public void generate(BatchEnvironment env, ClassDefinition cdef, File destDir) {
        RemoteClass remoteClass = RemoteClass.forClass(env, cdef);
        if (remoteClass == null)        // exit if an error occurred
            return;

        RMIGenerator gen;
        try {
            gen = new RMIGenerator(env, cdef, destDir, remoteClass, version);
        } catch (ClassNotFound e) {
            env.error(0, "rmic.class.not.found", e.name);
            return;
        }
        gen.generate();
    }

    private void generate() {
        env.addGeneratedFile(stubFile);

        try {
            IndentingWriter out = new IndentingWriter(
                new OutputStreamWriter(new FileOutputStream(stubFile)));
            writeStub(out);
            out.close();
            if (env.verbose()) {
                env.output(Main.getText("rmic.wrote", stubFile.getPath()));
            }
            env.parseFile(new ClassFile(stubFile));
        } catch (IOException e) {
            env.error(0, "cant.write", stubFile.toString());
            return;
        }

        if (version == STUB_VERSION_1_1 ||
            version == STUB_VERSION_FAT)
        {
            env.addGeneratedFile(skeletonFile);

            try {
                IndentingWriter out = new IndentingWriter(
                    new OutputStreamWriter(
                        new FileOutputStream(skeletonFile)));
                writeSkeleton(out);
                out.close();
                if (env.verbose()) {
                    env.output(Main.getText("rmic.wrote",
                        skeletonFile.getPath()));
                }
                env.parseFile(new ClassFile(skeletonFile));
            } catch (IOException e) {
                env.error(0, "cant.write", stubFile.toString());
                return;
            }
        } else {
            /*
             * For bugid 4135136: if skeleton files are not being generated
             * for this compilation run, delete old skeleton source or class
             * files for this remote implementation class that were
             * (presumably) left over from previous runs, to avoid user
             * confusion from extraneous or inconsistent generated files.
             */

            File outputDir = Util.getOutputDirectoryFor(remoteClassName,destDir,env);
            File skeletonClassFile = new File(outputDir,skeletonClassName.getName().toString() + ".class");

            skeletonFile.delete();      // ignore failures (no big deal)
            skeletonClassFile.delete();
        }
    }

    /**
     * Return the File object that should be used as the source file
     * for the given Java class, using the supplied destination
     * directory for the top of the package hierarchy.
     */
    protected static File sourceFileForClass(Identifier className,
                                             Identifier outputClassName,
                                             File destDir,
                                             BatchEnvironment env)
    {
        File packageDir = Util.getOutputDirectoryFor(className,destDir,env);
        String outputName = Names.mangleClass(outputClassName).getName().toString();

        // Is there any existing _Tie equivalent leftover from a
        // previous invocation of rmic -iiop? Only do this once per
        // class by looking for skeleton generation...

        if (outputName.endsWith("_Skel")) {
            String classNameStr = className.getName().toString();
            File temp = new File(packageDir, Utility.tieName(classNameStr) + ".class");
            if (temp.exists()) {

                // Found a tie. Is IIOP generation also being done?

                if (!env.getMain().iiopGeneration) {

                    // No, so write a warning...

                    env.error(0,"warn.rmic.tie.found",
                              classNameStr,
                              temp.getAbsolutePath());
                }
            }
        }

        String outputFileName = outputName + ".java";
        return new File(packageDir, outputFileName);
    }


    /** rmic environment for this object */
    private BatchEnvironment env;

    /** the remote class that this instance is generating code for */
    private RemoteClass remoteClass;

    /** version of the stub protocol to use in code generation */
    private int version;

    /** remote methods for remote class, indexed by operation number */
    private RemoteClass.Method[] remoteMethods;

    /**
     * Names for the remote class and the stub and skeleton classes
     * to be generated for it.
     */
    private Identifier remoteClassName;
    private Identifier stubClassName;
    private Identifier skeletonClassName;

    private ClassDefinition cdef;
    private File destDir;
    private File stubFile;
    private File skeletonFile;

    /**
     * Names to use for the java.lang.reflect.Method static fields
     * corresponding to each remote method.
     */
    private String[] methodFieldNames;

    /** cached definition for certain exception classes in this environment */
    private ClassDefinition defException;
    private ClassDefinition defRemoteException;
    private ClassDefinition defRuntimeException;

    /**
     * Create a new stub/skeleton Generator object for the given
     * remote implementation class to generate code according to
     * the given stub protocol version.
     */
    private RMIGenerator(BatchEnvironment env, ClassDefinition cdef,
                           File destDir, RemoteClass remoteClass, int version)
        throws ClassNotFound
    {
        this.destDir     = destDir;
        this.cdef        = cdef;
        this.env         = env;
        this.remoteClass = remoteClass;
        this.version     = version;

        remoteMethods = remoteClass.getRemoteMethods();

        remoteClassName = remoteClass.getName();
        stubClassName = Names.stubFor(remoteClassName);
        skeletonClassName = Names.skeletonFor(remoteClassName);

        methodFieldNames = nameMethodFields(remoteMethods);

        stubFile = sourceFileForClass(remoteClassName,stubClassName, destDir , env);
        skeletonFile = sourceFileForClass(remoteClassName,skeletonClassName, destDir, env);

        /*
         * Initialize cached definitions for exception classes used
         * in the generation process.
         */
        defException =
            env.getClassDeclaration(idJavaLangException).
                getClassDefinition(env);
        defRemoteException =
            env.getClassDeclaration(idRemoteException).
                getClassDefinition(env);
        defRuntimeException =
            env.getClassDeclaration(idJavaLangRuntimeException).
                getClassDefinition(env);
    }

    /**
     * Write the stub for the remote class to a stream.
     */
    private void writeStub(IndentingWriter p) throws IOException {

        /*
         * Write boiler plate comment.
         */
        p.pln("// Stub class generated by rmic, do not edit.");
        p.pln("// Contents subject to change without notice.");
        p.pln();

        /*
         * If remote implementation class was in a particular package,
         * declare the stub class to be in the same package.
         */
        if (remoteClassName.isQualified()) {
            p.pln("package " + remoteClassName.getQualifier() + ";");
            p.pln();
        }

        /*
         * Declare the stub class; implement all remote interfaces.
         */
        p.plnI("public final class " +
            Names.mangleClass(stubClassName.getName()));
        p.pln("extends " + idRemoteStub);
        ClassDefinition[] remoteInterfaces = remoteClass.getRemoteInterfaces();
        if (remoteInterfaces.length > 0) {
            p.p("implements ");
            for (int i = 0; i < remoteInterfaces.length; i++) {
                if (i > 0)
                    p.p(", ");
                p.p(remoteInterfaces[i].getName().toString());
            }
            p.pln();
        }
        p.pOlnI("{");

        if (version == STUB_VERSION_1_1 ||
            version == STUB_VERSION_FAT)
        {
            writeOperationsArray(p);
            p.pln();
            writeInterfaceHash(p);
            p.pln();
        }

        if (version == STUB_VERSION_FAT ||
            version == STUB_VERSION_1_2)
        {
            p.pln("private static final long serialVersionUID = " +
                STUB_SERIAL_VERSION_UID + ";");
            p.pln();

            /*
             * We only need to declare and initialize the static fields of
             * Method objects for each remote method if there are any remote
             * methods; otherwise, skip this code entirely, to avoid generating
             * a try/catch block for a checked exception that cannot occur
             * (see bugid 4125181).
             */
            if (methodFieldNames.length > 0) {
                if (version == STUB_VERSION_FAT) {
                    p.pln("private static boolean useNewInvoke;");
                }
                writeMethodFieldDeclarations(p);
                p.pln();

                /*
                 * Initialize java.lang.reflect.Method fields for each remote
                 * method in a static initializer.
                 */
                p.plnI("static {");
                p.plnI("try {");
                if (version == STUB_VERSION_FAT) {
                    /*
                     * Fat stubs must determine whether the API required for
                     * the JDK 1.2 stub protocol is supported in the current
                     * runtime, so that it can use it if supported.  This is
                     * determined by using the Reflection API to test if the
                     * new invoke method on RemoteRef exists, and setting the
                     * static boolean "useNewInvoke" to true if it does, or
                     * to false if a NoSuchMethodException is thrown.
                     */
                    p.plnI(idRemoteRef + ".class.getMethod(\"invoke\",");
                    p.plnI("new java.lang.Class[] {");
                    p.pln(idRemote + ".class,");
                    p.pln("java.lang.reflect.Method.class,");
                    p.pln("java.lang.Object[].class,");
                    p.pln("long.class");
                    p.pOln("});");
                    p.pO();
                    p.pln("useNewInvoke = true;");
                }
                writeMethodFieldInitializers(p);
                p.pOlnI("} catch (java.lang.NoSuchMethodException e) {");
                if (version == STUB_VERSION_FAT) {
                    p.pln("useNewInvoke = false;");
                } else {
                    /*
                     * REMIND: By throwing an Error here, the application will
                     * get the NoSuchMethodError directly when the stub class
                     * is initialized.  If we throw a RuntimeException
                     * instead, the application would get an
                     * ExceptionInInitializerError.  Would that be more
                     * appropriate, and if so, which RuntimeException should
                     * be thrown?
                     */
                    p.plnI("throw new java.lang.NoSuchMethodError(");
                    p.pln("\"stub class initialization failed\");");
                    p.pO();
                }
                p.pOln("}");            // end try/catch block
                p.pOln("}");            // end static initializer
                p.pln();
            }
        }

        writeStubConstructors(p);
        p.pln();

        /*
         * Write each stub method.
         */
        if (remoteMethods.length > 0) {
            p.pln("// methods from remote interfaces");
            for (int i = 0; i < remoteMethods.length; ++i) {
                p.pln();
                writeStubMethod(p, i);
            }
        }

        p.pOln("}");                    // end stub class
    }

    /**
     * Write the constructors for the stub class.
     */
    private void writeStubConstructors(IndentingWriter p)
        throws IOException
    {
        p.pln("// constructors");

        /*
         * Only stubs compatible with the JDK 1.1 stub protocol need
         * a no-arg constructor; later versions use reflection to find
         * the constructor that directly takes a RemoteRef argument.
         */
        if (version == STUB_VERSION_1_1 ||
            version == STUB_VERSION_FAT)
        {
            p.plnI("public " + Names.mangleClass(stubClassName.getName()) +
                "() {");
            p.pln("super();");
            p.pOln("}");
        }

        p.plnI("public " + Names.mangleClass(stubClassName.getName()) +
            "(" + idRemoteRef + " ref) {");
        p.pln("super(ref);");
        p.pOln("}");
    }

    /**
     * Write the stub method for the remote method with the given "opnum".
     */
    private void writeStubMethod(IndentingWriter p, int opnum)
        throws IOException
    {
        RemoteClass.Method method = remoteMethods[opnum];
        Identifier methodName = method.getName();
        Type methodType = method.getType();
        Type paramTypes[] = methodType.getArgumentTypes();
        String paramNames[] = nameParameters(paramTypes);
        Type returnType = methodType.getReturnType();
        ClassDeclaration[] exceptions = method.getExceptions();

        /*
         * Declare stub method; throw exceptions declared in remote
         * interface(s).
         */
        p.pln("// implementation of " +
            methodType.typeString(methodName.toString(), true, false));
        p.p("public " + returnType + " " + methodName + "(");
        for (int i = 0; i < paramTypes.length; i++) {
            if (i > 0)
                p.p(", ");
            p.p(paramTypes[i] + " " + paramNames[i]);
        }
        p.plnI(")");
        if (exceptions.length > 0) {
            p.p("throws ");
            for (int i = 0; i < exceptions.length; i++) {
                if (i > 0)
                    p.p(", ");
                p.p(exceptions[i].getName().toString());
            }
            p.pln();
        }
        p.pOlnI("{");

        /*
         * The RemoteRef.invoke methods throw Exception, but unless this
         * stub method throws Exception as well, we must catch Exceptions
         * thrown from the invocation.  So we must catch Exception and
         * rethrow something we can throw: UnexpectedException, which is a
         * subclass of RemoteException.  But for any subclasses of Exception
         * that we can throw, like RemoteException, RuntimeException, and
         * any of the exceptions declared by this stub method, we want them
         * to pass through unharmed, so first we must catch any such
         * exceptions and rethrow it directly.
         *
         * We have to be careful generating the rethrowing catch blocks
         * here, because javac will flag an error if there are any
         * unreachable catch blocks, i.e. if the catch of an exception class
         * follows a previous catch of it or of one of its superclasses.
         * The following method invocation takes care of these details.
         */
        Vector catchList = computeUniqueCatchList(exceptions);

        /*
         * If we need to catch any particular exceptions (i.e. this method
         * does not declare java.lang.Exception), put the entire stub
         * method in a try block.
         */
        if (catchList.size() > 0) {
            p.plnI("try {");
        }

        if (version == STUB_VERSION_FAT) {
            p.plnI("if (useNewInvoke) {");
        }
        if (version == STUB_VERSION_FAT ||
            version == STUB_VERSION_1_2)
        {
            if (!returnType.isType(TC_VOID)) {
                p.p("Object $result = ");               // REMIND: why $?
            }
            p.p("ref.invoke(this, " + methodFieldNames[opnum] + ", ");
            if (paramTypes.length > 0) {
                p.p("new java.lang.Object[] {");
                for (int i = 0; i < paramTypes.length; i++) {
                    if (i > 0)
                        p.p(", ");
                    p.p(wrapArgumentCode(paramTypes[i], paramNames[i]));
                }
                p.p("}");
            } else {
                p.p("null");
            }
            p.pln(", " + method.getMethodHash() + "L);");
            if (!returnType.isType(TC_VOID)) {
                p.pln("return " +
                    unwrapArgumentCode(returnType, "$result") + ";");
            }
        }
        if (version == STUB_VERSION_FAT) {
            p.pOlnI("} else {");
        }
        if (version == STUB_VERSION_1_1 ||
            version == STUB_VERSION_FAT)
        {
            p.pln(idRemoteCall + " call = ref.newCall((" + idRemoteObject +
                ") this, operations, " + opnum + ", interfaceHash);");

            if (paramTypes.length > 0) {
                p.plnI("try {");
                p.pln("java.io.ObjectOutput out = call.getOutputStream();");
                writeMarshalArguments(p, "out", paramTypes, paramNames);
                p.pOlnI("} catch (java.io.IOException e) {");
                p.pln("throw new " + idMarshalException +
                    "(\"error marshalling arguments\", e);");
                p.pOln("}");
            }

            p.pln("ref.invoke(call);");

            if (returnType.isType(TC_VOID)) {
                p.pln("ref.done(call);");
            } else {
                p.pln(returnType + " $result;");        // REMIND: why $?
                p.plnI("try {");
                p.pln("java.io.ObjectInput in = call.getInputStream();");
                boolean objectRead =
                    writeUnmarshalArgument(p, "in", returnType, "$result");
                p.pln(";");
                p.pOlnI("} catch (java.io.IOException e) {");
                p.pln("throw new " + idUnmarshalException +
                    "(\"error unmarshalling return\", e);");
                /*
                 * If any only if readObject has been invoked, we must catch
                 * ClassNotFoundException as well as IOException.
                 */
                if (objectRead) {
                    p.pOlnI("} catch (java.lang.ClassNotFoundException e) {");
                    p.pln("throw new " + idUnmarshalException +
                        "(\"error unmarshalling return\", e);");
                }
                p.pOlnI("} finally {");
                p.pln("ref.done(call);");
                p.pOln("}");
                p.pln("return $result;");
            }
        }
        if (version == STUB_VERSION_FAT) {
            p.pOln("}");                // end if/else (useNewInvoke) block
        }

        /*
         * If we need to catch any particular exceptions, finally write
         * the catch blocks for them, rethrow any other Exceptions with an
         * UnexpectedException, and end the try block.
         */
        if (catchList.size() > 0) {
            for (Enumeration enumeration = catchList.elements();
                 enumeration.hasMoreElements();)
            {
                ClassDefinition def = (ClassDefinition) enumeration.nextElement();
                p.pOlnI("} catch (" + def.getName() + " e) {");
                p.pln("throw e;");
            }
            p.pOlnI("} catch (java.lang.Exception e) {");
            p.pln("throw new " + idUnexpectedException +
                "(\"undeclared checked exception\", e);");
            p.pOln("}");                // end try/catch block
        }

        p.pOln("}");                    // end stub method
    }

    /**
     * Compute the exceptions which need to be caught and rethrown in a
     * stub method before wrapping Exceptions in UnexpectedExceptions,
     * given the exceptions declared in the throws clause of the method.
     * Returns a Vector containing ClassDefinition objects for each
     * exception to catch.  Each exception is guaranteed to be unique,
     * i.e. not a subclass of any of the other exceptions in the Vector,
     * so the catch blocks for these exceptions may be generated in any
     * order relative to each other.
     *
     * RemoteException and RuntimeException are each automatically placed
     * in the returned Vector (if none of their superclasses are already
     * present), since those exceptions should always be directly rethrown
     * by a stub method.
     *
     * The returned Vector will be empty if java.lang.Exception or one
     * of its superclasses is in the throws clause of the method, indicating
     * that no exceptions need to be caught.
     */
    private Vector computeUniqueCatchList(ClassDeclaration[] exceptions) {
        Vector uniqueList = new Vector();       // unique exceptions to catch

        uniqueList.addElement(defRuntimeException);
        uniqueList.addElement(defRemoteException);

        /* For each exception declared by the stub method's throws clause: */
    nextException:
        for (int i = 0; i < exceptions.length; i++) {
            ClassDeclaration decl = exceptions[i];
            try {
                if (defException.subClassOf(env, decl)) {
                    /*
                     * (If java.lang.Exception (or a superclass) was declared
                     * in the throws clause of this stub method, then we don't
                     * have to bother catching anything; clear the list and
                     * return.)
                     */
                    uniqueList.clear();
                    break;
                } else if (!defException.superClassOf(env, decl)) {
                    /*
                     * Ignore other Throwables that do not extend Exception,
                     * since they do not need to be caught anyway.
                     */
                    continue;
                }
                /*
                 * Compare this exception against the current list of
                 * exceptions that need to be caught:
                 */
                for (int j = 0; j < uniqueList.size();) {
                    ClassDefinition def =
                        (ClassDefinition) uniqueList.elementAt(j);
                    if (def.superClassOf(env, decl)) {
                        /*
                         * If a superclass of this exception is already on
                         * the list to catch, then ignore and continue;
                         */
                        continue nextException;
                    } else if (def.subClassOf(env, decl)) {
                        /*
                         * If a subclass of this exception is on the list
                         * to catch, then remove it.
                         */
                        uniqueList.removeElementAt(j);
                    } else {
                        j++;    // else continue comparing
                    }
                }
                /* This exception is unique: add it to the list to catch. */
                uniqueList.addElement(decl.getClassDefinition(env));
            } catch (ClassNotFound e) {
                env.error(0, "class.not.found", e.name, decl.getName());
                /*
                 * REMIND: We do not exit from this exceptional condition,
                 * generating questionable code and likely letting the
                 * compiler report a resulting error later.
                 */
            }
        }
        return uniqueList;
    }

    /**
     * Write the skeleton for the remote class to a stream.
     */
    private void writeSkeleton(IndentingWriter p) throws IOException {
        if (version == STUB_VERSION_1_2) {
            throw new Error("should not generate skeleton for version");
        }

        /*
         * Write boiler plate comment.
         */
        p.pln("// Skeleton class generated by rmic, do not edit.");
        p.pln("// Contents subject to change without notice.");
        p.pln();

        /*
         * If remote implementation class was in a particular package,
         * declare the skeleton class to be in the same package.
         */
        if (remoteClassName.isQualified()) {
            p.pln("package " + remoteClassName.getQualifier() + ";");
            p.pln();
        }

        /*
         * Declare the skeleton class.
         */
        p.plnI("public final class " +
            Names.mangleClass(skeletonClassName.getName()));
        p.pln("implements " + idSkeleton);
        p.pOlnI("{");

        writeOperationsArray(p);
        p.pln();

        writeInterfaceHash(p);
        p.pln();

        /*
         * Define the getOperations() method.
         */
        p.plnI("public " + idOperation + "[] getOperations() {");
        p.pln("return (" + idOperation + "[]) operations.clone();");
        p.pOln("}");
        p.pln();

        /*
         * Define the dispatch() method.
         */
        p.plnI("public void dispatch(" + idRemote + " obj, " +
            idRemoteCall + " call, int opnum, long hash)");
        p.pln("throws java.lang.Exception");
        p.pOlnI("{");

        if (version == STUB_VERSION_FAT) {
            p.plnI("if (opnum < 0) {");
            if (remoteMethods.length > 0) {
                for (int opnum = 0; opnum < remoteMethods.length; opnum++) {
                    if (opnum > 0)
                        p.pO("} else ");
                    p.plnI("if (hash == " +
                        remoteMethods[opnum].getMethodHash() + "L) {");
                    p.pln("opnum = " + opnum + ";");
                }
                p.pOlnI("} else {");
            }
            /*
             * Skeleton throws UnmarshalException if it does not recognize
             * the method hash; this is what UnicastServerRef.dispatch()
             * would do.
             */
            p.pln("throw new " +
                idUnmarshalException + "(\"invalid method hash\");");
            if (remoteMethods.length > 0) {
                p.pOln("}");
            }
            /*
             * Ignore the validation of the interface hash if the
             * operation number was negative, since it is really a
             * method hash instead.
             */
            p.pOlnI("} else {");
        }

        p.plnI("if (hash != interfaceHash)");
        p.pln("throw new " +
            idSkeletonMismatchException + "(\"interface hash mismatch\");");
        p.pO();

        if (version == STUB_VERSION_FAT) {
            p.pOln("}");                // end if/else (opnum < 0) block
        }
        p.pln();

        /*
         * Cast remote object instance to our specific implementation class.
         */
        p.pln(remoteClassName + " server = (" + remoteClassName + ") obj;");

        /*
         * Process call according to the operation number.
         */
        p.plnI("switch (opnum) {");
        for (int opnum = 0; opnum < remoteMethods.length; opnum++) {
            writeSkeletonDispatchCase(p, opnum);
        }
        p.pOlnI("default:");
        /*
         * Skeleton throws UnmarshalException if it does not recognize
         * the operation number; this is consistent with the case of an
         * unrecognized method hash.
         */
        p.pln("throw new " + idUnmarshalException +
            "(\"invalid method number\");");
        p.pOln("}");                    // end switch statement

        p.pOln("}");                    // end dispatch() method

        p.pOln("}");                    // end skeleton class
    }

    /**
     * Write the case block for the skeleton's dispatch method for
     * the remote method with the given "opnum".
     */
    private void writeSkeletonDispatchCase(IndentingWriter p, int opnum)
        throws IOException
    {
        RemoteClass.Method method = remoteMethods[opnum];
        Identifier methodName = method.getName();
        Type methodType = method.getType();
        Type paramTypes[] = methodType.getArgumentTypes();
        String paramNames[] = nameParameters(paramTypes);
        Type returnType = methodType.getReturnType();

        p.pOlnI("case " + opnum + ": // " +
            methodType.typeString(methodName.toString(), true, false));
        /*
         * Use nested block statement inside case to provide an independent
         * namespace for local variables used to unmarshal parameters for
         * this remote method.
         */
        p.pOlnI("{");

        if (paramTypes.length > 0) {
            /*
             * Declare local variables to hold arguments.
             */
            for (int i = 0; i < paramTypes.length; i++) {
                p.pln(paramTypes[i] + " " + paramNames[i] + ";");
            }

            /*
             * Unmarshal arguments from call stream.
             */
            p.plnI("try {");
            p.pln("java.io.ObjectInput in = call.getInputStream();");
            boolean objectsRead = writeUnmarshalArguments(p, "in",
                paramTypes, paramNames);
            p.pOlnI("} catch (java.io.IOException e) {");
            p.pln("throw new " + idUnmarshalException +
                "(\"error unmarshalling arguments\", e);");
            /*
             * If any only if readObject has been invoked, we must catch
             * ClassNotFoundException as well as IOException.
             */
            if (objectsRead) {
                p.pOlnI("} catch (java.lang.ClassNotFoundException e) {");
                p.pln("throw new " + idUnmarshalException +
                    "(\"error unmarshalling arguments\", e);");
            }
            p.pOlnI("} finally {");
            p.pln("call.releaseInputStream();");
            p.pOln("}");
        } else {
            p.pln("call.releaseInputStream();");
        }

        if (!returnType.isType(TC_VOID)) {
            /*
             * Declare variable to hold return type, if not void.
             */
            p.p(returnType + " $result = ");            // REMIND: why $?
        }

        /*
         * Invoke the method on the server object.
         */
        p.p("server." + methodName + "(");
        for (int i = 0; i < paramNames.length; i++) {
            if (i > 0)
                p.p(", ");
            p.p(paramNames[i]);
        }
        p.pln(");");

        /*
         * Always invoke getResultStream(true) on the call object to send
         * the indication of a successful invocation to the caller.  If
         * the return type is not void, keep the result stream and marshal
         * the return value.
         */
        p.plnI("try {");
        if (!returnType.isType(TC_VOID)) {
            p.p("java.io.ObjectOutput out = ");
        }
        p.pln("call.getResultStream(true);");
        if (!returnType.isType(TC_VOID)) {
            writeMarshalArgument(p, "out", returnType, "$result");
            p.pln(";");
        }
        p.pOlnI("} catch (java.io.IOException e) {");
        p.pln("throw new " +
            idMarshalException + "(\"error marshalling return\", e);");
        p.pOln("}");

        p.pln("break;");                // break from switch statement

        p.pOlnI("}");                   // end nested block statement
        p.pln();
    }

    /**
     * Write declaration and initializer for "operations" static array.
     */
    private void writeOperationsArray(IndentingWriter p)
        throws IOException
    {
        p.plnI("private static final " + idOperation + "[] operations = {");
        for (int i = 0; i < remoteMethods.length; i++) {
            if (i > 0)
                p.pln(",");
            p.p("new " + idOperation + "(\"" +
                remoteMethods[i].getOperationString() + "\")");
        }
        p.pln();
        p.pOln("};");
    }

    /**
     * Write declaration and initializer for "interfaceHash" static field.
     */
    private void writeInterfaceHash(IndentingWriter p)
        throws IOException
    {
        p.pln("private static final long interfaceHash = " +
            remoteClass.getInterfaceHash() + "L;");
    }

    /**
     * Write declaration for java.lang.reflect.Method static fields
     * corresponding to each remote method in a stub.
     */
    private void writeMethodFieldDeclarations(IndentingWriter p)
        throws IOException
    {
        for (int i = 0; i < methodFieldNames.length; i++) {
            p.pln("private static java.lang.reflect.Method " +
                methodFieldNames[i] + ";");
        }
    }

    /**
     * Write code to initialize the static fields for each method
     * using the Java Reflection API.
     */
    private void writeMethodFieldInitializers(IndentingWriter p)
        throws IOException
    {
        for (int i = 0; i < methodFieldNames.length; i++) {
            p.p(methodFieldNames[i] + " = ");
            /*
             * Here we look up the Method object in the arbitrary interface
             * that we find in the RemoteClass.Method object.
             * REMIND: Is this arbitrary choice OK?
             * REMIND: Should this access be part of RemoteClass.Method's
             * abstraction?
             */
            RemoteClass.Method method = remoteMethods[i];
            MemberDefinition def = method.getMemberDefinition();
            Identifier methodName = method.getName();
            Type methodType = method.getType();
            Type paramTypes[] = methodType.getArgumentTypes();

            p.p(def.getClassDefinition().getName() + ".class.getMethod(\"" +
                methodName + "\", new java.lang.Class[] {");
            for (int j = 0; j < paramTypes.length; j++) {
                if (j > 0)
                    p.p(", ");
                p.p(paramTypes[j] + ".class");
            }
            p.pln("});");
        }
    }


    /*
     * Following are a series of static utility methods useful during
     * the code generation process:
     */

    /**
     * Generate an array of names for fields that correspond to the given
     * array of remote methods.  Each name in the returned array is
     * guaranteed to be unique.
     *
     * The name of a method is included in its corresponding field name
     * to enhance readability of the generated code.
     */
    private static String[] nameMethodFields(RemoteClass.Method[] methods) {
        String[] names = new String[methods.length];
        for (int i = 0; i < names.length; i++) {
            names[i] = "$method_" + methods[i].getName() + "_" + i;
        }
        return names;
    }

    /**
     * Generate an array of names for parameters corresponding to the
     * given array of types for the parameters.  Each name in the returned
     * array is guaranteed to be unique.
     *
     * A representation of the type of a parameter is included in its
     * corresponding field name to enhance the readability of the generated
     * code.
     */
    private static String[] nameParameters(Type[] types) {
        String[] names = new String[types.length];
        for (int i = 0; i < names.length; i++) {
            names[i] = "$param_" +
                generateNameFromType(types[i]) + "_" + (i + 1);
        }
        return names;
    }

    /**
     * Generate a readable string representing the given type suitable
     * for embedding within a Java identifier.
     */
    private static String generateNameFromType(Type type) {
        int typeCode = type.getTypeCode();
        switch (typeCode) {
        case TC_BOOLEAN:
        case TC_BYTE:
        case TC_CHAR:
        case TC_SHORT:
        case TC_INT:
        case TC_LONG:
        case TC_FLOAT:
        case TC_DOUBLE:
            return type.toString();
        case TC_ARRAY:
            return "arrayOf_" + generateNameFromType(type.getElementType());
        case TC_CLASS:
            return Names.mangleClass(type.getClassName().getName()).toString();
        default:
            throw new Error("unexpected type code: " + typeCode);
        }
    }

    /**
     * Write a snippet of Java code to marshal a value named "name" of
     * type "type" to the java.io.ObjectOutput stream named "stream".
     *
     * Primitive types are marshalled with their corresponding methods
     * in the java.io.DataOutput interface, and objects (including arrays)
     * are marshalled using the writeObject method.
     */
    private static void writeMarshalArgument(IndentingWriter p,
                                             String streamName,
                                             Type type, String name)
        throws IOException
    {
        int typeCode = type.getTypeCode();
        switch (typeCode) {
        case TC_BOOLEAN:
            p.p(streamName + ".writeBoolean(" + name + ")");
            break;
        case TC_BYTE:
            p.p(streamName + ".writeByte(" + name + ")");
            break;
        case TC_CHAR:
            p.p(streamName + ".writeChar(" + name + ")");
            break;
        case TC_SHORT:
            p.p(streamName + ".writeShort(" + name + ")");
            break;
        case TC_INT:
            p.p(streamName + ".writeInt(" + name + ")");
            break;
        case TC_LONG:
            p.p(streamName + ".writeLong(" + name + ")");
            break;
        case TC_FLOAT:
            p.p(streamName + ".writeFloat(" + name + ")");
            break;
        case TC_DOUBLE:
            p.p(streamName + ".writeDouble(" + name + ")");
            break;
        case TC_ARRAY:
        case TC_CLASS:
            p.p(streamName + ".writeObject(" + name + ")");
            break;
        default:
            throw new Error("unexpected type code: " + typeCode);
        }
    }

    /**
     * Write Java statements to marshal a series of values in order as
     * named in the "names" array, with types as specified in the "types"
     * array", to the java.io.ObjectOutput stream named "stream".
     */
    private static void writeMarshalArguments(IndentingWriter p,
                                              String streamName,
                                              Type[] types, String[] names)
        throws IOException
    {
        if (types.length != names.length) {
            throw new Error("paramter type and name arrays different sizes");
        }

        for (int i = 0; i < types.length; i++) {
            writeMarshalArgument(p, streamName, types[i], names[i]);
            p.pln(";");
        }
    }

    /**
     * Write a snippet of Java code to unmarshal a value of type "type"
     * from the java.io.ObjectInput stream named "stream" into a variable
     * named "name" (if "name" is null, the value in unmarshalled and
     * discarded).
     *
     * Primitive types are unmarshalled with their corresponding methods
     * in the java.io.DataInput interface, and objects (including arrays)
     * are unmarshalled using the readObject method.
     */
    private static boolean writeUnmarshalArgument(IndentingWriter p,
                                                  String streamName,
                                                  Type type, String name)
        throws IOException
    {
        boolean readObject = false;

        if (name != null) {
            p.p(name + " = ");
        }

        int typeCode = type.getTypeCode();
        switch (type.getTypeCode()) {
        case TC_BOOLEAN:
            p.p(streamName + ".readBoolean()");
            break;
        case TC_BYTE:
            p.p(streamName + ".readByte()");
            break;
        case TC_CHAR:
            p.p(streamName + ".readChar()");
            break;
        case TC_SHORT:
            p.p(streamName + ".readShort()");
            break;
        case TC_INT:
            p.p(streamName + ".readInt()");
            break;
        case TC_LONG:
            p.p(streamName + ".readLong()");
            break;
        case TC_FLOAT:
            p.p(streamName + ".readFloat()");
            break;
        case TC_DOUBLE:
            p.p(streamName + ".readDouble()");
            break;
        case TC_ARRAY:
        case TC_CLASS:
            p.p("(" + type + ") " + streamName + ".readObject()");
            readObject = true;
            break;
        default:
            throw new Error("unexpected type code: " + typeCode);
        }
        return readObject;
    }

    /**
     * Write Java statements to unmarshal a series of values in order of
     * types as in the "types" array from the java.io.ObjectInput stream
     * named "stream" into variables as named in "names" (for any element
     * of "names" that is null, the corresponding value is unmarshalled
     * and discarded).
     */
    private static boolean writeUnmarshalArguments(IndentingWriter p,
                                                   String streamName,
                                                   Type[] types,
                                                   String[] names)
        throws IOException
    {
        if (types.length != names.length) {
            throw new Error("paramter type and name arrays different sizes");
        }

        boolean readObject = false;
        for (int i = 0; i < types.length; i++) {
            if (writeUnmarshalArgument(p, streamName, types[i], names[i])) {
                readObject = true;
            }
            p.pln(";");
        }
        return readObject;
    }

    /**
     * Return a snippet of Java code to wrap a value named "name" of
     * type "type" into an object as appropriate for use by the
     * Java Reflection API.
     *
     * For primitive types, an appropriate wrapper class instantiated
     * with the primitive value.  For object types (including arrays),
     * no wrapping is necessary, so the value is named directly.
     */
    private static String wrapArgumentCode(Type type, String name) {
        int typeCode = type.getTypeCode();
        switch (typeCode) {
        case TC_BOOLEAN:
            return ("(" + name +
                    " ? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE)");
        case TC_BYTE:
            return "new java.lang.Byte(" + name + ")";
        case TC_CHAR:
            return "new java.lang.Character(" + name + ")";
        case TC_SHORT:
            return "new java.lang.Short(" + name + ")";
        case TC_INT:
            return "new java.lang.Integer(" + name + ")";
        case TC_LONG:
            return "new java.lang.Long(" + name + ")";
        case TC_FLOAT:
            return "new java.lang.Float(" + name + ")";
        case TC_DOUBLE:
            return "new java.lang.Double(" + name + ")";
        case TC_ARRAY:
        case TC_CLASS:
            return name;
        default:
            throw new Error("unexpected type code: " + typeCode);
        }
    }

    /**
     * Return a snippet of Java code to unwrap a value named "name" into
     * a value of type "type", as appropriate for the Java Reflection API.
     *
     * For primitive types, the value is assumed to be of the corresponding
     * wrapper type, and a method is called on the wrapper type to retrieve
     * the primitive value.  For object types (include arrays), no
     * unwrapping is necessary; the value is simply cast to the expected
     * real object type.
     */
    private static String unwrapArgumentCode(Type type, String name) {
        int typeCode = type.getTypeCode();
        switch (typeCode) {
        case TC_BOOLEAN:
            return "((java.lang.Boolean) " + name + ").booleanValue()";
        case TC_BYTE:
            return "((java.lang.Byte) " + name + ").byteValue()";
        case TC_CHAR:
            return "((java.lang.Character) " + name + ").charValue()";
        case TC_SHORT:
            return "((java.lang.Short) " + name + ").shortValue()";
        case TC_INT:
            return "((java.lang.Integer) " + name + ").intValue()";
        case TC_LONG:
            return "((java.lang.Long) " + name + ").longValue()";
        case TC_FLOAT:
            return "((java.lang.Float) " + name + ").floatValue()";
        case TC_DOUBLE:
            return "((java.lang.Double) " + name + ").doubleValue()";
        case TC_ARRAY:
        case TC_CLASS:
            return "((" + type + ") " + name + ")";
        default:
            throw new Error("unexpected type code: " + typeCode);
        }
    }
}