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