JD.CAST.SUSP.MUST
ClassCastException for different types
JD.CAST.SUSP.MUST is triggered when an object is checked with an instance of operator for type A and then cast to type B, where types A and B are unrelated. That is, Klocwork cannot find that A is a subtype of B, or that B is a subtype of A.
Vulnerability and risk
This is usually an error, because cast is not safe; the object can actually be another type than B. In some cases, this error can produce false positives when the path from instanceof to cast is incompatible.
Mitigation and prevention
Choose which type you actually want to use--A or B--and either change the typecast to A, or check the instanceof to B.
Vulnerable code example 1
public class Test {
void badCast(Object o) {
if (o instanceof String) {
Number n = (Number) o;
System.out.println("bad cast");
}
}
}
JD.CAST.SUSP.MUST is reported on line 4; the object is known because it is being checked with the 'instanceof <Type> construction.
Vulnerable code example 2
void setValue(Object a, Object value) {
if (a instanceof String) {
StringBuffer b = (StringBuffer) a;
b.append("=");
b.append(value);
}
}
JD.CAST.SUSP.MUST is reported for cast on line 12: Suspicious cast of 'a' from 'String' to 'StringBuffer', where types are unrelated.-> 11: a instanceof String-> 12: (StringBuffer)a.