Example usage for org.aspectj.apache.bcel.generic ClassGen getMethods

List of usage examples for org.aspectj.apache.bcel.generic ClassGen getMethods

Introduction

In this page you can find the example usage for org.aspectj.apache.bcel.generic ClassGen getMethods.

Prototype

public Method[] getMethods() 

Source Link

Usage

From source file:br.jabuti.instrumenter.bytecode.bcel.ASMInstrumenter.java

License:Open Source License

/**
 * This is a test driver. It takes a class name on args[0], inserts
 * some instructions in several points of each method in the class
 * and then dump the instrumented class to "new_"<original_name> 
 * file// w  w w.ja v  a2s. co m
 */

public static void main(String args[]) throws Exception {
    // o melhor eh chamar com java ... ASMInstrumenter samples\arquivo.class
    // assim ele vai criar um novo arquivo new_samples\arquivo.class que
    // se pode testar

    JavaClass java_class;

    if ((java_class = Repository.lookupClass(args[0])) == null) {
        java_class = new ClassParser(args[0]).parse();
    } // May throw IOException

    ClassGen cg = new ClassGen(java_class);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] methods = cg.getMethods();

    for (int i = 0; i < methods.length; i++) {
        try {
            System.out.println("\n\n--------------------------");
            System.out.println(methods[i].getName());
            System.out.println("--------------------------");
            MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cp);
            ASMInstrumenter gi = new ASMInstrumenter(mg, cg, cp);
            int nvars = mg.getMaxLocals() + 10;

            String s = "GETSTATIC java.lang.System out \"Ljava/io/PrintStream;\"  " + "astore " + nvars + " ";
            String s2 = "aload " + nvars + " ";
            String s3 = "LDC \"Entrando no metodo " + mg.getName() + "\" ";
            String s4 = "LDC \"Saindo do metodo " + mg.getName() + "\\n \" ";
            String s5 = "invokevirtual java.io.PrintStream println " + "\"(Ljava/lang/Object;)V\" ";

            gi.insertBefore(mg.getInstructionList().getStart(), s + s2 + s3 + s5);
            gi.insertBefore(mg.getInstructionList().getEnd(), s2 + s4 + s5);
            methods[i] = mg.getMethod();
        } catch (ParseException e) {
            System.err.println("Parser error " + e.getMessage());
        }
    }
    cg.setMethods(methods);
    java_class = cg.getJavaClass();
    java_class.dump("new_" + args[0]);
}

From source file:br.jabuti.probe.desktop.DefaultProbeInsert.java

License:Open Source License

