AnalysisConsumer.cpp revision 9fb9474c5b267400d4abfbff63c8b39f378235d4
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 ActionWarnDeadStores(AnalysisConsumer &C, AnalysisManager& mgr,
322                                 Decl *D) {
323  if (LiveVariables *L = mgr.getLiveVariables(D)) {
324    BugReporter BR(mgr);
325    CheckDeadStores(*mgr.getCFG(D), *L, mgr.getParentMap(D), BR);
326  }
327}
328
329static void ActionWarnUninitVals(AnalysisConsumer &C, AnalysisManager& mgr,
330                                 Decl *D) {
331  if (CFG* c = mgr.getCFG(D)) {
332    CheckUninitializedValues(*c, mgr.getASTContext(), mgr.getDiagnostic());
333  }
334}
335
336
337static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager& mgr,
338                               Decl *D,
339                               TransferFuncs* tf) {
340
341  llvm::OwningPtr<TransferFuncs> TF(tf);
342
343  // Construct the analysis engine.  We first query for the LiveVariables
344  // information to see if the CFG is valid.
345  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
346  if (!mgr.getLiveVariables(D))
347    return;
348  ExprEngine Eng(mgr, TF.take());
349
350  if (C.Opts.EnableExperimentalInternalChecks)
351    RegisterExperimentalInternalChecks(Eng);
352
353  RegisterNSErrorChecks(Eng.getBugReporter(), Eng, *D);
354
355  if (C.Opts.EnableExperimentalChecks)
356    RegisterExperimentalChecks(Eng);
357
358  if (C.Opts.BufferOverflows)
359    RegisterArrayBoundCheckerV2(Eng);
360
361  // Enable AnalyzerStatsChecker if it was given as an argument
362  if (C.Opts.AnalyzerStats)
363    RegisterAnalyzerStatsChecker(Eng);
364
365  // Set the graph auditor.
366  llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
367  if (mgr.shouldVisualizeUbigraph()) {
368    Auditor.reset(CreateUbiViz());
369    ExplodedNode::SetAuditor(Auditor.get());
370  }
371
372  // Execute the worklist algorithm.
373  Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
374
375  // Release the auditor (if any) so that it doesn't monitor the graph
376  // created BugReporter.
377  ExplodedNode::SetAuditor(0);
378
379  // Visualize the exploded graph.
380  if (mgr.shouldVisualizeGraphviz())
381    Eng.ViewGraph(mgr.shouldTrimGraph());
382
383  // Display warnings.
384  Eng.getBugReporter().FlushReports();
385}
386
387static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr,
388                                  Decl *D, bool GCEnabled) {
389
390  TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(),
391                                         GCEnabled,
392                                         mgr.getLangOptions());
393
394  ActionExprEngine(C, mgr, D, TF);
395}
396
397static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
398                               Decl *D) {
399
400 switch (mgr.getLangOptions().getGCMode()) {
401 default:
402   assert (false && "Invalid GC mode.");
403 case LangOptions::NonGC:
404   ActionObjCMemCheckerAux(C, mgr, D, false);
405   break;
406
407 case LangOptions::GCOnly:
408   ActionObjCMemCheckerAux(C, mgr, D, true);
409   break;
410
411 case LangOptions::HybridGC:
412   ActionObjCMemCheckerAux(C, mgr, D, false);
413   ActionObjCMemCheckerAux(C, mgr, D, true);
414   break;
415 }
416}
417
418static void ActionDisplayLiveVariables(AnalysisConsumer &C,
419                                       AnalysisManager& mgr, Decl *D) {
420  if (LiveVariables* L = mgr.getLiveVariables(D)) {
421    L->dumpBlockLiveness(mgr.getSourceManager());
422  }
423}
424
425static void ActionCFGDump(AnalysisConsumer &C, AnalysisManager& mgr, Decl *D) {
426  if (CFG *cfg = mgr.getCFG(D)) {
427    cfg->dump(mgr.getLangOptions());
428  }
429}
430
431static void ActionCFGView(AnalysisConsumer &C, AnalysisManager& mgr, Decl *D) {
432  if (CFG *cfg = mgr.getCFG(D)) {
433    cfg->viewCFG(mgr.getLangOptions());
434  }
435}
436
437static void ActionSecuritySyntacticChecks(AnalysisConsumer &C,
438                                          AnalysisManager &mgr, Decl *D) {
439  BugReporter BR(mgr);
440  CheckSecuritySyntaxOnly(D, BR);
441}
442
443static void ActionWarnObjCDealloc(AnalysisConsumer &C, AnalysisManager& mgr,
444                                  Decl *D) {
445  if (mgr.getLangOptions().getGCMode() == LangOptions::GCOnly)
446    return;
447  BugReporter BR(mgr);
448  CheckObjCDealloc(cast<ObjCImplementationDecl>(D), mgr.getLangOptions(), BR);
449}
450
451static void ActionWarnObjCUnusedIvars(AnalysisConsumer &C, AnalysisManager& mgr,
452                                      Decl *D) {
453  BugReporter BR(mgr);
454  CheckObjCUnusedIvar(cast<ObjCImplementationDecl>(D), BR);
455}
456
457static void ActionWarnObjCMethSigs(AnalysisConsumer &C, AnalysisManager& mgr,
458                                   Decl *D) {
459  BugReporter BR(mgr);
460  CheckObjCInstMethSignature(cast<ObjCImplementationDecl>(D), BR);
461}
462
463static void ActionWarnSizeofPointer(AnalysisConsumer &C, AnalysisManager &mgr,
464                                    Decl *D) {
465  BugReporter BR(mgr);
466  CheckSizeofPointer(D, BR);
467}
468
469//===----------------------------------------------------------------------===//
470// AnalysisConsumer creation.
471//===----------------------------------------------------------------------===//
472
473ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
474                                           const std::string& OutDir,
475                                           const AnalyzerOptions& Opts) {
476  llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(pp, OutDir, Opts));
477
478  for (unsigned i = 0; i < Opts.AnalysisList.size(); ++i)
479    switch (Opts.AnalysisList[i]) {
480#define ANALYSIS(NAME, CMD, DESC, SCOPE)\
481    case NAME:\
482      C->add ## SCOPE ## Action(&Action ## NAME);\
483      break;
484#include "clang/Frontend/Analyses.def"
485    default: break;
486    }
487
488  // Last, disable the effects of '-Werror' when using the AnalysisConsumer.
489  pp.getDiagnostics().setWarningsAsErrors(false);
490
491  return C.take();
492}
493
494//===----------------------------------------------------------------------===//
495// Ubigraph Visualization.  FIXME: Move to separate file.
496//===----------------------------------------------------------------------===//
497
498namespace {
499
500class UbigraphViz : public ExplodedNode::Auditor {
501  llvm::OwningPtr<llvm::raw_ostream> Out;
502  llvm::sys::Path Dir, Filename;
503  unsigned Cntr;
504
505  typedef llvm::DenseMap<void*,unsigned> VMap;
506  VMap M;
507
508public:
509  UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
510              llvm::sys::Path& filename);
511
512  ~UbigraphViz();
513
514  virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst);
515};
516
517} // end anonymous namespace
518
519static ExplodedNode::Auditor* CreateUbiViz() {
520  std::string ErrMsg;
521
522  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
523  if (!ErrMsg.empty())
524    return 0;
525
526  llvm::sys::Path Filename = Dir;
527  Filename.appendComponent("llvm_ubi");
528  Filename.makeUnique(true,&ErrMsg);
529
530  if (!ErrMsg.empty())
531    return 0;
532
533  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
534
535  llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
536  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
537
538  if (!ErrMsg.empty())
539    return 0;
540
541  return new UbigraphViz(Stream.take(), Dir, Filename);
542}
543
544void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) {
545
546  assert (Src != Dst && "Self-edges are not allowed.");
547
548  // Lookup the Src.  If it is a new node, it's a root.
549  VMap::iterator SrcI= M.find(Src);
550  unsigned SrcID;
551
552  if (SrcI == M.end()) {
553    M[Src] = SrcID = Cntr++;
554    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
555  }
556  else
557    SrcID = SrcI->second;
558
559  // Lookup the Dst.
560  VMap::iterator DstI= M.find(Dst);
561  unsigned DstID;
562
563  if (DstI == M.end()) {
564    M[Dst] = DstID = Cntr++;
565    *Out << "('vertex', " << DstID << ")\n";
566  }
567  else {
568    // We have hit DstID before.  Change its style to reflect a cache hit.
569    DstID = DstI->second;
570    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
571  }
572
573  // Add the edge.
574  *Out << "('edge', " << SrcID << ", " << DstID
575       << ", ('arrow','true'), ('oriented', 'true'))\n";
576}
577
578UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
579                         llvm::sys::Path& filename)
580  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
581
582  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
583  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
584          " ('size', '1.5'))\n";
585}
586
587UbigraphViz::~UbigraphViz() {
588  Out.reset(0);
589  llvm::errs() << "Running 'ubiviz' program... ";
590  std::string ErrMsg;
591  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
592  std::vector<const char*> args;
593  args.push_back(Ubiviz.c_str());
594  args.push_back(Filename.c_str());
595  args.push_back(0);
596
597  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
598    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
599  }
600
601  // Delete the directory.
602  Dir.eraseFromDisk(true);
603}
604