Sun, 17 Feb 2013 16:44:55 -0500
Merge
1 /*
2 * Copyright (c) 1999, 2013, 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.lang.model.type.TypeKind;
35 import javax.tools.JavaFileManager;
36 import javax.tools.FileObject;
37 import javax.tools.JavaFileObject;
39 import com.sun.tools.javac.code.*;
40 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
41 import com.sun.tools.javac.code.Attribute.TypeCompound;
42 import com.sun.tools.javac.code.Symbol.*;
43 import com.sun.tools.javac.code.Type.*;
44 import com.sun.tools.javac.code.Types.UniqueType;
45 import com.sun.tools.javac.file.BaseFileObject;
46 import com.sun.tools.javac.jvm.Pool.DynamicMethod;
47 import com.sun.tools.javac.jvm.Pool.Method;
48 import com.sun.tools.javac.jvm.Pool.MethodHandle;
49 import com.sun.tools.javac.jvm.Pool.Variable;
50 import com.sun.tools.javac.util.*;
52 import static com.sun.tools.javac.code.Flags.*;
53 import static com.sun.tools.javac.code.Kinds.*;
54 import static com.sun.tools.javac.code.TypeTag.*;
55 import static com.sun.tools.javac.jvm.UninitializedType.*;
56 import static com.sun.tools.javac.main.Option.*;
57 import static javax.tools.StandardLocation.CLASS_OUTPUT;
60 /** This class provides operations to map an internal symbol table graph
61 * rooted in a ClassSymbol into a classfile.
62 *
63 * <p><b>This is NOT part of any supported API.
64 * If you write code that depends on this, you do so at your own risk.
65 * This code and its internal interfaces are subject to change or
66 * deletion without notice.</b>
67 */
68 public class ClassWriter extends ClassFile {
69 protected static final Context.Key<ClassWriter> classWriterKey =
70 new Context.Key<ClassWriter>();
72 private final Options options;
74 /** Switch: verbose output.
75 */
76 private boolean verbose;
78 /** Switch: scramble private field names.
79 */
80 private boolean scramble;
82 /** Switch: scramble all field names.
83 */
84 private boolean scrambleAll;
86 /** Switch: retrofit mode.
87 */
88 private boolean retrofit;
90 /** Switch: emit source file attribute.
91 */
92 private boolean emitSourceFile;
94 /** Switch: generate CharacterRangeTable attribute.
95 */
96 private boolean genCrt;
98 /** Switch: describe the generated stackmap.
99 */
100 boolean debugstackmap;
102 /**
103 * Target class version.
104 */
105 private Target target;
107 /**
108 * Source language version.
109 */
110 private Source source;
112 /** Type utilities. */
113 private Types types;
115 /** The initial sizes of the data and constant pool buffers.
116 * Sizes are increased when buffers get full.
117 */
118 static final int DATA_BUF_SIZE = 0x0fff0;
119 static final int POOL_BUF_SIZE = 0x1fff0;
121 /** An output buffer for member info.
122 */
123 ByteBuffer databuf = new ByteBuffer(DATA_BUF_SIZE);
125 /** An output buffer for the constant pool.
126 */
127 ByteBuffer poolbuf = new ByteBuffer(POOL_BUF_SIZE);
129 /** An output buffer for type signatures.
130 */
131 ByteBuffer sigbuf = new ByteBuffer();
133 /** The constant pool.
134 */
135 Pool pool;
137 /** The inner classes to be written, as a set.
138 */
139 Set<ClassSymbol> innerClasses;
141 /** The inner classes to be written, as a queue where
142 * enclosing classes come first.
143 */
144 ListBuffer<ClassSymbol> innerClassesQueue;
146 /** The bootstrap methods to be written in the corresponding class attribute
147 * (one for each invokedynamic)
148 */
149 Map<DynamicMethod, MethodHandle> bootstrapMethods;
151 /** The log to use for verbose output.
152 */
153 private final Log log;
155 /** The name table. */
156 private final Names names;
158 /** Access to files. */
159 private final JavaFileManager fileManager;
161 /** The tags and constants used in compressed stackmap. */
162 static final int SAME_FRAME_SIZE = 64;
163 static final int SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247;
164 static final int SAME_FRAME_EXTENDED = 251;
165 static final int FULL_FRAME = 255;
166 static final int MAX_LOCAL_LENGTH_DIFF = 4;
168 /** Get the ClassWriter instance for this context. */
169 public static ClassWriter instance(Context context) {
170 ClassWriter instance = context.get(classWriterKey);
171 if (instance == null)
172 instance = new ClassWriter(context);
173 return instance;
174 }
176 /** Construct a class writer, given an options table.
177 */
178 protected ClassWriter(Context context) {
179 context.put(classWriterKey, this);
181 log = Log.instance(context);
182 names = Names.instance(context);
183 options = Options.instance(context);
184 target = Target.instance(context);
185 source = Source.instance(context);
186 types = Types.instance(context);
187 fileManager = context.get(JavaFileManager.class);
189 verbose = options.isSet(VERBOSE);
190 scramble = options.isSet("-scramble");
191 scrambleAll = options.isSet("-scrambleAll");
192 retrofit = options.isSet("-retrofit");
193 genCrt = options.isSet(XJCOV);
194 debugstackmap = options.isSet("debugstackmap");
196 emitSourceFile = options.isUnset(G_CUSTOM) ||
197 options.isSet(G_CUSTOM, "source");
199 String dumpModFlags = options.get("dumpmodifiers");
200 dumpClassModifiers =
201 (dumpModFlags != null && dumpModFlags.indexOf('c') != -1);
202 dumpFieldModifiers =
203 (dumpModFlags != null && dumpModFlags.indexOf('f') != -1);
204 dumpInnerClassModifiers =
205 (dumpModFlags != null && dumpModFlags.indexOf('i') != -1);
206 dumpMethodModifiers =
207 (dumpModFlags != null && dumpModFlags.indexOf('m') != -1);
208 }
210 /******************************************************************
211 * Diagnostics: dump generated class names and modifiers
212 ******************************************************************/
214 /** Value of option 'dumpmodifiers' is a string
215 * indicating which modifiers should be dumped for debugging:
216 * 'c' -- classes
217 * 'f' -- fields
218 * 'i' -- innerclass attributes
219 * 'm' -- methods
220 * For example, to dump everything:
221 * javac -XDdumpmodifiers=cifm MyProg.java
222 */
223 private final boolean dumpClassModifiers; // -XDdumpmodifiers=c
224 private final boolean dumpFieldModifiers; // -XDdumpmodifiers=f
225 private final boolean dumpInnerClassModifiers; // -XDdumpmodifiers=i
226 private final boolean dumpMethodModifiers; // -XDdumpmodifiers=m
229 /** Return flags as a string, separated by " ".
230 */
231 public static String flagNames(long flags) {
232 StringBuilder sbuf = new StringBuilder();
233 int i = 0;
234 long f = flags & StandardFlags;
235 while (f != 0) {
236 if ((f & 1) != 0) {
237 sbuf.append(" ");
238 sbuf.append(flagName[i]);
239 }
240 f = f >> 1;
241 i++;
242 }
243 return sbuf.toString();
244 }
245 //where
246 private final static String[] flagName = {
247 "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL",
248 "SUPER", "VOLATILE", "TRANSIENT", "NATIVE", "INTERFACE",
249 "ABSTRACT", "STRICTFP"};
251 /******************************************************************
252 * Output routines
253 ******************************************************************/
255 /** Write a character into given byte buffer;
256 * byte buffer will not be grown.
257 */
258 void putChar(ByteBuffer buf, int op, int x) {
259 buf.elems[op ] = (byte)((x >> 8) & 0xFF);
260 buf.elems[op+1] = (byte)((x ) & 0xFF);
261 }
263 /** Write an integer into given byte buffer;
264 * byte buffer will not be grown.
265 */
266 void putInt(ByteBuffer buf, int adr, int x) {
267 buf.elems[adr ] = (byte)((x >> 24) & 0xFF);
268 buf.elems[adr+1] = (byte)((x >> 16) & 0xFF);
269 buf.elems[adr+2] = (byte)((x >> 8) & 0xFF);
270 buf.elems[adr+3] = (byte)((x ) & 0xFF);
271 }
273 /******************************************************************
274 * Signature Generation
275 ******************************************************************/
277 /** Assemble signature of given type in string buffer.
278 */
279 void assembleSig(Type type) {
280 type = type.unannotatedType();
281 switch (type.getTag()) {
282 case BYTE:
283 sigbuf.appendByte('B');
284 break;
285 case SHORT:
286 sigbuf.appendByte('S');
287 break;
288 case CHAR:
289 sigbuf.appendByte('C');
290 break;
291 case INT:
292 sigbuf.appendByte('I');
293 break;
294 case LONG:
295 sigbuf.appendByte('J');
296 break;
297 case FLOAT:
298 sigbuf.appendByte('F');
299 break;
300 case DOUBLE:
301 sigbuf.appendByte('D');
302 break;
303 case BOOLEAN:
304 sigbuf.appendByte('Z');
305 break;
306 case VOID:
307 sigbuf.appendByte('V');
308 break;
309 case CLASS:
310 sigbuf.appendByte('L');
311 assembleClassSig(type);
312 sigbuf.appendByte(';');
313 break;
314 case ARRAY:
315 ArrayType at = (ArrayType)type;
316 sigbuf.appendByte('[');
317 assembleSig(at.elemtype);
318 break;
319 case METHOD:
320 MethodType mt = (MethodType)type;
321 sigbuf.appendByte('(');
322 assembleSig(mt.argtypes);
323 sigbuf.appendByte(')');
324 assembleSig(mt.restype);
325 if (hasTypeVar(mt.thrown)) {
326 for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
327 sigbuf.appendByte('^');
328 assembleSig(l.head);
329 }
330 }
331 break;
332 case WILDCARD: {
333 WildcardType ta = (WildcardType) type;
334 switch (ta.kind) {
335 case SUPER:
336 sigbuf.appendByte('-');
337 assembleSig(ta.type);
338 break;
339 case EXTENDS:
340 sigbuf.appendByte('+');
341 assembleSig(ta.type);
342 break;
343 case UNBOUND:
344 sigbuf.appendByte('*');
345 break;
346 default:
347 throw new AssertionError(ta.kind);
348 }
349 break;
350 }
351 case TYPEVAR:
352 sigbuf.appendByte('T');
353 sigbuf.appendName(type.tsym.name);
354 sigbuf.appendByte(';');
355 break;
356 case FORALL:
357 ForAll ft = (ForAll)type;
358 assembleParamsSig(ft.tvars);
359 assembleSig(ft.qtype);
360 break;
361 case UNINITIALIZED_THIS:
362 case UNINITIALIZED_OBJECT:
363 // we don't yet have a spec for uninitialized types in the
364 // local variable table
365 assembleSig(types.erasure(((UninitializedType)type).qtype));
366 break;
367 default:
368 throw new AssertionError("typeSig " + type.getTag());
369 }
370 }
372 boolean hasTypeVar(List<Type> l) {
373 while (l.nonEmpty()) {
374 if (l.head.hasTag(TYPEVAR)) return true;
375 l = l.tail;
376 }
377 return false;
378 }
380 void assembleClassSig(Type type) {
381 type = type.unannotatedType();
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 || value instanceof Variable)
486 value = ((DelegatedSymbol)value).getUnderlyingSymbol();
488 if (value instanceof MethodSymbol) {
489 MethodSymbol m = (MethodSymbol)value;
490 if (!m.isDynamic()) {
491 poolbuf.appendByte((m.owner.flags() & INTERFACE) != 0
492 ? CONSTANT_InterfaceMethodref
493 : CONSTANT_Methodref);
494 poolbuf.appendChar(pool.put(m.owner));
495 poolbuf.appendChar(pool.put(nameType(m)));
496 } else {
497 //invokedynamic
498 DynamicMethodSymbol dynSym = (DynamicMethodSymbol)m;
499 MethodHandle handle = new MethodHandle(dynSym.bsmKind, dynSym.bsm, types);
500 DynamicMethod dynMeth = new DynamicMethod(dynSym, types);
501 bootstrapMethods.put(dynMeth, handle);
502 //init cp entries
503 pool.put(names.BootstrapMethods);
504 pool.put(handle);
505 for (Object staticArg : dynSym.staticArgs) {
506 pool.put(staticArg);
507 }
508 poolbuf.appendByte(CONSTANT_InvokeDynamic);
509 poolbuf.appendChar(bootstrapMethods.size() - 1);
510 poolbuf.appendChar(pool.put(nameType(dynSym)));
511 }
512 } else if (value instanceof VarSymbol) {
513 VarSymbol v = (VarSymbol)value;
514 poolbuf.appendByte(CONSTANT_Fieldref);
515 poolbuf.appendChar(pool.put(v.owner));
516 poolbuf.appendChar(pool.put(nameType(v)));
517 } else if (value instanceof Name) {
518 poolbuf.appendByte(CONSTANT_Utf8);
519 byte[] bs = ((Name)value).toUtf();
520 poolbuf.appendChar(bs.length);
521 poolbuf.appendBytes(bs, 0, bs.length);
522 if (bs.length > Pool.MAX_STRING_LENGTH)
523 throw new StringOverflow(value.toString());
524 } else if (value instanceof ClassSymbol) {
525 ClassSymbol c = (ClassSymbol)value;
526 if (c.owner.kind == TYP) pool.put(c.owner);
527 poolbuf.appendByte(CONSTANT_Class);
528 if (c.type.hasTag(ARRAY)) {
529 poolbuf.appendChar(pool.put(typeSig(c.type)));
530 } else {
531 poolbuf.appendChar(pool.put(names.fromUtf(externalize(c.flatname))));
532 enterInner(c);
533 }
534 } else if (value instanceof NameAndType) {
535 NameAndType nt = (NameAndType)value;
536 poolbuf.appendByte(CONSTANT_NameandType);
537 poolbuf.appendChar(pool.put(nt.name));
538 poolbuf.appendChar(pool.put(typeSig(nt.uniqueType.type)));
539 } else if (value instanceof Integer) {
540 poolbuf.appendByte(CONSTANT_Integer);
541 poolbuf.appendInt(((Integer)value).intValue());
542 } else if (value instanceof Long) {
543 poolbuf.appendByte(CONSTANT_Long);
544 poolbuf.appendLong(((Long)value).longValue());
545 i++;
546 } else if (value instanceof Float) {
547 poolbuf.appendByte(CONSTANT_Float);
548 poolbuf.appendFloat(((Float)value).floatValue());
549 } else if (value instanceof Double) {
550 poolbuf.appendByte(CONSTANT_Double);
551 poolbuf.appendDouble(((Double)value).doubleValue());
552 i++;
553 } else if (value instanceof String) {
554 poolbuf.appendByte(CONSTANT_String);
555 poolbuf.appendChar(pool.put(names.fromString((String)value)));
556 } else if (value instanceof UniqueType) {
557 Type type = ((UniqueType)value).type;
558 if (type instanceof MethodType) {
559 poolbuf.appendByte(CONSTANT_MethodType);
560 poolbuf.appendChar(pool.put(typeSig((MethodType)type)));
561 } else {
562 if (type.hasTag(CLASS)) enterInner((ClassSymbol)type.tsym);
563 poolbuf.appendByte(CONSTANT_Class);
564 poolbuf.appendChar(pool.put(xClassName(type)));
565 }
566 } else if (value instanceof MethodHandle) {
567 MethodHandle ref = (MethodHandle)value;
568 poolbuf.appendByte(CONSTANT_MethodHandle);
569 poolbuf.appendByte(ref.refKind);
570 poolbuf.appendChar(pool.put(ref.refSym));
571 } else {
572 Assert.error("writePool " + value);
573 }
574 i++;
575 }
576 if (pool.pp > Pool.MAX_ENTRIES)
577 throw new PoolOverflow();
578 putChar(poolbuf, poolCountIdx, pool.pp);
579 }
581 /** Given a field, return its name.
582 */
583 Name fieldName(Symbol sym) {
584 if (scramble && (sym.flags() & PRIVATE) != 0 ||
585 scrambleAll && (sym.flags() & (PROTECTED | PUBLIC)) == 0)
586 return names.fromString("_$" + sym.name.getIndex());
587 else
588 return sym.name;
589 }
591 /** Given a symbol, return its name-and-type.
592 */
593 NameAndType nameType(Symbol sym) {
594 return new NameAndType(fieldName(sym),
595 retrofit
596 ? sym.erasure(types)
597 : sym.externalType(types), types);
598 // if we retrofit, then the NameAndType has been read in as is
599 // and no change is necessary. If we compile normally, the
600 // NameAndType is generated from a symbol reference, and the
601 // adjustment of adding an additional this$n parameter needs to be made.
602 }
604 /******************************************************************
605 * Writing Attributes
606 ******************************************************************/
608 /** Write header for an attribute to data buffer and return
609 * position past attribute length index.
610 */
611 int writeAttr(Name attrName) {
612 databuf.appendChar(pool.put(attrName));
613 databuf.appendInt(0);
614 return databuf.length;
615 }
617 /** Fill in attribute length.
618 */
619 void endAttr(int index) {
620 putInt(databuf, index - 4, databuf.length - index);
621 }
623 /** Leave space for attribute count and return index for
624 * number of attributes field.
625 */
626 int beginAttrs() {
627 databuf.appendChar(0);
628 return databuf.length;
629 }
631 /** Fill in number of attributes.
632 */
633 void endAttrs(int index, int count) {
634 putChar(databuf, index - 2, count);
635 }
637 /** Write the EnclosingMethod attribute if needed.
638 * Returns the number of attributes written (0 or 1).
639 */
640 int writeEnclosingMethodAttribute(ClassSymbol c) {
641 if (!target.hasEnclosingMethodAttribute())
642 return 0;
643 return writeEnclosingMethodAttribute(names.EnclosingMethod, c);
644 }
646 /** Write the EnclosingMethod attribute with a specified name.
647 * Returns the number of attributes written (0 or 1).
648 */
649 protected int writeEnclosingMethodAttribute(Name attributeName, ClassSymbol c) {
650 if (c.owner.kind != MTH && // neither a local class
651 c.name != names.empty) // nor anonymous
652 return 0;
654 int alenIdx = writeAttr(attributeName);
655 ClassSymbol enclClass = c.owner.enclClass();
656 MethodSymbol enclMethod =
657 (c.owner.type == null // local to init block
658 || c.owner.kind != MTH) // or member init
659 ? null
660 : (MethodSymbol)c.owner;
661 databuf.appendChar(pool.put(enclClass));
662 databuf.appendChar(enclMethod == null ? 0 : pool.put(nameType(c.owner)));
663 endAttr(alenIdx);
664 return 1;
665 }
667 /** Write flag attributes; return number of attributes written.
668 */
669 int writeFlagAttrs(long flags) {
670 int acount = 0;
671 if ((flags & DEPRECATED) != 0) {
672 int alenIdx = writeAttr(names.Deprecated);
673 endAttr(alenIdx);
674 acount++;
675 }
676 if ((flags & ENUM) != 0 && !target.useEnumFlag()) {
677 int alenIdx = writeAttr(names.Enum);
678 endAttr(alenIdx);
679 acount++;
680 }
681 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag()) {
682 int alenIdx = writeAttr(names.Synthetic);
683 endAttr(alenIdx);
684 acount++;
685 }
686 if ((flags & BRIDGE) != 0 && !target.useBridgeFlag()) {
687 int alenIdx = writeAttr(names.Bridge);
688 endAttr(alenIdx);
689 acount++;
690 }
691 if ((flags & VARARGS) != 0 && !target.useVarargsFlag()) {
692 int alenIdx = writeAttr(names.Varargs);
693 endAttr(alenIdx);
694 acount++;
695 }
696 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag()) {
697 int alenIdx = writeAttr(names.Annotation);
698 endAttr(alenIdx);
699 acount++;
700 }
701 return acount;
702 }
704 /** Write member (field or method) attributes;
705 * return number of attributes written.
706 */
707 int writeMemberAttrs(Symbol sym) {
708 int acount = writeFlagAttrs(sym.flags());
709 long flags = sym.flags();
710 if (source.allowGenerics() &&
711 (flags & (SYNTHETIC|BRIDGE)) != SYNTHETIC &&
712 (flags & ANONCONSTR) == 0 &&
713 (!types.isSameType(sym.type, sym.erasure(types)) ||
714 hasTypeVar(sym.type.getThrownTypes()))) {
715 // note that a local class with captured variables
716 // will get a signature attribute
717 int alenIdx = writeAttr(names.Signature);
718 databuf.appendChar(pool.put(typeSig(sym.type)));
719 endAttr(alenIdx);
720 acount++;
721 }
722 acount += writeJavaAnnotations(sym.getRawAttributes());
723 acount += writeTypeAnnotations(sym.getRawTypeAttributes());
724 return acount;
725 }
727 /**
728 * Write method parameter names attribute.
729 */
730 int writeMethodParametersAttr(MethodSymbol m) {
731 MethodType ty = m.externalType(types).asMethodType();
732 final int allparams = ty.argtypes.size();
733 if (m.params != null && allparams != 0) {
734 final int attrIndex = writeAttr(names.MethodParameters);
735 databuf.appendByte(allparams);
736 // Write extra parameters first
737 for (VarSymbol s : m.extraParams) {
738 final int flags =
739 ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
740 ((int) m.flags() & SYNTHETIC);
741 databuf.appendChar(pool.put(s.name));
742 databuf.appendInt(flags);
743 }
744 // Now write the real parameters
745 for (VarSymbol s : m.params) {
746 final int flags =
747 ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
748 ((int) m.flags() & SYNTHETIC);
749 databuf.appendChar(pool.put(s.name));
750 databuf.appendInt(flags);
751 }
752 endAttr(attrIndex);
753 return 1;
754 } else
755 return 0;
756 }
759 /** Write method parameter annotations;
760 * return number of attributes written.
761 */
762 int writeParameterAttrs(MethodSymbol m) {
763 boolean hasVisible = false;
764 boolean hasInvisible = false;
765 if (m.params != null) for (VarSymbol s : m.params) {
766 for (Attribute.Compound a : s.getRawAttributes()) {
767 switch (types.getRetention(a)) {
768 case SOURCE: break;
769 case CLASS: hasInvisible = true; break;
770 case RUNTIME: hasVisible = true; break;
771 default: ;// /* fail soft */ throw new AssertionError(vis);
772 }
773 }
774 }
776 int attrCount = 0;
777 if (hasVisible) {
778 int attrIndex = writeAttr(names.RuntimeVisibleParameterAnnotations);
779 databuf.appendByte(m.params.length());
780 for (VarSymbol s : m.params) {
781 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
782 for (Attribute.Compound a : s.getRawAttributes())
783 if (types.getRetention(a) == RetentionPolicy.RUNTIME)
784 buf.append(a);
785 databuf.appendChar(buf.length());
786 for (Attribute.Compound a : buf)
787 writeCompoundAttribute(a);
788 }
789 endAttr(attrIndex);
790 attrCount++;
791 }
792 if (hasInvisible) {
793 int attrIndex = writeAttr(names.RuntimeInvisibleParameterAnnotations);
794 databuf.appendByte(m.params.length());
795 for (VarSymbol s : m.params) {
796 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
797 for (Attribute.Compound a : s.getRawAttributes())
798 if (types.getRetention(a) == RetentionPolicy.CLASS)
799 buf.append(a);
800 databuf.appendChar(buf.length());
801 for (Attribute.Compound a : buf)
802 writeCompoundAttribute(a);
803 }
804 endAttr(attrIndex);
805 attrCount++;
806 }
807 return attrCount;
808 }
810 /**********************************************************************
811 * Writing Java-language annotations (aka metadata, attributes)
812 **********************************************************************/
814 /** Write Java-language annotations; return number of JVM
815 * attributes written (zero or one).
816 */
817 int writeJavaAnnotations(List<Attribute.Compound> attrs) {
818 if (attrs.isEmpty()) return 0;
819 ListBuffer<Attribute.Compound> visibles = new ListBuffer<Attribute.Compound>();
820 ListBuffer<Attribute.Compound> invisibles = new ListBuffer<Attribute.Compound>();
821 for (Attribute.Compound a : attrs) {
822 switch (types.getRetention(a)) {
823 case SOURCE: break;
824 case CLASS: invisibles.append(a); break;
825 case RUNTIME: visibles.append(a); break;
826 default: ;// /* fail soft */ throw new AssertionError(vis);
827 }
828 }
830 int attrCount = 0;
831 if (visibles.length() != 0) {
832 int attrIndex = writeAttr(names.RuntimeVisibleAnnotations);
833 databuf.appendChar(visibles.length());
834 for (Attribute.Compound a : visibles)
835 writeCompoundAttribute(a);
836 endAttr(attrIndex);
837 attrCount++;
838 }
839 if (invisibles.length() != 0) {
840 int attrIndex = writeAttr(names.RuntimeInvisibleAnnotations);
841 databuf.appendChar(invisibles.length());
842 for (Attribute.Compound a : invisibles)
843 writeCompoundAttribute(a);
844 endAttr(attrIndex);
845 attrCount++;
846 }
847 return attrCount;
848 }
850 int writeTypeAnnotations(List<Attribute.TypeCompound> typeAnnos) {
851 if (typeAnnos.isEmpty()) return 0;
853 ListBuffer<Attribute.TypeCompound> visibles = ListBuffer.lb();
854 ListBuffer<Attribute.TypeCompound> invisibles = ListBuffer.lb();
856 for (Attribute.TypeCompound tc : typeAnnos) {
857 if (tc.position == null || tc.position.type == TargetType.UNKNOWN) {
858 boolean found = false;
859 // TODO: the position for the container annotation of a
860 // repeating type annotation has to be set.
861 // This cannot be done when the container is created, because
862 // then the position is not determined yet.
863 // How can we link these pieces better together?
864 if (tc.values.size() == 1) {
865 Pair<MethodSymbol, Attribute> val = tc.values.get(0);
866 if (val.fst.getSimpleName().contentEquals("value") &&
867 val.snd instanceof Attribute.Array) {
868 Attribute.Array arr = (Attribute.Array) val.snd;
869 if (arr.values.length != 0 &&
870 arr.values[0] instanceof Attribute.TypeCompound) {
871 TypeCompound atycomp = (Attribute.TypeCompound) arr.values[0];
872 if (atycomp.position.type != TargetType.UNKNOWN) {
873 tc.position = atycomp.position;
874 found = true;
875 }
876 }
877 }
878 }
879 if (!found) {
880 // This happens for nested types like @A Outer. @B Inner.
881 // For method parameters we get the annotation twice! Once with
882 // a valid position, once unknown.
883 // TODO: find a cleaner solution.
884 // System.err.println("ClassWriter: Position UNKNOWN in type annotation: " + tc);
885 continue;
886 }
887 }
888 if (!tc.position.emitToClassfile())
889 continue;
890 switch (types.getRetention(tc)) {
891 case SOURCE: break;
892 case CLASS: invisibles.append(tc); break;
893 case RUNTIME: visibles.append(tc); break;
894 default: ;// /* fail soft */ throw new AssertionError(vis);
895 }
896 }
898 int attrCount = 0;
899 if (visibles.length() != 0) {
900 int attrIndex = writeAttr(names.RuntimeVisibleTypeAnnotations);
901 databuf.appendChar(visibles.length());
902 for (Attribute.TypeCompound p : visibles)
903 writeTypeAnnotation(p);
904 endAttr(attrIndex);
905 attrCount++;
906 }
908 if (invisibles.length() != 0) {
909 int attrIndex = writeAttr(names.RuntimeInvisibleTypeAnnotations);
910 databuf.appendChar(invisibles.length());
911 for (Attribute.TypeCompound p : invisibles)
912 writeTypeAnnotation(p);
913 endAttr(attrIndex);
914 attrCount++;
915 }
917 return attrCount;
918 }
920 /** A visitor to write an attribute including its leading
921 * single-character marker.
922 */
923 class AttributeWriter implements Attribute.Visitor {
924 public void visitConstant(Attribute.Constant _value) {
925 Object value = _value.value;
926 switch (_value.type.getTag()) {
927 case BYTE:
928 databuf.appendByte('B');
929 break;
930 case CHAR:
931 databuf.appendByte('C');
932 break;
933 case SHORT:
934 databuf.appendByte('S');
935 break;
936 case INT:
937 databuf.appendByte('I');
938 break;
939 case LONG:
940 databuf.appendByte('J');
941 break;
942 case FLOAT:
943 databuf.appendByte('F');
944 break;
945 case DOUBLE:
946 databuf.appendByte('D');
947 break;
948 case BOOLEAN:
949 databuf.appendByte('Z');
950 break;
951 case CLASS:
952 Assert.check(value instanceof String);
953 databuf.appendByte('s');
954 value = names.fromString(value.toString()); // CONSTANT_Utf8
955 break;
956 default:
957 throw new AssertionError(_value.type);
958 }
959 databuf.appendChar(pool.put(value));
960 }
961 public void visitEnum(Attribute.Enum e) {
962 databuf.appendByte('e');
963 databuf.appendChar(pool.put(typeSig(e.value.type)));
964 databuf.appendChar(pool.put(e.value.name));
965 }
966 public void visitClass(Attribute.Class clazz) {
967 databuf.appendByte('c');
968 databuf.appendChar(pool.put(typeSig(clazz.classType)));
969 }
970 public void visitCompound(Attribute.Compound compound) {
971 databuf.appendByte('@');
972 writeCompoundAttribute(compound);
973 }
974 public void visitError(Attribute.Error x) {
975 throw new AssertionError(x);
976 }
977 public void visitArray(Attribute.Array array) {
978 databuf.appendByte('[');
979 databuf.appendChar(array.values.length);
980 for (Attribute a : array.values) {
981 a.accept(this);
982 }
983 }
984 }
985 AttributeWriter awriter = new AttributeWriter();
987 /** Write a compound attribute excluding the '@' marker. */
988 void writeCompoundAttribute(Attribute.Compound c) {
989 databuf.appendChar(pool.put(typeSig(c.type)));
990 databuf.appendChar(c.values.length());
991 for (Pair<Symbol.MethodSymbol,Attribute> p : c.values) {
992 databuf.appendChar(pool.put(p.fst.name));
993 p.snd.accept(awriter);
994 }
995 }
997 void writeTypeAnnotation(Attribute.TypeCompound c) {
998 writePosition(c.position);
999 writeCompoundAttribute(c);
1000 }
1002 void writePosition(TypeAnnotationPosition p) {
1003 databuf.appendByte(p.type.targetTypeValue()); // TargetType tag is a byte
1004 switch (p.type) {
1005 // instanceof
1006 case INSTANCEOF:
1007 // new expression
1008 case NEW:
1009 // constructor/method reference receiver
1010 case CONSTRUCTOR_REFERENCE:
1011 case METHOD_REFERENCE:
1012 databuf.appendChar(p.offset);
1013 break;
1014 // local variable
1015 case LOCAL_VARIABLE:
1016 // resource variable
1017 case RESOURCE_VARIABLE:
1018 databuf.appendChar(p.lvarOffset.length); // for table length
1019 for (int i = 0; i < p.lvarOffset.length; ++i) {
1020 databuf.appendChar(p.lvarOffset[i]);
1021 databuf.appendChar(p.lvarLength[i]);
1022 databuf.appendChar(p.lvarIndex[i]);
1023 }
1024 break;
1025 // exception parameter
1026 case EXCEPTION_PARAMETER:
1027 databuf.appendByte(p.exception_index);
1028 break;
1029 // method receiver
1030 case METHOD_RECEIVER:
1031 // Do nothing
1032 break;
1033 // type parameter
1034 case CLASS_TYPE_PARAMETER:
1035 case METHOD_TYPE_PARAMETER:
1036 databuf.appendByte(p.parameter_index);
1037 break;
1038 // type parameter bound
1039 case CLASS_TYPE_PARAMETER_BOUND:
1040 case METHOD_TYPE_PARAMETER_BOUND:
1041 databuf.appendByte(p.parameter_index);
1042 databuf.appendByte(p.bound_index);
1043 break;
1044 // class extends or implements clause
1045 case CLASS_EXTENDS:
1046 databuf.appendChar(p.type_index);
1047 break;
1048 // throws
1049 case THROWS:
1050 databuf.appendChar(p.type_index);
1051 break;
1052 // method parameter
1053 case METHOD_FORMAL_PARAMETER:
1054 databuf.appendByte(p.parameter_index);
1055 break;
1056 // type cast
1057 case CAST:
1058 // method/constructor/reference type argument
1059 case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
1060 case METHOD_INVOCATION_TYPE_ARGUMENT:
1061 case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
1062 case METHOD_REFERENCE_TYPE_ARGUMENT:
1063 databuf.appendChar(p.offset);
1064 databuf.appendByte(p.type_index);
1065 break;
1066 // We don't need to worry about these
1067 case METHOD_RETURN:
1068 case FIELD:
1069 break;
1070 case UNKNOWN:
1071 throw new AssertionError("jvm.ClassWriter: UNKNOWN target type should never occur!");
1072 default:
1073 throw new AssertionError("jvm.ClassWriter: Unknown target type for position: " + p);
1074 }
1076 { // Append location data for generics/arrays.
1077 databuf.appendByte(p.location.size());
1078 java.util.List<Integer> loc = TypeAnnotationPosition.getBinaryFromTypePath(p.location);
1079 for (int i : loc)
1080 databuf.appendByte((byte)i);
1081 }
1082 }
1084 /**********************************************************************
1085 * Writing Objects
1086 **********************************************************************/
1088 /** Enter an inner class into the `innerClasses' set/queue.
1089 */
1090 void enterInner(ClassSymbol c) {
1091 if (c.type.isCompound()) {
1092 throw new AssertionError("Unexpected intersection type: " + c.type);
1093 }
1094 try {
1095 c.complete();
1096 } catch (CompletionFailure ex) {
1097 System.err.println("error: " + c + ": " + ex.getMessage());
1098 throw ex;
1099 }
1100 if (!c.type.hasTag(CLASS)) return; // arrays
1101 if (pool != null && // pool might be null if called from xClassName
1102 c.owner.enclClass() != null &&
1103 (innerClasses == null || !innerClasses.contains(c))) {
1104 // log.errWriter.println("enter inner " + c);//DEBUG
1105 enterInner(c.owner.enclClass());
1106 pool.put(c);
1107 pool.put(c.name);
1108 if (innerClasses == null) {
1109 innerClasses = new HashSet<ClassSymbol>();
1110 innerClassesQueue = new ListBuffer<ClassSymbol>();
1111 pool.put(names.InnerClasses);
1112 }
1113 innerClasses.add(c);
1114 innerClassesQueue.append(c);
1115 }
1116 }
1118 /** Write "inner classes" attribute.
1119 */
1120 void writeInnerClasses() {
1121 int alenIdx = writeAttr(names.InnerClasses);
1122 databuf.appendChar(innerClassesQueue.length());
1123 for (List<ClassSymbol> l = innerClassesQueue.toList();
1124 l.nonEmpty();
1125 l = l.tail) {
1126 ClassSymbol inner = l.head;
1127 char flags = (char) adjustFlags(inner.flags_field);
1128 if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT
1129 if (inner.name.isEmpty()) flags &= ~FINAL; // Anonymous class: unset FINAL flag
1130 if (dumpInnerClassModifiers) {
1131 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1132 pw.println("INNERCLASS " + inner.name);
1133 pw.println("---" + flagNames(flags));
1134 }
1135 databuf.appendChar(pool.get(inner));
1136 databuf.appendChar(
1137 inner.owner.kind == TYP ? pool.get(inner.owner) : 0);
1138 databuf.appendChar(
1139 !inner.name.isEmpty() ? pool.get(inner.name) : 0);
1140 databuf.appendChar(flags);
1141 }
1142 endAttr(alenIdx);
1143 }
1145 /** Write "bootstrapMethods" attribute.
1146 */
1147 void writeBootstrapMethods() {
1148 int alenIdx = writeAttr(names.BootstrapMethods);
1149 databuf.appendChar(bootstrapMethods.size());
1150 for (Map.Entry<DynamicMethod, MethodHandle> entry : bootstrapMethods.entrySet()) {
1151 DynamicMethod dmeth = entry.getKey();
1152 DynamicMethodSymbol dsym = (DynamicMethodSymbol)dmeth.baseSymbol();
1153 //write BSM handle
1154 databuf.appendChar(pool.get(entry.getValue()));
1155 //write static args length
1156 databuf.appendChar(dsym.staticArgs.length);
1157 //write static args array
1158 Object[] uniqueArgs = dmeth.uniqueStaticArgs;
1159 for (Object o : uniqueArgs) {
1160 databuf.appendChar(pool.get(o));
1161 }
1162 }
1163 endAttr(alenIdx);
1164 }
1166 /** Write field symbol, entering all references into constant pool.
1167 */
1168 void writeField(VarSymbol v) {
1169 int flags = adjustFlags(v.flags());
1170 databuf.appendChar(flags);
1171 if (dumpFieldModifiers) {
1172 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1173 pw.println("FIELD " + fieldName(v));
1174 pw.println("---" + flagNames(v.flags()));
1175 }
1176 databuf.appendChar(pool.put(fieldName(v)));
1177 databuf.appendChar(pool.put(typeSig(v.erasure(types))));
1178 int acountIdx = beginAttrs();
1179 int acount = 0;
1180 if (v.getConstValue() != null) {
1181 int alenIdx = writeAttr(names.ConstantValue);
1182 databuf.appendChar(pool.put(v.getConstValue()));
1183 endAttr(alenIdx);
1184 acount++;
1185 }
1186 acount += writeMemberAttrs(v);
1187 endAttrs(acountIdx, acount);
1188 }
1190 /** Write method symbol, entering all references into constant pool.
1191 */
1192 void writeMethod(MethodSymbol m) {
1193 int flags = adjustFlags(m.flags());
1194 databuf.appendChar(flags);
1195 if (dumpMethodModifiers) {
1196 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1197 pw.println("METHOD " + fieldName(m));
1198 pw.println("---" + flagNames(m.flags()));
1199 }
1200 databuf.appendChar(pool.put(fieldName(m)));
1201 databuf.appendChar(pool.put(typeSig(m.externalType(types))));
1202 int acountIdx = beginAttrs();
1203 int acount = 0;
1204 if (m.code != null) {
1205 int alenIdx = writeAttr(names.Code);
1206 writeCode(m.code);
1207 m.code = null; // to conserve space
1208 endAttr(alenIdx);
1209 acount++;
1210 }
1211 List<Type> thrown = m.erasure(types).getThrownTypes();
1212 if (thrown.nonEmpty()) {
1213 int alenIdx = writeAttr(names.Exceptions);
1214 databuf.appendChar(thrown.length());
1215 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1216 databuf.appendChar(pool.put(l.head.tsym));
1217 endAttr(alenIdx);
1218 acount++;
1219 }
1220 if (m.defaultValue != null) {
1221 int alenIdx = writeAttr(names.AnnotationDefault);
1222 m.defaultValue.accept(awriter);
1223 endAttr(alenIdx);
1224 acount++;
1225 }
1226 if (options.isSet(PARAMETERS))
1227 acount += writeMethodParametersAttr(m);
1228 acount += writeMemberAttrs(m);
1229 acount += writeParameterAttrs(m);
1230 endAttrs(acountIdx, acount);
1231 }
1233 /** Write code attribute of method.
1234 */
1235 void writeCode(Code code) {
1236 databuf.appendChar(code.max_stack);
1237 databuf.appendChar(code.max_locals);
1238 databuf.appendInt(code.cp);
1239 databuf.appendBytes(code.code, 0, code.cp);
1240 databuf.appendChar(code.catchInfo.length());
1241 for (List<char[]> l = code.catchInfo.toList();
1242 l.nonEmpty();
1243 l = l.tail) {
1244 for (int i = 0; i < l.head.length; i++)
1245 databuf.appendChar(l.head[i]);
1246 }
1247 int acountIdx = beginAttrs();
1248 int acount = 0;
1250 if (code.lineInfo.nonEmpty()) {
1251 int alenIdx = writeAttr(names.LineNumberTable);
1252 databuf.appendChar(code.lineInfo.length());
1253 for (List<char[]> l = code.lineInfo.reverse();
1254 l.nonEmpty();
1255 l = l.tail)
1256 for (int i = 0; i < l.head.length; i++)
1257 databuf.appendChar(l.head[i]);
1258 endAttr(alenIdx);
1259 acount++;
1260 }
1262 if (genCrt && (code.crt != null)) {
1263 CRTable crt = code.crt;
1264 int alenIdx = writeAttr(names.CharacterRangeTable);
1265 int crtIdx = beginAttrs();
1266 int crtEntries = crt.writeCRT(databuf, code.lineMap, log);
1267 endAttrs(crtIdx, crtEntries);
1268 endAttr(alenIdx);
1269 acount++;
1270 }
1272 // counter for number of generic local variables
1273 int nGenericVars = 0;
1275 if (code.varBufferSize > 0) {
1276 int alenIdx = writeAttr(names.LocalVariableTable);
1277 databuf.appendChar(code.varBufferSize);
1279 for (int i=0; i<code.varBufferSize; i++) {
1280 Code.LocalVar var = code.varBuffer[i];
1282 // write variable info
1283 Assert.check(var.start_pc >= 0
1284 && var.start_pc <= code.cp);
1285 databuf.appendChar(var.start_pc);
1286 Assert.check(var.length >= 0
1287 && (var.start_pc + var.length) <= code.cp);
1288 databuf.appendChar(var.length);
1289 VarSymbol sym = var.sym;
1290 databuf.appendChar(pool.put(sym.name));
1291 Type vartype = sym.erasure(types);
1292 if (needsLocalVariableTypeEntry(sym.type))
1293 nGenericVars++;
1294 databuf.appendChar(pool.put(typeSig(vartype)));
1295 databuf.appendChar(var.reg);
1296 }
1297 endAttr(alenIdx);
1298 acount++;
1299 }
1301 if (nGenericVars > 0) {
1302 int alenIdx = writeAttr(names.LocalVariableTypeTable);
1303 databuf.appendChar(nGenericVars);
1304 int count = 0;
1306 for (int i=0; i<code.varBufferSize; i++) {
1307 Code.LocalVar var = code.varBuffer[i];
1308 VarSymbol sym = var.sym;
1309 if (!needsLocalVariableTypeEntry(sym.type))
1310 continue;
1311 count++;
1312 // write variable info
1313 databuf.appendChar(var.start_pc);
1314 databuf.appendChar(var.length);
1315 databuf.appendChar(pool.put(sym.name));
1316 databuf.appendChar(pool.put(typeSig(sym.type)));
1317 databuf.appendChar(var.reg);
1318 }
1319 Assert.check(count == nGenericVars);
1320 endAttr(alenIdx);
1321 acount++;
1322 }
1324 if (code.stackMapBufferSize > 0) {
1325 if (debugstackmap) System.out.println("Stack map for " + code.meth);
1326 int alenIdx = writeAttr(code.stackMap.getAttributeName(names));
1327 writeStackMap(code);
1328 endAttr(alenIdx);
1329 acount++;
1330 }
1331 endAttrs(acountIdx, acount);
1332 }
1333 //where
1334 private boolean needsLocalVariableTypeEntry(Type t) {
1335 //a local variable needs a type-entry if its type T is generic
1336 //(i.e. |T| != T) and if it's not an intersection type (not supported
1337 //in signature attribute grammar)
1338 return (!types.isSameType(t, types.erasure(t)) &&
1339 !t.isCompound());
1340 }
1342 void writeStackMap(Code code) {
1343 int nframes = code.stackMapBufferSize;
1344 if (debugstackmap) System.out.println(" nframes = " + nframes);
1345 databuf.appendChar(nframes);
1347 switch (code.stackMap) {
1348 case CLDC:
1349 for (int i=0; i<nframes; i++) {
1350 if (debugstackmap) System.out.print(" " + i + ":");
1351 Code.StackMapFrame frame = code.stackMapBuffer[i];
1353 // output PC
1354 if (debugstackmap) System.out.print(" pc=" + frame.pc);
1355 databuf.appendChar(frame.pc);
1357 // output locals
1358 int localCount = 0;
1359 for (int j=0; j<frame.locals.length;
1360 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1361 localCount++;
1362 }
1363 if (debugstackmap) System.out.print(" nlocals=" +
1364 localCount);
1365 databuf.appendChar(localCount);
1366 for (int j=0; j<frame.locals.length;
1367 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1368 if (debugstackmap) System.out.print(" local[" + j + "]=");
1369 writeStackMapType(frame.locals[j]);
1370 }
1372 // output stack
1373 int stackCount = 0;
1374 for (int j=0; j<frame.stack.length;
1375 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1376 stackCount++;
1377 }
1378 if (debugstackmap) System.out.print(" nstack=" +
1379 stackCount);
1380 databuf.appendChar(stackCount);
1381 for (int j=0; j<frame.stack.length;
1382 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1383 if (debugstackmap) System.out.print(" stack[" + j + "]=");
1384 writeStackMapType(frame.stack[j]);
1385 }
1386 if (debugstackmap) System.out.println();
1387 }
1388 break;
1389 case JSR202: {
1390 Assert.checkNull(code.stackMapBuffer);
1391 for (int i=0; i<nframes; i++) {
1392 if (debugstackmap) System.out.print(" " + i + ":");
1393 StackMapTableFrame frame = code.stackMapTableBuffer[i];
1394 frame.write(this);
1395 if (debugstackmap) System.out.println();
1396 }
1397 break;
1398 }
1399 default:
1400 throw new AssertionError("Unexpected stackmap format value");
1401 }
1402 }
1404 //where
1405 void writeStackMapType(Type t) {
1406 if (t == null) {
1407 if (debugstackmap) System.out.print("empty");
1408 databuf.appendByte(0);
1409 }
1410 else switch(t.getTag()) {
1411 case BYTE:
1412 case CHAR:
1413 case SHORT:
1414 case INT:
1415 case BOOLEAN:
1416 if (debugstackmap) System.out.print("int");
1417 databuf.appendByte(1);
1418 break;
1419 case FLOAT:
1420 if (debugstackmap) System.out.print("float");
1421 databuf.appendByte(2);
1422 break;
1423 case DOUBLE:
1424 if (debugstackmap) System.out.print("double");
1425 databuf.appendByte(3);
1426 break;
1427 case LONG:
1428 if (debugstackmap) System.out.print("long");
1429 databuf.appendByte(4);
1430 break;
1431 case BOT: // null
1432 if (debugstackmap) System.out.print("null");
1433 databuf.appendByte(5);
1434 break;
1435 case CLASS:
1436 case ARRAY:
1437 if (debugstackmap) System.out.print("object(" + t + ")");
1438 databuf.appendByte(7);
1439 databuf.appendChar(pool.put(t));
1440 break;
1441 case TYPEVAR:
1442 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")");
1443 databuf.appendByte(7);
1444 databuf.appendChar(pool.put(types.erasure(t).tsym));
1445 break;
1446 case UNINITIALIZED_THIS:
1447 if (debugstackmap) System.out.print("uninit_this");
1448 databuf.appendByte(6);
1449 break;
1450 case UNINITIALIZED_OBJECT:
1451 { UninitializedType uninitType = (UninitializedType)t;
1452 databuf.appendByte(8);
1453 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset);
1454 databuf.appendChar(uninitType.offset);
1455 }
1456 break;
1457 default:
1458 throw new AssertionError();
1459 }
1460 }
1462 /** An entry in the JSR202 StackMapTable */
1463 abstract static class StackMapTableFrame {
1464 abstract int getFrameType();
1466 void write(ClassWriter writer) {
1467 int frameType = getFrameType();
1468 writer.databuf.appendByte(frameType);
1469 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType);
1470 }
1472 static class SameFrame extends StackMapTableFrame {
1473 final int offsetDelta;
1474 SameFrame(int offsetDelta) {
1475 this.offsetDelta = offsetDelta;
1476 }
1477 int getFrameType() {
1478 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED;
1479 }
1480 @Override
1481 void write(ClassWriter writer) {
1482 super.write(writer);
1483 if (getFrameType() == SAME_FRAME_EXTENDED) {
1484 writer.databuf.appendChar(offsetDelta);
1485 if (writer.debugstackmap){
1486 System.out.print(" offset_delta=" + offsetDelta);
1487 }
1488 }
1489 }
1490 }
1492 static class SameLocals1StackItemFrame extends StackMapTableFrame {
1493 final int offsetDelta;
1494 final Type stack;
1495 SameLocals1StackItemFrame(int offsetDelta, Type stack) {
1496 this.offsetDelta = offsetDelta;
1497 this.stack = stack;
1498 }
1499 int getFrameType() {
1500 return (offsetDelta < SAME_FRAME_SIZE) ?
1501 (SAME_FRAME_SIZE + offsetDelta) :
1502 SAME_LOCALS_1_STACK_ITEM_EXTENDED;
1503 }
1504 @Override
1505 void write(ClassWriter writer) {
1506 super.write(writer);
1507 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) {
1508 writer.databuf.appendChar(offsetDelta);
1509 if (writer.debugstackmap) {
1510 System.out.print(" offset_delta=" + offsetDelta);
1511 }
1512 }
1513 if (writer.debugstackmap) {
1514 System.out.print(" stack[" + 0 + "]=");
1515 }
1516 writer.writeStackMapType(stack);
1517 }
1518 }
1520 static class ChopFrame extends StackMapTableFrame {
1521 final int frameType;
1522 final int offsetDelta;
1523 ChopFrame(int frameType, int offsetDelta) {
1524 this.frameType = frameType;
1525 this.offsetDelta = offsetDelta;
1526 }
1527 int getFrameType() { return frameType; }
1528 @Override
1529 void write(ClassWriter writer) {
1530 super.write(writer);
1531 writer.databuf.appendChar(offsetDelta);
1532 if (writer.debugstackmap) {
1533 System.out.print(" offset_delta=" + offsetDelta);
1534 }
1535 }
1536 }
1538 static class AppendFrame extends StackMapTableFrame {
1539 final int frameType;
1540 final int offsetDelta;
1541 final Type[] locals;
1542 AppendFrame(int frameType, int offsetDelta, Type[] locals) {
1543 this.frameType = frameType;
1544 this.offsetDelta = offsetDelta;
1545 this.locals = locals;
1546 }
1547 int getFrameType() { return frameType; }
1548 @Override
1549 void write(ClassWriter writer) {
1550 super.write(writer);
1551 writer.databuf.appendChar(offsetDelta);
1552 if (writer.debugstackmap) {
1553 System.out.print(" offset_delta=" + offsetDelta);
1554 }
1555 for (int i=0; i<locals.length; i++) {
1556 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1557 writer.writeStackMapType(locals[i]);
1558 }
1559 }
1560 }
1562 static class FullFrame extends StackMapTableFrame {
1563 final int offsetDelta;
1564 final Type[] locals;
1565 final Type[] stack;
1566 FullFrame(int offsetDelta, Type[] locals, Type[] stack) {
1567 this.offsetDelta = offsetDelta;
1568 this.locals = locals;
1569 this.stack = stack;
1570 }
1571 int getFrameType() { return FULL_FRAME; }
1572 @Override
1573 void write(ClassWriter writer) {
1574 super.write(writer);
1575 writer.databuf.appendChar(offsetDelta);
1576 writer.databuf.appendChar(locals.length);
1577 if (writer.debugstackmap) {
1578 System.out.print(" offset_delta=" + offsetDelta);
1579 System.out.print(" nlocals=" + locals.length);
1580 }
1581 for (int i=0; i<locals.length; i++) {
1582 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1583 writer.writeStackMapType(locals[i]);
1584 }
1586 writer.databuf.appendChar(stack.length);
1587 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); }
1588 for (int i=0; i<stack.length; i++) {
1589 if (writer.debugstackmap) System.out.print(" stack[" + i + "]=");
1590 writer.writeStackMapType(stack[i]);
1591 }
1592 }
1593 }
1595 /** Compare this frame with the previous frame and produce
1596 * an entry of compressed stack map frame. */
1597 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame,
1598 int prev_pc,
1599 Type[] prev_locals,
1600 Types types) {
1601 Type[] locals = this_frame.locals;
1602 Type[] stack = this_frame.stack;
1603 int offset_delta = this_frame.pc - prev_pc - 1;
1604 if (stack.length == 1) {
1605 if (locals.length == prev_locals.length
1606 && compare(prev_locals, locals, types) == 0) {
1607 return new SameLocals1StackItemFrame(offset_delta, stack[0]);
1608 }
1609 } else if (stack.length == 0) {
1610 int diff_length = compare(prev_locals, locals, types);
1611 if (diff_length == 0) {
1612 return new SameFrame(offset_delta);
1613 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) {
1614 // APPEND
1615 Type[] local_diff = new Type[-diff_length];
1616 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) {
1617 local_diff[j] = locals[i];
1618 }
1619 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length,
1620 offset_delta,
1621 local_diff);
1622 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) {
1623 // CHOP
1624 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length,
1625 offset_delta);
1626 }
1627 }
1628 // FULL_FRAME
1629 return new FullFrame(offset_delta, locals, stack);
1630 }
1632 static boolean isInt(Type t) {
1633 return (t.getTag().isStrictSubRangeOf(INT) || t.hasTag(BOOLEAN));
1634 }
1636 static boolean isSameType(Type t1, Type t2, Types types) {
1637 if (t1 == null) { return t2 == null; }
1638 if (t2 == null) { return false; }
1640 if (isInt(t1) && isInt(t2)) { return true; }
1642 if (t1.hasTag(UNINITIALIZED_THIS)) {
1643 return t2.hasTag(UNINITIALIZED_THIS);
1644 } else if (t1.hasTag(UNINITIALIZED_OBJECT)) {
1645 if (t2.hasTag(UNINITIALIZED_OBJECT)) {
1646 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset;
1647 } else {
1648 return false;
1649 }
1650 } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) {
1651 return false;
1652 }
1654 return types.isSameType(t1, t2);
1655 }
1657 static int compare(Type[] arr1, Type[] arr2, Types types) {
1658 int diff_length = arr1.length - arr2.length;
1659 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) {
1660 return Integer.MAX_VALUE;
1661 }
1662 int len = (diff_length > 0) ? arr2.length : arr1.length;
1663 for (int i=0; i<len; i++) {
1664 if (!isSameType(arr1[i], arr2[i], types)) {
1665 return Integer.MAX_VALUE;
1666 }
1667 }
1668 return diff_length;
1669 }
1670 }
1672 void writeFields(Scope.Entry e) {
1673 // process them in reverse sibling order;
1674 // i.e., process them in declaration order.
1675 List<VarSymbol> vars = List.nil();
1676 for (Scope.Entry i = e; i != null; i = i.sibling) {
1677 if (i.sym.kind == VAR) vars = vars.prepend((VarSymbol)i.sym);
1678 }
1679 while (vars.nonEmpty()) {
1680 writeField(vars.head);
1681 vars = vars.tail;
1682 }
1683 }
1685 void writeMethods(Scope.Entry e) {
1686 List<MethodSymbol> methods = List.nil();
1687 for (Scope.Entry i = e; i != null; i = i.sibling) {
1688 if (i.sym.kind == MTH && (i.sym.flags() & HYPOTHETICAL) == 0)
1689 methods = methods.prepend((MethodSymbol)i.sym);
1690 }
1691 while (methods.nonEmpty()) {
1692 writeMethod(methods.head);
1693 methods = methods.tail;
1694 }
1695 }
1697 /** Emit a class file for a given class.
1698 * @param c The class from which a class file is generated.
1699 */
1700 public JavaFileObject writeClass(ClassSymbol c)
1701 throws IOException, PoolOverflow, StringOverflow
1702 {
1703 JavaFileObject outFile
1704 = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
1705 c.flatname.toString(),
1706 JavaFileObject.Kind.CLASS,
1707 c.sourcefile);
1708 OutputStream out = outFile.openOutputStream();
1709 try {
1710 writeClassFile(out, c);
1711 if (verbose)
1712 log.printVerbose("wrote.file", outFile);
1713 out.close();
1714 out = null;
1715 } finally {
1716 if (out != null) {
1717 // if we are propogating an exception, delete the file
1718 out.close();
1719 outFile.delete();
1720 outFile = null;
1721 }
1722 }
1723 return outFile; // may be null if write failed
1724 }
1726 /** Write class `c' to outstream `out'.
1727 */
1728 public void writeClassFile(OutputStream out, ClassSymbol c)
1729 throws IOException, PoolOverflow, StringOverflow {
1730 Assert.check((c.flags() & COMPOUND) == 0);
1731 databuf.reset();
1732 poolbuf.reset();
1733 sigbuf.reset();
1734 pool = c.pool;
1735 innerClasses = null;
1736 innerClassesQueue = null;
1737 bootstrapMethods = new LinkedHashMap<DynamicMethod, MethodHandle>();
1739 Type supertype = types.supertype(c.type);
1740 List<Type> interfaces = types.interfaces(c.type);
1741 List<Type> typarams = c.type.getTypeArguments();
1743 int flags = adjustFlags(c.flags() & ~DEFAULT);
1744 if ((flags & PROTECTED) != 0) flags |= PUBLIC;
1745 flags = flags & ClassFlags & ~STRICTFP;
1746 if ((flags & INTERFACE) == 0) flags |= ACC_SUPER;
1747 if (c.isInner() && c.name.isEmpty()) flags &= ~FINAL;
1748 if (dumpClassModifiers) {
1749 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1750 pw.println();
1751 pw.println("CLASSFILE " + c.getQualifiedName());
1752 pw.println("---" + flagNames(flags));
1753 }
1754 databuf.appendChar(flags);
1756 databuf.appendChar(pool.put(c));
1757 databuf.appendChar(supertype.hasTag(CLASS) ? pool.put(supertype.tsym) : 0);
1758 databuf.appendChar(interfaces.length());
1759 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1760 databuf.appendChar(pool.put(l.head.tsym));
1761 int fieldsCount = 0;
1762 int methodsCount = 0;
1763 for (Scope.Entry e = c.members().elems; e != null; e = e.sibling) {
1764 switch (e.sym.kind) {
1765 case VAR: fieldsCount++; break;
1766 case MTH: if ((e.sym.flags() & HYPOTHETICAL) == 0) methodsCount++;
1767 break;
1768 case TYP: enterInner((ClassSymbol)e.sym); break;
1769 default : Assert.error();
1770 }
1771 }
1773 if (c.trans_local != null) {
1774 for (ClassSymbol local : c.trans_local) {
1775 enterInner(local);
1776 }
1777 }
1779 databuf.appendChar(fieldsCount);
1780 writeFields(c.members().elems);
1781 databuf.appendChar(methodsCount);
1782 writeMethods(c.members().elems);
1784 int acountIdx = beginAttrs();
1785 int acount = 0;
1787 boolean sigReq =
1788 typarams.length() != 0 || supertype.allparams().length() != 0;
1789 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail)
1790 sigReq = l.head.allparams().length() != 0;
1791 if (sigReq) {
1792 Assert.check(source.allowGenerics());
1793 int alenIdx = writeAttr(names.Signature);
1794 if (typarams.length() != 0) assembleParamsSig(typarams);
1795 assembleSig(supertype);
1796 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1797 assembleSig(l.head);
1798 databuf.appendChar(pool.put(sigbuf.toName(names)));
1799 sigbuf.reset();
1800 endAttr(alenIdx);
1801 acount++;
1802 }
1804 if (c.sourcefile != null && emitSourceFile) {
1805 int alenIdx = writeAttr(names.SourceFile);
1806 // WHM 6/29/1999: Strip file path prefix. We do it here at
1807 // the last possible moment because the sourcefile may be used
1808 // elsewhere in error diagnostics. Fixes 4241573.
1809 //databuf.appendChar(c.pool.put(c.sourcefile));
1810 String simpleName = BaseFileObject.getSimpleName(c.sourcefile);
1811 databuf.appendChar(c.pool.put(names.fromString(simpleName)));
1812 endAttr(alenIdx);
1813 acount++;
1814 }
1816 if (genCrt) {
1817 // Append SourceID attribute
1818 int alenIdx = writeAttr(names.SourceID);
1819 databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile)))));
1820 endAttr(alenIdx);
1821 acount++;
1822 // Append CompilationID attribute
1823 alenIdx = writeAttr(names.CompilationID);
1824 databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis()))));
1825 endAttr(alenIdx);
1826 acount++;
1827 }
1829 acount += writeFlagAttrs(c.flags());
1830 acount += writeJavaAnnotations(c.getRawAttributes());
1831 acount += writeTypeAnnotations(c.getRawTypeAttributes());
1832 acount += writeEnclosingMethodAttribute(c);
1833 acount += writeExtraClassAttributes(c);
1835 poolbuf.appendInt(JAVA_MAGIC);
1836 poolbuf.appendChar(target.minorVersion);
1837 poolbuf.appendChar(target.majorVersion);
1839 writePool(c.pool);
1841 if (innerClasses != null) {
1842 writeInnerClasses();
1843 acount++;
1844 }
1846 if (!bootstrapMethods.isEmpty()) {
1847 writeBootstrapMethods();
1848 acount++;
1849 }
1851 endAttrs(acountIdx, acount);
1853 poolbuf.appendBytes(databuf.elems, 0, databuf.length);
1854 out.write(poolbuf.elems, 0, poolbuf.length);
1856 pool = c.pool = null; // to conserve space
1857 }
1859 /**Allows subclasses to write additional class attributes
1860 *
1861 * @return the number of attributes written
1862 */
1863 protected int writeExtraClassAttributes(ClassSymbol c) {
1864 return 0;
1865 }
1867 int adjustFlags(final long flags) {
1868 int result = (int)flags;
1869 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag())
1870 result &= ~SYNTHETIC;
1871 if ((flags & ENUM) != 0 && !target.useEnumFlag())
1872 result &= ~ENUM;
1873 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag())
1874 result &= ~ANNOTATION;
1876 if ((flags & BRIDGE) != 0 && target.useBridgeFlag())
1877 result |= ACC_BRIDGE;
1878 if ((flags & VARARGS) != 0 && target.useVarargsFlag())
1879 result |= ACC_VARARGS;
1880 if ((flags & DEFAULT) != 0)
1881 result &= ~ABSTRACT;
1882 return result;
1883 }
1885 long getLastModified(FileObject filename) {
1886 long mod = 0;
1887 try {
1888 mod = filename.getLastModified();
1889 } catch (SecurityException e) {
1890 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage());
1891 }
1892 return mod;
1893 }
1894 }