com.strobel.assembler.metadata.MethodReference Java Examples

The following examples show how to use com.strobel.assembler.metadata.MethodReference. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NoRuntimeRetention.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc, DeclaredAnnotations da) {
    if (expr.getCode() == AstCode.InvokeVirtual && expr.getArguments().size() == 2) {
        MethodReference mr = (MethodReference) expr.getOperand();
        if ((mr.getDeclaringType().getInternalName().startsWith("java/lang/reflect/") || mr.getDeclaringType()
                .getInternalName().equals("java/lang/Class")) && mr.getName().contains("Annotation")) {
            Object constant = Nodes.getConstant(expr.getArguments().get(1));
            if (constant instanceof TypeReference) {
                TypeReference tr = (TypeReference) constant;
                DeclaredAnnotation annot = da.get(tr);
                if (annot != null && annot.getPolicy() != RetentionPolicy.RUNTIME) {
                    mc.report("AnnotationNoRuntimeRetention", 0, expr, ANNOTATION.create(tr));
                }
            }
        }
    }
}
 
Example #2
Source File: NumericComparison.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private void checkRem2Eq1(MethodContext mc, JvmType jvmType, AstCode code, Expression arg, long constant) {
    if (constant == 1 && (code == AstCode.CmpEq || code == AstCode.CmpNe) && arg.getCode() == AstCode.Rem && Integer
            .valueOf(2).equals(Nodes.getConstant(arg.getArguments().get(1)))) {
        Expression remInput = Exprs.getChild(arg, 0);
        if (remInput.getCode() == AstCode.InvokeStatic) {
            MethodReference mr = (MethodReference) remInput.getOperand();
            if (mr.getName().equals("abs") && mr.getDeclaringType().getInternalName().equals("java/lang/Math")) {
                return;
            }
        }
        if (getExpressionRange(jvmType, remInput).minValue < 0) {
            mc.report("CheckForOddnessFailsForNegative", 0, arg, Roles.OPERATION.create(code),
                Roles.REPLACEMENT_STRING.create(code == AstCode.CmpEq ? "!=" : "=="));
        }
    }
}
 
Example #3
Source File: NegativeRemainder.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    switch(expr.getCode()) {
    case StoreElement:
    case LoadElement:
        check(Exprs.getChild(expr, 1), mc);
        break;
    case InvokeInterface:
    case InvokeVirtual:
        MethodReference mr = (MethodReference) expr.getOperand();
        if(Types.isInstance(mr.getDeclaringType(), "java/util/List")) {
            if((mr.getName().equals("add") || mr.getName().equals("set")) && mr.getSignature().startsWith("(I") ||
                    (mr.getName().equals("get") || mr.getName().equals("remove")) && mr.getSignature().startsWith("(I)"))
                check(Exprs.getChild(expr, 1), mc);
        }
        break;
    default:
    }
}
 
Example #4
Source File: ArrayRangeCheck.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private static long getMaxLength(Expression expression) {
    return ValuesFlow.<Long>reduce(expression, expr -> {
        switch (expr.getCode()) {
        case InitArray:
            return (long) expr.getArguments().size();
        case NewArray: {
            Object length = Nodes.getConstant(expr.getArguments().get(0));
            if (length instanceof Integer)
                return (long) (Integer) length;
            break;
        }
        case InvokeVirtual: {
            MethodReference mr = (MethodReference) expr.getOperand();
            if (mr.getName().equals("clone") && mr.getErasedSignature().startsWith("()")) {
                return getMaxLength(Exprs.getChild(expr, 0));
            }
            break;
        }
        case CheckCast:
            return getMaxLength(Exprs.getChild(expr, 0));
        default:
            break;
        }
        return IMPOSSIBLE_ARRAY_LENGTH;
    }, Math::max, len -> len == IMPOSSIBLE_ARRAY_LENGTH);
}
 
