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