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