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