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