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