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