|
Java example source code file (ClassWriter.java)
The ClassWriter.java Java example source code
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.jvm;
import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import javax.tools.JavaFileManager;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Attribute.RetentionPolicy;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.code.Types.UniqueType;
import com.sun.tools.javac.file.BaseFileObject;
import com.sun.tools.javac.jvm.Pool.DynamicMethod;
import com.sun.tools.javac.jvm.Pool.Method;
import com.sun.tools.javac.jvm.Pool.MethodHandle;
import com.sun.tools.javac.jvm.Pool.Variable;
import com.sun.tools.javac.util.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.jvm.UninitializedType.*;
import static com.sun.tools.javac.main.Option.*;
import static javax.tools.StandardLocation.CLASS_OUTPUT;
/** This class provides operations to map an internal symbol table graph
* rooted in a ClassSymbol into a classfile.
*
* <p>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ClassWriter extends ClassFile {
protected static final Context.Key<ClassWriter> classWriterKey =
new Context.Key<ClassWriter>();
private final Options options;
/** Switch: verbose output.
*/
private boolean verbose;
/** Switch: scramble private field names.
*/
private boolean scramble;
/** Switch: scramble all field names.
*/
private boolean scrambleAll;
/** Switch: retrofit mode.
*/
private boolean retrofit;
/** Switch: emit source file attribute.
*/
private boolean emitSourceFile;
/** Switch: generate CharacterRangeTable attribute.
*/
private boolean genCrt;
/** Switch: describe the generated stackmap.
*/
boolean debugstackmap;
/**
* Target class version.
*/
private Target target;
/**
* Source language version.
*/
private Source source;
/** Type utilities. */
private Types types;
/** The initial sizes of the data and constant pool buffers.
* Sizes are increased when buffers get full.
*/
static final int DATA_BUF_SIZE = 0x0fff0;
static final int POOL_BUF_SIZE = 0x1fff0;
/** An output buffer for member info.
*/
ByteBuffer databuf = new ByteBuffer(DATA_BUF_SIZE);
/** An output buffer for the constant pool.
*/
ByteBuffer poolbuf = new ByteBuffer(POOL_BUF_SIZE);
/** The constant pool.
*/
Pool pool;
/** The inner classes to be written, as a set.
*/
Set<ClassSymbol> innerClasses;
/** The inner classes to be written, as a queue where
* enclosing classes come first.
*/
ListBuffer<ClassSymbol> innerClassesQueue;
/** The bootstrap methods to be written in the corresponding class attribute
* (one for each invokedynamic)
*/
Map<DynamicMethod, MethodHandle> bootstrapMethods;
/** The log to use for verbose output.
*/
private final Log log;
/** The name table. */
private final Names names;
/** Access to files. */
private final JavaFileManager fileManager;
/** Sole signature generator */
private final CWSignatureGenerator signatureGen;
/** The tags and constants used in compressed stackmap. */
static final int SAME_FRAME_SIZE = 64;
static final int SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247;
static final int SAME_FRAME_EXTENDED = 251;
static final int FULL_FRAME = 255;
static final int MAX_LOCAL_LENGTH_DIFF = 4;
/** Get the ClassWriter instance for this context. */
public static ClassWriter instance(Context context) {
ClassWriter instance = context.get(classWriterKey);
if (instance == null)
instance = new ClassWriter(context);
return instance;
}
/** Construct a class writer, given an options table.
*/
protected ClassWriter(Context context) {
context.put(classWriterKey, this);
log = Log.instance(context);
names = Names.instance(context);
options = Options.instance(context);
target = Target.instance(context);
source = Source.instance(context);
types = Types.instance(context);
fileManager = context.get(JavaFileManager.class);
signatureGen = new CWSignatureGenerator(types);
verbose = options.isSet(VERBOSE);
scramble = options.isSet("-scramble");
scrambleAll = options.isSet("-scrambleAll");
retrofit = options.isSet("-retrofit");
genCrt = options.isSet(XJCOV);
debugstackmap = options.isSet("debugstackmap");
emitSourceFile = options.isUnset(G_CUSTOM) ||
options.isSet(G_CUSTOM, "source");
String dumpModFlags = options.get("dumpmodifiers");
dumpClassModifiers =
(dumpModFlags != null && dumpModFlags.indexOf('c') != -1);
dumpFieldModifiers =
(dumpModFlags != null && dumpModFlags.indexOf('f') != -1);
dumpInnerClassModifiers =
(dumpModFlags != null && dumpModFlags.indexOf('i') != -1);
dumpMethodModifiers =
(dumpModFlags != null && dumpModFlags.indexOf('m') != -1);
}
/******************************************************************
* Diagnostics: dump generated class names and modifiers
******************************************************************/
/** Value of option 'dumpmodifiers' is a string
* indicating which modifiers should be dumped for debugging:
* 'c' -- classes
* 'f' -- fields
* 'i' -- innerclass attributes
* 'm' -- methods
* For example, to dump everything:
* javac -XDdumpmodifiers=cifm MyProg.java
*/
private final boolean dumpClassModifiers; // -XDdumpmodifiers=c
private final boolean dumpFieldModifiers; // -XDdumpmodifiers=f
private final boolean dumpInnerClassModifiers; // -XDdumpmodifiers=i
private final boolean dumpMethodModifiers; // -XDdumpmodifiers=m
/** Return flags as a string, separated by " ".
*/
public static String flagNames(long flags) {
StringBuilder sbuf = new StringBuilder();
int i = 0;
long f = flags & StandardFlags;
while (f != 0) {
if ((f & 1) != 0) {
sbuf.append(" ");
sbuf.append(flagName[i]);
}
f = f >> 1;
i++;
}
return sbuf.toString();
}
//where
private final static String[] flagName = {
"PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL",
"SUPER", "VOLATILE", "TRANSIENT", "NATIVE", "INTERFACE",
"ABSTRACT", "STRICTFP"};
/******************************************************************
* Output routines
******************************************************************/
/** Write a character into given byte buffer;
* byte buffer will not be grown.
*/
void putChar(ByteBuffer buf, int op, int x) {
buf.elems[op ] = (byte)((x >> 8) & 0xFF);
buf.elems[op+1] = (byte)((x ) & 0xFF);
}
/** Write an integer into given byte buffer;
* byte buffer will not be grown.
*/
void putInt(ByteBuffer buf, int adr, int x) {
buf.elems[adr ] = (byte)((x >> 24) & 0xFF);
buf.elems[adr+1] = (byte)((x >> 16) & 0xFF);
buf.elems[adr+2] = (byte)((x >> 8) & 0xFF);
buf.elems[adr+3] = (byte)((x ) & 0xFF);
}
/**
* Signature Generation
*/
private class CWSignatureGenerator extends Types.SignatureGenerator {
/**
* An output buffer for type signatures.
*/
ByteBuffer sigbuf = new ByteBuffer();
CWSignatureGenerator(Types types) {
super(types);
}
/**
* Assemble signature of given type in string buffer.
* Check for uninitialized types before calling the general case.
*/
@Override
public void assembleSig(Type type) {
type = type.unannotatedType();
switch (type.getTag()) {
case UNINITIALIZED_THIS:
case UNINITIALIZED_OBJECT:
// we don't yet have a spec for uninitialized types in the
// local variable table
assembleSig(types.erasure(((UninitializedType)type).qtype));
break;
default:
super.assembleSig(type);
}
}
@Override
protected void append(char ch) {
sigbuf.appendByte(ch);
}
@Override
protected void append(byte[] ba) {
sigbuf.appendBytes(ba);
}
@Override
protected void append(Name name) {
sigbuf.appendName(name);
}
@Override
protected void classReference(ClassSymbol c) {
enterInner(c);
}
private void reset() {
sigbuf.reset();
}
private Name toName() {
return sigbuf.toName(names);
}
private boolean isEmpty() {
return sigbuf.length == 0;
}
}
/**
* Return signature of given type
*/
Name typeSig(Type type) {
Assert.check(signatureGen.isEmpty());
//- System.out.println(" ? " + type);
signatureGen.assembleSig(type);
Name n = signatureGen.toName();
signatureGen.reset();
//- System.out.println(" " + n);
return n;
}
/** Given a type t, return the extended class name of its erasure in
* external representation.
*/
public Name xClassName(Type t) {
if (t.hasTag(CLASS)) {
return names.fromUtf(externalize(t.tsym.flatName()));
} else if (t.hasTag(ARRAY)) {
return typeSig(types.erasure(t));
} else {
throw new AssertionError("xClassName");
}
}
/******************************************************************
* Writing the Constant Pool
******************************************************************/
/** Thrown when the constant pool is over full.
*/
public static class PoolOverflow extends Exception {
private static final long serialVersionUID = 0;
public PoolOverflow() {}
}
public static class StringOverflow extends Exception {
private static final long serialVersionUID = 0;
public final String value;
public StringOverflow(String s) {
value = s;
}
}
/** Write constant pool to pool buffer.
* Note: during writing, constant pool
* might grow since some parts of constants still need to be entered.
*/
void writePool(Pool pool) throws PoolOverflow, StringOverflow {
int poolCountIdx = poolbuf.length;
poolbuf.appendChar(0);
int i = 1;
while (i < pool.pp) {
Object value = pool.pool[i];
Assert.checkNonNull(value);
if (value instanceof Method || value instanceof Variable)
value = ((DelegatedSymbol)value).getUnderlyingSymbol();
if (value instanceof MethodSymbol) {
MethodSymbol m = (MethodSymbol)value;
if (!m.isDynamic()) {
poolbuf.appendByte((m.owner.flags() & INTERFACE) != 0
? CONSTANT_InterfaceMethodref
: CONSTANT_Methodref);
poolbuf.appendChar(pool.put(m.owner));
poolbuf.appendChar(pool.put(nameType(m)));
} else {
//invokedynamic
DynamicMethodSymbol dynSym = (DynamicMethodSymbol)m;
MethodHandle handle = new MethodHandle(dynSym.bsmKind, dynSym.bsm, types);
DynamicMethod dynMeth = new DynamicMethod(dynSym, types);
bootstrapMethods.put(dynMeth, handle);
//init cp entries
pool.put(names.BootstrapMethods);
pool.put(handle);
for (Object staticArg : dynSym.staticArgs) {
pool.put(staticArg);
}
poolbuf.appendByte(CONSTANT_InvokeDynamic);
poolbuf.appendChar(bootstrapMethods.size() - 1);
poolbuf.appendChar(pool.put(nameType(dynSym)));
}
} else if (value instanceof VarSymbol) {
VarSymbol v = (VarSymbol)value;
poolbuf.appendByte(CONSTANT_Fieldref);
poolbuf.appendChar(pool.put(v.owner));
poolbuf.appendChar(pool.put(nameType(v)));
} else if (value instanceof Name) {
poolbuf.appendByte(CONSTANT_Utf8);
byte[] bs = ((Name)value).toUtf();
poolbuf.appendChar(bs.length);
poolbuf.appendBytes(bs, 0, bs.length);
if (bs.length > Pool.MAX_STRING_LENGTH)
throw new StringOverflow(value.toString());
} else if (value instanceof ClassSymbol) {
ClassSymbol c = (ClassSymbol)value;
if (c.owner.kind == TYP) pool.put(c.owner);
poolbuf.appendByte(CONSTANT_Class);
if (c.type.hasTag(ARRAY)) {
poolbuf.appendChar(pool.put(typeSig(c.type)));
} else {
poolbuf.appendChar(pool.put(names.fromUtf(externalize(c.flatname))));
enterInner(c);
}
} else if (value instanceof NameAndType) {
NameAndType nt = (NameAndType)value;
poolbuf.appendByte(CONSTANT_NameandType);
poolbuf.appendChar(pool.put(nt.name));
poolbuf.appendChar(pool.put(typeSig(nt.uniqueType.type)));
} else if (value instanceof Integer) {
poolbuf.appendByte(CONSTANT_Integer);
poolbuf.appendInt(((Integer)value).intValue());
} else if (value instanceof Long) {
poolbuf.appendByte(CONSTANT_Long);
poolbuf.appendLong(((Long)value).longValue());
i++;
} else if (value instanceof Float) {
poolbuf.appendByte(CONSTANT_Float);
poolbuf.appendFloat(((Float)value).floatValue());
} else if (value instanceof Double) {
poolbuf.appendByte(CONSTANT_Double);
poolbuf.appendDouble(((Double)value).doubleValue());
i++;
} else if (value instanceof String) {
poolbuf.appendByte(CONSTANT_String);
poolbuf.appendChar(pool.put(names.fromString((String)value)));
} else if (value instanceof UniqueType) {
Type type = ((UniqueType)value).type;
if (type instanceof MethodType) {
poolbuf.appendByte(CONSTANT_MethodType);
poolbuf.appendChar(pool.put(typeSig((MethodType)type)));
} else {
if (type.hasTag(CLASS)) enterInner((ClassSymbol)type.tsym);
poolbuf.appendByte(CONSTANT_Class);
poolbuf.appendChar(pool.put(xClassName(type)));
}
} else if (value instanceof MethodHandle) {
MethodHandle ref = (MethodHandle)value;
poolbuf.appendByte(CONSTANT_MethodHandle);
poolbuf.appendByte(ref.refKind);
poolbuf.appendChar(pool.put(ref.refSym));
} else {
Assert.error("writePool " + value);
}
i++;
}
if (pool.pp > Pool.MAX_ENTRIES)
throw new PoolOverflow();
putChar(poolbuf, poolCountIdx, pool.pp);
}
/** Given a field, return its name.
*/
Name fieldName(Symbol sym) {
if (scramble && (sym.flags() & PRIVATE) != 0 ||
scrambleAll && (sym.flags() & (PROTECTED | PUBLIC)) == 0)
return names.fromString("_$" + sym.name.getIndex());
else
return sym.name;
}
/** Given a symbol, return its name-and-type.
*/
NameAndType nameType(Symbol sym) {
return new NameAndType(fieldName(sym),
retrofit
? sym.erasure(types)
: sym.externalType(types), types);
// if we retrofit, then the NameAndType has been read in as is
// and no change is necessary. If we compile normally, the
// NameAndType is generated from a symbol reference, and the
// adjustment of adding an additional this$n parameter needs to be made.
}
/******************************************************************
* Writing Attributes
******************************************************************/
/** Write header for an attribute to data buffer and return
* position past attribute length index.
*/
int writeAttr(Name attrName) {
databuf.appendChar(pool.put(attrName));
databuf.appendInt(0);
return databuf.length;
}
/** Fill in attribute length.
*/
void endAttr(int index) {
putInt(databuf, index - 4, databuf.length - index);
}
/** Leave space for attribute count and return index for
* number of attributes field.
*/
int beginAttrs() {
databuf.appendChar(0);
return databuf.length;
}
/** Fill in number of attributes.
*/
void endAttrs(int index, int count) {
putChar(databuf, index - 2, count);
}
/** Write the EnclosingMethod attribute if needed.
* Returns the number of attributes written (0 or 1).
*/
int writeEnclosingMethodAttribute(ClassSymbol c) {
if (!target.hasEnclosingMethodAttribute())
return 0;
return writeEnclosingMethodAttribute(names.EnclosingMethod, c);
}
/** Write the EnclosingMethod attribute with a specified name.
* Returns the number of attributes written (0 or 1).
*/
protected int writeEnclosingMethodAttribute(Name attributeName, ClassSymbol c) {
if (c.owner.kind != MTH && // neither a local class
c.name != names.empty) // nor anonymous
return 0;
int alenIdx = writeAttr(attributeName);
ClassSymbol enclClass = c.owner.enclClass();
MethodSymbol enclMethod =
(c.owner.type == null // local to init block
|| c.owner.kind != MTH) // or member init
? null
: (MethodSymbol)c.owner;
databuf.appendChar(pool.put(enclClass));
databuf.appendChar(enclMethod == null ? 0 : pool.put(nameType(c.owner)));
endAttr(alenIdx);
return 1;
}
/** Write flag attributes; return number of attributes written.
*/
int writeFlagAttrs(long flags) {
int acount = 0;
if ((flags & DEPRECATED) != 0) {
int alenIdx = writeAttr(names.Deprecated);
endAttr(alenIdx);
acount++;
}
if ((flags & ENUM) != 0 && !target.useEnumFlag()) {
int alenIdx = writeAttr(names.Enum);
endAttr(alenIdx);
acount++;
}
if ((flags & SYNTHETIC) != 0 && !target.useSyntheticFlag()) {
int alenIdx = writeAttr(names.Synthetic);
endAttr(alenIdx);
acount++;
}
if ((flags & BRIDGE) != 0 && !target.useBridgeFlag()) {
int alenIdx = writeAttr(names.Bridge);
endAttr(alenIdx);
acount++;
}
if ((flags & VARARGS) != 0 && !target.useVarargsFlag()) {
int alenIdx = writeAttr(names.Varargs);
endAttr(alenIdx);
acount++;
}
if ((flags & ANNOTATION) != 0 && !target.useAnnotationFlag()) {
int alenIdx = writeAttr(names.Annotation);
endAttr(alenIdx);
acount++;
}
return acount;
}
/** Write member (field or method) attributes;
* return number of attributes written.
*/
int writeMemberAttrs(Symbol sym) {
int acount = writeFlagAttrs(sym.flags());
long flags = sym.flags();
if (source.allowGenerics() &&
(flags & (SYNTHETIC|BRIDGE)) != SYNTHETIC &&
(flags & ANONCONSTR) == 0 &&
(!types.isSameType(sym.type, sym.erasure(types)) ||
signatureGen.hasTypeVar(sym.type.getThrownTypes()))) {
// note that a local class with captured variables
// will get a signature attribute
int alenIdx = writeAttr(names.Signature);
databuf.appendChar(pool.put(typeSig(sym.type)));
endAttr(alenIdx);
acount++;
}
acount += writeJavaAnnotations(sym.getRawAttributes());
acount += writeTypeAnnotations(sym.getRawTypeAttributes(), false);
return acount;
}
/**
* Write method parameter names attribute.
*/
int writeMethodParametersAttr(MethodSymbol m) {
MethodType ty = m.externalType(types).asMethodType();
final int allparams = ty.argtypes.size();
if (m.params != null && allparams != 0) {
final int attrIndex = writeAttr(names.MethodParameters);
databuf.appendByte(allparams);
// Write extra parameters first
for (VarSymbol s : m.extraParams) {
final int flags =
((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
((int) m.flags() & SYNTHETIC);
databuf.appendChar(pool.put(s.name));
databuf.appendChar(flags);
}
// Now write the real parameters
for (VarSymbol s : m.params) {
final int flags =
((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
((int) m.flags() & SYNTHETIC);
databuf.appendChar(pool.put(s.name));
databuf.appendChar(flags);
}
// Now write the captured locals
for (VarSymbol s : m.capturedLocals) {
final int flags =
((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
((int) m.flags() & SYNTHETIC);
databuf.appendChar(pool.put(s.name));
databuf.appendChar(flags);
}
endAttr(attrIndex);
return 1;
} else
return 0;
}
/** Write method parameter annotations;
* return number of attributes written.
*/
int writeParameterAttrs(MethodSymbol m) {
boolean hasVisible = false;
boolean hasInvisible = false;
if (m.params != null) {
for (VarSymbol s : m.params) {
for (Attribute.Compound a : s.getRawAttributes()) {
switch (types.getRetention(a)) {
case SOURCE: break;
case CLASS: hasInvisible = true; break;
case RUNTIME: hasVisible = true; break;
default: ;// /* fail soft */ throw new AssertionError(vis);
}
}
}
}
int attrCount = 0;
if (hasVisible) {
int attrIndex = writeAttr(names.RuntimeVisibleParameterAnnotations);
databuf.appendByte(m.params.length());
for (VarSymbol s : m.params) {
ListBuffer<Attribute.Compound> buf = new ListBuffer
Other Java examples (source code examples)Here is a short list of links related to this Java ClassWriter.java source code file: |
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.