Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1 | //== Nullabilityhecker.cpp - Nullability checker ----------------*- C++ -*--==// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This checker tries to find nullability violations. There are several kinds of |
| 11 | // possible violations: |
| 12 | // * Null pointer is passed to a pointer which has a _Nonnull type. |
| 13 | // * Null pointer is returned from a function which has a _Nonnull return type. |
| 14 | // * Nullable pointer is passed to a pointer which has a _Nonnull type. |
| 15 | // * Nullable pointer is returned from a function which has a _Nonnull return |
| 16 | // type. |
| 17 | // * Nullable pointer is dereferenced. |
| 18 | // |
| 19 | // This checker propagates the nullability information of the pointers and looks |
| 20 | // for the patterns that are described above. Explicit casts are trusted and are |
| 21 | // considered a way to suppress false positives for this checker. The other way |
| 22 | // to suppress warnings would be to add asserts or guarding if statements to the |
| 23 | // code. In addition to the nullability propagation this checker also uses some |
| 24 | // heuristics to suppress potential false positives. |
| 25 | // |
| 26 | //===----------------------------------------------------------------------===// |
| 27 | |
| 28 | #include "ClangSACheckers.h" |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 29 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 30 | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" |
| 31 | #include "clang/StaticAnalyzer/Core/Checker.h" |
| 32 | #include "clang/StaticAnalyzer/Core/CheckerManager.h" |
| 33 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" |
| 34 | #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" |
| 35 | |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 36 | #include "llvm/ADT/StringExtras.h" |
| 37 | #include "llvm/Support/Path.h" |
| 38 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 39 | using namespace clang; |
| 40 | using namespace ento; |
| 41 | |
| 42 | namespace { |
| 43 | // Do not reorder! The getMostNullable method relies on the order. |
| 44 | // Optimization: Most pointers expected to be unspecified. When a symbol has an |
| 45 | // unspecified or nonnull type non of the rules would indicate any problem for |
| 46 | // that symbol. For this reason only nullable and contradicted nullability are |
| 47 | // stored for a symbol. When a symbol is already contradicted, it can not be |
| 48 | // casted back to nullable. |
| 49 | enum class Nullability : char { |
| 50 | Contradicted, // Tracked nullability is contradicted by an explicit cast. Do |
| 51 | // not report any nullability related issue for this symbol. |
Simon Pilgrim | 2c51880 | 2017-03-30 14:13:19 +0000 | [diff] [blame] | 52 | // This nullability is propagated aggressively to avoid false |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 53 | // positive results. See the comment on getMostNullable method. |
| 54 | Nullable, |
| 55 | Unspecified, |
| 56 | Nonnull |
| 57 | }; |
| 58 | |
| 59 | /// Returns the most nullable nullability. This is used for message expressions |
Simon Pilgrim | 2c51880 | 2017-03-30 14:13:19 +0000 | [diff] [blame] | 60 | /// like [receiver method], where the nullability of this expression is either |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 61 | /// the nullability of the receiver or the nullability of the return type of the |
| 62 | /// method, depending on which is more nullable. Contradicted is considered to |
| 63 | /// be the most nullable, to avoid false positive results. |
Gabor Horvath | 3943adb | 2015-09-11 16:29:05 +0000 | [diff] [blame] | 64 | Nullability getMostNullable(Nullability Lhs, Nullability Rhs) { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 65 | return static_cast<Nullability>( |
| 66 | std::min(static_cast<char>(Lhs), static_cast<char>(Rhs))); |
| 67 | } |
| 68 | |
Gabor Horvath | 3943adb | 2015-09-11 16:29:05 +0000 | [diff] [blame] | 69 | const char *getNullabilityString(Nullability Nullab) { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 70 | switch (Nullab) { |
| 71 | case Nullability::Contradicted: |
| 72 | return "contradicted"; |
| 73 | case Nullability::Nullable: |
| 74 | return "nullable"; |
| 75 | case Nullability::Unspecified: |
| 76 | return "unspecified"; |
| 77 | case Nullability::Nonnull: |
| 78 | return "nonnull"; |
| 79 | } |
Gabor Horvath | 3943adb | 2015-09-11 16:29:05 +0000 | [diff] [blame] | 80 | llvm_unreachable("Unexpected enumeration."); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 81 | return ""; |
| 82 | } |
| 83 | |
| 84 | // These enums are used as an index to ErrorMessages array. |
| 85 | enum class ErrorKind : int { |
| 86 | NilAssignedToNonnull, |
| 87 | NilPassedToNonnull, |
| 88 | NilReturnedToNonnull, |
| 89 | NullableAssignedToNonnull, |
| 90 | NullableReturnedToNonnull, |
| 91 | NullableDereferenced, |
| 92 | NullablePassedToNonnull |
| 93 | }; |
| 94 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 95 | class NullabilityChecker |
| 96 | : public Checker<check::Bind, check::PreCall, check::PreStmt<ReturnStmt>, |
| 97 | check::PostCall, check::PostStmt<ExplicitCastExpr>, |
| 98 | check::PostObjCMessage, check::DeadSymbols, |
| 99 | check::Event<ImplicitNullDerefEvent>> { |
| 100 | mutable std::unique_ptr<BugType> BT; |
| 101 | |
| 102 | public: |
Devin Coughlin | a1d9d75 | 2016-03-05 01:32:43 +0000 | [diff] [blame] | 103 | // If true, the checker will not diagnose nullabilility issues for calls |
| 104 | // to system headers. This option is motivated by the observation that large |
| 105 | // projects may have many nullability warnings. These projects may |
| 106 | // find warnings about nullability annotations that they have explicitly |
| 107 | // added themselves higher priority to fix than warnings on calls to system |
| 108 | // libraries. |
| 109 | DefaultBool NoDiagnoseCallsToSystemHeaders; |
| 110 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 111 | void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const; |
| 112 | void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext &C) const; |
| 113 | void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; |
| 114 | void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const; |
| 115 | void checkPostCall(const CallEvent &Call, CheckerContext &C) const; |
| 116 | void checkPreCall(const CallEvent &Call, CheckerContext &C) const; |
| 117 | void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; |
| 118 | void checkEvent(ImplicitNullDerefEvent Event) const; |
| 119 | |
| 120 | void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, |
| 121 | const char *Sep) const override; |
| 122 | |
| 123 | struct NullabilityChecksFilter { |
| 124 | DefaultBool CheckNullPassedToNonnull; |
| 125 | DefaultBool CheckNullReturnedFromNonnull; |
| 126 | DefaultBool CheckNullableDereferenced; |
| 127 | DefaultBool CheckNullablePassedToNonnull; |
| 128 | DefaultBool CheckNullableReturnedFromNonnull; |
| 129 | |
| 130 | CheckName CheckNameNullPassedToNonnull; |
| 131 | CheckName CheckNameNullReturnedFromNonnull; |
| 132 | CheckName CheckNameNullableDereferenced; |
| 133 | CheckName CheckNameNullablePassedToNonnull; |
| 134 | CheckName CheckNameNullableReturnedFromNonnull; |
| 135 | }; |
| 136 | |
| 137 | NullabilityChecksFilter Filter; |
Gabor Horvath | 2930735 | 2015-09-14 18:31:34 +0000 | [diff] [blame] | 138 | // When set to false no nullability information will be tracked in |
| 139 | // NullabilityMap. It is possible to catch errors like passing a null pointer |
| 140 | // to a callee that expects nonnull argument without the information that is |
| 141 | // stroed in the NullabilityMap. This is an optimization. |
| 142 | DefaultBool NeedTracking; |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 143 | |
| 144 | private: |
| 145 | class NullabilityBugVisitor |
| 146 | : public BugReporterVisitorImpl<NullabilityBugVisitor> { |
| 147 | public: |
| 148 | NullabilityBugVisitor(const MemRegion *M) : Region(M) {} |
| 149 | |
| 150 | void Profile(llvm::FoldingSetNodeID &ID) const override { |
| 151 | static int X = 0; |
| 152 | ID.AddPointer(&X); |
| 153 | ID.AddPointer(Region); |
| 154 | } |
| 155 | |
David Blaikie | 0a0c275 | 2017-01-05 17:26:53 +0000 | [diff] [blame] | 156 | std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N, |
| 157 | const ExplodedNode *PrevN, |
| 158 | BugReporterContext &BRC, |
| 159 | BugReport &BR) override; |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 160 | |
| 161 | private: |
| 162 | // The tracked region. |
| 163 | const MemRegion *Region; |
| 164 | }; |
| 165 | |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 166 | /// When any of the nonnull arguments of the analyzed function is null, do not |
| 167 | /// report anything and turn off the check. |
| 168 | /// |
| 169 | /// When \p SuppressPath is set to true, no more bugs will be reported on this |
| 170 | /// path by this checker. |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 171 | void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error, |
| 172 | ExplodedNode *N, const MemRegion *Region, |
| 173 | CheckerContext &C, |
| 174 | const Stmt *ValueExpr = nullptr, |
| 175 | bool SuppressPath = false) const; |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 176 | |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 177 | void reportBug(StringRef Msg, ErrorKind Error, ExplodedNode *N, |
| 178 | const MemRegion *Region, BugReporter &BR, |
| 179 | const Stmt *ValueExpr = nullptr) const { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 180 | if (!BT) |
Artem Dergachev | b6a513d | 2017-05-03 11:47:13 +0000 | [diff] [blame] | 181 | BT.reset(new BugType(this, "Nullability", categories::MemoryError)); |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 182 | |
| 183 | auto R = llvm::make_unique<BugReport>(*BT, Msg, N); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 184 | if (Region) { |
| 185 | R->markInteresting(Region); |
| 186 | R->addVisitor(llvm::make_unique<NullabilityBugVisitor>(Region)); |
| 187 | } |
| 188 | if (ValueExpr) { |
| 189 | R->addRange(ValueExpr->getSourceRange()); |
| 190 | if (Error == ErrorKind::NilAssignedToNonnull || |
| 191 | Error == ErrorKind::NilPassedToNonnull || |
| 192 | Error == ErrorKind::NilReturnedToNonnull) |
| 193 | bugreporter::trackNullOrUndefValue(N, ValueExpr, *R); |
| 194 | } |
| 195 | BR.emitReport(std::move(R)); |
| 196 | } |
Gabor Horvath | 2930735 | 2015-09-14 18:31:34 +0000 | [diff] [blame] | 197 | |
| 198 | /// If an SVal wraps a region that should be tracked, it will return a pointer |
| 199 | /// to the wrapped region. Otherwise it will return a nullptr. |
| 200 | const SymbolicRegion *getTrackRegion(SVal Val, |
| 201 | bool CheckSuperRegion = false) const; |
Devin Coughlin | a1d9d75 | 2016-03-05 01:32:43 +0000 | [diff] [blame] | 202 | |
| 203 | /// Returns true if the call is diagnosable in the currrent analyzer |
| 204 | /// configuration. |
| 205 | bool isDiagnosableCall(const CallEvent &Call) const { |
| 206 | if (NoDiagnoseCallsToSystemHeaders && Call.isInSystemHeader()) |
| 207 | return false; |
| 208 | |
| 209 | return true; |
| 210 | } |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 211 | }; |
| 212 | |
| 213 | class NullabilityState { |
| 214 | public: |
| 215 | NullabilityState(Nullability Nullab, const Stmt *Source = nullptr) |
| 216 | : Nullab(Nullab), Source(Source) {} |
| 217 | |
| 218 | const Stmt *getNullabilitySource() const { return Source; } |
| 219 | |
| 220 | Nullability getValue() const { return Nullab; } |
| 221 | |
| 222 | void Profile(llvm::FoldingSetNodeID &ID) const { |
| 223 | ID.AddInteger(static_cast<char>(Nullab)); |
| 224 | ID.AddPointer(Source); |
| 225 | } |
| 226 | |
| 227 | void print(raw_ostream &Out) const { |
| 228 | Out << getNullabilityString(Nullab) << "\n"; |
| 229 | } |
| 230 | |
| 231 | private: |
| 232 | Nullability Nullab; |
| 233 | // Source is the expression which determined the nullability. For example in a |
| 234 | // message like [nullable nonnull_returning] has nullable nullability, because |
| 235 | // the receiver is nullable. Here the receiver will be the source of the |
| 236 | // nullability. This is useful information when the diagnostics are generated. |
| 237 | const Stmt *Source; |
| 238 | }; |
| 239 | |
| 240 | bool operator==(NullabilityState Lhs, NullabilityState Rhs) { |
| 241 | return Lhs.getValue() == Rhs.getValue() && |
| 242 | Lhs.getNullabilitySource() == Rhs.getNullabilitySource(); |
| 243 | } |
| 244 | |
| 245 | } // end anonymous namespace |
| 246 | |
| 247 | REGISTER_MAP_WITH_PROGRAMSTATE(NullabilityMap, const MemRegion *, |
| 248 | NullabilityState) |
| 249 | |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 250 | // We say "the nullability type invariant is violated" when a location with a |
| 251 | // non-null type contains NULL or a function with a non-null return type returns |
| 252 | // NULL. Violations of the nullability type invariant can be detected either |
| 253 | // directly (for example, when NULL is passed as an argument to a nonnull |
| 254 | // parameter) or indirectly (for example, when, inside a function, the |
| 255 | // programmer defensively checks whether a nonnull parameter contains NULL and |
| 256 | // finds that it does). |
| 257 | // |
| 258 | // As a matter of policy, the nullability checker typically warns on direct |
| 259 | // violations of the nullability invariant (although it uses various |
| 260 | // heuristics to suppress warnings in some cases) but will not warn if the |
| 261 | // invariant has already been violated along the path (either directly or |
| 262 | // indirectly). As a practical matter, this prevents the analyzer from |
| 263 | // (1) warning on defensive code paths where a nullability precondition is |
| 264 | // determined to have been violated, (2) warning additional times after an |
| 265 | // initial direct violation has been discovered, and (3) warning after a direct |
| 266 | // violation that has been implicitly or explicitly suppressed (for |
| 267 | // example, with a cast of NULL to _Nonnull). In essence, once an invariant |
| 268 | // violation is detected on a path, this checker will be esentially turned off |
| 269 | // for the rest of the analysis |
| 270 | // |
| 271 | // The analyzer takes this approach (rather than generating a sink node) to |
| 272 | // ensure coverage of defensive paths, which may be important for backwards |
| 273 | // compatibility in codebases that were developed without nullability in mind. |
| 274 | REGISTER_TRAIT_WITH_PROGRAMSTATE(InvariantViolated, bool) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 275 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 276 | enum class NullConstraint { IsNull, IsNotNull, Unknown }; |
| 277 | |
| 278 | static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val, |
| 279 | ProgramStateRef State) { |
| 280 | ConditionTruthVal Nullness = State->isNull(Val); |
| 281 | if (Nullness.isConstrainedFalse()) |
| 282 | return NullConstraint::IsNotNull; |
| 283 | if (Nullness.isConstrainedTrue()) |
| 284 | return NullConstraint::IsNull; |
| 285 | return NullConstraint::Unknown; |
| 286 | } |
| 287 | |
Gabor Horvath | 2930735 | 2015-09-14 18:31:34 +0000 | [diff] [blame] | 288 | const SymbolicRegion * |
| 289 | NullabilityChecker::getTrackRegion(SVal Val, bool CheckSuperRegion) const { |
| 290 | if (!NeedTracking) |
| 291 | return nullptr; |
| 292 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 293 | auto RegionSVal = Val.getAs<loc::MemRegionVal>(); |
| 294 | if (!RegionSVal) |
| 295 | return nullptr; |
| 296 | |
| 297 | const MemRegion *Region = RegionSVal->getRegion(); |
| 298 | |
| 299 | if (CheckSuperRegion) { |
| 300 | if (auto FieldReg = Region->getAs<FieldRegion>()) |
| 301 | return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion()); |
Gabor Horvath | 3943adb | 2015-09-11 16:29:05 +0000 | [diff] [blame] | 302 | if (auto ElementReg = Region->getAs<ElementRegion>()) |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 303 | return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion()); |
| 304 | } |
| 305 | |
| 306 | return dyn_cast<SymbolicRegion>(Region); |
| 307 | } |
| 308 | |
David Blaikie | 0a0c275 | 2017-01-05 17:26:53 +0000 | [diff] [blame] | 309 | std::shared_ptr<PathDiagnosticPiece> |
| 310 | NullabilityChecker::NullabilityBugVisitor::VisitNode(const ExplodedNode *N, |
| 311 | const ExplodedNode *PrevN, |
| 312 | BugReporterContext &BRC, |
| 313 | BugReport &BR) { |
Gabor Horvath | 3943adb | 2015-09-11 16:29:05 +0000 | [diff] [blame] | 314 | ProgramStateRef State = N->getState(); |
| 315 | ProgramStateRef StatePrev = PrevN->getState(); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 316 | |
Gabor Horvath | 3943adb | 2015-09-11 16:29:05 +0000 | [diff] [blame] | 317 | const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 318 | const NullabilityState *TrackedNullabPrev = |
Gabor Horvath | 3943adb | 2015-09-11 16:29:05 +0000 | [diff] [blame] | 319 | StatePrev->get<NullabilityMap>(Region); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 320 | if (!TrackedNullab) |
| 321 | return nullptr; |
| 322 | |
| 323 | if (TrackedNullabPrev && |
| 324 | TrackedNullabPrev->getValue() == TrackedNullab->getValue()) |
| 325 | return nullptr; |
| 326 | |
| 327 | // Retrieve the associated statement. |
| 328 | const Stmt *S = TrackedNullab->getNullabilitySource(); |
Artem Dergachev | fbe891ee | 2017-06-05 12:40:03 +0000 | [diff] [blame] | 329 | if (!S || S->getLocStart().isInvalid()) { |
Gabor Horvath | 6ee4f90 | 2016-08-18 07:54:50 +0000 | [diff] [blame] | 330 | S = PathDiagnosticLocation::getStmt(N); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 331 | } |
| 332 | |
| 333 | if (!S) |
| 334 | return nullptr; |
| 335 | |
| 336 | std::string InfoText = |
| 337 | (llvm::Twine("Nullability '") + |
Devin Coughlin | c894ac8 | 2016-12-07 17:36:27 +0000 | [diff] [blame] | 338 | getNullabilityString(TrackedNullab->getValue()) + "' is inferred") |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 339 | .str(); |
| 340 | |
| 341 | // Generate the extra diagnostic. |
| 342 | PathDiagnosticLocation Pos(S, BRC.getSourceManager(), |
| 343 | N->getLocationContext()); |
David Blaikie | 0a0c275 | 2017-01-05 17:26:53 +0000 | [diff] [blame] | 344 | return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true, |
| 345 | nullptr); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 346 | } |
| 347 | |
| 348 | static Nullability getNullabilityAnnotation(QualType Type) { |
| 349 | const auto *AttrType = Type->getAs<AttributedType>(); |
| 350 | if (!AttrType) |
| 351 | return Nullability::Unspecified; |
| 352 | if (AttrType->getAttrKind() == AttributedType::attr_nullable) |
| 353 | return Nullability::Nullable; |
| 354 | else if (AttrType->getAttrKind() == AttributedType::attr_nonnull) |
| 355 | return Nullability::Nonnull; |
| 356 | return Nullability::Unspecified; |
| 357 | } |
| 358 | |
Devin Coughlin | b2d2a01 | 2016-04-13 00:41:54 +0000 | [diff] [blame] | 359 | /// Returns true when the value stored at the given location is null |
| 360 | /// and the passed in type is nonnnull. |
| 361 | static bool checkValueAtLValForInvariantViolation(ProgramStateRef State, |
| 362 | SVal LV, QualType T) { |
| 363 | if (getNullabilityAnnotation(T) != Nullability::Nonnull) |
| 364 | return false; |
| 365 | |
| 366 | auto RegionVal = LV.getAs<loc::MemRegionVal>(); |
| 367 | if (!RegionVal) |
| 368 | return false; |
| 369 | |
| 370 | auto StoredVal = |
| 371 | State->getSVal(RegionVal->getRegion()).getAs<DefinedOrUnknownSVal>(); |
| 372 | if (!StoredVal) |
| 373 | return false; |
| 374 | |
| 375 | if (getNullConstraint(*StoredVal, State) == NullConstraint::IsNull) |
| 376 | return true; |
| 377 | |
| 378 | return false; |
| 379 | } |
| 380 | |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 381 | static bool |
Devin Coughlin | b2d2a01 | 2016-04-13 00:41:54 +0000 | [diff] [blame] | 382 | checkParamsForPreconditionViolation(ArrayRef<ParmVarDecl *> Params, |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 383 | ProgramStateRef State, |
| 384 | const LocationContext *LocCtxt) { |
| 385 | for (const auto *ParamDecl : Params) { |
| 386 | if (ParamDecl->isParameterPack()) |
| 387 | break; |
| 388 | |
Devin Coughlin | b2d2a01 | 2016-04-13 00:41:54 +0000 | [diff] [blame] | 389 | SVal LV = State->getLValue(ParamDecl, LocCtxt); |
| 390 | if (checkValueAtLValForInvariantViolation(State, LV, |
| 391 | ParamDecl->getType())) { |
| 392 | return true; |
| 393 | } |
| 394 | } |
| 395 | return false; |
| 396 | } |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 397 | |
Devin Coughlin | b2d2a01 | 2016-04-13 00:41:54 +0000 | [diff] [blame] | 398 | static bool |
| 399 | checkSelfIvarsForInvariantViolation(ProgramStateRef State, |
| 400 | const LocationContext *LocCtxt) { |
| 401 | auto *MD = dyn_cast<ObjCMethodDecl>(LocCtxt->getDecl()); |
| 402 | if (!MD || !MD->isInstanceMethod()) |
| 403 | return false; |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 404 | |
Devin Coughlin | b2d2a01 | 2016-04-13 00:41:54 +0000 | [diff] [blame] | 405 | const ImplicitParamDecl *SelfDecl = LocCtxt->getSelfDecl(); |
| 406 | if (!SelfDecl) |
| 407 | return false; |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 408 | |
Devin Coughlin | b2d2a01 | 2016-04-13 00:41:54 +0000 | [diff] [blame] | 409 | SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, LocCtxt)); |
| 410 | |
| 411 | const ObjCObjectPointerType *SelfType = |
| 412 | dyn_cast<ObjCObjectPointerType>(SelfDecl->getType()); |
| 413 | if (!SelfType) |
| 414 | return false; |
| 415 | |
| 416 | const ObjCInterfaceDecl *ID = SelfType->getInterfaceDecl(); |
| 417 | if (!ID) |
| 418 | return false; |
| 419 | |
| 420 | for (const auto *IvarDecl : ID->ivars()) { |
| 421 | SVal LV = State->getLValue(IvarDecl, SelfVal); |
| 422 | if (checkValueAtLValForInvariantViolation(State, LV, IvarDecl->getType())) { |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 423 | return true; |
| 424 | } |
| 425 | } |
| 426 | return false; |
| 427 | } |
| 428 | |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 429 | static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N, |
| 430 | CheckerContext &C) { |
| 431 | if (State->get<InvariantViolated>()) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 432 | return true; |
| 433 | |
| 434 | const LocationContext *LocCtxt = C.getLocationContext(); |
| 435 | const Decl *D = LocCtxt->getDecl(); |
| 436 | if (!D) |
| 437 | return false; |
| 438 | |
Devin Coughlin | 851da71 | 2016-01-15 21:35:40 +0000 | [diff] [blame] | 439 | ArrayRef<ParmVarDecl*> Params; |
| 440 | if (const auto *BD = dyn_cast<BlockDecl>(D)) |
| 441 | Params = BD->parameters(); |
| 442 | else if (const auto *FD = dyn_cast<FunctionDecl>(D)) |
| 443 | Params = FD->parameters(); |
| 444 | else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) |
| 445 | Params = MD->parameters(); |
| 446 | else |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 447 | return false; |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 448 | |
Devin Coughlin | b2d2a01 | 2016-04-13 00:41:54 +0000 | [diff] [blame] | 449 | if (checkParamsForPreconditionViolation(Params, State, LocCtxt) || |
| 450 | checkSelfIvarsForInvariantViolation(State, LocCtxt)) { |
Devin Coughlin | 851da71 | 2016-01-15 21:35:40 +0000 | [diff] [blame] | 451 | if (!N->isSink()) |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 452 | C.addTransition(State->set<InvariantViolated>(true), N); |
Devin Coughlin | 851da71 | 2016-01-15 21:35:40 +0000 | [diff] [blame] | 453 | return true; |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 454 | } |
| 455 | return false; |
| 456 | } |
| 457 | |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 458 | void NullabilityChecker::reportBugIfInvariantHolds(StringRef Msg, |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 459 | ErrorKind Error, ExplodedNode *N, const MemRegion *Region, |
| 460 | CheckerContext &C, const Stmt *ValueExpr, bool SuppressPath) const { |
| 461 | ProgramStateRef OriginalState = N->getState(); |
| 462 | |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 463 | if (checkInvariantViolation(OriginalState, N, C)) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 464 | return; |
| 465 | if (SuppressPath) { |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 466 | OriginalState = OriginalState->set<InvariantViolated>(true); |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 467 | N = C.addTransition(OriginalState, N); |
| 468 | } |
| 469 | |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 470 | reportBug(Msg, Error, N, Region, C.getBugReporter(), ValueExpr); |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 471 | } |
| 472 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 473 | /// Cleaning up the program state. |
| 474 | void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR, |
| 475 | CheckerContext &C) const { |
Gabor Horvath | be87d5b | 2015-09-14 20:31:46 +0000 | [diff] [blame] | 476 | if (!SR.hasDeadSymbols()) |
| 477 | return; |
| 478 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 479 | ProgramStateRef State = C.getState(); |
| 480 | NullabilityMapTy Nullabilities = State->get<NullabilityMap>(); |
| 481 | for (NullabilityMapTy::iterator I = Nullabilities.begin(), |
| 482 | E = Nullabilities.end(); |
| 483 | I != E; ++I) { |
Gabor Horvath | be87d5b | 2015-09-14 20:31:46 +0000 | [diff] [blame] | 484 | const auto *Region = I->first->getAs<SymbolicRegion>(); |
| 485 | assert(Region && "Non-symbolic region is tracked."); |
| 486 | if (SR.isDead(Region->getSymbol())) { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 487 | State = State->remove<NullabilityMap>(I->first); |
| 488 | } |
| 489 | } |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 490 | // When one of the nonnull arguments are constrained to be null, nullability |
| 491 | // preconditions are violated. It is not enough to check this only when we |
| 492 | // actually report an error, because at that time interesting symbols might be |
| 493 | // reaped. |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 494 | if (checkInvariantViolation(State, C.getPredecessor(), C)) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 495 | return; |
| 496 | C.addTransition(State); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 497 | } |
| 498 | |
| 499 | /// This callback triggers when a pointer is dereferenced and the analyzer does |
| 500 | /// not know anything about the value of that pointer. When that pointer is |
| 501 | /// nullable, this code emits a warning. |
| 502 | void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event) const { |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 503 | if (Event.SinkNode->getState()->get<InvariantViolated>()) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 504 | return; |
| 505 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 506 | const MemRegion *Region = |
| 507 | getTrackRegion(Event.Location, /*CheckSuperregion=*/true); |
| 508 | if (!Region) |
| 509 | return; |
| 510 | |
| 511 | ProgramStateRef State = Event.SinkNode->getState(); |
| 512 | const NullabilityState *TrackedNullability = |
| 513 | State->get<NullabilityMap>(Region); |
| 514 | |
| 515 | if (!TrackedNullability) |
| 516 | return; |
| 517 | |
| 518 | if (Filter.CheckNullableDereferenced && |
| 519 | TrackedNullability->getValue() == Nullability::Nullable) { |
| 520 | BugReporter &BR = *Event.BR; |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 521 | // Do not suppress errors on defensive code paths, because dereferencing |
| 522 | // a nullable pointer is always an error. |
Gabor Horvath | 8d3ad6b | 2015-08-27 18:49:07 +0000 | [diff] [blame] | 523 | if (Event.IsDirectDereference) |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 524 | reportBug("Nullable pointer is dereferenced", |
| 525 | ErrorKind::NullableDereferenced, Event.SinkNode, Region, BR); |
| 526 | else { |
| 527 | reportBug("Nullable pointer is passed to a callee that requires a " |
| 528 | "non-null", ErrorKind::NullablePassedToNonnull, |
| 529 | Event.SinkNode, Region, BR); |
| 530 | } |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 531 | } |
| 532 | } |
| 533 | |
Devin Coughlin | 5a3843e | 2016-01-18 18:53:33 +0000 | [diff] [blame] | 534 | /// Find the outermost subexpression of E that is not an implicit cast. |
| 535 | /// This looks through the implicit casts to _Nonnull that ARC adds to |
| 536 | /// return expressions of ObjC types when the return type of the function or |
| 537 | /// method is non-null but the express is not. |
| 538 | static const Expr *lookThroughImplicitCasts(const Expr *E) { |
| 539 | assert(E); |
| 540 | |
| 541 | while (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { |
| 542 | E = ICE->getSubExpr(); |
| 543 | } |
| 544 | |
| 545 | return E; |
| 546 | } |
| 547 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 548 | /// This method check when nullable pointer or null value is returned from a |
| 549 | /// function that has nonnull return type. |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 550 | void NullabilityChecker::checkPreStmt(const ReturnStmt *S, |
| 551 | CheckerContext &C) const { |
| 552 | auto RetExpr = S->getRetValue(); |
| 553 | if (!RetExpr) |
| 554 | return; |
| 555 | |
| 556 | if (!RetExpr->getType()->isAnyPointerType()) |
| 557 | return; |
| 558 | |
| 559 | ProgramStateRef State = C.getState(); |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 560 | if (State->get<InvariantViolated>()) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 561 | return; |
| 562 | |
George Karpenkov | d703ec9 | 2018-01-17 20:27:29 +0000 | [diff] [blame] | 563 | auto RetSVal = C.getSVal(S).getAs<DefinedOrUnknownSVal>(); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 564 | if (!RetSVal) |
| 565 | return; |
| 566 | |
Devin Coughlin | de21767 | 2016-01-28 22:23:34 +0000 | [diff] [blame] | 567 | bool InSuppressedMethodFamily = false; |
Devin Coughlin | 4a33020 | 2016-01-22 01:01:11 +0000 | [diff] [blame] | 568 | |
Devin Coughlin | 851da71 | 2016-01-15 21:35:40 +0000 | [diff] [blame] | 569 | QualType RequiredRetType; |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 570 | AnalysisDeclContext *DeclCtxt = |
| 571 | C.getLocationContext()->getAnalysisDeclContext(); |
Devin Coughlin | 851da71 | 2016-01-15 21:35:40 +0000 | [diff] [blame] | 572 | const Decl *D = DeclCtxt->getDecl(); |
Devin Coughlin | 4a33020 | 2016-01-22 01:01:11 +0000 | [diff] [blame] | 573 | if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) { |
Devin Coughlin | de21767 | 2016-01-28 22:23:34 +0000 | [diff] [blame] | 574 | // HACK: This is a big hammer to avoid warning when there are defensive |
| 575 | // nil checks in -init and -copy methods. We should add more sophisticated |
| 576 | // logic here to suppress on common defensive idioms but still |
| 577 | // warn when there is a likely problem. |
| 578 | ObjCMethodFamily Family = MD->getMethodFamily(); |
| 579 | if (OMF_init == Family || OMF_copy == Family || OMF_mutableCopy == Family) |
| 580 | InSuppressedMethodFamily = true; |
| 581 | |
Devin Coughlin | 851da71 | 2016-01-15 21:35:40 +0000 | [diff] [blame] | 582 | RequiredRetType = MD->getReturnType(); |
Devin Coughlin | 4a33020 | 2016-01-22 01:01:11 +0000 | [diff] [blame] | 583 | } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { |
Devin Coughlin | 851da71 | 2016-01-15 21:35:40 +0000 | [diff] [blame] | 584 | RequiredRetType = FD->getReturnType(); |
Devin Coughlin | 4a33020 | 2016-01-22 01:01:11 +0000 | [diff] [blame] | 585 | } else { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 586 | return; |
Devin Coughlin | 4a33020 | 2016-01-22 01:01:11 +0000 | [diff] [blame] | 587 | } |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 588 | |
| 589 | NullConstraint Nullness = getNullConstraint(*RetSVal, State); |
| 590 | |
Devin Coughlin | 851da71 | 2016-01-15 21:35:40 +0000 | [diff] [blame] | 591 | Nullability RequiredNullability = getNullabilityAnnotation(RequiredRetType); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 592 | |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 593 | // If the returned value is null but the type of the expression |
| 594 | // generating it is nonnull then we will suppress the diagnostic. |
| 595 | // This enables explicit suppression when returning a nil literal in a |
| 596 | // function with a _Nonnull return type: |
| 597 | // return (NSString * _Nonnull)0; |
| 598 | Nullability RetExprTypeLevelNullability = |
Devin Coughlin | 5a3843e | 2016-01-18 18:53:33 +0000 | [diff] [blame] | 599 | getNullabilityAnnotation(lookThroughImplicitCasts(RetExpr)->getType()); |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 600 | |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 601 | bool NullReturnedFromNonNull = (RequiredNullability == Nullability::Nonnull && |
| 602 | Nullness == NullConstraint::IsNull); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 603 | if (Filter.CheckNullReturnedFromNonnull && |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 604 | NullReturnedFromNonNull && |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 605 | RetExprTypeLevelNullability != Nullability::Nonnull && |
Devin Coughlin | 49bd58f | 2016-04-12 19:29:52 +0000 | [diff] [blame] | 606 | !InSuppressedMethodFamily && |
| 607 | C.getLocationContext()->inTopFrame()) { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 608 | static CheckerProgramPointTag Tag(this, "NullReturnedFromNonnull"); |
Devin Coughlin | e39bd40 | 2015-09-16 22:03:05 +0000 | [diff] [blame] | 609 | ExplodedNode *N = C.generateErrorNode(State, &Tag); |
| 610 | if (!N) |
| 611 | return; |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 612 | |
| 613 | SmallString<256> SBuf; |
| 614 | llvm::raw_svector_ostream OS(SBuf); |
Anna Zaks | 6d4e76b | 2016-12-15 22:55:15 +0000 | [diff] [blame] | 615 | OS << (RetExpr->getType()->isObjCObjectPointerType() ? "nil" : "Null"); |
| 616 | OS << " returned from a " << C.getDeclDescription(D) << |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 617 | " that is expected to return a non-null value"; |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 618 | reportBugIfInvariantHolds(OS.str(), |
| 619 | ErrorKind::NilReturnedToNonnull, N, nullptr, C, |
| 620 | RetExpr); |
| 621 | return; |
| 622 | } |
| 623 | |
| 624 | // If null was returned from a non-null function, mark the nullability |
| 625 | // invariant as violated even if the diagnostic was suppressed. |
| 626 | if (NullReturnedFromNonNull) { |
| 627 | State = State->set<InvariantViolated>(true); |
| 628 | C.addTransition(State); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 629 | return; |
| 630 | } |
| 631 | |
| 632 | const MemRegion *Region = getTrackRegion(*RetSVal); |
| 633 | if (!Region) |
| 634 | return; |
| 635 | |
| 636 | const NullabilityState *TrackedNullability = |
| 637 | State->get<NullabilityMap>(Region); |
| 638 | if (TrackedNullability) { |
| 639 | Nullability TrackedNullabValue = TrackedNullability->getValue(); |
| 640 | if (Filter.CheckNullableReturnedFromNonnull && |
| 641 | Nullness != NullConstraint::IsNotNull && |
| 642 | TrackedNullabValue == Nullability::Nullable && |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 643 | RequiredNullability == Nullability::Nonnull) { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 644 | static CheckerProgramPointTag Tag(this, "NullableReturnedFromNonnull"); |
| 645 | ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag); |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 646 | |
| 647 | SmallString<256> SBuf; |
| 648 | llvm::raw_svector_ostream OS(SBuf); |
| 649 | OS << "Nullable pointer is returned from a " << C.getDeclDescription(D) << |
| 650 | " that is expected to return a non-null value"; |
| 651 | |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 652 | reportBugIfInvariantHolds(OS.str(), |
| 653 | ErrorKind::NullableReturnedToNonnull, N, |
| 654 | Region, C); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 655 | } |
| 656 | return; |
| 657 | } |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 658 | if (RequiredNullability == Nullability::Nullable) { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 659 | State = State->set<NullabilityMap>(Region, |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 660 | NullabilityState(RequiredNullability, |
| 661 | S)); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 662 | C.addTransition(State); |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | /// This callback warns when a nullable pointer or a null value is passed to a |
| 667 | /// function that expects its argument to be nonnull. |
| 668 | void NullabilityChecker::checkPreCall(const CallEvent &Call, |
| 669 | CheckerContext &C) const { |
| 670 | if (!Call.getDecl()) |
| 671 | return; |
| 672 | |
| 673 | ProgramStateRef State = C.getState(); |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 674 | if (State->get<InvariantViolated>()) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 675 | return; |
| 676 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 677 | ProgramStateRef OrigState = State; |
| 678 | |
| 679 | unsigned Idx = 0; |
| 680 | for (const ParmVarDecl *Param : Call.parameters()) { |
| 681 | if (Param->isParameterPack()) |
| 682 | break; |
| 683 | |
Devin Coughlin | e4224cc | 2016-11-14 22:46:02 +0000 | [diff] [blame] | 684 | if (Idx >= Call.getNumArgs()) |
| 685 | break; |
| 686 | |
| 687 | const Expr *ArgExpr = Call.getArgExpr(Idx); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 688 | auto ArgSVal = Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>(); |
| 689 | if (!ArgSVal) |
| 690 | continue; |
| 691 | |
| 692 | if (!Param->getType()->isAnyPointerType() && |
| 693 | !Param->getType()->isReferenceType()) |
| 694 | continue; |
| 695 | |
| 696 | NullConstraint Nullness = getNullConstraint(*ArgSVal, State); |
| 697 | |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 698 | Nullability RequiredNullability = |
| 699 | getNullabilityAnnotation(Param->getType()); |
| 700 | Nullability ArgExprTypeLevelNullability = |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 701 | getNullabilityAnnotation(ArgExpr->getType()); |
| 702 | |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 703 | unsigned ParamIdx = Param->getFunctionScopeIndex() + 1; |
| 704 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 705 | if (Filter.CheckNullPassedToNonnull && Nullness == NullConstraint::IsNull && |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 706 | ArgExprTypeLevelNullability != Nullability::Nonnull && |
Devin Coughlin | a1d9d75 | 2016-03-05 01:32:43 +0000 | [diff] [blame] | 707 | RequiredNullability == Nullability::Nonnull && |
| 708 | isDiagnosableCall(Call)) { |
Devin Coughlin | e39bd40 | 2015-09-16 22:03:05 +0000 | [diff] [blame] | 709 | ExplodedNode *N = C.generateErrorNode(State); |
| 710 | if (!N) |
| 711 | return; |
Anna Zaks | 6d4e76b | 2016-12-15 22:55:15 +0000 | [diff] [blame] | 712 | |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 713 | SmallString<256> SBuf; |
| 714 | llvm::raw_svector_ostream OS(SBuf); |
Anna Zaks | 6d4e76b | 2016-12-15 22:55:15 +0000 | [diff] [blame] | 715 | OS << (Param->getType()->isObjCObjectPointerType() ? "nil" : "Null"); |
| 716 | OS << " passed to a callee that requires a non-null " << ParamIdx |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 717 | << llvm::getOrdinalSuffix(ParamIdx) << " parameter"; |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 718 | reportBugIfInvariantHolds(OS.str(), ErrorKind::NilPassedToNonnull, N, |
| 719 | nullptr, C, |
| 720 | ArgExpr, /*SuppressPath=*/false); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 721 | return; |
| 722 | } |
| 723 | |
| 724 | const MemRegion *Region = getTrackRegion(*ArgSVal); |
| 725 | if (!Region) |
| 726 | continue; |
| 727 | |
| 728 | const NullabilityState *TrackedNullability = |
| 729 | State->get<NullabilityMap>(Region); |
| 730 | |
| 731 | if (TrackedNullability) { |
| 732 | if (Nullness == NullConstraint::IsNotNull || |
| 733 | TrackedNullability->getValue() != Nullability::Nullable) |
| 734 | continue; |
| 735 | |
| 736 | if (Filter.CheckNullablePassedToNonnull && |
Devin Coughlin | a1d9d75 | 2016-03-05 01:32:43 +0000 | [diff] [blame] | 737 | RequiredNullability == Nullability::Nonnull && |
| 738 | isDiagnosableCall(Call)) { |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 739 | ExplodedNode *N = C.addTransition(State); |
Anna Zaks | ad9e7ea | 2016-01-29 18:43:15 +0000 | [diff] [blame] | 740 | SmallString<256> SBuf; |
| 741 | llvm::raw_svector_ostream OS(SBuf); |
| 742 | OS << "Nullable pointer is passed to a callee that requires a non-null " |
| 743 | << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) << " parameter"; |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 744 | reportBugIfInvariantHolds(OS.str(), |
| 745 | ErrorKind::NullablePassedToNonnull, N, |
| 746 | Region, C, ArgExpr, /*SuppressPath=*/true); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 747 | return; |
| 748 | } |
| 749 | if (Filter.CheckNullableDereferenced && |
| 750 | Param->getType()->isReferenceType()) { |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 751 | ExplodedNode *N = C.addTransition(State); |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 752 | reportBugIfInvariantHolds("Nullable pointer is dereferenced", |
| 753 | ErrorKind::NullableDereferenced, N, Region, |
| 754 | C, ArgExpr, /*SuppressPath=*/true); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 755 | return; |
| 756 | } |
| 757 | continue; |
| 758 | } |
| 759 | // No tracked nullability yet. |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 760 | if (ArgExprTypeLevelNullability != Nullability::Nullable) |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 761 | continue; |
| 762 | State = State->set<NullabilityMap>( |
Devin Coughlin | 755baa4 | 2015-12-29 17:40:49 +0000 | [diff] [blame] | 763 | Region, NullabilityState(ArgExprTypeLevelNullability, ArgExpr)); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 764 | } |
| 765 | if (State != OrigState) |
| 766 | C.addTransition(State); |
| 767 | } |
| 768 | |
| 769 | /// Suppress the nullability warnings for some functions. |
| 770 | void NullabilityChecker::checkPostCall(const CallEvent &Call, |
| 771 | CheckerContext &C) const { |
| 772 | auto Decl = Call.getDecl(); |
| 773 | if (!Decl) |
| 774 | return; |
| 775 | // ObjC Messages handles in a different callback. |
| 776 | if (Call.getKind() == CE_ObjCMessage) |
| 777 | return; |
| 778 | const FunctionType *FuncType = Decl->getFunctionType(); |
| 779 | if (!FuncType) |
| 780 | return; |
| 781 | QualType ReturnType = FuncType->getReturnType(); |
| 782 | if (!ReturnType->isAnyPointerType()) |
| 783 | return; |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 784 | ProgramStateRef State = C.getState(); |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 785 | if (State->get<InvariantViolated>()) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 786 | return; |
| 787 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 788 | const MemRegion *Region = getTrackRegion(Call.getReturnValue()); |
| 789 | if (!Region) |
| 790 | return; |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 791 | |
| 792 | // CG headers are misannotated. Do not warn for symbols that are the results |
| 793 | // of CG calls. |
| 794 | const SourceManager &SM = C.getSourceManager(); |
| 795 | StringRef FilePath = SM.getFilename(SM.getSpellingLoc(Decl->getLocStart())); |
| 796 | if (llvm::sys::path::filename(FilePath).startswith("CG")) { |
| 797 | State = State->set<NullabilityMap>(Region, Nullability::Contradicted); |
| 798 | C.addTransition(State); |
| 799 | return; |
| 800 | } |
| 801 | |
| 802 | const NullabilityState *TrackedNullability = |
| 803 | State->get<NullabilityMap>(Region); |
| 804 | |
| 805 | if (!TrackedNullability && |
| 806 | getNullabilityAnnotation(ReturnType) == Nullability::Nullable) { |
| 807 | State = State->set<NullabilityMap>(Region, Nullability::Nullable); |
| 808 | C.addTransition(State); |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | static Nullability getReceiverNullability(const ObjCMethodCall &M, |
| 813 | ProgramStateRef State) { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 814 | if (M.isReceiverSelfOrSuper()) { |
| 815 | // For super and super class receivers we assume that the receiver is |
| 816 | // nonnull. |
Gabor Horvath | 3943adb | 2015-09-11 16:29:05 +0000 | [diff] [blame] | 817 | return Nullability::Nonnull; |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 818 | } |
Gabor Horvath | 3943adb | 2015-09-11 16:29:05 +0000 | [diff] [blame] | 819 | // Otherwise look up nullability in the state. |
| 820 | SVal Receiver = M.getReceiverSVal(); |
| 821 | if (auto DefOrUnknown = Receiver.getAs<DefinedOrUnknownSVal>()) { |
| 822 | // If the receiver is constrained to be nonnull, assume that it is nonnull |
| 823 | // regardless of its type. |
| 824 | NullConstraint Nullness = getNullConstraint(*DefOrUnknown, State); |
| 825 | if (Nullness == NullConstraint::IsNotNull) |
| 826 | return Nullability::Nonnull; |
| 827 | } |
| 828 | auto ValueRegionSVal = Receiver.getAs<loc::MemRegionVal>(); |
| 829 | if (ValueRegionSVal) { |
| 830 | const MemRegion *SelfRegion = ValueRegionSVal->getRegion(); |
| 831 | assert(SelfRegion); |
| 832 | |
| 833 | const NullabilityState *TrackedSelfNullability = |
| 834 | State->get<NullabilityMap>(SelfRegion); |
| 835 | if (TrackedSelfNullability) |
| 836 | return TrackedSelfNullability->getValue(); |
| 837 | } |
| 838 | return Nullability::Unspecified; |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 839 | } |
| 840 | |
| 841 | /// Calculate the nullability of the result of a message expr based on the |
| 842 | /// nullability of the receiver, the nullability of the return value, and the |
| 843 | /// constraints. |
| 844 | void NullabilityChecker::checkPostObjCMessage(const ObjCMethodCall &M, |
| 845 | CheckerContext &C) const { |
| 846 | auto Decl = M.getDecl(); |
| 847 | if (!Decl) |
| 848 | return; |
| 849 | QualType RetType = Decl->getReturnType(); |
| 850 | if (!RetType->isAnyPointerType()) |
| 851 | return; |
| 852 | |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 853 | ProgramStateRef State = C.getState(); |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 854 | if (State->get<InvariantViolated>()) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 855 | return; |
| 856 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 857 | const MemRegion *ReturnRegion = getTrackRegion(M.getReturnValue()); |
| 858 | if (!ReturnRegion) |
| 859 | return; |
| 860 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 861 | auto Interface = Decl->getClassInterface(); |
| 862 | auto Name = Interface ? Interface->getName() : ""; |
| 863 | // In order to reduce the noise in the diagnostics generated by this checker, |
| 864 | // some framework and programming style based heuristics are used. These |
| 865 | // heuristics are for Cocoa APIs which have NS prefix. |
| 866 | if (Name.startswith("NS")) { |
| 867 | // Developers rely on dynamic invariants such as an item should be available |
| 868 | // in a collection, or a collection is not empty often. Those invariants can |
| 869 | // not be inferred by any static analysis tool. To not to bother the users |
| 870 | // with too many false positives, every item retrieval function should be |
| 871 | // ignored for collections. The instance methods of dictionaries in Cocoa |
| 872 | // are either item retrieval related or not interesting nullability wise. |
| 873 | // Using this fact, to keep the code easier to read just ignore the return |
| 874 | // value of every instance method of dictionaries. |
| 875 | if (M.isInstanceMessage() && Name.find("Dictionary") != StringRef::npos) { |
| 876 | State = |
| 877 | State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted); |
| 878 | C.addTransition(State); |
| 879 | return; |
| 880 | } |
| 881 | // For similar reasons ignore some methods of Cocoa arrays. |
| 882 | StringRef FirstSelectorSlot = M.getSelector().getNameForSlot(0); |
| 883 | if (Name.find("Array") != StringRef::npos && |
| 884 | (FirstSelectorSlot == "firstObject" || |
| 885 | FirstSelectorSlot == "lastObject")) { |
| 886 | State = |
| 887 | State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted); |
| 888 | C.addTransition(State); |
| 889 | return; |
| 890 | } |
| 891 | |
| 892 | // Encoding related methods of string should not fail when lossless |
| 893 | // encodings are used. Using lossless encodings is so frequent that ignoring |
| 894 | // this class of methods reduced the emitted diagnostics by about 30% on |
| 895 | // some projects (and all of that was false positives). |
| 896 | if (Name.find("String") != StringRef::npos) { |
| 897 | for (auto Param : M.parameters()) { |
| 898 | if (Param->getName() == "encoding") { |
| 899 | State = State->set<NullabilityMap>(ReturnRegion, |
| 900 | Nullability::Contradicted); |
| 901 | C.addTransition(State); |
| 902 | return; |
| 903 | } |
| 904 | } |
| 905 | } |
| 906 | } |
| 907 | |
| 908 | const ObjCMessageExpr *Message = M.getOriginExpr(); |
| 909 | Nullability SelfNullability = getReceiverNullability(M, State); |
| 910 | |
| 911 | const NullabilityState *NullabilityOfReturn = |
| 912 | State->get<NullabilityMap>(ReturnRegion); |
| 913 | |
| 914 | if (NullabilityOfReturn) { |
| 915 | // When we have a nullability tracked for the return value, the nullability |
| 916 | // of the expression will be the most nullable of the receiver and the |
| 917 | // return value. |
| 918 | Nullability RetValTracked = NullabilityOfReturn->getValue(); |
| 919 | Nullability ComputedNullab = |
| 920 | getMostNullable(RetValTracked, SelfNullability); |
| 921 | if (ComputedNullab != RetValTracked && |
| 922 | ComputedNullab != Nullability::Unspecified) { |
| 923 | const Stmt *NullabilitySource = |
| 924 | ComputedNullab == RetValTracked |
| 925 | ? NullabilityOfReturn->getNullabilitySource() |
| 926 | : Message->getInstanceReceiver(); |
| 927 | State = State->set<NullabilityMap>( |
| 928 | ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource)); |
| 929 | C.addTransition(State); |
| 930 | } |
| 931 | return; |
| 932 | } |
| 933 | |
| 934 | // No tracked information. Use static type information for return value. |
| 935 | Nullability RetNullability = getNullabilityAnnotation(RetType); |
| 936 | |
| 937 | // Properties might be computed. For this reason the static analyzer creates a |
| 938 | // new symbol each time an unknown property is read. To avoid false pozitives |
| 939 | // do not treat unknown properties as nullable, even when they explicitly |
| 940 | // marked nullable. |
| 941 | if (M.getMessageKind() == OCM_PropertyAccess && !C.wasInlined) |
| 942 | RetNullability = Nullability::Nonnull; |
| 943 | |
| 944 | Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability); |
| 945 | if (ComputedNullab == Nullability::Nullable) { |
| 946 | const Stmt *NullabilitySource = ComputedNullab == RetNullability |
| 947 | ? Message |
| 948 | : Message->getInstanceReceiver(); |
| 949 | State = State->set<NullabilityMap>( |
| 950 | ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource)); |
| 951 | C.addTransition(State); |
| 952 | } |
| 953 | } |
| 954 | |
| 955 | /// Explicit casts are trusted. If there is a disagreement in the nullability |
| 956 | /// annotations in the destination and the source or '0' is casted to nonnull |
| 957 | /// track the value as having contraditory nullability. This will allow users to |
| 958 | /// suppress warnings. |
| 959 | void NullabilityChecker::checkPostStmt(const ExplicitCastExpr *CE, |
| 960 | CheckerContext &C) const { |
| 961 | QualType OriginType = CE->getSubExpr()->getType(); |
| 962 | QualType DestType = CE->getType(); |
| 963 | if (!OriginType->isAnyPointerType()) |
| 964 | return; |
| 965 | if (!DestType->isAnyPointerType()) |
| 966 | return; |
| 967 | |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 968 | ProgramStateRef State = C.getState(); |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 969 | if (State->get<InvariantViolated>()) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 970 | return; |
| 971 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 972 | Nullability DestNullability = getNullabilityAnnotation(DestType); |
| 973 | |
| 974 | // No explicit nullability in the destination type, so this cast does not |
| 975 | // change the nullability. |
| 976 | if (DestNullability == Nullability::Unspecified) |
| 977 | return; |
| 978 | |
George Karpenkov | d703ec9 | 2018-01-17 20:27:29 +0000 | [diff] [blame] | 979 | auto RegionSVal = C.getSVal(CE).getAs<DefinedOrUnknownSVal>(); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 980 | const MemRegion *Region = getTrackRegion(*RegionSVal); |
| 981 | if (!Region) |
| 982 | return; |
| 983 | |
| 984 | // When 0 is converted to nonnull mark it as contradicted. |
| 985 | if (DestNullability == Nullability::Nonnull) { |
| 986 | NullConstraint Nullness = getNullConstraint(*RegionSVal, State); |
| 987 | if (Nullness == NullConstraint::IsNull) { |
| 988 | State = State->set<NullabilityMap>(Region, Nullability::Contradicted); |
| 989 | C.addTransition(State); |
| 990 | return; |
| 991 | } |
| 992 | } |
| 993 | |
| 994 | const NullabilityState *TrackedNullability = |
| 995 | State->get<NullabilityMap>(Region); |
| 996 | |
| 997 | if (!TrackedNullability) { |
| 998 | if (DestNullability != Nullability::Nullable) |
| 999 | return; |
| 1000 | State = State->set<NullabilityMap>(Region, |
| 1001 | NullabilityState(DestNullability, CE)); |
| 1002 | C.addTransition(State); |
| 1003 | return; |
| 1004 | } |
| 1005 | |
| 1006 | if (TrackedNullability->getValue() != DestNullability && |
| 1007 | TrackedNullability->getValue() != Nullability::Contradicted) { |
| 1008 | State = State->set<NullabilityMap>(Region, Nullability::Contradicted); |
| 1009 | C.addTransition(State); |
| 1010 | } |
| 1011 | } |
| 1012 | |
Devin Coughlin | c198663 | 2015-11-24 19:15:11 +0000 | [diff] [blame] | 1013 | /// For a given statement performing a bind, attempt to syntactically |
| 1014 | /// match the expression resulting in the bound value. |
| 1015 | static const Expr * matchValueExprForBind(const Stmt *S) { |
| 1016 | // For `x = e` the value expression is the right-hand side. |
| 1017 | if (auto *BinOp = dyn_cast<BinaryOperator>(S)) { |
| 1018 | if (BinOp->getOpcode() == BO_Assign) |
| 1019 | return BinOp->getRHS(); |
| 1020 | } |
| 1021 | |
| 1022 | // For `int x = e` the value expression is the initializer. |
| 1023 | if (auto *DS = dyn_cast<DeclStmt>(S)) { |
| 1024 | if (DS->isSingleDecl()) { |
| 1025 | auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); |
| 1026 | if (!VD) |
| 1027 | return nullptr; |
| 1028 | |
| 1029 | if (const Expr *Init = VD->getInit()) |
| 1030 | return Init; |
| 1031 | } |
| 1032 | } |
| 1033 | |
| 1034 | return nullptr; |
| 1035 | } |
| 1036 | |
Devin Coughlin | 3ab8b2e7 | 2015-12-29 23:44:19 +0000 | [diff] [blame] | 1037 | /// Returns true if \param S is a DeclStmt for a local variable that |
| 1038 | /// ObjC automated reference counting initialized with zero. |
| 1039 | static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) { |
| 1040 | // We suppress diagnostics for ARC zero-initialized _Nonnull locals. This |
| 1041 | // prevents false positives when a _Nonnull local variable cannot be |
| 1042 | // initialized with an initialization expression: |
| 1043 | // NSString * _Nonnull s; // no-warning |
| 1044 | // @autoreleasepool { |
| 1045 | // s = ... |
| 1046 | // } |
| 1047 | // |
| 1048 | // FIXME: We should treat implicitly zero-initialized _Nonnull locals as |
| 1049 | // uninitialized in Sema's UninitializedValues analysis to warn when a use of |
| 1050 | // the zero-initialized definition will unexpectedly yield nil. |
| 1051 | |
| 1052 | // Locals are only zero-initialized when automated reference counting |
| 1053 | // is turned on. |
| 1054 | if (!C.getASTContext().getLangOpts().ObjCAutoRefCount) |
| 1055 | return false; |
| 1056 | |
| 1057 | auto *DS = dyn_cast<DeclStmt>(S); |
| 1058 | if (!DS || !DS->isSingleDecl()) |
| 1059 | return false; |
| 1060 | |
| 1061 | auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); |
| 1062 | if (!VD) |
| 1063 | return false; |
| 1064 | |
| 1065 | // Sema only zero-initializes locals with ObjCLifetimes. |
| 1066 | if(!VD->getType().getQualifiers().hasObjCLifetime()) |
| 1067 | return false; |
| 1068 | |
| 1069 | const Expr *Init = VD->getInit(); |
| 1070 | assert(Init && "ObjC local under ARC without initializer"); |
| 1071 | |
| 1072 | // Return false if the local is explicitly initialized (e.g., with '= nil'). |
| 1073 | if (!isa<ImplicitValueInitExpr>(Init)) |
| 1074 | return false; |
| 1075 | |
| 1076 | return true; |
| 1077 | } |
| 1078 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1079 | /// Propagate the nullability information through binds and warn when nullable |
| 1080 | /// pointer or null symbol is assigned to a pointer with a nonnull type. |
| 1081 | void NullabilityChecker::checkBind(SVal L, SVal V, const Stmt *S, |
| 1082 | CheckerContext &C) const { |
| 1083 | const TypedValueRegion *TVR = |
| 1084 | dyn_cast_or_null<TypedValueRegion>(L.getAsRegion()); |
| 1085 | if (!TVR) |
| 1086 | return; |
| 1087 | |
| 1088 | QualType LocType = TVR->getValueType(); |
| 1089 | if (!LocType->isAnyPointerType()) |
| 1090 | return; |
| 1091 | |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 1092 | ProgramStateRef State = C.getState(); |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 1093 | if (State->get<InvariantViolated>()) |
Gabor Horvath | b47128a | 2015-09-03 23:16:21 +0000 | [diff] [blame] | 1094 | return; |
| 1095 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1096 | auto ValDefOrUnknown = V.getAs<DefinedOrUnknownSVal>(); |
| 1097 | if (!ValDefOrUnknown) |
| 1098 | return; |
| 1099 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1100 | NullConstraint RhsNullness = getNullConstraint(*ValDefOrUnknown, State); |
| 1101 | |
| 1102 | Nullability ValNullability = Nullability::Unspecified; |
| 1103 | if (SymbolRef Sym = ValDefOrUnknown->getAsSymbol()) |
| 1104 | ValNullability = getNullabilityAnnotation(Sym->getType()); |
| 1105 | |
| 1106 | Nullability LocNullability = getNullabilityAnnotation(LocType); |
Devin Coughlin | 4ac1242 | 2016-04-13 17:59:24 +0000 | [diff] [blame] | 1107 | |
| 1108 | // If the type of the RHS expression is nonnull, don't warn. This |
| 1109 | // enables explicit suppression with a cast to nonnull. |
| 1110 | Nullability ValueExprTypeLevelNullability = Nullability::Unspecified; |
| 1111 | const Expr *ValueExpr = matchValueExprForBind(S); |
| 1112 | if (ValueExpr) { |
| 1113 | ValueExprTypeLevelNullability = |
| 1114 | getNullabilityAnnotation(lookThroughImplicitCasts(ValueExpr)->getType()); |
| 1115 | } |
| 1116 | |
| 1117 | bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull && |
| 1118 | RhsNullness == NullConstraint::IsNull); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1119 | if (Filter.CheckNullPassedToNonnull && |
Devin Coughlin | 4ac1242 | 2016-04-13 17:59:24 +0000 | [diff] [blame] | 1120 | NullAssignedToNonNull && |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1121 | ValNullability != Nullability::Nonnull && |
Devin Coughlin | 4ac1242 | 2016-04-13 17:59:24 +0000 | [diff] [blame] | 1122 | ValueExprTypeLevelNullability != Nullability::Nonnull && |
Devin Coughlin | 3ab8b2e7 | 2015-12-29 23:44:19 +0000 | [diff] [blame] | 1123 | !isARCNilInitializedLocal(C, S)) { |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1124 | static CheckerProgramPointTag Tag(this, "NullPassedToNonnull"); |
Devin Coughlin | e39bd40 | 2015-09-16 22:03:05 +0000 | [diff] [blame] | 1125 | ExplodedNode *N = C.generateErrorNode(State, &Tag); |
| 1126 | if (!N) |
| 1127 | return; |
Devin Coughlin | c198663 | 2015-11-24 19:15:11 +0000 | [diff] [blame] | 1128 | |
Devin Coughlin | 4ac1242 | 2016-04-13 17:59:24 +0000 | [diff] [blame] | 1129 | |
| 1130 | const Stmt *ValueStmt = S; |
| 1131 | if (ValueExpr) |
| 1132 | ValueStmt = ValueExpr; |
Devin Coughlin | c198663 | 2015-11-24 19:15:11 +0000 | [diff] [blame] | 1133 | |
Anna Zaks | 6d4e76b | 2016-12-15 22:55:15 +0000 | [diff] [blame] | 1134 | SmallString<256> SBuf; |
| 1135 | llvm::raw_svector_ostream OS(SBuf); |
| 1136 | OS << (LocType->isObjCObjectPointerType() ? "nil" : "Null"); |
| 1137 | OS << " assigned to a pointer which is expected to have non-null value"; |
| 1138 | reportBugIfInvariantHolds(OS.str(), |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 1139 | ErrorKind::NilAssignedToNonnull, N, nullptr, C, |
Devin Coughlin | 4ac1242 | 2016-04-13 17:59:24 +0000 | [diff] [blame] | 1140 | ValueStmt); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1141 | return; |
| 1142 | } |
Devin Coughlin | 4ac1242 | 2016-04-13 17:59:24 +0000 | [diff] [blame] | 1143 | |
| 1144 | // If null was returned from a non-null function, mark the nullability |
| 1145 | // invariant as violated even if the diagnostic was suppressed. |
| 1146 | if (NullAssignedToNonNull) { |
| 1147 | State = State->set<InvariantViolated>(true); |
| 1148 | C.addTransition(State); |
| 1149 | return; |
| 1150 | } |
| 1151 | |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1152 | // Intentionally missing case: '0' is bound to a reference. It is handled by |
| 1153 | // the DereferenceChecker. |
| 1154 | |
| 1155 | const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown); |
| 1156 | if (!ValueRegion) |
| 1157 | return; |
| 1158 | |
| 1159 | const NullabilityState *TrackedNullability = |
| 1160 | State->get<NullabilityMap>(ValueRegion); |
| 1161 | |
| 1162 | if (TrackedNullability) { |
| 1163 | if (RhsNullness == NullConstraint::IsNotNull || |
| 1164 | TrackedNullability->getValue() != Nullability::Nullable) |
| 1165 | return; |
| 1166 | if (Filter.CheckNullablePassedToNonnull && |
| 1167 | LocNullability == Nullability::Nonnull) { |
| 1168 | static CheckerProgramPointTag Tag(this, "NullablePassedToNonnull"); |
| 1169 | ExplodedNode *N = C.addTransition(State, C.getPredecessor(), &Tag); |
Devin Coughlin | 77942db | 2016-03-28 20:30:25 +0000 | [diff] [blame] | 1170 | reportBugIfInvariantHolds("Nullable pointer is assigned to a pointer " |
| 1171 | "which is expected to have non-null value", |
| 1172 | ErrorKind::NullableAssignedToNonnull, N, |
| 1173 | ValueRegion, C); |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1174 | } |
| 1175 | return; |
| 1176 | } |
| 1177 | |
| 1178 | const auto *BinOp = dyn_cast<BinaryOperator>(S); |
| 1179 | |
| 1180 | if (ValNullability == Nullability::Nullable) { |
| 1181 | // Trust the static information of the value more than the static |
| 1182 | // information on the location. |
| 1183 | const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S; |
| 1184 | State = State->set<NullabilityMap>( |
| 1185 | ValueRegion, NullabilityState(ValNullability, NullabilitySource)); |
| 1186 | C.addTransition(State); |
| 1187 | return; |
| 1188 | } |
| 1189 | |
| 1190 | if (LocNullability == Nullability::Nullable) { |
| 1191 | const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S; |
| 1192 | State = State->set<NullabilityMap>( |
| 1193 | ValueRegion, NullabilityState(LocNullability, NullabilitySource)); |
| 1194 | C.addTransition(State); |
| 1195 | } |
| 1196 | } |
| 1197 | |
| 1198 | void NullabilityChecker::printState(raw_ostream &Out, ProgramStateRef State, |
| 1199 | const char *NL, const char *Sep) const { |
| 1200 | |
| 1201 | NullabilityMapTy B = State->get<NullabilityMap>(); |
| 1202 | |
| 1203 | if (B.isEmpty()) |
| 1204 | return; |
| 1205 | |
| 1206 | Out << Sep << NL; |
| 1207 | |
| 1208 | for (NullabilityMapTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { |
| 1209 | Out << I->first << " : "; |
| 1210 | I->second.print(Out); |
| 1211 | Out << NL; |
| 1212 | } |
| 1213 | } |
| 1214 | |
Gabor Horvath | 2930735 | 2015-09-14 18:31:34 +0000 | [diff] [blame] | 1215 | #define REGISTER_CHECKER(name, trackingRequired) \ |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1216 | void ento::register##name##Checker(CheckerManager &mgr) { \ |
| 1217 | NullabilityChecker *checker = mgr.registerChecker<NullabilityChecker>(); \ |
| 1218 | checker->Filter.Check##name = true; \ |
| 1219 | checker->Filter.CheckName##name = mgr.getCurrentCheckName(); \ |
Gabor Horvath | 2930735 | 2015-09-14 18:31:34 +0000 | [diff] [blame] | 1220 | checker->NeedTracking = checker->NeedTracking || trackingRequired; \ |
Devin Coughlin | a1d9d75 | 2016-03-05 01:32:43 +0000 | [diff] [blame] | 1221 | checker->NoDiagnoseCallsToSystemHeaders = \ |
| 1222 | checker->NoDiagnoseCallsToSystemHeaders || \ |
| 1223 | mgr.getAnalyzerOptions().getBooleanOption( \ |
| 1224 | "NoDiagnoseCallsToSystemHeaders", false, checker, true); \ |
Gabor Horvath | 2869092 | 2015-08-26 23:17:43 +0000 | [diff] [blame] | 1225 | } |
| 1226 | |
Gabor Horvath | 2930735 | 2015-09-14 18:31:34 +0000 | [diff] [blame] | 1227 | // The checks are likely to be turned on by default and it is possible to do |
| 1228 | // them without tracking any nullability related information. As an optimization |
| 1229 | // no nullability information will be tracked when only these two checks are |
| 1230 | // enables. |
| 1231 | REGISTER_CHECKER(NullPassedToNonnull, false) |
| 1232 | REGISTER_CHECKER(NullReturnedFromNonnull, false) |
| 1233 | |
| 1234 | REGISTER_CHECKER(NullableDereferenced, true) |
| 1235 | REGISTER_CHECKER(NullablePassedToNonnull, true) |
| 1236 | REGISTER_CHECKER(NullableReturnedFromNonnull, true) |