1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===// 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 // "Meta" ASTConsumer for running different source analyses. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h" 15 #include "ModelInjector.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/RecursiveASTVisitor.h" 20 #include "clang/Analysis/Analyses/LiveVariables.h" 21 #include "clang/Analysis/CFG.h" 22 #include "clang/Analysis/CallGraph.h" 23 #include "clang/Analysis/CodeInjector.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Frontend/CompilerInstance.h" 26 #include "clang/Lex/Preprocessor.h" 27 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h" 28 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 29 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 30 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 31 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 32 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" 33 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 34 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 35 #include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h" 36 #include "llvm/ADT/PostOrderIterator.h" 37 #include "llvm/ADT/Statistic.h" 38 #include "llvm/Support/FileSystem.h" 39 #include "llvm/Support/Path.h" 40 #include "llvm/Support/Program.h" 41 #include "llvm/Support/Timer.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <memory> 44 #include <queue> 45 #include <utility> 46 47 using namespace clang; 48 using namespace ento; 49 50 #define DEBUG_TYPE "AnalysisConsumer" 51 52 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz(); 53 54 STATISTIC(NumFunctionTopLevel, "The # of functions at top level."); 55 STATISTIC(NumFunctionsAnalyzed, 56 "The # of functions and blocks analyzed (as top level " 57 "with inlining turned on)."); 58 STATISTIC(NumBlocksInAnalyzedFunctions, 59 "The # of basic blocks in the analyzed functions."); 60 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks."); 61 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function."); 62 63 //===----------------------------------------------------------------------===// 64 // Special PathDiagnosticConsumers. 65 //===----------------------------------------------------------------------===// 66 67 void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, 68 PathDiagnosticConsumers &C, 69 const std::string &prefix, 70 const Preprocessor &PP) { 71 createHTMLDiagnosticConsumer(AnalyzerOpts, C, 72 llvm::sys::path::parent_path(prefix), PP); 73 createPlistDiagnosticConsumer(AnalyzerOpts, C, prefix, PP); 74 } 75 76 void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, 77 PathDiagnosticConsumers &C, 78 const std::string &Prefix, 79 const clang::Preprocessor &PP) { 80 llvm_unreachable("'text' consumer should be enabled on ClangDiags"); 81 } 82 83 namespace { 84 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer { 85 DiagnosticsEngine &Diag; 86 bool IncludePath; 87 public: 88 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag) 89 : Diag(Diag), IncludePath(false) {} 90 ~ClangDiagPathDiagConsumer() override {} 91 StringRef getName() const override { return "ClangDiags"; } 92 93 bool supportsLogicalOpControlFlow() const override { return true; } 94 bool supportsCrossFileDiagnostics() const override { return true; } 95 96 PathGenerationScheme getGenerationScheme() const override { 97 return IncludePath ? Minimal : None; 98 } 99 100 void enablePaths() { 101 IncludePath = true; 102 } 103 104 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags, 105 FilesMade *filesMade) override { 106 unsigned WarnID = Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0"); 107 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0"); 108 109 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(), 110 E = Diags.end(); I != E; ++I) { 111 const PathDiagnostic *PD = *I; 112 SourceLocation WarnLoc = PD->getLocation().asLocation(); 113 Diag.Report(WarnLoc, WarnID) << PD->getShortDescription() 114 << PD->path.back()->getRanges(); 115 116 if (!IncludePath) 117 continue; 118 119 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true); 120 for (PathPieces::const_iterator PI = FlatPath.begin(), 121 PE = FlatPath.end(); 122 PI != PE; ++PI) { 123 SourceLocation NoteLoc = (*PI)->getLocation().asLocation(); 124 Diag.Report(NoteLoc, NoteID) << (*PI)->getString() 125 << (*PI)->getRanges(); 126 } 127 } 128 } 129 }; 130 } // end anonymous namespace 131 132 //===----------------------------------------------------------------------===// 133 // AnalysisConsumer declaration. 134 //===----------------------------------------------------------------------===// 135 136 namespace { 137 138 class AnalysisConsumer : public AnalysisASTConsumer, 139 public RecursiveASTVisitor<AnalysisConsumer> { 140 enum { 141 AM_None = 0, 142 AM_Syntax = 0x1, 143 AM_Path = 0x2 144 }; 145 typedef unsigned AnalysisMode; 146 147 /// Mode of the analyzes while recursively visiting Decls. 148 AnalysisMode RecVisitorMode; 149 /// Bug Reporter to use while recursively visiting Decls. 150 BugReporter *RecVisitorBR; 151 152 public: 153 ASTContext *Ctx; 154 const Preprocessor &PP; 155 const std::string OutDir; 156 AnalyzerOptionsRef Opts; 157 ArrayRef<std::string> Plugins; 158 CodeInjector *Injector; 159 160 /// \brief Stores the declarations from the local translation unit. 161 /// Note, we pre-compute the local declarations at parse time as an 162 /// optimization to make sure we do not deserialize everything from disk. 163 /// The local declaration to all declarations ratio might be very small when 164 /// working with a PCH file. 165 SetOfDecls LocalTUDecls; 166 167 // Set of PathDiagnosticConsumers. Owned by AnalysisManager. 168 PathDiagnosticConsumers PathConsumers; 169 170 StoreManagerCreator CreateStoreMgr; 171 ConstraintManagerCreator CreateConstraintMgr; 172 173 std::unique_ptr<CheckerManager> checkerMgr; 174 std::unique_ptr<AnalysisManager> Mgr; 175 176 /// Time the analyzes time of each translation unit. 177 static llvm::Timer* TUTotalTimer; 178 179 /// The information about analyzed functions shared throughout the 180 /// translation unit. 181 FunctionSummariesTy FunctionSummaries; 182 183 AnalysisConsumer(const Preprocessor &pp, const std::string &outdir, 184 AnalyzerOptionsRef opts, ArrayRef<std::string> plugins, 185 CodeInjector *injector) 186 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr), PP(pp), 187 OutDir(outdir), Opts(std::move(opts)), Plugins(plugins), 188 Injector(injector) { 189 DigestAnalyzerOptions(); 190 if (Opts->PrintStats) { 191 llvm::EnableStatistics(); 192 TUTotalTimer = new llvm::Timer("Analyzer Total Time"); 193 } 194 } 195 196 ~AnalysisConsumer() override { 197 if (Opts->PrintStats) { 198 delete TUTotalTimer; 199 llvm::PrintStatistics(); 200 } 201 } 202 203 void DigestAnalyzerOptions() { 204 if (Opts->AnalysisDiagOpt != PD_NONE) { 205 // Create the PathDiagnosticConsumer. 206 ClangDiagPathDiagConsumer *clangDiags = 207 new ClangDiagPathDiagConsumer(PP.getDiagnostics()); 208 PathConsumers.push_back(clangDiags); 209 210 if (Opts->AnalysisDiagOpt == PD_TEXT) { 211 clangDiags->enablePaths(); 212 213 } else if (!OutDir.empty()) { 214 switch (Opts->AnalysisDiagOpt) { 215 default: 216 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \ 217 case PD_##NAME: \ 218 CREATEFN(*Opts.get(), PathConsumers, OutDir, PP); \ 219 break; 220 #include "clang/StaticAnalyzer/Core/Analyses.def" 221 } 222 } 223 } 224 225 // Create the analyzer component creators. 226 switch (Opts->AnalysisStoreOpt) { 227 default: 228 llvm_unreachable("Unknown store manager."); 229 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \ 230 case NAME##Model: CreateStoreMgr = CREATEFN; break; 231 #include "clang/StaticAnalyzer/Core/Analyses.def" 232 } 233 234 switch (Opts->AnalysisConstraintsOpt) { 235 default: 236 llvm_unreachable("Unknown constraint manager."); 237 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \ 238 case NAME##Model: CreateConstraintMgr = CREATEFN; break; 239 #include "clang/StaticAnalyzer/Core/Analyses.def" 240 } 241 } 242 243 void DisplayFunction(const Decl *D, AnalysisMode Mode, 244 ExprEngine::InliningModes IMode) { 245 if (!Opts->AnalyzerDisplayProgress) 246 return; 247 248 SourceManager &SM = Mgr->getASTContext().getSourceManager(); 249 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation()); 250 if (Loc.isValid()) { 251 llvm::errs() << "ANALYZE"; 252 253 if (Mode == AM_Syntax) 254 llvm::errs() << " (Syntax)"; 255 else if (Mode == AM_Path) { 256 llvm::errs() << " (Path, "; 257 switch (IMode) { 258 case ExprEngine::Inline_Minimal: 259 llvm::errs() << " Inline_Minimal"; 260 break; 261 case ExprEngine::Inline_Regular: 262 llvm::errs() << " Inline_Regular"; 263 break; 264 } 265 llvm::errs() << ")"; 266 } 267 else 268 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!"); 269 270 llvm::errs() << ": " << Loc.getFilename() << ' ' 271 << getFunctionName(D) << '\n'; 272 } 273 } 274 275 void Initialize(ASTContext &Context) override { 276 Ctx = &Context; 277 checkerMgr = createCheckerManager(*Opts, PP.getLangOpts(), Plugins, 278 PP.getDiagnostics()); 279 280 Mgr = llvm::make_unique<AnalysisManager>( 281 *Ctx, PP.getDiagnostics(), PP.getLangOpts(), PathConsumers, 282 CreateStoreMgr, CreateConstraintMgr, checkerMgr.get(), *Opts, Injector); 283 } 284 285 /// \brief Store the top level decls in the set to be processed later on. 286 /// (Doing this pre-processing avoids deserialization of data from PCH.) 287 bool HandleTopLevelDecl(DeclGroupRef D) override; 288 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override; 289 290 void HandleTranslationUnit(ASTContext &C) override; 291 292 /// \brief Determine which inlining mode should be used when this function is 293 /// analyzed. This allows to redefine the default inlining policies when 294 /// analyzing a given function. 295 ExprEngine::InliningModes 296 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited); 297 298 /// \brief Build the call graph for all the top level decls of this TU and 299 /// use it to define the order in which the functions should be visited. 300 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize); 301 302 /// \brief Run analyzes(syntax or path sensitive) on the given function. 303 /// \param Mode - determines if we are requesting syntax only or path 304 /// sensitive only analysis. 305 /// \param VisitedCallees - The output parameter, which is populated with the 306 /// set of functions which should be considered analyzed after analyzing the 307 /// given root function. 308 void HandleCode(Decl *D, AnalysisMode Mode, 309 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal, 310 SetOfConstDecls *VisitedCallees = nullptr); 311 312 void RunPathSensitiveChecks(Decl *D, 313 ExprEngine::InliningModes IMode, 314 SetOfConstDecls *VisitedCallees); 315 void ActionExprEngine(Decl *D, bool ObjCGCEnabled, 316 ExprEngine::InliningModes IMode, 317 SetOfConstDecls *VisitedCallees); 318 319 /// Visitors for the RecursiveASTVisitor. 320 bool shouldWalkTypesOfTypeLocs() const { return false; } 321 322 /// Handle callbacks for arbitrary Decls. 323 bool VisitDecl(Decl *D) { 324 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode); 325 if (Mode & AM_Syntax) 326 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR); 327 return true; 328 } 329 330 bool VisitFunctionDecl(FunctionDecl *FD) { 331 IdentifierInfo *II = FD->getIdentifier(); 332 if (II && II->getName().startswith("__inline")) 333 return true; 334 335 // We skip function template definitions, as their semantics is 336 // only determined when they are instantiated. 337 if (FD->isThisDeclarationADefinition() && 338 !FD->isDependentContext()) { 339 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 340 HandleCode(FD, RecVisitorMode); 341 } 342 return true; 343 } 344 345 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) { 346 if (MD->isThisDeclarationADefinition()) { 347 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 348 HandleCode(MD, RecVisitorMode); 349 } 350 return true; 351 } 352 353 bool VisitBlockDecl(BlockDecl *BD) { 354 if (BD->hasBody()) { 355 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 356 // Since we skip function template definitions, we should skip blocks 357 // declared in those functions as well. 358 if (!BD->isDependentContext()) { 359 HandleCode(BD, RecVisitorMode); 360 } 361 } 362 return true; 363 } 364 365 void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override { 366 PathConsumers.push_back(Consumer); 367 } 368 369 private: 370 void storeTopLevelDecls(DeclGroupRef DG); 371 std::string getFunctionName(const Decl *D); 372 373 /// \brief Check if we should skip (not analyze) the given function. 374 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode); 375 376 }; 377 } // end anonymous namespace 378 379 380 //===----------------------------------------------------------------------===// 381 // AnalysisConsumer implementation. 382 //===----------------------------------------------------------------------===// 383 llvm::Timer* AnalysisConsumer::TUTotalTimer = nullptr; 384 385 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) { 386 storeTopLevelDecls(DG); 387 return true; 388 } 389 390 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { 391 storeTopLevelDecls(DG); 392 } 393 394 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) { 395 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { 396 397 // Skip ObjCMethodDecl, wait for the objc container to avoid 398 // analyzing twice. 399 if (isa<ObjCMethodDecl>(*I)) 400 continue; 401 402 LocalTUDecls.push_back(*I); 403 } 404 } 405 406 static bool shouldSkipFunction(const Decl *D, 407 const SetOfConstDecls &Visited, 408 const SetOfConstDecls &VisitedAsTopLevel) { 409 if (VisitedAsTopLevel.count(D)) 410 return true; 411 412 // We want to re-analyse the functions as top level in the following cases: 413 // - The 'init' methods should be reanalyzed because 414 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns 415 // 'nil' and unless we analyze the 'init' functions as top level, we will 416 // not catch errors within defensive code. 417 // - We want to reanalyze all ObjC methods as top level to report Retain 418 // Count naming convention errors more aggressively. 419 if (isa<ObjCMethodDecl>(D)) 420 return false; 421 // We also want to reanalyze all C++ copy and move assignment operators to 422 // separately check the two cases where 'this' aliases with the parameter and 423 // where it may not. (cplusplus.SelfAssignmentChecker) 424 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 425 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) 426 return false; 427 } 428 429 // Otherwise, if we visited the function before, do not reanalyze it. 430 return Visited.count(D); 431 } 432 433 ExprEngine::InliningModes 434 AnalysisConsumer::getInliningModeForFunction(const Decl *D, 435 const SetOfConstDecls &Visited) { 436 // We want to reanalyze all ObjC methods as top level to report Retain 437 // Count naming convention errors more aggressively. But we should tune down 438 // inlining when reanalyzing an already inlined function. 439 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) { 440 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D); 441 if (ObjCM->getMethodFamily() != OMF_init) 442 return ExprEngine::Inline_Minimal; 443 } 444 445 return ExprEngine::Inline_Regular; 446 } 447 448 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) { 449 // Build the Call Graph by adding all the top level declarations to the graph. 450 // Note: CallGraph can trigger deserialization of more items from a pch 451 // (though HandleInterestingDecl); triggering additions to LocalTUDecls. 452 // We rely on random access to add the initially processed Decls to CG. 453 CallGraph CG; 454 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 455 CG.addToCallGraph(LocalTUDecls[i]); 456 } 457 458 // Walk over all of the call graph nodes in topological order, so that we 459 // analyze parents before the children. Skip the functions inlined into 460 // the previously processed functions. Use external Visited set to identify 461 // inlined functions. The topological order allows the "do not reanalyze 462 // previously inlined function" performance heuristic to be triggered more 463 // often. 464 SetOfConstDecls Visited; 465 SetOfConstDecls VisitedAsTopLevel; 466 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG); 467 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator 468 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) { 469 NumFunctionTopLevel++; 470 471 CallGraphNode *N = *I; 472 Decl *D = N->getDecl(); 473 474 // Skip the abstract root node. 475 if (!D) 476 continue; 477 478 // Skip the functions which have been processed already or previously 479 // inlined. 480 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel)) 481 continue; 482 483 // Analyze the function. 484 SetOfConstDecls VisitedCallees; 485 486 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited), 487 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees)); 488 489 // Add the visited callees to the global visited set. 490 for (const Decl *Callee : VisitedCallees) 491 // Decls from CallGraph are already canonical. But Decls coming from 492 // CallExprs may be not. We should canonicalize them manually. 493 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee 494 : Callee->getCanonicalDecl()); 495 VisitedAsTopLevel.insert(D); 496 } 497 } 498 499 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 500 // Don't run the actions if an error has occurred with parsing the file. 501 DiagnosticsEngine &Diags = PP.getDiagnostics(); 502 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 503 return; 504 505 // Don't analyze if the user explicitly asked for no checks to be performed 506 // on this file. 507 if (Opts->DisableAllChecks) 508 return; 509 510 { 511 if (TUTotalTimer) TUTotalTimer->startTimer(); 512 513 // Introduce a scope to destroy BR before Mgr. 514 BugReporter BR(*Mgr); 515 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 516 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 517 518 // Run the AST-only checks using the order in which functions are defined. 519 // If inlining is not turned on, use the simplest function order for path 520 // sensitive analyzes as well. 521 RecVisitorMode = AM_Syntax; 522 if (!Mgr->shouldInlineCall()) 523 RecVisitorMode |= AM_Path; 524 RecVisitorBR = &BR; 525 526 // Process all the top level declarations. 527 // 528 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more 529 // entries. Thus we don't use an iterator, but rely on LocalTUDecls 530 // random access. By doing so, we automatically compensate for iterators 531 // possibly being invalidated, although this is a bit slower. 532 const unsigned LocalTUDeclsSize = LocalTUDecls.size(); 533 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 534 TraverseDecl(LocalTUDecls[i]); 535 } 536 537 if (Mgr->shouldInlineCall()) 538 HandleDeclsCallGraph(LocalTUDeclsSize); 539 540 // After all decls handled, run checkers on the entire TranslationUnit. 541 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 542 543 RecVisitorBR = nullptr; 544 } 545 546 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 547 // FIXME: This should be replaced with something that doesn't rely on 548 // side-effects in PathDiagnosticConsumer's destructor. This is required when 549 // used with option -disable-free. 550 Mgr.reset(); 551 552 if (TUTotalTimer) TUTotalTimer->stopTimer(); 553 554 // Count how many basic blocks we have not covered. 555 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks(); 556 if (NumBlocksInAnalyzedFunctions > 0) 557 PercentReachableBlocks = 558 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) / 559 NumBlocksInAnalyzedFunctions; 560 561 } 562 563 std::string AnalysisConsumer::getFunctionName(const Decl *D) { 564 std::string Str; 565 llvm::raw_string_ostream OS(Str); 566 567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 568 OS << FD->getQualifiedNameAsString(); 569 570 // In C++, there are overloads. 571 if (Ctx->getLangOpts().CPlusPlus) { 572 OS << '('; 573 for (const auto &P : FD->parameters()) { 574 if (P != *FD->param_begin()) 575 OS << ", "; 576 OS << P->getType().getAsString(); 577 } 578 OS << ')'; 579 } 580 581 } else if (isa<BlockDecl>(D)) { 582 PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation()); 583 584 if (Loc.isValid()) { 585 OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn() 586 << ')'; 587 } 588 589 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 590 591 // FIXME: copy-pasted from CGDebugInfo.cpp. 592 OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; 593 const DeclContext *DC = OMD->getDeclContext(); 594 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) { 595 OS << OID->getName(); 596 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) { 597 OS << OID->getName(); 598 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) { 599 if (OC->IsClassExtension()) { 600 OS << OC->getClassInterface()->getName(); 601 } else { 602 OS << OC->getIdentifier()->getNameStart() << '(' 603 << OC->getIdentifier()->getNameStart() << ')'; 604 } 605 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) { 606 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' 607 << OCD->getIdentifier()->getNameStart() << ')'; 608 } else if (isa<ObjCProtocolDecl>(DC)) { 609 // We can extract the type of the class from the self pointer. 610 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) { 611 QualType ClassTy = 612 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType(); 613 ClassTy.print(OS, PrintingPolicy(LangOptions())); 614 } 615 } 616 OS << ' ' << OMD->getSelector().getAsString() << ']'; 617 618 } 619 620 return OS.str(); 621 } 622 623 AnalysisConsumer::AnalysisMode 624 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) { 625 if (!Opts->AnalyzeSpecificFunction.empty() && 626 getFunctionName(D) != Opts->AnalyzeSpecificFunction) 627 return AM_None; 628 629 // Unless -analyze-all is specified, treat decls differently depending on 630 // where they came from: 631 // - Main source file: run both path-sensitive and non-path-sensitive checks. 632 // - Header files: run non-path-sensitive checks only. 633 // - System headers: don't run any checks. 634 SourceManager &SM = Ctx->getSourceManager(); 635 const Stmt *Body = D->getBody(); 636 SourceLocation SL = Body ? Body->getLocStart() : D->getLocation(); 637 SL = SM.getExpansionLoc(SL); 638 639 if (!Opts->AnalyzeAll && !SM.isWrittenInMainFile(SL)) { 640 if (SL.isInvalid() || SM.isInSystemHeader(SL)) 641 return AM_None; 642 return Mode & ~AM_Path; 643 } 644 645 return Mode; 646 } 647 648 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode, 649 ExprEngine::InliningModes IMode, 650 SetOfConstDecls *VisitedCallees) { 651 if (!D->hasBody()) 652 return; 653 Mode = getModeForDecl(D, Mode); 654 if (Mode == AM_None) 655 return; 656 657 // Clear the AnalysisManager of old AnalysisDeclContexts. 658 Mgr->ClearContexts(); 659 // Ignore autosynthesized code. 660 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized()) 661 return; 662 663 DisplayFunction(D, Mode, IMode); 664 CFG *DeclCFG = Mgr->getCFG(D); 665 if (DeclCFG) { 666 unsigned CFGSize = DeclCFG->size(); 667 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize; 668 } 669 670 BugReporter BR(*Mgr); 671 672 if (Mode & AM_Syntax) 673 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR); 674 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) { 675 RunPathSensitiveChecks(D, IMode, VisitedCallees); 676 if (IMode != ExprEngine::Inline_Minimal) 677 NumFunctionsAnalyzed++; 678 } 679 } 680 681 //===----------------------------------------------------------------------===// 682 // Path-sensitive checking. 683 //===----------------------------------------------------------------------===// 684 685 void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled, 686 ExprEngine::InliningModes IMode, 687 SetOfConstDecls *VisitedCallees) { 688 // Construct the analysis engine. First check if the CFG is valid. 689 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 690 if (!Mgr->getCFG(D)) 691 return; 692 693 // See if the LiveVariables analysis scales. 694 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>()) 695 return; 696 697 ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode); 698 699 // Set the graph auditor. 700 std::unique_ptr<ExplodedNode::Auditor> Auditor; 701 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) { 702 Auditor = CreateUbiViz(); 703 ExplodedNode::SetAuditor(Auditor.get()); 704 } 705 706 // Execute the worklist algorithm. 707 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D), 708 Mgr->options.getMaxNodesPerTopLevelFunction()); 709 710 // Release the auditor (if any) so that it doesn't monitor the graph 711 // created BugReporter. 712 ExplodedNode::SetAuditor(nullptr); 713 714 // Visualize the exploded graph. 715 if (Mgr->options.visualizeExplodedGraphWithGraphViz) 716 Eng.ViewGraph(Mgr->options.TrimGraph); 717 718 // Display warnings. 719 Eng.getBugReporter().FlushReports(); 720 } 721 722 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D, 723 ExprEngine::InliningModes IMode, 724 SetOfConstDecls *Visited) { 725 726 switch (Mgr->getLangOpts().getGC()) { 727 case LangOptions::NonGC: 728 ActionExprEngine(D, false, IMode, Visited); 729 break; 730 731 case LangOptions::GCOnly: 732 ActionExprEngine(D, true, IMode, Visited); 733 break; 734 735 case LangOptions::HybridGC: 736 ActionExprEngine(D, false, IMode, Visited); 737 ActionExprEngine(D, true, IMode, Visited); 738 break; 739 } 740 } 741 742 //===----------------------------------------------------------------------===// 743 // AnalysisConsumer creation. 744 //===----------------------------------------------------------------------===// 745 746 std::unique_ptr<AnalysisASTConsumer> 747 ento::CreateAnalysisConsumer(CompilerInstance &CI) { 748 // Disable the effects of '-Werror' when using the AnalysisConsumer. 749 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false); 750 751 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts(); 752 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0; 753 754 return llvm::make_unique<AnalysisConsumer>( 755 CI.getPreprocessor(), CI.getFrontendOpts().OutputFile, analyzerOpts, 756 CI.getFrontendOpts().Plugins, 757 hasModelPath ? new ModelInjector(CI) : nullptr); 758 } 759 760 //===----------------------------------------------------------------------===// 761 // Ubigraph Visualization. FIXME: Move to separate file. 762 //===----------------------------------------------------------------------===// 763 764 namespace { 765 766 class UbigraphViz : public ExplodedNode::Auditor { 767 std::unique_ptr<raw_ostream> Out; 768 std::string Filename; 769 unsigned Cntr; 770 771 typedef llvm::DenseMap<void*,unsigned> VMap; 772 VMap M; 773 774 public: 775 UbigraphViz(std::unique_ptr<raw_ostream> Out, StringRef Filename); 776 777 ~UbigraphViz() override; 778 779 void AddEdge(ExplodedNode *Src, ExplodedNode *Dst) override; 780 }; 781 782 } // end anonymous namespace 783 784 static std::unique_ptr<ExplodedNode::Auditor> CreateUbiViz() { 785 SmallString<128> P; 786 int FD; 787 llvm::sys::fs::createTemporaryFile("llvm_ubi", "", FD, P); 788 llvm::errs() << "Writing '" << P << "'.\n"; 789 790 auto Stream = llvm::make_unique<llvm::raw_fd_ostream>(FD, true); 791 792 return llvm::make_unique<UbigraphViz>(std::move(Stream), P); 793 } 794 795 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 796 797 assert (Src != Dst && "Self-edges are not allowed."); 798 799 // Lookup the Src. If it is a new node, it's a root. 800 VMap::iterator SrcI= M.find(Src); 801 unsigned SrcID; 802 803 if (SrcI == M.end()) { 804 M[Src] = SrcID = Cntr++; 805 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 806 } 807 else 808 SrcID = SrcI->second; 809 810 // Lookup the Dst. 811 VMap::iterator DstI= M.find(Dst); 812 unsigned DstID; 813 814 if (DstI == M.end()) { 815 M[Dst] = DstID = Cntr++; 816 *Out << "('vertex', " << DstID << ")\n"; 817 } 818 else { 819 // We have hit DstID before. Change its style to reflect a cache hit. 820 DstID = DstI->second; 821 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 822 } 823 824 // Add the edge. 825 *Out << "('edge', " << SrcID << ", " << DstID 826 << ", ('arrow','true'), ('oriented', 'true'))\n"; 827 } 828 829 UbigraphViz::UbigraphViz(std::unique_ptr<raw_ostream> OutStream, 830 StringRef Filename) 831 : Out(std::move(OutStream)), Filename(Filename), Cntr(0) { 832 833 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 834 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 835 " ('size', '1.5'))\n"; 836 } 837 838 UbigraphViz::~UbigraphViz() { 839 Out.reset(); 840 llvm::errs() << "Running 'ubiviz' program... "; 841 std::string ErrMsg; 842 std::string Ubiviz; 843 if (auto Path = llvm::sys::findProgramByName("ubiviz")) 844 Ubiviz = *Path; 845 const char *args[] = {Ubiviz.c_str(), Filename.c_str(), nullptr}; 846 847 if (llvm::sys::ExecuteAndWait(Ubiviz, &args[0], nullptr, nullptr, 0, 0, 848 &ErrMsg)) { 849 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 850 } 851 852 // Delete the file. 853 llvm::sys::fs::remove(Filename); 854 } 855