package Sequenic.T2ext.CoverageEngine.ga; import java.lang.reflect.Field; import java.util.Iterator; import java.util.List; import org.apache.bcel.Repository; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.BIPUSH; import org.apache.bcel.generic.ClassGen; import org.apache.bcel.generic.GETFIELD; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.MethodGen; import org.apache.bcel.util.InstructionFinder; import Sequenic.T2.Seq.Trace; import Sequenic.T2.Seq.TraceExecInfo; import Sequenic.T2ext.CoverageEngine.BaseEngine; import Sequenic.T2ext.Instrumenter.Sensor; /** * This GA evaluator searches for an if(int==constant) pattern in the CUT and can * calculate the fitness based on the distance between the ints. * * @author Christiaan Hees */ public class IntEqualsIntEvaluator extends Evaluator { private String i1; private Number i2; public IntEqualsIntEvaluator(BaseEngine engine) { super(engine); JavaClass clazz = null; try { clazz = Repository.lookupClass(engine.t2covAnalyzer.getC()); } catch (ClassNotFoundException e) { e.printStackTrace(); System.exit(1); } ClassGen cGen = new ClassGen(clazz); for(Method m : cGen.getMethods()) { MethodGen mGen = new MethodGen(m, cGen.getClassName(), cGen.getConstantPool()); // Search for if(int==int) InstructionFinder finder = new InstructionFinder(mGen.getInstructionList()); Iterator i = finder.search("aload_0 getfield bipush if_icmpne"); while(i.hasNext()) { // TODO what if you find more than 1 of these patterns? InstructionHandle[] match = (InstructionHandle[]) i.next(); GETFIELD getfield = (GETFIELD) match[1].getInstruction(); i1 = getfield.getFieldName(cGen.getConstantPool()); BIPUSH bipush = (BIPUSH) match[2].getInstruction(); i2 = bipush.getValue(); containingMethod = m.getName(); System.out.println("Found if(int==constant) pattern in " + containingMethod + ": " + i1 + " " + i2); } } } public double getFitness(Trace candidate, List population) { // Execute the trace and calculate the fitness based on the 3 ints Sensor.ejectObservations(); TraceExecInfo info = engine.executeT2Trace(candidate); Class c = engine.t2covAnalyzer.getC(); try { Field f1 = c.getDeclaredField(i1); f1.setAccessible(true); // TODO is this obj actually the one we need? Object obj = info.lastStepResult.receiverObj; if(obj == null) return 1000; // FIXME Double.MAX_VALUE; return Math.abs((double)f1.getInt(obj) - i2.doubleValue()); } catch (Exception e) { e.printStackTrace(); } return 0; } }