ClassReader.java revision 2740:c956c25f9334
1/*
2 * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.tools.javac.jvm;
27
28import java.io.*;
29import java.net.URI;
30import java.net.URISyntaxException;
31import java.nio.CharBuffer;
32import java.nio.file.Path;
33import java.util.Arrays;
34import java.util.EnumSet;
35import java.util.HashMap;
36import java.util.HashSet;
37import java.util.Map;
38import java.util.Set;
39
40import javax.tools.JavaFileManager;
41import javax.tools.JavaFileObject;
42
43import com.sun.tools.javac.code.*;
44import com.sun.tools.javac.code.Lint.LintCategory;
45import com.sun.tools.javac.code.Scope.WriteableScope;
46import com.sun.tools.javac.code.Symbol.*;
47import com.sun.tools.javac.code.Symtab;
48import com.sun.tools.javac.code.Type.*;
49import com.sun.tools.javac.comp.Annotate;
50import com.sun.tools.javac.file.BaseFileObject;
51import com.sun.tools.javac.jvm.ClassFile.NameAndType;
52import com.sun.tools.javac.jvm.ClassFile.Version;
53import com.sun.tools.javac.util.*;
54import com.sun.tools.javac.util.DefinedBy.Api;
55import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
56
57import static com.sun.tools.javac.code.Flags.*;
58import static com.sun.tools.javac.code.Kinds.Kind.*;
59import static com.sun.tools.javac.code.TypeTag.CLASS;
60import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
61import static com.sun.tools.javac.jvm.ClassFile.*;
62import static com.sun.tools.javac.jvm.ClassFile.Version.*;
63
64import static com.sun.tools.javac.main.Option.*;
65
66/** This class provides operations to read a classfile into an internal
67 *  representation. The internal representation is anchored in a
68 *  ClassSymbol which contains in its scope symbol representations
69 *  for all other definitions in the classfile. Top-level Classes themselves
70 *  appear as members of the scopes of PackageSymbols.
71 *
72 *  <p><b>This is NOT part of any supported API.
73 *  If you write code that depends on this, you do so at your own risk.
74 *  This code and its internal interfaces are subject to change or
75 *  deletion without notice.</b>
76 */
77public class ClassReader {
78    /** The context key for the class reader. */
79    protected static final Context.Key<ClassReader> classReaderKey = new Context.Key<>();
80
81    public static final int INITIAL_BUFFER_SIZE = 0x0fff0;
82
83    Annotate annotate;
84
85    /** Switch: verbose output.
86     */
87    boolean verbose;
88
89    /** Switch: check class file for correct minor version, unrecognized
90     *  attributes.
91     */
92    boolean checkClassFile;
93
94    /** Switch: read constant pool and code sections. This switch is initially
95     *  set to false but can be turned on from outside.
96     */
97    public boolean readAllOfClassFile = false;
98
99    /** Switch: allow simplified varargs.
100     */
101    boolean allowSimplifiedVarargs;
102
103   /** Lint option: warn about classfile issues
104     */
105    boolean lintClassfile;
106
107    /** Switch: preserve parameter names from the variable table.
108     */
109    public boolean saveParameterNames;
110
111    /**
112     * The currently selected profile.
113     */
114    public final Profile profile;
115
116    /** The log to use for verbose output
117     */
118    final Log log;
119
120    /** The symbol table. */
121    Symtab syms;
122
123    Types types;
124
125    /** The name table. */
126    final Names names;
127
128    /** Access to files
129     */
130    private final JavaFileManager fileManager;
131
132    /** Factory for diagnostics
133     */
134    JCDiagnostic.Factory diagFactory;
135
136    /** The current scope where type variables are entered.
137     */
138    protected WriteableScope typevars;
139
140    /** The path name of the class file currently being read.
141     */
142    protected JavaFileObject currentClassFile = null;
143
144    /** The class or method currently being read.
145     */
146    protected Symbol currentOwner = null;
147
148    /** The buffer containing the currently read class file.
149     */
150    byte[] buf = new byte[INITIAL_BUFFER_SIZE];
151
152    /** The current input pointer.
153     */
154    protected int bp;
155
156    /** The objects of the constant pool.
157     */
158    Object[] poolObj;
159
160    /** For every constant pool entry, an index into buf where the
161     *  defining section of the entry is found.
162     */
163    int[] poolIdx;
164
165    /** The major version number of the class file being read. */
166    int majorVersion;
167    /** The minor version number of the class file being read. */
168    int minorVersion;
169
170    /** A table to hold the constant pool indices for method parameter
171     * names, as given in LocalVariableTable attributes.
172     */
173    int[] parameterNameIndices;
174
175    /**
176     * Whether or not any parameter names have been found.
177     */
178    boolean haveParameterNameIndices;
179
180    /** Set this to false every time we start reading a method
181     * and are saving parameter names.  Set it to true when we see
182     * MethodParameters, if it's set when we see a LocalVariableTable,
183     * then we ignore the parameter names from the LVT.
184     */
185    boolean sawMethodParameters;
186
187    /**
188     * The set of attribute names for which warnings have been generated for the current class
189     */
190    Set<Name> warnedAttrs = new HashSet<>();
191
192    /** Get the ClassReader instance for this invocation. */
193    public static ClassReader instance(Context context) {
194        ClassReader instance = context.get(classReaderKey);
195        if (instance == null)
196            instance = new ClassReader(context);
197        return instance;
198    }
199
200    /** Construct a new class reader. */
201    protected ClassReader(Context context) {
202        context.put(classReaderKey, this);
203        names = Names.instance(context);
204        syms = Symtab.instance(context);
205        types = Types.instance(context);
206        fileManager = context.get(JavaFileManager.class);
207        if (fileManager == null)
208            throw new AssertionError("FileManager initialization error");
209        diagFactory = JCDiagnostic.Factory.instance(context);
210
211        log = Log.instance(context);
212
213        Options options = Options.instance(context);
214        annotate = Annotate.instance(context);
215        verbose        = options.isSet(VERBOSE);
216        checkClassFile = options.isSet("-checkclassfile");
217
218        Source source = Source.instance(context);
219        allowSimplifiedVarargs = source.allowSimplifiedVarargs();
220
221        saveParameterNames = options.isSet("save-parameter-names");
222
223        profile = Profile.instance(context);
224
225        typevars = WriteableScope.create(syms.noSymbol);
226
227        lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);
228
229        initAttributeReaders();
230    }
231
232    /** Add member to class unless it is synthetic.
233     */
234    private void enterMember(ClassSymbol c, Symbol sym) {
235        // Synthetic members are not entered -- reason lost to history (optimization?).
236        // Lambda methods must be entered because they may have inner classes (which reference them)
237        if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC || sym.name.startsWith(names.lambda))
238            c.members_field.enter(sym);
239    }
240
241/************************************************************************
242 * Error Diagnoses
243 ***********************************************************************/
244
245    public ClassFinder.BadClassFile badClassFile(String key, Object... args) {
246        return new ClassFinder.BadClassFile (
247            currentOwner.enclClass(),
248            currentClassFile,
249            diagFactory.fragment(key, args),
250            diagFactory);
251    }
252
253/************************************************************************
254 * Buffer Access
255 ***********************************************************************/
256
257    /** Read a character.
258     */
259    char nextChar() {
260        return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF));
261    }
262
263    /** Read a byte.
264     */
265    int nextByte() {
266        return buf[bp++] & 0xFF;
267    }
268
269    /** Read an integer.
270     */
271    int nextInt() {
272        return
273            ((buf[bp++] & 0xFF) << 24) +
274            ((buf[bp++] & 0xFF) << 16) +
275            ((buf[bp++] & 0xFF) << 8) +
276            (buf[bp++] & 0xFF);
277    }
278
279    /** Extract a character at position bp from buf.
280     */
281    char getChar(int bp) {
282        return
283            (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF));
284    }
285
286    /** Extract an integer at position bp from buf.
287     */
288    int getInt(int bp) {
289        return
290            ((buf[bp] & 0xFF) << 24) +
291            ((buf[bp+1] & 0xFF) << 16) +
292            ((buf[bp+2] & 0xFF) << 8) +
293            (buf[bp+3] & 0xFF);
294    }
295
296
297    /** Extract a long integer at position bp from buf.
298     */
299    long getLong(int bp) {
300        DataInputStream bufin =
301            new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
302        try {
303            return bufin.readLong();
304        } catch (IOException e) {
305            throw new AssertionError(e);
306        }
307    }
308
309    /** Extract a float at position bp from buf.
310     */
311    float getFloat(int bp) {
312        DataInputStream bufin =
313            new DataInputStream(new ByteArrayInputStream(buf, bp, 4));
314        try {
315            return bufin.readFloat();
316        } catch (IOException e) {
317            throw new AssertionError(e);
318        }
319    }
320
321    /** Extract a double at position bp from buf.
322     */
323    double getDouble(int bp) {
324        DataInputStream bufin =
325            new DataInputStream(new ByteArrayInputStream(buf, bp, 8));
326        try {
327            return bufin.readDouble();
328        } catch (IOException e) {
329            throw new AssertionError(e);
330        }
331    }
332
333/************************************************************************
334 * Constant Pool Access
335 ***********************************************************************/
336
337    /** Index all constant pool entries, writing their start addresses into
338     *  poolIdx.
339     */
340    void indexPool() {
341        poolIdx = new int[nextChar()];
342        poolObj = new Object[poolIdx.length];
343        int i = 1;
344        while (i < poolIdx.length) {
345            poolIdx[i++] = bp;
346            byte tag = buf[bp++];
347            switch (tag) {
348            case CONSTANT_Utf8: case CONSTANT_Unicode: {
349                int len = nextChar();
350                bp = bp + len;
351                break;
352            }
353            case CONSTANT_Class:
354            case CONSTANT_String:
355            case CONSTANT_MethodType:
356                bp = bp + 2;
357                break;
358            case CONSTANT_MethodHandle:
359                bp = bp + 3;
360                break;
361            case CONSTANT_Fieldref:
362            case CONSTANT_Methodref:
363            case CONSTANT_InterfaceMethodref:
364            case CONSTANT_NameandType:
365            case CONSTANT_Integer:
366            case CONSTANT_Float:
367            case CONSTANT_InvokeDynamic:
368                bp = bp + 4;
369                break;
370            case CONSTANT_Long:
371            case CONSTANT_Double:
372                bp = bp + 8;
373                i++;
374                break;
375            default:
376                throw badClassFile("bad.const.pool.tag.at",
377                                   Byte.toString(tag),
378                                   Integer.toString(bp -1));
379            }
380        }
381    }
382
383    /** Read constant pool entry at start address i, use pool as a cache.
384     */
385    Object readPool(int i) {
386        Object result = poolObj[i];
387        if (result != null) return result;
388
389        int index = poolIdx[i];
390        if (index == 0) return null;
391
392        byte tag = buf[index];
393        switch (tag) {
394        case CONSTANT_Utf8:
395            poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1));
396            break;
397        case CONSTANT_Unicode:
398            throw badClassFile("unicode.str.not.supported");
399        case CONSTANT_Class:
400            poolObj[i] = readClassOrType(getChar(index + 1));
401            break;
402        case CONSTANT_String:
403            // FIXME: (footprint) do not use toString here
404            poolObj[i] = readName(getChar(index + 1)).toString();
405            break;
406        case CONSTANT_Fieldref: {
407            ClassSymbol owner = readClassSymbol(getChar(index + 1));
408            NameAndType nt = readNameAndType(getChar(index + 3));
409            poolObj[i] = new VarSymbol(0, nt.name, nt.uniqueType.type, owner);
410            break;
411        }
412        case CONSTANT_Methodref:
413        case CONSTANT_InterfaceMethodref: {
414            ClassSymbol owner = readClassSymbol(getChar(index + 1));
415            NameAndType nt = readNameAndType(getChar(index + 3));
416            poolObj[i] = new MethodSymbol(0, nt.name, nt.uniqueType.type, owner);
417            break;
418        }
419        case CONSTANT_NameandType:
420            poolObj[i] = new NameAndType(
421                readName(getChar(index + 1)),
422                readType(getChar(index + 3)), types);
423            break;
424        case CONSTANT_Integer:
425            poolObj[i] = getInt(index + 1);
426            break;
427        case CONSTANT_Float:
428            poolObj[i] = new Float(getFloat(index + 1));
429            break;
430        case CONSTANT_Long:
431            poolObj[i] = new Long(getLong(index + 1));
432            break;
433        case CONSTANT_Double:
434            poolObj[i] = new Double(getDouble(index + 1));
435            break;
436        case CONSTANT_MethodHandle:
437            skipBytes(4);
438            break;
439        case CONSTANT_MethodType:
440            skipBytes(3);
441            break;
442        case CONSTANT_InvokeDynamic:
443            skipBytes(5);
444            break;
445        default:
446            throw badClassFile("bad.const.pool.tag", Byte.toString(tag));
447        }
448        return poolObj[i];
449    }
450
451    /** Read signature and convert to type.
452     */
453    Type readType(int i) {
454        int index = poolIdx[i];
455        return sigToType(buf, index + 3, getChar(index + 1));
456    }
457
458    /** If name is an array type or class signature, return the
459     *  corresponding type; otherwise return a ClassSymbol with given name.
460     */
461    Object readClassOrType(int i) {
462        int index =  poolIdx[i];
463        int len = getChar(index + 1);
464        int start = index + 3;
465        Assert.check(buf[start] == '[' || buf[start + len - 1] != ';');
466        // by the above assertion, the following test can be
467        // simplified to (buf[start] == '[')
468        return (buf[start] == '[' || buf[start + len - 1] == ';')
469            ? (Object)sigToType(buf, start, len)
470            : (Object)syms.enterClass(names.fromUtf(internalize(buf, start,
471                                                           len)));
472    }
473
474    /** Read signature and convert to type parameters.
475     */
476    List<Type> readTypeParams(int i) {
477        int index = poolIdx[i];
478        return sigToTypeParams(buf, index + 3, getChar(index + 1));
479    }
480
481    /** Read class entry.
482     */
483    ClassSymbol readClassSymbol(int i) {
484        Object obj = readPool(i);
485        if (obj != null && !(obj instanceof ClassSymbol))
486            throw badClassFile("bad.const.pool.entry",
487                               currentClassFile.toString(),
488                               "CONSTANT_Class_info", i);
489        return (ClassSymbol)obj;
490    }
491
492    /** Read name.
493     */
494    Name readName(int i) {
495        Object obj = readPool(i);
496        if (obj != null && !(obj instanceof Name))
497            throw badClassFile("bad.const.pool.entry",
498                               currentClassFile.toString(),
499                               "CONSTANT_Utf8_info or CONSTANT_String_info", i);
500        return (Name)obj;
501    }
502
503    /** Read name and type.
504     */
505    NameAndType readNameAndType(int i) {
506        Object obj = readPool(i);
507        if (obj != null && !(obj instanceof NameAndType))
508            throw badClassFile("bad.const.pool.entry",
509                               currentClassFile.toString(),
510                               "CONSTANT_NameAndType_info", i);
511        return (NameAndType)obj;
512    }
513
514/************************************************************************
515 * Reading Types
516 ***********************************************************************/
517
518    /** The unread portion of the currently read type is
519     *  signature[sigp..siglimit-1].
520     */
521    byte[] signature;
522    int sigp;
523    int siglimit;
524    boolean sigEnterPhase = false;
525
526    /** Convert signature to type, where signature is a byte array segment.
527     */
528    Type sigToType(byte[] sig, int offset, int len) {
529        signature = sig;
530        sigp = offset;
531        siglimit = offset + len;
532        return sigToType();
533    }
534
535    /** Convert signature to type, where signature is implicit.
536     */
537    Type sigToType() {
538        switch ((char) signature[sigp]) {
539        case 'T':
540            sigp++;
541            int start = sigp;
542            while (signature[sigp] != ';') sigp++;
543            sigp++;
544            return sigEnterPhase
545                ? Type.noType
546                : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
547        case '+': {
548            sigp++;
549            Type t = sigToType();
550            return new WildcardType(t, BoundKind.EXTENDS, syms.boundClass);
551        }
552        case '*':
553            sigp++;
554            return new WildcardType(syms.objectType, BoundKind.UNBOUND,
555                                    syms.boundClass);
556        case '-': {
557            sigp++;
558            Type t = sigToType();
559            return new WildcardType(t, BoundKind.SUPER, syms.boundClass);
560        }
561        case 'B':
562            sigp++;
563            return syms.byteType;
564        case 'C':
565            sigp++;
566            return syms.charType;
567        case 'D':
568            sigp++;
569            return syms.doubleType;
570        case 'F':
571            sigp++;
572            return syms.floatType;
573        case 'I':
574            sigp++;
575            return syms.intType;
576        case 'J':
577            sigp++;
578            return syms.longType;
579        case 'L':
580            {
581                // int oldsigp = sigp;
582                Type t = classSigToType();
583                if (sigp < siglimit && signature[sigp] == '.')
584                    throw badClassFile("deprecated inner class signature syntax " +
585                                       "(please recompile from source)");
586                /*
587                System.err.println(" decoded " +
588                                   new String(signature, oldsigp, sigp-oldsigp) +
589                                   " => " + t + " outer " + t.outer());
590                */
591                return t;
592            }
593        case 'S':
594            sigp++;
595            return syms.shortType;
596        case 'V':
597            sigp++;
598            return syms.voidType;
599        case 'Z':
600            sigp++;
601            return syms.booleanType;
602        case '[':
603            sigp++;
604            return new ArrayType(sigToType(), syms.arrayClass);
605        case '(':
606            sigp++;
607            List<Type> argtypes = sigToTypes(')');
608            Type restype = sigToType();
609            List<Type> thrown = List.nil();
610            while (signature[sigp] == '^') {
611                sigp++;
612                thrown = thrown.prepend(sigToType());
613            }
614            // if there is a typevar in the throws clause we should state it.
615            for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) {
616                if (l.head.hasTag(TYPEVAR)) {
617                    l.head.tsym.flags_field |= THROWS;
618                }
619            }
620            return new MethodType(argtypes,
621                                  restype,
622                                  thrown.reverse(),
623                                  syms.methodClass);
624        case '<':
625            typevars = typevars.dup(currentOwner);
626            Type poly = new ForAll(sigToTypeParams(), sigToType());
627            typevars = typevars.leave();
628            return poly;
629        default:
630            throw badClassFile("bad.signature",
631                               Convert.utf2string(signature, sigp, 10));
632        }
633    }
634
635    byte[] signatureBuffer = new byte[0];
636    int sbp = 0;
637    /** Convert class signature to type, where signature is implicit.
638     */
639    Type classSigToType() {
640        if (signature[sigp] != 'L')
641            throw badClassFile("bad.class.signature",
642                               Convert.utf2string(signature, sigp, 10));
643        sigp++;
644        Type outer = Type.noType;
645        int startSbp = sbp;
646
647        while (true) {
648            final byte c = signature[sigp++];
649            switch (c) {
650
651            case ';': {         // end
652                ClassSymbol t = syms.enterClass(names.fromUtf(signatureBuffer,
653                                                         startSbp,
654                                                         sbp - startSbp));
655
656                try {
657                    return (outer == Type.noType) ?
658                            t.erasure(types) :
659                        new ClassType(outer, List.<Type>nil(), t);
660                } finally {
661                    sbp = startSbp;
662                }
663            }
664
665            case '<':           // generic arguments
666                ClassSymbol t = syms.enterClass(names.fromUtf(signatureBuffer,
667                                                         startSbp,
668                                                         sbp - startSbp));
669                outer = new ClassType(outer, sigToTypes('>'), t) {
670                        boolean completed = false;
671                        @Override @DefinedBy(Api.LANGUAGE_MODEL)
672                        public Type getEnclosingType() {
673                            if (!completed) {
674                                completed = true;
675                                tsym.complete();
676                                Type enclosingType = tsym.type.getEnclosingType();
677                                if (enclosingType != Type.noType) {
678                                    List<Type> typeArgs =
679                                        super.getEnclosingType().allparams();
680                                    List<Type> typeParams =
681                                        enclosingType.allparams();
682                                    if (typeParams.length() != typeArgs.length()) {
683                                        // no "rare" types
684                                        super.setEnclosingType(types.erasure(enclosingType));
685                                    } else {
686                                        super.setEnclosingType(types.subst(enclosingType,
687                                                                           typeParams,
688                                                                           typeArgs));
689                                    }
690                                } else {
691                                    super.setEnclosingType(Type.noType);
692                                }
693                            }
694                            return super.getEnclosingType();
695                        }
696                        @Override
697                        public void setEnclosingType(Type outer) {
698                            throw new UnsupportedOperationException();
699                        }
700                    };
701                switch (signature[sigp++]) {
702                case ';':
703                    if (sigp < signature.length && signature[sigp] == '.') {
704                        // support old-style GJC signatures
705                        // The signature produced was
706                        // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>;
707                        // rather than say
708                        // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>;
709                        // so we skip past ".Lfoo/Outer$"
710                        sigp += (sbp - startSbp) + // "foo/Outer"
711                            3;  // ".L" and "$"
712                        signatureBuffer[sbp++] = (byte)'$';
713                        break;
714                    } else {
715                        sbp = startSbp;
716                        return outer;
717                    }
718                case '.':
719                    signatureBuffer[sbp++] = (byte)'$';
720                    break;
721                default:
722                    throw new AssertionError(signature[sigp-1]);
723                }
724                continue;
725
726            case '.':
727                //we have seen an enclosing non-generic class
728                if (outer != Type.noType) {
729                    t = syms.enterClass(names.fromUtf(signatureBuffer,
730                                                 startSbp,
731                                                 sbp - startSbp));
732                    outer = new ClassType(outer, List.<Type>nil(), t);
733                }
734                signatureBuffer[sbp++] = (byte)'$';
735                continue;
736            case '/':
737                signatureBuffer[sbp++] = (byte)'.';
738                continue;
739            default:
740                signatureBuffer[sbp++] = c;
741                continue;
742            }
743        }
744    }
745
746    /** Convert (implicit) signature to list of types
747     *  until `terminator' is encountered.
748     */
749    List<Type> sigToTypes(char terminator) {
750        List<Type> head = List.of(null);
751        List<Type> tail = head;
752        while (signature[sigp] != terminator)
753            tail = tail.setTail(List.of(sigToType()));
754        sigp++;
755        return head.tail;
756    }
757
758    /** Convert signature to type parameters, where signature is a byte
759     *  array segment.
760     */
761    List<Type> sigToTypeParams(byte[] sig, int offset, int len) {
762        signature = sig;
763        sigp = offset;
764        siglimit = offset + len;
765        return sigToTypeParams();
766    }
767
768    /** Convert signature to type parameters, where signature is implicit.
769     */
770    List<Type> sigToTypeParams() {
771        List<Type> tvars = List.nil();
772        if (signature[sigp] == '<') {
773            sigp++;
774            int start = sigp;
775            sigEnterPhase = true;
776            while (signature[sigp] != '>')
777                tvars = tvars.prepend(sigToTypeParam());
778            sigEnterPhase = false;
779            sigp = start;
780            while (signature[sigp] != '>')
781                sigToTypeParam();
782            sigp++;
783        }
784        return tvars.reverse();
785    }
786
787    /** Convert (implicit) signature to type parameter.
788     */
789    Type sigToTypeParam() {
790        int start = sigp;
791        while (signature[sigp] != ':') sigp++;
792        Name name = names.fromUtf(signature, start, sigp - start);
793        TypeVar tvar;
794        if (sigEnterPhase) {
795            tvar = new TypeVar(name, currentOwner, syms.botType);
796            typevars.enter(tvar.tsym);
797        } else {
798            tvar = (TypeVar)findTypeVar(name);
799        }
800        List<Type> bounds = List.nil();
801        boolean allInterfaces = false;
802        if (signature[sigp] == ':' && signature[sigp+1] == ':') {
803            sigp++;
804            allInterfaces = true;
805        }
806        while (signature[sigp] == ':') {
807            sigp++;
808            bounds = bounds.prepend(sigToType());
809        }
810        if (!sigEnterPhase) {
811            types.setBounds(tvar, bounds.reverse(), allInterfaces);
812        }
813        return tvar;
814    }
815
816    /** Find type variable with given name in `typevars' scope.
817     */
818    Type findTypeVar(Name name) {
819        Symbol s = typevars.findFirst(name);
820        if (s != null) {
821            return s.type;
822        } else {
823            if (readingClassAttr) {
824                // While reading the class attribute, the supertypes
825                // might refer to a type variable from an enclosing element
826                // (method or class).
827                // If the type variable is defined in the enclosing class,
828                // we can actually find it in
829                // currentOwner.owner.type.getTypeArguments()
830                // However, until we have read the enclosing method attribute
831                // we don't know for sure if this owner is correct.  It could
832                // be a method and there is no way to tell before reading the
833                // enclosing method attribute.
834                TypeVar t = new TypeVar(name, currentOwner, syms.botType);
835                missingTypeVariables = missingTypeVariables.prepend(t);
836                // System.err.println("Missing type var " + name);
837                return t;
838            }
839            throw badClassFile("undecl.type.var", name);
840        }
841    }
842
843/************************************************************************
844 * Reading Attributes
845 ***********************************************************************/
846
847    protected enum AttributeKind { CLASS, MEMBER }
848
849    protected abstract class AttributeReader {
850        protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) {
851            this.name = name;
852            this.version = version;
853            this.kinds = kinds;
854        }
855
856        protected boolean accepts(AttributeKind kind) {
857            if (kinds.contains(kind)) {
858                if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
859                    return true;
860
861                if (lintClassfile && !warnedAttrs.contains(name)) {
862                    JavaFileObject prev = log.useSource(currentClassFile);
863                    try {
864                        log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
865                                name, version.major, version.minor, majorVersion, minorVersion);
866                    } finally {
867                        log.useSource(prev);
868                    }
869                    warnedAttrs.add(name);
870                }
871            }
872            return false;
873        }
874
875        protected abstract void read(Symbol sym, int attrLen);
876
877        protected final Name name;
878        protected final ClassFile.Version version;
879        protected final Set<AttributeKind> kinds;
880    }
881
882    protected Set<AttributeKind> CLASS_ATTRIBUTE =
883            EnumSet.of(AttributeKind.CLASS);
884    protected Set<AttributeKind> MEMBER_ATTRIBUTE =
885            EnumSet.of(AttributeKind.MEMBER);
886    protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE =
887            EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER);
888
889    protected Map<Name, AttributeReader> attributeReaders = new HashMap<>();
890
891    private void initAttributeReaders() {
892        AttributeReader[] readers = {
893            // v45.3 attributes
894
895            new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) {
896                protected void read(Symbol sym, int attrLen) {
897                    if (readAllOfClassFile || saveParameterNames)
898                        ((MethodSymbol)sym).code = readCode(sym);
899                    else
900                        bp = bp + attrLen;
901                }
902            },
903
904            new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) {
905                protected void read(Symbol sym, int attrLen) {
906                    Object v = readPool(nextChar());
907                    // Ignore ConstantValue attribute if field not final.
908                    if ((sym.flags() & FINAL) != 0)
909                        ((VarSymbol) sym).setData(v);
910                }
911            },
912
913            new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
914                protected void read(Symbol sym, int attrLen) {
915                    sym.flags_field |= DEPRECATED;
916                }
917            },
918
919            new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
920                protected void read(Symbol sym, int attrLen) {
921                    int nexceptions = nextChar();
922                    List<Type> thrown = List.nil();
923                    for (int j = 0; j < nexceptions; j++)
924                        thrown = thrown.prepend(readClassSymbol(nextChar()).type);
925                    if (sym.type.getThrownTypes().isEmpty())
926                        sym.type.asMethodType().thrown = thrown.reverse();
927                }
928            },
929
930            new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) {
931                protected void read(Symbol sym, int attrLen) {
932                    ClassSymbol c = (ClassSymbol) sym;
933                    readInnerClasses(c);
934                }
935            },
936
937            new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
938                protected void read(Symbol sym, int attrLen) {
939                    int newbp = bp + attrLen;
940                    if (saveParameterNames && !sawMethodParameters) {
941                        // Pick up parameter names from the variable table.
942                        // Parameter names are not explicitly identified as such,
943                        // but all parameter name entries in the LocalVariableTable
944                        // have a start_pc of 0.  Therefore, we record the name
945                        // indicies of all slots with a start_pc of zero in the
946                        // parameterNameIndicies array.
947                        // Note that this implicitly honors the JVMS spec that
948                        // there may be more than one LocalVariableTable, and that
949                        // there is no specified ordering for the entries.
950                        int numEntries = nextChar();
951                        for (int i = 0; i < numEntries; i++) {
952                            int start_pc = nextChar();
953                            int length = nextChar();
954                            int nameIndex = nextChar();
955                            int sigIndex = nextChar();
956                            int register = nextChar();
957                            if (start_pc == 0) {
958                                // ensure array large enough
959                                if (register >= parameterNameIndices.length) {
960                                    int newSize = Math.max(register, parameterNameIndices.length + 8);
961                                    parameterNameIndices =
962                                            Arrays.copyOf(parameterNameIndices, newSize);
963                                }
964                                parameterNameIndices[register] = nameIndex;
965                                haveParameterNameIndices = true;
966                            }
967                        }
968                    }
969                    bp = newbp;
970                }
971            },
972
973            new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) {
974                protected void read(Symbol sym, int attrlen) {
975                    int newbp = bp + attrlen;
976                    if (saveParameterNames) {
977                        sawMethodParameters = true;
978                        int numEntries = nextByte();
979                        parameterNameIndices = new int[numEntries];
980                        haveParameterNameIndices = true;
981                        for (int i = 0; i < numEntries; i++) {
982                            int nameIndex = nextChar();
983                            int flags = nextChar();
984                            parameterNameIndices[i] = nameIndex;
985                        }
986                    }
987                    bp = newbp;
988                }
989            },
990
991
992            new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
993                protected void read(Symbol sym, int attrLen) {
994                    ClassSymbol c = (ClassSymbol) sym;
995                    Name n = readName(nextChar());
996                    c.sourcefile = new SourceFileObject(n, c.flatname);
997                    // If the class is a toplevel class, originating from a Java source file,
998                    // but the class name does not match the file name, then it is
999                    // an auxiliary class.
1000                    String sn = n.toString();
1001                    if (c.owner.kind == PCK &&
1002                        sn.endsWith(".java") &&
1003                        !sn.equals(c.name.toString()+".java")) {
1004                        c.flags_field |= AUXILIARY;
1005                    }
1006                }
1007            },
1008
1009            new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
1010                protected void read(Symbol sym, int attrLen) {
1011                    sym.flags_field |= SYNTHETIC;
1012                }
1013            },
1014
1015            // standard v49 attributes
1016
1017            new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) {
1018                protected void read(Symbol sym, int attrLen) {
1019                    int newbp = bp + attrLen;
1020                    readEnclosingMethodAttr(sym);
1021                    bp = newbp;
1022                }
1023            },
1024
1025            new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1026                protected void read(Symbol sym, int attrLen) {
1027                    if (sym.kind == TYP) {
1028                        ClassSymbol c = (ClassSymbol) sym;
1029                        readingClassAttr = true;
1030                        try {
1031                            ClassType ct1 = (ClassType)c.type;
1032                            Assert.check(c == currentOwner);
1033                            ct1.typarams_field = readTypeParams(nextChar());
1034                            ct1.supertype_field = sigToType();
1035                            ListBuffer<Type> is = new ListBuffer<>();
1036                            while (sigp != siglimit) is.append(sigToType());
1037                            ct1.interfaces_field = is.toList();
1038                        } finally {
1039                            readingClassAttr = false;
1040                        }
1041                    } else {
1042                        List<Type> thrown = sym.type.getThrownTypes();
1043                        sym.type = readType(nextChar());
1044                        //- System.err.println(" # " + sym.type);
1045                        if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty())
1046                            sym.type.asMethodType().thrown = thrown;
1047
1048                    }
1049                }
1050            },
1051
1052            // v49 annotation attributes
1053
1054            new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1055                protected void read(Symbol sym, int attrLen) {
1056                    attachAnnotationDefault(sym);
1057                }
1058            },
1059
1060            new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1061                protected void read(Symbol sym, int attrLen) {
1062                    attachAnnotations(sym);
1063                }
1064            },
1065
1066            new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1067                protected void read(Symbol sym, int attrLen) {
1068                    attachParameterAnnotations(sym);
1069                }
1070            },
1071
1072            new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1073                protected void read(Symbol sym, int attrLen) {
1074                    attachAnnotations(sym);
1075                }
1076            },
1077
1078            new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1079                protected void read(Symbol sym, int attrLen) {
1080                    attachParameterAnnotations(sym);
1081                }
1082            },
1083
1084            // additional "legacy" v49 attributes, superceded by flags
1085
1086            new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1087                protected void read(Symbol sym, int attrLen) {
1088                    sym.flags_field |= ANNOTATION;
1089                }
1090            },
1091
1092            new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) {
1093                protected void read(Symbol sym, int attrLen) {
1094                    sym.flags_field |= BRIDGE;
1095                }
1096            },
1097
1098            new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1099                protected void read(Symbol sym, int attrLen) {
1100                    sym.flags_field |= ENUM;
1101                }
1102            },
1103
1104            new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) {
1105                protected void read(Symbol sym, int attrLen) {
1106                    sym.flags_field |= VARARGS;
1107                }
1108            },
1109
1110            new AttributeReader(names.RuntimeVisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
1111                protected void read(Symbol sym, int attrLen) {
1112                    attachTypeAnnotations(sym);
1113                }
1114            },
1115
1116            new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) {
1117                protected void read(Symbol sym, int attrLen) {
1118                    attachTypeAnnotations(sym);
1119                }
1120            },
1121
1122
1123            // The following attributes for a Code attribute are not currently handled
1124            // StackMapTable
1125            // SourceDebugExtension
1126            // LineNumberTable
1127            // LocalVariableTypeTable
1128        };
1129
1130        for (AttributeReader r: readers)
1131            attributeReaders.put(r.name, r);
1132    }
1133
1134    /** Report unrecognized attribute.
1135     */
1136    void unrecognized(Name attrName) {
1137        if (checkClassFile)
1138            printCCF("ccf.unrecognized.attribute", attrName);
1139    }
1140
1141
1142
1143    protected void readEnclosingMethodAttr(Symbol sym) {
1144        // sym is a nested class with an "Enclosing Method" attribute
1145        // remove sym from it's current owners scope and place it in
1146        // the scope specified by the attribute
1147        sym.owner.members().remove(sym);
1148        ClassSymbol self = (ClassSymbol)sym;
1149        ClassSymbol c = readClassSymbol(nextChar());
1150        NameAndType nt = readNameAndType(nextChar());
1151
1152        if (c.members_field == null)
1153            throw badClassFile("bad.enclosing.class", self, c);
1154
1155        MethodSymbol m = findMethod(nt, c.members_field, self.flags());
1156        if (nt != null && m == null)
1157            throw badClassFile("bad.enclosing.method", self);
1158
1159        self.name = simpleBinaryName(self.flatname, c.flatname) ;
1160        self.owner = m != null ? m : c;
1161        if (self.name.isEmpty())
1162            self.fullname = names.empty;
1163        else
1164            self.fullname = ClassSymbol.formFullName(self.name, self.owner);
1165
1166        if (m != null) {
1167            ((ClassType)sym.type).setEnclosingType(m.type);
1168        } else if ((self.flags_field & STATIC) == 0) {
1169            ((ClassType)sym.type).setEnclosingType(c.type);
1170        } else {
1171            ((ClassType)sym.type).setEnclosingType(Type.noType);
1172        }
1173        enterTypevars(self);
1174        if (!missingTypeVariables.isEmpty()) {
1175            ListBuffer<Type> typeVars =  new ListBuffer<>();
1176            for (Type typevar : missingTypeVariables) {
1177                typeVars.append(findTypeVar(typevar.tsym.name));
1178            }
1179            foundTypeVariables = typeVars.toList();
1180        } else {
1181            foundTypeVariables = List.nil();
1182        }
1183    }
1184
1185    // See java.lang.Class
1186    private Name simpleBinaryName(Name self, Name enclosing) {
1187        String simpleBinaryName = self.toString().substring(enclosing.toString().length());
1188        if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$')
1189            throw badClassFile("bad.enclosing.method", self);
1190        int index = 1;
1191        while (index < simpleBinaryName.length() &&
1192               isAsciiDigit(simpleBinaryName.charAt(index)))
1193            index++;
1194        return names.fromString(simpleBinaryName.substring(index));
1195    }
1196
1197    private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) {
1198        if (nt == null)
1199            return null;
1200
1201        MethodType type = nt.uniqueType.type.asMethodType();
1202
1203        for (Symbol sym : scope.getSymbolsByName(nt.name)) {
1204            if (sym.kind == MTH && isSameBinaryType(sym.type.asMethodType(), type))
1205                return (MethodSymbol)sym;
1206        }
1207
1208        if (nt.name != names.init)
1209            // not a constructor
1210            return null;
1211        if ((flags & INTERFACE) != 0)
1212            // no enclosing instance
1213            return null;
1214        if (nt.uniqueType.type.getParameterTypes().isEmpty())
1215            // no parameters
1216            return null;
1217
1218        // A constructor of an inner class.
1219        // Remove the first argument (the enclosing instance)
1220        nt.setType(new MethodType(nt.uniqueType.type.getParameterTypes().tail,
1221                                 nt.uniqueType.type.getReturnType(),
1222                                 nt.uniqueType.type.getThrownTypes(),
1223                                 syms.methodClass));
1224        // Try searching again
1225        return findMethod(nt, scope, flags);
1226    }
1227
1228    /** Similar to Types.isSameType but avoids completion */
1229    private boolean isSameBinaryType(MethodType mt1, MethodType mt2) {
1230        List<Type> types1 = types.erasure(mt1.getParameterTypes())
1231            .prepend(types.erasure(mt1.getReturnType()));
1232        List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType());
1233        while (!types1.isEmpty() && !types2.isEmpty()) {
1234            if (types1.head.tsym != types2.head.tsym)
1235                return false;
1236            types1 = types1.tail;
1237            types2 = types2.tail;
1238        }
1239        return types1.isEmpty() && types2.isEmpty();
1240    }
1241
1242    /**
1243     * Character.isDigit answers <tt>true</tt> to some non-ascii
1244     * digits.  This one does not.  <b>copied from java.lang.Class</b>
1245     */
1246    private static boolean isAsciiDigit(char c) {
1247        return '0' <= c && c <= '9';
1248    }
1249
1250    /** Read member attributes.
1251     */
1252    void readMemberAttrs(Symbol sym) {
1253        readAttrs(sym, AttributeKind.MEMBER);
1254    }
1255
1256    void readAttrs(Symbol sym, AttributeKind kind) {
1257        char ac = nextChar();
1258        for (int i = 0; i < ac; i++) {
1259            Name attrName = readName(nextChar());
1260            int attrLen = nextInt();
1261            AttributeReader r = attributeReaders.get(attrName);
1262            if (r != null && r.accepts(kind))
1263                r.read(sym, attrLen);
1264            else  {
1265                unrecognized(attrName);
1266                bp = bp + attrLen;
1267            }
1268        }
1269    }
1270
1271    private boolean readingClassAttr = false;
1272    private List<Type> missingTypeVariables = List.nil();
1273    private List<Type> foundTypeVariables = List.nil();
1274
1275    /** Read class attributes.
1276     */
1277    void readClassAttrs(ClassSymbol c) {
1278        readAttrs(c, AttributeKind.CLASS);
1279    }
1280
1281    /** Read code block.
1282     */
1283    Code readCode(Symbol owner) {
1284        nextChar(); // max_stack
1285        nextChar(); // max_locals
1286        final int  code_length = nextInt();
1287        bp += code_length;
1288        final char exception_table_length = nextChar();
1289        bp += exception_table_length * 8;
1290        readMemberAttrs(owner);
1291        return null;
1292    }
1293
1294/************************************************************************
1295 * Reading Java-language annotations
1296 ***********************************************************************/
1297
1298    /** Attach annotations.
1299     */
1300    void attachAnnotations(final Symbol sym) {
1301        int numAttributes = nextChar();
1302        if (numAttributes != 0) {
1303            ListBuffer<CompoundAnnotationProxy> proxies = new ListBuffer<>();
1304            for (int i = 0; i<numAttributes; i++) {
1305                CompoundAnnotationProxy proxy = readCompoundAnnotation();
1306                proxies.append(proxy);
1307            }
1308            annotate.normal(new AnnotationCompleter(sym, proxies.toList()));
1309        }
1310    }
1311
1312    /** Attach parameter annotations.
1313     */
1314    void attachParameterAnnotations(final Symbol method) {
1315        final MethodSymbol meth = (MethodSymbol)method;
1316        int numParameters = buf[bp++] & 0xFF;
1317        List<VarSymbol> parameters = meth.params();
1318        int pnum = 0;
1319        while (parameters.tail != null) {
1320            attachAnnotations(parameters.head);
1321            parameters = parameters.tail;
1322            pnum++;
1323        }
1324        if (pnum != numParameters) {
1325            throw badClassFile("bad.runtime.invisible.param.annotations", meth);
1326        }
1327    }
1328
1329    void attachTypeAnnotations(final Symbol sym) {
1330        int numAttributes = nextChar();
1331        if (numAttributes != 0) {
1332            ListBuffer<TypeAnnotationProxy> proxies = new ListBuffer<>();
1333            for (int i = 0; i < numAttributes; i++)
1334                proxies.append(readTypeAnnotation());
1335            annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList()));
1336        }
1337    }
1338
1339    /** Attach the default value for an annotation element.
1340     */
1341    void attachAnnotationDefault(final Symbol sym) {
1342        final MethodSymbol meth = (MethodSymbol)sym; // only on methods
1343        final Attribute value = readAttributeValue();
1344
1345        // The default value is set later during annotation. It might
1346        // be the case that the Symbol sym is annotated _after_ the
1347        // repeating instances that depend on this default value,
1348        // because of this we set an interim value that tells us this
1349        // element (most likely) has a default.
1350        //
1351        // Set interim value for now, reset just before we do this
1352        // properly at annotate time.
1353        meth.defaultValue = value;
1354        annotate.normal(new AnnotationDefaultCompleter(meth, value));
1355    }
1356
1357    Type readTypeOrClassSymbol(int i) {
1358        // support preliminary jsr175-format class files
1359        if (buf[poolIdx[i]] == CONSTANT_Class)
1360            return readClassSymbol(i).type;
1361        return readType(i);
1362    }
1363    Type readEnumType(int i) {
1364        // support preliminary jsr175-format class files
1365        int index = poolIdx[i];
1366        int length = getChar(index + 1);
1367        if (buf[index + length + 2] != ';')
1368            return syms.enterClass(readName(i)).type;
1369        return readType(i);
1370    }
1371
1372    CompoundAnnotationProxy readCompoundAnnotation() {
1373        Type t = readTypeOrClassSymbol(nextChar());
1374        int numFields = nextChar();
1375        ListBuffer<Pair<Name,Attribute>> pairs = new ListBuffer<>();
1376        for (int i=0; i<numFields; i++) {
1377            Name name = readName(nextChar());
1378            Attribute value = readAttributeValue();
1379            pairs.append(new Pair<>(name, value));
1380        }
1381        return new CompoundAnnotationProxy(t, pairs.toList());
1382    }
1383
1384    TypeAnnotationProxy readTypeAnnotation() {
1385        TypeAnnotationPosition position = readPosition();
1386        CompoundAnnotationProxy proxy = readCompoundAnnotation();
1387
1388        return new TypeAnnotationProxy(proxy, position);
1389    }
1390
1391    TypeAnnotationPosition readPosition() {
1392        int tag = nextByte(); // TargetType tag is a byte
1393
1394        if (!TargetType.isValidTargetTypeValue(tag))
1395            throw badClassFile("bad.type.annotation.value", String.format("0x%02X", tag));
1396
1397        TargetType type = TargetType.fromTargetTypeValue(tag);
1398
1399        switch (type) {
1400        // instanceof
1401        case INSTANCEOF: {
1402            final int offset = nextChar();
1403            final TypeAnnotationPosition position =
1404                TypeAnnotationPosition.instanceOf(readTypePath());
1405            position.offset = offset;
1406            return position;
1407        }
1408        // new expression
1409        case NEW: {
1410            final int offset = nextChar();
1411            final TypeAnnotationPosition position =
1412                TypeAnnotationPosition.newObj(readTypePath());
1413            position.offset = offset;
1414            return position;
1415        }
1416        // constructor/method reference receiver
1417        case CONSTRUCTOR_REFERENCE: {
1418            final int offset = nextChar();
1419            final TypeAnnotationPosition position =
1420                TypeAnnotationPosition.constructorRef(readTypePath());
1421            position.offset = offset;
1422            return position;
1423        }
1424        case METHOD_REFERENCE: {
1425            final int offset = nextChar();
1426            final TypeAnnotationPosition position =
1427                TypeAnnotationPosition.methodRef(readTypePath());
1428            position.offset = offset;
1429            return position;
1430        }
1431        // local variable
1432        case LOCAL_VARIABLE: {
1433            final int table_length = nextChar();
1434            final int[] newLvarOffset = new int[table_length];
1435            final int[] newLvarLength = new int[table_length];
1436            final int[] newLvarIndex = new int[table_length];
1437
1438            for (int i = 0; i < table_length; ++i) {
1439                newLvarOffset[i] = nextChar();
1440                newLvarLength[i] = nextChar();
1441                newLvarIndex[i] = nextChar();
1442            }
1443
1444            final TypeAnnotationPosition position =
1445                    TypeAnnotationPosition.localVariable(readTypePath());
1446            position.lvarOffset = newLvarOffset;
1447            position.lvarLength = newLvarLength;
1448            position.lvarIndex = newLvarIndex;
1449            return position;
1450        }
1451        // resource variable
1452        case RESOURCE_VARIABLE: {
1453            final int table_length = nextChar();
1454            final int[] newLvarOffset = new int[table_length];
1455            final int[] newLvarLength = new int[table_length];
1456            final int[] newLvarIndex = new int[table_length];
1457
1458            for (int i = 0; i < table_length; ++i) {
1459                newLvarOffset[i] = nextChar();
1460                newLvarLength[i] = nextChar();
1461                newLvarIndex[i] = nextChar();
1462            }
1463
1464            final TypeAnnotationPosition position =
1465                    TypeAnnotationPosition.resourceVariable(readTypePath());
1466            position.lvarOffset = newLvarOffset;
1467            position.lvarLength = newLvarLength;
1468            position.lvarIndex = newLvarIndex;
1469            return position;
1470        }
1471        // exception parameter
1472        case EXCEPTION_PARAMETER: {
1473            final int exception_index = nextChar();
1474            final TypeAnnotationPosition position =
1475                TypeAnnotationPosition.exceptionParameter(readTypePath());
1476            position.setExceptionIndex(exception_index);
1477            return position;
1478        }
1479        // method receiver
1480        case METHOD_RECEIVER:
1481            return TypeAnnotationPosition.methodReceiver(readTypePath());
1482        // type parameter
1483        case CLASS_TYPE_PARAMETER: {
1484            final int parameter_index = nextByte();
1485            return TypeAnnotationPosition
1486                .typeParameter(readTypePath(), parameter_index);
1487        }
1488        case METHOD_TYPE_PARAMETER: {
1489            final int parameter_index = nextByte();
1490            return TypeAnnotationPosition
1491                .methodTypeParameter(readTypePath(), parameter_index);
1492        }
1493        // type parameter bound
1494        case CLASS_TYPE_PARAMETER_BOUND: {
1495            final int parameter_index = nextByte();
1496            final int bound_index = nextByte();
1497            return TypeAnnotationPosition
1498                .typeParameterBound(readTypePath(), parameter_index,
1499                                    bound_index);
1500        }
1501        case METHOD_TYPE_PARAMETER_BOUND: {
1502            final int parameter_index = nextByte();
1503            final int bound_index = nextByte();
1504            return TypeAnnotationPosition
1505                .methodTypeParameterBound(readTypePath(), parameter_index,
1506                                          bound_index);
1507        }
1508        // class extends or implements clause
1509        case CLASS_EXTENDS: {
1510            final int type_index = nextChar();
1511            return TypeAnnotationPosition.classExtends(readTypePath(),
1512                                                       type_index);
1513        }
1514        // throws
1515        case THROWS: {
1516            final int type_index = nextChar();
1517            return TypeAnnotationPosition.methodThrows(readTypePath(),
1518                                                       type_index);
1519        }
1520        // method parameter
1521        case METHOD_FORMAL_PARAMETER: {
1522            final int parameter_index = nextByte();
1523            return TypeAnnotationPosition.methodParameter(readTypePath(),
1524                                                          parameter_index);
1525        }
1526        // type cast
1527        case CAST: {
1528            final int offset = nextChar();
1529            final int type_index = nextByte();
1530            final TypeAnnotationPosition position =
1531                TypeAnnotationPosition.typeCast(readTypePath(), type_index);
1532            position.offset = offset;
1533            return position;
1534        }
1535        // method/constructor/reference type argument
1536        case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: {
1537            final int offset = nextChar();
1538            final int type_index = nextByte();
1539            final TypeAnnotationPosition position = TypeAnnotationPosition
1540                .constructorInvocationTypeArg(readTypePath(), type_index);
1541            position.offset = offset;
1542            return position;
1543        }
1544        case METHOD_INVOCATION_TYPE_ARGUMENT: {
1545            final int offset = nextChar();
1546            final int type_index = nextByte();
1547            final TypeAnnotationPosition position = TypeAnnotationPosition
1548                .methodInvocationTypeArg(readTypePath(), type_index);
1549            position.offset = offset;
1550            return position;
1551        }
1552        case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: {
1553            final int offset = nextChar();
1554            final int type_index = nextByte();
1555            final TypeAnnotationPosition position = TypeAnnotationPosition
1556                .constructorRefTypeArg(readTypePath(), type_index);
1557            position.offset = offset;
1558            return position;
1559        }
1560        case METHOD_REFERENCE_TYPE_ARGUMENT: {
1561            final int offset = nextChar();
1562            final int type_index = nextByte();
1563            final TypeAnnotationPosition position = TypeAnnotationPosition
1564                .methodRefTypeArg(readTypePath(), type_index);
1565            position.offset = offset;
1566            return position;
1567        }
1568        // We don't need to worry about these
1569        case METHOD_RETURN:
1570            return TypeAnnotationPosition.methodReturn(readTypePath());
1571        case FIELD:
1572            return TypeAnnotationPosition.field(readTypePath());
1573        case UNKNOWN:
1574            throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!");
1575        default:
1576            throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + type);
1577        }
1578    }
1579
1580    List<TypeAnnotationPosition.TypePathEntry> readTypePath() {
1581        int len = nextByte();
1582        ListBuffer<Integer> loc = new ListBuffer<>();
1583        for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i)
1584            loc = loc.append(nextByte());
1585
1586        return TypeAnnotationPosition.getTypePathFromBinary(loc.toList());
1587
1588    }
1589
1590    Attribute readAttributeValue() {
1591        char c = (char) buf[bp++];
1592        switch (c) {
1593        case 'B':
1594            return new Attribute.Constant(syms.byteType, readPool(nextChar()));
1595        case 'C':
1596            return new Attribute.Constant(syms.charType, readPool(nextChar()));
1597        case 'D':
1598            return new Attribute.Constant(syms.doubleType, readPool(nextChar()));
1599        case 'F':
1600            return new Attribute.Constant(syms.floatType, readPool(nextChar()));
1601        case 'I':
1602            return new Attribute.Constant(syms.intType, readPool(nextChar()));
1603        case 'J':
1604            return new Attribute.Constant(syms.longType, readPool(nextChar()));
1605        case 'S':
1606            return new Attribute.Constant(syms.shortType, readPool(nextChar()));
1607        case 'Z':
1608            return new Attribute.Constant(syms.booleanType, readPool(nextChar()));
1609        case 's':
1610            return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString());
1611        case 'e':
1612            return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar()));
1613        case 'c':
1614            return new Attribute.Class(types, readTypeOrClassSymbol(nextChar()));
1615        case '[': {
1616            int n = nextChar();
1617            ListBuffer<Attribute> l = new ListBuffer<>();
1618            for (int i=0; i<n; i++)
1619                l.append(readAttributeValue());
1620            return new ArrayAttributeProxy(l.toList());
1621        }
1622        case '@':
1623            return readCompoundAnnotation();
1624        default:
1625            throw new AssertionError("unknown annotation tag '" + c + "'");
1626        }
1627    }
1628
1629    interface ProxyVisitor extends Attribute.Visitor {
1630        void visitEnumAttributeProxy(EnumAttributeProxy proxy);
1631        void visitArrayAttributeProxy(ArrayAttributeProxy proxy);
1632        void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy);
1633    }
1634
1635    static class EnumAttributeProxy extends Attribute {
1636        Type enumType;
1637        Name enumerator;
1638        public EnumAttributeProxy(Type enumType, Name enumerator) {
1639            super(null);
1640            this.enumType = enumType;
1641            this.enumerator = enumerator;
1642        }
1643        public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); }
1644        @Override @DefinedBy(Api.LANGUAGE_MODEL)
1645        public String toString() {
1646            return "/*proxy enum*/" + enumType + "." + enumerator;
1647        }
1648    }
1649
1650    static class ArrayAttributeProxy extends Attribute {
1651        List<Attribute> values;
1652        ArrayAttributeProxy(List<Attribute> values) {
1653            super(null);
1654            this.values = values;
1655        }
1656        public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); }
1657        @Override @DefinedBy(Api.LANGUAGE_MODEL)
1658        public String toString() {
1659            return "{" + values + "}";
1660        }
1661    }
1662
1663    /** A temporary proxy representing a compound attribute.
1664     */
1665    static class CompoundAnnotationProxy extends Attribute {
1666        final List<Pair<Name,Attribute>> values;
1667        public CompoundAnnotationProxy(Type type,
1668                                      List<Pair<Name,Attribute>> values) {
1669            super(type);
1670            this.values = values;
1671        }
1672        public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); }
1673        @Override @DefinedBy(Api.LANGUAGE_MODEL)
1674        public String toString() {
1675            StringBuilder buf = new StringBuilder();
1676            buf.append("@");
1677            buf.append(type.tsym.getQualifiedName());
1678            buf.append("/*proxy*/{");
1679            boolean first = true;
1680            for (List<Pair<Name,Attribute>> v = values;
1681                 v.nonEmpty(); v = v.tail) {
1682                Pair<Name,Attribute> value = v.head;
1683                if (!first) buf.append(",");
1684                first = false;
1685                buf.append(value.fst);
1686                buf.append("=");
1687                buf.append(value.snd);
1688            }
1689            buf.append("}");
1690            return buf.toString();
1691        }
1692    }
1693
1694    /** A temporary proxy representing a type annotation.
1695     */
1696    static class TypeAnnotationProxy {
1697        final CompoundAnnotationProxy compound;
1698        final TypeAnnotationPosition position;
1699        public TypeAnnotationProxy(CompoundAnnotationProxy compound,
1700                TypeAnnotationPosition position) {
1701            this.compound = compound;
1702            this.position = position;
1703        }
1704    }
1705
1706    class AnnotationDeproxy implements ProxyVisitor {
1707        private ClassSymbol requestingOwner = currentOwner.kind == MTH
1708            ? currentOwner.enclClass() : (ClassSymbol)currentOwner;
1709
1710        List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) {
1711            // also must fill in types!!!!
1712            ListBuffer<Attribute.Compound> buf = new ListBuffer<>();
1713            for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) {
1714                buf.append(deproxyCompound(l.head));
1715            }
1716            return buf.toList();
1717        }
1718
1719        Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) {
1720            ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf = new ListBuffer<>();
1721            for (List<Pair<Name,Attribute>> l = a.values;
1722                 l.nonEmpty();
1723                 l = l.tail) {
1724                MethodSymbol meth = findAccessMethod(a.type, l.head.fst);
1725                buf.append(new Pair<>(meth, deproxy(meth.type.getReturnType(), l.head.snd)));
1726            }
1727            return new Attribute.Compound(a.type, buf.toList());
1728        }
1729
1730        MethodSymbol findAccessMethod(Type container, Name name) {
1731            CompletionFailure failure = null;
1732            try {
1733                for (Symbol sym : container.tsym.members().getSymbolsByName(name)) {
1734                    if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0)
1735                        return (MethodSymbol) sym;
1736                }
1737            } catch (CompletionFailure ex) {
1738                failure = ex;
1739            }
1740            // The method wasn't found: emit a warning and recover
1741            JavaFileObject prevSource = log.useSource(requestingOwner.classfile);
1742            try {
1743                if (failure == null) {
1744                    log.warning("annotation.method.not.found",
1745                                container,
1746                                name);
1747                } else {
1748                    log.warning("annotation.method.not.found.reason",
1749                                container,
1750                                name,
1751                                failure.getDetailValue());//diagnostic, if present
1752                }
1753            } finally {
1754                log.useSource(prevSource);
1755            }
1756            // Construct a new method type and symbol.  Use bottom
1757            // type (typeof null) as return type because this type is
1758            // a subtype of all reference types and can be converted
1759            // to primitive types by unboxing.
1760            MethodType mt = new MethodType(List.<Type>nil(),
1761                                           syms.botType,
1762                                           List.<Type>nil(),
1763                                           syms.methodClass);
1764            return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym);
1765        }
1766
1767        Attribute result;
1768        Type type;
1769        Attribute deproxy(Type t, Attribute a) {
1770            Type oldType = type;
1771            try {
1772                type = t;
1773                a.accept(this);
1774                return result;
1775            } finally {
1776                type = oldType;
1777            }
1778        }
1779
1780        // implement Attribute.Visitor below
1781
1782        public void visitConstant(Attribute.Constant value) {
1783            // assert value.type == type;
1784            result = value;
1785        }
1786
1787        public void visitClass(Attribute.Class clazz) {
1788            result = clazz;
1789        }
1790
1791        public void visitEnum(Attribute.Enum e) {
1792            throw new AssertionError(); // shouldn't happen
1793        }
1794
1795        public void visitCompound(Attribute.Compound compound) {
1796            throw new AssertionError(); // shouldn't happen
1797        }
1798
1799        public void visitArray(Attribute.Array array) {
1800            throw new AssertionError(); // shouldn't happen
1801        }
1802
1803        public void visitError(Attribute.Error e) {
1804            throw new AssertionError(); // shouldn't happen
1805        }
1806
1807        public void visitEnumAttributeProxy(EnumAttributeProxy proxy) {
1808            // type.tsym.flatName() should == proxy.enumFlatName
1809            TypeSymbol enumTypeSym = proxy.enumType.tsym;
1810            VarSymbol enumerator = null;
1811            CompletionFailure failure = null;
1812            try {
1813                for (Symbol sym : enumTypeSym.members().getSymbolsByName(proxy.enumerator)) {
1814                    if (sym.kind == VAR) {
1815                        enumerator = (VarSymbol)sym;
1816                        break;
1817                    }
1818                }
1819            }
1820            catch (CompletionFailure ex) {
1821                failure = ex;
1822            }
1823            if (enumerator == null) {
1824                if (failure != null) {
1825                    log.warning("unknown.enum.constant.reason",
1826                              currentClassFile, enumTypeSym, proxy.enumerator,
1827                              failure.getDiagnostic());
1828                } else {
1829                    log.warning("unknown.enum.constant",
1830                              currentClassFile, enumTypeSym, proxy.enumerator);
1831                }
1832                result = new Attribute.Enum(enumTypeSym.type,
1833                        new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym));
1834            } else {
1835                result = new Attribute.Enum(enumTypeSym.type, enumerator);
1836            }
1837        }
1838
1839        public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) {
1840            int length = proxy.values.length();
1841            Attribute[] ats = new Attribute[length];
1842            Type elemtype = types.elemtype(type);
1843            int i = 0;
1844            for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) {
1845                ats[i++] = deproxy(elemtype, p.head);
1846            }
1847            result = new Attribute.Array(type, ats);
1848        }
1849
1850        public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) {
1851            result = deproxyCompound(proxy);
1852        }
1853    }
1854
1855    class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Worker {
1856        final MethodSymbol sym;
1857        final Attribute value;
1858        final JavaFileObject classFile = currentClassFile;
1859        @Override
1860        public String toString() {
1861            return " ClassReader store default for " + sym.owner + "." + sym + " is " + value;
1862        }
1863        AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) {
1864            this.sym = sym;
1865            this.value = value;
1866        }
1867        // implement Annotate.Worker.run()
1868        public void run() {
1869            JavaFileObject previousClassFile = currentClassFile;
1870            try {
1871                // Reset the interim value set earlier in
1872                // attachAnnotationDefault().
1873                sym.defaultValue = null;
1874                currentClassFile = classFile;
1875                sym.defaultValue = deproxy(sym.type.getReturnType(), value);
1876            } finally {
1877                currentClassFile = previousClassFile;
1878            }
1879        }
1880    }
1881
1882    class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Worker {
1883        final Symbol sym;
1884        final List<CompoundAnnotationProxy> l;
1885        final JavaFileObject classFile;
1886        @Override
1887        public String toString() {
1888            return " ClassReader annotate " + sym.owner + "." + sym + " with " + l;
1889        }
1890        AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) {
1891            this.sym = sym;
1892            this.l = l;
1893            this.classFile = currentClassFile;
1894        }
1895        // implement Annotate.Worker.run()
1896        public void run() {
1897            JavaFileObject previousClassFile = currentClassFile;
1898            try {
1899                currentClassFile = classFile;
1900                List<Attribute.Compound> newList = deproxyCompoundList(l);
1901                if (sym.annotationsPendingCompletion()) {
1902                    sym.setDeclarationAttributes(newList);
1903                } else {
1904                    sym.appendAttributes(newList);
1905                }
1906            } finally {
1907                currentClassFile = previousClassFile;
1908            }
1909        }
1910    }
1911
1912    class TypeAnnotationCompleter extends AnnotationCompleter {
1913
1914        List<TypeAnnotationProxy> proxies;
1915
1916        TypeAnnotationCompleter(Symbol sym,
1917                List<TypeAnnotationProxy> proxies) {
1918            super(sym, List.<CompoundAnnotationProxy>nil());
1919            this.proxies = proxies;
1920        }
1921
1922        List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) {
1923            ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
1924            for (TypeAnnotationProxy proxy: proxies) {
1925                Attribute.Compound compound = deproxyCompound(proxy.compound);
1926                Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position);
1927                buf.add(typeCompound);
1928            }
1929            return buf.toList();
1930        }
1931
1932        @Override
1933        public void run() {
1934            JavaFileObject previousClassFile = currentClassFile;
1935            try {
1936                currentClassFile = classFile;
1937                List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies);
1938                sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes()));
1939            } finally {
1940                currentClassFile = previousClassFile;
1941            }
1942        }
1943    }
1944
1945
1946/************************************************************************
1947 * Reading Symbols
1948 ***********************************************************************/
1949
1950    /** Read a field.
1951     */
1952    VarSymbol readField() {
1953        long flags = adjustFieldFlags(nextChar());
1954        Name name = readName(nextChar());
1955        Type type = readType(nextChar());
1956        VarSymbol v = new VarSymbol(flags, name, type, currentOwner);
1957        readMemberAttrs(v);
1958        return v;
1959    }
1960
1961    /** Read a method.
1962     */
1963    MethodSymbol readMethod() {
1964        long flags = adjustMethodFlags(nextChar());
1965        Name name = readName(nextChar());
1966        Type type = readType(nextChar());
1967        if (currentOwner.isInterface() &&
1968                (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) {
1969            if (majorVersion > Version.V52.major ||
1970                    (majorVersion == Version.V52.major && minorVersion >= Version.V52.minor)) {
1971                if ((flags & STATIC) == 0) {
1972                    currentOwner.flags_field |= DEFAULT;
1973                    flags |= DEFAULT | ABSTRACT;
1974                }
1975            } else {
1976                //protect against ill-formed classfiles
1977                throw badClassFile((flags & STATIC) == 0 ? "invalid.default.interface" : "invalid.static.interface",
1978                                   Integer.toString(majorVersion),
1979                                   Integer.toString(minorVersion));
1980            }
1981        }
1982        if (name == names.init && currentOwner.hasOuterInstance()) {
1983            // Sometimes anonymous classes don't have an outer
1984            // instance, however, there is no reliable way to tell so
1985            // we never strip this$n
1986            if (!currentOwner.name.isEmpty())
1987                type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()),
1988                                      type.getReturnType(),
1989                                      type.getThrownTypes(),
1990                                      syms.methodClass);
1991        }
1992        MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner);
1993        if (types.isSignaturePolymorphic(m)) {
1994            m.flags_field |= SIGNATURE_POLYMORPHIC;
1995        }
1996        if (saveParameterNames)
1997            initParameterNames(m);
1998        Symbol prevOwner = currentOwner;
1999        currentOwner = m;
2000        try {
2001            readMemberAttrs(m);
2002        } finally {
2003            currentOwner = prevOwner;
2004        }
2005        if (saveParameterNames)
2006            setParameterNames(m, type);
2007        return m;
2008    }
2009
2010    private List<Type> adjustMethodParams(long flags, List<Type> args) {
2011        boolean isVarargs = (flags & VARARGS) != 0;
2012        if (isVarargs) {
2013            Type varargsElem = args.last();
2014            ListBuffer<Type> adjustedArgs = new ListBuffer<>();
2015            for (Type t : args) {
2016                adjustedArgs.append(t != varargsElem ?
2017                    t :
2018                    ((ArrayType)t).makeVarargs());
2019            }
2020            args = adjustedArgs.toList();
2021        }
2022        return args.tail;
2023    }
2024
2025    /**
2026     * Init the parameter names array.
2027     * Parameter names are currently inferred from the names in the
2028     * LocalVariableTable attributes of a Code attribute.
2029     * (Note: this means parameter names are currently not available for
2030     * methods without a Code attribute.)
2031     * This method initializes an array in which to store the name indexes
2032     * of parameter names found in LocalVariableTable attributes. It is
2033     * slightly supersized to allow for additional slots with a start_pc of 0.
2034     */
2035    void initParameterNames(MethodSymbol sym) {
2036        // make allowance for synthetic parameters.
2037        final int excessSlots = 4;
2038        int expectedParameterSlots =
2039                Code.width(sym.type.getParameterTypes()) + excessSlots;
2040        if (parameterNameIndices == null
2041                || parameterNameIndices.length < expectedParameterSlots) {
2042            parameterNameIndices = new int[expectedParameterSlots];
2043        } else
2044            Arrays.fill(parameterNameIndices, 0);
2045        haveParameterNameIndices = false;
2046        sawMethodParameters = false;
2047    }
2048
2049    /**
2050     * Set the parameter names for a symbol from the name index in the
2051     * parameterNameIndicies array. The type of the symbol may have changed
2052     * while reading the method attributes (see the Signature attribute).
2053     * This may be because of generic information or because anonymous
2054     * synthetic parameters were added.   The original type (as read from
2055     * the method descriptor) is used to help guess the existence of
2056     * anonymous synthetic parameters.
2057     * On completion, sym.savedParameter names will either be null (if
2058     * no parameter names were found in the class file) or will be set to a
2059     * list of names, one per entry in sym.type.getParameterTypes, with
2060     * any missing names represented by the empty name.
2061     */
2062    void setParameterNames(MethodSymbol sym, Type jvmType) {
2063        // if no names were found in the class file, there's nothing more to do
2064        if (!haveParameterNameIndices)
2065            return;
2066        // If we get parameter names from MethodParameters, then we
2067        // don't need to skip.
2068        int firstParam = 0;
2069        if (!sawMethodParameters) {
2070            firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
2071            // the code in readMethod may have skipped the first
2072            // parameter when setting up the MethodType. If so, we
2073            // make a corresponding allowance here for the position of
2074            // the first parameter.  Note that this assumes the
2075            // skipped parameter has a width of 1 -- i.e. it is not
2076        // a double width type (long or double.)
2077        if (sym.name == names.init && currentOwner.hasOuterInstance()) {
2078            // Sometimes anonymous classes don't have an outer
2079            // instance, however, there is no reliable way to tell so
2080            // we never strip this$n
2081            if (!currentOwner.name.isEmpty())
2082                firstParam += 1;
2083        }
2084
2085        if (sym.type != jvmType) {
2086                // reading the method attributes has caused the
2087                // symbol's type to be changed. (i.e. the Signature
2088                // attribute.)  This may happen if there are hidden
2089                // (synthetic) parameters in the descriptor, but not
2090                // in the Signature.  The position of these hidden
2091                // parameters is unspecified; for now, assume they are
2092                // at the beginning, and so skip over them. The
2093                // primary case for this is two hidden parameters
2094                // passed into Enum constructors.
2095            int skip = Code.width(jvmType.getParameterTypes())
2096                    - Code.width(sym.type.getParameterTypes());
2097            firstParam += skip;
2098        }
2099        }
2100        List<Name> paramNames = List.nil();
2101        int index = firstParam;
2102        for (Type t: sym.type.getParameterTypes()) {
2103            int nameIdx = (index < parameterNameIndices.length
2104                    ? parameterNameIndices[index] : 0);
2105            Name name = nameIdx == 0 ? names.empty : readName(nameIdx);
2106            paramNames = paramNames.prepend(name);
2107            index += Code.width(t);
2108        }
2109        sym.savedParameterNames = paramNames.reverse();
2110    }
2111
2112    /**
2113     * skip n bytes
2114     */
2115    void skipBytes(int n) {
2116        bp = bp + n;
2117    }
2118
2119    /** Skip a field or method
2120     */
2121    void skipMember() {
2122        bp = bp + 6;
2123        char ac = nextChar();
2124        for (int i = 0; i < ac; i++) {
2125            bp = bp + 2;
2126            int attrLen = nextInt();
2127            bp = bp + attrLen;
2128        }
2129    }
2130
2131    /** Enter type variables of this classtype and all enclosing ones in
2132     *  `typevars'.
2133     */
2134    protected void enterTypevars(Type t) {
2135        if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS))
2136            enterTypevars(t.getEnclosingType());
2137        for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail)
2138            typevars.enter(xs.head.tsym);
2139    }
2140
2141    protected void enterTypevars(Symbol sym) {
2142        if (sym.owner.kind == MTH) {
2143            enterTypevars(sym.owner);
2144            enterTypevars(sym.owner.owner);
2145        }
2146        enterTypevars(sym.type);
2147    }
2148
2149    /** Read contents of a given class symbol `c'. Both external and internal
2150     *  versions of an inner class are read.
2151     */
2152    void readClass(ClassSymbol c) {
2153        ClassType ct = (ClassType)c.type;
2154
2155        // allocate scope for members
2156        c.members_field = WriteableScope.create(c);
2157
2158        // prepare type variable table
2159        typevars = typevars.dup(currentOwner);
2160        if (ct.getEnclosingType().hasTag(CLASS))
2161            enterTypevars(ct.getEnclosingType());
2162
2163        // read flags, or skip if this is an inner class
2164        long flags = adjustClassFlags(nextChar());
2165        if (c.owner.kind == PCK) c.flags_field = flags;
2166
2167        // read own class name and check that it matches
2168        ClassSymbol self = readClassSymbol(nextChar());
2169        if (c != self)
2170            throw badClassFile("class.file.wrong.class",
2171                               self.flatname);
2172
2173        // class attributes must be read before class
2174        // skip ahead to read class attributes
2175        int startbp = bp;
2176        nextChar();
2177        char interfaceCount = nextChar();
2178        bp += interfaceCount * 2;
2179        char fieldCount = nextChar();
2180        for (int i = 0; i < fieldCount; i++) skipMember();
2181        char methodCount = nextChar();
2182        for (int i = 0; i < methodCount; i++) skipMember();
2183        readClassAttrs(c);
2184
2185        if (readAllOfClassFile) {
2186            for (int i = 1; i < poolObj.length; i++) readPool(i);
2187            c.pool = new Pool(poolObj.length, poolObj, types);
2188        }
2189
2190        // reset and read rest of classinfo
2191        bp = startbp;
2192        int n = nextChar();
2193        if (ct.supertype_field == null)
2194            ct.supertype_field = (n == 0)
2195                ? Type.noType
2196                : readClassSymbol(n).erasure(types);
2197        n = nextChar();
2198        List<Type> is = List.nil();
2199        for (int i = 0; i < n; i++) {
2200            Type _inter = readClassSymbol(nextChar()).erasure(types);
2201            is = is.prepend(_inter);
2202        }
2203        if (ct.interfaces_field == null)
2204            ct.interfaces_field = is.reverse();
2205
2206        Assert.check(fieldCount == nextChar());
2207        for (int i = 0; i < fieldCount; i++) enterMember(c, readField());
2208        Assert.check(methodCount == nextChar());
2209        for (int i = 0; i < methodCount; i++) enterMember(c, readMethod());
2210
2211        typevars = typevars.leave();
2212    }
2213
2214    /** Read inner class info. For each inner/outer pair allocate a
2215     *  member class.
2216     */
2217    void readInnerClasses(ClassSymbol c) {
2218        int n = nextChar();
2219        for (int i = 0; i < n; i++) {
2220            nextChar(); // skip inner class symbol
2221            ClassSymbol outer = readClassSymbol(nextChar());
2222            Name name = readName(nextChar());
2223            if (name == null) name = names.empty;
2224            long flags = adjustClassFlags(nextChar());
2225            if (outer != null) { // we have a member class
2226                if (name == names.empty)
2227                    name = names.one;
2228                ClassSymbol member = syms.enterClass(name, outer);
2229                if ((flags & STATIC) == 0) {
2230                    ((ClassType)member.type).setEnclosingType(outer.type);
2231                    if (member.erasure_field != null)
2232                        ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type));
2233                }
2234                if (c == outer) {
2235                    member.flags_field = flags;
2236                    enterMember(c, member);
2237                }
2238            }
2239        }
2240    }
2241
2242    /** Read a class definition from the bytes in buf.
2243     */
2244    private void readClassBuffer(ClassSymbol c) throws IOException {
2245        int magic = nextInt();
2246        if (magic != JAVA_MAGIC)
2247            throw badClassFile("illegal.start.of.class.file");
2248
2249        minorVersion = nextChar();
2250        majorVersion = nextChar();
2251        int maxMajor = Version.MAX().major;
2252        int maxMinor = Version.MAX().minor;
2253        if (majorVersion > maxMajor ||
2254            majorVersion * 1000 + minorVersion <
2255            Version.MIN().major * 1000 + Version.MIN().minor)
2256        {
2257            if (majorVersion == (maxMajor + 1))
2258                log.warning("big.major.version",
2259                            currentClassFile,
2260                            majorVersion,
2261                            maxMajor);
2262            else
2263                throw badClassFile("wrong.version",
2264                                   Integer.toString(majorVersion),
2265                                   Integer.toString(minorVersion),
2266                                   Integer.toString(maxMajor),
2267                                   Integer.toString(maxMinor));
2268        }
2269        else if (checkClassFile &&
2270                 majorVersion == maxMajor &&
2271                 minorVersion > maxMinor)
2272        {
2273            printCCF("found.later.version",
2274                     Integer.toString(minorVersion));
2275        }
2276        indexPool();
2277        if (signatureBuffer.length < bp) {
2278            int ns = Integer.highestOneBit(bp) << 1;
2279            signatureBuffer = new byte[ns];
2280        }
2281        readClass(c);
2282    }
2283
2284    public void readClassFile(ClassSymbol c) {
2285        currentOwner = c;
2286        currentClassFile = c.classfile;
2287        warnedAttrs.clear();
2288        filling = true;
2289        try {
2290            bp = 0;
2291            buf = readInputStream(buf, c.classfile.openInputStream());
2292            readClassBuffer(c);
2293            if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) {
2294                List<Type> missing = missingTypeVariables;
2295                List<Type> found = foundTypeVariables;
2296                missingTypeVariables = List.nil();
2297                foundTypeVariables = List.nil();
2298                filling = false;
2299                ClassType ct = (ClassType)currentOwner.type;
2300                ct.supertype_field =
2301                    types.subst(ct.supertype_field, missing, found);
2302                ct.interfaces_field =
2303                    types.subst(ct.interfaces_field, missing, found);
2304            } else if (missingTypeVariables.isEmpty() !=
2305                       foundTypeVariables.isEmpty()) {
2306                Name name = missingTypeVariables.head.tsym.name;
2307                throw badClassFile("undecl.type.var", name);
2308            }
2309        } catch (IOException ex) {
2310            throw badClassFile("unable.to.access.file", ex.getMessage());
2311        } catch (ArrayIndexOutOfBoundsException ex) {
2312            throw badClassFile("bad.class.file", c.flatname);
2313        } finally {
2314            missingTypeVariables = List.nil();
2315            foundTypeVariables = List.nil();
2316            filling = false;
2317        }
2318    }
2319    // where
2320        private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
2321            try {
2322                buf = ensureCapacity(buf, s.available());
2323                int r = s.read(buf);
2324                int bp = 0;
2325                while (r != -1) {
2326                    bp += r;
2327                    buf = ensureCapacity(buf, bp);
2328                    r = s.read(buf, bp, buf.length - bp);
2329                }
2330                return buf;
2331            } finally {
2332                try {
2333                    s.close();
2334                } catch (IOException e) {
2335                    /* Ignore any errors, as this stream may have already
2336                     * thrown a related exception which is the one that
2337                     * should be reported.
2338                     */
2339                }
2340            }
2341        }
2342        /*
2343         * ensureCapacity will increase the buffer as needed, taking note that
2344         * the new buffer will always be greater than the needed and never
2345         * exactly equal to the needed size or bp. If equal then the read (above)
2346         * will infinitely loop as buf.length - bp == 0.
2347         */
2348        private static byte[] ensureCapacity(byte[] buf, int needed) {
2349            if (buf.length <= needed) {
2350                byte[] old = buf;
2351                buf = new byte[Integer.highestOneBit(needed) << 1];
2352                System.arraycopy(old, 0, buf, 0, old.length);
2353            }
2354            return buf;
2355        }
2356
2357    /** We can only read a single class file at a time; this
2358     *  flag keeps track of when we are currently reading a class
2359     *  file.
2360     */
2361    public boolean filling = false;
2362
2363/************************************************************************
2364 * Adjusting flags
2365 ***********************************************************************/
2366
2367    long adjustFieldFlags(long flags) {
2368        return flags;
2369    }
2370
2371    long adjustMethodFlags(long flags) {
2372        if ((flags & ACC_BRIDGE) != 0) {
2373            flags &= ~ACC_BRIDGE;
2374            flags |= BRIDGE;
2375        }
2376        if ((flags & ACC_VARARGS) != 0) {
2377            flags &= ~ACC_VARARGS;
2378            flags |= VARARGS;
2379        }
2380        return flags;
2381    }
2382
2383    long adjustClassFlags(long flags) {
2384        return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded
2385    }
2386
2387    /** Output for "-checkclassfile" option.
2388     *  @param key The key to look up the correct internationalized string.
2389     *  @param arg An argument for substitution into the output string.
2390     */
2391    private void printCCF(String key, Object arg) {
2392        log.printLines(key, arg);
2393    }
2394
2395    /**
2396     * A subclass of JavaFileObject for the sourcefile attribute found in a classfile.
2397     * The attribute is only the last component of the original filename, so is unlikely
2398     * to be valid as is, so operations other than those to access the name throw
2399     * UnsupportedOperationException
2400     */
2401    private static class SourceFileObject extends BaseFileObject {
2402
2403        /** The file's name.
2404         */
2405        private Name name;
2406        private Name flatname;
2407
2408        public SourceFileObject(Name name, Name flatname) {
2409            super(null); // no file manager; never referenced for this file object
2410            this.name = name;
2411            this.flatname = flatname;
2412        }
2413
2414        @Override @DefinedBy(Api.COMPILER)
2415        public URI toUri() {
2416            try {
2417                return new URI(null, name.toString(), null);
2418            } catch (URISyntaxException e) {
2419                throw new CannotCreateUriError(name.toString(), e);
2420            }
2421        }
2422
2423        @Override @DefinedBy(Api.COMPILER)
2424        public String getName() {
2425            return name.toString();
2426        }
2427
2428        @Override
2429        public String getShortName() {
2430            return getName();
2431        }
2432
2433        @Override @DefinedBy(Api.COMPILER)
2434        public JavaFileObject.Kind getKind() {
2435            return getKind(getName());
2436        }
2437
2438        @Override @DefinedBy(Api.COMPILER)
2439        public InputStream openInputStream() {
2440            throw new UnsupportedOperationException();
2441        }
2442
2443        @Override @DefinedBy(Api.COMPILER)
2444        public OutputStream openOutputStream() {
2445            throw new UnsupportedOperationException();
2446        }
2447
2448        @Override @DefinedBy(Api.COMPILER)
2449        public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
2450            throw new UnsupportedOperationException();
2451        }
2452
2453        @Override @DefinedBy(Api.COMPILER)
2454        public Reader openReader(boolean ignoreEncodingErrors) {
2455            throw new UnsupportedOperationException();
2456        }
2457
2458        @Override @DefinedBy(Api.COMPILER)
2459        public Writer openWriter() {
2460            throw new UnsupportedOperationException();
2461        }
2462
2463        @Override @DefinedBy(Api.COMPILER)
2464        public long getLastModified() {
2465            throw new UnsupportedOperationException();
2466        }
2467
2468        @Override @DefinedBy(Api.COMPILER)
2469        public boolean delete() {
2470            throw new UnsupportedOperationException();
2471        }
2472
2473        @Override
2474        protected String inferBinaryName(Iterable<? extends Path> path) {
2475            return flatname.toString();
2476        }
2477
2478        @Override @DefinedBy(Api.COMPILER)
2479        public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) {
2480            return true; // fail-safe mode
2481        }
2482
2483        /**
2484         * Check if two file objects are equal.
2485         * SourceFileObjects are just placeholder objects for the value of a
2486         * SourceFile attribute, and do not directly represent specific files.
2487         * Two SourceFileObjects are equal if their names are equal.
2488         */
2489        @Override
2490        public boolean equals(Object other) {
2491            if (this == other)
2492                return true;
2493
2494            if (!(other instanceof SourceFileObject))
2495                return false;
2496
2497            SourceFileObject o = (SourceFileObject) other;
2498            return name.equals(o.name);
2499        }
2500
2501        @Override
2502        public int hashCode() {
2503            return name.hashCode();
2504        }
2505    }
2506}
2507