src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java

Fri, 18 Jun 2010 15:12:04 -0700

author
jrose
date
Fri, 18 Jun 2010 15:12:04 -0700
changeset 573
005bec70ca27
parent 554
9d9f26857129
parent 571
f0e3ec1f9d9f
child 591
d1d7595fa824
permissions
-rw-r--r--

Merge

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

mercurial