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