1 /*
   2  * Copyright (c) 1999, 2023, 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.Symbol.*;
  44 import com.sun.tools.javac.code.Type.*;
  45 import com.sun.tools.javac.code.Types.SignatureGenerator.InvalidSignatureException;
  46 import com.sun.tools.javac.comp.Check;
  47 import com.sun.tools.javac.file.PathFileObject;
  48 import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant;
  49 import com.sun.tools.javac.jvm.PoolConstant.Dynamic.BsmKey;
  50 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  51 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  52 import com.sun.tools.javac.util.*;
  53 import com.sun.tools.javac.util.List;
  54 
  55 import static com.sun.tools.javac.code.Flags.*;
  56 import static com.sun.tools.javac.code.Kinds.Kind.*;
  57 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  58 import static com.sun.tools.javac.code.TypeTag.*;
  59 import static com.sun.tools.javac.main.Option.*;
  60 
  61 import static javax.tools.StandardLocation.CLASS_OUTPUT;
  62 
  63 /** This class provides operations to map an internal symbol table graph
  64  *  rooted in a ClassSymbol into a classfile.
  65  *
  66  *  <p><b>This is NOT part of any supported API.
  67  *  If you write code that depends on this, you do so at your own risk.
  68  *  This code and its internal interfaces are subject to change or
  69  *  deletion without notice.</b>
  70  */
  71 public class ClassWriter extends ClassFile {
  72     protected static final Context.Key<ClassWriter> classWriterKey = new Context.Key<>();
  73 
  74     private final Options options;
  75 
  76     /** Switch: verbose output.
  77      */
  78     private boolean verbose;
  79 
  80     /** Switch: emit source file attribute.
  81      */
  82     private boolean emitSourceFile;
  83 
  84     /** Switch: generate CharacterRangeTable attribute.
  85      */
  86     private boolean genCrt;
  87 
  88     /** Switch: describe the generated stackmap.
  89      */
  90     private boolean debugstackmap;
  91 
  92     /** Preview language level.
  93      */
  94     private Preview preview;
  95 
  96     /**
  97      * Target class version.
  98      */
  99     private Target target;
 100 
 101     /**
 102      * Source language version.
 103      */
 104     private Source source;
 105 
 106     /** Type utilities. */
 107     private Types types;
 108 
 109     private Check check;
 110 
 111     /**
 112      * If true, class files will be written in module-specific subdirectories
 113      * of the CLASS_OUTPUT location.
 114      */
 115     public boolean multiModuleMode;
 116 
 117     private List<ToIntFunction<Symbol>> extraAttributeHooks = List.nil();
 118 
 119     /** The initial sizes of the data and constant pool buffers.
 120      *  Sizes are increased when buffers get full.
 121      */
 122     static final int DATA_BUF_SIZE = 0x0fff0;
 123     static final int CLASS_BUF_SIZE = 0x1fff0;
 124 
 125     /** An output buffer for member info.
 126      */
 127     public ByteBuffer databuf = new ByteBuffer(DATA_BUF_SIZE);
 128 
 129     /** An output buffer for the constant pool.
 130      */
 131     ByteBuffer poolbuf = new ByteBuffer(CLASS_BUF_SIZE);
 132 
 133     /** The constant pool writer.
 134      */
 135     final PoolWriter poolWriter;
 136 
 137     /** The log to use for verbose output.
 138      */
 139     private final Log log;
 140 
 141     /** The name table. */
 142     private final Names names;
 143 
 144     /** Access to files. */
 145     private final JavaFileManager fileManager;
 146 
 147     /** The tags and constants used in compressed stackmap. */
 148     static final int SAME_FRAME_SIZE = 64;
 149     static final int SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247;
 150     static final int SAME_FRAME_EXTENDED = 251;
 151     static final int FULL_FRAME = 255;
 152     static final int MAX_LOCAL_LENGTH_DIFF = 4;
 153 
 154     /** Get the ClassWriter instance for this context. */
 155     public static ClassWriter instance(Context context) {
 156         ClassWriter instance = context.get(classWriterKey);
 157         if (instance == null)
 158             instance = new ClassWriter(context);
 159         return instance;
 160     }
 161 
 162     /** Construct a class writer, given an options table.
 163      */
 164     @SuppressWarnings("this-escape")
 165     protected ClassWriter(Context context) {
 166         context.put(classWriterKey, this);
 167 
 168         log = Log.instance(context);
 169         names = Names.instance(context);
 170         options = Options.instance(context);
 171         preview = Preview.instance(context);
 172         target = Target.instance(context);
 173         source = Source.instance(context);
 174         types = Types.instance(context);
 175         check = Check.instance(context);
 176         fileManager = context.get(JavaFileManager.class);
 177         poolWriter = Gen.instance(context).poolWriter;
 178 
 179         verbose        = options.isSet(VERBOSE);
 180         genCrt         = options.isSet(XJCOV);
 181         debugstackmap = options.isSet("debug.stackmap");
 182 
 183         emitSourceFile = options.isUnset(G_CUSTOM) ||
 184                             options.isSet(G_CUSTOM, "source");
 185 
 186         String modifierFlags = options.get("debug.dumpmodifiers");
 187         if (modifierFlags != null) {
 188             dumpClassModifiers = modifierFlags.indexOf('c') != -1;
 189             dumpFieldModifiers = modifierFlags.indexOf('f') != -1;
 190             dumpInnerClassModifiers = modifierFlags.indexOf('i') != -1;
 191             dumpMethodModifiers = modifierFlags.indexOf('m') != -1;
 192         }
 193     }
 194 
 195     public void addExtraAttributes(ToIntFunction<Symbol> addExtraAttributes) {
 196         extraAttributeHooks = extraAttributeHooks.prepend(addExtraAttributes);
 197     }
 198 
 199 /* ****************************************************************
 200  * Diagnostics: dump generated class names and modifiers
 201  ******************************************************************/
 202 
 203     /** Value of option 'dumpmodifiers' is a string
 204      *  indicating which modifiers should be dumped for debugging:
 205      *    'c' -- classes
 206      *    'f' -- fields
 207      *    'i' -- innerclass attributes
 208      *    'm' -- methods
 209      *  For example, to dump everything:
 210      *    javac -XDdumpmodifiers=cifm MyProg.java
 211      */
 212     private boolean dumpClassModifiers; // -XDdumpmodifiers=c
 213     private boolean dumpFieldModifiers; // -XDdumpmodifiers=f
 214     private boolean dumpInnerClassModifiers; // -XDdumpmodifiers=i
 215     private boolean dumpMethodModifiers; // -XDdumpmodifiers=m
 216 
 217 
 218     /** Return flags as a string, separated by " ".
 219      */
 220     public static String flagNames(long flags) {
 221         StringBuilder sbuf = new StringBuilder();
 222         int i = 0;
 223         long f = flags & StandardFlags;
 224         while (f != 0) {
 225             if ((f & 1) != 0 && flagName[i] != "") {
 226                 sbuf.append(" ");
 227                 sbuf.append(flagName[i]);
 228             }
 229             f = f >> 1;
 230             i++;
 231         }
 232         return sbuf.toString();
 233     }
 234     //where
 235         private static final String[] flagName = {
 236             "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL",
 237             // the empty position should be for synchronized but right now we don't have any test checking it
 238             "", "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  * Writing the Constant Pool
 265  ******************************************************************/
 266 
 267     /** Thrown when the constant pool is over full.
 268      */
 269     public static class PoolOverflow extends RuntimeException {
 270         private static final long serialVersionUID = 0;
 271         public PoolOverflow() {}
 272     }
 273     public static class StringOverflow extends RuntimeException {
 274         private static final long serialVersionUID = 0;
 275         public final String value;
 276         public StringOverflow(String s) {
 277             value = s;
 278         }
 279     }
 280 
 281 /* ****************************************************************
 282  * Writing Attributes
 283  ******************************************************************/
 284 
 285     /** Write header for an attribute to data buffer and return
 286      *  position past attribute length index.
 287      */
 288     public int writeAttr(Name attrName) {
 289         int index = poolWriter.putName(attrName);
 290         databuf.appendChar(index);
 291         databuf.appendInt(0);
 292         return databuf.length;
 293     }
 294 
 295     /** Fill in attribute length.
 296      */
 297     public void endAttr(int index) {
 298         putInt(databuf, index - 4, databuf.length - index);
 299     }
 300 
 301     /** Leave space for attribute count and return index for
 302      *  number of attributes field.
 303      */
 304     int beginAttrs() {
 305         databuf.appendChar(0);
 306         return databuf.length;
 307     }
 308 
 309     /** Fill in number of attributes.
 310      */
 311     void endAttrs(int index, int count) {
 312         putChar(databuf, index - 2, count);
 313     }
 314 
 315     /** Write the EnclosingMethod attribute if needed.
 316      *  Returns the number of attributes written (0 or 1).
 317      */
 318     int writeEnclosingMethodAttribute(ClassSymbol c) {
 319         return writeEnclosingMethodAttribute(names.EnclosingMethod, c);
 320     }
 321 
 322     /** Write the EnclosingMethod attribute with a specified name.
 323      *  Returns the number of attributes written (0 or 1).
 324      */
 325     protected int writeEnclosingMethodAttribute(Name attributeName, ClassSymbol c) {
 326         if (c.owner.kind != MTH && // neither a local class
 327             c.name != names.empty) // nor anonymous
 328             return 0;
 329 
 330         int alenIdx = writeAttr(attributeName);
 331         ClassSymbol enclClass = c.owner.enclClass();
 332         MethodSymbol enclMethod =
 333             ((c.owner.flags() & BLOCK) != 0 // local to init block
 334              || c.owner.kind != MTH) // or member init
 335             ? null
 336             : ((MethodSymbol)c.owner).originalEnclosingMethod();
 337         databuf.appendChar(poolWriter.putClass(enclClass));
 338         databuf.appendChar(enclMethod == null ? 0 : poolWriter.putNameAndType(enclMethod));
 339         endAttr(alenIdx);
 340         return 1;
 341     }
 342 
 343     /** Write flag attributes; return number of attributes written.
 344      */
 345     int writeFlagAttrs(long flags) {
 346         int acount = 0;
 347         if ((flags & DEPRECATED) != 0) {
 348             int alenIdx = writeAttr(names.Deprecated);
 349             endAttr(alenIdx);
 350             acount++;
 351         }
 352         return acount;
 353     }
 354 
 355     /** Write member (field or method) attributes;
 356      *  return number of attributes written.
 357      */
 358     int writeMemberAttrs(Symbol sym, boolean isRecordComponent) {
 359         int acount = 0;
 360         if (!isRecordComponent) {
 361             acount = writeFlagAttrs(sym.flags());
 362         }
 363         long flags = sym.flags();
 364         if ((flags & (SYNTHETIC | BRIDGE)) != SYNTHETIC &&
 365             (flags & ANONCONSTR) == 0 &&
 366             (!types.isSameType(sym.type, sym.erasure(types)) ||
 367              poolWriter.signatureGen.hasTypeVar(sym.type.getThrownTypes()))) {
 368             // note that a local class with captured variables
 369             // will get a signature attribute
 370             int alenIdx = writeAttr(names.Signature);
 371             databuf.appendChar(poolWriter.putSignature(sym));
 372             endAttr(alenIdx);
 373             acount++;
 374         }
 375         acount += writeJavaAnnotations(sym.getRawAttributes());
 376         acount += writeTypeAnnotations(sym.getRawTypeAttributes(), false);
 377         return acount;
 378     }
 379 
 380     /**
 381      * Write method parameter names attribute.
 382      */
 383     int writeMethodParametersAttr(MethodSymbol m, boolean writeParamNames) {
 384         MethodType ty = m.externalType(types).asMethodType();
 385         final int allparams = ty.argtypes.size();
 386         if (m.params != null && allparams != 0) {
 387             final int attrIndex = writeAttr(names.MethodParameters);
 388             databuf.appendByte(allparams);
 389             // Write extra parameters first
 390             for (VarSymbol s : m.extraParams) {
 391                 final int flags =
 392                     ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
 393                     ((int) m.flags() & SYNTHETIC);
 394                 if (writeParamNames)
 395                     databuf.appendChar(poolWriter.putName(s.name));
 396                 else
 397                     databuf.appendChar(0);
 398                 databuf.appendChar(flags);
 399             }
 400             // Now write the real parameters
 401             for (VarSymbol s : m.params) {
 402                 final int flags =
 403                     ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
 404                     ((int) m.flags() & SYNTHETIC);
 405                 if (writeParamNames)
 406                     databuf.appendChar(poolWriter.putName(s.name));
 407                 else
 408                     databuf.appendChar(0);
 409                 databuf.appendChar(flags);
 410             }
 411             // Now write the captured locals
 412             for (VarSymbol s : m.capturedLocals) {
 413                 final int flags =
 414                     ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
 415                     ((int) m.flags() & SYNTHETIC);
 416                 if (writeParamNames)
 417                     databuf.appendChar(poolWriter.putName(s.name));
 418                 else
 419                     databuf.appendChar(0);
 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             int flags = adjustFlags(inner, inner.flags_field);
 839             if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT
 840             if (dumpInnerClassModifiers) {
 841                 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
 842                 pw.println("INNERCLASS  " + inner.name);
 843                 pw.println("---" + flagNames(flags));
 844             }
 845             databuf.appendChar(poolWriter.putClass(inner));
 846             databuf.appendChar(
 847                 inner.owner.kind == TYP && !inner.name.isEmpty() ? poolWriter.putClass((ClassSymbol)inner.owner) : 0);
 848             databuf.appendChar(
 849                 !inner.name.isEmpty() ? poolWriter.putName(inner.name) : 0);
 850             databuf.appendChar(flags);
 851         }
 852         endAttr(alenIdx);
 853     }
 854 
 855      /** Write out "LoadableDescriptors" attribute by enumerating the value classes encountered in field/method descriptors during this compilation.
 856       */
 857      void writeLoadableDescriptorsAttribute() {
 858         int alenIdx = writeAttr(names.LoadableDescriptors);
 859         databuf.appendChar(poolWriter.loadableDescriptors.size());
 860         for (Symbol c : poolWriter.loadableDescriptors) {
 861             databuf.appendChar(poolWriter.putDescriptor(c));
 862         }
 863         endAttr(alenIdx);
 864      }
 865 
 866     int writeRecordAttribute(ClassSymbol csym) {
 867         int alenIdx = writeAttr(names.Record);
 868         Scope s = csym.members();
 869         databuf.appendChar(csym.getRecordComponents().size());
 870         for (VarSymbol v: csym.getRecordComponents()) {
 871             //databuf.appendChar(poolWriter.putMember(v.accessor.head.snd));
 872             databuf.appendChar(poolWriter.putName(v.name));
 873             databuf.appendChar(poolWriter.putDescriptor(v));
 874             int acountIdx = beginAttrs();
 875             int acount = 0;
 876             acount += writeMemberAttrs(v, true);
 877             endAttrs(acountIdx, acount);
 878         }
 879         endAttr(alenIdx);
 880         return 1;
 881     }
 882 
 883     /**
 884      * Write NestMembers attribute (if needed)
 885      */
 886     int writeNestMembersIfNeeded(ClassSymbol csym) {
 887         ListBuffer<ClassSymbol> nested = new ListBuffer<>();
 888         listNested(csym, nested);
 889         Set<ClassSymbol> nestedUnique = new LinkedHashSet<>(nested);
 890         if (csym.owner.kind == PCK && !nestedUnique.isEmpty()) {
 891             int alenIdx = writeAttr(names.NestMembers);
 892             databuf.appendChar(nestedUnique.size());
 893             for (ClassSymbol s : nestedUnique) {
 894                 databuf.appendChar(poolWriter.putClass(s));
 895             }
 896             endAttr(alenIdx);
 897             return 1;
 898         }
 899         return 0;
 900     }
 901 
 902     /**
 903      * Write NestHost attribute (if needed)
 904      */
 905     int writeNestHostIfNeeded(ClassSymbol csym) {
 906         if (csym.owner.kind != PCK) {
 907             int alenIdx = writeAttr(names.NestHost);
 908             databuf.appendChar(poolWriter.putClass(csym.outermostClass()));
 909             endAttr(alenIdx);
 910             return 1;
 911         }
 912         return 0;
 913     }
 914 
 915     private void listNested(Symbol sym, ListBuffer<ClassSymbol> seen) {
 916         if (sym.kind != TYP) return;
 917         ClassSymbol csym = (ClassSymbol)sym;
 918         if (csym.owner.kind != PCK) {
 919             seen.add(csym);
 920         }
 921         if (csym.members() != null) {
 922             for (Symbol s : sym.members().getSymbols()) {
 923                 listNested(s, seen);
 924             }
 925         }
 926         if (csym.trans_local != null) {
 927             for (Symbol s : csym.trans_local) {
 928                 listNested(s, seen);
 929             }
 930         }
 931     }
 932 
 933     /** Write "PermittedSubclasses" attribute.
 934      */
 935     int writePermittedSubclassesIfNeeded(ClassSymbol csym) {
 936         if (csym.getPermittedSubclasses().nonEmpty()) {
 937             int alenIdx = writeAttr(names.PermittedSubclasses);
 938             databuf.appendChar(csym.getPermittedSubclasses().size());
 939             for (Type t : csym.getPermittedSubclasses()) {
 940                 databuf.appendChar(poolWriter.putClass((ClassSymbol) t.tsym));
 941             }
 942             endAttr(alenIdx);
 943             return 1;
 944         }
 945         return 0;
 946     }
 947 
 948     /** Write "bootstrapMethods" attribute.
 949      */
 950     void writeBootstrapMethods() {
 951         int alenIdx = writeAttr(names.BootstrapMethods);
 952         int lastBootstrapMethods;
 953         do {
 954             lastBootstrapMethods = poolWriter.bootstrapMethods.size();
 955             for (BsmKey bsmKey : java.util.List.copyOf(poolWriter.bootstrapMethods.keySet())) {
 956                 for (LoadableConstant arg : bsmKey.staticArgs) {
 957                     poolWriter.putConstant(arg);
 958                 }
 959             }
 960         } while (lastBootstrapMethods < poolWriter.bootstrapMethods.size());
 961         databuf.appendChar(poolWriter.bootstrapMethods.size());
 962         for (BsmKey bsmKey : poolWriter.bootstrapMethods.keySet()) {
 963             //write BSM handle
 964             databuf.appendChar(poolWriter.putConstant(bsmKey.bsm));
 965             LoadableConstant[] uniqueArgs = bsmKey.staticArgs;
 966             //write static args length
 967             databuf.appendChar(uniqueArgs.length);
 968             //write static args array
 969             for (LoadableConstant arg : uniqueArgs) {
 970                 databuf.appendChar(poolWriter.putConstant(arg));
 971             }
 972         }
 973         endAttr(alenIdx);
 974     }
 975 
 976     /** Write field symbol, entering all references into constant pool.
 977      */
 978     void writeField(VarSymbol v) {
 979         int flags = adjustFlags(v, v.flags());
 980         databuf.appendChar(flags);
 981         if (dumpFieldModifiers) {
 982             PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
 983             pw.println("FIELD  " + v.name);
 984             pw.println("---" + flagNames(v.flags()));
 985         }
 986         databuf.appendChar(poolWriter.putName(v.name));
 987         databuf.appendChar(poolWriter.putDescriptor(v));
 988         Type fldType = v.erasure(types);
 989         if (fldType.requiresLoadableDescriptors(v.owner)) {
 990             poolWriter.enterLoadableDescriptorsClass(fldType.tsym);
 991             if (preview.isPreview(Source.Feature.VALUE_CLASSES)) {
 992                 preview.markUsesPreview(null);
 993             }
 994         }
 995         int acountIdx = beginAttrs();
 996         int acount = 0;
 997         if (v.getConstValue() != null) {
 998             int alenIdx = writeAttr(names.ConstantValue);
 999             databuf.appendChar(poolWriter.putConstant(v.getConstValue()));
1000             endAttr(alenIdx);
1001             acount++;
1002         }
1003         acount += writeMemberAttrs(v, false);
1004         acount += writeExtraAttributes(v);
1005         endAttrs(acountIdx, acount);
1006     }
1007 
1008     /** Write method symbol, entering all references into constant pool.
1009      */
1010     void writeMethod(MethodSymbol m) {
1011         int flags = adjustFlags(m, m.flags());
1012         databuf.appendChar(flags);
1013         if (dumpMethodModifiers) {
1014             PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1015             pw.println("METHOD  " + m.name);
1016             pw.println("---" + flagNames(m.flags()));
1017         }
1018         databuf.appendChar(poolWriter.putName(m.name));
1019         databuf.appendChar(poolWriter.putDescriptor(m));
1020         MethodType mtype = (MethodType) m.externalType(types);
1021         for (Type t : mtype.getParameterTypes()) {
1022             if (t.requiresLoadableDescriptors(m.owner)) {
1023                 poolWriter.enterLoadableDescriptorsClass(t.tsym);
1024                 if (preview.isPreview(Source.Feature.VALUE_CLASSES)) {
1025                     preview.markUsesPreview(null);
1026                 }
1027             }
1028         }
1029         Type returnType = mtype.getReturnType();
1030         if (returnType.requiresLoadableDescriptors(m.owner)) {
1031             poolWriter.enterLoadableDescriptorsClass(returnType.tsym);
1032             if (preview.isPreview(Source.Feature.VALUE_CLASSES)) {
1033                 preview.markUsesPreview(null);
1034             }
1035         }
1036         int acountIdx = beginAttrs();
1037         int acount = 0;
1038         if (m.code != null) {
1039             int alenIdx = writeAttr(names.Code);
1040             writeCode(m.code);
1041             m.code = null; // to conserve space
1042             endAttr(alenIdx);
1043             acount++;
1044         }
1045         List<Type> thrown = m.erasure(types).getThrownTypes();
1046         if (thrown.nonEmpty()) {
1047             int alenIdx = writeAttr(names.Exceptions);
1048             databuf.appendChar(thrown.length());
1049             for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1050                 databuf.appendChar(poolWriter.putClass(l.head));
1051             endAttr(alenIdx);
1052             acount++;
1053         }
1054         if (m.defaultValue != null) {
1055             int alenIdx = writeAttr(names.AnnotationDefault);
1056             m.defaultValue.accept(awriter);
1057             endAttr(alenIdx);
1058             acount++;
1059         }
1060         if (target.hasMethodParameters()) {
1061             if (!m.isLambdaMethod()) { // Per JDK-8138729, do not emit parameters table for lambda bodies.
1062                 boolean requiresParamNames = requiresParamNames(m);
1063                 if (requiresParamNames || requiresParamFlags(m))
1064                     acount += writeMethodParametersAttr(m, requiresParamNames);
1065             }
1066         }
1067         acount += writeMemberAttrs(m, false);
1068         if (!m.isLambdaMethod())
1069             acount += writeParameterAttrs(m.params);
1070         acount += writeExtraAttributes(m);
1071         endAttrs(acountIdx, acount);
1072     }
1073 
1074     private boolean requiresParamNames(MethodSymbol m) {
1075         if (options.isSet(PARAMETERS))
1076             return true;
1077         if (m.isConstructor() && (m.flags_field & RECORD) != 0)
1078             return true;
1079         return false;
1080     }
1081 
1082     private boolean requiresParamFlags(MethodSymbol m) {
1083         if (!m.extraParams.isEmpty()) {
1084             return m.extraParams.stream().anyMatch(p -> (p.flags_field & (SYNTHETIC | MANDATED)) != 0);
1085         }
1086         if (m.params != null) {
1087             // parameter is stored in params for Enum#valueOf(name)
1088             return m.params.stream().anyMatch(p -> (p.flags_field & (SYNTHETIC | MANDATED)) != 0);
1089         }
1090         return false;
1091     }
1092 
1093     /** Write code attribute of method.
1094      */
1095     void writeCode(Code code) {
1096         databuf.appendChar(code.max_stack);
1097         databuf.appendChar(code.max_locals);
1098         databuf.appendInt(code.cp);
1099         databuf.appendBytes(code.code, 0, code.cp);
1100         databuf.appendChar(code.catchInfo.length());
1101         for (List<char[]> l = code.catchInfo.toList();
1102              l.nonEmpty();
1103              l = l.tail) {
1104             for (int i = 0; i < l.head.length; i++)
1105                 databuf.appendChar(l.head[i]);
1106         }
1107         int acountIdx = beginAttrs();
1108         int acount = 0;
1109 
1110         if (code.lineInfo.nonEmpty()) {
1111             int alenIdx = writeAttr(names.LineNumberTable);
1112             databuf.appendChar(code.lineInfo.length());
1113             for (List<char[]> l = code.lineInfo.reverse();
1114                  l.nonEmpty();
1115                  l = l.tail)
1116                 for (int i = 0; i < l.head.length; i++)
1117                     databuf.appendChar(l.head[i]);
1118             endAttr(alenIdx);
1119             acount++;
1120         }
1121 
1122         if (genCrt && (code.crt != null)) {
1123             CRTable crt = code.crt;
1124             int alenIdx = writeAttr(names.CharacterRangeTable);
1125             int crtIdx = beginAttrs();
1126             int crtEntries = crt.writeCRT(databuf, code.lineMap, log);
1127             endAttrs(crtIdx, crtEntries);
1128             endAttr(alenIdx);
1129             acount++;
1130         }
1131 
1132         // counter for number of generic local variables
1133         if (code.varDebugInfo && code.varBufferSize > 0) {
1134             int nGenericVars = 0;
1135             int alenIdx = writeAttr(names.LocalVariableTable);
1136             databuf.appendChar(code.getLVTSize());
1137             for (int i=0; i<code.varBufferSize; i++) {
1138                 Code.LocalVar var = code.varBuffer[i];
1139 
1140                 for (Code.LocalVar.Range r: var.aliveRanges) {
1141                     // write variable info
1142                     Assert.check(r.start_pc >= 0
1143                             && r.start_pc <= code.cp);
1144                     databuf.appendChar(r.start_pc);
1145                     Assert.check(r.length > 0
1146                             && (r.start_pc + r.length) <= code.cp);
1147                     databuf.appendChar(r.length);
1148                     VarSymbol sym = var.sym;
1149                     databuf.appendChar(poolWriter.putName(sym.name));
1150                     databuf.appendChar(poolWriter.putDescriptor(sym));
1151                     databuf.appendChar(var.reg);
1152                     if (needsLocalVariableTypeEntry(var.sym.type)) {
1153                         nGenericVars++;
1154                     }
1155                 }
1156             }
1157             endAttr(alenIdx);
1158             acount++;
1159 
1160             if (nGenericVars > 0) {
1161                 alenIdx = writeAttr(names.LocalVariableTypeTable);
1162                 databuf.appendChar(nGenericVars);
1163                 int count = 0;
1164 
1165                 for (int i=0; i<code.varBufferSize; i++) {
1166                     Code.LocalVar var = code.varBuffer[i];
1167                     VarSymbol sym = var.sym;
1168                     if (!needsLocalVariableTypeEntry(sym.type))
1169                         continue;
1170                     for (Code.LocalVar.Range r : var.aliveRanges) {
1171                         // write variable info
1172                         databuf.appendChar(r.start_pc);
1173                         databuf.appendChar(r.length);
1174                         databuf.appendChar(poolWriter.putName(sym.name));
1175                         databuf.appendChar(poolWriter.putSignature(sym));
1176                         databuf.appendChar(var.reg);
1177                         count++;
1178                     }
1179                 }
1180                 Assert.check(count == nGenericVars);
1181                 endAttr(alenIdx);
1182                 acount++;
1183             }
1184         }
1185 
1186         if (code.stackMapBufferSize > 0) {
1187             if (debugstackmap) System.out.println("Stack map for " + code.meth);
1188             int alenIdx = writeAttr(code.stackMap.getAttributeName(names));
1189             writeStackMap(code);
1190             endAttr(alenIdx);
1191             acount++;
1192         }
1193 
1194         acount += writeTypeAnnotations(code.meth.getRawTypeAttributes(), true);
1195 
1196         endAttrs(acountIdx, acount);
1197     }
1198     //where
1199     private boolean needsLocalVariableTypeEntry(Type t) {
1200         //a local variable needs a type-entry if its type T is generic
1201         //(i.e. |T| != T) and if it's not an non-denotable type (non-denotable
1202         // types are not supported in signature attribute grammar!)
1203         return !types.isSameType(t, types.erasure(t)) &&
1204                 check.checkDenotable(t);
1205     }
1206 
1207     void writeStackMap(Code code) {
1208         int nframes = code.stackMapBufferSize;
1209         if (debugstackmap) System.out.println(" nframes = " + nframes);
1210         databuf.appendChar(nframes);
1211 
1212         switch (code.stackMap) {
1213         case CLDC:
1214             for (int i=0; i<nframes; i++) {
1215                 if (debugstackmap) System.out.print("  " + i + ":");
1216                 Code.StackMapFrame frame = code.stackMapBuffer[i];
1217 
1218                 // output PC
1219                 if (debugstackmap) System.out.print(" pc=" + frame.pc);
1220                 databuf.appendChar(frame.pc);
1221 
1222                 // output locals
1223                 int localCount = 0;
1224                 for (int j=0; j<frame.locals.length;
1225                      j += Code.width(frame.locals[j])) {
1226                     localCount++;
1227                 }
1228                 if (debugstackmap) System.out.print(" nlocals=" +
1229                                                     localCount);
1230                 databuf.appendChar(localCount);
1231                 for (int j=0; j<frame.locals.length;
1232                      j += Code.width(frame.locals[j])) {
1233                     if (debugstackmap) System.out.print(" local[" + j + "]=");
1234                     writeStackMapType(frame.locals[j]);
1235                 }
1236 
1237                 // output stack
1238                 int stackCount = 0;
1239                 for (int j=0; j<frame.stack.length;
1240                      j += Code.width(frame.stack[j])) {
1241                     stackCount++;
1242                 }
1243                 if (debugstackmap) System.out.print(" nstack=" +
1244                                                     stackCount);
1245                 databuf.appendChar(stackCount);
1246                 for (int j=0; j<frame.stack.length;
1247                      j += Code.width(frame.stack[j])) {
1248                     if (debugstackmap) System.out.print(" stack[" + j + "]=");
1249                     writeStackMapType(frame.stack[j]);
1250                 }
1251                 if (debugstackmap) System.out.println();
1252             }
1253             break;
1254         case JSR202: {
1255             Assert.checkNull(code.stackMapBuffer);
1256             for (int i=0; i<nframes; i++) {
1257                 if (debugstackmap) System.out.print("  " + i + ":");
1258                 StackMapTableFrame frame = code.stackMapTableBuffer[i];
1259                 frame.write(this);
1260                 if (debugstackmap) System.out.println();
1261             }
1262             break;
1263         }
1264         default:
1265             throw new AssertionError("Unexpected stackmap format value");
1266         }
1267     }
1268 
1269         //where
1270         void writeStackMapType(Type t) {
1271             if (t == null) {
1272                 if (debugstackmap) System.out.print("empty");
1273                 databuf.appendByte(0);
1274             }
1275             else switch(t.getTag()) {
1276             case BYTE:
1277             case CHAR:
1278             case SHORT:
1279             case INT:
1280             case BOOLEAN:
1281                 if (debugstackmap) System.out.print("int");
1282                 databuf.appendByte(1);
1283                 break;
1284             case FLOAT:
1285                 if (debugstackmap) System.out.print("float");
1286                 databuf.appendByte(2);
1287                 break;
1288             case DOUBLE:
1289                 if (debugstackmap) System.out.print("double");
1290                 databuf.appendByte(3);
1291                 break;
1292             case LONG:
1293                 if (debugstackmap) System.out.print("long");
1294                 databuf.appendByte(4);
1295                 break;
1296             case BOT: // null
1297                 if (debugstackmap) System.out.print("null");
1298                 databuf.appendByte(5);
1299                 break;
1300             case CLASS:
1301             case ARRAY:
1302             case TYPEVAR:
1303                 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")");
1304                 databuf.appendByte(7);
1305                 databuf.appendChar(poolWriter.putClass(types.erasure(t)));
1306                 break;
1307             case UNINITIALIZED_THIS:
1308                 if (debugstackmap) System.out.print("uninit_this");
1309                 databuf.appendByte(6);
1310                 break;
1311             case UNINITIALIZED_OBJECT:
1312                 { UninitializedType uninitType = (UninitializedType)t;
1313                 databuf.appendByte(8);
1314                 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset);
1315                 databuf.appendChar(uninitType.offset);
1316                 }
1317                 break;
1318             default:
1319                 throw new AssertionError();
1320             }
1321         }
1322 
1323     /** An entry in the JSR202 StackMapTable */
1324     abstract static class StackMapTableFrame {
1325         abstract int getFrameType();
1326 
1327         void write(ClassWriter writer) {
1328             int frameType = getFrameType();
1329             writer.databuf.appendByte(frameType);
1330             if (writer.debugstackmap) System.out.print(" frame_type=" + frameType);
1331         }
1332 
1333         static class SameFrame extends StackMapTableFrame {
1334             final int offsetDelta;
1335             SameFrame(int offsetDelta) {
1336                 this.offsetDelta = offsetDelta;
1337             }
1338             int getFrameType() {
1339                 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED;
1340             }
1341             @Override
1342             void write(ClassWriter writer) {
1343                 super.write(writer);
1344                 if (getFrameType() == SAME_FRAME_EXTENDED) {
1345                     writer.databuf.appendChar(offsetDelta);
1346                     if (writer.debugstackmap){
1347                         System.out.print(" offset_delta=" + offsetDelta);
1348                     }
1349                 }
1350             }
1351         }
1352 
1353         static class SameLocals1StackItemFrame extends StackMapTableFrame {
1354             final int offsetDelta;
1355             final Type stack;
1356             SameLocals1StackItemFrame(int offsetDelta, Type stack) {
1357                 this.offsetDelta = offsetDelta;
1358                 this.stack = stack;
1359             }
1360             int getFrameType() {
1361                 return (offsetDelta < SAME_FRAME_SIZE) ?
1362                        (SAME_FRAME_SIZE + offsetDelta) :
1363                        SAME_LOCALS_1_STACK_ITEM_EXTENDED;
1364             }
1365             @Override
1366             void write(ClassWriter writer) {
1367                 super.write(writer);
1368                 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) {
1369                     writer.databuf.appendChar(offsetDelta);
1370                     if (writer.debugstackmap) {
1371                         System.out.print(" offset_delta=" + offsetDelta);
1372                     }
1373                 }
1374                 if (writer.debugstackmap) {
1375                     System.out.print(" stack[" + 0 + "]=");
1376                 }
1377                 writer.writeStackMapType(stack);
1378             }
1379         }
1380 
1381         static class ChopFrame extends StackMapTableFrame {
1382             final int frameType;
1383             final int offsetDelta;
1384             ChopFrame(int frameType, int offsetDelta) {
1385                 this.frameType = frameType;
1386                 this.offsetDelta = offsetDelta;
1387             }
1388             int getFrameType() { return frameType; }
1389             @Override
1390             void write(ClassWriter writer) {
1391                 super.write(writer);
1392                 writer.databuf.appendChar(offsetDelta);
1393                 if (writer.debugstackmap) {
1394                     System.out.print(" offset_delta=" + offsetDelta);
1395                 }
1396             }
1397         }
1398 
1399         static class AppendFrame extends StackMapTableFrame {
1400             final int frameType;
1401             final int offsetDelta;
1402             final Type[] locals;
1403             AppendFrame(int frameType, int offsetDelta, Type[] locals) {
1404                 this.frameType = frameType;
1405                 this.offsetDelta = offsetDelta;
1406                 this.locals = locals;
1407             }
1408             int getFrameType() { return frameType; }
1409             @Override
1410             void write(ClassWriter writer) {
1411                 super.write(writer);
1412                 writer.databuf.appendChar(offsetDelta);
1413                 if (writer.debugstackmap) {
1414                     System.out.print(" offset_delta=" + offsetDelta);
1415                 }
1416                 for (int i=0; i<locals.length; i++) {
1417                      if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1418                      writer.writeStackMapType(locals[i]);
1419                 }
1420             }
1421         }
1422 
1423         static class FullFrame extends StackMapTableFrame {
1424             final int offsetDelta;
1425             final Type[] locals;
1426             final Type[] stack;
1427             FullFrame(int offsetDelta, Type[] locals, Type[] stack) {
1428                 this.offsetDelta = offsetDelta;
1429                 this.locals = locals;
1430                 this.stack = stack;
1431             }
1432             int getFrameType() { return FULL_FRAME; }
1433             @Override
1434             void write(ClassWriter writer) {
1435                 super.write(writer);
1436                 writer.databuf.appendChar(offsetDelta);
1437                 writer.databuf.appendChar(locals.length);
1438                 if (writer.debugstackmap) {
1439                     System.out.print(" offset_delta=" + offsetDelta);
1440                     System.out.print(" nlocals=" + locals.length);
1441                 }
1442                 for (int i=0; i<locals.length; i++) {
1443                     if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1444                     writer.writeStackMapType(locals[i]);
1445                 }
1446 
1447                 writer.databuf.appendChar(stack.length);
1448                 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); }
1449                 for (int i=0; i<stack.length; i++) {
1450                     if (writer.debugstackmap) System.out.print(" stack[" + i + "]=");
1451                     writer.writeStackMapType(stack[i]);
1452                 }
1453             }
1454         }
1455 
1456        /** Compare this frame with the previous frame and produce
1457         *  an entry of compressed stack map frame. */
1458         static StackMapTableFrame getInstance(Code.StackMapFrame this_frame,
1459                                               int prev_pc,
1460                                               Type[] prev_locals,
1461                                               Types types) {
1462             Type[] locals = this_frame.locals;
1463             Type[] stack = this_frame.stack;
1464             int offset_delta = this_frame.pc - prev_pc - 1;
1465             if (stack.length == 1) {
1466                 if (locals.length == prev_locals.length
1467                     && compare(prev_locals, locals, types) == 0) {
1468                     return new SameLocals1StackItemFrame(offset_delta, stack[0]);
1469                 }
1470             } else if (stack.length == 0) {
1471                 int diff_length = compare(prev_locals, locals, types);
1472                 if (diff_length == 0) {
1473                     return new SameFrame(offset_delta);
1474                 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) {
1475                     // APPEND
1476                     Type[] local_diff = new Type[-diff_length];
1477                     for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) {
1478                         local_diff[j] = locals[i];
1479                     }
1480                     return new AppendFrame(SAME_FRAME_EXTENDED - diff_length,
1481                                            offset_delta,
1482                                            local_diff);
1483                 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) {
1484                     // CHOP
1485                     return new ChopFrame(SAME_FRAME_EXTENDED - diff_length,
1486                                          offset_delta);
1487                 }
1488             }
1489             // FULL_FRAME
1490             return new FullFrame(offset_delta, locals, stack);
1491         }
1492 
1493         static boolean isInt(Type t) {
1494             return (t.getTag().isStrictSubRangeOf(INT)  || t.hasTag(BOOLEAN));
1495         }
1496 
1497         static boolean isSameType(Type t1, Type t2, Types types) {
1498             if (t1 == null) { return t2 == null; }
1499             if (t2 == null) { return false; }
1500 
1501             if (isInt(t1) && isInt(t2)) { return true; }
1502 
1503             if (t1.hasTag(UNINITIALIZED_THIS)) {
1504                 return t2.hasTag(UNINITIALIZED_THIS);
1505             } else if (t1.hasTag(UNINITIALIZED_OBJECT)) {
1506                 if (t2.hasTag(UNINITIALIZED_OBJECT)) {
1507                     return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset;
1508                 } else {
1509                     return false;
1510                 }
1511             } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) {
1512                 return false;
1513             }
1514 
1515             return types.isSameType(t1, t2);
1516         }
1517 
1518         static int compare(Type[] arr1, Type[] arr2, Types types) {
1519             int diff_length = arr1.length - arr2.length;
1520             if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) {
1521                 return Integer.MAX_VALUE;
1522             }
1523             int len = (diff_length > 0) ? arr2.length : arr1.length;
1524             for (int i=0; i<len; i++) {
1525                 if (!isSameType(arr1[i], arr2[i], types)) {
1526                     return Integer.MAX_VALUE;
1527                 }
1528             }
1529             return diff_length;
1530         }
1531     }
1532 
1533     void writeFields(Scope s) {
1534         // process them in reverse sibling order;
1535         // i.e., process them in declaration order.
1536         List<VarSymbol> vars = List.nil();
1537         for (Symbol sym : s.getSymbols(NON_RECURSIVE)) {
1538             if (sym.kind == VAR) vars = vars.prepend((VarSymbol)sym);
1539         }
1540         while (vars.nonEmpty()) {
1541             writeField(vars.head);
1542             vars = vars.tail;
1543         }
1544     }
1545 
1546     void writeMethods(Scope s) {
1547         List<MethodSymbol> methods = List.nil();
1548         for (Symbol sym : s.getSymbols(NON_RECURSIVE)) {
1549             if (sym.kind == MTH && (sym.flags() & HYPOTHETICAL) == 0)
1550                 methods = methods.prepend((MethodSymbol)sym);
1551         }
1552         while (methods.nonEmpty()) {
1553             writeMethod(methods.head);
1554             methods = methods.tail;
1555         }
1556     }
1557 
1558     /** Emit a class file for a given class.
1559      *  @param c      The class from which a class file is generated.
1560      */
1561     public JavaFileObject writeClass(ClassSymbol c)
1562         throws IOException, PoolOverflow, StringOverflow
1563     {
1564         String name = (c.owner.kind == MDL ? c.name : c.flatname).toString();
1565         Location outLocn;
1566         if (multiModuleMode) {
1567             ModuleSymbol msym = c.owner.kind == MDL ? (ModuleSymbol) c.owner : c.packge().modle;
1568             outLocn = fileManager.getLocationForModule(CLASS_OUTPUT, msym.name.toString());
1569         } else {
1570             outLocn = CLASS_OUTPUT;
1571         }
1572         JavaFileObject outFile
1573             = fileManager.getJavaFileForOutput(outLocn,
1574                                                name,
1575                                                JavaFileObject.Kind.CLASS,
1576                                                c.sourcefile);
1577         OutputStream out = outFile.openOutputStream();
1578         try {
1579             writeClassFile(out, c);
1580             if (verbose)
1581                 log.printVerbose("wrote.file", outFile.getName());
1582             out.close();
1583             out = null;
1584         } catch (InvalidSignatureException ex) {
1585             log.error(Errors.CannotGenerateClass(c, Fragments.IllegalSignature(c, ex.type())));
1586         } finally {
1587             if (out != null) {
1588                 // if we are propagating an exception, delete the file
1589                 out.close();
1590                 outFile.delete();
1591                 outFile = null;
1592             }
1593         }
1594         return outFile; // may be null if write failed
1595     }
1596 
1597     /** Write class `c' to outstream `out'.
1598      */
1599     public void writeClassFile(OutputStream out, ClassSymbol c)
1600         throws IOException, PoolOverflow, StringOverflow {
1601         Assert.check((c.flags() & COMPOUND) == 0);
1602         databuf.reset();
1603         poolbuf.reset();
1604 
1605         Type supertype = types.supertype(c.type);
1606         List<Type> interfaces = types.interfaces(c.type);
1607         List<Type> typarams = c.type.getTypeArguments();
1608 
1609         int flags;
1610         if (c.owner.kind == MDL) {
1611             flags = ACC_MODULE;
1612         } else {
1613             long originalFlags = c.flags();
1614             flags = adjustFlags(c, c.flags() & ~(DEFAULT | STRICTFP));
1615             if ((flags & PROTECTED) != 0) flags |= PUBLIC;
1616             flags = flags & ClassFlags;
1617             flags |= (originalFlags & IDENTITY_TYPE) != 0 ? ACC_IDENTITY : flags;
1618         }
1619 
1620         if (dumpClassModifiers) {
1621             PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1622             pw.println();
1623             pw.println("CLASSFILE  " + c.getQualifiedName());
1624             pw.println("---" + flagNames(flags));
1625         }
1626         databuf.appendChar(flags);
1627 
1628         if (c.owner.kind == MDL) {
1629             PackageSymbol unnamed = ((ModuleSymbol) c.owner).unnamedPackage;
1630             databuf.appendChar(poolWriter.putClass(new ClassSymbol(0, names.module_info, unnamed)));
1631         } else {
1632             databuf.appendChar(poolWriter.putClass(c));
1633         }
1634         databuf.appendChar(supertype.hasTag(CLASS) ? poolWriter.putClass((ClassSymbol)supertype.tsym) : 0);
1635         databuf.appendChar(interfaces.length());
1636         for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1637             databuf.appendChar(poolWriter.putClass((ClassSymbol)l.head.tsym));
1638         int fieldsCount = 0;
1639         int methodsCount = 0;
1640         for (Symbol sym : c.members().getSymbols(NON_RECURSIVE)) {
1641             switch (sym.kind) {
1642             case VAR: fieldsCount++; break;
1643             case MTH: if ((sym.flags() & HYPOTHETICAL) == 0) methodsCount++;
1644                       break;
1645             case TYP: poolWriter.enterInner((ClassSymbol)sym); break;
1646             default : Assert.error();
1647             }
1648         }
1649 
1650         if (c.trans_local != null) {
1651             for (ClassSymbol local : c.trans_local) {
1652                 poolWriter.enterInner(local);
1653             }
1654         }
1655 
1656         databuf.appendChar(fieldsCount);
1657         writeFields(c.members());
1658         databuf.appendChar(methodsCount);
1659         writeMethods(c.members());
1660 
1661         int acountIdx = beginAttrs();
1662         int acount = 0;
1663 
1664         boolean sigReq =
1665             typarams.length() != 0 || supertype.allparams().length() != 0;
1666         for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail)
1667             sigReq = l.head.allparams().length() != 0;
1668         if (sigReq) {
1669             int alenIdx = writeAttr(names.Signature);
1670             databuf.appendChar(poolWriter.putSignature(c));
1671             endAttr(alenIdx);
1672             acount++;
1673         }
1674 
1675         if (c.sourcefile != null && emitSourceFile) {
1676             int alenIdx = writeAttr(names.SourceFile);
1677             // WHM 6/29/1999: Strip file path prefix.  We do it here at
1678             // the last possible moment because the sourcefile may be used
1679             // elsewhere in error diagnostics. Fixes 4241573.
1680             String simpleName = PathFileObject.getSimpleName(c.sourcefile);
1681             databuf.appendChar(poolWriter.putName(names.fromString(simpleName)));
1682             endAttr(alenIdx);
1683             acount++;
1684         }
1685 
1686         if (genCrt) {
1687             // Append SourceID attribute
1688             int alenIdx = writeAttr(names.SourceID);
1689             databuf.appendChar(poolWriter.putName(names.fromString(Long.toString(getLastModified(c.sourcefile)))));
1690             endAttr(alenIdx);
1691             acount++;
1692             // Append CompilationID attribute
1693             alenIdx = writeAttr(names.CompilationID);
1694             databuf.appendChar(poolWriter.putName(names.fromString(Long.toString(System.currentTimeMillis()))));
1695             endAttr(alenIdx);
1696             acount++;
1697         }
1698 
1699         acount += writeFlagAttrs(c.flags());
1700         acount += writeJavaAnnotations(c.getRawAttributes());
1701         acount += writeTypeAnnotations(c.getRawTypeAttributes(), false);
1702         acount += writeEnclosingMethodAttribute(c);
1703         if (c.owner.kind == MDL) {
1704             acount += writeModuleAttribute(c);
1705             acount += writeFlagAttrs(c.owner.flags() & ~DEPRECATED);
1706         }
1707         acount += writeExtraClassAttributes(c);
1708         acount += writeExtraAttributes(c);
1709 
1710         poolbuf.appendInt(JAVA_MAGIC);
1711         if (preview.isEnabled() && preview.usesPreview(c.sourcefile)) {
1712             poolbuf.appendChar(ClassFile.PREVIEW_MINOR_VERSION);
1713         } else {
1714             poolbuf.appendChar(target.minorVersion);
1715         }
1716         poolbuf.appendChar(target.majorVersion);
1717 
1718         if (c.owner.kind != MDL) {
1719             if (target.hasNestmateAccess()) {
1720                 acount += writeNestMembersIfNeeded(c);
1721                 acount += writeNestHostIfNeeded(c);
1722             }
1723         }
1724 
1725         if (c.isRecord()) {
1726             acount += writeRecordAttribute(c);
1727         }
1728 
1729         if (target.hasSealedClasses()) {
1730             acount += writePermittedSubclassesIfNeeded(c);
1731         }
1732 
1733         if (!poolWriter.bootstrapMethods.isEmpty()) {
1734             writeBootstrapMethods();
1735             acount++;
1736         }
1737 
1738         if (!poolWriter.innerClasses.isEmpty()) {
1739             writeInnerClasses();
1740             acount++;
1741         }
1742 
1743         if (!poolWriter.loadableDescriptors.isEmpty()) {
1744             writeLoadableDescriptorsAttribute();
1745             acount++;
1746         }
1747 
1748         endAttrs(acountIdx, acount);
1749 
1750         out.write(poolbuf.elems, 0, poolbuf.length);
1751 
1752         poolWriter.writePool(out);
1753         poolWriter.reset(); // to save space
1754 
1755         out.write(databuf.elems, 0, databuf.length);
1756     }
1757 
1758      /**Allows subclasses to write additional class attributes
1759       *
1760       * @return the number of attributes written
1761       */
1762     protected int writeExtraClassAttributes(ClassSymbol c) {
1763         return 0;
1764     }
1765 
1766     /**Allows friends to write additional attributes
1767      *
1768      * @return the number of attributes written
1769      */
1770     protected int writeExtraAttributes(Symbol sym) {
1771         int i = 0;
1772         for (ToIntFunction<Symbol> hook : extraAttributeHooks) {
1773             i += hook.applyAsInt(sym);
1774         }
1775         return i;
1776     }
1777 
1778     int adjustFlags(Symbol sym, final long flags) {
1779         int result = (int)flags;
1780 
1781         // Elide strictfp bit in class files
1782         if (target.obsoleteAccStrict())
1783             result &= ~STRICTFP;
1784 
1785         if ((flags & BRIDGE) != 0)
1786             result |= ACC_BRIDGE;
1787         if ((flags & VARARGS) != 0)
1788             result |= ACC_VARARGS;
1789         if ((flags & DEFAULT) != 0)
1790             result &= ~ABSTRACT;
1791         if ((flags & IDENTITY_TYPE) != 0) {
1792             result |= ACC_IDENTITY;
1793         }
1794         if (sym.kind == VAR) {
1795             if ((flags & STRICT) != 0) {
1796                 result |= ACC_STRICT;
1797             }
1798         }
1799         return result;
1800     }
1801 
1802     long getLastModified(FileObject filename) {
1803         long mod = 0;
1804         try {
1805             mod = filename.getLastModified();
1806         } catch (SecurityException e) {
1807             throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage());
1808         }
1809         return mod;
1810     }
1811 }