Search in sources :

Example 16 with InstructionList

use of org.apache.bcel.generic.InstructionList in project core by s4.

the class OverloadDispatcherGenerator method generate.

public Class<Object> generate() {
    Random rand = new Random(System.currentTimeMillis());
    String dispatcherClassName = "OverloadDispatcher" + (Math.abs(rand.nextInt() % 3256));
    String interfaceName = "io.s4.processor.OverloadDispatcher";
    if (forSlot) {
        interfaceName = "io.s4.processor.OverloadDispatcherSlot";
    }
    ClassGen cg = new ClassGen(dispatcherClassName, "java.lang.Object", dispatcherClassName + ".java", Constants.ACC_PUBLIC | Constants.ACC_SUPER, new String[] { interfaceName });
    ConstantPoolGen cp = cg.getConstantPool();
    InstructionFactory instFactory = new InstructionFactory(cg, cp);
    InstructionList il = new InstructionList();
    // build constructor method for new class
    MethodGen constructor = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", dispatcherClassName, il, cp);
    il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
    il.append(instFactory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
    il.append(InstructionFactory.createReturn(Type.VOID));
    constructor.setMaxStack();
    constructor.setMaxLocals();
    cg.addMethod(constructor.getMethod());
    il.dispose();
    // build dispatch method
    il = new InstructionList();
    Type[] dispatchArgumentTypes = null;
    String[] dispatchArgumentNames = null;
    int postArgumentVariableSlot = 3;
    if (forSlot) {
        dispatchArgumentTypes = new Type[] { ObjectType.OBJECT, ObjectType.OBJECT, ObjectType.LONG, abstractWindowingPEType };
        dispatchArgumentNames = new String[] { "slot", "event", "slotTime", "pe" };
        postArgumentVariableSlot = 6;
    } else {
        dispatchArgumentTypes = new Type[] { ObjectType.OBJECT, ObjectType.OBJECT };
        dispatchArgumentNames = new String[] { "pe", "event" };
    }
    MethodGen method = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, dispatchArgumentTypes, dispatchArgumentNames, "dispatch", dispatcherClassName, il, cp);
    List<InstructionHandle> targetInstructions = new ArrayList<InstructionHandle>();
    List<BranchInstruction> branchInstructions = new ArrayList<BranchInstruction>();
    List<BranchInstruction> gotoInstructions = new ArrayList<BranchInstruction>();
    ObjectType peType = new ObjectType(targetClass.getName());
    il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
    il.append(instFactory.createCheckCast(peType));
    il.append(InstructionFactory.createStore(peType, postArgumentVariableSlot));
    for (int i = 0; i < hierarchies.size(); i++) {
        Hierarchy hierarchy = hierarchies.get(i);
        ObjectType hierarchyTop = new ObjectType(hierarchy.getTop().getName());
        InstructionHandle ih = il.append(InstructionFactory.createLoad(Type.OBJECT, 2));
        if (i > 0) {
            targetInstructions.add(ih);
        }
        il.append(new INSTANCEOF(cp.addClass(hierarchyTop)));
        BranchInstruction bi = InstructionFactory.createBranchInstruction(Constants.IFEQ, null);
        il.append(bi);
        branchInstructions.add(bi);
        il.append(InstructionFactory.createLoad(peType, postArgumentVariableSlot));
        il.append(InstructionFactory.createLoad(hierarchyTop, 2));
        il.append(instFactory.createCheckCast(hierarchyTop));
        if (forSlot) {
            il.append(InstructionFactory.createLoad(ObjectType.LONG, 3));
            il.append(InstructionFactory.createLoad(abstractWindowingPEType, 5));
        }
        Type[] argumentTypes = null;
        if (forSlot) {
            argumentTypes = new Type[] { hierarchyTop, ObjectType.LONG, abstractWindowingPEType };
        } else {
            argumentTypes = new Type[] { hierarchyTop };
        }
        il.append(instFactory.createInvoke(targetClass.getName(), "processEvent", Type.VOID, argumentTypes, Constants.INVOKEVIRTUAL));
        // no branch needed for last check
        if (i < (hierarchies.size() - 1)) {
            bi = InstructionFactory.createBranchInstruction(Constants.GOTO, null);
            il.append(bi);
            gotoInstructions.add(bi);
        }
    }
    InstructionHandle returnInstruction = il.append(InstructionFactory.createReturn(Type.VOID));
    for (int i = 0; i < targetInstructions.size(); i++) {
        branchInstructions.get(i).setTarget(targetInstructions.get(i));
    }
    branchInstructions.get(branchInstructions.size() - 1).setTarget(returnInstruction);
    for (BranchInstruction gotoInstruction : gotoInstructions) {
        gotoInstruction.setTarget(returnInstruction);
    }
    method.setMaxStack();
    method.setMaxLocals();
    cg.addMethod(method.getMethod());
    il.dispose();
    JavaClass jc = cg.getJavaClass();
    OverloadDispatcherClassLoader cl = new OverloadDispatcherClassLoader();
    // debug
    if (classDumpFile != null) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(classDumpFile);
            fos.write(jc.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null)
                try {
                    fos.close();
                } catch (Exception e) {
                }
        }
    }
    return cl.loadClassFromBytes(dispatcherClassName, jc.getBytes());
}
Also used : INSTANCEOF(org.apache.bcel.generic.INSTANCEOF) BranchInstruction(org.apache.bcel.generic.BranchInstruction) InstructionList(org.apache.bcel.generic.InstructionList) ClassGen(org.apache.bcel.generic.ClassGen) ArrayList(java.util.ArrayList) MethodGen(org.apache.bcel.generic.MethodGen) InstructionHandle(org.apache.bcel.generic.InstructionHandle) InstructionFactory(org.apache.bcel.generic.InstructionFactory) ConstantPoolGen(org.apache.bcel.generic.ConstantPoolGen) ObjectType(org.apache.bcel.generic.ObjectType) Type(org.apache.bcel.generic.Type) ObjectType(org.apache.bcel.generic.ObjectType) Random(java.util.Random) JavaClass(org.apache.bcel.classfile.JavaClass) FileOutputStream(java.io.FileOutputStream)

