Mon, 21 Jan 2013 20:15:16 +0000
8005851: Remove support for synchronized interface methods
Summary: Synchronized default methods are no longer supported
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2012, 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 */
26 package com.sun.tools.javac.jvm;
28 import java.io.*;
29 import java.util.LinkedHashMap;
30 import java.util.Map;
31 import java.util.Set;
32 import java.util.HashSet;
34 import javax.tools.JavaFileManager;
35 import javax.tools.FileObject;
36 import javax.tools.JavaFileObject;
38 import com.sun.tools.javac.code.*;
39 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
40 import com.sun.tools.javac.code.Symbol.*;
41 import com.sun.tools.javac.code.Type.*;
42 import com.sun.tools.javac.code.Types.UniqueType;
43 import com.sun.tools.javac.file.BaseFileObject;
44 import com.sun.tools.javac.jvm.Pool.DynamicMethod;
45 import com.sun.tools.javac.jvm.Pool.Method;
46 import com.sun.tools.javac.jvm.Pool.MethodHandle;
47 import com.sun.tools.javac.jvm.Pool.Variable;
48 import com.sun.tools.javac.util.*;
50 import static com.sun.tools.javac.code.BoundKind.*;
51 import static com.sun.tools.javac.code.Flags.*;
52 import static com.sun.tools.javac.code.Kinds.*;
53 import static com.sun.tools.javac.code.TypeTag.*;
54 import static com.sun.tools.javac.jvm.UninitializedType.*;
55 import static com.sun.tools.javac.main.Option.*;
56 import static javax.tools.StandardLocation.CLASS_OUTPUT;
59 /** This class provides operations to map an internal symbol table graph
60 * rooted in a ClassSymbol into a classfile.
61 *
62 * <p><b>This is NOT part of any supported API.
63 * If you write code that depends on this, you do so at your own risk.
64 * This code and its internal interfaces are subject to change or
65 * deletion without notice.</b>
66 */
67 public class ClassWriter extends ClassFile {
68 protected static final Context.Key<ClassWriter> classWriterKey =
69 new Context.Key<ClassWriter>();
71 private final Symtab syms;
73 private final Options options;
75 /** Switch: verbose output.
76 */
77 private boolean verbose;
79 /** Switch: scramble private names.
80 */
81 private boolean scramble;
83 /** Switch: scramble private names.
84 */
85 private boolean scrambleAll;
87 /** Switch: retrofit mode.
88 */
89 private boolean retrofit;
91 /** Switch: emit source file attribute.
92 */
93 private boolean emitSourceFile;
95 /** Switch: generate CharacterRangeTable attribute.
96 */
97 private boolean genCrt;
99 /** Switch: describe the generated stackmap
100 */
101 boolean debugstackmap;
103 /**
104 * Target class version.
105 */
106 private Target target;
108 /**
109 * Source language version.
110 */
111 private Source source;
113 /** Type utilities. */
114 private Types types;
116 /** The initial sizes of the data and constant pool buffers.
117 * sizes are increased when buffers get full.
118 */
119 static final int DATA_BUF_SIZE = 0x0fff0;
120 static final int POOL_BUF_SIZE = 0x1fff0;
122 /** An output buffer for member info.
123 */
124 ByteBuffer databuf = new ByteBuffer(DATA_BUF_SIZE);
126 /** An output buffer for the constant pool.
127 */
128 ByteBuffer poolbuf = new ByteBuffer(POOL_BUF_SIZE);
130 /** An output buffer for type signatures.
131 */
132 ByteBuffer sigbuf = new ByteBuffer();
134 /** The constant pool.
135 */
136 Pool pool;
138 /** The inner classes to be written, as a set.
139 */
140 Set<ClassSymbol> innerClasses;
142 /** The inner classes to be written, as a queue where
143 * enclosing classes come first.
144 */
145 ListBuffer<ClassSymbol> innerClassesQueue;
147 /** The bootstrap methods to be written in the corresponding class attribute
148 * (one for each invokedynamic)
149 */
150 Map<DynamicMethod, MethodHandle> bootstrapMethods;
152 /** The log to use for verbose output.
153 */
154 private final Log log;
156 /** The name table. */
157 private final Names names;
159 /** Access to files. */
160 private final JavaFileManager fileManager;
162 /** The tags and constants used in compressed stackmap. */
163 static final int SAME_FRAME_SIZE = 64;
164 static final int SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247;
165 static final int SAME_FRAME_EXTENDED = 251;
166 static final int FULL_FRAME = 255;
167 static final int MAX_LOCAL_LENGTH_DIFF = 4;
169 /** Get the ClassWriter instance for this context. */
170 public static ClassWriter instance(Context context) {
171 ClassWriter instance = context.get(classWriterKey);
172 if (instance == null)
173 instance = new ClassWriter(context);
174 return instance;
175 }
177 /** Construct a class writer, given an options table.
178 */
179 protected ClassWriter(Context context) {
180 context.put(classWriterKey, this);
182 log = Log.instance(context);
183 names = Names.instance(context);
184 syms = Symtab.instance(context);
185 options = Options.instance(context);
186 target = Target.instance(context);
187 source = Source.instance(context);
188 types = Types.instance(context);
189 fileManager = context.get(JavaFileManager.class);
191 verbose = options.isSet(VERBOSE);
192 scramble = options.isSet("-scramble");
193 scrambleAll = options.isSet("-scrambleAll");
194 retrofit = options.isSet("-retrofit");
195 genCrt = options.isSet(XJCOV);
196 debugstackmap = options.isSet("debugstackmap");
198 emitSourceFile = options.isUnset(G_CUSTOM) ||
199 options.isSet(G_CUSTOM, "source");
201 String dumpModFlags = options.get("dumpmodifiers");
202 dumpClassModifiers =
203 (dumpModFlags != null && dumpModFlags.indexOf('c') != -1);
204 dumpFieldModifiers =
205 (dumpModFlags != null && dumpModFlags.indexOf('f') != -1);
206 dumpInnerClassModifiers =
207 (dumpModFlags != null && dumpModFlags.indexOf('i') != -1);
208 dumpMethodModifiers =
209 (dumpModFlags != null && dumpModFlags.indexOf('m') != -1);
210 }
212 /******************************************************************
213 * Diagnostics: dump generated class names and modifiers
214 ******************************************************************/
216 /** Value of option 'dumpmodifiers' is a string
217 * indicating which modifiers should be dumped for debugging:
218 * 'c' -- classes
219 * 'f' -- fields
220 * 'i' -- innerclass attributes
221 * 'm' -- methods
222 * For example, to dump everything:
223 * javac -XDdumpmodifiers=cifm MyProg.java
224 */
225 private final boolean dumpClassModifiers; // -XDdumpmodifiers=c
226 private final boolean dumpFieldModifiers; // -XDdumpmodifiers=f
227 private final boolean dumpInnerClassModifiers; // -XDdumpmodifiers=i
228 private final boolean dumpMethodModifiers; // -XDdumpmodifiers=m
231 /** Return flags as a string, separated by " ".
232 */
233 public static String flagNames(long flags) {
234 StringBuilder sbuf = new StringBuilder();
235 int i = 0;
236 long f = flags & StandardFlags;
237 while (f != 0) {
238 if ((f & 1) != 0) {
239 sbuf.append(" ");
240 sbuf.append(flagName[i]);
241 }
242 f = f >> 1;
243 i++;
244 }
245 return sbuf.toString();
246 }
247 //where
248 private final static String[] flagName = {
249 "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL",
250 "SUPER", "VOLATILE", "TRANSIENT", "NATIVE", "INTERFACE",
251 "ABSTRACT", "STRICTFP"};
253 /******************************************************************
254 * Output routines
255 ******************************************************************/
257 /** Write a character into given byte buffer;
258 * byte buffer will not be grown.
259 */
260 void putChar(ByteBuffer buf, int op, int x) {
261 buf.elems[op ] = (byte)((x >> 8) & 0xFF);
262 buf.elems[op+1] = (byte)((x ) & 0xFF);
263 }
265 /** Write an integer into given byte buffer;
266 * byte buffer will not be grown.
267 */
268 void putInt(ByteBuffer buf, int adr, int x) {
269 buf.elems[adr ] = (byte)((x >> 24) & 0xFF);
270 buf.elems[adr+1] = (byte)((x >> 16) & 0xFF);
271 buf.elems[adr+2] = (byte)((x >> 8) & 0xFF);
272 buf.elems[adr+3] = (byte)((x ) & 0xFF);
273 }
275 /******************************************************************
276 * Signature Generation
277 ******************************************************************/
279 /** Assemble signature of given type in string buffer.
280 */
281 void assembleSig(Type type) {
282 switch (type.getTag()) {
283 case BYTE:
284 sigbuf.appendByte('B');
285 break;
286 case SHORT:
287 sigbuf.appendByte('S');
288 break;
289 case CHAR:
290 sigbuf.appendByte('C');
291 break;
292 case INT:
293 sigbuf.appendByte('I');
294 break;
295 case LONG:
296 sigbuf.appendByte('J');
297 break;
298 case FLOAT:
299 sigbuf.appendByte('F');
300 break;
301 case DOUBLE:
302 sigbuf.appendByte('D');
303 break;
304 case BOOLEAN:
305 sigbuf.appendByte('Z');
306 break;
307 case VOID:
308 sigbuf.appendByte('V');
309 break;
310 case CLASS:
311 sigbuf.appendByte('L');
312 assembleClassSig(type);
313 sigbuf.appendByte(';');
314 break;
315 case ARRAY:
316 ArrayType at = (ArrayType)type;
317 sigbuf.appendByte('[');
318 assembleSig(at.elemtype);
319 break;
320 case METHOD:
321 MethodType mt = (MethodType)type;
322 sigbuf.appendByte('(');
323 assembleSig(mt.argtypes);
324 sigbuf.appendByte(')');
325 assembleSig(mt.restype);
326 if (hasTypeVar(mt.thrown)) {
327 for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
328 sigbuf.appendByte('^');
329 assembleSig(l.head);
330 }
331 }
332 break;
333 case WILDCARD: {
334 WildcardType ta = (WildcardType) type;
335 switch (ta.kind) {
336 case SUPER:
337 sigbuf.appendByte('-');
338 assembleSig(ta.type);
339 break;
340 case EXTENDS:
341 sigbuf.appendByte('+');
342 assembleSig(ta.type);
343 break;
344 case UNBOUND:
345 sigbuf.appendByte('*');
346 break;
347 default:
348 throw new AssertionError(ta.kind);
349 }
350 break;
351 }
352 case TYPEVAR:
353 sigbuf.appendByte('T');
354 sigbuf.appendName(type.tsym.name);
355 sigbuf.appendByte(';');
356 break;
357 case FORALL:
358 ForAll ft = (ForAll)type;
359 assembleParamsSig(ft.tvars);
360 assembleSig(ft.qtype);
361 break;
362 case UNINITIALIZED_THIS:
363 case UNINITIALIZED_OBJECT:
364 // we don't yet have a spec for uninitialized types in the
365 // local variable table
366 assembleSig(types.erasure(((UninitializedType)type).qtype));
367 break;
368 default:
369 throw new AssertionError("typeSig " + type.getTag());
370 }
371 }
373 boolean hasTypeVar(List<Type> l) {
374 while (l.nonEmpty()) {
375 if (l.head.hasTag(TYPEVAR)) return true;
376 l = l.tail;
377 }
378 return false;
379 }
381 void assembleClassSig(Type type) {
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 }
409 void assembleSig(List<Type> types) {
410 for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail)
411 assembleSig(ts.head);
412 }
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 }
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 }
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 }
456 /******************************************************************
457 * Writing the Constant Pool
458 ******************************************************************/
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 }
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;
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 }
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 }
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 }
606 /******************************************************************
607 * Writing Attributes
608 ******************************************************************/
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 }
619 /** Fill in attribute length.
620 */
621 void endAttr(int index) {
622 putInt(databuf, index - 4, databuf.length - index);
623 }
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 }
633 /** Fill in number of attributes.
634 */
635 void endAttrs(int index, int count) {
636 putChar(databuf, index - 2, count);
637 }
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 }
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;
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 }
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 }
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 return acount;
726 }
728 /**
729 * Write method parameter names attribute.
730 */
731 int writeMethodParametersAttr(MethodSymbol m) {
732 if (m.params != null && 0 != m.params.length()) {
733 int attrIndex = writeAttr(names.MethodParameters);
734 databuf.appendByte(m.params.length());
735 for (VarSymbol s : m.params) {
736 // TODO: expand to cover synthesized, once we figure out
737 // how to represent that.
738 final int flags = (int) s.flags() & (FINAL | SYNTHETIC);
739 // output parameter info
740 databuf.appendChar(pool.put(s.name));
741 databuf.appendInt(flags);
742 }
743 endAttr(attrIndex);
744 return 1;
745 } else
746 return 0;
747 }
750 /** Write method parameter annotations;
751 * return number of attributes written.
752 */
753 int writeParameterAttrs(MethodSymbol m) {
754 boolean hasVisible = false;
755 boolean hasInvisible = false;
756 if (m.params != null) for (VarSymbol s : m.params) {
757 for (Attribute.Compound a : s.getRawAttributes()) {
758 switch (types.getRetention(a)) {
759 case SOURCE: break;
760 case CLASS: hasInvisible = true; break;
761 case RUNTIME: hasVisible = true; break;
762 default: ;// /* fail soft */ throw new AssertionError(vis);
763 }
764 }
765 }
767 int attrCount = 0;
768 if (hasVisible) {
769 int attrIndex = writeAttr(names.RuntimeVisibleParameterAnnotations);
770 databuf.appendByte(m.params.length());
771 for (VarSymbol s : m.params) {
772 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
773 for (Attribute.Compound a : s.getRawAttributes())
774 if (types.getRetention(a) == RetentionPolicy.RUNTIME)
775 buf.append(a);
776 databuf.appendChar(buf.length());
777 for (Attribute.Compound a : buf)
778 writeCompoundAttribute(a);
779 }
780 endAttr(attrIndex);
781 attrCount++;
782 }
783 if (hasInvisible) {
784 int attrIndex = writeAttr(names.RuntimeInvisibleParameterAnnotations);
785 databuf.appendByte(m.params.length());
786 for (VarSymbol s : m.params) {
787 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
788 for (Attribute.Compound a : s.getRawAttributes())
789 if (types.getRetention(a) == RetentionPolicy.CLASS)
790 buf.append(a);
791 databuf.appendChar(buf.length());
792 for (Attribute.Compound a : buf)
793 writeCompoundAttribute(a);
794 }
795 endAttr(attrIndex);
796 attrCount++;
797 }
798 return attrCount;
799 }
801 /**********************************************************************
802 * Writing Java-language annotations (aka metadata, attributes)
803 **********************************************************************/
805 /** Write Java-language annotations; return number of JVM
806 * attributes written (zero or one).
807 */
808 int writeJavaAnnotations(List<Attribute.Compound> attrs) {
809 if (attrs.isEmpty()) return 0;
810 ListBuffer<Attribute.Compound> visibles = new ListBuffer<Attribute.Compound>();
811 ListBuffer<Attribute.Compound> invisibles = new ListBuffer<Attribute.Compound>();
812 for (Attribute.Compound a : attrs) {
813 switch (types.getRetention(a)) {
814 case SOURCE: break;
815 case CLASS: invisibles.append(a); break;
816 case RUNTIME: visibles.append(a); break;
817 default: ;// /* fail soft */ throw new AssertionError(vis);
818 }
819 }
821 int attrCount = 0;
822 if (visibles.length() != 0) {
823 int attrIndex = writeAttr(names.RuntimeVisibleAnnotations);
824 databuf.appendChar(visibles.length());
825 for (Attribute.Compound a : visibles)
826 writeCompoundAttribute(a);
827 endAttr(attrIndex);
828 attrCount++;
829 }
830 if (invisibles.length() != 0) {
831 int attrIndex = writeAttr(names.RuntimeInvisibleAnnotations);
832 databuf.appendChar(invisibles.length());
833 for (Attribute.Compound a : invisibles)
834 writeCompoundAttribute(a);
835 endAttr(attrIndex);
836 attrCount++;
837 }
838 return attrCount;
839 }
841 /** A visitor to write an attribute including its leading
842 * single-character marker.
843 */
844 class AttributeWriter implements Attribute.Visitor {
845 public void visitConstant(Attribute.Constant _value) {
846 Object value = _value.value;
847 switch (_value.type.getTag()) {
848 case BYTE:
849 databuf.appendByte('B');
850 break;
851 case CHAR:
852 databuf.appendByte('C');
853 break;
854 case SHORT:
855 databuf.appendByte('S');
856 break;
857 case INT:
858 databuf.appendByte('I');
859 break;
860 case LONG:
861 databuf.appendByte('J');
862 break;
863 case FLOAT:
864 databuf.appendByte('F');
865 break;
866 case DOUBLE:
867 databuf.appendByte('D');
868 break;
869 case BOOLEAN:
870 databuf.appendByte('Z');
871 break;
872 case CLASS:
873 Assert.check(value instanceof String);
874 databuf.appendByte('s');
875 value = names.fromString(value.toString()); // CONSTANT_Utf8
876 break;
877 default:
878 throw new AssertionError(_value.type);
879 }
880 databuf.appendChar(pool.put(value));
881 }
882 public void visitEnum(Attribute.Enum e) {
883 databuf.appendByte('e');
884 databuf.appendChar(pool.put(typeSig(e.value.type)));
885 databuf.appendChar(pool.put(e.value.name));
886 }
887 public void visitClass(Attribute.Class clazz) {
888 databuf.appendByte('c');
889 databuf.appendChar(pool.put(typeSig(clazz.classType)));
890 }
891 public void visitCompound(Attribute.Compound compound) {
892 databuf.appendByte('@');
893 writeCompoundAttribute(compound);
894 }
895 public void visitError(Attribute.Error x) {
896 throw new AssertionError(x);
897 }
898 public void visitArray(Attribute.Array array) {
899 databuf.appendByte('[');
900 databuf.appendChar(array.values.length);
901 for (Attribute a : array.values) {
902 a.accept(this);
903 }
904 }
905 }
906 AttributeWriter awriter = new AttributeWriter();
908 /** Write a compound attribute excluding the '@' marker. */
909 void writeCompoundAttribute(Attribute.Compound c) {
910 databuf.appendChar(pool.put(typeSig(c.type)));
911 databuf.appendChar(c.values.length());
912 for (Pair<Symbol.MethodSymbol,Attribute> p : c.values) {
913 databuf.appendChar(pool.put(p.fst.name));
914 p.snd.accept(awriter);
915 }
916 }
917 /**********************************************************************
918 * Writing Objects
919 **********************************************************************/
921 /** Enter an inner class into the `innerClasses' set/queue.
922 */
923 void enterInner(ClassSymbol c) {
924 if (c.type.isCompound()) {
925 throw new AssertionError("Unexpected intersection type: " + c.type);
926 }
927 try {
928 c.complete();
929 } catch (CompletionFailure ex) {
930 System.err.println("error: " + c + ": " + ex.getMessage());
931 throw ex;
932 }
933 if (!c.type.hasTag(CLASS)) return; // arrays
934 if (pool != null && // pool might be null if called from xClassName
935 c.owner.enclClass() != null &&
936 (innerClasses == null || !innerClasses.contains(c))) {
937 // log.errWriter.println("enter inner " + c);//DEBUG
938 enterInner(c.owner.enclClass());
939 pool.put(c);
940 pool.put(c.name);
941 if (innerClasses == null) {
942 innerClasses = new HashSet<ClassSymbol>();
943 innerClassesQueue = new ListBuffer<ClassSymbol>();
944 pool.put(names.InnerClasses);
945 }
946 innerClasses.add(c);
947 innerClassesQueue.append(c);
948 }
949 }
951 /** Write "inner classes" attribute.
952 */
953 void writeInnerClasses() {
954 int alenIdx = writeAttr(names.InnerClasses);
955 databuf.appendChar(innerClassesQueue.length());
956 for (List<ClassSymbol> l = innerClassesQueue.toList();
957 l.nonEmpty();
958 l = l.tail) {
959 ClassSymbol inner = l.head;
960 char flags = (char) adjustFlags(inner.flags_field);
961 if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT
962 if (inner.name.isEmpty()) flags &= ~FINAL; // Anonymous class: unset FINAL flag
963 if (dumpInnerClassModifiers) {
964 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
965 pw.println("INNERCLASS " + inner.name);
966 pw.println("---" + flagNames(flags));
967 }
968 databuf.appendChar(pool.get(inner));
969 databuf.appendChar(
970 inner.owner.kind == TYP ? pool.get(inner.owner) : 0);
971 databuf.appendChar(
972 !inner.name.isEmpty() ? pool.get(inner.name) : 0);
973 databuf.appendChar(flags);
974 }
975 endAttr(alenIdx);
976 }
978 /** Write "bootstrapMethods" attribute.
979 */
980 void writeBootstrapMethods() {
981 int alenIdx = writeAttr(names.BootstrapMethods);
982 databuf.appendChar(bootstrapMethods.size());
983 for (Map.Entry<DynamicMethod, MethodHandle> entry : bootstrapMethods.entrySet()) {
984 DynamicMethod dmeth = entry.getKey();
985 DynamicMethodSymbol dsym = (DynamicMethodSymbol)dmeth.baseSymbol();
986 //write BSM handle
987 databuf.appendChar(pool.get(entry.getValue()));
988 //write static args length
989 databuf.appendChar(dsym.staticArgs.length);
990 //write static args array
991 Object[] uniqueArgs = dmeth.uniqueStaticArgs;
992 for (Object o : uniqueArgs) {
993 databuf.appendChar(pool.get(o));
994 }
995 }
996 endAttr(alenIdx);
997 }
999 /** Write field symbol, entering all references into constant pool.
1000 */
1001 void writeField(VarSymbol v) {
1002 int flags = adjustFlags(v.flags());
1003 databuf.appendChar(flags);
1004 if (dumpFieldModifiers) {
1005 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1006 pw.println("FIELD " + fieldName(v));
1007 pw.println("---" + flagNames(v.flags()));
1008 }
1009 databuf.appendChar(pool.put(fieldName(v)));
1010 databuf.appendChar(pool.put(typeSig(v.erasure(types))));
1011 int acountIdx = beginAttrs();
1012 int acount = 0;
1013 if (v.getConstValue() != null) {
1014 int alenIdx = writeAttr(names.ConstantValue);
1015 databuf.appendChar(pool.put(v.getConstValue()));
1016 endAttr(alenIdx);
1017 acount++;
1018 }
1019 acount += writeMemberAttrs(v);
1020 endAttrs(acountIdx, acount);
1021 }
1023 /** Write method symbol, entering all references into constant pool.
1024 */
1025 void writeMethod(MethodSymbol m) {
1026 int flags = adjustFlags(m.flags());
1027 databuf.appendChar(flags);
1028 if (dumpMethodModifiers) {
1029 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1030 pw.println("METHOD " + fieldName(m));
1031 pw.println("---" + flagNames(m.flags()));
1032 }
1033 databuf.appendChar(pool.put(fieldName(m)));
1034 databuf.appendChar(pool.put(typeSig(m.externalType(types))));
1035 int acountIdx = beginAttrs();
1036 int acount = 0;
1037 if (m.code != null) {
1038 int alenIdx = writeAttr(names.Code);
1039 writeCode(m.code);
1040 m.code = null; // to conserve space
1041 endAttr(alenIdx);
1042 acount++;
1043 }
1044 List<Type> thrown = m.erasure(types).getThrownTypes();
1045 if (thrown.nonEmpty()) {
1046 int alenIdx = writeAttr(names.Exceptions);
1047 databuf.appendChar(thrown.length());
1048 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1049 databuf.appendChar(pool.put(l.head.tsym));
1050 endAttr(alenIdx);
1051 acount++;
1052 }
1053 if (m.defaultValue != null) {
1054 int alenIdx = writeAttr(names.AnnotationDefault);
1055 m.defaultValue.accept(awriter);
1056 endAttr(alenIdx);
1057 acount++;
1058 }
1059 if (options.isSet(PARAMETERS))
1060 acount += writeMethodParametersAttr(m);
1061 acount += writeMemberAttrs(m);
1062 acount += writeParameterAttrs(m);
1063 endAttrs(acountIdx, acount);
1064 }
1066 /** Write code attribute of method.
1067 */
1068 void writeCode(Code code) {
1069 databuf.appendChar(code.max_stack);
1070 databuf.appendChar(code.max_locals);
1071 databuf.appendInt(code.cp);
1072 databuf.appendBytes(code.code, 0, code.cp);
1073 databuf.appendChar(code.catchInfo.length());
1074 for (List<char[]> l = code.catchInfo.toList();
1075 l.nonEmpty();
1076 l = l.tail) {
1077 for (int i = 0; i < l.head.length; i++)
1078 databuf.appendChar(l.head[i]);
1079 }
1080 int acountIdx = beginAttrs();
1081 int acount = 0;
1083 if (code.lineInfo.nonEmpty()) {
1084 int alenIdx = writeAttr(names.LineNumberTable);
1085 databuf.appendChar(code.lineInfo.length());
1086 for (List<char[]> l = code.lineInfo.reverse();
1087 l.nonEmpty();
1088 l = l.tail)
1089 for (int i = 0; i < l.head.length; i++)
1090 databuf.appendChar(l.head[i]);
1091 endAttr(alenIdx);
1092 acount++;
1093 }
1095 if (genCrt && (code.crt != null)) {
1096 CRTable crt = code.crt;
1097 int alenIdx = writeAttr(names.CharacterRangeTable);
1098 int crtIdx = beginAttrs();
1099 int crtEntries = crt.writeCRT(databuf, code.lineMap, log);
1100 endAttrs(crtIdx, crtEntries);
1101 endAttr(alenIdx);
1102 acount++;
1103 }
1105 // counter for number of generic local variables
1106 int nGenericVars = 0;
1108 if (code.varBufferSize > 0) {
1109 int alenIdx = writeAttr(names.LocalVariableTable);
1110 databuf.appendChar(code.varBufferSize);
1112 for (int i=0; i<code.varBufferSize; i++) {
1113 Code.LocalVar var = code.varBuffer[i];
1115 // write variable info
1116 Assert.check(var.start_pc >= 0
1117 && var.start_pc <= code.cp);
1118 databuf.appendChar(var.start_pc);
1119 Assert.check(var.length >= 0
1120 && (var.start_pc + var.length) <= code.cp);
1121 databuf.appendChar(var.length);
1122 VarSymbol sym = var.sym;
1123 databuf.appendChar(pool.put(sym.name));
1124 Type vartype = sym.erasure(types);
1125 if (needsLocalVariableTypeEntry(sym.type))
1126 nGenericVars++;
1127 databuf.appendChar(pool.put(typeSig(vartype)));
1128 databuf.appendChar(var.reg);
1129 }
1130 endAttr(alenIdx);
1131 acount++;
1132 }
1134 if (nGenericVars > 0) {
1135 int alenIdx = writeAttr(names.LocalVariableTypeTable);
1136 databuf.appendChar(nGenericVars);
1137 int count = 0;
1139 for (int i=0; i<code.varBufferSize; i++) {
1140 Code.LocalVar var = code.varBuffer[i];
1141 VarSymbol sym = var.sym;
1142 if (!needsLocalVariableTypeEntry(sym.type))
1143 continue;
1144 count++;
1145 // write variable info
1146 databuf.appendChar(var.start_pc);
1147 databuf.appendChar(var.length);
1148 databuf.appendChar(pool.put(sym.name));
1149 databuf.appendChar(pool.put(typeSig(sym.type)));
1150 databuf.appendChar(var.reg);
1151 }
1152 Assert.check(count == nGenericVars);
1153 endAttr(alenIdx);
1154 acount++;
1155 }
1157 if (code.stackMapBufferSize > 0) {
1158 if (debugstackmap) System.out.println("Stack map for " + code.meth);
1159 int alenIdx = writeAttr(code.stackMap.getAttributeName(names));
1160 writeStackMap(code);
1161 endAttr(alenIdx);
1162 acount++;
1163 }
1164 endAttrs(acountIdx, acount);
1165 }
1166 //where
1167 private boolean needsLocalVariableTypeEntry(Type t) {
1168 //a local variable needs a type-entry if its type T is generic
1169 //(i.e. |T| != T) and if it's not an intersection type (not supported
1170 //in signature attribute grammar)
1171 return (!types.isSameType(t, types.erasure(t)) &&
1172 !t.isCompound());
1173 }
1175 void writeStackMap(Code code) {
1176 int nframes = code.stackMapBufferSize;
1177 if (debugstackmap) System.out.println(" nframes = " + nframes);
1178 databuf.appendChar(nframes);
1180 switch (code.stackMap) {
1181 case CLDC:
1182 for (int i=0; i<nframes; i++) {
1183 if (debugstackmap) System.out.print(" " + i + ":");
1184 Code.StackMapFrame frame = code.stackMapBuffer[i];
1186 // output PC
1187 if (debugstackmap) System.out.print(" pc=" + frame.pc);
1188 databuf.appendChar(frame.pc);
1190 // output locals
1191 int localCount = 0;
1192 for (int j=0; j<frame.locals.length;
1193 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1194 localCount++;
1195 }
1196 if (debugstackmap) System.out.print(" nlocals=" +
1197 localCount);
1198 databuf.appendChar(localCount);
1199 for (int j=0; j<frame.locals.length;
1200 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1201 if (debugstackmap) System.out.print(" local[" + j + "]=");
1202 writeStackMapType(frame.locals[j]);
1203 }
1205 // output stack
1206 int stackCount = 0;
1207 for (int j=0; j<frame.stack.length;
1208 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1209 stackCount++;
1210 }
1211 if (debugstackmap) System.out.print(" nstack=" +
1212 stackCount);
1213 databuf.appendChar(stackCount);
1214 for (int j=0; j<frame.stack.length;
1215 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1216 if (debugstackmap) System.out.print(" stack[" + j + "]=");
1217 writeStackMapType(frame.stack[j]);
1218 }
1219 if (debugstackmap) System.out.println();
1220 }
1221 break;
1222 case JSR202: {
1223 Assert.checkNull(code.stackMapBuffer);
1224 for (int i=0; i<nframes; i++) {
1225 if (debugstackmap) System.out.print(" " + i + ":");
1226 StackMapTableFrame frame = code.stackMapTableBuffer[i];
1227 frame.write(this);
1228 if (debugstackmap) System.out.println();
1229 }
1230 break;
1231 }
1232 default:
1233 throw new AssertionError("Unexpected stackmap format value");
1234 }
1235 }
1237 //where
1238 void writeStackMapType(Type t) {
1239 if (t == null) {
1240 if (debugstackmap) System.out.print("empty");
1241 databuf.appendByte(0);
1242 }
1243 else switch(t.getTag()) {
1244 case BYTE:
1245 case CHAR:
1246 case SHORT:
1247 case INT:
1248 case BOOLEAN:
1249 if (debugstackmap) System.out.print("int");
1250 databuf.appendByte(1);
1251 break;
1252 case FLOAT:
1253 if (debugstackmap) System.out.print("float");
1254 databuf.appendByte(2);
1255 break;
1256 case DOUBLE:
1257 if (debugstackmap) System.out.print("double");
1258 databuf.appendByte(3);
1259 break;
1260 case LONG:
1261 if (debugstackmap) System.out.print("long");
1262 databuf.appendByte(4);
1263 break;
1264 case BOT: // null
1265 if (debugstackmap) System.out.print("null");
1266 databuf.appendByte(5);
1267 break;
1268 case CLASS:
1269 case ARRAY:
1270 if (debugstackmap) System.out.print("object(" + t + ")");
1271 databuf.appendByte(7);
1272 databuf.appendChar(pool.put(t));
1273 break;
1274 case TYPEVAR:
1275 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")");
1276 databuf.appendByte(7);
1277 databuf.appendChar(pool.put(types.erasure(t).tsym));
1278 break;
1279 case UNINITIALIZED_THIS:
1280 if (debugstackmap) System.out.print("uninit_this");
1281 databuf.appendByte(6);
1282 break;
1283 case UNINITIALIZED_OBJECT:
1284 { UninitializedType uninitType = (UninitializedType)t;
1285 databuf.appendByte(8);
1286 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset);
1287 databuf.appendChar(uninitType.offset);
1288 }
1289 break;
1290 default:
1291 throw new AssertionError();
1292 }
1293 }
1295 /** An entry in the JSR202 StackMapTable */
1296 abstract static class StackMapTableFrame {
1297 abstract int getFrameType();
1299 void write(ClassWriter writer) {
1300 int frameType = getFrameType();
1301 writer.databuf.appendByte(frameType);
1302 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType);
1303 }
1305 static class SameFrame extends StackMapTableFrame {
1306 final int offsetDelta;
1307 SameFrame(int offsetDelta) {
1308 this.offsetDelta = offsetDelta;
1309 }
1310 int getFrameType() {
1311 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED;
1312 }
1313 @Override
1314 void write(ClassWriter writer) {
1315 super.write(writer);
1316 if (getFrameType() == SAME_FRAME_EXTENDED) {
1317 writer.databuf.appendChar(offsetDelta);
1318 if (writer.debugstackmap){
1319 System.out.print(" offset_delta=" + offsetDelta);
1320 }
1321 }
1322 }
1323 }
1325 static class SameLocals1StackItemFrame extends StackMapTableFrame {
1326 final int offsetDelta;
1327 final Type stack;
1328 SameLocals1StackItemFrame(int offsetDelta, Type stack) {
1329 this.offsetDelta = offsetDelta;
1330 this.stack = stack;
1331 }
1332 int getFrameType() {
1333 return (offsetDelta < SAME_FRAME_SIZE) ?
1334 (SAME_FRAME_SIZE + offsetDelta) :
1335 SAME_LOCALS_1_STACK_ITEM_EXTENDED;
1336 }
1337 @Override
1338 void write(ClassWriter writer) {
1339 super.write(writer);
1340 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) {
1341 writer.databuf.appendChar(offsetDelta);
1342 if (writer.debugstackmap) {
1343 System.out.print(" offset_delta=" + offsetDelta);
1344 }
1345 }
1346 if (writer.debugstackmap) {
1347 System.out.print(" stack[" + 0 + "]=");
1348 }
1349 writer.writeStackMapType(stack);
1350 }
1351 }
1353 static class ChopFrame extends StackMapTableFrame {
1354 final int frameType;
1355 final int offsetDelta;
1356 ChopFrame(int frameType, int offsetDelta) {
1357 this.frameType = frameType;
1358 this.offsetDelta = offsetDelta;
1359 }
1360 int getFrameType() { return frameType; }
1361 @Override
1362 void write(ClassWriter writer) {
1363 super.write(writer);
1364 writer.databuf.appendChar(offsetDelta);
1365 if (writer.debugstackmap) {
1366 System.out.print(" offset_delta=" + offsetDelta);
1367 }
1368 }
1369 }
1371 static class AppendFrame extends StackMapTableFrame {
1372 final int frameType;
1373 final int offsetDelta;
1374 final Type[] locals;
1375 AppendFrame(int frameType, int offsetDelta, Type[] locals) {
1376 this.frameType = frameType;
1377 this.offsetDelta = offsetDelta;
1378 this.locals = locals;
1379 }
1380 int getFrameType() { return frameType; }
1381 @Override
1382 void write(ClassWriter writer) {
1383 super.write(writer);
1384 writer.databuf.appendChar(offsetDelta);
1385 if (writer.debugstackmap) {
1386 System.out.print(" offset_delta=" + offsetDelta);
1387 }
1388 for (int i=0; i<locals.length; i++) {
1389 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1390 writer.writeStackMapType(locals[i]);
1391 }
1392 }
1393 }
1395 static class FullFrame extends StackMapTableFrame {
1396 final int offsetDelta;
1397 final Type[] locals;
1398 final Type[] stack;
1399 FullFrame(int offsetDelta, Type[] locals, Type[] stack) {
1400 this.offsetDelta = offsetDelta;
1401 this.locals = locals;
1402 this.stack = stack;
1403 }
1404 int getFrameType() { return FULL_FRAME; }
1405 @Override
1406 void write(ClassWriter writer) {
1407 super.write(writer);
1408 writer.databuf.appendChar(offsetDelta);
1409 writer.databuf.appendChar(locals.length);
1410 if (writer.debugstackmap) {
1411 System.out.print(" offset_delta=" + offsetDelta);
1412 System.out.print(" nlocals=" + locals.length);
1413 }
1414 for (int i=0; i<locals.length; i++) {
1415 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1416 writer.writeStackMapType(locals[i]);
1417 }
1419 writer.databuf.appendChar(stack.length);
1420 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); }
1421 for (int i=0; i<stack.length; i++) {
1422 if (writer.debugstackmap) System.out.print(" stack[" + i + "]=");
1423 writer.writeStackMapType(stack[i]);
1424 }
1425 }
1426 }
1428 /** Compare this frame with the previous frame and produce
1429 * an entry of compressed stack map frame. */
1430 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame,
1431 int prev_pc,
1432 Type[] prev_locals,
1433 Types types) {
1434 Type[] locals = this_frame.locals;
1435 Type[] stack = this_frame.stack;
1436 int offset_delta = this_frame.pc - prev_pc - 1;
1437 if (stack.length == 1) {
1438 if (locals.length == prev_locals.length
1439 && compare(prev_locals, locals, types) == 0) {
1440 return new SameLocals1StackItemFrame(offset_delta, stack[0]);
1441 }
1442 } else if (stack.length == 0) {
1443 int diff_length = compare(prev_locals, locals, types);
1444 if (diff_length == 0) {
1445 return new SameFrame(offset_delta);
1446 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) {
1447 // APPEND
1448 Type[] local_diff = new Type[-diff_length];
1449 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) {
1450 local_diff[j] = locals[i];
1451 }
1452 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length,
1453 offset_delta,
1454 local_diff);
1455 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) {
1456 // CHOP
1457 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length,
1458 offset_delta);
1459 }
1460 }
1461 // FULL_FRAME
1462 return new FullFrame(offset_delta, locals, stack);
1463 }
1465 static boolean isInt(Type t) {
1466 return (t.getTag().isStrictSubRangeOf(INT) || t.hasTag(BOOLEAN));
1467 }
1469 static boolean isSameType(Type t1, Type t2, Types types) {
1470 if (t1 == null) { return t2 == null; }
1471 if (t2 == null) { return false; }
1473 if (isInt(t1) && isInt(t2)) { return true; }
1475 if (t1.hasTag(UNINITIALIZED_THIS)) {
1476 return t2.hasTag(UNINITIALIZED_THIS);
1477 } else if (t1.hasTag(UNINITIALIZED_OBJECT)) {
1478 if (t2.hasTag(UNINITIALIZED_OBJECT)) {
1479 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset;
1480 } else {
1481 return false;
1482 }
1483 } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) {
1484 return false;
1485 }
1487 return types.isSameType(t1, t2);
1488 }
1490 static int compare(Type[] arr1, Type[] arr2, Types types) {
1491 int diff_length = arr1.length - arr2.length;
1492 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) {
1493 return Integer.MAX_VALUE;
1494 }
1495 int len = (diff_length > 0) ? arr2.length : arr1.length;
1496 for (int i=0; i<len; i++) {
1497 if (!isSameType(arr1[i], arr2[i], types)) {
1498 return Integer.MAX_VALUE;
1499 }
1500 }
1501 return diff_length;
1502 }
1503 }
1505 void writeFields(Scope.Entry e) {
1506 // process them in reverse sibling order;
1507 // i.e., process them in declaration order.
1508 List<VarSymbol> vars = List.nil();
1509 for (Scope.Entry i = e; i != null; i = i.sibling) {
1510 if (i.sym.kind == VAR) vars = vars.prepend((VarSymbol)i.sym);
1511 }
1512 while (vars.nonEmpty()) {
1513 writeField(vars.head);
1514 vars = vars.tail;
1515 }
1516 }
1518 void writeMethods(Scope.Entry e) {
1519 List<MethodSymbol> methods = List.nil();
1520 for (Scope.Entry i = e; i != null; i = i.sibling) {
1521 if (i.sym.kind == MTH && (i.sym.flags() & HYPOTHETICAL) == 0)
1522 methods = methods.prepend((MethodSymbol)i.sym);
1523 }
1524 while (methods.nonEmpty()) {
1525 writeMethod(methods.head);
1526 methods = methods.tail;
1527 }
1528 }
1530 /** Emit a class file for a given class.
1531 * @param c The class from which a class file is generated.
1532 */
1533 public JavaFileObject writeClass(ClassSymbol c)
1534 throws IOException, PoolOverflow, StringOverflow
1535 {
1536 JavaFileObject outFile
1537 = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
1538 c.flatname.toString(),
1539 JavaFileObject.Kind.CLASS,
1540 c.sourcefile);
1541 OutputStream out = outFile.openOutputStream();
1542 try {
1543 writeClassFile(out, c);
1544 if (verbose)
1545 log.printVerbose("wrote.file", outFile);
1546 out.close();
1547 out = null;
1548 } finally {
1549 if (out != null) {
1550 // if we are propogating an exception, delete the file
1551 out.close();
1552 outFile.delete();
1553 outFile = null;
1554 }
1555 }
1556 return outFile; // may be null if write failed
1557 }
1559 /** Write class `c' to outstream `out'.
1560 */
1561 public void writeClassFile(OutputStream out, ClassSymbol c)
1562 throws IOException, PoolOverflow, StringOverflow {
1563 Assert.check((c.flags() & COMPOUND) == 0);
1564 databuf.reset();
1565 poolbuf.reset();
1566 sigbuf.reset();
1567 pool = c.pool;
1568 innerClasses = null;
1569 innerClassesQueue = null;
1570 bootstrapMethods = new LinkedHashMap<DynamicMethod, MethodHandle>();
1572 Type supertype = types.supertype(c.type);
1573 List<Type> interfaces = types.interfaces(c.type);
1574 List<Type> typarams = c.type.getTypeArguments();
1576 int flags = adjustFlags(c.flags() & ~DEFAULT);
1577 if ((flags & PROTECTED) != 0) flags |= PUBLIC;
1578 flags = flags & ClassFlags & ~STRICTFP;
1579 if ((flags & INTERFACE) == 0) flags |= ACC_SUPER;
1580 if (c.isInner() && c.name.isEmpty()) flags &= ~FINAL;
1581 if (dumpClassModifiers) {
1582 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1583 pw.println();
1584 pw.println("CLASSFILE " + c.getQualifiedName());
1585 pw.println("---" + flagNames(flags));
1586 }
1587 databuf.appendChar(flags);
1589 databuf.appendChar(pool.put(c));
1590 databuf.appendChar(supertype.hasTag(CLASS) ? pool.put(supertype.tsym) : 0);
1591 databuf.appendChar(interfaces.length());
1592 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1593 databuf.appendChar(pool.put(l.head.tsym));
1594 int fieldsCount = 0;
1595 int methodsCount = 0;
1596 for (Scope.Entry e = c.members().elems; e != null; e = e.sibling) {
1597 switch (e.sym.kind) {
1598 case VAR: fieldsCount++; break;
1599 case MTH: if ((e.sym.flags() & HYPOTHETICAL) == 0) methodsCount++;
1600 break;
1601 case TYP: enterInner((ClassSymbol)e.sym); break;
1602 default : Assert.error();
1603 }
1604 }
1606 if (c.trans_local != null) {
1607 for (ClassSymbol local : c.trans_local) {
1608 enterInner(local);
1609 }
1610 }
1612 databuf.appendChar(fieldsCount);
1613 writeFields(c.members().elems);
1614 databuf.appendChar(methodsCount);
1615 writeMethods(c.members().elems);
1617 int acountIdx = beginAttrs();
1618 int acount = 0;
1620 boolean sigReq =
1621 typarams.length() != 0 || supertype.allparams().length() != 0;
1622 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail)
1623 sigReq = l.head.allparams().length() != 0;
1624 if (sigReq) {
1625 Assert.check(source.allowGenerics());
1626 int alenIdx = writeAttr(names.Signature);
1627 if (typarams.length() != 0) assembleParamsSig(typarams);
1628 assembleSig(supertype);
1629 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1630 assembleSig(l.head);
1631 databuf.appendChar(pool.put(sigbuf.toName(names)));
1632 sigbuf.reset();
1633 endAttr(alenIdx);
1634 acount++;
1635 }
1637 if (c.sourcefile != null && emitSourceFile) {
1638 int alenIdx = writeAttr(names.SourceFile);
1639 // WHM 6/29/1999: Strip file path prefix. We do it here at
1640 // the last possible moment because the sourcefile may be used
1641 // elsewhere in error diagnostics. Fixes 4241573.
1642 //databuf.appendChar(c.pool.put(c.sourcefile));
1643 String simpleName = BaseFileObject.getSimpleName(c.sourcefile);
1644 databuf.appendChar(c.pool.put(names.fromString(simpleName)));
1645 endAttr(alenIdx);
1646 acount++;
1647 }
1649 if (genCrt) {
1650 // Append SourceID attribute
1651 int alenIdx = writeAttr(names.SourceID);
1652 databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile)))));
1653 endAttr(alenIdx);
1654 acount++;
1655 // Append CompilationID attribute
1656 alenIdx = writeAttr(names.CompilationID);
1657 databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis()))));
1658 endAttr(alenIdx);
1659 acount++;
1660 }
1662 acount += writeFlagAttrs(c.flags());
1663 acount += writeJavaAnnotations(c.getRawAttributes());
1664 acount += writeEnclosingMethodAttribute(c);
1665 acount += writeExtraClassAttributes(c);
1667 poolbuf.appendInt(JAVA_MAGIC);
1668 poolbuf.appendChar(target.minorVersion);
1669 poolbuf.appendChar(target.majorVersion);
1671 writePool(c.pool);
1673 if (innerClasses != null) {
1674 writeInnerClasses();
1675 acount++;
1676 }
1678 if (!bootstrapMethods.isEmpty()) {
1679 writeBootstrapMethods();
1680 acount++;
1681 }
1683 endAttrs(acountIdx, acount);
1685 poolbuf.appendBytes(databuf.elems, 0, databuf.length);
1686 out.write(poolbuf.elems, 0, poolbuf.length);
1688 pool = c.pool = null; // to conserve space
1689 }
1691 /**Allows subclasses to write additional class attributes
1692 *
1693 * @return the number of attributes written
1694 */
1695 protected int writeExtraClassAttributes(ClassSymbol c) {
1696 return 0;
1697 }
1699 int adjustFlags(final long flags) {
1700 int result = (int)flags;
1701 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag())
1702 result &= ~SYNTHETIC;
1703 if ((flags & ENUM) != 0 && !target.useEnumFlag())
1704 result &= ~ENUM;
1705 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag())
1706 result &= ~ANNOTATION;
1708 if ((flags & BRIDGE) != 0 && target.useBridgeFlag())
1709 result |= ACC_BRIDGE;
1710 if ((flags & VARARGS) != 0 && target.useVarargsFlag())
1711 result |= ACC_VARARGS;
1712 if ((flags & DEFAULT) != 0)
1713 result &= ~ABSTRACT;
1714 return result;
1715 }
1717 long getLastModified(FileObject filename) {
1718 long mod = 0;
1719 try {
1720 mod = filename.getLastModified();
1721 } catch (SecurityException e) {
1722 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage());
1723 }
1724 return mod;
1725 }
1726 }