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