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