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