S2259: Null pointers should not be dereferenced

java

(Jiaoyang Ma) #1
  • versions used (SonarQube, Scanner, language analyzer)
    SonarQube Version 6.7.2 (build 37468)
    SonarJava Version 5.9.2 (build 16552)

  • minimal code sample to reproduce (with analysis parameter, and potential instructions to compile).

Object obj = someFunction();
CheckUtils.checkNotNull(obj);
obj.run(); // S2259

Our CheckUtils do something like this:

if (obj == null) {
    throw new XxxException();
}

We can see that at obj.run(), obj can not be null, but is pointed out by Sonar.
How can we let this pass?

Thanks,
Tsubasa


(Michael Gumowski) #2

Hello @tsubasa,

Thanks for the feedback. This is indeed an obvious False Positive from the rule.

Just a few words about the rule now. Rule squid:S2259 is based on a Symbolic Execution (SE) engine. This engine is validating execution paths and checking for non-null values or null-check along the way, exploring all the possibilities. Unfortunately, its actual state also has some limitations, like the one you are hitting here.

As for today, the SE engine is able to explore non-overridable methods (static, for instance), when declared in the same file being analyzed. When exploring such methods, the engine then deduces behaviors regarding null-checking (among other things). The SonarJava SE engine is however, by default, not configured to explore methods declared in other files (in your case, your utility class CheckUtils).

While the engine is in practice already able to explore code from other files if needed (relying solely on bytecode), we restrain this approach to a limited set of well-known methods from standard libraries, for which we know that behaviors are correctly produced. This cross-file approach analysis can be quite resource-consuming, and we are not ready to openly enable the feature.

Now, you can find the list of whitelisted methods here. Maybe one of these methods is already doing what your methods is doing, and could be considered as replacement.

For the time being, I would unfortunately recommend to “mark as False Positive” the issue.

Cheers,
Michael


(Jiaoyang Ma) #3

Hi Michael,

Thanks for your relpy.
Cause we need throw our own Runtime Exception, well-known methods won’t help.
We resolved it by adding our tools’ path in the white list, and repackaging it.
Things go fine now.
We really appreciate your help.

Thanks,
Tsubasa


(Eivind Elseth) #4

Hi @Michael!
I’m very new to sonar, is there a way to add methods to the whitelist?