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