Package org.apache.bcel.generic

Examples of org.apache.bcel.generic.ClassGen


     * @param context the transformation context
     * @param klass the class set.
     */
    public void transformCode(final Context context, final Klass klass) {

        final ClassGen cg = klass.getClassGen();
        ClassMetaData classMetaData =
                BcelMetaDataMaker.createClassMetaData(context.getJavaClass(cg));

        if (classFilter(classMetaData, cg)) {
            return;
        }

        final InstructionFactory factory = new InstructionFactory(cg);
        final ConstantPoolGen cpg = cg.getConstantPool();
        final Method[] methods = cg.getMethods();

        // get the indexes for the <init> methods
        List initIndexes = new ArrayList();
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals("<init>")) {
                initIndexes.add(new Integer(i));
            }
        }

        // build and sort the method lookup list
        final List methodLookupList = new ArrayList();
        for (int i = 0; i < methods.length; i++) {
            if (methodFilter(classMetaData, methods[i]) == null) {
                continue;
            }
            methodLookupList.add(methods[i]);
        }

        Collections.sort(methodLookupList, BCELMethodComparator.getInstance());

        final Map methodSequences = new HashMap();
        final List proxyMethods = new ArrayList();
        for (int i = 0; i < methods.length; i++) {

            // filter the methods
            String uuid = methodFilter(classMetaData, methods[i]);
            if (methods[i].isStatic() || uuid == null) {
                continue;
            }

            final MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cpg);

            // take care of identification of overloaded methods by inserting a sequence number
            if (methodSequences.containsKey(methods[i].getName())) {
                int sequence = ((Integer)methodSequences.get(methods[i].getName())).intValue();
                methodSequences.remove(methods[i].getName());
                sequence++;
                methodSequences.put(methods[i].getName(), new Integer(sequence));
            }
            else {
                methodSequences.put(methods[i].getName(), new Integer(1));
            }

            final int methodLookupId = methodLookupList.indexOf(methods[i]);
            final int methodSequence = ((Integer)methodSequences.
                    get(methods[i].getName())).intValue();

            handleCallToOverriddenSuperClassMethod(mg, cg, cpg, factory, methodSequence, context);

            // check if the pointcut should be deployed as thread safe or not

            addJoinPointField(cpg, cg, mg, methodSequence);

            // get the join point controller
            MethodMetaData methodMetaData = BcelMetaDataMaker.createMethodMetaData(methods[i]);

            final String controllerClassName =
                    m_definition.getJoinPointController(classMetaData, methodMetaData);

            // advise all the constructors
            for (Iterator it = initIndexes.iterator(); it.hasNext();) {
                final int initIndex = ((Integer)it.next()).intValue();

                methods[initIndex] = createJoinPointField(
                        cpg, cg,
                        methods[initIndex],
                        methods[i],
                        factory,
                        methodSequence
                ).getMethod();
            }

            proxyMethods.add(createProxyMethod(
                    cpg, cg, mg,
                    factory,
                    methodLookupId,
                    methodSequence,
                    methods[i].getAccessFlags(),
                    uuid,
                    controllerClassName
            ));

            methods[i] = addPrefixToMethod(mg, methods[i], methodSequence);

            mg.setMaxStack();
        }

        // update the old methods
        cg.setMethods(methods);

        // add the proxy methods
        for (Iterator it = proxyMethods.iterator(); it.hasNext();) {
            Method method = (Method)it.next();
            cg.addMethod(method);
        }
    }
View Full Code Here


        Class generatedClass;
        synchronized ( Type.class )
        {
            // Create BCEL class generator
            m_classGenerator =
                new ClassGen(
                    wrapperClassName,
                    WRAPPER_SUPERCLASS_NAME,
                    null,
                    Constants.ACC_FINAL
                |Constants.ACC_PUBLIC
View Full Code Here

        return c;
    }

    private byte[] transform(JavaClass javaclazz) throws ClassNotFoundException {
        // make all methods of java class continuable
        ClassGen clazz = new ClassGen(javaclazz);
        ConstantPoolGen cp = clazz.getConstantPool();
        // obsolete, but neccesary to execute the InvokeContext
        InstConstraintVisitor icv = new InstConstraintVisitor();
        icv.setConstantPoolGen(cp);
        // vistor to build the frame information
        ExecutionVisitor ev = new ExecutionVisitor();
        ev.setConstantPoolGen(cp);

        Method[] methods = clazz.getMethods();
        for (int i = 0; i < methods.length; i++) {
            MethodGen method = new MethodGen(methods[i], clazz.getClassName(), cp);

            currentMethodStatic = methods[i].isStatic();
            if (isValid(method)) {
                // analyse the code of the method to create the frame
                // information about every instruction
                ControlFlowGraph cfg = new ControlFlowGraph(method);
                analyse(clazz, method, cfg, icv, ev);
                // add intercepting code
                rewrite(method, cfg);
                // make last optional check for consistency
                clazz.replaceMethod(methods[i], method.getMethod());
            }
        }
        clazz.addInterface(CONTINUATIONCAPABLE_CLASS);
        return clazz.getJavaClass().getBytes();
    }
View Full Code Here

        return c;
    }

    private byte[] transform(JavaClass javaclazz) throws ClassNotFoundException {
        // make all methods of java class continuable
        ClassGen clazz = new ClassGen(javaclazz);
        ConstantPoolGen cp = clazz.getConstantPool();
        // obsolete, but neccesary to execute the InvokeContext
        InstConstraintVisitor icv = new InstConstraintVisitor();
        icv.setConstantPoolGen(cp);
        // vistor to build the frame information
        ExecutionVisitor ev = new ExecutionVisitor();
        ev.setConstantPoolGen(cp);

        Method[] methods = clazz.getMethods();
        for (int i = 0; i < methods.length; i++) {
            MethodGen method = new MethodGen(methods[i], clazz.getClassName(), cp);

            currentMethodStatic = methods[i].isStatic();
            if (isValid(method)) {
                // analyse the code of the method to create the frame
                // information about every instruction
                ControlFlowGraph cfg = new ControlFlowGraph(method);
                analyse(clazz, method, cfg, icv, ev);
                // add intercepting code
                rewrite(method, cfg);
                // make last optional check for consistency
                clazz.replaceMethod(methods[i], method.getMethod());
            }
        }
        clazz.addInterface(CONTINUATIONCAPABLE_CLASS);
        return clazz.getJavaClass().getBytes();
    }
