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