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.TRANSITIVE) && 1206 (majorVersion != Version.MAX().major || !previewClassFile) && 1207 !preview.participatesInPreview(syms, msym)) { 1208 throw badClassFile("bad.requires.flag", RequiresFlag.TRANSITIVE); 1209 } 1210 if (flags.contains(RequiresFlag.STATIC_PHASE)) { 1211 throw badClassFile("bad.requires.flag", RequiresFlag.STATIC_PHASE); 1212 } 1213 } 1214 nextChar(); // skip compiled version 1215 requires.add(new RequiresDirective(rsym, flags)); 1216 } 1217 msym.requires = requires.toList(); 1218 directives.addAll(msym.requires); 1219 1220 ListBuffer<ExportsDirective> exports = new ListBuffer<>(); 1221 int nexports = nextChar(); 1222 for (int i = 0; i < nexports; i++) { 1223 PackageSymbol p = poolReader.getPackage(nextChar()); 1224 Set<ExportsFlag> flags = readExportsFlags(nextChar()); 1225 int nto = nextChar(); 1226 List<ModuleSymbol> to; 1227 if (nto == 0) { 1228 to = null; 1229 } else { 1230 ListBuffer<ModuleSymbol> lb = new ListBuffer<>(); 1231 for (int t = 0; t < nto; t++) 1232 lb.append(poolReader.getModule(nextChar())); 1233 to = lb.toList(); 1234 } 1235 exports.add(new ExportsDirective(p, to, flags)); 1236 } 1237 msym.exports = exports.toList(); 1238 directives.addAll(msym.exports); 1239 ListBuffer<OpensDirective> opens = new ListBuffer<>(); 1240 int nopens = nextChar(); 1241 if (nopens != 0 && msym.flags.contains(ModuleFlags.OPEN)) { 1242 throw badClassFile("module.non.zero.opens", currentModule.name); 1243 } 1244 for (int i = 0; i < nopens; i++) { 1245 PackageSymbol p = poolReader.getPackage(nextChar()); 1246 Set<OpensFlag> flags = readOpensFlags(nextChar()); 1247 int nto = nextChar(); 1248 List<ModuleSymbol> to; 1249 if (nto == 0) { 1250 to = null; 1251 } else { 1252 ListBuffer<ModuleSymbol> lb = new ListBuffer<>(); 1253 for (int t = 0; t < nto; t++) 1254 lb.append(poolReader.getModule(nextChar())); 1255 to = lb.toList(); 1256 } 1257 opens.add(new OpensDirective(p, to, flags)); 1258 } 1259 msym.opens = opens.toList(); 1260 directives.addAll(msym.opens); 1261 1262 msym.directives = directives.toList(); 1263 1264 ListBuffer<InterimUsesDirective> uses = new ListBuffer<>(); 1265 int nuses = nextChar(); 1266 for (int i = 0; i < nuses; i++) { 1267 Name srvc = poolReader.peekClassName(nextChar(), this::classNameMapper); 1268 uses.add(new InterimUsesDirective(srvc)); 1269 } 1270 interimUses = uses.toList(); 1271 1272 ListBuffer<InterimProvidesDirective> provides = new ListBuffer<>(); 1273 int nprovides = nextChar(); 1274 for (int p = 0; p < nprovides; p++) { 1275 Name srvc = poolReader.peekClassName(nextChar(), this::classNameMapper); 1276 int nimpls = nextChar(); 1277 ListBuffer<Name> impls = new ListBuffer<>(); 1278 for (int i = 0; i < nimpls; i++) { 1279 impls.append(poolReader.peekClassName(nextChar(), this::classNameMapper)); 1280 provides.add(new InterimProvidesDirective(srvc, impls.toList())); 1281 } 1282 } 1283 interimProvides = provides.toList(); 1284 } 1285 } 1286 1287 private Name classNameMapper(byte[] arr, int offset, int length) throws InvalidUtfException { 1288 byte[] buf = ClassFile.internalize(arr, offset, length); 1289 try { 1290 return names.fromUtf(buf, 0, buf.length, utf8validation); 1291 } catch (InvalidUtfException e) { 1292 if (warnOnIllegalUtf8) { 1293 log.warning(Warnings.InvalidUtf8InClassfile(currentClassFile, 1294 Fragments.BadUtf8ByteSequenceAt(e.getOffset()))); 1295 return names.fromUtfLax(buf, 0, buf.length); 1296 } 1297 throw e; 1298 } 1299 } 1300 }, 1301 1302 new AttributeReader(names.ModuleResolution, V53, CLASS_ATTRIBUTE) { 1303 @Override 1304 protected boolean accepts(AttributeKind kind) { 1305 return super.accepts(kind) && allowModules; 1306 } 1307 protected void read(Symbol sym, int attrLen) { 1308 if (sym.kind == TYP && sym.owner.kind == MDL) { 1309 ModuleSymbol msym = (ModuleSymbol) sym.owner; 1310 msym.resolutionFlags.addAll(readModuleResolutionFlags(nextChar())); 1311 } 1312 } 1313 }, 1314 1315 new AttributeReader(names.Record, V58, CLASS_ATTRIBUTE) { 1316 @Override 1317 protected boolean accepts(AttributeKind kind) { 1318 return super.accepts(kind) && allowRecords; 1319 } 1320 protected void read(Symbol sym, int attrLen) { 1321 if (sym.kind == TYP) { 1322 sym.flags_field |= RECORD; 1323 } 1324 int componentCount = nextChar(); 1325 ListBuffer<RecordComponent> components = new ListBuffer<>(); 1326 for (int i = 0; i < componentCount; i++) { 1327 Name name = poolReader.getName(nextChar()); 1328 Type type = poolReader.getType(nextChar()); 1329 RecordComponent c = new RecordComponent(name, type, sym); 1330 readAttrs(c, AttributeKind.MEMBER); 1331 components.add(c); 1332 } 1333 ((ClassSymbol) sym).setRecordComponents(components.toList()); 1334 } 1335 }, 1336 new AttributeReader(names.PermittedSubclasses, V59, CLASS_ATTRIBUTE) { 1337 @Override 1338 protected boolean accepts(AttributeKind kind) { 1339 return super.accepts(kind) && allowSealedTypes; 1340 } 1341 protected void read(Symbol sym, int attrLen) { 1342 if (sym.kind == TYP) { 1343 ListBuffer<Symbol> subtypes = new ListBuffer<>(); 1344 int numberOfPermittedSubtypes = nextChar(); 1345 for (int i = 0; i < numberOfPermittedSubtypes; i++) { 1346 subtypes.add(poolReader.getClass(nextChar())); 1347 } 1348 ((ClassSymbol)sym).setPermittedSubclasses(subtypes.toList()); 1349 } 1350 } 1351 }, 1352 }; 1353 1354 for (AttributeReader r: readers) 1355 attributeReaders.put(r.name, r); 1356 } 1357 1358 protected void readEnclosingMethodAttr(Symbol sym) { 1359 // sym is a nested class with an "Enclosing Method" attribute 1360 // remove sym from it's current owners scope and place it in 1361 // the scope specified by the attribute 1362 sym.owner.members().remove(sym); 1363 ClassSymbol self = (ClassSymbol)sym; 1364 ClassSymbol c = poolReader.getClass(nextChar()); 1365 NameAndType nt = optPoolEntry(nextChar(), poolReader::getNameAndType, null); 1366 1367 if (c.members_field == null || c.kind != TYP) 1368 throw badClassFile("bad.enclosing.class", self, c); 1369 1370 MethodSymbol m = findMethod(nt, c.members_field, self.flags()); 1371 if (nt != null && m == null) 1372 throw badEnclosingMethod(self); 1373 1374 self.name = simpleBinaryName(self.flatname, c.flatname) ; 1375 self.owner = m != null ? m : c; 1376 if (self.name.isEmpty()) 1377 self.fullname = names.empty; 1378 else 1379 self.fullname = ClassSymbol.formFullName(self.name, self.owner); 1380 1381 if (m != null) { 1382 ((ClassType)sym.type).setEnclosingType(m.type); 1383 } else if ((self.flags_field & STATIC) == 0) { 1384 ((ClassType)sym.type).setEnclosingType(c.type); 1385 } else { 1386 ((ClassType)sym.type).setEnclosingType(Type.noType); 1387 } 1388 enterTypevars(self, self.type); 1389 if (!missingTypeVariables.isEmpty()) { 1390 ListBuffer<Type> typeVars = new ListBuffer<>(); 1391 for (Type typevar : missingTypeVariables) { 1392 typeVars.append(findTypeVar(typevar.tsym.name)); 1393 } 1394 foundTypeVariables = typeVars.toList(); 1395 } else { 1396 foundTypeVariables = List.nil(); 1397 } 1398 } 1399 1400 // See java.lang.Class 1401 private Name simpleBinaryName(Name self, Name enclosing) { 1402 if (!self.startsWith(enclosing)) { 1403 throw badClassFile("bad.enclosing.method", self); 1404 } 1405 1406 String simpleBinaryName = self.toString().substring(enclosing.toString().length()); 1407 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$') 1408 throw badClassFile("bad.enclosing.method", self); 1409 int index = 1; 1410 while (index < simpleBinaryName.length() && 1411 isAsciiDigit(simpleBinaryName.charAt(index))) 1412 index++; 1413 return names.fromString(simpleBinaryName.substring(index)); 1414 } 1415 1416 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) { 1417 if (nt == null) 1418 return null; 1419 1420 MethodType type = nt.type.asMethodType(); 1421 1422 for (Symbol sym : scope.getSymbolsByName(nt.name)) { 1423 if (sym.kind == MTH && isSameBinaryType(sym.type.asMethodType(), type)) 1424 return (MethodSymbol)sym; 1425 } 1426 1427 if (nt.name != names.init) 1428 // not a constructor 1429 return null; 1430 if ((flags & INTERFACE) != 0) 1431 // no enclosing instance 1432 return null; 1433 if (nt.type.getParameterTypes().isEmpty()) 1434 // no parameters 1435 return null; 1436 1437 // A constructor of an inner class. 1438 // Remove the first argument (the enclosing instance) 1439 nt = new NameAndType(nt.name, new MethodType(nt.type.getParameterTypes().tail, 1440 nt.type.getReturnType(), 1441 nt.type.getThrownTypes(), 1442 syms.methodClass)); 1443 // Try searching again 1444 return findMethod(nt, scope, flags); 1445 } 1446 1447 /** Similar to Types.isSameType but avoids completion */ 1448 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) { 1449 List<Type> types1 = types.erasure(mt1.getParameterTypes()) 1450 .prepend(types.erasure(mt1.getReturnType())); 1451 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType()); 1452 while (!types1.isEmpty() && !types2.isEmpty()) { 1453 if (types1.head.tsym != types2.head.tsym) 1454 return false; 1455 types1 = types1.tail; 1456 types2 = types2.tail; 1457 } 1458 return types1.isEmpty() && types2.isEmpty(); 1459 } 1460 1461 /** 1462 * Character.isDigit answers <tt>true</tt> to some non-ascii 1463 * digits. This one does not. <b>copied from java.lang.Class</b> 1464 */ 1465 private static boolean isAsciiDigit(char c) { 1466 return '0' <= c && c <= '9'; 1467 } 1468 1469 /** Read member attributes. 1470 */ 1471 void readMemberAttrs(Symbol sym) { 1472 readAttrs(sym, AttributeKind.MEMBER); 1473 } 1474 1475 void readAttrs(Symbol sym, AttributeKind kind) { 1476 char ac = nextChar(); 1477 for (int i = 0; i < ac; i++) { 1478 Name attrName = poolReader.getName(nextChar()); 1479 int attrLen = nextInt(); 1480 AttributeReader r = attributeReaders.get(attrName); 1481 if (r != null && r.accepts(kind)) 1482 r.read(sym, attrLen); 1483 else { 1484 bp = bp + attrLen; 1485 } 1486 } 1487 } 1488 1489 private boolean readingClassAttr = false; 1490 private List<Type> missingTypeVariables = List.nil(); 1491 private List<Type> foundTypeVariables = List.nil(); 1492 1493 /** Read class attributes. 1494 */ 1495 void readClassAttrs(ClassSymbol c) { 1496 readAttrs(c, AttributeKind.CLASS); 1497 } 1498 1499 /** Read code block. 1500 */ 1501 Code readCode(Symbol owner) { 1502 nextChar(); // max_stack 1503 nextChar(); // max_locals 1504 final int code_length = nextInt(); 1505 bp += code_length; 1506 final char exception_table_length = nextChar(); 1507 bp += exception_table_length * 8; 1508 readMemberAttrs(owner); 1509 return null; 1510 } 1511 1512 /* ********************************************************************** 1513 * Reading Java-language annotations 1514 ***********************************************************************/ 1515 1516 /** 1517 * Save annotations. 1518 */ 1519 List<CompoundAnnotationProxy> readAnnotations() { 1520 int numAttributes = nextChar(); 1521 ListBuffer<CompoundAnnotationProxy> annotations = new ListBuffer<>(); 1522 for (int i = 0; i < numAttributes; i++) { 1523 annotations.append(readCompoundAnnotation()); 1524 } 1525 return annotations.toList(); 1526 } 1527 1528 /** Attach annotations. 1529 */ 1530 void attachAnnotations(final Symbol sym) { 1531 attachAnnotations(sym, readAnnotations()); 1532 } 1533 1534 /** 1535 * Attach annotations. 1536 */ 1537 void attachAnnotations(final Symbol sym, List<CompoundAnnotationProxy> annotations) { 1538 if (annotations.isEmpty()) { 1539 return; 1540 } 1541 ListBuffer<CompoundAnnotationProxy> proxies = new ListBuffer<>(); 1542 for (CompoundAnnotationProxy proxy : annotations) { 1543 if (proxy.type.tsym.flatName() == syms.proprietaryType.tsym.flatName()) 1544 sym.flags_field |= PROPRIETARY; 1545 else if (proxy.type.tsym.flatName() == syms.profileType.tsym.flatName()) { 1546 if (profile != Profile.DEFAULT) { 1547 for (Pair<Name, Attribute> v : proxy.values) { 1548 if (v.fst == names.value && v.snd instanceof Attribute.Constant constant) { 1549 if (constant.type == syms.intType && ((Integer) constant.value) > profile.value) { 1550 sym.flags_field |= NOT_IN_PROFILE; 1551 } 1552 } 1553 } 1554 } 1555 } else if (proxy.type.tsym.flatName() == syms.previewFeatureInternalType.tsym.flatName()) { 1556 sym.flags_field |= PREVIEW_API; 1557 setFlagIfAttributeTrue(proxy, sym, names.reflective, PREVIEW_REFLECTIVE); 1558 } else if (proxy.type.tsym.flatName() == syms.valueBasedInternalType.tsym.flatName()) { 1559 Assert.check(sym.kind == TYP); 1560 sym.flags_field |= VALUE_BASED; 1561 } else if (proxy.type.tsym.flatName() == syms.restrictedInternalType.tsym.flatName()) { 1562 Assert.check(sym.kind == MTH); 1563 sym.flags_field |= RESTRICTED; 1564 } else { 1565 if (proxy.type.tsym == syms.annotationTargetType.tsym) { 1566 target = proxy; 1567 } else if (proxy.type.tsym == syms.repeatableType.tsym) { 1568 repeatable = proxy; 1569 } else if (proxy.type.tsym == syms.deprecatedType.tsym) { 1570 sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION); 1571 setFlagIfAttributeTrue(proxy, sym, names.forRemoval, DEPRECATED_REMOVAL); 1572 } else if (proxy.type.tsym == syms.previewFeatureType.tsym) { 1573 sym.flags_field |= PREVIEW_API; 1574 setFlagIfAttributeTrue(proxy, sym, names.reflective, PREVIEW_REFLECTIVE); 1575 } else if (proxy.type.tsym == syms.valueBasedType.tsym && sym.kind == TYP) { 1576 sym.flags_field |= VALUE_BASED; 1577 } else if (proxy.type.tsym == syms.restrictedType.tsym) { 1578 Assert.check(sym.kind == MTH); 1579 sym.flags_field |= RESTRICTED; 1580 } 1581 proxies.append(proxy); 1582 } 1583 } 1584 annotate.normal(new AnnotationCompleter(sym, proxies.toList())); 1585 } 1586 //where: 1587 private void setFlagIfAttributeTrue(CompoundAnnotationProxy proxy, Symbol sym, Name attribute, long flag) { 1588 for (Pair<Name, Attribute> v : proxy.values) { 1589 if (v.fst == attribute && v.snd instanceof Attribute.Constant constant) { 1590 if (constant.type == syms.booleanType && ((Integer) constant.value) != 0) { 1591 sym.flags_field |= flag; 1592 } 1593 } 1594 } 1595 } 1596 1597 /** Read parameter annotations. 1598 */ 1599 void readParameterAnnotations(Symbol meth) { 1600 int numParameters; 1601 try { 1602 numParameters = buf.getByte(bp++) & 0xFF; 1603 } catch (UnderflowException e) { 1604 throw badClassFile(Fragments.BadClassTruncatedAtOffset(e.getLength())); 1605 } 1606 if (parameterAnnotations == null) { 1607 parameterAnnotations = new ParameterAnnotations[numParameters]; 1608 } else if (parameterAnnotations.length != numParameters) { 1609 //the RuntimeVisibleParameterAnnotations and RuntimeInvisibleParameterAnnotations 1610 //provide annotations for a different number of parameters, ignore: 1611 lint.logIfEnabled(LintWarnings.RuntimeVisibleInvisibleParamAnnotationsMismatch(currentClassFile)); 1612 for (int pnum = 0; pnum < numParameters; pnum++) { 1613 readAnnotations(); 1614 } 1615 parameterAnnotations = null; 1616 return ; 1617 } 1618 for (int pnum = 0; pnum < numParameters; pnum++) { 1619 if (parameterAnnotations[pnum] == null) { 1620 parameterAnnotations[pnum] = new ParameterAnnotations(); 1621 } 1622 parameterAnnotations[pnum].add(readAnnotations()); 1623 } 1624 } 1625 1626 void attachTypeAnnotations(final Symbol sym) { 1627 int numAttributes = nextChar(); 1628 if (numAttributes != 0) { 1629 ListBuffer<TypeAnnotationProxy> proxies = new ListBuffer<>(); 1630 for (int i = 0; i < numAttributes; i++) 1631 proxies.append(readTypeAnnotation()); 1632 annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList())); 1633 } 1634 } 1635 1636 /** Attach the default value for an annotation element. 1637 */ 1638 void attachAnnotationDefault(final Symbol sym) { 1639 final MethodSymbol meth = (MethodSymbol)sym; // only on methods 1640 final Attribute value = readAttributeValue(); 1641 1642 // The default value is set later during annotation. It might 1643 // be the case that the Symbol sym is annotated _after_ the 1644 // repeating instances that depend on this default value, 1645 // because of this we set an interim value that tells us this 1646 // element (most likely) has a default. 1647 // 1648 // Set interim value for now, reset just before we do this 1649 // properly at annotate time. 1650 meth.defaultValue = value; 1651 annotate.normal(new AnnotationDefaultCompleter(meth, value)); 1652 } 1653 1654 Type readTypeOrClassSymbol(int i) { 1655 return readTypeToProxy(i); 1656 } 1657 Type readTypeToProxy(int i) { 1658 if (currentModule.module_info == currentOwner) { 1659 return new ProxyType(i); 1660 } else { 1661 return poolReader.getType(i); 1662 } 1663 } 1664 1665 CompoundAnnotationProxy readCompoundAnnotation() { 1666 Type t; 1667 if (currentModule.module_info == currentOwner) { 1668 int cpIndex = nextChar(); 1669 t = new ProxyType(cpIndex); 1670 } else { 1671 t = readTypeOrClassSymbol(nextChar()); 1672 } 1673 int numFields = nextChar(); 1674 ListBuffer<Pair<Name,Attribute>> pairs = new ListBuffer<>(); 1675 for (int i=0; i<numFields; i++) { 1676 Name name = poolReader.getName(nextChar()); 1677 Attribute value = readAttributeValue(); 1678 pairs.append(new Pair<>(name, value)); 1679 } 1680 return new CompoundAnnotationProxy(t, pairs.toList()); 1681 } 1682 1683 TypeAnnotationProxy readTypeAnnotation() { 1684 TypeAnnotationPosition position = readPosition(); 1685 CompoundAnnotationProxy proxy = readCompoundAnnotation(); 1686 1687 return new TypeAnnotationProxy(proxy, position); 1688 } 1689 1690 TypeAnnotationPosition readPosition() { 1691 int tag = nextByte(); // TargetType tag is a byte 1692 1693 if (!TargetType.isValidTargetTypeValue(tag)) 1694 throw badClassFile("bad.type.annotation.value", String.format("0x%02X", tag)); 1695 1696 TargetType type = TargetType.fromTargetTypeValue(tag); 1697 1698 switch (type) { 1699 // instanceof 1700 case INSTANCEOF: { 1701 final int offset = nextChar(); 1702 final TypeAnnotationPosition position = 1703 TypeAnnotationPosition.instanceOf(readTypePath()); 1704 position.offset = offset; 1705 return position; 1706 } 1707 // new expression 1708 case NEW: { 1709 final int offset = nextChar(); 1710 final TypeAnnotationPosition position = 1711 TypeAnnotationPosition.newObj(readTypePath()); 1712 position.offset = offset; 1713 return position; 1714 } 1715 // constructor/method reference receiver 1716 case CONSTRUCTOR_REFERENCE: { 1717 final int offset = nextChar(); 1718 final TypeAnnotationPosition position = 1719 TypeAnnotationPosition.constructorRef(readTypePath()); 1720 position.offset = offset; 1721 return position; 1722 } 1723 case METHOD_REFERENCE: { 1724 final int offset = nextChar(); 1725 final TypeAnnotationPosition position = 1726 TypeAnnotationPosition.methodRef(readTypePath()); 1727 position.offset = offset; 1728 return position; 1729 } 1730 // local variable 1731 case LOCAL_VARIABLE: { 1732 final int table_length = nextChar(); 1733 final int[] newLvarOffset = new int[table_length]; 1734 final int[] newLvarLength = new int[table_length]; 1735 final int[] newLvarIndex = new int[table_length]; 1736 1737 for (int i = 0; i < table_length; ++i) { 1738 newLvarOffset[i] = nextChar(); 1739 newLvarLength[i] = nextChar(); 1740 newLvarIndex[i] = nextChar(); 1741 } 1742 1743 final TypeAnnotationPosition position = 1744 TypeAnnotationPosition.localVariable(readTypePath()); 1745 position.lvarOffset = newLvarOffset; 1746 position.lvarLength = newLvarLength; 1747 position.lvarIndex = newLvarIndex; 1748 return position; 1749 } 1750 // resource variable 1751 case RESOURCE_VARIABLE: { 1752 final int table_length = nextChar(); 1753 final int[] newLvarOffset = new int[table_length]; 1754 final int[] newLvarLength = new int[table_length]; 1755 final int[] newLvarIndex = new int[table_length]; 1756 1757 for (int i = 0; i < table_length; ++i) { 1758 newLvarOffset[i] = nextChar(); 1759 newLvarLength[i] = nextChar(); 1760 newLvarIndex[i] = nextChar(); 1761 } 1762 1763 final TypeAnnotationPosition position = 1764 TypeAnnotationPosition.resourceVariable(readTypePath()); 1765 position.lvarOffset = newLvarOffset; 1766 position.lvarLength = newLvarLength; 1767 position.lvarIndex = newLvarIndex; 1768 return position; 1769 } 1770 // exception parameter 1771 case EXCEPTION_PARAMETER: { 1772 final int exception_index = nextChar(); 1773 final TypeAnnotationPosition position = 1774 TypeAnnotationPosition.exceptionParameter(readTypePath()); 1775 position.setExceptionIndex(exception_index); 1776 return position; 1777 } 1778 // method receiver 1779 case METHOD_RECEIVER: 1780 return TypeAnnotationPosition.methodReceiver(readTypePath()); 1781 // type parameter 1782 case CLASS_TYPE_PARAMETER: { 1783 final int parameter_index = nextByte(); 1784 return TypeAnnotationPosition 1785 .typeParameter(readTypePath(), parameter_index); 1786 } 1787 case METHOD_TYPE_PARAMETER: { 1788 final int parameter_index = nextByte(); 1789 return TypeAnnotationPosition 1790 .methodTypeParameter(readTypePath(), parameter_index); 1791 } 1792 // type parameter bound 1793 case CLASS_TYPE_PARAMETER_BOUND: { 1794 final int parameter_index = nextByte(); 1795 final int bound_index = nextByte(); 1796 return TypeAnnotationPosition 1797 .typeParameterBound(readTypePath(), parameter_index, 1798 bound_index); 1799 } 1800 case METHOD_TYPE_PARAMETER_BOUND: { 1801 final int parameter_index = nextByte(); 1802 final int bound_index = nextByte(); 1803 return TypeAnnotationPosition 1804 .methodTypeParameterBound(readTypePath(), parameter_index, 1805 bound_index); 1806 } 1807 // class extends or implements clause 1808 case CLASS_EXTENDS: { 1809 final int type_index = nextChar(); 1810 return TypeAnnotationPosition.classExtends(readTypePath(), 1811 type_index); 1812 } 1813 // throws 1814 case THROWS: { 1815 final int type_index = nextChar(); 1816 return TypeAnnotationPosition.methodThrows(readTypePath(), 1817 type_index); 1818 } 1819 // method parameter 1820 case METHOD_FORMAL_PARAMETER: { 1821 final int parameter_index = nextByte(); 1822 return TypeAnnotationPosition.methodParameter(readTypePath(), 1823 parameter_index); 1824 } 1825 // type cast 1826 case CAST: { 1827 final int offset = nextChar(); 1828 final int type_index = nextByte(); 1829 final TypeAnnotationPosition position = 1830 TypeAnnotationPosition.typeCast(readTypePath(), type_index); 1831 position.offset = offset; 1832 return position; 1833 } 1834 // method/constructor/reference type argument 1835 case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: { 1836 final int offset = nextChar(); 1837 final int type_index = nextByte(); 1838 final TypeAnnotationPosition position = TypeAnnotationPosition 1839 .constructorInvocationTypeArg(readTypePath(), type_index); 1840 position.offset = offset; 1841 return position; 1842 } 1843 case METHOD_INVOCATION_TYPE_ARGUMENT: { 1844 final int offset = nextChar(); 1845 final int type_index = nextByte(); 1846 final TypeAnnotationPosition position = TypeAnnotationPosition 1847 .methodInvocationTypeArg(readTypePath(), type_index); 1848 position.offset = offset; 1849 return position; 1850 } 1851 case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: { 1852 final int offset = nextChar(); 1853 final int type_index = nextByte(); 1854 final TypeAnnotationPosition position = TypeAnnotationPosition 1855 .constructorRefTypeArg(readTypePath(), type_index); 1856 position.offset = offset; 1857 return position; 1858 } 1859 case METHOD_REFERENCE_TYPE_ARGUMENT: { 1860 final int offset = nextChar(); 1861 final int type_index = nextByte(); 1862 final TypeAnnotationPosition position = TypeAnnotationPosition 1863 .methodRefTypeArg(readTypePath(), type_index); 1864 position.offset = offset; 1865 return position; 1866 } 1867 // We don't need to worry about these 1868 case METHOD_RETURN: 1869 return TypeAnnotationPosition.methodReturn(readTypePath()); 1870 case FIELD: 1871 return TypeAnnotationPosition.field(readTypePath()); 1872 case UNKNOWN: 1873 throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!"); 1874 default: 1875 throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + type); 1876 } 1877 } 1878 1879 List<TypeAnnotationPosition.TypePathEntry> readTypePath() { 1880 int len = nextByte(); 1881 ListBuffer<Integer> loc = new ListBuffer<>(); 1882 for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i) 1883 loc = loc.append(nextByte()); 1884 1885 return TypeAnnotationPosition.getTypePathFromBinary(loc.toList()); 1886 1887 } 1888 1889 /** 1890 * Helper function to read an optional pool entry (with given function); this is used while parsing 1891 * InnerClasses and EnclosingMethod attributes, as well as when parsing supertype descriptor, 1892 * as per JVMS. 1893 */ 1894 <Z> Z optPoolEntry(int index, IntFunction<Z> poolFunc, Z defaultValue) { 1895 return (index == 0) ? 1896 defaultValue : 1897 poolFunc.apply(index); 1898 } 1899 1900 Attribute readAttributeValue() { 1901 char c; 1902 try { 1903 c = (char)buf.getByte(bp++); 1904 } catch (UnderflowException e) { 1905 throw badClassFile(Fragments.BadClassTruncatedAtOffset(e.getLength())); 1906 } 1907 switch (c) { 1908 case 'B': 1909 return new Attribute.Constant(syms.byteType, poolReader.getConstant(nextChar())); 1910 case 'C': 1911 return new Attribute.Constant(syms.charType, poolReader.getConstant(nextChar())); 1912 case 'D': 1913 return new Attribute.Constant(syms.doubleType, poolReader.getConstant(nextChar())); 1914 case 'F': 1915 return new Attribute.Constant(syms.floatType, poolReader.getConstant(nextChar())); 1916 case 'I': 1917 return new Attribute.Constant(syms.intType, poolReader.getConstant(nextChar())); 1918 case 'J': 1919 return new Attribute.Constant(syms.longType, poolReader.getConstant(nextChar())); 1920 case 'S': 1921 return new Attribute.Constant(syms.shortType, poolReader.getConstant(nextChar())); 1922 case 'Z': 1923 return new Attribute.Constant(syms.booleanType, poolReader.getConstant(nextChar())); 1924 case 's': 1925 return new Attribute.Constant(syms.stringType, poolReader.getName(nextChar()).toString()); 1926 case 'e': 1927 return new EnumAttributeProxy(readTypeToProxy(nextChar()), poolReader.getName(nextChar())); 1928 case 'c': 1929 return new ClassAttributeProxy(readTypeOrClassSymbol(nextChar())); 1930 case '[': { 1931 int n = nextChar(); 1932 ListBuffer<Attribute> l = new ListBuffer<>(); 1933 for (int i=0; i<n; i++) 1934 l.append(readAttributeValue()); 1935 return new ArrayAttributeProxy(l.toList()); 1936 } 1937 case '@': 1938 return readCompoundAnnotation(); 1939 default: 1940 throw new AssertionError("unknown annotation tag '" + c + "'"); 1941 } 1942 } 1943 1944 interface ProxyVisitor extends Attribute.Visitor { 1945 void visitEnumAttributeProxy(EnumAttributeProxy proxy); 1946 void visitClassAttributeProxy(ClassAttributeProxy proxy); 1947 void visitArrayAttributeProxy(ArrayAttributeProxy proxy); 1948 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy); 1949 } 1950 1951 static class EnumAttributeProxy extends Attribute { 1952 Type enumType; 1953 Name enumerator; 1954 public EnumAttributeProxy(Type enumType, Name enumerator) { 1955 super(null); 1956 this.enumType = enumType; 1957 this.enumerator = enumerator; 1958 } 1959 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); } 1960 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1961 public String toString() { 1962 return "/*proxy enum*/" + enumType + "." + enumerator; 1963 } 1964 } 1965 1966 static class ClassAttributeProxy extends Attribute { 1967 Type classType; 1968 public ClassAttributeProxy(Type classType) { 1969 super(null); 1970 this.classType = classType; 1971 } 1972 public void accept(Visitor v) { ((ProxyVisitor)v).visitClassAttributeProxy(this); } 1973 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1974 public String toString() { 1975 return "/*proxy class*/" + classType + ".class"; 1976 } 1977 } 1978 1979 static class ArrayAttributeProxy extends Attribute { 1980 List<Attribute> values; 1981 ArrayAttributeProxy(List<Attribute> values) { 1982 super(null); 1983 this.values = values; 1984 } 1985 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); } 1986 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1987 public String toString() { 1988 return "{" + values + "}"; 1989 } 1990 } 1991 1992 /** A temporary proxy representing a compound attribute. 1993 */ 1994 static class CompoundAnnotationProxy extends Attribute { 1995 final List<Pair<Name,Attribute>> values; 1996 public CompoundAnnotationProxy(Type type, 1997 List<Pair<Name,Attribute>> values) { 1998 super(type); 1999 this.values = values; 2000 } 2001 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); } 2002 @Override @DefinedBy(Api.LANGUAGE_MODEL) 2003 public String toString() { 2004 StringBuilder buf = new StringBuilder(); 2005 buf.append("@"); 2006 buf.append(type.tsym.getQualifiedName()); 2007 buf.append("/*proxy*/{"); 2008 boolean first = true; 2009 for (List<Pair<Name,Attribute>> v = values; 2010 v.nonEmpty(); v = v.tail) { 2011 Pair<Name,Attribute> value = v.head; 2012 if (!first) buf.append(","); 2013 first = false; 2014 buf.append(value.fst); 2015 buf.append("="); 2016 buf.append(value.snd); 2017 } 2018 buf.append("}"); 2019 return buf.toString(); 2020 } 2021 } 2022 2023 /** A temporary proxy representing a type annotation. 2024 */ 2025 static class TypeAnnotationProxy { 2026 final CompoundAnnotationProxy compound; 2027 final TypeAnnotationPosition position; 2028 public TypeAnnotationProxy(CompoundAnnotationProxy compound, 2029 TypeAnnotationPosition position) { 2030 this.compound = compound; 2031 this.position = position; 2032 } 2033 } 2034 2035 class AnnotationDeproxy implements ProxyVisitor { 2036 private ClassSymbol requestingOwner; 2037 2038 AnnotationDeproxy(ClassSymbol owner) { 2039 this.requestingOwner = owner; 2040 } 2041 2042 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) { 2043 // also must fill in types!!!! 2044 ListBuffer<Attribute.Compound> buf = new ListBuffer<>(); 2045 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) { 2046 buf.append(deproxyCompound(l.head)); 2047 } 2048 return buf.toList(); 2049 } 2050 2051 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) { 2052 Type annotationType = resolvePossibleProxyType(a.type); 2053 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf = new ListBuffer<>(); 2054 for (List<Pair<Name,Attribute>> l = a.values; 2055 l.nonEmpty(); 2056 l = l.tail) { 2057 MethodSymbol meth = findAccessMethod(annotationType, l.head.fst); 2058 buf.append(new Pair<>(meth, deproxy(meth.type.getReturnType(), l.head.snd))); 2059 } 2060 return new Attribute.Compound(annotationType, buf.toList()); 2061 } 2062 2063 MethodSymbol findAccessMethod(Type container, Name name) { 2064 CompletionFailure failure = null; 2065 try { 2066 for (Symbol sym : container.tsym.members().getSymbolsByName(name)) { 2067 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0) 2068 return (MethodSymbol) sym; 2069 } 2070 } catch (CompletionFailure ex) { 2071 failure = ex; 2072 } 2073 // The method wasn't found: emit a warning and recover 2074 JavaFileObject prevSource = log.useSource(requestingOwner.classfile); 2075 try { 2076 if (failure == null) { 2077 lint.logIfEnabled(LintWarnings.AnnotationMethodNotFound(container, name)); 2078 } else { 2079 lint.logIfEnabled(LintWarnings.AnnotationMethodNotFoundReason(container, 2080 name, 2081 failure.getDetailValue()));//diagnostic, if present 2082 } 2083 } finally { 2084 log.useSource(prevSource); 2085 } 2086 // Construct a new method type and symbol. Use bottom 2087 // type (typeof null) as return type because this type is 2088 // a subtype of all reference types and can be converted 2089 // to primitive types by unboxing. 2090 MethodType mt = new MethodType(List.nil(), 2091 syms.botType, 2092 List.nil(), 2093 syms.methodClass); 2094 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym); 2095 } 2096 2097 Attribute result; 2098 Type type; 2099 Attribute deproxy(Type t, Attribute a) { 2100 Type oldType = type; 2101 try { 2102 type = t; 2103 a.accept(this); 2104 return result; 2105 } finally { 2106 type = oldType; 2107 } 2108 } 2109 2110 // implement Attribute.Visitor below 2111 2112 public void visitConstant(Attribute.Constant value) { 2113 // assert value.type == type; 2114 result = value; 2115 } 2116 2117 public void visitClass(Attribute.Class clazz) { 2118 result = clazz; 2119 } 2120 2121 public void visitEnum(Attribute.Enum e) { 2122 throw new AssertionError(); // shouldn't happen 2123 } 2124 2125 public void visitCompound(Attribute.Compound compound) { 2126 throw new AssertionError(); // shouldn't happen 2127 } 2128 2129 public void visitArray(Attribute.Array array) { 2130 throw new AssertionError(); // shouldn't happen 2131 } 2132 2133 public void visitError(Attribute.Error e) { 2134 throw new AssertionError(); // shouldn't happen 2135 } 2136 2137 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) { 2138 // type.tsym.flatName() should == proxy.enumFlatName 2139 Type enumType = resolvePossibleProxyType(proxy.enumType); 2140 TypeSymbol enumTypeSym = enumType.tsym; 2141 VarSymbol enumerator = null; 2142 CompletionFailure failure = null; 2143 try { 2144 for (Symbol sym : enumTypeSym.members().getSymbolsByName(proxy.enumerator)) { 2145 if (sym.kind == VAR) { 2146 enumerator = (VarSymbol)sym; 2147 break; 2148 } 2149 } 2150 } 2151 catch (CompletionFailure ex) { 2152 failure = ex; 2153 } 2154 if (enumerator == null) { 2155 if (failure != null) { 2156 log.warning(Warnings.UnknownEnumConstantReason(currentClassFile, 2157 enumTypeSym, 2158 proxy.enumerator, 2159 failure.getDiagnostic())); 2160 } else { 2161 log.warning(Warnings.UnknownEnumConstant(currentClassFile, 2162 enumTypeSym, 2163 proxy.enumerator)); 2164 } 2165 result = new Attribute.Enum(enumTypeSym.type, 2166 new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym)); 2167 } else { 2168 result = new Attribute.Enum(enumTypeSym.type, enumerator); 2169 } 2170 } 2171 2172 @Override 2173 public void visitClassAttributeProxy(ClassAttributeProxy proxy) { 2174 Type classType = resolvePossibleProxyType(proxy.classType); 2175 result = new Attribute.Class(types, classType); 2176 } 2177 2178 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) { 2179 int length = proxy.values.length(); 2180 Attribute[] ats = new Attribute[length]; 2181 Type elemtype = types.elemtype(type); 2182 int i = 0; 2183 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) { 2184 ats[i++] = deproxy(elemtype, p.head); 2185 } 2186 result = new Attribute.Array(type, ats); 2187 } 2188 2189 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) { 2190 result = deproxyCompound(proxy); 2191 } 2192 2193 Type resolvePossibleProxyType(Type t) { 2194 if (t instanceof ProxyType proxyType) { 2195 Assert.check(requestingOwner.owner instanceof ModuleSymbol); 2196 ModuleSymbol prevCurrentModule = currentModule; 2197 currentModule = (ModuleSymbol) requestingOwner.owner; 2198 try { 2199 return proxyType.resolve(); 2200 } finally { 2201 currentModule = prevCurrentModule; 2202 } 2203 } else { 2204 return t; 2205 } 2206 } 2207 } 2208 2209 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Runnable { 2210 final MethodSymbol sym; 2211 final Attribute value; 2212 final JavaFileObject classFile = currentClassFile; 2213 2214 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) { 2215 super(currentOwner.kind == MTH 2216 ? currentOwner.enclClass() : (ClassSymbol)currentOwner); 2217 this.sym = sym; 2218 this.value = value; 2219 } 2220 2221 @Override 2222 public void run() { 2223 JavaFileObject previousClassFile = currentClassFile; 2224 try { 2225 // Reset the interim value set earlier in 2226 // attachAnnotationDefault(). 2227 sym.defaultValue = null; 2228 currentClassFile = classFile; 2229 sym.defaultValue = deproxy(sym.type.getReturnType(), value); 2230 } finally { 2231 currentClassFile = previousClassFile; 2232 } 2233 } 2234 2235 @Override 2236 public String toString() { 2237 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value; 2238 } 2239 } 2240 2241 class AnnotationCompleter extends AnnotationDeproxy implements Runnable { 2242 final Symbol sym; 2243 final List<CompoundAnnotationProxy> l; 2244 final JavaFileObject classFile; 2245 2246 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) { 2247 super(currentOwner.kind == MTH 2248 ? currentOwner.enclClass() : (ClassSymbol)currentOwner); 2249 if (sym.kind == TYP && sym.owner.kind == MDL) { 2250 this.sym = sym.owner; 2251 } else { 2252 this.sym = sym; 2253 } 2254 this.l = l; 2255 this.classFile = currentClassFile; 2256 } 2257 2258 @Override 2259 public void run() { 2260 JavaFileObject previousClassFile = currentClassFile; 2261 try { 2262 currentClassFile = classFile; 2263 List<Attribute.Compound> newList = deproxyCompoundList(l); 2264 for (Attribute.Compound attr : newList) { 2265 if (attr.type.tsym == syms.deprecatedType.tsym) { 2266 sym.flags_field |= (DEPRECATED | DEPRECATED_ANNOTATION); 2267 Attribute forRemoval = attr.member(names.forRemoval); 2268 if (forRemoval instanceof Attribute.Constant constant) { 2269 if (constant.type == syms.booleanType && ((Integer) constant.value) != 0) { 2270 sym.flags_field |= DEPRECATED_REMOVAL; 2271 } 2272 } 2273 } 2274 } 2275 if (sym.annotationsPendingCompletion()) { 2276 sym.setDeclarationAttributes(newList); 2277 } else { 2278 sym.appendAttributes(newList); 2279 } 2280 } finally { 2281 currentClassFile = previousClassFile; 2282 } 2283 } 2284 2285 @Override 2286 public String toString() { 2287 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l; 2288 } 2289 } 2290 2291 class TypeAnnotationCompleter extends AnnotationCompleter { 2292 2293 List<TypeAnnotationProxy> proxies; 2294 2295 TypeAnnotationCompleter(Symbol sym, 2296 List<TypeAnnotationProxy> proxies) { 2297 super(sym, List.nil()); 2298 this.proxies = proxies; 2299 } 2300 2301 List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) { 2302 ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>(); 2303 for (TypeAnnotationProxy proxy: proxies) { 2304 Attribute.Compound compound = deproxyCompound(proxy.compound); 2305 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position); 2306 buf.add(typeCompound); 2307 } 2308 return buf.toList(); 2309 } 2310 2311 @Override 2312 public void run() { 2313 JavaFileObject previousClassFile = currentClassFile; 2314 try { 2315 currentClassFile = classFile; 2316 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies); 2317 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes())); 2318 addTypeAnnotationsToSymbol(sym, newList); 2319 } finally { 2320 currentClassFile = previousClassFile; 2321 } 2322 } 2323 } 2324 2325 /** 2326 * Rewrites types in the given symbol to include type annotations. 2327 * 2328 * <p>The list of type annotations includes annotations for all types in the signature of the 2329 * symbol. Associating the annotations with the correct type requires interpreting the JVMS 2330 * 4.7.20-A target_type to locate the correct type to rewrite, and then interpreting the JVMS 2331 * 4.7.20.2 type_path to associate the annotation with the correct contained type. 2332 */ 2333 private void addTypeAnnotationsToSymbol(Symbol s, List<Attribute.TypeCompound> attributes) { 2334 try { 2335 new TypeAnnotationSymbolVisitor(attributes).visit(s, null); 2336 } catch (CompletionFailure ex) { 2337 JavaFileObject prev = log.useSource(currentClassFile); 2338 try { 2339 log.error(Errors.CantAttachTypeAnnotations(attributes, s.owner, s.name, ex.getDetailValue())); 2340 } finally { 2341 log.useSource(prev); 2342 } 2343 } 2344 } 2345 2346 private static class TypeAnnotationSymbolVisitor 2347 extends Types.DefaultSymbolVisitor<Void, Void> { 2348 2349 private final List<Attribute.TypeCompound> attributes; 2350 2351 private TypeAnnotationSymbolVisitor(List<Attribute.TypeCompound> attributes) { 2352 this.attributes = attributes; 2353 } 2354 2355 /** 2356 * A supertype_index value of 65535 specifies that the annotation appears on the superclass 2357 * in an extends clause of a class declaration, see JVMS 4.7.20.1 2358 */ 2359 public static final int SUPERCLASS_INDEX = 65535; 2360 2361 @Override 2362 public Void visitClassSymbol(Symbol.ClassSymbol s, Void unused) { 2363 ClassType t = (ClassType) s.type; 2364 int i = 0; 2365 ListBuffer<Type> interfaces = new ListBuffer<>(); 2366 for (Type itf : t.interfaces_field) { 2367 interfaces.add(addTypeAnnotations(itf, classExtends(i++))); 2368 } 2369 t.interfaces_field = interfaces.toList(); 2370 t.supertype_field = addTypeAnnotations(t.supertype_field, classExtends(SUPERCLASS_INDEX)); 2371 if (t.typarams_field != null) { 2372 t.typarams_field = 2373 rewriteTypeParameters( 2374 t.typarams_field, TargetType.CLASS_TYPE_PARAMETER_BOUND); 2375 } 2376 return null; 2377 } 2378 2379 @Override 2380 public Void visitMethodSymbol(Symbol.MethodSymbol s, Void unused) { 2381 Type t = s.type; 2382 if (t.hasTag(TypeTag.FORALL)) { 2383 Type.ForAll fa = (Type.ForAll) t; 2384 fa.tvars = rewriteTypeParameters(fa.tvars, TargetType.METHOD_TYPE_PARAMETER_BOUND); 2385 t = fa.qtype; 2386 } 2387 MethodType mt = (MethodType) t; 2388 ListBuffer<Type> argtypes = new ListBuffer<>(); 2389 int i = 0; 2390 for (Symbol.VarSymbol param : s.params) { 2391 param.type = addTypeAnnotations(param.type, methodFormalParameter(i++)); 2392 argtypes.add(param.type); 2393 } 2394 mt.argtypes = argtypes.toList(); 2395 ListBuffer<Type> thrown = new ListBuffer<>(); 2396 i = 0; 2397 for (Type thrownType : mt.thrown) { 2398 thrown.add(addTypeAnnotations(thrownType, thrownType(i++))); 2399 } 2400 mt.thrown = thrown.toList(); 2401 /* possible information loss if the type of the method is void then we can't add type 2402 * annotations to it 2403 */ 2404 if (!mt.restype.hasTag(TypeTag.VOID)) { 2405 mt.restype = addTypeAnnotations(mt.restype, TargetType.METHOD_RETURN); 2406 } 2407 2408 Type recvtype = mt.recvtype != null ? mt.recvtype : s.implicitReceiverType(); 2409 if (recvtype != null) { 2410 Type annotated = addTypeAnnotations(recvtype, TargetType.METHOD_RECEIVER); 2411 if (annotated != recvtype) { 2412 mt.recvtype = annotated; 2413 } 2414 } 2415 return null; 2416 } 2417 2418 @Override 2419 public Void visitVarSymbol(Symbol.VarSymbol s, Void unused) { 2420 s.type = addTypeAnnotations(s.type, TargetType.FIELD); 2421 return null; 2422 } 2423 2424 @Override 2425 public Void visitSymbol(Symbol s, Void unused) { 2426 return null; 2427 } 2428 2429 private List<Type> rewriteTypeParameters(List<Type> tvars, TargetType boundType) { 2430 ListBuffer<Type> tvarbuf = new ListBuffer<>(); 2431 int typeVariableIndex = 0; 2432 for (Type tvar : tvars) { 2433 Type bound = tvar.getUpperBound(); 2434 if (bound.isCompound()) { 2435 ClassType ct = (ClassType) bound; 2436 int boundIndex = 0; 2437 if (ct.supertype_field != null) { 2438 ct.supertype_field = 2439 addTypeAnnotations( 2440 ct.supertype_field, 2441 typeParameterBound( 2442 boundType, typeVariableIndex, boundIndex++)); 2443 } 2444 ListBuffer<Type> itfbuf = new ListBuffer<>(); 2445 for (Type itf : ct.interfaces_field) { 2446 itfbuf.add( 2447 addTypeAnnotations( 2448 itf, 2449 typeParameterBound( 2450 boundType, typeVariableIndex, boundIndex++))); 2451 } 2452 ct.interfaces_field = itfbuf.toList(); 2453 } else { 2454 bound = 2455 addTypeAnnotations( 2456 bound, 2457 typeParameterBound( 2458 boundType, 2459 typeVariableIndex, 2460 bound.isInterface() ? 1 : 0)); 2461 } 2462 ((TypeVar) tvar).setUpperBound(bound); 2463 tvarbuf.add(tvar); 2464 typeVariableIndex++; 2465 } 2466 return tvarbuf.toList(); 2467 } 2468 2469 private Type addTypeAnnotations(Type type, TargetType targetType) { 2470 return addTypeAnnotations(type, pos -> pos.type == targetType); 2471 } 2472 2473 private Type addTypeAnnotations(Type type, Predicate<TypeAnnotationPosition> filter) { 2474 Assert.checkNonNull(type); 2475 2476 // Find type annotations that match the given target type 2477 ListBuffer<Attribute.TypeCompound> filtered = new ListBuffer<>(); 2478 for (Attribute.TypeCompound attribute : this.attributes) { 2479 if (filter.test(attribute.position)) { 2480 filtered.add(attribute); 2481 } 2482 } 2483 if (filtered.isEmpty()) { 2484 return type; 2485 } 2486 2487 // Group the matching annotations by their type path. Each group of annotations will be 2488 // added to a type at that location. 2489 Map<List<TypeAnnotationPosition.TypePathEntry>, ListBuffer<Attribute.TypeCompound>> 2490 attributesByPath = new HashMap<>(); 2491 for (Attribute.TypeCompound attribute : filtered.toList()) { 2492 attributesByPath 2493 .computeIfAbsent(attribute.position.location, k -> new ListBuffer<>()) 2494 .add(attribute); 2495 } 2496 2497 // Rewrite the type and add the annotations 2498 type = new TypeAnnotationStructuralTypeMapping(attributesByPath).visit(type, List.nil()); 2499 2500 return type; 2501 } 2502 2503 private static Predicate<TypeAnnotationPosition> typeParameterBound( 2504 TargetType targetType, int parameterIndex, int boundIndex) { 2505 return pos -> 2506 pos.type == targetType 2507 && pos.parameter_index == parameterIndex 2508 && pos.bound_index == boundIndex; 2509 } 2510 2511 private static Predicate<TypeAnnotationPosition> methodFormalParameter(int index) { 2512 return pos -> 2513 pos.type == TargetType.METHOD_FORMAL_PARAMETER && pos.parameter_index == index; 2514 } 2515 2516 private static Predicate<TypeAnnotationPosition> thrownType(int index) { 2517 return pos -> pos.type == TargetType.THROWS && pos.type_index == index; 2518 } 2519 2520 private static Predicate<TypeAnnotationPosition> classExtends(int index) { 2521 return pos -> pos.type == TargetType.CLASS_EXTENDS && pos.type_index == index; 2522 } 2523 } 2524 2525 /** 2526 * A type mapping that rewrites the type to include type annotations. 2527 * 2528 * <p>This logic is similar to {@link Type.StructuralTypeMapping}, but also tracks the path to 2529 * the contained types being rewritten, and so cannot easily share the existing logic. 2530 */ 2531 private static final class TypeAnnotationStructuralTypeMapping 2532 extends Types.TypeMapping<List<TypeAnnotationPosition.TypePathEntry>> { 2533 2534 private final Map<List<TypeAnnotationPosition.TypePathEntry>, 2535 ListBuffer<Attribute.TypeCompound>> attributesByPath; 2536 2537 private TypeAnnotationStructuralTypeMapping( 2538 Map<List<TypeAnnotationPosition.TypePathEntry>, ListBuffer<Attribute.TypeCompound>> 2539 attributesByPath) { 2540 this.attributesByPath = attributesByPath; 2541 } 2542 2543 2544 @Override 2545 public Type visitClassType(ClassType t, List<TypeAnnotationPosition.TypePathEntry> path) { 2546 // As described in JVMS 4.7.20.2, type annotations on nested types are located with 2547 // 'left-to-right' steps starting on 'the outermost part of the type for which a type 2548 // annotation is admissible'. So the current path represents the outermost containing 2549 // type of the type being visited, and we add type path steps for every contained nested 2550 // type. 2551 Type outer = t.getEnclosingType(); 2552 Type outer1 = outer != Type.noType ? visit(outer, path) : outer; 2553 for (Type curr = t.getEnclosingType(); 2554 curr != Type.noType; 2555 curr = curr.getEnclosingType()) { 2556 path = path.append(TypeAnnotationPosition.TypePathEntry.INNER_TYPE); 2557 } 2558 List<Type> typarams = t.getTypeArguments(); 2559 List<Type> typarams1 = rewriteTypeParams(path, typarams); 2560 if (outer1 != outer || typarams != typarams1) { 2561 t = new ClassType(outer1, typarams1, t.tsym, t.getMetadata()); 2562 } 2563 return reannotate(t, path); 2564 } 2565 2566 private List<Type> rewriteTypeParams( 2567 List<TypeAnnotationPosition.TypePathEntry> path, List<Type> typarams) { 2568 var i = IntStream.iterate(0, x -> x + 1).iterator(); 2569 return typarams.map(typaram -> visit(typaram, 2570 path.append(new TypeAnnotationPosition.TypePathEntry( 2571 TypeAnnotationPosition.TypePathEntryKind.TYPE_ARGUMENT, i.nextInt())))); 2572 } 2573 2574 @Override 2575 public Type visitWildcardType( 2576 WildcardType wt, List<TypeAnnotationPosition.TypePathEntry> path) { 2577 Type t = wt.type; 2578 if (t != null) { 2579 t = visit(t, path.append(TypeAnnotationPosition.TypePathEntry.WILDCARD)); 2580 } 2581 if (t != wt.type) { 2582 wt = new WildcardType(t, wt.kind, wt.tsym, wt.bound, wt.getMetadata()); 2583 } 2584 return reannotate(wt, path); 2585 } 2586 2587 @Override 2588 public Type visitArrayType(ArrayType t, List<TypeAnnotationPosition.TypePathEntry> path) { 2589 Type elemtype = t.elemtype; 2590 Type elemtype1 = 2591 visit(elemtype, path.append(TypeAnnotationPosition.TypePathEntry.ARRAY)); 2592 if (elemtype1 != elemtype) { 2593 t = new ArrayType(elemtype1, t.tsym, t.getMetadata()); 2594 } 2595 return reannotate(t, path); 2596 } 2597 2598 @Override 2599 public Type visitType(Type t, List<TypeAnnotationPosition.TypePathEntry> path) { 2600 return reannotate(t, path); 2601 } 2602 2603 Type reannotate(Type type, List<TypeAnnotationPosition.TypePathEntry> path) { 2604 List<Attribute.TypeCompound> attributes = attributesForPath(path); 2605 if (attributes.isEmpty()) { 2606 return type; 2607 } 2608 // Runtime-visible and -invisible annotations are completed separately, so if the same 2609 // type has annotations from both it will get annotated twice. 2610 TypeMetadata.Annotations existing = type.getMetadata(TypeMetadata.Annotations.class); 2611 if (existing != null) { 2612 existing.annotationBuffer().addAll(attributes); 2613 return type; 2614 } 2615 return type.annotatedType(attributes); 2616 } 2617 2618 List<Attribute.TypeCompound> attributesForPath( 2619 List<TypeAnnotationPosition.TypePathEntry> path) { 2620 ListBuffer<Attribute.TypeCompound> attributes = attributesByPath.remove(path); 2621 return attributes != null ? attributes.toList() : List.nil(); 2622 } 2623 } 2624 2625 /* ********************************************************************** 2626 * Reading Symbols 2627 ***********************************************************************/ 2628 2629 /** Read a field. 2630 */ 2631 VarSymbol readField() { 2632 char rawFlags = nextChar(); 2633 long flags = adjustFieldFlags(rawFlags); 2634 Name name = poolReader.getName(nextChar()); 2635 Type type = poolReader.getType(nextChar()); 2636 VarSymbol v = new VarSymbol(flags, name, type, currentOwner); 2637 readMemberAttrs(v); 2638 if (Integer.bitCount(rawFlags & (PUBLIC | PRIVATE | PROTECTED)) > 1 || 2639 Integer.bitCount(rawFlags & (FINAL | VOLATILE)) > 1) 2640 throw badClassFile("illegal.flag.combo", Flags.toString((long)rawFlags), "field", v); 2641 return v; 2642 } 2643 2644 /** Read a method. 2645 */ 2646 MethodSymbol readMethod() { 2647 char rawFlags = nextChar(); 2648 long flags = adjustMethodFlags(rawFlags); 2649 Name name = poolReader.getName(nextChar()); 2650 Type descriptorType = poolReader.getType(nextChar()); 2651 Type type = descriptorType; 2652 if (currentOwner.isInterface() && 2653 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) { 2654 if (majorVersion > Version.V52.major || 2655 (majorVersion == Version.V52.major && minorVersion >= Version.V52.minor)) { 2656 if ((flags & (STATIC | PRIVATE)) == 0) { 2657 currentOwner.flags_field |= DEFAULT; 2658 flags |= DEFAULT | ABSTRACT; 2659 } 2660 } else { 2661 //protect against ill-formed classfiles 2662 throw badClassFile((flags & STATIC) == 0 ? "invalid.default.interface" : "invalid.static.interface", 2663 Integer.toString(majorVersion), 2664 Integer.toString(minorVersion)); 2665 } 2666 } 2667 validateMethodType(name, type); 2668 boolean forceLocal = false; 2669 if (name == names.init && currentOwner.hasOuterInstance()) { 2670 // Sometimes anonymous classes don't have an outer 2671 // instance, however, there is no reliable way to tell so 2672 // we never strip this$n 2673 // ditto for local classes. Local classes that have an enclosing method set 2674 // won't pass the "hasOuterInstance" check above, but those that don't have an 2675 // enclosing method (i.e. from initializers) will pass that check. 2676 boolean local = forceLocal = 2677 !currentOwner.owner.members().includes(currentOwner, LookupKind.NON_RECURSIVE); 2678 if (!currentOwner.name.isEmpty() && !local) 2679 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()), 2680 type.getReturnType(), 2681 type.getThrownTypes(), 2682 syms.methodClass); 2683 } 2684 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner); 2685 if (types.isSignaturePolymorphic(m)) { 2686 m.flags_field |= SIGNATURE_POLYMORPHIC; 2687 } 2688 if (saveParameterNames) 2689 initParameterNames(m); 2690 Symbol prevOwner = currentOwner; 2691 currentOwner = m; 2692 try { 2693 readMemberAttrs(m); 2694 } finally { 2695 currentOwner = prevOwner; 2696 } 2697 validateMethodType(name, m.type); 2698 adjustParameterAnnotations(m, descriptorType, forceLocal); 2699 setParameters(m, type); 2700 2701 if (Integer.bitCount(rawFlags & (PUBLIC | PRIVATE | PROTECTED)) > 1) 2702 throw badClassFile("illegal.flag.combo", Flags.toString((long)rawFlags), "method", m); 2703 if ((flags & VARARGS) != 0) { 2704 final Type last = type.getParameterTypes().last(); 2705 if (last == null || !last.hasTag(ARRAY)) { 2706 m.flags_field &= ~VARARGS; 2707 throw badClassFile("malformed.vararg.method", m); 2708 } 2709 } 2710 2711 return m; 2712 } 2713 2714 void validateMethodType(Name name, Type t) { 2715 if ((!t.hasTag(TypeTag.METHOD) && !t.hasTag(TypeTag.FORALL)) || 2716 (name == names.init && !t.getReturnType().hasTag(TypeTag.VOID))) { 2717 throw badClassFile("method.descriptor.invalid", name); 2718 } 2719 } 2720 2721 private List<Type> adjustMethodParams(long flags, List<Type> args) { 2722 if (args.isEmpty()) { 2723 return args; 2724 } 2725 boolean isVarargs = (flags & VARARGS) != 0; 2726 if (isVarargs) { 2727 Type varargsElem = args.last(); 2728 ListBuffer<Type> adjustedArgs = new ListBuffer<>(); 2729 for (Type t : args) { 2730 adjustedArgs.append(t != varargsElem ? 2731 t : 2732 ((ArrayType)t).makeVarargs()); 2733 } 2734 args = adjustedArgs.toList(); 2735 } 2736 return args.tail; 2737 } 2738 2739 /** 2740 * Init the parameter names array. 2741 * Parameter names are currently inferred from the names in the 2742 * LocalVariableTable attributes of a Code attribute. 2743 * (Note: this means parameter names are currently not available for 2744 * methods without a Code attribute.) 2745 * This method initializes an array in which to store the name indexes 2746 * of parameter names found in LocalVariableTable attributes. It is 2747 * slightly supersized to allow for additional slots with a start_pc of 0. 2748 */ 2749 void initParameterNames(MethodSymbol sym) { 2750 // make allowance for synthetic parameters. 2751 final int excessSlots = 4; 2752 int expectedParameterSlots = 2753 Code.width(sym.type.getParameterTypes()) + excessSlots; 2754 if (parameterNameIndicesLvt == null 2755 || parameterNameIndicesLvt.length < expectedParameterSlots) { 2756 parameterNameIndicesLvt = new int[expectedParameterSlots]; 2757 } else 2758 Arrays.fill(parameterNameIndicesLvt, 0); 2759 } 2760 2761 /** 2762 * Set the parameters for a method symbol, including any names and 2763 * annotations that were read. 2764 * 2765 * <p>The type of the symbol may have changed while reading the 2766 * method attributes (see the Signature attribute). This may be 2767 * because of generic information or because anonymous synthetic 2768 * parameters were added. The original type (as read from the 2769 * method descriptor) is used to help guess the existence of 2770 * anonymous synthetic parameters. 2771 */ 2772 void setParameters(MethodSymbol sym, Type jvmType) { 2773 int firstParamLvt = ((sym.flags() & STATIC) == 0) ? 1 : 0; 2774 // the code in readMethod may have skipped the first 2775 // parameter when setting up the MethodType. If so, we 2776 // make a corresponding allowance here for the position of 2777 // the first parameter. Note that this assumes the 2778 // skipped parameter has a width of 1 -- i.e. it is not 2779 // a double width type (long or double.) 2780 if (sym.name == names.init && currentOwner.hasOuterInstance()) { 2781 // Sometimes anonymous classes don't have an outer 2782 // instance, however, there is no reliable way to tell so 2783 // we never strip this$n 2784 if (!currentOwner.name.isEmpty()) 2785 firstParamLvt += 1; 2786 } 2787 2788 if (sym.type != jvmType) { 2789 // reading the method attributes has caused the 2790 // symbol's type to be changed. (i.e. the Signature 2791 // attribute.) This may happen if there are hidden 2792 // (synthetic) parameters in the descriptor, but not 2793 // in the Signature. The position of these hidden 2794 // parameters is unspecified; for now, assume they are 2795 // at the beginning, and so skip over them. The 2796 // primary case for this is two hidden parameters 2797 // passed into Enum constructors. 2798 int skip = Code.width(jvmType.getParameterTypes()) 2799 - Code.width(sym.type.getParameterTypes()); 2800 firstParamLvt += skip; 2801 } 2802 Set<Name> paramNames = new HashSet<>(); 2803 ListBuffer<VarSymbol> params = new ListBuffer<>(); 2804 // we maintain two index pointers, one for the LocalVariableTable attribute 2805 // and the other for the MethodParameters attribute. 2806 // This is needed as the MethodParameters attribute may contain 2807 // name_index = 0 in which case we want to fall back to the LocalVariableTable. 2808 // In such case, we still want to read the flags from the MethodParameters with that index. 2809 int nameIndexLvt = firstParamLvt; 2810 int nameIndexMp = 0; 2811 int annotationIndex = 0; 2812 for (Type t: sym.type.getParameterTypes()) { 2813 VarSymbol param = parameter(nameIndexMp, nameIndexLvt, t, sym, paramNames); 2814 params.append(param); 2815 if (parameterAnnotations != null) { 2816 ParameterAnnotations annotations = parameterAnnotations[annotationIndex]; 2817 if (annotations != null && annotations.proxies != null 2818 && !annotations.proxies.isEmpty()) { 2819 annotate.normal(new AnnotationCompleter(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 }