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