AnalysisConsumer.cpp revision 6f42b62b6194f53bcbc349f5d17388e1936535d7
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/Diagnostic.h" 31#include "clang/Basic/FileManager.h" 32#include "clang/Basic/SourceManager.h" 33#include "clang/Frontend/AnalyzerOptions.h" 34#include "clang/Lex/Preprocessor.h" 35#include "llvm/Support/raw_ostream.h" 36#include "llvm/Support/Path.h" 37#include "llvm/Support/Program.h" 38#include "llvm/ADT/OwningPtr.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 } 162 163 virtual void HandleTranslationUnit(ASTContext &C); 164 void HandleDeclContext(ASTContext &C, DeclContext *dc); 165 void HandleDeclContextDecl(ASTContext &C, Decl *D); 166 167 void HandleCode(Decl *D); 168}; 169} // end anonymous namespace 170 171//===----------------------------------------------------------------------===// 172// AnalysisConsumer implementation. 173//===----------------------------------------------------------------------===// 174 175void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) { 176 for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end(); 177 I != E; ++I) { 178 HandleDeclContextDecl(C, *I); 179 } 180} 181 182void AnalysisConsumer::HandleDeclContextDecl(ASTContext &C, Decl *D) { 183 { // Handle callbacks for arbitrary decls. 184 BugReporter BR(*Mgr); 185 checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR); 186 } 187 188 switch (D->getKind()) { 189 case Decl::Namespace: { 190 HandleDeclContext(C, cast<NamespaceDecl>(D)); 191 break; 192 } 193 case Decl::CXXConstructor: 194 case Decl::CXXDestructor: 195 case Decl::CXXConversion: 196 case Decl::CXXMethod: 197 case Decl::Function: { 198 FunctionDecl *FD = cast<FunctionDecl>(D); 199 // We skip function template definitions, as their semantics is 200 // only determined when they are instantiated. 201 if (FD->isThisDeclarationADefinition() && 202 !FD->isDependentContext()) { 203 if (!Opts.AnalyzeSpecificFunction.empty() && 204 FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction) 205 break; 206 DisplayFunction(FD); 207 HandleCode(FD); 208 } 209 break; 210 } 211 212 case Decl::ObjCCategoryImpl: 213 case Decl::ObjCImplementation: { 214 ObjCImplDecl *ID = cast<ObjCImplDecl>(D); 215 HandleCode(ID); 216 217 for (ObjCContainerDecl::method_iterator MI = ID->meth_begin(), 218 ME = ID->meth_end(); MI != ME; ++MI) { 219 BugReporter BR(*Mgr); 220 checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR); 221 222 if ((*MI)->isThisDeclarationADefinition()) { 223 if (!Opts.AnalyzeSpecificFunction.empty() && 224 Opts.AnalyzeSpecificFunction != 225 (*MI)->getSelector().getAsString()) 226 continue; 227 DisplayFunction(*MI); 228 HandleCode(*MI); 229 } 230 } 231 break; 232 } 233 234 default: 235 break; 236 } 237} 238 239void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 240 { 241 // Introduce a scope to destroy BR before Mgr. 242 BugReporter BR(*Mgr); 243 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 244 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 245 HandleDeclContext(C, TU); 246 247 // After all decls handled, run checkers on the entire TranslationUnit. 248 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 249 } 250 251 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 252 // FIXME: This should be replaced with something that doesn't rely on 253 // side-effects in PathDiagnosticConsumer's destructor. This is required when 254 // used with option -disable-free. 255 Mgr.reset(NULL); 256} 257 258static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) { 259 if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) 260 WL.push_back(BD); 261 262 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 263 I!=E; ++I) 264 if (DeclContext *DC = dyn_cast<DeclContext>(*I)) 265 FindBlocks(DC, WL); 266} 267 268static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr, 269 Decl *D); 270 271void AnalysisConsumer::HandleCode(Decl *D) { 272 273 // Don't run the actions if an error has occurred with parsing the file. 274 DiagnosticsEngine &Diags = PP.getDiagnostics(); 275 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 276 return; 277 278 // Don't run the actions on declarations in header files unless 279 // otherwise specified. 280 SourceManager &SM = Ctx->getSourceManager(); 281 SourceLocation SL = SM.getExpansionLoc(D->getLocation()); 282 if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL)) 283 return; 284 285 // Clear the AnalysisManager of old AnalysisDeclContexts. 286 Mgr->ClearContexts(); 287 288 // Dispatch on the actions. 289 SmallVector<Decl*, 10> WL; 290 WL.push_back(D); 291 292 if (D->hasBody() && Opts.AnalyzeNestedBlocks) 293 FindBlocks(cast<DeclContext>(D), WL); 294 295 BugReporter BR(*Mgr); 296 for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end(); 297 WI != WE; ++WI) 298 if ((*WI)->hasBody()) { 299 checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR); 300 if (checkerMgr->hasPathSensitiveCheckers()) 301 RunPathSensitiveChecks(*this, *Mgr, *WI); 302 } 303} 304 305//===----------------------------------------------------------------------===// 306// Path-sensitive checking. 307//===----------------------------------------------------------------------===// 308 309static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager &mgr, 310 Decl *D, bool ObjCGCEnabled) { 311 // Construct the analysis engine. First check if the CFG is valid. 312 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 313 if (!mgr.getCFG(D)) 314 return; 315 ExprEngine Eng(mgr, ObjCGCEnabled); 316 317 // Set the graph auditor. 318 OwningPtr<ExplodedNode::Auditor> Auditor; 319 if (mgr.shouldVisualizeUbigraph()) { 320 Auditor.reset(CreateUbiViz()); 321 ExplodedNode::SetAuditor(Auditor.get()); 322 } 323 324 // Execute the worklist algorithm. 325 Eng.ExecuteWorkList(mgr.getAnalysisDeclContextManager().getStackFrame(D, 0), 326 mgr.getMaxNodes()); 327 328 // Release the auditor (if any) so that it doesn't monitor the graph 329 // created BugReporter. 330 ExplodedNode::SetAuditor(0); 331 332 // Visualize the exploded graph. 333 if (mgr.shouldVisualizeGraphviz()) 334 Eng.ViewGraph(mgr.shouldTrimGraph()); 335 336 // Display warnings. 337 Eng.getBugReporter().FlushReports(); 338} 339 340static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr, 341 Decl *D) { 342 343 switch (mgr.getLangOptions().getGC()) { 344 case LangOptions::NonGC: 345 ActionExprEngine(C, mgr, D, false); 346 break; 347 348 case LangOptions::GCOnly: 349 ActionExprEngine(C, mgr, D, true); 350 break; 351 352 case LangOptions::HybridGC: 353 ActionExprEngine(C, mgr, D, false); 354 ActionExprEngine(C, mgr, D, true); 355 break; 356 } 357} 358 359//===----------------------------------------------------------------------===// 360// AnalysisConsumer creation. 361//===----------------------------------------------------------------------===// 362 363ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp, 364 const std::string& outDir, 365 const AnalyzerOptions& opts, 366 ArrayRef<std::string> plugins) { 367 // Disable the effects of '-Werror' when using the AnalysisConsumer. 368 pp.getDiagnostics().setWarningsAsErrors(false); 369 370 return new AnalysisConsumer(pp, outDir, opts, plugins); 371} 372 373//===----------------------------------------------------------------------===// 374// Ubigraph Visualization. FIXME: Move to separate file. 375//===----------------------------------------------------------------------===// 376 377namespace { 378 379class UbigraphViz : public ExplodedNode::Auditor { 380 OwningPtr<raw_ostream> Out; 381 llvm::sys::Path Dir, Filename; 382 unsigned Cntr; 383 384 typedef llvm::DenseMap<void*,unsigned> VMap; 385 VMap M; 386 387public: 388 UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 389 llvm::sys::Path& filename); 390 391 ~UbigraphViz(); 392 393 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst); 394}; 395 396} // end anonymous namespace 397 398static ExplodedNode::Auditor* CreateUbiViz() { 399 std::string ErrMsg; 400 401 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); 402 if (!ErrMsg.empty()) 403 return 0; 404 405 llvm::sys::Path Filename = Dir; 406 Filename.appendComponent("llvm_ubi"); 407 Filename.makeUnique(true,&ErrMsg); 408 409 if (!ErrMsg.empty()) 410 return 0; 411 412 llvm::errs() << "Writing '" << Filename.str() << "'.\n"; 413 414 OwningPtr<llvm::raw_fd_ostream> Stream; 415 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg)); 416 417 if (!ErrMsg.empty()) 418 return 0; 419 420 return new UbigraphViz(Stream.take(), Dir, Filename); 421} 422 423void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 424 425 assert (Src != Dst && "Self-edges are not allowed."); 426 427 // Lookup the Src. If it is a new node, it's a root. 428 VMap::iterator SrcI= M.find(Src); 429 unsigned SrcID; 430 431 if (SrcI == M.end()) { 432 M[Src] = SrcID = Cntr++; 433 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 434 } 435 else 436 SrcID = SrcI->second; 437 438 // Lookup the Dst. 439 VMap::iterator DstI= M.find(Dst); 440 unsigned DstID; 441 442 if (DstI == M.end()) { 443 M[Dst] = DstID = Cntr++; 444 *Out << "('vertex', " << DstID << ")\n"; 445 } 446 else { 447 // We have hit DstID before. Change its style to reflect a cache hit. 448 DstID = DstI->second; 449 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 450 } 451 452 // Add the edge. 453 *Out << "('edge', " << SrcID << ", " << DstID 454 << ", ('arrow','true'), ('oriented', 'true'))\n"; 455} 456 457UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 458 llvm::sys::Path& filename) 459 : Out(out), Dir(dir), Filename(filename), Cntr(0) { 460 461 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 462 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 463 " ('size', '1.5'))\n"; 464} 465 466UbigraphViz::~UbigraphViz() { 467 Out.reset(0); 468 llvm::errs() << "Running 'ubiviz' program... "; 469 std::string ErrMsg; 470 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz"); 471 std::vector<const char*> args; 472 args.push_back(Ubiviz.c_str()); 473 args.push_back(Filename.c_str()); 474 args.push_back(0); 475 476 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { 477 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 478 } 479 480 // Delete the directory. 481 Dir.eraseFromDisk(true); 482} 483