Example #5
Source File: ConstAnnotator.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private Integer getArrayLength(Expression expression) {
    return ValuesFlow.reduce(expression, e -> {
        switch(e.getCode()) {
        case InvokeVirtual: {
            MethodReference mr = (MethodReference) e.getOperand();
            if (mr.getName().equals("clone") && mr.getErasedSignature().startsWith("()")) {
                return getArrayLength(Exprs.getChild(e, 0));
            }
            return null;
        }
        case CheckCast:
            return getArrayLength(Exprs.getChild(e, 0));
        case InitArray:
            return e.getArguments().size();
        case NewArray:
            Object constant = getValue(e.getArguments().get(0));
            if(constant instanceof Integer)
                return (Integer)constant;
            return null;
        default:
            return null;
        }
    }, (a, b) -> Objects.equals(a, b) ? a : null, Objects::isNull);
}
 
Example #6
Source File: IncorrectVarArg.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    if(expr.getOperand() instanceof MethodReference) {
        MethodReference mr = (MethodReference) expr.getOperand();
        if(mr.getErasedSignature().contains("[Ljava/lang/Object;)")) {
            Expression lastArg = expr.getArguments().get(expr.getArguments().size()-1);
            if(lastArg.getCode() == AstCode.InitArray && lastArg.getArguments().size() == 1) {
                TypeReference nested = lastArg.getArguments().get(0).getInferredType();
                if(nested != null && nested.isArray() && nested.getElementType().isPrimitive()) {
                    int priority = 0;
                    if(!highPriority(mr)) {
                        priority = 10;
                        MethodDefinition md = mr.resolve();
                        if(md == null) {
                            priority = 20;
                        } else if(!md.isVarArgs())
                            return;
                    }
                    mc.report("PrimitiveArrayPassedAsVarArg", priority, lastArg, Roles.CALLED_METHOD.create(mr),
                        Roles.ARRAY_TYPE.create(nested));
                }
            }
        }
    }
}
 
Example #7
Source File: EqualsContract.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private static boolean isComparison(Expression expr) {
    switch(expr.getCode()) {
    case CmpEq:
    case CmpNe:
        return true;
    case InvokeVirtual:
        return Methods.isEqualsMethod((MethodReference) expr.getOperand());
    case InvokeStatic: {
        MethodReference mr = (MethodReference) expr.getOperand();
        TypeReference tr = mr.getDeclaringType();
        return (mr.getName().equals("equals") || mr.getName().equals("deepEquals")) &&
                (Types.is(tr, Arrays.class) || Types.is(tr, Objects.class));
    }
    default:
        return false;
    }
}
 
Example #8
Source File: Nodes.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
public static boolean isUnboxing(Node node) {
    if (!isOp(node, AstCode.InvokeVirtual))
        return false;
    MethodReference ref = (MethodReference) ((Expression) node).getOperand();
    TypeReference type = ref.getDeclaringType();
    if (type.getInternalName().equals("java/lang/Double") && ref.getName().equals("doubleValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Integer") && ref.getName().equals("intValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Long") && ref.getName().equals("longValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Boolean") && ref.getName().equals("booleanValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Short") && ref.getName().equals("shortValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Character") && ref.getName().equals("charValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Float") && ref.getName().equals("floatValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Byte") && ref.getName().equals("byteValue"))
        return true;
    return false;
}
 
Example #9
Source File: RegexProblems.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private void checkRegexp(MethodContext mc, Expression regexExpr, int flags) {
    if((flags & Pattern.LITERAL) == 0) {
        if(regexExpr.getCode() == AstCode.GetStatic) {
            FieldReference fr = (FieldReference) regexExpr.getOperand();
            if(fr.getName().equals("separator") && fr.getDeclaringType().getInternalName().equals("java/io/File")) {
                mc.report("RegexFileSeparator", 0, regexExpr);
            }
        } else if(regexExpr.getCode() == AstCode.InvokeVirtual) {
            MethodReference mr = (MethodReference)regexExpr.getOperand();
            if(mr.getName().equals("getSeparator") && mr.getDeclaringType().getInternalName().equals("java/nio/file/FileSystem")) {
                mc.report("RegexFileSeparator", 0, regexExpr);
            }
        }
    }
    Object regexObj = Nodes.getConstant(regexExpr);
    if(!(regexObj instanceof String)) {
        return;
    }
    String regex = (String)regexObj;
    try {
        Pattern.compile(regex, flags);
    } catch (PatternSyntaxException e) {
        mc.report("RegexBadSyntax", 0, regexExpr, Roles.REGEXP.create(regex), ERROR_MESSAGE.create(e.getMessage()));
    }
}
 
