com.strobel.assembler.metadata.TypeReference Java Examples

The following examples show how to use com.strobel.assembler.metadata.TypeReference. 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: SingleType.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
static EType of(TypeReference tr, What what) {
    if (tr == null || tr.isPrimitive() || (what == What.SUBTYPE && Types.isObject(tr)))
        return UNKNOWN;
    TypeDefinition td = tr.resolve();
    if (td == null)
        return UNKNOWN;
    if (td.isFinal() || td.isPrimitive()) {
        if (what == What.SUBTYPE)
            what = What.EXACT;
        if (what == What.NOT)
            what = What.NOT_SUBTYPE;
    }
    TypeReference newTr = td;
    while (tr.isArray()) {
        tr = tr.getElementType();
        newTr = newTr.makeArrayType();
    }
    boolean complete = Types.hasCompleteHierarchy(td);
    return new SingleType(newTr, what, complete);
}
 
Example #2
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 #3
Source File: NumericComparison.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private JvmType getIntegralType(Expression expression) {
    TypeReference type = expression.getInferredType();
    if (type == null)
        return null;
    JvmType jvmType = type.getSimpleType();
    if (!jvmType.isIntegral())
        return null;
    if (jvmType == JvmType.Integer || jvmType == JvmType.Long)
        return jvmType;
    // Fix procyon type inference
    switch (expression.getCode()) {
    case Add:
    case Sub:
    case Div:
    case Rem:
    case Mul:
    case Shr:
    case Shl:
    case UShr:
    case Neg:
        return JvmType.Integer;
    default:
        return jvmType;
    }
}
 
Example #4
Source File: Naming.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@ClassVisitor
public void visitClass(TypeDefinition td, ClassContext cc) {
    if (td.isAnonymous() || td.isSynthetic())
        return;
    String name = td.getSimpleName();
    if (Character.isLetter(name.charAt(0)) && !Character.isUpperCase(name.charAt(0)) && name.indexOf('_') == -1) {
        cc.report("BadNameOfClass", td.isPublic() ? 0 : 15);
    }
    if (name.endsWith("Exception") && !Types.isInstance(td, "java/lang/Throwable")) {
        cc.report("BadNameOfClassException", td.isPublic() ? 0 : 15);
    }
    TypeReference superClass = td.getBaseType();
    if (superClass != null && superClass.getSimpleName().equals(name)) {
        cc.report("BadNameOfClassSameAsSuperclass", td.isPublic() ? 0 : 15, Roles.SUPERCLASS.create(superClass));
    }
    for (TypeReference iface : td.getExplicitInterfaces()) {
        if (iface.getSimpleName().equals(name)) {
            cc.report("BadNameOfClassSameAsInterface", td.isPublic() ? 0 : 15, Roles.INTERFACE.create(iface));
        }
    }
}
 
Example #5
Source File: SerializationIdiom.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@ClassVisitor
public void visitClass(TypeDefinition td, ClassContext cc) {
    isSerializable = Types.isInstance(td, "java/io/Serializable");
    if(Types.isInstance(td, "java/util/Comparator") && !td.isAnonymous() && !td.isLocalClass()
            && !isSerializable) {
        int priority = 0;
        for(FieldDefinition fd : td.getDeclaredFields()) {
            TypeReference fieldType = fd.getFieldType();
            while(fieldType.isArray())
                fieldType = fieldType.getElementType();
            if(fieldType.isPrimitive())
                continue;
            if(Types.isInstance(fieldType, "java/io/Serializable")) {
                priority+=10;
                if(priority > 20)
                    break;
            }
        }
        cc.report("ComparatorIsNotSerializable", priority, SHOULD_IMPLEMENT.create("java/io/Serializable"));
    }
}
 
Example #6
Source File: CFG.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@Override
public void addExceptional(BasicBlock block, TypeReference exception) {
    for (Entry<CatchBlock, BasicBlock> entry : catches.entrySet()) {
        for (TypeReference tr : types(entry.getKey())) {
            if (Types.isInstance(exception, tr)) {
                // Exact match: catch and return
                block.addTarget(EdgeType.FAIL, entry.getValue());
                return;
            } else if (Types.isInstance(tr, exception) || !Types.hasCompleteHierarchy(tr.resolve())) {
                // Inexact match: probably caught here or by another catch block
                block.addTarget(EdgeType.FAIL, entry.getValue());
            }
        }
    }
    super.addExceptional(block, exception);
}
 
