Example usage for org.aspectj.apache.bcel.generic InstructionHandle getNext

List of usage examples for org.aspectj.apache.bcel.generic InstructionHandle getNext

Introduction

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

Prototype

public final InstructionHandle getNext() 

Source Link

Usage

From source file:br.jabuti.graph.datastructure.ig.InstructionGraph.java

License:Open Source License

/** <P>Constructor that creates a graph from a method code<br></p>
        /*from   ww w .j ava 2s .  c om*/
 @param mg The method for wich the graph will be created
 */
public InstructionGraph(MethodGen mg) {
    meth = mg;
    il = mg.getInstructionList();
    if (il == null) {
        return;
    } // no code (abstract or native method)

    // cria os nos do grafo e
    // coloca uma instrucao em cada no do grafo

    Hashtable verify = new Hashtable(); // serve para achar o no do grafo
    // dada uma certa instrucao.
    InstructionHandle ih = null;

    for (ih = il.getStart(); ih != null; ih = ih.getNext()) {
        InstructionNode in = new InstructionNode(ih);

        add(in);
        verify.put(ih, in);
    }

    HashMap jumpsAndEntries = new HashMap();
    CodeExceptionGen[] ceg = meth.getExceptionHandlers();

    // acerta os edges principais e secundarios de cada no
    for (int i = 0; i < size(); i++) {
        // include edges from each node to its exception handlers
        InstructionNode vf = (InstructionNode) elementAt(i);

        for (int j = 0; j < ceg.length; j++) {
            int init, fim;

            init = ceg[j].getStartPC().getPosition();
            fim = ceg[j].getEndPC().getPosition();
            if (vf.ih.getPosition() >= init && vf.ih.getPosition() <= fim) {
                addSecondaryEdge(vf, (InstructionNode) verify.get(ceg[j].getHandlerPC()));
            }
        }

        // depois acerta os edges principais.
        InstructionHandle[] nx = InstructCtrl.nextToExec(vf.ih);

        if (vf.ih.getInstruction() instanceof JsrInstruction) {
            // Coloca o proximo fisico como proximo no grafo
            InstructionHandle nih = (InstructionHandle) vf.ih.getNext();

            addPrimaryEdge(vf, (GraphNode) verify.get(nih));
            // mapeamento JSR -- Entrada
            jumpsAndEntries.put(vf.ih, nx[0]);
        } else {
            for (int j = 0; j < nx.length; j++) {
                addPrimaryEdge(vf, (GraphNode) verify.get(nx[j]));
            }
        }
    }

    int lastsize = 0, cursize = 0;
    int cont;
    Vector ventry = new Vector();

    ventry.add(verify.get(il.getStart()));
    Hashtable entriesDom = new Hashtable();

    // aqui calcula os nos dominados por cada entrada;
    do {
        cont = 0;
        lastsize = cursize;
        cursize = ventry.size();
        for (int i = lastsize; i < cursize; i++) {
            InstructionNode entr = (InstructionNode) ventry.elementAt(i);

            setEntryNode(entr);
            // Calcula os dominators
            RRDominator rrd = new RRDominator("Dominator");

            roundRobinAlgorithm(rrd, true);
            HashSet edm = new HashSet();

            entriesDom.put(entr, edm);
            for (int j = 0; j < size(); j++) {
                InstructionNode in = (InstructionNode) elementAt(j);
                HashSet dom = (HashSet) in.getUserData("Dominator");

                if (dom != null && dom.contains(entr)) {
                    edm.add(in);
                    if (in.ih.getInstruction() instanceof JsrInstruction) {
                        ventry.add(verify.get(jumpsAndEntries.get(in.ih)));
                        cont++;
                    }
                }
            }
        }

    } while (cont > 0);

    InstructionNode[] entries = (InstructionNode[]) ventry.toArray(new InstructionNode[0]);

    Vector aux = new Vector();

    aux.addAll((HashSet) entriesDom.get(entries[0]));
    lastsize = 0;
    cursize = 0;

    do {
        cont = 0;
        lastsize = cursize;
        cursize = aux.size();

        for (int i = lastsize; i < cursize; i++) {
            InstructionNode isJmp = (InstructionNode) aux.elementAt(i);

            if (!(isJmp.ih.getInstruction() instanceof JsrInstruction)) {
                continue;
            }
            InstructionNode retTarget = (InstructionNode) getArrivingNodesByPrimaryEdge(isJmp).iterator()
                    .next();

            removePrimaryEdge(isJmp, retTarget);
            InstructionNode retNode = null;

            cont++;
            // achou JSR. deve duplicar o seu destino
            // entr eh o no destino do JSP
            InstructionHandle ihEntr = (InstructionHandle) jumpsAndEntries.get(isJmp.ih);
            InstructionNode entr = (InstructionNode) verify.get(ihEntr);
            // entrSet eh o conjunto de nos dominados pelo no de entrada
            HashSet entrSet = (HashSet) entriesDom.get(entr);
            Iterator in = entrSet.iterator();
            Hashtable auxVerify = new Hashtable();

            while (in.hasNext()) { // duplica cada elemento no conjunto
                InstructionNode inSet = (InstructionNode) in.next();
                InstructionNode newNode = new InstructionNode(inSet.ih);

                // insere no grapho
                add(newNode);

                // seta qual eh o jsr correspondente
                newNode.setDomEntry(isJmp);

                aux.add(newNode);
                auxVerify.put(inSet, newNode);
                if (newNode.ih.getInstruction() instanceof RET) {
                    retNode = newNode;
                }
            }

            // agora precisa fazer as ligacoes
            in = entrSet.iterator();
            while (in.hasNext()) {
                InstructionNode inSet = (InstructionNode) in.next();
                InstructionNode newNode = (InstructionNode) auxVerify.get(inSet);
                GraphNode[] nx = (GraphNode[]) getArrivingNodesByPrimaryEdge(inSet).toArray(new GraphNode[0]);

                for (int j = 0; j < nx.length; j++) {
                    InstructionNode nxin = (InstructionNode) auxVerify.get(nx[j]);

                    addPrimaryEdge(newNode, nxin);
                }
                nx = (GraphNode[]) getArrivingNodesBySecondaryEdge(inSet).toArray(new GraphNode[0]);
                for (int j = 0; j < nx.length; j++) {
                    InstructionNode nxin = (InstructionNode) auxVerify.get(nx[j]);

                    // se nxin eh null significa que o no nao estah no mesmo
                    // conjunto. Para corrigir isso no final eh feito
                    // tratamento especial (ver *** )
                    if (nxin != null) {
                        addSecondaryEdge(newNode, nxin);
                    }
                }
            }
            // liga agora o JSR e o RET, se existir
            addPrimaryEdge(isJmp, (InstructionNode) auxVerify.get(entr));
            if (retNode != null) {
                addPrimaryEdge(retNode, retTarget);
            }
        }
    } while (cont > 0);

    // Faz interseccao com vetor aux
    for (int i = 1; i < entries.length; i++) {
        HashSet edm = (HashSet) entriesDom.get(entries[i]);
        Iterator it = edm.iterator();

        while (it.hasNext()) {
            InstructionNode in = (InstructionNode) it.next();

            removeNode(in);
        }
    }

    // ***
    removeEntryNodes();
    setEntryNode(entries[0]);

    // acha Depth firs tree
    GraphNode[] dft = findDFTNodes(true);

    for (int i = 0; i < dft.length; i++) {
        // include edges from each node to its exception handlers
        InstructionNode vf = (InstructionNode) dft[i];

        nextException: for (int j = 0; j < ceg.length; j++) {
            int init, fim;

            init = ceg[j].getStartPC().getPosition();
            fim = ceg[j].getEndPC().getPosition();
            InstructionHandle handler = ceg[j].getHandlerPC();

            if (vf.ih.getPosition() >= init && vf.ih.getPosition() <= fim) {
                Set<GraphNode> vnx = getArrivingNodesBySecondaryEdge(vf);
                Iterator<GraphNode> k = vnx.iterator();
                while (k.hasNext()) {
                    InstructionNode nx = (InstructionNode) k.next();
                    if (nx.ih == handler) {
                        continue nextException;
                    }
                }

                // procura quem trata da interrupo
                for (int l = vnx.size() - 1; l >= 0; l--) {
                    InstructionNode dftk = (InstructionNode) dft[l];
                    if (dftk.ih.getPosition() >= init && dftk.ih.getPosition() <= fim) {
                        Set<GraphNode> vx = getArrivingNodesBySecondaryEdge(dft[l]);
                        Iterator<GraphNode> z = vx.iterator();
                        InstructionNode hdl = null;
                        while (z.hasNext()) {
                            hdl = (InstructionNode) z.next();
                            if (hdl.ih == handler) {
                                break;
                            }
                        }
                        vf.addSecNext(hdl);
                        break;
                    }
                }
            }

        }
    }
}

