Exemple #1
0
  /**
   * Create the content of the condition
   *
   * @param ctInvocation
   * @return
   */
  private CtBlock<Object> createThen(CtInvocation<?> ctInvocation) {
    CtBlock<Object> thenStatement = ctInvocation.getFactory().Core().createBlock();
    thenStatement.addStatement(
        (getFactory().Code().createCodeSnippetStatement("System.out.println(\"Else...\")")));
    thenStatement.addStatement(
        (getFactory()
            .Code()
            .createCodeSnippetStatement(
                "System.out.println(" + Debug.class.getCanonicalName() + ".getSolvedPC())")));

    CtAssert<Object> ctAssert = ctInvocation.getFactory().Core().createAssert();

    CtCodeSnippetExpression<Boolean> assertExpression =
        getFactory().Core().createCodeSnippetExpression();
    assertExpression.setValue("false");

    ctAssert.setAssertExpression(assertExpression);
    ctAssert.setExpression(
        getFactory()
            .Code()
            .createCodeSnippetExpression(
                String.format("\"%s\"", ctInvocation.toString().replaceAll("\"", "'"))));

    thenStatement.addStatement(ctAssert);

    return thenStatement;
  }
  protected Map<Statement, Double> buildCodeFragmentFor(CtType cl, Coverage coverage) {
    Factory factory = cl.getFactory();
    Map<Statement, Double> codeFragments = new LinkedHashMap<>();

    for (CtMethod<?> mth : (Set<CtMethod>) cl.getMethods()) {
      if (!mth.getModifiers().contains(ModifierKind.ABSTRACT)
          && !mth.getModifiers().contains(ModifierKind.PRIVATE)) {
        //                    && getCoverageForMethod(coverage, cl, mth) != 1.0) {

        CtExecutableReference executableRef = factory.Executable().createReference(mth);
        executableRef.setStatic(mth.getModifiers().contains(ModifierKind.STATIC));
        CtInvocation invocation =
            factory.Code().createInvocation(buildVarRef(cl.getReference(), factory), executableRef);
        invocation.setArguments(
            mth.getParameters()
                .stream()
                .map(param -> buildVarRef(param.getType(), factory))
                .collect(Collectors.toList()));
        invocation.setType(mth.getType());
        Statement stmt = new Statement(invocation);
        codeFragments.put(stmt, getCoverageForMethod(coverage, cl, mth));
      }
    }
    return codeFragments;
  }
  private static <T> void processConstructor(CtConstructor<T> c, CtClass<T> toMerge) {
    CtStatement firstStmt = c.getBody().getStatements().get(0);
    if (firstStmt instanceof CtInvocation) {
      CtInvocation<?> superConstructorCall = (CtInvocation) firstStmt;
      if (!(superConstructorCall.getExecutable().getDeclaration() instanceof CtConstructor)) return;
      CtConstructor superConstructor =
          (CtConstructor) superConstructorCall.getExecutable().getDeclaration();
      if (superConstructor.getDeclaringType() == toMerge) {
        CtBlock superConstructorBody = c.getFactory().Core().clone(superConstructor.getBody());
        superConstructorBody.accept(
            new CtScanner() {
              @Override
              public <T> void visitCtParameterReference(CtParameterReference<T> ref) {
                int parameterOrder = superConstructor.getParameters().indexOf(ref.getDeclaration());
                ref.setDeclaringExecutable(c.getReference());
                CtExpression<?> arg = superConstructorCall.getArguments().get(parameterOrder);
                if (!(arg instanceof CtVariableAccess))
                  throw sgce("super() should be directly called in " + c);
                CtVariable param = ((CtVariableAccess) arg).getVariable().getDeclaration();
                if (!(param instanceof CtParameter))
                  throw sgce("super() should be directly called in " + c);
                ref.setSimpleName(param.getSimpleName());

                super.visitCtParameterReference(ref);
              }
            });
        c.getBody().removeStatement(firstStmt);
        List<CtStatement> superConstructorBodyStatements = superConstructorBody.getStatements();
        for (int i = superConstructorBodyStatements.size() - 1; i >= 0; i--) {
          c.getBody().insertBegin(superConstructorBodyStatements.get(i));
        }
      }
    }
  }