View Full Code Here

         else if (!superclass.isAssignableFrom(targetType)) {
            throw new RuntimeException("unexpected: " + targetType);
         }
      }

      ClassGen cg = new ClassGen(proxyClassName,
                                 superClassName,
                                 "<generated>",
                                 Constants.ACC_PUBLIC | Constants.ACC_FINAL,
         interfaceNames);
     
      ProxyImplementationFactory factory =
         new ProxyImplementationFactory(superClassName, proxyClassName, cg);

      cg.addField(factory.createInvocationHandlerField());
      cg.addField(factory.createRuntimeField());
      cg.addMethod(factory.createConstructor());
     
      // ProxyTarget implementation

      cg.addMethod(factory.createGetInvocationHandler());
      cg.addMethod(factory.createGetTargetTypes());
          
      boolean haveToString = false;

      if (trace) log.trace("Creating proxy methods...");

      // Implement the methods of the target types.
      for (int i = 0; i < methods.length; i++)
      {
         Method m = methods[i];
         if (trace) log.trace("Reflected method: " + m);

         String name = m.getName();
         Class rTypeClass = m.getReturnType();
         String rTypeName = rTypeClass.getName();
         Type rType = Utility.getType(rTypeClass);
         Type[] pTypes = Utility.getTypes(m.getParameterTypes());
         String[] exceptionNames = getNames(m.getExceptionTypes());

         if (name.equals("toString") && pTypes.length == 0) {
            haveToString = true;
         }

         org.apache.bcel.classfile.Method proxyMethod =
            factory.createProxyMethod(name, i, rType, pTypes, exceptionNames);

         if (trace) log.trace("Created proxy method: " + proxyMethod);

         cg.addMethod(proxyMethod);
      }

      if (!haveToString) {
         cg.addMethod(factory.createToString());
      }

      JavaClass jclass = cg.getJavaClass();
      if (trace) log.trace("Generated Java class: " + jclass);

      // dump the class if we have been configured todo so
      if (CLASS_DUMP_PATH != null) {
         try {
View Full Code Here

        String interfaceName = "org.apache.s4.processor.OverloadDispatcher";
        if (forSlot) {
            interfaceName = "org.apache.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;
View Full Code Here

    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[] { "org.apache.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());
    }
View Full Code Here

            }
            ClassParser classParser = new ClassParser(classAsStream, className);
            m_javaClass = classParser.parse();

            m_constantPoolGen = new ConstantPoolGen(m_javaClass.getConstantPool());
            m_classGen = new ClassGen(m_javaClass);
        }
        catch (Exception e) {
            throw new WrappedRuntimeException(e);
        }
        return true;
View Full Code Here

        try {
            log(klass);

            // build the ClassGen
            ClassParser parser = new ClassParser(new ByteArrayInputStream(abyte), "<generated>");//@todo is this needed _"+klass+">");
            ClassGen cg = new ClassGen(parser.parse());

            // instrument
            if (!cg.isInterface() && !Arrays.asList(cg.getInterfaceNames()).contains("java.util.EventListener")) {
                cg.addInterface("java.util.EventListener");
            }

            try {
                cg.getJavaClass().dump("_dump/" + klass.replace('.', '/') + ".class");
            }
            catch (Exception e) {
                System.err.println("failed to dump " + klass);
                e.printStackTrace();
            }


            return cg.getJavaClass().getBytes();
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
View Full Code Here

        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;
View Full Code Here

TOP

Related Classes of org.apache.bcel.generic.ClassGen

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.