Search code examples
javaclasscastexceptionsoot

Soot: soot.jimple.JimpleBody cannot be cast to soot.dava.DavaBody


I ran the following code to get the exception handler in .class file:

public void getException(SootMethod method){
    DavaBody db = (DavaBody) method.retrieveActiveBody();
    IterableSet excepFacts = db.get_ExceptionFacts();
    Iterator<ExceptionNode> it = excepFacts.iterator();
    while(it.hasNext()){
        ExceptionNode en = it.next();
        ...
    }
}

I got errors after running above code:

Exception in thread "main" java.lang.ClassCastException: 
soot.jimple.JimpleBody cannot be cast to soot.dava.DavaBody

The method method.retrieveActiveBody() returns Body type, not JimpleBody, so why is this error happening?


Solution

  • By the documentation, public Body retrieveActiveBody() is:

    Returns the active body if present, else constructs an active body and returns that.

    Let's look at the Body class:

    public abstract class Body
    extends AbstractHost
    implements Serializable
    

    So it is Abstract class, and by your exception, it returns JimpleBody, subclass of Body.

    If Rabbit is Animal, and Wolf is also Animal, Rabbit is not a Wolf.

    You can edit code like that:

    if (method.retrieveActiveBody() instanceof JimpleBody) {
    
    } else if (method.retrieveActiveBody() instanceof DavaBody) {
    
    } else if (method.retrieveActiveBody() instanceof BafBody) {
    
    } else if (method.retrieveActiveBody() instanceof StmtBody) {
    
    } else {
    
    }