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 throw new AssertionError("Unexpected intersection type: " + c.type); 1044 } 1045 try { 1046 c.complete(); 1047 } catch (CompletionFailure ex) { 1048 System.err.println("error: " + c + ": " + ex.getMessage()); 1049 throw ex; 1050 } 1051 if (!c.type.hasTag(CLASS)) return; // arrays 1052 if (pool != null && // pool might be null if called from xClassName 1053 c.owner.enclClass() != null && 1054 (innerClasses == null || !innerClasses.contains(c))) { 1055 // log.errWriter.println("enter inner " + c);//DEBUG 1056 enterInner(c.owner.enclClass()); 1057 pool.put(c); 1058 if (c.name != names.empty) 1059 pool.put(c.name); 1060 if (innerClasses == null) { 1061 innerClasses = new HashSet<>(); 1062 innerClassesQueue = new ListBuffer<>(); 1063 pool.put(names.InnerClasses); 1064 } 1065 innerClasses.add(c); 1066 innerClassesQueue.append(c); 1067 } 1068 } 1069 1070 /** Write "inner classes" attribute. 1071 */ 1072 void writeInnerClasses() { 1073 int alenIdx = writeAttr(names.InnerClasses); 1074 databuf.appendChar(innerClassesQueue.length()); 1075 for (List<ClassSymbol> l = innerClassesQueue.toList(); 1076 l.nonEmpty(); 1077 l = l.tail) { 1078 ClassSymbol inner = l.head; 1079 inner.markAbstractIfNeeded(types); 1080 char flags = (char) adjustFlags(inner.flags_field); 1081 if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT 1082 flags &= ~STRICTFP; //inner classes should not have the strictfp flag set. 1083 if (dumpInnerClassModifiers) { 1084 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1085 pw.println("INNERCLASS " + inner.name); 1086 pw.println("---" + flagNames(flags)); 1087 } 1088 databuf.appendChar(pool.get(inner)); 1089 databuf.appendChar( 1090 inner.owner.kind == TYP && !inner.name.isEmpty() ? pool.get(inner.owner) : 0); 1091 databuf.appendChar( 1092 !inner.name.isEmpty() ? pool.get(inner.name) : 0); 1093 databuf.appendChar(flags); 1094 } 1095 endAttr(alenIdx); 1096 } 1097 1098 /** Write "bootstrapMethods" attribute. 1099 */ 1100 void writeBootstrapMethods() { 1101 int alenIdx = writeAttr(names.BootstrapMethods); 1102 databuf.appendChar(bootstrapMethods.size()); 1103 for (Map.Entry<DynamicMethod.BootstrapMethodsKey, DynamicMethod.BootstrapMethodsValue> entry : bootstrapMethods.entrySet()) { 1104 DynamicMethod.BootstrapMethodsKey bsmKey = entry.getKey(); 1105 //write BSM handle 1106 databuf.appendChar(pool.get(entry.getValue().mh)); 1107 Object[] uniqueArgs = bsmKey.getUniqueArgs(); 1108 //write static args length 1109 databuf.appendChar(uniqueArgs.length); 1110 //write static args array 1111 for (Object o : uniqueArgs) { 1112 databuf.appendChar(pool.get(o)); 1113 } 1114 } 1115 endAttr(alenIdx); 1116 } 1117 1118 /** Write field symbol, entering all references into constant pool. 1119 */ 1120 void writeField(VarSymbol v) { 1121 int flags = adjustFlags(v.flags()); 1122 databuf.appendChar(flags); 1123 if (dumpFieldModifiers) { 1124 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1125 pw.println("FIELD " + v.name); 1126 pw.println("---" + flagNames(v.flags())); 1127 } 1128 databuf.appendChar(pool.put(v.name)); 1129 databuf.appendChar(pool.put(typeSig(v.erasure(types)))); 1130 int acountIdx = beginAttrs(); 1131 int acount = 0; 1132 if (v.getConstValue() != null) { 1133 int alenIdx = writeAttr(names.ConstantValue); 1134 databuf.appendChar(pool.put(v.getConstValue())); 1135 endAttr(alenIdx); 1136 acount++; 1137 } 1138 acount += writeMemberAttrs(v); 1139 endAttrs(acountIdx, acount); 1140 } 1141 1142 /** Write method symbol, entering all references into constant pool. 1143 */ 1144 void writeMethod(MethodSymbol m) { 1145 int flags = adjustFlags(m.flags()); 1146 databuf.appendChar(flags); 1147 if (dumpMethodModifiers) { 1148 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1149 pw.println("METHOD " + m.name); 1150 pw.println("---" + flagNames(m.flags())); 1151 } 1152 databuf.appendChar(pool.put(m.name)); 1153 databuf.appendChar(pool.put(typeSig(m.externalType(types)))); 1154 int acountIdx = beginAttrs(); 1155 int acount = 0; 1156 if (m.code != null) { 1157 int alenIdx = writeAttr(names.Code); 1158 writeCode(m.code); 1159 m.code = null; // to conserve space 1160 endAttr(alenIdx); 1161 acount++; 1162 } 1163 List<Type> thrown = m.erasure(types).getThrownTypes(); 1164 if (thrown.nonEmpty()) { 1165 int alenIdx = writeAttr(names.Exceptions); 1166 databuf.appendChar(thrown.length()); 1167 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) 1168 databuf.appendChar(pool.put(l.head.tsym)); 1169 endAttr(alenIdx); 1170 acount++; 1171 } 1172 if (m.defaultValue != null) { 1173 int alenIdx = writeAttr(names.AnnotationDefault); 1174 m.defaultValue.accept(awriter); 1175 endAttr(alenIdx); 1176 acount++; 1177 } 1178 if (options.isSet(PARAMETERS) && target.hasMethodParameters()) { 1179 if (!m.isLambdaMethod()) // Per JDK-8138729, do not emit parameters table for lambda bodies. 1180 acount += writeMethodParametersAttr(m); 1181 } 1182 acount += writeMemberAttrs(m); 1183 if (!m.isLambdaMethod()) 1184 acount += writeParameterAttrs(m); 1185 endAttrs(acountIdx, acount); 1186 } 1187 1188 /** Write code attribute of method. 1189 */ 1190 void writeCode(Code code) { 1191 databuf.appendChar(code.max_stack); 1192 databuf.appendChar(code.max_locals); 1193 databuf.appendInt(code.cp); 1194 databuf.appendBytes(code.code, 0, code.cp); 1195 databuf.appendChar(code.catchInfo.length()); 1196 for (List<char[]> l = code.catchInfo.toList(); 1197 l.nonEmpty(); 1198 l = l.tail) { 1199 for (int i = 0; i < l.head.length; i++) 1200 databuf.appendChar(l.head[i]); 1201 } 1202 int acountIdx = beginAttrs(); 1203 int acount = 0; 1204 1205 if (code.lineInfo.nonEmpty()) { 1206 int alenIdx = writeAttr(names.LineNumberTable); 1207 databuf.appendChar(code.lineInfo.length()); 1208 for (List<char[]> l = code.lineInfo.reverse(); 1209 l.nonEmpty(); 1210 l = l.tail) 1211 for (int i = 0; i < l.head.length; i++) 1212 databuf.appendChar(l.head[i]); 1213 endAttr(alenIdx); 1214 acount++; 1215 } 1216 1217 if (genCrt && (code.crt != null)) { 1218 CRTable crt = code.crt; 1219 int alenIdx = writeAttr(names.CharacterRangeTable); 1220 int crtIdx = beginAttrs(); 1221 int crtEntries = crt.writeCRT(databuf, code.lineMap, log); 1222 endAttrs(crtIdx, crtEntries); 1223 endAttr(alenIdx); 1224 acount++; 1225 } 1226 1227 // counter for number of generic local variables 1228 if (code.varDebugInfo && code.varBufferSize > 0) { 1229 int nGenericVars = 0; 1230 int alenIdx = writeAttr(names.LocalVariableTable); 1231 databuf.appendChar(code.getLVTSize()); 1232 for (int i=0; i<code.varBufferSize; i++) { 1233 Code.LocalVar var = code.varBuffer[i]; 1234 1235 for (Code.LocalVar.Range r: var.aliveRanges) { 1236 // write variable info 1237 Assert.check(r.start_pc >= 0 1238 && r.start_pc <= code.cp); 1239 databuf.appendChar(r.start_pc); 1240 Assert.check(r.length > 0 1241 && (r.start_pc + r.length) <= code.cp); 1242 databuf.appendChar(r.length); 1243 VarSymbol sym = var.sym; 1244 databuf.appendChar(pool.put(sym.name)); 1245 Type vartype = sym.erasure(types); 1246 databuf.appendChar(pool.put(typeSig(vartype))); 1247 databuf.appendChar(var.reg); 1248 if (needsLocalVariableTypeEntry(var.sym.type)) { 1249 nGenericVars++; 1250 } 1251 } 1252 } 1253 endAttr(alenIdx); 1254 acount++; 1255 1256 if (nGenericVars > 0) { 1257 alenIdx = writeAttr(names.LocalVariableTypeTable); 1258 databuf.appendChar(nGenericVars); 1259 int count = 0; 1260 1261 for (int i=0; i<code.varBufferSize; i++) { 1262 Code.LocalVar var = code.varBuffer[i]; 1263 VarSymbol sym = var.sym; 1264 if (!needsLocalVariableTypeEntry(sym.type)) 1265 continue; 1266 for (Code.LocalVar.Range r : var.aliveRanges) { 1267 // write variable info 1268 databuf.appendChar(r.start_pc); 1269 databuf.appendChar(r.length); 1270 databuf.appendChar(pool.put(sym.name)); 1271 databuf.appendChar(pool.put(typeSig(sym.type))); 1272 databuf.appendChar(var.reg); 1273 count++; 1274 } 1275 } 1276 Assert.check(count == nGenericVars); 1277 endAttr(alenIdx); 1278 acount++; 1279 } 1280 } 1281 1282 if (code.stackMapBufferSize > 0) { 1283 if (debugstackmap) System.out.println("Stack map for " + code.meth); 1284 int alenIdx = writeAttr(code.stackMap.getAttributeName(names)); 1285 writeStackMap(code); 1286 endAttr(alenIdx); 1287 acount++; 1288 } 1289 1290 acount += writeTypeAnnotations(code.meth.getRawTypeAttributes(), true); 1291 1292 endAttrs(acountIdx, acount); 1293 } 1294 //where 1295 private boolean needsLocalVariableTypeEntry(Type t) { 1296 //a local variable needs a type-entry if its type T is generic 1297 //(i.e. |T| != T) and if it's not an intersection type (not supported 1298 //in signature attribute grammar) 1299 return (!types.isSameType(t, types.erasure(t)) && 1300 !t.isCompound()); 1301 } 1302 1303 void writeStackMap(Code code) { 1304 int nframes = code.stackMapBufferSize; 1305 if (debugstackmap) System.out.println(" nframes = " + nframes); 1306 databuf.appendChar(nframes); 1307 1308 switch (code.stackMap) { 1309 case CLDC: 1310 for (int i=0; i<nframes; i++) { 1311 if (debugstackmap) System.out.print(" " + i + ":"); 1312 Code.StackMapFrame frame = code.stackMapBuffer[i]; 1313 1314 // output PC 1315 if (debugstackmap) System.out.print(" pc=" + frame.pc); 1316 databuf.appendChar(frame.pc); 1317 1318 // output locals 1319 int localCount = 0; 1320 for (int j=0; j<frame.locals.length; 1321 j += Code.width(frame.locals[j])) { 1322 localCount++; 1323 } 1324 if (debugstackmap) System.out.print(" nlocals=" + 1325 localCount); 1326 databuf.appendChar(localCount); 1327 for (int j=0; j<frame.locals.length; 1328 j += Code.width(frame.locals[j])) { 1329 if (debugstackmap) System.out.print(" local[" + j + "]="); 1330 writeStackMapType(frame.locals[j]); 1331 } 1332 1333 // output stack 1334 int stackCount = 0; 1335 for (int j=0; j<frame.stack.length; 1336 j += Code.width(frame.stack[j])) { 1337 stackCount++; 1338 } 1339 if (debugstackmap) System.out.print(" nstack=" + 1340 stackCount); 1341 databuf.appendChar(stackCount); 1342 for (int j=0; j<frame.stack.length; 1343 j += Code.width(frame.stack[j])) { 1344 if (debugstackmap) System.out.print(" stack[" + j + "]="); 1345 writeStackMapType(frame.stack[j]); 1346 } 1347 if (debugstackmap) System.out.println(); 1348 } 1349 break; 1350 case JSR202: { 1351 Assert.checkNull(code.stackMapBuffer); 1352 for (int i=0; i<nframes; i++) { 1353 if (debugstackmap) System.out.print(" " + i + ":"); 1354 StackMapTableFrame frame = code.stackMapTableBuffer[i]; 1355 frame.write(this); 1356 if (debugstackmap) System.out.println(); 1357 } 1358 break; 1359 } 1360 default: 1361 throw new AssertionError("Unexpected stackmap format value"); 1362 } 1363 } 1364 1365 //where 1366 void writeStackMapType(Type t) { 1367 if (t == null) { 1368 if (debugstackmap) System.out.print("empty"); 1369 databuf.appendByte(0); 1370 } 1371 else switch(t.getTag()) { 1372 case BYTE: 1373 case CHAR: 1374 case SHORT: 1375 case INT: 1376 case BOOLEAN: 1377 if (debugstackmap) System.out.print("int"); 1378 databuf.appendByte(1); 1379 break; 1380 case FLOAT: 1381 if (debugstackmap) System.out.print("float"); 1382 databuf.appendByte(2); 1383 break; 1384 case DOUBLE: 1385 if (debugstackmap) System.out.print("double"); 1386 databuf.appendByte(3); 1387 break; 1388 case LONG: 1389 if (debugstackmap) System.out.print("long"); 1390 databuf.appendByte(4); 1391 break; 1392 case BOT: // null 1393 if (debugstackmap) System.out.print("null"); 1394 databuf.appendByte(5); 1395 break; 1396 case CLASS: 1397 case ARRAY: 1398 if (debugstackmap) System.out.print("object(" + t + ")"); 1399 databuf.appendByte(7); 1400 databuf.appendChar(pool.put(t)); 1401 break; 1402 case TYPEVAR: 1403 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")"); 1404 databuf.appendByte(7); 1405 databuf.appendChar(pool.put(types.erasure(t).tsym)); 1406 break; 1407 case UNINITIALIZED_THIS: 1408 if (debugstackmap) System.out.print("uninit_this"); 1409 databuf.appendByte(6); 1410 break; 1411 case UNINITIALIZED_OBJECT: 1412 { UninitializedType uninitType = (UninitializedType)t; 1413 databuf.appendByte(8); 1414 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset); 1415 databuf.appendChar(uninitType.offset); 1416 } 1417 break; 1418 default: 1419 throw new AssertionError(); 1420 } 1421 } 1422 1423 /** An entry in the JSR202 StackMapTable */ 1424 abstract static class StackMapTableFrame { 1425 abstract int getFrameType(); 1426 1427 void write(ClassWriter writer) { 1428 int frameType = getFrameType(); 1429 writer.databuf.appendByte(frameType); 1430 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType); 1431 } 1432 1433 static class SameFrame extends StackMapTableFrame { 1434 final int offsetDelta; 1435 SameFrame(int offsetDelta) { 1436 this.offsetDelta = offsetDelta; 1437 } 1438 int getFrameType() { 1439 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED; 1440 } 1441 @Override 1442 void write(ClassWriter writer) { 1443 super.write(writer); 1444 if (getFrameType() == SAME_FRAME_EXTENDED) { 1445 writer.databuf.appendChar(offsetDelta); 1446 if (writer.debugstackmap){ 1447 System.out.print(" offset_delta=" + offsetDelta); 1448 } 1449 } 1450 } 1451 } 1452 1453 static class SameLocals1StackItemFrame extends StackMapTableFrame { 1454 final int offsetDelta; 1455 final Type stack; 1456 SameLocals1StackItemFrame(int offsetDelta, Type stack) { 1457 this.offsetDelta = offsetDelta; 1458 this.stack = stack; 1459 } 1460 int getFrameType() { 1461 return (offsetDelta < SAME_FRAME_SIZE) ? 1462 (SAME_FRAME_SIZE + offsetDelta) : 1463 SAME_LOCALS_1_STACK_ITEM_EXTENDED; 1464 } 1465 @Override 1466 void write(ClassWriter writer) { 1467 super.write(writer); 1468 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) { 1469 writer.databuf.appendChar(offsetDelta); 1470 if (writer.debugstackmap) { 1471 System.out.print(" offset_delta=" + offsetDelta); 1472 } 1473 } 1474 if (writer.debugstackmap) { 1475 System.out.print(" stack[" + 0 + "]="); 1476 } 1477 writer.writeStackMapType(stack); 1478 } 1479 } 1480 1481 static class ChopFrame extends StackMapTableFrame { 1482 final int frameType; 1483 final int offsetDelta; 1484 ChopFrame(int frameType, int offsetDelta) { 1485 this.frameType = frameType; 1486 this.offsetDelta = offsetDelta; 1487 } 1488 int getFrameType() { return frameType; } 1489 @Override 1490 void write(ClassWriter writer) { 1491 super.write(writer); 1492 writer.databuf.appendChar(offsetDelta); 1493 if (writer.debugstackmap) { 1494 System.out.print(" offset_delta=" + offsetDelta); 1495 } 1496 } 1497 } 1498 1499 static class AppendFrame extends StackMapTableFrame { 1500 final int frameType; 1501 final int offsetDelta; 1502 final Type[] locals; 1503 AppendFrame(int frameType, int offsetDelta, Type[] locals) { 1504 this.frameType = frameType; 1505 this.offsetDelta = offsetDelta; 1506 this.locals = locals; 1507 } 1508 int getFrameType() { return frameType; } 1509 @Override 1510 void write(ClassWriter writer) { 1511 super.write(writer); 1512 writer.databuf.appendChar(offsetDelta); 1513 if (writer.debugstackmap) { 1514 System.out.print(" offset_delta=" + offsetDelta); 1515 } 1516 for (int i=0; i<locals.length; i++) { 1517 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1518 writer.writeStackMapType(locals[i]); 1519 } 1520 } 1521 } 1522 1523 static class FullFrame extends StackMapTableFrame { 1524 final int offsetDelta; 1525 final Type[] locals; 1526 final Type[] stack; 1527 FullFrame(int offsetDelta, Type[] locals, Type[] stack) { 1528 this.offsetDelta = offsetDelta; 1529 this.locals = locals; 1530 this.stack = stack; 1531 } 1532 int getFrameType() { return FULL_FRAME; } 1533 @Override 1534 void write(ClassWriter writer) { 1535 super.write(writer); 1536 writer.databuf.appendChar(offsetDelta); 1537 writer.databuf.appendChar(locals.length); 1538 if (writer.debugstackmap) { 1539 System.out.print(" offset_delta=" + offsetDelta); 1540 System.out.print(" nlocals=" + locals.length); 1541 } 1542 for (int i=0; i<locals.length; i++) { 1543 if (writer.debugstackmap) System.out.print(" locals[" + i + "]="); 1544 writer.writeStackMapType(locals[i]); 1545 } 1546 1547 writer.databuf.appendChar(stack.length); 1548 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); } 1549 for (int i=0; i<stack.length; i++) { 1550 if (writer.debugstackmap) System.out.print(" stack[" + i + "]="); 1551 writer.writeStackMapType(stack[i]); 1552 } 1553 } 1554 } 1555 1556 /** Compare this frame with the previous frame and produce 1557 * an entry of compressed stack map frame. */ 1558 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame, 1559 int prev_pc, 1560 Type[] prev_locals, 1561 Types types) { 1562 Type[] locals = this_frame.locals; 1563 Type[] stack = this_frame.stack; 1564 int offset_delta = this_frame.pc - prev_pc - 1; 1565 if (stack.length == 1) { 1566 if (locals.length == prev_locals.length 1567 && compare(prev_locals, locals, types) == 0) { 1568 return new SameLocals1StackItemFrame(offset_delta, stack[0]); 1569 } 1570 } else if (stack.length == 0) { 1571 int diff_length = compare(prev_locals, locals, types); 1572 if (diff_length == 0) { 1573 return new SameFrame(offset_delta); 1574 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) { 1575 // APPEND 1576 Type[] local_diff = new Type[-diff_length]; 1577 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) { 1578 local_diff[j] = locals[i]; 1579 } 1580 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length, 1581 offset_delta, 1582 local_diff); 1583 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) { 1584 // CHOP 1585 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length, 1586 offset_delta); 1587 } 1588 } 1589 // FULL_FRAME 1590 return new FullFrame(offset_delta, locals, stack); 1591 } 1592 1593 static boolean isInt(Type t) { 1594 return (t.getTag().isStrictSubRangeOf(INT) || t.hasTag(BOOLEAN)); 1595 } 1596 1597 static boolean isSameType(Type t1, Type t2, Types types) { 1598 if (t1 == null) { return t2 == null; } 1599 if (t2 == null) { return false; } 1600 1601 if (isInt(t1) && isInt(t2)) { return true; } 1602 1603 if (t1.hasTag(UNINITIALIZED_THIS)) { 1604 return t2.hasTag(UNINITIALIZED_THIS); 1605 } else if (t1.hasTag(UNINITIALIZED_OBJECT)) { 1606 if (t2.hasTag(UNINITIALIZED_OBJECT)) { 1607 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset; 1608 } else { 1609 return false; 1610 } 1611 } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) { 1612 return false; 1613 } 1614 1615 return types.isSameType(t1, t2); 1616 } 1617 1618 static int compare(Type[] arr1, Type[] arr2, Types types) { 1619 int diff_length = arr1.length - arr2.length; 1620 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) { 1621 return Integer.MAX_VALUE; 1622 } 1623 int len = (diff_length > 0) ? arr2.length : arr1.length; 1624 for (int i=0; i<len; i++) { 1625 if (!isSameType(arr1[i], arr2[i], types)) { 1626 return Integer.MAX_VALUE; 1627 } 1628 } 1629 return diff_length; 1630 } 1631 } 1632 1633 void writeFields(Scope s) { 1634 // process them in reverse sibling order; 1635 // i.e., process them in declaration order. 1636 List<VarSymbol> vars = List.nil(); 1637 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { 1638 if (sym.kind == VAR) vars = vars.prepend((VarSymbol)sym); 1639 } 1640 while (vars.nonEmpty()) { 1641 writeField(vars.head); 1642 vars = vars.tail; 1643 } 1644 } 1645 1646 void writeMethods(Scope s) { 1647 List<MethodSymbol> methods = List.nil(); 1648 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) { 1649 if (sym.kind == MTH && (sym.flags() & HYPOTHETICAL) == 0) 1650 methods = methods.prepend((MethodSymbol)sym); 1651 } 1652 while (methods.nonEmpty()) { 1653 writeMethod(methods.head); 1654 methods = methods.tail; 1655 } 1656 } 1657 1658 /** Emit a class file for a given class. 1659 * @param c The class from which a class file is generated. 1660 */ 1661 public JavaFileObject writeClass(ClassSymbol c) 1662 throws IOException, PoolOverflow, StringOverflow 1663 { 1664 String name = (c.owner.kind == MDL ? c.name : c.flatname).toString(); 1665 Location outLocn; 1666 if (multiModuleMode) { 1667 ModuleSymbol msym = c.owner.kind == MDL ? (ModuleSymbol) c.owner : c.packge().modle; 1668 outLocn = fileManager.getLocationForModule(CLASS_OUTPUT, msym.name.toString()); 1669 } else { 1670 outLocn = CLASS_OUTPUT; 1671 } 1672 JavaFileObject outFile 1673 = fileManager.getJavaFileForOutput(outLocn, 1674 name, 1675 JavaFileObject.Kind.CLASS, 1676 c.sourcefile); 1677 OutputStream out = outFile.openOutputStream(); 1678 try { 1679 writeClassFile(out, c); 1680 if (verbose) 1681 log.printVerbose("wrote.file", outFile.getName()); 1682 out.close(); 1683 out = null; 1684 } finally { 1685 if (out != null) { 1686 // if we are propagating an exception, delete the file 1687 out.close(); 1688 outFile.delete(); 1689 outFile = null; 1690 } 1691 } 1692 return outFile; // may be null if write failed 1693 } 1694 1695 /** Write class `c' to outstream `out'. 1696 */ 1697 public void writeClassFile(OutputStream out, ClassSymbol c) 1698 throws IOException, PoolOverflow, StringOverflow { 1699 Assert.check((c.flags() & COMPOUND) == 0); 1700 databuf.reset(); 1701 poolbuf.reset(); 1702 signatureGen.reset(); 1703 pool = c.pool; 1704 innerClasses = null; 1705 innerClassesQueue = null; 1706 bootstrapMethods = new LinkedHashMap<>(); 1707 1708 Type supertype = types.supertype(c.type); 1709 List<Type> interfaces = types.interfaces(c.type); 1710 List<Type> typarams = c.type.getTypeArguments(); 1711 1712 int flags; 1713 if (c.owner.kind == MDL) { 1714 flags = ACC_MODULE; 1715 } else { 1716 flags = adjustFlags(c.flags() & ~DEFAULT); 1717 if ((flags & PROTECTED) != 0) flags |= PUBLIC; 1718 flags = flags & ClassFlags & ~STRICTFP; 1719 if ((flags & INTERFACE) == 0) flags |= ACC_SUPER; 1720 } 1721 1722 if (dumpClassModifiers) { 1723 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR); 1724 pw.println(); 1725 pw.println("CLASSFILE " + c.getQualifiedName()); 1726 pw.println("---" + flagNames(flags)); 1727 } 1728 databuf.appendChar(flags); 1729 1730 if (c.owner.kind == MDL) { 1731 PackageSymbol unnamed = ((ModuleSymbol) c.owner).unnamedPackage; 1732 databuf.appendChar(pool.put(new ClassSymbol(0, names.module_info, unnamed))); 1733 } else { 1734 databuf.appendChar(pool.put(c)); 1735 } 1736 databuf.appendChar(supertype.hasTag(CLASS) ? pool.put(supertype.tsym) : 0); 1737 databuf.appendChar(interfaces.length()); 1738 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail) 1739 databuf.appendChar(pool.put(l.head.tsym)); 1740 int fieldsCount = 0; 1741 int methodsCount = 0; 1742 for (Symbol sym : c.members().getSymbols(NON_RECURSIVE)) { 1743 switch (sym.kind) { 1744 case VAR: fieldsCount++; break; 1745 case MTH: if ((sym.flags() & HYPOTHETICAL) == 0) methodsCount++; 1746 break; 1747 case TYP: enterInner((ClassSymbol)sym); break; 1748 default : Assert.error(); 1749 } 1750 } 1751 1752 if (c.trans_local != null) { 1753 for (ClassSymbol local : c.trans_local) { 1754 enterInner(local); 1755 } 1756 } 1757 1758 databuf.appendChar(fieldsCount); 1759 writeFields(c.members()); 1760 databuf.appendChar(methodsCount); 1761 writeMethods(c.members()); 1762 1763 int acountIdx = beginAttrs(); 1764 int acount = 0; 1765 1766 boolean sigReq = 1767 typarams.length() != 0 || supertype.allparams().length() != 0; 1768 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail) 1769 sigReq = l.head.allparams().length() != 0; 1770 if (sigReq) { 1771 int alenIdx = writeAttr(names.Signature); 1772 if (typarams.length() != 0) signatureGen.assembleParamsSig(typarams); 1773 signatureGen.assembleSig(supertype); 1774 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail) 1775 signatureGen.assembleSig(l.head); 1776 databuf.appendChar(pool.put(signatureGen.toName())); 1777 signatureGen.reset(); 1778 endAttr(alenIdx); 1779 acount++; 1780 } 1781 1782 if (c.sourcefile != null && emitSourceFile) { 1783 int alenIdx = writeAttr(names.SourceFile); 1784 // WHM 6/29/1999: Strip file path prefix. We do it here at 1785 // the last possible moment because the sourcefile may be used 1786 // elsewhere in error diagnostics. Fixes 4241573. 1787 //databuf.appendChar(c.pool.put(c.sourcefile)); 1788 String simpleName = PathFileObject.getSimpleName(c.sourcefile); 1789 databuf.appendChar(c.pool.put(names.fromString(simpleName))); 1790 endAttr(alenIdx); 1791 acount++; 1792 } 1793 1794 if (genCrt) { 1795 // Append SourceID attribute 1796 int alenIdx = writeAttr(names.SourceID); 1797 databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile))))); 1798 endAttr(alenIdx); 1799 acount++; 1800 // Append CompilationID attribute 1801 alenIdx = writeAttr(names.CompilationID); 1802 databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis())))); 1803 endAttr(alenIdx); 1804 acount++; 1805 } 1806 1807 acount += writeFlagAttrs(c.flags()); 1808 acount += writeJavaAnnotations(c.getRawAttributes()); 1809 acount += writeTypeAnnotations(c.getRawTypeAttributes(), false); 1810 acount += writeEnclosingMethodAttribute(c); 1811 if (c.owner.kind == MDL) { 1812 acount += writeModuleAttribute(c); 1813 acount += writeFlagAttrs(c.owner.flags() & ~DEPRECATED); 1814 } 1815 acount += writeExtraClassAttributes(c); 1816 1817 poolbuf.appendInt(JAVA_MAGIC); 1818 poolbuf.appendChar(target.minorVersion); 1819 poolbuf.appendChar(target.majorVersion); 1820 1821 writePool(c.pool); 1822 1823 if (innerClasses != null) { 1824 writeInnerClasses(); 1825 acount++; 1826 } 1827 1828 if (!bootstrapMethods.isEmpty()) { 1829 writeBootstrapMethods(); 1830 acount++; 1831 } 1832 1833 endAttrs(acountIdx, acount); 1834 1835 poolbuf.appendBytes(databuf.elems, 0, databuf.length); 1836 out.write(poolbuf.elems, 0, poolbuf.length); 1837 1838 pool = c.pool = null; // to conserve space 1839 } 1840 1841 /**Allows subclasses to write additional class attributes 1842 * 1843 * @return the number of attributes written 1844 */ 1845 protected int writeExtraClassAttributes(ClassSymbol c) { 1846 return 0; 1847 } 1848 1849 int adjustFlags(final long flags) { 1850 int result = (int)flags; 1851 1852 if ((flags & BRIDGE) != 0) 1853 result |= ACC_BRIDGE; 1854 if ((flags & VARARGS) != 0) 1855 result |= ACC_VARARGS; 1856 if ((flags & DEFAULT) != 0) 1857 result &= ~ABSTRACT; 1858 return result; 1859 } 1860 1861 long getLastModified(FileObject filename) { 1862 long mod = 0; 1863 try { 1864 mod = filename.getLastModified(); 1865 } catch (SecurityException e) { 1866 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage()); 1867 } 1868 return mod; 1869 } 1870 }