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