ClassWriter.java revision 3793:5a2b9f22ba5d
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;
33import java.util.LinkedHashSet;
34
35import javax.tools.JavaFileManager;
36import javax.tools.FileObject;
37import javax.tools.JavaFileManager.Location;
38import javax.tools.JavaFileObject;
39
40import com.sun.tools.javac.code.*;
41import com.sun.tools.javac.code.Attribute.RetentionPolicy;
42import com.sun.tools.javac.code.Directive.*;
43import com.sun.tools.javac.code.Symbol.*;
44import com.sun.tools.javac.code.Type.*;
45import com.sun.tools.javac.code.Types.UniqueType;
46import com.sun.tools.javac.file.PathFileObject;
47import com.sun.tools.javac.jvm.Pool.DynamicMethod;
48import com.sun.tools.javac.jvm.Pool.Method;
49import com.sun.tools.javac.jvm.Pool.MethodHandle;
50import com.sun.tools.javac.jvm.Pool.Variable;
51import com.sun.tools.javac.main.Option;
52import com.sun.tools.javac.util.*;
53
54import static com.sun.tools.javac.code.Flags.*;
55import static com.sun.tools.javac.code.Kinds.Kind.*;
56import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
57import static com.sun.tools.javac.code.TypeTag.*;
58import static com.sun.tools.javac.main.Option.*;
59
60import static javax.tools.StandardLocation.CLASS_OUTPUT;
61
62/** This class provides operations to map an internal symbol table graph
63 *  rooted in a ClassSymbol into a classfile.
64 *
65 *  <p><b>This is NOT part of any supported API.
66 *  If you write code that depends on this, you do so at your own risk.
67 *  This code and its internal interfaces are subject to change or
68 *  deletion without notice.</b>
69 */
70public class ClassWriter extends ClassFile {
71    protected static final Context.Key<ClassWriter> classWriterKey = new Context.Key<>();
72
73    private final Options options;
74
75    /** Switch: verbose output.
76     */
77    private boolean verbose;
78
79    /** Switch: emit source file attribute.
80     */
81    private boolean emitSourceFile;
82
83    /** Switch: generate CharacterRangeTable attribute.
84     */
85    private boolean genCrt;
86
87    /** Switch: describe the generated stackmap.
88     */
89    private boolean debugstackmap;
90
91    /**
92     * Target class version.
93     */
94    private Target target;
95
96    /**
97     * Source language version.
98     */
99    private Source source;
100
101    /** Type utilities. */
102    private Types types;
103
104    /**
105     * If true, class files will be written in module-specific subdirectories
106     * of the CLASS_OUTPUT location.
107     */
108    public boolean multiModuleMode;
109
110    /** The initial sizes of the data and constant pool buffers.
111     *  Sizes are increased when buffers get full.
112     */
113    static final int DATA_BUF_SIZE = 0x0fff0;
114    static final int POOL_BUF_SIZE = 0x1fff0;
115
116    /** An output buffer for member info.
117     */
118    ByteBuffer databuf = new ByteBuffer(DATA_BUF_SIZE);
119
120    /** An output buffer for the constant pool.
121     */
122    ByteBuffer poolbuf = new ByteBuffer(POOL_BUF_SIZE);
123
124    /** The constant pool.
125     */
126    Pool pool;
127
128    /** The inner classes to be written, as a set.
129     */
130    Set<ClassSymbol> innerClasses;
131
132    /** The inner classes to be written, as a queue where
133     *  enclosing classes come first.
134     */
135    ListBuffer<ClassSymbol> innerClassesQueue;
136
137    /** The bootstrap methods to be written in the corresponding class attribute
138     *  (one for each invokedynamic)
139     */
140    Map<DynamicMethod.BootstrapMethodsKey, DynamicMethod.BootstrapMethodsValue> bootstrapMethods;
141
142    /** The log to use for verbose output.
143     */
144    private final Log log;
145
146    /** The name table. */
147    private final Names names;
148
149    /** Access to files. */
150    private final JavaFileManager fileManager;
151
152    /** Sole signature generator */
153    private final CWSignatureGenerator signatureGen;
154
155    /** The tags and constants used in compressed stackmap. */
156    static final int SAME_FRAME_SIZE = 64;
157    static final int SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247;
158    static final int SAME_FRAME_EXTENDED = 251;
159    static final int FULL_FRAME = 255;
160    static final int MAX_LOCAL_LENGTH_DIFF = 4;
161
162    /** Get the ClassWriter instance for this context. */
163    public static ClassWriter instance(Context context) {
164        ClassWriter instance = context.get(classWriterKey);
165        if (instance == null)
166            instance = new ClassWriter(context);
167        return instance;
168    }
169
170    /** Construct a class writer, given an options table.
171     */
172    protected ClassWriter(Context context) {
173        context.put(classWriterKey, this);
174
175        log = Log.instance(context);
176        names = Names.instance(context);
177        options = Options.instance(context);
178        target = Target.instance(context);
179        source = Source.instance(context);
180        types = Types.instance(context);
181        fileManager = context.get(JavaFileManager.class);
182        signatureGen = new CWSignatureGenerator(types);
183
184        verbose        = options.isSet(VERBOSE);
185        genCrt         = options.isSet(XJCOV);
186        debugstackmap = options.isSet("debug.stackmap");
187
188        emitSourceFile = options.isUnset(G_CUSTOM) ||
189                            options.isSet(G_CUSTOM, "source");
190
191        String modifierFlags = options.get("debug.dumpmodifiers");
192        if (modifierFlags != null) {
193            dumpClassModifiers = modifierFlags.indexOf('c') != -1;
194            dumpFieldModifiers = modifierFlags.indexOf('f') != -1;
195            dumpInnerClassModifiers = modifierFlags.indexOf('i') != -1;
196            dumpMethodModifiers = modifierFlags.indexOf('m') != -1;
197        }
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 boolean dumpClassModifiers; // -XDdumpmodifiers=c
214    private boolean dumpFieldModifiers; // -XDdumpmodifiers=f
215    private boolean dumpInnerClassModifiers; // -XDdumpmodifiers=i
216    private 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(types.erasure(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
957        databuf.appendChar(pool.put(names.fromUtf(externalize(m.name))));
958        databuf.appendChar(ModuleFlags.value(m.flags)); // module_flags
959
960        ListBuffer<RequiresDirective> requires = new ListBuffer<>();
961        for (RequiresDirective r: m.requires) {
962            if (!r.flags.contains(RequiresFlag.EXTRA))
963                requires.add(r);
964        }
965        databuf.appendChar(requires.size());
966        for (RequiresDirective r: requires) {
967            databuf.appendChar(pool.put(names.fromUtf(externalize(r.module.name))));
968            databuf.appendChar(RequiresFlag.value(r.flags));
969        }
970
971        List<ExportsDirective> exports = m.exports;
972        databuf.appendChar(exports.size());
973        for (ExportsDirective e: exports) {
974            databuf.appendChar(pool.put(names.fromUtf(externalize(e.packge.flatName()))));
975            databuf.appendChar(ExportsFlag.value(e.flags));
976            if (e.modules == null) {
977                databuf.appendChar(0);
978            } else {
979                databuf.appendChar(e.modules.size());
980                for (ModuleSymbol msym: e.modules) {
981                    databuf.appendChar(pool.put(names.fromUtf(externalize(msym.name))));
982                }
983            }
984        }
985
986        List<OpensDirective> opens = m.opens;
987        databuf.appendChar(opens.size());
988        for (OpensDirective o: opens) {
989            databuf.appendChar(pool.put(names.fromUtf(externalize(o.packge.flatName()))));
990            databuf.appendChar(OpensFlag.value(o.flags));
991            if (o.modules == null) {
992                databuf.appendChar(0);
993            } else {
994                databuf.appendChar(o.modules.size());
995                for (ModuleSymbol msym: o.modules) {
996                    databuf.appendChar(pool.put(names.fromUtf(externalize(msym.name))));
997                }
998            }
999        }
1000
1001        List<UsesDirective> uses = m.uses;
1002        databuf.appendChar(uses.size());
1003        for (UsesDirective s: uses) {
1004            databuf.appendChar(pool.put(s.service));
1005        }
1006
1007        // temporary fix to merge repeated provides clause for same service;
1008        // eventually this should be disallowed when analyzing the module,
1009        // so that each service type only appears once.
1010        Map<ClassSymbol, Set<ClassSymbol>> mergedProvides = new LinkedHashMap<>();
1011        for (ProvidesDirective p : m.provides) {
1012            mergedProvides.computeIfAbsent(p.service, s -> new LinkedHashSet<>()).addAll(p.impls);
1013        }
1014        databuf.appendChar(mergedProvides.size());
1015        mergedProvides.forEach((srvc, impls) -> {
1016            databuf.appendChar(pool.put(srvc));
1017            databuf.appendChar(impls.size());
1018            impls.forEach(impl -> databuf.appendChar(pool.put(impl)));
1019        });
1020
1021        endAttr(alenIdx);
1022        return 1;
1023    }
1024
1025/**********************************************************************
1026 * Writing Objects
1027 **********************************************************************/
1028
1029    /** Enter an inner class into the `innerClasses' set/queue.
1030     */
1031    void enterInner(ClassSymbol c) {
1032        if (c.type.isCompound()) {
1033            throw new AssertionError("Unexpected intersection type: " + c.type);
1034        }
1035        try {
1036            c.complete();
1037        } catch (CompletionFailure ex) {
1038            System.err.println("error: " + c + ": " + ex.getMessage());
1039            throw ex;
1040        }
1041        if (!c.type.hasTag(CLASS)) return; // arrays
1042        if (pool != null && // pool might be null if called from xClassName
1043            c.owner.enclClass() != null &&
1044            (innerClasses == null || !innerClasses.contains(c))) {
1045//          log.errWriter.println("enter inner " + c);//DEBUG
1046            enterInner(c.owner.enclClass());
1047            pool.put(c);
1048            if (c.name != names.empty)
1049                pool.put(c.name);
1050            if (innerClasses == null) {
1051                innerClasses = new HashSet<>();
1052                innerClassesQueue = new ListBuffer<>();
1053                pool.put(names.InnerClasses);
1054            }
1055            innerClasses.add(c);
1056            innerClassesQueue.append(c);
1057        }
1058    }
1059
1060    /** Write "inner classes" attribute.
1061     */
1062    void writeInnerClasses() {
1063        int alenIdx = writeAttr(names.InnerClasses);
1064        databuf.appendChar(innerClassesQueue.length());
1065        for (List<ClassSymbol> l = innerClassesQueue.toList();
1066             l.nonEmpty();
1067             l = l.tail) {
1068            ClassSymbol inner = l.head;
1069            inner.markAbstractIfNeeded(types);
1070            char flags = (char) adjustFlags(inner.flags_field);
1071            if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT
1072            flags &= ~STRICTFP; //inner classes should not have the strictfp flag set.
1073            if (dumpInnerClassModifiers) {
1074                PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1075                pw.println("INNERCLASS  " + inner.name);
1076                pw.println("---" + flagNames(flags));
1077            }
1078            databuf.appendChar(pool.get(inner));
1079            databuf.appendChar(
1080                inner.owner.kind == TYP && !inner.name.isEmpty() ? pool.get(inner.owner) : 0);
1081            databuf.appendChar(
1082                !inner.name.isEmpty() ? pool.get(inner.name) : 0);
1083            databuf.appendChar(flags);
1084        }
1085        endAttr(alenIdx);
1086    }
1087
1088    /** Write "bootstrapMethods" attribute.
1089     */
1090    void writeBootstrapMethods() {
1091        int alenIdx = writeAttr(names.BootstrapMethods);
1092        databuf.appendChar(bootstrapMethods.size());
1093        for (Map.Entry<DynamicMethod.BootstrapMethodsKey, DynamicMethod.BootstrapMethodsValue> entry : bootstrapMethods.entrySet()) {
1094            DynamicMethod.BootstrapMethodsKey bsmKey = entry.getKey();
1095            //write BSM handle
1096            databuf.appendChar(pool.get(entry.getValue().mh));
1097            Object[] uniqueArgs = bsmKey.getUniqueArgs();
1098            //write static args length
1099            databuf.appendChar(uniqueArgs.length);
1100            //write static args array
1101            for (Object o : uniqueArgs) {
1102                databuf.appendChar(pool.get(o));
1103            }
1104        }
1105        endAttr(alenIdx);
1106    }
1107
1108    /** Write field symbol, entering all references into constant pool.
1109     */
1110    void writeField(VarSymbol v) {
1111        int flags = adjustFlags(v.flags());
1112        databuf.appendChar(flags);
1113        if (dumpFieldModifiers) {
1114            PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1115            pw.println("FIELD  " + v.name);
1116            pw.println("---" + flagNames(v.flags()));
1117        }
1118        databuf.appendChar(pool.put(v.name));
1119        databuf.appendChar(pool.put(typeSig(v.erasure(types))));
1120        int acountIdx = beginAttrs();
1121        int acount = 0;
1122        if (v.getConstValue() != null) {
1123            int alenIdx = writeAttr(names.ConstantValue);
1124            databuf.appendChar(pool.put(v.getConstValue()));
1125            endAttr(alenIdx);
1126            acount++;
1127        }
1128        acount += writeMemberAttrs(v);
1129        endAttrs(acountIdx, acount);
1130    }
1131
1132    /** Write method symbol, entering all references into constant pool.
1133     */
1134    void writeMethod(MethodSymbol m) {
1135        int flags = adjustFlags(m.flags());
1136        databuf.appendChar(flags);
1137        if (dumpMethodModifiers) {
1138            PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1139            pw.println("METHOD  " + m.name);
1140            pw.println("---" + flagNames(m.flags()));
1141        }
1142        databuf.appendChar(pool.put(m.name));
1143        databuf.appendChar(pool.put(typeSig(m.externalType(types))));
1144        int acountIdx = beginAttrs();
1145        int acount = 0;
1146        if (m.code != null) {
1147            int alenIdx = writeAttr(names.Code);
1148            writeCode(m.code);
1149            m.code = null; // to conserve space
1150            endAttr(alenIdx);
1151            acount++;
1152        }
1153        List<Type> thrown = m.erasure(types).getThrownTypes();
1154        if (thrown.nonEmpty()) {
1155            int alenIdx = writeAttr(names.Exceptions);
1156            databuf.appendChar(thrown.length());
1157            for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1158                databuf.appendChar(pool.put(l.head.tsym));
1159            endAttr(alenIdx);
1160            acount++;
1161        }
1162        if (m.defaultValue != null) {
1163            int alenIdx = writeAttr(names.AnnotationDefault);
1164            m.defaultValue.accept(awriter);
1165            endAttr(alenIdx);
1166            acount++;
1167        }
1168        if (options.isSet(PARAMETERS)) {
1169            if (!m.isLambdaMethod()) // Per JDK-8138729, do not emit parameters table for lambda bodies.
1170                acount += writeMethodParametersAttr(m);
1171        }
1172        acount += writeMemberAttrs(m);
1173        if (!m.isLambdaMethod())
1174            acount += writeParameterAttrs(m);
1175        endAttrs(acountIdx, acount);
1176    }
1177
1178    /** Write code attribute of method.
1179     */
1180    void writeCode(Code code) {
1181        databuf.appendChar(code.max_stack);
1182        databuf.appendChar(code.max_locals);
1183        databuf.appendInt(code.cp);
1184        databuf.appendBytes(code.code, 0, code.cp);
1185        databuf.appendChar(code.catchInfo.length());
1186        for (List<char[]> l = code.catchInfo.toList();
1187             l.nonEmpty();
1188             l = l.tail) {
1189            for (int i = 0; i < l.head.length; i++)
1190                databuf.appendChar(l.head[i]);
1191        }
1192        int acountIdx = beginAttrs();
1193        int acount = 0;
1194
1195        if (code.lineInfo.nonEmpty()) {
1196            int alenIdx = writeAttr(names.LineNumberTable);
1197            databuf.appendChar(code.lineInfo.length());
1198            for (List<char[]> l = code.lineInfo.reverse();
1199                 l.nonEmpty();
1200                 l = l.tail)
1201                for (int i = 0; i < l.head.length; i++)
1202                    databuf.appendChar(l.head[i]);
1203            endAttr(alenIdx);
1204            acount++;
1205        }
1206
1207        if (genCrt && (code.crt != null)) {
1208            CRTable crt = code.crt;
1209            int alenIdx = writeAttr(names.CharacterRangeTable);
1210            int crtIdx = beginAttrs();
1211            int crtEntries = crt.writeCRT(databuf, code.lineMap, log);
1212            endAttrs(crtIdx, crtEntries);
1213            endAttr(alenIdx);
1214            acount++;
1215        }
1216
1217        // counter for number of generic local variables
1218        if (code.varDebugInfo && code.varBufferSize > 0) {
1219            int nGenericVars = 0;
1220            int alenIdx = writeAttr(names.LocalVariableTable);
1221            databuf.appendChar(code.getLVTSize());
1222            for (int i=0; i<code.varBufferSize; i++) {
1223                Code.LocalVar var = code.varBuffer[i];
1224
1225                for (Code.LocalVar.Range r: var.aliveRanges) {
1226                    // write variable info
1227                    Assert.check(r.start_pc >= 0
1228                            && r.start_pc <= code.cp);
1229                    databuf.appendChar(r.start_pc);
1230                    Assert.check(r.length > 0
1231                            && (r.start_pc + r.length) <= code.cp);
1232                    databuf.appendChar(r.length);
1233                    VarSymbol sym = var.sym;
1234                    databuf.appendChar(pool.put(sym.name));
1235                    Type vartype = sym.erasure(types);
1236                    databuf.appendChar(pool.put(typeSig(vartype)));
1237                    databuf.appendChar(var.reg);
1238                    if (needsLocalVariableTypeEntry(var.sym.type)) {
1239                        nGenericVars++;
1240                    }
1241                }
1242            }
1243            endAttr(alenIdx);
1244            acount++;
1245
1246            if (nGenericVars > 0) {
1247                alenIdx = writeAttr(names.LocalVariableTypeTable);
1248                databuf.appendChar(nGenericVars);
1249                int count = 0;
1250
1251                for (int i=0; i<code.varBufferSize; i++) {
1252                    Code.LocalVar var = code.varBuffer[i];
1253                    VarSymbol sym = var.sym;
1254                    if (!needsLocalVariableTypeEntry(sym.type))
1255                        continue;
1256                    for (Code.LocalVar.Range r : var.aliveRanges) {
1257                        // write variable info
1258                        databuf.appendChar(r.start_pc);
1259                        databuf.appendChar(r.length);
1260                        databuf.appendChar(pool.put(sym.name));
1261                        databuf.appendChar(pool.put(typeSig(sym.type)));
1262                        databuf.appendChar(var.reg);
1263                        count++;
1264                    }
1265                }
1266                Assert.check(count == nGenericVars);
1267                endAttr(alenIdx);
1268                acount++;
1269            }
1270        }
1271
1272        if (code.stackMapBufferSize > 0) {
1273            if (debugstackmap) System.out.println("Stack map for " + code.meth);
1274            int alenIdx = writeAttr(code.stackMap.getAttributeName(names));
1275            writeStackMap(code);
1276            endAttr(alenIdx);
1277            acount++;
1278        }
1279
1280        acount += writeTypeAnnotations(code.meth.getRawTypeAttributes(), true);
1281
1282        endAttrs(acountIdx, acount);
1283    }
1284    //where
1285    private boolean needsLocalVariableTypeEntry(Type t) {
1286        //a local variable needs a type-entry if its type T is generic
1287        //(i.e. |T| != T) and if it's not an intersection type (not supported
1288        //in signature attribute grammar)
1289        return (!types.isSameType(t, types.erasure(t)) &&
1290                !t.isCompound());
1291    }
1292
1293    void writeStackMap(Code code) {
1294        int nframes = code.stackMapBufferSize;
1295        if (debugstackmap) System.out.println(" nframes = " + nframes);
1296        databuf.appendChar(nframes);
1297
1298        switch (code.stackMap) {
1299        case CLDC:
1300            for (int i=0; i<nframes; i++) {
1301                if (debugstackmap) System.out.print("  " + i + ":");
1302                Code.StackMapFrame frame = code.stackMapBuffer[i];
1303
1304                // output PC
1305                if (debugstackmap) System.out.print(" pc=" + frame.pc);
1306                databuf.appendChar(frame.pc);
1307
1308                // output locals
1309                int localCount = 0;
1310                for (int j=0; j<frame.locals.length;
1311                     j += Code.width(frame.locals[j])) {
1312                    localCount++;
1313                }
1314                if (debugstackmap) System.out.print(" nlocals=" +
1315                                                    localCount);
1316                databuf.appendChar(localCount);
1317                for (int j=0; j<frame.locals.length;
1318                     j += Code.width(frame.locals[j])) {
1319                    if (debugstackmap) System.out.print(" local[" + j + "]=");
1320                    writeStackMapType(frame.locals[j]);
1321                }
1322
1323                // output stack
1324                int stackCount = 0;
1325                for (int j=0; j<frame.stack.length;
1326                     j += Code.width(frame.stack[j])) {
1327                    stackCount++;
1328                }
1329                if (debugstackmap) System.out.print(" nstack=" +
1330                                                    stackCount);
1331                databuf.appendChar(stackCount);
1332                for (int j=0; j<frame.stack.length;
1333                     j += Code.width(frame.stack[j])) {
1334                    if (debugstackmap) System.out.print(" stack[" + j + "]=");
1335                    writeStackMapType(frame.stack[j]);
1336                }
1337                if (debugstackmap) System.out.println();
1338            }
1339            break;
1340        case JSR202: {
1341            Assert.checkNull(code.stackMapBuffer);
1342            for (int i=0; i<nframes; i++) {
1343                if (debugstackmap) System.out.print("  " + i + ":");
1344                StackMapTableFrame frame = code.stackMapTableBuffer[i];
1345                frame.write(this);
1346                if (debugstackmap) System.out.println();
1347            }
1348            break;
1349        }
1350        default:
1351            throw new AssertionError("Unexpected stackmap format value");
1352        }
1353    }
1354
1355        //where
1356        void writeStackMapType(Type t) {
1357            if (t == null) {
1358                if (debugstackmap) System.out.print("empty");
1359                databuf.appendByte(0);
1360            }
1361            else switch(t.getTag()) {
1362            case BYTE:
1363            case CHAR:
1364            case SHORT:
1365            case INT:
1366            case BOOLEAN:
1367                if (debugstackmap) System.out.print("int");
1368                databuf.appendByte(1);
1369                break;
1370            case FLOAT:
1371                if (debugstackmap) System.out.print("float");
1372                databuf.appendByte(2);
1373                break;
1374            case DOUBLE:
1375                if (debugstackmap) System.out.print("double");
1376                databuf.appendByte(3);
1377                break;
1378            case LONG:
1379                if (debugstackmap) System.out.print("long");
1380                databuf.appendByte(4);
1381                break;
1382            case BOT: // null
1383                if (debugstackmap) System.out.print("null");
1384                databuf.appendByte(5);
1385                break;
1386            case CLASS:
1387            case ARRAY:
1388                if (debugstackmap) System.out.print("object(" + t + ")");
1389                databuf.appendByte(7);
1390                databuf.appendChar(pool.put(t));
1391                break;
1392            case TYPEVAR:
1393                if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")");
1394                databuf.appendByte(7);
1395                databuf.appendChar(pool.put(types.erasure(t).tsym));
1396                break;
1397            case UNINITIALIZED_THIS:
1398                if (debugstackmap) System.out.print("uninit_this");
1399                databuf.appendByte(6);
1400                break;
1401            case UNINITIALIZED_OBJECT:
1402                { UninitializedType uninitType = (UninitializedType)t;
1403                databuf.appendByte(8);
1404                if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset);
1405                databuf.appendChar(uninitType.offset);
1406                }
1407                break;
1408            default:
1409                throw new AssertionError();
1410            }
1411        }
1412
1413    /** An entry in the JSR202 StackMapTable */
1414    abstract static class StackMapTableFrame {
1415        abstract int getFrameType();
1416
1417        void write(ClassWriter writer) {
1418            int frameType = getFrameType();
1419            writer.databuf.appendByte(frameType);
1420            if (writer.debugstackmap) System.out.print(" frame_type=" + frameType);
1421        }
1422
1423        static class SameFrame extends StackMapTableFrame {
1424            final int offsetDelta;
1425            SameFrame(int offsetDelta) {
1426                this.offsetDelta = offsetDelta;
1427            }
1428            int getFrameType() {
1429                return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED;
1430            }
1431            @Override
1432            void write(ClassWriter writer) {
1433                super.write(writer);
1434                if (getFrameType() == SAME_FRAME_EXTENDED) {
1435                    writer.databuf.appendChar(offsetDelta);
1436                    if (writer.debugstackmap){
1437                        System.out.print(" offset_delta=" + offsetDelta);
1438                    }
1439                }
1440            }
1441        }
1442
1443        static class SameLocals1StackItemFrame extends StackMapTableFrame {
1444            final int offsetDelta;
1445            final Type stack;
1446            SameLocals1StackItemFrame(int offsetDelta, Type stack) {
1447                this.offsetDelta = offsetDelta;
1448                this.stack = stack;
1449            }
1450            int getFrameType() {
1451                return (offsetDelta < SAME_FRAME_SIZE) ?
1452                       (SAME_FRAME_SIZE + offsetDelta) :
1453                       SAME_LOCALS_1_STACK_ITEM_EXTENDED;
1454            }
1455            @Override
1456            void write(ClassWriter writer) {
1457                super.write(writer);
1458                if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) {
1459                    writer.databuf.appendChar(offsetDelta);
1460                    if (writer.debugstackmap) {
1461                        System.out.print(" offset_delta=" + offsetDelta);
1462                    }
1463                }
1464                if (writer.debugstackmap) {
1465                    System.out.print(" stack[" + 0 + "]=");
1466                }
1467                writer.writeStackMapType(stack);
1468            }
1469        }
1470
1471        static class ChopFrame extends StackMapTableFrame {
1472            final int frameType;
1473            final int offsetDelta;
1474            ChopFrame(int frameType, int offsetDelta) {
1475                this.frameType = frameType;
1476                this.offsetDelta = offsetDelta;
1477            }
1478            int getFrameType() { return frameType; }
1479            @Override
1480            void write(ClassWriter writer) {
1481                super.write(writer);
1482                writer.databuf.appendChar(offsetDelta);
1483                if (writer.debugstackmap) {
1484                    System.out.print(" offset_delta=" + offsetDelta);
1485                }
1486            }
1487        }
1488
1489        static class AppendFrame extends StackMapTableFrame {
1490            final int frameType;
1491            final int offsetDelta;
1492            final Type[] locals;
1493            AppendFrame(int frameType, int offsetDelta, Type[] locals) {
1494                this.frameType = frameType;
1495                this.offsetDelta = offsetDelta;
1496                this.locals = locals;
1497            }
1498            int getFrameType() { return frameType; }
1499            @Override
1500            void write(ClassWriter writer) {
1501                super.write(writer);
1502                writer.databuf.appendChar(offsetDelta);
1503                if (writer.debugstackmap) {
1504                    System.out.print(" offset_delta=" + offsetDelta);
1505                }
1506                for (int i=0; i<locals.length; i++) {
1507                     if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1508                     writer.writeStackMapType(locals[i]);
1509                }
1510            }
1511        }
1512
1513        static class FullFrame extends StackMapTableFrame {
1514            final int offsetDelta;
1515            final Type[] locals;
1516            final Type[] stack;
1517            FullFrame(int offsetDelta, Type[] locals, Type[] stack) {
1518                this.offsetDelta = offsetDelta;
1519                this.locals = locals;
1520                this.stack = stack;
1521            }
1522            int getFrameType() { return FULL_FRAME; }
1523            @Override
1524            void write(ClassWriter writer) {
1525                super.write(writer);
1526                writer.databuf.appendChar(offsetDelta);
1527                writer.databuf.appendChar(locals.length);
1528                if (writer.debugstackmap) {
1529                    System.out.print(" offset_delta=" + offsetDelta);
1530                    System.out.print(" nlocals=" + locals.length);
1531                }
1532                for (int i=0; i<locals.length; i++) {
1533                    if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1534                    writer.writeStackMapType(locals[i]);
1535                }
1536
1537                writer.databuf.appendChar(stack.length);
1538                if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); }
1539                for (int i=0; i<stack.length; i++) {
1540                    if (writer.debugstackmap) System.out.print(" stack[" + i + "]=");
1541                    writer.writeStackMapType(stack[i]);
1542                }
1543            }
1544        }
1545
1546       /** Compare this frame with the previous frame and produce
1547        *  an entry of compressed stack map frame. */
1548        static StackMapTableFrame getInstance(Code.StackMapFrame this_frame,
1549                                              int prev_pc,
1550                                              Type[] prev_locals,
1551                                              Types types) {
1552            Type[] locals = this_frame.locals;
1553            Type[] stack = this_frame.stack;
1554            int offset_delta = this_frame.pc - prev_pc - 1;
1555            if (stack.length == 1) {
1556                if (locals.length == prev_locals.length
1557                    && compare(prev_locals, locals, types) == 0) {
1558                    return new SameLocals1StackItemFrame(offset_delta, stack[0]);
1559                }
1560            } else if (stack.length == 0) {
1561                int diff_length = compare(prev_locals, locals, types);
1562                if (diff_length == 0) {
1563                    return new SameFrame(offset_delta);
1564                } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) {
1565                    // APPEND
1566                    Type[] local_diff = new Type[-diff_length];
1567                    for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) {
1568                        local_diff[j] = locals[i];
1569                    }
1570                    return new AppendFrame(SAME_FRAME_EXTENDED - diff_length,
1571                                           offset_delta,
1572                                           local_diff);
1573                } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) {
1574                    // CHOP
1575                    return new ChopFrame(SAME_FRAME_EXTENDED - diff_length,
1576                                         offset_delta);
1577                }
1578            }
1579            // FULL_FRAME
1580            return new FullFrame(offset_delta, locals, stack);
1581        }
1582
1583        static boolean isInt(Type t) {
1584            return (t.getTag().isStrictSubRangeOf(INT)  || t.hasTag(BOOLEAN));
1585        }
1586
1587        static boolean isSameType(Type t1, Type t2, Types types) {
1588            if (t1 == null) { return t2 == null; }
1589            if (t2 == null) { return false; }
1590
1591            if (isInt(t1) && isInt(t2)) { return true; }
1592
1593            if (t1.hasTag(UNINITIALIZED_THIS)) {
1594                return t2.hasTag(UNINITIALIZED_THIS);
1595            } else if (t1.hasTag(UNINITIALIZED_OBJECT)) {
1596                if (t2.hasTag(UNINITIALIZED_OBJECT)) {
1597                    return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset;
1598                } else {
1599                    return false;
1600                }
1601            } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) {
1602                return false;
1603            }
1604
1605            return types.isSameType(t1, t2);
1606        }
1607
1608        static int compare(Type[] arr1, Type[] arr2, Types types) {
1609            int diff_length = arr1.length - arr2.length;
1610            if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) {
1611                return Integer.MAX_VALUE;
1612            }
1613            int len = (diff_length > 0) ? arr2.length : arr1.length;
1614            for (int i=0; i<len; i++) {
1615                if (!isSameType(arr1[i], arr2[i], types)) {
1616                    return Integer.MAX_VALUE;
1617                }
1618            }
1619            return diff_length;
1620        }
1621    }
1622
1623    void writeFields(Scope s) {
1624        // process them in reverse sibling order;
1625        // i.e., process them in declaration order.
1626        List<VarSymbol> vars = List.nil();
1627        for (Symbol sym : s.getSymbols(NON_RECURSIVE)) {
1628            if (sym.kind == VAR) vars = vars.prepend((VarSymbol)sym);
1629        }
1630        while (vars.nonEmpty()) {
1631            writeField(vars.head);
1632            vars = vars.tail;
1633        }
1634    }
1635
1636    void writeMethods(Scope s) {
1637        List<MethodSymbol> methods = List.nil();
1638        for (Symbol sym : s.getSymbols(NON_RECURSIVE)) {
1639            if (sym.kind == MTH && (sym.flags() & HYPOTHETICAL) == 0)
1640                methods = methods.prepend((MethodSymbol)sym);
1641        }
1642        while (methods.nonEmpty()) {
1643            writeMethod(methods.head);
1644            methods = methods.tail;
1645        }
1646    }
1647
1648    /** Emit a class file for a given class.
1649     *  @param c      The class from which a class file is generated.
1650     */
1651    public JavaFileObject writeClass(ClassSymbol c)
1652        throws IOException, PoolOverflow, StringOverflow
1653    {
1654        String name = (c.owner.kind == MDL ? c.name : c.flatname).toString();
1655        Location outLocn;
1656        if (multiModuleMode) {
1657            ModuleSymbol msym = c.owner.kind == MDL ? (ModuleSymbol) c.owner : c.packge().modle;
1658            outLocn = fileManager.getLocationForModule(CLASS_OUTPUT, msym.name.toString());
1659        } else {
1660            outLocn = CLASS_OUTPUT;
1661        }
1662        JavaFileObject outFile
1663            = fileManager.getJavaFileForOutput(outLocn,
1664                                               name,
1665                                               JavaFileObject.Kind.CLASS,
1666                                               c.sourcefile);
1667        OutputStream out = outFile.openOutputStream();
1668        try {
1669            writeClassFile(out, c);
1670            if (verbose)
1671                log.printVerbose("wrote.file", outFile);
1672            out.close();
1673            out = null;
1674        } finally {
1675            if (out != null) {
1676                // if we are propagating an exception, delete the file
1677                out.close();
1678                outFile.delete();
1679                outFile = null;
1680            }
1681        }
1682        return outFile; // may be null if write failed
1683    }
1684
1685    /** Write class `c' to outstream `out'.
1686     */
1687    public void writeClassFile(OutputStream out, ClassSymbol c)
1688        throws IOException, PoolOverflow, StringOverflow {
1689        Assert.check((c.flags() & COMPOUND) == 0);
1690        databuf.reset();
1691        poolbuf.reset();
1692        signatureGen.reset();
1693        pool = c.pool;
1694        innerClasses = null;
1695        innerClassesQueue = null;
1696        bootstrapMethods = new LinkedHashMap<>();
1697
1698        Type supertype = types.supertype(c.type);
1699        List<Type> interfaces = types.interfaces(c.type);
1700        List<Type> typarams = c.type.getTypeArguments();
1701
1702        int flags;
1703        if (c.owner.kind == MDL) {
1704            flags = ACC_MODULE;
1705        } else {
1706            flags = adjustFlags(c.flags() & ~DEFAULT);
1707            if ((flags & PROTECTED) != 0) flags |= PUBLIC;
1708            flags = flags & ClassFlags & ~STRICTFP;
1709            if ((flags & INTERFACE) == 0) flags |= ACC_SUPER;
1710        }
1711
1712        if (dumpClassModifiers) {
1713            PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1714            pw.println();
1715            pw.println("CLASSFILE  " + c.getQualifiedName());
1716            pw.println("---" + flagNames(flags));
1717        }
1718        databuf.appendChar(flags);
1719
1720        if (c.owner.kind == MDL) {
1721            databuf.appendChar(0);
1722        } else {
1723            databuf.appendChar(pool.put(c));
1724        }
1725        databuf.appendChar(supertype.hasTag(CLASS) ? pool.put(supertype.tsym) : 0);
1726        databuf.appendChar(interfaces.length());
1727        for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1728            databuf.appendChar(pool.put(l.head.tsym));
1729        int fieldsCount = 0;
1730        int methodsCount = 0;
1731        for (Symbol sym : c.members().getSymbols(NON_RECURSIVE)) {
1732            switch (sym.kind) {
1733            case VAR: fieldsCount++; break;
1734            case MTH: if ((sym.flags() & HYPOTHETICAL) == 0) methodsCount++;
1735                      break;
1736            case TYP: enterInner((ClassSymbol)sym); break;
1737            default : Assert.error();
1738            }
1739        }
1740
1741        if (c.trans_local != null) {
1742            for (ClassSymbol local : c.trans_local) {
1743                enterInner(local);
1744            }
1745        }
1746
1747        databuf.appendChar(fieldsCount);
1748        writeFields(c.members());
1749        databuf.appendChar(methodsCount);
1750        writeMethods(c.members());
1751
1752        int acountIdx = beginAttrs();
1753        int acount = 0;
1754
1755        boolean sigReq =
1756            typarams.length() != 0 || supertype.allparams().length() != 0;
1757        for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail)
1758            sigReq = l.head.allparams().length() != 0;
1759        if (sigReq) {
1760            int alenIdx = writeAttr(names.Signature);
1761            if (typarams.length() != 0) signatureGen.assembleParamsSig(typarams);
1762            signatureGen.assembleSig(supertype);
1763            for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1764                signatureGen.assembleSig(l.head);
1765            databuf.appendChar(pool.put(signatureGen.toName()));
1766            signatureGen.reset();
1767            endAttr(alenIdx);
1768            acount++;
1769        }
1770
1771        if (c.sourcefile != null && emitSourceFile) {
1772            int alenIdx = writeAttr(names.SourceFile);
1773            // WHM 6/29/1999: Strip file path prefix.  We do it here at
1774            // the last possible moment because the sourcefile may be used
1775            // elsewhere in error diagnostics. Fixes 4241573.
1776            //databuf.appendChar(c.pool.put(c.sourcefile));
1777            String simpleName = PathFileObject.getSimpleName(c.sourcefile);
1778            databuf.appendChar(c.pool.put(names.fromString(simpleName)));
1779            endAttr(alenIdx);
1780            acount++;
1781        }
1782
1783        if (genCrt) {
1784            // Append SourceID attribute
1785            int alenIdx = writeAttr(names.SourceID);
1786            databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile)))));
1787            endAttr(alenIdx);
1788            acount++;
1789            // Append CompilationID attribute
1790            alenIdx = writeAttr(names.CompilationID);
1791            databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis()))));
1792            endAttr(alenIdx);
1793            acount++;
1794        }
1795
1796        acount += writeFlagAttrs(c.flags());
1797        acount += writeJavaAnnotations(c.getRawAttributes());
1798        acount += writeTypeAnnotations(c.getRawTypeAttributes(), false);
1799        acount += writeEnclosingMethodAttribute(c);
1800        if (c.owner.kind == MDL) {
1801            acount += writeModuleAttribute(c);
1802            acount += writeFlagAttrs(c.owner.flags());
1803        }
1804        acount += writeExtraClassAttributes(c);
1805
1806        poolbuf.appendInt(JAVA_MAGIC);
1807
1808        if (c.owner.kind == MDL) {
1809            // temporarily overide to force use of v53 for module-info.class
1810            poolbuf.appendChar(0);
1811            poolbuf.appendChar(53);
1812        } else {
1813            poolbuf.appendChar(target.minorVersion);
1814            poolbuf.appendChar(target.majorVersion);
1815        }
1816
1817        writePool(c.pool);
1818
1819        if (innerClasses != null) {
1820            writeInnerClasses();
1821            acount++;
1822        }
1823
1824        if (!bootstrapMethods.isEmpty()) {
1825            writeBootstrapMethods();
1826            acount++;
1827        }
1828
1829        endAttrs(acountIdx, acount);
1830
1831        poolbuf.appendBytes(databuf.elems, 0, databuf.length);
1832        out.write(poolbuf.elems, 0, poolbuf.length);
1833
1834        pool = c.pool = null; // to conserve space
1835     }
1836
1837    /**Allows subclasses to write additional class attributes
1838     *
1839     * @return the number of attributes written
1840     */
1841    protected int writeExtraClassAttributes(ClassSymbol c) {
1842        return 0;
1843    }
1844
1845    int adjustFlags(final long flags) {
1846        int result = (int)flags;
1847
1848        if ((flags & BRIDGE) != 0)
1849            result |= ACC_BRIDGE;
1850        if ((flags & VARARGS) != 0)
1851            result |= ACC_VARARGS;
1852        if ((flags & DEFAULT) != 0)
1853            result &= ~ABSTRACT;
1854        return result;
1855    }
1856
1857    long getLastModified(FileObject filename) {
1858        long mod = 0;
1859        try {
1860            mod = filename.getLastModified();
1861        } catch (SecurityException e) {
1862            throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage());
1863        }
1864        return mod;
1865    }
1866}
1867