Example #10
Source File: SelfComputation.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    if ((expr.getCode() == AstCode.And || expr.getCode() == AstCode.Or || expr.getCode() == AstCode.Xor
        || expr.getCode() == AstCode.Sub || expr.getCode() == AstCode.Div || expr.getCode() == AstCode.Rem)
        && sameArgs(expr)) {
        mc.report("SelfComputation", 0, expr.getArguments().get(0), Roles.OPERATION.create(expr));
    } else if (expr.getCode().isComparison() && sameArgs(expr)) {
        JvmType type = expr.getArguments().get(0).getInferredType().getSimpleType();
        if ((expr.getCode() != AstCode.CmpEq && expr.getCode() != AstCode.CmpNe)
            || (type != JvmType.Double && type != JvmType.Float))
            mc.report("SelfComparison", 0, expr.getArguments().get(0), Roles.OPERATION.create(expr.getCode()));
    } else if (expr.getCode() == AstCode.InvokeVirtual
        && Methods.isEqualsMethod((MethodReference) expr.getOperand()) && sameArgs(expr) &&
        !Exprs.isAssertion(expr)) {
        mc.report("SelfEquals", 0, expr.getArguments().get(0));
    }
}
 
Example #11
Source File: InfiniteRecursion.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private boolean selfCall(Expression expr, MethodDefinition md) {
    if (!(expr.getOperand() instanceof MethodReference))
        return false;
    MethodReference mr = (MethodReference) expr.getOperand();
    if (!mr.isEquivalentTo(md))
        return false;
    switch (expr.getCode()) {
    case InvokeStatic:
        return md.isStatic();
    case InitObject:
    case InvokeSpecial:
        return md.isConstructor();
    case InvokeVirtual:
    case InvokeInterface:
        return !md.isStatic() && Exprs.isThis(expr.getArguments().get(0));
    default:
        return false;
    }
}
 
Example #12
Source File: KnownComparison.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    if (expr.getCode().isComparison() || (expr.getCode() == AstCode.InvokeVirtual && Methods.isEqualsMethod(
        (MethodReference) expr.getOperand()))) {
        Object result = Nodes.getConstant(expr);
        if (result instanceof Boolean && !Exprs.isAssertion(expr)) {
            Object left = Nodes.getConstant(expr.getArguments().get(0));
            Object right = Nodes.getConstant(expr.getArguments().get(1));
            if (left != null && right != null) {
                CodeBlock deadCode = mc.findDeadCode(expr, (boolean) result ? EdgeType.FALSE : EdgeType.TRUE);
                if (deadCode == null) {
                    mc.report("ResultOfComparisonIsStaticallyKnown", 0, expr, Roles.EXPRESSION.create(expr),
                        LEFT_OPERAND.createFromConst(left), RIGHT_OPERAND.createFromConst(right), Roles.OPERATION
                                .create(expr), RESULT.create(result.toString()));
                } else if (!deadCode.isExceptional) {
                    mc.report("ResultOfComparisonIsStaticallyKnownDeadCode", 0, expr,
                        Roles.EXPRESSION.create(expr), LEFT_OPERAND.createFromConst(left), RIGHT_OPERAND
                                .createFromConst(right), Roles.OPERATION.create(expr), Roles.DEAD_CODE_LOCATION.create(
                            mc, deadCode.startExpr), RESULT.create(result.toString()));
                }
            }
        }
    }
}
 
Example #13
Source File: AbandonedStream.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS, minVersion=8)
public void visit(Expression expr, MethodContext mc) {
    if(expr.getCode() == AstCode.InvokeInterface) {
        MethodReference mr = (MethodReference) expr.getOperand();
        if(mr.getReturnType().getPackageName().equals("java.util.stream")
                && Types.isBaseStream(mr.getReturnType())) {
            // intermediate stream operation
            if(mc.isAnnotated() && !Inf.BACKLINK.findTransitiveUsages(expr, true).findAny().isPresent()) {
                // .parallel()/.sequential()/.onClose()/.unordered() excluded as may return itself
                if(Types.is(mr.getReturnType(), BaseStream.class)) {
                    mc.report("StreamMethodMayNotReturnItself", 0, expr);
                } else {
                    mc.report("AbandonedStream", 0, expr);
                }
            }
        }
    }
}
 