Example #7
Source File: Types.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
public static boolean isInstance(TypeReference type, String wantedType) {
    if (type == null || type.isPrimitive())
        return false;
    if (wantedType.equals("java/lang/Object"))
        return true;
    if (type.getInternalName().equals(wantedType))
        return true;
    if (type.isArray()) {
        if(!wantedType.startsWith("["))
            return false;
        return isInstance(type.getElementType(), wantedType.substring(1));
    }
    TypeDefinition td = type.resolve();
    if (td == null)
        return false;
    for (TypeReference iface : td.getExplicitInterfaces()) {
        if (isInstance(iface, wantedType))
            return true;
    }
    TypeReference bt = td.getBaseType();
    if (bt == null)
        return false;
    return isInstance(bt, wantedType);
}
 
Example #8
Source File: AndType.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@Override
public YesNoMaybe is(TypeReference tr, boolean exact) {
    boolean hasYes = false, hasNo = false;
    for (EType type : types) {
        switch (type.is(tr, exact)) {
        case YES:
            hasYes = true;
            break;
        case NO:
            hasNo = true;
            break;
        default:
        }
    }
    if (hasYes && hasNo)
        return YesNoMaybe.MAYBE;
    if (hasYes)
        return YesNoMaybe.YES;
    if (hasNo)
        return YesNoMaybe.NO;
    return YesNoMaybe.MAYBE;
}
 
Example #9
Source File: InitializerRefersSubclass.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS, methodName="<clinit>")
public void visit(Expression expr, NodeChain nc, MethodContext mc, TypeDefinition td) {
    if(expr.getOperand() instanceof MemberReference) {
        MemberReference mr = (MemberReference) expr.getOperand();
        TypeReference tr = mr.getDeclaringType();
        TypeDefinition subType = tr == null ? null : tr.resolve();
        if (subType != null && (subType.isAnonymous() || subType.isLocalClass())) {
            subType = subType.getBaseType().resolve();
        }
        if (subType != null && !td.isEquivalentTo(subType) && Types.isInstance(subType, td) && nc
                .getLambdaMethod() == null) {
            mc.report("InitializerRefersSubclass", td.isNonPublic() || subType.isNonPublic() ? 5 : 0, expr,
                Roles.SUBCLASS.create(subType));
        }
    }
}
 
Example #10
Source File: LockProblems.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.InvokeVirtual)
        return;
    MethodReference mr = (MethodReference) expr.getOperand();
    String name = mr.getName();
    if (!Types.isObject(mr.getDeclaringType()) || (!name.equals("wait") && !name.startsWith("notify")))
        return;
    TypeReference type = ValuesFlow.reduceType(expr.getArguments().get(0));
    if (type == null || !type.getInternalName().startsWith("java/util/concurrent/"))
        return;
    TypeDefinition target = type.resolve();
    if (target == null || !target.isPublic())
        return;
    MethodDefinition replacement = findReplacement(name, target);
    if(replacement != null) {
        mc.report("IncorrectConcurrentMethod", 0, expr, TARGET.create(target), Roles.REPLACEMENT_METHOD.create(replacement));
    }
}
 
Example #11
Source File: AndType.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
@Override
public EType shrinkConstraint(TypeReference tr, boolean exact) {
    Set<SingleType> yes = new HashSet<>(), no = new HashSet<>();
    for (SingleType type : types) {
        switch (type.is(tr, exact)) {
        case YES:
            yes.add(type);
            break;
        case NO:
            no.add(type);
            break;
        default:
        }
    }
    if (!yes.isEmpty() && !no.isEmpty())
        return this;
    if (!yes.isEmpty())
        return of(yes);
    if (!no.isEmpty())
        return of(no);
    return this;
}
 
Example #12
Source File: CovariantArrays.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private boolean allImplementationsDerivedFromSubclass(Hierarchy h, TypeReference superClass,
        TypeReference subClass) {
    TypeDefinition td = superClass.resolve();
    if(td == null || (!td.isInterface() && !Flags.testAny(td.getFlags(), Flags.ABSTRACT)) )
        return false;
    for(TypeHierarchy th : h.get(td).getSubClasses()) {
        if(subClass.getInternalName().equals(th.getInternalName()))
            continue;
        if(th.hasFlag(Flags.INTERFACE) || th.hasFlag(Flags.ABSTRACT))
            continue;
        TypeReference subType = td.getResolver().lookupType(th.getInternalName());
        if(subType == null || Types.isInstance(subType, subClass))
            continue;
        return false;
    }
    return true;
}
 
