George Karpenkov | 70c2ee3 | 2018-08-17 21:41:07 +0000 | [diff] [blame^] | 1 | //==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- 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 file defines the methods for RetainCountChecker, which implements |
| 11 | // a reference count checker for Core Foundation and Cocoa on (Mac OS X). |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "RetainCountChecker.h" |
| 16 | |
| 17 | using namespace clang; |
| 18 | using namespace ento; |
| 19 | using namespace objc_retain; |
| 20 | using namespace retaincountchecker; |
| 21 | using llvm::StrInStrNoCase; |
| 22 | |
| 23 | REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal) |
| 24 | |
| 25 | namespace clang { |
| 26 | namespace ento { |
| 27 | namespace retaincountchecker { |
| 28 | |
| 29 | const RefVal *getRefBinding(ProgramStateRef State, SymbolRef Sym) { |
| 30 | return State->get<RefBindings>(Sym); |
| 31 | } |
| 32 | |
| 33 | ProgramStateRef setRefBinding(ProgramStateRef State, SymbolRef Sym, |
| 34 | RefVal Val) { |
| 35 | return State->set<RefBindings>(Sym, Val); |
| 36 | } |
| 37 | |
| 38 | ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) { |
| 39 | return State->remove<RefBindings>(Sym); |
| 40 | } |
| 41 | |
| 42 | } // end namespace retaincountchecker |
| 43 | } // end namespace ento |
| 44 | } // end namespace clang |
| 45 | |
| 46 | void RefVal::print(raw_ostream &Out) const { |
| 47 | if (!T.isNull()) |
| 48 | Out << "Tracked " << T.getAsString() << '/'; |
| 49 | |
| 50 | switch (getKind()) { |
| 51 | default: llvm_unreachable("Invalid RefVal kind"); |
| 52 | case Owned: { |
| 53 | Out << "Owned"; |
| 54 | unsigned cnt = getCount(); |
| 55 | if (cnt) Out << " (+ " << cnt << ")"; |
| 56 | break; |
| 57 | } |
| 58 | |
| 59 | case NotOwned: { |
| 60 | Out << "NotOwned"; |
| 61 | unsigned cnt = getCount(); |
| 62 | if (cnt) Out << " (+ " << cnt << ")"; |
| 63 | break; |
| 64 | } |
| 65 | |
| 66 | case ReturnedOwned: { |
| 67 | Out << "ReturnedOwned"; |
| 68 | unsigned cnt = getCount(); |
| 69 | if (cnt) Out << " (+ " << cnt << ")"; |
| 70 | break; |
| 71 | } |
| 72 | |
| 73 | case ReturnedNotOwned: { |
| 74 | Out << "ReturnedNotOwned"; |
| 75 | unsigned cnt = getCount(); |
| 76 | if (cnt) Out << " (+ " << cnt << ")"; |
| 77 | break; |
| 78 | } |
| 79 | |
| 80 | case Released: |
| 81 | Out << "Released"; |
| 82 | break; |
| 83 | |
| 84 | case ErrorDeallocNotOwned: |
| 85 | Out << "-dealloc (not-owned)"; |
| 86 | break; |
| 87 | |
| 88 | case ErrorLeak: |
| 89 | Out << "Leaked"; |
| 90 | break; |
| 91 | |
| 92 | case ErrorLeakReturned: |
| 93 | Out << "Leaked (Bad naming)"; |
| 94 | break; |
| 95 | |
| 96 | case ErrorUseAfterRelease: |
| 97 | Out << "Use-After-Release [ERROR]"; |
| 98 | break; |
| 99 | |
| 100 | case ErrorReleaseNotOwned: |
| 101 | Out << "Release of Not-Owned [ERROR]"; |
| 102 | break; |
| 103 | |
| 104 | case RefVal::ErrorOverAutorelease: |
| 105 | Out << "Over-autoreleased"; |
| 106 | break; |
| 107 | |
| 108 | case RefVal::ErrorReturnedNotOwned: |
| 109 | Out << "Non-owned object returned instead of owned"; |
| 110 | break; |
| 111 | } |
| 112 | |
| 113 | switch (getIvarAccessHistory()) { |
| 114 | case IvarAccessHistory::None: |
| 115 | break; |
| 116 | case IvarAccessHistory::AccessedDirectly: |
| 117 | Out << " [direct ivar access]"; |
| 118 | break; |
| 119 | case IvarAccessHistory::ReleasedAfterDirectAccess: |
| 120 | Out << " [released after direct ivar access]"; |
| 121 | } |
| 122 | |
| 123 | if (ACnt) { |
| 124 | Out << " [autorelease -" << ACnt << ']'; |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | namespace { |
| 129 | class StopTrackingCallback final : public SymbolVisitor { |
| 130 | ProgramStateRef state; |
| 131 | public: |
| 132 | StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {} |
| 133 | ProgramStateRef getState() const { return state; } |
| 134 | |
| 135 | bool VisitSymbol(SymbolRef sym) override { |
| 136 | state = state->remove<RefBindings>(sym); |
| 137 | return true; |
| 138 | } |
| 139 | }; |
| 140 | } // end anonymous namespace |
| 141 | |
| 142 | //===----------------------------------------------------------------------===// |
| 143 | // Handle statements that may have an effect on refcounts. |
| 144 | //===----------------------------------------------------------------------===// |
| 145 | |
| 146 | void RetainCountChecker::checkPostStmt(const BlockExpr *BE, |
| 147 | CheckerContext &C) const { |
| 148 | |
| 149 | // Scan the BlockDecRefExprs for any object the retain count checker |
| 150 | // may be tracking. |
| 151 | if (!BE->getBlockDecl()->hasCaptures()) |
| 152 | return; |
| 153 | |
| 154 | ProgramStateRef state = C.getState(); |
| 155 | auto *R = cast<BlockDataRegion>(C.getSVal(BE).getAsRegion()); |
| 156 | |
| 157 | BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(), |
| 158 | E = R->referenced_vars_end(); |
| 159 | |
| 160 | if (I == E) |
| 161 | return; |
| 162 | |
| 163 | // FIXME: For now we invalidate the tracking of all symbols passed to blocks |
| 164 | // via captured variables, even though captured variables result in a copy |
| 165 | // and in implicit increment/decrement of a retain count. |
| 166 | SmallVector<const MemRegion*, 10> Regions; |
| 167 | const LocationContext *LC = C.getLocationContext(); |
| 168 | MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager(); |
| 169 | |
| 170 | for ( ; I != E; ++I) { |
| 171 | const VarRegion *VR = I.getCapturedRegion(); |
| 172 | if (VR->getSuperRegion() == R) { |
| 173 | VR = MemMgr.getVarRegion(VR->getDecl(), LC); |
| 174 | } |
| 175 | Regions.push_back(VR); |
| 176 | } |
| 177 | |
| 178 | state = |
| 179 | state->scanReachableSymbols<StopTrackingCallback>(Regions.data(), |
| 180 | Regions.data() + Regions.size()).getState(); |
| 181 | C.addTransition(state); |
| 182 | } |
| 183 | |
| 184 | void RetainCountChecker::checkPostStmt(const CastExpr *CE, |
| 185 | CheckerContext &C) const { |
| 186 | const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE); |
| 187 | if (!BE) |
| 188 | return; |
| 189 | |
| 190 | ArgEffect AE = IncRef; |
| 191 | |
| 192 | switch (BE->getBridgeKind()) { |
| 193 | case OBC_Bridge: |
| 194 | // Do nothing. |
| 195 | return; |
| 196 | case OBC_BridgeRetained: |
| 197 | AE = IncRef; |
| 198 | break; |
| 199 | case OBC_BridgeTransfer: |
| 200 | AE = DecRefBridgedTransferred; |
| 201 | break; |
| 202 | } |
| 203 | |
| 204 | ProgramStateRef state = C.getState(); |
| 205 | SymbolRef Sym = C.getSVal(CE).getAsLocSymbol(); |
| 206 | if (!Sym) |
| 207 | return; |
| 208 | const RefVal* T = getRefBinding(state, Sym); |
| 209 | if (!T) |
| 210 | return; |
| 211 | |
| 212 | RefVal::Kind hasErr = (RefVal::Kind) 0; |
| 213 | state = updateSymbol(state, Sym, *T, AE, hasErr, C); |
| 214 | |
| 215 | if (hasErr) { |
| 216 | // FIXME: If we get an error during a bridge cast, should we report it? |
| 217 | return; |
| 218 | } |
| 219 | |
| 220 | C.addTransition(state); |
| 221 | } |
| 222 | |
| 223 | void RetainCountChecker::processObjCLiterals(CheckerContext &C, |
| 224 | const Expr *Ex) const { |
| 225 | ProgramStateRef state = C.getState(); |
| 226 | const ExplodedNode *pred = C.getPredecessor(); |
| 227 | for (const Stmt *Child : Ex->children()) { |
| 228 | SVal V = pred->getSVal(Child); |
| 229 | if (SymbolRef sym = V.getAsSymbol()) |
| 230 | if (const RefVal* T = getRefBinding(state, sym)) { |
| 231 | RefVal::Kind hasErr = (RefVal::Kind) 0; |
| 232 | state = updateSymbol(state, sym, *T, MayEscape, hasErr, C); |
| 233 | if (hasErr) { |
| 234 | processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C); |
| 235 | return; |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | // Return the object as autoreleased. |
| 241 | // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC); |
| 242 | if (SymbolRef sym = |
| 243 | state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) { |
| 244 | QualType ResultTy = Ex->getType(); |
| 245 | state = setRefBinding(state, sym, |
| 246 | RefVal::makeNotOwned(RetEffect::ObjC, ResultTy)); |
| 247 | } |
| 248 | |
| 249 | C.addTransition(state); |
| 250 | } |
| 251 | |
| 252 | void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL, |
| 253 | CheckerContext &C) const { |
| 254 | // Apply the 'MayEscape' to all values. |
| 255 | processObjCLiterals(C, AL); |
| 256 | } |
| 257 | |
| 258 | void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL, |
| 259 | CheckerContext &C) const { |
| 260 | // Apply the 'MayEscape' to all keys and values. |
| 261 | processObjCLiterals(C, DL); |
| 262 | } |
| 263 | |
| 264 | void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex, |
| 265 | CheckerContext &C) const { |
| 266 | const ExplodedNode *Pred = C.getPredecessor(); |
| 267 | ProgramStateRef State = Pred->getState(); |
| 268 | |
| 269 | if (SymbolRef Sym = Pred->getSVal(Ex).getAsSymbol()) { |
| 270 | QualType ResultTy = Ex->getType(); |
| 271 | State = setRefBinding(State, Sym, |
| 272 | RefVal::makeNotOwned(RetEffect::ObjC, ResultTy)); |
| 273 | } |
| 274 | |
| 275 | C.addTransition(State); |
| 276 | } |
| 277 | |
| 278 | void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE, |
| 279 | CheckerContext &C) const { |
| 280 | Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>(); |
| 281 | if (!IVarLoc) |
| 282 | return; |
| 283 | |
| 284 | ProgramStateRef State = C.getState(); |
| 285 | SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol(); |
| 286 | if (!Sym || !dyn_cast_or_null<ObjCIvarRegion>(Sym->getOriginRegion())) |
| 287 | return; |
| 288 | |
| 289 | // Accessing an ivar directly is unusual. If we've done that, be more |
| 290 | // forgiving about what the surrounding code is allowed to do. |
| 291 | |
| 292 | QualType Ty = Sym->getType(); |
| 293 | RetEffect::ObjKind Kind; |
| 294 | if (Ty->isObjCRetainableType()) |
| 295 | Kind = RetEffect::ObjC; |
| 296 | else if (coreFoundation::isCFObjectRef(Ty)) |
| 297 | Kind = RetEffect::CF; |
| 298 | else |
| 299 | return; |
| 300 | |
| 301 | // If the value is already known to be nil, don't bother tracking it. |
| 302 | ConstraintManager &CMgr = State->getConstraintManager(); |
| 303 | if (CMgr.isNull(State, Sym).isConstrainedTrue()) |
| 304 | return; |
| 305 | |
| 306 | if (const RefVal *RV = getRefBinding(State, Sym)) { |
| 307 | // If we've seen this symbol before, or we're only seeing it now because |
| 308 | // of something the analyzer has synthesized, don't do anything. |
| 309 | if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None || |
| 310 | isSynthesizedAccessor(C.getStackFrame())) { |
| 311 | return; |
| 312 | } |
| 313 | |
| 314 | // Note that this value has been loaded from an ivar. |
| 315 | C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess())); |
| 316 | return; |
| 317 | } |
| 318 | |
| 319 | RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty); |
| 320 | |
| 321 | // In a synthesized accessor, the effective retain count is +0. |
| 322 | if (isSynthesizedAccessor(C.getStackFrame())) { |
| 323 | C.addTransition(setRefBinding(State, Sym, PlusZero)); |
| 324 | return; |
| 325 | } |
| 326 | |
| 327 | State = setRefBinding(State, Sym, PlusZero.withIvarAccess()); |
| 328 | C.addTransition(State); |
| 329 | } |
| 330 | |
| 331 | void RetainCountChecker::checkPostCall(const CallEvent &Call, |
| 332 | CheckerContext &C) const { |
| 333 | RetainSummaryManager &Summaries = getSummaryManager(C); |
| 334 | const RetainSummary *Summ = Summaries.getSummary(Call, C.getState()); |
| 335 | |
| 336 | if (C.wasInlined) { |
| 337 | processSummaryOfInlined(*Summ, Call, C); |
| 338 | return; |
| 339 | } |
| 340 | checkSummary(*Summ, Call, C); |
| 341 | } |
| 342 | |
| 343 | /// GetReturnType - Used to get the return type of a message expression or |
| 344 | /// function call with the intention of affixing that type to a tracked symbol. |
| 345 | /// While the return type can be queried directly from RetEx, when |
| 346 | /// invoking class methods we augment to the return type to be that of |
| 347 | /// a pointer to the class (as opposed it just being id). |
| 348 | // FIXME: We may be able to do this with related result types instead. |
| 349 | // This function is probably overestimating. |
| 350 | static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) { |
| 351 | QualType RetTy = RetE->getType(); |
| 352 | // If RetE is not a message expression just return its type. |
| 353 | // If RetE is a message expression, return its types if it is something |
| 354 | /// more specific than id. |
| 355 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE)) |
| 356 | if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>()) |
| 357 | if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() || |
| 358 | PT->isObjCClassType()) { |
| 359 | // At this point we know the return type of the message expression is |
| 360 | // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this |
| 361 | // is a call to a class method whose type we can resolve. In such |
| 362 | // cases, promote the return type to XXX* (where XXX is the class). |
| 363 | const ObjCInterfaceDecl *D = ME->getReceiverInterface(); |
| 364 | return !D ? RetTy : |
| 365 | Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D)); |
| 366 | } |
| 367 | |
| 368 | return RetTy; |
| 369 | } |
| 370 | |
| 371 | // We don't always get the exact modeling of the function with regards to the |
| 372 | // retain count checker even when the function is inlined. For example, we need |
| 373 | // to stop tracking the symbols which were marked with StopTrackingHard. |
| 374 | void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ, |
| 375 | const CallEvent &CallOrMsg, |
| 376 | CheckerContext &C) const { |
| 377 | ProgramStateRef state = C.getState(); |
| 378 | |
| 379 | // Evaluate the effect of the arguments. |
| 380 | for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) { |
| 381 | if (Summ.getArg(idx) == StopTrackingHard) { |
| 382 | SVal V = CallOrMsg.getArgSVal(idx); |
| 383 | if (SymbolRef Sym = V.getAsLocSymbol()) { |
| 384 | state = removeRefBinding(state, Sym); |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | // Evaluate the effect on the message receiver. |
| 390 | const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg); |
| 391 | if (MsgInvocation) { |
| 392 | if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) { |
| 393 | if (Summ.getReceiverEffect() == StopTrackingHard) { |
| 394 | state = removeRefBinding(state, Sym); |
| 395 | } |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | // Consult the summary for the return value. |
| 400 | RetEffect RE = Summ.getRetEffect(); |
| 401 | if (RE.getKind() == RetEffect::NoRetHard) { |
| 402 | SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol(); |
| 403 | if (Sym) |
| 404 | state = removeRefBinding(state, Sym); |
| 405 | } |
| 406 | |
| 407 | C.addTransition(state); |
| 408 | } |
| 409 | |
| 410 | static ProgramStateRef updateOutParameter(ProgramStateRef State, |
| 411 | SVal ArgVal, |
| 412 | ArgEffect Effect) { |
| 413 | auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion()); |
| 414 | if (!ArgRegion) |
| 415 | return State; |
| 416 | |
| 417 | QualType PointeeTy = ArgRegion->getValueType(); |
| 418 | if (!coreFoundation::isCFObjectRef(PointeeTy)) |
| 419 | return State; |
| 420 | |
| 421 | SVal PointeeVal = State->getSVal(ArgRegion); |
| 422 | SymbolRef Pointee = PointeeVal.getAsLocSymbol(); |
| 423 | if (!Pointee) |
| 424 | return State; |
| 425 | |
| 426 | switch (Effect) { |
| 427 | case UnretainedOutParameter: |
| 428 | State = setRefBinding(State, Pointee, |
| 429 | RefVal::makeNotOwned(RetEffect::CF, PointeeTy)); |
| 430 | break; |
| 431 | case RetainedOutParameter: |
| 432 | // Do nothing. Retained out parameters will either point to a +1 reference |
| 433 | // or NULL, but the way you check for failure differs depending on the API. |
| 434 | // Consequently, we don't have a good way to track them yet. |
| 435 | break; |
| 436 | |
| 437 | default: |
| 438 | llvm_unreachable("only for out parameters"); |
| 439 | } |
| 440 | |
| 441 | return State; |
| 442 | } |
| 443 | |
| 444 | void RetainCountChecker::checkSummary(const RetainSummary &Summ, |
| 445 | const CallEvent &CallOrMsg, |
| 446 | CheckerContext &C) const { |
| 447 | ProgramStateRef state = C.getState(); |
| 448 | |
| 449 | // Evaluate the effect of the arguments. |
| 450 | RefVal::Kind hasErr = (RefVal::Kind) 0; |
| 451 | SourceRange ErrorRange; |
| 452 | SymbolRef ErrorSym = nullptr; |
| 453 | |
| 454 | for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) { |
| 455 | SVal V = CallOrMsg.getArgSVal(idx); |
| 456 | |
| 457 | ArgEffect Effect = Summ.getArg(idx); |
| 458 | if (Effect == RetainedOutParameter || Effect == UnretainedOutParameter) { |
| 459 | state = updateOutParameter(state, V, Effect); |
| 460 | } else if (SymbolRef Sym = V.getAsLocSymbol()) { |
| 461 | if (const RefVal *T = getRefBinding(state, Sym)) { |
| 462 | state = updateSymbol(state, Sym, *T, Effect, hasErr, C); |
| 463 | if (hasErr) { |
| 464 | ErrorRange = CallOrMsg.getArgSourceRange(idx); |
| 465 | ErrorSym = Sym; |
| 466 | break; |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | // Evaluate the effect on the message receiver. |
| 473 | bool ReceiverIsTracked = false; |
| 474 | if (!hasErr) { |
| 475 | const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg); |
| 476 | if (MsgInvocation) { |
| 477 | if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) { |
| 478 | if (const RefVal *T = getRefBinding(state, Sym)) { |
| 479 | ReceiverIsTracked = true; |
| 480 | state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(), |
| 481 | hasErr, C); |
| 482 | if (hasErr) { |
| 483 | ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange(); |
| 484 | ErrorSym = Sym; |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | // Process any errors. |
| 492 | if (hasErr) { |
| 493 | processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C); |
| 494 | return; |
| 495 | } |
| 496 | |
| 497 | // Consult the summary for the return value. |
| 498 | RetEffect RE = Summ.getRetEffect(); |
| 499 | |
| 500 | if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) { |
| 501 | if (ReceiverIsTracked) |
| 502 | RE = getSummaryManager(C).getObjAllocRetEffect(); |
| 503 | else |
| 504 | RE = RetEffect::MakeNoRet(); |
| 505 | } |
| 506 | |
| 507 | switch (RE.getKind()) { |
| 508 | default: |
| 509 | llvm_unreachable("Unhandled RetEffect."); |
| 510 | |
| 511 | case RetEffect::NoRet: |
| 512 | case RetEffect::NoRetHard: |
| 513 | // No work necessary. |
| 514 | break; |
| 515 | |
| 516 | case RetEffect::OwnedSymbol: { |
| 517 | SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol(); |
| 518 | if (!Sym) |
| 519 | break; |
| 520 | |
| 521 | // Use the result type from the CallEvent as it automatically adjusts |
| 522 | // for methods/functions that return references. |
| 523 | QualType ResultTy = CallOrMsg.getResultType(); |
| 524 | state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(), |
| 525 | ResultTy)); |
| 526 | |
| 527 | // FIXME: Add a flag to the checker where allocations are assumed to |
| 528 | // *not* fail. |
| 529 | break; |
| 530 | } |
| 531 | |
| 532 | case RetEffect::NotOwnedSymbol: { |
| 533 | const Expr *Ex = CallOrMsg.getOriginExpr(); |
| 534 | SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol(); |
| 535 | if (!Sym) |
| 536 | break; |
| 537 | assert(Ex); |
| 538 | // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *. |
| 539 | QualType ResultTy = GetReturnType(Ex, C.getASTContext()); |
| 540 | state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(), |
| 541 | ResultTy)); |
| 542 | break; |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | // This check is actually necessary; otherwise the statement builder thinks |
| 547 | // we've hit a previously-found path. |
| 548 | // Normally addTransition takes care of this, but we want the node pointer. |
| 549 | ExplodedNode *NewNode; |
| 550 | if (state == C.getState()) { |
| 551 | NewNode = C.getPredecessor(); |
| 552 | } else { |
| 553 | NewNode = C.addTransition(state); |
| 554 | } |
| 555 | |
| 556 | // Annotate the node with summary we used. |
| 557 | if (NewNode) { |
| 558 | // FIXME: This is ugly. See checkEndAnalysis for why it's necessary. |
| 559 | if (ShouldResetSummaryLog) { |
| 560 | SummaryLog.clear(); |
| 561 | ShouldResetSummaryLog = false; |
| 562 | } |
| 563 | SummaryLog[NewNode] = &Summ; |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | ProgramStateRef |
| 568 | RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym, |
| 569 | RefVal V, ArgEffect E, RefVal::Kind &hasErr, |
| 570 | CheckerContext &C) const { |
| 571 | bool IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount; |
| 572 | switch (E) { |
| 573 | default: |
| 574 | break; |
| 575 | case IncRefMsg: |
| 576 | E = IgnoreRetainMsg ? DoNothing : IncRef; |
| 577 | break; |
| 578 | case DecRefMsg: |
| 579 | E = IgnoreRetainMsg ? DoNothing: DecRef; |
| 580 | break; |
| 581 | case DecRefMsgAndStopTrackingHard: |
| 582 | E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard; |
| 583 | break; |
| 584 | } |
| 585 | |
| 586 | // Handle all use-after-releases. |
| 587 | if (V.getKind() == RefVal::Released) { |
| 588 | V = V ^ RefVal::ErrorUseAfterRelease; |
| 589 | hasErr = V.getKind(); |
| 590 | return setRefBinding(state, sym, V); |
| 591 | } |
| 592 | |
| 593 | switch (E) { |
| 594 | case DecRefMsg: |
| 595 | case IncRefMsg: |
| 596 | case DecRefMsgAndStopTrackingHard: |
| 597 | llvm_unreachable("DecRefMsg/IncRefMsg already converted"); |
| 598 | |
| 599 | case UnretainedOutParameter: |
| 600 | case RetainedOutParameter: |
| 601 | llvm_unreachable("Applies to pointer-to-pointer parameters, which should " |
| 602 | "not have ref state."); |
| 603 | |
| 604 | case Dealloc: |
| 605 | switch (V.getKind()) { |
| 606 | default: |
| 607 | llvm_unreachable("Invalid RefVal state for an explicit dealloc."); |
| 608 | case RefVal::Owned: |
| 609 | // The object immediately transitions to the released state. |
| 610 | V = V ^ RefVal::Released; |
| 611 | V.clearCounts(); |
| 612 | return setRefBinding(state, sym, V); |
| 613 | case RefVal::NotOwned: |
| 614 | V = V ^ RefVal::ErrorDeallocNotOwned; |
| 615 | hasErr = V.getKind(); |
| 616 | break; |
| 617 | } |
| 618 | break; |
| 619 | |
| 620 | case MayEscape: |
| 621 | if (V.getKind() == RefVal::Owned) { |
| 622 | V = V ^ RefVal::NotOwned; |
| 623 | break; |
| 624 | } |
| 625 | |
| 626 | // Fall-through. |
| 627 | |
| 628 | case DoNothing: |
| 629 | return state; |
| 630 | |
| 631 | case Autorelease: |
| 632 | // Update the autorelease counts. |
| 633 | V = V.autorelease(); |
| 634 | break; |
| 635 | |
| 636 | case StopTracking: |
| 637 | case StopTrackingHard: |
| 638 | return removeRefBinding(state, sym); |
| 639 | |
| 640 | case IncRef: |
| 641 | switch (V.getKind()) { |
| 642 | default: |
| 643 | llvm_unreachable("Invalid RefVal state for a retain."); |
| 644 | case RefVal::Owned: |
| 645 | case RefVal::NotOwned: |
| 646 | V = V + 1; |
| 647 | break; |
| 648 | } |
| 649 | break; |
| 650 | |
| 651 | case DecRef: |
| 652 | case DecRefBridgedTransferred: |
| 653 | case DecRefAndStopTrackingHard: |
| 654 | switch (V.getKind()) { |
| 655 | default: |
| 656 | // case 'RefVal::Released' handled above. |
| 657 | llvm_unreachable("Invalid RefVal state for a release."); |
| 658 | |
| 659 | case RefVal::Owned: |
| 660 | assert(V.getCount() > 0); |
| 661 | if (V.getCount() == 1) { |
| 662 | if (E == DecRefBridgedTransferred || |
| 663 | V.getIvarAccessHistory() == |
| 664 | RefVal::IvarAccessHistory::AccessedDirectly) |
| 665 | V = V ^ RefVal::NotOwned; |
| 666 | else |
| 667 | V = V ^ RefVal::Released; |
| 668 | } else if (E == DecRefAndStopTrackingHard) { |
| 669 | return removeRefBinding(state, sym); |
| 670 | } |
| 671 | |
| 672 | V = V - 1; |
| 673 | break; |
| 674 | |
| 675 | case RefVal::NotOwned: |
| 676 | if (V.getCount() > 0) { |
| 677 | if (E == DecRefAndStopTrackingHard) |
| 678 | return removeRefBinding(state, sym); |
| 679 | V = V - 1; |
| 680 | } else if (V.getIvarAccessHistory() == |
| 681 | RefVal::IvarAccessHistory::AccessedDirectly) { |
| 682 | // Assume that the instance variable was holding on the object at |
| 683 | // +1, and we just didn't know. |
| 684 | if (E == DecRefAndStopTrackingHard) |
| 685 | return removeRefBinding(state, sym); |
| 686 | V = V.releaseViaIvar() ^ RefVal::Released; |
| 687 | } else { |
| 688 | V = V ^ RefVal::ErrorReleaseNotOwned; |
| 689 | hasErr = V.getKind(); |
| 690 | } |
| 691 | break; |
| 692 | } |
| 693 | break; |
| 694 | } |
| 695 | return setRefBinding(state, sym, V); |
| 696 | } |
| 697 | |
| 698 | void RetainCountChecker::processNonLeakError(ProgramStateRef St, |
| 699 | SourceRange ErrorRange, |
| 700 | RefVal::Kind ErrorKind, |
| 701 | SymbolRef Sym, |
| 702 | CheckerContext &C) const { |
| 703 | // HACK: Ignore retain-count issues on values accessed through ivars, |
| 704 | // because of cases like this: |
| 705 | // [_contentView retain]; |
| 706 | // [_contentView removeFromSuperview]; |
| 707 | // [self addSubview:_contentView]; // invalidates 'self' |
| 708 | // [_contentView release]; |
| 709 | if (const RefVal *RV = getRefBinding(St, Sym)) |
| 710 | if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None) |
| 711 | return; |
| 712 | |
| 713 | ExplodedNode *N = C.generateErrorNode(St); |
| 714 | if (!N) |
| 715 | return; |
| 716 | |
| 717 | CFRefBug *BT; |
| 718 | switch (ErrorKind) { |
| 719 | default: |
| 720 | llvm_unreachable("Unhandled error."); |
| 721 | case RefVal::ErrorUseAfterRelease: |
| 722 | if (!useAfterRelease) |
| 723 | useAfterRelease.reset(new UseAfterRelease(this)); |
| 724 | BT = useAfterRelease.get(); |
| 725 | break; |
| 726 | case RefVal::ErrorReleaseNotOwned: |
| 727 | if (!releaseNotOwned) |
| 728 | releaseNotOwned.reset(new BadRelease(this)); |
| 729 | BT = releaseNotOwned.get(); |
| 730 | break; |
| 731 | case RefVal::ErrorDeallocNotOwned: |
| 732 | if (!deallocNotOwned) |
| 733 | deallocNotOwned.reset(new DeallocNotOwned(this)); |
| 734 | BT = deallocNotOwned.get(); |
| 735 | break; |
| 736 | } |
| 737 | |
| 738 | assert(BT); |
| 739 | auto report = std::unique_ptr<BugReport>( |
| 740 | new CFRefReport(*BT, C.getASTContext().getLangOpts(), |
| 741 | SummaryLog, N, Sym)); |
| 742 | report->addRange(ErrorRange); |
| 743 | C.emitReport(std::move(report)); |
| 744 | } |
| 745 | |
| 746 | //===----------------------------------------------------------------------===// |
| 747 | // Handle the return values of retain-count-related functions. |
| 748 | //===----------------------------------------------------------------------===// |
| 749 | |
| 750 | bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const { |
| 751 | // Get the callee. We're only interested in simple C functions. |
| 752 | ProgramStateRef state = C.getState(); |
| 753 | const FunctionDecl *FD = C.getCalleeDecl(CE); |
| 754 | if (!FD) |
| 755 | return false; |
| 756 | |
| 757 | IdentifierInfo *II = FD->getIdentifier(); |
| 758 | if (!II) |
| 759 | return false; |
| 760 | |
| 761 | // For now, we're only handling the functions that return aliases of their |
| 762 | // arguments: CFRetain (and its families). |
| 763 | // Eventually we should add other functions we can model entirely, |
| 764 | // such as CFRelease, which don't invalidate their arguments or globals. |
| 765 | if (CE->getNumArgs() != 1) |
| 766 | return false; |
| 767 | |
| 768 | // Get the name of the function. |
| 769 | StringRef FName = II->getName(); |
| 770 | FName = FName.substr(FName.find_first_not_of('_')); |
| 771 | |
| 772 | // See if it's one of the specific functions we know how to eval. |
| 773 | bool canEval = false; |
| 774 | // See if the function has 'rc_ownership_trusted_implementation' |
| 775 | // annotate attribute. If it does, we will not inline it. |
| 776 | bool hasTrustedImplementationAnnotation = false; |
| 777 | |
| 778 | QualType ResultTy = CE->getCallReturnType(C.getASTContext()); |
| 779 | if (ResultTy->isPointerType()) { |
| 780 | // Handle: (CF|CG|CV)Retain |
| 781 | // CFAutorelease |
| 782 | // It's okay to be a little sloppy here. |
| 783 | if (cocoa::isRefType(ResultTy, "CF", FName) || |
| 784 | cocoa::isRefType(ResultTy, "CG", FName) || |
| 785 | cocoa::isRefType(ResultTy, "CV", FName)) { |
| 786 | canEval = RetainSummary::isRetain(FD, FName) || |
| 787 | RetainSummary::isAutorelease(FD, FName); |
| 788 | } else { |
| 789 | if (FD->getDefinition()) { |
| 790 | canEval = RetainSummary::isTrustedReferenceCountImplementation( |
| 791 | FD->getDefinition()); |
| 792 | hasTrustedImplementationAnnotation = canEval; |
| 793 | } |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | if (!canEval) |
| 798 | return false; |
| 799 | |
| 800 | // Bind the return value. |
| 801 | const LocationContext *LCtx = C.getLocationContext(); |
| 802 | SVal RetVal = state->getSVal(CE->getArg(0), LCtx); |
| 803 | if (RetVal.isUnknown() || |
| 804 | (hasTrustedImplementationAnnotation && !ResultTy.isNull())) { |
| 805 | // If the receiver is unknown or the function has |
| 806 | // 'rc_ownership_trusted_implementation' annotate attribute, conjure a |
| 807 | // return value. |
| 808 | SValBuilder &SVB = C.getSValBuilder(); |
| 809 | RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount()); |
| 810 | } |
| 811 | state = state->BindExpr(CE, LCtx, RetVal, false); |
| 812 | |
| 813 | // FIXME: This should not be necessary, but otherwise the argument seems to be |
| 814 | // considered alive during the next statement. |
| 815 | if (const MemRegion *ArgRegion = RetVal.getAsRegion()) { |
| 816 | // Save the refcount status of the argument. |
| 817 | SymbolRef Sym = RetVal.getAsLocSymbol(); |
| 818 | const RefVal *Binding = nullptr; |
| 819 | if (Sym) |
| 820 | Binding = getRefBinding(state, Sym); |
| 821 | |
| 822 | // Invalidate the argument region. |
| 823 | state = state->invalidateRegions( |
| 824 | ArgRegion, CE, C.blockCount(), LCtx, |
| 825 | /*CausesPointerEscape*/ hasTrustedImplementationAnnotation); |
| 826 | |
| 827 | // Restore the refcount status of the argument. |
| 828 | if (Binding) |
| 829 | state = setRefBinding(state, Sym, *Binding); |
| 830 | } |
| 831 | |
| 832 | C.addTransition(state); |
| 833 | return true; |
| 834 | } |
| 835 | |
| 836 | //===----------------------------------------------------------------------===// |
| 837 | // Handle return statements. |
| 838 | //===----------------------------------------------------------------------===// |
| 839 | |
| 840 | void RetainCountChecker::checkPreStmt(const ReturnStmt *S, |
| 841 | CheckerContext &C) const { |
| 842 | |
| 843 | // Only adjust the reference count if this is the top-level call frame, |
| 844 | // and not the result of inlining. In the future, we should do |
| 845 | // better checking even for inlined calls, and see if they match |
| 846 | // with their expected semantics (e.g., the method should return a retained |
| 847 | // object, etc.). |
| 848 | if (!C.inTopFrame()) |
| 849 | return; |
| 850 | |
| 851 | const Expr *RetE = S->getRetValue(); |
| 852 | if (!RetE) |
| 853 | return; |
| 854 | |
| 855 | ProgramStateRef state = C.getState(); |
| 856 | SymbolRef Sym = |
| 857 | state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol(); |
| 858 | if (!Sym) |
| 859 | return; |
| 860 | |
| 861 | // Get the reference count binding (if any). |
| 862 | const RefVal *T = getRefBinding(state, Sym); |
| 863 | if (!T) |
| 864 | return; |
| 865 | |
| 866 | // Change the reference count. |
| 867 | RefVal X = *T; |
| 868 | |
| 869 | switch (X.getKind()) { |
| 870 | case RefVal::Owned: { |
| 871 | unsigned cnt = X.getCount(); |
| 872 | assert(cnt > 0); |
| 873 | X.setCount(cnt - 1); |
| 874 | X = X ^ RefVal::ReturnedOwned; |
| 875 | break; |
| 876 | } |
| 877 | |
| 878 | case RefVal::NotOwned: { |
| 879 | unsigned cnt = X.getCount(); |
| 880 | if (cnt) { |
| 881 | X.setCount(cnt - 1); |
| 882 | X = X ^ RefVal::ReturnedOwned; |
| 883 | } |
| 884 | else { |
| 885 | X = X ^ RefVal::ReturnedNotOwned; |
| 886 | } |
| 887 | break; |
| 888 | } |
| 889 | |
| 890 | default: |
| 891 | return; |
| 892 | } |
| 893 | |
| 894 | // Update the binding. |
| 895 | state = setRefBinding(state, Sym, X); |
| 896 | ExplodedNode *Pred = C.addTransition(state); |
| 897 | |
| 898 | // At this point we have updated the state properly. |
| 899 | // Everything after this is merely checking to see if the return value has |
| 900 | // been over- or under-retained. |
| 901 | |
| 902 | // Did we cache out? |
| 903 | if (!Pred) |
| 904 | return; |
| 905 | |
| 906 | // Update the autorelease counts. |
| 907 | static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease"); |
| 908 | state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X); |
| 909 | |
| 910 | // Did we cache out? |
| 911 | if (!state) |
| 912 | return; |
| 913 | |
| 914 | // Get the updated binding. |
| 915 | T = getRefBinding(state, Sym); |
| 916 | assert(T); |
| 917 | X = *T; |
| 918 | |
| 919 | // Consult the summary of the enclosing method. |
| 920 | RetainSummaryManager &Summaries = getSummaryManager(C); |
| 921 | const Decl *CD = &Pred->getCodeDecl(); |
| 922 | RetEffect RE = RetEffect::MakeNoRet(); |
| 923 | |
| 924 | // FIXME: What is the convention for blocks? Is there one? |
| 925 | if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) { |
| 926 | const RetainSummary *Summ = Summaries.getMethodSummary(MD); |
| 927 | RE = Summ->getRetEffect(); |
| 928 | } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) { |
| 929 | if (!isa<CXXMethodDecl>(FD)) { |
| 930 | const RetainSummary *Summ = Summaries.getFunctionSummary(FD); |
| 931 | RE = Summ->getRetEffect(); |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state); |
| 936 | } |
| 937 | |
| 938 | void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S, |
| 939 | CheckerContext &C, |
| 940 | ExplodedNode *Pred, |
| 941 | RetEffect RE, RefVal X, |
| 942 | SymbolRef Sym, |
| 943 | ProgramStateRef state) const { |
| 944 | // HACK: Ignore retain-count issues on values accessed through ivars, |
| 945 | // because of cases like this: |
| 946 | // [_contentView retain]; |
| 947 | // [_contentView removeFromSuperview]; |
| 948 | // [self addSubview:_contentView]; // invalidates 'self' |
| 949 | // [_contentView release]; |
| 950 | if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None) |
| 951 | return; |
| 952 | |
| 953 | // Any leaks or other errors? |
| 954 | if (X.isReturnedOwned() && X.getCount() == 0) { |
| 955 | if (RE.getKind() != RetEffect::NoRet) { |
| 956 | bool hasError = false; |
| 957 | if (!RE.isOwned()) { |
| 958 | // The returning type is a CF, we expect the enclosing method should |
| 959 | // return ownership. |
| 960 | hasError = true; |
| 961 | X = X ^ RefVal::ErrorLeakReturned; |
| 962 | } |
| 963 | |
| 964 | if (hasError) { |
| 965 | // Generate an error node. |
| 966 | state = setRefBinding(state, Sym, X); |
| 967 | |
| 968 | static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak"); |
| 969 | ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag); |
| 970 | if (N) { |
| 971 | const LangOptions &LOpts = C.getASTContext().getLangOpts(); |
| 972 | C.emitReport(std::unique_ptr<BugReport>(new CFRefLeakReport( |
| 973 | *getLeakAtReturnBug(LOpts), LOpts, |
| 974 | SummaryLog, N, Sym, C, IncludeAllocationLine))); |
| 975 | } |
| 976 | } |
| 977 | } |
| 978 | } else if (X.isReturnedNotOwned()) { |
| 979 | if (RE.isOwned()) { |
| 980 | if (X.getIvarAccessHistory() == |
| 981 | RefVal::IvarAccessHistory::AccessedDirectly) { |
| 982 | // Assume the method was trying to transfer a +1 reference from a |
| 983 | // strong ivar to the caller. |
| 984 | state = setRefBinding(state, Sym, |
| 985 | X.releaseViaIvar() ^ RefVal::ReturnedOwned); |
| 986 | } else { |
| 987 | // Trying to return a not owned object to a caller expecting an |
| 988 | // owned object. |
| 989 | state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned); |
| 990 | |
| 991 | static CheckerProgramPointTag |
| 992 | ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned"); |
| 993 | |
| 994 | ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag); |
| 995 | if (N) { |
| 996 | if (!returnNotOwnedForOwned) |
| 997 | returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this)); |
| 998 | |
| 999 | C.emitReport(std::unique_ptr<BugReport>(new CFRefReport( |
| 1000 | *returnNotOwnedForOwned, C.getASTContext().getLangOpts(), |
| 1001 | SummaryLog, N, Sym))); |
| 1002 | } |
| 1003 | } |
| 1004 | } |
| 1005 | } |
| 1006 | } |
| 1007 | |
| 1008 | //===----------------------------------------------------------------------===// |
| 1009 | // Check various ways a symbol can be invalidated. |
| 1010 | //===----------------------------------------------------------------------===// |
| 1011 | |
| 1012 | void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S, |
| 1013 | CheckerContext &C) const { |
| 1014 | // Are we storing to something that causes the value to "escape"? |
| 1015 | bool escapes = true; |
| 1016 | |
| 1017 | // A value escapes in three possible cases (this may change): |
| 1018 | // |
| 1019 | // (1) we are binding to something that is not a memory region. |
| 1020 | // (2) we are binding to a memregion that does not have stack storage |
| 1021 | // (3) we are binding to a memregion with stack storage that the store |
| 1022 | // does not understand. |
| 1023 | ProgramStateRef state = C.getState(); |
| 1024 | |
| 1025 | if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) { |
| 1026 | escapes = !regionLoc->getRegion()->hasStackStorage(); |
| 1027 | |
| 1028 | if (!escapes) { |
| 1029 | // To test (3), generate a new state with the binding added. If it is |
| 1030 | // the same state, then it escapes (since the store cannot represent |
| 1031 | // the binding). |
| 1032 | // Do this only if we know that the store is not supposed to generate the |
| 1033 | // same state. |
| 1034 | SVal StoredVal = state->getSVal(regionLoc->getRegion()); |
| 1035 | if (StoredVal != val) |
| 1036 | escapes = (state == (state->bindLoc(*regionLoc, val, C.getLocationContext()))); |
| 1037 | } |
| 1038 | if (!escapes) { |
| 1039 | // Case 4: We do not currently model what happens when a symbol is |
| 1040 | // assigned to a struct field, so be conservative here and let the symbol |
| 1041 | // go. TODO: This could definitely be improved upon. |
| 1042 | escapes = !isa<VarRegion>(regionLoc->getRegion()); |
| 1043 | } |
| 1044 | } |
| 1045 | |
| 1046 | // If we are storing the value into an auto function scope variable annotated |
| 1047 | // with (__attribute__((cleanup))), stop tracking the value to avoid leak |
| 1048 | // false positives. |
| 1049 | if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) { |
| 1050 | const VarDecl *VD = LVR->getDecl(); |
| 1051 | if (VD->hasAttr<CleanupAttr>()) { |
| 1052 | escapes = true; |
| 1053 | } |
| 1054 | } |
| 1055 | |
| 1056 | // If our store can represent the binding and we aren't storing to something |
| 1057 | // that doesn't have local storage then just return and have the simulation |
| 1058 | // state continue as is. |
| 1059 | if (!escapes) |
| 1060 | return; |
| 1061 | |
| 1062 | // Otherwise, find all symbols referenced by 'val' that we are tracking |
| 1063 | // and stop tracking them. |
| 1064 | state = state->scanReachableSymbols<StopTrackingCallback>(val).getState(); |
| 1065 | C.addTransition(state); |
| 1066 | } |
| 1067 | |
| 1068 | ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state, |
| 1069 | SVal Cond, |
| 1070 | bool Assumption) const { |
| 1071 | // FIXME: We may add to the interface of evalAssume the list of symbols |
| 1072 | // whose assumptions have changed. For now we just iterate through the |
| 1073 | // bindings and check if any of the tracked symbols are NULL. This isn't |
| 1074 | // too bad since the number of symbols we will track in practice are |
| 1075 | // probably small and evalAssume is only called at branches and a few |
| 1076 | // other places. |
| 1077 | RefBindingsTy B = state->get<RefBindings>(); |
| 1078 | |
| 1079 | if (B.isEmpty()) |
| 1080 | return state; |
| 1081 | |
| 1082 | bool changed = false; |
| 1083 | RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>(); |
| 1084 | |
| 1085 | for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { |
| 1086 | // Check if the symbol is null stop tracking the symbol. |
| 1087 | ConstraintManager &CMgr = state->getConstraintManager(); |
| 1088 | ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey()); |
| 1089 | if (AllocFailed.isConstrainedTrue()) { |
| 1090 | changed = true; |
| 1091 | B = RefBFactory.remove(B, I.getKey()); |
| 1092 | } |
| 1093 | } |
| 1094 | |
| 1095 | if (changed) |
| 1096 | state = state->set<RefBindings>(B); |
| 1097 | |
| 1098 | return state; |
| 1099 | } |
| 1100 | |
| 1101 | ProgramStateRef |
| 1102 | RetainCountChecker::checkRegionChanges(ProgramStateRef state, |
| 1103 | const InvalidatedSymbols *invalidated, |
| 1104 | ArrayRef<const MemRegion *> ExplicitRegions, |
| 1105 | ArrayRef<const MemRegion *> Regions, |
| 1106 | const LocationContext *LCtx, |
| 1107 | const CallEvent *Call) const { |
| 1108 | if (!invalidated) |
| 1109 | return state; |
| 1110 | |
| 1111 | llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols; |
| 1112 | for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), |
| 1113 | E = ExplicitRegions.end(); I != E; ++I) { |
| 1114 | if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>()) |
| 1115 | WhitelistedSymbols.insert(SR->getSymbol()); |
| 1116 | } |
| 1117 | |
| 1118 | for (InvalidatedSymbols::const_iterator I=invalidated->begin(), |
| 1119 | E = invalidated->end(); I!=E; ++I) { |
| 1120 | SymbolRef sym = *I; |
| 1121 | if (WhitelistedSymbols.count(sym)) |
| 1122 | continue; |
| 1123 | // Remove any existing reference-count binding. |
| 1124 | state = removeRefBinding(state, sym); |
| 1125 | } |
| 1126 | return state; |
| 1127 | } |
| 1128 | |
| 1129 | //===----------------------------------------------------------------------===// |
| 1130 | // Handle dead symbols and end-of-path. |
| 1131 | //===----------------------------------------------------------------------===// |
| 1132 | |
| 1133 | ProgramStateRef |
| 1134 | RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state, |
| 1135 | ExplodedNode *Pred, |
| 1136 | const ProgramPointTag *Tag, |
| 1137 | CheckerContext &Ctx, |
| 1138 | SymbolRef Sym, RefVal V) const { |
| 1139 | unsigned ACnt = V.getAutoreleaseCount(); |
| 1140 | |
| 1141 | // No autorelease counts? Nothing to be done. |
| 1142 | if (!ACnt) |
| 1143 | return state; |
| 1144 | |
| 1145 | unsigned Cnt = V.getCount(); |
| 1146 | |
| 1147 | // FIXME: Handle sending 'autorelease' to already released object. |
| 1148 | |
| 1149 | if (V.getKind() == RefVal::ReturnedOwned) |
| 1150 | ++Cnt; |
| 1151 | |
| 1152 | // If we would over-release here, but we know the value came from an ivar, |
| 1153 | // assume it was a strong ivar that's just been relinquished. |
| 1154 | if (ACnt > Cnt && |
| 1155 | V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) { |
| 1156 | V = V.releaseViaIvar(); |
| 1157 | --ACnt; |
| 1158 | } |
| 1159 | |
| 1160 | if (ACnt <= Cnt) { |
| 1161 | if (ACnt == Cnt) { |
| 1162 | V.clearCounts(); |
| 1163 | if (V.getKind() == RefVal::ReturnedOwned) |
| 1164 | V = V ^ RefVal::ReturnedNotOwned; |
| 1165 | else |
| 1166 | V = V ^ RefVal::NotOwned; |
| 1167 | } else { |
| 1168 | V.setCount(V.getCount() - ACnt); |
| 1169 | V.setAutoreleaseCount(0); |
| 1170 | } |
| 1171 | return setRefBinding(state, Sym, V); |
| 1172 | } |
| 1173 | |
| 1174 | // HACK: Ignore retain-count issues on values accessed through ivars, |
| 1175 | // because of cases like this: |
| 1176 | // [_contentView retain]; |
| 1177 | // [_contentView removeFromSuperview]; |
| 1178 | // [self addSubview:_contentView]; // invalidates 'self' |
| 1179 | // [_contentView release]; |
| 1180 | if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None) |
| 1181 | return state; |
| 1182 | |
| 1183 | // Woah! More autorelease counts then retain counts left. |
| 1184 | // Emit hard error. |
| 1185 | V = V ^ RefVal::ErrorOverAutorelease; |
| 1186 | state = setRefBinding(state, Sym, V); |
| 1187 | |
| 1188 | ExplodedNode *N = Ctx.generateSink(state, Pred, Tag); |
| 1189 | if (N) { |
| 1190 | SmallString<128> sbuf; |
| 1191 | llvm::raw_svector_ostream os(sbuf); |
| 1192 | os << "Object was autoreleased "; |
| 1193 | if (V.getAutoreleaseCount() > 1) |
| 1194 | os << V.getAutoreleaseCount() << " times but the object "; |
| 1195 | else |
| 1196 | os << "but "; |
| 1197 | os << "has a +" << V.getCount() << " retain count"; |
| 1198 | |
| 1199 | if (!overAutorelease) |
| 1200 | overAutorelease.reset(new OverAutorelease(this)); |
| 1201 | |
| 1202 | const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); |
| 1203 | Ctx.emitReport(std::unique_ptr<BugReport>( |
| 1204 | new CFRefReport(*overAutorelease, LOpts, |
| 1205 | SummaryLog, N, Sym, os.str()))); |
| 1206 | } |
| 1207 | |
| 1208 | return nullptr; |
| 1209 | } |
| 1210 | |
| 1211 | ProgramStateRef |
| 1212 | RetainCountChecker::handleSymbolDeath(ProgramStateRef state, |
| 1213 | SymbolRef sid, RefVal V, |
| 1214 | SmallVectorImpl<SymbolRef> &Leaked) const { |
| 1215 | bool hasLeak; |
| 1216 | |
| 1217 | // HACK: Ignore retain-count issues on values accessed through ivars, |
| 1218 | // because of cases like this: |
| 1219 | // [_contentView retain]; |
| 1220 | // [_contentView removeFromSuperview]; |
| 1221 | // [self addSubview:_contentView]; // invalidates 'self' |
| 1222 | // [_contentView release]; |
| 1223 | if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None) |
| 1224 | hasLeak = false; |
| 1225 | else if (V.isOwned()) |
| 1226 | hasLeak = true; |
| 1227 | else if (V.isNotOwned() || V.isReturnedOwned()) |
| 1228 | hasLeak = (V.getCount() > 0); |
| 1229 | else |
| 1230 | hasLeak = false; |
| 1231 | |
| 1232 | if (!hasLeak) |
| 1233 | return removeRefBinding(state, sid); |
| 1234 | |
| 1235 | Leaked.push_back(sid); |
| 1236 | return setRefBinding(state, sid, V ^ RefVal::ErrorLeak); |
| 1237 | } |
| 1238 | |
| 1239 | ExplodedNode * |
| 1240 | RetainCountChecker::processLeaks(ProgramStateRef state, |
| 1241 | SmallVectorImpl<SymbolRef> &Leaked, |
| 1242 | CheckerContext &Ctx, |
| 1243 | ExplodedNode *Pred) const { |
| 1244 | // Generate an intermediate node representing the leak point. |
| 1245 | ExplodedNode *N = Ctx.addTransition(state, Pred); |
| 1246 | |
| 1247 | if (N) { |
| 1248 | for (SmallVectorImpl<SymbolRef>::iterator |
| 1249 | I = Leaked.begin(), E = Leaked.end(); I != E; ++I) { |
| 1250 | |
| 1251 | const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); |
| 1252 | CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts) |
| 1253 | : getLeakAtReturnBug(LOpts); |
| 1254 | assert(BT && "BugType not initialized."); |
| 1255 | |
| 1256 | Ctx.emitReport(std::unique_ptr<BugReport>( |
| 1257 | new CFRefLeakReport(*BT, LOpts, SummaryLog, N, *I, Ctx, |
| 1258 | IncludeAllocationLine))); |
| 1259 | } |
| 1260 | } |
| 1261 | |
| 1262 | return N; |
| 1263 | } |
| 1264 | |
| 1265 | static bool isGeneralizedObjectRef(QualType Ty) { |
| 1266 | if (Ty.getAsString().substr(0, 4) == "isl_") |
| 1267 | return true; |
| 1268 | else |
| 1269 | return false; |
| 1270 | } |
| 1271 | |
| 1272 | void RetainCountChecker::checkBeginFunction(CheckerContext &Ctx) const { |
| 1273 | if (!Ctx.inTopFrame()) |
| 1274 | return; |
| 1275 | |
| 1276 | const LocationContext *LCtx = Ctx.getLocationContext(); |
| 1277 | const FunctionDecl *FD = dyn_cast<FunctionDecl>(LCtx->getDecl()); |
| 1278 | |
| 1279 | if (!FD || RetainSummary::isTrustedReferenceCountImplementation(FD)) |
| 1280 | return; |
| 1281 | |
| 1282 | ProgramStateRef state = Ctx.getState(); |
| 1283 | |
| 1284 | const RetainSummary *FunctionSummary = |
| 1285 | getSummaryManager(Ctx).getFunctionSummary(FD); |
| 1286 | ArgEffects CalleeSideArgEffects = FunctionSummary->getArgEffects(); |
| 1287 | |
| 1288 | for (unsigned idx = 0, e = FD->getNumParams(); idx != e; ++idx) { |
| 1289 | const ParmVarDecl *Param = FD->getParamDecl(idx); |
| 1290 | SymbolRef Sym = state->getSVal(state->getRegion(Param, LCtx)).getAsSymbol(); |
| 1291 | |
| 1292 | QualType Ty = Param->getType(); |
| 1293 | const ArgEffect *AE = CalleeSideArgEffects.lookup(idx); |
| 1294 | if (AE && *AE == DecRef && isGeneralizedObjectRef(Ty)) { |
| 1295 | state = setRefBinding(state, Sym, RefVal::makeOwned(RetEffect::ObjKind::Generalized, Ty)); |
| 1296 | } else if (isGeneralizedObjectRef(Ty)) { |
| 1297 | state = setRefBinding( |
| 1298 | state, Sym, |
| 1299 | RefVal::makeNotOwned(RetEffect::ObjKind::Generalized, Ty)); |
| 1300 | } |
| 1301 | } |
| 1302 | |
| 1303 | Ctx.addTransition(state); |
| 1304 | } |
| 1305 | |
| 1306 | void RetainCountChecker::checkEndFunction(const ReturnStmt *RS, |
| 1307 | CheckerContext &Ctx) const { |
| 1308 | ProgramStateRef state = Ctx.getState(); |
| 1309 | RefBindingsTy B = state->get<RefBindings>(); |
| 1310 | ExplodedNode *Pred = Ctx.getPredecessor(); |
| 1311 | |
| 1312 | // Don't process anything within synthesized bodies. |
| 1313 | const LocationContext *LCtx = Pred->getLocationContext(); |
| 1314 | if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) { |
| 1315 | assert(!LCtx->inTopFrame()); |
| 1316 | return; |
| 1317 | } |
| 1318 | |
| 1319 | for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { |
| 1320 | state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx, |
| 1321 | I->first, I->second); |
| 1322 | if (!state) |
| 1323 | return; |
| 1324 | } |
| 1325 | |
| 1326 | // If the current LocationContext has a parent, don't check for leaks. |
| 1327 | // We will do that later. |
| 1328 | // FIXME: we should instead check for imbalances of the retain/releases, |
| 1329 | // and suggest annotations. |
| 1330 | if (LCtx->getParent()) |
| 1331 | return; |
| 1332 | |
| 1333 | B = state->get<RefBindings>(); |
| 1334 | SmallVector<SymbolRef, 10> Leaked; |
| 1335 | |
| 1336 | for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) |
| 1337 | state = handleSymbolDeath(state, I->first, I->second, Leaked); |
| 1338 | |
| 1339 | processLeaks(state, Leaked, Ctx, Pred); |
| 1340 | } |
| 1341 | |
| 1342 | const ProgramPointTag * |
| 1343 | RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const { |
| 1344 | const CheckerProgramPointTag *&tag = DeadSymbolTags[sym]; |
| 1345 | if (!tag) { |
| 1346 | SmallString<64> buf; |
| 1347 | llvm::raw_svector_ostream out(buf); |
| 1348 | out << "Dead Symbol : "; |
| 1349 | sym->dumpToStream(out); |
| 1350 | tag = new CheckerProgramPointTag(this, out.str()); |
| 1351 | } |
| 1352 | return tag; |
| 1353 | } |
| 1354 | |
| 1355 | void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper, |
| 1356 | CheckerContext &C) const { |
| 1357 | ExplodedNode *Pred = C.getPredecessor(); |
| 1358 | |
| 1359 | ProgramStateRef state = C.getState(); |
| 1360 | RefBindingsTy B = state->get<RefBindings>(); |
| 1361 | SmallVector<SymbolRef, 10> Leaked; |
| 1362 | |
| 1363 | // Update counts from autorelease pools |
| 1364 | for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), |
| 1365 | E = SymReaper.dead_end(); I != E; ++I) { |
| 1366 | SymbolRef Sym = *I; |
| 1367 | if (const RefVal *T = B.lookup(Sym)){ |
| 1368 | // Use the symbol as the tag. |
| 1369 | // FIXME: This might not be as unique as we would like. |
| 1370 | const ProgramPointTag *Tag = getDeadSymbolTag(Sym); |
| 1371 | state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T); |
| 1372 | if (!state) |
| 1373 | return; |
| 1374 | |
| 1375 | // Fetch the new reference count from the state, and use it to handle |
| 1376 | // this symbol. |
| 1377 | state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked); |
| 1378 | } |
| 1379 | } |
| 1380 | |
| 1381 | if (Leaked.empty()) { |
| 1382 | C.addTransition(state); |
| 1383 | return; |
| 1384 | } |
| 1385 | |
| 1386 | Pred = processLeaks(state, Leaked, C, Pred); |
| 1387 | |
| 1388 | // Did we cache out? |
| 1389 | if (!Pred) |
| 1390 | return; |
| 1391 | |
| 1392 | // Now generate a new node that nukes the old bindings. |
| 1393 | // The only bindings left at this point are the leaked symbols. |
| 1394 | RefBindingsTy::Factory &F = state->get_context<RefBindings>(); |
| 1395 | B = state->get<RefBindings>(); |
| 1396 | |
| 1397 | for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(), |
| 1398 | E = Leaked.end(); |
| 1399 | I != E; ++I) |
| 1400 | B = F.remove(B, *I); |
| 1401 | |
| 1402 | state = state->set<RefBindings>(B); |
| 1403 | C.addTransition(state, Pred); |
| 1404 | } |
| 1405 | |
| 1406 | void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State, |
| 1407 | const char *NL, const char *Sep) const { |
| 1408 | |
| 1409 | RefBindingsTy B = State->get<RefBindings>(); |
| 1410 | |
| 1411 | if (B.isEmpty()) |
| 1412 | return; |
| 1413 | |
| 1414 | Out << Sep << NL; |
| 1415 | |
| 1416 | for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { |
| 1417 | Out << I->first << " : "; |
| 1418 | I->second.print(Out); |
| 1419 | Out << NL; |
| 1420 | } |
| 1421 | } |
| 1422 | |
| 1423 | //===----------------------------------------------------------------------===// |
| 1424 | // Implementation of the CallEffects API. |
| 1425 | //===----------------------------------------------------------------------===// |
| 1426 | |
| 1427 | namespace clang { |
| 1428 | namespace ento { |
| 1429 | namespace objc_retain { |
| 1430 | |
| 1431 | // This is a bit gross, but it allows us to populate CallEffects without |
| 1432 | // creating a bunch of accessors. This kind is very localized, so the |
| 1433 | // damage of this macro is limited. |
| 1434 | #define createCallEffect(D, KIND)\ |
| 1435 | ASTContext &Ctx = D->getASTContext();\ |
| 1436 | LangOptions L = Ctx.getLangOpts();\ |
| 1437 | RetainSummaryManager M(Ctx, L.ObjCAutoRefCount);\ |
| 1438 | const RetainSummary *S = M.get ## KIND ## Summary(D);\ |
| 1439 | CallEffects CE(S->getRetEffect());\ |
| 1440 | CE.Receiver = S->getReceiverEffect();\ |
| 1441 | unsigned N = D->param_size();\ |
| 1442 | for (unsigned i = 0; i < N; ++i) {\ |
| 1443 | CE.Args.push_back(S->getArg(i));\ |
| 1444 | } |
| 1445 | |
| 1446 | CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) { |
| 1447 | createCallEffect(MD, Method); |
| 1448 | return CE; |
| 1449 | } |
| 1450 | |
| 1451 | CallEffects CallEffects::getEffect(const FunctionDecl *FD) { |
| 1452 | createCallEffect(FD, Function); |
| 1453 | return CE; |
| 1454 | } |
| 1455 | |
| 1456 | #undef createCallEffect |
| 1457 | |
| 1458 | } // end namespace objc_retain |
| 1459 | } // end namespace ento |
| 1460 | } // end namespace clang |
| 1461 | |
| 1462 | //===----------------------------------------------------------------------===// |
| 1463 | // Checker registration. |
| 1464 | //===----------------------------------------------------------------------===// |
| 1465 | |
| 1466 | void ento::registerRetainCountChecker(CheckerManager &Mgr) { |
| 1467 | Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions()); |
| 1468 | } |