Example #14
Source File: Nodes.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
public static boolean isBoxing(Node node) {
    if (!isOp(node, AstCode.InvokeStatic))
        return false;
    MethodReference ref = (MethodReference) ((Expression) node).getOperand();
    if (!ref.getName().equals("valueOf"))
        return false;
    TypeReference type = ref.getDeclaringType();
    if (type.getInternalName().equals("java/lang/Double") && ref.getSignature().equals("(D)Ljava/lang/Double;"))
        return true;
    if (type.getInternalName().equals("java/lang/Integer") && ref.getSignature().equals("(I)Ljava/lang/Integer;"))
        return true;
    if (type.getInternalName().equals("java/lang/Long") && ref.getSignature().equals("(J)Ljava/lang/Long;"))
        return true;
    if (type.getInternalName().equals("java/lang/Boolean") && ref.getSignature().equals("(Z)Ljava/lang/Boolean;"))
        return true;
    if (type.getInternalName().equals("java/lang/Short") && ref.getSignature().equals("(S)Ljava/lang/Short;"))
        return true;
    if (type.getInternalName().equals("java/lang/Character") && ref.getSignature().equals(
        "(C)Ljava/lang/Character;"))
        return true;
    if (type.getInternalName().equals("java/lang/Float") && ref.getSignature().equals("(F)Ljava/lang/Float;"))
        return true;
    if (type.getInternalName().equals("java/lang/Byte") && ref.getSignature().equals("(B)Ljava/lang/Byte;"))
        return true;
    return false;
}
 
Example #15
Source File: SqlBadArgument.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    if(expr.getCode() == AstCode.InvokeInterface) {
        MethodReference mr = (MethodReference) expr.getOperand();
        String warningType = null;
        if (mr.getDeclaringType().getInternalName().equals("java/sql/ResultSet")
            && (mr.getName().startsWith("get") || mr.getName().startsWith("update"))
            && firstParameterIsInt(mr)) {
            warningType = "BadResultSetArgument";
        } else if(mr.getDeclaringType().getInternalName().equals("java/sql/PreparedStatement") &&
                mr.getName().startsWith("set") && firstParameterIsInt(mr)) {
            warningType = "BadPreparedStatementArgument";
        }
        if(warningType != null) {
            Expression arg = expr.getArguments().get(1);
            Object constant = Nodes.getConstant(arg);
            if (Integer.valueOf(0).equals(constant)) {
                mc.report(warningType, 0, expr);
            } else if (ValuesFlow.reduce(arg, e -> Integer.valueOf(0).equals(Nodes.getConstant(e)),
                Boolean::logicalOr, Boolean::booleanValue)) {
                mc.report(warningType, 20, expr);
            }
        }
    }
}
 
Example #16
Source File: RandomUsage.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression node, MethodContext ctx) {
    if (node.getCode() == AstCode.D2I) {
        Expression child = Exprs.getChild(node, 0);
        if (isRandomDouble(child)) {
            ctx.report("RandomDoubleToInt", 0, child, getReplacement(((MethodReference) child.getOperand())
                    .getDeclaringType().getInternalName()));
        }
        Expression mul = node.getArguments().get(0);
        if (mul.getCode() == AstCode.Mul) {
            mul.getArguments().stream().filter(this::isRandomDouble).findFirst().ifPresent(
                expr -> {
                    int priority = 0;
                    MethodReference mr = (MethodReference) expr.getOperand();
                    String type = mr.getDeclaringType().getInternalName();
                    if (type.equals("java/lang/Math")) {
                        priority = 20;
                    }
                    ctx.report("RandomNextIntViaNextDouble", priority, node, Roles.CALLED_METHOD.create(mr),
                        getReplacement(type));
                });
        }
    }
    checkOnlyOnce(node, ctx);
}
 
Example #17
Source File: UncalledPrivateMethod.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
static void extractCalls(MethodDefinition md, Predicate<MethodReference> action) {
    MethodBody body = md.getBody();
    if(body == null)
        return;
    for(Instruction inst : body.getInstructions()) {
        for(int i=0; i<inst.getOperandCount(); i++) {
            Object operand = inst.getOperand(i);
            if(operand instanceof MethodReference) {
                if(!action.test((MethodReference)operand))
                    return;
            }
            if(operand instanceof DynamicCallSite) {
                MethodHandle mh = Nodes.getMethodHandle((DynamicCallSite) operand);
                if(mh != null) {
                    if(!action.test(mh.getMethod()))
                        return;
                }
            }
        }
    }
}
 
