Tue, 04 Feb 2020 17:57:00 +0800
Merge
1 /*
2 * Copyright (c) 1999, 2015, 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 inner.markAbstractIfNeeded(types);
1031 char flags = (char) adjustFlags(inner.flags_field);
1032 if ((flags & INTERFACE) != 0) flags |= ABSTRACT; // Interfaces are always ABSTRACT
1033 if (inner.name.isEmpty()) flags &= ~FINAL; // Anonymous class: unset FINAL flag
1034 flags &= ~STRICTFP; //inner classes should not have the strictfp flag set.
1035 if (dumpInnerClassModifiers) {
1036 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1037 pw.println("INNERCLASS " + inner.name);
1038 pw.println("---" + flagNames(flags));
1039 }
1040 databuf.appendChar(pool.get(inner));
1041 databuf.appendChar(
1042 inner.owner.kind == TYP && !inner.name.isEmpty() ? pool.get(inner.owner) : 0);
1043 databuf.appendChar(
1044 !inner.name.isEmpty() ? pool.get(inner.name) : 0);
1045 databuf.appendChar(flags);
1046 }
1047 endAttr(alenIdx);
1048 }
1050 /** Write "bootstrapMethods" attribute.
1051 */
1052 void writeBootstrapMethods() {
1053 int alenIdx = writeAttr(names.BootstrapMethods);
1054 databuf.appendChar(bootstrapMethods.size());
1055 for (Map.Entry<DynamicMethod, MethodHandle> entry : bootstrapMethods.entrySet()) {
1056 DynamicMethod dmeth = entry.getKey();
1057 DynamicMethodSymbol dsym = (DynamicMethodSymbol)dmeth.baseSymbol();
1058 //write BSM handle
1059 databuf.appendChar(pool.get(entry.getValue()));
1060 //write static args length
1061 databuf.appendChar(dsym.staticArgs.length);
1062 //write static args array
1063 Object[] uniqueArgs = dmeth.uniqueStaticArgs;
1064 for (Object o : uniqueArgs) {
1065 databuf.appendChar(pool.get(o));
1066 }
1067 }
1068 endAttr(alenIdx);
1069 }
1071 /** Write field symbol, entering all references into constant pool.
1072 */
1073 void writeField(VarSymbol v) {
1074 int flags = adjustFlags(v.flags());
1075 databuf.appendChar(flags);
1076 if (dumpFieldModifiers) {
1077 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1078 pw.println("FIELD " + fieldName(v));
1079 pw.println("---" + flagNames(v.flags()));
1080 }
1081 databuf.appendChar(pool.put(fieldName(v)));
1082 databuf.appendChar(pool.put(typeSig(v.erasure(types))));
1083 int acountIdx = beginAttrs();
1084 int acount = 0;
1085 if (v.getConstValue() != null) {
1086 int alenIdx = writeAttr(names.ConstantValue);
1087 databuf.appendChar(pool.put(v.getConstValue()));
1088 endAttr(alenIdx);
1089 acount++;
1090 }
1091 acount += writeMemberAttrs(v);
1092 endAttrs(acountIdx, acount);
1093 }
1095 /** Write method symbol, entering all references into constant pool.
1096 */
1097 void writeMethod(MethodSymbol m) {
1098 int flags = adjustFlags(m.flags());
1099 databuf.appendChar(flags);
1100 if (dumpMethodModifiers) {
1101 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1102 pw.println("METHOD " + fieldName(m));
1103 pw.println("---" + flagNames(m.flags()));
1104 }
1105 databuf.appendChar(pool.put(fieldName(m)));
1106 databuf.appendChar(pool.put(typeSig(m.externalType(types))));
1107 int acountIdx = beginAttrs();
1108 int acount = 0;
1109 if (m.code != null) {
1110 int alenIdx = writeAttr(names.Code);
1111 writeCode(m.code);
1112 m.code = null; // to conserve space
1113 endAttr(alenIdx);
1114 acount++;
1115 }
1116 List<Type> thrown = m.erasure(types).getThrownTypes();
1117 if (thrown.nonEmpty()) {
1118 int alenIdx = writeAttr(names.Exceptions);
1119 databuf.appendChar(thrown.length());
1120 for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1121 databuf.appendChar(pool.put(l.head.tsym));
1122 endAttr(alenIdx);
1123 acount++;
1124 }
1125 if (m.defaultValue != null) {
1126 int alenIdx = writeAttr(names.AnnotationDefault);
1127 m.defaultValue.accept(awriter);
1128 endAttr(alenIdx);
1129 acount++;
1130 }
1131 if (options.isSet(PARAMETERS))
1132 acount += writeMethodParametersAttr(m);
1133 acount += writeMemberAttrs(m);
1134 acount += writeParameterAttrs(m);
1135 endAttrs(acountIdx, acount);
1136 }
1138 /** Write code attribute of method.
1139 */
1140 void writeCode(Code code) {
1141 databuf.appendChar(code.max_stack);
1142 databuf.appendChar(code.max_locals);
1143 databuf.appendInt(code.cp);
1144 databuf.appendBytes(code.code, 0, code.cp);
1145 databuf.appendChar(code.catchInfo.length());
1146 for (List<char[]> l = code.catchInfo.toList();
1147 l.nonEmpty();
1148 l = l.tail) {
1149 for (int i = 0; i < l.head.length; i++)
1150 databuf.appendChar(l.head[i]);
1151 }
1152 int acountIdx = beginAttrs();
1153 int acount = 0;
1155 if (code.lineInfo.nonEmpty()) {
1156 int alenIdx = writeAttr(names.LineNumberTable);
1157 databuf.appendChar(code.lineInfo.length());
1158 for (List<char[]> l = code.lineInfo.reverse();
1159 l.nonEmpty();
1160 l = l.tail)
1161 for (int i = 0; i < l.head.length; i++)
1162 databuf.appendChar(l.head[i]);
1163 endAttr(alenIdx);
1164 acount++;
1165 }
1167 if (genCrt && (code.crt != null)) {
1168 CRTable crt = code.crt;
1169 int alenIdx = writeAttr(names.CharacterRangeTable);
1170 int crtIdx = beginAttrs();
1171 int crtEntries = crt.writeCRT(databuf, code.lineMap, log);
1172 endAttrs(crtIdx, crtEntries);
1173 endAttr(alenIdx);
1174 acount++;
1175 }
1177 // counter for number of generic local variables
1178 if (code.varDebugInfo && code.varBufferSize > 0) {
1179 int nGenericVars = 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 }
1203 endAttr(alenIdx);
1204 acount++;
1206 if (nGenericVars > 0) {
1207 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 }
1230 }
1232 if (code.stackMapBufferSize > 0) {
1233 if (debugstackmap) System.out.println("Stack map for " + code.meth);
1234 int alenIdx = writeAttr(code.stackMap.getAttributeName(names));
1235 writeStackMap(code);
1236 endAttr(alenIdx);
1237 acount++;
1238 }
1240 acount += writeTypeAnnotations(code.meth.getRawTypeAttributes(), true);
1242 endAttrs(acountIdx, acount);
1243 }
1244 //where
1245 private boolean needsLocalVariableTypeEntry(Type t) {
1246 //a local variable needs a type-entry if its type T is generic
1247 //(i.e. |T| != T) and if it's not an intersection type (not supported
1248 //in signature attribute grammar)
1249 return (!types.isSameType(t, types.erasure(t)) &&
1250 !t.isCompound());
1251 }
1253 void writeStackMap(Code code) {
1254 int nframes = code.stackMapBufferSize;
1255 if (debugstackmap) System.out.println(" nframes = " + nframes);
1256 databuf.appendChar(nframes);
1258 switch (code.stackMap) {
1259 case CLDC:
1260 for (int i=0; i<nframes; i++) {
1261 if (debugstackmap) System.out.print(" " + i + ":");
1262 Code.StackMapFrame frame = code.stackMapBuffer[i];
1264 // output PC
1265 if (debugstackmap) System.out.print(" pc=" + frame.pc);
1266 databuf.appendChar(frame.pc);
1268 // output locals
1269 int localCount = 0;
1270 for (int j=0; j<frame.locals.length;
1271 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1272 localCount++;
1273 }
1274 if (debugstackmap) System.out.print(" nlocals=" +
1275 localCount);
1276 databuf.appendChar(localCount);
1277 for (int j=0; j<frame.locals.length;
1278 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.locals[j]))) {
1279 if (debugstackmap) System.out.print(" local[" + j + "]=");
1280 writeStackMapType(frame.locals[j]);
1281 }
1283 // output stack
1284 int stackCount = 0;
1285 for (int j=0; j<frame.stack.length;
1286 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1287 stackCount++;
1288 }
1289 if (debugstackmap) System.out.print(" nstack=" +
1290 stackCount);
1291 databuf.appendChar(stackCount);
1292 for (int j=0; j<frame.stack.length;
1293 j += (target.generateEmptyAfterBig() ? 1 : Code.width(frame.stack[j]))) {
1294 if (debugstackmap) System.out.print(" stack[" + j + "]=");
1295 writeStackMapType(frame.stack[j]);
1296 }
1297 if (debugstackmap) System.out.println();
1298 }
1299 break;
1300 case JSR202: {
1301 Assert.checkNull(code.stackMapBuffer);
1302 for (int i=0; i<nframes; i++) {
1303 if (debugstackmap) System.out.print(" " + i + ":");
1304 StackMapTableFrame frame = code.stackMapTableBuffer[i];
1305 frame.write(this);
1306 if (debugstackmap) System.out.println();
1307 }
1308 break;
1309 }
1310 default:
1311 throw new AssertionError("Unexpected stackmap format value");
1312 }
1313 }
1315 //where
1316 void writeStackMapType(Type t) {
1317 if (t == null) {
1318 if (debugstackmap) System.out.print("empty");
1319 databuf.appendByte(0);
1320 }
1321 else switch(t.getTag()) {
1322 case BYTE:
1323 case CHAR:
1324 case SHORT:
1325 case INT:
1326 case BOOLEAN:
1327 if (debugstackmap) System.out.print("int");
1328 databuf.appendByte(1);
1329 break;
1330 case FLOAT:
1331 if (debugstackmap) System.out.print("float");
1332 databuf.appendByte(2);
1333 break;
1334 case DOUBLE:
1335 if (debugstackmap) System.out.print("double");
1336 databuf.appendByte(3);
1337 break;
1338 case LONG:
1339 if (debugstackmap) System.out.print("long");
1340 databuf.appendByte(4);
1341 break;
1342 case BOT: // null
1343 if (debugstackmap) System.out.print("null");
1344 databuf.appendByte(5);
1345 break;
1346 case CLASS:
1347 case ARRAY:
1348 if (debugstackmap) System.out.print("object(" + t + ")");
1349 databuf.appendByte(7);
1350 databuf.appendChar(pool.put(t));
1351 break;
1352 case TYPEVAR:
1353 if (debugstackmap) System.out.print("object(" + types.erasure(t).tsym + ")");
1354 databuf.appendByte(7);
1355 databuf.appendChar(pool.put(types.erasure(t).tsym));
1356 break;
1357 case UNINITIALIZED_THIS:
1358 if (debugstackmap) System.out.print("uninit_this");
1359 databuf.appendByte(6);
1360 break;
1361 case UNINITIALIZED_OBJECT:
1362 { UninitializedType uninitType = (UninitializedType)t;
1363 databuf.appendByte(8);
1364 if (debugstackmap) System.out.print("uninit_object@" + uninitType.offset);
1365 databuf.appendChar(uninitType.offset);
1366 }
1367 break;
1368 default:
1369 throw new AssertionError();
1370 }
1371 }
1373 /** An entry in the JSR202 StackMapTable */
1374 abstract static class StackMapTableFrame {
1375 abstract int getFrameType();
1377 void write(ClassWriter writer) {
1378 int frameType = getFrameType();
1379 writer.databuf.appendByte(frameType);
1380 if (writer.debugstackmap) System.out.print(" frame_type=" + frameType);
1381 }
1383 static class SameFrame extends StackMapTableFrame {
1384 final int offsetDelta;
1385 SameFrame(int offsetDelta) {
1386 this.offsetDelta = offsetDelta;
1387 }
1388 int getFrameType() {
1389 return (offsetDelta < SAME_FRAME_SIZE) ? offsetDelta : SAME_FRAME_EXTENDED;
1390 }
1391 @Override
1392 void write(ClassWriter writer) {
1393 super.write(writer);
1394 if (getFrameType() == SAME_FRAME_EXTENDED) {
1395 writer.databuf.appendChar(offsetDelta);
1396 if (writer.debugstackmap){
1397 System.out.print(" offset_delta=" + offsetDelta);
1398 }
1399 }
1400 }
1401 }
1403 static class SameLocals1StackItemFrame extends StackMapTableFrame {
1404 final int offsetDelta;
1405 final Type stack;
1406 SameLocals1StackItemFrame(int offsetDelta, Type stack) {
1407 this.offsetDelta = offsetDelta;
1408 this.stack = stack;
1409 }
1410 int getFrameType() {
1411 return (offsetDelta < SAME_FRAME_SIZE) ?
1412 (SAME_FRAME_SIZE + offsetDelta) :
1413 SAME_LOCALS_1_STACK_ITEM_EXTENDED;
1414 }
1415 @Override
1416 void write(ClassWriter writer) {
1417 super.write(writer);
1418 if (getFrameType() == SAME_LOCALS_1_STACK_ITEM_EXTENDED) {
1419 writer.databuf.appendChar(offsetDelta);
1420 if (writer.debugstackmap) {
1421 System.out.print(" offset_delta=" + offsetDelta);
1422 }
1423 }
1424 if (writer.debugstackmap) {
1425 System.out.print(" stack[" + 0 + "]=");
1426 }
1427 writer.writeStackMapType(stack);
1428 }
1429 }
1431 static class ChopFrame extends StackMapTableFrame {
1432 final int frameType;
1433 final int offsetDelta;
1434 ChopFrame(int frameType, int offsetDelta) {
1435 this.frameType = frameType;
1436 this.offsetDelta = offsetDelta;
1437 }
1438 int getFrameType() { return frameType; }
1439 @Override
1440 void write(ClassWriter writer) {
1441 super.write(writer);
1442 writer.databuf.appendChar(offsetDelta);
1443 if (writer.debugstackmap) {
1444 System.out.print(" offset_delta=" + offsetDelta);
1445 }
1446 }
1447 }
1449 static class AppendFrame extends StackMapTableFrame {
1450 final int frameType;
1451 final int offsetDelta;
1452 final Type[] locals;
1453 AppendFrame(int frameType, int offsetDelta, Type[] locals) {
1454 this.frameType = frameType;
1455 this.offsetDelta = offsetDelta;
1456 this.locals = locals;
1457 }
1458 int getFrameType() { return frameType; }
1459 @Override
1460 void write(ClassWriter writer) {
1461 super.write(writer);
1462 writer.databuf.appendChar(offsetDelta);
1463 if (writer.debugstackmap) {
1464 System.out.print(" offset_delta=" + offsetDelta);
1465 }
1466 for (int i=0; i<locals.length; i++) {
1467 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1468 writer.writeStackMapType(locals[i]);
1469 }
1470 }
1471 }
1473 static class FullFrame extends StackMapTableFrame {
1474 final int offsetDelta;
1475 final Type[] locals;
1476 final Type[] stack;
1477 FullFrame(int offsetDelta, Type[] locals, Type[] stack) {
1478 this.offsetDelta = offsetDelta;
1479 this.locals = locals;
1480 this.stack = stack;
1481 }
1482 int getFrameType() { return FULL_FRAME; }
1483 @Override
1484 void write(ClassWriter writer) {
1485 super.write(writer);
1486 writer.databuf.appendChar(offsetDelta);
1487 writer.databuf.appendChar(locals.length);
1488 if (writer.debugstackmap) {
1489 System.out.print(" offset_delta=" + offsetDelta);
1490 System.out.print(" nlocals=" + locals.length);
1491 }
1492 for (int i=0; i<locals.length; i++) {
1493 if (writer.debugstackmap) System.out.print(" locals[" + i + "]=");
1494 writer.writeStackMapType(locals[i]);
1495 }
1497 writer.databuf.appendChar(stack.length);
1498 if (writer.debugstackmap) { System.out.print(" nstack=" + stack.length); }
1499 for (int i=0; i<stack.length; i++) {
1500 if (writer.debugstackmap) System.out.print(" stack[" + i + "]=");
1501 writer.writeStackMapType(stack[i]);
1502 }
1503 }
1504 }
1506 /** Compare this frame with the previous frame and produce
1507 * an entry of compressed stack map frame. */
1508 static StackMapTableFrame getInstance(Code.StackMapFrame this_frame,
1509 int prev_pc,
1510 Type[] prev_locals,
1511 Types types) {
1512 Type[] locals = this_frame.locals;
1513 Type[] stack = this_frame.stack;
1514 int offset_delta = this_frame.pc - prev_pc - 1;
1515 if (stack.length == 1) {
1516 if (locals.length == prev_locals.length
1517 && compare(prev_locals, locals, types) == 0) {
1518 return new SameLocals1StackItemFrame(offset_delta, stack[0]);
1519 }
1520 } else if (stack.length == 0) {
1521 int diff_length = compare(prev_locals, locals, types);
1522 if (diff_length == 0) {
1523 return new SameFrame(offset_delta);
1524 } else if (-MAX_LOCAL_LENGTH_DIFF < diff_length && diff_length < 0) {
1525 // APPEND
1526 Type[] local_diff = new Type[-diff_length];
1527 for (int i=prev_locals.length, j=0; i<locals.length; i++,j++) {
1528 local_diff[j] = locals[i];
1529 }
1530 return new AppendFrame(SAME_FRAME_EXTENDED - diff_length,
1531 offset_delta,
1532 local_diff);
1533 } else if (0 < diff_length && diff_length < MAX_LOCAL_LENGTH_DIFF) {
1534 // CHOP
1535 return new ChopFrame(SAME_FRAME_EXTENDED - diff_length,
1536 offset_delta);
1537 }
1538 }
1539 // FULL_FRAME
1540 return new FullFrame(offset_delta, locals, stack);
1541 }
1543 static boolean isInt(Type t) {
1544 return (t.getTag().isStrictSubRangeOf(INT) || t.hasTag(BOOLEAN));
1545 }
1547 static boolean isSameType(Type t1, Type t2, Types types) {
1548 if (t1 == null) { return t2 == null; }
1549 if (t2 == null) { return false; }
1551 if (isInt(t1) && isInt(t2)) { return true; }
1553 if (t1.hasTag(UNINITIALIZED_THIS)) {
1554 return t2.hasTag(UNINITIALIZED_THIS);
1555 } else if (t1.hasTag(UNINITIALIZED_OBJECT)) {
1556 if (t2.hasTag(UNINITIALIZED_OBJECT)) {
1557 return ((UninitializedType)t1).offset == ((UninitializedType)t2).offset;
1558 } else {
1559 return false;
1560 }
1561 } else if (t2.hasTag(UNINITIALIZED_THIS) || t2.hasTag(UNINITIALIZED_OBJECT)) {
1562 return false;
1563 }
1565 return types.isSameType(t1, t2);
1566 }
1568 static int compare(Type[] arr1, Type[] arr2, Types types) {
1569 int diff_length = arr1.length - arr2.length;
1570 if (diff_length > MAX_LOCAL_LENGTH_DIFF || diff_length < -MAX_LOCAL_LENGTH_DIFF) {
1571 return Integer.MAX_VALUE;
1572 }
1573 int len = (diff_length > 0) ? arr2.length : arr1.length;
1574 for (int i=0; i<len; i++) {
1575 if (!isSameType(arr1[i], arr2[i], types)) {
1576 return Integer.MAX_VALUE;
1577 }
1578 }
1579 return diff_length;
1580 }
1581 }
1583 void writeFields(Scope.Entry e) {
1584 // process them in reverse sibling order;
1585 // i.e., process them in declaration order.
1586 List<VarSymbol> vars = List.nil();
1587 for (Scope.Entry i = e; i != null; i = i.sibling) {
1588 if (i.sym.kind == VAR) vars = vars.prepend((VarSymbol)i.sym);
1589 }
1590 while (vars.nonEmpty()) {
1591 writeField(vars.head);
1592 vars = vars.tail;
1593 }
1594 }
1596 void writeMethods(Scope.Entry e) {
1597 List<MethodSymbol> methods = List.nil();
1598 for (Scope.Entry i = e; i != null; i = i.sibling) {
1599 if (i.sym.kind == MTH && (i.sym.flags() & HYPOTHETICAL) == 0)
1600 methods = methods.prepend((MethodSymbol)i.sym);
1601 }
1602 while (methods.nonEmpty()) {
1603 writeMethod(methods.head);
1604 methods = methods.tail;
1605 }
1606 }
1608 /** Emit a class file for a given class.
1609 * @param c The class from which a class file is generated.
1610 */
1611 public JavaFileObject writeClass(ClassSymbol c)
1612 throws IOException, PoolOverflow, StringOverflow
1613 {
1614 JavaFileObject outFile
1615 = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
1616 c.flatname.toString(),
1617 JavaFileObject.Kind.CLASS,
1618 c.sourcefile);
1619 OutputStream out = outFile.openOutputStream();
1620 try {
1621 writeClassFile(out, c);
1622 if (verbose)
1623 log.printVerbose("wrote.file", outFile);
1624 out.close();
1625 out = null;
1626 } finally {
1627 if (out != null) {
1628 // if we are propagating an exception, delete the file
1629 out.close();
1630 outFile.delete();
1631 outFile = null;
1632 }
1633 }
1634 return outFile; // may be null if write failed
1635 }
1637 /** Write class `c' to outstream `out'.
1638 */
1639 public void writeClassFile(OutputStream out, ClassSymbol c)
1640 throws IOException, PoolOverflow, StringOverflow {
1641 Assert.check((c.flags() & COMPOUND) == 0);
1642 databuf.reset();
1643 poolbuf.reset();
1644 signatureGen.reset();
1645 pool = c.pool;
1646 innerClasses = null;
1647 innerClassesQueue = null;
1648 bootstrapMethods = new LinkedHashMap<DynamicMethod, MethodHandle>();
1650 Type supertype = types.supertype(c.type);
1651 List<Type> interfaces = types.interfaces(c.type);
1652 List<Type> typarams = c.type.getTypeArguments();
1654 int flags = adjustFlags(c.flags() & ~DEFAULT);
1655 if ((flags & PROTECTED) != 0) flags |= PUBLIC;
1656 flags = flags & ClassFlags & ~STRICTFP;
1657 if ((flags & INTERFACE) == 0) flags |= ACC_SUPER;
1658 if (c.isInner() && c.name.isEmpty()) flags &= ~FINAL;
1659 if (dumpClassModifiers) {
1660 PrintWriter pw = log.getWriter(Log.WriterKind.ERROR);
1661 pw.println();
1662 pw.println("CLASSFILE " + c.getQualifiedName());
1663 pw.println("---" + flagNames(flags));
1664 }
1665 databuf.appendChar(flags);
1667 databuf.appendChar(pool.put(c));
1668 databuf.appendChar(supertype.hasTag(CLASS) ? pool.put(supertype.tsym) : 0);
1669 databuf.appendChar(interfaces.length());
1670 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1671 databuf.appendChar(pool.put(l.head.tsym));
1672 int fieldsCount = 0;
1673 int methodsCount = 0;
1674 for (Scope.Entry e = c.members().elems; e != null; e = e.sibling) {
1675 switch (e.sym.kind) {
1676 case VAR: fieldsCount++; break;
1677 case MTH: if ((e.sym.flags() & HYPOTHETICAL) == 0) methodsCount++;
1678 break;
1679 case TYP: enterInner((ClassSymbol)e.sym); break;
1680 default : Assert.error();
1681 }
1682 }
1684 if (c.trans_local != null) {
1685 for (ClassSymbol local : c.trans_local) {
1686 enterInner(local);
1687 }
1688 }
1690 databuf.appendChar(fieldsCount);
1691 writeFields(c.members().elems);
1692 databuf.appendChar(methodsCount);
1693 writeMethods(c.members().elems);
1695 int acountIdx = beginAttrs();
1696 int acount = 0;
1698 boolean sigReq =
1699 typarams.length() != 0 || supertype.allparams().length() != 0;
1700 for (List<Type> l = interfaces; !sigReq && l.nonEmpty(); l = l.tail)
1701 sigReq = l.head.allparams().length() != 0;
1702 if (sigReq) {
1703 Assert.check(source.allowGenerics());
1704 int alenIdx = writeAttr(names.Signature);
1705 if (typarams.length() != 0) signatureGen.assembleParamsSig(typarams);
1706 signatureGen.assembleSig(supertype);
1707 for (List<Type> l = interfaces; l.nonEmpty(); l = l.tail)
1708 signatureGen.assembleSig(l.head);
1709 databuf.appendChar(pool.put(signatureGen.toName()));
1710 signatureGen.reset();
1711 endAttr(alenIdx);
1712 acount++;
1713 }
1715 if (c.sourcefile != null && emitSourceFile) {
1716 int alenIdx = writeAttr(names.SourceFile);
1717 // WHM 6/29/1999: Strip file path prefix. We do it here at
1718 // the last possible moment because the sourcefile may be used
1719 // elsewhere in error diagnostics. Fixes 4241573.
1720 //databuf.appendChar(c.pool.put(c.sourcefile));
1721 String simpleName = BaseFileObject.getSimpleName(c.sourcefile);
1722 databuf.appendChar(c.pool.put(names.fromString(simpleName)));
1723 endAttr(alenIdx);
1724 acount++;
1725 }
1727 if (genCrt) {
1728 // Append SourceID attribute
1729 int alenIdx = writeAttr(names.SourceID);
1730 databuf.appendChar(c.pool.put(names.fromString(Long.toString(getLastModified(c.sourcefile)))));
1731 endAttr(alenIdx);
1732 acount++;
1733 // Append CompilationID attribute
1734 alenIdx = writeAttr(names.CompilationID);
1735 databuf.appendChar(c.pool.put(names.fromString(Long.toString(System.currentTimeMillis()))));
1736 endAttr(alenIdx);
1737 acount++;
1738 }
1740 acount += writeFlagAttrs(c.flags());
1741 acount += writeJavaAnnotations(c.getRawAttributes());
1742 acount += writeTypeAnnotations(c.getRawTypeAttributes(), false);
1743 acount += writeEnclosingMethodAttribute(c);
1744 acount += writeExtraClassAttributes(c);
1746 poolbuf.appendInt(JAVA_MAGIC);
1747 poolbuf.appendChar(target.minorVersion);
1748 poolbuf.appendChar(target.majorVersion);
1750 writePool(c.pool);
1752 if (innerClasses != null) {
1753 writeInnerClasses();
1754 acount++;
1755 }
1757 if (!bootstrapMethods.isEmpty()) {
1758 writeBootstrapMethods();
1759 acount++;
1760 }
1762 endAttrs(acountIdx, acount);
1764 poolbuf.appendBytes(databuf.elems, 0, databuf.length);
1765 out.write(poolbuf.elems, 0, poolbuf.length);
1767 pool = c.pool = null; // to conserve space
1768 }
1770 /**Allows subclasses to write additional class attributes
1771 *
1772 * @return the number of attributes written
1773 */
1774 protected int writeExtraClassAttributes(ClassSymbol c) {
1775 return 0;
1776 }
1778 int adjustFlags(final long flags) {
1779 int result = (int)flags;
1780 if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag())
1781 result &= ~SYNTHETIC;
1782 if ((flags & ENUM) != 0 && !target.useEnumFlag())
1783 result &= ~ENUM;
1784 if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag())
1785 result &= ~ANNOTATION;
1787 if ((flags & BRIDGE) != 0 && target.useBridgeFlag())
1788 result |= ACC_BRIDGE;
1789 if ((flags & VARARGS) != 0 && target.useVarargsFlag())
1790 result |= ACC_VARARGS;
1791 if ((flags & DEFAULT) != 0)
1792 result &= ~ABSTRACT;
1793 return result;
1794 }
1796 long getLastModified(FileObject filename) {
1797 long mod = 0;
1798 try {
1799 mod = filename.getLastModified();
1800 } catch (SecurityException e) {
1801 throw new AssertionError("CRT: couldn't get source file modification date: " + e.getMessage());
1802 }
1803 return mod;
1804 }
1805 }