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