Example #18
Source File: SyncGetClass.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor
public void visit(Node node, MethodContext mc, TypeHierarchy th, TypeDefinition td) {
    if(node instanceof TryCatchBlock) {
        Expression syncObject = Nodes.getSyncObject((TryCatchBlock) node);
        if(syncObject != null) {
            if(syncObject.getCode() == AstCode.InvokeVirtual && Methods.isGetClass((MethodReference) syncObject.getOperand())
                    && Exprs.isThis(Exprs.getChild(syncObject, 0))) {
                int priority = 0;
                if(th != null && !th.hasSubClasses())
                    priority += 10;
                if(Nodes.find(node, n -> isStaticFieldAccess(n, td)) == null)
                    priority += 15;
                mc.report("SyncOnGetClass", priority, syncObject);
            }
        }
    }
}
 
Example #19
Source File: ToArrayDowncast.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    if (expr.getCode() != AstCode.CheckCast)
        return;
    TypeReference targetType = (TypeReference) expr.getOperand();
    if (!targetType.isArray() || Types.isObject(targetType.getElementType()))
        return;
    Expression arg = Exprs.getChild(expr, 0);
    if (arg.getCode() != AstCode.InvokeVirtual && arg.getCode() != AstCode.InvokeInterface)
        return;
    MethodReference mr = (MethodReference) arg.getOperand();
    if (!mr.getName().equals("toArray") || !mr.getSignature().equals("()[Ljava/lang/Object;"))
        return;
    Expression target = Exprs.getChild(arg, 0);
    if (!Types.isInstance(target.getInferredType(), "java/util/Collection"))
        return;
    mc.report("ImpossibleToArrayDowncast", 0, target, Roles.TARGET_TYPE.create(targetType),
        TARGET_ELEMENT_TYPE.create(targetType.getElementType()));
}
 
Example #20
Source File: CheckReturnValue.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS)
public void visit(Expression expr, NodeChain nc, MethodContext mc) {
    if(nc.getNode() instanceof Expression)
        return;
    if(expr.getCode() == AstCode.InvokeVirtual || expr.getCode() == AstCode.InvokeInterface) {
        MethodReference mr = (MethodReference) expr.getOperand();
        boolean skipMethod = mr.getName().equals("skip") && mr.getSignature().equals("(J)J") ||
                mr.getName().equals("skipBytes") && mr.getSignature().equals("(I)I");
        boolean readMethod = mr.getName().equals("read") && (mr.getSignature().equals("([B)I") ||
                mr.getSignature().equals("([BII)I") || mr.getSignature().equals("([C)I") ||
                mr.getSignature().equals("([CII)I"));
        if(skipMethod || readMethod) {
            TypeReference type = ValuesFlow.reduceType(expr.getArguments().get(0));
            if(type == null)
                type = mr.getDeclaringType();
            if(!isInputStream(type))
                return;
            if(skipMethod && Types.isInstance(type, "javax/imageio/stream/ImageInputStream"))
                return;
            int priority = 0;
            if(!Types.isInstance(type, "java/io/BufferedInputStream"))
                priority += 15;
            mc.report(skipMethod ? "ReturnValueOfSkip" : "ReturnValueOfRead", priority, expr);
        }
    }
}
 
Example #21
Source File: FinalizerContract.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@AstVisitor
public void visit(Node node, MethodContext mc, MethodDefinition md) {
    if (Nodes.isOp(node, AstCode.InvokeVirtual) && isFinalizer((MethodReference) ((Expression) node)
            .getOperand())) {
        mc.report("FinalizeInvocation", isFinalizer(md) ? 10 : 0, node);
    }
}
 
