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