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