AnalysisConsumer.cpp revision 2e471a3e476396be1ddca4ab8b9df721bcfc9437
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.getLangOptions(), 179 PP.getDiagnostics())); 180 Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(), 181 PP.getLangOptions(), PD, 182 CreateStoreMgr, CreateConstraintMgr, 183 checkerMgr.get(), 184 /* Indexer */ 0, 185 Opts.MaxNodes, Opts.MaxLoop, 186 Opts.VisualizeEGDot, Opts.VisualizeEGUbi, 187 Opts.PurgeDead, Opts.EagerlyAssume, 188 Opts.TrimGraph, Opts.InlineCall, 189 Opts.UnoptimizedCFG, Opts.CFGAddImplicitDtors, 190 Opts.CFGAddInitializers, 191 Opts.EagerlyTrimEGraph)); 192 } 193 194 virtual void HandleTranslationUnit(ASTContext &C); 195 void HandleDeclContext(ASTContext &C, DeclContext *dc); 196 197 void HandleCode(Decl *D, Actions& actions); 198}; 199} // end anonymous namespace 200 201//===----------------------------------------------------------------------===// 202// AnalysisConsumer implementation. 203//===----------------------------------------------------------------------===// 204 205void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) { 206 BugReporter BR(*Mgr); 207 for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end(); 208 I != E; ++I) { 209 Decl *D = *I; 210 checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR); 211 212 switch (D->getKind()) { 213 case Decl::Namespace: { 214 HandleDeclContext(C, cast<NamespaceDecl>(D)); 215 break; 216 } 217 case Decl::CXXConstructor: 218 case Decl::CXXDestructor: 219 case Decl::CXXConversion: 220 case Decl::CXXMethod: 221 case Decl::Function: { 222 FunctionDecl* FD = cast<FunctionDecl>(D); 223 // We skip function template definitions, as their semantics is 224 // only determined when they are instantiated. 225 if (FD->isThisDeclarationADefinition() && 226 !FD->isDependentContext()) { 227 if (!Opts.AnalyzeSpecificFunction.empty() && 228 FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction) 229 break; 230 DisplayFunction(FD); 231 HandleCode(FD, FunctionActions); 232 } 233 break; 234 } 235 236 case Decl::ObjCImplementation: { 237 ObjCImplementationDecl* ID = cast<ObjCImplementationDecl>(*I); 238 HandleCode(ID, ObjCImplementationActions); 239 240 for (ObjCImplementationDecl::method_iterator MI = ID->meth_begin(), 241 ME = ID->meth_end(); MI != ME; ++MI) { 242 if ((*MI)->isThisDeclarationADefinition()) { 243 if (!Opts.AnalyzeSpecificFunction.empty() && 244 Opts.AnalyzeSpecificFunction != (*MI)->getSelector().getAsString()) 245 break; 246 DisplayFunction(*MI); 247 HandleCode(*MI, ObjCMethodActions); 248 } 249 } 250 break; 251 } 252 253 default: 254 break; 255 } 256 } 257} 258 259void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 260 BugReporter BR(*Mgr); 261 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 262 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 263 HandleDeclContext(C, TU); 264 265 // Explicitly destroy the PathDiagnosticClient. This will flush its output. 266 // FIXME: This should be replaced with something that doesn't rely on 267 // side-effects in PathDiagnosticClient's destructor. This is required when 268 // used with option -disable-free. 269 Mgr.reset(NULL); 270} 271 272static void FindBlocks(DeclContext *D, llvm::SmallVectorImpl<Decl*> &WL) { 273 if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) 274 WL.push_back(BD); 275 276 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 277 I!=E; ++I) 278 if (DeclContext *DC = dyn_cast<DeclContext>(*I)) 279 FindBlocks(DC, WL); 280} 281 282void AnalysisConsumer::HandleCode(Decl *D, Actions& actions) { 283 284 // Don't run the actions if an error has occured with parsing the file. 285 Diagnostic &Diags = PP.getDiagnostics(); 286 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 287 return; 288 289 // Don't run the actions on declarations in header files unless 290 // otherwise specified. 291 SourceManager &SM = Ctx->getSourceManager(); 292 SourceLocation SL = SM.getInstantiationLoc(D->getLocation()); 293 if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL)) 294 return; 295 296 // Clear the AnalysisManager of old AnalysisContexts. 297 Mgr->ClearContexts(); 298 299 // Dispatch on the actions. 300 llvm::SmallVector<Decl*, 10> WL; 301 WL.push_back(D); 302 303 if (D->hasBody() && Opts.AnalyzeNestedBlocks) 304 FindBlocks(cast<DeclContext>(D), WL); 305 306 BugReporter BR(*Mgr); 307 for (llvm::SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end(); 308 WI != WE; ++WI) 309 if ((*WI)->hasBody()) 310 checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR); 311 312 for (Actions::iterator I = actions.begin(), E = actions.end(); I != E; ++I) 313 for (llvm::SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end(); 314 WI != WE; ++WI) 315 (*I)(*this, *Mgr, *WI); 316} 317 318//===----------------------------------------------------------------------===// 319// Analyses 320//===----------------------------------------------------------------------===// 321 322static void ActionWarnUninitVals(AnalysisConsumer &C, AnalysisManager& mgr, 323 Decl *D) { 324 if (CFG* c = mgr.getCFG(D)) { 325 CheckUninitializedValues(*c, mgr.getASTContext(), mgr.getDiagnostic()); 326 } 327} 328 329 330static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager& mgr, 331 Decl *D, 332 TransferFuncs* tf) { 333 334 llvm::OwningPtr<TransferFuncs> TF(tf); 335 336 // Construct the analysis engine. We first query for the LiveVariables 337 // information to see if the CFG is valid. 338 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 339 if (!mgr.getLiveVariables(D)) 340 return; 341 ExprEngine Eng(mgr, TF.take()); 342 343 if (C.Opts.EnableExperimentalInternalChecks) 344 RegisterExperimentalInternalChecks(Eng); 345 346 RegisterNSErrorChecks(Eng.getBugReporter(), Eng, *D); 347 348 if (C.Opts.EnableExperimentalChecks) 349 RegisterExperimentalChecks(Eng); 350 351 if (C.Opts.BufferOverflows) 352 RegisterArrayBoundCheckerV2(Eng); 353 354 // Enable AnalyzerStatsChecker if it was given as an argument 355 if (C.Opts.AnalyzerStats) 356 RegisterAnalyzerStatsChecker(Eng); 357 358 // Set the graph auditor. 359 llvm::OwningPtr<ExplodedNode::Auditor> Auditor; 360 if (mgr.shouldVisualizeUbigraph()) { 361 Auditor.reset(CreateUbiViz()); 362 ExplodedNode::SetAuditor(Auditor.get()); 363 } 364 365 // Execute the worklist algorithm. 366 Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes()); 367 368 // Release the auditor (if any) so that it doesn't monitor the graph 369 // created BugReporter. 370 ExplodedNode::SetAuditor(0); 371 372 // Visualize the exploded graph. 373 if (mgr.shouldVisualizeGraphviz()) 374 Eng.ViewGraph(mgr.shouldTrimGraph()); 375 376 // Display warnings. 377 Eng.getBugReporter().FlushReports(); 378} 379 380static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr, 381 Decl *D, bool GCEnabled) { 382 383 TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(), 384 GCEnabled, 385 mgr.getLangOptions()); 386 387 ActionExprEngine(C, mgr, D, TF); 388} 389 390static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr, 391 Decl *D) { 392 393 switch (mgr.getLangOptions().getGCMode()) { 394 default: 395 assert (false && "Invalid GC mode."); 396 case LangOptions::NonGC: 397 ActionObjCMemCheckerAux(C, mgr, D, false); 398 break; 399 400 case LangOptions::GCOnly: 401 ActionObjCMemCheckerAux(C, mgr, D, true); 402 break; 403 404 case LangOptions::HybridGC: 405 ActionObjCMemCheckerAux(C, mgr, D, false); 406 ActionObjCMemCheckerAux(C, mgr, D, true); 407 break; 408 } 409} 410 411//===----------------------------------------------------------------------===// 412// AnalysisConsumer creation. 413//===----------------------------------------------------------------------===// 414 415ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp, 416 const std::string& OutDir, 417 const AnalyzerOptions& Opts) { 418 llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(pp, OutDir, Opts)); 419 420 for (unsigned i = 0; i < Opts.AnalysisList.size(); ++i) 421 switch (Opts.AnalysisList[i]) { 422#define ANALYSIS(NAME, CMD, DESC, SCOPE)\ 423 case NAME:\ 424 C->add ## SCOPE ## Action(&Action ## NAME);\ 425 break; 426#include "clang/Frontend/Analyses.def" 427 default: break; 428 } 429 430 // Last, disable the effects of '-Werror' when using the AnalysisConsumer. 431 pp.getDiagnostics().setWarningsAsErrors(false); 432 433 return C.take(); 434} 435 436//===----------------------------------------------------------------------===// 437// Ubigraph Visualization. FIXME: Move to separate file. 438//===----------------------------------------------------------------------===// 439 440namespace { 441 442class UbigraphViz : public ExplodedNode::Auditor { 443 llvm::OwningPtr<llvm::raw_ostream> Out; 444 llvm::sys::Path Dir, Filename; 445 unsigned Cntr; 446 447 typedef llvm::DenseMap<void*,unsigned> VMap; 448 VMap M; 449 450public: 451 UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir, 452 llvm::sys::Path& filename); 453 454 ~UbigraphViz(); 455 456 virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst); 457}; 458 459} // end anonymous namespace 460 461static ExplodedNode::Auditor* CreateUbiViz() { 462 std::string ErrMsg; 463 464 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); 465 if (!ErrMsg.empty()) 466 return 0; 467 468 llvm::sys::Path Filename = Dir; 469 Filename.appendComponent("llvm_ubi"); 470 Filename.makeUnique(true,&ErrMsg); 471 472 if (!ErrMsg.empty()) 473 return 0; 474 475 llvm::errs() << "Writing '" << Filename.str() << "'.\n"; 476 477 llvm::OwningPtr<llvm::raw_fd_ostream> Stream; 478 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg)); 479 480 if (!ErrMsg.empty()) 481 return 0; 482 483 return new UbigraphViz(Stream.take(), Dir, Filename); 484} 485 486void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) { 487 488 assert (Src != Dst && "Self-edges are not allowed."); 489 490 // Lookup the Src. If it is a new node, it's a root. 491 VMap::iterator SrcI= M.find(Src); 492 unsigned SrcID; 493 494 if (SrcI == M.end()) { 495 M[Src] = SrcID = Cntr++; 496 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 497 } 498 else 499 SrcID = SrcI->second; 500 501 // Lookup the Dst. 502 VMap::iterator DstI= M.find(Dst); 503 unsigned DstID; 504 505 if (DstI == M.end()) { 506 M[Dst] = DstID = Cntr++; 507 *Out << "('vertex', " << DstID << ")\n"; 508 } 509 else { 510 // We have hit DstID before. Change its style to reflect a cache hit. 511 DstID = DstI->second; 512 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 513 } 514 515 // Add the edge. 516 *Out << "('edge', " << SrcID << ", " << DstID 517 << ", ('arrow','true'), ('oriented', 'true'))\n"; 518} 519 520UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir, 521 llvm::sys::Path& filename) 522 : Out(out), Dir(dir), Filename(filename), Cntr(0) { 523 524 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 525 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 526 " ('size', '1.5'))\n"; 527} 528 529UbigraphViz::~UbigraphViz() { 530 Out.reset(0); 531 llvm::errs() << "Running 'ubiviz' program... "; 532 std::string ErrMsg; 533 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz"); 534 std::vector<const char*> args; 535 args.push_back(Ubiviz.c_str()); 536 args.push_back(Filename.c_str()); 537 args.push_back(0); 538 539 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { 540 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 541 } 542 543 // Delete the directory. 544 Dir.eraseFromDisk(true); 545} 546