Example 17 with InstructionList

use of org.apache.bcel.generic.InstructionList in project core by s4.

the class ClonerGenerator method generate.

public Class generate(Class clazz) {
    String className = clazz.getName();
    Random rand = new Random(System.currentTimeMillis());
    String clonerClassname = "Cloner" + (Math.abs(rand.nextInt() % 3256));
    ClassGen cg = new ClassGen(clonerClassname, "java.lang.Object", clonerClassname + ".java", Constants.ACC_PUBLIC | Constants.ACC_SUPER, new String[] { "io.s4.util.Cloner" });
    ConstantPoolGen cp = cg.getConstantPool();
    InstructionFactory instFactory = new InstructionFactory(cg, cp);
    InstructionList il = new InstructionList();
    // build constructor method for new class
    MethodGen constructor = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", clonerClassname, il, cp);
    il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
    il.append(instFactory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
    il.append(InstructionFactory.createReturn(Type.VOID));
    constructor.setMaxStack();
    constructor.setMaxLocals();
    cg.addMethod(constructor.getMethod());
    il.dispose();
    // build clone method
    il = new InstructionList();
    MethodGen method = new MethodGen(Constants.ACC_PUBLIC, Type.OBJECT, new Type[] { Type.OBJECT }, new String[] { "arg0" }, "clone", clonerClassname, il, cp);
    il.append(InstructionConstants.ACONST_NULL);
    il.append(InstructionFactory.createStore(Type.OBJECT, 2));
    il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
    il.append(new INSTANCEOF(cp.addClass(new ObjectType(className))));
    BranchInstruction ifeq_6 = InstructionFactory.createBranchInstruction(Constants.IFEQ, null);
    il.append(ifeq_6);
    il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
    il.append(instFactory.createCheckCast(new ObjectType(className)));
    il.append(InstructionFactory.createStore(Type.OBJECT, 2));
    InstructionHandle ih_14 = il.append(InstructionFactory.createLoad(Type.OBJECT, 2));
    il.append(new INSTANCEOF(cp.addClass(new ObjectType("java.lang.Cloneable"))));
    BranchInstruction ifne_18 = InstructionFactory.createBranchInstruction(Constants.IFNE, null);
    il.append(ifne_18);
    il.append(instFactory.createFieldAccess("java.lang.System", "out", new ObjectType("java.io.PrintStream"), Constants.GETSTATIC));
    il.append(new PUSH(cp, "Not cloneable!"));
    il.append(instFactory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL));
    il.append(InstructionConstants.ACONST_NULL);
    il.append(InstructionFactory.createReturn(Type.OBJECT));
    InstructionHandle ih_31 = il.append(InstructionFactory.createLoad(Type.OBJECT, 2));
    il.append(instFactory.createInvoke(className, "clone", Type.OBJECT, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
    il.append(InstructionFactory.createReturn(Type.OBJECT));
    ifeq_6.setTarget(ih_14);
    ifne_18.setTarget(ih_31);
    method.setMaxStack();
    method.setMaxLocals();
    cg.addMethod(method.getMethod());
    il.dispose();
    JavaClass jc = cg.getJavaClass();
    ClonerClassLoader cl = new ClonerClassLoader();
    return cl.loadClassFromBytes(clonerClassname, jc.getBytes());
}
Also used : INSTANCEOF(org.apache.bcel.generic.INSTANCEOF) BranchInstruction(org.apache.bcel.generic.BranchInstruction) InstructionList(org.apache.bcel.generic.InstructionList) ClassGen(org.apache.bcel.generic.ClassGen) MethodGen(org.apache.bcel.generic.MethodGen) InstructionHandle(org.apache.bcel.generic.InstructionHandle) InstructionFactory(org.apache.bcel.generic.InstructionFactory) ConstantPoolGen(org.apache.bcel.generic.ConstantPoolGen) ObjectType(org.apache.bcel.generic.ObjectType) Type(org.apache.bcel.generic.Type) ObjectType(org.apache.bcel.generic.ObjectType) Random(java.util.Random) JavaClass(org.apache.bcel.classfile.JavaClass) PUSH(org.apache.bcel.generic.PUSH)

Example 18 with InstructionList

use of org.apache.bcel.generic.InstructionList in project candle-decompiler by bradsdavis.

the class ClassIntermediateVisitor method visitMethod.

@Override
public void visitMethod(Method obj) {
    MethodGen methodGenerator = new MethodGen(obj, this.javaClass.getClassName(), this.constantPool);
    LOG.debug("Processing MethodInvocation: " + methodGenerator.toString());
    IntermediateContext intermediateContext = new IntermediateContext(this.javaClass, methodGenerator);
    InstructionList instructions = methodGenerator.getInstructionList();
    instructions.setPositions(true);
    InstructionGraphFactory igf = new InstructionGraphFactory(instructions, methodGenerator.getExceptionHandlers());
    InstructionGraphContext igc = igf.process();
    List<InstructionGraphEnhancer> iges = new ArrayList<InstructionGraphEnhancer>();
    iges.add(new InstructionGraphWriter(igc, "before.dot"));
    iges.add(new SplitInstructionEnhancer(igc));
    iges.add(new ConditionEdgeEnhancer(igc));
    iges.add(new ExceptionEdgeEnhancer(igc, methodGenerator.getExceptionHandlers()));
    iges.add(new InstructionToIntermediateEnhancer(igc, intermediateContext));
    iges.add(new BackEdgeEnhancer(igc));
    iges.add(new LoopHeader(igc));
    iges.add(new ContinuousLoop(igc));
    iges.add(new NonIntermediateEliminator(igc));
    iges.add(new InstructionGraphWriter(igc, "after.dot"));
    for (InstructionGraphEnhancer ige : iges) {
        ige.process();
    }
    IntermediateGraphTransformer igt = new IntermediateGraphTransformer(igc);
    IntermediateGraphContext interGraphContext = igt.getIntermediateGraphContext();
    processIntermediate(interGraphContext);
    MethodBlock method = extractMethodSignature(methodGenerator);
    BlockVisitor iv = new BlockVisitor(interGraphContext, method);
    iv.process();
    classBlock.addChild(method);
    method.setParent(classBlock);
}
Also used : InstructionGraphEnhancer(org.candle.decompiler.instruction.graph.enhancer.InstructionGraphEnhancer) IntermediateGraphTransformer(org.candle.decompiler.intermediate.graph.IntermediateGraphTransformer) MethodBlock(org.candle.decompiler.ast.MethodBlock) BackEdgeEnhancer(org.candle.decompiler.instruction.graph.enhancer.BackEdgeEnhancer) InstructionGraphWriter(org.candle.decompiler.instruction.graph.enhancer.InstructionGraphWriter) InstructionList(org.apache.bcel.generic.InstructionList) ContinuousLoop(org.candle.decompiler.instruction.graph.enhancer.ContinuousLoop) ArrayList(java.util.ArrayList) MethodGen(org.apache.bcel.generic.MethodGen) SplitInstructionEnhancer(org.candle.decompiler.instruction.graph.enhancer.SplitInstructionEnhancer) InstructionToIntermediateEnhancer(org.candle.decompiler.instruction.graph.enhancer.InstructionToIntermediateEnhancer) InstructionGraphContext(org.candle.decompiler.instruction.graph.InstructionGraphContext) IntermediateGraphContext(org.candle.decompiler.intermediate.graph.context.IntermediateGraphContext) ConditionEdgeEnhancer(org.candle.decompiler.instruction.graph.enhancer.ConditionEdgeEnhancer) InstructionGraphFactory(org.candle.decompiler.instruction.graph.InstructionGraphFactory) NonIntermediateEliminator(org.candle.decompiler.instruction.graph.enhancer.NonIntermediateEliminator) ExceptionEdgeEnhancer(org.candle.decompiler.instruction.graph.enhancer.ExceptionEdgeEnhancer) LoopHeader(org.candle.decompiler.instruction.graph.enhancer.LoopHeader) BlockVisitor(org.candle.decompiler.ast.BlockVisitor)

Example 19 with InstructionList

use of org.apache.bcel.generic.InstructionList in project servicemix-bundles by apache.

the class FunctionCall method translateDesynthesized.

/**
 * Compile the function call and treat as an expression
 * Update true/false-lists.
 */
public void translateDesynthesized(ClassGenerator classGen, MethodGenerator methodGen) {
    Type type = Type.Boolean;
    if (_chosenMethodType != null)
        type = _chosenMethodType.resultType();
    final InstructionList il = methodGen.getInstructionList();
    translate(classGen, methodGen);
    if ((type instanceof BooleanType) || (type instanceof IntType)) {
        _falseList.add(il.append(new IFEQ(null)));
    }
}
Also used : BooleanType(org.apache.xalan.xsltc.compiler.util.BooleanType) Type(org.apache.xalan.xsltc.compiler.util.Type) ObjectType(org.apache.xalan.xsltc.compiler.util.ObjectType) IntType(org.apache.xalan.xsltc.compiler.util.IntType) MethodType(org.apache.xalan.xsltc.compiler.util.MethodType) ReferenceType(org.apache.xalan.xsltc.compiler.util.ReferenceType) InstructionList(org.apache.bcel.generic.InstructionList) BooleanType(org.apache.xalan.xsltc.compiler.util.BooleanType) IFEQ(org.apache.bcel.generic.IFEQ) IntType(org.apache.xalan.xsltc.compiler.util.IntType)

Example 20 with InstructionList

use of org.apache.bcel.generic.InstructionList in project servicemix-bundles by apache.

the class FunctionCall method translate.

/**
 * Translate a function call. The compiled code will leave the function's
 * return value on the JVM's stack.
 */
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
    final int n = argumentCount();
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = methodGen.getInstructionList();
    final boolean isSecureProcessing = classGen.getParser().getXSLTC().isSecureProcessing();
    int index;
    // Translate calls to methods in the BasisLibrary
    if (isStandard() || isExtension()) {
        for (int i = 0; i < n; i++) {
            final Expression exp = argument(i);
            exp.translate(classGen, methodGen);
            exp.startIterator(classGen, methodGen);
        }
        // append "F" to the function's name
        final String name = _fname.toString().replace('-', '_') + "F";
        String args = Constants.EMPTYSTRING;
        // Special precautions for some method calls
        if (name.equals("sumF")) {
            args = DOM_INTF_SIG;
            il.append(methodGen.loadDOM());
        } else if (name.equals("normalize_spaceF")) {
            if (_chosenMethodType.toSignature(args).equals("()Ljava/lang/String;")) {
                args = "I" + DOM_INTF_SIG;
                il.append(methodGen.loadContextNode());
                il.append(methodGen.loadDOM());
            }
        }
        // Invoke the method in the basis library
        index = cpg.addMethodref(BASIS_LIBRARY_CLASS, name, _chosenMethodType.toSignature(args));
        il.append(new INVOKESTATIC(index));
    } else // run-time error message for unsupported external functions
    if (unresolvedExternal) {
        index = cpg.addMethodref(BASIS_LIBRARY_CLASS, "unresolved_externalF", "(Ljava/lang/String;)V");
        il.append(new PUSH(cpg, _fname.toString()));
        il.append(new INVOKESTATIC(index));
    } else if (_isExtConstructor) {
        if (isSecureProcessing)
            translateUnallowedExtension(cpg, il);
        final String clazz = _chosenConstructor.getDeclaringClass().getName();
        Class[] paramTypes = _chosenConstructor.getParameterTypes();
        LocalVariableGen[] paramTemp = new LocalVariableGen[n];
        for (int i = 0; i < n; i++) {
            final Expression exp = argument(i);
            Type expType = exp.getType();
            exp.translate(classGen, methodGen);
            // Convert the argument to its Java type
            exp.startIterator(classGen, methodGen);
            expType.translateTo(classGen, methodGen, paramTypes[i]);
            paramTemp[i] = methodGen.addLocalVariable("function_call_tmp" + i, expType.toJCType(), null, null);
            paramTemp[i].setStart(il.append(expType.STORE(paramTemp[i].getIndex())));
        }
        il.append(new NEW(cpg.addClass(_className)));
        il.append(InstructionConstants.DUP);
        for (int i = 0; i < n; i++) {
            final Expression arg = argument(i);
            paramTemp[i].setEnd(il.append(arg.getType().LOAD(paramTemp[i].getIndex())));
        }
        final StringBuffer buffer = new StringBuffer();
        buffer.append('(');
        for (int i = 0; i < paramTypes.length; i++) {
            buffer.append(getSignature(paramTypes[i]));
        }
        buffer.append(')');
        buffer.append("V");
        index = cpg.addMethodref(clazz, "<init>", buffer.toString());
        il.append(new INVOKESPECIAL(index));
        // Convert the return type back to our internal type
        (Type.Object).translateFrom(classGen, methodGen, _chosenConstructor.getDeclaringClass());
    } else // Invoke function calls that are handled in separate classes
    {
        if (isSecureProcessing)
            translateUnallowedExtension(cpg, il);
        final String clazz = _chosenMethod.getDeclaringClass().getName();
        Class[] paramTypes = _chosenMethod.getParameterTypes();
        // Push "this" if it is an instance method
        if (_thisArgument != null) {
            _thisArgument.translate(classGen, methodGen);
        }
        for (int i = 0; i < n; i++) {
            final Expression exp = argument(i);
            exp.translate(classGen, methodGen);
            // Convert the argument to its Java type
            exp.startIterator(classGen, methodGen);
            exp.getType().translateTo(classGen, methodGen, paramTypes[i]);
        }
        final StringBuffer buffer = new StringBuffer();
        buffer.append('(');
        for (int i = 0; i < paramTypes.length; i++) {
            buffer.append(getSignature(paramTypes[i]));
        }
        buffer.append(')');
        buffer.append(getSignature(_chosenMethod.getReturnType()));
        if (_thisArgument != null && _clazz.isInterface()) {
            index = cpg.addInterfaceMethodref(clazz, _fname.getLocalPart(), buffer.toString());
            il.append(new INVOKEINTERFACE(index, n + 1));
        } else {
            index = cpg.addMethodref(clazz, _fname.getLocalPart(), buffer.toString());
            il.append(_thisArgument != null ? (InvokeInstruction) new INVOKEVIRTUAL(index) : (InvokeInstruction) new INVOKESTATIC(index));
        }
        // Convert the return type back to our internal type
        _type.translateFrom(classGen, methodGen, _chosenMethod.getReturnType());
    }
}
Also used : INVOKESTATIC(org.apache.bcel.generic.INVOKESTATIC) NEW(org.apache.bcel.generic.NEW) InstructionList(org.apache.bcel.generic.InstructionList) LocalVariableGen(org.apache.bcel.generic.LocalVariableGen) INVOKESPECIAL(org.apache.bcel.generic.INVOKESPECIAL) ConstantPoolGen(org.apache.bcel.generic.ConstantPoolGen) InvokeInstruction(org.apache.bcel.generic.InvokeInstruction) BooleanType(org.apache.xalan.xsltc.compiler.util.BooleanType) Type(org.apache.xalan.xsltc.compiler.util.Type) ObjectType(org.apache.xalan.xsltc.compiler.util.ObjectType) IntType(org.apache.xalan.xsltc.compiler.util.IntType) MethodType(org.apache.xalan.xsltc.compiler.util.MethodType) ReferenceType(org.apache.xalan.xsltc.compiler.util.ReferenceType) INVOKEINTERFACE(org.apache.bcel.generic.INVOKEINTERFACE) INVOKEVIRTUAL(org.apache.bcel.generic.INVOKEVIRTUAL) PUSH(org.apache.bcel.generic.PUSH)

Aggregations

InstructionList (org.apache.bcel.generic.InstructionList)37 InstructionHandle (org.apache.bcel.generic.InstructionHandle)27 Iterator (java.util.Iterator)9 MethodGen (org.apache.bcel.generic.MethodGen)8 Instruction (org.apache.bcel.generic.Instruction)7 InvokeInstruction (org.apache.bcel.generic.InvokeInstruction)7 Type (org.apache.bcel.generic.Type)7 InstructionFinder (org.apache.bcel.util.InstructionFinder)7 MethodCode (com.jopdesign.common.MethodCode)6 CPInstruction (org.apache.bcel.generic.CPInstruction)6 ConstantPoolGen (org.apache.bcel.generic.ConstantPoolGen)6 FieldInstruction (org.apache.bcel.generic.FieldInstruction)6 MethodInfo (com.jopdesign.common.MethodInfo)5 NOP (org.apache.bcel.generic.NOP)5 BranchInstruction (org.apache.bcel.generic.BranchInstruction)4 ReturnInstruction (org.apache.bcel.generic.ReturnInstruction)4 ClassInfo (com.jopdesign.common.ClassInfo)3 InvokeSite (com.jopdesign.common.code.InvokeSite)3 Constant (org.apache.bcel.classfile.Constant)3 JavaClass (org.apache.bcel.classfile.JavaClass)3