ClassWriter.java revision 3013:45897784a998
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 acount += writeMethodParametersAttr(m); 1112 acount += writeMemberAttrs(m); 1113 acount += writeParameterAttrs(m); 1114 endAttrs(acountIdx, acount); 1115 } 1116 1117 /** Write code attribute of method. 1118 */ 1119 void writeCode(Code code) { 1120 databuf.appendChar(code.max_stack); 1121 databuf.appendChar(code.max_locals); 1122 databuf.appendInt(code.cp); 1123 databuf.appendBytes(code.code, 0, code.cp); 1124 databuf.appendChar(code.catchInfo.length()); 1125 for (List<char[]> l = code.catchInfo.toList(); 1126 l.nonEmpty(); 1127 l = l.tail) { 1128 for (int i = 0; i < l.head.length; i++) 1129 databuf.appendChar(l.head[i]); 1130 } 1131 int acountIdx = beginAttrs(); 1132 int acount = 0; 1133 1134 if (code.lineInfo.nonEmpty()) { 1135 int alenIdx = writeAttr(names.LineNumberTable); 1136 databuf.appendChar(code.lineInfo.length()); 1137 for (List<char[]> l = code.lineInfo.reverse(); 1138 l.nonEmpty(); 1139 l = l.tail) 1140 for (int i = 0; i < l.head.length; i++) 1141 databuf.appendChar(l.head[i]); 1142 endAttr(alenIdx); 1143 acount++; 1144 } 1145 1146 if (genCrt && (code.crt != null)) { 1147 CRTable crt = code.crt; 1148 int alenIdx = writeAttr(names.CharacterRangeTable); 1149 int crtIdx = beginAttrs(); 1150 int crtEntries = crt.writeCRT(databuf, code.lineMap, log); 1151 endAttrs(crtIdx, crtEntries); 1152 endAttr(alenIdx); 1153 acount++; 1154 } 1155 1156 // counter for number of generic local variables 1157 if (code.varDebugInfo && code.varBufferSize > 0) { 1158 int nGenericVars = 0; 1159 int alenIdx = writeAttr(names.LocalVariableTable); 1160 databuf.appendChar(code.getLVTSize()); 1161 for (int i=0; i<code.varBufferSize; i++) { 1162 Code.LocalVar var = code.varBuffer[i]; 1163 1164 for (Code.LocalVar.Range r: var.aliveRanges) { 1165 // write variable info 1166 Assert.check(r.start_pc >= 0 1167 && r.start_pc <= code.cp); 1168 databuf.appendChar(r.start_pc); 1169 Assert.check(r.length > 0 1170 && (r.start_pc + r.length) <= code.cp); 1171 databuf.appendChar(r.length); 1172 VarSymbol sym = var.sym; 1173 databuf.appendChar(pool.put(sym.name)); 1174 Type vartype = sym.erasure(types); 1175 databuf.appendChar(pool.put(typeSig(vartype))); 1176 databuf.appendChar(var.reg); 1177 if (needsLocalVariableTypeEntry(var.sym.type)) { 1178 nGenericVars++; 1179 } 1180 } 1181 } 1182 endAttr(alenIdx); 1183 acount++; 1184 1185 if (nGenericVars > 0) { 1186 alenIdx = writeAttr(names.LocalVariableTypeTable); 1187 databuf.appendChar(nGenericVars); 1188 int count = 0; 1189 1190 for (int i=0; i<code.varBufferSize; i++) { 1191 Code.LocalVar var = code.varBuffer[i]; 1192 VarSymbol sym = var.sym; 1193 if (!needsLocalVariableTypeEntry(sym.type)) 1194 continue; 1195 for (Code.LocalVar.Range r : var.aliveRanges) { 1196 // write variable info 1197 databuf.appendChar(r.start_pc); 1198 databuf.appendChar(r.length); 1199 databuf.appendChar(pool.put(sym.name)); 1200 databuf.appendChar(pool.put(typeSig(sym.type))); 1201 databuf.appendChar(var.reg); 1202 count++; 1203 } 1204 } 1205 Assert.check(count == nGenericVars); 1206 endAttr(alenIdx); 1207 acount++; 1208 } 1209 } 1210 1211 if (code.stackMapBufferSize > 0) { 1212 if (debugstackmap) System.out.println("Stack map for " + code.meth); 1213 int alenIdx = writeAttr(code.stackMap.getAttributeName(names)); 1214 writeStackMap(code); 1215 endAttr(alenIdx); 1216 acount++; 1217 } 1218 1219 acount += writeTypeAnnotations(code.meth.getRawTypeAttributes(), true); 1220 1221 endAttrs(acountIdx, acount); 1222 } 1223 //where 1224 private boolean needsLocalVariableTypeEntry(Type t) { 1225 //a local variable needs a type-entry if its type T is generic 1226 //(i.e. |T| != T) and if it's not an intersection type (not supported 1227 //in signature attribute grammar) 1228 return (!types.isSameType(t, types.erasure(t)) && 1229 !t.isCompound()); 1230 } 1231 1232 void writeStackMap(Code code) { 1233 int nframes = code.stackMapBufferSize; 1234 if (debugstackmap) System.out.println(" nframes = " + nframes); 1235 databuf.appendChar(nframes); 1236 1237 switch (code.stackMap) { 1238 case CLDC: 1239 for (int i=0; i<nframes; i++) { 1240 if (debugstackmap) System.out.print(" " + i + ":"); 1241 Code.StackMapFrame frame = code.stackMapBuffer[i]; 1242 1243 // output PC 1244 if (debugstackmap) System.out.print(" pc=" + frame.pc); 1245 databuf.appendChar(frame.pc); 1246 1247 // output locals 1248 int localCount = 0; 1249 for (int j=0; j<frame.locals.length; 1250 j += Code.width(frame.locals[j])) { 1251 localCount++; 1252 } 1253 if (debugstackmap) System.out.print(" nlocals=" + 1254 localCount); 1255 databuf.appendChar(localCount); 1256 for (int j=0; j<frame.locals.length; 1257 j += Code.width(frame.locals[j])) { 1258 if (debugstackmap) System.out.print(" local[" + j + "]="); 1259 writeStackMapType(frame.locals[j]); 1260 } 1261 1262 // output stack 1263 int stackCount = 0; 1264 for (int j=0; j<frame.stack.length; 1265 j += Code.width(frame.stack[j])) { 1266 stackCount++; 1267 } 1268 if (debugstackmap) System.out.print(" nstack=" + 1269 stackCount); 1270 databuf.appendChar(stackCount); 1271 for (int j=0; j<frame.stack.length; 1272 j += Code.width(frame.stack[j])) { 1273 if (debugstackmap) System.out.print(" stack[" + j + "]="); 1274 writeStackMapType(frame.stack[j]); 1275 } 1276 if (debugstackmap) System.out.println(); 1277 } 1278 break; 1279 case JSR202: { 1280 Assert.checkNull(code.stackMapBuffer); 1281 for (int i=0; i<nframes; i++) { 1282 if (debugstackmap) System.out.print(" " + i + ":"); 1283 StackMapTableFrame frame = code.stackMapTableBuffer[i]; 1284 frame.write(this); 1285 if (debugstackmap) System.out.println(); 1286 } 1287 break; 1288 } 1289 default: 1290 throw new AssertionError("Unexpected stackmap format value"); 1291 } 1292 } 1293 1294 //where 1295 void writeStackMapType(Type t) { 1296 if (t == null) { 1297 if (debugstackmap) System.out.print("empty"); 1298 databuf.appendByte(0); 1299 } 1300 else switch(t.getTag()) { 1301 case BYTE: 1302 case CHAR: 1303 case SHORT: 1304 case INT: 1305 case BOOLEAN: 1306 if (debugstackmap) System.out.print("int"); 1307 databuf.appendByte(1); 1308 break; 1309 case FLOAT: 1310 if (debugstackmap) System.out.print("float"); 1311 databuf.appendByte(2); 1312 break; 1313 case DOUBLE: 1314 if (debugstackmap) System.out.print("double"); 1315 databuf.appendByte(3); 1316 break; 1317 case LONG: 1318 if (debugstackmap) System.out.print("long"); 1319 databuf.appendByte(4); 1320 break; 1321 case BOT: // null 1322 if (debugstackmap) System.out.print("null"); 1323 databuf.appendByte(5); 1324 break; 1325 case CLASS: 1326 case ARRAY: 1327 if (debugstackmap) System.out.print("object(" + t + ")"); 1328 databuf.appendByte(7); 1329 databuf.appendChar(pool.put(t)); 1330 break; 1331 case TYPEVAR: 1332 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")"); 1333 databuf.appendByte(7); 1334 databuf.appendChar(pool.put(types.erasure(t).tsym)); 1335 break; 1336 case UNINITIALIZED_THIS: 1337 if (debugstackmap) System.out.print("uninit_this"); 1338 databuf.appendByte(6); 1339 break; 1340 case UNINITIALIZED_OBJECT: 1341 { UninitializedType uninitType = (UninitializedType)t; 1342 databuf.appendByte(8); 1343 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset); 1344 databuf.appendChar(uninitType.offset); 1345 } 1346 break; 1347 default: 1348 throw new AssertionError(); 1349 } 1350 } 1351 1352 /** An entry in the JSR202 StackMapTable */ 1353 abstract static class StackMapTableFrame { 1354 abstract int getFrameType(); 1355 1356 void write(ClassWriter writer) { 1357 int frameType = getFrameType(); 1358 writer.databuf.appendByte(frameType); 1359 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType); 1360 } 1361 1362 static class SameFrame extends StackMapTableFrame { 1363 final int offsetDelta; 1364 SameFrame(int offsetDelta) { 1365 this.offsetDelta = offsetDelta; 1366 } 1367 int getFrameType() { 1368 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED; 1369 } 1370 @Override 1371 void write(ClassWriter writer) { 1372 super.write(writer); 1373 if (getFrameType() == SAME_FRAME_EXTENDED) { 1374 writer.databuf.appendChar(offsetDelta); 1375 if (writer.debugstackmap){ 1376 System.out.print(" offset_delta=" + offsetDelta); 1377 } 1378 } 1379 } 1380 } 1381 1382 static class SameLocals1StackItemFrame extends StackMapTableFrame { 1383 final int offsetDelta; 1384 final Type stack; 1385 SameLocals1StackItemFrame(int offsetDelta, Type stack) { 1386 this.offsetDelta = offsetDelta; 1387 this.stack = stack; 1388 } 1389 int getFrameType() { 1390 return (offsetDelta < SAME_FRAME_SIZE) ? 1391 (SAME_FRAME_SIZE + offsetDelta) : 1392 SAME_LOCALS_1_STACK_ITEM_EXTENDED; 1393 } 1394 @Override 1395 void write(ClassWriter writer) { 1396 super.write(writer); 1397 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) { 1398 writer.databuf.appendChar(offsetDelta); 1399 if (writer.debugstackmap) { 1400 System.out.print(" offset_delta=" + offsetDelta); 1401 } 1402 } 1403 if (writer.debugstackmap) { 1404 System.out.print(" stack[" + 0 + "]="); 1405 } 1406 writer.writeStackMapType(stack); 1407 } 1408 } 1409 1410 static class ChopFrame extends StackMapTableFrame { 1411 final int frameType; 1412 final int offsetDelta; 1413 ChopFrame(int frameType, int offsetDelta) { 1414 this.frameType = frameType; 1415 this.offsetDelta = offsetDelta; 1416 } 1417 int getFrameType() { return frameType; } 1418 @Override 1419 void write(ClassWriter writer) { 1420 super.write(writer); 1421 writer.databuf.appendChar(offsetDelta); 1422 if (writer.debugstackmap) { 1423 System.out.print(" offset_delta=" + offsetDelta); 1424 } 1425 } 1426 } 1427 1428 static class AppendFrame extends StackMapTableFrame { 1429 final int frameType; 1430 final int offsetDelta; 1431 final Type[] locals; 1432 AppendFrame(int frameType, int offsetDelta, Type[] locals) { 1433 this.frameType = frameType; 1434 this.offsetDelta = offsetDelta; 1435 this.locals = locals; 1436 } 1437 int getFrameType() { return frameType; } 1438 @Override 1439 void write(ClassWriter writer) { 1440 super.write(writer); 1441 writer.databuf.appendChar(offsetDelta); 1442 if (writer.debugstackmap) { 1443 System.out.print(" offset_delta=" + offsetDelta); 1444 } 1445 for (int i=0; i<locals.length; i++) { 1446 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1447 writer.writeStackMapType(locals[i]); 1448 } 1449 } 1450 } 1451 1452 static class FullFrame extends StackMapTableFrame { 1453 final int offsetDelta; 1454 final Type[] locals; 1455 final Type[] stack; 1456 FullFrame(int offsetDelta, Type[] locals, Type[] stack) { 1457 this.offsetDelta = offsetDelta; 1458 this.locals = locals; 1459 this.stack = stack; 1460 } 1461 int getFrameType() { return FULL_FRAME; } 1462 @Override 1463 void write(ClassWriter writer) { 1464 super.write(writer); 1465 writer.databuf.appendChar(offsetDelta); 1466 writer.databuf.appendChar(locals.length); 1467 if (writer.debugstackmap) { 1468 System.out.print(" offset_delta=" + offsetDelta); 1469 System.out.print(" nlocals=" + locals.length); 1470 } 1471 for (int i=0; i<locals.length; i++) { 1472 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1473 writer.writeStackMapType(locals[i]); 1474 } 1475 1476 writer.databuf.appendChar(stack.length); 1477 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); } 1478 for (int i=0; i<stack.length; i++) { 1479 if (writer.debugstackmap) System.out.print(" stack[" + i + "]="); 1480 writer.writeStackMapType(stack[i]); 1481 } 1482 } 1483 } 1484 1485 /** Compare this frame with the previous frame and produce 1486 * an entry of compressed stack map frame. */ 1487 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame, 1488 int prev_pc, 1489 Type[] prev_locals, 1490 Types types) { 1491 Type[] locals = this_frame.locals; 1492 Type[] stack = this_frame.stack; 1493 int offset_delta = this_frame.pc - prev_pc - 1; 1494 if (stack.length == 1) { 1495 if (locals.length == prev_locals.length 1496 && compare(prev_locals, locals, types) == 0) { 1497 return new SameLocals1StackItemFrame(offset_delta, stack[0]); 1498 } 1499 } else if (stack.length == 0) { 1500 int diff_length = compare(prev_locals, locals, types); 1501 if (diff_length == 0) { 1502 return new SameFrame(offset_delta); 1503 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) { 1504 // APPEND 1505 Type[] local_diff = new Type[-diff_length]; 1506 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) { 1507 local_diff[j] = locals[i]; 1508 } 1509 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length, 1510 offset_delta, 1511 local_diff); 1512 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) { 1513 // CHOP 1514 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length, 1515 offset_delta); 1516 } 1517 } 1518 // FULL_FRAME 1519 return new FullFrame(offset_delta, locals, stack); 1520 } 1521 1522 static boolean isInt(Type t) { 1523 return (t.getTag().isStrictSubRangeOf(INT) || t.hasTag(BOOLEAN)); 1524 } 1525 1526 static boolean isSameType(Type t1, Type t2, Types types) { 1527 if (t1 == null) { return t2 == null; } 1528 if (t2 == null) { return false; } 1529 1530 if (isInt(t1) && isInt(t2)) { return true; } 1531 1532 if (t1.hasTag(UNINITIALIZED_THIS)) { 1533 return t2.hasTag(UNINITIALIZED_THIS); 1534 } else if (t1.hasTag(UNINITIALIZED_OBJECT)) { 1535 if (t2.hasTag(UNINITIALIZED_OBJECT)) { 1536 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset; 1537 } else { 1538 return false; 1539 } 1540 } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) { 1541 return false; 1542 } 1543 1544 return types.isSameType(t1, t2); 1545 } 1546 1547 static int compare(Type[] arr1, Type[] arr2, Types types) { 1548 int diff_length = arr1.length - arr2.length; 1549 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) { 1550 return Integer.MAX_VALUE; 1551 } 1552 int len = (diff_length > 0) ? arr2.length : arr1.length; 1553 for (int i=0; i<len; i++) { 1554 if (!isSameType(arr1[i], arr2[i], types)) { 1555 return Integer.MAX_VALUE; 1556 } 1557 } 1558 return diff_length; 1559 } 1560 } 1561 1562 void writeFields(Scope s) { 1563 // process them in reverse sibling order; 1564 // i.e., process them in declaration order. 1565 List<VarSymbol> vars = List.nil(); 1566 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { 1567 if (sym.kind == VAR) vars = vars.prepend((VarSymbol)sym); 1568 } 1569 while (vars.nonEmpty()) { 1570 writeField(vars.head); 1571 vars = vars.tail; 1572 } 1573 } 1574 1575 void writeMethods(Scope s) { 1576 List<MethodSymbol> methods = List.nil(); 1577 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { 1578 if (sym.kind == MTH && (sym.flags() & HYPOTHETICAL) == 0) 1579 methods = methods.prepend((MethodSymbol)sym); 1580 } 1581 while (methods.nonEmpty()) { 1582 writeMethod(methods.head); 1583 methods = methods.tail; 1584 } 1585 } 1586 1587 /** Emit a class file for a given class. 1588 * @param c The class from which a class file is generated. 1589 */ 1590 public JavaFileObject writeClass(ClassSymbol c) 1591 throws IOException, PoolOverflow, StringOverflow 1592 { 1593 JavaFileObject outFile 1594 = fileManager.getJavaFileForOutput(CLASS_OUTPUT, 1595 c.flatname.toString(), 1596 JavaFileObject.Kind.CLASS, 1597 c.sourcefile); 1598 OutputStream out = outFile.openOutputStream(); 1599 try { 1600 writeClassFile(out, c); 1601 if (verbose) 1602 log.printVerbose("wrote.file", outFile); 1603 out.close(); 1604 out = null; 1605 } finally { 1606 if (out != null) { 1607 // if we are propagating an exception, delete the file 1608 out.close(); 1609 outFile.delete(); 1610 outFile = null; 1611 } 1612 } 1613 return outFile; // may be null if write failed 1614 } 1615 1616 /** Write class `c' to outstream `out'. 1617 */ 1618 public void writeClassFile(OutputStream out, ClassSymbol c) 1619 throws IOException, PoolOverflow, StringOverflow { 1620 Assert.check((c.flags() & COMPOUND) == 0); 1621 databuf.reset(); 1622 poolbuf.reset(); 1623 signatureGen.reset(); 1624 pool = c.pool; 1625 innerClasses = null; 1626 innerClassesQueue = null; 1627 bootstrapMethods = new LinkedHashMap<>(); 1628 1629 Type supertype = types.supertype(c.type); 1630 List<Type> interfaces = types.interfaces(c.type); 1631 List<Type> typarams = c.type.getTypeArguments(); 1632 1633 int flags = adjustFlags(c.flags() & ~DEFAULT); 1634 if ((flags & PROTECTED) != 0) flags |= PUBLIC; 1635 flags = flags & ClassFlags & ~STRICTFP; 1636 if ((flags & INTERFACE) == 0) flags |= ACC_SUPER; 1637 if (c.isInner() && c.name.isEmpty()) flags &= ~FINAL; 1638 if (dumpClassModifiers) { 1639 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1640 pw.println(); 1641 pw.println("CLASSFILE " + c.getQualifiedName()); 1642 pw.println("---" + flagNames(flags)); 1643 } 1644 databuf.appendChar(flags); 1645 1646 databuf.appendChar(pool.put(c)); 1647 databuf.appendChar(supertype.hasTag(CLASS) ? pool.put(supertype.tsym) : 0); 1648 databuf.appendChar(interfaces.length()); 1649 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail) 1650 databuf.appendChar(pool.put(l.head.tsym)); 1651 int fieldsCount = 0; 1652 int methodsCount = 0; 1653 for (Symbol sym : c.members().getSymbols(NON_RECURSIVE)) { 1654 switch (sym.kind) { 1655 case VAR: fieldsCount++; break; 1656 case MTH: if ((sym.flags() & HYPOTHETICAL) == 0) methodsCount++; 1657 break; 1658 case TYP: enterInner((ClassSymbol)sym); break; 1659 default : Assert.error(); 1660 } 1661 } 1662 1663 if (c.trans_local != null) { 1664 for (ClassSymbol local : c.trans_local) { 1665 enterInner(local); 1666 } 1667 } 1668 1669 databuf.appendChar(fieldsCount); 1670 writeFields(c.members()); 1671 databuf.appendChar(methodsCount); 1672 writeMethods(c.members()); 1673 1674 int acountIdx = beginAttrs(); 1675 int acount = 0; 1676 1677 boolean sigReq = 1678 typarams.length() != 0 || supertype.allparams().length() != 0; 1679 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail) 1680 sigReq = l.head.allparams().length() != 0; 1681 if (sigReq) { 1682 int alenIdx = writeAttr(names.Signature); 1683 if (typarams.length() != 0) signatureGen.assembleParamsSig(typarams); 1684 signatureGen.assembleSig(supertype); 1685 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail) 1686 signatureGen.assembleSig(l.head); 1687 databuf.appendChar(pool.put(signatureGen.toName())); 1688 signatureGen.reset(); 1689 endAttr(alenIdx); 1690 acount++; 1691 } 1692 1693 if (c.sourcefile != null && emitSourceFile) { 1694 int alenIdx = writeAttr(names.SourceFile); 1695 // WHM 6/29/1999: Strip file path prefix. We do it here at 1696 // the last possible moment because the sourcefile may be used 1697 // elsewhere in error diagnostics. Fixes 4241573. 1698 //databuf.appendChar(c.pool.put(c.sourcefile)); 1699 String simpleName = BaseFileObject.getSimpleName(c.sourcefile); 1700 databuf.appendChar(c.pool.put(names.fromString(simpleName))); 1701 endAttr(alenIdx); 1702 acount++; 1703 } 1704 1705 if (genCrt) { 1706 // Append SourceID attribute 1707 int alenIdx = writeAttr(names.SourceID); 1708 databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile))))); 1709 endAttr(alenIdx); 1710 acount++; 1711 // Append CompilationID attribute 1712 alenIdx = writeAttr(names.CompilationID); 1713 databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis())))); 1714 endAttr(alenIdx); 1715 acount++; 1716 } 1717 1718 acount += writeFlagAttrs(c.flags()); 1719 acount += writeJavaAnnotations(c.getRawAttributes()); 1720 acount += writeTypeAnnotations(c.getRawTypeAttributes(), false); 1721 acount += writeEnclosingMethodAttribute(c); 1722 acount += writeExtraClassAttributes(c); 1723 1724 poolbuf.appendInt(JAVA_MAGIC); 1725 poolbuf.appendChar(target.minorVersion); 1726 poolbuf.appendChar(target.majorVersion); 1727 1728 writePool(c.pool); 1729 1730 if (innerClasses != null) { 1731 writeInnerClasses(); 1732 acount++; 1733 } 1734 1735 if (!bootstrapMethods.isEmpty()) { 1736 writeBootstrapMethods(); 1737 acount++; 1738 } 1739 1740 endAttrs(acountIdx, acount); 1741 1742 poolbuf.appendBytes(databuf.elems, 0, databuf.length); 1743 out.write(poolbuf.elems, 0, poolbuf.length); 1744 1745 pool = c.pool = null; // to conserve space 1746 } 1747 1748 /**Allows subclasses to write additional class attributes 1749 * 1750 * @return the number of attributes written 1751 */ 1752 protected int writeExtraClassAttributes(ClassSymbol c) { 1753 return 0; 1754 } 1755 1756 int adjustFlags(final long flags) { 1757 int result = (int)flags; 1758 1759 if ((flags & BRIDGE) != 0) 1760 result |= ACC_BRIDGE; 1761 if ((flags & VARARGS) != 0) 1762 result |= ACC_VARARGS; 1763 if ((flags & DEFAULT) != 0) 1764 result &= ~ABSTRACT; 1765 return result; 1766 } 1767 1768 long getLastModified(FileObject filename) { 1769 long mod = 0; 1770 try { 1771 mod = filename.getLastModified(); 1772 } catch (SecurityException e) { 1773 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage()); 1774 } 1775 return mod; 1776 } 1777} 1778