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