Exemple #4
0
 @Override
 public boolean isToBeProcessed(CtInvocation<?> candidate) {
   if (!candidate.getExecutable().getSimpleName().contains("assert")) {
     return false;
   }
   CtExecutableReference<?> executable = candidate.getExecutable();
   CtPackageReference executablePackage = executable.getDeclaringType().getPackage();
   if (executablePackage == null || !executablePackage.getSimpleName().contains("junit")) {
     return false;
   }
   CtMethod<?> parentMethod = candidate.getParent(CtMethod.class);
   if (parentMethod == null) {
     return false;
   }
   createExecutionMethod(candidate);
   return super.isToBeProcessed(candidate);
   /*
    * boolean found = false; for (TestCase testCase : faillingTest) { if
    * (testCase.className().equals(parentClass.getQualifiedName())) { if
    * (testCase.testName().equals(parentMethod.getSimpleName())) { found =
    * true; break; } } }
    *
    * return found;
    */
 }
Exemple #5
0
  /**
   * replace assertTrue
   *
   * @param ctInvocation
   * @return
   */
  private CtStatement replaceAssertTrueFalse(boolean type, CtInvocation<?> ctInvocation) {
    List<?> arguments = ctInvocation.getArguments();
    CtIf newIf = ctInvocation.getFactory().Core().createIf();

    Object elem1 = arguments.get(0);
    if (arguments.size() > 1) {
      elem1 = arguments.get(1);
    }
    if (!type) {
      CtExpression<Boolean> condition =
          ctInvocation.getFactory().Code().createCodeSnippetExpression("!(" + elem1 + ")");
      newIf.setCondition(condition);
    } else {
      newIf.setCondition((CtExpression<Boolean>) elem1);
    }
    // newIf.setThenStatement(getFactory().Code().createCodeSnippetStatement(
    // Debug.class.getCanonicalName() + ".printPC(\"Path Condition: \")"));
    /*
     * CtBlock<Object> thenStatement = ctInvocation.getFactory().Core()
     * .createBlock(); // thenStatement.addStatement((getFactory().Code().
     * createCodeSnippetStatement("System.out.println(\"Then...\")")));
     * thenStatement.addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(" +
     * Debug.class.getCanonicalName() + ".getSolvedPC())")));
     * newIf.setThenStatement(thenStatement);
     */
    newIf.setThenStatement(createThen(ctInvocation));
    return newIf;
  }
Exemple #6
0
  private void createExecutionMethod(CtInvocation<?> ctInvocation) {
    CtClass<?> parent = ctInvocation.getParent(CtClass.class);
    if (!parent.isTopLevel()) {
      return;
    }
    if (parent.getModifiers().contains(ModifierKind.ABSTRACT)) {
      return;
    }
    CtTypeReference<String[]> typedReference = getFactory().Class().createReference(String[].class);
    if (parent.getMethod("runJPFTest", typedReference) != null) {
      return;
    }
    CtTypeReference<Object> returntypedReference = getFactory().Class().createReference("void");

    Set<ModifierKind> modifiers = new LinkedHashSet<ModifierKind>(2);
    modifiers.add(ModifierKind.PUBLIC);
    modifiers.add(ModifierKind.STATIC);

    String invocation = parent.getQualifiedName() + "(";
    if (parent.getConstructor() == null) {
      // CtTypeReference<?> superClass = parent.getSuperclass();
      if (parent.getConstructor(ctInvocation.getFactory().Class().STRING) != null) {
        invocation += "\"" + parent.getSimpleName() + "\"";
      } else {
        return;
      }
    }
    invocation += ")";

    CtBlock<?> body = getFactory().Core().createBlock();
    String bodyString = "for (String method : methods) {\n";
    bodyString += "\t\tSystem.out.println(method);\n\t\t";
    bodyString += parent.getQualifiedName() + " instance = new " + invocation + ";\n\t\t";
    if (parent.getMethod("setUp") != null) {
      bodyString += "instance.setUp();";
    }
    bodyString +=
        parent.getQualifiedName() + ".class.getMethod(method, null).invoke(instance);\n\t\t";
    bodyString += "}\n";
    body.addStatement(getFactory().Code().createCodeSnippetStatement(bodyString));
    HashSet<CtTypeReference<? extends Throwable>> exceptions =
        new HashSet<CtTypeReference<? extends Throwable>>();
    exceptions.add(getFactory().Class().createReference(Exception.class));
    CtMethod<?> method =
        getFactory()
            .Method()
            .create(
                parent,
                modifiers,
                returntypedReference,
                "runJPFTest",
                new ArrayList<CtParameter<?>>(),
                exceptions,
                body);
    getFactory().Method().createParameter(method, typedReference, "methods");
  }
