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