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