Exemple #7
0
  /**
   * replace assertNotNull
   *
   * @param ctInvocation
   * @return
   */
  private CtStatement replaceAssertNotNull(CtInvocation<?> ctInvocation) {
    List<?> arguments = ctInvocation.getArguments();
    CtIf newIf = ctInvocation.getFactory().Core().createIf();

    Object elem1 = arguments.get(0);
    CtExpression<Boolean> condition =
        ctInvocation.getFactory().Code().createCodeSnippetExpression("(" + elem1 + ") != null");
    newIf.setCondition(condition);
    // newIf.setThenStatement(getFactory().Code().createCodeSnippetStatement(
    // Debug.class.getCanonicalName() + ".printPC(\"Path Condition: \")"));
    /*
     * CtBlock<Object> thenStatement = ctInvocation.getFactory().Core()
     * .createBlock(); thenStatement .addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(\"Then...\")")));
     * thenStatement.addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(" +
     * Debug.class.getCanonicalName() + ".getSolvedPC())")));
     * newIf.setThenStatement(thenStatement);
     */
    newIf.setThenStatement(createThen(ctInvocation));
    return newIf;
  }
  private static <T> void processOverridden(
      CtClass<?> mergeInto, CtClass<?> toMerge, final CtMethod<T> methodToMerge) {
    List<CtInvocation<T>> superInvocations =
        mergeInto.getElements(
            new Filter<CtInvocation<T>>() {
              @Override
              public boolean matches(CtInvocation<T> invocation) {
                if (!(invocation.getTarget() instanceof CtSuperAccess)) return false;
                CtExecutable<?> m = invocation.getExecutable().getDeclaration();
                return m != null && MethodNode.overrides((CtMethod<?>) m, methodToMerge);
              }
            });

    methodToMerge.setSimpleName(classPrefixedName(toMerge, methodToMerge));
    methodToMerge.setVisibility(PRIVATE);
    removeAnnotation(methodToMerge, Override.class);

    for (CtInvocation<T> superInvocation : superInvocations) {
      superInvocation.setTarget(null);
      superInvocation.setExecutable(methodToMerge.getReference());
    }
    add(mergeInto, methodToMerge, mergeInto::addMethod);
  }
  /**
   * Resolves all the variables used by the snippet. The ones which are initialized and the ones
   * which are not
   *
   * @return True if the context was extracted successfully
   */
  private boolean resolveDataContext(CtStatement statement) {

    needsInitialization = false;

    // Check some preconditions needed for the processor to run:
    // All variable access made inside the statement
    List<CtVariableAccess> access = statement.getElements(new TypeFilter<>(CtVariableAccess.class));

    if (statement.getElements(new TypeFilter<>(CtThisAccess.class)).size() > 0) {
      mustSerializeThiz =
          new Preconditions().checkTypeRef(statement.getParent(CtClass.class).getReference());
    }

    initialized = new HashSet<>();

    // Get all THIZ field access from all invocations used in the element
    HashSet<CtInvocation> visited = new HashSet<>();
    Stack<CtInvocation> invStack = new Stack<>();
    invStack.addAll(statement.getElements(new TypeFilter<>(CtInvocation.class)));
    while (!invStack.empty()) {
      CtInvocation inv = invStack.pop();
      if (!visited.contains(inv)) {
        visited.add(inv);
        CtBlock b;
        try {
          b = inv.getExecutable().getDeclaration().getBody();
        } catch (NullPointerException ex) {
          b = null;
        }
        if (visibility(inv) != PUBLIC && b != null) {
          for (CtFieldAccess ta :
              b.getElements(new TypeFilter<CtFieldAccess>(CtFieldAccess.class))) {
            if (ta.getTarget() instanceof CtThisAccess || ta.getTarget() == null) {
              access.add(ta);
              // initialized.add(ta);
            }
          }
          for (CtInvocation i : b.getElements(new TypeFilter<CtInvocation>(CtInvocation.class))) {
            if (!visited.contains(i)) invStack.push(i);
          }
        }
      }
    }

    access = cleanRepeatedAccesses(access);
    setAccesses(access);

    // Find initialized variables of allowed types
    ControlFlowBuilder v = new ControlFlowBuilder();
    CtMethod m = statement.getParent(CtMethod.class);
    if (m == null) return false;
    m.accept(v);
    ControlFlowGraph g = v.getResult();
    g.simplify();
    try {
      InitializedVariables vars = new InitializedVariables();
      vars.run(ControlFlowBuilder.firstNode(g, statement));

      for (CtVariableAccess a : access) {
        // A variable must be initialized if is local and is not a serializable field
        // Also if is not a constant. Constant get declared in the body of the microbenchmark
        if (isInitialized(a, statement, vars) && !isAConstant(a)) initialized.add(a);
      }
    } catch (NotFoundException e) {
      return false;
    } catch (StackOverflowError e) {
      System.out.print(g.toGraphVisText());
      throw e;
    }

    needsInitialization = initialized.size() > 0;
    if (access.size() <= 0) return true;

    int i = 0;
    int replaced = 0;
    do {
      if (i == 0) replaced = 0;
      CtVariableAccess a = access.get(i);
      if (canBeReplacedByTarget(a)) {
        CtVariableAccess targetOfA = null;
        CtTargetedExpression ta = (CtTargetedExpression) a;
        if (ta.getTarget() != null) {
          if (ta.getTarget() instanceof CtVariableAccess) {
            targetOfA = (CtVariableAccess) ta.getTarget();
          } else if (ta.getTarget() instanceof CtThisAccess) {
            mustSerializeThiz = true;
          }
        } else {
          mustSerializeThiz = true;
        }
        if (targetOfA != null) {
          if (!access.contains(targetOfA)) access.add(targetOfA);
          if (initialized.contains(a) && !initialized.contains(targetOfA))
            initialized.add(targetOfA);
        }
        access.remove(a);
        if (initialized.contains(a)) initialized.remove(a);
        replaced++;
      } else i++;
      if (i >= access.size()) i = 0;
    } while (replaced > 0 || i != 0);
    return true;
  }
