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