Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CFG Visualizer (implemented as a test detector) #2014

Merged
merged 8 commits into from May 4, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions spotbugs/etc/findbugs.xml
Expand Up @@ -623,6 +623,8 @@
reports="IO_APPENDING_TO_OBJECT_OUTPUT_STREAM"/>
<Detector class="edu.umd.cs.findbugs.detect.TestASM" speed="fast" disabled="true"
hidden="true" reports="TESTING"/>
<Detector class="edu.umd.cs.findbugs.detect.ViewCFG" disabled="true"
hidden="true"/>
<Detector class="edu.umd.cs.findbugs.detect.FindUnrelatedTypesInGenericContainer"
speed="fast"
reports="GC_UNRELATED_TYPES,DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES,DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION,DMI_VACUOUS_SELF_COLLECTION_CALL,GC_UNCHECKED_TYPE_IN_GENERIC_CALL"/>
Expand Down
7 changes: 7 additions & 0 deletions spotbugs/etc/messages.xml
Expand Up @@ -1586,6 +1586,13 @@ factory pattern to create these objects.</p>
]]>
</Details>
</Detector>
<Detector class="edu.umd.cs.findbugs.detect.ViewCFG">
<Details>
<![CDATA[
<p> Generate DOT files from the CFGs. </p>
]]>
</Details>
</Detector>
<Detector class="edu.umd.cs.findbugs.detect.FindUnrelatedTypesInGenericContainer">
<Details>
<![CDATA[
Expand Down
176 changes: 176 additions & 0 deletions spotbugs/src/main/java/edu/umd/cs/findbugs/detect/ViewCFG.java
@@ -0,0 +1,176 @@
package edu.umd.cs.findbugs.detect;

import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;

import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.InstructionHandle;

import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.Edge;
import static edu.umd.cs.findbugs.ba.EdgeTypes.*;

public class ViewCFG implements Detector {

private final BugReporter bugReporter;
private Path tempDir;

public ViewCFG(BugReporter bugReporter) {
this.bugReporter = bugReporter;
try {
tempDir = Files.createTempDirectory("cfg-");
} catch (IOException e) {
bugReporter.logError("Could not create temporary directory", e);
}
}

@Override
public void visitClassContext(ClassContext classContext) {
if (tempDir == null) {
return;
}
//
JavaClass cls = classContext.getJavaClass();
String classDirName = (cls.getPackageName() != "") ? (cls.getPackageName() + "." + cls.getClassName()) : cls.getClassName();
KengoTODA marked this conversation as resolved.
Show resolved Hide resolved
Path classDir;
//
try {
classDir = Files.createDirectory(Paths.get(tempDir.toString(), classDirName));
} catch (IOException e) {
bugReporter.logError("Could not create directory for class " + cls.getClassName(), e);
return;
}
//
for (Method method : cls.getMethods()) {
try {
analyzeMethod(classContext, method, classDir);
} catch (CFGBuilderException e) {
bugReporter.logError("Error analyzing method", e);
}
}
}

private void analyzeMethod(ClassContext classContext, Method method, Path classDir) throws CFGBuilderException {
Path methodFile = getMethodFile(classDir, method.getName());

try (PrintStream out = new PrintStream(Files.createFile(methodFile).toFile(), Charset.defaultCharset().name())) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Methods of the PrintStream class does not throw IOException, so better to check problems by the checkError() method after you finish using the stream.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Creation of PrintStream throws IOException. Is it OK now that I moved this to a conventional try block?

CFG cfg = classContext.getCFG(method);
out.println("digraph " + method.getName() + " {");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably we need to wrap the method name by ", to support special names like <new>.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is worse. Characters like < and > are not supported on Windows so I changed method names like <init> to ____init.

for (Iterator<BasicBlock> bi = cfg.blockIterator(); bi.hasNext();) {
BasicBlock block = bi.next();
if (block == cfg.getEntry()) {
out.println(" Node" + block.getLabel() + " [shape=record label=\"{" + block.getLabel() +
" (ENTRY) }\"];");
continue;
}
//
if (block == cfg.getExit()) {
out.println(" Node" + block.getLabel() + " [shape=record label=\"{" + block.getLabel() +
" (EXIT) }\"];");
continue;
}
//
out.print(" Node" + block.getLabel() + " [shape=record label=\"{" + block.getLabel());
if (block.getFirstInstruction() != null) {
out.print("|");
}
for (Iterator<InstructionHandle> ii = block.instructionIterator(); ii.hasNext();) {
InstructionHandle ins = ii.next();
String insStr = ins.toString(false).replaceAll(" ->", "").replaceAll(" (\\d+)$", " #$1");
baloghadamsoftware marked this conversation as resolved.
Show resolved Hide resolved
out.print(insStr + "\\l");
}
out.println("}\"];");
}

for (Iterator<Edge> ei = cfg.edgeIterator(); ei.hasNext();) {
Edge edge = ei.next();
BasicBlock src = edge.getSource();
BasicBlock tgt = edge.getTarget();
switch (edge.getType()) {
default:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() + ";");
break;
case IFCMP_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" True branch\"];");
break;
case HANDLED_EXCEPTION_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" Handled exception for #" +
edge.getSource().getExceptionThrower().getPosition() + "\"];");
break;
case UNHANDLED_EXCEPTION_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" Unhandled exception for #" +
edge.getSource().getExceptionThrower().getPosition() + "\"];");
break;
case RETURN_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" Return\"];");
break;
case START_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" Start\"];");
break;
case EXIT_EDGE:
out.println(" Node" + src.getLabel() + " -> Exit" + tgt.getLabel() +
" [shape=plaintext label=\" Exit\"];");
break;
case SWITCH_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" Switch case (non-default)\"];");
break;
case SWITCH_DEFAULT_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" Switch case (default)\"];");
break;
case JSR_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" JSR statement\"];");
break;
case RET_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" RET statement\"];");
break;
case GOTO_EDGE:
out.println(" Node" + src.getLabel() + " -> Node" + tgt.getLabel() +
" [shape=plaintext label=\" GOTO statement\"];");
break;
}
}
out.println("}");
} catch (IOException e) {
bugReporter.logError("Could not create file for method " + method.getName(), e);
}
}

private Path getMethodFile(Path classDir, String methodName) {
String methodFileName = methodName;
Path methodFile;
int index = 0;

do {
methodFile = Paths.get(classDir.toString(), methodFileName + ".dot");
methodFileName = methodName + ++index;
} while (Files.exists(methodFile));
KengoTODA marked this conversation as resolved.
Show resolved Hide resolved
return methodFile;
}

@Override
public void report() {
if (tempDir != null) {
System.out.println("CFGs generated into directory: " + tempDir + ". Please do not forget to delete it.");
}
}
}