ClassWriter.java revision 2571:10fc81ac75b4
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 Assert.checkNonNull(tc.position); 744 if (tc.position.type.isLocal() != inCode) { 745 continue; 746 } 747 if (!tc.position.emitToClassfile()) { 748 continue; 749 } 750 switch (types.getRetention(tc)) { 751 case SOURCE: break; 752 case CLASS: invisibles.append(tc); break; 753 case RUNTIME: visibles.append(tc); break; 754 default: // /* fail soft */ throw new AssertionError(vis); 755 } 756 } 757 758 int attrCount = 0; 759 if (visibles.length() != 0) { 760 int attrIndex = writeAttr(names.RuntimeVisibleTypeAnnotations); 761 databuf.appendChar(visibles.length()); 762 for (Attribute.TypeCompound p : visibles) 763 writeTypeAnnotation(p); 764 endAttr(attrIndex); 765 attrCount++; 766 } 767 768 if (invisibles.length() != 0) { 769 int attrIndex = writeAttr(names.RuntimeInvisibleTypeAnnotations); 770 databuf.appendChar(invisibles.length()); 771 for (Attribute.TypeCompound p : invisibles) 772 writeTypeAnnotation(p); 773 endAttr(attrIndex); 774 attrCount++; 775 } 776 777 return attrCount; 778 } 779 780 /** A visitor to write an attribute including its leading 781 * single-character marker. 782 */ 783 class AttributeWriter implements Attribute.Visitor { 784 public void visitConstant(Attribute.Constant _value) { 785 Object value = _value.value; 786 switch (_value.type.getTag()) { 787 case BYTE: 788 databuf.appendByte('B'); 789 break; 790 case CHAR: 791 databuf.appendByte('C'); 792 break; 793 case SHORT: 794 databuf.appendByte('S'); 795 break; 796 case INT: 797 databuf.appendByte('I'); 798 break; 799 case LONG: 800 databuf.appendByte('J'); 801 break; 802 case FLOAT: 803 databuf.appendByte('F'); 804 break; 805 case DOUBLE: 806 databuf.appendByte('D'); 807 break; 808 case BOOLEAN: 809 databuf.appendByte('Z'); 810 break; 811 case CLASS: 812 Assert.check(value instanceof String); 813 databuf.appendByte('s'); 814 value = names.fromString(value.toString()); // CONSTANT_Utf8 815 break; 816 default: 817 throw new AssertionError(_value.type); 818 } 819 databuf.appendChar(pool.put(value)); 820 } 821 public void visitEnum(Attribute.Enum e) { 822 databuf.appendByte('e'); 823 databuf.appendChar(pool.put(typeSig(e.value.type))); 824 databuf.appendChar(pool.put(e.value.name)); 825 } 826 public void visitClass(Attribute.Class clazz) { 827 databuf.appendByte('c'); 828 databuf.appendChar(pool.put(typeSig(clazz.classType))); 829 } 830 public void visitCompound(Attribute.Compound compound) { 831 databuf.appendByte('@'); 832 writeCompoundAttribute(compound); 833 } 834 public void visitError(Attribute.Error x) { 835 throw new AssertionError(x); 836 } 837 public void visitArray(Attribute.Array array) { 838 databuf.appendByte('['); 839 databuf.appendChar(array.values.length); 840 for (Attribute a : array.values) { 841 a.accept(this); 842 } 843 } 844 } 845 AttributeWriter awriter = new AttributeWriter(); 846 847 /** Write a compound attribute excluding the '@' marker. */ 848 void writeCompoundAttribute(Attribute.Compound c) { 849 databuf.appendChar(pool.put(typeSig(c.type))); 850 databuf.appendChar(c.values.length()); 851 for (Pair<Symbol.MethodSymbol,Attribute> p : c.values) { 852 databuf.appendChar(pool.put(p.fst.name)); 853 p.snd.accept(awriter); 854 } 855 } 856 857 void writeTypeAnnotation(Attribute.TypeCompound c) { 858 writePosition(c.position); 859 writeCompoundAttribute(c); 860 } 861 862 void writePosition(TypeAnnotationPosition p) { 863 databuf.appendByte(p.type.targetTypeValue()); // TargetType tag is a byte 864 switch (p.type) { 865 // instanceof 866 case INSTANCEOF: 867 // new expression 868 case NEW: 869 // constructor/method reference receiver 870 case CONSTRUCTOR_REFERENCE: 871 case METHOD_REFERENCE: 872 databuf.appendChar(p.offset); 873 break; 874 // local variable 875 case LOCAL_VARIABLE: 876 // resource variable 877 case RESOURCE_VARIABLE: 878 databuf.appendChar(p.lvarOffset.length); // for table length 879 for (int i = 0; i < p.lvarOffset.length; ++i) { 880 databuf.appendChar(p.lvarOffset[i]); 881 databuf.appendChar(p.lvarLength[i]); 882 databuf.appendChar(p.lvarIndex[i]); 883 } 884 break; 885 // exception parameter 886 case EXCEPTION_PARAMETER: 887 databuf.appendChar(p.getExceptionIndex()); 888 break; 889 // method receiver 890 case METHOD_RECEIVER: 891 // Do nothing 892 break; 893 // type parameter 894 case CLASS_TYPE_PARAMETER: 895 case METHOD_TYPE_PARAMETER: 896 databuf.appendByte(p.parameter_index); 897 break; 898 // type parameter bound 899 case CLASS_TYPE_PARAMETER_BOUND: 900 case METHOD_TYPE_PARAMETER_BOUND: 901 databuf.appendByte(p.parameter_index); 902 databuf.appendByte(p.bound_index); 903 break; 904 // class extends or implements clause 905 case CLASS_EXTENDS: 906 databuf.appendChar(p.type_index); 907 break; 908 // throws 909 case THROWS: 910 databuf.appendChar(p.type_index); 911 break; 912 // method parameter 913 case METHOD_FORMAL_PARAMETER: 914 databuf.appendByte(p.parameter_index); 915 break; 916 // type cast 917 case CAST: 918 // method/constructor/reference type argument 919 case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: 920 case METHOD_INVOCATION_TYPE_ARGUMENT: 921 case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: 922 case METHOD_REFERENCE_TYPE_ARGUMENT: 923 databuf.appendChar(p.offset); 924 databuf.appendByte(p.type_index); 925 break; 926 // We don't need to worry about these 927 case METHOD_RETURN: 928 case FIELD: 929 break; 930 default: 931 throw new AssertionError("jvm.ClassWriter: Unknown target type for position: " + p); 932 } 933 934 { // Append location data for generics/arrays. 935 databuf.appendByte(p.location.size()); 936 java.util.List<Integer> loc = TypeAnnotationPosition.getBinaryFromTypePath(p.location); 937 for (int i : loc) 938 databuf.appendByte((byte)i); 939 } 940 } 941 942/********************************************************************** 943 * Writing Objects 944 **********************************************************************/ 945 946 /** Enter an inner class into the `innerClasses' set/queue. 947 */ 948 void enterInner(ClassSymbol c) { 949 if (c.type.isCompound()) { 950 throw new AssertionError("Unexpected intersection type: " + c.type); 951 } 952 try { 953 c.complete(); 954 } catch (CompletionFailure ex) { 955 System.err.println("error: " + c + ": " + ex.getMessage()); 956 throw ex; 957 } 958 if (!c.type.hasTag(CLASS)) return; // arrays 959 if (pool != null && // pool might be null if called from xClassName 960 c.owner.enclClass() != null && 961 (innerClasses == null || !innerClasses.contains(c))) { 962// log.errWriter.println("enter inner " + c);//DEBUG 963 enterInner(c.owner.enclClass()); 964 pool.put(c); 965 if (c.name != names.empty) 966 pool.put(c.name); 967 if (innerClasses == null) { 968 innerClasses = new HashSet<>(); 969 innerClassesQueue = new ListBuffer<>(); 970 pool.put(names.InnerClasses); 971 } 972 innerClasses.add(c); 973 innerClassesQueue.append(c); 974 } 975 } 976 977 /** Write "inner classes" attribute. 978 */ 979 void writeInnerClasses() { 980 int alenIdx = writeAttr(names.InnerClasses); 981 databuf.appendChar(innerClassesQueue.length()); 982 for (List<ClassSymbol> l = innerClassesQueue.toList(); 983 l.nonEmpty(); 984 l = l.tail) { 985 ClassSymbol inner = l.head; 986 char flags = (char) adjustFlags(inner.flags_field); 987 if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT 988 if (inner.name.isEmpty()) flags &= ~FINAL; // Anonymous class: unset FINAL flag 989 flags &= ~STRICTFP; //inner classes should not have the strictfp flag set. 990 if (dumpInnerClassModifiers) { 991 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 992 pw.println("INNERCLASS " + inner.name); 993 pw.println("---" + flagNames(flags)); 994 } 995 databuf.appendChar(pool.get(inner)); 996 databuf.appendChar( 997 inner.owner.kind == TYP && !inner.name.isEmpty() ? pool.get(inner.owner) : 0); 998 databuf.appendChar( 999 !inner.name.isEmpty() ? pool.get(inner.name) : 0); 1000 databuf.appendChar(flags); 1001 } 1002 endAttr(alenIdx); 1003 } 1004 1005 /** Write "bootstrapMethods" attribute. 1006 */ 1007 void writeBootstrapMethods() { 1008 int alenIdx = writeAttr(names.BootstrapMethods); 1009 databuf.appendChar(bootstrapMethods.size()); 1010 for (Map.Entry<DynamicMethod, MethodHandle> entry : bootstrapMethods.entrySet()) { 1011 DynamicMethod dmeth = entry.getKey(); 1012 DynamicMethodSymbol dsym = (DynamicMethodSymbol)dmeth.baseSymbol(); 1013 //write BSM handle 1014 databuf.appendChar(pool.get(entry.getValue())); 1015 //write static args length 1016 databuf.appendChar(dsym.staticArgs.length); 1017 //write static args array 1018 Object[] uniqueArgs = dmeth.uniqueStaticArgs; 1019 for (Object o : uniqueArgs) { 1020 databuf.appendChar(pool.get(o)); 1021 } 1022 } 1023 endAttr(alenIdx); 1024 } 1025 1026 /** Write field symbol, entering all references into constant pool. 1027 */ 1028 void writeField(VarSymbol v) { 1029 int flags = adjustFlags(v.flags()); 1030 databuf.appendChar(flags); 1031 if (dumpFieldModifiers) { 1032 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1033 pw.println("FIELD " + fieldName(v)); 1034 pw.println("---" + flagNames(v.flags())); 1035 } 1036 databuf.appendChar(pool.put(fieldName(v))); 1037 databuf.appendChar(pool.put(typeSig(v.erasure(types)))); 1038 int acountIdx = beginAttrs(); 1039 int acount = 0; 1040 if (v.getConstValue() != null) { 1041 int alenIdx = writeAttr(names.ConstantValue); 1042 databuf.appendChar(pool.put(v.getConstValue())); 1043 endAttr(alenIdx); 1044 acount++; 1045 } 1046 acount += writeMemberAttrs(v); 1047 endAttrs(acountIdx, acount); 1048 } 1049 1050 /** Write method symbol, entering all references into constant pool. 1051 */ 1052 void writeMethod(MethodSymbol m) { 1053 int flags = adjustFlags(m.flags()); 1054 databuf.appendChar(flags); 1055 if (dumpMethodModifiers) { 1056 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1057 pw.println("METHOD " + fieldName(m)); 1058 pw.println("---" + flagNames(m.flags())); 1059 } 1060 databuf.appendChar(pool.put(fieldName(m))); 1061 databuf.appendChar(pool.put(typeSig(m.externalType(types)))); 1062 int acountIdx = beginAttrs(); 1063 int acount = 0; 1064 if (m.code != null) { 1065 int alenIdx = writeAttr(names.Code); 1066 writeCode(m.code); 1067 m.code = null; // to conserve space 1068 endAttr(alenIdx); 1069 acount++; 1070 } 1071 List<Type> thrown = m.erasure(types).getThrownTypes(); 1072 if (thrown.nonEmpty()) { 1073 int alenIdx = writeAttr(names.Exceptions); 1074 databuf.appendChar(thrown.length()); 1075 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) 1076 databuf.appendChar(pool.put(l.head.tsym)); 1077 endAttr(alenIdx); 1078 acount++; 1079 } 1080 if (m.defaultValue != null) { 1081 int alenIdx = writeAttr(names.AnnotationDefault); 1082 m.defaultValue.accept(awriter); 1083 endAttr(alenIdx); 1084 acount++; 1085 } 1086 if (options.isSet(PARAMETERS)) 1087 acount += writeMethodParametersAttr(m); 1088 acount += writeMemberAttrs(m); 1089 acount += writeParameterAttrs(m); 1090 endAttrs(acountIdx, acount); 1091 } 1092 1093 /** Write code attribute of method. 1094 */ 1095 void writeCode(Code code) { 1096 databuf.appendChar(code.max_stack); 1097 databuf.appendChar(code.max_locals); 1098 databuf.appendInt(code.cp); 1099 databuf.appendBytes(code.code, 0, code.cp); 1100 databuf.appendChar(code.catchInfo.length()); 1101 for (List<char[]> l = code.catchInfo.toList(); 1102 l.nonEmpty(); 1103 l = l.tail) { 1104 for (int i = 0; i < l.head.length; i++) 1105 databuf.appendChar(l.head[i]); 1106 } 1107 int acountIdx = beginAttrs(); 1108 int acount = 0; 1109 1110 if (code.lineInfo.nonEmpty()) { 1111 int alenIdx = writeAttr(names.LineNumberTable); 1112 databuf.appendChar(code.lineInfo.length()); 1113 for (List<char[]> l = code.lineInfo.reverse(); 1114 l.nonEmpty(); 1115 l = l.tail) 1116 for (int i = 0; i < l.head.length; i++) 1117 databuf.appendChar(l.head[i]); 1118 endAttr(alenIdx); 1119 acount++; 1120 } 1121 1122 if (genCrt && (code.crt != null)) { 1123 CRTable crt = code.crt; 1124 int alenIdx = writeAttr(names.CharacterRangeTable); 1125 int crtIdx = beginAttrs(); 1126 int crtEntries = crt.writeCRT(databuf, code.lineMap, log); 1127 endAttrs(crtIdx, crtEntries); 1128 endAttr(alenIdx); 1129 acount++; 1130 } 1131 1132 // counter for number of generic local variables 1133 if (code.varDebugInfo && code.varBufferSize > 0) { 1134 int nGenericVars = 0; 1135 int alenIdx = writeAttr(names.LocalVariableTable); 1136 databuf.appendChar(code.getLVTSize()); 1137 for (int i=0; i<code.varBufferSize; i++) { 1138 Code.LocalVar var = code.varBuffer[i]; 1139 1140 for (Code.LocalVar.Range r: var.aliveRanges) { 1141 // write variable info 1142 Assert.check(r.start_pc >= 0 1143 && r.start_pc <= code.cp); 1144 databuf.appendChar(r.start_pc); 1145 Assert.check(r.length >= 0 1146 && (r.start_pc + r.length) <= code.cp); 1147 databuf.appendChar(r.length); 1148 VarSymbol sym = var.sym; 1149 databuf.appendChar(pool.put(sym.name)); 1150 Type vartype = sym.erasure(types); 1151 databuf.appendChar(pool.put(typeSig(vartype))); 1152 databuf.appendChar(var.reg); 1153 if (needsLocalVariableTypeEntry(var.sym.type)) { 1154 nGenericVars++; 1155 } 1156 } 1157 } 1158 endAttr(alenIdx); 1159 acount++; 1160 1161 if (nGenericVars > 0) { 1162 alenIdx = writeAttr(names.LocalVariableTypeTable); 1163 databuf.appendChar(nGenericVars); 1164 int count = 0; 1165 1166 for (int i=0; i<code.varBufferSize; i++) { 1167 Code.LocalVar var = code.varBuffer[i]; 1168 VarSymbol sym = var.sym; 1169 if (!needsLocalVariableTypeEntry(sym.type)) 1170 continue; 1171 for (Code.LocalVar.Range r : var.aliveRanges) { 1172 // write variable info 1173 databuf.appendChar(r.start_pc); 1174 databuf.appendChar(r.length); 1175 databuf.appendChar(pool.put(sym.name)); 1176 databuf.appendChar(pool.put(typeSig(sym.type))); 1177 databuf.appendChar(var.reg); 1178 count++; 1179 } 1180 } 1181 Assert.check(count == nGenericVars); 1182 endAttr(alenIdx); 1183 acount++; 1184 } 1185 } 1186 1187 if (code.stackMapBufferSize > 0) { 1188 if (debugstackmap) System.out.println("Stack map for " + code.meth); 1189 int alenIdx = writeAttr(code.stackMap.getAttributeName(names)); 1190 writeStackMap(code); 1191 endAttr(alenIdx); 1192 acount++; 1193 } 1194 1195 acount += writeTypeAnnotations(code.meth.getRawTypeAttributes(), true); 1196 1197 endAttrs(acountIdx, acount); 1198 } 1199 //where 1200 private boolean needsLocalVariableTypeEntry(Type t) { 1201 //a local variable needs a type-entry if its type T is generic 1202 //(i.e. |T| != T) and if it's not an intersection type (not supported 1203 //in signature attribute grammar) 1204 return (!types.isSameType(t, types.erasure(t)) && 1205 !t.isCompound()); 1206 } 1207 1208 void writeStackMap(Code code) { 1209 int nframes = code.stackMapBufferSize; 1210 if (debugstackmap) System.out.println(" nframes = " + nframes); 1211 databuf.appendChar(nframes); 1212 1213 switch (code.stackMap) { 1214 case CLDC: 1215 for (int i=0; i<nframes; i++) { 1216 if (debugstackmap) System.out.print(" " + i + ":"); 1217 Code.StackMapFrame frame = code.stackMapBuffer[i]; 1218 1219 // output PC 1220 if (debugstackmap) System.out.print(" pc=" + frame.pc); 1221 databuf.appendChar(frame.pc); 1222 1223 // output locals 1224 int localCount = 0; 1225 for (int j=0; j<frame.locals.length; 1226 j += Code.width(frame.locals[j])) { 1227 localCount++; 1228 } 1229 if (debugstackmap) System.out.print(" nlocals=" + 1230 localCount); 1231 databuf.appendChar(localCount); 1232 for (int j=0; j<frame.locals.length; 1233 j += Code.width(frame.locals[j])) { 1234 if (debugstackmap) System.out.print(" local[" + j + "]="); 1235 writeStackMapType(frame.locals[j]); 1236 } 1237 1238 // output stack 1239 int stackCount = 0; 1240 for (int j=0; j<frame.stack.length; 1241 j += Code.width(frame.stack[j])) { 1242 stackCount++; 1243 } 1244 if (debugstackmap) System.out.print(" nstack=" + 1245 stackCount); 1246 databuf.appendChar(stackCount); 1247 for (int j=0; j<frame.stack.length; 1248 j += Code.width(frame.stack[j])) { 1249 if (debugstackmap) System.out.print(" stack[" + j + "]="); 1250 writeStackMapType(frame.stack[j]); 1251 } 1252 if (debugstackmap) System.out.println(); 1253 } 1254 break; 1255 case JSR202: { 1256 Assert.checkNull(code.stackMapBuffer); 1257 for (int i=0; i<nframes; i++) { 1258 if (debugstackmap) System.out.print(" " + i + ":"); 1259 StackMapTableFrame frame = code.stackMapTableBuffer[i]; 1260 frame.write(this); 1261 if (debugstackmap) System.out.println(); 1262 } 1263 break; 1264 } 1265 default: 1266 throw new AssertionError("Unexpected stackmap format value"); 1267 } 1268 } 1269 1270 //where 1271 void writeStackMapType(Type t) { 1272 if (t == null) { 1273 if (debugstackmap) System.out.print("empty"); 1274 databuf.appendByte(0); 1275 } 1276 else switch(t.getTag()) { 1277 case BYTE: 1278 case CHAR: 1279 case SHORT: 1280 case INT: 1281 case BOOLEAN: 1282 if (debugstackmap) System.out.print("int"); 1283 databuf.appendByte(1); 1284 break; 1285 case FLOAT: 1286 if (debugstackmap) System.out.print("float"); 1287 databuf.appendByte(2); 1288 break; 1289 case DOUBLE: 1290 if (debugstackmap) System.out.print("double"); 1291 databuf.appendByte(3); 1292 break; 1293 case LONG: 1294 if (debugstackmap) System.out.print("long"); 1295 databuf.appendByte(4); 1296 break; 1297 case BOT: // null 1298 if (debugstackmap) System.out.print("null"); 1299 databuf.appendByte(5); 1300 break; 1301 case CLASS: 1302 case ARRAY: 1303 if (debugstackmap) System.out.print("object(" + t + ")"); 1304 databuf.appendByte(7); 1305 databuf.appendChar(pool.put(t)); 1306 break; 1307 case TYPEVAR: 1308 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")"); 1309 databuf.appendByte(7); 1310 databuf.appendChar(pool.put(types.erasure(t).tsym)); 1311 break; 1312 case UNINITIALIZED_THIS: 1313 if (debugstackmap) System.out.print("uninit_this"); 1314 databuf.appendByte(6); 1315 break; 1316 case UNINITIALIZED_OBJECT: 1317 { UninitializedType uninitType = (UninitializedType)t; 1318 databuf.appendByte(8); 1319 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset); 1320 databuf.appendChar(uninitType.offset); 1321 } 1322 break; 1323 default: 1324 throw new AssertionError(); 1325 } 1326 } 1327 1328 /** An entry in the JSR202 StackMapTable */ 1329 abstract static class StackMapTableFrame { 1330 abstract int getFrameType(); 1331 1332 void write(ClassWriter writer) { 1333 int frameType = getFrameType(); 1334 writer.databuf.appendByte(frameType); 1335 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType); 1336 } 1337 1338 static class SameFrame extends StackMapTableFrame { 1339 final int offsetDelta; 1340 SameFrame(int offsetDelta) { 1341 this.offsetDelta = offsetDelta; 1342 } 1343 int getFrameType() { 1344 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED; 1345 } 1346 @Override 1347 void write(ClassWriter writer) { 1348 super.write(writer); 1349 if (getFrameType() == SAME_FRAME_EXTENDED) { 1350 writer.databuf.appendChar(offsetDelta); 1351 if (writer.debugstackmap){ 1352 System.out.print(" offset_delta=" + offsetDelta); 1353 } 1354 } 1355 } 1356 } 1357 1358 static class SameLocals1StackItemFrame extends StackMapTableFrame { 1359 final int offsetDelta; 1360 final Type stack; 1361 SameLocals1StackItemFrame(int offsetDelta, Type stack) { 1362 this.offsetDelta = offsetDelta; 1363 this.stack = stack; 1364 } 1365 int getFrameType() { 1366 return (offsetDelta < SAME_FRAME_SIZE) ? 1367 (SAME_FRAME_SIZE + offsetDelta) : 1368 SAME_LOCALS_1_STACK_ITEM_EXTENDED; 1369 } 1370 @Override 1371 void write(ClassWriter writer) { 1372 super.write(writer); 1373 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) { 1374 writer.databuf.appendChar(offsetDelta); 1375 if (writer.debugstackmap) { 1376 System.out.print(" offset_delta=" + offsetDelta); 1377 } 1378 } 1379 if (writer.debugstackmap) { 1380 System.out.print(" stack[" + 0 + "]="); 1381 } 1382 writer.writeStackMapType(stack); 1383 } 1384 } 1385 1386 static class ChopFrame extends StackMapTableFrame { 1387 final int frameType; 1388 final int offsetDelta; 1389 ChopFrame(int frameType, int offsetDelta) { 1390 this.frameType = frameType; 1391 this.offsetDelta = offsetDelta; 1392 } 1393 int getFrameType() { return frameType; } 1394 @Override 1395 void write(ClassWriter writer) { 1396 super.write(writer); 1397 writer.databuf.appendChar(offsetDelta); 1398 if (writer.debugstackmap) { 1399 System.out.print(" offset_delta=" + offsetDelta); 1400 } 1401 } 1402 } 1403 1404 static class AppendFrame extends StackMapTableFrame { 1405 final int frameType; 1406 final int offsetDelta; 1407 final Type[] locals; 1408 AppendFrame(int frameType, int offsetDelta, Type[] locals) { 1409 this.frameType = frameType; 1410 this.offsetDelta = offsetDelta; 1411 this.locals = locals; 1412 } 1413 int getFrameType() { return frameType; } 1414 @Override 1415 void write(ClassWriter writer) { 1416 super.write(writer); 1417 writer.databuf.appendChar(offsetDelta); 1418 if (writer.debugstackmap) { 1419 System.out.print(" offset_delta=" + offsetDelta); 1420 } 1421 for (int i=0; i<locals.length; i++) { 1422 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1423 writer.writeStackMapType(locals[i]); 1424 } 1425 } 1426 } 1427 1428 static class FullFrame extends StackMapTableFrame { 1429 final int offsetDelta; 1430 final Type[] locals; 1431 final Type[] stack; 1432 FullFrame(int offsetDelta, Type[] locals, Type[] stack) { 1433 this.offsetDelta = offsetDelta; 1434 this.locals = locals; 1435 this.stack = stack; 1436 } 1437 int getFrameType() { return FULL_FRAME; } 1438 @Override 1439 void write(ClassWriter writer) { 1440 super.write(writer); 1441 writer.databuf.appendChar(offsetDelta); 1442 writer.databuf.appendChar(locals.length); 1443 if (writer.debugstackmap) { 1444 System.out.print(" offset_delta=" + offsetDelta); 1445 System.out.print(" nlocals=" + locals.length); 1446 } 1447 for (int i=0; i<locals.length; i++) { 1448 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1449 writer.writeStackMapType(locals[i]); 1450 } 1451 1452 writer.databuf.appendChar(stack.length); 1453 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); } 1454 for (int i=0; i<stack.length; i++) { 1455 if (writer.debugstackmap) System.out.print(" stack[" + i + "]="); 1456 writer.writeStackMapType(stack[i]); 1457 } 1458 } 1459 } 1460 1461 /** Compare this frame with the previous frame and produce 1462 * an entry of compressed stack map frame. */ 1463 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame, 1464 int prev_pc, 1465 Type[] prev_locals, 1466 Types types) { 1467 Type[] locals = this_frame.locals; 1468 Type[] stack = this_frame.stack; 1469 int offset_delta = this_frame.pc - prev_pc - 1; 1470 if (stack.length == 1) { 1471 if (locals.length == prev_locals.length 1472 && compare(prev_locals, locals, types) == 0) { 1473 return new SameLocals1StackItemFrame(offset_delta, stack[0]); 1474 } 1475 } else if (stack.length == 0) { 1476 int diff_length = compare(prev_locals, locals, types); 1477 if (diff_length == 0) { 1478 return new SameFrame(offset_delta); 1479 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) { 1480 // APPEND 1481 Type[] local_diff = new Type[-diff_length]; 1482 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) { 1483 local_diff[j] = locals[i]; 1484 } 1485 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length, 1486 offset_delta, 1487 local_diff); 1488 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) { 1489 // CHOP 1490 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length, 1491 offset_delta); 1492 } 1493 } 1494 // FULL_FRAME 1495 return new FullFrame(offset_delta, locals, stack); 1496 } 1497 1498 static boolean isInt(Type t) { 1499 return (t.getTag().isStrictSubRangeOf(INT) || t.hasTag(BOOLEAN)); 1500 } 1501 1502 static boolean isSameType(Type t1, Type t2, Types types) { 1503 if (t1 == null) { return t2 == null; } 1504 if (t2 == null) { return false; } 1505 1506 if (isInt(t1) && isInt(t2)) { return true; } 1507 1508 if (t1.hasTag(UNINITIALIZED_THIS)) { 1509 return t2.hasTag(UNINITIALIZED_THIS); 1510 } else if (t1.hasTag(UNINITIALIZED_OBJECT)) { 1511 if (t2.hasTag(UNINITIALIZED_OBJECT)) { 1512 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset; 1513 } else { 1514 return false; 1515 } 1516 } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) { 1517 return false; 1518 } 1519 1520 return types.isSameType(t1, t2); 1521 } 1522 1523 static int compare(Type[] arr1, Type[] arr2, Types types) { 1524 int diff_length = arr1.length - arr2.length; 1525 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) { 1526 return Integer.MAX_VALUE; 1527 } 1528 int len = (diff_length > 0) ? arr2.length : arr1.length; 1529 for (int i=0; i<len; i++) { 1530 if (!isSameType(arr1[i], arr2[i], types)) { 1531 return Integer.MAX_VALUE; 1532 } 1533 } 1534 return diff_length; 1535 } 1536 } 1537 1538 void writeFields(Scope s) { 1539 // process them in reverse sibling order; 1540 // i.e., process them in declaration order. 1541 List<VarSymbol> vars = List.nil(); 1542 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { 1543 if (sym.kind == VAR) vars = vars.prepend((VarSymbol)sym); 1544 } 1545 while (vars.nonEmpty()) { 1546 writeField(vars.head); 1547 vars = vars.tail; 1548 } 1549 } 1550 1551 void writeMethods(Scope s) { 1552 List<MethodSymbol> methods = List.nil(); 1553 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { 1554 if (sym.kind == MTH && (sym.flags() & HYPOTHETICAL) == 0) 1555 methods = methods.prepend((MethodSymbol)sym); 1556 } 1557 while (methods.nonEmpty()) { 1558 writeMethod(methods.head); 1559 methods = methods.tail; 1560 } 1561 } 1562 1563 /** Emit a class file for a given class. 1564 * @param c The class from which a class file is generated. 1565 */ 1566 public JavaFileObject writeClass(ClassSymbol c) 1567 throws IOException, PoolOverflow, StringOverflow 1568 { 1569 JavaFileObject outFile 1570 = fileManager.getJavaFileForOutput(CLASS_OUTPUT, 1571 c.flatname.toString(), 1572 JavaFileObject.Kind.CLASS, 1573 c.sourcefile); 1574 OutputStream out = outFile.openOutputStream(); 1575 try { 1576 writeClassFile(out, c); 1577 if (verbose) 1578 log.printVerbose("wrote.file", outFile); 1579 out.close(); 1580 out = null; 1581 } finally { 1582 if (out != null) { 1583 // if we are propagating an exception, delete the file 1584 out.close(); 1585 outFile.delete(); 1586 outFile = null; 1587 } 1588 } 1589 return outFile; // may be null if write failed 1590 } 1591 1592 /** Write class `c' to outstream `out'. 1593 */ 1594 public void writeClassFile(OutputStream out, ClassSymbol c) 1595 throws IOException, PoolOverflow, StringOverflow { 1596 Assert.check((c.flags() & COMPOUND) == 0); 1597 databuf.reset(); 1598 poolbuf.reset(); 1599 signatureGen.reset(); 1600 pool = c.pool; 1601 innerClasses = null; 1602 innerClassesQueue = null; 1603 bootstrapMethods = new LinkedHashMap<>(); 1604 1605 Type supertype = types.supertype(c.type); 1606 List<Type> interfaces = types.interfaces(c.type); 1607 List<Type> typarams = c.type.getTypeArguments(); 1608 1609 int flags = adjustFlags(c.flags() & ~DEFAULT); 1610 if ((flags & PROTECTED) != 0) flags |= PUBLIC; 1611 flags = flags & ClassFlags & ~STRICTFP; 1612 if ((flags & INTERFACE) == 0) flags |= ACC_SUPER; 1613 if (c.isInner() && c.name.isEmpty()) flags &= ~FINAL; 1614 if (dumpClassModifiers) { 1615 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1616 pw.println(); 1617 pw.println("CLASSFILE " + c.getQualifiedName()); 1618 pw.println("---" + flagNames(flags)); 1619 } 1620 databuf.appendChar(flags); 1621 1622 databuf.appendChar(pool.put(c)); 1623 databuf.appendChar(supertype.hasTag(CLASS) ? pool.put(supertype.tsym) : 0); 1624 databuf.appendChar(interfaces.length()); 1625 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail) 1626 databuf.appendChar(pool.put(l.head.tsym)); 1627 int fieldsCount = 0; 1628 int methodsCount = 0; 1629 for (Symbol sym : c.members().getSymbols(NON_RECURSIVE)) { 1630 switch (sym.kind) { 1631 case VAR: fieldsCount++; break; 1632 case MTH: if ((sym.flags() & HYPOTHETICAL) == 0) methodsCount++; 1633 break; 1634 case TYP: enterInner((ClassSymbol)sym); break; 1635 default : Assert.error(); 1636 } 1637 } 1638 1639 if (c.trans_local != null) { 1640 for (ClassSymbol local : c.trans_local) { 1641 enterInner(local); 1642 } 1643 } 1644 1645 databuf.appendChar(fieldsCount); 1646 writeFields(c.members()); 1647 databuf.appendChar(methodsCount); 1648 writeMethods(c.members()); 1649 1650 int acountIdx = beginAttrs(); 1651 int acount = 0; 1652 1653 boolean sigReq = 1654 typarams.length() != 0 || supertype.allparams().length() != 0; 1655 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail) 1656 sigReq = l.head.allparams().length() != 0; 1657 if (sigReq) { 1658 int alenIdx = writeAttr(names.Signature); 1659 if (typarams.length() != 0) signatureGen.assembleParamsSig(typarams); 1660 signatureGen.assembleSig(supertype); 1661 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail) 1662 signatureGen.assembleSig(l.head); 1663 databuf.appendChar(pool.put(signatureGen.toName())); 1664 signatureGen.reset(); 1665 endAttr(alenIdx); 1666 acount++; 1667 } 1668 1669 if (c.sourcefile != null && emitSourceFile) { 1670 int alenIdx = writeAttr(names.SourceFile); 1671 // WHM 6/29/1999: Strip file path prefix. We do it here at 1672 // the last possible moment because the sourcefile may be used 1673 // elsewhere in error diagnostics. Fixes 4241573. 1674 //databuf.appendChar(c.pool.put(c.sourcefile)); 1675 String simpleName = BaseFileObject.getSimpleName(c.sourcefile); 1676 databuf.appendChar(c.pool.put(names.fromString(simpleName))); 1677 endAttr(alenIdx); 1678 acount++; 1679 } 1680 1681 if (genCrt) { 1682 // Append SourceID attribute 1683 int alenIdx = writeAttr(names.SourceID); 1684 databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile))))); 1685 endAttr(alenIdx); 1686 acount++; 1687 // Append CompilationID attribute 1688 alenIdx = writeAttr(names.CompilationID); 1689 databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis())))); 1690 endAttr(alenIdx); 1691 acount++; 1692 } 1693 1694 acount += writeFlagAttrs(c.flags()); 1695 acount += writeJavaAnnotations(c.getRawAttributes()); 1696 acount += writeTypeAnnotations(c.getRawTypeAttributes(), false); 1697 acount += writeEnclosingMethodAttribute(c); 1698 acount += writeExtraClassAttributes(c); 1699 1700 poolbuf.appendInt(JAVA_MAGIC); 1701 poolbuf.appendChar(target.minorVersion); 1702 poolbuf.appendChar(target.majorVersion); 1703 1704 writePool(c.pool); 1705 1706 if (innerClasses != null) { 1707 writeInnerClasses(); 1708 acount++; 1709 } 1710 1711 if (!bootstrapMethods.isEmpty()) { 1712 writeBootstrapMethods(); 1713 acount++; 1714 } 1715 1716 endAttrs(acountIdx, acount); 1717 1718 poolbuf.appendBytes(databuf.elems, 0, databuf.length); 1719 out.write(poolbuf.elems, 0, poolbuf.length); 1720 1721 pool = c.pool = null; // to conserve space 1722 } 1723 1724 /**Allows subclasses to write additional class attributes 1725 * 1726 * @return the number of attributes written 1727 */ 1728 protected int writeExtraClassAttributes(ClassSymbol c) { 1729 return 0; 1730 } 1731 1732 int adjustFlags(final long flags) { 1733 int result = (int)flags; 1734 1735 if ((flags & BRIDGE) != 0) 1736 result |= ACC_BRIDGE; 1737 if ((flags & VARARGS) != 0) 1738 result |= ACC_VARARGS; 1739 if ((flags & DEFAULT) != 0) 1740 result &= ~ABSTRACT; 1741 return result; 1742 } 1743 1744 long getLastModified(FileObject filename) { 1745 long mod = 0; 1746 try { 1747 mod = filename.getLastModified(); 1748 } catch (SecurityException e) { 1749 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage()); 1750 } 1751 return mod; 1752 } 1753} 1754