AnalysisConsumer.cpp revision fee618af5dd7dee2caaa7347b372eb3dc5fdeffc
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/PathSensitive/TransferFuncs.h" 29#include "clang/StaticAnalyzer/Core/PathDiagnosticClients.h" 30 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 PathDiagnosticClients. 47//===----------------------------------------------------------------------===// 48 49static PathDiagnosticClient* 50createPlistHTMLDiagnosticClient(const std::string& prefix, 51 const Preprocessor &PP) { 52 PathDiagnosticClient *PD = 53 createHTMLDiagnosticClient(llvm::sys::path::parent_path(prefix), PP); 54 return createPlistDiagnosticClient(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 PathDiagnosticClient *PD; 73 74 StoreManagerCreator CreateStoreMgr; 75 ConstraintManagerCreator CreateConstraintMgr; 76 77 llvm::OwningPtr<CheckerManager> checkerMgr; 78 llvm::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 PathDiagnosticClient. 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 = createTextPathDiagnosticClient("", PP); 101 } 102 103 // Create the analyzer component creators. 104 switch (Opts.AnalysisStoreOpt) { 105 default: 106 assert(0 && "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 assert(0 && "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.PurgeDead, 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 break; 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 BugReporter BR(*Mgr); 241 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 242 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 243 HandleDeclContext(C, TU); 244 245 // After all decls handled, run checkers on the entire TranslationUnit. 246 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 247 248 // Explicitly destroy the PathDiagnosticClient. This will flush its output. 249 // FIXME: This should be replaced with something that doesn't rely on 250 // side-effects in PathDiagnosticClient's destructor. This is required when 251 // used with option -disable-free. 252 Mgr.reset(NULL); 253} 254 255static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) { 256 if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) 257 WL.push_back(BD); 258 259 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 260 I!=E; ++I) 261 if (DeclContext *DC = dyn_cast<DeclContext>(*I)) 262 FindBlocks(DC, WL); 263} 264 265static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr, 266 Decl *D); 267 268void AnalysisConsumer::HandleCode(Decl *D) { 269 270 // Don't run the actions if an error has occurred with parsing the file. 271 Diagnostic &Diags = PP.getDiagnostics(); 272 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 273 return; 274 275 // Don't run the actions on declarations in header files unless 276 // otherwise specified. 277 SourceManager &SM = Ctx->getSourceManager(); 278 SourceLocation SL = SM.getExpansionLoc(D->getLocation()); 279 if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL)) 280 return; 281 282 // Clear the AnalysisManager of old AnalysisContexts. 283 Mgr->ClearContexts(); 284 285 // Dispatch on the actions. 286 SmallVector<Decl*, 10> WL; 287 WL.push_back(D); 288 289 if (D->hasBody() && Opts.AnalyzeNestedBlocks) 290 FindBlocks(cast<DeclContext>(D), WL); 291 292 BugReporter BR(*Mgr); 293 for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end(); 294 WI != WE; ++WI) 295 if ((*WI)->hasBody()) { 296 checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR); 297 if (checkerMgr->hasPathSensitiveCheckers()) 298 ActionObjCMemChecker(*this, *Mgr, *WI); 299 } 300} 301 302//===----------------------------------------------------------------------===// 303// Path-sensitive checking. 304//===----------------------------------------------------------------------===// 305 306static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager& mgr, 307 Decl *D, 308 TransferFuncs* tf) { 309 310 llvm::OwningPtr<TransferFuncs> TF(tf); 311 312 // Construct the analysis engine. We first query for the LiveVariables 313 // information to see if the CFG is valid. 314 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 315 if (!mgr.getLiveVariables(D)) 316 return; 317 ExprEngine Eng(mgr, TF.take()); 318 319 // Set the graph auditor. 320 llvm::OwningPtr<ExplodedNode::Auditor> Auditor; 321 if (mgr.shouldVisualizeUbigraph()) { 322 Auditor.reset(CreateUbiViz()); 323 ExplodedNode::SetAuditor(Auditor.get()); 324 } 325 326 // Execute the worklist algorithm. 327 Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes()); 328 329 // Release the auditor (if any) so that it doesn't monitor the graph 330 // created BugReporter. 331 ExplodedNode::SetAuditor(0); 332 333 // Visualize the exploded graph. 334 if (mgr.shouldVisualizeGraphviz()) 335 Eng.ViewGraph(mgr.shouldTrimGraph()); 336 337 // Display warnings. 338 Eng.getBugReporter().FlushReports(); 339} 340 341static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr, 342 Decl *D, bool GCEnabled) { 343 344 TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(), 345 GCEnabled, 346 mgr.getLangOptions()); 347 348 ActionExprEngine(C, mgr, D, TF); 349} 350 351static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr, 352 Decl *D) { 353 354 switch (mgr.getLangOptions().getGCMode()) { 355 default: 356 assert (false && "Invalid GC mode."); 357 case LangOptions::NonGC: 358 ActionObjCMemCheckerAux(C, mgr, D, false); 359 break; 360 361 case LangOptions::GCOnly: 362 ActionObjCMemCheckerAux(C, mgr, D, true); 363 break; 364 365 case LangOptions::HybridGC: 366 ActionObjCMemCheckerAux(C, mgr, D, false); 367 ActionObjCMemCheckerAux(C, mgr, D, true); 368 break; 369 } 370} 371 372//===----------------------------------------------------------------------===// 373// AnalysisConsumer creation. 374//===----------------------------------------------------------------------===// 375 376ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp, 377 const std::string& outDir, 378 const AnalyzerOptions& opts, 379 ArrayRef<std::string> plugins) { 380 // Disable the effects of '-Werror' when using the AnalysisConsumer. 381 pp.getDiagnostics().setWarningsAsErrors(false); 382 383 return new AnalysisConsumer(pp, outDir, opts, plugins); 384} 385 386//===----------------------------------------------------------------------===// 387// Ubigraph Visualization. FIXME: Move to separate file. 388//===----------------------------------------------------------------------===// 389 390namespace { 391 392class UbigraphViz : public ExplodedNode::Auditor { 393 llvm::OwningPtr<raw_ostream> Out; 394 llvm::sys::Path Dir, Filename; 395 unsigned Cntr; 396 397 typedef llvm::DenseMap<void*,unsigned> VMap; 398 VMap M; 399 400public: 401 UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 402 llvm::sys::Path& filename); 403 404 ~UbigraphViz(); 405 406 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst); 407}; 408 409} // end anonymous namespace 410 411static ExplodedNode::Auditor* CreateUbiViz() { 412 std::string ErrMsg; 413 414 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); 415 if (!ErrMsg.empty()) 416 return 0; 417 418 llvm::sys::Path Filename = Dir; 419 Filename.appendComponent("llvm_ubi"); 420 Filename.makeUnique(true,&ErrMsg); 421 422 if (!ErrMsg.empty()) 423 return 0; 424 425 llvm::errs() << "Writing '" << Filename.str() << "'.\n"; 426 427 llvm::OwningPtr<llvm::raw_fd_ostream> Stream; 428 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg)); 429 430 if (!ErrMsg.empty()) 431 return 0; 432 433 return new UbigraphViz(Stream.take(), Dir, Filename); 434} 435 436void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 437 438 assert (Src != Dst && "Self-edges are not allowed."); 439 440 // Lookup the Src. If it is a new node, it's a root. 441 VMap::iterator SrcI= M.find(Src); 442 unsigned SrcID; 443 444 if (SrcI == M.end()) { 445 M[Src] = SrcID = Cntr++; 446 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 447 } 448 else 449 SrcID = SrcI->second; 450 451 // Lookup the Dst. 452 VMap::iterator DstI= M.find(Dst); 453 unsigned DstID; 454 455 if (DstI == M.end()) { 456 M[Dst] = DstID = Cntr++; 457 *Out << "('vertex', " << DstID << ")\n"; 458 } 459 else { 460 // We have hit DstID before. Change its style to reflect a cache hit. 461 DstID = DstI->second; 462 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 463 } 464 465 // Add the edge. 466 *Out << "('edge', " << SrcID << ", " << DstID 467 << ", ('arrow','true'), ('oriented', 'true'))\n"; 468} 469 470UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 471 llvm::sys::Path& filename) 472 : Out(out), Dir(dir), Filename(filename), Cntr(0) { 473 474 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 475 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 476 " ('size', '1.5'))\n"; 477} 478 479UbigraphViz::~UbigraphViz() { 480 Out.reset(0); 481 llvm::errs() << "Running 'ubiviz' program... "; 482 std::string ErrMsg; 483 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz"); 484 std::vector<const char*> args; 485 args.push_back(Ubiviz.c_str()); 486 args.push_back(Filename.c_str()); 487 args.push_back(0); 488 489 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { 490 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 491 } 492 493 // Delete the directory. 494 Dir.eraseFromDisk(true); 495} 496