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