From source file:br.jabuti.graph.view.gvf.GVFDrawPanel.java

License:Open Source License

public void mouseMoved(MouseEvent evt) {
    tip = null;//  w w  w .j a v  a  2  s. c o m
    boolean found = false;

    for (Enumeration e = vNodes.elements(); e.hasMoreElements();) {
        GVFNode newNode = (GVFNode) e.nextElement();

        if (newNode.itsMe(evt.getX(), evt.getY())) {
            tip = newNode.getGraphNode().toString();

            // Adding the corresponding source line numbers to
            // the GraphNode information...

            LineNumberTable lnTable = newNode.getMethodGen().getLineNumberTable(newNode.getConstantPoolGen());

            tip += "Corresponding Source Lines:\n";

            InstructionHandle ih = br.jabuti.util.InstructCtrl.findInstruction(newNode.getMethodGen(),
                    ((CFGNode) newNode.getGraphNode()).getStart());
            int srcLine = lnTable.getSourceLine(ih.getPosition());
            HashSet srcLines = new HashSet();

            srcLines.add(new Integer(srcLine));
            while (ih.getPosition() != ((CFGNode) newNode.getGraphNode()).getEnd()) {
                ih = ih.getNext();
                srcLine = lnTable.getSourceLine(ih.getPosition());
                srcLines.add(new Integer(srcLine));
            }
            Object[] lines = srcLines.toArray();

            Arrays.sort(lines);

            tip += "\t" + lines[0];
            for (int i = 1; i < lines.length; i++) {
                tip += ", " + lines[i];
            }
            tip += "\n";

            tipX = newNode.getX() + 30;
            tipY = newNode.getY();
            reDraw();
            found = true;
        }
    }
    if (!found) {
        reDraw();
    }
}

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

