1 /* 2 * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package com.sun.tools.javac.jvm; 27 28 import java.io.*; 29 import java.util.LinkedHashMap; 30 import java.util.Map; 31 import java.util.Set; 32 import java.util.LinkedHashSet; 33 import java.util.function.ToIntFunction; 34 35 import javax.tools.JavaFileManager; 36 import javax.tools.FileObject; 37 import javax.tools.JavaFileManager.Location; 38 import javax.tools.JavaFileObject; 39 40 import com.sun.tools.javac.code.*; 41 import com.sun.tools.javac.code.Attribute.RetentionPolicy; 42 import com.sun.tools.javac.code.Directive.*; 43 import com.sun.tools.javac.code.Symbol.*; 44 import com.sun.tools.javac.code.Type.*; 45 import com.sun.tools.javac.code.Types.SignatureGenerator.InvalidSignatureException; 46 import com.sun.tools.javac.comp.Check; 47 import com.sun.tools.javac.file.PathFileObject; 48 import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant; 49 import com.sun.tools.javac.jvm.PoolConstant.Dynamic.BsmKey; 50 import com.sun.tools.javac.resources.CompilerProperties.Errors; 51 import com.sun.tools.javac.resources.CompilerProperties.Fragments; 52 import com.sun.tools.javac.util.*; 53 import com.sun.tools.javac.util.List; 54 55 import static com.sun.tools.javac.code.Flags.*; 56 import static com.sun.tools.javac.code.Kinds.Kind.*; 57 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; 58 import static com.sun.tools.javac.code.TypeTag.*; 59 import static com.sun.tools.javac.main.Option.*; 60 61 import static javax.tools.StandardLocation.CLASS_OUTPUT; 62 63 /** This class provides operations to map an internal symbol table graph 64 * rooted in a ClassSymbol into a classfile. 65 * 66 * <p><b>This is NOT part of any supported API. 67 * If you write code that depends on this, you do so at your own risk. 68 * This code and its internal interfaces are subject to change or 69 * deletion without notice.</b> 70 */ 71 public class ClassWriter extends ClassFile { 72 protected static final Context.Key<ClassWriter> classWriterKey = new Context.Key<>(); 73 74 private final Options options; 75 76 /** Switch: verbose output. 77 */ 78 private boolean verbose; 79 80 /** Switch: emit source file attribute. 81 */ 82 private boolean emitSourceFile; 83 84 /** Switch: generate CharacterRangeTable attribute. 85 */ 86 private boolean genCrt; 87 88 /** Switch: describe the generated stackmap. 89 */ 90 private boolean debugstackmap; 91 92 /** Preview language level. 93 */ 94 private Preview preview; 95 96 /** 97 * Target class version. 98 */ 99 private Target target; 100 101 /** 102 * Source language version. 103 */ 104 private Source source; 105 106 /** Type utilities. */ 107 private Types types; 108 109 private Check check; 110 111 /** 112 * If true, class files will be written in module-specific subdirectories 113 * of the CLASS_OUTPUT location. 114 */ 115 public boolean multiModuleMode; 116 117 private List<ToIntFunction<Symbol>> extraAttributeHooks = List.nil(); 118 119 /** The initial sizes of the data and constant pool buffers. 120 * Sizes are increased when buffers get full. 121 */ 122 static final int DATA_BUF_SIZE = 0x0fff0; 123 static final int CLASS_BUF_SIZE = 0x1fff0; 124 125 /** An output buffer for member info. 126 */ 127 public ByteBuffer databuf = new ByteBuffer(DATA_BUF_SIZE); 128 129 /** An output buffer for the constant pool. 130 */ 131 ByteBuffer poolbuf = new ByteBuffer(CLASS_BUF_SIZE); 132 133 /** The constant pool writer. 134 */ 135 final PoolWriter poolWriter; 136 137 /** The log to use for verbose output. 138 */ 139 private final Log log; 140 141 /** The name table. */ 142 private final Names names; 143 144 /** Access to files. */ 145 private final JavaFileManager fileManager; 146 147 /** The tags and constants used in compressed stackmap. */ 148 static final int SAME_FRAME_SIZE = 64; 149 static final int SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247; 150 static final int SAME_FRAME_EXTENDED = 251; 151 static final int FULL_FRAME = 255; 152 static final int MAX_LOCAL_LENGTH_DIFF = 4; 153 154 /** Get the ClassWriter instance for this context. */ 155 public static ClassWriter instance(Context context) { 156 ClassWriter instance = context.get(classWriterKey); 157 if (instance == null) 158 instance = new ClassWriter(context); 159 return instance; 160 } 161 162 /** Construct a class writer, given an options table. 163 */ 164 @SuppressWarnings("this-escape") 165 protected ClassWriter(Context context) { 166 context.put(classWriterKey, this); 167 168 log = Log.instance(context); 169 names = Names.instance(context); 170 options = Options.instance(context); 171 preview = Preview.instance(context); 172 target = Target.instance(context); 173 source = Source.instance(context); 174 types = Types.instance(context); 175 check = Check.instance(context); 176 fileManager = context.get(JavaFileManager.class); 177 poolWriter = Gen.instance(context).poolWriter; 178 179 verbose = options.isSet(VERBOSE); 180 genCrt = options.isSet(XJCOV); 181 debugstackmap = options.isSet("debug.stackmap"); 182 183 emitSourceFile = options.isUnset(G_CUSTOM) || 184 options.isSet(G_CUSTOM, "source"); 185 186 String modifierFlags = options.get("debug.dumpmodifiers"); 187 if (modifierFlags != null) { 188 dumpClassModifiers = modifierFlags.indexOf('c') != -1; 189 dumpFieldModifiers = modifierFlags.indexOf('f') != -1; 190 dumpInnerClassModifiers = modifierFlags.indexOf('i') != -1; 191 dumpMethodModifiers = modifierFlags.indexOf('m') != -1; 192 } 193 } 194 195 public void addExtraAttributes(ToIntFunction<Symbol> addExtraAttributes) { 196 extraAttributeHooks = extraAttributeHooks.prepend(addExtraAttributes); 197 } 198 199 /****************************************************************** 200 * Diagnostics: dump generated class names and modifiers 201 ******************************************************************/ 202 203 /** Value of option 'dumpmodifiers' is a string 204 * indicating which modifiers should be dumped for debugging: 205 * 'c' -- classes 206 * 'f' -- fields 207 * 'i' -- innerclass attributes 208 * 'm' -- methods 209 * For example, to dump everything: 210 * javac -XDdumpmodifiers=cifm MyProg.java 211 */ 212 private boolean dumpClassModifiers; // -XDdumpmodifiers=c 213 private boolean dumpFieldModifiers; // -XDdumpmodifiers=f 214 private boolean dumpInnerClassModifiers; // -XDdumpmodifiers=i 215 private boolean dumpMethodModifiers; // -XDdumpmodifiers=m 216 217 218 /** Return flags as a string, separated by " ". 219 */ 220 public static String flagNames(long flags) { 221 StringBuilder sbuf = new StringBuilder(); 222 int i = 0; 223 long f = flags & StandardFlags; 224 while (f != 0) { 225 if ((f & 1) != 0 && flagName[i] != "") { 226 sbuf.append(" "); 227 sbuf.append(flagName[i]); 228 } 229 f = f >> 1; 230 i++; 231 } 232 return sbuf.toString(); 233 } 234 //where 235 private static final String[] flagName = { 236 "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL", 237 // the empty position should be for synchronized but right now we don't have any test checking it 238 "", "VOLATILE", "TRANSIENT", "NATIVE", "INTERFACE", 239 "ABSTRACT", "STRICTFP"}; 240 241 /****************************************************************** 242 * Output routines 243 ******************************************************************/ 244 245 /** Write a character into given byte buffer; 246 * byte buffer will not be grown. 247 */ 248 void putChar(ByteBuffer buf, int op, int x) { 249 buf.elems[op ] = (byte)((x >> 8) & 0xFF); 250 buf.elems[op+1] = (byte)((x ) & 0xFF); 251 } 252 253 /** Write an integer into given byte buffer; 254 * byte buffer will not be grown. 255 */ 256 void putInt(ByteBuffer buf, int adr, int x) { 257 buf.elems[adr ] = (byte)((x >> 24) & 0xFF); 258 buf.elems[adr+1] = (byte)((x >> 16) & 0xFF); 259 buf.elems[adr+2] = (byte)((x >> 8) & 0xFF); 260 buf.elems[adr+3] = (byte)((x ) & 0xFF); 261 } 262 263 /****************************************************************** 264 * Writing the Constant Pool 265 ******************************************************************/ 266 267 /** Thrown when the constant pool is over full. 268 */ 269 public static class PoolOverflow extends RuntimeException { 270 private static final long serialVersionUID = 0; 271 public PoolOverflow() {} 272 } 273 public static class StringOverflow extends RuntimeException { 274 private static final long serialVersionUID = 0; 275 public final String value; 276 public StringOverflow(String s) { 277 value = s; 278 } 279 } 280 281 /****************************************************************** 282 * Writing Attributes 283 ******************************************************************/ 284 285 /** Write header for an attribute to data buffer and return 286 * position past attribute length index. 287 */ 288 public int writeAttr(Name attrName) { 289 int index = poolWriter.putName(attrName); 290 databuf.appendChar(index); 291 databuf.appendInt(0); 292 return databuf.length; 293 } 294 295 /** Fill in attribute length. 296 */ 297 public void endAttr(int index) { 298 putInt(databuf, index - 4, databuf.length - index); 299 } 300 301 /** Leave space for attribute count and return index for 302 * number of attributes field. 303 */ 304 int beginAttrs() { 305 databuf.appendChar(0); 306 return databuf.length; 307 } 308 309 /** Fill in number of attributes. 310 */ 311 void endAttrs(int index, int count) { 312 putChar(databuf, index - 2, count); 313 } 314 315 /** Write the EnclosingMethod attribute if needed. 316 * Returns the number of attributes written (0 or 1). 317 */ 318 int writeEnclosingMethodAttribute(ClassSymbol c) { 319 return writeEnclosingMethodAttribute(names.EnclosingMethod, c); 320 } 321 322 /** Write the EnclosingMethod attribute with a specified name. 323 * Returns the number of attributes written (0 or 1). 324 */ 325 protected int writeEnclosingMethodAttribute(Name attributeName, ClassSymbol c) { 326 if (c.owner.kind != MTH && // neither a local class 327 c.name != names.empty) // nor anonymous 328 return 0; 329 330 int alenIdx = writeAttr(attributeName); 331 ClassSymbol enclClass = c.owner.enclClass(); 332 MethodSymbol enclMethod = 333 (c.owner.type == null // local to init block 334 || c.owner.kind != MTH) // or member init 335 ? null 336 : ((MethodSymbol)c.owner).originalEnclosingMethod(); 337 databuf.appendChar(poolWriter.putClass(enclClass)); 338 databuf.appendChar(enclMethod == null ? 0 : poolWriter.putNameAndType(enclMethod)); 339 endAttr(alenIdx); 340 return 1; 341 } 342 343 /** Write flag attributes; return number of attributes written. 344 */ 345 int writeFlagAttrs(long flags) { 346 int acount = 0; 347 if ((flags & DEPRECATED) != 0) { 348 int alenIdx = writeAttr(names.Deprecated); 349 endAttr(alenIdx); 350 acount++; 351 } 352 return acount; 353 } 354 355 /** Write member (field or method) attributes; 356 * return number of attributes written. 357 */ 358 int writeMemberAttrs(Symbol sym, boolean isRecordComponent) { 359 int acount = 0; 360 if (!isRecordComponent) { 361 acount = writeFlagAttrs(sym.flags()); 362 } 363 long flags = sym.flags(); 364 if ((flags & (SYNTHETIC | BRIDGE)) != SYNTHETIC && 365 (flags & ANONCONSTR) == 0 && 366 (!types.isSameType(sym.type, sym.erasure(types)) || 367 poolWriter.signatureGen.hasTypeVar(sym.type.getThrownTypes()))) { 368 // note that a local class with captured variables 369 // will get a signature attribute 370 int alenIdx = writeAttr(names.Signature); 371 databuf.appendChar(poolWriter.putSignature(sym)); 372 endAttr(alenIdx); 373 acount++; 374 } 375 acount += writeJavaAnnotations(sym.getRawAttributes()); 376 acount += writeTypeAnnotations(sym.getRawTypeAttributes(), false); 377 return acount; 378 } 379 380 /** 381 * Write method parameter names attribute. 382 */ 383 int writeMethodParametersAttr(MethodSymbol m, boolean writeParamNames) { 384 MethodType ty = m.externalType(types).asMethodType(); 385 final int allparams = ty.argtypes.size(); 386 if (m.params != null && allparams != 0) { 387 final int attrIndex = writeAttr(names.MethodParameters); 388 databuf.appendByte(allparams); 389 // Write extra parameters first 390 for (VarSymbol s : m.extraParams) { 391 final int flags = 392 ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) | 393 ((int) m.flags() & SYNTHETIC); 394 if (writeParamNames) 395 databuf.appendChar(poolWriter.putName(s.name)); 396 else 397 databuf.appendChar(0); 398 databuf.appendChar(flags); 399 } 400 // Now write the real parameters 401 for (VarSymbol s : m.params) { 402 final int flags = 403 ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) | 404 ((int) m.flags() & SYNTHETIC); 405 if (writeParamNames) 406 databuf.appendChar(poolWriter.putName(s.name)); 407 else 408 databuf.appendChar(0); 409 databuf.appendChar(flags); 410 } 411 // Now write the captured locals 412 for (VarSymbol s : m.capturedLocals) { 413 final int flags = 414 ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) | 415 ((int) m.flags() & SYNTHETIC); 416 if (writeParamNames) 417 databuf.appendChar(poolWriter.putName(s.name)); 418 else 419 databuf.appendChar(0); 420 databuf.appendChar(flags); 421 } 422 endAttr(attrIndex); 423 return 1; 424 } else 425 return 0; 426 } 427 428 private void writeParamAnnotations(List<VarSymbol> params, 429 RetentionPolicy retention) { 430 databuf.appendByte(params.length()); 431 for (VarSymbol s : params) { 432 ListBuffer<Attribute.Compound> buf = new ListBuffer<>(); 433 for (Attribute.Compound a : s.getRawAttributes()) 434 if (types.getRetention(a) == retention) 435 buf.append(a); 436 databuf.appendChar(buf.length()); 437 for (Attribute.Compound a : buf) 438 writeCompoundAttribute(a); 439 } 440 441 } 442 443 private void writeParamAnnotations(MethodSymbol m, 444 RetentionPolicy retention) { 445 databuf.appendByte(m.params.length()); 446 writeParamAnnotations(m.params, retention); 447 } 448 449 /** Write method parameter annotations; 450 * return number of attributes written. 451 */ 452 int writeParameterAttrs(List<VarSymbol> vars) { 453 boolean hasVisible = false; 454 boolean hasInvisible = false; 455 if (vars != null) { 456 for (VarSymbol s : vars) { 457 for (Attribute.Compound a : s.getRawAttributes()) { 458 switch (types.getRetention(a)) { 459 case SOURCE: break; 460 case CLASS: hasInvisible = true; break; 461 case RUNTIME: hasVisible = true; break; 462 default: // /* fail soft */ throw new AssertionError(vis); 463 } 464 } 465 } 466 } 467 468 int attrCount = 0; 469 if (hasVisible) { 470 int attrIndex = writeAttr(names.RuntimeVisibleParameterAnnotations); 471 writeParamAnnotations(vars, RetentionPolicy.RUNTIME); 472 endAttr(attrIndex); 473 attrCount++; 474 } 475 if (hasInvisible) { 476 int attrIndex = writeAttr(names.RuntimeInvisibleParameterAnnotations); 477 writeParamAnnotations(vars, RetentionPolicy.CLASS); 478 endAttr(attrIndex); 479 attrCount++; 480 } 481 return attrCount; 482 } 483 484 /********************************************************************** 485 * Writing Java-language annotations (aka metadata, attributes) 486 **********************************************************************/ 487 488 /** Write Java-language annotations; return number of JVM 489 * attributes written (zero or one). 490 */ 491 int writeJavaAnnotations(List<Attribute.Compound> attrs) { 492 if (attrs.isEmpty()) return 0; 493 ListBuffer<Attribute.Compound> visibles = new ListBuffer<>(); 494 ListBuffer<Attribute.Compound> invisibles = new ListBuffer<>(); 495 for (Attribute.Compound a : attrs) { 496 switch (types.getRetention(a)) { 497 case SOURCE: break; 498 case CLASS: invisibles.append(a); break; 499 case RUNTIME: visibles.append(a); break; 500 default: // /* fail soft */ throw new AssertionError(vis); 501 } 502 } 503 504 int attrCount = 0; 505 if (visibles.length() != 0) { 506 int attrIndex = writeAttr(names.RuntimeVisibleAnnotations); 507 databuf.appendChar(visibles.length()); 508 for (Attribute.Compound a : visibles) 509 writeCompoundAttribute(a); 510 endAttr(attrIndex); 511 attrCount++; 512 } 513 if (invisibles.length() != 0) { 514 int attrIndex = writeAttr(names.RuntimeInvisibleAnnotations); 515 databuf.appendChar(invisibles.length()); 516 for (Attribute.Compound a : invisibles) 517 writeCompoundAttribute(a); 518 endAttr(attrIndex); 519 attrCount++; 520 } 521 return attrCount; 522 } 523 524 int writeTypeAnnotations(List<Attribute.TypeCompound> typeAnnos, boolean inCode) { 525 if (typeAnnos.isEmpty()) return 0; 526 527 ListBuffer<Attribute.TypeCompound> visibles = new ListBuffer<>(); 528 ListBuffer<Attribute.TypeCompound> invisibles = new ListBuffer<>(); 529 530 for (Attribute.TypeCompound tc : typeAnnos) { 531 if (tc.hasUnknownPosition()) { 532 boolean fixed = tc.tryFixPosition(); 533 534 // Could we fix it? 535 if (!fixed) { 536 // This happens for nested types like @A Outer. @B Inner. 537 // For method parameters we get the annotation twice! Once with 538 // a valid position, once unknown. 539 // TODO: find a cleaner solution. 540 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 541 pw.println("ClassWriter: Position UNKNOWN in type annotation: " + tc); 542 continue; 543 } 544 } 545 546 if (tc.position.type.isLocal() != inCode) 547 continue; 548 if (!tc.position.emitToClassfile()) 549 continue; 550 switch (types.getRetention(tc)) { 551 case SOURCE: break; 552 case CLASS: invisibles.append(tc); break; 553 case RUNTIME: visibles.append(tc); break; 554 default: // /* fail soft */ throw new AssertionError(vis); 555 } 556 } 557 558 int attrCount = 0; 559 if (visibles.length() != 0) { 560 int attrIndex = writeAttr(names.RuntimeVisibleTypeAnnotations); 561 databuf.appendChar(visibles.length()); 562 for (Attribute.TypeCompound p : visibles) 563 writeTypeAnnotation(p); 564 endAttr(attrIndex); 565 attrCount++; 566 } 567 568 if (invisibles.length() != 0) { 569 int attrIndex = writeAttr(names.RuntimeInvisibleTypeAnnotations); 570 databuf.appendChar(invisibles.length()); 571 for (Attribute.TypeCompound p : invisibles) 572 writeTypeAnnotation(p); 573 endAttr(attrIndex); 574 attrCount++; 575 } 576 577 return attrCount; 578 } 579 580 /** A visitor to write an attribute including its leading 581 * single-character marker. 582 */ 583 class AttributeWriter implements Attribute.Visitor { 584 public void visitConstant(Attribute.Constant _value) { 585 if (_value.type.getTag() == CLASS) { 586 Assert.check(_value.value instanceof String); 587 String s = (String)_value.value; 588 databuf.appendByte('s'); 589 databuf.appendChar(poolWriter.putName(names.fromString(s))); 590 } else { 591 switch (_value.type.getTag()) { 592 case BYTE: 593 databuf.appendByte('B'); 594 break; 595 case CHAR: 596 databuf.appendByte('C'); 597 break; 598 case SHORT: 599 databuf.appendByte('S'); 600 break; 601 case INT: 602 databuf.appendByte('I'); 603 break; 604 case LONG: 605 databuf.appendByte('J'); 606 break; 607 case FLOAT: 608 databuf.appendByte('F'); 609 break; 610 case DOUBLE: 611 databuf.appendByte('D'); 612 break; 613 case BOOLEAN: 614 databuf.appendByte('Z'); 615 break; 616 default: 617 throw new AssertionError(_value.type); 618 } 619 databuf.appendChar(poolWriter.putConstant(_value.value)); 620 } 621 } 622 public void visitEnum(Attribute.Enum e) { 623 databuf.appendByte('e'); 624 databuf.appendChar(poolWriter.putDescriptor(e.value.type)); 625 databuf.appendChar(poolWriter.putName(e.value.name)); 626 } 627 public void visitClass(Attribute.Class clazz) { 628 databuf.appendByte('c'); 629 databuf.appendChar(poolWriter.putDescriptor(clazz.classType)); 630 } 631 public void visitCompound(Attribute.Compound compound) { 632 databuf.appendByte('@'); 633 writeCompoundAttribute(compound); 634 } 635 public void visitError(Attribute.Error x) { 636 throw new AssertionError(x); 637 } 638 public void visitArray(Attribute.Array array) { 639 databuf.appendByte('['); 640 databuf.appendChar(array.values.length); 641 for (Attribute a : array.values) { 642 a.accept(this); 643 } 644 } 645 } 646 AttributeWriter awriter = new AttributeWriter(); 647 648 /** Write a compound attribute excluding the '@' marker. */ 649 void writeCompoundAttribute(Attribute.Compound c) { 650 databuf.appendChar(poolWriter.putDescriptor(c.type)); 651 databuf.appendChar(c.values.length()); 652 for (Pair<Symbol.MethodSymbol,Attribute> p : c.values) { 653 databuf.appendChar(poolWriter.putName(p.fst.name)); 654 p.snd.accept(awriter); 655 } 656 } 657 658 void writeTypeAnnotation(Attribute.TypeCompound c) { 659 writePosition(c.position); 660 writeCompoundAttribute(c); 661 } 662 663 void writePosition(TypeAnnotationPosition p) { 664 databuf.appendByte(p.type.targetTypeValue()); // TargetType tag is a byte 665 switch (p.type) { 666 // instanceof 667 case INSTANCEOF: 668 // new expression 669 case NEW: 670 // constructor/method reference receiver 671 case CONSTRUCTOR_REFERENCE: 672 case METHOD_REFERENCE: 673 databuf.appendChar(p.offset); 674 break; 675 // local variable 676 case LOCAL_VARIABLE: 677 // resource variable 678 case RESOURCE_VARIABLE: 679 databuf.appendChar(p.lvarOffset.length); // for table length 680 for (int i = 0; i < p.lvarOffset.length; ++i) { 681 databuf.appendChar(p.lvarOffset[i]); 682 databuf.appendChar(p.lvarLength[i]); 683 databuf.appendChar(p.lvarIndex[i]); 684 } 685 break; 686 // exception parameter 687 case EXCEPTION_PARAMETER: 688 databuf.appendChar(p.getExceptionIndex()); 689 break; 690 // method receiver 691 case METHOD_RECEIVER: 692 // Do nothing 693 break; 694 // type parameter 695 case CLASS_TYPE_PARAMETER: 696 case METHOD_TYPE_PARAMETER: 697 databuf.appendByte(p.parameter_index); 698 break; 699 // type parameter bound 700 case CLASS_TYPE_PARAMETER_BOUND: 701 case METHOD_TYPE_PARAMETER_BOUND: 702 databuf.appendByte(p.parameter_index); 703 databuf.appendByte(p.bound_index); 704 break; 705 // class extends or implements clause 706 case CLASS_EXTENDS: 707 databuf.appendChar(p.type_index); 708 break; 709 // throws 710 case THROWS: 711 databuf.appendChar(p.type_index); 712 break; 713 // method parameter 714 case METHOD_FORMAL_PARAMETER: 715 databuf.appendByte(p.parameter_index); 716 break; 717 // type cast 718 case CAST: 719 // method/constructor/reference type argument 720 case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: 721 case METHOD_INVOCATION_TYPE_ARGUMENT: 722 case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: 723 case METHOD_REFERENCE_TYPE_ARGUMENT: 724 databuf.appendChar(p.offset); 725 databuf.appendByte(p.type_index); 726 break; 727 // We don't need to worry about these 728 case METHOD_RETURN: 729 case FIELD: 730 break; 731 case UNKNOWN: 732 throw new AssertionError("jvm.ClassWriter: UNKNOWN target type should never occur!"); 733 default: 734 throw new AssertionError("jvm.ClassWriter: Unknown target type for position: " + p); 735 } 736 737 { // Append location data for generics/arrays. 738 databuf.appendByte(p.location.size()); 739 java.util.List<Integer> loc = TypeAnnotationPosition.getBinaryFromTypePath(p.location); 740 for (int i : loc) 741 databuf.appendByte((byte)i); 742 } 743 } 744 745 /********************************************************************** 746 * Writing module attributes 747 **********************************************************************/ 748 749 /** Write the Module attribute if needed. 750 * Returns the number of attributes written (0 or 1). 751 */ 752 int writeModuleAttribute(ClassSymbol c) { 753 ModuleSymbol m = (ModuleSymbol) c.owner; 754 755 int alenIdx = writeAttr(names.Module); 756 757 databuf.appendChar(poolWriter.putModule(m)); 758 databuf.appendChar(ModuleFlags.value(m.flags)); // module_flags 759 databuf.appendChar(m.version != null ? poolWriter.putName(m.version) : 0); 760 761 ListBuffer<RequiresDirective> requires = new ListBuffer<>(); 762 for (RequiresDirective r: m.requires) { 763 if (!r.flags.contains(RequiresFlag.EXTRA)) 764 requires.add(r); 765 } 766 databuf.appendChar(requires.size()); 767 for (RequiresDirective r: requires) { 768 databuf.appendChar(poolWriter.putModule(r.module)); 769 databuf.appendChar(RequiresFlag.value(r.flags)); 770 databuf.appendChar(r.module.version != null ? poolWriter.putName(r.module.version) : 0); 771 } 772 773 List<ExportsDirective> exports = m.exports; 774 databuf.appendChar(exports.size()); 775 for (ExportsDirective e: exports) { 776 databuf.appendChar(poolWriter.putPackage(e.packge)); 777 databuf.appendChar(ExportsFlag.value(e.flags)); 778 if (e.modules == null) { 779 databuf.appendChar(0); 780 } else { 781 databuf.appendChar(e.modules.size()); 782 for (ModuleSymbol msym: e.modules) { 783 databuf.appendChar(poolWriter.putModule(msym)); 784 } 785 } 786 } 787 788 List<OpensDirective> opens = m.opens; 789 databuf.appendChar(opens.size()); 790 for (OpensDirective o: opens) { 791 databuf.appendChar(poolWriter.putPackage(o.packge)); 792 databuf.appendChar(OpensFlag.value(o.flags)); 793 if (o.modules == null) { 794 databuf.appendChar(0); 795 } else { 796 databuf.appendChar(o.modules.size()); 797 for (ModuleSymbol msym: o.modules) { 798 databuf.appendChar(poolWriter.putModule(msym)); 799 } 800 } 801 } 802 803 List<UsesDirective> uses = m.uses; 804 databuf.appendChar(uses.size()); 805 for (UsesDirective s: uses) { 806 databuf.appendChar(poolWriter.putClass(s.service)); 807 } 808 809 // temporary fix to merge repeated provides clause for same service; 810 // eventually this should be disallowed when analyzing the module, 811 // so that each service type only appears once. 812 Map<ClassSymbol, Set<ClassSymbol>> mergedProvides = new LinkedHashMap<>(); 813 for (ProvidesDirective p : m.provides) { 814 mergedProvides.computeIfAbsent(p.service, s -> new LinkedHashSet<>()).addAll(p.impls); 815 } 816 databuf.appendChar(mergedProvides.size()); 817 mergedProvides.forEach((srvc, impls) -> { 818 databuf.appendChar(poolWriter.putClass(srvc)); 819 databuf.appendChar(impls.size()); 820 impls.forEach(impl -> databuf.appendChar(poolWriter.putClass(impl))); 821 }); 822 823 endAttr(alenIdx); 824 return 1; 825 } 826 827 /********************************************************************** 828 * Writing Objects 829 **********************************************************************/ 830 831 /** Write "inner classes" attribute. 832 */ 833 void writeInnerClasses() { 834 int alenIdx = writeAttr(names.InnerClasses); 835 databuf.appendChar(poolWriter.innerClasses.size()); 836 for (ClassSymbol inner : poolWriter.innerClasses) { 837 inner.markAbstractIfNeeded(types); 838 int flags = adjustFlags(inner.flags_field); 839 if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT 840 if (dumpInnerClassModifiers) { 841 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 842 pw.println("INNERCLASS " + inner.name); 843 pw.println("---" + flagNames(flags)); 844 } 845 databuf.appendChar(poolWriter.putClass(inner)); 846 databuf.appendChar( 847 inner.owner.kind == TYP && !inner.name.isEmpty() ? poolWriter.putClass((ClassSymbol)inner.owner) : 0); 848 databuf.appendChar( 849 !inner.name.isEmpty() ? poolWriter.putName(inner.name) : 0); 850 databuf.appendChar(flags); 851 } 852 endAttr(alenIdx); 853 } 854 855 /** Write out "Preload" attribute by enumerating the value classes encountered in field/method descriptors during this compilation. 856 */ 857 void writePreloadAttribute() { 858 int alenIdx = writeAttr(names.Preload); 859 databuf.appendChar(poolWriter.preloadClasses.size()); 860 for (ClassSymbol c : poolWriter.preloadClasses) { 861 databuf.appendChar(poolWriter.putClass(c)); 862 } 863 endAttr(alenIdx); 864 } 865 866 int writeRecordAttribute(ClassSymbol csym) { 867 int alenIdx = writeAttr(names.Record); 868 Scope s = csym.members(); 869 databuf.appendChar(csym.getRecordComponents().size()); 870 for (VarSymbol v: csym.getRecordComponents()) { 871 //databuf.appendChar(poolWriter.putMember(v.accessor.head.snd)); 872 databuf.appendChar(poolWriter.putName(v.name)); 873 databuf.appendChar(poolWriter.putDescriptor(v)); 874 int acountIdx = beginAttrs(); 875 int acount = 0; 876 acount += writeMemberAttrs(v, true); 877 endAttrs(acountIdx, acount); 878 } 879 endAttr(alenIdx); 880 return 1; 881 } 882 883 /** 884 * Write NestMembers attribute (if needed) 885 */ 886 int writeNestMembersIfNeeded(ClassSymbol csym) { 887 ListBuffer<ClassSymbol> nested = new ListBuffer<>(); 888 listNested(csym, nested); 889 Set<ClassSymbol> nestedUnique = new LinkedHashSet<>(nested); 890 if (csym.owner.kind == PCK && !nestedUnique.isEmpty()) { 891 int alenIdx = writeAttr(names.NestMembers); 892 databuf.appendChar(nestedUnique.size()); 893 for (ClassSymbol s : nestedUnique) { 894 databuf.appendChar(poolWriter.putClass(s)); 895 } 896 endAttr(alenIdx); 897 return 1; 898 } 899 return 0; 900 } 901 902 /** 903 * Write NestHost attribute (if needed) 904 */ 905 int writeNestHostIfNeeded(ClassSymbol csym) { 906 if (csym.owner.kind != PCK) { 907 int alenIdx = writeAttr(names.NestHost); 908 databuf.appendChar(poolWriter.putClass(csym.outermostClass())); 909 endAttr(alenIdx); 910 return 1; 911 } 912 return 0; 913 } 914 915 private void listNested(Symbol sym, ListBuffer<ClassSymbol> seen) { 916 if (sym.kind != TYP) return; 917 ClassSymbol csym = (ClassSymbol)sym; 918 if (csym.owner.kind != PCK) { 919 seen.add(csym); 920 } 921 if (csym.members() != null) { 922 for (Symbol s : sym.members().getSymbols()) { 923 listNested(s, seen); 924 } 925 } 926 if (csym.trans_local != null) { 927 for (Symbol s : csym.trans_local) { 928 listNested(s, seen); 929 } 930 } 931 } 932 933 /** Write "PermittedSubclasses" attribute. 934 */ 935 int writePermittedSubclassesIfNeeded(ClassSymbol csym) { 936 if (csym.permitted.nonEmpty()) { 937 int alenIdx = writeAttr(names.PermittedSubclasses); 938 databuf.appendChar(csym.permitted.size()); 939 for (Symbol c : csym.permitted) { 940 databuf.appendChar(poolWriter.putClass((ClassSymbol) c)); 941 } 942 endAttr(alenIdx); 943 return 1; 944 } 945 return 0; 946 } 947 948 /** Write "bootstrapMethods" attribute. 949 */ 950 void writeBootstrapMethods() { 951 int alenIdx = writeAttr(names.BootstrapMethods); 952 int lastBootstrapMethods; 953 do { 954 lastBootstrapMethods = poolWriter.bootstrapMethods.size(); 955 for (BsmKey bsmKey : java.util.List.copyOf(poolWriter.bootstrapMethods.keySet())) { 956 for (LoadableConstant arg : bsmKey.staticArgs) { 957 poolWriter.putConstant(arg); 958 } 959 } 960 } while (lastBootstrapMethods < poolWriter.bootstrapMethods.size()); 961 databuf.appendChar(poolWriter.bootstrapMethods.size()); 962 for (BsmKey bsmKey : poolWriter.bootstrapMethods.keySet()) { 963 //write BSM handle 964 databuf.appendChar(poolWriter.putConstant(bsmKey.bsm)); 965 LoadableConstant[] uniqueArgs = bsmKey.staticArgs; 966 //write static args length 967 databuf.appendChar(uniqueArgs.length); 968 //write static args array 969 for (LoadableConstant arg : uniqueArgs) { 970 databuf.appendChar(poolWriter.putConstant(arg)); 971 } 972 } 973 endAttr(alenIdx); 974 } 975 976 /** Write field symbol, entering all references into constant pool. 977 */ 978 void writeField(VarSymbol v) { 979 int flags = adjustFlags(v.flags()); 980 databuf.appendChar(flags); 981 if (dumpFieldModifiers) { 982 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 983 pw.println("FIELD " + v.name); 984 pw.println("---" + flagNames(v.flags())); 985 } 986 databuf.appendChar(poolWriter.putName(v.name)); 987 databuf.appendChar(poolWriter.putDescriptor(v)); 988 Type fldType = v.erasure(types); 989 if (fldType.requiresPreload(v.owner)) { 990 poolWriter.enterPreloadClass((ClassSymbol) fldType.tsym); 991 } 992 int acountIdx = beginAttrs(); 993 int acount = 0; 994 if (v.getConstValue() != null) { 995 int alenIdx = writeAttr(names.ConstantValue); 996 databuf.appendChar(poolWriter.putConstant(v.getConstValue())); 997 endAttr(alenIdx); 998 acount++; 999 } 1000 acount += writeMemberAttrs(v, false); 1001 acount += writeExtraAttributes(v); 1002 endAttrs(acountIdx, acount); 1003 } 1004 1005 /** Write method symbol, entering all references into constant pool. 1006 */ 1007 void writeMethod(MethodSymbol m) { 1008 int flags = adjustFlags(m.flags()); 1009 databuf.appendChar(flags); 1010 if (dumpMethodModifiers) { 1011 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1012 pw.println("METHOD " + m.name); 1013 pw.println("---" + flagNames(m.flags())); 1014 } 1015 databuf.appendChar(poolWriter.putName(m.name)); 1016 databuf.appendChar(poolWriter.putDescriptor(m)); 1017 MethodType mtype = (MethodType) m.externalType(types); 1018 for (Type t : mtype.getParameterTypes()) { 1019 if (t.requiresPreload(m.owner)) { 1020 poolWriter.enterPreloadClass((ClassSymbol) t.tsym); 1021 } 1022 } 1023 Type returnType = mtype.getReturnType(); 1024 if (returnType.requiresPreload(m.owner)) { 1025 poolWriter.enterPreloadClass((ClassSymbol) returnType.tsym); 1026 } 1027 int acountIdx = beginAttrs(); 1028 int acount = 0; 1029 if (m.code != null) { 1030 int alenIdx = writeAttr(names.Code); 1031 writeCode(m.code); 1032 m.code = null; // to conserve space 1033 endAttr(alenIdx); 1034 acount++; 1035 } 1036 List<Type> thrown = m.erasure(types).getThrownTypes(); 1037 if (thrown.nonEmpty()) { 1038 int alenIdx = writeAttr(names.Exceptions); 1039 databuf.appendChar(thrown.length()); 1040 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) 1041 databuf.appendChar(poolWriter.putClass(l.head)); 1042 endAttr(alenIdx); 1043 acount++; 1044 } 1045 if (m.defaultValue != null) { 1046 int alenIdx = writeAttr(names.AnnotationDefault); 1047 m.defaultValue.accept(awriter); 1048 endAttr(alenIdx); 1049 acount++; 1050 } 1051 if (target.hasMethodParameters()) { 1052 if (!m.isLambdaMethod()) { // Per JDK-8138729, do not emit parameters table for lambda bodies. 1053 boolean requiresParamNames = requiresParamNames(m); 1054 if (requiresParamNames || requiresParamFlags(m)) 1055 acount += writeMethodParametersAttr(m, requiresParamNames); 1056 } 1057 } 1058 acount += writeMemberAttrs(m, false); 1059 if (!m.isLambdaMethod()) 1060 acount += writeParameterAttrs(m.params); 1061 acount += writeExtraAttributes(m); 1062 endAttrs(acountIdx, acount); 1063 } 1064 1065 private boolean requiresParamNames(MethodSymbol m) { 1066 if (options.isSet(PARAMETERS)) 1067 return true; 1068 if (m.isConstructor() && (m.flags_field & RECORD) != 0) 1069 return true; 1070 return false; 1071 } 1072 1073 private boolean requiresParamFlags(MethodSymbol m) { 1074 if (!m.extraParams.isEmpty()) { 1075 return m.extraParams.stream().anyMatch(p -> (p.flags_field & (SYNTHETIC | MANDATED)) != 0); 1076 } 1077 if (m.params != null) { 1078 // parameter is stored in params for Enum#valueOf(name) 1079 return m.params.stream().anyMatch(p -> (p.flags_field & (SYNTHETIC | MANDATED)) != 0); 1080 } 1081 return false; 1082 } 1083 1084 /** Write code attribute of method. 1085 */ 1086 void writeCode(Code code) { 1087 databuf.appendChar(code.max_stack); 1088 databuf.appendChar(code.max_locals); 1089 databuf.appendInt(code.cp); 1090 databuf.appendBytes(code.code, 0, code.cp); 1091 databuf.appendChar(code.catchInfo.length()); 1092 for (List<char[]> l = code.catchInfo.toList(); 1093 l.nonEmpty(); 1094 l = l.tail) { 1095 for (int i = 0; i < l.head.length; i++) 1096 databuf.appendChar(l.head[i]); 1097 } 1098 int acountIdx = beginAttrs(); 1099 int acount = 0; 1100 1101 if (code.lineInfo.nonEmpty()) { 1102 int alenIdx = writeAttr(names.LineNumberTable); 1103 databuf.appendChar(code.lineInfo.length()); 1104 for (List<char[]> l = code.lineInfo.reverse(); 1105 l.nonEmpty(); 1106 l = l.tail) 1107 for (int i = 0; i < l.head.length; i++) 1108 databuf.appendChar(l.head[i]); 1109 endAttr(alenIdx); 1110 acount++; 1111 } 1112 1113 if (genCrt && (code.crt != null)) { 1114 CRTable crt = code.crt; 1115 int alenIdx = writeAttr(names.CharacterRangeTable); 1116 int crtIdx = beginAttrs(); 1117 int crtEntries = crt.writeCRT(databuf, code.lineMap, log); 1118 endAttrs(crtIdx, crtEntries); 1119 endAttr(alenIdx); 1120 acount++; 1121 } 1122 1123 // counter for number of generic local variables 1124 if (code.varDebugInfo && code.varBufferSize > 0) { 1125 int nGenericVars = 0; 1126 int alenIdx = writeAttr(names.LocalVariableTable); 1127 databuf.appendChar(code.getLVTSize()); 1128 for (int i=0; i<code.varBufferSize; i++) { 1129 Code.LocalVar var = code.varBuffer[i]; 1130 1131 for (Code.LocalVar.Range r: var.aliveRanges) { 1132 // write variable info 1133 Assert.check(r.start_pc >= 0 1134 && r.start_pc <= code.cp); 1135 databuf.appendChar(r.start_pc); 1136 Assert.check(r.length > 0 1137 && (r.start_pc + r.length) <= code.cp); 1138 databuf.appendChar(r.length); 1139 VarSymbol sym = var.sym; 1140 databuf.appendChar(poolWriter.putName(sym.name)); 1141 databuf.appendChar(poolWriter.putDescriptor(sym)); 1142 databuf.appendChar(var.reg); 1143 if (needsLocalVariableTypeEntry(var.sym.type)) { 1144 nGenericVars++; 1145 } 1146 } 1147 } 1148 endAttr(alenIdx); 1149 acount++; 1150 1151 if (nGenericVars > 0) { 1152 alenIdx = writeAttr(names.LocalVariableTypeTable); 1153 databuf.appendChar(nGenericVars); 1154 int count = 0; 1155 1156 for (int i=0; i<code.varBufferSize; i++) { 1157 Code.LocalVar var = code.varBuffer[i]; 1158 VarSymbol sym = var.sym; 1159 if (!needsLocalVariableTypeEntry(sym.type)) 1160 continue; 1161 for (Code.LocalVar.Range r : var.aliveRanges) { 1162 // write variable info 1163 databuf.appendChar(r.start_pc); 1164 databuf.appendChar(r.length); 1165 databuf.appendChar(poolWriter.putName(sym.name)); 1166 databuf.appendChar(poolWriter.putSignature(sym)); 1167 databuf.appendChar(var.reg); 1168 count++; 1169 } 1170 } 1171 Assert.check(count == nGenericVars); 1172 endAttr(alenIdx); 1173 acount++; 1174 } 1175 } 1176 1177 if (code.stackMapBufferSize > 0) { 1178 if (debugstackmap) System.out.println("Stack map for " + code.meth); 1179 int alenIdx = writeAttr(code.stackMap.getAttributeName(names)); 1180 writeStackMap(code); 1181 endAttr(alenIdx); 1182 acount++; 1183 } 1184 1185 acount += writeTypeAnnotations(code.meth.getRawTypeAttributes(), true); 1186 1187 endAttrs(acountIdx, acount); 1188 } 1189 //where 1190 private boolean needsLocalVariableTypeEntry(Type t) { 1191 //a local variable needs a type-entry if its type T is generic 1192 //(i.e. |T| != T) and if it's not an non-denotable type (non-denotable 1193 // types are not supported in signature attribute grammar!) 1194 return !types.isSameType(t, types.erasure(t)) && 1195 check.checkDenotable(t); 1196 } 1197 1198 void writeStackMap(Code code) { 1199 int nframes = code.stackMapBufferSize; 1200 if (debugstackmap) System.out.println(" nframes = " + nframes); 1201 databuf.appendChar(nframes); 1202 1203 switch (code.stackMap) { 1204 case CLDC: 1205 for (int i=0; i<nframes; i++) { 1206 if (debugstackmap) System.out.print(" " + i + ":"); 1207 Code.StackMapFrame frame = code.stackMapBuffer[i]; 1208 1209 // output PC 1210 if (debugstackmap) System.out.print(" pc=" + frame.pc); 1211 databuf.appendChar(frame.pc); 1212 1213 // output locals 1214 int localCount = 0; 1215 for (int j=0; j<frame.locals.length; 1216 j += Code.width(frame.locals[j])) { 1217 localCount++; 1218 } 1219 if (debugstackmap) System.out.print(" nlocals=" + 1220 localCount); 1221 databuf.appendChar(localCount); 1222 for (int j=0; j<frame.locals.length; 1223 j += Code.width(frame.locals[j])) { 1224 if (debugstackmap) System.out.print(" local[" + j + "]="); 1225 writeStackMapType(frame.locals[j]); 1226 } 1227 1228 // output stack 1229 int stackCount = 0; 1230 for (int j=0; j<frame.stack.length; 1231 j += Code.width(frame.stack[j])) { 1232 stackCount++; 1233 } 1234 if (debugstackmap) System.out.print(" nstack=" + 1235 stackCount); 1236 databuf.appendChar(stackCount); 1237 for (int j=0; j<frame.stack.length; 1238 j += Code.width(frame.stack[j])) { 1239 if (debugstackmap) System.out.print(" stack[" + j + "]="); 1240 writeStackMapType(frame.stack[j]); 1241 } 1242 if (debugstackmap) System.out.println(); 1243 } 1244 break; 1245 case JSR202: { 1246 Assert.checkNull(code.stackMapBuffer); 1247 for (int i=0; i<nframes; i++) { 1248 if (debugstackmap) System.out.print(" " + i + ":"); 1249 StackMapTableFrame frame = code.stackMapTableBuffer[i]; 1250 frame.write(this); 1251 if (debugstackmap) System.out.println(); 1252 } 1253 break; 1254 } 1255 default: 1256 throw new AssertionError("Unexpected stackmap format value"); 1257 } 1258 } 1259 1260 //where 1261 void writeStackMapType(Type t) { 1262 if (t == null) { 1263 if (debugstackmap) System.out.print("empty"); 1264 databuf.appendByte(0); 1265 } 1266 else switch(t.getTag()) { 1267 case BYTE: 1268 case CHAR: 1269 case SHORT: 1270 case INT: 1271 case BOOLEAN: 1272 if (debugstackmap) System.out.print("int"); 1273 databuf.appendByte(1); 1274 break; 1275 case FLOAT: 1276 if (debugstackmap) System.out.print("float"); 1277 databuf.appendByte(2); 1278 break; 1279 case DOUBLE: 1280 if (debugstackmap) System.out.print("double"); 1281 databuf.appendByte(3); 1282 break; 1283 case LONG: 1284 if (debugstackmap) System.out.print("long"); 1285 databuf.appendByte(4); 1286 break; 1287 case BOT: // null 1288 if (debugstackmap) System.out.print("null"); 1289 databuf.appendByte(5); 1290 break; 1291 case CLASS: 1292 case ARRAY: 1293 case TYPEVAR: 1294 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")"); 1295 databuf.appendByte(7); 1296 databuf.appendChar(poolWriter.putClass(types.erasure(t))); 1297 break; 1298 case UNINITIALIZED_THIS: 1299 if (debugstackmap) System.out.print("uninit_this"); 1300 databuf.appendByte(6); 1301 break; 1302 case UNINITIALIZED_OBJECT: 1303 { UninitializedType uninitType = (UninitializedType)t; 1304 databuf.appendByte(8); 1305 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset); 1306 databuf.appendChar(uninitType.offset); 1307 } 1308 break; 1309 default: 1310 throw new AssertionError(); 1311 } 1312 } 1313 1314 /** An entry in the JSR202 StackMapTable */ 1315 abstract static class StackMapTableFrame { 1316 abstract int getFrameType(); 1317 1318 void write(ClassWriter writer) { 1319 int frameType = getFrameType(); 1320 writer.databuf.appendByte(frameType); 1321 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType); 1322 } 1323 1324 static class SameFrame extends StackMapTableFrame { 1325 final int offsetDelta; 1326 SameFrame(int offsetDelta) { 1327 this.offsetDelta = offsetDelta; 1328 } 1329 int getFrameType() { 1330 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED; 1331 } 1332 @Override 1333 void write(ClassWriter writer) { 1334 super.write(writer); 1335 if (getFrameType() == SAME_FRAME_EXTENDED) { 1336 writer.databuf.appendChar(offsetDelta); 1337 if (writer.debugstackmap){ 1338 System.out.print(" offset_delta=" + offsetDelta); 1339 } 1340 } 1341 } 1342 } 1343 1344 static class SameLocals1StackItemFrame extends StackMapTableFrame { 1345 final int offsetDelta; 1346 final Type stack; 1347 SameLocals1StackItemFrame(int offsetDelta, Type stack) { 1348 this.offsetDelta = offsetDelta; 1349 this.stack = stack; 1350 } 1351 int getFrameType() { 1352 return (offsetDelta < SAME_FRAME_SIZE) ? 1353 (SAME_FRAME_SIZE + offsetDelta) : 1354 SAME_LOCALS_1_STACK_ITEM_EXTENDED; 1355 } 1356 @Override 1357 void write(ClassWriter writer) { 1358 super.write(writer); 1359 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) { 1360 writer.databuf.appendChar(offsetDelta); 1361 if (writer.debugstackmap) { 1362 System.out.print(" offset_delta=" + offsetDelta); 1363 } 1364 } 1365 if (writer.debugstackmap) { 1366 System.out.print(" stack[" + 0 + "]="); 1367 } 1368 writer.writeStackMapType(stack); 1369 } 1370 } 1371 1372 static class ChopFrame extends StackMapTableFrame { 1373 final int frameType; 1374 final int offsetDelta; 1375 ChopFrame(int frameType, int offsetDelta) { 1376 this.frameType = frameType; 1377 this.offsetDelta = offsetDelta; 1378 } 1379 int getFrameType() { return frameType; } 1380 @Override 1381 void write(ClassWriter writer) { 1382 super.write(writer); 1383 writer.databuf.appendChar(offsetDelta); 1384 if (writer.debugstackmap) { 1385 System.out.print(" offset_delta=" + offsetDelta); 1386 } 1387 } 1388 } 1389 1390 static class AppendFrame extends StackMapTableFrame { 1391 final int frameType; 1392 final int offsetDelta; 1393 final Type[] locals; 1394 AppendFrame(int frameType, int offsetDelta, Type[] locals) { 1395 this.frameType = frameType; 1396 this.offsetDelta = offsetDelta; 1397 this.locals = locals; 1398 } 1399 int getFrameType() { return frameType; } 1400 @Override 1401 void write(ClassWriter writer) { 1402 super.write(writer); 1403 writer.databuf.appendChar(offsetDelta); 1404 if (writer.debugstackmap) { 1405 System.out.print(" offset_delta=" + offsetDelta); 1406 } 1407 for (int i=0; i<locals.length; i++) { 1408 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1409 writer.writeStackMapType(locals[i]); 1410 } 1411 } 1412 } 1413 1414 static class FullFrame extends StackMapTableFrame { 1415 final int offsetDelta; 1416 final Type[] locals; 1417 final Type[] stack; 1418 FullFrame(int offsetDelta, Type[] locals, Type[] stack) { 1419 this.offsetDelta = offsetDelta; 1420 this.locals = locals; 1421 this.stack = stack; 1422 } 1423 int getFrameType() { return FULL_FRAME; } 1424 @Override 1425 void write(ClassWriter writer) { 1426 super.write(writer); 1427 writer.databuf.appendChar(offsetDelta); 1428 writer.databuf.appendChar(locals.length); 1429 if (writer.debugstackmap) { 1430 System.out.print(" offset_delta=" + offsetDelta); 1431 System.out.print(" nlocals=" + locals.length); 1432 } 1433 for (int i=0; i<locals.length; i++) { 1434 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1435 writer.writeStackMapType(locals[i]); 1436 } 1437 1438 writer.databuf.appendChar(stack.length); 1439 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); } 1440 for (int i=0; i<stack.length; i++) { 1441 if (writer.debugstackmap) System.out.print(" stack[" + i + "]="); 1442 writer.writeStackMapType(stack[i]); 1443 } 1444 } 1445 } 1446 1447 /** Compare this frame with the previous frame and produce 1448 * an entry of compressed stack map frame. */ 1449 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame, 1450 int prev_pc, 1451 Type[] prev_locals, 1452 Types types) { 1453 Type[] locals = this_frame.locals; 1454 Type[] stack = this_frame.stack; 1455 int offset_delta = this_frame.pc - prev_pc - 1; 1456 if (stack.length == 1) { 1457 if (locals.length == prev_locals.length 1458 && compare(prev_locals, locals, types) == 0) { 1459 return new SameLocals1StackItemFrame(offset_delta, stack[0]); 1460 } 1461 } else if (stack.length == 0) { 1462 int diff_length = compare(prev_locals, locals, types); 1463 if (diff_length == 0) { 1464 return new SameFrame(offset_delta); 1465 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) { 1466 // APPEND 1467 Type[] local_diff = new Type[-diff_length]; 1468 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) { 1469 local_diff[j] = locals[i]; 1470 } 1471 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length, 1472 offset_delta, 1473 local_diff); 1474 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) { 1475 // CHOP 1476 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length, 1477 offset_delta); 1478 } 1479 } 1480 // FULL_FRAME 1481 return new FullFrame(offset_delta, locals, stack); 1482 } 1483 1484 static boolean isInt(Type t) { 1485 return (t.getTag().isStrictSubRangeOf(INT) || t.hasTag(BOOLEAN)); 1486 } 1487 1488 static boolean isSameType(Type t1, Type t2, Types types) { 1489 if (t1 == null) { return t2 == null; } 1490 if (t2 == null) { return false; } 1491 1492 if (isInt(t1) && isInt(t2)) { return true; } 1493 1494 if (t1.hasTag(UNINITIALIZED_THIS)) { 1495 return t2.hasTag(UNINITIALIZED_THIS); 1496 } else if (t1.hasTag(UNINITIALIZED_OBJECT)) { 1497 if (t2.hasTag(UNINITIALIZED_OBJECT)) { 1498 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset; 1499 } else { 1500 return false; 1501 } 1502 } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) { 1503 return false; 1504 } 1505 1506 return types.isSameType(t1, t2); 1507 } 1508 1509 static int compare(Type[] arr1, Type[] arr2, Types types) { 1510 int diff_length = arr1.length - arr2.length; 1511 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) { 1512 return Integer.MAX_VALUE; 1513 } 1514 int len = (diff_length > 0) ? arr2.length : arr1.length; 1515 for (int i=0; i<len; i++) { 1516 if (!isSameType(arr1[i], arr2[i], types)) { 1517 return Integer.MAX_VALUE; 1518 } 1519 } 1520 return diff_length; 1521 } 1522 } 1523 1524 void writeFields(Scope s) { 1525 // process them in reverse sibling order; 1526 // i.e., process them in declaration order. 1527 List<VarSymbol> vars = List.nil(); 1528 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { 1529 if (sym.kind == VAR) vars = vars.prepend((VarSymbol)sym); 1530 } 1531 while (vars.nonEmpty()) { 1532 writeField(vars.head); 1533 vars = vars.tail; 1534 } 1535 } 1536 1537 void writeMethods(Scope s) { 1538 List<MethodSymbol> methods = List.nil(); 1539 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { 1540 if (sym.kind == MTH && (sym.flags() & HYPOTHETICAL) == 0) 1541 methods = methods.prepend((MethodSymbol)sym); 1542 } 1543 while (methods.nonEmpty()) { 1544 writeMethod(methods.head); 1545 methods = methods.tail; 1546 } 1547 } 1548 1549 /** Emit a class file for a given class. 1550 * @param c The class from which a class file is generated. 1551 */ 1552 public JavaFileObject writeClass(ClassSymbol c) 1553 throws IOException, PoolOverflow, StringOverflow 1554 { 1555 String name = (c.owner.kind == MDL ? c.name : c.flatname).toString(); 1556 Location outLocn; 1557 if (multiModuleMode) { 1558 ModuleSymbol msym = c.owner.kind == MDL ? (ModuleSymbol) c.owner : c.packge().modle; 1559 outLocn = fileManager.getLocationForModule(CLASS_OUTPUT, msym.name.toString()); 1560 } else { 1561 outLocn = CLASS_OUTPUT; 1562 } 1563 JavaFileObject outFile 1564 = fileManager.getJavaFileForOutput(outLocn, 1565 name, 1566 JavaFileObject.Kind.CLASS, 1567 c.sourcefile); 1568 OutputStream out = outFile.openOutputStream(); 1569 try { 1570 writeClassFile(out, c); 1571 if (verbose) 1572 log.printVerbose("wrote.file", outFile.getName()); 1573 out.close(); 1574 out = null; 1575 } catch (InvalidSignatureException ex) { 1576 log.error(Errors.CannotGenerateClass(c, Fragments.IllegalSignature(c, ex.type()))); 1577 } finally { 1578 if (out != null) { 1579 // if we are propagating an exception, delete the file 1580 out.close(); 1581 outFile.delete(); 1582 outFile = null; 1583 } 1584 } 1585 return outFile; // may be null if write failed 1586 } 1587 1588 /** Write class `c' to outstream `out'. 1589 */ 1590 public void writeClassFile(OutputStream out, ClassSymbol c) 1591 throws IOException, PoolOverflow, StringOverflow { 1592 Assert.check((c.flags() & COMPOUND) == 0); 1593 databuf.reset(); 1594 poolbuf.reset(); 1595 1596 Type supertype = types.supertype(c.type); 1597 List<Type> interfaces = types.interfaces(c.type); 1598 List<Type> typarams = c.type.getTypeArguments(); 1599 1600 int flags; 1601 if (c.owner.kind == MDL) { 1602 flags = ACC_MODULE; 1603 } else { 1604 long originalFlags = c.flags(); 1605 flags = adjustFlags(c.flags() & ~(DEFAULT | STRICTFP)); 1606 if ((flags & PROTECTED) != 0) flags |= PUBLIC; 1607 flags = flags & ClassFlags; 1608 flags |= (originalFlags & IDENTITY_TYPE) != 0 ? ACC_IDENTITY : flags; 1609 } 1610 1611 if (dumpClassModifiers) { 1612 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1613 pw.println(); 1614 pw.println("CLASSFILE " + c.getQualifiedName()); 1615 pw.println("---" + flagNames(flags)); 1616 } 1617 databuf.appendChar(flags); 1618 1619 if (c.owner.kind == MDL) { 1620 PackageSymbol unnamed = ((ModuleSymbol) c.owner).unnamedPackage; 1621 databuf.appendChar(poolWriter.putClass(new ClassSymbol(0, names.module_info, unnamed))); 1622 } else { 1623 databuf.appendChar(poolWriter.putClass(c)); 1624 } 1625 databuf.appendChar(supertype.hasTag(CLASS) ? poolWriter.putClass((ClassSymbol)supertype.tsym) : 0); 1626 databuf.appendChar(interfaces.length()); 1627 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail) 1628 databuf.appendChar(poolWriter.putClass((ClassSymbol)l.head.tsym)); 1629 int fieldsCount = 0; 1630 int methodsCount = 0; 1631 for (Symbol sym : c.members().getSymbols(NON_RECURSIVE)) { 1632 switch (sym.kind) { 1633 case VAR: fieldsCount++; break; 1634 case MTH: if ((sym.flags() & HYPOTHETICAL) == 0) methodsCount++; 1635 break; 1636 case TYP: poolWriter.enterInner((ClassSymbol)sym); break; 1637 default : Assert.error(); 1638 } 1639 } 1640 1641 if (c.trans_local != null) { 1642 for (ClassSymbol local : c.trans_local) { 1643 poolWriter.enterInner(local); 1644 } 1645 } 1646 1647 databuf.appendChar(fieldsCount); 1648 writeFields(c.members()); 1649 databuf.appendChar(methodsCount); 1650 writeMethods(c.members()); 1651 1652 int acountIdx = beginAttrs(); 1653 int acount = 0; 1654 1655 boolean sigReq = 1656 typarams.length() != 0 || supertype.allparams().length() != 0; 1657 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail) 1658 sigReq = l.head.allparams().length() != 0; 1659 if (sigReq) { 1660 int alenIdx = writeAttr(names.Signature); 1661 databuf.appendChar(poolWriter.putSignature(c)); 1662 endAttr(alenIdx); 1663 acount++; 1664 } 1665 1666 if (c.sourcefile != null && emitSourceFile) { 1667 int alenIdx = writeAttr(names.SourceFile); 1668 // WHM 6/29/1999: Strip file path prefix. We do it here at 1669 // the last possible moment because the sourcefile may be used 1670 // elsewhere in error diagnostics. Fixes 4241573. 1671 String simpleName = PathFileObject.getSimpleName(c.sourcefile); 1672 databuf.appendChar(poolWriter.putName(names.fromString(simpleName))); 1673 endAttr(alenIdx); 1674 acount++; 1675 } 1676 1677 if (genCrt) { 1678 // Append SourceID attribute 1679 int alenIdx = writeAttr(names.SourceID); 1680 databuf.appendChar(poolWriter.putName(names.fromString(Long.toString(getLastModified(c.sourcefile))))); 1681 endAttr(alenIdx); 1682 acount++; 1683 // Append CompilationID attribute 1684 alenIdx = writeAttr(names.CompilationID); 1685 databuf.appendChar(poolWriter.putName(names.fromString(Long.toString(System.currentTimeMillis())))); 1686 endAttr(alenIdx); 1687 acount++; 1688 } 1689 1690 acount += writeFlagAttrs(c.flags()); 1691 acount += writeJavaAnnotations(c.getRawAttributes()); 1692 acount += writeTypeAnnotations(c.getRawTypeAttributes(), false); 1693 acount += writeEnclosingMethodAttribute(c); 1694 if (c.owner.kind == MDL) { 1695 acount += writeModuleAttribute(c); 1696 acount += writeFlagAttrs(c.owner.flags() & ~DEPRECATED); 1697 } 1698 acount += writeExtraClassAttributes(c); 1699 acount += writeExtraAttributes(c); 1700 1701 poolbuf.appendInt(JAVA_MAGIC); 1702 if (preview.isEnabled() && preview.usesPreview(c.sourcefile)) { 1703 poolbuf.appendChar(ClassFile.PREVIEW_MINOR_VERSION); 1704 } else { 1705 poolbuf.appendChar(target.minorVersion); 1706 } 1707 poolbuf.appendChar(target.majorVersion); 1708 1709 if (c.owner.kind != MDL) { 1710 if (target.hasNestmateAccess()) { 1711 acount += writeNestMembersIfNeeded(c); 1712 acount += writeNestHostIfNeeded(c); 1713 } 1714 } 1715 1716 if (c.isRecord()) { 1717 acount += writeRecordAttribute(c); 1718 } 1719 1720 if (target.hasSealedClasses()) { 1721 acount += writePermittedSubclassesIfNeeded(c); 1722 } 1723 1724 if (!poolWriter.bootstrapMethods.isEmpty()) { 1725 writeBootstrapMethods(); 1726 acount++; 1727 } 1728 1729 if (!poolWriter.innerClasses.isEmpty()) { 1730 writeInnerClasses(); 1731 acount++; 1732 } 1733 1734 if (!poolWriter.preloadClasses.isEmpty()) { 1735 writePreloadAttribute(); 1736 acount++; 1737 } 1738 1739 endAttrs(acountIdx, acount); 1740 1741 out.write(poolbuf.elems, 0, poolbuf.length); 1742 1743 poolWriter.writePool(out); 1744 poolWriter.reset(); // to save space 1745 1746 out.write(databuf.elems, 0, databuf.length); 1747 } 1748 1749 /**Allows subclasses to write additional class attributes 1750 * 1751 * @return the number of attributes written 1752 */ 1753 protected int writeExtraClassAttributes(ClassSymbol c) { 1754 return 0; 1755 } 1756 1757 /**Allows friends to write additional attributes 1758 * 1759 * @return the number of attributes written 1760 */ 1761 protected int writeExtraAttributes(Symbol sym) { 1762 int i = 0; 1763 for (ToIntFunction<Symbol> hook : extraAttributeHooks) { 1764 i += hook.applyAsInt(sym); 1765 } 1766 return i; 1767 } 1768 1769 int adjustFlags(final long flags) { 1770 int result = (int)flags; 1771 1772 // Elide strictfp bit in class files 1773 if (target.obsoleteAccStrict()) 1774 result &= ~STRICTFP; 1775 1776 if ((flags & BRIDGE) != 0) 1777 result |= ACC_BRIDGE; 1778 if ((flags & VARARGS) != 0) 1779 result |= ACC_VARARGS; 1780 if ((flags & DEFAULT) != 0) 1781 result &= ~ABSTRACT; 1782 if ((flags & IDENTITY_TYPE) != 0) { 1783 result |= ACC_IDENTITY; 1784 } 1785 if ((flags & STRICT) != 0) { 1786 result |= ACC_STRICT; 1787 } 1788 return result; 1789 } 1790 1791 long getLastModified(FileObject filename) { 1792 long mod = 0; 1793 try { 1794 mod = filename.getLastModified(); 1795 } catch (SecurityException e) { 1796 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage()); 1797 } 1798 return mod; 1799 } 1800 }