Exemple #10
0
  /**
   * replace assert Equals
   *
   * @param ctInvocation
   * @return
   */
  private CtStatement replaceAssertEquals(CtInvocation<?> ctInvocation) {
    List<CtExpression<?>> arguments = ctInvocation.getArguments();
    CtIf newIf = ctInvocation.getFactory().Core().createIf();
    CtCodeSnippetExpression<Boolean> condition =
        ctInvocation.getFactory().Core().createCodeSnippetExpression();
    CtExpression<?> elem1 = arguments.get(0);
    CtExpression<?> elem2 = arguments.get(1);
    if (arguments.size() > 2
        && (elem1.getType().equals(ctInvocation.getFactory().Class().STRING)
            || elem1.getType().equals(getFactory().Class().nullType()))) {
      elem1 = arguments.get(1);
      elem2 = arguments.get(2);
    }

    boolean isNull = false;
    Class<?> classArg1 = null;
    if (elem1.toString().equals("null")) {
      isNull = true;
    } else {
      try {
        classArg1 = ((CtTypedElement<?>) elem1).getType().getActualClass();
      } catch (SpoonException e) {
        e.printStackTrace();
      }
    }
    if (isNull
        || (classArg1 != null
            && (classArg1.equals(int.class)
                || classArg1.equals(Integer.class)
                || classArg1.equals(boolean.class)
                || classArg1.equals(Boolean.class)
                || classArg1.equals(byte.class)
                || classArg1.equals(Byte.class)
                || classArg1.equals(long.class)
                || classArg1.equals(Long.class)
                || classArg1.equals(double.class)
                || classArg1.equals(Double.class)
                || classArg1.equals(float.class)
                || classArg1.equals(Float.class)
                || classArg1.equals(short.class)
                || classArg1.equals(Short.class)
                || classArg1.equals(char.class)
                || classArg1.equals(Character.class)))) {
      condition.setValue("" + elem1 + " == " + elem2 + "");
    } else {
      condition.setValue("(" + elem1 + ".equals(" + elem2 + "))");
    }
    newIf.setCondition(condition);
    // newIf.setThenStatement(getFactory().Code().createCodeSnippetStatement(
    // Debug.class.getCanonicalName() + ".printPC(\"Path Condition: \")"));
    // newIf.setThenStatement(getFactory().Code().createCodeSnippetStatement("System.out.println("+Debug.class.getCanonicalName()+".getSolvedPC())"));
    /*
     * CtBlock<Object> thenStatement = ctInvocation.getFactory().Core()
     * .createBlock(); thenStatement.addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(\"Then...\")")));
     * thenStatement.addStatement((getFactory().Code()
     * .createCodeSnippetStatement("System.out.println(" +
     * Debug.class.getCanonicalName() + ".getSolvedPC())")));
     * newIf.setThenStatement(thenStatement);
     */
    newIf.setThenStatement(createThen(ctInvocation));

    return newIf;
  }