License:Open Source License

/** Inserts one single instruction after a given instruction
 in the specified method. To insert means that the new instruction
 will take the place of the next one that will be shifted down.
        /*  w ww  .  ja  va2s.  c om*/
 @param ih The instruction before which the code will be inserted
 @param x The instruction to be inserted
        
        
 */
public void insertAfter(InstructionHandle ih, Instruction x) {
    InstructionHandle nextih = ih.getNext();
    //        InstructionHandle newih = null;

    if (nextih != null) {
        //            newih = 
        il.insert(nextih, x);
    } else {
        //            newih = 
        il.append(x);
    }
    // recalTables(ih, newih);
}

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

License:Open Source License

/** The same of {@link Instrumenter#insertAfter(InstructionHandle ih, Instruction x)}
 but a list of instructions is inserted.
        //from  w  ww  . j a  va2 s.c o  m
 @param ih The instruction before which the code will be inserted
 @param x The list of instructions to be inserted
        
 */

public void insertAfter(InstructionHandle ih, InstructionList x) {
    InstructionHandle nextih = ih.getNext();
    //        InstructionHandle newih = null;

    if (nextih != null) {
        //            newih = 
        il.insert(nextih, x);
    } else {
        //            newih = 
        il.append(x);
    }
    // if ( newih == null)
    // return;
    // recalTables(ih, newih);
}

From source file:br.jabuti.project.ClassMethod.java

License:Open Source License

public GraphNode getGraphNodeFromOffset(int offset) {
    GraphNode theNode = null;/*w ww  . jav a  2 s .c om*/

    try {
        CFG cfg = getCFG();

        GraphNode[] fdt = cfg.findDFTNodes(true);

        for (int i = 0; i < fdt.length && theNode == null; i++) {
            GraphNode gn = fdt[i];

            InstructionHandle ih = br.jabuti.util.InstructCtrl.findInstruction(getMethodGen(),
                    ((CFGNode) gn).getStart());
            String inst = ih.toString();
            int index = inst.indexOf(":");
            Integer off = new Integer(inst.substring(0, index).trim());

            if (off.intValue() == offset) {
                theNode = gn;
            }

            while ((theNode == null) && (ih.getPosition() != ((CFGNode) gn).getEnd())) {
                ih = ih.getNext();
                inst = ih.toString();
                index = inst.indexOf(":");
                off = new Integer(inst.substring(0, index).trim());

                if (off.intValue() == offset) {
                    theNode = gn;
                }
            }
        }
    } catch (Exception e) {
        ToolConstants.reportException(e, ToolConstants.STDERR);
        return null;
    }
    return theNode;
}

From source file:br.jabuti.ui.gui.BytecodePanel.java

License:Open Source License

