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