AnalysisConsumer.cpp revision 2d67b90a21c9c1093e6598809c2cbc832919cfe6
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
410//===----------------------------------------------------------------------===//
411// AnalysisConsumer creation.
412//===----------------------------------------------------------------------===//
413
414ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
415                                           const std::string& OutDir,
416                                           const AnalyzerOptions& Opts) {
417  llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(pp, OutDir, Opts));
418
419  for (unsigned i = 0; i < Opts.AnalysisList.size(); ++i)
420    switch (Opts.AnalysisList[i]) {
421#define ANALYSIS(NAME, CMD, DESC, SCOPE)\
422    case NAME:\
423      C->add ## SCOPE ## Action(&Action ## NAME);\
424      break;
425#include "clang/Frontend/Analyses.def"
426    default: break;
427    }
428
429  // Last, disable the effects of '-Werror' when using the AnalysisConsumer.
430  pp.getDiagnostics().setWarningsAsErrors(false);
431
432  return C.take();
433}
434
435//===----------------------------------------------------------------------===//
436// Ubigraph Visualization.  FIXME: Move to separate file.
437//===----------------------------------------------------------------------===//
438
439namespace {
440
441class UbigraphViz : public ExplodedNode::Auditor {
442  llvm::OwningPtr<llvm::raw_ostream> Out;
443  llvm::sys::Path Dir, Filename;
444  unsigned Cntr;
445
446  typedef llvm::DenseMap<void*,unsigned> VMap;
447  VMap M;
448
449public:
450  UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
451              llvm::sys::Path& filename);
452
453  ~UbigraphViz();
454
455  virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst);
456};
457
458} // end anonymous namespace
459
460static ExplodedNode::Auditor* CreateUbiViz() {
461  std::string ErrMsg;
462
463  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
464  if (!ErrMsg.empty())
465    return 0;
466
467  llvm::sys::Path Filename = Dir;
468  Filename.appendComponent("llvm_ubi");
469  Filename.makeUnique(true,&ErrMsg);
470
471  if (!ErrMsg.empty())
472    return 0;
473
474  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
475
476  llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
477  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
478
479  if (!ErrMsg.empty())
480    return 0;
481
482  return new UbigraphViz(Stream.take(), Dir, Filename);
483}
484
485void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) {
486
487  assert (Src != Dst && "Self-edges are not allowed.");
488
489  // Lookup the Src.  If it is a new node, it's a root.
490  VMap::iterator SrcI= M.find(Src);
491  unsigned SrcID;
492
493  if (SrcI == M.end()) {
494    M[Src] = SrcID = Cntr++;
495    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
496  }
497  else
498    SrcID = SrcI->second;
499
500  // Lookup the Dst.
501  VMap::iterator DstI= M.find(Dst);
502  unsigned DstID;
503
504  if (DstI == M.end()) {
505    M[Dst] = DstID = Cntr++;
506    *Out << "('vertex', " << DstID << ")\n";
507  }
508  else {
509    // We have hit DstID before.  Change its style to reflect a cache hit.
510    DstID = DstI->second;
511    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
512  }
513
514  // Add the edge.
515  *Out << "('edge', " << SrcID << ", " << DstID
516       << ", ('arrow','true'), ('oriented', 'true'))\n";
517}
518
519UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
520                         llvm::sys::Path& filename)
521  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
522
523  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
524  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
525          " ('size', '1.5'))\n";
526}
527
528UbigraphViz::~UbigraphViz() {
529  Out.reset(0);
530  llvm::errs() << "Running 'ubiviz' program... ";
531  std::string ErrMsg;
532  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
533  std::vector<const char*> args;
534  args.push_back(Ubiviz.c_str());
535  args.push_back(Filename.c_str());
536  args.push_back(0);
537
538  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
539    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
540  }
541
542  // Delete the directory.
543  Dir.eraseFromDisk(true);
544}
545