private JavaClass doDefaultInstrument(JavaClass java_class, String className)
        throws InvalidInstructionException, InvalidStackArgument {

    ClassGen cg = new ClassGen(java_class);
    ConstantPoolGen cp = cg.getConstantPool();

    Method[] methods = cg.getMethods();

    // System.out.println( "Instrumenting class: " + className +
    // " cfg option: " + typeOfCFG );

    for (int i = 0; i < methods.length; i++) {
        try {/*  ww w . j  a v  a2  s.c  om*/
            MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cp);

            // System.out.println( "\tCurrent method: " + mg.getName() );

            // does not instrument static initializations or abstract methods
            if ((methods[i].getName().equals("<clinit>")) || (methods[i].isAbstract())) {
                continue;
            }

            InstructionList il = mg.getInstructionList();
            InstructionHandle[] ihVec = il.getInstructionHandles();
            int[] ihOffset = il.getInstructionPositions();

            ASMInstrumenter gi = new ASMInstrumenter(mg, cg, cp);

            int nextLocal = mg.getMaxLocals() + 1;
            CFG gfc = new CFG(mg, cg);

            // gfc.releaseInstructionGraph(); // free some memory

            HashSet jahFoi = new HashSet(); // controla quas nos jah foram instrumentados

            // insert probes at the end of each node in a constructor
            if (methods[i].getName().equals("<init>")) {
                CFGNode superNode = null;

                // acha a chamada ao super
                for (int m = 0; m < gfc.size(); m++) {
                    CFGNode ey = (CFGNode) gfc.elementAt(m);

                    if (ey instanceof CFGSuperNode) {
                        superNode = ey;
                        break;
                    }
                }

                // acha os nos que veem antes da chamada ao super
                // System.out.println( "Instrumentando classe: " + cg.getClassName() );
                // System.out.println( gfc );
                gfc.findIDFT(false, superNode);
                InstructionHandle ih = InstructionList.findHandle(ihVec, ihOffset, ihOffset.length,
                        superNode.getEnd());

                gi.insertAfter(ih, "aload_0 " + // empilha o objeto
                        " ldc \"" + className + "\"" + // empilha o nome da classe
                        " ldc " + i + // empilha o numero do metodo
                        " lconst_0 " + // empilha aninhamento que para construtor
                                       // eh sempre 0
                        " ldc " + // empilha o numero do no
                        "\"" + superNode.getNumber() + "\" " + "invokestatic " + getProbeClass()
                        + " probe \"(Ljava/lang/Object;" + "Ljava/lang/String;IJLjava/lang/Object;)V\"");

                jahFoi.add(ih);

                // coloca a instrumentacao em cada no
                for (int m = 0; m < gfc.size(); m++) {
                    CFGNode ey = (CFGNode) gfc.elementAt(m);

                    // if marked means it is befor the super
                    if (ey.getMark()) {
                        continue;
                    }

                    ih = InstructionList.findHandle(ihVec, ihOffset, ihOffset.length, ey.getStart());
                    // System.out.println("No: " + ey);
                    // System.out.println("Inicio do noh: " + ih);
                    // System.out.println("Inicio do noh: " + ey.getStart());
                    if (!jahFoi.contains(ih)) {
                        jahFoi.add(ih);
                        gi.insertBefore(ih, "aload_0 " + // empilha o objeto
                                " ldc \"" + className + "\"" + // empilha o nome da classe
                                " ldc " + i + // empilha o numero do metodo
                                " lconst_0 " + // empilha aninhamento que para construtor
                                               // eh sempre 0
                                " ldc " + // empilha o numero do no
                                "\"" + ey.getNumber() + "\" " + "invokestatic " + getProbeClass()
                                + " probe \"(Ljava/lang/Object;"
                                + "Ljava/lang/String;IJLjava/lang/Object;)V\"");
                    }
                }
            } else { // in this case the method is an ordinary method
                String probStat = null, method = null;

                if (mg.isStatic()) {
                    probStat = "";
                    method = "";
                } else {
                    probStat = "aload_0";
                    method = "Ljava/lang/Object;";
                }
                for (int m = 0; m < gfc.size(); m++) {
                    CFGNode gn = (CFGNode) gfc.elementAt(m);

                    InstructionHandle ih = InstructionList.findHandle(ihVec, ihOffset, ihOffset.length,
                            gn.getStart());

                    if (gfc.isEntryNode(gn)) {
                        String s = "invokestatic " + getProbeClass() + " getNest \"()J\"" + " lstore "
                                + nextLocal;
                        gi.addBefore(ih, s);
                    }

                    String s = probStat + " ldc \"" + className + "\"" + // empilha o nome da classe
                            " ldc " + i + // empilha o numero do metodo
                            " lload " + nextLocal + // empilha nivel de aninhamento
                            " ldc " + // empilha o numero do no
                            "\"" + gn.getNumber() + "\" " + "invokestatic " + getProbeClass() + " probe \"("
                            + method + "Ljava/lang/String;IJLjava/lang/Object;)V\"";

                    if (!jahFoi.contains(ih)) {
                        jahFoi.add(ih);
                        gi.insertBefore(ih, s);
                    }
                }
                int stackSize = mg.getMaxStack();
                // Tentativa de contornar os erros do BCEL que n<E3>o altera corretamente o
                // tamanho da pilha
                if (stackSize < 6) {
                    mg.setMaxStack(stackSize + 6);
                }
            }
            methods[i] = mg.getMethod();
        } catch (ParseException e) {
            System.out.println(className);
            System.err.println("Parser error " + e.getMessage());
        }
    }
    int newIndex = cp.addUtf8(JABUTI_DEFAULT_INSTR_ATTRIBUTE);
    Attribute atr = new Unknown(newIndex, JABUTI_DEFAULT_INSTR_ATTRIBUTE.length(),
            JABUTI_DEFAULT_INSTR_ATTRIBUTE.getBytes(), cp.getConstantPool());
    cg.setConstantPool(cp);
    cg.addAttribute(atr);
    cg.setMethods(methods);
    return (cg.getJavaClass());
}

From source file:br.jabuti.probe.desktop.DefaultProbeInsert.java

License:Open Source License

/**
 * This method wraps a given method code between two pieces of code: one to be executed before
 * the method and other after, as a finaly clause. The instrumentation will use the next 2 free
 * local variable, so the code to be inserted should not use them.
 * //  w ww.j a v a 2s.  co  m
 * @param jv - The JavaClass where to find the method
 * @param name - the method name
 * @param sig - method signature
 * @param cfg - the control flow graph of the method
 * @param before - the code to be inserted before the method code
 * @param after - the code to be inserted after the method
 */
