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