1 //===- ThreadSafety.cpp ---------------------------------------------------===// 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 // A intra-procedural analysis for thread safety (e.g. deadlocks and race 11 // conditions), based off of an annotation system. 12 // 13 // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html 14 // for more information. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "clang/Analysis/Analyses/ThreadSafety.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclGroup.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/OperationKinds.h" 26 #include "clang/AST/Stmt.h" 27 #include "clang/AST/StmtVisitor.h" 28 #include "clang/AST/Type.h" 29 #include "clang/Analysis/Analyses/PostOrderCFGView.h" 30 #include "clang/Analysis/Analyses/ThreadSafetyCommon.h" 31 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h" 32 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h" 33 #include "clang/Analysis/Analyses/ThreadSafetyUtil.h" 34 #include "clang/Analysis/AnalysisDeclContext.h" 35 #include "clang/Analysis/CFG.h" 36 #include "clang/Basic/LLVM.h" 37 #include "clang/Basic/OperatorKinds.h" 38 #include "clang/Basic/SourceLocation.h" 39 #include "clang/Basic/Specifiers.h" 40 #include "llvm/ADT/ArrayRef.h" 41 #include "llvm/ADT/DenseMap.h" 42 #include "llvm/ADT/ImmutableMap.h" 43 #include "llvm/ADT/Optional.h" 44 #include "llvm/ADT/STLExtras.h" 45 #include "llvm/ADT/SmallVector.h" 46 #include "llvm/ADT/StringRef.h" 47 #include "llvm/Support/Allocator.h" 48 #include "llvm/Support/Casting.h" 49 #include "llvm/Support/ErrorHandling.h" 50 #include "llvm/Support/raw_ostream.h" 51 #include <algorithm> 52 #include <cassert> 53 #include <functional> 54 #include <iterator> 55 #include <memory> 56 #include <string> 57 #include <type_traits> 58 #include <utility> 59 #include <vector> 60 61 using namespace clang; 62 using namespace threadSafety; 63 64 // Key method definition 65 ThreadSafetyHandler::~ThreadSafetyHandler() = default; 66 67 namespace { 68 69 class TILPrinter : 70 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {}; 71 72 } // namespace 73 74 /// Issue a warning about an invalid lock expression 75 static void warnInvalidLock(ThreadSafetyHandler &Handler, 76 const Expr *MutexExp, const NamedDecl *D, 77 const Expr *DeclExp, StringRef Kind) { 78 SourceLocation Loc; 79 if (DeclExp) 80 Loc = DeclExp->getExprLoc(); 81 82 // FIXME: add a note about the attribute location in MutexExp or D 83 if (Loc.isValid()) 84 Handler.handleInvalidLockExp(Kind, Loc); 85 } 86 87 namespace { 88 89 /// \brief A set of CapabilityInfo objects, which are compiled from the 90 /// requires attributes on a function. 91 class CapExprSet : public SmallVector<CapabilityExpr, 4> { 92 public: 93 /// \brief Push M onto list, but discard duplicates. 94 void push_back_nodup(const CapabilityExpr &CapE) { 95 iterator It = std::find_if(begin(), end(), 96 [=](const CapabilityExpr &CapE2) { 97 return CapE.equals(CapE2); 98 }); 99 if (It == end()) 100 push_back(CapE); 101 } 102 }; 103 104 class FactManager; 105 class FactSet; 106 107 /// \brief This is a helper class that stores a fact that is known at a 108 /// particular point in program execution. Currently, a fact is a capability, 109 /// along with additional information, such as where it was acquired, whether 110 /// it is exclusive or shared, etc. 111 /// 112 /// FIXME: this analysis does not currently support either re-entrant 113 /// locking or lock "upgrading" and "downgrading" between exclusive and 114 /// shared. 115 class FactEntry : public CapabilityExpr { 116 private: 117 /// Exclusive or shared. 118 LockKind LKind; 119 120 /// Where it was acquired. 121 SourceLocation AcquireLoc; 122 123 /// True if the lock was asserted. 124 bool Asserted; 125 126 /// True if the lock was declared. 127 bool Declared; 128 129 public: 130 FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc, 131 bool Asrt, bool Declrd = false) 132 : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt), 133 Declared(Declrd) {} 134 virtual ~FactEntry() = default; 135 136 LockKind kind() const { return LKind; } 137 SourceLocation loc() const { return AcquireLoc; } 138 bool asserted() const { return Asserted; } 139 bool declared() const { return Declared; } 140 141 void setDeclared(bool D) { Declared = D; } 142 143 virtual void 144 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan, 145 SourceLocation JoinLoc, LockErrorKind LEK, 146 ThreadSafetyHandler &Handler) const = 0; 147 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan, 148 const CapabilityExpr &Cp, SourceLocation UnlockLoc, 149 bool FullyRemove, ThreadSafetyHandler &Handler, 150 StringRef DiagKind) const = 0; 151 152 // Return true if LKind >= LK, where exclusive > shared 153 bool isAtLeast(LockKind LK) { 154 return (LKind == LK_Exclusive) || (LK == LK_Shared); 155 } 156 }; 157 158 using FactID = unsigned short; 159 160 /// \brief FactManager manages the memory for all facts that are created during 161 /// the analysis of a single routine. 162 class FactManager { 163 private: 164 std::vector<std::unique_ptr<FactEntry>> Facts; 165 166 public: 167 FactID newFact(std::unique_ptr<FactEntry> Entry) { 168 Facts.push_back(std::move(Entry)); 169 return static_cast<unsigned short>(Facts.size() - 1); 170 } 171 172 const FactEntry &operator[](FactID F) const { return *Facts[F]; } 173 FactEntry &operator[](FactID F) { return *Facts[F]; } 174 }; 175 176 /// \brief A FactSet is the set of facts that are known to be true at a 177 /// particular program point. FactSets must be small, because they are 178 /// frequently copied, and are thus implemented as a set of indices into a 179 /// table maintained by a FactManager. A typical FactSet only holds 1 or 2 180 /// locks, so we can get away with doing a linear search for lookup. Note 181 /// that a hashtable or map is inappropriate in this case, because lookups 182 /// may involve partial pattern matches, rather than exact matches. 183 class FactSet { 184 private: 185 using FactVec = SmallVector<FactID, 4>; 186 187 FactVec FactIDs; 188 189 public: 190 using iterator = FactVec::iterator; 191 using const_iterator = FactVec::const_iterator; 192 193 iterator begin() { return FactIDs.begin(); } 194 const_iterator begin() const { return FactIDs.begin(); } 195 196 iterator end() { return FactIDs.end(); } 197 const_iterator end() const { return FactIDs.end(); } 198 199 bool isEmpty() const { return FactIDs.size() == 0; } 200 201 // Return true if the set contains only negative facts 202 bool isEmpty(FactManager &FactMan) const { 203 for (const auto FID : *this) { 204 if (!FactMan[FID].negative()) 205 return false; 206 } 207 return true; 208 } 209 210 void addLockByID(FactID ID) { FactIDs.push_back(ID); } 211 212 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) { 213 FactID F = FM.newFact(std::move(Entry)); 214 FactIDs.push_back(F); 215 return F; 216 } 217 218 bool removeLock(FactManager& FM, const CapabilityExpr &CapE) { 219 unsigned n = FactIDs.size(); 220 if (n == 0) 221 return false; 222 223 for (unsigned i = 0; i < n-1; ++i) { 224 if (FM[FactIDs[i]].matches(CapE)) { 225 FactIDs[i] = FactIDs[n-1]; 226 FactIDs.pop_back(); 227 return true; 228 } 229 } 230 if (FM[FactIDs[n-1]].matches(CapE)) { 231 FactIDs.pop_back(); 232 return true; 233 } 234 return false; 235 } 236 237 iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) { 238 return std::find_if(begin(), end(), [&](FactID ID) { 239 return FM[ID].matches(CapE); 240 }); 241 } 242 243 FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const { 244 auto I = std::find_if(begin(), end(), [&](FactID ID) { 245 return FM[ID].matches(CapE); 246 }); 247 return I != end() ? &FM[*I] : nullptr; 248 } 249 250 FactEntry *findLockUniv(FactManager &FM, const CapabilityExpr &CapE) const { 251 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool { 252 return FM[ID].matchesUniv(CapE); 253 }); 254 return I != end() ? &FM[*I] : nullptr; 255 } 256 257 FactEntry *findPartialMatch(FactManager &FM, 258 const CapabilityExpr &CapE) const { 259 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool { 260 return FM[ID].partiallyMatches(CapE); 261 }); 262 return I != end() ? &FM[*I] : nullptr; 263 } 264 265 bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const { 266 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool { 267 return FM[ID].valueDecl() == Vd; 268 }); 269 return I != end(); 270 } 271 }; 272 273 class ThreadSafetyAnalyzer; 274 275 } // namespace 276 277 namespace clang { 278 namespace threadSafety { 279 280 class BeforeSet { 281 private: 282 using BeforeVect = SmallVector<const ValueDecl *, 4>; 283 284 struct BeforeInfo { 285 BeforeVect Vect; 286 int Visited = 0; 287 288 BeforeInfo() = default; 289 BeforeInfo(BeforeInfo &&) = default; 290 }; 291 292 using BeforeMap = 293 llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>; 294 using CycleMap = llvm::DenseMap<const ValueDecl *, bool>; 295 296 public: 297 BeforeSet() = default; 298 299 BeforeInfo* insertAttrExprs(const ValueDecl* Vd, 300 ThreadSafetyAnalyzer& Analyzer); 301 302 BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd, 303 ThreadSafetyAnalyzer &Analyzer); 304 305 void checkBeforeAfter(const ValueDecl* Vd, 306 const FactSet& FSet, 307 ThreadSafetyAnalyzer& Analyzer, 308 SourceLocation Loc, StringRef CapKind); 309 310 private: 311 BeforeMap BMap; 312 CycleMap CycMap; 313 }; 314 315 } // namespace threadSafety 316 } // namespace clang 317 318 namespace { 319 320 class LocalVariableMap; 321 322 using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>; 323 324 /// A side (entry or exit) of a CFG node. 325 enum CFGBlockSide { CBS_Entry, CBS_Exit }; 326 327 /// CFGBlockInfo is a struct which contains all the information that is 328 /// maintained for each block in the CFG. See LocalVariableMap for more 329 /// information about the contexts. 330 struct CFGBlockInfo { 331 // Lockset held at entry to block 332 FactSet EntrySet; 333 334 // Lockset held at exit from block 335 FactSet ExitSet; 336 337 // Context held at entry to block 338 LocalVarContext EntryContext; 339 340 // Context held at exit from block 341 LocalVarContext ExitContext; 342 343 // Location of first statement in block 344 SourceLocation EntryLoc; 345 346 // Location of last statement in block. 347 SourceLocation ExitLoc; 348 349 // Used to replay contexts later 350 unsigned EntryIndex; 351 352 // Is this block reachable? 353 bool Reachable = false; 354 355 const FactSet &getSet(CFGBlockSide Side) const { 356 return Side == CBS_Entry ? EntrySet : ExitSet; 357 } 358 359 SourceLocation getLocation(CFGBlockSide Side) const { 360 return Side == CBS_Entry ? EntryLoc : ExitLoc; 361 } 362 363 private: 364 CFGBlockInfo(LocalVarContext EmptyCtx) 365 : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {} 366 367 public: 368 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M); 369 }; 370 371 // A LocalVariableMap maintains a map from local variables to their currently 372 // valid definitions. It provides SSA-like functionality when traversing the 373 // CFG. Like SSA, each definition or assignment to a variable is assigned a 374 // unique name (an integer), which acts as the SSA name for that definition. 375 // The total set of names is shared among all CFG basic blocks. 376 // Unlike SSA, we do not rewrite expressions to replace local variables declrefs 377 // with their SSA-names. Instead, we compute a Context for each point in the 378 // code, which maps local variables to the appropriate SSA-name. This map 379 // changes with each assignment. 380 // 381 // The map is computed in a single pass over the CFG. Subsequent analyses can 382 // then query the map to find the appropriate Context for a statement, and use 383 // that Context to look up the definitions of variables. 384 class LocalVariableMap { 385 public: 386 using Context = LocalVarContext; 387 388 /// A VarDefinition consists of an expression, representing the value of the 389 /// variable, along with the context in which that expression should be 390 /// interpreted. A reference VarDefinition does not itself contain this 391 /// information, but instead contains a pointer to a previous VarDefinition. 392 struct VarDefinition { 393 public: 394 friend class LocalVariableMap; 395 396 // The original declaration for this variable. 397 const NamedDecl *Dec; 398 399 // The expression for this variable, OR 400 const Expr *Exp = nullptr; 401 402 // Reference to another VarDefinition 403 unsigned Ref = 0; 404 405 // The map with which Exp should be interpreted. 406 Context Ctx; 407 408 bool isReference() { return !Exp; } 409 410 private: 411 // Create ordinary variable definition 412 VarDefinition(const NamedDecl *D, const Expr *E, Context C) 413 : Dec(D), Exp(E), Ctx(C) {} 414 415 // Create reference to previous definition 416 VarDefinition(const NamedDecl *D, unsigned R, Context C) 417 : Dec(D), Ref(R), Ctx(C) {} 418 }; 419 420 private: 421 Context::Factory ContextFactory; 422 std::vector<VarDefinition> VarDefinitions; 423 std::vector<unsigned> CtxIndices; 424 std::vector<std::pair<Stmt *, Context>> SavedContexts; 425 426 public: 427 LocalVariableMap() { 428 // index 0 is a placeholder for undefined variables (aka phi-nodes). 429 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext())); 430 } 431 432 /// Look up a definition, within the given context. 433 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) { 434 const unsigned *i = Ctx.lookup(D); 435 if (!i) 436 return nullptr; 437 assert(*i < VarDefinitions.size()); 438 return &VarDefinitions[*i]; 439 } 440 441 /// Look up the definition for D within the given context. Returns 442 /// NULL if the expression is not statically known. If successful, also 443 /// modifies Ctx to hold the context of the return Expr. 444 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) { 445 const unsigned *P = Ctx.lookup(D); 446 if (!P) 447 return nullptr; 448 449 unsigned i = *P; 450 while (i > 0) { 451 if (VarDefinitions[i].Exp) { 452 Ctx = VarDefinitions[i].Ctx; 453 return VarDefinitions[i].Exp; 454 } 455 i = VarDefinitions[i].Ref; 456 } 457 return nullptr; 458 } 459 460 Context getEmptyContext() { return ContextFactory.getEmptyMap(); } 461 462 /// Return the next context after processing S. This function is used by 463 /// clients of the class to get the appropriate context when traversing the 464 /// CFG. It must be called for every assignment or DeclStmt. 465 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) { 466 if (SavedContexts[CtxIndex+1].first == S) { 467 CtxIndex++; 468 Context Result = SavedContexts[CtxIndex].second; 469 return Result; 470 } 471 return C; 472 } 473 474 void dumpVarDefinitionName(unsigned i) { 475 if (i == 0) { 476 llvm::errs() << "Undefined"; 477 return; 478 } 479 const NamedDecl *Dec = VarDefinitions[i].Dec; 480 if (!Dec) { 481 llvm::errs() << "<<NULL>>"; 482 return; 483 } 484 Dec->printName(llvm::errs()); 485 llvm::errs() << "." << i << " " << ((const void*) Dec); 486 } 487 488 /// Dumps an ASCII representation of the variable map to llvm::errs() 489 void dump() { 490 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) { 491 const Expr *Exp = VarDefinitions[i].Exp; 492 unsigned Ref = VarDefinitions[i].Ref; 493 494 dumpVarDefinitionName(i); 495 llvm::errs() << " = "; 496 if (Exp) Exp->dump(); 497 else { 498 dumpVarDefinitionName(Ref); 499 llvm::errs() << "\n"; 500 } 501 } 502 } 503 504 /// Dumps an ASCII representation of a Context to llvm::errs() 505 void dumpContext(Context C) { 506 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) { 507 const NamedDecl *D = I.getKey(); 508 D->printName(llvm::errs()); 509 const unsigned *i = C.lookup(D); 510 llvm::errs() << " -> "; 511 dumpVarDefinitionName(*i); 512 llvm::errs() << "\n"; 513 } 514 } 515 516 /// Builds the variable map. 517 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph, 518 std::vector<CFGBlockInfo> &BlockInfo); 519 520 protected: 521 friend class VarMapBuilder; 522 523 // Get the current context index 524 unsigned getContextIndex() { return SavedContexts.size()-1; } 525 526 // Save the current context for later replay 527 void saveContext(Stmt *S, Context C) { 528 SavedContexts.push_back(std::make_pair(S, C)); 529 } 530 531 // Adds a new definition to the given context, and returns a new context. 532 // This method should be called when declaring a new variable. 533 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) { 534 assert(!Ctx.contains(D)); 535 unsigned newID = VarDefinitions.size(); 536 Context NewCtx = ContextFactory.add(Ctx, D, newID); 537 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx)); 538 return NewCtx; 539 } 540 541 // Add a new reference to an existing definition. 542 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) { 543 unsigned newID = VarDefinitions.size(); 544 Context NewCtx = ContextFactory.add(Ctx, D, newID); 545 VarDefinitions.push_back(VarDefinition(D, i, Ctx)); 546 return NewCtx; 547 } 548 549 // Updates a definition only if that definition is already in the map. 550 // This method should be called when assigning to an existing variable. 551 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) { 552 if (Ctx.contains(D)) { 553 unsigned newID = VarDefinitions.size(); 554 Context NewCtx = ContextFactory.remove(Ctx, D); 555 NewCtx = ContextFactory.add(NewCtx, D, newID); 556 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx)); 557 return NewCtx; 558 } 559 return Ctx; 560 } 561 562 // Removes a definition from the context, but keeps the variable name 563 // as a valid variable. The index 0 is a placeholder for cleared definitions. 564 Context clearDefinition(const NamedDecl *D, Context Ctx) { 565 Context NewCtx = Ctx; 566 if (NewCtx.contains(D)) { 567 NewCtx = ContextFactory.remove(NewCtx, D); 568 NewCtx = ContextFactory.add(NewCtx, D, 0); 569 } 570 return NewCtx; 571 } 572 573 // Remove a definition entirely frmo the context. 574 Context removeDefinition(const NamedDecl *D, Context Ctx) { 575 Context NewCtx = Ctx; 576 if (NewCtx.contains(D)) { 577 NewCtx = ContextFactory.remove(NewCtx, D); 578 } 579 return NewCtx; 580 } 581 582 Context intersectContexts(Context C1, Context C2); 583 Context createReferenceContext(Context C); 584 void intersectBackEdge(Context C1, Context C2); 585 }; 586 587 } // namespace 588 589 // This has to be defined after LocalVariableMap. 590 CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) { 591 return CFGBlockInfo(M.getEmptyContext()); 592 } 593 594 namespace { 595 596 /// Visitor which builds a LocalVariableMap 597 class VarMapBuilder : public StmtVisitor<VarMapBuilder> { 598 public: 599 LocalVariableMap* VMap; 600 LocalVariableMap::Context Ctx; 601 602 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C) 603 : VMap(VM), Ctx(C) {} 604 605 void VisitDeclStmt(DeclStmt *S); 606 void VisitBinaryOperator(BinaryOperator *BO); 607 }; 608 609 } // namespace 610 611 // Add new local variables to the variable map 612 void VarMapBuilder::VisitDeclStmt(DeclStmt *S) { 613 bool modifiedCtx = false; 614 DeclGroupRef DGrp = S->getDeclGroup(); 615 for (const auto *D : DGrp) { 616 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) { 617 const Expr *E = VD->getInit(); 618 619 // Add local variables with trivial type to the variable map 620 QualType T = VD->getType(); 621 if (T.isTrivialType(VD->getASTContext())) { 622 Ctx = VMap->addDefinition(VD, E, Ctx); 623 modifiedCtx = true; 624 } 625 } 626 } 627 if (modifiedCtx) 628 VMap->saveContext(S, Ctx); 629 } 630 631 // Update local variable definitions in variable map 632 void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) { 633 if (!BO->isAssignmentOp()) 634 return; 635 636 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts(); 637 638 // Update the variable map and current context. 639 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) { 640 const ValueDecl *VDec = DRE->getDecl(); 641 if (Ctx.lookup(VDec)) { 642 if (BO->getOpcode() == BO_Assign) 643 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx); 644 else 645 // FIXME -- handle compound assignment operators 646 Ctx = VMap->clearDefinition(VDec, Ctx); 647 VMap->saveContext(BO, Ctx); 648 } 649 } 650 } 651 652 // Computes the intersection of two contexts. The intersection is the 653 // set of variables which have the same definition in both contexts; 654 // variables with different definitions are discarded. 655 LocalVariableMap::Context 656 LocalVariableMap::intersectContexts(Context C1, Context C2) { 657 Context Result = C1; 658 for (const auto &P : C1) { 659 const NamedDecl *Dec = P.first; 660 const unsigned *i2 = C2.lookup(Dec); 661 if (!i2) // variable doesn't exist on second path 662 Result = removeDefinition(Dec, Result); 663 else if (*i2 != P.second) // variable exists, but has different definition 664 Result = clearDefinition(Dec, Result); 665 } 666 return Result; 667 } 668 669 // For every variable in C, create a new variable that refers to the 670 // definition in C. Return a new context that contains these new variables. 671 // (We use this for a naive implementation of SSA on loop back-edges.) 672 LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) { 673 Context Result = getEmptyContext(); 674 for (const auto &P : C) 675 Result = addReference(P.first, P.second, Result); 676 return Result; 677 } 678 679 // This routine also takes the intersection of C1 and C2, but it does so by 680 // altering the VarDefinitions. C1 must be the result of an earlier call to 681 // createReferenceContext. 682 void LocalVariableMap::intersectBackEdge(Context C1, Context C2) { 683 for (const auto &P : C1) { 684 unsigned i1 = P.second; 685 VarDefinition *VDef = &VarDefinitions[i1]; 686 assert(VDef->isReference()); 687 688 const unsigned *i2 = C2.lookup(P.first); 689 if (!i2 || (*i2 != i1)) 690 VDef->Ref = 0; // Mark this variable as undefined 691 } 692 } 693 694 // Traverse the CFG in topological order, so all predecessors of a block 695 // (excluding back-edges) are visited before the block itself. At 696 // each point in the code, we calculate a Context, which holds the set of 697 // variable definitions which are visible at that point in execution. 698 // Visible variables are mapped to their definitions using an array that 699 // contains all definitions. 700 // 701 // At join points in the CFG, the set is computed as the intersection of 702 // the incoming sets along each edge, E.g. 703 // 704 // { Context | VarDefinitions } 705 // int x = 0; { x -> x1 | x1 = 0 } 706 // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 } 707 // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... } 708 // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... } 709 // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... } 710 // 711 // This is essentially a simpler and more naive version of the standard SSA 712 // algorithm. Those definitions that remain in the intersection are from blocks 713 // that strictly dominate the current block. We do not bother to insert proper 714 // phi nodes, because they are not used in our analysis; instead, wherever 715 // a phi node would be required, we simply remove that definition from the 716 // context (E.g. x above). 717 // 718 // The initial traversal does not capture back-edges, so those need to be 719 // handled on a separate pass. Whenever the first pass encounters an 720 // incoming back edge, it duplicates the context, creating new definitions 721 // that refer back to the originals. (These correspond to places where SSA 722 // might have to insert a phi node.) On the second pass, these definitions are 723 // set to NULL if the variable has changed on the back-edge (i.e. a phi 724 // node was actually required.) E.g. 725 // 726 // { Context | VarDefinitions } 727 // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 } 728 // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; } 729 // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... } 730 // ... { y -> y1 | x3 = 2, x2 = 1, ... } 731 void LocalVariableMap::traverseCFG(CFG *CFGraph, 732 const PostOrderCFGView *SortedGraph, 733 std::vector<CFGBlockInfo> &BlockInfo) { 734 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph); 735 736 CtxIndices.resize(CFGraph->getNumBlockIDs()); 737 738 for (const auto *CurrBlock : *SortedGraph) { 739 int CurrBlockID = CurrBlock->getBlockID(); 740 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID]; 741 742 VisitedBlocks.insert(CurrBlock); 743 744 // Calculate the entry context for the current block 745 bool HasBackEdges = false; 746 bool CtxInit = true; 747 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(), 748 PE = CurrBlock->pred_end(); PI != PE; ++PI) { 749 // if *PI -> CurrBlock is a back edge, so skip it 750 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) { 751 HasBackEdges = true; 752 continue; 753 } 754 755 int PrevBlockID = (*PI)->getBlockID(); 756 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 757 758 if (CtxInit) { 759 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext; 760 CtxInit = false; 761 } 762 else { 763 CurrBlockInfo->EntryContext = 764 intersectContexts(CurrBlockInfo->EntryContext, 765 PrevBlockInfo->ExitContext); 766 } 767 } 768 769 // Duplicate the context if we have back-edges, so we can call 770 // intersectBackEdges later. 771 if (HasBackEdges) 772 CurrBlockInfo->EntryContext = 773 createReferenceContext(CurrBlockInfo->EntryContext); 774 775 // Create a starting context index for the current block 776 saveContext(nullptr, CurrBlockInfo->EntryContext); 777 CurrBlockInfo->EntryIndex = getContextIndex(); 778 779 // Visit all the statements in the basic block. 780 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext); 781 for (const auto &BI : *CurrBlock) { 782 switch (BI.getKind()) { 783 case CFGElement::Statement: { 784 CFGStmt CS = BI.castAs<CFGStmt>(); 785 VMapBuilder.Visit(const_cast<Stmt *>(CS.getStmt())); 786 break; 787 } 788 default: 789 break; 790 } 791 } 792 CurrBlockInfo->ExitContext = VMapBuilder.Ctx; 793 794 // Mark variables on back edges as "unknown" if they've been changed. 795 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(), 796 SE = CurrBlock->succ_end(); SI != SE; ++SI) { 797 // if CurrBlock -> *SI is *not* a back edge 798 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI)) 799 continue; 800 801 CFGBlock *FirstLoopBlock = *SI; 802 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext; 803 Context LoopEnd = CurrBlockInfo->ExitContext; 804 intersectBackEdge(LoopBegin, LoopEnd); 805 } 806 } 807 808 // Put an extra entry at the end of the indexed context array 809 unsigned exitID = CFGraph->getExit().getBlockID(); 810 saveContext(nullptr, BlockInfo[exitID].ExitContext); 811 } 812 813 /// Find the appropriate source locations to use when producing diagnostics for 814 /// each block in the CFG. 815 static void findBlockLocations(CFG *CFGraph, 816 const PostOrderCFGView *SortedGraph, 817 std::vector<CFGBlockInfo> &BlockInfo) { 818 for (const auto *CurrBlock : *SortedGraph) { 819 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()]; 820 821 // Find the source location of the last statement in the block, if the 822 // block is not empty. 823 if (const Stmt *S = CurrBlock->getTerminator()) { 824 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart(); 825 } else { 826 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(), 827 BE = CurrBlock->rend(); BI != BE; ++BI) { 828 // FIXME: Handle other CFGElement kinds. 829 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) { 830 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart(); 831 break; 832 } 833 } 834 } 835 836 if (CurrBlockInfo->ExitLoc.isValid()) { 837 // This block contains at least one statement. Find the source location 838 // of the first statement in the block. 839 for (const auto &BI : *CurrBlock) { 840 // FIXME: Handle other CFGElement kinds. 841 if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) { 842 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart(); 843 break; 844 } 845 } 846 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() && 847 CurrBlock != &CFGraph->getExit()) { 848 // The block is empty, and has a single predecessor. Use its exit 849 // location. 850 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = 851 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc; 852 } 853 } 854 } 855 856 namespace { 857 858 class LockableFactEntry : public FactEntry { 859 private: 860 /// managed by ScopedLockable object 861 bool Managed; 862 863 public: 864 LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc, 865 bool Mng = false, bool Asrt = false) 866 : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {} 867 868 void 869 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan, 870 SourceLocation JoinLoc, LockErrorKind LEK, 871 ThreadSafetyHandler &Handler) const override { 872 if (!Managed && !asserted() && !negative() && !isUniversal()) { 873 Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc, 874 LEK); 875 } 876 } 877 878 void handleUnlock(FactSet &FSet, FactManager &FactMan, 879 const CapabilityExpr &Cp, SourceLocation UnlockLoc, 880 bool FullyRemove, ThreadSafetyHandler &Handler, 881 StringRef DiagKind) const override { 882 FSet.removeLock(FactMan, Cp); 883 if (!Cp.negative()) { 884 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>( 885 !Cp, LK_Exclusive, UnlockLoc)); 886 } 887 } 888 }; 889 890 class ScopedLockableFactEntry : public FactEntry { 891 private: 892 SmallVector<const til::SExpr *, 4> UnderlyingMutexes; 893 894 public: 895 ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc, 896 const CapExprSet &Excl, const CapExprSet &Shrd) 897 : FactEntry(CE, LK_Exclusive, Loc, false) { 898 for (const auto &M : Excl) 899 UnderlyingMutexes.push_back(M.sexpr()); 900 for (const auto &M : Shrd) 901 UnderlyingMutexes.push_back(M.sexpr()); 902 } 903 904 void 905 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan, 906 SourceLocation JoinLoc, LockErrorKind LEK, 907 ThreadSafetyHandler &Handler) const override { 908 for (const auto *UnderlyingMutex : UnderlyingMutexes) { 909 if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) { 910 // If this scoped lock manages another mutex, and if the underlying 911 // mutex is still held, then warn about the underlying mutex. 912 Handler.handleMutexHeldEndOfScope( 913 "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK); 914 } 915 } 916 } 917 918 void handleUnlock(FactSet &FSet, FactManager &FactMan, 919 const CapabilityExpr &Cp, SourceLocation UnlockLoc, 920 bool FullyRemove, ThreadSafetyHandler &Handler, 921 StringRef DiagKind) const override { 922 assert(!Cp.negative() && "Managing object cannot be negative."); 923 for (const auto *UnderlyingMutex : UnderlyingMutexes) { 924 CapabilityExpr UnderCp(UnderlyingMutex, false); 925 auto UnderEntry = llvm::make_unique<LockableFactEntry>( 926 !UnderCp, LK_Exclusive, UnlockLoc); 927 928 if (FullyRemove) { 929 // We're destroying the managing object. 930 // Remove the underlying mutex if it exists; but don't warn. 931 if (FSet.findLock(FactMan, UnderCp)) { 932 FSet.removeLock(FactMan, UnderCp); 933 FSet.addLock(FactMan, std::move(UnderEntry)); 934 } 935 } else { 936 // We're releasing the underlying mutex, but not destroying the 937 // managing object. Warn on dual release. 938 if (!FSet.findLock(FactMan, UnderCp)) { 939 Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(), 940 UnlockLoc); 941 } 942 FSet.removeLock(FactMan, UnderCp); 943 FSet.addLock(FactMan, std::move(UnderEntry)); 944 } 945 } 946 if (FullyRemove) 947 FSet.removeLock(FactMan, Cp); 948 } 949 }; 950 951 /// \brief Class which implements the core thread safety analysis routines. 952 class ThreadSafetyAnalyzer { 953 friend class BuildLockset; 954 friend class threadSafety::BeforeSet; 955 956 llvm::BumpPtrAllocator Bpa; 957 threadSafety::til::MemRegionRef Arena; 958 threadSafety::SExprBuilder SxBuilder; 959 960 ThreadSafetyHandler &Handler; 961 const CXXMethodDecl *CurrentMethod; 962 LocalVariableMap LocalVarMap; 963 FactManager FactMan; 964 std::vector<CFGBlockInfo> BlockInfo; 965 966 BeforeSet *GlobalBeforeSet; 967 968 public: 969 ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset) 970 : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {} 971 972 bool inCurrentScope(const CapabilityExpr &CapE); 973 974 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry, 975 StringRef DiagKind, bool ReqAttr = false); 976 void removeLock(FactSet &FSet, const CapabilityExpr &CapE, 977 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind, 978 StringRef DiagKind); 979 980 template <typename AttrType> 981 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp, 982 const NamedDecl *D, VarDecl *SelfDecl = nullptr); 983 984 template <class AttrType> 985 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp, 986 const NamedDecl *D, 987 const CFGBlock *PredBlock, const CFGBlock *CurrBlock, 988 Expr *BrE, bool Neg); 989 990 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C, 991 bool &Negate); 992 993 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet, 994 const CFGBlock* PredBlock, 995 const CFGBlock *CurrBlock); 996 997 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2, 998 SourceLocation JoinLoc, 999 LockErrorKind LEK1, LockErrorKind LEK2, 1000 bool Modify=true); 1001 1002 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2, 1003 SourceLocation JoinLoc, LockErrorKind LEK1, 1004 bool Modify=true) { 1005 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify); 1006 } 1007 1008 void runAnalysis(AnalysisDeclContext &AC); 1009 }; 1010 1011 } // namespace 1012 1013 /// Process acquired_before and acquired_after attributes on Vd. 1014 BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd, 1015 ThreadSafetyAnalyzer& Analyzer) { 1016 // Create a new entry for Vd. 1017 BeforeInfo *Info = nullptr; 1018 { 1019 // Keep InfoPtr in its own scope in case BMap is modified later and the 1020 // reference becomes invalid. 1021 std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd]; 1022 if (!InfoPtr) 1023 InfoPtr.reset(new BeforeInfo()); 1024 Info = InfoPtr.get(); 1025 } 1026 1027 for (const auto *At : Vd->attrs()) { 1028 switch (At->getKind()) { 1029 case attr::AcquiredBefore: { 1030 const auto *A = cast<AcquiredBeforeAttr>(At); 1031 1032 // Read exprs from the attribute, and add them to BeforeVect. 1033 for (const auto *Arg : A->args()) { 1034 CapabilityExpr Cp = 1035 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr); 1036 if (const ValueDecl *Cpvd = Cp.valueDecl()) { 1037 Info->Vect.push_back(Cpvd); 1038 const auto It = BMap.find(Cpvd); 1039 if (It == BMap.end()) 1040 insertAttrExprs(Cpvd, Analyzer); 1041 } 1042 } 1043 break; 1044 } 1045 case attr::AcquiredAfter: { 1046 const auto *A = cast<AcquiredAfterAttr>(At); 1047 1048 // Read exprs from the attribute, and add them to BeforeVect. 1049 for (const auto *Arg : A->args()) { 1050 CapabilityExpr Cp = 1051 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr); 1052 if (const ValueDecl *ArgVd = Cp.valueDecl()) { 1053 // Get entry for mutex listed in attribute 1054 BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer); 1055 ArgInfo->Vect.push_back(Vd); 1056 } 1057 } 1058 break; 1059 } 1060 default: 1061 break; 1062 } 1063 } 1064 1065 return Info; 1066 } 1067 1068 BeforeSet::BeforeInfo * 1069 BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd, 1070 ThreadSafetyAnalyzer &Analyzer) { 1071 auto It = BMap.find(Vd); 1072 BeforeInfo *Info = nullptr; 1073 if (It == BMap.end()) 1074 Info = insertAttrExprs(Vd, Analyzer); 1075 else 1076 Info = It->second.get(); 1077 assert(Info && "BMap contained nullptr?"); 1078 return Info; 1079 } 1080 1081 /// Return true if any mutexes in FSet are in the acquired_before set of Vd. 1082 void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd, 1083 const FactSet& FSet, 1084 ThreadSafetyAnalyzer& Analyzer, 1085 SourceLocation Loc, StringRef CapKind) { 1086 SmallVector<BeforeInfo*, 8> InfoVect; 1087 1088 // Do a depth-first traversal of Vd. 1089 // Return true if there are cycles. 1090 std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) { 1091 if (!Vd) 1092 return false; 1093 1094 BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer); 1095 1096 if (Info->Visited == 1) 1097 return true; 1098 1099 if (Info->Visited == 2) 1100 return false; 1101 1102 if (Info->Vect.empty()) 1103 return false; 1104 1105 InfoVect.push_back(Info); 1106 Info->Visited = 1; 1107 for (const auto *Vdb : Info->Vect) { 1108 // Exclude mutexes in our immediate before set. 1109 if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) { 1110 StringRef L1 = StartVd->getName(); 1111 StringRef L2 = Vdb->getName(); 1112 Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc); 1113 } 1114 // Transitively search other before sets, and warn on cycles. 1115 if (traverse(Vdb)) { 1116 if (CycMap.find(Vd) == CycMap.end()) { 1117 CycMap.insert(std::make_pair(Vd, true)); 1118 StringRef L1 = Vd->getName(); 1119 Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation()); 1120 } 1121 } 1122 } 1123 Info->Visited = 2; 1124 return false; 1125 }; 1126 1127 traverse(StartVd); 1128 1129 for (auto *Info : InfoVect) 1130 Info->Visited = 0; 1131 } 1132 1133 /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs. 1134 static const ValueDecl *getValueDecl(const Expr *Exp) { 1135 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp)) 1136 return getValueDecl(CE->getSubExpr()); 1137 1138 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp)) 1139 return DR->getDecl(); 1140 1141 if (const auto *ME = dyn_cast<MemberExpr>(Exp)) 1142 return ME->getMemberDecl(); 1143 1144 return nullptr; 1145 } 1146 1147 namespace { 1148 1149 template <typename Ty> 1150 class has_arg_iterator_range { 1151 using yes = char[1]; 1152 using no = char[2]; 1153 1154 template <typename Inner> 1155 static yes& test(Inner *I, decltype(I->args()) * = nullptr); 1156 1157 template <typename> 1158 static no& test(...); 1159 1160 public: 1161 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes); 1162 }; 1163 1164 } // namespace 1165 1166 static StringRef ClassifyDiagnostic(const CapabilityAttr *A) { 1167 return A->getName(); 1168 } 1169 1170 static StringRef ClassifyDiagnostic(QualType VDT) { 1171 // We need to look at the declaration of the type of the value to determine 1172 // which it is. The type should either be a record or a typedef, or a pointer 1173 // or reference thereof. 1174 if (const auto *RT = VDT->getAs<RecordType>()) { 1175 if (const auto *RD = RT->getDecl()) 1176 if (const auto *CA = RD->getAttr<CapabilityAttr>()) 1177 return ClassifyDiagnostic(CA); 1178 } else if (const auto *TT = VDT->getAs<TypedefType>()) { 1179 if (const auto *TD = TT->getDecl()) 1180 if (const auto *CA = TD->getAttr<CapabilityAttr>()) 1181 return ClassifyDiagnostic(CA); 1182 } else if (VDT->isPointerType() || VDT->isReferenceType()) 1183 return ClassifyDiagnostic(VDT->getPointeeType()); 1184 1185 return "mutex"; 1186 } 1187 1188 static StringRef ClassifyDiagnostic(const ValueDecl *VD) { 1189 assert(VD && "No ValueDecl passed"); 1190 1191 // The ValueDecl is the declaration of a mutex or role (hopefully). 1192 return ClassifyDiagnostic(VD->getType()); 1193 } 1194 1195 template <typename AttrTy> 1196 static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value, 1197 StringRef>::type 1198 ClassifyDiagnostic(const AttrTy *A) { 1199 if (const ValueDecl *VD = getValueDecl(A->getArg())) 1200 return ClassifyDiagnostic(VD); 1201 return "mutex"; 1202 } 1203 1204 template <typename AttrTy> 1205 static typename std::enable_if<has_arg_iterator_range<AttrTy>::value, 1206 StringRef>::type 1207 ClassifyDiagnostic(const AttrTy *A) { 1208 for (const auto *Arg : A->args()) { 1209 if (const ValueDecl *VD = getValueDecl(Arg)) 1210 return ClassifyDiagnostic(VD); 1211 } 1212 return "mutex"; 1213 } 1214 1215 bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) { 1216 if (!CurrentMethod) 1217 return false; 1218 if (const auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) { 1219 const auto *VD = P->clangDecl(); 1220 if (VD) 1221 return VD->getDeclContext() == CurrentMethod->getDeclContext(); 1222 } 1223 return false; 1224 } 1225 1226 /// \brief Add a new lock to the lockset, warning if the lock is already there. 1227 /// \param ReqAttr -- true if this is part of an initial Requires attribute. 1228 void ThreadSafetyAnalyzer::addLock(FactSet &FSet, 1229 std::unique_ptr<FactEntry> Entry, 1230 StringRef DiagKind, bool ReqAttr) { 1231 if (Entry->shouldIgnore()) 1232 return; 1233 1234 if (!ReqAttr && !Entry->negative()) { 1235 // look for the negative capability, and remove it from the fact set. 1236 CapabilityExpr NegC = !*Entry; 1237 FactEntry *Nen = FSet.findLock(FactMan, NegC); 1238 if (Nen) { 1239 FSet.removeLock(FactMan, NegC); 1240 } 1241 else { 1242 if (inCurrentScope(*Entry) && !Entry->asserted()) 1243 Handler.handleNegativeNotHeld(DiagKind, Entry->toString(), 1244 NegC.toString(), Entry->loc()); 1245 } 1246 } 1247 1248 // Check before/after constraints 1249 if (Handler.issueBetaWarnings() && 1250 !Entry->asserted() && !Entry->declared()) { 1251 GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this, 1252 Entry->loc(), DiagKind); 1253 } 1254 1255 // FIXME: Don't always warn when we have support for reentrant locks. 1256 if (FSet.findLock(FactMan, *Entry)) { 1257 if (!Entry->asserted()) 1258 Handler.handleDoubleLock(DiagKind, Entry->toString(), Entry->loc()); 1259 } else { 1260 FSet.addLock(FactMan, std::move(Entry)); 1261 } 1262 } 1263 1264 /// \brief Remove a lock from the lockset, warning if the lock is not there. 1265 /// \param UnlockLoc The source location of the unlock (only used in error msg) 1266 void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp, 1267 SourceLocation UnlockLoc, 1268 bool FullyRemove, LockKind ReceivedKind, 1269 StringRef DiagKind) { 1270 if (Cp.shouldIgnore()) 1271 return; 1272 1273 const FactEntry *LDat = FSet.findLock(FactMan, Cp); 1274 if (!LDat) { 1275 Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc); 1276 return; 1277 } 1278 1279 // Generic lock removal doesn't care about lock kind mismatches, but 1280 // otherwise diagnose when the lock kinds are mismatched. 1281 if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) { 1282 Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(), 1283 LDat->kind(), ReceivedKind, UnlockLoc); 1284 } 1285 1286 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler, 1287 DiagKind); 1288 } 1289 1290 /// \brief Extract the list of mutexIDs from the attribute on an expression, 1291 /// and push them onto Mtxs, discarding any duplicates. 1292 template <typename AttrType> 1293 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, 1294 Expr *Exp, const NamedDecl *D, 1295 VarDecl *SelfDecl) { 1296 if (Attr->args_size() == 0) { 1297 // The mutex held is the "this" object. 1298 CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl); 1299 if (Cp.isInvalid()) { 1300 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr)); 1301 return; 1302 } 1303 //else 1304 if (!Cp.shouldIgnore()) 1305 Mtxs.push_back_nodup(Cp); 1306 return; 1307 } 1308 1309 for (const auto *Arg : Attr->args()) { 1310 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl); 1311 if (Cp.isInvalid()) { 1312 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr)); 1313 continue; 1314 } 1315 //else 1316 if (!Cp.shouldIgnore()) 1317 Mtxs.push_back_nodup(Cp); 1318 } 1319 } 1320 1321 /// \brief Extract the list of mutexIDs from a trylock attribute. If the 1322 /// trylock applies to the given edge, then push them onto Mtxs, discarding 1323 /// any duplicates. 1324 template <class AttrType> 1325 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, 1326 Expr *Exp, const NamedDecl *D, 1327 const CFGBlock *PredBlock, 1328 const CFGBlock *CurrBlock, 1329 Expr *BrE, bool Neg) { 1330 // Find out which branch has the lock 1331 bool branch = false; 1332 if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) 1333 branch = BLE->getValue(); 1334 else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) 1335 branch = ILE->getValue().getBoolValue(); 1336 1337 int branchnum = branch ? 0 : 1; 1338 if (Neg) 1339 branchnum = !branchnum; 1340 1341 // If we've taken the trylock branch, then add the lock 1342 int i = 0; 1343 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(), 1344 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) { 1345 if (*SI == CurrBlock && i == branchnum) 1346 getMutexIDs(Mtxs, Attr, Exp, D); 1347 } 1348 } 1349 1350 static bool getStaticBooleanValue(Expr *E, bool &TCond) { 1351 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) { 1352 TCond = false; 1353 return true; 1354 } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) { 1355 TCond = BLE->getValue(); 1356 return true; 1357 } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) { 1358 TCond = ILE->getValue().getBoolValue(); 1359 return true; 1360 } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E)) 1361 return getStaticBooleanValue(CE->getSubExpr(), TCond); 1362 return false; 1363 } 1364 1365 // If Cond can be traced back to a function call, return the call expression. 1366 // The negate variable should be called with false, and will be set to true 1367 // if the function call is negated, e.g. if (!mu.tryLock(...)) 1368 const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond, 1369 LocalVarContext C, 1370 bool &Negate) { 1371 if (!Cond) 1372 return nullptr; 1373 1374 if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) 1375 return CallExp; 1376 else if (const auto *PE = dyn_cast<ParenExpr>(Cond)) 1377 return getTrylockCallExpr(PE->getSubExpr(), C, Negate); 1378 else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond)) 1379 return getTrylockCallExpr(CE->getSubExpr(), C, Negate); 1380 else if (const auto *EWC = dyn_cast<ExprWithCleanups>(Cond)) 1381 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate); 1382 else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) { 1383 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C); 1384 return getTrylockCallExpr(E, C, Negate); 1385 } 1386 else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) { 1387 if (UOP->getOpcode() == UO_LNot) { 1388 Negate = !Negate; 1389 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate); 1390 } 1391 return nullptr; 1392 } 1393 else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) { 1394 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) { 1395 if (BOP->getOpcode() == BO_NE) 1396 Negate = !Negate; 1397 1398 bool TCond = false; 1399 if (getStaticBooleanValue(BOP->getRHS(), TCond)) { 1400 if (!TCond) Negate = !Negate; 1401 return getTrylockCallExpr(BOP->getLHS(), C, Negate); 1402 } 1403 TCond = false; 1404 if (getStaticBooleanValue(BOP->getLHS(), TCond)) { 1405 if (!TCond) Negate = !Negate; 1406 return getTrylockCallExpr(BOP->getRHS(), C, Negate); 1407 } 1408 return nullptr; 1409 } 1410 if (BOP->getOpcode() == BO_LAnd) { 1411 // LHS must have been evaluated in a different block. 1412 return getTrylockCallExpr(BOP->getRHS(), C, Negate); 1413 } 1414 if (BOP->getOpcode() == BO_LOr) 1415 return getTrylockCallExpr(BOP->getRHS(), C, Negate); 1416 return nullptr; 1417 } 1418 return nullptr; 1419 } 1420 1421 /// \brief Find the lockset that holds on the edge between PredBlock 1422 /// and CurrBlock. The edge set is the exit set of PredBlock (passed 1423 /// as the ExitSet parameter) plus any trylocks, which are conditionally held. 1424 void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result, 1425 const FactSet &ExitSet, 1426 const CFGBlock *PredBlock, 1427 const CFGBlock *CurrBlock) { 1428 Result = ExitSet; 1429 1430 const Stmt *Cond = PredBlock->getTerminatorCondition(); 1431 if (!Cond) 1432 return; 1433 1434 bool Negate = false; 1435 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()]; 1436 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext; 1437 StringRef CapDiagKind = "mutex"; 1438 1439 auto *Exp = const_cast<CallExpr *>(getTrylockCallExpr(Cond, LVarCtx, Negate)); 1440 if (!Exp) 1441 return; 1442 1443 auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl()); 1444 if(!FunDecl || !FunDecl->hasAttrs()) 1445 return; 1446 1447 CapExprSet ExclusiveLocksToAdd; 1448 CapExprSet SharedLocksToAdd; 1449 1450 // If the condition is a call to a Trylock function, then grab the attributes 1451 for (const auto *Attr : FunDecl->attrs()) { 1452 switch (Attr->getKind()) { 1453 case attr::ExclusiveTrylockFunction: { 1454 const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr); 1455 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl, 1456 PredBlock, CurrBlock, A->getSuccessValue(), Negate); 1457 CapDiagKind = ClassifyDiagnostic(A); 1458 break; 1459 } 1460 case attr::SharedTrylockFunction: { 1461 const auto *A = cast<SharedTrylockFunctionAttr>(Attr); 1462 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl, 1463 PredBlock, CurrBlock, A->getSuccessValue(), Negate); 1464 CapDiagKind = ClassifyDiagnostic(A); 1465 break; 1466 } 1467 default: 1468 break; 1469 } 1470 } 1471 1472 // Add and remove locks. 1473 SourceLocation Loc = Exp->getExprLoc(); 1474 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd) 1475 addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd, 1476 LK_Exclusive, Loc), 1477 CapDiagKind); 1478 for (const auto &SharedLockToAdd : SharedLocksToAdd) 1479 addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd, 1480 LK_Shared, Loc), 1481 CapDiagKind); 1482 } 1483 1484 namespace { 1485 1486 /// \brief We use this class to visit different types of expressions in 1487 /// CFGBlocks, and build up the lockset. 1488 /// An expression may cause us to add or remove locks from the lockset, or else 1489 /// output error messages related to missing locks. 1490 /// FIXME: In future, we may be able to not inherit from a visitor. 1491 class BuildLockset : public StmtVisitor<BuildLockset> { 1492 friend class ThreadSafetyAnalyzer; 1493 1494 ThreadSafetyAnalyzer *Analyzer; 1495 FactSet FSet; 1496 LocalVariableMap::Context LVarCtx; 1497 unsigned CtxIndex; 1498 1499 // helper functions 1500 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK, 1501 Expr *MutexExp, ProtectedOperationKind POK, 1502 StringRef DiagKind, SourceLocation Loc); 1503 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp, 1504 StringRef DiagKind); 1505 1506 void checkAccess(const Expr *Exp, AccessKind AK, 1507 ProtectedOperationKind POK = POK_VarAccess); 1508 void checkPtAccess(const Expr *Exp, AccessKind AK, 1509 ProtectedOperationKind POK = POK_VarAccess); 1510 1511 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr); 1512 1513 public: 1514 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info) 1515 : StmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet), 1516 LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {} 1517 1518 void VisitUnaryOperator(UnaryOperator *UO); 1519 void VisitBinaryOperator(BinaryOperator *BO); 1520 void VisitCastExpr(CastExpr *CE); 1521 void VisitCallExpr(CallExpr *Exp); 1522 void VisitCXXConstructExpr(CXXConstructExpr *Exp); 1523 void VisitDeclStmt(DeclStmt *S); 1524 }; 1525 1526 } // namespace 1527 1528 /// \brief Warn if the LSet does not contain a lock sufficient to protect access 1529 /// of at least the passed in AccessKind. 1530 void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, 1531 AccessKind AK, Expr *MutexExp, 1532 ProtectedOperationKind POK, 1533 StringRef DiagKind, SourceLocation Loc) { 1534 LockKind LK = getLockKindFromAccessKind(AK); 1535 1536 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp); 1537 if (Cp.isInvalid()) { 1538 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind); 1539 return; 1540 } else if (Cp.shouldIgnore()) { 1541 return; 1542 } 1543 1544 if (Cp.negative()) { 1545 // Negative capabilities act like locks excluded 1546 FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp); 1547 if (LDat) { 1548 Analyzer->Handler.handleFunExcludesLock( 1549 DiagKind, D->getNameAsString(), (!Cp).toString(), Loc); 1550 return; 1551 } 1552 1553 // If this does not refer to a negative capability in the same class, 1554 // then stop here. 1555 if (!Analyzer->inCurrentScope(Cp)) 1556 return; 1557 1558 // Otherwise the negative requirement must be propagated to the caller. 1559 LDat = FSet.findLock(Analyzer->FactMan, Cp); 1560 if (!LDat) { 1561 Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(), 1562 LK_Shared, Loc); 1563 } 1564 return; 1565 } 1566 1567 FactEntry* LDat = FSet.findLockUniv(Analyzer->FactMan, Cp); 1568 bool NoError = true; 1569 if (!LDat) { 1570 // No exact match found. Look for a partial match. 1571 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp); 1572 if (LDat) { 1573 // Warn that there's no precise match. 1574 std::string PartMatchStr = LDat->toString(); 1575 StringRef PartMatchName(PartMatchStr); 1576 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(), 1577 LK, Loc, &PartMatchName); 1578 } else { 1579 // Warn that there's no match at all. 1580 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(), 1581 LK, Loc); 1582 } 1583 NoError = false; 1584 } 1585 // Make sure the mutex we found is the right kind. 1586 if (NoError && LDat && !LDat->isAtLeast(LK)) { 1587 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(), 1588 LK, Loc); 1589 } 1590 } 1591 1592 /// \brief Warn if the LSet contains the given lock. 1593 void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, 1594 Expr *MutexExp, StringRef DiagKind) { 1595 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp); 1596 if (Cp.isInvalid()) { 1597 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind); 1598 return; 1599 } else if (Cp.shouldIgnore()) { 1600 return; 1601 } 1602 1603 FactEntry* LDat = FSet.findLock(Analyzer->FactMan, Cp); 1604 if (LDat) { 1605 Analyzer->Handler.handleFunExcludesLock( 1606 DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc()); 1607 } 1608 } 1609 1610 /// \brief Checks guarded_by and pt_guarded_by attributes. 1611 /// Whenever we identify an access (read or write) to a DeclRefExpr that is 1612 /// marked with guarded_by, we must ensure the appropriate mutexes are held. 1613 /// Similarly, we check if the access is to an expression that dereferences 1614 /// a pointer marked with pt_guarded_by. 1615 void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK, 1616 ProtectedOperationKind POK) { 1617 Exp = Exp->IgnoreImplicit()->IgnoreParenCasts(); 1618 1619 SourceLocation Loc = Exp->getExprLoc(); 1620 1621 // Local variables of reference type cannot be re-assigned; 1622 // map them to their initializer. 1623 while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) { 1624 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl()); 1625 if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) { 1626 if (const auto *E = VD->getInit()) { 1627 Exp = E; 1628 continue; 1629 } 1630 } 1631 break; 1632 } 1633 1634 if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) { 1635 // For dereferences 1636 if (UO->getOpcode() == UO_Deref) 1637 checkPtAccess(UO->getSubExpr(), AK, POK); 1638 return; 1639 } 1640 1641 if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) { 1642 checkPtAccess(AE->getLHS(), AK, POK); 1643 return; 1644 } 1645 1646 if (const auto *ME = dyn_cast<MemberExpr>(Exp)) { 1647 if (ME->isArrow()) 1648 checkPtAccess(ME->getBase(), AK, POK); 1649 else 1650 checkAccess(ME->getBase(), AK, POK); 1651 } 1652 1653 const ValueDecl *D = getValueDecl(Exp); 1654 if (!D || !D->hasAttrs()) 1655 return; 1656 1657 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) { 1658 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc); 1659 } 1660 1661 for (const auto *I : D->specific_attrs<GuardedByAttr>()) 1662 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK, 1663 ClassifyDiagnostic(I), Loc); 1664 } 1665 1666 /// \brief Checks pt_guarded_by and pt_guarded_var attributes. 1667 /// POK is the same operationKind that was passed to checkAccess. 1668 void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK, 1669 ProtectedOperationKind POK) { 1670 while (true) { 1671 if (const auto *PE = dyn_cast<ParenExpr>(Exp)) { 1672 Exp = PE->getSubExpr(); 1673 continue; 1674 } 1675 if (const auto *CE = dyn_cast<CastExpr>(Exp)) { 1676 if (CE->getCastKind() == CK_ArrayToPointerDecay) { 1677 // If it's an actual array, and not a pointer, then it's elements 1678 // are protected by GUARDED_BY, not PT_GUARDED_BY; 1679 checkAccess(CE->getSubExpr(), AK, POK); 1680 return; 1681 } 1682 Exp = CE->getSubExpr(); 1683 continue; 1684 } 1685 break; 1686 } 1687 1688 // Pass by reference warnings are under a different flag. 1689 ProtectedOperationKind PtPOK = POK_VarDereference; 1690 if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef; 1691 1692 const ValueDecl *D = getValueDecl(Exp); 1693 if (!D || !D->hasAttrs()) 1694 return; 1695 1696 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) 1697 Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK, 1698 Exp->getExprLoc()); 1699 1700 for (auto const *I : D->specific_attrs<PtGuardedByAttr>()) 1701 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK, 1702 ClassifyDiagnostic(I), Exp->getExprLoc()); 1703 } 1704 1705 /// \brief Process a function call, method call, constructor call, 1706 /// or destructor call. This involves looking at the attributes on the 1707 /// corresponding function/method/constructor/destructor, issuing warnings, 1708 /// and updating the locksets accordingly. 1709 /// 1710 /// FIXME: For classes annotated with one of the guarded annotations, we need 1711 /// to treat const method calls as reads and non-const method calls as writes, 1712 /// and check that the appropriate locks are held. Non-const method calls with 1713 /// the same signature as const method calls can be also treated as reads. 1714 /// 1715 void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) { 1716 SourceLocation Loc = Exp->getExprLoc(); 1717 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd; 1718 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove; 1719 CapExprSet ScopedExclusiveReqs, ScopedSharedReqs; 1720 StringRef CapDiagKind = "mutex"; 1721 1722 // Figure out if we're constructing an object of scoped lockable class 1723 bool isScopedVar = false; 1724 if (VD) { 1725 if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) { 1726 const CXXRecordDecl* PD = CD->getParent(); 1727 if (PD && PD->hasAttr<ScopedLockableAttr>()) 1728 isScopedVar = true; 1729 } 1730 } 1731 1732 for(Attr *Atconst : D->attrs()) { 1733 auto *At = const_cast<Attr *>(Atconst); 1734 switch (At->getKind()) { 1735 // When we encounter a lock function, we need to add the lock to our 1736 // lockset. 1737 case attr::AcquireCapability: { 1738 const auto *A = cast<AcquireCapabilityAttr>(At); 1739 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd 1740 : ExclusiveLocksToAdd, 1741 A, Exp, D, VD); 1742 1743 CapDiagKind = ClassifyDiagnostic(A); 1744 break; 1745 } 1746 1747 // An assert will add a lock to the lockset, but will not generate 1748 // a warning if it is already there, and will not generate a warning 1749 // if it is not removed. 1750 case attr::AssertExclusiveLock: { 1751 const auto *A = cast<AssertExclusiveLockAttr>(At); 1752 1753 CapExprSet AssertLocks; 1754 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD); 1755 for (const auto &AssertLock : AssertLocks) 1756 Analyzer->addLock(FSet, 1757 llvm::make_unique<LockableFactEntry>( 1758 AssertLock, LK_Exclusive, Loc, false, true), 1759 ClassifyDiagnostic(A)); 1760 break; 1761 } 1762 case attr::AssertSharedLock: { 1763 const auto *A = cast<AssertSharedLockAttr>(At); 1764 1765 CapExprSet AssertLocks; 1766 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD); 1767 for (const auto &AssertLock : AssertLocks) 1768 Analyzer->addLock(FSet, 1769 llvm::make_unique<LockableFactEntry>( 1770 AssertLock, LK_Shared, Loc, false, true), 1771 ClassifyDiagnostic(A)); 1772 break; 1773 } 1774 1775 case attr::AssertCapability: { 1776 const auto *A = cast<AssertCapabilityAttr>(At); 1777 CapExprSet AssertLocks; 1778 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD); 1779 for (const auto &AssertLock : AssertLocks) 1780 Analyzer->addLock(FSet, 1781 llvm::make_unique<LockableFactEntry>( 1782 AssertLock, 1783 A->isShared() ? LK_Shared : LK_Exclusive, Loc, 1784 false, true), 1785 ClassifyDiagnostic(A)); 1786 break; 1787 } 1788 1789 // When we encounter an unlock function, we need to remove unlocked 1790 // mutexes from the lockset, and flag a warning if they are not there. 1791 case attr::ReleaseCapability: { 1792 const auto *A = cast<ReleaseCapabilityAttr>(At); 1793 if (A->isGeneric()) 1794 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD); 1795 else if (A->isShared()) 1796 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD); 1797 else 1798 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD); 1799 1800 CapDiagKind = ClassifyDiagnostic(A); 1801 break; 1802 } 1803 1804 case attr::RequiresCapability: { 1805 const auto *A = cast<RequiresCapabilityAttr>(At); 1806 for (auto *Arg : A->args()) { 1807 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg, 1808 POK_FunctionCall, ClassifyDiagnostic(A), 1809 Exp->getExprLoc()); 1810 // use for adopting a lock 1811 if (isScopedVar) { 1812 Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs 1813 : ScopedExclusiveReqs, 1814 A, Exp, D, VD); 1815 } 1816 } 1817 break; 1818 } 1819 1820 case attr::LocksExcluded: { 1821 const auto *A = cast<LocksExcludedAttr>(At); 1822 for (auto *Arg : A->args()) 1823 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A)); 1824 break; 1825 } 1826 1827 // Ignore attributes unrelated to thread-safety 1828 default: 1829 break; 1830 } 1831 } 1832 1833 // Add locks. 1834 for (const auto &M : ExclusiveLocksToAdd) 1835 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>( 1836 M, LK_Exclusive, Loc, isScopedVar), 1837 CapDiagKind); 1838 for (const auto &M : SharedLocksToAdd) 1839 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>( 1840 M, LK_Shared, Loc, isScopedVar), 1841 CapDiagKind); 1842 1843 if (isScopedVar) { 1844 // Add the managing object as a dummy mutex, mapped to the underlying mutex. 1845 SourceLocation MLoc = VD->getLocation(); 1846 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation()); 1847 // FIXME: does this store a pointer to DRE? 1848 CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr); 1849 1850 std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(), 1851 std::back_inserter(ExclusiveLocksToAdd)); 1852 std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(), 1853 std::back_inserter(SharedLocksToAdd)); 1854 Analyzer->addLock(FSet, 1855 llvm::make_unique<ScopedLockableFactEntry>( 1856 Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd), 1857 CapDiagKind); 1858 } 1859 1860 // Remove locks. 1861 // FIXME -- should only fully remove if the attribute refers to 'this'. 1862 bool Dtor = isa<CXXDestructorDecl>(D); 1863 for (const auto &M : ExclusiveLocksToRemove) 1864 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind); 1865 for (const auto &M : SharedLocksToRemove) 1866 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind); 1867 for (const auto &M : GenericLocksToRemove) 1868 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind); 1869 } 1870 1871 /// \brief For unary operations which read and write a variable, we need to 1872 /// check whether we hold any required mutexes. Reads are checked in 1873 /// VisitCastExpr. 1874 void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) { 1875 switch (UO->getOpcode()) { 1876 case UO_PostDec: 1877 case UO_PostInc: 1878 case UO_PreDec: 1879 case UO_PreInc: 1880 checkAccess(UO->getSubExpr(), AK_Written); 1881 break; 1882 default: 1883 break; 1884 } 1885 } 1886 1887 /// For binary operations which assign to a variable (writes), we need to check 1888 /// whether we hold any required mutexes. 1889 /// FIXME: Deal with non-primitive types. 1890 void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) { 1891 if (!BO->isAssignmentOp()) 1892 return; 1893 1894 // adjust the context 1895 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx); 1896 1897 checkAccess(BO->getLHS(), AK_Written); 1898 } 1899 1900 /// Whenever we do an LValue to Rvalue cast, we are reading a variable and 1901 /// need to ensure we hold any required mutexes. 1902 /// FIXME: Deal with non-primitive types. 1903 void BuildLockset::VisitCastExpr(CastExpr *CE) { 1904 if (CE->getCastKind() != CK_LValueToRValue) 1905 return; 1906 checkAccess(CE->getSubExpr(), AK_Read); 1907 } 1908 1909 void BuildLockset::VisitCallExpr(CallExpr *Exp) { 1910 bool ExamineArgs = true; 1911 bool OperatorFun = false; 1912 1913 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) { 1914 const auto *ME = dyn_cast<MemberExpr>(CE->getCallee()); 1915 // ME can be null when calling a method pointer 1916 const CXXMethodDecl *MD = CE->getMethodDecl(); 1917 1918 if (ME && MD) { 1919 if (ME->isArrow()) { 1920 if (MD->isConst()) 1921 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read); 1922 else // FIXME -- should be AK_Written 1923 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read); 1924 } else { 1925 if (MD->isConst()) 1926 checkAccess(CE->getImplicitObjectArgument(), AK_Read); 1927 else // FIXME -- should be AK_Written 1928 checkAccess(CE->getImplicitObjectArgument(), AK_Read); 1929 } 1930 } 1931 } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) { 1932 OperatorFun = true; 1933 1934 auto OEop = OE->getOperator(); 1935 switch (OEop) { 1936 case OO_Equal: { 1937 ExamineArgs = false; 1938 const Expr *Target = OE->getArg(0); 1939 const Expr *Source = OE->getArg(1); 1940 checkAccess(Target, AK_Written); 1941 checkAccess(Source, AK_Read); 1942 break; 1943 } 1944 case OO_Star: 1945 case OO_Arrow: 1946 case OO_Subscript: { 1947 const Expr *Obj = OE->getArg(0); 1948 checkAccess(Obj, AK_Read); 1949 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) { 1950 // Grrr. operator* can be multiplication... 1951 checkPtAccess(Obj, AK_Read); 1952 } 1953 break; 1954 } 1955 default: { 1956 // TODO: get rid of this, and rely on pass-by-ref instead. 1957 const Expr *Obj = OE->getArg(0); 1958 checkAccess(Obj, AK_Read); 1959 break; 1960 } 1961 } 1962 } 1963 1964 if (ExamineArgs) { 1965 if (FunctionDecl *FD = Exp->getDirectCallee()) { 1966 // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it 1967 // only turns off checking within the body of a function, but we also 1968 // use it to turn off checking in arguments to the function. This 1969 // could result in some false negatives, but the alternative is to 1970 // create yet another attribute. 1971 if (!FD->hasAttr<NoThreadSafetyAnalysisAttr>()) { 1972 unsigned Fn = FD->getNumParams(); 1973 unsigned Cn = Exp->getNumArgs(); 1974 unsigned Skip = 0; 1975 1976 unsigned i = 0; 1977 if (OperatorFun) { 1978 if (isa<CXXMethodDecl>(FD)) { 1979 // First arg in operator call is implicit self argument, 1980 // and doesn't appear in the FunctionDecl. 1981 Skip = 1; 1982 Cn--; 1983 } else { 1984 // Ignore the first argument of operators; it's been checked above. 1985 i = 1; 1986 } 1987 } 1988 // Ignore default arguments 1989 unsigned n = (Fn < Cn) ? Fn : Cn; 1990 1991 for (; i < n; ++i) { 1992 ParmVarDecl* Pvd = FD->getParamDecl(i); 1993 Expr* Arg = Exp->getArg(i+Skip); 1994 QualType Qt = Pvd->getType(); 1995 if (Qt->isReferenceType()) 1996 checkAccess(Arg, AK_Read, POK_PassByRef); 1997 } 1998 } 1999 } 2000 } 2001 2002 auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl()); 2003 if(!D || !D->hasAttrs()) 2004 return; 2005 handleCall(Exp, D); 2006 } 2007 2008 void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) { 2009 const CXXConstructorDecl *D = Exp->getConstructor(); 2010 if (D && D->isCopyConstructor()) { 2011 const Expr* Source = Exp->getArg(0); 2012 checkAccess(Source, AK_Read); 2013 } 2014 // FIXME -- only handles constructors in DeclStmt below. 2015 } 2016 2017 static CXXConstructorDecl * 2018 findConstructorForByValueReturn(const CXXRecordDecl *RD) { 2019 // Prefer a move constructor over a copy constructor. If there's more than 2020 // one copy constructor or more than one move constructor, we arbitrarily 2021 // pick the first declared such constructor rather than trying to guess which 2022 // one is more appropriate. 2023 CXXConstructorDecl *CopyCtor = nullptr; 2024 for (auto *Ctor : RD->ctors()) { 2025 if (Ctor->isDeleted()) 2026 continue; 2027 if (Ctor->isMoveConstructor()) 2028 return Ctor; 2029 if (!CopyCtor && Ctor->isCopyConstructor()) 2030 CopyCtor = Ctor; 2031 } 2032 return CopyCtor; 2033 } 2034 2035 static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args, 2036 SourceLocation Loc) { 2037 ASTContext &Ctx = CD->getASTContext(); 2038 return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc, 2039 CD, true, Args, false, false, false, false, 2040 CXXConstructExpr::CK_Complete, 2041 SourceRange(Loc, Loc)); 2042 } 2043 2044 void BuildLockset::VisitDeclStmt(DeclStmt *S) { 2045 // adjust the context 2046 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx); 2047 2048 for (auto *D : S->getDeclGroup()) { 2049 if (auto *VD = dyn_cast_or_null<VarDecl>(D)) { 2050 Expr *E = VD->getInit(); 2051 if (!E) 2052 continue; 2053 E = E->IgnoreParens(); 2054 2055 // handle constructors that involve temporaries 2056 if (auto *EWC = dyn_cast<ExprWithCleanups>(E)) 2057 E = EWC->getSubExpr(); 2058 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E)) 2059 E = BTE->getSubExpr(); 2060 2061 if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) { 2062 const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor()); 2063 if (!CtorD || !CtorD->hasAttrs()) 2064 continue; 2065 handleCall(E, CtorD, VD); 2066 } else if (isa<CallExpr>(E) && E->isRValue()) { 2067 // If the object is initialized by a function call that returns a 2068 // scoped lockable by value, use the attributes on the copy or move 2069 // constructor to figure out what effect that should have on the 2070 // lockset. 2071 // FIXME: Is this really the best way to handle this situation? 2072 auto *RD = E->getType()->getAsCXXRecordDecl(); 2073 if (!RD || !RD->hasAttr<ScopedLockableAttr>()) 2074 continue; 2075 CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD); 2076 if (!CtorD || !CtorD->hasAttrs()) 2077 continue; 2078 handleCall(buildFakeCtorCall(CtorD, {E}, E->getLocStart()), CtorD, VD); 2079 } 2080 } 2081 } 2082 } 2083 2084 /// \brief Compute the intersection of two locksets and issue warnings for any 2085 /// locks in the symmetric difference. 2086 /// 2087 /// This function is used at a merge point in the CFG when comparing the lockset 2088 /// of each branch being merged. For example, given the following sequence: 2089 /// A; if () then B; else C; D; we need to check that the lockset after B and C 2090 /// are the same. In the event of a difference, we use the intersection of these 2091 /// two locksets at the start of D. 2092 /// 2093 /// \param FSet1 The first lockset. 2094 /// \param FSet2 The second lockset. 2095 /// \param JoinLoc The location of the join point for error reporting 2096 /// \param LEK1 The error message to report if a mutex is missing from LSet1 2097 /// \param LEK2 The error message to report if a mutex is missing from Lset2 2098 void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1, 2099 const FactSet &FSet2, 2100 SourceLocation JoinLoc, 2101 LockErrorKind LEK1, 2102 LockErrorKind LEK2, 2103 bool Modify) { 2104 FactSet FSet1Orig = FSet1; 2105 2106 // Find locks in FSet2 that conflict or are not in FSet1, and warn. 2107 for (const auto &Fact : FSet2) { 2108 const FactEntry *LDat1 = nullptr; 2109 const FactEntry *LDat2 = &FactMan[Fact]; 2110 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2); 2111 if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1]; 2112 2113 if (LDat1) { 2114 if (LDat1->kind() != LDat2->kind()) { 2115 Handler.handleExclusiveAndShared("mutex", LDat2->toString(), 2116 LDat2->loc(), LDat1->loc()); 2117 if (Modify && LDat1->kind() != LK_Exclusive) { 2118 // Take the exclusive lock, which is the one in FSet2. 2119 *Iter1 = Fact; 2120 } 2121 } 2122 else if (Modify && LDat1->asserted() && !LDat2->asserted()) { 2123 // The non-asserted lock in FSet2 is the one we want to track. 2124 *Iter1 = Fact; 2125 } 2126 } else { 2127 LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1, 2128 Handler); 2129 } 2130 } 2131 2132 // Find locks in FSet1 that are not in FSet2, and remove them. 2133 for (const auto &Fact : FSet1Orig) { 2134 const FactEntry *LDat1 = &FactMan[Fact]; 2135 const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1); 2136 2137 if (!LDat2) { 2138 LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2, 2139 Handler); 2140 if (Modify) 2141 FSet1.removeLock(FactMan, *LDat1); 2142 } 2143 } 2144 } 2145 2146 // Return true if block B never continues to its successors. 2147 static bool neverReturns(const CFGBlock *B) { 2148 if (B->hasNoReturnElement()) 2149 return true; 2150 if (B->empty()) 2151 return false; 2152 2153 CFGElement Last = B->back(); 2154 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) { 2155 if (isa<CXXThrowExpr>(S->getStmt())) 2156 return true; 2157 } 2158 return false; 2159 } 2160 2161 /// \brief Check a function's CFG for thread-safety violations. 2162 /// 2163 /// We traverse the blocks in the CFG, compute the set of mutexes that are held 2164 /// at the end of each block, and issue warnings for thread safety violations. 2165 /// Each block in the CFG is traversed exactly once. 2166 void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) { 2167 // TODO: this whole function needs be rewritten as a visitor for CFGWalker. 2168 // For now, we just use the walker to set things up. 2169 threadSafety::CFGWalker walker; 2170 if (!walker.init(AC)) 2171 return; 2172 2173 // AC.dumpCFG(true); 2174 // threadSafety::printSCFG(walker); 2175 2176 CFG *CFGraph = walker.getGraph(); 2177 const NamedDecl *D = walker.getDecl(); 2178 const auto *CurrentFunction = dyn_cast<FunctionDecl>(D); 2179 CurrentMethod = dyn_cast<CXXMethodDecl>(D); 2180 2181 if (D->hasAttr<NoThreadSafetyAnalysisAttr>()) 2182 return; 2183 2184 // FIXME: Do something a bit more intelligent inside constructor and 2185 // destructor code. Constructors and destructors must assume unique access 2186 // to 'this', so checks on member variable access is disabled, but we should 2187 // still enable checks on other objects. 2188 if (isa<CXXConstructorDecl>(D)) 2189 return; // Don't check inside constructors. 2190 if (isa<CXXDestructorDecl>(D)) 2191 return; // Don't check inside destructors. 2192 2193 Handler.enterFunction(CurrentFunction); 2194 2195 BlockInfo.resize(CFGraph->getNumBlockIDs(), 2196 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap)); 2197 2198 // We need to explore the CFG via a "topological" ordering. 2199 // That way, we will be guaranteed to have information about required 2200 // predecessor locksets when exploring a new block. 2201 const PostOrderCFGView *SortedGraph = walker.getSortedGraph(); 2202 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph); 2203 2204 // Mark entry block as reachable 2205 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true; 2206 2207 // Compute SSA names for local variables 2208 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo); 2209 2210 // Fill in source locations for all CFGBlocks. 2211 findBlockLocations(CFGraph, SortedGraph, BlockInfo); 2212 2213 CapExprSet ExclusiveLocksAcquired; 2214 CapExprSet SharedLocksAcquired; 2215 CapExprSet LocksReleased; 2216 2217 // Add locks from exclusive_locks_required and shared_locks_required 2218 // to initial lockset. Also turn off checking for lock and unlock functions. 2219 // FIXME: is there a more intelligent way to check lock/unlock functions? 2220 if (!SortedGraph->empty() && D->hasAttrs()) { 2221 const CFGBlock *FirstBlock = *SortedGraph->begin(); 2222 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet; 2223 2224 CapExprSet ExclusiveLocksToAdd; 2225 CapExprSet SharedLocksToAdd; 2226 StringRef CapDiagKind = "mutex"; 2227 2228 SourceLocation Loc = D->getLocation(); 2229 for (const auto *Attr : D->attrs()) { 2230 Loc = Attr->getLocation(); 2231 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) { 2232 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A, 2233 nullptr, D); 2234 CapDiagKind = ClassifyDiagnostic(A); 2235 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) { 2236 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation. 2237 // We must ignore such methods. 2238 if (A->args_size() == 0) 2239 return; 2240 // FIXME -- deal with exclusive vs. shared unlock functions? 2241 getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D); 2242 getMutexIDs(LocksReleased, A, nullptr, D); 2243 CapDiagKind = ClassifyDiagnostic(A); 2244 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) { 2245 if (A->args_size() == 0) 2246 return; 2247 getMutexIDs(A->isShared() ? SharedLocksAcquired 2248 : ExclusiveLocksAcquired, 2249 A, nullptr, D); 2250 CapDiagKind = ClassifyDiagnostic(A); 2251 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) { 2252 // Don't try to check trylock functions for now 2253 return; 2254 } else if (isa<SharedTrylockFunctionAttr>(Attr)) { 2255 // Don't try to check trylock functions for now 2256 return; 2257 } 2258 } 2259 2260 // FIXME -- Loc can be wrong here. 2261 for (const auto &Mu : ExclusiveLocksToAdd) { 2262 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc); 2263 Entry->setDeclared(true); 2264 addLock(InitialLockset, std::move(Entry), CapDiagKind, true); 2265 } 2266 for (const auto &Mu : SharedLocksToAdd) { 2267 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc); 2268 Entry->setDeclared(true); 2269 addLock(InitialLockset, std::move(Entry), CapDiagKind, true); 2270 } 2271 } 2272 2273 for (const auto *CurrBlock : *SortedGraph) { 2274 int CurrBlockID = CurrBlock->getBlockID(); 2275 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID]; 2276 2277 // Use the default initial lockset in case there are no predecessors. 2278 VisitedBlocks.insert(CurrBlock); 2279 2280 // Iterate through the predecessor blocks and warn if the lockset for all 2281 // predecessors is not the same. We take the entry lockset of the current 2282 // block to be the intersection of all previous locksets. 2283 // FIXME: By keeping the intersection, we may output more errors in future 2284 // for a lock which is not in the intersection, but was in the union. We 2285 // may want to also keep the union in future. As an example, let's say 2286 // the intersection contains Mutex L, and the union contains L and M. 2287 // Later we unlock M. At this point, we would output an error because we 2288 // never locked M; although the real error is probably that we forgot to 2289 // lock M on all code paths. Conversely, let's say that later we lock M. 2290 // In this case, we should compare against the intersection instead of the 2291 // union because the real error is probably that we forgot to unlock M on 2292 // all code paths. 2293 bool LocksetInitialized = false; 2294 SmallVector<CFGBlock *, 8> SpecialBlocks; 2295 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(), 2296 PE = CurrBlock->pred_end(); PI != PE; ++PI) { 2297 // if *PI -> CurrBlock is a back edge 2298 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) 2299 continue; 2300 2301 int PrevBlockID = (*PI)->getBlockID(); 2302 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 2303 2304 // Ignore edges from blocks that can't return. 2305 if (neverReturns(*PI) || !PrevBlockInfo->Reachable) 2306 continue; 2307 2308 // Okay, we can reach this block from the entry. 2309 CurrBlockInfo->Reachable = true; 2310 2311 // If the previous block ended in a 'continue' or 'break' statement, then 2312 // a difference in locksets is probably due to a bug in that block, rather 2313 // than in some other predecessor. In that case, keep the other 2314 // predecessor's lockset. 2315 if (const Stmt *Terminator = (*PI)->getTerminator()) { 2316 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) { 2317 SpecialBlocks.push_back(*PI); 2318 continue; 2319 } 2320 } 2321 2322 FactSet PrevLockset; 2323 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock); 2324 2325 if (!LocksetInitialized) { 2326 CurrBlockInfo->EntrySet = PrevLockset; 2327 LocksetInitialized = true; 2328 } else { 2329 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset, 2330 CurrBlockInfo->EntryLoc, 2331 LEK_LockedSomePredecessors); 2332 } 2333 } 2334 2335 // Skip rest of block if it's not reachable. 2336 if (!CurrBlockInfo->Reachable) 2337 continue; 2338 2339 // Process continue and break blocks. Assume that the lockset for the 2340 // resulting block is unaffected by any discrepancies in them. 2341 for (const auto *PrevBlock : SpecialBlocks) { 2342 int PrevBlockID = PrevBlock->getBlockID(); 2343 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 2344 2345 if (!LocksetInitialized) { 2346 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet; 2347 LocksetInitialized = true; 2348 } else { 2349 // Determine whether this edge is a loop terminator for diagnostic 2350 // purposes. FIXME: A 'break' statement might be a loop terminator, but 2351 // it might also be part of a switch. Also, a subsequent destructor 2352 // might add to the lockset, in which case the real issue might be a 2353 // double lock on the other path. 2354 const Stmt *Terminator = PrevBlock->getTerminator(); 2355 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator); 2356 2357 FactSet PrevLockset; 2358 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, 2359 PrevBlock, CurrBlock); 2360 2361 // Do not update EntrySet. 2362 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset, 2363 PrevBlockInfo->ExitLoc, 2364 IsLoop ? LEK_LockedSomeLoopIterations 2365 : LEK_LockedSomePredecessors, 2366 false); 2367 } 2368 } 2369 2370 BuildLockset LocksetBuilder(this, *CurrBlockInfo); 2371 2372 // Visit all the statements in the basic block. 2373 for (const auto &BI : *CurrBlock) { 2374 switch (BI.getKind()) { 2375 case CFGElement::Statement: { 2376 CFGStmt CS = BI.castAs<CFGStmt>(); 2377 LocksetBuilder.Visit(const_cast<Stmt *>(CS.getStmt())); 2378 break; 2379 } 2380 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now. 2381 case CFGElement::AutomaticObjectDtor: { 2382 CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>(); 2383 auto *DD = const_cast<CXXDestructorDecl *>( 2384 AD.getDestructorDecl(AC.getASTContext())); 2385 if (!DD->hasAttrs()) 2386 break; 2387 2388 // Create a dummy expression, 2389 auto *VD = const_cast<VarDecl *>(AD.getVarDecl()); 2390 DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(), 2391 VK_LValue, AD.getTriggerStmt()->getLocEnd()); 2392 LocksetBuilder.handleCall(&DRE, DD); 2393 break; 2394 } 2395 default: 2396 break; 2397 } 2398 } 2399 CurrBlockInfo->ExitSet = LocksetBuilder.FSet; 2400 2401 // For every back edge from CurrBlock (the end of the loop) to another block 2402 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to 2403 // the one held at the beginning of FirstLoopBlock. We can look up the 2404 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map. 2405 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(), 2406 SE = CurrBlock->succ_end(); SI != SE; ++SI) { 2407 // if CurrBlock -> *SI is *not* a back edge 2408 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI)) 2409 continue; 2410 2411 CFGBlock *FirstLoopBlock = *SI; 2412 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()]; 2413 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID]; 2414 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet, 2415 PreLoop->EntryLoc, 2416 LEK_LockedSomeLoopIterations, 2417 false); 2418 } 2419 } 2420 2421 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()]; 2422 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()]; 2423 2424 // Skip the final check if the exit block is unreachable. 2425 if (!Final->Reachable) 2426 return; 2427 2428 // By default, we expect all locks held on entry to be held on exit. 2429 FactSet ExpectedExitSet = Initial->EntrySet; 2430 2431 // Adjust the expected exit set by adding or removing locks, as declared 2432 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then 2433 // issue the appropriate warning. 2434 // FIXME: the location here is not quite right. 2435 for (const auto &Lock : ExclusiveLocksAcquired) 2436 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>( 2437 Lock, LK_Exclusive, D->getLocation())); 2438 for (const auto &Lock : SharedLocksAcquired) 2439 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>( 2440 Lock, LK_Shared, D->getLocation())); 2441 for (const auto &Lock : LocksReleased) 2442 ExpectedExitSet.removeLock(FactMan, Lock); 2443 2444 // FIXME: Should we call this function for all blocks which exit the function? 2445 intersectAndWarn(ExpectedExitSet, Final->ExitSet, 2446 Final->ExitLoc, 2447 LEK_LockedAtEndOfFunction, 2448 LEK_NotLockedAtEndOfFunction, 2449 false); 2450 2451 Handler.leaveFunction(CurrentFunction); 2452 } 2453 2454 /// \brief Check a function's CFG for thread-safety violations. 2455 /// 2456 /// We traverse the blocks in the CFG, compute the set of mutexes that are held 2457 /// at the end of each block, and issue warnings for thread safety violations. 2458 /// Each block in the CFG is traversed exactly once. 2459 void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC, 2460 ThreadSafetyHandler &Handler, 2461 BeforeSet **BSet) { 2462 if (!*BSet) 2463 *BSet = new BeforeSet; 2464 ThreadSafetyAnalyzer Analyzer(Handler, *BSet); 2465 Analyzer.runAnalysis(AC); 2466 } 2467 2468 void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; } 2469 2470 /// \brief Helper function that returns a LockKind required for the given level 2471 /// of access. 2472 LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) { 2473 switch (AK) { 2474 case AK_Read : 2475 return LK_Shared; 2476 case AK_Written : 2477 return LK_Exclusive; 2478 } 2479 llvm_unreachable("Unknown AccessKind"); 2480 } 2481