Example #22
Source File: MinValueHandling.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
private void checkAbs(MethodContext mc, Node body, Node parent, int priority, boolean forget) {
	if(Nodes.isOp(body, AstCode.InvokeStatic)) {
	    MethodReference absCandidate = (MethodReference)((Expression)body).getOperand();
	    if(absCandidate.getName().equals("abs") && absCandidate.getDeclaringType().getInternalName().equals("java/lang/Math")) {
	        Node source = Nodes.getChild(body, 0);
	        if(Nodes.isOp(source, AstCode.InvokeVirtual)) {
	            MethodReference sourceCall = (MethodReference)((Expression)source).getOperand();
	            String methodName = sourceCall.getName();
				String methodSig = sourceCall.getSignature();
				if((methodName.equals("nextInt") || methodName.equals("nextLong"))
	                    && (methodSig.equals("()I") || methodSig.equals("()J"))
	                    && Types.isRandomClass(sourceCall.getDeclaringType())) {
				    if(methodSig.equals("()J"))
				        priority += 20;
				    if(Nodes.isOp(parent, AstCode.Neg)) {
				        return;
				    }
				    if(forget)
				        mc.forgetLastBug();
				    mc.report("AbsoluteValueOfRandomInt", priority, source);
	            } else if(Methods.isHashCodeMethod(sourceCall)) {
	                if(Nodes.isOp(parent, AstCode.TernaryOp)) {
	                    Node comparison = Nodes.getChild(parent, 0);
	                    Integer minValue = Integer.MIN_VALUE;
						if(Nodes.isComparison(comparison) && (minValue.equals(Nodes.getConstant(Nodes.getChild(comparison, 0))) ||
	                            minValue.equals(Nodes.getConstant(Nodes.getChild(comparison, 1)))))
	                        return;
	                }
	                if(Nodes.isOp(parent, AstCode.Neg)) {
	                    return;
	                }
                       if(forget)
                           mc.forgetLastBug();
	                mc.report("AbsoluteValueOfHashCode", priority, source);
	            }
	        }
	    }
	}
}
 
Example #23
Source File: MethodTranslator.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private ExecutableElement findMethod(String name, TypeMirror type, MethodReference methodDef) {
  TypeElement typeElement = (TypeElement) parserEnv.typeUtilities().asElement(type);
  String signature = methodDef.getSignature();
  String erasedSignature = methodDef.getErasedSignature();
  for (Element e : typeElement.getEnclosedElements()) {
    if (e.getKind() == ElementKind.METHOD && e.getSimpleName().contentEquals(name)) {
      String sig = typeUtil.getReferenceSignature((ExecutableElement) e);
      if (sig.equals(signature) || sig.equals(erasedSignature)) {
        return (ExecutableElement) e;
      }
    }
  }
  throw new AssertionError("failed method lookup: " + type + " " + name + signature);
}
 
Example #24
Source File: MethodContext.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
public void report(String warning, int priority, Node node, Collection<WarningAnnotation<?>> annotations) {
    WarningType wt = resolveWarningType(warning, priority);
    if(wt == null)
        return;
    List<WarningAnnotation<?>> anno = new ArrayList<>();
    anno.addAll(cc.getTypeSpecificAnnotations());
    anno.addAll(mdata.getMethodSpecificAnnotations());
    Location loc = getLocation(node);
    if (node instanceof Expression) {
        Expression expr = (Expression) node;
        Object operand = expr.getOperand();
        if (operand instanceof Variable) {
            anno.add(WarningAnnotation.forVariable((Variable) operand));
            operand = ValuesFlow.getSource(expr).getOperand();
        }
        if (operand instanceof FieldReference && !annotations.stream().anyMatch(wa -> wa
            .getRole() == Roles.FIELD)) {
            anno.add(Roles.FIELD.create((FieldReference) operand));
        }
        if (operand instanceof MethodReference && !annotations.stream().anyMatch(wa -> wa
                .getRole() == Roles.CALLED_METHOD)) {
            MethodReference mr = (MethodReference) operand;
            anno.add(Roles.CALLED_METHOD.create(mr));
        }
    }
    anno.addAll(annotations);
    WarningInfo info = new WarningInfo(wt, priority, loc, anno);
    if (lastWarning == null) {
        lastWarning = info;
    } else if (!lastWarning.tryMerge(info)) {
        reportWarning(lastWarning.build());
        lastWarning = info;
    }
}
 
