Tue, 08 Nov 2011 17:06:08 -0800
7108668: allow Log to be initialized and used earlier
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 1999, 2011, 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.OptionName.*;
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: scrable private names.
73 */
74 private boolean scramble;
76 /** Switch: scrable private names.
77 */
78 private boolean scrambleAll;
80 /** Switch: retrofit mode.
81 */
82 private boolean retrofit;
84 /** Switch: emit source file attribute.
85 */
86 private boolean emitSourceFile;
88 /** Switch: generate CharacterRangeTable attribute.
89 */
90 private boolean genCrt;
92 /** Switch: describe the generated stackmap
93 */
94 boolean debugstackmap;
96 /**
97 * Target class version.
98 */
99 private Target target;
101 /**
102 * Source language version.
103 */
104 private Source source;
106 /** Type utilities. */
107 private Types types;
109 /** The initial sizes of the data and constant pool buffers.
110 * sizes are increased when buffers get full.
111 */
112 static final int DATA_BUF_SIZE = 0x0fff0;
113 static final int POOL_BUF_SIZE = 0x1fff0;
115 /** An output buffer for member info.
116 */
117 ByteBuffer databuf = new ByteBuffer(DATA_BUF_SIZE);
119 /** An output buffer for the constant pool.
120 */
121 ByteBuffer poolbuf = new ByteBuffer(POOL_BUF_SIZE);
123 /** An output buffer for type signatures.
124 */
125 ByteBuffer sigbuf = new ByteBuffer();
127 /** The constant pool.
128 */
129 Pool pool;
131 /** The inner classes to be written, as a set.
132 */
133 Set<ClassSymbol> innerClasses;
135 /** The inner classes to be written, as a queue where
136 * enclosing classes come first.
137 */
138 ListBuffer<ClassSymbol> innerClassesQueue;
140 /** The log to use for verbose output.
141 */
142 private final Log log;
144 /** The name table. */
145 private final Names names;
147 /** Access to files. */
148 private final JavaFileManager fileManager;
150 /** The tags and constants used in compressed stackmap. */
151 static final int SAME_FRAME_SIZE = 64;
152 static final int SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247;
153 static final int SAME_FRAME_EXTENDED = 251;
154 static final int FULL_FRAME = 255;
155 static final int MAX_LOCAL_LENGTH_DIFF = 4;
157 /** Get the ClassWriter instance for this context. */
158 public static ClassWriter instance(Context context) {
159 ClassWriter instance = context.get(classWriterKey);
160 if (instance == null)
161 instance = new ClassWriter(context);
162 return instance;
163 }
165 /** Construct a class writer, given an options table.
166 */
167 private ClassWriter(Context context) {
168 context.put(classWriterKey, this);
170 log = Log.instance(context);
171 names = Names.instance(context);
172 syms = Symtab.instance(context);
173 options = Options.instance(context);
174 target = Target.instance(context);
175 source = Source.instance(context);
176 types = Types.instance(context);
177 fileManager = context.get(JavaFileManager.class);
179 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 c.owner.kind != MTH && // neither a local class
606 c.name != names.empty) // nor anonymous
607 return 0;
609 int alenIdx = writeAttr(names.EnclosingMethod);
610 ClassSymbol enclClass = c.owner.enclClass();
611 MethodSymbol enclMethod =
612 (c.owner.type == null // local to init block
613 || c.owner.kind != MTH) // or member init
614 ? null
615 : (MethodSymbol)c.owner;
616 databuf.appendChar(pool.put(enclClass));
617 databuf.appendChar(enclMethod == null ? 0 : pool.put(nameType(c.owner)));
618 endAttr(alenIdx);
619 return 1;
620 }
622 /** Write flag attributes; return number of attributes written.
623 */
624 int writeFlagAttrs(long flags) {
625 int acount = 0;
626 if ((flags & DEPRECATED) != 0) {
627 int alenIdx = writeAttr(names.Deprecated);
628 endAttr(alenIdx);
629 acount++;
630 }
631 if ((flags & ENUM) != 0 && !target.useEnumFlag()) {
632 int alenIdx = writeAttr(names.Enum);
633 endAttr(alenIdx);
634 acount++;
635 }
636 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag()) {
637 int alenIdx = writeAttr(names.Synthetic);
638 endAttr(alenIdx);
639 acount++;
640 }
641 if ((flags & BRIDGE) != 0 && !target.useBridgeFlag()) {
642 int alenIdx = writeAttr(names.Bridge);
643 endAttr(alenIdx);
644 acount++;
645 }
646 if ((flags & VARARGS) != 0 && !target.useVarargsFlag()) {
647 int alenIdx = writeAttr(names.Varargs);
648 endAttr(alenIdx);
649 acount++;
650 }
651 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag()) {
652 int alenIdx = writeAttr(names.Annotation);
653 endAttr(alenIdx);
654 acount++;
655 }
656 return acount;
657 }
659 /** Write member (field or method) attributes;
660 * return number of attributes written.
661 */
662 int writeMemberAttrs(Symbol sym) {
663 int acount = writeFlagAttrs(sym.flags());
664 long flags = sym.flags();
665 if (source.allowGenerics() &&
666 (flags & (SYNTHETIC|BRIDGE)) != SYNTHETIC &&
667 (flags & ANONCONSTR) == 0 &&
668 (!types.isSameType(sym.type, sym.erasure(types)) ||
669 hasTypeVar(sym.type.getThrownTypes()))) {
670 // note that a local class with captured variables
671 // will get a signature attribute
672 int alenIdx = writeAttr(names.Signature);
673 databuf.appendChar(pool.put(typeSig(sym.type)));
674 endAttr(alenIdx);
675 acount++;
676 }
677 acount += writeJavaAnnotations(sym.getAnnotationMirrors());
678 return acount;
679 }
681 /** Write method parameter annotations;
682 * return number of attributes written.
683 */
684 int writeParameterAttrs(MethodSymbol m) {
685 boolean hasVisible = false;
686 boolean hasInvisible = false;
687 if (m.params != null) for (VarSymbol s : m.params) {
688 for (Attribute.Compound a : s.getAnnotationMirrors()) {
689 switch (types.getRetention(a)) {
690 case SOURCE: break;
691 case CLASS: hasInvisible = true; break;
692 case RUNTIME: hasVisible = true; break;
693 default: ;// /* fail soft */ throw new AssertionError(vis);
694 }
695 }
696 }
698 int attrCount = 0;
699 if (hasVisible) {
700 int attrIndex = writeAttr(names.RuntimeVisibleParameterAnnotations);
701 databuf.appendByte(m.params.length());
702 for (VarSymbol s : m.params) {
703 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
704 for (Attribute.Compound a : s.getAnnotationMirrors())
705 if (types.getRetention(a) == RetentionPolicy.RUNTIME)
706 buf.append(a);
707 databuf.appendChar(buf.length());
708 for (Attribute.Compound a : buf)
709 writeCompoundAttribute(a);
710 }
711 endAttr(attrIndex);
712 attrCount++;
713 }
714 if (hasInvisible) {
715 int attrIndex = writeAttr(names.RuntimeInvisibleParameterAnnotations);
716 databuf.appendByte(m.params.length());
717 for (VarSymbol s : m.params) {
718 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
719 for (Attribute.Compound a : s.getAnnotationMirrors())
720 if (types.getRetention(a) == RetentionPolicy.CLASS)
721 buf.append(a);
722 databuf.appendChar(buf.length());
723 for (Attribute.Compound a : buf)
724 writeCompoundAttribute(a);
725 }
726 endAttr(attrIndex);
727 attrCount++;
728 }
729 return attrCount;
730 }
732 /**********************************************************************
733 * Writing Java-language annotations (aka metadata, attributes)
734 **********************************************************************/
736 /** Write Java-language annotations; return number of JVM
737 * attributes written (zero or one).
738 */
739 int writeJavaAnnotations(List<Attribute.Compound> attrs) {
740 if (attrs.isEmpty()) return 0;
741 ListBuffer<Attribute.Compound> visibles = new ListBuffer<Attribute.Compound>();
742 ListBuffer<Attribute.Compound> invisibles = new ListBuffer<Attribute.Compound>();
743 for (Attribute.Compound a : attrs) {
744 switch (types.getRetention(a)) {
745 case SOURCE: break;
746 case CLASS: invisibles.append(a); break;
747 case RUNTIME: visibles.append(a); break;
748 default: ;// /* fail soft */ throw new AssertionError(vis);
749 }
750 }
752 int attrCount = 0;
753 if (visibles.length() != 0) {
754 int attrIndex = writeAttr(names.RuntimeVisibleAnnotations);
755 databuf.appendChar(visibles.length());
756 for (Attribute.Compound a : visibles)
757 writeCompoundAttribute(a);
758 endAttr(attrIndex);
759 attrCount++;
760 }
761 if (invisibles.length() != 0) {
762 int attrIndex = writeAttr(names.RuntimeInvisibleAnnotations);
763 databuf.appendChar(invisibles.length());
764 for (Attribute.Compound a : invisibles)
765 writeCompoundAttribute(a);
766 endAttr(attrIndex);
767 attrCount++;
768 }
769 return attrCount;
770 }
772 /** A visitor to write an attribute including its leading
773 * single-character marker.
774 */
775 class AttributeWriter implements Attribute.Visitor {
776 public void visitConstant(Attribute.Constant _value) {
777 Object value = _value.value;
778 switch (_value.type.tag) {
779 case BYTE:
780 databuf.appendByte('B');
781 break;
782 case CHAR:
783 databuf.appendByte('C');
784 break;
785 case SHORT:
786 databuf.appendByte('S');
787 break;
788 case INT:
789 databuf.appendByte('I');
790 break;
791 case LONG:
792 databuf.appendByte('J');
793 break;
794 case FLOAT:
795 databuf.appendByte('F');
796 break;
797 case DOUBLE:
798 databuf.appendByte('D');
799 break;
800 case BOOLEAN:
801 databuf.appendByte('Z');
802 break;
803 case CLASS:
804 Assert.check(value instanceof String);
805 databuf.appendByte('s');
806 value = names.fromString(value.toString()); // CONSTANT_Utf8
807 break;
808 default:
809 throw new AssertionError(_value.type);
810 }
811 databuf.appendChar(pool.put(value));
812 }
813 public void visitEnum(Attribute.Enum e) {
814 databuf.appendByte('e');
815 databuf.appendChar(pool.put(typeSig(e.value.type)));
816 databuf.appendChar(pool.put(e.value.name));
817 }
818 public void visitClass(Attribute.Class clazz) {
819 databuf.appendByte('c');
820 databuf.appendChar(pool.put(typeSig(clazz.type)));
821 }
822 public void visitCompound(Attribute.Compound compound) {
823 databuf.appendByte('@');
824 writeCompoundAttribute(compound);
825 }
826 public void visitError(Attribute.Error x) {
827 throw new AssertionError(x);
828 }
829 public void visitArray(Attribute.Array array) {
830 databuf.appendByte('[');
831 databuf.appendChar(array.values.length);
832 for (Attribute a : array.values) {
833 a.accept(this);
834 }
835 }
836 }
837 AttributeWriter awriter = new AttributeWriter();
839 /** Write a compound attribute excluding the '@' marker. */
840 void writeCompoundAttribute(Attribute.Compound c) {
841 databuf.appendChar(pool.put(typeSig(c.type)));
842 databuf.appendChar(c.values.length());
843 for (Pair<Symbol.MethodSymbol,Attribute> p : c.values) {
844 databuf.appendChar(pool.put(p.fst.name));
845 p.snd.accept(awriter);
846 }
847 }
848 /**********************************************************************
849 * Writing Objects
850 **********************************************************************/
852 /** Enter an inner class into the `innerClasses' set/queue.
853 */
854 void enterInner(ClassSymbol c) {
855 if (c.type.isCompound()) {
856 throw new AssertionError("Unexpected intersection type: " + c.type);
857 }
858 try {
859 c.complete();
860 } catch (CompletionFailure ex) {
861 System.err.println("error: " + c + ": " + ex.getMessage());
862 throw ex;
863 }
864 if (c.type.tag != CLASS) return; // arrays
865 if (pool != null && // pool might be null if called from xClassName
866 c.owner.enclClass() != null &&
867 (innerClasses == null || !innerClasses.contains(c))) {
868 // log.errWriter.println("enter inner " + c);//DEBUG
869 enterInner(c.owner.enclClass());
870 pool.put(c);
871 pool.put(c.name);
872 if (innerClasses == null) {
873 innerClasses = new HashSet<ClassSymbol>();
874 innerClassesQueue = new ListBuffer<ClassSymbol>();
875 pool.put(names.InnerClasses);
876 }
877 innerClasses.add(c);
878 innerClassesQueue.append(c);
879 }
880 }
882 /** Write "inner classes" attribute.
883 */
884 void writeInnerClasses() {
885 int alenIdx = writeAttr(names.InnerClasses);
886 databuf.appendChar(innerClassesQueue.length());
887 for (List<ClassSymbol> l = innerClassesQueue.toList();
888 l.nonEmpty();
889 l = l.tail) {
890 ClassSymbol inner = l.head;
891 char flags = (char) adjustFlags(inner.flags_field);
892 if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT
893 if (inner.name.isEmpty()) flags &= ~FINAL; // Anonymous class: unset FINAL flag
894 if (dumpInnerClassModifiers) {
895 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
896 pw.println("INNERCLASS " + inner.name);
897 pw.println("---" + flagNames(flags));
898 }
899 databuf.appendChar(pool.get(inner));
900 databuf.appendChar(
901 inner.owner.kind == TYP ? pool.get(inner.owner) : 0);
902 databuf.appendChar(
903 !inner.name.isEmpty() ? pool.get(inner.name) : 0);
904 databuf.appendChar(flags);
905 }
906 endAttr(alenIdx);
907 }
909 /** Write field symbol, entering all references into constant pool.
910 */
911 void writeField(VarSymbol v) {
912 int flags = adjustFlags(v.flags());
913 databuf.appendChar(flags);
914 if (dumpFieldModifiers) {
915 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
916 pw.println("FIELD " + fieldName(v));
917 pw.println("---" + flagNames(v.flags()));
918 }
919 databuf.appendChar(pool.put(fieldName(v)));
920 databuf.appendChar(pool.put(typeSig(v.erasure(types))));
921 int acountIdx = beginAttrs();
922 int acount = 0;
923 if (v.getConstValue() != null) {
924 int alenIdx = writeAttr(names.ConstantValue);
925 databuf.appendChar(pool.put(v.getConstValue()));
926 endAttr(alenIdx);
927 acount++;
928 }
929 acount += writeMemberAttrs(v);
930 endAttrs(acountIdx, acount);
931 }
933 /** Write method symbol, entering all references into constant pool.
934 */
935 void writeMethod(MethodSymbol m) {
936 int flags = adjustFlags(m.flags());
937 databuf.appendChar(flags);
938 if (dumpMethodModifiers) {
939 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
940 pw.println("METHOD " + fieldName(m));
941 pw.println("---" + flagNames(m.flags()));
942 }
943 databuf.appendChar(pool.put(fieldName(m)));
944 databuf.appendChar(pool.put(typeSig(m.externalType(types))));
945 int acountIdx = beginAttrs();
946 int acount = 0;
947 if (m.code != null) {
948 int alenIdx = writeAttr(names.Code);
949 writeCode(m.code);
950 m.code = null; // to conserve space
951 endAttr(alenIdx);
952 acount++;
953 }
954 List<Type> thrown = m.erasure(types).getThrownTypes();
955 if (thrown.nonEmpty()) {
956 int alenIdx = writeAttr(names.Exceptions);
957 databuf.appendChar(thrown.length());
958 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
959 databuf.appendChar(pool.put(l.head.tsym));
960 endAttr(alenIdx);
961 acount++;
962 }
963 if (m.defaultValue != null) {
964 int alenIdx = writeAttr(names.AnnotationDefault);
965 m.defaultValue.accept(awriter);
966 endAttr(alenIdx);
967 acount++;
968 }
969 acount += writeMemberAttrs(m);
970 acount += writeParameterAttrs(m);
971 endAttrs(acountIdx, acount);
972 }
974 /** Write code attribute of method.
975 */
976 void writeCode(Code code) {
977 databuf.appendChar(code.max_stack);
978 databuf.appendChar(code.max_locals);
979 databuf.appendInt(code.cp);
980 databuf.appendBytes(code.code, 0, code.cp);
981 databuf.appendChar(code.catchInfo.length());
982 for (List<char[]> l = code.catchInfo.toList();
983 l.nonEmpty();
984 l = l.tail) {
985 for (int i = 0; i < l.head.length; i++)
986 databuf.appendChar(l.head[i]);
987 }
988 int acountIdx = beginAttrs();
989 int acount = 0;
991 if (code.lineInfo.nonEmpty()) {
992 int alenIdx = writeAttr(names.LineNumberTable);
993 databuf.appendChar(code.lineInfo.length());
994 for (List<char[]> l = code.lineInfo.reverse();
995 l.nonEmpty();
996 l = l.tail)
997 for (int i = 0; i < l.head.length; i++)
998 databuf.appendChar(l.head[i]);
999 endAttr(alenIdx);
1000 acount++;
1001 }
1003 if (genCrt && (code.crt != null)) {
1004 CRTable crt = code.crt;
1005 int alenIdx = writeAttr(names.CharacterRangeTable);
1006 int crtIdx = beginAttrs();
1007 int crtEntries = crt.writeCRT(databuf, code.lineMap, log);
1008 endAttrs(crtIdx, crtEntries);
1009 endAttr(alenIdx);
1010 acount++;
1011 }
1013 // counter for number of generic local variables
1014 int nGenericVars = 0;
1016 if (code.varBufferSize > 0) {
1017 int alenIdx = writeAttr(names.LocalVariableTable);
1018 databuf.appendChar(code.varBufferSize);
1020 for (int i=0; i<code.varBufferSize; i++) {
1021 Code.LocalVar var = code.varBuffer[i];
1023 // write variable info
1024 Assert.check(var.start_pc >= 0
1025 && var.start_pc <= code.cp);
1026 databuf.appendChar(var.start_pc);
1027 Assert.check(var.length >= 0
1028 && (var.start_pc + var.length) <= code.cp);
1029 databuf.appendChar(var.length);
1030 VarSymbol sym = var.sym;
1031 databuf.appendChar(pool.put(sym.name));
1032 Type vartype = sym.erasure(types);
1033 if (needsLocalVariableTypeEntry(sym.type))
1034 nGenericVars++;
1035 databuf.appendChar(pool.put(typeSig(vartype)));
1036 databuf.appendChar(var.reg);
1037 }
1038 endAttr(alenIdx);
1039 acount++;
1040 }
1042 if (nGenericVars > 0) {
1043 int alenIdx = writeAttr(names.LocalVariableTypeTable);
1044 databuf.appendChar(nGenericVars);
1045 int count = 0;
1047 for (int i=0; i<code.varBufferSize; i++) {
1048 Code.LocalVar var = code.varBuffer[i];
1049 VarSymbol sym = var.sym;
1050 if (!needsLocalVariableTypeEntry(sym.type))
1051 continue;
1052 count++;
1053 // write variable info
1054 databuf.appendChar(var.start_pc);
1055 databuf.appendChar(var.length);
1056 databuf.appendChar(pool.put(sym.name));
1057 databuf.appendChar(pool.put(typeSig(sym.type)));
1058 databuf.appendChar(var.reg);
1059 }
1060 Assert.check(count == nGenericVars);
1061 endAttr(alenIdx);
1062 acount++;
1063 }
1065 if (code.stackMapBufferSize > 0) {
1066 if (debugstackmap) System.out.println("Stack map for " + code.meth);
1067 int alenIdx = writeAttr(code.stackMap.getAttributeName(names));
1068 writeStackMap(code);
1069 endAttr(alenIdx);
1070 acount++;
1071 }
1072 endAttrs(acountIdx, acount);
1073 }
1074 //where
1075 private boolean needsLocalVariableTypeEntry(Type t) {
1076 //a local variable needs a type-entry if its type T is generic
1077 //(i.e. |T| != T) and if it's not an intersection type (not supported
1078 //in signature attribute grammar)
1079 return (!types.isSameType(t, types.erasure(t)) &&
1080 !t.isCompound());
1081 }
1083 void writeStackMap(Code code) {
1084 int nframes = code.stackMapBufferSize;
1085 if (debugstackmap) System.out.println(" nframes = " + nframes);
1086 databuf.appendChar(nframes);
1088 switch (code.stackMap) {
1089 case CLDC:
1090 for (int i=0; i<nframes; i++) {
1091 if (debugstackmap) System.out.print(" " + i + ":");
1092 Code.StackMapFrame frame = code.stackMapBuffer[i];
1094 // output PC
1095 if (debugstackmap) System.out.print(" pc=" + frame.pc);
1096 databuf.appendChar(frame.pc);
1098 // output locals
1099 int localCount = 0;
1100 for (int j=0; j<frame.locals.length;
1101 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1102 localCount++;
1103 }
1104 if (debugstackmap) System.out.print(" nlocals=" +
1105 localCount);
1106 databuf.appendChar(localCount);
1107 for (int j=0; j<frame.locals.length;
1108 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1109 if (debugstackmap) System.out.print(" local[" + j + "]=");
1110 writeStackMapType(frame.locals[j]);
1111 }
1113 // output stack
1114 int stackCount = 0;
1115 for (int j=0; j<frame.stack.length;
1116 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1117 stackCount++;
1118 }
1119 if (debugstackmap) System.out.print(" nstack=" +
1120 stackCount);
1121 databuf.appendChar(stackCount);
1122 for (int j=0; j<frame.stack.length;
1123 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1124 if (debugstackmap) System.out.print(" stack[" + j + "]=");
1125 writeStackMapType(frame.stack[j]);
1126 }
1127 if (debugstackmap) System.out.println();
1128 }
1129 break;
1130 case JSR202: {
1131 Assert.checkNull(code.stackMapBuffer);
1132 for (int i=0; i<nframes; i++) {
1133 if (debugstackmap) System.out.print(" " + i + ":");
1134 StackMapTableFrame frame = code.stackMapTableBuffer[i];
1135 frame.write(this);
1136 if (debugstackmap) System.out.println();
1137 }
1138 break;
1139 }
1140 default:
1141 throw new AssertionError("Unexpected stackmap format value");
1142 }
1143 }
1145 //where
1146 void writeStackMapType(Type t) {
1147 if (t == null) {
1148 if (debugstackmap) System.out.print("empty");
1149 databuf.appendByte(0);
1150 }
1151 else switch(t.tag) {
1152 case BYTE:
1153 case CHAR:
1154 case SHORT:
1155 case INT:
1156 case BOOLEAN:
1157 if (debugstackmap) System.out.print("int");
1158 databuf.appendByte(1);
1159 break;
1160 case FLOAT:
1161 if (debugstackmap) System.out.print("float");
1162 databuf.appendByte(2);
1163 break;
1164 case DOUBLE:
1165 if (debugstackmap) System.out.print("double");
1166 databuf.appendByte(3);
1167 break;
1168 case LONG:
1169 if (debugstackmap) System.out.print("long");
1170 databuf.appendByte(4);
1171 break;
1172 case BOT: // null
1173 if (debugstackmap) System.out.print("null");
1174 databuf.appendByte(5);
1175 break;
1176 case CLASS:
1177 case ARRAY:
1178 if (debugstackmap) System.out.print("object(" + t + ")");
1179 databuf.appendByte(7);
1180 databuf.appendChar(pool.put(t));
1181 break;
1182 case TYPEVAR:
1183 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")");
1184 databuf.appendByte(7);
1185 databuf.appendChar(pool.put(types.erasure(t).tsym));
1186 break;
1187 case UNINITIALIZED_THIS:
1188 if (debugstackmap) System.out.print("uninit_this");
1189 databuf.appendByte(6);
1190 break;
1191 case UNINITIALIZED_OBJECT:
1192 { UninitializedType uninitType = (UninitializedType)t;
1193 databuf.appendByte(8);
1194 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset);
1195 databuf.appendChar(uninitType.offset);
1196 }
1197 break;
1198 default:
1199 throw new AssertionError();
1200 }
1201 }
1203 /** An entry in the JSR202 StackMapTable */
1204 abstract static class StackMapTableFrame {
1205 abstract int getFrameType();
1207 void write(ClassWriter writer) {
1208 int frameType = getFrameType();
1209 writer.databuf.appendByte(frameType);
1210 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType);
1211 }
1213 static class SameFrame extends StackMapTableFrame {
1214 final int offsetDelta;
1215 SameFrame(int offsetDelta) {
1216 this.offsetDelta = offsetDelta;
1217 }
1218 int getFrameType() {
1219 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED;
1220 }
1221 @Override
1222 void write(ClassWriter writer) {
1223 super.write(writer);
1224 if (getFrameType() == SAME_FRAME_EXTENDED) {
1225 writer.databuf.appendChar(offsetDelta);
1226 if (writer.debugstackmap){
1227 System.out.print(" offset_delta=" + offsetDelta);
1228 }
1229 }
1230 }
1231 }
1233 static class SameLocals1StackItemFrame extends StackMapTableFrame {
1234 final int offsetDelta;
1235 final Type stack;
1236 SameLocals1StackItemFrame(int offsetDelta, Type stack) {
1237 this.offsetDelta = offsetDelta;
1238 this.stack = stack;
1239 }
1240 int getFrameType() {
1241 return (offsetDelta < SAME_FRAME_SIZE) ?
1242 (SAME_FRAME_SIZE + offsetDelta) :
1243 SAME_LOCALS_1_STACK_ITEM_EXTENDED;
1244 }
1245 @Override
1246 void write(ClassWriter writer) {
1247 super.write(writer);
1248 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) {
1249 writer.databuf.appendChar(offsetDelta);
1250 if (writer.debugstackmap) {
1251 System.out.print(" offset_delta=" + offsetDelta);
1252 }
1253 }
1254 if (writer.debugstackmap) {
1255 System.out.print(" stack[" + 0 + "]=");
1256 }
1257 writer.writeStackMapType(stack);
1258 }
1259 }
1261 static class ChopFrame extends StackMapTableFrame {
1262 final int frameType;
1263 final int offsetDelta;
1264 ChopFrame(int frameType, int offsetDelta) {
1265 this.frameType = frameType;
1266 this.offsetDelta = offsetDelta;
1267 }
1268 int getFrameType() { return frameType; }
1269 @Override
1270 void write(ClassWriter writer) {
1271 super.write(writer);
1272 writer.databuf.appendChar(offsetDelta);
1273 if (writer.debugstackmap) {
1274 System.out.print(" offset_delta=" + offsetDelta);
1275 }
1276 }
1277 }
1279 static class AppendFrame extends StackMapTableFrame {
1280 final int frameType;
1281 final int offsetDelta;
1282 final Type[] locals;
1283 AppendFrame(int frameType, int offsetDelta, Type[] locals) {
1284 this.frameType = frameType;
1285 this.offsetDelta = offsetDelta;
1286 this.locals = locals;
1287 }
1288 int getFrameType() { return frameType; }
1289 @Override
1290 void write(ClassWriter writer) {
1291 super.write(writer);
1292 writer.databuf.appendChar(offsetDelta);
1293 if (writer.debugstackmap) {
1294 System.out.print(" offset_delta=" + offsetDelta);
1295 }
1296 for (int i=0; i<locals.length; i++) {
1297 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1298 writer.writeStackMapType(locals[i]);
1299 }
1300 }
1301 }
1303 static class FullFrame extends StackMapTableFrame {
1304 final int offsetDelta;
1305 final Type[] locals;
1306 final Type[] stack;
1307 FullFrame(int offsetDelta, Type[] locals, Type[] stack) {
1308 this.offsetDelta = offsetDelta;
1309 this.locals = locals;
1310 this.stack = stack;
1311 }
1312 int getFrameType() { return FULL_FRAME; }
1313 @Override
1314 void write(ClassWriter writer) {
1315 super.write(writer);
1316 writer.databuf.appendChar(offsetDelta);
1317 writer.databuf.appendChar(locals.length);
1318 if (writer.debugstackmap) {
1319 System.out.print(" offset_delta=" + offsetDelta);
1320 System.out.print(" nlocals=" + locals.length);
1321 }
1322 for (int i=0; i<locals.length; i++) {
1323 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1324 writer.writeStackMapType(locals[i]);
1325 }
1327 writer.databuf.appendChar(stack.length);
1328 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); }
1329 for (int i=0; i<stack.length; i++) {
1330 if (writer.debugstackmap) System.out.print(" stack[" + i + "]=");
1331 writer.writeStackMapType(stack[i]);
1332 }
1333 }
1334 }
1336 /** Compare this frame with the previous frame and produce
1337 * an entry of compressed stack map frame. */
1338 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame,
1339 int prev_pc,
1340 Type[] prev_locals,
1341 Types types) {
1342 Type[] locals = this_frame.locals;
1343 Type[] stack = this_frame.stack;
1344 int offset_delta = this_frame.pc - prev_pc - 1;
1345 if (stack.length == 1) {
1346 if (locals.length == prev_locals.length
1347 && compare(prev_locals, locals, types) == 0) {
1348 return new SameLocals1StackItemFrame(offset_delta, stack[0]);
1349 }
1350 } else if (stack.length == 0) {
1351 int diff_length = compare(prev_locals, locals, types);
1352 if (diff_length == 0) {
1353 return new SameFrame(offset_delta);
1354 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) {
1355 // APPEND
1356 Type[] local_diff = new Type[-diff_length];
1357 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) {
1358 local_diff[j] = locals[i];
1359 }
1360 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length,
1361 offset_delta,
1362 local_diff);
1363 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) {
1364 // CHOP
1365 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length,
1366 offset_delta);
1367 }
1368 }
1369 // FULL_FRAME
1370 return new FullFrame(offset_delta, locals, stack);
1371 }
1373 static boolean isInt(Type t) {
1374 return (t.tag < TypeTags.INT || t.tag == TypeTags.BOOLEAN);
1375 }
1377 static boolean isSameType(Type t1, Type t2, Types types) {
1378 if (t1 == null) { return t2 == null; }
1379 if (t2 == null) { return false; }
1381 if (isInt(t1) && isInt(t2)) { return true; }
1383 if (t1.tag == UNINITIALIZED_THIS) {
1384 return t2.tag == UNINITIALIZED_THIS;
1385 } else if (t1.tag == UNINITIALIZED_OBJECT) {
1386 if (t2.tag == UNINITIALIZED_OBJECT) {
1387 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset;
1388 } else {
1389 return false;
1390 }
1391 } else if (t2.tag == UNINITIALIZED_THIS || t2.tag == UNINITIALIZED_OBJECT) {
1392 return false;
1393 }
1395 return types.isSameType(t1, t2);
1396 }
1398 static int compare(Type[] arr1, Type[] arr2, Types types) {
1399 int diff_length = arr1.length - arr2.length;
1400 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) {
1401 return Integer.MAX_VALUE;
1402 }
1403 int len = (diff_length > 0) ? arr2.length : arr1.length;
1404 for (int i=0; i<len; i++) {
1405 if (!isSameType(arr1[i], arr2[i], types)) {
1406 return Integer.MAX_VALUE;
1407 }
1408 }
1409 return diff_length;
1410 }
1411 }
1413 void writeFields(Scope.Entry e) {
1414 // process them in reverse sibling order;
1415 // i.e., process them in declaration order.
1416 List<VarSymbol> vars = List.nil();
1417 for (Scope.Entry i = e; i != null; i = i.sibling) {
1418 if (i.sym.kind == VAR) vars = vars.prepend((VarSymbol)i.sym);
1419 }
1420 while (vars.nonEmpty()) {
1421 writeField(vars.head);
1422 vars = vars.tail;
1423 }
1424 }
1426 void writeMethods(Scope.Entry e) {
1427 List<MethodSymbol> methods = List.nil();
1428 for (Scope.Entry i = e; i != null; i = i.sibling) {
1429 if (i.sym.kind == MTH && (i.sym.flags() & HYPOTHETICAL) == 0)
1430 methods = methods.prepend((MethodSymbol)i.sym);
1431 }
1432 while (methods.nonEmpty()) {
1433 writeMethod(methods.head);
1434 methods = methods.tail;
1435 }
1436 }
1438 /** Emit a class file for a given class.
1439 * @param c The class from which a class file is generated.
1440 */
1441 public JavaFileObject writeClass(ClassSymbol c)
1442 throws IOException, PoolOverflow, StringOverflow
1443 {
1444 JavaFileObject outFile
1445 = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
1446 c.flatname.toString(),
1447 JavaFileObject.Kind.CLASS,
1448 c.sourcefile);
1449 OutputStream out = outFile.openOutputStream();
1450 try {
1451 writeClassFile(out, c);
1452 if (verbose)
1453 log.printVerbose("wrote.file", outFile);
1454 out.close();
1455 out = null;
1456 } finally {
1457 if (out != null) {
1458 // if we are propogating an exception, delete the file
1459 out.close();
1460 outFile.delete();
1461 outFile = null;
1462 }
1463 }
1464 return outFile; // may be null if write failed
1465 }
1467 /** Write class `c' to outstream `out'.
1468 */
1469 public void writeClassFile(OutputStream out, ClassSymbol c)
1470 throws IOException, PoolOverflow, StringOverflow {
1471 Assert.check((c.flags() & COMPOUND) == 0);
1472 databuf.reset();
1473 poolbuf.reset();
1474 sigbuf.reset();
1475 pool = c.pool;
1476 innerClasses = null;
1477 innerClassesQueue = null;
1479 Type supertype = types.supertype(c.type);
1480 List<Type> interfaces = types.interfaces(c.type);
1481 List<Type> typarams = c.type.getTypeArguments();
1483 int flags = adjustFlags(c.flags());
1484 if ((flags & PROTECTED) != 0) flags |= PUBLIC;
1485 flags = flags & ClassFlags & ~STRICTFP;
1486 if ((flags & INTERFACE) == 0) flags |= ACC_SUPER;
1487 if (c.isInner() && c.name.isEmpty()) flags &= ~FINAL;
1488 if (dumpClassModifiers) {
1489 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1490 pw.println();
1491 pw.println("CLASSFILE " + c.getQualifiedName());
1492 pw.println("---" + flagNames(flags));
1493 }
1494 databuf.appendChar(flags);
1496 databuf.appendChar(pool.put(c));
1497 databuf.appendChar(supertype.tag == CLASS ? pool.put(supertype.tsym) : 0);
1498 databuf.appendChar(interfaces.length());
1499 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1500 databuf.appendChar(pool.put(l.head.tsym));
1501 int fieldsCount = 0;
1502 int methodsCount = 0;
1503 for (Scope.Entry e = c.members().elems; e != null; e = e.sibling) {
1504 switch (e.sym.kind) {
1505 case VAR: fieldsCount++; break;
1506 case MTH: if ((e.sym.flags() & HYPOTHETICAL) == 0) methodsCount++;
1507 break;
1508 case TYP: enterInner((ClassSymbol)e.sym); break;
1509 default : Assert.error();
1510 }
1511 }
1513 if (c.trans_local != null) {
1514 for (ClassSymbol local : c.trans_local) {
1515 enterInner(local);
1516 }
1517 }
1519 databuf.appendChar(fieldsCount);
1520 writeFields(c.members().elems);
1521 databuf.appendChar(methodsCount);
1522 writeMethods(c.members().elems);
1524 int acountIdx = beginAttrs();
1525 int acount = 0;
1527 boolean sigReq =
1528 typarams.length() != 0 || supertype.allparams().length() != 0;
1529 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail)
1530 sigReq = l.head.allparams().length() != 0;
1531 if (sigReq) {
1532 Assert.check(source.allowGenerics());
1533 int alenIdx = writeAttr(names.Signature);
1534 if (typarams.length() != 0) assembleParamsSig(typarams);
1535 assembleSig(supertype);
1536 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1537 assembleSig(l.head);
1538 databuf.appendChar(pool.put(sigbuf.toName(names)));
1539 sigbuf.reset();
1540 endAttr(alenIdx);
1541 acount++;
1542 }
1544 if (c.sourcefile != null && emitSourceFile) {
1545 int alenIdx = writeAttr(names.SourceFile);
1546 // WHM 6/29/1999: Strip file path prefix. We do it here at
1547 // the last possible moment because the sourcefile may be used
1548 // elsewhere in error diagnostics. Fixes 4241573.
1549 //databuf.appendChar(c.pool.put(c.sourcefile));
1550 String simpleName = BaseFileObject.getSimpleName(c.sourcefile);
1551 databuf.appendChar(c.pool.put(names.fromString(simpleName)));
1552 endAttr(alenIdx);
1553 acount++;
1554 }
1556 if (genCrt) {
1557 // Append SourceID attribute
1558 int alenIdx = writeAttr(names.SourceID);
1559 databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile)))));
1560 endAttr(alenIdx);
1561 acount++;
1562 // Append CompilationID attribute
1563 alenIdx = writeAttr(names.CompilationID);
1564 databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis()))));
1565 endAttr(alenIdx);
1566 acount++;
1567 }
1569 acount += writeFlagAttrs(c.flags());
1570 acount += writeJavaAnnotations(c.getAnnotationMirrors());
1571 acount += writeEnclosingMethodAttribute(c);
1573 poolbuf.appendInt(JAVA_MAGIC);
1574 poolbuf.appendChar(target.minorVersion);
1575 poolbuf.appendChar(target.majorVersion);
1577 writePool(c.pool);
1579 if (innerClasses != null) {
1580 writeInnerClasses();
1581 acount++;
1582 }
1583 endAttrs(acountIdx, acount);
1585 poolbuf.appendBytes(databuf.elems, 0, databuf.length);
1586 out.write(poolbuf.elems, 0, poolbuf.length);
1588 pool = c.pool = null; // to conserve space
1589 }
1591 int adjustFlags(final long flags) {
1592 int result = (int)flags;
1593 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag())
1594 result &= ~SYNTHETIC;
1595 if ((flags & ENUM) != 0 && !target.useEnumFlag())
1596 result &= ~ENUM;
1597 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag())
1598 result &= ~ANNOTATION;
1600 if ((flags & BRIDGE) != 0 && target.useBridgeFlag())
1601 result |= ACC_BRIDGE;
1602 if ((flags & VARARGS) != 0 && target.useVarargsFlag())
1603 result |= ACC_VARARGS;
1604 return result;
1605 }
1607 long getLastModified(FileObject filename) {
1608 long mod = 0;
1609 try {
1610 mod = filename.getLastModified();
1611 } catch (SecurityException e) {
1612 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage());
1613 }
1614 return mod;
1615 }
1616 }