Exemple #11
0
  @Override
  public void process(CtInvocation<?> ctInvocation) {
    // ignore no assert invocation
    // CtTypeReference<?> executableType = executable.getDeclaringType();

    // List<CtExpression<?>> parameters = ctInvocation.getArguments();
    // int parametersSize = parameters.size();
    // Class<?>[] parameterTypes = new Class<?>[parametersSize];
    // for (int i = 0; i < parametersSize; i++) {
    // parameterTypes[0] = parameters.get(i).getType().getActualClass();
    // }
    // List<CtExpression<?>> arguments = ctInvocation.getArguments();
    // CtIf newIf = ctInvocation.getFactory().Core().createIf();
    // String body = Assert.class.getCanonicalName() + "."
    // + ctInvocation.getExecutable().getSimpleName() + "(";
    // for (int i = 0; i < arguments.size(); i++) {
    // CtExpression<?> ctExpression = arguments.get(i);
    // body += ctExpression;
    // if (i < arguments.size() - 1) {
    // body += ", ";
    // }
    // }
    // body += ")";
    // CtCodeSnippetExpression<Boolean> condition =
    // ctInvocation.getFactory()
    // .Code().createCodeSnippetExpression(body);
    // newIf.setCondition(condition);
    // newIf.setElseStatement(createThen(ctInvocation));
    // ctInvocation.replace(newIf);
    // createExecutionMethod(ctInvocation);
    // return;
    // CtTry ctTry = getFactory().Core().createTry();
    // CtCatch ctCatch = getFactory().Core().createCatch();
    CtCatchVariable<Exception> localVariable =
        getFactory()
            .Code()
            .createCatchVariable(
                getFactory().Class().createReference(Exception.class),
                "exception" + (++exceptionCount));
    // ctCatch.setParameter(localVariable);
    // ctCatch.setBody(createThen(ctInvocation));
    // ctTry.addCatcher(ctCatch);
    CtBlock<Object> tryBody = ctInvocation.getFactory().Core().createBlock();
    // ctTry.setBody(tryBody);
    switch (ctInvocation.getExecutable().getSimpleName()) {
      case "assertEquals":
        ctInvocation.replace(replaceAssertEquals(ctInvocation));
        break;
      case "assertFalse":
        ctInvocation.replace(replaceAssertTrueFalse(false, ctInvocation));
        break;
      case "assertTrue":
        ctInvocation.replace(replaceAssertTrueFalse(true, ctInvocation));
        break;
      case "assertNull":
        ctInvocation.replace(replaceAssertNull(ctInvocation));
        break;
      case "assertNotNull":
        ctInvocation.replace(replaceAssertNotNull(ctInvocation));
        break;
      default:
        // System.out.println("Assert transformation not found: " +
        // ctInvocation.getExecutable().getSimpleName());
        return;
    }
    // insertAfterUnderSameParent(((getFactory().Code().createCodeSnippetStatement("System.out.println(\"Fianlly: \" + "+Debug.class.getCanonicalName()+".getSolvedPC())"))),
    // ctInvocation);
    /*if(ctInvocation.getParent(CtTry.class) == null) {
    	ctInvocation.replace(ctTry);
    } else {
    	ctInvocation.replace(tryBody);
    }*/
    /*
     * System.out.println("REPLACE: "); System.out.println(ctInvocation);
     * System.out.println("BY: "); System.out.println(ctTry);
     */
    // createExecutionMethod(ctInvocation);
  }