AnalysisConsumer.cpp revision 65d39251ff57b8e33cf6d3a7fcc6aa1c6f8cdc68
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  RegisterNSErrorChecks(Eng.getBugReporter(), Eng, *D);
344
345  if (C.Opts.EnableExperimentalChecks)
346    RegisterExperimentalChecks(Eng);
347
348  if (C.Opts.BufferOverflows)
349    RegisterArrayBoundCheckerV2(Eng);
350
351  // Enable AnalyzerStatsChecker if it was given as an argument
352  if (C.Opts.AnalyzerStats)
353    RegisterAnalyzerStatsChecker(Eng);
354
355  // Set the graph auditor.
356  llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
357  if (mgr.shouldVisualizeUbigraph()) {
358    Auditor.reset(CreateUbiViz());
359    ExplodedNode::SetAuditor(Auditor.get());
360  }
361
362  // Execute the worklist algorithm.
363  Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
364
365  // Release the auditor (if any) so that it doesn't monitor the graph
366  // created BugReporter.
367  ExplodedNode::SetAuditor(0);
368
369  // Visualize the exploded graph.
370  if (mgr.shouldVisualizeGraphviz())
371    Eng.ViewGraph(mgr.shouldTrimGraph());
372
373  // Display warnings.
374  Eng.getBugReporter().FlushReports();
375}
376
377static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr,
378                                  Decl *D, bool GCEnabled) {
379
380  TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(),
381                                         GCEnabled,
382                                         mgr.getLangOptions());
383
384  ActionExprEngine(C, mgr, D, TF);
385}
386
387static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
388                               Decl *D) {
389
390 switch (mgr.getLangOptions().getGCMode()) {
391 default:
392   assert (false && "Invalid GC mode.");
393 case LangOptions::NonGC:
394   ActionObjCMemCheckerAux(C, mgr, D, false);
395   break;
396
397 case LangOptions::GCOnly:
398   ActionObjCMemCheckerAux(C, mgr, D, true);
399   break;
400
401 case LangOptions::HybridGC:
402   ActionObjCMemCheckerAux(C, mgr, D, false);
403   ActionObjCMemCheckerAux(C, mgr, D, true);
404   break;
405 }
406}
407
408//===----------------------------------------------------------------------===//
409// AnalysisConsumer creation.
410//===----------------------------------------------------------------------===//
411
412ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
413                                           const std::string& OutDir,
414                                           const AnalyzerOptions& Opts) {
415  llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(pp, OutDir, Opts));
416
417  for (unsigned i = 0; i < Opts.AnalysisList.size(); ++i)
418    switch (Opts.AnalysisList[i]) {
419#define ANALYSIS(NAME, CMD, DESC, SCOPE)\
420    case NAME:\
421      C->add ## SCOPE ## Action(&Action ## NAME);\
422      break;
423#include "clang/Frontend/Analyses.def"
424    default: break;
425    }
426
427  // Last, disable the effects of '-Werror' when using the AnalysisConsumer.
428  pp.getDiagnostics().setWarningsAsErrors(false);
429
430  return C.take();
431}
432
433//===----------------------------------------------------------------------===//
434// Ubigraph Visualization.  FIXME: Move to separate file.
435//===----------------------------------------------------------------------===//
436
437namespace {
438
439class UbigraphViz : public ExplodedNode::Auditor {
440  llvm::OwningPtr<llvm::raw_ostream> Out;
441  llvm::sys::Path Dir, Filename;
442  unsigned Cntr;
443
444  typedef llvm::DenseMap<void*,unsigned> VMap;
445  VMap M;
446
447public:
448  UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
449              llvm::sys::Path& filename);
450
451  ~UbigraphViz();
452
453  virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst);
454};
455
456} // end anonymous namespace
457
458static ExplodedNode::Auditor* CreateUbiViz() {
459  std::string ErrMsg;
460
461  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
462  if (!ErrMsg.empty())
463    return 0;
464
465  llvm::sys::Path Filename = Dir;
466  Filename.appendComponent("llvm_ubi");
467  Filename.makeUnique(true,&ErrMsg);
468
469  if (!ErrMsg.empty())
470    return 0;
471
472  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
473
474  llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
475  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
476
477  if (!ErrMsg.empty())
478    return 0;
479
480  return new UbigraphViz(Stream.take(), Dir, Filename);
481}
482
483void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) {
484
485  assert (Src != Dst && "Self-edges are not allowed.");
486
487  // Lookup the Src.  If it is a new node, it's a root.
488  VMap::iterator SrcI= M.find(Src);
489  unsigned SrcID;
490
491  if (SrcI == M.end()) {
492    M[Src] = SrcID = Cntr++;
493    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
494  }
495  else
496    SrcID = SrcI->second;
497
498  // Lookup the Dst.
499  VMap::iterator DstI= M.find(Dst);
500  unsigned DstID;
501
502  if (DstI == M.end()) {
503    M[Dst] = DstID = Cntr++;
504    *Out << "('vertex', " << DstID << ")\n";
505  }
506  else {
507    // We have hit DstID before.  Change its style to reflect a cache hit.
508    DstID = DstI->second;
509    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
510  }
511
512  // Add the edge.
513  *Out << "('edge', " << SrcID << ", " << DstID
514       << ", ('arrow','true'), ('oriented', 'true'))\n";
515}
516
517UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
518                         llvm::sys::Path& filename)
519  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
520
521  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
522  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
523          " ('size', '1.5'))\n";
524}
525
526UbigraphViz::~UbigraphViz() {
527  Out.reset(0);
528  llvm::errs() << "Running 'ubiviz' program... ";
529  std::string ErrMsg;
530  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
531  std::vector<const char*> args;
532  args.push_back(Ubiviz.c_str());
533  args.push_back(Filename.c_str());
534  args.push_back(0);
535
536  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
537    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
538  }
539
540  // Delete the directory.
541  Dir.eraseFromDisk(true);
542}
543