You are viewing a plain text version of this content. The canonical link for it is here.
Posted to bcel-dev@jakarta.apache.org by tc...@apache.org on 2006/03/15 12:33:43 UTC
svn commit: r386056 [24/28] - in /jakarta/bcel/trunk: examples/
examples/Mini/ src/java/org/apache/bcel/
src/java/org/apache/bcel/classfile/ src/java/org/apache/bcel/generic/
src/java/org/apache/bcel/util/ src/java/org/apache/bcel/verifier/
src/java/or...
Modified: jakarta/bcel/trunk/src/java/org/apache/bcel/util/BCELFactory.java
URL: http://svn.apache.org/viewcvs/jakarta/bcel/trunk/src/java/org/apache/bcel/util/BCELFactory.java?rev=386056&r1=386055&r2=386056&view=diff
==============================================================================
--- jakarta/bcel/trunk/src/java/org/apache/bcel/util/BCELFactory.java (original)
+++ jakarta/bcel/trunk/src/java/org/apache/bcel/util/BCELFactory.java Wed Mar 15 03:31:56 2006
@@ -39,7 +39,6 @@
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.Type;
-
/**
* Factory creates il.append() statements, and sets instruction targets.
* A helper class for BCELifier.
@@ -49,291 +48,263 @@
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
*/
class BCELFactory extends EmptyVisitor {
- private MethodGen _mg;
- private PrintWriter _out;
- private ConstantPoolGen _cp;
-
- BCELFactory(MethodGen mg, PrintWriter out) {
- _mg = mg;
- _cp = mg.getConstantPool();
- _out = out;
- }
-
- private Map branch_map = new HashMap(); // Map<Instruction, InstructionHandle>
-
- public void start() {
- if(!_mg.isAbstract() && !_mg.isNative()) {
- for(InstructionHandle ih = _mg.getInstructionList().getStart();
- ih != null; ih = ih.getNext()) {
- Instruction i = ih.getInstruction();
-
- if(i instanceof BranchInstruction) {
- branch_map.put(i, ih); // memorize container
- }
-
- if(ih.hasTargeters()) {
- if(i instanceof BranchInstruction) {
- _out.println(" InstructionHandle ih_" + ih.getPosition() + ";");
- } else {
- _out.print(" InstructionHandle ih_" + ih.getPosition() + " = ");
- }
- } else {
- _out.print(" ");
- }
-
- if(!visitInstruction(i))
- i.accept(this);
- }
-
- updateBranchTargets();
- updateExceptionHandlers();
- }
- }
-
- private boolean visitInstruction(Instruction i) {
- short opcode = i.getOpcode();
-
- if((InstructionConstants.INSTRUCTIONS[opcode] != null) &&
- !(i instanceof ConstantPushInstruction) &&
- !(i instanceof ReturnInstruction)) { // Handled below
- _out.println("il.append(InstructionConstants." +
- i.getName().toUpperCase(Locale.ENGLISH) + ");");
- return true;
- }
-
- return false;
- }
-
- public void visitLocalVariableInstruction(LocalVariableInstruction i) {
- short opcode = i.getOpcode();
- Type type = i.getType(_cp);
-
- if(opcode == Constants.IINC) {
- _out.println("il.append(new IINC(" + i.getIndex() + ", " +
- ((IINC)i).getIncrement() + "));");
- } else {
- String kind = (opcode < Constants.ISTORE)? "Load" : "Store";
- _out.println("il.append(_factory.create" + kind + "(" +
- BCELifier.printType(type) + ", " +
- i.getIndex() + "));");
- }
- }
-
- public void visitArrayInstruction(ArrayInstruction i) {
- short opcode = i.getOpcode();
- Type type = i.getType(_cp);
- String kind = (opcode < Constants.IASTORE)? "Load" : "Store";
-
- _out.println("il.append(_factory.createArray" + kind + "(" +
- BCELifier.printType(type) + "));");
- }
-
- public void visitFieldInstruction(FieldInstruction i) {
- short opcode = i.getOpcode();
-
- String class_name = i.getClassName(_cp);
- String field_name = i.getFieldName(_cp);
- Type type = i.getFieldType(_cp);
-
- _out.println("il.append(_factory.createFieldAccess(\"" +
- class_name + "\", \"" + field_name + "\", " +
- BCELifier.printType(type) + ", " +
- "Constants." + Constants.OPCODE_NAMES[opcode].toUpperCase(Locale.ENGLISH) +
- "));");
- }
-
- public void visitInvokeInstruction(InvokeInstruction i) {
- short opcode = i.getOpcode();
- String class_name = i.getClassName(_cp);
- String method_name = i.getMethodName(_cp);
- Type type = i.getReturnType(_cp);
- Type[] arg_types = i.getArgumentTypes(_cp);
-
- _out.println("il.append(_factory.createInvoke(\"" +
- class_name + "\", \"" + method_name + "\", " +
- BCELifier.printType(type) + ", " +
- BCELifier.printArgumentTypes(arg_types) + ", " +
- "Constants." + Constants.OPCODE_NAMES[opcode].toUpperCase(Locale.ENGLISH) +
- "));");
- }
-
- public void visitAllocationInstruction(AllocationInstruction i) {
- Type type;
-
- if(i instanceof CPInstruction) {
- type = ((CPInstruction)i).getType(_cp);
- } else {
- type = ((NEWARRAY)i).getType();
- }
-
- short opcode = ((Instruction)i).getOpcode();
- int dim = 1;
-
- switch(opcode) {
- case Constants.NEW:
- _out.println("il.append(_factory.createNew(\"" +
- ((ObjectType)type).getClassName() + "\"));");
- break;
-
- case Constants.MULTIANEWARRAY:
- dim = ((MULTIANEWARRAY)i).getDimensions();
-
- case Constants.ANEWARRAY:
- case Constants.NEWARRAY:
- if (type instanceof ArrayType)
- type = ((ArrayType)type).getBasicType();
- _out.println("il.append(_factory.createNewArray(" +
- BCELifier.printType(type) + ", (short) " + dim + "));");
- break;
-
- default:
- throw new RuntimeException("Oops: " + opcode);
- }
- }
-
- private void createConstant(Object value) {
- String embed = value.toString();
-
- if(value instanceof String)
- embed = '"' + Utility.convertString(value.toString()) + '"';
- else if(value instanceof Character)
- embed = "(char)0x" + Integer.toHexString(((Character)value).charValue());
-
- _out.println("il.append(new PUSH(_cp, " + embed + "));");
- }
-
- public void visitLDC(LDC i) {
- createConstant(i.getValue(_cp));
- }
-
- public void visitLDC2_W(LDC2_W i) {
- createConstant(i.getValue(_cp));
- }
-
- public void visitConstantPushInstruction(ConstantPushInstruction i) {
- createConstant(i.getValue());
- }
-
- public void visitINSTANCEOF(INSTANCEOF i) {
- Type type = i.getType(_cp);
-
- _out.println("il.append(new INSTANCEOF(_cp.addClass(" +
- BCELifier.printType(type) + ")));");
- }
-
- public void visitCHECKCAST(CHECKCAST i) {
- Type type = i.getType(_cp);
-
- _out.println("il.append(_factory.createCheckCast(" +
- BCELifier.printType(type) + "));");
- }
-
- public void visitReturnInstruction(ReturnInstruction i) {
- Type type = i.getType(_cp);
-
- _out.println("il.append(_factory.createReturn(" +
- BCELifier.printType(type) + "));");
- }
-
- // Memorize BranchInstructions that need an update
- private List branches = new ArrayList();
-
- public void visitBranchInstruction(BranchInstruction bi) {
- BranchHandle bh = (BranchHandle)branch_map.get(bi);
- int pos = bh.getPosition();
- String name = bi.getName() + "_" + pos;
-
- if(bi instanceof Select) {
- Select s = (Select)bi;
- branches.add(bi);
-
- StringBuffer args = new StringBuffer("new int[] { ");
- int[] matchs = s.getMatchs();
-
- for(int i=0; i < matchs.length; i++) {
- args.append(matchs[i]);
-
- if(i < matchs.length - 1)
- args.append(", ");
- }
-
- args.append(" }");
-
- _out.print("Select " + name + " = new " +
- bi.getName().toUpperCase(Locale.ENGLISH) + "(" + args +
- ", new InstructionHandle[] { ");
-
- for(int i=0; i < matchs.length; i++) {
- _out.print("null");
-
- if(i < matchs.length - 1)
- _out.print(", ");
- }
-
- _out.println(" }, null);");
- } else {
- int t_pos = bh.getTarget().getPosition();
- String target;
-
- if(pos > t_pos) {
- target = "ih_" + t_pos;
- } else {
- branches.add(bi);
- target = "null";
- }
-
- _out.println(" BranchInstruction " + name +
- " = _factory.createBranchInstruction(" +
- "Constants." + bi.getName().toUpperCase(Locale.ENGLISH) + ", " +
- target + ");");
- }
-
- if(bh.hasTargeters())
- _out.println(" ih_" + pos + " = il.append(" + name + ");");
- else
- _out.println(" il.append(" + name + ");");
- }
-
- public void visitRET(RET i) {
- _out.println("il.append(new RET(" + i.getIndex() + ")));");
- }
-
- private void updateBranchTargets() {
- for(Iterator i = branches.iterator(); i.hasNext(); ) {
- BranchInstruction bi = (BranchInstruction)i.next();
- BranchHandle bh = (BranchHandle)branch_map.get(bi);
- int pos = bh.getPosition();
- String name = bi.getName() + "_" + pos;
- int t_pos = bh.getTarget().getPosition();
-
- _out.println(" " + name + ".setTarget(ih_" + t_pos + ");");
-
- if(bi instanceof Select) {
- InstructionHandle[] ihs = ((Select)bi).getTargets();
-
- for(int j = 0; j < ihs.length; j++) {
- t_pos = ihs[j].getPosition();
-
- _out.println(" " + name + ".setTarget(" + j +
- ", ih_" + t_pos + ");");
- }
- }
- }
- }
-
- private void updateExceptionHandlers() {
- CodeExceptionGen[] handlers = _mg.getExceptionHandlers();
-
- for(int i=0; i < handlers.length; i++) {
- CodeExceptionGen h = handlers[i];
- String type = (h.getCatchType() == null)?
- "null" : BCELifier.printType(h.getCatchType());
-
- _out.println(" method.addExceptionHandler(" +
- "ih_" + h.getStartPC().getPosition() + ", " +
- "ih_" + h.getEndPC().getPosition() + ", " +
- "ih_" + h.getHandlerPC().getPosition() + ", " +
- type + ");");
+
+ private MethodGen _mg;
+ private PrintWriter _out;
+ private ConstantPoolGen _cp;
+
+
+ BCELFactory(MethodGen mg, PrintWriter out) {
+ _mg = mg;
+ _cp = mg.getConstantPool();
+ _out = out;
+ }
+
+ private Map branch_map = new HashMap(); // Map<Instruction, InstructionHandle>
+
+
+ public void start() {
+ if (!_mg.isAbstract() && !_mg.isNative()) {
+ for (InstructionHandle ih = _mg.getInstructionList().getStart(); ih != null; ih = ih
+ .getNext()) {
+ Instruction i = ih.getInstruction();
+ if (i instanceof BranchInstruction) {
+ branch_map.put(i, ih); // memorize container
+ }
+ if (ih.hasTargeters()) {
+ if (i instanceof BranchInstruction) {
+ _out.println(" InstructionHandle ih_" + ih.getPosition() + ";");
+ } else {
+ _out.print(" InstructionHandle ih_" + ih.getPosition() + " = ");
+ }
+ } else {
+ _out.print(" ");
+ }
+ if (!visitInstruction(i)) {
+ i.accept(this);
+ }
+ }
+ updateBranchTargets();
+ updateExceptionHandlers();
+ }
+ }
+
+
+ private boolean visitInstruction( Instruction i ) {
+ short opcode = i.getOpcode();
+ if ((InstructionConstants.INSTRUCTIONS[opcode] != null)
+ && !(i instanceof ConstantPushInstruction) && !(i instanceof ReturnInstruction)) { // Handled below
+ _out.println("il.append(InstructionConstants."
+ + i.getName().toUpperCase(Locale.ENGLISH) + ");");
+ return true;
+ }
+ return false;
+ }
+
+
+ public void visitLocalVariableInstruction( LocalVariableInstruction i ) {
+ short opcode = i.getOpcode();
+ Type type = i.getType(_cp);
+ if (opcode == Constants.IINC) {
+ _out.println("il.append(new IINC(" + i.getIndex() + ", " + ((IINC) i).getIncrement()
+ + "));");
+ } else {
+ String kind = (opcode < Constants.ISTORE) ? "Load" : "Store";
+ _out.println("il.append(_factory.create" + kind + "(" + BCELifier.printType(type)
+ + ", " + i.getIndex() + "));");
+ }
+ }
+
+
+ public void visitArrayInstruction( ArrayInstruction i ) {
+ short opcode = i.getOpcode();
+ Type type = i.getType(_cp);
+ String kind = (opcode < Constants.IASTORE) ? "Load" : "Store";
+ _out.println("il.append(_factory.createArray" + kind + "(" + BCELifier.printType(type)
+ + "));");
+ }
+
+
+ public void visitFieldInstruction( FieldInstruction i ) {
+ short opcode = i.getOpcode();
+ String class_name = i.getClassName(_cp);
+ String field_name = i.getFieldName(_cp);
+ Type type = i.getFieldType(_cp);
+ _out.println("il.append(_factory.createFieldAccess(\"" + class_name + "\", \"" + field_name
+ + "\", " + BCELifier.printType(type) + ", " + "Constants."
+ + Constants.OPCODE_NAMES[opcode].toUpperCase(Locale.ENGLISH) + "));");
+ }
+
+
+ public void visitInvokeInstruction( InvokeInstruction i ) {
+ short opcode = i.getOpcode();
+ String class_name = i.getClassName(_cp);
+ String method_name = i.getMethodName(_cp);
+ Type type = i.getReturnType(_cp);
+ Type[] arg_types = i.getArgumentTypes(_cp);
+ _out.println("il.append(_factory.createInvoke(\"" + class_name + "\", \"" + method_name
+ + "\", " + BCELifier.printType(type) + ", "
+ + BCELifier.printArgumentTypes(arg_types) + ", " + "Constants."
+ + Constants.OPCODE_NAMES[opcode].toUpperCase(Locale.ENGLISH) + "));");
+ }
+
+
+ public void visitAllocationInstruction( AllocationInstruction i ) {
+ Type type;
+ if (i instanceof CPInstruction) {
+ type = ((CPInstruction) i).getType(_cp);
+ } else {
+ type = ((NEWARRAY) i).getType();
+ }
+ short opcode = ((Instruction) i).getOpcode();
+ int dim = 1;
+ switch (opcode) {
+ case Constants.NEW:
+ _out.println("il.append(_factory.createNew(\"" + ((ObjectType) type).getClassName()
+ + "\"));");
+ break;
+ case Constants.MULTIANEWARRAY:
+ dim = ((MULTIANEWARRAY) i).getDimensions();
+ case Constants.ANEWARRAY:
+ case Constants.NEWARRAY:
+ if (type instanceof ArrayType) {
+ type = ((ArrayType) type).getBasicType();
+ }
+ _out.println("il.append(_factory.createNewArray(" + BCELifier.printType(type)
+ + ", (short) " + dim + "));");
+ break;
+ default:
+ throw new RuntimeException("Oops: " + opcode);
+ }
+ }
+
+
+ private void createConstant( Object value ) {
+ String embed = value.toString();
+ if (value instanceof String) {
+ embed = '"' + Utility.convertString(value.toString()) + '"';
+ } else if (value instanceof Character) {
+ embed = "(char)0x" + Integer.toHexString(((Character) value).charValue());
+ }
+ _out.println("il.append(new PUSH(_cp, " + embed + "));");
+ }
+
+
+ public void visitLDC( LDC i ) {
+ createConstant(i.getValue(_cp));
+ }
+
+
+ public void visitLDC2_W( LDC2_W i ) {
+ createConstant(i.getValue(_cp));
+ }
+
+
+ public void visitConstantPushInstruction( ConstantPushInstruction i ) {
+ createConstant(i.getValue());
+ }
+
+
+ public void visitINSTANCEOF( INSTANCEOF i ) {
+ Type type = i.getType(_cp);
+ _out.println("il.append(new INSTANCEOF(_cp.addClass(" + BCELifier.printType(type) + ")));");
+ }
+
+
+ public void visitCHECKCAST( CHECKCAST i ) {
+ Type type = i.getType(_cp);
+ _out.println("il.append(_factory.createCheckCast(" + BCELifier.printType(type) + "));");
+ }
+
+
+ public void visitReturnInstruction( ReturnInstruction i ) {
+ Type type = i.getType(_cp);
+ _out.println("il.append(_factory.createReturn(" + BCELifier.printType(type) + "));");
+ }
+
+ // Memorize BranchInstructions that need an update
+ private List branches = new ArrayList();
+
+
+ public void visitBranchInstruction( BranchInstruction bi ) {
+ BranchHandle bh = (BranchHandle) branch_map.get(bi);
+ int pos = bh.getPosition();
+ String name = bi.getName() + "_" + pos;
+ if (bi instanceof Select) {
+ Select s = (Select) bi;
+ branches.add(bi);
+ StringBuffer args = new StringBuffer("new int[] { ");
+ int[] matchs = s.getMatchs();
+ for (int i = 0; i < matchs.length; i++) {
+ args.append(matchs[i]);
+ if (i < matchs.length - 1) {
+ args.append(", ");
+ }
+ }
+ args.append(" }");
+ _out.print("Select " + name + " = new " + bi.getName().toUpperCase(Locale.ENGLISH)
+ + "(" + args + ", new InstructionHandle[] { ");
+ for (int i = 0; i < matchs.length; i++) {
+ _out.print("null");
+ if (i < matchs.length - 1) {
+ _out.print(", ");
+ }
+ }
+ _out.println(" }, null);");
+ } else {
+ int t_pos = bh.getTarget().getPosition();
+ String target;
+ if (pos > t_pos) {
+ target = "ih_" + t_pos;
+ } else {
+ branches.add(bi);
+ target = "null";
+ }
+ _out.println(" BranchInstruction " + name + " = _factory.createBranchInstruction("
+ + "Constants." + bi.getName().toUpperCase(Locale.ENGLISH) + ", " + target
+ + ");");
+ }
+ if (bh.hasTargeters()) {
+ _out.println(" ih_" + pos + " = il.append(" + name + ");");
+ } else {
+ _out.println(" il.append(" + name + ");");
+ }
+ }
+
+
+ public void visitRET( RET i ) {
+ _out.println("il.append(new RET(" + i.getIndex() + ")));");
+ }
+
+
+ private void updateBranchTargets() {
+ for (Iterator i = branches.iterator(); i.hasNext();) {
+ BranchInstruction bi = (BranchInstruction) i.next();
+ BranchHandle bh = (BranchHandle) branch_map.get(bi);
+ int pos = bh.getPosition();
+ String name = bi.getName() + "_" + pos;
+ int t_pos = bh.getTarget().getPosition();
+ _out.println(" " + name + ".setTarget(ih_" + t_pos + ");");
+ if (bi instanceof Select) {
+ InstructionHandle[] ihs = ((Select) bi).getTargets();
+ for (int j = 0; j < ihs.length; j++) {
+ t_pos = ihs[j].getPosition();
+ _out.println(" " + name + ".setTarget(" + j + ", ih_" + t_pos + ");");
+ }
+ }
+ }
+ }
+
+
+ private void updateExceptionHandlers() {
+ CodeExceptionGen[] handlers = _mg.getExceptionHandlers();
+ for (int i = 0; i < handlers.length; i++) {
+ CodeExceptionGen h = handlers[i];
+ String type = (h.getCatchType() == null) ? "null" : BCELifier.printType(h
+ .getCatchType());
+ _out.println(" method.addExceptionHandler(" + "ih_" + h.getStartPC().getPosition()
+ + ", " + "ih_" + h.getEndPC().getPosition() + ", " + "ih_"
+ + h.getHandlerPC().getPosition() + ", " + type + ");");
+ }
}
- }
}
Modified: jakarta/bcel/trunk/src/java/org/apache/bcel/util/BCELifier.java
URL: http://svn.apache.org/viewcvs/jakarta/bcel/trunk/src/java/org/apache/bcel/util/BCELifier.java?rev=386056&r1=386055&r2=386056&view=diff
==============================================================================
--- jakarta/bcel/trunk/src/java/org/apache/bcel/util/BCELifier.java (original)
+++ jakarta/bcel/trunk/src/java/org/apache/bcel/util/BCELifier.java Wed Mar 15 03:31:56 2006
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
- */
+ */
package org.apache.bcel.util;
import java.io.OutputStream;
@@ -43,253 +43,226 @@
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
*/
public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor {
- private static final int FLAG_FOR_UNKNOWN = -1;
- private static final int FLAG_FOR_CLASS = 0;
- private static final int FLAG_FOR_METHOD = 1;
-
- private JavaClass _clazz;
- private PrintWriter _out;
- private ConstantPoolGen _cp;
-
- /** @param clazz Java class to "decompile"
- * @param out where to output Java program
- */
- public BCELifier(JavaClass clazz, OutputStream out) {
- _clazz = clazz;
- _out = new PrintWriter(out);
- _cp = new ConstantPoolGen(_clazz.getConstantPool());
- }
-
- /** Start Java code generation
- */
- public void start() {
- visitJavaClass(_clazz);
- _out.flush();
- }
-
- public void visitJavaClass(JavaClass clazz) {
- String class_name = clazz.getClassName();
- String super_name = clazz.getSuperclassName();
- String package_name = clazz.getPackageName();
- String inter = Utility.printArray(clazz.getInterfaceNames(),
- false, true);
- if(!"".equals(package_name)) {
- class_name = class_name.substring(package_name.length() + 1);
- _out.println("package " + package_name + ";");
- _out.println();
- }
-
- _out.println("import org.apache.bcel.generic.*;");
- _out.println("import org.apache.bcel.classfile.*;");
- _out.println("import org.apache.bcel.*;");
- _out.println("import java.io.*;");
- _out.println();
-
- _out.println("public class " + class_name + "Creator implements Constants {");
- _out.println(" private InstructionFactory _factory;");
- _out.println(" private ConstantPoolGen _cp;");
- _out.println(" private ClassGen _cg;");
- _out.println();
-
- _out.println(" public " + class_name + "Creator() {");
- _out.println(" _cg = new ClassGen(\"" +
- (("".equals(package_name))? class_name :
- package_name + "." + class_name) +
- "\", \"" + super_name + "\", " +
- "\"" + clazz.getSourceFileName() + "\", " +
- printFlags(clazz.getAccessFlags(), FLAG_FOR_CLASS) + ", " +
- "new String[] { " + inter + " });");
- _out.println();
-
- _out.println(" _cp = _cg.getConstantPool();");
- _out.println(" _factory = new InstructionFactory(_cg, _cp);");
- _out.println(" }");
- _out.println();
-
- printCreate();
-
- Field[] fields = clazz.getFields();
-
- if(fields.length > 0) {
- _out.println(" private void createFields() {");
- _out.println(" FieldGen field;");
-
- for(int i=0; i < fields.length; i++) {
- fields[i].accept(this);
- }
-
- _out.println(" }");
- _out.println();
- }
-
- Method[] methods = clazz.getMethods();
-
- for(int i=0; i < methods.length; i++) {
- _out.println(" private void createMethod_" + i + "() {");
-
- methods[i].accept(this);
- _out.println(" }");
- _out.println();
- }
-
- printMain();
- _out.println("}");
- }
-
- private void printCreate() {
- _out.println(" public void create(OutputStream out) throws IOException {");
-
- Field[] fields = _clazz.getFields();
- if(fields.length > 0) {
- _out.println(" createFields();");
- }
-
- Method[] methods = _clazz.getMethods();
- for(int i=0; i < methods.length; i++) {
- _out.println(" createMethod_" + i + "();");
- }
-
- _out.println(" _cg.getJavaClass().dump(out);");
-
- _out.println(" }");
- _out.println();
- }
-
- private void printMain() {
- String class_name = _clazz.getClassName();
-
- _out.println(" public static void main(String[] args) throws Exception {");
- _out.println(" " + class_name + "Creator creator = new " +
- class_name + "Creator();");
- _out.println(" creator.create(new FileOutputStream(\"" + class_name +
- ".class\"));");
- _out.println(" }");
- }
-
- public void visitField(Field field) {
- _out.println();
- _out.println(" field = new FieldGen(" +
- printFlags(field.getAccessFlags()) +
- ", " + printType(field.getSignature()) + ", \"" +
- field.getName() + "\", _cp);");
-
- ConstantValue cv = field.getConstantValue();
-
- if(cv != null) {
- String value = cv.toString();
- _out.println(" field.setInitValue(" + value + ")");
- }
-
- _out.println(" _cg.addField(field.getField());");
- }
-
- public void visitMethod(Method method) {
- MethodGen mg = new MethodGen(method, _clazz.getClassName(), _cp);
-
- Type result_type = mg.getReturnType();
- Type[] arg_types = mg.getArgumentTypes();
-
- _out.println(" InstructionList il = new InstructionList();");
- _out.println(" MethodGen method = new MethodGen(" +
- printFlags(method.getAccessFlags(), FLAG_FOR_METHOD) +
- ", " + printType(result_type) +
- ", " + printArgumentTypes(arg_types) + ", " +
- "new String[] { " +
- Utility.printArray(mg.getArgumentNames(), false, true) +
- " }, \"" + method.getName() + "\", \"" +
- _clazz.getClassName() + "\", il, _cp);");
- _out.println();
-
- BCELFactory factory = new BCELFactory(mg, _out);
- factory.start();
-
- _out.println(" method.setMaxStack();");
- _out.println(" method.setMaxLocals();");
- _out.println(" _cg.addMethod(method.getMethod());");
- _out.println(" il.dispose();");
- }
-
- static String printFlags(int flags) {
- return printFlags(flags, FLAG_FOR_UNKNOWN);
- }
-
- static String printFlags(int flags, int reason) {
- if(flags == 0)
- return "0";
-
- StringBuffer buf = new StringBuffer();
- for(int i=0, pow=1; i <= Constants.MAX_ACC_FLAG; i++) {
- if((flags & pow) != 0) {
- if((pow == Constants.ACC_SYNCHRONIZED) && (reason == FLAG_FOR_CLASS))
- buf.append("ACC_SUPER | ");
- else if ((pow == Constants.ACC_VOLATILE) && (reason == FLAG_FOR_METHOD))
- buf.append("ACC_BRIDGE | ");
- else if ((pow == Constants.ACC_TRANSIENT) && (reason == FLAG_FOR_METHOD))
- buf.append("ACC_VARARGS | ");
- else
- buf.append("ACC_").append(Constants.ACCESS_NAMES[i].toUpperCase(Locale.ENGLISH)).append(" | ");
- }
-
- pow <<= 1;
- }
-
- String str = buf.toString();
- return str.substring(0, str.length() - 3);
- }
-
- static String printArgumentTypes(Type[] arg_types) {
- if(arg_types.length == 0)
- return "Type.NO_ARGS";
-
- StringBuffer args = new StringBuffer();
-
- for(int i=0; i < arg_types.length; i++) {
- args.append(printType(arg_types[i]));
-
- if(i < arg_types.length - 1)
- args.append(", ");
- }
-
- return "new Type[] { " + args.toString() + " }";
- }
-
- static String printType(Type type) {
- return printType(type.getSignature());
- }
-
- static String printType(String signature) {
- Type type = Type.getType(signature);
- byte t = type.getType();
-
- if(t <= Constants.T_VOID) {
- return "Type." + Constants.TYPE_NAMES[t].toUpperCase(Locale.ENGLISH);
- } else if(type.toString().equals("java.lang.String")) {
- return "Type.STRING";
- } else if(type.toString().equals("java.lang.Object")) {
- return "Type.OBJECT";
- } else if(type.toString().equals("java.lang.StringBuffer")) {
- return "Type.STRINGBUFFER";
- } else if(type instanceof ArrayType) {
- ArrayType at = (ArrayType)type;
-
- return "new ArrayType(" + printType(at.getBasicType()) +
- ", " + at.getDimensions() + ")";
- } else {
- return "new ObjectType(\"" + Utility.signatureToString(signature, false) +
- "\")";
- }
- }
-
- /** Default main method
- */
- public static void main(String[] argv) throws Exception {
- JavaClass java_class;
- String name = argv[0];
-
- if((java_class = Repository.lookupClass(name)) == null)
- java_class = new ClassParser(name).parse(); // May throw IOException
-
- BCELifier bcelifier = new BCELifier(java_class, System.out);
- bcelifier.start();
- }
+
+ private static final int FLAG_FOR_UNKNOWN = -1;
+ private static final int FLAG_FOR_CLASS = 0;
+ private static final int FLAG_FOR_METHOD = 1;
+ private JavaClass _clazz;
+ private PrintWriter _out;
+ private ConstantPoolGen _cp;
+
+
+ /** @param clazz Java class to "decompile"
+ * @param out where to output Java program
+ */
+ public BCELifier(JavaClass clazz, OutputStream out) {
+ _clazz = clazz;
+ _out = new PrintWriter(out);
+ _cp = new ConstantPoolGen(_clazz.getConstantPool());
+ }
+
+
+ /** Start Java code generation
+ */
+ public void start() {
+ visitJavaClass(_clazz);
+ _out.flush();
+ }
+
+
+ public void visitJavaClass( JavaClass clazz ) {
+ String class_name = clazz.getClassName();
+ String super_name = clazz.getSuperclassName();
+ String package_name = clazz.getPackageName();
+ String inter = Utility.printArray(clazz.getInterfaceNames(), false, true);
+ if (!"".equals(package_name)) {
+ class_name = class_name.substring(package_name.length() + 1);
+ _out.println("package " + package_name + ";");
+ _out.println();
+ }
+ _out.println("import org.apache.bcel.generic.*;");
+ _out.println("import org.apache.bcel.classfile.*;");
+ _out.println("import org.apache.bcel.*;");
+ _out.println("import java.io.*;");
+ _out.println();
+ _out.println("public class " + class_name + "Creator implements Constants {");
+ _out.println(" private InstructionFactory _factory;");
+ _out.println(" private ConstantPoolGen _cp;");
+ _out.println(" private ClassGen _cg;");
+ _out.println();
+ _out.println(" public " + class_name + "Creator() {");
+ _out.println(" _cg = new ClassGen(\""
+ + (("".equals(package_name)) ? class_name : package_name + "." + class_name)
+ + "\", \"" + super_name + "\", " + "\"" + clazz.getSourceFileName() + "\", "
+ + printFlags(clazz.getAccessFlags(), FLAG_FOR_CLASS) + ", " + "new String[] { "
+ + inter + " });");
+ _out.println();
+ _out.println(" _cp = _cg.getConstantPool();");
+ _out.println(" _factory = new InstructionFactory(_cg, _cp);");
+ _out.println(" }");
+ _out.println();
+ printCreate();
+ Field[] fields = clazz.getFields();
+ if (fields.length > 0) {
+ _out.println(" private void createFields() {");
+ _out.println(" FieldGen field;");
+ for (int i = 0; i < fields.length; i++) {
+ fields[i].accept(this);
+ }
+ _out.println(" }");
+ _out.println();
+ }
+ Method[] methods = clazz.getMethods();
+ for (int i = 0; i < methods.length; i++) {
+ _out.println(" private void createMethod_" + i + "() {");
+ methods[i].accept(this);
+ _out.println(" }");
+ _out.println();
+ }
+ printMain();
+ _out.println("}");
+ }
+
+
+ private void printCreate() {
+ _out.println(" public void create(OutputStream out) throws IOException {");
+ Field[] fields = _clazz.getFields();
+ if (fields.length > 0) {
+ _out.println(" createFields();");
+ }
+ Method[] methods = _clazz.getMethods();
+ for (int i = 0; i < methods.length; i++) {
+ _out.println(" createMethod_" + i + "();");
+ }
+ _out.println(" _cg.getJavaClass().dump(out);");
+ _out.println(" }");
+ _out.println();
+ }
+
+
+ private void printMain() {
+ String class_name = _clazz.getClassName();
+ _out.println(" public static void main(String[] args) throws Exception {");
+ _out.println(" " + class_name + "Creator creator = new " + class_name + "Creator();");
+ _out.println(" creator.create(new FileOutputStream(\"" + class_name + ".class\"));");
+ _out.println(" }");
+ }
+
+
+ public void visitField( Field field ) {
+ _out.println();
+ _out.println(" field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", "
+ + printType(field.getSignature()) + ", \"" + field.getName() + "\", _cp);");
+ ConstantValue cv = field.getConstantValue();
+ if (cv != null) {
+ String value = cv.toString();
+ _out.println(" field.setInitValue(" + value + ")");
+ }
+ _out.println(" _cg.addField(field.getField());");
+ }
+
+
+ public void visitMethod( Method method ) {
+ MethodGen mg = new MethodGen(method, _clazz.getClassName(), _cp);
+ Type result_type = mg.getReturnType();
+ Type[] arg_types = mg.getArgumentTypes();
+ _out.println(" InstructionList il = new InstructionList();");
+ _out.println(" MethodGen method = new MethodGen("
+ + printFlags(method.getAccessFlags(), FLAG_FOR_METHOD) + ", "
+ + printType(result_type) + ", " + printArgumentTypes(arg_types) + ", "
+ + "new String[] { " + Utility.printArray(mg.getArgumentNames(), false, true)
+ + " }, \"" + method.getName() + "\", \"" + _clazz.getClassName() + "\", il, _cp);");
+ _out.println();
+ BCELFactory factory = new BCELFactory(mg, _out);
+ factory.start();
+ _out.println(" method.setMaxStack();");
+ _out.println(" method.setMaxLocals();");
+ _out.println(" _cg.addMethod(method.getMethod());");
+ _out.println(" il.dispose();");
+ }
+
+
+ static String printFlags( int flags ) {
+ return printFlags(flags, FLAG_FOR_UNKNOWN);
+ }
+
+
+ static String printFlags( int flags, int reason ) {
+ if (flags == 0) {
+ return "0";
+ }
+ StringBuffer buf = new StringBuffer();
+ for (int i = 0, pow = 1; i <= Constants.MAX_ACC_FLAG; i++) {
+ if ((flags & pow) != 0) {
+ if ((pow == Constants.ACC_SYNCHRONIZED) && (reason == FLAG_FOR_CLASS)) {
+ buf.append("ACC_SUPER | ");
+ } else if ((pow == Constants.ACC_VOLATILE) && (reason == FLAG_FOR_METHOD)) {
+ buf.append("ACC_BRIDGE | ");
+ } else if ((pow == Constants.ACC_TRANSIENT) && (reason == FLAG_FOR_METHOD)) {
+ buf.append("ACC_VARARGS | ");
+ } else {
+ buf.append("ACC_")
+ .append(Constants.ACCESS_NAMES[i].toUpperCase(Locale.ENGLISH)).append(
+ " | ");
+ }
+ }
+ pow <<= 1;
+ }
+ String str = buf.toString();
+ return str.substring(0, str.length() - 3);
+ }
+
+
+ static String printArgumentTypes( Type[] arg_types ) {
+ if (arg_types.length == 0) {
+ return "Type.NO_ARGS";
+ }
+ StringBuffer args = new StringBuffer();
+ for (int i = 0; i < arg_types.length; i++) {
+ args.append(printType(arg_types[i]));
+ if (i < arg_types.length - 1) {
+ args.append(", ");
+ }
+ }
+ return "new Type[] { " + args.toString() + " }";
+ }
+
+
+ static String printType( Type type ) {
+ return printType(type.getSignature());
+ }
+
+
+ static String printType( String signature ) {
+ Type type = Type.getType(signature);
+ byte t = type.getType();
+ if (t <= Constants.T_VOID) {
+ return "Type." + Constants.TYPE_NAMES[t].toUpperCase(Locale.ENGLISH);
+ } else if (type.toString().equals("java.lang.String")) {
+ return "Type.STRING";
+ } else if (type.toString().equals("java.lang.Object")) {
+ return "Type.OBJECT";
+ } else if (type.toString().equals("java.lang.StringBuffer")) {
+ return "Type.STRINGBUFFER";
+ } else if (type instanceof ArrayType) {
+ ArrayType at = (ArrayType) type;
+ return "new ArrayType(" + printType(at.getBasicType()) + ", " + at.getDimensions()
+ + ")";
+ } else {
+ return "new ObjectType(\"" + Utility.signatureToString(signature, false) + "\")";
+ }
+ }
+
+
+ /** Default main method
+ */
+ public static void main( String[] argv ) throws Exception {
+ JavaClass java_class;
+ String name = argv[0];
+ if ((java_class = Repository.lookupClass(name)) == null) {
+ java_class = new ClassParser(name).parse(); // May throw IOException
+ }
+ BCELifier bcelifier = new BCELifier(java_class, System.out);
+ bcelifier.start();
+ }
}
Modified: jakarta/bcel/trunk/src/java/org/apache/bcel/util/ByteSequence.java
URL: http://svn.apache.org/viewcvs/jakarta/bcel/trunk/src/java/org/apache/bcel/util/ByteSequence.java?rev=386056&r1=386055&r2=386056&view=diff
==============================================================================
--- jakarta/bcel/trunk/src/java/org/apache/bcel/util/ByteSequence.java (original)
+++ jakarta/bcel/trunk/src/java/org/apache/bcel/util/ByteSequence.java Wed Mar 15 03:31:56 2006
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
- */
+ */
package org.apache.bcel.util;
import java.io.ByteArrayInputStream;
@@ -28,19 +28,41 @@
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
*/
public final class ByteSequence extends DataInputStream {
- private ByteArrayStream byte_stream;
- public ByteSequence(byte[] bytes) {
- super(new ByteArrayStream(bytes));
- byte_stream = (ByteArrayStream)in;
- }
-
- public final int getIndex() { return byte_stream.getPosition(); }
- final void unreadByte() { byte_stream.unreadByte(); }
-
- private static final class ByteArrayStream extends ByteArrayInputStream {
- ByteArrayStream(byte[] bytes) { super(bytes); }
- final int getPosition() { return pos; } // is protected in ByteArrayInputStream
- final void unreadByte() { if(pos > 0) pos--; }
- }
+ private ByteArrayStream byte_stream;
+
+
+ public ByteSequence(byte[] bytes) {
+ super(new ByteArrayStream(bytes));
+ byte_stream = (ByteArrayStream) in;
+ }
+
+
+ public final int getIndex() {
+ return byte_stream.getPosition();
+ }
+
+
+ final void unreadByte() {
+ byte_stream.unreadByte();
+ }
+
+ private static final class ByteArrayStream extends ByteArrayInputStream {
+
+ ByteArrayStream(byte[] bytes) {
+ super(bytes);
+ }
+
+
+ final int getPosition() {
+ return pos;
+ } // is protected in ByteArrayInputStream
+
+
+ final void unreadByte() {
+ if (pos > 0) {
+ pos--;
+ }
+ }
+ }
}
Modified: jakarta/bcel/trunk/src/java/org/apache/bcel/util/Class2HTML.java
URL: http://svn.apache.org/viewcvs/jakarta/bcel/trunk/src/java/org/apache/bcel/util/Class2HTML.java?rev=386056&r1=386055&r2=386056&view=diff
==============================================================================
--- jakarta/bcel/trunk/src/java/org/apache/bcel/util/Class2HTML.java (original)
+++ jakarta/bcel/trunk/src/java/org/apache/bcel/util/Class2HTML.java Wed Mar 15 03:31:56 2006
@@ -13,10 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
- */
+ */
package org.apache.bcel.util;
-
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -50,193 +49,183 @@
*
* @version $Id$
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
-*/
-public class Class2HTML implements Constants
-{
- private JavaClass java_class; // current class object
- private String dir;
-
- private static String class_package; // name of package, unclean to make it static, but ...
- private static String class_name; // name of current class, dito
- private static ConstantPool constant_pool;
-
- /**
- * Write contents of the given JavaClass into HTML files.
- *
- * @param java_class The class to write
- * @param dir The directory to put the files in
- */
- public Class2HTML(JavaClass java_class, String dir) throws IOException {
- Method[] methods = java_class.getMethods();
-
- this.java_class = java_class;
- this.dir = dir;
- class_name = java_class.getClassName(); // Remember full name
- constant_pool = java_class.getConstantPool();
-
- // Get package name by tacking off everything after the last `.'
- int index = class_name.lastIndexOf('.');
- if(index > -1)
- class_package = class_name.substring(0, index);
- else
- class_package = ""; // default package
-
- ConstantHTML constant_html = new ConstantHTML(dir, class_name, class_package, methods,
- constant_pool);
-
- /* Attributes can't be written in one step, so we just open a file
- * which will be written consequently.
+ */
+public class Class2HTML implements Constants {
+
+ private JavaClass java_class; // current class object
+ private String dir;
+ private static String class_package; // name of package, unclean to make it static, but ...
+ private static String class_name; // name of current class, dito
+ private static ConstantPool constant_pool;
+
+
+ /**
+ * Write contents of the given JavaClass into HTML files.
+ *
+ * @param java_class The class to write
+ * @param dir The directory to put the files in
+ */
+ public Class2HTML(JavaClass java_class, String dir) throws IOException {
+ Method[] methods = java_class.getMethods();
+ this.java_class = java_class;
+ this.dir = dir;
+ class_name = java_class.getClassName(); // Remember full name
+ constant_pool = java_class.getConstantPool();
+ // Get package name by tacking off everything after the last `.'
+ int index = class_name.lastIndexOf('.');
+ if (index > -1) {
+ class_package = class_name.substring(0, index);
+ } else {
+ class_package = ""; // default package
+ }
+ ConstantHTML constant_html = new ConstantHTML(dir, class_name, class_package, methods,
+ constant_pool);
+ /* Attributes can't be written in one step, so we just open a file
+ * which will be written consequently.
+ */
+ AttributeHTML attribute_html = new AttributeHTML(dir, class_name, constant_pool,
+ constant_html);
+ MethodHTML method_html = new MethodHTML(dir, class_name, methods, java_class.getFields(),
+ constant_html, attribute_html);
+ // Write main file (with frames, yuk)
+ writeMainHTML(attribute_html);
+ new CodeHTML(dir, class_name, methods, constant_pool, constant_html);
+ attribute_html.close();
+ }
+
+
+ public static void main( String argv[] ) {
+ String[] file_name = new String[argv.length];
+ int files = 0;
+ ClassParser parser = null;
+ JavaClass java_class = null;
+ String zip_file = null;
+ char sep = System.getProperty("file.separator").toCharArray()[0];
+ String dir = "." + sep; // Where to store HTML files
+ try {
+ /* Parse command line arguments.
+ */
+ for (int i = 0; i < argv.length; i++) {
+ if (argv[i].charAt(0) == '-') { // command line switch
+ if (argv[i].equals("-d")) { // Specify target directory, default `.´
+ dir = argv[++i];
+ if (!dir.endsWith("" + sep)) {
+ dir = dir + sep;
+ }
+ new File(dir).mkdirs(); // Create target directory if necessary
+ } else if (argv[i].equals("-zip")) {
+ zip_file = argv[++i];
+ } else {
+ System.out.println("Unknown option " + argv[i]);
+ }
+ } else {
+ file_name[files++] = argv[i];
+ }
+ }
+ if (files == 0) {
+ System.err.println("Class2HTML: No input files specified.");
+ } else { // Loop through files ...
+ for (int i = 0; i < files; i++) {
+ System.out.print("Processing " + file_name[i] + "...");
+ if (zip_file == null) {
+ parser = new ClassParser(file_name[i]); // Create parser object from file
+ } else {
+ parser = new ClassParser(zip_file, file_name[i]); // Create parser object from zip file
+ }
+ java_class = parser.parse();
+ new Class2HTML(java_class, dir);
+ System.out.println("Done.");
+ }
+ }
+ } catch (Exception e) {
+ System.out.println(e);
+ e.printStackTrace(System.out);
+ }
+ }
+
+
+ /**
+ * Utility method that converts a class reference in the constant pool,
+ * i.e., an index to a string.
*/
- AttributeHTML attribute_html = new AttributeHTML(dir, class_name, constant_pool, constant_html);
+ static String referenceClass( int index ) {
+ String str = constant_pool.getConstantString(index, CONSTANT_Class);
+ str = Utility.compactClassName(str);
+ str = Utility.compactClassName(str, class_package + ".", true);
+ return "<A HREF=\"" + class_name + "_cp.html#cp" + index + "\" TARGET=ConstantPool>" + str
+ + "</A>";
+ }
+
+
+ static final String referenceType( String type ) {
+ String short_type = Utility.compactClassName(type);
+ short_type = Utility.compactClassName(short_type, class_package + ".", true);
+ int index = type.indexOf('['); // Type is an array?
+ String base_type = type;
+ if (index > -1) {
+ base_type = type.substring(0, index); // Tack of the `['
+ }
+ // test for basic type
+ if (base_type.equals("int") || base_type.equals("short") || base_type.equals("boolean")
+ || base_type.equals("void") || base_type.equals("char") || base_type.equals("byte")
+ || base_type.equals("long") || base_type.equals("double")
+ || base_type.equals("float")) {
+ return "<FONT COLOR=\"#00FF00\">" + type + "</FONT>";
+ } else {
+ return "<A HREF=\"" + base_type + ".html\" TARGET=_top>" + short_type + "</A>";
+ }
+ }
- MethodHTML method_html = new MethodHTML(dir, class_name, methods, java_class.getFields(),
- constant_html, attribute_html);
- // Write main file (with frames, yuk)
- writeMainHTML(attribute_html);
- new CodeHTML(dir, class_name, methods, constant_pool, constant_html);
- attribute_html.close();
- }
-
- public static void main(String argv[])
- {
- String[] file_name = new String[argv.length];
- int files=0;
- ClassParser parser=null;
- JavaClass java_class=null;
- String zip_file = null;
- char sep = System.getProperty("file.separator").toCharArray()[0];
- String dir = "." + sep; // Where to store HTML files
-
- try {
- /* Parse command line arguments.
- */
- for(int i=0; i < argv.length; i++) {
- if(argv[i].charAt(0) == '-') { // command line switch
- if(argv[i].equals("-d")) { // Specify target directory, default `.´
- dir = argv[++i];
-
- if(!dir.endsWith("" + sep))
- dir = dir + sep;
-
- new File(dir).mkdirs(); // Create target directory if necessary
- }
- else if(argv[i].equals("-zip"))
- zip_file = argv[++i];
- else
- System.out.println("Unknown option " + argv[i]);
- }
- else // add file name to list */
- file_name[files++] = argv[i];
- }
-
- if(files == 0)
- System.err.println("Class2HTML: No input files specified.");
- else { // Loop through files ...
- for(int i=0; i < files; i++) {
- System.out.print("Processing " + file_name[i] + "...");
- if(zip_file == null)
- parser = new ClassParser(file_name[i]); // Create parser object from file
- else
- parser = new ClassParser(zip_file, file_name[i]); // Create parser object from zip file
-
- java_class = parser.parse();
- new Class2HTML(java_class, dir);
- System.out.println("Done.");
- }
- }
- } catch(Exception e) {
- System.out.println(e);
- e.printStackTrace(System.out);
- }
- }
-
- /**
- * Utility method that converts a class reference in the constant pool,
- * i.e., an index to a string.
- */
- static String referenceClass(int index) {
- String str = constant_pool.getConstantString(index, CONSTANT_Class);
- str = Utility.compactClassName(str);
- str = Utility.compactClassName(str, class_package + ".", true);
-
- return "<A HREF=\"" + class_name + "_cp.html#cp" + index +
- "\" TARGET=ConstantPool>" + str + "</A>";
- }
-
- static final String referenceType(String type) {
- String short_type = Utility.compactClassName(type);
- short_type = Utility.compactClassName(short_type, class_package + ".", true);
-
- int index = type.indexOf('['); // Type is an array?
- String base_type = type;
-
- if (index > -1) {
- base_type = type.substring(0, index); // Tack of the `['
- }
-
- // test for basic type
- if (base_type.equals("int")
- || base_type.equals("short")
- || base_type.equals("boolean")
- || base_type.equals("void")
- || base_type.equals("char")
- || base_type.equals("byte")
- || base_type.equals("long")
- || base_type.equals("double")
- || base_type.equals("float")) {
- return "<FONT COLOR=\"#00FF00\">" + type + "</FONT>";
- } else {
- return "<A HREF=\"" + base_type + ".html\" TARGET=_top>" + short_type + "</A>";
- }
- }
-
- static String toHTML(String str) {
- StringBuffer buf = new StringBuffer();
-
- try { // Filter any characters HTML doesn't like such as < and > in particular
- for(int i=0; i < str.length(); i++) {
- char ch;
-
- switch(ch=str.charAt(i)) {
- case '<': buf.append("<"); break;
- case '>': buf.append(">"); break;
- case '\n': buf.append("\\n"); break;
- case '\r': buf.append("\\r"); break;
- default: buf.append(ch);
- }
- }
- } catch(StringIndexOutOfBoundsException e) {} // Never occurs
-
- return buf.toString();
- }
-
- private void writeMainHTML(AttributeHTML attribute_html) throws IOException {
- PrintWriter file = new PrintWriter(new FileOutputStream(dir + class_name + ".html"));
- Attribute[] attributes = java_class.getAttributes();
-
- file.println("<HTML>\n" + "<HEAD><TITLE>Documentation for " + class_name + "</TITLE>" +
- "</HEAD>\n" +
- "<FRAMESET BORDER=1 cols=\"30%,*\">\n" +
- "<FRAMESET BORDER=1 rows=\"80%,*\">\n" +
-
- "<FRAME NAME=\"ConstantPool\" SRC=\"" + class_name + "_cp.html" + "\"\n MARGINWIDTH=\"0\" " +
- "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" +
- "<FRAME NAME=\"Attributes\" SRC=\"" + class_name + "_attributes.html" +
- "\"\n MARGINWIDTH=\"0\" " +
- "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" +
- "</FRAMESET>\n" +
-
- "<FRAMESET BORDER=1 rows=\"80%,*\">\n" +
- "<FRAME NAME=\"Code\" SRC=\"" + class_name + "_code.html\"\n MARGINWIDTH=0 " +
- "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" +
- "<FRAME NAME=\"Methods\" SRC=\"" + class_name + "_methods.html\"\n MARGINWIDTH=0 " +
- "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" +
- "</FRAMESET></FRAMESET></HTML>"
- );
-
- file.close();
-
- for(int i=0; i < attributes.length; i++)
- attribute_html.writeAttribute(attributes[i], "class" + i);
- }
+
+ static String toHTML( String str ) {
+ StringBuffer buf = new StringBuffer();
+ try { // Filter any characters HTML doesn't like such as < and > in particular
+ for (int i = 0; i < str.length(); i++) {
+ char ch;
+ switch (ch = str.charAt(i)) {
+ case '<':
+ buf.append("<");
+ break;
+ case '>':
+ buf.append(">");
+ break;
+ case '\n':
+ buf.append("\\n");
+ break;
+ case '\r':
+ buf.append("\\r");
+ break;
+ default:
+ buf.append(ch);
+ }
+ }
+ } catch (StringIndexOutOfBoundsException e) {
+ } // Never occurs
+ return buf.toString();
+ }
+
+
+ private void writeMainHTML( AttributeHTML attribute_html ) throws IOException {
+ PrintWriter file = new PrintWriter(new FileOutputStream(dir + class_name + ".html"));
+ Attribute[] attributes = java_class.getAttributes();
+ file.println("<HTML>\n" + "<HEAD><TITLE>Documentation for " + class_name + "</TITLE>"
+ + "</HEAD>\n" + "<FRAMESET BORDER=1 cols=\"30%,*\">\n"
+ + "<FRAMESET BORDER=1 rows=\"80%,*\">\n" + "<FRAME NAME=\"ConstantPool\" SRC=\""
+ + class_name + "_cp.html" + "\"\n MARGINWIDTH=\"0\" "
+ + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n"
+ + "<FRAME NAME=\"Attributes\" SRC=\"" + class_name + "_attributes.html"
+ + "\"\n MARGINWIDTH=\"0\" "
+ + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" + "</FRAMESET>\n"
+ + "<FRAMESET BORDER=1 rows=\"80%,*\">\n" + "<FRAME NAME=\"Code\" SRC=\""
+ + class_name + "_code.html\"\n MARGINWIDTH=0 "
+ + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n"
+ + "<FRAME NAME=\"Methods\" SRC=\"" + class_name
+ + "_methods.html\"\n MARGINWIDTH=0 "
+ + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n"
+ + "</FRAMESET></FRAMESET></HTML>");
+ file.close();
+ for (int i = 0; i < attributes.length; i++) {
+ attribute_html.writeAttribute(attributes[i], "class" + i);
+ }
+ }
}
Modified: jakarta/bcel/trunk/src/java/org/apache/bcel/util/ClassLoader.java
URL: http://svn.apache.org/viewcvs/jakarta/bcel/trunk/src/java/org/apache/bcel/util/ClassLoader.java?rev=386056&r1=386055&r2=386056&view=diff
==============================================================================
--- jakarta/bcel/trunk/src/java/org/apache/bcel/util/ClassLoader.java (original)
+++ jakarta/bcel/trunk/src/java/org/apache/bcel/util/ClassLoader.java Wed Mar 15 03:31:56 2006
@@ -13,10 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
- */
+ */
package org.apache.bcel.util;
-
import java.io.ByteArrayInputStream;
import java.util.Hashtable;
import org.apache.bcel.Constants;
@@ -52,140 +51,134 @@
* @see ClassPath
*/
public class ClassLoader extends java.lang.ClassLoader {
- public static final String[] DEFAULT_IGNORED_PACKAGES = {
- "java.", "javax.", "sun."
- };
-
- private Hashtable classes = new Hashtable(); // Hashtable is synchronized thus thread-safe
- private String[] ignored_packages;
-
- private Repository repository = SyntheticRepository.getInstance();
-
- /** Ignored packages are by default ( "java.", "sun.",
- * "javax."), i.e. loaded by system class loader
- */
- public ClassLoader() {
- this(DEFAULT_IGNORED_PACKAGES);
- }
-
- /** @param deferTo delegate class loader to use for ignored packages
- */
- public ClassLoader(java.lang.ClassLoader deferTo) {
- super(deferTo);
- this.ignored_packages = DEFAULT_IGNORED_PACKAGES;
- this.repository = new ClassLoaderRepository(deferTo);
- }
-
- /** @param ignored_packages classes contained in these packages will be loaded
- * with the system class loader
- */
- public ClassLoader(String[] ignored_packages) {
- this.ignored_packages = ignored_packages;
- }
-
- /** @param ignored_packages classes contained in these packages will be loaded
- * with the system class loader
- * @param deferTo delegate class loader to use for ignored packages
- */
- public ClassLoader(java.lang.ClassLoader deferTo, String [] ignored_packages) {
- this(ignored_packages);
- this.repository = new ClassLoaderRepository(deferTo);
- }
-
- protected Class loadClass(String class_name, boolean resolve)
- throws ClassNotFoundException
- {
- Class cl = null;
-
- /* First try: lookup hash table.
- */
- if((cl=(Class)classes.get(class_name)) == null) {
- /* Second try: Load system class using system class loader. You better
- * don't mess around with them.
- */
- for(int i=0; i < ignored_packages.length; i++) {
- if(class_name.startsWith(ignored_packages[i])) {
- cl = getParent().loadClass(class_name);
- break;
- }
- }
-
- if(cl == null) {
- JavaClass clazz = null;
-
- /* Third try: Special request?
- */
- if(class_name.indexOf("$$BCEL$$") >= 0)
- clazz = createClass(class_name);
- else { // Fourth try: Load classes via repository
- if ((clazz = repository.loadClass(class_name)) != null) {
- clazz = modifyClass(clazz);
- }
- else
- throw new ClassNotFoundException(class_name);
- }
-
- if(clazz != null) {
- byte[] bytes = clazz.getBytes();
- cl = defineClass(class_name, bytes, 0, bytes.length);
- } else // Fourth try: Use default class loader
- cl = Class.forName(class_name);
- }
-
- if(resolve)
- resolveClass(cl);
- }
-
- classes.put(class_name, cl);
-
- return cl;
- }
-
- /** Override this method if you want to alter a class before it gets actually
- * loaded. Does nothing by default.
- */
- protected JavaClass modifyClass(JavaClass clazz) {
- return clazz;
- }
-
- /**
- * Override this method to create you own classes on the fly. The
- * name contains the special token $$BCEL$$. Everything before that
- * token is consddered to be a package name. You can encode you own
- * arguments into the subsequent string. You must regard however not
- * to use any "illegal" characters, i.e., characters that may not
- * appear in a Java class name too<br>
- *
- * The default implementation interprets the string as a encoded compressed
- * Java class, unpacks and decodes it with the Utility.decode() method, and
- * parses the resulting byte array and returns the resulting JavaClass object.
- *
- * @param class_name compressed byte code with "$$BCEL$$" in it
- */
- protected JavaClass createClass(String class_name) {
- int index = class_name.indexOf("$$BCEL$$");
- String real_name = class_name.substring(index + 8);
-
- JavaClass clazz = null;
- try {
- byte[] bytes = Utility.decode(real_name, true);
- ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo");
-
- clazz = parser.parse();
- } catch(Throwable e) {
- e.printStackTrace();
- return null;
- }
-
- // Adapt the class name to the passed value
- ConstantPool cp = clazz.getConstantPool();
-
- ConstantClass cl = (ConstantClass)cp.getConstant(clazz.getClassNameIndex(),
- Constants.CONSTANT_Class);
- ConstantUtf8 name = (ConstantUtf8)cp.getConstant(cl.getNameIndex(),
- Constants.CONSTANT_Utf8);
- name.setBytes(class_name.replace('.', '/'));
- return clazz;
- }
+ public static final String[] DEFAULT_IGNORED_PACKAGES = {
+ "java.", "javax.", "sun."
+ };
+ private Hashtable classes = new Hashtable(); // Hashtable is synchronized thus thread-safe
+ private String[] ignored_packages;
+ private Repository repository = SyntheticRepository.getInstance();
+
+
+ /** Ignored packages are by default ( "java.", "sun.",
+ * "javax."), i.e. loaded by system class loader
+ */
+ public ClassLoader() {
+ this(DEFAULT_IGNORED_PACKAGES);
+ }
+
+
+ /** @param deferTo delegate class loader to use for ignored packages
+ */
+ public ClassLoader(java.lang.ClassLoader deferTo) {
+ super(deferTo);
+ this.ignored_packages = DEFAULT_IGNORED_PACKAGES;
+ this.repository = new ClassLoaderRepository(deferTo);
+ }
+
+
+ /** @param ignored_packages classes contained in these packages will be loaded
+ * with the system class loader
+ */
+ public ClassLoader(String[] ignored_packages) {
+ this.ignored_packages = ignored_packages;
+ }
+
+
+ /** @param ignored_packages classes contained in these packages will be loaded
+ * with the system class loader
+ * @param deferTo delegate class loader to use for ignored packages
+ */
+ public ClassLoader(java.lang.ClassLoader deferTo, String[] ignored_packages) {
+ this(ignored_packages);
+ this.repository = new ClassLoaderRepository(deferTo);
+ }
+
+
+ protected Class loadClass( String class_name, boolean resolve ) throws ClassNotFoundException {
+ Class cl = null;
+ /* First try: lookup hash table.
+ */
+ if ((cl = (Class) classes.get(class_name)) == null) {
+ /* Second try: Load system class using system class loader. You better
+ * don't mess around with them.
+ */
+ for (int i = 0; i < ignored_packages.length; i++) {
+ if (class_name.startsWith(ignored_packages[i])) {
+ cl = getParent().loadClass(class_name);
+ break;
+ }
+ }
+ if (cl == null) {
+ JavaClass clazz = null;
+ /* Third try: Special request?
+ */
+ if (class_name.indexOf("$$BCEL$$") >= 0) {
+ clazz = createClass(class_name);
+ } else { // Fourth try: Load classes via repository
+ if ((clazz = repository.loadClass(class_name)) != null) {
+ clazz = modifyClass(clazz);
+ } else {
+ throw new ClassNotFoundException(class_name);
+ }
+ }
+ if (clazz != null) {
+ byte[] bytes = clazz.getBytes();
+ cl = defineClass(class_name, bytes, 0, bytes.length);
+ } else {
+ cl = Class.forName(class_name);
+ }
+ }
+ if (resolve) {
+ resolveClass(cl);
+ }
+ }
+ classes.put(class_name, cl);
+ return cl;
+ }
+
+
+ /** Override this method if you want to alter a class before it gets actually
+ * loaded. Does nothing by default.
+ */
+ protected JavaClass modifyClass( JavaClass clazz ) {
+ return clazz;
+ }
+
+
+ /**
+ * Override this method to create you own classes on the fly. The
+ * name contains the special token $$BCEL$$. Everything before that
+ * token is consddered to be a package name. You can encode you own
+ * arguments into the subsequent string. You must regard however not
+ * to use any "illegal" characters, i.e., characters that may not
+ * appear in a Java class name too<br>
+ *
+ * The default implementation interprets the string as a encoded compressed
+ * Java class, unpacks and decodes it with the Utility.decode() method, and
+ * parses the resulting byte array and returns the resulting JavaClass object.
+ *
+ * @param class_name compressed byte code with "$$BCEL$$" in it
+ */
+ protected JavaClass createClass( String class_name ) {
+ int index = class_name.indexOf("$$BCEL$$");
+ String real_name = class_name.substring(index + 8);
+ JavaClass clazz = null;
+ try {
+ byte[] bytes = Utility.decode(real_name, true);
+ ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo");
+ clazz = parser.parse();
+ } catch (Throwable e) {
+ e.printStackTrace();
+ return null;
+ }
+ // Adapt the class name to the passed value
+ ConstantPool cp = clazz.getConstantPool();
+ ConstantClass cl = (ConstantClass) cp.getConstant(clazz.getClassNameIndex(),
+ Constants.CONSTANT_Class);
+ ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(),
+ Constants.CONSTANT_Utf8);
+ name.setBytes(class_name.replace('.', '/'));
+ return clazz;
+ }
}
Modified: jakarta/bcel/trunk/src/java/org/apache/bcel/util/ClassLoaderRepository.java
URL: http://svn.apache.org/viewcvs/jakarta/bcel/trunk/src/java/org/apache/bcel/util/ClassLoaderRepository.java?rev=386056&r1=386055&r2=386056&view=diff
==============================================================================
--- jakarta/bcel/trunk/src/java/org/apache/bcel/util/ClassLoaderRepository.java (original)
+++ jakarta/bcel/trunk/src/java/org/apache/bcel/util/ClassLoaderRepository.java Wed Mar 15 03:31:56 2006
@@ -13,10 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
- */
+ */
package org.apache.bcel.util;
-
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
@@ -38,82 +37,85 @@
* @author David Dixon-Peugh
*/
public class ClassLoaderRepository implements Repository {
- private java.lang.ClassLoader loader;
- private Map loadedClasses = new HashMap(); // CLASSNAME X JAVACLASS
- public ClassLoaderRepository(java.lang.ClassLoader loader) {
- this.loader = loader;
- }
-
- /**
- * Store a new JavaClass into this Repository.
- */
- public void storeClass(JavaClass clazz) {
- loadedClasses.put(clazz.getClassName(), clazz);
- clazz.setRepository(this);
- }
-
- /**
- * Remove class from repository
- */
- public void removeClass(JavaClass clazz) {
- loadedClasses.remove(clazz.getClassName());
- }
-
- /**
- * Find an already defined JavaClass.
- */
- public JavaClass findClass(String className) {
- if (loadedClasses.containsKey(className)) {
- return (JavaClass)loadedClasses.get(className);
- } else {
- return null;
- }
- }
-
- /**
- * Lookup a JavaClass object from the Class Name provided.
- */
- public JavaClass loadClass(String className) throws ClassNotFoundException {
- String classFile = className.replace('.', '/');
-
- JavaClass RC = findClass(className);
- if (RC != null) {
- return RC;
- }
-
- try {
- InputStream is = loader.getResourceAsStream(classFile + ".class");
-
- if (is == null) {
- throw new ClassNotFoundException(className + " not found.");
- }
-
- ClassParser parser = new ClassParser(is, className);
- RC = parser.parse();
-
- storeClass(RC);
-
- return RC;
- } catch (IOException e) {
- throw new ClassNotFoundException(e.toString());
- }
- }
-
- public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
- return loadClass(clazz.getName());
- }
-
- /** Clear all entries from cache.
- */
- public void clear() {
- loadedClasses.clear();
- }
-
- /*
- * @return null
- */
- public ClassPath getClassPath() {
- return null;
- }
+ private java.lang.ClassLoader loader;
+ private Map loadedClasses = new HashMap(); // CLASSNAME X JAVACLASS
+
+
+ public ClassLoaderRepository(java.lang.ClassLoader loader) {
+ this.loader = loader;
+ }
+
+
+ /**
+ * Store a new JavaClass into this Repository.
+ */
+ public void storeClass( JavaClass clazz ) {
+ loadedClasses.put(clazz.getClassName(), clazz);
+ clazz.setRepository(this);
+ }
+
+
+ /**
+ * Remove class from repository
+ */
+ public void removeClass( JavaClass clazz ) {
+ loadedClasses.remove(clazz.getClassName());
+ }
+
+
+ /**
+ * Find an already defined JavaClass.
+ */
+ public JavaClass findClass( String className ) {
+ if (loadedClasses.containsKey(className)) {
+ return (JavaClass) loadedClasses.get(className);
+ } else {
+ return null;
+ }
+ }
+
+
+ /**
+ * Lookup a JavaClass object from the Class Name provided.
+ */
+ public JavaClass loadClass( String className ) throws ClassNotFoundException {
+ String classFile = className.replace('.', '/');
+ JavaClass RC = findClass(className);
+ if (RC != null) {
+ return RC;
+ }
+ try {
+ InputStream is = loader.getResourceAsStream(classFile + ".class");
+ if (is == null) {
+ throw new ClassNotFoundException(className + " not found.");
+ }
+ ClassParser parser = new ClassParser(is, className);
+ RC = parser.parse();
+ storeClass(RC);
+ return RC;
+ } catch (IOException e) {
+ throw new ClassNotFoundException(e.toString());
+ }
+ }
+
+
+ public JavaClass loadClass( Class clazz ) throws ClassNotFoundException {
+ return loadClass(clazz.getName());
+ }
+
+
+ /** Clear all entries from cache.
+ */
+ public void clear() {
+ loadedClasses.clear();
+ }
+
+
+ /*
+ * @return null
+ */
+ public ClassPath getClassPath() {
+ return null;
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: bcel-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: bcel-dev-help@jakarta.apache.org