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