static public JavaClass wrapMethod(JavaClass jv, String name, String sig,
        // CFG cfg,
        String before, String after) {
    ClassGen cg = new ClassGen(jv);
    ConstantPoolGen cp = cg.getConstantPool();

    Method[] methods = cg.getMethods();
    int i;
    for (i = 0; i < methods.length; i++) {
        String n = methods[i].getName();
        String s = methods[i].getSignature();
        if (s.equals(sig) && n.equals(name))
            break;
    }
    if (i >= methods.length)
        return jv;
    MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cp);
    try {
        int nextLocal = mg.getMaxLocals();
        ASMInstrumenter gi = new ASMInstrumenter(mg, cg, cp);

        InstructionList iList = mg.getInstructionList();

        // pega instrucao inicial
        InstructionHandle first = iList.getStart();
        // System.out.println("First: " + first);
        // System.out.println(iList);
        gi.insertBefore(first, " NOP " + (before == null ? "" : before));
        // System.out.println(iList);

        // iList = mg.getInstructionList();
        InstructionHandle preambulo = iList.getStart();
        // System.out.println("Preambulo: " + preambulo);

        // ultima instrucao do metodo
        InstructionHandle last = iList.getEnd();
        // System.out.println("Last: " + last);

        // comeca a inserir o tratador de instrucoes
        gi.insertAfter(last, " astore " + (nextLocal + 1));
        // iList = mg.getInstructionList();
        InstructionHandle catcher = iList.getEnd();
        gi.insertAfter(catcher, " jsr l1 aload " + (nextLocal + 1) + " athrow " + " l1: NOP ");

        // System.out.println("catcher: " + catcher);

        // comeca a inserir o codigo do finally
        // iList = mg.getInstructionList();
        InstructionHandle subroutine = iList.getEnd();
        // System.out.println("subroutine: " + subroutine);

        String finali = " astore " + nextLocal;
        finali += after;
        finali += " ret " + nextLocal;
        gi.insertAfter(subroutine, finali);

        // iList = mg.getInstructionList();

        InstructionHandle nx = first, curr;
        mg.getMethod();

        // para cada return no codigo faz uma chamada aa subrotina
        do {
            curr = nx;
            BranchInstruction jsr = new JSR(subroutine);
            Instruction ins = curr.getInstruction();
            if (ins instanceof ReturnInstruction) {
                gi.insertBefore(curr, jsr);
            }
            nx = curr.getNext();
        } while (curr != last);

        // e finalmente, coloca o tratador de excees para todo
        // o cdigo orignal
        iList = mg.getInstructionList();
        mg.addExceptionHandler(preambulo, last, catcher, (ObjectType) null);
    } catch (ParseException e) {
        System.err.println("Parser error " + e.getMessage());
    }

    mg.setMaxStack();
    mg.setMaxLocals();
    methods[i] = mg.getMethod();
    cg.setMethods(methods);
    return (cg.getJavaClass());
}

From source file:br.jabuti.probe.mobiledevice.HostProbeInsert.java

License:Open Source License

protected JavaClass xdoMethodInstrument(JavaClass java_class)
        throws InvalidInstructionException, InvalidStackArgument {

    ClassGen cg = new ClassGen(java_class);
    ConstantPoolGen cp = cg.getConstantPool();

    Method[] methods = cg.getMethods();

    for (int i = 0; i < methods.length; i++) {
        // only instrument the run() method
        if (!methods[i].getName().equals("run") || !methods[i].getSignature().equals("()V")) {
            continue;
        }//from  ww  w.j  a v  a 2 s.  c  o  m

        MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cp);
        mg.setName(MuAgent.runName);

        methods[i] = mg.getMethod();
    }
    cg.setMethods(methods);
    return (cg.getJavaClass());
}

From source file:br.jabuti.probe.mobiledevice.HostProberInstrum.java

License:Open Source License

/**
 *  Instrumenta a classe base, methodo Main
 *//*from  ww w.j a  v  a 2  s.  co m*/
public static JavaClass instrumentMain(JavaClass jv, String hostName, String projName, int delay)
        throws Exception {
    ClassGen cg = new ClassGen(jv);
    ConstantPoolGen cp = cg.getConstantPool();

    Method[] methods = cg.getMethods();
    int i = 0;
    for (i = 0; i < methods.length; i++)
        if (methods[i].getName().equals("main") && methods[i].getSignature().equals("([Ljava/lang/String;)V")) {
            break;
        }
    if (i >= methods.length) {
        System.out.println("Method static public main(String[]) not found");
        System.exit(0);
    }

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

    InstructionList il = mg.getInstructionList();
    InstructionHandle last = il.getStart();
    //      InstructionHandle pen = last.getPrev(); 
    //      il.delete(il.getStart(), pen);
    ASMInstrumenter gi = new ASMInstrumenter(mg, cg, cp);
    gi.insertBefore(last, " ldc \"" + hostName + "\"" + // empilha o endereco do servidor de teste
            " ldc \"" + projName + "\"" + // empilha o nome projeto
            " ldc " + delay + // empilha o tempo de espera
            "aconst_null " + "invokestatic br.jabuti.probe.mobiledevice.mobile.HostProber"
            + " init \"(Ljava/lang/String;Ljava/lang/String;ILmucode/MuServer;)V\"");
    methods[i] = mg.getMethod();
    cg.setConstantPool(cp);
    cg.setMethods(methods);
    return (cg.getJavaClass());

}