Example #13
Source File: UnnecessaryInstanceOf.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
private void report(MethodContext mc, TypeReference typeRef, Expression expr, Expression cond, EdgeType deadEdge,
        EType eType, String wType) {
    int priority = 0;
    List<WarningAnnotation<?>> anno = new ArrayList<>(Arrays.asList(Roles.TARGET_TYPE.create(typeRef), ETYPE.create(
        eType.toString()), Roles.EXPRESSION.create(expr)));
    if (deadEdge != null) {
        CodeBlock deadCode = mc.findDeadCode(cond, deadEdge);
        if (deadCode != null) {
            priority = deadCode.isExceptional ? 40 : 0;
            anno.add(Roles.DEAD_CODE_LOCATION.create(mc, deadCode.startExpr));
        } else {
            priority = 20;
        }
    }
    mc.report(wType, priority, expr, anno);
}
 
Example #14
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 #15
Source File: Types.java    From huntbugs with Apache License 2.0 6 votes vote down vote up
public static TypeReference mergeTypes(TypeReference t1, TypeReference t2) {
    if (t1 == null || t2 == null)
        return null;
    if (t1 == BuiltinTypes.Null)
        return t2;
    if (t2 == BuiltinTypes.Null)
        return t1;
    if (t1.isEquivalentTo(t2))
        return t1;
    if(t1.isArray() ^ t2.isArray())
        return null;
    if(t1.isArray()) {
        TypeReference merged = mergeTypes(t1.getElementType(), t2.getElementType());
        return merged == null ? null : merged.makeArrayType();
    }
    List<TypeReference> chain1 = getBaseTypes(t1);
    List<TypeReference> chain2 = getBaseTypes(t2);
    for (int i = Math.min(chain1.size(), chain2.size()) - 1; i >= 0; i--) {
        if (chain1.get(i).equals(chain2.get(i)))
            return chain1.get(i);
    }
    return null;
}
 
Example #16
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 #17
Source File: Hierarchy.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@Override
protected void visitType(TypeDefinition td) {
    TypeHierarchy th = getOrCreate(td);
    th.flags = td.getFlags();
    link(th, td.getBaseType());
    for (TypeReference id : td.getExplicitInterfaces())
        link(th, id);
}
 
Example #18
Source File: IgnoredException.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
private static int getExceptionPriority(TypeReference tr) {
    switch(tr.getInternalName()) {
    case "java/lang/Throwable":
        return 0;
    case "java/lang/Error":
        return 1;
    case "java/lang/Exception":
        return 5;
    case "java/lang/RuntimeException":
        return 7;
    default:
        return -1;
    }
}
 
Example #19
Source File: SingleType.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@Override
public YesNoMaybe is(TypeReference other, boolean exact) {
    switch (what) {
    case EXACT:
        if (exact)
            return YesNoMaybe.of(tr.getInternalName().equals(other.getInternalName()));
        if (Types.isInstance(tr, other))
            return YesNoMaybe.YES;
        if (!complete)
            return YesNoMaybe.MAYBE;
        return YesNoMaybe.NO;
    case NOT:
        if (exact)
            return YesNoMaybe.of(!tr.getInternalName().equals(other.getInternalName()));
        return YesNoMaybe.MAYBE;
    case NOT_SUBTYPE:
        return Types.isInstance(other, tr) ? YesNoMaybe.NO : YesNoMaybe.MAYBE;
    case SUBTYPE: {
        if (exact)
            return Types.isInstance(other, tr) || !Types.hasCompleteHierarchy(other.resolve()) ? YesNoMaybe.MAYBE
                    : YesNoMaybe.NO;
        if (Types.isInstance(tr, other))
            return YesNoMaybe.YES;
        if (!complete || tr.resolve().isInterface())
            return YesNoMaybe.MAYBE;
        TypeDefinition superTd = other.resolve();
        if (superTd == null || superTd.isInterface() || Types.isInstance(other, tr) || !Types.hasCompleteHierarchy(
            superTd))
            return YesNoMaybe.MAYBE;
        return YesNoMaybe.NO;
    }
    default:
        throw new InternalError();
    }
}
 
Example #20
Source File: NodeChain.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
public boolean isInCatch(String wantedException) {
    NodeChain nc = this;
    while(nc != null) {
        if(nc.getNode() instanceof CatchBlock) {
            CatchBlock catchBlock = (CatchBlock)nc.getNode();
            TypeReference exType = catchBlock.getExceptionType();
            if(exType != null && Types.isInstance(exType, wantedException))
                return true;
            if(catchBlock.getCaughtTypes().stream().anyMatch(t -> Types.isInstance(t, wantedException)))
                return true;
        }
        nc = nc.getParent();
    }
    return false;
}
 
Example #21
Source File: ETypeAnnotator.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@Override
public ContextTypes transferState(ContextTypes src, Expression expr) {
    if (expr.getCode() == AstCode.CheckCast) {
        Expression arg = expr.getArguments().get(0);
        if (arg.getCode() == AstCode.Load) {
            Variable var = (Variable) arg.getOperand();
            EType type = EType.subType((TypeReference) expr.getOperand());
            return src.and(var, type);
        }
    }
    return src.transfer(expr);
}
 
