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