AnalysisConsumer.cpp revision 8235f9c9c8b3d1737d1c6bd57f7ba3f616b92392
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 "AnalysisConsumer.h" 15#include "clang/AST/ASTConsumer.h" 16#include "clang/AST/Decl.h" 17#include "clang/AST/DeclCXX.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/ParentMap.h" 20#include "clang/Analysis/CFG.h" 21#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h" 22#include "clang/StaticAnalyzer/Core/CheckerManager.h" 23#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h" 24#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 25#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 26#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 27#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 28#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" 29 30#include "clang/Basic/FileManager.h" 31#include "clang/Basic/SourceManager.h" 32#include "clang/Frontend/AnalyzerOptions.h" 33#include "clang/Lex/Preprocessor.h" 34#include "llvm/Support/raw_ostream.h" 35#include "llvm/Support/Path.h" 36#include "llvm/Support/Program.h" 37#include "llvm/ADT/OwningPtr.h" 38#include "llvm/ADT/Statistic.h" 39 40using namespace clang; 41using namespace ento; 42 43static ExplodedNode::Auditor* CreateUbiViz(); 44 45//===----------------------------------------------------------------------===// 46// Special PathDiagnosticConsumers. 47//===----------------------------------------------------------------------===// 48 49static PathDiagnosticConsumer* 50createPlistHTMLDiagnosticConsumer(const std::string& prefix, 51 const Preprocessor &PP) { 52 PathDiagnosticConsumer *PD = 53 createHTMLDiagnosticConsumer(llvm::sys::path::parent_path(prefix), PP); 54 return createPlistDiagnosticConsumer(prefix, PP, PD); 55} 56 57//===----------------------------------------------------------------------===// 58// AnalysisConsumer declaration. 59//===----------------------------------------------------------------------===// 60 61namespace { 62 63class AnalysisConsumer : public ASTConsumer { 64public: 65 ASTContext *Ctx; 66 const Preprocessor &PP; 67 const std::string OutDir; 68 AnalyzerOptions Opts; 69 ArrayRef<std::string> Plugins; 70 71 // PD is owned by AnalysisManager. 72 PathDiagnosticConsumer *PD; 73 74 StoreManagerCreator CreateStoreMgr; 75 ConstraintManagerCreator CreateConstraintMgr; 76 77 OwningPtr<CheckerManager> checkerMgr; 78 OwningPtr<AnalysisManager> Mgr; 79 80 AnalysisConsumer(const Preprocessor& pp, 81 const std::string& outdir, 82 const AnalyzerOptions& opts, 83 ArrayRef<std::string> plugins) 84 : Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins), PD(0) { 85 DigestAnalyzerOptions(); 86 } 87 88 void DigestAnalyzerOptions() { 89 // Create the PathDiagnosticConsumer. 90 if (!OutDir.empty()) { 91 switch (Opts.AnalysisDiagOpt) { 92 default: 93#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \ 94 case PD_##NAME: PD = CREATEFN(OutDir, PP); break; 95#include "clang/Frontend/Analyses.def" 96 } 97 } else if (Opts.AnalysisDiagOpt == PD_TEXT) { 98 // Create the text client even without a specified output file since 99 // it just uses diagnostic notes. 100 PD = createTextPathDiagnosticConsumer("", PP); 101 } 102 103 // Create the analyzer component creators. 104 switch (Opts.AnalysisStoreOpt) { 105 default: 106 llvm_unreachable("Unknown store manager."); 107#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \ 108 case NAME##Model: CreateStoreMgr = CREATEFN; break; 109#include "clang/Frontend/Analyses.def" 110 } 111 112 switch (Opts.AnalysisConstraintsOpt) { 113 default: 114 llvm_unreachable("Unknown store manager."); 115#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \ 116 case NAME##Model: CreateConstraintMgr = CREATEFN; break; 117#include "clang/Frontend/Analyses.def" 118 } 119 } 120 121 void DisplayFunction(const Decl *D) { 122 if (!Opts.AnalyzerDisplayProgress) 123 return; 124 125 SourceManager &SM = Mgr->getASTContext().getSourceManager(); 126 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation()); 127 if (Loc.isValid()) { 128 llvm::errs() << "ANALYZE: " << Loc.getFilename(); 129 130 if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { 131 const NamedDecl *ND = cast<NamedDecl>(D); 132 llvm::errs() << ' ' << *ND << '\n'; 133 } 134 else if (isa<BlockDecl>(D)) { 135 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:" 136 << Loc.getColumn() << '\n'; 137 } 138 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 139 Selector S = MD->getSelector(); 140 llvm::errs() << ' ' << S.getAsString(); 141 } 142 } 143 } 144 145 virtual void Initialize(ASTContext &Context) { 146 Ctx = &Context; 147 checkerMgr.reset(createCheckerManager(Opts, PP.getLangOptions(), Plugins, 148 PP.getDiagnostics())); 149 Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(), 150 PP.getLangOptions(), PD, 151 CreateStoreMgr, CreateConstraintMgr, 152 checkerMgr.get(), 153 /* Indexer */ 0, 154 Opts.MaxNodes, Opts.MaxLoop, 155 Opts.VisualizeEGDot, Opts.VisualizeEGUbi, 156 Opts.AnalysisPurgeOpt, Opts.EagerlyAssume, 157 Opts.TrimGraph, Opts.InlineCall, 158 Opts.UnoptimizedCFG, Opts.CFGAddImplicitDtors, 159 Opts.CFGAddInitializers, 160 Opts.EagerlyTrimEGraph, 161 Opts.InlineMaxStackDepth, 162 Opts.InlineMaxFunctionSize)); 163 if (Opts.PrintStats) 164 llvm::EnableStatistics(); 165 } 166 167 virtual void HandleTranslationUnit(ASTContext &C); 168 void HandleDeclContext(ASTContext &C, DeclContext *dc); 169 void HandleDeclContextDecl(ASTContext &C, Decl *D); 170 171 void HandleCode(Decl *D); 172}; 173} // end anonymous namespace 174 175//===----------------------------------------------------------------------===// 176// AnalysisConsumer implementation. 177//===----------------------------------------------------------------------===// 178 179void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) { 180 for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end(); 181 I != E; ++I) { 182 HandleDeclContextDecl(C, *I); 183 } 184} 185 186void AnalysisConsumer::HandleDeclContextDecl(ASTContext &C, Decl *D) { 187 { // Handle callbacks for arbitrary decls. 188 BugReporter BR(*Mgr); 189 checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR); 190 } 191 192 switch (D->getKind()) { 193 case Decl::Namespace: { 194 HandleDeclContext(C, cast<NamespaceDecl>(D)); 195 break; 196 } 197 case Decl::CXXConstructor: 198 case Decl::CXXDestructor: 199 case Decl::CXXConversion: 200 case Decl::CXXMethod: 201 case Decl::Function: { 202 FunctionDecl *FD = cast<FunctionDecl>(D); 203 // We skip function template definitions, as their semantics is 204 // only determined when they are instantiated. 205 if (FD->isThisDeclarationADefinition() && 206 !FD->isDependentContext()) { 207 if (!Opts.AnalyzeSpecificFunction.empty() && 208 FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction) 209 break; 210 DisplayFunction(FD); 211 HandleCode(FD); 212 } 213 break; 214 } 215 216 case Decl::ObjCCategoryImpl: 217 case Decl::ObjCImplementation: { 218 ObjCImplDecl *ID = cast<ObjCImplDecl>(D); 219 HandleCode(ID); 220 221 for (ObjCContainerDecl::method_iterator MI = ID->meth_begin(), 222 ME = ID->meth_end(); MI != ME; ++MI) { 223 BugReporter BR(*Mgr); 224 checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR); 225 226 if ((*MI)->isThisDeclarationADefinition()) { 227 if (!Opts.AnalyzeSpecificFunction.empty() && 228 Opts.AnalyzeSpecificFunction != 229 (*MI)->getSelector().getAsString()) 230 continue; 231 DisplayFunction(*MI); 232 HandleCode(*MI); 233 } 234 } 235 break; 236 } 237 238 default: 239 break; 240 } 241} 242 243void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 244 { 245 // Introduce a scope to destroy BR before Mgr. 246 BugReporter BR(*Mgr); 247 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 248 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 249 HandleDeclContext(C, TU); 250 251 // After all decls handled, run checkers on the entire TranslationUnit. 252 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 253 } 254 255 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 256 // FIXME: This should be replaced with something that doesn't rely on 257 // side-effects in PathDiagnosticConsumer's destructor. This is required when 258 // used with option -disable-free. 259 Mgr.reset(NULL); 260} 261 262static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) { 263 if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) 264 WL.push_back(BD); 265 266 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 267 I!=E; ++I) 268 if (DeclContext *DC = dyn_cast<DeclContext>(*I)) 269 FindBlocks(DC, WL); 270} 271 272static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr, 273 Decl *D); 274 275void AnalysisConsumer::HandleCode(Decl *D) { 276 277 // Don't run the actions if an error has occurred with parsing the file. 278 DiagnosticsEngine &Diags = PP.getDiagnostics(); 279 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 280 return; 281 282 // Don't run the actions on declarations in header files unless 283 // otherwise specified. 284 SourceManager &SM = Ctx->getSourceManager(); 285 SourceLocation SL = SM.getExpansionLoc(D->getLocation()); 286 if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL)) 287 return; 288 289 // Clear the AnalysisManager of old AnalysisDeclContexts. 290 Mgr->ClearContexts(); 291 292 // Dispatch on the actions. 293 SmallVector<Decl*, 10> WL; 294 WL.push_back(D); 295 296 if (D->hasBody() && Opts.AnalyzeNestedBlocks) 297 FindBlocks(cast<DeclContext>(D), WL); 298 299 BugReporter BR(*Mgr); 300 for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end(); 301 WI != WE; ++WI) 302 if ((*WI)->hasBody()) { 303 checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR); 304 if (checkerMgr->hasPathSensitiveCheckers()) 305 RunPathSensitiveChecks(*this, *Mgr, *WI); 306 } 307} 308 309//===----------------------------------------------------------------------===// 310// Path-sensitive checking. 311//===----------------------------------------------------------------------===// 312 313static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager &mgr, 314 Decl *D, bool ObjCGCEnabled) { 315 // Construct the analysis engine. First check if the CFG is valid. 316 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 317 if (!mgr.getCFG(D)) 318 return; 319 ExprEngine Eng(mgr, ObjCGCEnabled); 320 321 // Set the graph auditor. 322 OwningPtr<ExplodedNode::Auditor> Auditor; 323 if (mgr.shouldVisualizeUbigraph()) { 324 Auditor.reset(CreateUbiViz()); 325 ExplodedNode::SetAuditor(Auditor.get()); 326 } 327 328 // Execute the worklist algorithm. 329 Eng.ExecuteWorkList(mgr.getAnalysisDeclContextManager().getStackFrame(D, 0), 330 mgr.getMaxNodes()); 331 332 // Release the auditor (if any) so that it doesn't monitor the graph 333 // created BugReporter. 334 ExplodedNode::SetAuditor(0); 335 336 // Visualize the exploded graph. 337 if (mgr.shouldVisualizeGraphviz()) 338 Eng.ViewGraph(mgr.shouldTrimGraph()); 339 340 // Display warnings. 341 Eng.getBugReporter().FlushReports(); 342} 343 344static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr, 345 Decl *D) { 346 347 switch (mgr.getLangOptions().getGC()) { 348 case LangOptions::NonGC: 349 ActionExprEngine(C, mgr, D, false); 350 break; 351 352 case LangOptions::GCOnly: 353 ActionExprEngine(C, mgr, D, true); 354 break; 355 356 case LangOptions::HybridGC: 357 ActionExprEngine(C, mgr, D, false); 358 ActionExprEngine(C, mgr, D, true); 359 break; 360 } 361} 362 363//===----------------------------------------------------------------------===// 364// AnalysisConsumer creation. 365//===----------------------------------------------------------------------===// 366 367ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp, 368 const std::string& outDir, 369 const AnalyzerOptions& opts, 370 ArrayRef<std::string> plugins) { 371 // Disable the effects of '-Werror' when using the AnalysisConsumer. 372 pp.getDiagnostics().setWarningsAsErrors(false); 373 374 return new AnalysisConsumer(pp, outDir, opts, plugins); 375} 376 377//===----------------------------------------------------------------------===// 378// Ubigraph Visualization. FIXME: Move to separate file. 379//===----------------------------------------------------------------------===// 380 381namespace { 382 383class UbigraphViz : public ExplodedNode::Auditor { 384 OwningPtr<raw_ostream> Out; 385 llvm::sys::Path Dir, Filename; 386 unsigned Cntr; 387 388 typedef llvm::DenseMap<void*,unsigned> VMap; 389 VMap M; 390 391public: 392 UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 393 llvm::sys::Path& filename); 394 395 ~UbigraphViz(); 396 397 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst); 398}; 399 400} // end anonymous namespace 401 402static ExplodedNode::Auditor* CreateUbiViz() { 403 std::string ErrMsg; 404 405 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); 406 if (!ErrMsg.empty()) 407 return 0; 408 409 llvm::sys::Path Filename = Dir; 410 Filename.appendComponent("llvm_ubi"); 411 Filename.makeUnique(true,&ErrMsg); 412 413 if (!ErrMsg.empty()) 414 return 0; 415 416 llvm::errs() << "Writing '" << Filename.str() << "'.\n"; 417 418 OwningPtr<llvm::raw_fd_ostream> Stream; 419 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg)); 420 421 if (!ErrMsg.empty()) 422 return 0; 423 424 return new UbigraphViz(Stream.take(), Dir, Filename); 425} 426 427void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 428 429 assert (Src != Dst && "Self-edges are not allowed."); 430 431 // Lookup the Src. If it is a new node, it's a root. 432 VMap::iterator SrcI= M.find(Src); 433 unsigned SrcID; 434 435 if (SrcI == M.end()) { 436 M[Src] = SrcID = Cntr++; 437 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 438 } 439 else 440 SrcID = SrcI->second; 441 442 // Lookup the Dst. 443 VMap::iterator DstI= M.find(Dst); 444 unsigned DstID; 445 446 if (DstI == M.end()) { 447 M[Dst] = DstID = Cntr++; 448 *Out << "('vertex', " << DstID << ")\n"; 449 } 450 else { 451 // We have hit DstID before. Change its style to reflect a cache hit. 452 DstID = DstI->second; 453 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 454 } 455 456 // Add the edge. 457 *Out << "('edge', " << SrcID << ", " << DstID 458 << ", ('arrow','true'), ('oriented', 'true'))\n"; 459} 460 461UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 462 llvm::sys::Path& filename) 463 : Out(out), Dir(dir), Filename(filename), Cntr(0) { 464 465 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 466 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 467 " ('size', '1.5'))\n"; 468} 469 470UbigraphViz::~UbigraphViz() { 471 Out.reset(0); 472 llvm::errs() << "Running 'ubiviz' program... "; 473 std::string ErrMsg; 474 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz"); 475 std::vector<const char*> args; 476 args.push_back(Ubiviz.c_str()); 477 args.push_back(Filename.c_str()); 478 args.push_back(0); 479 480 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { 481 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 482 } 483 484 // Delete the directory. 485 Dir.eraseFromDisk(true); 486} 487