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