Example #22
Source File: DecompilerLinkProvider.java    From Luyten with Apache License 2.0 5 votes vote down vote up
private String getPathAndTypeStr(TypeReference typeRef) {
	String name = typeRef.getName();
	String packageStr = typeRef.getPackageName();
	TypeReference mostOuterTypeRef = getMostOuterTypeRef(typeRef);
	String mostOuterTypeName = mostOuterTypeRef.getName();
	if (name != null && packageStr != null && mostOuterTypeName != null && name.trim().length() > 0
			&& mostOuterTypeName.trim().length() > 0) {
		String pathStr = packageStr.replaceAll("\\.", "/") + "/" + mostOuterTypeName;
		String typeStr = packageStr + "." + name.replace(".", "$");
		return pathStr + "|" + typeStr;
	}
	return null;
}
 
Example #23
Source File: CFG.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@Override
public void addExceptional(BasicBlock block, TypeReference exception) {
    List<BasicBlock> oldTargets = block.failTargets;
    block.failTargets = null;
    super.addExceptional(block, exception);
    List<BasicBlock> newTargets = block.failTargets;
    block.failTargets = oldTargets;
    newTargets.forEach(t -> block.addTarget(EdgeType.FAIL, targetEntries.computeIfAbsent(t,
        tt -> new BasicBlock())));
}
 
Example #24
Source File: Hierarchy.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
private void link(TypeHierarchy th, TypeReference superType) {
    if (superType == null || Types.isObject(superType))
        return;
    TypeHierarchy superTh = getOrCreate(superType);
    th.superClasses.add(superTh);
    superTh.subClasses.add(th);
}
 
Example #25
Source File: OrType.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@Override
public YesNoMaybe is(TypeReference tr, boolean exact) {
    boolean hasYes = false, hasNo = false, hasMaybe = false;
    for (EType type : types) {
        YesNoMaybe cur = type.is(tr, exact);
        switch (cur) {
        case YES:
            hasYes = true;
            break;
        case NO:
            hasNo = true;
            break;
        case MAYBE:
            hasMaybe = true;
            break;
        default:
            throw new InternalError();
        }
    }
    if (hasMaybe || hasYes && hasNo)
        return YesNoMaybe.MAYBE;
    if (hasYes)
        return YesNoMaybe.YES;
    if (hasNo)
        return YesNoMaybe.NO;
    return YesNoMaybe.MAYBE;
}
 
Example #26
Source File: Equi.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
private static boolean equiTypes(TypeReference left, TypeReference right) {
    if (left == null)
        return right == null;
    if (right == null)
        return false;
    return left.getInternalName().equals(right.getInternalName());
}
 
Example #27
Source File: Types.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
public static synchronized TypeDefinition lookupJdkType(String internalName) {
    TypeReference tr = ms.lookupType(internalName);
    if (tr == null) {
        throw new InternalError("Unable to lookup type " + internalName);
    }
    TypeDefinition td = tr.resolve();
    if (td == null) {
        throw new InternalError("Unable to resolve type " + internalName);
    }
    return td;
}
 
Example #28
Source File: Types.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
public static List<TypeReference> getBaseTypes(TypeReference input) {
    List<TypeReference> result = new ArrayList<>();
    while (true) {
        result.add(input);
        TypeDefinition td = input.resolve();
        if (td == null)
            break;
        input = td.getBaseType();
        if (input == null)
            break;
    }
    Collections.reverse(result);
    return result;
}
 
Example #29
Source File: UncalledPrivateMethod.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
@Override
protected void visitType(TypeDefinition td) {
    TypeReference tr = td.getDeclaringType();
    if(tr == null) return;
    TypeDefinition outer = tr.resolve();
    if(outer == null || !outer.isAnonymous()) return;
    for(MethodDefinition md : td.getDeclaredMethods()) {
        extractCalls(md, mr -> {
            mis.add(new MemberInfo(mr));
            return true;
        });
    }
}
 
Example #30
Source File: DecompilerLinkProvider.java    From Luyten with Apache License 2.0 5 votes vote down vote up
private TypeReference getMostOuterTypeRef(TypeReference typeRef) {
	int maxDecraringDepth = typeRef.getFullName().split("(\\.|\\$)").length;
	for (int i = 0; i < maxDecraringDepth; i++) {
		TypeReference declaringTypeRef = typeRef.getDeclaringType();
		if (declaringTypeRef == null) {
			break;
		} else {
			typeRef = declaringTypeRef;
		}
	}
	if (typeRef.getName().contains("$")) {
		return getMostOuterTypeRefBySlowLookuping(typeRef);
	}
	return typeRef;
}