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