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