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