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