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