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) 486 value = ((Method)value).m; 487 else if (value instanceof Variable) 488 value = ((Variable)value).v; 489 490 if (value instanceof MethodSymbol) { 491 MethodSymbol m = (MethodSymbol)value; 492 if (!m.isDynamic()) { 493 poolbuf.appendByte((m.owner.flags() & INTERFACE) != 0 494 ? CONSTANT_InterfaceMethodref 495 : CONSTANT_Methodref); 496 poolbuf.appendChar(pool.put(m.owner)); 497 poolbuf.appendChar(pool.put(nameType(m))); 498 } else { 499 //invokedynamic 500 DynamicMethodSymbol dynSym = (DynamicMethodSymbol)m; 501 MethodHandle handle = new MethodHandle(dynSym.bsmKind, dynSym.bsm, types); 502 DynamicMethod dynMeth = new DynamicMethod(dynSym, types); 503 bootstrapMethods.put(dynMeth, handle); 504 //init cp entries 505 pool.put(names.BootstrapMethods); 506 pool.put(handle); 507 for (Object staticArg : dynSym.staticArgs) { 508 pool.put(staticArg); 509 } 510 poolbuf.appendByte(CONSTANT_InvokeDynamic); 511 poolbuf.appendChar(bootstrapMethods.size() - 1); 512 poolbuf.appendChar(pool.put(nameType(dynSym))); 513 } 514 } else if (value instanceof VarSymbol) { 515 VarSymbol v = (VarSymbol)value; 516 poolbuf.appendByte(CONSTANT_Fieldref); 517 poolbuf.appendChar(pool.put(v.owner)); 518 poolbuf.appendChar(pool.put(nameType(v))); 519 } else if (value instanceof Name) { 520 poolbuf.appendByte(CONSTANT_Utf8); 521 byte[] bs = ((Name)value).toUtf(); 522 poolbuf.appendChar(bs.length); 523 poolbuf.appendBytes(bs, 0, bs.length); 524 if (bs.length > Pool.MAX_STRING_LENGTH) 525 throw new StringOverflow(value.toString()); 526 } else if (value instanceof ClassSymbol) { 527 ClassSymbol c = (ClassSymbol)value; 528 if (c.owner.kind == TYP) pool.put(c.owner); 529 poolbuf.appendByte(CONSTANT_Class); 530 if (c.type.hasTag(ARRAY)) { 531 poolbuf.appendChar(pool.put(typeSig(c.type))); 532 } else { 533 poolbuf.appendChar(pool.put(names.fromUtf(externalize(c.flatname)))); 534 enterInner(c); 535 } 536 } else if (value instanceof NameAndType) { 537 NameAndType nt = (NameAndType)value; 538 poolbuf.appendByte(CONSTANT_NameandType); 539 poolbuf.appendChar(pool.put(nt.name)); 540 poolbuf.appendChar(pool.put(typeSig(nt.uniqueType.type))); 541 } else if (value instanceof Integer) { 542 poolbuf.appendByte(CONSTANT_Integer); 543 poolbuf.appendInt(((Integer)value).intValue()); 544 } else if (value instanceof Long) { 545 poolbuf.appendByte(CONSTANT_Long); 546 poolbuf.appendLong(((Long)value).longValue()); 547 i++; 548 } else if (value instanceof Float) { 549 poolbuf.appendByte(CONSTANT_Float); 550 poolbuf.appendFloat(((Float)value).floatValue()); 551 } else if (value instanceof Double) { 552 poolbuf.appendByte(CONSTANT_Double); 553 poolbuf.appendDouble(((Double)value).doubleValue()); 554 i++; 555 } else if (value instanceof String) { 556 poolbuf.appendByte(CONSTANT_String); 557 poolbuf.appendChar(pool.put(names.fromString((String)value))); 558 } else if (value instanceof UniqueType) { 559 Type type = ((UniqueType)value).type; 560 if (type instanceof MethodType) { 561 poolbuf.appendByte(CONSTANT_MethodType); 562 poolbuf.appendChar(pool.put(typeSig((MethodType)type))); 563 } else { 564 if (type.hasTag(CLASS)) enterInner((ClassSymbol)type.tsym); 565 poolbuf.appendByte(CONSTANT_Class); 566 poolbuf.appendChar(pool.put(xClassName(type))); 567 } 568 } else if (value instanceof MethodHandle) { 569 MethodHandle ref = (MethodHandle)value; 570 poolbuf.appendByte(CONSTANT_MethodHandle); 571 poolbuf.appendByte(ref.refKind); 572 poolbuf.appendChar(pool.put(ref.refSym)); 573 } else { 574 Assert.error("writePool " + value); 575 } 576 i++; 577 } 578 if (pool.pp > Pool.MAX_ENTRIES) 579 throw new PoolOverflow(); 580 putChar(poolbuf, poolCountIdx, pool.pp); 581 } 582 583 /** Given a field, return its name. 584 */ 585 Name fieldName(Symbol sym) { 586 if (scramble && (sym.flags() & PRIVATE) != 0 || 587 scrambleAll && (sym.flags() & (PROTECTED | PUBLIC)) == 0) 588 return names.fromString("_$" + sym.name.getIndex()); 589 else 590 return sym.name; 591 } 592 593 /** Given a symbol, return its name-and-type. 594 */ 595 NameAndType nameType(Symbol sym) { 596 return new NameAndType(fieldName(sym), 597 retrofit 598 ? sym.erasure(types) 599 : sym.externalType(types), types); 600 // if we retrofit, then the NameAndType has been read in as is 601 // and no change is necessary. If we compile normally, the 602 // NameAndType is generated from a symbol reference, and the 603 // adjustment of adding an additional this$n parameter needs to be made. 604 } 605 606 /****************************************************************** 607 * Writing Attributes 608 ******************************************************************/ 609 610 /** Write header for an attribute to data buffer and return 611 * position past attribute length index. 612 */ 613 int writeAttr(Name attrName) { 614 databuf.appendChar(pool.put(attrName)); 615 databuf.appendInt(0); 616 return databuf.length; 617 } 618 619 /** Fill in attribute length. 620 */ 621 void endAttr(int index) { 622 putInt(databuf, index - 4, databuf.length - index); 623 } 624 625 /** Leave space for attribute count and return index for 626 * number of attributes field. 627 */ 628 int beginAttrs() { 629 databuf.appendChar(0); 630 return databuf.length; 631 } 632 633 /** Fill in number of attributes. 634 */ 635 void endAttrs(int index, int count) { 636 putChar(databuf, index - 2, count); 637 } 638 639 /** Write the EnclosingMethod attribute if needed. 640 * Returns the number of attributes written (0 or 1). 641 */ 642 int writeEnclosingMethodAttribute(ClassSymbol c) { 643 if (!target.hasEnclosingMethodAttribute()) 644 return 0; 645 return writeEnclosingMethodAttribute(names.EnclosingMethod, c); 646 } 647 648 /** Write the EnclosingMethod attribute with a specified name. 649 * Returns the number of attributes written (0 or 1). 650 */ 651 protected int writeEnclosingMethodAttribute(Name attributeName, ClassSymbol c) { 652 if (c.owner.kind != MTH && // neither a local class 653 c.name != names.empty) // nor anonymous 654 return 0; 655 656 int alenIdx = writeAttr(attributeName); 657 ClassSymbol enclClass = c.owner.enclClass(); 658 MethodSymbol enclMethod = 659 (c.owner.type == null // local to init block 660 || c.owner.kind != MTH) // or member init 661 ? null 662 : (MethodSymbol)c.owner; 663 databuf.appendChar(pool.put(enclClass)); 664 databuf.appendChar(enclMethod == null ? 0 : pool.put(nameType(c.owner))); 665 endAttr(alenIdx); 666 return 1; 667 } 668 669 /** Write flag attributes; return number of attributes written. 670 */ 671 int writeFlagAttrs(long flags) { 672 int acount = 0; 673 if ((flags & DEPRECATED) != 0) { 674 int alenIdx = writeAttr(names.Deprecated); 675 endAttr(alenIdx); 676 acount++; 677 } 678 if ((flags & ENUM) != 0 && !target.useEnumFlag()) { 679 int alenIdx = writeAttr(names.Enum); 680 endAttr(alenIdx); 681 acount++; 682 } 683 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag()) { 684 int alenIdx = writeAttr(names.Synthetic); 685 endAttr(alenIdx); 686 acount++; 687 } 688 if ((flags & BRIDGE) != 0 && !target.useBridgeFlag()) { 689 int alenIdx = writeAttr(names.Bridge); 690 endAttr(alenIdx); 691 acount++; 692 } 693 if ((flags & VARARGS) != 0 && !target.useVarargsFlag()) { 694 int alenIdx = writeAttr(names.Varargs); 695 endAttr(alenIdx); 696 acount++; 697 } 698 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag()) { 699 int alenIdx = writeAttr(names.Annotation); 700 endAttr(alenIdx); 701 acount++; 702 } 703 return acount; 704 } 705 706 /** Write member (field or method) attributes; 707 * return number of attributes written. 708 */ 709 int writeMemberAttrs(Symbol sym) { 710 int acount = writeFlagAttrs(sym.flags()); 711 long flags = sym.flags(); 712 if (source.allowGenerics() && 713 (flags & (SYNTHETIC|BRIDGE)) != SYNTHETIC && 714 (flags & ANONCONSTR) == 0 && 715 (!types.isSameType(sym.type, sym.erasure(types)) || 716 hasTypeVar(sym.type.getThrownTypes()))) { 717 // note that a local class with captured variables 718 // will get a signature attribute 719 int alenIdx = writeAttr(names.Signature); 720 databuf.appendChar(pool.put(typeSig(sym.type))); 721 endAttr(alenIdx); 722 acount++; 723 } 724 acount += writeJavaAnnotations(sym.getRawAttributes()); 725 acount += writeTypeAnnotations(sym.getRawTypeAttributes()); 726 return acount; 727 } 728 729 /** 730 * Write method parameter names attribute. 731 */ 732 int writeMethodParametersAttr(MethodSymbol m) { 733 MethodType ty = m.externalType(types).asMethodType(); 734 final int allparams = ty.argtypes.size(); 735 if (m.params != null && allparams != 0) { 736 final int attrIndex = writeAttr(names.MethodParameters); 737 databuf.appendByte(allparams); 738 // Write extra parameters first 739 for (VarSymbol s : m.extraParams) { 740 final int flags = 741 ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) | 742 ((int) m.flags() & SYNTHETIC); 743 databuf.appendChar(pool.put(s.name)); 744 databuf.appendInt(flags); 745 } 746 // Now write the real parameters 747 for (VarSymbol s : m.params) { 748 final int flags = 749 ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) | 750 ((int) m.flags() & SYNTHETIC); 751 databuf.appendChar(pool.put(s.name)); 752 databuf.appendInt(flags); 753 } 754 endAttr(attrIndex); 755 return 1; 756 } else 757 return 0; 758 } 759 760 761 /** Write method parameter annotations; 762 * return number of attributes written. 763 */ 764 int writeParameterAttrs(MethodSymbol m) { 765 boolean hasVisible = false; 766 boolean hasInvisible = false; 767 if (m.params != null) for (VarSymbol s : m.params) { 768 for (Attribute.Compound a : s.getRawAttributes()) { 769 switch (types.getRetention(a)) { 770 case SOURCE: break; 771 case CLASS: hasInvisible = true; break; 772 case RUNTIME: hasVisible = true; break; 773 default: ;// /* fail soft */ throw new AssertionError(vis); 774 } 775 } 776 } 777 778 int attrCount = 0; 779 if (hasVisible) { 780 int attrIndex = writeAttr(names.RuntimeVisibleParameterAnnotations); 781 databuf.appendByte(m.params.length()); 782 for (VarSymbol s : m.params) { 783 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>(); 784 for (Attribute.Compound a : s.getRawAttributes()) 785 if (types.getRetention(a) == RetentionPolicy.RUNTIME) 786 buf.append(a); 787 databuf.appendChar(buf.length()); 788 for (Attribute.Compound a : buf) 789 writeCompoundAttribute(a); 790 } 791 endAttr(attrIndex); 792 attrCount++; 793 } 794 if (hasInvisible) { 795 int attrIndex = writeAttr(names.RuntimeInvisibleParameterAnnotations); 796 databuf.appendByte(m.params.length()); 797 for (VarSymbol s : m.params) { 798 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>(); 799 for (Attribute.Compound a : s.getRawAttributes()) 800 if (types.getRetention(a) == RetentionPolicy.CLASS) 801 buf.append(a); 802 databuf.appendChar(buf.length()); 803 for (Attribute.Compound a : buf) 804 writeCompoundAttribute(a); 805 } 806 endAttr(attrIndex); 807 attrCount++; 808 } 809 return attrCount; 810 } 811 812 /********************************************************************** 813 * Writing Java-language annotations (aka metadata, attributes) 814 **********************************************************************/ 815 816 /** Write Java-language annotations; return number of JVM 817 * attributes written (zero or one). 818 */ 819 int writeJavaAnnotations(List<Attribute.Compound> attrs) { 820 if (attrs.isEmpty()) return 0; 821 ListBuffer<Attribute.Compound> visibles = new ListBuffer<Attribute.Compound>(); 822 ListBuffer<Attribute.Compound> invisibles = new ListBuffer<Attribute.Compound>(); 823 for (Attribute.Compound a : attrs) { 824 switch (types.getRetention(a)) { 825 case SOURCE: break; 826 case CLASS: invisibles.append(a); break; 827 case RUNTIME: visibles.append(a); break; 828 default: ;// /* fail soft */ throw new AssertionError(vis); 829 } 830 } 831 832 int attrCount = 0; 833 if (visibles.length() != 0) { 834 int attrIndex = writeAttr(names.RuntimeVisibleAnnotations); 835 databuf.appendChar(visibles.length()); 836 for (Attribute.Compound a : visibles) 837 writeCompoundAttribute(a); 838 endAttr(attrIndex); 839 attrCount++; 840 } 841 if (invisibles.length() != 0) { 842 int attrIndex = writeAttr(names.RuntimeInvisibleAnnotations); 843 databuf.appendChar(invisibles.length()); 844 for (Attribute.Compound a : invisibles) 845 writeCompoundAttribute(a); 846 endAttr(attrIndex); 847 attrCount++; 848 } 849 return attrCount; 850 } 851 852 int writeTypeAnnotations(List<Attribute.TypeCompound> typeAnnos) { 853 if (typeAnnos.isEmpty()) return 0; 854 855 ListBuffer<Attribute.TypeCompound> visibles = ListBuffer.lb(); 856 ListBuffer<Attribute.TypeCompound> invisibles = ListBuffer.lb(); 857 858 for (Attribute.TypeCompound tc : typeAnnos) { 859 if (tc.position == null || tc.position.type == TargetType.UNKNOWN) { 860 boolean found = false; 861 // TODO: the position for the container annotation of a 862 // repeating type annotation has to be set. 863 // This cannot be done when the container is created, because 864 // then the position is not determined yet. 865 // How can we link these pieces better together? 866 if (tc.values.size() == 1) { 867 Pair<MethodSymbol, Attribute> val = tc.values.get(0); 868 if (val.fst.getSimpleName().contentEquals("value") && 869 val.snd instanceof Attribute.Array) { 870 Attribute.Array arr = (Attribute.Array) val.snd; 871 if (arr.values.length != 0 && 872 arr.values[0] instanceof Attribute.TypeCompound) { 873 TypeCompound atycomp = (Attribute.TypeCompound) arr.values[0]; 874 if (atycomp.position.type != TargetType.UNKNOWN) { 875 tc.position = atycomp.position; 876 found = true; 877 } 878 } 879 } 880 } 881 if (!found) { 882 // This happens for nested types like @A Outer. @B Inner. 883 // For method parameters we get the annotation twice! Once with 884 // a valid position, once unknown. 885 // TODO: find a cleaner solution. 886 // System.err.println("ClassWriter: Position UNKNOWN in type annotation: " + tc); 887 continue; 888 } 889 } 890 if (!tc.position.emitToClassfile()) 891 continue; 892 switch (types.getRetention(tc)) { 893 case SOURCE: break; 894 case CLASS: invisibles.append(tc); break; 895 case RUNTIME: visibles.append(tc); break; 896 default: ;// /* fail soft */ throw new AssertionError(vis); 897 } 898 } 899 900 int attrCount = 0; 901 if (visibles.length() != 0) { 902 int attrIndex = writeAttr(names.RuntimeVisibleTypeAnnotations); 903 databuf.appendChar(visibles.length()); 904 for (Attribute.TypeCompound p : visibles) 905 writeTypeAnnotation(p); 906 endAttr(attrIndex); 907 attrCount++; 908 } 909 910 if (invisibles.length() != 0) { 911 int attrIndex = writeAttr(names.RuntimeInvisibleTypeAnnotations); 912 databuf.appendChar(invisibles.length()); 913 for (Attribute.TypeCompound p : invisibles) 914 writeTypeAnnotation(p); 915 endAttr(attrIndex); 916 attrCount++; 917 } 918 919 return attrCount; 920 } 921 922 /** A visitor to write an attribute including its leading 923 * single-character marker. 924 */ 925 class AttributeWriter implements Attribute.Visitor { 926 public void visitConstant(Attribute.Constant _value) { 927 Object value = _value.value; 928 switch (_value.type.getTag()) { 929 case BYTE: 930 databuf.appendByte('B'); 931 break; 932 case CHAR: 933 databuf.appendByte('C'); 934 break; 935 case SHORT: 936 databuf.appendByte('S'); 937 break; 938 case INT: 939 databuf.appendByte('I'); 940 break; 941 case LONG: 942 databuf.appendByte('J'); 943 break; 944 case FLOAT: 945 databuf.appendByte('F'); 946 break; 947 case DOUBLE: 948 databuf.appendByte('D'); 949 break; 950 case BOOLEAN: 951 databuf.appendByte('Z'); 952 break; 953 case CLASS: 954 Assert.check(value instanceof String); 955 databuf.appendByte('s'); 956 value = names.fromString(value.toString()); // CONSTANT_Utf8 957 break; 958 default: 959 throw new AssertionError(_value.type); 960 } 961 databuf.appendChar(pool.put(value)); 962 } 963 public void visitEnum(Attribute.Enum e) { 964 databuf.appendByte('e'); 965 databuf.appendChar(pool.put(typeSig(e.value.type))); 966 databuf.appendChar(pool.put(e.value.name)); 967 } 968 public void visitClass(Attribute.Class clazz) { 969 databuf.appendByte('c'); 970 databuf.appendChar(pool.put(typeSig(clazz.classType))); 971 } 972 public void visitCompound(Attribute.Compound compound) { 973 databuf.appendByte('@'); 974 writeCompoundAttribute(compound); 975 } 976 public void visitError(Attribute.Error x) { 977 throw new AssertionError(x); 978 } 979 public void visitArray(Attribute.Array array) { 980 databuf.appendByte('['); 981 databuf.appendChar(array.values.length); 982 for (Attribute a : array.values) { 983 a.accept(this); 984 } 985 } 986 } 987 AttributeWriter awriter = new AttributeWriter(); 988 989 /** Write a compound attribute excluding the '@' marker. */ 990 void writeCompoundAttribute(Attribute.Compound c) { 991 databuf.appendChar(pool.put(typeSig(c.type))); 992 databuf.appendChar(c.values.length()); 993 for (Pair<Symbol.MethodSymbol,Attribute> p : c.values) { 994 databuf.appendChar(pool.put(p.fst.name)); 995 p.snd.accept(awriter); 996 } 997 } 998 999 void writeTypeAnnotation(Attribute.TypeCompound c) { 1000 writePosition(c.position); 1001 writeCompoundAttribute(c); 1002 } 1003 1004 void writePosition(TypeAnnotationPosition p) { 1005 databuf.appendByte(p.type.targetTypeValue()); // TargetType tag is a byte 1006 switch (p.type) { 1007 // type cast 1008 case CAST: 1009 // instanceof 1010 case INSTANCEOF: 1011 // new expression 1012 case NEW: 1013 databuf.appendChar(p.offset); 1014 break; 1015 // local variable 1016 case LOCAL_VARIABLE: 1017 // resource variable 1018 case RESOURCE_VARIABLE: 1019 databuf.appendChar(p.lvarOffset.length); // for table length 1020 for (int i = 0; i < p.lvarOffset.length; ++i) { 1021 databuf.appendChar(p.lvarOffset[i]); 1022 databuf.appendChar(p.lvarLength[i]); 1023 databuf.appendChar(p.lvarIndex[i]); 1024 } 1025 break; 1026 // exception parameter 1027 case EXCEPTION_PARAMETER: 1028 databuf.appendByte(p.exception_index); 1029 break; 1030 // method receiver 1031 case METHOD_RECEIVER: 1032 // Do nothing 1033 break; 1034 // type parameter 1035 case CLASS_TYPE_PARAMETER: 1036 case METHOD_TYPE_PARAMETER: 1037 databuf.appendByte(p.parameter_index); 1038 break; 1039 // type parameter bound 1040 case CLASS_TYPE_PARAMETER_BOUND: 1041 case METHOD_TYPE_PARAMETER_BOUND: 1042 databuf.appendByte(p.parameter_index); 1043 databuf.appendByte(p.bound_index); 1044 break; 1045 // class extends or implements clause 1046 case CLASS_EXTENDS: 1047 databuf.appendChar(p.type_index); 1048 break; 1049 // throws 1050 case THROWS: 1051 databuf.appendChar(p.type_index); 1052 break; 1053 // method parameter 1054 case METHOD_FORMAL_PARAMETER: 1055 databuf.appendByte(p.parameter_index); 1056 break; 1057 // method/constructor/reference type argument 1058 case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: 1059 case METHOD_INVOCATION_TYPE_ARGUMENT: 1060 case METHOD_REFERENCE_TYPE_ARGUMENT: 1061 databuf.appendChar(p.offset); 1062 databuf.appendByte(p.type_index); 1063 break; 1064 // We don't need to worry about these 1065 case METHOD_RETURN: 1066 case FIELD: 1067 break; 1068 // lambda formal parameter 1069 case LAMBDA_FORMAL_PARAMETER: 1070 databuf.appendByte(p.parameter_index); 1071 break; 1072 case UNKNOWN: 1073 throw new AssertionError("jvm.ClassWriter: UNKNOWN target type should never occur!"); 1074 default: 1075 throw new AssertionError("jvm.ClassWriter: Unknown target type for position: " + p); 1076 } 1077 1078 { // Append location data for generics/arrays. 1079 databuf.appendByte(p.location.size()); 1080 java.util.List<Integer> loc = TypeAnnotationPosition.getBinaryFromTypePath(p.location); 1081 for (int i : loc) 1082 databuf.appendByte((byte)i); 1083 } 1084 } 1085 1086 /********************************************************************** 1087 * Writing Objects 1088 **********************************************************************/ 1089 1090 /** Enter an inner class into the `innerClasses' set/queue. 1091 */ 1092 void enterInner(ClassSymbol c) { 1093 if (c.type.isCompound()) { 1094 throw new AssertionError("Unexpected intersection type: " + c.type); 1095 } 1096 try { 1097 c.complete(); 1098 } catch (CompletionFailure ex) { 1099 System.err.println("error: " + c + ": " + ex.getMessage()); 1100 throw ex; 1101 } 1102 if (!c.type.hasTag(CLASS)) return; // arrays 1103 if (pool != null && // pool might be null if called from xClassName 1104 c.owner.enclClass() != null && 1105 (innerClasses == null || !innerClasses.contains(c))) { 1106 // log.errWriter.println("enter inner " + c);//DEBUG 1107 enterInner(c.owner.enclClass()); 1108 pool.put(c); 1109 pool.put(c.name); 1110 if (innerClasses == null) { 1111 innerClasses = new HashSet<ClassSymbol>(); 1112 innerClassesQueue = new ListBuffer<ClassSymbol>(); 1113 pool.put(names.InnerClasses); 1114 } 1115 innerClasses.add(c); 1116 innerClassesQueue.append(c); 1117 } 1118 } 1119 1120 /** Write "inner classes" attribute. 1121 */ 1122 void writeInnerClasses() { 1123 int alenIdx = writeAttr(names.InnerClasses); 1124 databuf.appendChar(innerClassesQueue.length()); 1125 for (List<ClassSymbol> l = innerClassesQueue.toList(); 1126 l.nonEmpty(); 1127 l = l.tail) { 1128 ClassSymbol inner = l.head; 1129 char flags = (char) adjustFlags(inner.flags_field); 1130 if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT 1131 if (inner.name.isEmpty()) flags &= ~FINAL; // Anonymous class: unset FINAL flag 1132 if (dumpInnerClassModifiers) { 1133 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1134 pw.println("INNERCLASS " + inner.name); 1135 pw.println("---" + flagNames(flags)); 1136 } 1137 databuf.appendChar(pool.get(inner)); 1138 databuf.appendChar( 1139 inner.owner.kind == TYP ? pool.get(inner.owner) : 0); 1140 databuf.appendChar( 1141 !inner.name.isEmpty() ? pool.get(inner.name) : 0); 1142 databuf.appendChar(flags); 1143 } 1144 endAttr(alenIdx); 1145 } 1146 1147 /** Write "bootstrapMethods" attribute. 1148 */ 1149 void writeBootstrapMethods() { 1150 int alenIdx = writeAttr(names.BootstrapMethods); 1151 databuf.appendChar(bootstrapMethods.size()); 1152 for (Map.Entry<DynamicMethod, MethodHandle> entry : bootstrapMethods.entrySet()) { 1153 DynamicMethod dmeth = entry.getKey(); 1154 DynamicMethodSymbol dsym = (DynamicMethodSymbol)dmeth.baseSymbol(); 1155 //write BSM handle 1156 databuf.appendChar(pool.get(entry.getValue())); 1157 //write static args length 1158 databuf.appendChar(dsym.staticArgs.length); 1159 //write static args array 1160 Object[] uniqueArgs = dmeth.uniqueStaticArgs; 1161 for (Object o : uniqueArgs) { 1162 databuf.appendChar(pool.get(o)); 1163 } 1164 } 1165 endAttr(alenIdx); 1166 } 1167 1168 /** Write field symbol, entering all references into constant pool. 1169 */ 1170 void writeField(VarSymbol v) { 1171 int flags = adjustFlags(v.flags()); 1172 databuf.appendChar(flags); 1173 if (dumpFieldModifiers) { 1174 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1175 pw.println("FIELD " + fieldName(v)); 1176 pw.println("---" + flagNames(v.flags())); 1177 } 1178 databuf.appendChar(pool.put(fieldName(v))); 1179 databuf.appendChar(pool.put(typeSig(v.erasure(types)))); 1180 int acountIdx = beginAttrs(); 1181 int acount = 0; 1182 if (v.getConstValue() != null) { 1183 int alenIdx = writeAttr(names.ConstantValue); 1184 databuf.appendChar(pool.put(v.getConstValue())); 1185 endAttr(alenIdx); 1186 acount++; 1187 } 1188 acount += writeMemberAttrs(v); 1189 endAttrs(acountIdx, acount); 1190 } 1191 1192 /** Write method symbol, entering all references into constant pool. 1193 */ 1194 void writeMethod(MethodSymbol m) { 1195 int flags = adjustFlags(m.flags()); 1196 databuf.appendChar(flags); 1197 if (dumpMethodModifiers) { 1198 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1199 pw.println("METHOD " + fieldName(m)); 1200 pw.println("---" + flagNames(m.flags())); 1201 } 1202 databuf.appendChar(pool.put(fieldName(m))); 1203 databuf.appendChar(pool.put(typeSig(m.externalType(types)))); 1204 int acountIdx = beginAttrs(); 1205 int acount = 0; 1206 if (m.code != null) { 1207 int alenIdx = writeAttr(names.Code); 1208 writeCode(m.code); 1209 m.code = null; // to conserve space 1210 endAttr(alenIdx); 1211 acount++; 1212 } 1213 List<Type> thrown = m.erasure(types).getThrownTypes(); 1214 if (thrown.nonEmpty()) { 1215 int alenIdx = writeAttr(names.Exceptions); 1216 databuf.appendChar(thrown.length()); 1217 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) 1218 databuf.appendChar(pool.put(l.head.tsym)); 1219 endAttr(alenIdx); 1220 acount++; 1221 } 1222 if (m.defaultValue != null) { 1223 int alenIdx = writeAttr(names.AnnotationDefault); 1224 m.defaultValue.accept(awriter); 1225 endAttr(alenIdx); 1226 acount++; 1227 } 1228 if (options.isSet(PARAMETERS)) 1229 acount += writeMethodParametersAttr(m); 1230 acount += writeMemberAttrs(m); 1231 acount += writeParameterAttrs(m); 1232 endAttrs(acountIdx, acount); 1233 } 1234 1235 /** Write code attribute of method. 1236 */ 1237 void writeCode(Code code) { 1238 databuf.appendChar(code.max_stack); 1239 databuf.appendChar(code.max_locals); 1240 databuf.appendInt(code.cp); 1241 databuf.appendBytes(code.code, 0, code.cp); 1242 databuf.appendChar(code.catchInfo.length()); 1243 for (List<char[]> l = code.catchInfo.toList(); 1244 l.nonEmpty(); 1245 l = l.tail) { 1246 for (int i = 0; i < l.head.length; i++) 1247 databuf.appendChar(l.head[i]); 1248 } 1249 int acountIdx = beginAttrs(); 1250 int acount = 0; 1251 1252 if (code.lineInfo.nonEmpty()) { 1253 int alenIdx = writeAttr(names.LineNumberTable); 1254 databuf.appendChar(code.lineInfo.length()); 1255 for (List<char[]> l = code.lineInfo.reverse(); 1256 l.nonEmpty(); 1257 l = l.tail) 1258 for (int i = 0; i < l.head.length; i++) 1259 databuf.appendChar(l.head[i]); 1260 endAttr(alenIdx); 1261 acount++; 1262 } 1263 1264 if (genCrt && (code.crt != null)) { 1265 CRTable crt = code.crt; 1266 int alenIdx = writeAttr(names.CharacterRangeTable); 1267 int crtIdx = beginAttrs(); 1268 int crtEntries = crt.writeCRT(databuf, code.lineMap, log); 1269 endAttrs(crtIdx, crtEntries); 1270 endAttr(alenIdx); 1271 acount++; 1272 } 1273 1274 // counter for number of generic local variables 1275 int nGenericVars = 0; 1276 1277 if (code.varBufferSize > 0) { 1278 int alenIdx = writeAttr(names.LocalVariableTable); 1279 databuf.appendChar(code.varBufferSize); 1280 1281 for (int i=0; i<code.varBufferSize; i++) { 1282 Code.LocalVar var = code.varBuffer[i]; 1283 1284 // write variable info 1285 Assert.check(var.start_pc >= 0 1286 && var.start_pc <= code.cp); 1287 databuf.appendChar(var.start_pc); 1288 Assert.check(var.length >= 0 1289 && (var.start_pc + var.length) <= code.cp); 1290 databuf.appendChar(var.length); 1291 VarSymbol sym = var.sym; 1292 databuf.appendChar(pool.put(sym.name)); 1293 Type vartype = sym.erasure(types); 1294 if (needsLocalVariableTypeEntry(sym.type)) 1295 nGenericVars++; 1296 databuf.appendChar(pool.put(typeSig(vartype))); 1297 databuf.appendChar(var.reg); 1298 } 1299 endAttr(alenIdx); 1300 acount++; 1301 } 1302 1303 if (nGenericVars > 0) { 1304 int alenIdx = writeAttr(names.LocalVariableTypeTable); 1305 databuf.appendChar(nGenericVars); 1306 int count = 0; 1307 1308 for (int i=0; i<code.varBufferSize; i++) { 1309 Code.LocalVar var = code.varBuffer[i]; 1310 VarSymbol sym = var.sym; 1311 if (!needsLocalVariableTypeEntry(sym.type)) 1312 continue; 1313 count++; 1314 // write variable info 1315 databuf.appendChar(var.start_pc); 1316 databuf.appendChar(var.length); 1317 databuf.appendChar(pool.put(sym.name)); 1318 databuf.appendChar(pool.put(typeSig(sym.type))); 1319 databuf.appendChar(var.reg); 1320 } 1321 Assert.check(count == nGenericVars); 1322 endAttr(alenIdx); 1323 acount++; 1324 } 1325 1326 if (code.stackMapBufferSize > 0) { 1327 if (debugstackmap) System.out.println("Stack map for " + code.meth); 1328 int alenIdx = writeAttr(code.stackMap.getAttributeName(names)); 1329 writeStackMap(code); 1330 endAttr(alenIdx); 1331 acount++; 1332 } 1333 endAttrs(acountIdx, acount); 1334 } 1335 //where 1336 private boolean needsLocalVariableTypeEntry(Type t) { 1337 //a local variable needs a type-entry if its type T is generic 1338 //(i.e. |T| != T) and if it's not an intersection type (not supported 1339 //in signature attribute grammar) 1340 return (!types.isSameType(t, types.erasure(t)) && 1341 !t.isCompound()); 1342 } 1343 1344 void writeStackMap(Code code) { 1345 int nframes = code.stackMapBufferSize; 1346 if (debugstackmap) System.out.println(" nframes = " + nframes); 1347 databuf.appendChar(nframes); 1348 1349 switch (code.stackMap) { 1350 case CLDC: 1351 for (int i=0; i<nframes; i++) { 1352 if (debugstackmap) System.out.print(" " + i + ":"); 1353 Code.StackMapFrame frame = code.stackMapBuffer[i]; 1354 1355 // output PC 1356 if (debugstackmap) System.out.print(" pc=" + frame.pc); 1357 databuf.appendChar(frame.pc); 1358 1359 // output locals 1360 int localCount = 0; 1361 for (int j=0; j<frame.locals.length; 1362 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) { 1363 localCount++; 1364 } 1365 if (debugstackmap) System.out.print(" nlocals=" + 1366 localCount); 1367 databuf.appendChar(localCount); 1368 for (int j=0; j<frame.locals.length; 1369 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) { 1370 if (debugstackmap) System.out.print(" local[" + j + "]="); 1371 writeStackMapType(frame.locals[j]); 1372 } 1373 1374 // output stack 1375 int stackCount = 0; 1376 for (int j=0; j<frame.stack.length; 1377 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) { 1378 stackCount++; 1379 } 1380 if (debugstackmap) System.out.print(" nstack=" + 1381 stackCount); 1382 databuf.appendChar(stackCount); 1383 for (int j=0; j<frame.stack.length; 1384 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) { 1385 if (debugstackmap) System.out.print(" stack[" + j + "]="); 1386 writeStackMapType(frame.stack[j]); 1387 } 1388 if (debugstackmap) System.out.println(); 1389 } 1390 break; 1391 case JSR202: { 1392 Assert.checkNull(code.stackMapBuffer); 1393 for (int i=0; i<nframes; i++) { 1394 if (debugstackmap) System.out.print(" " + i + ":"); 1395 StackMapTableFrame frame = code.stackMapTableBuffer[i]; 1396 frame.write(this); 1397 if (debugstackmap) System.out.println(); 1398 } 1399 break; 1400 } 1401 default: 1402 throw new AssertionError("Unexpected stackmap format value"); 1403 } 1404 } 1405 1406 //where 1407 void writeStackMapType(Type t) { 1408 if (t == null) { 1409 if (debugstackmap) System.out.print("empty"); 1410 databuf.appendByte(0); 1411 } 1412 else switch(t.getTag()) { 1413 case BYTE: 1414 case CHAR: 1415 case SHORT: 1416 case INT: 1417 case BOOLEAN: 1418 if (debugstackmap) System.out.print("int"); 1419 databuf.appendByte(1); 1420 break; 1421 case FLOAT: 1422 if (debugstackmap) System.out.print("float"); 1423 databuf.appendByte(2); 1424 break; 1425 case DOUBLE: 1426 if (debugstackmap) System.out.print("double"); 1427 databuf.appendByte(3); 1428 break; 1429 case LONG: 1430 if (debugstackmap) System.out.print("long"); 1431 databuf.appendByte(4); 1432 break; 1433 case BOT: // null 1434 if (debugstackmap) System.out.print("null"); 1435 databuf.appendByte(5); 1436 break; 1437 case CLASS: 1438 case ARRAY: 1439 if (debugstackmap) System.out.print("object(" + t + ")"); 1440 databuf.appendByte(7); 1441 databuf.appendChar(pool.put(t)); 1442 break; 1443 case TYPEVAR: 1444 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")"); 1445 databuf.appendByte(7); 1446 databuf.appendChar(pool.put(types.erasure(t).tsym)); 1447 break; 1448 case UNINITIALIZED_THIS: 1449 if (debugstackmap) System.out.print("uninit_this"); 1450 databuf.appendByte(6); 1451 break; 1452 case UNINITIALIZED_OBJECT: 1453 { UninitializedType uninitType = (UninitializedType)t; 1454 databuf.appendByte(8); 1455 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset); 1456 databuf.appendChar(uninitType.offset); 1457 } 1458 break; 1459 default: 1460 throw new AssertionError(); 1461 } 1462 } 1463 1464 /** An entry in the JSR202 StackMapTable */ 1465 abstract static class StackMapTableFrame { 1466 abstract int getFrameType(); 1467 1468 void write(ClassWriter writer) { 1469 int frameType = getFrameType(); 1470 writer.databuf.appendByte(frameType); 1471 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType); 1472 } 1473 1474 static class SameFrame extends StackMapTableFrame { 1475 final int offsetDelta; 1476 SameFrame(int offsetDelta) { 1477 this.offsetDelta = offsetDelta; 1478 } 1479 int getFrameType() { 1480 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED; 1481 } 1482 @Override 1483 void write(ClassWriter writer) { 1484 super.write(writer); 1485 if (getFrameType() == SAME_FRAME_EXTENDED) { 1486 writer.databuf.appendChar(offsetDelta); 1487 if (writer.debugstackmap){ 1488 System.out.print(" offset_delta=" + offsetDelta); 1489 } 1490 } 1491 } 1492 } 1493 1494 static class SameLocals1StackItemFrame extends StackMapTableFrame { 1495 final int offsetDelta; 1496 final Type stack; 1497 SameLocals1StackItemFrame(int offsetDelta, Type stack) { 1498 this.offsetDelta = offsetDelta; 1499 this.stack = stack; 1500 } 1501 int getFrameType() { 1502 return (offsetDelta < SAME_FRAME_SIZE) ? 1503 (SAME_FRAME_SIZE + offsetDelta) : 1504 SAME_LOCALS_1_STACK_ITEM_EXTENDED; 1505 } 1506 @Override 1507 void write(ClassWriter writer) { 1508 super.write(writer); 1509 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) { 1510 writer.databuf.appendChar(offsetDelta); 1511 if (writer.debugstackmap) { 1512 System.out.print(" offset_delta=" + offsetDelta); 1513 } 1514 } 1515 if (writer.debugstackmap) { 1516 System.out.print(" stack[" + 0 + "]="); 1517 } 1518 writer.writeStackMapType(stack); 1519 } 1520 } 1521 1522 static class ChopFrame extends StackMapTableFrame { 1523 final int frameType; 1524 final int offsetDelta; 1525 ChopFrame(int frameType, int offsetDelta) { 1526 this.frameType = frameType; 1527 this.offsetDelta = offsetDelta; 1528 } 1529 int getFrameType() { return frameType; } 1530 @Override 1531 void write(ClassWriter writer) { 1532 super.write(writer); 1533 writer.databuf.appendChar(offsetDelta); 1534 if (writer.debugstackmap) { 1535 System.out.print(" offset_delta=" + offsetDelta); 1536 } 1537 } 1538 } 1539 1540 static class AppendFrame extends StackMapTableFrame { 1541 final int frameType; 1542 final int offsetDelta; 1543 final Type[] locals; 1544 AppendFrame(int frameType, int offsetDelta, Type[] locals) { 1545 this.frameType = frameType; 1546 this.offsetDelta = offsetDelta; 1547 this.locals = locals; 1548 } 1549 int getFrameType() { return frameType; } 1550 @Override 1551 void write(ClassWriter writer) { 1552 super.write(writer); 1553 writer.databuf.appendChar(offsetDelta); 1554 if (writer.debugstackmap) { 1555 System.out.print(" offset_delta=" + offsetDelta); 1556 } 1557 for (int i=0; i<locals.length; i++) { 1558 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1559 writer.writeStackMapType(locals[i]); 1560 } 1561 } 1562 } 1563 1564 static class FullFrame extends StackMapTableFrame { 1565 final int offsetDelta; 1566 final Type[] locals; 1567 final Type[] stack; 1568 FullFrame(int offsetDelta, Type[] locals, Type[] stack) { 1569 this.offsetDelta = offsetDelta; 1570 this.locals = locals; 1571 this.stack = stack; 1572 } 1573 int getFrameType() { return FULL_FRAME; } 1574 @Override 1575 void write(ClassWriter writer) { 1576 super.write(writer); 1577 writer.databuf.appendChar(offsetDelta); 1578 writer.databuf.appendChar(locals.length); 1579 if (writer.debugstackmap) { 1580 System.out.print(" offset_delta=" + offsetDelta); 1581 System.out.print(" nlocals=" + locals.length); 1582 } 1583 for (int i=0; i<locals.length; i++) { 1584 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1585 writer.writeStackMapType(locals[i]); 1586 } 1587 1588 writer.databuf.appendChar(stack.length); 1589 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); } 1590 for (int i=0; i<stack.length; i++) { 1591 if (writer.debugstackmap) System.out.print(" stack[" + i + "]="); 1592 writer.writeStackMapType(stack[i]); 1593 } 1594 } 1595 } 1596 1597 /** Compare this frame with the previous frame and produce 1598 * an entry of compressed stack map frame. */ 1599 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame, 1600 int prev_pc, 1601 Type[] prev_locals, 1602 Types types) { 1603 Type[] locals = this_frame.locals; 1604 Type[] stack = this_frame.stack; 1605 int offset_delta = this_frame.pc - prev_pc - 1; 1606 if (stack.length == 1) { 1607 if (locals.length == prev_locals.length 1608 && compare(prev_locals, locals, types) == 0) { 1609 return new SameLocals1StackItemFrame(offset_delta, stack[0]); 1610 } 1611 } else if (stack.length == 0) { 1612 int diff_length = compare(prev_locals, locals, types); 1613 if (diff_length == 0) { 1614 return new SameFrame(offset_delta); 1615 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) { 1616 // APPEND 1617 Type[] local_diff = new Type[-diff_length]; 1618 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) { 1619 local_diff[j] = locals[i]; 1620 } 1621 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length, 1622 offset_delta, 1623 local_diff); 1624 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) { 1625 // CHOP 1626 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length, 1627 offset_delta); 1628 } 1629 } 1630 // FULL_FRAME 1631 return new FullFrame(offset_delta, locals, stack); 1632 } 1633 1634 static boolean isInt(Type t) { 1635 return (t.getTag().isStrictSubRangeOf(INT) || t.hasTag(BOOLEAN)); 1636 } 1637 1638 static boolean isSameType(Type t1, Type t2, Types types) { 1639 if (t1 == null) { return t2 == null; } 1640 if (t2 == null) { return false; } 1641 1642 if (isInt(t1) && isInt(t2)) { return true; } 1643 1644 if (t1.hasTag(UNINITIALIZED_THIS)) { 1645 return t2.hasTag(UNINITIALIZED_THIS); 1646 } else if (t1.hasTag(UNINITIALIZED_OBJECT)) { 1647 if (t2.hasTag(UNINITIALIZED_OBJECT)) { 1648 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset; 1649 } else { 1650 return false; 1651 } 1652 } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) { 1653 return false; 1654 } 1655 1656 return types.isSameType(t1, t2); 1657 } 1658 1659 static int compare(Type[] arr1, Type[] arr2, Types types) { 1660 int diff_length = arr1.length - arr2.length; 1661 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) { 1662 return Integer.MAX_VALUE; 1663 } 1664 int len = (diff_length > 0) ? arr2.length : arr1.length; 1665 for (int i=0; i<len; i++) { 1666 if (!isSameType(arr1[i], arr2[i], types)) { 1667 return Integer.MAX_VALUE; 1668 } 1669 } 1670 return diff_length; 1671 } 1672 } 1673 1674 void writeFields(Scope.Entry e) { 1675 // process them in reverse sibling order; 1676 // i.e., process them in declaration order. 1677 List<VarSymbol> vars = List.nil(); 1678 for (Scope.Entry i = e; i != null; i = i.sibling) { 1679 if (i.sym.kind == VAR) vars = vars.prepend((VarSymbol)i.sym); 1680 } 1681 while (vars.nonEmpty()) { 1682 writeField(vars.head); 1683 vars = vars.tail; 1684 } 1685 } 1686 1687 void writeMethods(Scope.Entry e) { 1688 List<MethodSymbol> methods = List.nil(); 1689 for (Scope.Entry i = e; i != null; i = i.sibling) { 1690 if (i.sym.kind == MTH && (i.sym.flags() & HYPOTHETICAL) == 0) 1691 methods = methods.prepend((MethodSymbol)i.sym); 1692 } 1693 while (methods.nonEmpty()) { 1694 writeMethod(methods.head); 1695 methods = methods.tail; 1696 } 1697 } 1698 1699 /** Emit a class file for a given class. 1700 * @param c The class from which a class file is generated. 1701 */ 1702 public JavaFileObject writeClass(ClassSymbol c) 1703 throws IOException, PoolOverflow, StringOverflow 1704 { 1705 JavaFileObject outFile 1706 = fileManager.getJavaFileForOutput(CLASS_OUTPUT, 1707 c.flatname.toString(), 1708 JavaFileObject.Kind.CLASS, 1709 c.sourcefile); 1710 OutputStream out = outFile.openOutputStream(); 1711 try { 1712 writeClassFile(out, c); 1713 if (verbose) 1714 log.printVerbose("wrote.file", outFile); 1715 out.close(); 1716 out = null; 1717 } finally { 1718 if (out != null) { 1719 // if we are propogating an exception, delete the file 1720 out.close(); 1721 outFile.delete(); 1722 outFile = null; 1723 } 1724 } 1725 return outFile; // may be null if write failed 1726 } 1727 1728 /** Write class `c' to outstream `out'. 1729 */ 1730 public void writeClassFile(OutputStream out, ClassSymbol c) 1731 throws IOException, PoolOverflow, StringOverflow { 1732 Assert.check((c.flags() & COMPOUND) == 0); 1733 databuf.reset(); 1734 poolbuf.reset(); 1735 sigbuf.reset(); 1736 pool = c.pool; 1737 innerClasses = null; 1738 innerClassesQueue = null; 1739 bootstrapMethods = new LinkedHashMap<DynamicMethod, MethodHandle>(); 1740 1741 Type supertype = types.supertype(c.type); 1742 List<Type> interfaces = types.interfaces(c.type); 1743 List<Type> typarams = c.type.getTypeArguments(); 1744 1745 int flags = adjustFlags(c.flags() & ~DEFAULT); 1746 if ((flags & PROTECTED) != 0) flags |= PUBLIC; 1747 flags = flags & ClassFlags & ~STRICTFP; 1748 if ((flags & INTERFACE) == 0) flags |= ACC_SUPER; 1749 if (c.isInner() && c.name.isEmpty()) flags &= ~FINAL; 1750 if (dumpClassModifiers) { 1751 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1752 pw.println(); 1753 pw.println("CLASSFILE " + c.getQualifiedName()); 1754 pw.println("---" + flagNames(flags)); 1755 } 1756 databuf.appendChar(flags); 1757 1758 databuf.appendChar(pool.put(c)); 1759 databuf.appendChar(supertype.hasTag(CLASS) ? pool.put(supertype.tsym) : 0); 1760 databuf.appendChar(interfaces.length()); 1761 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail) 1762 databuf.appendChar(pool.put(l.head.tsym)); 1763 int fieldsCount = 0; 1764 int methodsCount = 0; 1765 for (Scope.Entry e = c.members().elems; e != null; e = e.sibling) { 1766 switch (e.sym.kind) { 1767 case VAR: fieldsCount++; break; 1768 case MTH: if ((e.sym.flags() & HYPOTHETICAL) == 0) methodsCount++; 1769 break; 1770 case TYP: enterInner((ClassSymbol)e.sym); break; 1771 default : Assert.error(); 1772 } 1773 } 1774 1775 if (c.trans_local != null) { 1776 for (ClassSymbol local : c.trans_local) { 1777 enterInner(local); 1778 } 1779 } 1780 1781 databuf.appendChar(fieldsCount); 1782 writeFields(c.members().elems); 1783 databuf.appendChar(methodsCount); 1784 writeMethods(c.members().elems); 1785 1786 int acountIdx = beginAttrs(); 1787 int acount = 0; 1788 1789 boolean sigReq = 1790 typarams.length() != 0 || supertype.allparams().length() != 0; 1791 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail) 1792 sigReq = l.head.allparams().length() != 0; 1793 if (sigReq) { 1794 Assert.check(source.allowGenerics()); 1795 int alenIdx = writeAttr(names.Signature); 1796 if (typarams.length() != 0) assembleParamsSig(typarams); 1797 assembleSig(supertype); 1798 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail) 1799 assembleSig(l.head); 1800 databuf.appendChar(pool.put(sigbuf.toName(names))); 1801 sigbuf.reset(); 1802 endAttr(alenIdx); 1803 acount++; 1804 } 1805 1806 if (c.sourcefile != null && emitSourceFile) { 1807 int alenIdx = writeAttr(names.SourceFile); 1808 // WHM 6/29/1999: Strip file path prefix. We do it here at 1809 // the last possible moment because the sourcefile may be used 1810 // elsewhere in error diagnostics. Fixes 4241573. 1811 //databuf.appendChar(c.pool.put(c.sourcefile)); 1812 String simpleName = BaseFileObject.getSimpleName(c.sourcefile); 1813 databuf.appendChar(c.pool.put(names.fromString(simpleName))); 1814 endAttr(alenIdx); 1815 acount++; 1816 } 1817 1818 if (genCrt) { 1819 // Append SourceID attribute 1820 int alenIdx = writeAttr(names.SourceID); 1821 databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile))))); 1822 endAttr(alenIdx); 1823 acount++; 1824 // Append CompilationID attribute 1825 alenIdx = writeAttr(names.CompilationID); 1826 databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis())))); 1827 endAttr(alenIdx); 1828 acount++; 1829 } 1830 1831 acount += writeFlagAttrs(c.flags()); 1832 acount += writeJavaAnnotations(c.getRawAttributes()); 1833 acount += writeTypeAnnotations(c.getRawTypeAttributes()); 1834 acount += writeEnclosingMethodAttribute(c); 1835 acount += writeExtraClassAttributes(c); 1836 1837 poolbuf.appendInt(JAVA_MAGIC); 1838 poolbuf.appendChar(target.minorVersion); 1839 poolbuf.appendChar(target.majorVersion); 1840 1841 writePool(c.pool); 1842 1843 if (innerClasses != null) { 1844 writeInnerClasses(); 1845 acount++; 1846 } 1847 1848 if (!bootstrapMethods.isEmpty()) { 1849 writeBootstrapMethods(); 1850 acount++; 1851 } 1852 1853 endAttrs(acountIdx, acount); 1854 1855 poolbuf.appendBytes(databuf.elems, 0, databuf.length); 1856 out.write(poolbuf.elems, 0, poolbuf.length); 1857 1858 pool = c.pool = null; // to conserve space 1859 } 1860 1861 /**Allows subclasses to write additional class attributes 1862 * 1863 * @return the number of attributes written 1864 */ 1865 protected int writeExtraClassAttributes(ClassSymbol c) { 1866 return 0; 1867 } 1868 1869 int adjustFlags(final long flags) { 1870 int result = (int)flags; 1871 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag()) 1872 result &= ~SYNTHETIC; 1873 if ((flags & ENUM) != 0 && !target.useEnumFlag()) 1874 result &= ~ENUM; 1875 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag()) 1876 result &= ~ANNOTATION; 1877 1878 if ((flags & BRIDGE) != 0 && target.useBridgeFlag()) 1879 result |= ACC_BRIDGE; 1880 if ((flags & VARARGS) != 0 && target.useVarargsFlag()) 1881 result |= ACC_VARARGS; 1882 if ((flags & DEFAULT) != 0) 1883 result &= ~ABSTRACT; 1884 return result; 1885 } 1886 1887 long getLastModified(FileObject filename) { 1888 long mod = 0; 1889 try { 1890 mod = filename.getLastModified(); 1891 } catch (SecurityException e) { 1892 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage()); 1893 } 1894 return mod; 1895 } 1896 }