ClassReader.java revision 2852:2d47da183295
1/* 2 * Copyright (c) 1999, 2015, 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 26package com.sun.tools.javac.jvm; 27 28import java.io.*; 29import java.net.URI; 30import java.net.URISyntaxException; 31import java.nio.CharBuffer; 32import java.nio.file.Path; 33import java.util.Arrays; 34import java.util.EnumSet; 35import java.util.HashMap; 36import java.util.HashSet; 37import java.util.Map; 38import java.util.Set; 39 40import javax.tools.JavaFileManager; 41import javax.tools.JavaFileObject; 42 43import com.sun.tools.javac.code.*; 44import com.sun.tools.javac.code.Lint.LintCategory; 45import com.sun.tools.javac.code.Scope.WriteableScope; 46import com.sun.tools.javac.code.Symbol.*; 47import com.sun.tools.javac.code.Symtab; 48import com.sun.tools.javac.code.Type.*; 49import com.sun.tools.javac.comp.Annotate; 50import com.sun.tools.javac.file.BaseFileObject; 51import com.sun.tools.javac.jvm.ClassFile.NameAndType; 52import com.sun.tools.javac.jvm.ClassFile.Version; 53import com.sun.tools.javac.util.*; 54import com.sun.tools.javac.util.DefinedBy.Api; 55import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 56 57import static com.sun.tools.javac.code.Flags.*; 58import static com.sun.tools.javac.code.Kinds.Kind.*; 59import static com.sun.tools.javac.code.TypeTag.ARRAY; 60import static com.sun.tools.javac.code.TypeTag.CLASS; 61import static com.sun.tools.javac.code.TypeTag.TYPEVAR; 62import static com.sun.tools.javac.jvm.ClassFile.*; 63import static com.sun.tools.javac.jvm.ClassFile.Version.*; 64 65import static com.sun.tools.javac.main.Option.*; 66 67/** This class provides operations to read a classfile into an internal 68 * representation. The internal representation is anchored in a 69 * ClassSymbol which contains in its scope symbol representations 70 * for all other definitions in the classfile. Top-level Classes themselves 71 * appear as members of the scopes of PackageSymbols. 72 * 73 * <p><b>This is NOT part of any supported API. 74 * If you write code that depends on this, you do so at your own risk. 75 * This code and its internal interfaces are subject to change or 76 * deletion without notice.</b> 77 */ 78public class ClassReader { 79 /** The context key for the class reader. */ 80 protected static final Context.Key<ClassReader> classReaderKey = new Context.Key<>(); 81 82 public static final int INITIAL_BUFFER_SIZE = 0x0fff0; 83 84 Annotate annotate; 85 86 /** Switch: verbose output. 87 */ 88 boolean verbose; 89 90 /** Switch: check class file for correct minor version, unrecognized 91 * attributes. 92 */ 93 boolean checkClassFile; 94 95 /** Switch: read constant pool and code sections. This switch is initially 96 * set to false but can be turned on from outside. 97 */ 98 public boolean readAllOfClassFile = false; 99 100 /** Switch: allow simplified varargs. 101 */ 102 boolean allowSimplifiedVarargs; 103 104 /** Lint option: warn about classfile issues 105 */ 106 boolean lintClassfile; 107 108 /** Switch: preserve parameter names from the variable table. 109 */ 110 public boolean saveParameterNames; 111 112 /** 113 * The currently selected profile. 114 */ 115 public final Profile profile; 116 117 /** The log to use for verbose output 118 */ 119 final Log log; 120 121 /** The symbol table. */ 122 Symtab syms; 123 124 Types types; 125 126 /** The name table. */ 127 final Names names; 128 129 /** Access to files 130 */ 131 private final JavaFileManager fileManager; 132 133 /** Factory for diagnostics 134 */ 135 JCDiagnostic.Factory diagFactory; 136 137 /** The current scope where type variables are entered. 138 */ 139 protected WriteableScope typevars; 140 141 /** The path name of the class file currently being read. 142 */ 143 protected JavaFileObject currentClassFile = null; 144 145 /** The class or method currently being read. 146 */ 147 protected Symbol currentOwner = null; 148 149 /** The buffer containing the currently read class file. 150 */ 151 byte[] buf = new byte[INITIAL_BUFFER_SIZE]; 152 153 /** The current input pointer. 154 */ 155 protected int bp; 156 157 /** The objects of the constant pool. 158 */ 159 Object[] poolObj; 160 161 /** For every constant pool entry, an index into buf where the 162 * defining section of the entry is found. 163 */ 164 int[] poolIdx; 165 166 /** The major version number of the class file being read. */ 167 int majorVersion; 168 /** The minor version number of the class file being read. */ 169 int minorVersion; 170 171 /** A table to hold the constant pool indices for method parameter 172 * names, as given in LocalVariableTable attributes. 173 */ 174 int[] parameterNameIndices; 175 176 /** 177 * Whether or not any parameter names have been found. 178 */ 179 boolean haveParameterNameIndices; 180 181 /** Set this to false every time we start reading a method 182 * and are saving parameter names. Set it to true when we see 183 * MethodParameters, if it's set when we see a LocalVariableTable, 184 * then we ignore the parameter names from the LVT. 185 */ 186 boolean sawMethodParameters; 187 188 /** 189 * The set of attribute names for which warnings have been generated for the current class 190 */ 191 Set<Name> warnedAttrs = new HashSet<>(); 192 193 /** Get the ClassReader instance for this invocation. */ 194 public static ClassReader instance(Context context) { 195 ClassReader instance = context.get(classReaderKey); 196 if (instance == null) 197 instance = new ClassReader(context); 198 return instance; 199 } 200 201 /** Construct a new class reader. */ 202 protected ClassReader(Context context) { 203 context.put(classReaderKey, this); 204 names = Names.instance(context); 205 syms = Symtab.instance(context); 206 types = Types.instance(context); 207 fileManager = context.get(JavaFileManager.class); 208 if (fileManager == null) 209 throw new AssertionError("FileManager initialization error"); 210 diagFactory = JCDiagnostic.Factory.instance(context); 211 212 log = Log.instance(context); 213 214 Options options = Options.instance(context); 215 annotate = Annotate.instance(context); 216 verbose = options.isSet(VERBOSE); 217 checkClassFile = options.isSet("-checkclassfile"); 218 219 Source source = Source.instance(context); 220 allowSimplifiedVarargs = source.allowSimplifiedVarargs(); 221 222 saveParameterNames = options.isSet("save-parameter-names"); 223 224 profile = Profile.instance(context); 225 226 typevars = WriteableScope.create(syms.noSymbol); 227 228 lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE); 229 230 initAttributeReaders(); 231 } 232 233 /** Add member to class unless it is synthetic. 234 */ 235 private void enterMember(ClassSymbol c, Symbol sym) { 236 // Synthetic members are not entered -- reason lost to history (optimization?). 237 // Lambda methods must be entered because they may have inner classes (which reference them) 238 if ((sym.flags_field & (SYNTHETIC|BRIDGE)) != SYNTHETIC || sym.name.startsWith(names.lambda)) 239 c.members_field.enter(sym); 240 } 241 242/************************************************************************ 243 * Error Diagnoses 244 ***********************************************************************/ 245 246 public ClassFinder.BadClassFile badClassFile(String key, Object... args) { 247 return new ClassFinder.BadClassFile ( 248 currentOwner.enclClass(), 249 currentClassFile, 250 diagFactory.fragment(key, args), 251 diagFactory); 252 } 253 254/************************************************************************ 255 * Buffer Access 256 ***********************************************************************/ 257 258 /** Read a character. 259 */ 260 char nextChar() { 261 return (char)(((buf[bp++] & 0xFF) << 8) + (buf[bp++] & 0xFF)); 262 } 263 264 /** Read a byte. 265 */ 266 int nextByte() { 267 return buf[bp++] & 0xFF; 268 } 269 270 /** Read an integer. 271 */ 272 int nextInt() { 273 return 274 ((buf[bp++] & 0xFF) << 24) + 275 ((buf[bp++] & 0xFF) << 16) + 276 ((buf[bp++] & 0xFF) << 8) + 277 (buf[bp++] & 0xFF); 278 } 279 280 /** Extract a character at position bp from buf. 281 */ 282 char getChar(int bp) { 283 return 284 (char)(((buf[bp] & 0xFF) << 8) + (buf[bp+1] & 0xFF)); 285 } 286 287 /** Extract an integer at position bp from buf. 288 */ 289 int getInt(int bp) { 290 return 291 ((buf[bp] & 0xFF) << 24) + 292 ((buf[bp+1] & 0xFF) << 16) + 293 ((buf[bp+2] & 0xFF) << 8) + 294 (buf[bp+3] & 0xFF); 295 } 296 297 298 /** Extract a long integer at position bp from buf. 299 */ 300 long getLong(int bp) { 301 DataInputStream bufin = 302 new DataInputStream(new ByteArrayInputStream(buf, bp, 8)); 303 try { 304 return bufin.readLong(); 305 } catch (IOException e) { 306 throw new AssertionError(e); 307 } 308 } 309 310 /** Extract a float at position bp from buf. 311 */ 312 float getFloat(int bp) { 313 DataInputStream bufin = 314 new DataInputStream(new ByteArrayInputStream(buf, bp, 4)); 315 try { 316 return bufin.readFloat(); 317 } catch (IOException e) { 318 throw new AssertionError(e); 319 } 320 } 321 322 /** Extract a double at position bp from buf. 323 */ 324 double getDouble(int bp) { 325 DataInputStream bufin = 326 new DataInputStream(new ByteArrayInputStream(buf, bp, 8)); 327 try { 328 return bufin.readDouble(); 329 } catch (IOException e) { 330 throw new AssertionError(e); 331 } 332 } 333 334/************************************************************************ 335 * Constant Pool Access 336 ***********************************************************************/ 337 338 /** Index all constant pool entries, writing their start addresses into 339 * poolIdx. 340 */ 341 void indexPool() { 342 poolIdx = new int[nextChar()]; 343 poolObj = new Object[poolIdx.length]; 344 int i = 1; 345 while (i < poolIdx.length) { 346 poolIdx[i++] = bp; 347 byte tag = buf[bp++]; 348 switch (tag) { 349 case CONSTANT_Utf8: case CONSTANT_Unicode: { 350 int len = nextChar(); 351 bp = bp + len; 352 break; 353 } 354 case CONSTANT_Class: 355 case CONSTANT_String: 356 case CONSTANT_MethodType: 357 bp = bp + 2; 358 break; 359 case CONSTANT_MethodHandle: 360 bp = bp + 3; 361 break; 362 case CONSTANT_Fieldref: 363 case CONSTANT_Methodref: 364 case CONSTANT_InterfaceMethodref: 365 case CONSTANT_NameandType: 366 case CONSTANT_Integer: 367 case CONSTANT_Float: 368 case CONSTANT_InvokeDynamic: 369 bp = bp + 4; 370 break; 371 case CONSTANT_Long: 372 case CONSTANT_Double: 373 bp = bp + 8; 374 i++; 375 break; 376 default: 377 throw badClassFile("bad.const.pool.tag.at", 378 Byte.toString(tag), 379 Integer.toString(bp -1)); 380 } 381 } 382 } 383 384 /** Read constant pool entry at start address i, use pool as a cache. 385 */ 386 Object readPool(int i) { 387 Object result = poolObj[i]; 388 if (result != null) return result; 389 390 int index = poolIdx[i]; 391 if (index == 0) return null; 392 393 byte tag = buf[index]; 394 switch (tag) { 395 case CONSTANT_Utf8: 396 poolObj[i] = names.fromUtf(buf, index + 3, getChar(index + 1)); 397 break; 398 case CONSTANT_Unicode: 399 throw badClassFile("unicode.str.not.supported"); 400 case CONSTANT_Class: 401 poolObj[i] = readClassOrType(getChar(index + 1)); 402 break; 403 case CONSTANT_String: 404 // FIXME: (footprint) do not use toString here 405 poolObj[i] = readName(getChar(index + 1)).toString(); 406 break; 407 case CONSTANT_Fieldref: { 408 ClassSymbol owner = readClassSymbol(getChar(index + 1)); 409 NameAndType nt = readNameAndType(getChar(index + 3)); 410 poolObj[i] = new VarSymbol(0, nt.name, nt.uniqueType.type, owner); 411 break; 412 } 413 case CONSTANT_Methodref: 414 case CONSTANT_InterfaceMethodref: { 415 ClassSymbol owner = readClassSymbol(getChar(index + 1)); 416 NameAndType nt = readNameAndType(getChar(index + 3)); 417 poolObj[i] = new MethodSymbol(0, nt.name, nt.uniqueType.type, owner); 418 break; 419 } 420 case CONSTANT_NameandType: 421 poolObj[i] = new NameAndType( 422 readName(getChar(index + 1)), 423 readType(getChar(index + 3)), types); 424 break; 425 case CONSTANT_Integer: 426 poolObj[i] = getInt(index + 1); 427 break; 428 case CONSTANT_Float: 429 poolObj[i] = new Float(getFloat(index + 1)); 430 break; 431 case CONSTANT_Long: 432 poolObj[i] = new Long(getLong(index + 1)); 433 break; 434 case CONSTANT_Double: 435 poolObj[i] = new Double(getDouble(index + 1)); 436 break; 437 case CONSTANT_MethodHandle: 438 skipBytes(4); 439 break; 440 case CONSTANT_MethodType: 441 skipBytes(3); 442 break; 443 case CONSTANT_InvokeDynamic: 444 skipBytes(5); 445 break; 446 default: 447 throw badClassFile("bad.const.pool.tag", Byte.toString(tag)); 448 } 449 return poolObj[i]; 450 } 451 452 /** Read signature and convert to type. 453 */ 454 Type readType(int i) { 455 int index = poolIdx[i]; 456 return sigToType(buf, index + 3, getChar(index + 1)); 457 } 458 459 /** If name is an array type or class signature, return the 460 * corresponding type; otherwise return a ClassSymbol with given name. 461 */ 462 Object readClassOrType(int i) { 463 int index = poolIdx[i]; 464 int len = getChar(index + 1); 465 int start = index + 3; 466 Assert.check(buf[start] == '[' || buf[start + len - 1] != ';'); 467 // by the above assertion, the following test can be 468 // simplified to (buf[start] == '[') 469 return (buf[start] == '[' || buf[start + len - 1] == ';') 470 ? (Object)sigToType(buf, start, len) 471 : (Object)syms.enterClass(names.fromUtf(internalize(buf, start, 472 len))); 473 } 474 475 /** Read signature and convert to type parameters. 476 */ 477 List<Type> readTypeParams(int i) { 478 int index = poolIdx[i]; 479 return sigToTypeParams(buf, index + 3, getChar(index + 1)); 480 } 481 482 /** Read class entry. 483 */ 484 ClassSymbol readClassSymbol(int i) { 485 Object obj = readPool(i); 486 if (obj != null && !(obj instanceof ClassSymbol)) 487 throw badClassFile("bad.const.pool.entry", 488 currentClassFile.toString(), 489 "CONSTANT_Class_info", i); 490 return (ClassSymbol)obj; 491 } 492 493 /** Read name. 494 */ 495 Name readName(int i) { 496 Object obj = readPool(i); 497 if (obj != null && !(obj instanceof Name)) 498 throw badClassFile("bad.const.pool.entry", 499 currentClassFile.toString(), 500 "CONSTANT_Utf8_info or CONSTANT_String_info", i); 501 return (Name)obj; 502 } 503 504 /** Read name and type. 505 */ 506 NameAndType readNameAndType(int i) { 507 Object obj = readPool(i); 508 if (obj != null && !(obj instanceof NameAndType)) 509 throw badClassFile("bad.const.pool.entry", 510 currentClassFile.toString(), 511 "CONSTANT_NameAndType_info", i); 512 return (NameAndType)obj; 513 } 514 515/************************************************************************ 516 * Reading Types 517 ***********************************************************************/ 518 519 /** The unread portion of the currently read type is 520 * signature[sigp..siglimit-1]. 521 */ 522 byte[] signature; 523 int sigp; 524 int siglimit; 525 boolean sigEnterPhase = false; 526 527 /** Convert signature to type, where signature is a byte array segment. 528 */ 529 Type sigToType(byte[] sig, int offset, int len) { 530 signature = sig; 531 sigp = offset; 532 siglimit = offset + len; 533 return sigToType(); 534 } 535 536 /** Convert signature to type, where signature is implicit. 537 */ 538 Type sigToType() { 539 switch ((char) signature[sigp]) { 540 case 'T': 541 sigp++; 542 int start = sigp; 543 while (signature[sigp] != ';') sigp++; 544 sigp++; 545 return sigEnterPhase 546 ? Type.noType 547 : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start)); 548 case '+': { 549 sigp++; 550 Type t = sigToType(); 551 return new WildcardType(t, BoundKind.EXTENDS, syms.boundClass); 552 } 553 case '*': 554 sigp++; 555 return new WildcardType(syms.objectType, BoundKind.UNBOUND, 556 syms.boundClass); 557 case '-': { 558 sigp++; 559 Type t = sigToType(); 560 return new WildcardType(t, BoundKind.SUPER, syms.boundClass); 561 } 562 case 'B': 563 sigp++; 564 return syms.byteType; 565 case 'C': 566 sigp++; 567 return syms.charType; 568 case 'D': 569 sigp++; 570 return syms.doubleType; 571 case 'F': 572 sigp++; 573 return syms.floatType; 574 case 'I': 575 sigp++; 576 return syms.intType; 577 case 'J': 578 sigp++; 579 return syms.longType; 580 case 'L': 581 { 582 // int oldsigp = sigp; 583 Type t = classSigToType(); 584 if (sigp < siglimit && signature[sigp] == '.') 585 throw badClassFile("deprecated inner class signature syntax " + 586 "(please recompile from source)"); 587 /* 588 System.err.println(" decoded " + 589 new String(signature, oldsigp, sigp-oldsigp) + 590 " => " + t + " outer " + t.outer()); 591 */ 592 return t; 593 } 594 case 'S': 595 sigp++; 596 return syms.shortType; 597 case 'V': 598 sigp++; 599 return syms.voidType; 600 case 'Z': 601 sigp++; 602 return syms.booleanType; 603 case '[': 604 sigp++; 605 return new ArrayType(sigToType(), syms.arrayClass); 606 case '(': 607 sigp++; 608 List<Type> argtypes = sigToTypes(')'); 609 Type restype = sigToType(); 610 List<Type> thrown = List.nil(); 611 while (signature[sigp] == '^') { 612 sigp++; 613 thrown = thrown.prepend(sigToType()); 614 } 615 // if there is a typevar in the throws clause we should state it. 616 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) { 617 if (l.head.hasTag(TYPEVAR)) { 618 l.head.tsym.flags_field |= THROWS; 619 } 620 } 621 return new MethodType(argtypes, 622 restype, 623 thrown.reverse(), 624 syms.methodClass); 625 case '<': 626 typevars = typevars.dup(currentOwner); 627 Type poly = new ForAll(sigToTypeParams(), sigToType()); 628 typevars = typevars.leave(); 629 return poly; 630 default: 631 throw badClassFile("bad.signature", 632 Convert.utf2string(signature, sigp, 10)); 633 } 634 } 635 636 byte[] signatureBuffer = new byte[0]; 637 int sbp = 0; 638 /** Convert class signature to type, where signature is implicit. 639 */ 640 Type classSigToType() { 641 if (signature[sigp] != 'L') 642 throw badClassFile("bad.class.signature", 643 Convert.utf2string(signature, sigp, 10)); 644 sigp++; 645 Type outer = Type.noType; 646 int startSbp = sbp; 647 648 while (true) { 649 final byte c = signature[sigp++]; 650 switch (c) { 651 652 case ';': { // end 653 ClassSymbol t = syms.enterClass(names.fromUtf(signatureBuffer, 654 startSbp, 655 sbp - startSbp)); 656 657 try { 658 return (outer == Type.noType) ? 659 t.erasure(types) : 660 new ClassType(outer, List.<Type>nil(), t); 661 } finally { 662 sbp = startSbp; 663 } 664 } 665 666 case '<': // generic arguments 667 ClassSymbol t = syms.enterClass(names.fromUtf(signatureBuffer, 668 startSbp, 669 sbp - startSbp)); 670 outer = new ClassType(outer, sigToTypes('>'), t) { 671 boolean completed = false; 672 @Override @DefinedBy(Api.LANGUAGE_MODEL) 673 public Type getEnclosingType() { 674 if (!completed) { 675 completed = true; 676 tsym.complete(); 677 Type enclosingType = tsym.type.getEnclosingType(); 678 if (enclosingType != Type.noType) { 679 List<Type> typeArgs = 680 super.getEnclosingType().allparams(); 681 List<Type> typeParams = 682 enclosingType.allparams(); 683 if (typeParams.length() != typeArgs.length()) { 684 // no "rare" types 685 super.setEnclosingType(types.erasure(enclosingType)); 686 } else { 687 super.setEnclosingType(types.subst(enclosingType, 688 typeParams, 689 typeArgs)); 690 } 691 } else { 692 super.setEnclosingType(Type.noType); 693 } 694 } 695 return super.getEnclosingType(); 696 } 697 @Override 698 public void setEnclosingType(Type outer) { 699 throw new UnsupportedOperationException(); 700 } 701 }; 702 switch (signature[sigp++]) { 703 case ';': 704 if (sigp < signature.length && signature[sigp] == '.') { 705 // support old-style GJC signatures 706 // The signature produced was 707 // Lfoo/Outer<Lfoo/X;>;.Lfoo/Outer$Inner<Lfoo/Y;>; 708 // rather than say 709 // Lfoo/Outer<Lfoo/X;>.Inner<Lfoo/Y;>; 710 // so we skip past ".Lfoo/Outer$" 711 sigp += (sbp - startSbp) + // "foo/Outer" 712 3; // ".L" and "$" 713 signatureBuffer[sbp++] = (byte)'$'; 714 break; 715 } else { 716 sbp = startSbp; 717 return outer; 718 } 719 case '.': 720 signatureBuffer[sbp++] = (byte)'$'; 721 break; 722 default: 723 throw new AssertionError(signature[sigp-1]); 724 } 725 continue; 726 727 case '.': 728 //we have seen an enclosing non-generic class 729 if (outer != Type.noType) { 730 t = syms.enterClass(names.fromUtf(signatureBuffer, 731 startSbp, 732 sbp - startSbp)); 733 outer = new ClassType(outer, List.<Type>nil(), t); 734 } 735 signatureBuffer[sbp++] = (byte)'$'; 736 continue; 737 case '/': 738 signatureBuffer[sbp++] = (byte)'.'; 739 continue; 740 default: 741 signatureBuffer[sbp++] = c; 742 continue; 743 } 744 } 745 } 746 747 /** Convert (implicit) signature to list of types 748 * until `terminator' is encountered. 749 */ 750 List<Type> sigToTypes(char terminator) { 751 List<Type> head = List.of(null); 752 List<Type> tail = head; 753 while (signature[sigp] != terminator) 754 tail = tail.setTail(List.of(sigToType())); 755 sigp++; 756 return head.tail; 757 } 758 759 /** Convert signature to type parameters, where signature is a byte 760 * array segment. 761 */ 762 List<Type> sigToTypeParams(byte[] sig, int offset, int len) { 763 signature = sig; 764 sigp = offset; 765 siglimit = offset + len; 766 return sigToTypeParams(); 767 } 768 769 /** Convert signature to type parameters, where signature is implicit. 770 */ 771 List<Type> sigToTypeParams() { 772 List<Type> tvars = List.nil(); 773 if (signature[sigp] == '<') { 774 sigp++; 775 int start = sigp; 776 sigEnterPhase = true; 777 while (signature[sigp] != '>') 778 tvars = tvars.prepend(sigToTypeParam()); 779 sigEnterPhase = false; 780 sigp = start; 781 while (signature[sigp] != '>') 782 sigToTypeParam(); 783 sigp++; 784 } 785 return tvars.reverse(); 786 } 787 788 /** Convert (implicit) signature to type parameter. 789 */ 790 Type sigToTypeParam() { 791 int start = sigp; 792 while (signature[sigp] != ':') sigp++; 793 Name name = names.fromUtf(signature, start, sigp - start); 794 TypeVar tvar; 795 if (sigEnterPhase) { 796 tvar = new TypeVar(name, currentOwner, syms.botType); 797 typevars.enter(tvar.tsym); 798 } else { 799 tvar = (TypeVar)findTypeVar(name); 800 } 801 List<Type> bounds = List.nil(); 802 boolean allInterfaces = false; 803 if (signature[sigp] == ':' && signature[sigp+1] == ':') { 804 sigp++; 805 allInterfaces = true; 806 } 807 while (signature[sigp] == ':') { 808 sigp++; 809 bounds = bounds.prepend(sigToType()); 810 } 811 if (!sigEnterPhase) { 812 types.setBounds(tvar, bounds.reverse(), allInterfaces); 813 } 814 return tvar; 815 } 816 817 /** Find type variable with given name in `typevars' scope. 818 */ 819 Type findTypeVar(Name name) { 820 Symbol s = typevars.findFirst(name); 821 if (s != null) { 822 return s.type; 823 } else { 824 if (readingClassAttr) { 825 // While reading the class attribute, the supertypes 826 // might refer to a type variable from an enclosing element 827 // (method or class). 828 // If the type variable is defined in the enclosing class, 829 // we can actually find it in 830 // currentOwner.owner.type.getTypeArguments() 831 // However, until we have read the enclosing method attribute 832 // we don't know for sure if this owner is correct. It could 833 // be a method and there is no way to tell before reading the 834 // enclosing method attribute. 835 TypeVar t = new TypeVar(name, currentOwner, syms.botType); 836 missingTypeVariables = missingTypeVariables.prepend(t); 837 // System.err.println("Missing type var " + name); 838 return t; 839 } 840 throw badClassFile("undecl.type.var", name); 841 } 842 } 843 844/************************************************************************ 845 * Reading Attributes 846 ***********************************************************************/ 847 848 protected enum AttributeKind { CLASS, MEMBER } 849 850 protected abstract class AttributeReader { 851 protected AttributeReader(Name name, ClassFile.Version version, Set<AttributeKind> kinds) { 852 this.name = name; 853 this.version = version; 854 this.kinds = kinds; 855 } 856 857 protected boolean accepts(AttributeKind kind) { 858 if (kinds.contains(kind)) { 859 if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor)) 860 return true; 861 862 if (lintClassfile && !warnedAttrs.contains(name)) { 863 JavaFileObject prev = log.useSource(currentClassFile); 864 try { 865 log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr", 866 name, version.major, version.minor, majorVersion, minorVersion); 867 } finally { 868 log.useSource(prev); 869 } 870 warnedAttrs.add(name); 871 } 872 } 873 return false; 874 } 875 876 protected abstract void read(Symbol sym, int attrLen); 877 878 protected final Name name; 879 protected final ClassFile.Version version; 880 protected final Set<AttributeKind> kinds; 881 } 882 883 protected Set<AttributeKind> CLASS_ATTRIBUTE = 884 EnumSet.of(AttributeKind.CLASS); 885 protected Set<AttributeKind> MEMBER_ATTRIBUTE = 886 EnumSet.of(AttributeKind.MEMBER); 887 protected Set<AttributeKind> CLASS_OR_MEMBER_ATTRIBUTE = 888 EnumSet.of(AttributeKind.CLASS, AttributeKind.MEMBER); 889 890 protected Map<Name, AttributeReader> attributeReaders = new HashMap<>(); 891 892 private void initAttributeReaders() { 893 AttributeReader[] readers = { 894 // v45.3 attributes 895 896 new AttributeReader(names.Code, V45_3, MEMBER_ATTRIBUTE) { 897 protected void read(Symbol sym, int attrLen) { 898 if (readAllOfClassFile || saveParameterNames) 899 ((MethodSymbol)sym).code = readCode(sym); 900 else 901 bp = bp + attrLen; 902 } 903 }, 904 905 new AttributeReader(names.ConstantValue, V45_3, MEMBER_ATTRIBUTE) { 906 protected void read(Symbol sym, int attrLen) { 907 Object v = readPool(nextChar()); 908 // Ignore ConstantValue attribute if field not final. 909 if ((sym.flags() & FINAL) != 0) 910 ((VarSymbol) sym).setData(v); 911 } 912 }, 913 914 new AttributeReader(names.Deprecated, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) { 915 protected void read(Symbol sym, int attrLen) { 916 sym.flags_field |= DEPRECATED; 917 } 918 }, 919 920 new AttributeReader(names.Exceptions, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) { 921 protected void read(Symbol sym, int attrLen) { 922 int nexceptions = nextChar(); 923 List<Type> thrown = List.nil(); 924 for (int j = 0; j < nexceptions; j++) 925 thrown = thrown.prepend(readClassSymbol(nextChar()).type); 926 if (sym.type.getThrownTypes().isEmpty()) 927 sym.type.asMethodType().thrown = thrown.reverse(); 928 } 929 }, 930 931 new AttributeReader(names.InnerClasses, V45_3, CLASS_ATTRIBUTE) { 932 protected void read(Symbol sym, int attrLen) { 933 ClassSymbol c = (ClassSymbol) sym; 934 readInnerClasses(c); 935 } 936 }, 937 938 new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) { 939 protected void read(Symbol sym, int attrLen) { 940 int newbp = bp + attrLen; 941 if (saveParameterNames && !sawMethodParameters) { 942 // Pick up parameter names from the variable table. 943 // Parameter names are not explicitly identified as such, 944 // but all parameter name entries in the LocalVariableTable 945 // have a start_pc of 0. Therefore, we record the name 946 // indicies of all slots with a start_pc of zero in the 947 // parameterNameIndicies array. 948 // Note that this implicitly honors the JVMS spec that 949 // there may be more than one LocalVariableTable, and that 950 // there is no specified ordering for the entries. 951 int numEntries = nextChar(); 952 for (int i = 0; i < numEntries; i++) { 953 int start_pc = nextChar(); 954 int length = nextChar(); 955 int nameIndex = nextChar(); 956 int sigIndex = nextChar(); 957 int register = nextChar(); 958 if (start_pc == 0) { 959 // ensure array large enough 960 if (register >= parameterNameIndices.length) { 961 int newSize = Math.max(register, parameterNameIndices.length + 8); 962 parameterNameIndices = 963 Arrays.copyOf(parameterNameIndices, newSize); 964 } 965 parameterNameIndices[register] = nameIndex; 966 haveParameterNameIndices = true; 967 } 968 } 969 } 970 bp = newbp; 971 } 972 }, 973 974 new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) { 975 protected void read(Symbol sym, int attrlen) { 976 int newbp = bp + attrlen; 977 if (saveParameterNames) { 978 sawMethodParameters = true; 979 int numEntries = nextByte(); 980 parameterNameIndices = new int[numEntries]; 981 haveParameterNameIndices = true; 982 for (int i = 0; i < numEntries; i++) { 983 int nameIndex = nextChar(); 984 int flags = nextChar(); 985 parameterNameIndices[i] = nameIndex; 986 } 987 } 988 bp = newbp; 989 } 990 }, 991 992 993 new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) { 994 protected void read(Symbol sym, int attrLen) { 995 ClassSymbol c = (ClassSymbol) sym; 996 Name n = readName(nextChar()); 997 c.sourcefile = new SourceFileObject(n, c.flatname); 998 // If the class is a toplevel class, originating from a Java source file, 999 // but the class name does not match the file name, then it is 1000 // an auxiliary class. 1001 String sn = n.toString(); 1002 if (c.owner.kind == PCK && 1003 sn.endsWith(".java") && 1004 !sn.equals(c.name.toString()+".java")) { 1005 c.flags_field |= AUXILIARY; 1006 } 1007 } 1008 }, 1009 1010 new AttributeReader(names.Synthetic, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) { 1011 protected void read(Symbol sym, int attrLen) { 1012 sym.flags_field |= SYNTHETIC; 1013 } 1014 }, 1015 1016 // standard v49 attributes 1017 1018 new AttributeReader(names.EnclosingMethod, V49, CLASS_ATTRIBUTE) { 1019 protected void read(Symbol sym, int attrLen) { 1020 int newbp = bp + attrLen; 1021 readEnclosingMethodAttr(sym); 1022 bp = newbp; 1023 } 1024 }, 1025 1026 new AttributeReader(names.Signature, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1027 protected void read(Symbol sym, int attrLen) { 1028 if (sym.kind == TYP) { 1029 ClassSymbol c = (ClassSymbol) sym; 1030 readingClassAttr = true; 1031 try { 1032 ClassType ct1 = (ClassType)c.type; 1033 Assert.check(c == currentOwner); 1034 ct1.typarams_field = readTypeParams(nextChar()); 1035 ct1.supertype_field = sigToType(); 1036 ListBuffer<Type> is = new ListBuffer<>(); 1037 while (sigp != siglimit) is.append(sigToType()); 1038 ct1.interfaces_field = is.toList(); 1039 } finally { 1040 readingClassAttr = false; 1041 } 1042 } else { 1043 List<Type> thrown = sym.type.getThrownTypes(); 1044 sym.type = readType(nextChar()); 1045 //- System.err.println(" # " + sym.type); 1046 if (sym.kind == MTH && sym.type.getThrownTypes().isEmpty()) 1047 sym.type.asMethodType().thrown = thrown; 1048 1049 } 1050 } 1051 }, 1052 1053 // v49 annotation attributes 1054 1055 new AttributeReader(names.AnnotationDefault, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1056 protected void read(Symbol sym, int attrLen) { 1057 attachAnnotationDefault(sym); 1058 } 1059 }, 1060 1061 new AttributeReader(names.RuntimeInvisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1062 protected void read(Symbol sym, int attrLen) { 1063 attachAnnotations(sym); 1064 } 1065 }, 1066 1067 new AttributeReader(names.RuntimeInvisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1068 protected void read(Symbol sym, int attrLen) { 1069 attachParameterAnnotations(sym); 1070 } 1071 }, 1072 1073 new AttributeReader(names.RuntimeVisibleAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1074 protected void read(Symbol sym, int attrLen) { 1075 attachAnnotations(sym); 1076 } 1077 }, 1078 1079 new AttributeReader(names.RuntimeVisibleParameterAnnotations, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1080 protected void read(Symbol sym, int attrLen) { 1081 attachParameterAnnotations(sym); 1082 } 1083 }, 1084 1085 // additional "legacy" v49 attributes, superceded by flags 1086 1087 new AttributeReader(names.Annotation, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1088 protected void read(Symbol sym, int attrLen) { 1089 sym.flags_field |= ANNOTATION; 1090 } 1091 }, 1092 1093 new AttributeReader(names.Bridge, V49, MEMBER_ATTRIBUTE) { 1094 protected void read(Symbol sym, int attrLen) { 1095 sym.flags_field |= BRIDGE; 1096 } 1097 }, 1098 1099 new AttributeReader(names.Enum, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1100 protected void read(Symbol sym, int attrLen) { 1101 sym.flags_field |= ENUM; 1102 } 1103 }, 1104 1105 new AttributeReader(names.Varargs, V49, CLASS_OR_MEMBER_ATTRIBUTE) { 1106 protected void read(Symbol sym, int attrLen) { 1107 sym.flags_field |= VARARGS; 1108 } 1109 }, 1110 1111 new AttributeReader(names.RuntimeVisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) { 1112 protected void read(Symbol sym, int attrLen) { 1113 attachTypeAnnotations(sym); 1114 } 1115 }, 1116 1117 new AttributeReader(names.RuntimeInvisibleTypeAnnotations, V52, CLASS_OR_MEMBER_ATTRIBUTE) { 1118 protected void read(Symbol sym, int attrLen) { 1119 attachTypeAnnotations(sym); 1120 } 1121 }, 1122 1123 1124 // The following attributes for a Code attribute are not currently handled 1125 // StackMapTable 1126 // SourceDebugExtension 1127 // LineNumberTable 1128 // LocalVariableTypeTable 1129 }; 1130 1131 for (AttributeReader r: readers) 1132 attributeReaders.put(r.name, r); 1133 } 1134 1135 /** Report unrecognized attribute. 1136 */ 1137 void unrecognized(Name attrName) { 1138 if (checkClassFile) 1139 printCCF("ccf.unrecognized.attribute", attrName); 1140 } 1141 1142 1143 1144 protected void readEnclosingMethodAttr(Symbol sym) { 1145 // sym is a nested class with an "Enclosing Method" attribute 1146 // remove sym from it's current owners scope and place it in 1147 // the scope specified by the attribute 1148 sym.owner.members().remove(sym); 1149 ClassSymbol self = (ClassSymbol)sym; 1150 ClassSymbol c = readClassSymbol(nextChar()); 1151 NameAndType nt = readNameAndType(nextChar()); 1152 1153 if (c.members_field == null) 1154 throw badClassFile("bad.enclosing.class", self, c); 1155 1156 MethodSymbol m = findMethod(nt, c.members_field, self.flags()); 1157 if (nt != null && m == null) 1158 throw badClassFile("bad.enclosing.method", self); 1159 1160 self.name = simpleBinaryName(self.flatname, c.flatname) ; 1161 self.owner = m != null ? m : c; 1162 if (self.name.isEmpty()) 1163 self.fullname = names.empty; 1164 else 1165 self.fullname = ClassSymbol.formFullName(self.name, self.owner); 1166 1167 if (m != null) { 1168 ((ClassType)sym.type).setEnclosingType(m.type); 1169 } else if ((self.flags_field & STATIC) == 0) { 1170 ((ClassType)sym.type).setEnclosingType(c.type); 1171 } else { 1172 ((ClassType)sym.type).setEnclosingType(Type.noType); 1173 } 1174 enterTypevars(self); 1175 if (!missingTypeVariables.isEmpty()) { 1176 ListBuffer<Type> typeVars = new ListBuffer<>(); 1177 for (Type typevar : missingTypeVariables) { 1178 typeVars.append(findTypeVar(typevar.tsym.name)); 1179 } 1180 foundTypeVariables = typeVars.toList(); 1181 } else { 1182 foundTypeVariables = List.nil(); 1183 } 1184 } 1185 1186 // See java.lang.Class 1187 private Name simpleBinaryName(Name self, Name enclosing) { 1188 String simpleBinaryName = self.toString().substring(enclosing.toString().length()); 1189 if (simpleBinaryName.length() < 1 || simpleBinaryName.charAt(0) != '$') 1190 throw badClassFile("bad.enclosing.method", self); 1191 int index = 1; 1192 while (index < simpleBinaryName.length() && 1193 isAsciiDigit(simpleBinaryName.charAt(index))) 1194 index++; 1195 return names.fromString(simpleBinaryName.substring(index)); 1196 } 1197 1198 private MethodSymbol findMethod(NameAndType nt, Scope scope, long flags) { 1199 if (nt == null) 1200 return null; 1201 1202 MethodType type = nt.uniqueType.type.asMethodType(); 1203 1204 for (Symbol sym : scope.getSymbolsByName(nt.name)) { 1205 if (sym.kind == MTH && isSameBinaryType(sym.type.asMethodType(), type)) 1206 return (MethodSymbol)sym; 1207 } 1208 1209 if (nt.name != names.init) 1210 // not a constructor 1211 return null; 1212 if ((flags & INTERFACE) != 0) 1213 // no enclosing instance 1214 return null; 1215 if (nt.uniqueType.type.getParameterTypes().isEmpty()) 1216 // no parameters 1217 return null; 1218 1219 // A constructor of an inner class. 1220 // Remove the first argument (the enclosing instance) 1221 nt.setType(new MethodType(nt.uniqueType.type.getParameterTypes().tail, 1222 nt.uniqueType.type.getReturnType(), 1223 nt.uniqueType.type.getThrownTypes(), 1224 syms.methodClass)); 1225 // Try searching again 1226 return findMethod(nt, scope, flags); 1227 } 1228 1229 /** Similar to Types.isSameType but avoids completion */ 1230 private boolean isSameBinaryType(MethodType mt1, MethodType mt2) { 1231 List<Type> types1 = types.erasure(mt1.getParameterTypes()) 1232 .prepend(types.erasure(mt1.getReturnType())); 1233 List<Type> types2 = mt2.getParameterTypes().prepend(mt2.getReturnType()); 1234 while (!types1.isEmpty() && !types2.isEmpty()) { 1235 if (types1.head.tsym != types2.head.tsym) 1236 return false; 1237 types1 = types1.tail; 1238 types2 = types2.tail; 1239 } 1240 return types1.isEmpty() && types2.isEmpty(); 1241 } 1242 1243 /** 1244 * Character.isDigit answers <tt>true</tt> to some non-ascii 1245 * digits. This one does not. <b>copied from java.lang.Class</b> 1246 */ 1247 private static boolean isAsciiDigit(char c) { 1248 return '0' <= c && c <= '9'; 1249 } 1250 1251 /** Read member attributes. 1252 */ 1253 void readMemberAttrs(Symbol sym) { 1254 readAttrs(sym, AttributeKind.MEMBER); 1255 } 1256 1257 void readAttrs(Symbol sym, AttributeKind kind) { 1258 char ac = nextChar(); 1259 for (int i = 0; i < ac; i++) { 1260 Name attrName = readName(nextChar()); 1261 int attrLen = nextInt(); 1262 AttributeReader r = attributeReaders.get(attrName); 1263 if (r != null && r.accepts(kind)) 1264 r.read(sym, attrLen); 1265 else { 1266 unrecognized(attrName); 1267 bp = bp + attrLen; 1268 } 1269 } 1270 } 1271 1272 private boolean readingClassAttr = false; 1273 private List<Type> missingTypeVariables = List.nil(); 1274 private List<Type> foundTypeVariables = List.nil(); 1275 1276 /** Read class attributes. 1277 */ 1278 void readClassAttrs(ClassSymbol c) { 1279 readAttrs(c, AttributeKind.CLASS); 1280 } 1281 1282 /** Read code block. 1283 */ 1284 Code readCode(Symbol owner) { 1285 nextChar(); // max_stack 1286 nextChar(); // max_locals 1287 final int code_length = nextInt(); 1288 bp += code_length; 1289 final char exception_table_length = nextChar(); 1290 bp += exception_table_length * 8; 1291 readMemberAttrs(owner); 1292 return null; 1293 } 1294 1295/************************************************************************ 1296 * Reading Java-language annotations 1297 ***********************************************************************/ 1298 1299 /** Attach annotations. 1300 */ 1301 void attachAnnotations(final Symbol sym) { 1302 int numAttributes = nextChar(); 1303 if (numAttributes != 0) { 1304 ListBuffer<CompoundAnnotationProxy> proxies = new ListBuffer<>(); 1305 for (int i = 0; i<numAttributes; i++) { 1306 CompoundAnnotationProxy proxy = readCompoundAnnotation(); 1307 proxies.append(proxy); 1308 } 1309 annotate.normal(new AnnotationCompleter(sym, proxies.toList())); 1310 } 1311 } 1312 1313 /** Attach parameter annotations. 1314 */ 1315 void attachParameterAnnotations(final Symbol method) { 1316 final MethodSymbol meth = (MethodSymbol)method; 1317 int numParameters = buf[bp++] & 0xFF; 1318 List<VarSymbol> parameters = meth.params(); 1319 int pnum = 0; 1320 while (parameters.tail != null) { 1321 attachAnnotations(parameters.head); 1322 parameters = parameters.tail; 1323 pnum++; 1324 } 1325 if (pnum != numParameters) { 1326 throw badClassFile("bad.runtime.invisible.param.annotations", meth); 1327 } 1328 } 1329 1330 void attachTypeAnnotations(final Symbol sym) { 1331 int numAttributes = nextChar(); 1332 if (numAttributes != 0) { 1333 ListBuffer<TypeAnnotationProxy> proxies = new ListBuffer<>(); 1334 for (int i = 0; i < numAttributes; i++) 1335 proxies.append(readTypeAnnotation()); 1336 annotate.normal(new TypeAnnotationCompleter(sym, proxies.toList())); 1337 } 1338 } 1339 1340 /** Attach the default value for an annotation element. 1341 */ 1342 void attachAnnotationDefault(final Symbol sym) { 1343 final MethodSymbol meth = (MethodSymbol)sym; // only on methods 1344 final Attribute value = readAttributeValue(); 1345 1346 // The default value is set later during annotation. It might 1347 // be the case that the Symbol sym is annotated _after_ the 1348 // repeating instances that depend on this default value, 1349 // because of this we set an interim value that tells us this 1350 // element (most likely) has a default. 1351 // 1352 // Set interim value for now, reset just before we do this 1353 // properly at annotate time. 1354 meth.defaultValue = value; 1355 annotate.normal(new AnnotationDefaultCompleter(meth, value)); 1356 } 1357 1358 Type readTypeOrClassSymbol(int i) { 1359 // support preliminary jsr175-format class files 1360 if (buf[poolIdx[i]] == CONSTANT_Class) 1361 return readClassSymbol(i).type; 1362 return readType(i); 1363 } 1364 Type readEnumType(int i) { 1365 // support preliminary jsr175-format class files 1366 int index = poolIdx[i]; 1367 int length = getChar(index + 1); 1368 if (buf[index + length + 2] != ';') 1369 return syms.enterClass(readName(i)).type; 1370 return readType(i); 1371 } 1372 1373 CompoundAnnotationProxy readCompoundAnnotation() { 1374 Type t = readTypeOrClassSymbol(nextChar()); 1375 int numFields = nextChar(); 1376 ListBuffer<Pair<Name,Attribute>> pairs = new ListBuffer<>(); 1377 for (int i=0; i<numFields; i++) { 1378 Name name = readName(nextChar()); 1379 Attribute value = readAttributeValue(); 1380 pairs.append(new Pair<>(name, value)); 1381 } 1382 return new CompoundAnnotationProxy(t, pairs.toList()); 1383 } 1384 1385 TypeAnnotationProxy readTypeAnnotation() { 1386 TypeAnnotationPosition position = readPosition(); 1387 CompoundAnnotationProxy proxy = readCompoundAnnotation(); 1388 1389 return new TypeAnnotationProxy(proxy, position); 1390 } 1391 1392 TypeAnnotationPosition readPosition() { 1393 int tag = nextByte(); // TargetType tag is a byte 1394 1395 if (!TargetType.isValidTargetTypeValue(tag)) 1396 throw badClassFile("bad.type.annotation.value", String.format("0x%02X", tag)); 1397 1398 TargetType type = TargetType.fromTargetTypeValue(tag); 1399 1400 switch (type) { 1401 // instanceof 1402 case INSTANCEOF: { 1403 final int offset = nextChar(); 1404 final TypeAnnotationPosition position = 1405 TypeAnnotationPosition.instanceOf(readTypePath()); 1406 position.offset = offset; 1407 return position; 1408 } 1409 // new expression 1410 case NEW: { 1411 final int offset = nextChar(); 1412 final TypeAnnotationPosition position = 1413 TypeAnnotationPosition.newObj(readTypePath()); 1414 position.offset = offset; 1415 return position; 1416 } 1417 // constructor/method reference receiver 1418 case CONSTRUCTOR_REFERENCE: { 1419 final int offset = nextChar(); 1420 final TypeAnnotationPosition position = 1421 TypeAnnotationPosition.constructorRef(readTypePath()); 1422 position.offset = offset; 1423 return position; 1424 } 1425 case METHOD_REFERENCE: { 1426 final int offset = nextChar(); 1427 final TypeAnnotationPosition position = 1428 TypeAnnotationPosition.methodRef(readTypePath()); 1429 position.offset = offset; 1430 return position; 1431 } 1432 // local variable 1433 case LOCAL_VARIABLE: { 1434 final int table_length = nextChar(); 1435 final int[] newLvarOffset = new int[table_length]; 1436 final int[] newLvarLength = new int[table_length]; 1437 final int[] newLvarIndex = new int[table_length]; 1438 1439 for (int i = 0; i < table_length; ++i) { 1440 newLvarOffset[i] = nextChar(); 1441 newLvarLength[i] = nextChar(); 1442 newLvarIndex[i] = nextChar(); 1443 } 1444 1445 final TypeAnnotationPosition position = 1446 TypeAnnotationPosition.localVariable(readTypePath()); 1447 position.lvarOffset = newLvarOffset; 1448 position.lvarLength = newLvarLength; 1449 position.lvarIndex = newLvarIndex; 1450 return position; 1451 } 1452 // resource variable 1453 case RESOURCE_VARIABLE: { 1454 final int table_length = nextChar(); 1455 final int[] newLvarOffset = new int[table_length]; 1456 final int[] newLvarLength = new int[table_length]; 1457 final int[] newLvarIndex = new int[table_length]; 1458 1459 for (int i = 0; i < table_length; ++i) { 1460 newLvarOffset[i] = nextChar(); 1461 newLvarLength[i] = nextChar(); 1462 newLvarIndex[i] = nextChar(); 1463 } 1464 1465 final TypeAnnotationPosition position = 1466 TypeAnnotationPosition.resourceVariable(readTypePath()); 1467 position.lvarOffset = newLvarOffset; 1468 position.lvarLength = newLvarLength; 1469 position.lvarIndex = newLvarIndex; 1470 return position; 1471 } 1472 // exception parameter 1473 case EXCEPTION_PARAMETER: { 1474 final int exception_index = nextChar(); 1475 final TypeAnnotationPosition position = 1476 TypeAnnotationPosition.exceptionParameter(readTypePath()); 1477 position.setExceptionIndex(exception_index); 1478 return position; 1479 } 1480 // method receiver 1481 case METHOD_RECEIVER: 1482 return TypeAnnotationPosition.methodReceiver(readTypePath()); 1483 // type parameter 1484 case CLASS_TYPE_PARAMETER: { 1485 final int parameter_index = nextByte(); 1486 return TypeAnnotationPosition 1487 .typeParameter(readTypePath(), parameter_index); 1488 } 1489 case METHOD_TYPE_PARAMETER: { 1490 final int parameter_index = nextByte(); 1491 return TypeAnnotationPosition 1492 .methodTypeParameter(readTypePath(), parameter_index); 1493 } 1494 // type parameter bound 1495 case CLASS_TYPE_PARAMETER_BOUND: { 1496 final int parameter_index = nextByte(); 1497 final int bound_index = nextByte(); 1498 return TypeAnnotationPosition 1499 .typeParameterBound(readTypePath(), parameter_index, 1500 bound_index); 1501 } 1502 case METHOD_TYPE_PARAMETER_BOUND: { 1503 final int parameter_index = nextByte(); 1504 final int bound_index = nextByte(); 1505 return TypeAnnotationPosition 1506 .methodTypeParameterBound(readTypePath(), parameter_index, 1507 bound_index); 1508 } 1509 // class extends or implements clause 1510 case CLASS_EXTENDS: { 1511 final int type_index = nextChar(); 1512 return TypeAnnotationPosition.classExtends(readTypePath(), 1513 type_index); 1514 } 1515 // throws 1516 case THROWS: { 1517 final int type_index = nextChar(); 1518 return TypeAnnotationPosition.methodThrows(readTypePath(), 1519 type_index); 1520 } 1521 // method parameter 1522 case METHOD_FORMAL_PARAMETER: { 1523 final int parameter_index = nextByte(); 1524 return TypeAnnotationPosition.methodParameter(readTypePath(), 1525 parameter_index); 1526 } 1527 // type cast 1528 case CAST: { 1529 final int offset = nextChar(); 1530 final int type_index = nextByte(); 1531 final TypeAnnotationPosition position = 1532 TypeAnnotationPosition.typeCast(readTypePath(), type_index); 1533 position.offset = offset; 1534 return position; 1535 } 1536 // method/constructor/reference type argument 1537 case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: { 1538 final int offset = nextChar(); 1539 final int type_index = nextByte(); 1540 final TypeAnnotationPosition position = TypeAnnotationPosition 1541 .constructorInvocationTypeArg(readTypePath(), type_index); 1542 position.offset = offset; 1543 return position; 1544 } 1545 case METHOD_INVOCATION_TYPE_ARGUMENT: { 1546 final int offset = nextChar(); 1547 final int type_index = nextByte(); 1548 final TypeAnnotationPosition position = TypeAnnotationPosition 1549 .methodInvocationTypeArg(readTypePath(), type_index); 1550 position.offset = offset; 1551 return position; 1552 } 1553 case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: { 1554 final int offset = nextChar(); 1555 final int type_index = nextByte(); 1556 final TypeAnnotationPosition position = TypeAnnotationPosition 1557 .constructorRefTypeArg(readTypePath(), type_index); 1558 position.offset = offset; 1559 return position; 1560 } 1561 case METHOD_REFERENCE_TYPE_ARGUMENT: { 1562 final int offset = nextChar(); 1563 final int type_index = nextByte(); 1564 final TypeAnnotationPosition position = TypeAnnotationPosition 1565 .methodRefTypeArg(readTypePath(), type_index); 1566 position.offset = offset; 1567 return position; 1568 } 1569 // We don't need to worry about these 1570 case METHOD_RETURN: 1571 return TypeAnnotationPosition.methodReturn(readTypePath()); 1572 case FIELD: 1573 return TypeAnnotationPosition.field(readTypePath()); 1574 case UNKNOWN: 1575 throw new AssertionError("jvm.ClassReader: UNKNOWN target type should never occur!"); 1576 default: 1577 throw new AssertionError("jvm.ClassReader: Unknown target type for position: " + type); 1578 } 1579 } 1580 1581 List<TypeAnnotationPosition.TypePathEntry> readTypePath() { 1582 int len = nextByte(); 1583 ListBuffer<Integer> loc = new ListBuffer<>(); 1584 for (int i = 0; i < len * TypeAnnotationPosition.TypePathEntry.bytesPerEntry; ++i) 1585 loc = loc.append(nextByte()); 1586 1587 return TypeAnnotationPosition.getTypePathFromBinary(loc.toList()); 1588 1589 } 1590 1591 Attribute readAttributeValue() { 1592 char c = (char) buf[bp++]; 1593 switch (c) { 1594 case 'B': 1595 return new Attribute.Constant(syms.byteType, readPool(nextChar())); 1596 case 'C': 1597 return new Attribute.Constant(syms.charType, readPool(nextChar())); 1598 case 'D': 1599 return new Attribute.Constant(syms.doubleType, readPool(nextChar())); 1600 case 'F': 1601 return new Attribute.Constant(syms.floatType, readPool(nextChar())); 1602 case 'I': 1603 return new Attribute.Constant(syms.intType, readPool(nextChar())); 1604 case 'J': 1605 return new Attribute.Constant(syms.longType, readPool(nextChar())); 1606 case 'S': 1607 return new Attribute.Constant(syms.shortType, readPool(nextChar())); 1608 case 'Z': 1609 return new Attribute.Constant(syms.booleanType, readPool(nextChar())); 1610 case 's': 1611 return new Attribute.Constant(syms.stringType, readPool(nextChar()).toString()); 1612 case 'e': 1613 return new EnumAttributeProxy(readEnumType(nextChar()), readName(nextChar())); 1614 case 'c': 1615 return new Attribute.Class(types, readTypeOrClassSymbol(nextChar())); 1616 case '[': { 1617 int n = nextChar(); 1618 ListBuffer<Attribute> l = new ListBuffer<>(); 1619 for (int i=0; i<n; i++) 1620 l.append(readAttributeValue()); 1621 return new ArrayAttributeProxy(l.toList()); 1622 } 1623 case '@': 1624 return readCompoundAnnotation(); 1625 default: 1626 throw new AssertionError("unknown annotation tag '" + c + "'"); 1627 } 1628 } 1629 1630 interface ProxyVisitor extends Attribute.Visitor { 1631 void visitEnumAttributeProxy(EnumAttributeProxy proxy); 1632 void visitArrayAttributeProxy(ArrayAttributeProxy proxy); 1633 void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy); 1634 } 1635 1636 static class EnumAttributeProxy extends Attribute { 1637 Type enumType; 1638 Name enumerator; 1639 public EnumAttributeProxy(Type enumType, Name enumerator) { 1640 super(null); 1641 this.enumType = enumType; 1642 this.enumerator = enumerator; 1643 } 1644 public void accept(Visitor v) { ((ProxyVisitor)v).visitEnumAttributeProxy(this); } 1645 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1646 public String toString() { 1647 return "/*proxy enum*/" + enumType + "." + enumerator; 1648 } 1649 } 1650 1651 static class ArrayAttributeProxy extends Attribute { 1652 List<Attribute> values; 1653 ArrayAttributeProxy(List<Attribute> values) { 1654 super(null); 1655 this.values = values; 1656 } 1657 public void accept(Visitor v) { ((ProxyVisitor)v).visitArrayAttributeProxy(this); } 1658 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1659 public String toString() { 1660 return "{" + values + "}"; 1661 } 1662 } 1663 1664 /** A temporary proxy representing a compound attribute. 1665 */ 1666 static class CompoundAnnotationProxy extends Attribute { 1667 final List<Pair<Name,Attribute>> values; 1668 public CompoundAnnotationProxy(Type type, 1669 List<Pair<Name,Attribute>> values) { 1670 super(type); 1671 this.values = values; 1672 } 1673 public void accept(Visitor v) { ((ProxyVisitor)v).visitCompoundAnnotationProxy(this); } 1674 @Override @DefinedBy(Api.LANGUAGE_MODEL) 1675 public String toString() { 1676 StringBuilder buf = new StringBuilder(); 1677 buf.append("@"); 1678 buf.append(type.tsym.getQualifiedName()); 1679 buf.append("/*proxy*/{"); 1680 boolean first = true; 1681 for (List<Pair<Name,Attribute>> v = values; 1682 v.nonEmpty(); v = v.tail) { 1683 Pair<Name,Attribute> value = v.head; 1684 if (!first) buf.append(","); 1685 first = false; 1686 buf.append(value.fst); 1687 buf.append("="); 1688 buf.append(value.snd); 1689 } 1690 buf.append("}"); 1691 return buf.toString(); 1692 } 1693 } 1694 1695 /** A temporary proxy representing a type annotation. 1696 */ 1697 static class TypeAnnotationProxy { 1698 final CompoundAnnotationProxy compound; 1699 final TypeAnnotationPosition position; 1700 public TypeAnnotationProxy(CompoundAnnotationProxy compound, 1701 TypeAnnotationPosition position) { 1702 this.compound = compound; 1703 this.position = position; 1704 } 1705 } 1706 1707 class AnnotationDeproxy implements ProxyVisitor { 1708 private ClassSymbol requestingOwner = currentOwner.kind == MTH 1709 ? currentOwner.enclClass() : (ClassSymbol)currentOwner; 1710 1711 List<Attribute.Compound> deproxyCompoundList(List<CompoundAnnotationProxy> pl) { 1712 // also must fill in types!!!! 1713 ListBuffer<Attribute.Compound> buf = new ListBuffer<>(); 1714 for (List<CompoundAnnotationProxy> l = pl; l.nonEmpty(); l=l.tail) { 1715 buf.append(deproxyCompound(l.head)); 1716 } 1717 return buf.toList(); 1718 } 1719 1720 Attribute.Compound deproxyCompound(CompoundAnnotationProxy a) { 1721 ListBuffer<Pair<Symbol.MethodSymbol,Attribute>> buf = new ListBuffer<>(); 1722 for (List<Pair<Name,Attribute>> l = a.values; 1723 l.nonEmpty(); 1724 l = l.tail) { 1725 MethodSymbol meth = findAccessMethod(a.type, l.head.fst); 1726 buf.append(new Pair<>(meth, deproxy(meth.type.getReturnType(), l.head.snd))); 1727 } 1728 return new Attribute.Compound(a.type, buf.toList()); 1729 } 1730 1731 MethodSymbol findAccessMethod(Type container, Name name) { 1732 CompletionFailure failure = null; 1733 try { 1734 for (Symbol sym : container.tsym.members().getSymbolsByName(name)) { 1735 if (sym.kind == MTH && sym.type.getParameterTypes().length() == 0) 1736 return (MethodSymbol) sym; 1737 } 1738 } catch (CompletionFailure ex) { 1739 failure = ex; 1740 } 1741 // The method wasn't found: emit a warning and recover 1742 JavaFileObject prevSource = log.useSource(requestingOwner.classfile); 1743 try { 1744 if (lintClassfile) { 1745 if (failure == null) { 1746 log.warning("annotation.method.not.found", 1747 container, 1748 name); 1749 } else { 1750 log.warning("annotation.method.not.found.reason", 1751 container, 1752 name, 1753 failure.getDetailValue());//diagnostic, if present 1754 } 1755 } 1756 } finally { 1757 log.useSource(prevSource); 1758 } 1759 // Construct a new method type and symbol. Use bottom 1760 // type (typeof null) as return type because this type is 1761 // a subtype of all reference types and can be converted 1762 // to primitive types by unboxing. 1763 MethodType mt = new MethodType(List.<Type>nil(), 1764 syms.botType, 1765 List.<Type>nil(), 1766 syms.methodClass); 1767 return new MethodSymbol(PUBLIC | ABSTRACT, name, mt, container.tsym); 1768 } 1769 1770 Attribute result; 1771 Type type; 1772 Attribute deproxy(Type t, Attribute a) { 1773 Type oldType = type; 1774 try { 1775 type = t; 1776 a.accept(this); 1777 return result; 1778 } finally { 1779 type = oldType; 1780 } 1781 } 1782 1783 // implement Attribute.Visitor below 1784 1785 public void visitConstant(Attribute.Constant value) { 1786 // assert value.type == type; 1787 result = value; 1788 } 1789 1790 public void visitClass(Attribute.Class clazz) { 1791 result = clazz; 1792 } 1793 1794 public void visitEnum(Attribute.Enum e) { 1795 throw new AssertionError(); // shouldn't happen 1796 } 1797 1798 public void visitCompound(Attribute.Compound compound) { 1799 throw new AssertionError(); // shouldn't happen 1800 } 1801 1802 public void visitArray(Attribute.Array array) { 1803 throw new AssertionError(); // shouldn't happen 1804 } 1805 1806 public void visitError(Attribute.Error e) { 1807 throw new AssertionError(); // shouldn't happen 1808 } 1809 1810 public void visitEnumAttributeProxy(EnumAttributeProxy proxy) { 1811 // type.tsym.flatName() should == proxy.enumFlatName 1812 TypeSymbol enumTypeSym = proxy.enumType.tsym; 1813 VarSymbol enumerator = null; 1814 CompletionFailure failure = null; 1815 try { 1816 for (Symbol sym : enumTypeSym.members().getSymbolsByName(proxy.enumerator)) { 1817 if (sym.kind == VAR) { 1818 enumerator = (VarSymbol)sym; 1819 break; 1820 } 1821 } 1822 } 1823 catch (CompletionFailure ex) { 1824 failure = ex; 1825 } 1826 if (enumerator == null) { 1827 if (failure != null) { 1828 log.warning("unknown.enum.constant.reason", 1829 currentClassFile, enumTypeSym, proxy.enumerator, 1830 failure.getDiagnostic()); 1831 } else { 1832 log.warning("unknown.enum.constant", 1833 currentClassFile, enumTypeSym, proxy.enumerator); 1834 } 1835 result = new Attribute.Enum(enumTypeSym.type, 1836 new VarSymbol(0, proxy.enumerator, syms.botType, enumTypeSym)); 1837 } else { 1838 result = new Attribute.Enum(enumTypeSym.type, enumerator); 1839 } 1840 } 1841 1842 public void visitArrayAttributeProxy(ArrayAttributeProxy proxy) { 1843 int length = proxy.values.length(); 1844 Attribute[] ats = new Attribute[length]; 1845 Type elemtype = types.elemtype(type); 1846 int i = 0; 1847 for (List<Attribute> p = proxy.values; p.nonEmpty(); p = p.tail) { 1848 ats[i++] = deproxy(elemtype, p.head); 1849 } 1850 result = new Attribute.Array(type, ats); 1851 } 1852 1853 public void visitCompoundAnnotationProxy(CompoundAnnotationProxy proxy) { 1854 result = deproxyCompound(proxy); 1855 } 1856 } 1857 1858 class AnnotationDefaultCompleter extends AnnotationDeproxy implements Annotate.Worker { 1859 final MethodSymbol sym; 1860 final Attribute value; 1861 final JavaFileObject classFile = currentClassFile; 1862 @Override 1863 public String toString() { 1864 return " ClassReader store default for " + sym.owner + "." + sym + " is " + value; 1865 } 1866 AnnotationDefaultCompleter(MethodSymbol sym, Attribute value) { 1867 this.sym = sym; 1868 this.value = value; 1869 } 1870 // implement Annotate.Worker.run() 1871 public void run() { 1872 JavaFileObject previousClassFile = currentClassFile; 1873 try { 1874 // Reset the interim value set earlier in 1875 // attachAnnotationDefault(). 1876 sym.defaultValue = null; 1877 currentClassFile = classFile; 1878 sym.defaultValue = deproxy(sym.type.getReturnType(), value); 1879 } finally { 1880 currentClassFile = previousClassFile; 1881 } 1882 } 1883 } 1884 1885 class AnnotationCompleter extends AnnotationDeproxy implements Annotate.Worker { 1886 final Symbol sym; 1887 final List<CompoundAnnotationProxy> l; 1888 final JavaFileObject classFile; 1889 @Override 1890 public String toString() { 1891 return " ClassReader annotate " + sym.owner + "." + sym + " with " + l; 1892 } 1893 AnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l) { 1894 this.sym = sym; 1895 this.l = l; 1896 this.classFile = currentClassFile; 1897 } 1898 // implement Annotate.Worker.run() 1899 public void run() { 1900 JavaFileObject previousClassFile = currentClassFile; 1901 try { 1902 currentClassFile = classFile; 1903 List<Attribute.Compound> newList = deproxyCompoundList(l); 1904 if (sym.annotationsPendingCompletion()) { 1905 sym.setDeclarationAttributes(newList); 1906 } else { 1907 sym.appendAttributes(newList); 1908 } 1909 } finally { 1910 currentClassFile = previousClassFile; 1911 } 1912 } 1913 } 1914 1915 class TypeAnnotationCompleter extends AnnotationCompleter { 1916 1917 List<TypeAnnotationProxy> proxies; 1918 1919 TypeAnnotationCompleter(Symbol sym, 1920 List<TypeAnnotationProxy> proxies) { 1921 super(sym, List.<CompoundAnnotationProxy>nil()); 1922 this.proxies = proxies; 1923 } 1924 1925 List<Attribute.TypeCompound> deproxyTypeCompoundList(List<TypeAnnotationProxy> proxies) { 1926 ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>(); 1927 for (TypeAnnotationProxy proxy: proxies) { 1928 Attribute.Compound compound = deproxyCompound(proxy.compound); 1929 Attribute.TypeCompound typeCompound = new Attribute.TypeCompound(compound, proxy.position); 1930 buf.add(typeCompound); 1931 } 1932 return buf.toList(); 1933 } 1934 1935 @Override 1936 public void run() { 1937 JavaFileObject previousClassFile = currentClassFile; 1938 try { 1939 currentClassFile = classFile; 1940 List<Attribute.TypeCompound> newList = deproxyTypeCompoundList(proxies); 1941 sym.setTypeAttributes(newList.prependList(sym.getRawTypeAttributes())); 1942 } finally { 1943 currentClassFile = previousClassFile; 1944 } 1945 } 1946 } 1947 1948 1949/************************************************************************ 1950 * Reading Symbols 1951 ***********************************************************************/ 1952 1953 /** Read a field. 1954 */ 1955 VarSymbol readField() { 1956 long flags = adjustFieldFlags(nextChar()); 1957 Name name = readName(nextChar()); 1958 Type type = readType(nextChar()); 1959 VarSymbol v = new VarSymbol(flags, name, type, currentOwner); 1960 readMemberAttrs(v); 1961 return v; 1962 } 1963 1964 /** Read a method. 1965 */ 1966 MethodSymbol readMethod() { 1967 long flags = adjustMethodFlags(nextChar()); 1968 Name name = readName(nextChar()); 1969 Type type = readType(nextChar()); 1970 if (currentOwner.isInterface() && 1971 (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) { 1972 if (majorVersion > Version.V52.major || 1973 (majorVersion == Version.V52.major && minorVersion >= Version.V52.minor)) { 1974 if ((flags & STATIC) == 0) { 1975 currentOwner.flags_field |= DEFAULT; 1976 flags |= DEFAULT | ABSTRACT; 1977 } 1978 } else { 1979 //protect against ill-formed classfiles 1980 throw badClassFile((flags & STATIC) == 0 ? "invalid.default.interface" : "invalid.static.interface", 1981 Integer.toString(majorVersion), 1982 Integer.toString(minorVersion)); 1983 } 1984 } 1985 if (name == names.init && currentOwner.hasOuterInstance()) { 1986 // Sometimes anonymous classes don't have an outer 1987 // instance, however, there is no reliable way to tell so 1988 // we never strip this$n 1989 if (!currentOwner.name.isEmpty()) 1990 type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()), 1991 type.getReturnType(), 1992 type.getThrownTypes(), 1993 syms.methodClass); 1994 } 1995 MethodSymbol m = new MethodSymbol(flags, name, type, currentOwner); 1996 if (types.isSignaturePolymorphic(m)) { 1997 m.flags_field |= SIGNATURE_POLYMORPHIC; 1998 } 1999 if (saveParameterNames) 2000 initParameterNames(m); 2001 Symbol prevOwner = currentOwner; 2002 currentOwner = m; 2003 try { 2004 readMemberAttrs(m); 2005 } finally { 2006 currentOwner = prevOwner; 2007 } 2008 if (saveParameterNames) 2009 setParameterNames(m, type); 2010 2011 if ((flags & VARARGS) != 0) { 2012 final Type last = type.getParameterTypes().last(); 2013 if (last == null || !last.hasTag(ARRAY)) { 2014 m.flags_field &= ~VARARGS; 2015 throw badClassFile("malformed.vararg.method", m); 2016 } 2017 } 2018 2019 return m; 2020 } 2021 2022 private List<Type> adjustMethodParams(long flags, List<Type> args) { 2023 boolean isVarargs = (flags & VARARGS) != 0; 2024 if (isVarargs) { 2025 Type varargsElem = args.last(); 2026 ListBuffer<Type> adjustedArgs = new ListBuffer<>(); 2027 for (Type t : args) { 2028 adjustedArgs.append(t != varargsElem ? 2029 t : 2030 ((ArrayType)t).makeVarargs()); 2031 } 2032 args = adjustedArgs.toList(); 2033 } 2034 return args.tail; 2035 } 2036 2037 /** 2038 * Init the parameter names array. 2039 * Parameter names are currently inferred from the names in the 2040 * LocalVariableTable attributes of a Code attribute. 2041 * (Note: this means parameter names are currently not available for 2042 * methods without a Code attribute.) 2043 * This method initializes an array in which to store the name indexes 2044 * of parameter names found in LocalVariableTable attributes. It is 2045 * slightly supersized to allow for additional slots with a start_pc of 0. 2046 */ 2047 void initParameterNames(MethodSymbol sym) { 2048 // make allowance for synthetic parameters. 2049 final int excessSlots = 4; 2050 int expectedParameterSlots = 2051 Code.width(sym.type.getParameterTypes()) + excessSlots; 2052 if (parameterNameIndices == null 2053 || parameterNameIndices.length < expectedParameterSlots) { 2054 parameterNameIndices = new int[expectedParameterSlots]; 2055 } else 2056 Arrays.fill(parameterNameIndices, 0); 2057 haveParameterNameIndices = false; 2058 sawMethodParameters = false; 2059 } 2060 2061 /** 2062 * Set the parameter names for a symbol from the name index in the 2063 * parameterNameIndicies array. The type of the symbol may have changed 2064 * while reading the method attributes (see the Signature attribute). 2065 * This may be because of generic information or because anonymous 2066 * synthetic parameters were added. The original type (as read from 2067 * the method descriptor) is used to help guess the existence of 2068 * anonymous synthetic parameters. 2069 * On completion, sym.savedParameter names will either be null (if 2070 * no parameter names were found in the class file) or will be set to a 2071 * list of names, one per entry in sym.type.getParameterTypes, with 2072 * any missing names represented by the empty name. 2073 */ 2074 void setParameterNames(MethodSymbol sym, Type jvmType) { 2075 // if no names were found in the class file, there's nothing more to do 2076 if (!haveParameterNameIndices) 2077 return; 2078 // If we get parameter names from MethodParameters, then we 2079 // don't need to skip. 2080 int firstParam = 0; 2081 if (!sawMethodParameters) { 2082 firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0; 2083 // the code in readMethod may have skipped the first 2084 // parameter when setting up the MethodType. If so, we 2085 // make a corresponding allowance here for the position of 2086 // the first parameter. Note that this assumes the 2087 // skipped parameter has a width of 1 -- i.e. it is not 2088 // a double width type (long or double.) 2089 if (sym.name == names.init && currentOwner.hasOuterInstance()) { 2090 // Sometimes anonymous classes don't have an outer 2091 // instance, however, there is no reliable way to tell so 2092 // we never strip this$n 2093 if (!currentOwner.name.isEmpty()) 2094 firstParam += 1; 2095 } 2096 2097 if (sym.type != jvmType) { 2098 // reading the method attributes has caused the 2099 // symbol's type to be changed. (i.e. the Signature 2100 // attribute.) This may happen if there are hidden 2101 // (synthetic) parameters in the descriptor, but not 2102 // in the Signature. The position of these hidden 2103 // parameters is unspecified; for now, assume they are 2104 // at the beginning, and so skip over them. The 2105 // primary case for this is two hidden parameters 2106 // passed into Enum constructors. 2107 int skip = Code.width(jvmType.getParameterTypes()) 2108 - Code.width(sym.type.getParameterTypes()); 2109 firstParam += skip; 2110 } 2111 } 2112 List<Name> paramNames = List.nil(); 2113 int index = firstParam; 2114 for (Type t: sym.type.getParameterTypes()) { 2115 int nameIdx = (index < parameterNameIndices.length 2116 ? parameterNameIndices[index] : 0); 2117 Name name = nameIdx == 0 ? names.empty : readName(nameIdx); 2118 paramNames = paramNames.prepend(name); 2119 index += Code.width(t); 2120 } 2121 sym.savedParameterNames = paramNames.reverse(); 2122 } 2123 2124 /** 2125 * skip n bytes 2126 */ 2127 void skipBytes(int n) { 2128 bp = bp + n; 2129 } 2130 2131 /** Skip a field or method 2132 */ 2133 void skipMember() { 2134 bp = bp + 6; 2135 char ac = nextChar(); 2136 for (int i = 0; i < ac; i++) { 2137 bp = bp + 2; 2138 int attrLen = nextInt(); 2139 bp = bp + attrLen; 2140 } 2141 } 2142 2143 /** Enter type variables of this classtype and all enclosing ones in 2144 * `typevars'. 2145 */ 2146 protected void enterTypevars(Type t) { 2147 if (t.getEnclosingType() != null && t.getEnclosingType().hasTag(CLASS)) 2148 enterTypevars(t.getEnclosingType()); 2149 for (List<Type> xs = t.getTypeArguments(); xs.nonEmpty(); xs = xs.tail) 2150 typevars.enter(xs.head.tsym); 2151 } 2152 2153 protected void enterTypevars(Symbol sym) { 2154 if (sym.owner.kind == MTH) { 2155 enterTypevars(sym.owner); 2156 enterTypevars(sym.owner.owner); 2157 } 2158 enterTypevars(sym.type); 2159 } 2160 2161 /** Read contents of a given class symbol `c'. Both external and internal 2162 * versions of an inner class are read. 2163 */ 2164 void readClass(ClassSymbol c) { 2165 ClassType ct = (ClassType)c.type; 2166 2167 // allocate scope for members 2168 c.members_field = WriteableScope.create(c); 2169 2170 // prepare type variable table 2171 typevars = typevars.dup(currentOwner); 2172 if (ct.getEnclosingType().hasTag(CLASS)) 2173 enterTypevars(ct.getEnclosingType()); 2174 2175 // read flags, or skip if this is an inner class 2176 long flags = adjustClassFlags(nextChar()); 2177 if (c.owner.kind == PCK) c.flags_field = flags; 2178 2179 // read own class name and check that it matches 2180 ClassSymbol self = readClassSymbol(nextChar()); 2181 if (c != self) 2182 throw badClassFile("class.file.wrong.class", 2183 self.flatname); 2184 2185 // class attributes must be read before class 2186 // skip ahead to read class attributes 2187 int startbp = bp; 2188 nextChar(); 2189 char interfaceCount = nextChar(); 2190 bp += interfaceCount * 2; 2191 char fieldCount = nextChar(); 2192 for (int i = 0; i < fieldCount; i++) skipMember(); 2193 char methodCount = nextChar(); 2194 for (int i = 0; i < methodCount; i++) skipMember(); 2195 readClassAttrs(c); 2196 2197 if (readAllOfClassFile) { 2198 for (int i = 1; i < poolObj.length; i++) readPool(i); 2199 c.pool = new Pool(poolObj.length, poolObj, types); 2200 } 2201 2202 // reset and read rest of classinfo 2203 bp = startbp; 2204 int n = nextChar(); 2205 if (ct.supertype_field == null) 2206 ct.supertype_field = (n == 0) 2207 ? Type.noType 2208 : readClassSymbol(n).erasure(types); 2209 n = nextChar(); 2210 List<Type> is = List.nil(); 2211 for (int i = 0; i < n; i++) { 2212 Type _inter = readClassSymbol(nextChar()).erasure(types); 2213 is = is.prepend(_inter); 2214 } 2215 if (ct.interfaces_field == null) 2216 ct.interfaces_field = is.reverse(); 2217 2218 Assert.check(fieldCount == nextChar()); 2219 for (int i = 0; i < fieldCount; i++) enterMember(c, readField()); 2220 Assert.check(methodCount == nextChar()); 2221 for (int i = 0; i < methodCount; i++) enterMember(c, readMethod()); 2222 2223 typevars = typevars.leave(); 2224 } 2225 2226 /** Read inner class info. For each inner/outer pair allocate a 2227 * member class. 2228 */ 2229 void readInnerClasses(ClassSymbol c) { 2230 int n = nextChar(); 2231 for (int i = 0; i < n; i++) { 2232 nextChar(); // skip inner class symbol 2233 ClassSymbol outer = readClassSymbol(nextChar()); 2234 Name name = readName(nextChar()); 2235 if (name == null) name = names.empty; 2236 long flags = adjustClassFlags(nextChar()); 2237 if (outer != null) { // we have a member class 2238 if (name == names.empty) 2239 name = names.one; 2240 ClassSymbol member = syms.enterClass(name, outer); 2241 if ((flags & STATIC) == 0) { 2242 ((ClassType)member.type).setEnclosingType(outer.type); 2243 if (member.erasure_field != null) 2244 ((ClassType)member.erasure_field).setEnclosingType(types.erasure(outer.type)); 2245 } 2246 if (c == outer) { 2247 member.flags_field = flags; 2248 enterMember(c, member); 2249 } 2250 } 2251 } 2252 } 2253 2254 /** Read a class definition from the bytes in buf. 2255 */ 2256 private void readClassBuffer(ClassSymbol c) throws IOException { 2257 int magic = nextInt(); 2258 if (magic != JAVA_MAGIC) 2259 throw badClassFile("illegal.start.of.class.file"); 2260 2261 minorVersion = nextChar(); 2262 majorVersion = nextChar(); 2263 int maxMajor = Version.MAX().major; 2264 int maxMinor = Version.MAX().minor; 2265 if (majorVersion > maxMajor || 2266 majorVersion * 1000 + minorVersion < 2267 Version.MIN().major * 1000 + Version.MIN().minor) 2268 { 2269 if (majorVersion == (maxMajor + 1)) 2270 log.warning("big.major.version", 2271 currentClassFile, 2272 majorVersion, 2273 maxMajor); 2274 else 2275 throw badClassFile("wrong.version", 2276 Integer.toString(majorVersion), 2277 Integer.toString(minorVersion), 2278 Integer.toString(maxMajor), 2279 Integer.toString(maxMinor)); 2280 } 2281 else if (checkClassFile && 2282 majorVersion == maxMajor && 2283 minorVersion > maxMinor) 2284 { 2285 printCCF("found.later.version", 2286 Integer.toString(minorVersion)); 2287 } 2288 indexPool(); 2289 if (signatureBuffer.length < bp) { 2290 int ns = Integer.highestOneBit(bp) << 1; 2291 signatureBuffer = new byte[ns]; 2292 } 2293 readClass(c); 2294 } 2295 2296 public void readClassFile(ClassSymbol c) { 2297 currentOwner = c; 2298 currentClassFile = c.classfile; 2299 warnedAttrs.clear(); 2300 filling = true; 2301 try { 2302 bp = 0; 2303 buf = readInputStream(buf, c.classfile.openInputStream()); 2304 readClassBuffer(c); 2305 if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) { 2306 List<Type> missing = missingTypeVariables; 2307 List<Type> found = foundTypeVariables; 2308 missingTypeVariables = List.nil(); 2309 foundTypeVariables = List.nil(); 2310 filling = false; 2311 ClassType ct = (ClassType)currentOwner.type; 2312 ct.supertype_field = 2313 types.subst(ct.supertype_field, missing, found); 2314 ct.interfaces_field = 2315 types.subst(ct.interfaces_field, missing, found); 2316 } else if (missingTypeVariables.isEmpty() != 2317 foundTypeVariables.isEmpty()) { 2318 Name name = missingTypeVariables.head.tsym.name; 2319 throw badClassFile("undecl.type.var", name); 2320 } 2321 } catch (IOException ex) { 2322 throw badClassFile("unable.to.access.file", ex.getMessage()); 2323 } catch (ArrayIndexOutOfBoundsException ex) { 2324 throw badClassFile("bad.class.file", c.flatname); 2325 } finally { 2326 missingTypeVariables = List.nil(); 2327 foundTypeVariables = List.nil(); 2328 filling = false; 2329 } 2330 } 2331 // where 2332 private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException { 2333 try { 2334 buf = ensureCapacity(buf, s.available()); 2335 int r = s.read(buf); 2336 int bp = 0; 2337 while (r != -1) { 2338 bp += r; 2339 buf = ensureCapacity(buf, bp); 2340 r = s.read(buf, bp, buf.length - bp); 2341 } 2342 return buf; 2343 } finally { 2344 try { 2345 s.close(); 2346 } catch (IOException e) { 2347 /* Ignore any errors, as this stream may have already 2348 * thrown a related exception which is the one that 2349 * should be reported. 2350 */ 2351 } 2352 } 2353 } 2354 /* 2355 * ensureCapacity will increase the buffer as needed, taking note that 2356 * the new buffer will always be greater than the needed and never 2357 * exactly equal to the needed size or bp. If equal then the read (above) 2358 * will infinitely loop as buf.length - bp == 0. 2359 */ 2360 private static byte[] ensureCapacity(byte[] buf, int needed) { 2361 if (buf.length <= needed) { 2362 byte[] old = buf; 2363 buf = new byte[Integer.highestOneBit(needed) << 1]; 2364 System.arraycopy(old, 0, buf, 0, old.length); 2365 } 2366 return buf; 2367 } 2368 2369 /** We can only read a single class file at a time; this 2370 * flag keeps track of when we are currently reading a class 2371 * file. 2372 */ 2373 public boolean filling = false; 2374 2375/************************************************************************ 2376 * Adjusting flags 2377 ***********************************************************************/ 2378 2379 long adjustFieldFlags(long flags) { 2380 return flags; 2381 } 2382 2383 long adjustMethodFlags(long flags) { 2384 if ((flags & ACC_BRIDGE) != 0) { 2385 flags &= ~ACC_BRIDGE; 2386 flags |= BRIDGE; 2387 } 2388 if ((flags & ACC_VARARGS) != 0) { 2389 flags &= ~ACC_VARARGS; 2390 flags |= VARARGS; 2391 } 2392 return flags; 2393 } 2394 2395 long adjustClassFlags(long flags) { 2396 return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded 2397 } 2398 2399 /** Output for "-checkclassfile" option. 2400 * @param key The key to look up the correct internationalized string. 2401 * @param arg An argument for substitution into the output string. 2402 */ 2403 private void printCCF(String key, Object arg) { 2404 log.printLines(key, arg); 2405 } 2406 2407 /** 2408 * A subclass of JavaFileObject for the sourcefile attribute found in a classfile. 2409 * The attribute is only the last component of the original filename, so is unlikely 2410 * to be valid as is, so operations other than those to access the name throw 2411 * UnsupportedOperationException 2412 */ 2413 private static class SourceFileObject extends BaseFileObject { 2414 2415 /** The file's name. 2416 */ 2417 private Name name; 2418 private Name flatname; 2419 2420 public SourceFileObject(Name name, Name flatname) { 2421 super(null); // no file manager; never referenced for this file object 2422 this.name = name; 2423 this.flatname = flatname; 2424 } 2425 2426 @Override @DefinedBy(Api.COMPILER) 2427 public URI toUri() { 2428 try { 2429 return new URI(null, name.toString(), null); 2430 } catch (URISyntaxException e) { 2431 throw new CannotCreateUriError(name.toString(), e); 2432 } 2433 } 2434 2435 @Override @DefinedBy(Api.COMPILER) 2436 public String getName() { 2437 return name.toString(); 2438 } 2439 2440 @Override 2441 public String getShortName() { 2442 return getName(); 2443 } 2444 2445 @Override @DefinedBy(Api.COMPILER) 2446 public JavaFileObject.Kind getKind() { 2447 return getKind(getName()); 2448 } 2449 2450 @Override @DefinedBy(Api.COMPILER) 2451 public InputStream openInputStream() { 2452 throw new UnsupportedOperationException(); 2453 } 2454 2455 @Override @DefinedBy(Api.COMPILER) 2456 public OutputStream openOutputStream() { 2457 throw new UnsupportedOperationException(); 2458 } 2459 2460 @Override @DefinedBy(Api.COMPILER) 2461 public CharBuffer getCharContent(boolean ignoreEncodingErrors) { 2462 throw new UnsupportedOperationException(); 2463 } 2464 2465 @Override @DefinedBy(Api.COMPILER) 2466 public Reader openReader(boolean ignoreEncodingErrors) { 2467 throw new UnsupportedOperationException(); 2468 } 2469 2470 @Override @DefinedBy(Api.COMPILER) 2471 public Writer openWriter() { 2472 throw new UnsupportedOperationException(); 2473 } 2474 2475 @Override @DefinedBy(Api.COMPILER) 2476 public long getLastModified() { 2477 throw new UnsupportedOperationException(); 2478 } 2479 2480 @Override @DefinedBy(Api.COMPILER) 2481 public boolean delete() { 2482 throw new UnsupportedOperationException(); 2483 } 2484 2485 @Override 2486 protected String inferBinaryName(Iterable<? extends Path> path) { 2487 return flatname.toString(); 2488 } 2489 2490 @Override @DefinedBy(Api.COMPILER) 2491 public boolean isNameCompatible(String simpleName, JavaFileObject.Kind kind) { 2492 return true; // fail-safe mode 2493 } 2494 2495 /** 2496 * Check if two file objects are equal. 2497 * SourceFileObjects are just placeholder objects for the value of a 2498 * SourceFile attribute, and do not directly represent specific files. 2499 * Two SourceFileObjects are equal if their names are equal. 2500 */ 2501 @Override 2502 public boolean equals(Object other) { 2503 if (this == other) 2504 return true; 2505 2506 if (!(other instanceof SourceFileObject)) 2507 return false; 2508 2509 SourceFileObject o = (SourceFileObject) other; 2510 return name.equals(o.name); 2511 } 2512 2513 @Override 2514 public int hashCode() { 2515 return name.hashCode(); 2516 } 2517 } 2518} 2519