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