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