Fri, 31 Aug 2012 10:37:46 +0100
7151010: Add compiler support for repeating annotations
Reviewed-by: jjg, mcimadamore
1 /*
2 * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.jvm;
28 import java.io.*;
29 import java.util.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 com.sun.tools.javac.main.Option.*;
49 import static javax.tools.StandardLocation.CLASS_OUTPUT;
52 /** This class provides operations to map an internal symbol table graph
53 * rooted in a ClassSymbol into a classfile.
54 *
55 * <p><b>This is NOT part of any supported API.
56 * If you write code that depends on this, you do so at your own risk.
57 * This code and its internal interfaces are subject to change or
58 * deletion without notice.</b>
59 */
60 public class ClassWriter extends ClassFile {
61 protected static final Context.Key<ClassWriter> classWriterKey =
62 new Context.Key<ClassWriter>();
64 private final Symtab syms;
66 private final Options options;
68 /** Switch: verbose output.
69 */
70 private boolean verbose;
72 /** Switch: scramble private names.
73 */
74 private boolean scramble;
76 /** Switch: scramble 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 protected 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 verbose = options.isSet(VERBOSE);
180 scramble = options.isSet("-scramble");
181 scrambleAll = options.isSet("-scrambleAll");
182 retrofit = options.isSet("-retrofit");
183 genCrt = options.isSet(XJCOV);
184 debugstackmap = options.isSet("debugstackmap");
186 emitSourceFile = options.isUnset(G_CUSTOM) ||
187 options.isSet(G_CUSTOM, "source");
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 StringBuilder sbuf = new StringBuilder();
223 int i = 0;
224 long f = flags & StandardFlags;
225 while (f != 0) {
226 if ((f & 1) != 0) {
227 sbuf.append(" ");
228 sbuf.append(flagName[i]);
229 }
230 f = f >> 1;
231 i++;
232 }
233 return sbuf.toString();
234 }
235 //where
236 private final static String[] flagName = {
237 "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL",
238 "SUPER", "VOLATILE", "TRANSIENT", "NATIVE", "INTERFACE",
239 "ABSTRACT", "STRICTFP"};
241 /******************************************************************
242 * Output routines
243 ******************************************************************/
245 /** Write a character into given byte buffer;
246 * byte buffer will not be grown.
247 */
248 void putChar(ByteBuffer buf, int op, int x) {
249 buf.elems[op ] = (byte)((x >> 8) & 0xFF);
250 buf.elems[op+1] = (byte)((x ) & 0xFF);
251 }
253 /** Write an integer into given byte buffer;
254 * byte buffer will not be grown.
255 */
256 void putInt(ByteBuffer buf, int adr, int x) {
257 buf.elems[adr ] = (byte)((x >> 24) & 0xFF);
258 buf.elems[adr+1] = (byte)((x >> 16) & 0xFF);
259 buf.elems[adr+2] = (byte)((x >> 8) & 0xFF);
260 buf.elems[adr+3] = (byte)((x ) & 0xFF);
261 }
263 /******************************************************************
264 * Signature Generation
265 ******************************************************************/
267 /** Assemble signature of given type in string buffer.
268 */
269 void assembleSig(Type type) {
270 switch (type.tag) {
271 case BYTE:
272 sigbuf.appendByte('B');
273 break;
274 case SHORT:
275 sigbuf.appendByte('S');
276 break;
277 case CHAR:
278 sigbuf.appendByte('C');
279 break;
280 case INT:
281 sigbuf.appendByte('I');
282 break;
283 case LONG:
284 sigbuf.appendByte('J');
285 break;
286 case FLOAT:
287 sigbuf.appendByte('F');
288 break;
289 case DOUBLE:
290 sigbuf.appendByte('D');
291 break;
292 case BOOLEAN:
293 sigbuf.appendByte('Z');
294 break;
295 case VOID:
296 sigbuf.appendByte('V');
297 break;
298 case CLASS:
299 sigbuf.appendByte('L');
300 assembleClassSig(type);
301 sigbuf.appendByte(';');
302 break;
303 case ARRAY:
304 ArrayType at = (ArrayType)type;
305 sigbuf.appendByte('[');
306 assembleSig(at.elemtype);
307 break;
308 case METHOD:
309 MethodType mt = (MethodType)type;
310 sigbuf.appendByte('(');
311 assembleSig(mt.argtypes);
312 sigbuf.appendByte(')');
313 assembleSig(mt.restype);
314 if (hasTypeVar(mt.thrown)) {
315 for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
316 sigbuf.appendByte('^');
317 assembleSig(l.head);
318 }
319 }
320 break;
321 case WILDCARD: {
322 WildcardType ta = (WildcardType) type;
323 switch (ta.kind) {
324 case SUPER:
325 sigbuf.appendByte('-');
326 assembleSig(ta.type);
327 break;
328 case EXTENDS:
329 sigbuf.appendByte('+');
330 assembleSig(ta.type);
331 break;
332 case UNBOUND:
333 sigbuf.appendByte('*');
334 break;
335 default:
336 throw new AssertionError(ta.kind);
337 }
338 break;
339 }
340 case TYPEVAR:
341 sigbuf.appendByte('T');
342 sigbuf.appendName(type.tsym.name);
343 sigbuf.appendByte(';');
344 break;
345 case FORALL:
346 ForAll ft = (ForAll)type;
347 assembleParamsSig(ft.tvars);
348 assembleSig(ft.qtype);
349 break;
350 case UNINITIALIZED_THIS:
351 case UNINITIALIZED_OBJECT:
352 // we don't yet have a spec for uninitialized types in the
353 // local variable table
354 assembleSig(types.erasure(((UninitializedType)type).qtype));
355 break;
356 default:
357 throw new AssertionError("typeSig " + type.tag);
358 }
359 }
361 boolean hasTypeVar(List<Type> l) {
362 while (l.nonEmpty()) {
363 if (l.head.tag == TypeTags.TYPEVAR) return true;
364 l = l.tail;
365 }
366 return false;
367 }
369 void assembleClassSig(Type type) {
370 ClassType ct = (ClassType)type;
371 ClassSymbol c = (ClassSymbol)ct.tsym;
372 enterInner(c);
373 Type outer = ct.getEnclosingType();
374 if (outer.allparams().nonEmpty()) {
375 boolean rawOuter =
376 c.owner.kind == MTH || // either a local class
377 c.name == names.empty; // or anonymous
378 assembleClassSig(rawOuter
379 ? types.erasure(outer)
380 : outer);
381 sigbuf.appendByte('.');
382 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
383 sigbuf.appendName(rawOuter
384 ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength()+1,c.flatname.getByteLength())
385 : c.name);
386 } else {
387 sigbuf.appendBytes(externalize(c.flatname));
388 }
389 if (ct.getTypeArguments().nonEmpty()) {
390 sigbuf.appendByte('<');
391 assembleSig(ct.getTypeArguments());
392 sigbuf.appendByte('>');
393 }
394 }
397 void assembleSig(List<Type> types) {
398 for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail)
399 assembleSig(ts.head);
400 }
402 void assembleParamsSig(List<Type> typarams) {
403 sigbuf.appendByte('<');
404 for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
405 TypeVar tvar = (TypeVar)ts.head;
406 sigbuf.appendName(tvar.tsym.name);
407 List<Type> bounds = types.getBounds(tvar);
408 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
409 sigbuf.appendByte(':');
410 }
411 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
412 sigbuf.appendByte(':');
413 assembleSig(l.head);
414 }
415 }
416 sigbuf.appendByte('>');
417 }
419 /** Return signature of given type
420 */
421 Name typeSig(Type type) {
422 Assert.check(sigbuf.length == 0);
423 //- System.out.println(" ? " + type);
424 assembleSig(type);
425 Name n = sigbuf.toName(names);
426 sigbuf.reset();
427 //- System.out.println(" " + n);
428 return n;
429 }
431 /** Given a type t, return the extended class name of its erasure in
432 * external representation.
433 */
434 public Name xClassName(Type t) {
435 if (t.tag == CLASS) {
436 return names.fromUtf(externalize(t.tsym.flatName()));
437 } else if (t.tag == ARRAY) {
438 return typeSig(types.erasure(t));
439 } else {
440 throw new AssertionError("xClassName");
441 }
442 }
444 /******************************************************************
445 * Writing the Constant Pool
446 ******************************************************************/
448 /** Thrown when the constant pool is over full.
449 */
450 public static class PoolOverflow extends Exception {
451 private static final long serialVersionUID = 0;
452 public PoolOverflow() {}
453 }
454 public static class StringOverflow extends Exception {
455 private static final long serialVersionUID = 0;
456 public final String value;
457 public StringOverflow(String s) {
458 value = s;
459 }
460 }
462 /** Write constant pool to pool buffer.
463 * Note: during writing, constant pool
464 * might grow since some parts of constants still need to be entered.
465 */
466 void writePool(Pool pool) throws PoolOverflow, StringOverflow {
467 int poolCountIdx = poolbuf.length;
468 poolbuf.appendChar(0);
469 int i = 1;
470 while (i < pool.pp) {
471 Object value = pool.pool[i];
472 Assert.checkNonNull(value);
473 if (value instanceof Pool.Method)
474 value = ((Pool.Method)value).m;
475 else if (value instanceof Pool.Variable)
476 value = ((Pool.Variable)value).v;
478 if (value instanceof MethodSymbol) {
479 MethodSymbol m = (MethodSymbol)value;
480 poolbuf.appendByte((m.owner.flags() & INTERFACE) != 0
481 ? CONSTANT_InterfaceMethodref
482 : CONSTANT_Methodref);
483 poolbuf.appendChar(pool.put(m.owner));
484 poolbuf.appendChar(pool.put(nameType(m)));
485 } else if (value instanceof VarSymbol) {
486 VarSymbol v = (VarSymbol)value;
487 poolbuf.appendByte(CONSTANT_Fieldref);
488 poolbuf.appendChar(pool.put(v.owner));
489 poolbuf.appendChar(pool.put(nameType(v)));
490 } else if (value instanceof Name) {
491 poolbuf.appendByte(CONSTANT_Utf8);
492 byte[] bs = ((Name)value).toUtf();
493 poolbuf.appendChar(bs.length);
494 poolbuf.appendBytes(bs, 0, bs.length);
495 if (bs.length > Pool.MAX_STRING_LENGTH)
496 throw new StringOverflow(value.toString());
497 } else if (value instanceof ClassSymbol) {
498 ClassSymbol c = (ClassSymbol)value;
499 if (c.owner.kind == TYP) pool.put(c.owner);
500 poolbuf.appendByte(CONSTANT_Class);
501 if (c.type.tag == ARRAY) {
502 poolbuf.appendChar(pool.put(typeSig(c.type)));
503 } else {
504 poolbuf.appendChar(pool.put(names.fromUtf(externalize(c.flatname))));
505 enterInner(c);
506 }
507 } else if (value instanceof NameAndType) {
508 NameAndType nt = (NameAndType)value;
509 poolbuf.appendByte(CONSTANT_NameandType);
510 poolbuf.appendChar(pool.put(nt.name));
511 poolbuf.appendChar(pool.put(typeSig(nt.type)));
512 } else if (value instanceof Integer) {
513 poolbuf.appendByte(CONSTANT_Integer);
514 poolbuf.appendInt(((Integer)value).intValue());
515 } else if (value instanceof Long) {
516 poolbuf.appendByte(CONSTANT_Long);
517 poolbuf.appendLong(((Long)value).longValue());
518 i++;
519 } else if (value instanceof Float) {
520 poolbuf.appendByte(CONSTANT_Float);
521 poolbuf.appendFloat(((Float)value).floatValue());
522 } else if (value instanceof Double) {
523 poolbuf.appendByte(CONSTANT_Double);
524 poolbuf.appendDouble(((Double)value).doubleValue());
525 i++;
526 } else if (value instanceof String) {
527 poolbuf.appendByte(CONSTANT_String);
528 poolbuf.appendChar(pool.put(names.fromString((String)value)));
529 } else if (value instanceof Type) {
530 Type type = (Type)value;
531 if (type.tag == CLASS) enterInner((ClassSymbol)type.tsym);
532 poolbuf.appendByte(CONSTANT_Class);
533 poolbuf.appendChar(pool.put(xClassName(type)));
534 } else {
535 Assert.error("writePool " + value);
536 }
537 i++;
538 }
539 if (pool.pp > Pool.MAX_ENTRIES)
540 throw new PoolOverflow();
541 putChar(poolbuf, poolCountIdx, pool.pp);
542 }
544 /** Given a field, return its name.
545 */
546 Name fieldName(Symbol sym) {
547 if (scramble && (sym.flags() & PRIVATE) != 0 ||
548 scrambleAll && (sym.flags() & (PROTECTED | PUBLIC)) == 0)
549 return names.fromString("_$" + sym.name.getIndex());
550 else
551 return sym.name;
552 }
554 /** Given a symbol, return its name-and-type.
555 */
556 NameAndType nameType(Symbol sym) {
557 return new NameAndType(fieldName(sym),
558 retrofit
559 ? sym.erasure(types)
560 : sym.externalType(types));
561 // if we retrofit, then the NameAndType has been read in as is
562 // and no change is necessary. If we compile normally, the
563 // NameAndType is generated from a symbol reference, and the
564 // adjustment of adding an additional this$n parameter needs to be made.
565 }
567 /******************************************************************
568 * Writing Attributes
569 ******************************************************************/
571 /** Write header for an attribute to data buffer and return
572 * position past attribute length index.
573 */
574 int writeAttr(Name attrName) {
575 databuf.appendChar(pool.put(attrName));
576 databuf.appendInt(0);
577 return databuf.length;
578 }
580 /** Fill in attribute length.
581 */
582 void endAttr(int index) {
583 putInt(databuf, index - 4, databuf.length - index);
584 }
586 /** Leave space for attribute count and return index for
587 * number of attributes field.
588 */
589 int beginAttrs() {
590 databuf.appendChar(0);
591 return databuf.length;
592 }
594 /** Fill in number of attributes.
595 */
596 void endAttrs(int index, int count) {
597 putChar(databuf, index - 2, count);
598 }
600 /** Write the EnclosingMethod attribute if needed.
601 * Returns the number of attributes written (0 or 1).
602 */
603 int writeEnclosingMethodAttribute(ClassSymbol c) {
604 if (!target.hasEnclosingMethodAttribute())
605 return 0;
606 return writeEnclosingMethodAttribute(names.EnclosingMethod, c);
607 }
609 /** Write the EnclosingMethod attribute with a specified name.
610 * Returns the number of attributes written (0 or 1).
611 */
612 protected int writeEnclosingMethodAttribute(Name attributeName, ClassSymbol c) {
613 if (c.owner.kind != MTH && // neither a local class
614 c.name != names.empty) // nor anonymous
615 return 0;
617 int alenIdx = writeAttr(attributeName);
618 ClassSymbol enclClass = c.owner.enclClass();
619 MethodSymbol enclMethod =
620 (c.owner.type == null // local to init block
621 || c.owner.kind != MTH) // or member init
622 ? null
623 : (MethodSymbol)c.owner;
624 databuf.appendChar(pool.put(enclClass));
625 databuf.appendChar(enclMethod == null ? 0 : pool.put(nameType(c.owner)));
626 endAttr(alenIdx);
627 return 1;
628 }
630 /** Write flag attributes; return number of attributes written.
631 */
632 int writeFlagAttrs(long flags) {
633 int acount = 0;
634 if ((flags & DEPRECATED) != 0) {
635 int alenIdx = writeAttr(names.Deprecated);
636 endAttr(alenIdx);
637 acount++;
638 }
639 if ((flags & ENUM) != 0 && !target.useEnumFlag()) {
640 int alenIdx = writeAttr(names.Enum);
641 endAttr(alenIdx);
642 acount++;
643 }
644 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag()) {
645 int alenIdx = writeAttr(names.Synthetic);
646 endAttr(alenIdx);
647 acount++;
648 }
649 if ((flags & BRIDGE) != 0 && !target.useBridgeFlag()) {
650 int alenIdx = writeAttr(names.Bridge);
651 endAttr(alenIdx);
652 acount++;
653 }
654 if ((flags & VARARGS) != 0 && !target.useVarargsFlag()) {
655 int alenIdx = writeAttr(names.Varargs);
656 endAttr(alenIdx);
657 acount++;
658 }
659 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag()) {
660 int alenIdx = writeAttr(names.Annotation);
661 endAttr(alenIdx);
662 acount++;
663 }
664 return acount;
665 }
667 /** Write member (field or method) attributes;
668 * return number of attributes written.
669 */
670 int writeMemberAttrs(Symbol sym) {
671 int acount = writeFlagAttrs(sym.flags());
672 long flags = sym.flags();
673 if (source.allowGenerics() &&
674 (flags & (SYNTHETIC|BRIDGE)) != SYNTHETIC &&
675 (flags & ANONCONSTR) == 0 &&
676 (!types.isSameType(sym.type, sym.erasure(types)) ||
677 hasTypeVar(sym.type.getThrownTypes()))) {
678 // note that a local class with captured variables
679 // will get a signature attribute
680 int alenIdx = writeAttr(names.Signature);
681 databuf.appendChar(pool.put(typeSig(sym.type)));
682 endAttr(alenIdx);
683 acount++;
684 }
685 acount += writeJavaAnnotations(sym.getAnnotationMirrors());
686 return acount;
687 }
689 /** Write method parameter annotations;
690 * return number of attributes written.
691 */
692 int writeParameterAttrs(MethodSymbol m) {
693 boolean hasVisible = false;
694 boolean hasInvisible = false;
695 if (m.params != null) for (VarSymbol s : m.params) {
696 for (Attribute.Compound a : s.getAnnotationMirrors()) {
697 switch (types.getRetention(a)) {
698 case SOURCE: break;
699 case CLASS: hasInvisible = true; break;
700 case RUNTIME: hasVisible = true; break;
701 default: ;// /* fail soft */ throw new AssertionError(vis);
702 }
703 }
704 }
706 int attrCount = 0;
707 if (hasVisible) {
708 int attrIndex = writeAttr(names.RuntimeVisibleParameterAnnotations);
709 databuf.appendByte(m.params.length());
710 for (VarSymbol s : m.params) {
711 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
712 for (Attribute.Compound a : s.getAnnotationMirrors())
713 if (types.getRetention(a) == RetentionPolicy.RUNTIME)
714 buf.append(a);
715 databuf.appendChar(buf.length());
716 for (Attribute.Compound a : buf)
717 writeCompoundAttribute(a);
718 }
719 endAttr(attrIndex);
720 attrCount++;
721 }
722 if (hasInvisible) {
723 int attrIndex = writeAttr(names.RuntimeInvisibleParameterAnnotations);
724 databuf.appendByte(m.params.length());
725 for (VarSymbol s : m.params) {
726 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
727 for (Attribute.Compound a : s.getAnnotationMirrors())
728 if (types.getRetention(a) == RetentionPolicy.CLASS)
729 buf.append(a);
730 databuf.appendChar(buf.length());
731 for (Attribute.Compound a : buf)
732 writeCompoundAttribute(a);
733 }
734 endAttr(attrIndex);
735 attrCount++;
736 }
737 return attrCount;
738 }
740 /**********************************************************************
741 * Writing Java-language annotations (aka metadata, attributes)
742 **********************************************************************/
744 /** Write Java-language annotations; return number of JVM
745 * attributes written (zero or one).
746 */
747 int writeJavaAnnotations(List<Attribute.Compound> attrs) {
748 if (attrs.isEmpty()) return 0;
749 ListBuffer<Attribute.Compound> visibles = new ListBuffer<Attribute.Compound>();
750 ListBuffer<Attribute.Compound> invisibles = new ListBuffer<Attribute.Compound>();
751 for (Attribute.Compound a : attrs) {
752 switch (types.getRetention(a)) {
753 case SOURCE: break;
754 case CLASS: invisibles.append(a); break;
755 case RUNTIME: visibles.append(a); break;
756 default: ;// /* fail soft */ throw new AssertionError(vis);
757 }
758 }
760 int attrCount = 0;
761 if (visibles.length() != 0) {
762 int attrIndex = writeAttr(names.RuntimeVisibleAnnotations);
763 databuf.appendChar(visibles.length());
764 for (Attribute.Compound a : visibles)
765 writeCompoundAttribute(a);
766 endAttr(attrIndex);
767 attrCount++;
768 }
769 if (invisibles.length() != 0) {
770 int attrIndex = writeAttr(names.RuntimeInvisibleAnnotations);
771 databuf.appendChar(invisibles.length());
772 for (Attribute.Compound a : invisibles)
773 writeCompoundAttribute(a);
774 endAttr(attrIndex);
775 attrCount++;
776 }
777 return attrCount;
778 }
780 /** A visitor to write an attribute including its leading
781 * single-character marker.
782 */
783 class AttributeWriter implements Attribute.Visitor {
784 public void visitConstant(Attribute.Constant _value) {
785 Object value = _value.value;
786 switch (_value.type.tag) {
787 case BYTE:
788 databuf.appendByte('B');
789 break;
790 case CHAR:
791 databuf.appendByte('C');
792 break;
793 case SHORT:
794 databuf.appendByte('S');
795 break;
796 case INT:
797 databuf.appendByte('I');
798 break;
799 case LONG:
800 databuf.appendByte('J');
801 break;
802 case FLOAT:
803 databuf.appendByte('F');
804 break;
805 case DOUBLE:
806 databuf.appendByte('D');
807 break;
808 case BOOLEAN:
809 databuf.appendByte('Z');
810 break;
811 case CLASS:
812 Assert.check(value instanceof String);
813 databuf.appendByte('s');
814 value = names.fromString(value.toString()); // CONSTANT_Utf8
815 break;
816 default:
817 throw new AssertionError(_value.type);
818 }
819 databuf.appendChar(pool.put(value));
820 }
821 public void visitEnum(Attribute.Enum e) {
822 databuf.appendByte('e');
823 databuf.appendChar(pool.put(typeSig(e.value.type)));
824 databuf.appendChar(pool.put(e.value.name));
825 }
826 public void visitClass(Attribute.Class clazz) {
827 databuf.appendByte('c');
828 databuf.appendChar(pool.put(typeSig(clazz.classType)));
829 }
830 public void visitCompound(Attribute.Compound compound) {
831 databuf.appendByte('@');
832 writeCompoundAttribute(compound);
833 }
834 public void visitError(Attribute.Error x) {
835 throw new AssertionError(x);
836 }
837 public void visitArray(Attribute.Array array) {
838 databuf.appendByte('[');
839 databuf.appendChar(array.values.length);
840 for (Attribute a : array.values) {
841 a.accept(this);
842 }
843 }
844 }
845 AttributeWriter awriter = new AttributeWriter();
847 /** Write a compound attribute excluding the '@' marker. */
848 void writeCompoundAttribute(Attribute.Compound c) {
849 databuf.appendChar(pool.put(typeSig(c.type)));
850 databuf.appendChar(c.values.length());
851 for (Pair<Symbol.MethodSymbol,Attribute> p : c.values) {
852 databuf.appendChar(pool.put(p.fst.name));
853 p.snd.accept(awriter);
854 }
855 }
856 /**********************************************************************
857 * Writing Objects
858 **********************************************************************/
860 /** Enter an inner class into the `innerClasses' set/queue.
861 */
862 void enterInner(ClassSymbol c) {
863 if (c.type.isCompound()) {
864 throw new AssertionError("Unexpected intersection type: " + c.type);
865 }
866 try {
867 c.complete();
868 } catch (CompletionFailure ex) {
869 System.err.println("error: " + c + ": " + ex.getMessage());
870 throw ex;
871 }
872 if (c.type.tag != CLASS) return; // arrays
873 if (pool != null && // pool might be null if called from xClassName
874 c.owner.enclClass() != null &&
875 (innerClasses == null || !innerClasses.contains(c))) {
876 // log.errWriter.println("enter inner " + c);//DEBUG
877 enterInner(c.owner.enclClass());
878 pool.put(c);
879 pool.put(c.name);
880 if (innerClasses == null) {
881 innerClasses = new HashSet<ClassSymbol>();
882 innerClassesQueue = new ListBuffer<ClassSymbol>();
883 pool.put(names.InnerClasses);
884 }
885 innerClasses.add(c);
886 innerClassesQueue.append(c);
887 }
888 }
890 /** Write "inner classes" attribute.
891 */
892 void writeInnerClasses() {
893 int alenIdx = writeAttr(names.InnerClasses);
894 databuf.appendChar(innerClassesQueue.length());
895 for (List<ClassSymbol> l = innerClassesQueue.toList();
896 l.nonEmpty();
897 l = l.tail) {
898 ClassSymbol inner = l.head;
899 char flags = (char) adjustFlags(inner.flags_field);
900 if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT
901 if (inner.name.isEmpty()) flags &= ~FINAL; // Anonymous class: unset FINAL flag
902 if (dumpInnerClassModifiers) {
903 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
904 pw.println("INNERCLASS " + inner.name);
905 pw.println("---" + flagNames(flags));
906 }
907 databuf.appendChar(pool.get(inner));
908 databuf.appendChar(
909 inner.owner.kind == TYP ? pool.get(inner.owner) : 0);
910 databuf.appendChar(
911 !inner.name.isEmpty() ? pool.get(inner.name) : 0);
912 databuf.appendChar(flags);
913 }
914 endAttr(alenIdx);
915 }
917 /** Write field symbol, entering all references into constant pool.
918 */
919 void writeField(VarSymbol v) {
920 int flags = adjustFlags(v.flags());
921 databuf.appendChar(flags);
922 if (dumpFieldModifiers) {
923 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
924 pw.println("FIELD " + fieldName(v));
925 pw.println("---" + flagNames(v.flags()));
926 }
927 databuf.appendChar(pool.put(fieldName(v)));
928 databuf.appendChar(pool.put(typeSig(v.erasure(types))));
929 int acountIdx = beginAttrs();
930 int acount = 0;
931 if (v.getConstValue() != null) {
932 int alenIdx = writeAttr(names.ConstantValue);
933 databuf.appendChar(pool.put(v.getConstValue()));
934 endAttr(alenIdx);
935 acount++;
936 }
937 acount += writeMemberAttrs(v);
938 endAttrs(acountIdx, acount);
939 }
941 /** Write method symbol, entering all references into constant pool.
942 */
943 void writeMethod(MethodSymbol m) {
944 int flags = adjustFlags(m.flags());
945 databuf.appendChar(flags);
946 if (dumpMethodModifiers) {
947 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
948 pw.println("METHOD " + fieldName(m));
949 pw.println("---" + flagNames(m.flags()));
950 }
951 databuf.appendChar(pool.put(fieldName(m)));
952 databuf.appendChar(pool.put(typeSig(m.externalType(types))));
953 int acountIdx = beginAttrs();
954 int acount = 0;
955 if (m.code != null) {
956 int alenIdx = writeAttr(names.Code);
957 writeCode(m.code);
958 m.code = null; // to conserve space
959 endAttr(alenIdx);
960 acount++;
961 }
962 List<Type> thrown = m.erasure(types).getThrownTypes();
963 if (thrown.nonEmpty()) {
964 int alenIdx = writeAttr(names.Exceptions);
965 databuf.appendChar(thrown.length());
966 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
967 databuf.appendChar(pool.put(l.head.tsym));
968 endAttr(alenIdx);
969 acount++;
970 }
971 if (m.defaultValue != null) {
972 int alenIdx = writeAttr(names.AnnotationDefault);
973 m.defaultValue.accept(awriter);
974 endAttr(alenIdx);
975 acount++;
976 }
977 acount += writeMemberAttrs(m);
978 acount += writeParameterAttrs(m);
979 endAttrs(acountIdx, acount);
980 }
982 /** Write code attribute of method.
983 */
984 void writeCode(Code code) {
985 databuf.appendChar(code.max_stack);
986 databuf.appendChar(code.max_locals);
987 databuf.appendInt(code.cp);
988 databuf.appendBytes(code.code, 0, code.cp);
989 databuf.appendChar(code.catchInfo.length());
990 for (List<char[]> l = code.catchInfo.toList();
991 l.nonEmpty();
992 l = l.tail) {
993 for (int i = 0; i < l.head.length; i++)
994 databuf.appendChar(l.head[i]);
995 }
996 int acountIdx = beginAttrs();
997 int acount = 0;
999 if (code.lineInfo.nonEmpty()) {
1000 int alenIdx = writeAttr(names.LineNumberTable);
1001 databuf.appendChar(code.lineInfo.length());
1002 for (List<char[]> l = code.lineInfo.reverse();
1003 l.nonEmpty();
1004 l = l.tail)
1005 for (int i = 0; i < l.head.length; i++)
1006 databuf.appendChar(l.head[i]);
1007 endAttr(alenIdx);
1008 acount++;
1009 }
1011 if (genCrt && (code.crt != null)) {
1012 CRTable crt = code.crt;
1013 int alenIdx = writeAttr(names.CharacterRangeTable);
1014 int crtIdx = beginAttrs();
1015 int crtEntries = crt.writeCRT(databuf, code.lineMap, log);
1016 endAttrs(crtIdx, crtEntries);
1017 endAttr(alenIdx);
1018 acount++;
1019 }
1021 // counter for number of generic local variables
1022 int nGenericVars = 0;
1024 if (code.varBufferSize > 0) {
1025 int alenIdx = writeAttr(names.LocalVariableTable);
1026 databuf.appendChar(code.varBufferSize);
1028 for (int i=0; i<code.varBufferSize; i++) {
1029 Code.LocalVar var = code.varBuffer[i];
1031 // write variable info
1032 Assert.check(var.start_pc >= 0
1033 && var.start_pc <= code.cp);
1034 databuf.appendChar(var.start_pc);
1035 Assert.check(var.length >= 0
1036 && (var.start_pc + var.length) <= code.cp);
1037 databuf.appendChar(var.length);
1038 VarSymbol sym = var.sym;
1039 databuf.appendChar(pool.put(sym.name));
1040 Type vartype = sym.erasure(types);
1041 if (needsLocalVariableTypeEntry(sym.type))
1042 nGenericVars++;
1043 databuf.appendChar(pool.put(typeSig(vartype)));
1044 databuf.appendChar(var.reg);
1045 }
1046 endAttr(alenIdx);
1047 acount++;
1048 }
1050 if (nGenericVars > 0) {
1051 int alenIdx = writeAttr(names.LocalVariableTypeTable);
1052 databuf.appendChar(nGenericVars);
1053 int count = 0;
1055 for (int i=0; i<code.varBufferSize; i++) {
1056 Code.LocalVar var = code.varBuffer[i];
1057 VarSymbol sym = var.sym;
1058 if (!needsLocalVariableTypeEntry(sym.type))
1059 continue;
1060 count++;
1061 // write variable info
1062 databuf.appendChar(var.start_pc);
1063 databuf.appendChar(var.length);
1064 databuf.appendChar(pool.put(sym.name));
1065 databuf.appendChar(pool.put(typeSig(sym.type)));
1066 databuf.appendChar(var.reg);
1067 }
1068 Assert.check(count == nGenericVars);
1069 endAttr(alenIdx);
1070 acount++;
1071 }
1073 if (code.stackMapBufferSize > 0) {
1074 if (debugstackmap) System.out.println("Stack map for " + code.meth);
1075 int alenIdx = writeAttr(code.stackMap.getAttributeName(names));
1076 writeStackMap(code);
1077 endAttr(alenIdx);
1078 acount++;
1079 }
1080 endAttrs(acountIdx, acount);
1081 }
1082 //where
1083 private boolean needsLocalVariableTypeEntry(Type t) {
1084 //a local variable needs a type-entry if its type T is generic
1085 //(i.e. |T| != T) and if it's not an intersection type (not supported
1086 //in signature attribute grammar)
1087 return (!types.isSameType(t, types.erasure(t)) &&
1088 !t.isCompound());
1089 }
1091 void writeStackMap(Code code) {
1092 int nframes = code.stackMapBufferSize;
1093 if (debugstackmap) System.out.println(" nframes = " + nframes);
1094 databuf.appendChar(nframes);
1096 switch (code.stackMap) {
1097 case CLDC:
1098 for (int i=0; i<nframes; i++) {
1099 if (debugstackmap) System.out.print(" " + i + ":");
1100 Code.StackMapFrame frame = code.stackMapBuffer[i];
1102 // output PC
1103 if (debugstackmap) System.out.print(" pc=" + frame.pc);
1104 databuf.appendChar(frame.pc);
1106 // output locals
1107 int localCount = 0;
1108 for (int j=0; j<frame.locals.length;
1109 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1110 localCount++;
1111 }
1112 if (debugstackmap) System.out.print(" nlocals=" +
1113 localCount);
1114 databuf.appendChar(localCount);
1115 for (int j=0; j<frame.locals.length;
1116 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1117 if (debugstackmap) System.out.print(" local[" + j + "]=");
1118 writeStackMapType(frame.locals[j]);
1119 }
1121 // output stack
1122 int stackCount = 0;
1123 for (int j=0; j<frame.stack.length;
1124 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1125 stackCount++;
1126 }
1127 if (debugstackmap) System.out.print(" nstack=" +
1128 stackCount);
1129 databuf.appendChar(stackCount);
1130 for (int j=0; j<frame.stack.length;
1131 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1132 if (debugstackmap) System.out.print(" stack[" + j + "]=");
1133 writeStackMapType(frame.stack[j]);
1134 }
1135 if (debugstackmap) System.out.println();
1136 }
1137 break;
1138 case JSR202: {
1139 Assert.checkNull(code.stackMapBuffer);
1140 for (int i=0; i<nframes; i++) {
1141 if (debugstackmap) System.out.print(" " + i + ":");
1142 StackMapTableFrame frame = code.stackMapTableBuffer[i];
1143 frame.write(this);
1144 if (debugstackmap) System.out.println();
1145 }
1146 break;
1147 }
1148 default:
1149 throw new AssertionError("Unexpected stackmap format value");
1150 }
1151 }
1153 //where
1154 void writeStackMapType(Type t) {
1155 if (t == null) {
1156 if (debugstackmap) System.out.print("empty");
1157 databuf.appendByte(0);
1158 }
1159 else switch(t.tag) {
1160 case BYTE:
1161 case CHAR:
1162 case SHORT:
1163 case INT:
1164 case BOOLEAN:
1165 if (debugstackmap) System.out.print("int");
1166 databuf.appendByte(1);
1167 break;
1168 case FLOAT:
1169 if (debugstackmap) System.out.print("float");
1170 databuf.appendByte(2);
1171 break;
1172 case DOUBLE:
1173 if (debugstackmap) System.out.print("double");
1174 databuf.appendByte(3);
1175 break;
1176 case LONG:
1177 if (debugstackmap) System.out.print("long");
1178 databuf.appendByte(4);
1179 break;
1180 case BOT: // null
1181 if (debugstackmap) System.out.print("null");
1182 databuf.appendByte(5);
1183 break;
1184 case CLASS:
1185 case ARRAY:
1186 if (debugstackmap) System.out.print("object(" + t + ")");
1187 databuf.appendByte(7);
1188 databuf.appendChar(pool.put(t));
1189 break;
1190 case TYPEVAR:
1191 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")");
1192 databuf.appendByte(7);
1193 databuf.appendChar(pool.put(types.erasure(t).tsym));
1194 break;
1195 case UNINITIALIZED_THIS:
1196 if (debugstackmap) System.out.print("uninit_this");
1197 databuf.appendByte(6);
1198 break;
1199 case UNINITIALIZED_OBJECT:
1200 { UninitializedType uninitType = (UninitializedType)t;
1201 databuf.appendByte(8);
1202 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset);
1203 databuf.appendChar(uninitType.offset);
1204 }
1205 break;
1206 default:
1207 throw new AssertionError();
1208 }
1209 }
1211 /** An entry in the JSR202 StackMapTable */
1212 abstract static class StackMapTableFrame {
1213 abstract int getFrameType();
1215 void write(ClassWriter writer) {
1216 int frameType = getFrameType();
1217 writer.databuf.appendByte(frameType);
1218 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType);
1219 }
1221 static class SameFrame extends StackMapTableFrame {
1222 final int offsetDelta;
1223 SameFrame(int offsetDelta) {
1224 this.offsetDelta = offsetDelta;
1225 }
1226 int getFrameType() {
1227 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED;
1228 }
1229 @Override
1230 void write(ClassWriter writer) {
1231 super.write(writer);
1232 if (getFrameType() == SAME_FRAME_EXTENDED) {
1233 writer.databuf.appendChar(offsetDelta);
1234 if (writer.debugstackmap){
1235 System.out.print(" offset_delta=" + offsetDelta);
1236 }
1237 }
1238 }
1239 }
1241 static class SameLocals1StackItemFrame extends StackMapTableFrame {
1242 final int offsetDelta;
1243 final Type stack;
1244 SameLocals1StackItemFrame(int offsetDelta, Type stack) {
1245 this.offsetDelta = offsetDelta;
1246 this.stack = stack;
1247 }
1248 int getFrameType() {
1249 return (offsetDelta < SAME_FRAME_SIZE) ?
1250 (SAME_FRAME_SIZE + offsetDelta) :
1251 SAME_LOCALS_1_STACK_ITEM_EXTENDED;
1252 }
1253 @Override
1254 void write(ClassWriter writer) {
1255 super.write(writer);
1256 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) {
1257 writer.databuf.appendChar(offsetDelta);
1258 if (writer.debugstackmap) {
1259 System.out.print(" offset_delta=" + offsetDelta);
1260 }
1261 }
1262 if (writer.debugstackmap) {
1263 System.out.print(" stack[" + 0 + "]=");
1264 }
1265 writer.writeStackMapType(stack);
1266 }
1267 }
1269 static class ChopFrame extends StackMapTableFrame {
1270 final int frameType;
1271 final int offsetDelta;
1272 ChopFrame(int frameType, int offsetDelta) {
1273 this.frameType = frameType;
1274 this.offsetDelta = offsetDelta;
1275 }
1276 int getFrameType() { return frameType; }
1277 @Override
1278 void write(ClassWriter writer) {
1279 super.write(writer);
1280 writer.databuf.appendChar(offsetDelta);
1281 if (writer.debugstackmap) {
1282 System.out.print(" offset_delta=" + offsetDelta);
1283 }
1284 }
1285 }
1287 static class AppendFrame extends StackMapTableFrame {
1288 final int frameType;
1289 final int offsetDelta;
1290 final Type[] locals;
1291 AppendFrame(int frameType, int offsetDelta, Type[] locals) {
1292 this.frameType = frameType;
1293 this.offsetDelta = offsetDelta;
1294 this.locals = locals;
1295 }
1296 int getFrameType() { return frameType; }
1297 @Override
1298 void write(ClassWriter writer) {
1299 super.write(writer);
1300 writer.databuf.appendChar(offsetDelta);
1301 if (writer.debugstackmap) {
1302 System.out.print(" offset_delta=" + offsetDelta);
1303 }
1304 for (int i=0; i<locals.length; i++) {
1305 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1306 writer.writeStackMapType(locals[i]);
1307 }
1308 }
1309 }
1311 static class FullFrame extends StackMapTableFrame {
1312 final int offsetDelta;
1313 final Type[] locals;
1314 final Type[] stack;
1315 FullFrame(int offsetDelta, Type[] locals, Type[] stack) {
1316 this.offsetDelta = offsetDelta;
1317 this.locals = locals;
1318 this.stack = stack;
1319 }
1320 int getFrameType() { return FULL_FRAME; }
1321 @Override
1322 void write(ClassWriter writer) {
1323 super.write(writer);
1324 writer.databuf.appendChar(offsetDelta);
1325 writer.databuf.appendChar(locals.length);
1326 if (writer.debugstackmap) {
1327 System.out.print(" offset_delta=" + offsetDelta);
1328 System.out.print(" nlocals=" + locals.length);
1329 }
1330 for (int i=0; i<locals.length; i++) {
1331 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1332 writer.writeStackMapType(locals[i]);
1333 }
1335 writer.databuf.appendChar(stack.length);
1336 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); }
1337 for (int i=0; i<stack.length; i++) {
1338 if (writer.debugstackmap) System.out.print(" stack[" + i + "]=");
1339 writer.writeStackMapType(stack[i]);
1340 }
1341 }
1342 }
1344 /** Compare this frame with the previous frame and produce
1345 * an entry of compressed stack map frame. */
1346 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame,
1347 int prev_pc,
1348 Type[] prev_locals,
1349 Types types) {
1350 Type[] locals = this_frame.locals;
1351 Type[] stack = this_frame.stack;
1352 int offset_delta = this_frame.pc - prev_pc - 1;
1353 if (stack.length == 1) {
1354 if (locals.length == prev_locals.length
1355 && compare(prev_locals, locals, types) == 0) {
1356 return new SameLocals1StackItemFrame(offset_delta, stack[0]);
1357 }
1358 } else if (stack.length == 0) {
1359 int diff_length = compare(prev_locals, locals, types);
1360 if (diff_length == 0) {
1361 return new SameFrame(offset_delta);
1362 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) {
1363 // APPEND
1364 Type[] local_diff = new Type[-diff_length];
1365 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) {
1366 local_diff[j] = locals[i];
1367 }
1368 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length,
1369 offset_delta,
1370 local_diff);
1371 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) {
1372 // CHOP
1373 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length,
1374 offset_delta);
1375 }
1376 }
1377 // FULL_FRAME
1378 return new FullFrame(offset_delta, locals, stack);
1379 }
1381 static boolean isInt(Type t) {
1382 return (t.tag < TypeTags.INT || t.tag == TypeTags.BOOLEAN);
1383 }
1385 static boolean isSameType(Type t1, Type t2, Types types) {
1386 if (t1 == null) { return t2 == null; }
1387 if (t2 == null) { return false; }
1389 if (isInt(t1) && isInt(t2)) { return true; }
1391 if (t1.tag == UNINITIALIZED_THIS) {
1392 return t2.tag == UNINITIALIZED_THIS;
1393 } else if (t1.tag == UNINITIALIZED_OBJECT) {
1394 if (t2.tag == UNINITIALIZED_OBJECT) {
1395 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset;
1396 } else {
1397 return false;
1398 }
1399 } else if (t2.tag == UNINITIALIZED_THIS || t2.tag == UNINITIALIZED_OBJECT) {
1400 return false;
1401 }
1403 return types.isSameType(t1, t2);
1404 }
1406 static int compare(Type[] arr1, Type[] arr2, Types types) {
1407 int diff_length = arr1.length - arr2.length;
1408 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) {
1409 return Integer.MAX_VALUE;
1410 }
1411 int len = (diff_length > 0) ? arr2.length : arr1.length;
1412 for (int i=0; i<len; i++) {
1413 if (!isSameType(arr1[i], arr2[i], types)) {
1414 return Integer.MAX_VALUE;
1415 }
1416 }
1417 return diff_length;
1418 }
1419 }
1421 void writeFields(Scope.Entry e) {
1422 // process them in reverse sibling order;
1423 // i.e., process them in declaration order.
1424 List<VarSymbol> vars = List.nil();
1425 for (Scope.Entry i = e; i != null; i = i.sibling) {
1426 if (i.sym.kind == VAR) vars = vars.prepend((VarSymbol)i.sym);
1427 }
1428 while (vars.nonEmpty()) {
1429 writeField(vars.head);
1430 vars = vars.tail;
1431 }
1432 }
1434 void writeMethods(Scope.Entry e) {
1435 List<MethodSymbol> methods = List.nil();
1436 for (Scope.Entry i = e; i != null; i = i.sibling) {
1437 if (i.sym.kind == MTH && (i.sym.flags() & HYPOTHETICAL) == 0)
1438 methods = methods.prepend((MethodSymbol)i.sym);
1439 }
1440 while (methods.nonEmpty()) {
1441 writeMethod(methods.head);
1442 methods = methods.tail;
1443 }
1444 }
1446 /** Emit a class file for a given class.
1447 * @param c The class from which a class file is generated.
1448 */
1449 public JavaFileObject writeClass(ClassSymbol c)
1450 throws IOException, PoolOverflow, StringOverflow
1451 {
1452 JavaFileObject outFile
1453 = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
1454 c.flatname.toString(),
1455 JavaFileObject.Kind.CLASS,
1456 c.sourcefile);
1457 OutputStream out = outFile.openOutputStream();
1458 try {
1459 writeClassFile(out, c);
1460 if (verbose)
1461 log.printVerbose("wrote.file", outFile);
1462 out.close();
1463 out = null;
1464 } finally {
1465 if (out != null) {
1466 // if we are propogating an exception, delete the file
1467 out.close();
1468 outFile.delete();
1469 outFile = null;
1470 }
1471 }
1472 return outFile; // may be null if write failed
1473 }
1475 /** Write class `c' to outstream `out'.
1476 */
1477 public void writeClassFile(OutputStream out, ClassSymbol c)
1478 throws IOException, PoolOverflow, StringOverflow {
1479 Assert.check((c.flags() & COMPOUND) == 0);
1480 databuf.reset();
1481 poolbuf.reset();
1482 sigbuf.reset();
1483 pool = c.pool;
1484 innerClasses = null;
1485 innerClassesQueue = null;
1487 Type supertype = types.supertype(c.type);
1488 List<Type> interfaces = types.interfaces(c.type);
1489 List<Type> typarams = c.type.getTypeArguments();
1491 int flags = adjustFlags(c.flags());
1492 if ((flags & PROTECTED) != 0) flags |= PUBLIC;
1493 flags = flags & ClassFlags & ~STRICTFP;
1494 if ((flags & INTERFACE) == 0) flags |= ACC_SUPER;
1495 if (c.isInner() && c.name.isEmpty()) flags &= ~FINAL;
1496 if (dumpClassModifiers) {
1497 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1498 pw.println();
1499 pw.println("CLASSFILE " + c.getQualifiedName());
1500 pw.println("---" + flagNames(flags));
1501 }
1502 databuf.appendChar(flags);
1504 databuf.appendChar(pool.put(c));
1505 databuf.appendChar(supertype.tag == CLASS ? pool.put(supertype.tsym) : 0);
1506 databuf.appendChar(interfaces.length());
1507 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1508 databuf.appendChar(pool.put(l.head.tsym));
1509 int fieldsCount = 0;
1510 int methodsCount = 0;
1511 for (Scope.Entry e = c.members().elems; e != null; e = e.sibling) {
1512 switch (e.sym.kind) {
1513 case VAR: fieldsCount++; break;
1514 case MTH: if ((e.sym.flags() & HYPOTHETICAL) == 0) methodsCount++;
1515 break;
1516 case TYP: enterInner((ClassSymbol)e.sym); break;
1517 default : Assert.error();
1518 }
1519 }
1521 if (c.trans_local != null) {
1522 for (ClassSymbol local : c.trans_local) {
1523 enterInner(local);
1524 }
1525 }
1527 databuf.appendChar(fieldsCount);
1528 writeFields(c.members().elems);
1529 databuf.appendChar(methodsCount);
1530 writeMethods(c.members().elems);
1532 int acountIdx = beginAttrs();
1533 int acount = 0;
1535 boolean sigReq =
1536 typarams.length() != 0 || supertype.allparams().length() != 0;
1537 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail)
1538 sigReq = l.head.allparams().length() != 0;
1539 if (sigReq) {
1540 Assert.check(source.allowGenerics());
1541 int alenIdx = writeAttr(names.Signature);
1542 if (typarams.length() != 0) assembleParamsSig(typarams);
1543 assembleSig(supertype);
1544 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1545 assembleSig(l.head);
1546 databuf.appendChar(pool.put(sigbuf.toName(names)));
1547 sigbuf.reset();
1548 endAttr(alenIdx);
1549 acount++;
1550 }
1552 if (c.sourcefile != null && emitSourceFile) {
1553 int alenIdx = writeAttr(names.SourceFile);
1554 // WHM 6/29/1999: Strip file path prefix. We do it here at
1555 // the last possible moment because the sourcefile may be used
1556 // elsewhere in error diagnostics. Fixes 4241573.
1557 //databuf.appendChar(c.pool.put(c.sourcefile));
1558 String simpleName = BaseFileObject.getSimpleName(c.sourcefile);
1559 databuf.appendChar(c.pool.put(names.fromString(simpleName)));
1560 endAttr(alenIdx);
1561 acount++;
1562 }
1564 if (genCrt) {
1565 // Append SourceID attribute
1566 int alenIdx = writeAttr(names.SourceID);
1567 databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile)))));
1568 endAttr(alenIdx);
1569 acount++;
1570 // Append CompilationID attribute
1571 alenIdx = writeAttr(names.CompilationID);
1572 databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis()))));
1573 endAttr(alenIdx);
1574 acount++;
1575 }
1577 acount += writeFlagAttrs(c.flags());
1578 acount += writeJavaAnnotations(c.getAnnotationMirrors());
1579 acount += writeEnclosingMethodAttribute(c);
1580 acount += writeExtraClassAttributes(c);
1582 poolbuf.appendInt(JAVA_MAGIC);
1583 poolbuf.appendChar(target.minorVersion);
1584 poolbuf.appendChar(target.majorVersion);
1586 writePool(c.pool);
1588 if (innerClasses != null) {
1589 writeInnerClasses();
1590 acount++;
1591 }
1592 endAttrs(acountIdx, acount);
1594 poolbuf.appendBytes(databuf.elems, 0, databuf.length);
1595 out.write(poolbuf.elems, 0, poolbuf.length);
1597 pool = c.pool = null; // to conserve space
1598 }
1600 /**Allows subclasses to write additional class attributes
1601 *
1602 * @return the number of attributes written
1603 */
1604 protected int writeExtraClassAttributes(ClassSymbol c) {
1605 return 0;
1606 }
1608 int adjustFlags(final long flags) {
1609 int result = (int)flags;
1610 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag())
1611 result &= ~SYNTHETIC;
1612 if ((flags & ENUM) != 0 && !target.useEnumFlag())
1613 result &= ~ENUM;
1614 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag())
1615 result &= ~ANNOTATION;
1617 if ((flags & BRIDGE) != 0 && target.useBridgeFlag())
1618 result |= ACC_BRIDGE;
1619 if ((flags & VARARGS) != 0 && target.useVarargsFlag())
1620 result |= ACC_VARARGS;
1621 return result;
1622 }
1624 long getLastModified(FileObject filename) {
1625 long mod = 0;
1626 try {
1627 mod = filename.getLastModified();
1628 } catch (SecurityException e) {
1629 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage());
1630 }
1631 return mod;
1632 }
1633 }