Example #25
Source File: UnusedParameter.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
private Expression findOverloadCall(MethodDefinition md, Block block) {
    return (Expression)Nodes.find(block, node -> {
        if (Nodes.isOp(node, md.isConstructor() ? AstCode.InvokeSpecial
                : md.isStatic() ? AstCode.InvokeStatic : AstCode.InvokeVirtual)) {
            Expression expr = (Expression) node;
            MethodReference mr = (MethodReference) expr.getOperand();
            if (mr.getDeclaringType().isEquivalentTo(md.getDeclaringType()) && mr.getName().equals(md.getName())
                && !mr.getSignature().equals(md.getSignature())) {
                return true;
            }
        }
        return false;
    });
}
 
Example #26
Source File: Internationalization.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    if(expr.getCode() == AstCode.InvokeVirtual || expr.getCode() == AstCode.InitObject) {
        MethodReference mr = (MethodReference) expr.getOperand();
        if(mr.getDeclaringType().getInternalName().equals("java/lang/String") && mr.getSignature().equals("()Ljava/lang/String;")
                && (mr.getName().equals("toUpperCase") || mr.getName().equals("toLowerCase"))) {
            mc.report("ConvertCaseWithDefaultLocale", 0, expr, Roles.REPLACEMENT_METHOD.create(mr.getDeclaringType()
                    .getInternalName(), mr.getName(), "(Ljava/util/Locale;)Ljava/lang/String;"));
        } else {
            MemberInfo mi = new MemberInfo(mr);
            if(defEncodingMethods.containsKey(mi)) {
                if(!expr.getArguments().isEmpty()) {
                    Expression arg = Exprs.getChild(expr, 0);
                    if(arg.getCode() == AstCode.GetStatic) {
                        FieldReference fr = (FieldReference) arg.getOperand();
                        if(fr.getDeclaringType().getInternalName().equals("java/lang/System")) {
                            // Usages like new Formatter(System.out) are considered ok
                            return;
                        }
                    }
                }
                MemberInfo replacement = defEncodingMethods.get(mi);
                if(replacement != null) {
                    mc.report("MethodReliesOnDefaultEncoding", replacement.getSignature().contains("Charset") ? 0
                            : 3, expr, Roles.REPLACEMENT_METHOD.create(replacement));
                } else {
                    mc.report("MethodReliesOnDefaultEncoding", 10, expr);
                }
            }
        }
    }
}
 
Example #27
Source File: Methods.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
public static MethodDefinition findSuperMethod(MethodReference mr) {
    MethodDefinition md = mr.resolve();
    if(md == null)
        return null;
    TypeDefinition td = md.getDeclaringType();
    return findSuperMethod(td, new MemberInfo(resolveToBridge(md)));
}
 
Example #28
Source File: NewGetClass.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS)
public void visit(Expression node, MethodContext ctx) {
    if(node.getCode() == AstCode.InvokeVirtual) {
        MethodReference ref = (MethodReference) node.getOperand();
        if (Methods.isGetClass(ref) && node.getArguments().get(0).getCode() == AstCode.InitObject) {
            ctx.report("NewForGetClass", 0, node, OBJECT_TYPE.create(ref.getDeclaringType()));
        }
    }
}
 
Example #29
Source File: AtomicConcurrent.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
private boolean isGetOrContains(Expression self, Expression key, Expression call) {
    if (call.getCode() != AstCode.InvokeVirtual && call.getCode() != AstCode.InvokeInterface)
        return false;
    MethodReference mr = (MethodReference) call.getOperand();
    if (!mr.getName().equals("containsKey") && !mr.getName().equals("get"))
        return false;
    if (!Nodes.isEquivalent(self, call.getArguments().get(0)))
        return false;
    if (!Nodes.isEquivalent(key, call.getArguments().get(1)))
        return false;
    return true;
}
 
Example #30
Source File: AppendObjectOutputStream.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
private static boolean isAppendOutput(Expression expr) {
    if (expr.getCode() == AstCode.InitObject) {
        MethodReference ctor = (MethodReference) expr.getOperand();
        if (ctor.getDeclaringType().getInternalName().equals("java/io/FileOutputStream")
            && (ctor.getSignature().equals("(Ljava/io/File;Z)V") || ctor.getSignature().equals(
                "(Ljava/lang/String;Z)V"))) {
            Object constant = Nodes.getConstant(expr.getArguments().get(1));
            if (constant instanceof Integer && ((Integer) constant).intValue() == 1) {
                return true;
            }
        }
    }
    return false;
}