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