public BytecodePanel showBytecodePanel(int toOffset) {

    parent = JabutiGUI.mainWindow();//from   ww  w .j a v a2 s.c  om

    String className = JabutiGUI.getProject().getCurClassName();

    ClassFile cl = JabutiGUI.getProject().getClassFile(className);

    // Empting the content of the text panel
    tp.setText("");

    // UPDATING THE SOURCE COLOR...
    tp.setBackground(ToolConstants.getColor(ToolConstants.COLOR_0));

    Document doc = tp.getStyledDocument();

    SimpleAttributeSet attr = new SimpleAttributeSet();

    //StyleConstants.setFontFamily(attr, "Courier New");
    //StyleConstants.setFontSize(attr, ToolConstants.sourceFontSize);
    StyleConstants.setBackground(attr, ToolConstants.getColor(ToolConstants.COLOR_0));

    JavaClass javaClass = cl.getJavaClass();
    Method[] methods = cl.getMethods();

    // BUILDING THE COLOR PANEL...
    buttonPanel.setVisible(false);
    buttonPanel.removeAll();

    Hashtable colorButtonTable = WeightColor.getColorButtonTable();

    buttonPanel.setLayout(new GridLayout(1, colorButtonTable.size()));

    int[] labels = WeightColor.getColorBarLabels();

    for (int i = 0; i < labels.length; i++) {
        Integer label = new Integer(labels[i]);
        JButton button = new JButton(label.toString());

        int color = ((Integer) colorButtonTable.get(label)).intValue();

        button.setBackground(ToolConstants.getColor(color));

        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setEnabled(false);

        buttonPanel.add(button);
    }
    buttonPanel.setVisible(true);
    add(buttonPanel, BorderLayout.NORTH);

    try {
        // Printing the header of the class file
        BufferedReader strReader = new BufferedReader(new StringReader(javaClass.toString()));
        String nl = System.getProperty("line.separator");

        // Printing the class name
        doc.insertString(doc.getLength(), strReader.readLine() + nl, attr);
        // Printing the class file name
        doc.insertString(doc.getLength(), strReader.readLine() + nl, attr);
        // Printing the source file name
        doc.insertString(doc.getLength(), strReader.readLine() + nl, attr);

        for (int i = 0; i < methods.length; i++) {
            String methodName = methods[i].getName() + methods[i].getSignature();

            // Reseting the Background Color...
            StyleConstants.setBackground(attr, ToolConstants.getColor(ToolConstants.COLOR_0));

            ClassMethod method = cl.getMethod(methodName);

            method.setBeginBytecodeOffset(doc.getEndPosition().getOffset());

            // Printing the name of the method
            doc.insertString(doc.getLength(),
                    nl + nl + method.getMethodGen().getReturnType() + " " + methodName + "\n", attr);

            Code code = methods[i].getCode();

            Hashtable offsetLines = new Hashtable();
            Hashtable offsetColors = new Hashtable();

            if (code != null) {
                strReader = new BufferedReader(new StringReader(code.toString()));
                String line = strReader.readLine();

                while (line != null) {
                    try {
                        int index = line.indexOf(":");

                        if (index > 0) {
                            Integer offset = new Integer(line.substring(0, index));

                            offsetLines.put(offset, line);
                            offsetColors.put(offset, new Integer(0));
                        }
                    } catch (NumberFormatException nfe) {
                    }
                    line = strReader.readLine();
                }
            }

            Hashtable positionTable = null;
            Hashtable classVariables = WeightColor.getClassVariableTable();

            // ALL-USES: Painting only the offset where the
            // variable definition is located
            if (JabutiGUI.isAllPrimaryUses() || JabutiGUI.isAllSecondaryUses()
                    || JabutiGUI.isAllPrimaryPotUses() || JabutiGUI.isAllSecondaryPotUses()) {

                // Position table can be null if
                // the method has no def-use requirement
                Integer mId = new Integer(method.getMethodId());

                // ERROR: remove this above if statement
                // Consequences: if the method has no def-use association a
                // null pointer exception is thrown.
                if (classVariables != null && classVariables.containsKey(mId)) {
                    positionTable = (Hashtable) classVariables.get(mId);

                    if (!SelectedPoint.isSelected()) {
                        // For each defined variable
                        Iterator itPos = positionTable.keySet().iterator();

                        while (itPos.hasNext()) {
                            Integer pos = (Integer) itPos.next();

                            Vector nodeVar = WeightColor.getWeightestVariableFromPosition(method.getMethodId(),
                                    pos);

                            if (nodeVar != null) {
                                GraphNode gn = (GraphNode) nodeVar.elementAt(0);
                                String varDef = (String) nodeVar.elementAt(1);
                                Integer varDefOff = ((CFGNode) gn).getDefinitionOffset(varDef);

                                Integer varDefWgt = WeightColor
                                        .getVariableDefinitionWeight(method.getMethodId(), gn, varDef);
                                Integer varDefColor = new Integer(
                                        WeightColor.getColorByWeight(labels, varDefWgt));

                                // Setting the color of the definition offset
                                if (offsetColors.containsKey(varDefOff)) {
                                    Integer curColor = (Integer) offsetColors.get(varDefOff);

                                    if (curColor.intValue() < varDefColor.intValue()) {
                                        offsetColors.put(varDefOff, varDefColor);
                                    }
                                }
                            }
                        }
                    } else if (SelectedPoint.isSelected()
                            && SelectedPoint.getMethod() == method.getMethodId()) {

                        Integer defOffset = ((CFGNode) SelectedPoint.getNode())
                                .getDefinitionOffset(SelectedPoint.getVariable());
                        Integer varDefColor = (Integer) SelectedPoint
                                .recoverFromNode(ToolConstants.LABEL_COLOR);

                        // Setting the color of the definition offset
                        if (offsetColors.containsKey(defOffset)) {
                            offsetColors.put(defOffset, varDefColor);
                        }

                        System.out.println("Selected method: " + SelectedPoint.getMethod());
                        System.out.println("Selected node: " + SelectedPoint.getNode());
                        System.out.println("Selected variable: " + SelectedPoint.getVariable());

                        // Getting all uses of the selected definition
                        Hashtable defUseTable = (Hashtable) WeightColor.getClassWeights()
                                .get(new Integer(SelectedPoint.getMethod()));
                        Hashtable defTable = (Hashtable) defUseTable.get(SelectedPoint.getNode());
                        Hashtable useTable = (Hashtable) defTable.get(SelectedPoint.getVariable());

                        Iterator itUse = useTable.keySet().iterator();

                        while (itUse.hasNext()) {
                            DefUse du = (DefUse) itUse.next();

                            System.out.println("DEF-USE: " + du);

                            Integer useWgt = (Integer) useTable.get(du);

                            System.out.println("\tDU weight: " + useWgt);

                            int useColor = WeightColor.getColorByWeight(labels, useWgt);

                            // C-Use color....
                            GraphNode gnUse = method.getGraphNodeByLabel(du.getUseFrom());
                            Integer useOffset = ((CFGNode) gnUse).getUseOffset(du.getVar());

                            System.out.println("\tUse node: " + gnUse);
                            System.out.println("\tUse offset: " + useOffset);

                            if (offsetColors.containsKey(useOffset)) {
                                Integer curColor = (Integer) offsetColors.get(useOffset);

                                if (curColor.intValue() < useColor) {
                                    offsetColors.put(useOffset, new Integer(useColor));
                                }
                            }

                            // If p-use, change the color of the entire second node
                            String useLabel = du.getUseTo();

                            if (useLabel != null) {
                                System.out.println("CHANGING THE COLOR OF NODE: " + useLabel);
                                GraphNode gn = method.getGraphNodeByLabel(useLabel);
                                int c = ((Integer) gn.getUserData(ToolConstants.LABEL_COLOR)).intValue();

                                System.out.println("Current color: " + c);

                                InstructionHandle ih = br.jabuti.util.InstructCtrl
                                        .findInstruction(method.getMethodGen(), ((CFGNode) gn).getStart());
                                String inst = ih.toString();
                                int index = inst.indexOf(":");
                                Integer offset = new Integer(inst.substring(0, index).trim());

                                if (offsetColors.containsKey(offset)) {
                                    int cNumber = ((Integer) offsetColors.get(offset)).intValue();

                                    if (cNumber < c) {
                                        offsetColors.put(offset, new Integer(c));
                                    }
                                }

                                while (ih.getPosition() != ((CFGNode) gn).getEnd()) {
                                    ih = ih.getNext();
                                    inst = ih.toString();
                                    index = inst.indexOf(":");
                                    offset = new Integer(inst.substring(0, index).trim());
                                    if (offsetColors.containsKey(offset)) {
                                        int cNumber = ((Integer) offsetColors.get(offset)).intValue();

                                        if (cNumber < c) {
                                            offsetColors.put(offset, new Integer(c));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                CFG cfg = method.getCFG();
                GraphNode[] fdt = cfg.findDFTNodes(true);

                int c = 0;

                /*
                 Hashtable defUseTable = null;
                        
                 if (allUsesCriterion.isSelected()) {
                 defUseTable = (Hashtable) classWeights.get(new Integer(method.getMethodId()));
                 }
                 */

                for (int x = 0; x < fdt.length; x++) {

                    GraphNode gn = fdt[x];

                    // Getting the color associated with this node
                    Integer weightColor = (Integer) gn.getUserData(ToolConstants.LABEL_COLOR);

                    if (weightColor != null) {
                        c = weightColor.intValue();
                    } else {
                        c = 0;
                    }

                    // ALL-EDGES: Painting only the decision bytecode instruction 
                    // when a decision node is selected
                    if ((JabutiGUI.isAllPrimaryEdges() || JabutiGUI.isAllSecondaryEdges())
                            && ((!SelectedPoint.isSelected()) || (SelectedPoint.isSelected()
                                    && gn.getLabel().equals(SelectedPoint.getNodeLabel())))) {
                        InstructionHandle ih = br.jabuti.util.InstructCtrl
                                .findInstruction(method.getMethodGen(), ((CFGNode) gn).getEnd());
                        String inst = ih.toString();
                        int index = inst.indexOf(":");
                        Integer offset = new Integer(inst.substring(0, index).trim());

                        if (offsetColors.containsKey(offset)) {
                            int cNumber = ((Integer) offsetColors.get(offset)).intValue();

                            if (cNumber < c) {
                                offsetColors.put(offset, new Integer(c));
                            }
                        }
                    } else {
                        InstructionHandle ih = br.jabuti.util.InstructCtrl
                                .findInstruction(method.getMethodGen(), ((CFGNode) gn).getStart());
                        String inst = ih.toString();
                        int index = inst.indexOf(":");
                        Integer offset = new Integer(inst.substring(0, index).trim());

                        if (offsetColors.containsKey(offset)) {
                            int cNumber = ((Integer) offsetColors.get(offset)).intValue();

                            if (cNumber < c) {
                                offsetColors.put(offset, new Integer(c));
                            }
                        }

                        while (ih.getPosition() != ((CFGNode) gn).getEnd()) {
                            ih = ih.getNext();
                            inst = ih.toString();
                            index = inst.indexOf(":");
                            offset = new Integer(inst.substring(0, index).trim());
                            if (offsetColors.containsKey(offset)) {
                                int cNumber = ((Integer) offsetColors.get(offset)).intValue();

                                if (cNumber < c) {
                                    offsetColors.put(offset, new Integer(c));
                                }
                            }
                        }
                    }
                }
            }

            // Printing the code, independently of the tsting
            // criterion                    

            Object[] orderedInstr = offsetLines.keySet().toArray();

            Arrays.sort(orderedInstr);
            for (int x = 0; x < orderedInstr.length; x++) {
                Integer offset = (Integer) orderedInstr[x];

                String line = (String) offsetLines.get(offset);

                int c;

                if (offsetColors.containsKey(offset)) {
                    c = ((Integer) offsetColors.get(offset)).intValue();
                } else {
                    c = 0;
                }
                StyleConstants.setBackground(attr, ToolConstants.getColor(c));
                doc.insertString(doc.getLength(), line + nl, attr);

                // To print the code in the standard output...
                // System.out.println( line );
            }
            method.setEndBytecodeOffset(doc.getEndPosition().getOffset());
        }
    } catch (Exception e) {
        ToolConstants.reportException(e, ToolConstants.STDERR);
    }

    scrollPane.setViewportView(tp);

    setCaret(toOffset);

    int row = tp.getStyledDocument().getDefaultRootElement().getElementIndex(tp.getCaretPosition());
    int end = tp.getStyledDocument().getDefaultRootElement().getElementIndex(tp.getDocument().getLength());

    String criterion = parent.getActiveCriterionName();

    ssp.setContent("File: " + className, "Line: " + (row + 1) + " of " + (end + 1), "Coverage: " + criterion,
            "Highlighting: All Priorized");
    ssp.setVisible(true);

    return this;
}

From source file:br.jabuti.ui.gui.SourcePanel.java

License:Open Source License

public SourcePanel showSourcePanel(int toOffset) {

    parent = JabutiGUI.mainWindow();//from ww  w. ja  v a2 s .c om

    prj = JabutiGUI.getProject();
    String className = prj.getCurClassName();

    ClassFile cl = prj.getClassFile(className);
    ClassSourceFile src = cl.getSourceFile();

    tp.setText("");

    BufferedReader buffer = null;

    if (src.exists()) {
        buffer = src.getSourceCode();

        lineNodeTable = new Hashtable();

        // UPDATING THE SOURCE COLOR...
        tp.setBackground(ToolConstants.getColor(ToolConstants.COLOR_0));

        Document doc = tp.getStyledDocument();
        String nl = System.getProperty("line.separator");

        SimpleAttributeSet attr = new SimpleAttributeSet();

        //StyleConstants.setFontFamily(attr, "Courier New");
        //StyleConstants.setFontSize(attr, ToolConstants.sourceFontSize);
        StyleConstants.setBackground(attr, ToolConstants.getColor(ToolConstants.COLOR_0));

        Method[] methods = cl.getMethods();

        // BUILDING THE COLOR PANEL...
        buttonPanel.setVisible(false);
        buttonPanel.removeAll();

        Hashtable colorButtonTable = WeightColor.getColorButtonTable();

        buttonPanel.setLayout(new GridLayout(1, colorButtonTable.size()));

        Object[] keySet = colorButtonTable.keySet().toArray();

        Arrays.sort(keySet);

        for (int i = 0; i < keySet.length; i++) {
            JButton button = new JButton(((Integer) keySet[i]).toString());

            int color = ((Integer) colorButtonTable.get((Integer) keySet[i])).intValue();

            button.setBackground(ToolConstants.getColor(color));

            button.setBorderPainted(false);
            button.setFocusPainted(false);
            button.setEnabled(false);

            buttonPanel.add(button);
        }
        buttonPanel.setVisible(true);
        add(buttonPanel, BorderLayout.NORTH);

        if (buffer != null) {
            try {
                Vector sourceColor = new Vector();

                // Inserting something at position 0
                sourceColor.add(new Integer(ToolConstants.COLOR_0));

                // The code starts at position 1
                String line = buffer.readLine();

                while (line != null) {
                    sourceColor.add(new Integer(ToolConstants.COLOR_0));
                    line = buffer.readLine();
                }

                int[] labels = null;

                if (JabutiGUI.isAllPrimaryUses() || JabutiGUI.isAllSecondaryUses()
                        || JabutiGUI.isAllPrimaryPotUses() || JabutiGUI.isAllSecondaryPotUses()) {
                    labels = WeightColor.getColorBarLabels();
                }

                for (int i = 0; i < methods.length; i++) {
                    String methodName = methods[i].getName() + methods[i].getSignature();

                    ClassMethod method = cl.getMethod(methodName);

                    // Line number table to map bytecode offset into
                    // source code line...
                    LineNumberTable lnTable = method.getMethodGen()
                            .getLineNumberTable(method.getConstantPoolGen());

                    Hashtable positionTable = null;
                    Hashtable classVariables = WeightColor.getClassVariableTable();

                    // ALL-USES: Painting only the offset where the
                    // variable definition is located
                    if (JabutiGUI.isAllPrimaryUses() || JabutiGUI.isAllSecondaryUses()
                            || JabutiGUI.isAllPrimaryPotUses() || JabutiGUI.isAllSecondaryPotUses()) {

                        // Position table can be null if
                        // the method has no def-use requirement
                        Integer mId = new Integer(method.getMethodId());

                        // ERROR: remove this above if statement
                        // Consequences: if the method has no def-use association a
                        // null pointer exception is thrown.
                        if (classVariables != null && classVariables.containsKey(mId)) {

                            positionTable = (Hashtable) WeightColor.getClassVariableTable().get(mId);

                            if (!SelectedPoint.isSelected()) {
                                // For each defined variable
                                Iterator itPos = positionTable.keySet().iterator();

                                while (itPos.hasNext()) {
                                    Integer pos = (Integer) itPos.next();

                                    Vector nodeVar = WeightColor
                                            .getWeightestVariableFromPosition(method.getMethodId(), pos);

                                    if (nodeVar != null) {
                                        GraphNode gn = (GraphNode) nodeVar.elementAt(0);
                                        String varDef = (String) nodeVar.elementAt(1);

                                        Integer varDefWgt = WeightColor
                                                .getVariableDefinitionWeight(method.getMethodId(), gn, varDef);
                                        Integer varDefColor = new Integer(
                                                WeightColor.getColorByWeight(labels, varDefWgt));

                                        System.out.println("MID " + mId + " name : " + method.getMethodName());

                                        System.out.println("Var Weight " + varDefWgt);
                                        System.out.println("Var Color " + varDefColor);
                                        System.out.println("Var Por " + pos);

                                        // TO HANDLE ASPECT ORIENTED PROGRAMS
                                        if (pos != null && pos.intValue() >= 0)
                                            sourceColor.setElementAt(varDefColor, pos.intValue());
                                    }
                                }
                            } else if (SelectedPoint.isSelected()
                                    && SelectedPoint.getMethod() == method.getMethodId()) {

                                Integer defOffset = ((CFGNode) SelectedPoint.getNode())
                                        .getDefinitionOffset(SelectedPoint.getVariable());
                                int defSrcLine = method.bytecodeOffset2SourceLine(defOffset.intValue());

                                Integer varDefColor = (Integer) SelectedPoint
                                        .recoverFromNode(ToolConstants.LABEL_COLOR);

                                // TO HANDLE ASPECT ORIENTED PROGRAMS
                                if (defSrcLine >= 0)
                                    // Painting the definition node
                                    sourceColor.setElementAt(varDefColor, defSrcLine);

                                // Getting all uses of the selected definition
                                Hashtable defUseTable = (Hashtable) WeightColor.getClassWeights()
                                        .get(new Integer(SelectedPoint.getMethod()));
                                Hashtable defTable = (Hashtable) defUseTable.get(SelectedPoint.getNode());
                                Hashtable useTable = (Hashtable) defTable.get(SelectedPoint.getVariable());

                                Iterator itUse = useTable.keySet().iterator();

                                while (itUse.hasNext()) {
                                    DefUse du = (DefUse) itUse.next();
                                    Integer useWgt = (Integer) useTable.get(du);

                                    int useColor = WeightColor.getColorByWeight(labels, useWgt);

                                    // C-Use color....
                                    GraphNode gnUse = method.getGraphNodeByLabel(du.getUseFrom());
                                    Integer useOffset = ((CFGNode) gnUse).getUseOffset(du.getVar());
                                    int useLine = method.bytecodeOffset2SourceLine(useOffset.intValue());

                                    // TO HANDLE ASPECT ORIENTED PROGRAMS
                                    if (useLine >= 0) {
                                        Integer cor = (Integer) sourceColor.elementAt(useLine);

                                        if (cor.intValue() < useColor) {
                                            sourceColor.setElementAt(new Integer(useColor), useLine);
                                        }

                                        // If p-use, change the color of the entire second node
                                        String useLabel = du.getUseTo();

                                        if (useLabel != null) {
                                            GraphNode gn = method.getGraphNodeByLabel(useLabel);
                                            int c = ((Integer) gn.getUserData(ToolConstants.LABEL_COLOR))
                                                    .intValue();

                                            InstructionHandle ih = br.jabuti.util.InstructCtrl.findInstruction(
                                                    method.getMethodGen(), ((CFGNode) gn).getStart());
                                            int srcLine = lnTable.getSourceLine(ih.getPosition());

                                            // TO HANDLE ASPECT ORIENTED PROGRAMS
                                            if (srcLine >= 0) {
                                                cor = (Integer) sourceColor.elementAt(srcLine);

                                                if (cor.intValue() < c) {
                                                    sourceColor.setElementAt(new Integer(c), srcLine);
                                                }

                                                while (ih.getPosition() != ((CFGNode) gn).getEnd()) {
                                                    ih = ih.getNext();
                                                    srcLine = lnTable.getSourceLine(ih.getPosition());
                                                    cor = (Integer) sourceColor.elementAt(srcLine);
                                                    if (cor.intValue() < c) {
                                                        sourceColor.setElementAt(new Integer(c), srcLine);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        // Traversing the CFG looking for the color of each node...
                        CFG cfg = method.getCFG();
                        GraphNode[] fdt = cfg.findDFTNodes(true);

                        int c = 0;

                        for (int x = 0; x < fdt.length; x++) {

                            GraphNode gn = fdt[x];

                            // Getting the color associated with this node
                            Integer weightColor = (Integer) gn.getUserData(ToolConstants.LABEL_COLOR);

                            if (weightColor != null) {
                                c = weightColor.intValue();
                            } else {
                                c = 0;
                            }

                            // ALL-EDGES: Painting only the decision bytecode instruction 
                            // when a decision node is selected
                            if ((!SelectedPoint.isSelected()
                                    && (JabutiGUI.isAllPrimaryEdges() || JabutiGUI.isAllSecondaryEdges()))
                                    || (SelectedPoint.isSelected()
                                            && gn.getLabel().equals(SelectedPoint.getNodeLabel()))) {
                                InstructionHandle ih = br.jabuti.util.InstructCtrl
                                        .findInstruction(method.getMethodGen(), ((CFGNode) gn).getEnd());
                                int srcLine = lnTable.getSourceLine(ih.getPosition());

                                // TO HANDLE ASPECT ORIENTED PROGRAMS
                                if (srcLine >= 0) {
                                    int cor = ((Integer) sourceColor.elementAt(srcLine)).intValue();

                                    if (cor < c) {
                                        Integer nc = new Integer(c);
                                        Integer ln = new Integer(srcLine);

                                        sourceColor.setElementAt(nc, srcLine);
                                        lineNodeTable.put(ln, gn.getLabel());
                                        System.out.println("LINE " + ln + " NODE: " + gn.getLabel());
                                    }
                                }
                                // ALL-NODES: Painting all offset of a given CFG Node
                            } else {
                                InstructionHandle ih = br.jabuti.util.InstructCtrl
                                        .findInstruction(method.getMethodGen(), ((CFGNode) gn).getStart());
                                //System.out.println( "METHOD ATUAL: " + method.getMethodName() );

                                int srcLine = -1;
                                try {
                                    srcLine = lnTable.getSourceLine(ih.getPosition());
                                    int cor = ((Integer) sourceColor.elementAt(srcLine)).intValue();

                                    if (cor < c) {
                                        sourceColor.setElementAt(new Integer(c), srcLine);
                                    }
                                } catch (ArrayIndexOutOfBoundsException aobe) {
                                    //System.out.println("Exceo gerada");                           
                                }
                                //System.out.println( "\tBytecode position: " + ih.getPosition() );
                                //System.out.println( "\tSource line position: " + srcLine );
                                // TO HANDLE ASPECT ORIENTED PROGRAMS
                                while (ih.getPosition() != ((CFGNode) gn).getEnd()) {
                                    ih = ih.getNext();
                                    try {
                                        srcLine = lnTable.getSourceLine(ih.getPosition());
                                        int cor = ((Integer) sourceColor.elementAt(srcLine)).intValue();
                                        if (cor < c) {
                                            sourceColor.setElementAt(new Integer(c), srcLine);
                                        }
                                    } catch (ArrayIndexOutOfBoundsException aobe) {
                                        //System.out.println("Exceo gerada");                           
                                    }
                                    //System.out.println( "\tBytecode position: " + ih.getPosition() );
                                    //System.out.println( "\tSource line position: " + srcLine );
                                }
                            }
                        }
                    }
                }

                // Printing and painting the source code...
                buffer = src.getSourceCode();

                line = buffer.readLine();
                // The code starts at position 1
                int curLine = 1;

                while (line != null) {
                    int cor = ((Integer) sourceColor.elementAt(curLine)).intValue();

                    StyleConstants.setBackground(attr, ToolConstants.getColor(cor));

                    String lineNumber = new String("/* " + ToolConstants.getFourDigitNumber(curLine) + " */ ");

                    doc.insertString(doc.getLength(), lineNumber + line + nl, attr);

                    // To print the code in the standard output...
                    // System.out.println( lineNumber + line );

                    line = buffer.readLine();
                    curLine++;
                }
            } catch (Exception e) {
                ToolConstants.reportException(e, ToolConstants.STDERR);
            }
        }

        scrollPane.setViewportView(tp);

        setCaretByLine(toOffset);
        int row = tp.getStyledDocument().getDefaultRootElement().getElementIndex(tp.getCaretPosition());
        int end = tp.getStyledDocument().getDefaultRootElement().getElementIndex(tp.getDocument().getLength());

        String criterion = parent.getActiveCriterionName();

        ssp.setContent("File: " + className, "Line: " + (row + 1) + " of " + (end + 1),
                "Coverage: " + criterion, "Highlighting: All Priorized");
        ssp.setVisible(true);
    } else {
        // buffer = cl.getBytecode();
        JOptionPane.showMessageDialog(null,
                "No source file available for the selected class file: " + className, "Warning...",
                JOptionPane.WARNING_MESSAGE);
    }
    return this;
}

From source file:br.jabuti.util.InstructCtrl.java

License:Open Source License

/** Computes the set of instructions that can be executed after a 
 given instruction./*w  w  w . java 2  s  .  c  o m*/
        
 @param x The instruction for which is wanted the set of possible
 followers
 @return The set of instructions that can be executed after the instruction
 got as argument
 */
static public InstructionHandle[] nextToExec(InstructionHandle x) {
    Vector v = new Vector();
    InstructionHandle pr = x.getNext();
    Instruction inst = x.getInstruction();

    if (pr != null) {
        if (!(inst instanceof UnconditionalBranch || inst instanceof Select || inst instanceof ReturnInstruction
                || inst instanceof RET)) {
            v.add(pr);
        }
    }
    if (inst instanceof Select) {
        InstructionHandle[] targ = ((Select) inst).getTargets();

        for (int i = 0; i < targ.length; i++) {
            v.add(targ[i]);
        }
    }
    if (inst instanceof BranchInstruction) {
        v.add(((BranchInstruction) inst).getTarget());
    }
    return (InstructionHandle[]) v.toArray(new InstructionHandle[0]);
}