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