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