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