From source file:br.jabuti.ui.cli.ClassSummary.java

License:Open Source License

/**
 * Capturar e imprimir as informaes sobre definies e usuos de variveis. Gerar o CFG por
 * metodo de cada uma das classes.//from w w w.jav  a2s  .c o  m
 */

private static void getClassSummary(JavaClass java_class) {
    ClassGen cg = new ClassGen(java_class);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] methods = cg.getMethods();

    System.out.println("Class File: " + cg.getClassName());

    for (int i = 0; i < methods.length; i++) {
        try {
            MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cp);

            CFG g;
            g = new CFG(mg, cg);

            // For collecting data w.r.t Dominators, Inverse Dominator and Live Variables
            if (detailed) {
                // g.computeDefUse();
                RRDominator rrd = new RRDominator("Dominator");

                g.roundRobinAlgorithm(rrd, true);

                rrd = new RRDominator("IDominator");
                g.roundIRobinAlgorithm(rrd, true);

                RRLiveDefs rral = new RRLiveDefs("Alive definitions", RRLiveDefs.ALL);

                g.roundRobinAlgorithm(rral, true);
            }

            // Gerarating the CFG file (dot format)
            if (cfg) {
                createCFGDotFile(g, cg.getClassName(), methods[i].getName());
                createAllTreeDotFiles(g, cg.getClassName(), methods[i].getName());
            }

            System.out.println("\t\tNumber of Blocks: " + g.size());
            if (detailed) {
                System.out.println("\t\t\tBlock Details");
            }

            int decisions = 0;
            Vector decisionBlocks = new Vector(5, 5);
            CFGNode pred;

            for (int j = 0; j < g.size(); j++) {
                pred = (CFGNode) g.elementAt(j);
                if (detailed) {
                    System.out.println(
                            "\t\t\t\t" + pred.getLabel() + " PC: " + pred.getStart() + " to " + pred.getEnd());

                    // Variable Definitions and Usages
                    // Usages...
                    if (defuse) {
                        getUsages(pred);

                        // Definitions
                        getDefinitions(pred);
                    }

                    // Children
                    if (childrens) {
                        // Primary children
                        getPrimChildren(pred);

                        // Secondary children (Exceptions)
                        getSecChildren(pred);
                    }

                    if (dominators) {
                        // Dominators of a given node
                        getDominators(pred);

                        // Inverse Dominators
                        getInverseDominators(pred);
                    }

                    // Set of live definitions
                    if (alive) {
                        getAliveDefinitions(pred);
                    }
                }
                if (pred.getPrimNext().size() > 1) {
                    decisions++;
                    decisionBlocks.add(pred);
                }
            }
            System.out.println("\t\tNumber of Decisions: " + decisions);
            if (detailed) {
                System.out.println("\t\t\tDecision Details");
                while (!(decisionBlocks.isEmpty())) {
                    pred = (CFGNode) decisionBlocks.firstElement();
                    System.out.println("\t\t\t\t" + pred.getLabel() + " Start: " + pred.getStart() + " End: "
                            + pred.getEnd());
                    decisionBlocks.remove(pred);
                }
            }
        } catch (InvalidInstructionException ii) {
            ToolConstants.reportException(ii, ToolConstants.STDERR);
        } catch (InvalidStackArgument ia) {
            ToolConstants.reportException(ia, ToolConstants.STDERR);
        }

    }

}

From source file:org.caesarj.mixer.intern.ClassModifyingVisitor.java

License:Open Source License

/**
 * Remove all methods from <code>clazz</code> whose names start
 * with '$new'.//w ww .  j a v a2 s. com
 * @param clazz   The class to modify   
 * @return   The class with removed methods
 */
protected JavaClass removeFactoryMethods(JavaClass clazz) {
    ClassGen gen = new ClassGen(clazz);

    Method[] methods = gen.getMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method.getName().startsWith(CaesarConstants.FACTORY_METHOD_PREFIX)) {
            gen.removeMethod(method);
        }
    }

    return gen.getJavaClass();
}