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/PathDiagnosticConsumers.h"
29 
30 #include "clang/Basic/FileManager.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Frontend/AnalyzerOptions.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Program.h"
37 #include "llvm/ADT/OwningPtr.h"
38 
39 using namespace clang;
40 using namespace ento;
41 
42 static ExplodedNode::Auditor* CreateUbiViz();
43 
44 //===----------------------------------------------------------------------===//
45 // Special PathDiagnosticConsumers.
46 //===----------------------------------------------------------------------===//
47 
48 static PathDiagnosticConsumer*
49 createPlistHTMLDiagnosticConsumer(const std::string& prefix,
50                                 const Preprocessor &PP) {
51   PathDiagnosticConsumer *PD =
52     createHTMLDiagnosticConsumer(llvm::sys::path::parent_path(prefix), PP);
53   return createPlistDiagnosticConsumer(prefix, PP, PD);
54 }
55 
56 //===----------------------------------------------------------------------===//
57 // AnalysisConsumer declaration.
58 //===----------------------------------------------------------------------===//
59 
60 namespace {
61 
62 class AnalysisConsumer : public ASTConsumer {
63 public:
64   ASTContext *Ctx;
65   const Preprocessor &PP;
66   const std::string OutDir;
67   AnalyzerOptions Opts;
68   ArrayRef<std::string> Plugins;
69 
70   // PD is owned by AnalysisManager.
71   PathDiagnosticConsumer *PD;
72 
73   StoreManagerCreator CreateStoreMgr;
74   ConstraintManagerCreator CreateConstraintMgr;
75 
76   OwningPtr<CheckerManager> checkerMgr;
77   OwningPtr<AnalysisManager> Mgr;
78 
79   AnalysisConsumer(const Preprocessor& pp,
80                    const std::string& outdir,
81                    const AnalyzerOptions& opts,
82                    ArrayRef<std::string> plugins)
83     : Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins), PD(0) {
84     DigestAnalyzerOptions();
85   }
86 
87   void DigestAnalyzerOptions() {
88     // Create the PathDiagnosticConsumer.
89     if (!OutDir.empty()) {
90       switch (Opts.AnalysisDiagOpt) {
91       default:
92 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
93         case PD_##NAME: PD = CREATEFN(OutDir, PP); break;
94 #include "clang/Frontend/Analyses.def"
95       }
96     } else if (Opts.AnalysisDiagOpt == PD_TEXT) {
97       // Create the text client even without a specified output file since
98       // it just uses diagnostic notes.
99       PD = createTextPathDiagnosticConsumer("", PP);
100     }
101 
102     // Create the analyzer component creators.
103     switch (Opts.AnalysisStoreOpt) {
104     default:
105       llvm_unreachable("Unknown store manager.");
106 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN)           \
107       case NAME##Model: CreateStoreMgr = CREATEFN; break;
108 #include "clang/Frontend/Analyses.def"
109     }
110 
111     switch (Opts.AnalysisConstraintsOpt) {
112     default:
113       llvm_unreachable("Unknown store manager.");
114 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \
115       case NAME##Model: CreateConstraintMgr = CREATEFN; break;
116 #include "clang/Frontend/Analyses.def"
117     }
118   }
119 
120   void DisplayFunction(const Decl *D) {
121     if (!Opts.AnalyzerDisplayProgress)
122       return;
123 
124     SourceManager &SM = Mgr->getASTContext().getSourceManager();
125     PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
126     if (Loc.isValid()) {
127       llvm::errs() << "ANALYZE: " << Loc.getFilename();
128 
129       if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
130         const NamedDecl *ND = cast<NamedDecl>(D);
131         llvm::errs() << ' ' << *ND << '\n';
132       }
133       else if (isa<BlockDecl>(D)) {
134         llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
135                      << Loc.getColumn() << '\n';
136       }
137       else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
138         Selector S = MD->getSelector();
139         llvm::errs() << ' ' << S.getAsString();
140       }
141     }
142   }
143 
144   virtual void Initialize(ASTContext &Context) {
145     Ctx = &Context;
146     checkerMgr.reset(createCheckerManager(Opts, PP.getLangOptions(), Plugins,
147                                           PP.getDiagnostics()));
148     Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(),
149                                   PP.getLangOptions(), PD,
150                                   CreateStoreMgr, CreateConstraintMgr,
151                                   checkerMgr.get(),
152                                   /* Indexer */ 0,
153                                   Opts.MaxNodes, Opts.MaxLoop,
154                                   Opts.VisualizeEGDot, Opts.VisualizeEGUbi,
155                                   Opts.AnalysisPurgeOpt, Opts.EagerlyAssume,
156                                   Opts.TrimGraph, Opts.InlineCall,
157                                   Opts.UnoptimizedCFG, Opts.CFGAddImplicitDtors,
158                                   Opts.CFGAddInitializers,
159                                   Opts.EagerlyTrimEGraph));
160   }
161 
162   virtual void HandleTranslationUnit(ASTContext &C);
163   void HandleDeclContext(ASTContext &C, DeclContext *dc);
164   void HandleDeclContextDecl(ASTContext &C, Decl *D);
165 
166   void HandleCode(Decl *D);
167 };
168 } // end anonymous namespace
169 
170 //===----------------------------------------------------------------------===//
171 // AnalysisConsumer implementation.
172 //===----------------------------------------------------------------------===//
173 
174 void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
175   for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
176        I != E; ++I) {
177     HandleDeclContextDecl(C, *I);
178   }
179 }
180 
181 void AnalysisConsumer::HandleDeclContextDecl(ASTContext &C, Decl *D) {
182   { // Handle callbacks for arbitrary decls.
183     BugReporter BR(*Mgr);
184     checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
185   }
186 
187   switch (D->getKind()) {
188     case Decl::Namespace: {
189       HandleDeclContext(C, cast<NamespaceDecl>(D));
190       break;
191     }
192     case Decl::CXXConstructor:
193     case Decl::CXXDestructor:
194     case Decl::CXXConversion:
195     case Decl::CXXMethod:
196     case Decl::Function: {
197       FunctionDecl *FD = cast<FunctionDecl>(D);
198       // We skip function template definitions, as their semantics is
199       // only determined when they are instantiated.
200       if (FD->isThisDeclarationADefinition() &&
201           !FD->isDependentContext()) {
202         if (!Opts.AnalyzeSpecificFunction.empty() &&
203             FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction)
204           break;
205         DisplayFunction(FD);
206         HandleCode(FD);
207       }
208       break;
209     }
210 
211     case Decl::ObjCCategoryImpl:
212     case Decl::ObjCImplementation: {
213       ObjCImplDecl *ID = cast<ObjCImplDecl>(D);
214       HandleCode(ID);
215 
216       for (ObjCContainerDecl::method_iterator MI = ID->meth_begin(),
217            ME = ID->meth_end(); MI != ME; ++MI) {
218         BugReporter BR(*Mgr);
219         checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR);
220 
221         if ((*MI)->isThisDeclarationADefinition()) {
222           if (!Opts.AnalyzeSpecificFunction.empty() &&
223               Opts.AnalyzeSpecificFunction !=
224                 (*MI)->getSelector().getAsString())
225             continue;
226           DisplayFunction(*MI);
227           HandleCode(*MI);
228         }
229       }
230       break;
231     }
232 
233     default:
234       break;
235   }
236 }
237 
238 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
239   {
240     // Introduce a scope to destroy BR before Mgr.
241     BugReporter BR(*Mgr);
242     TranslationUnitDecl *TU = C.getTranslationUnitDecl();
243     checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
244     HandleDeclContext(C, TU);
245 
246     // After all decls handled, run checkers on the entire TranslationUnit.
247     checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
248   }
249 
250   // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
251   // FIXME: This should be replaced with something that doesn't rely on
252   // side-effects in PathDiagnosticConsumer's destructor. This is required when
253   // used with option -disable-free.
254   Mgr.reset(NULL);
255 }
256 
257 static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
258   if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
259     WL.push_back(BD);
260 
261   for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
262        I!=E; ++I)
263     if (DeclContext *DC = dyn_cast<DeclContext>(*I))
264       FindBlocks(DC, WL);
265 }
266 
267 static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
268                                    Decl *D);
269 
270 void AnalysisConsumer::HandleCode(Decl *D) {
271 
272   // Don't run the actions if an error has occurred with parsing the file.
273   DiagnosticsEngine &Diags = PP.getDiagnostics();
274   if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
275     return;
276 
277   // Don't run the actions on declarations in header files unless
278   // otherwise specified.
279   SourceManager &SM = Ctx->getSourceManager();
280   SourceLocation SL = SM.getExpansionLoc(D->getLocation());
281   if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
282     return;
283 
284   // Clear the AnalysisManager of old AnalysisDeclContexts.
285   Mgr->ClearContexts();
286 
287   // Dispatch on the actions.
288   SmallVector<Decl*, 10> WL;
289   WL.push_back(D);
290 
291   if (D->hasBody() && Opts.AnalyzeNestedBlocks)
292     FindBlocks(cast<DeclContext>(D), WL);
293 
294   BugReporter BR(*Mgr);
295   for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
296        WI != WE; ++WI)
297     if ((*WI)->hasBody()) {
298       checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
299       if (checkerMgr->hasPathSensitiveCheckers())
300         RunPathSensitiveChecks(*this, *Mgr, *WI);
301     }
302 }
303 
304 //===----------------------------------------------------------------------===//
305 // Path-sensitive checking.
306 //===----------------------------------------------------------------------===//
307 
308 static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager &mgr,
309                              Decl *D, bool ObjCGCEnabled) {
310   // Construct the analysis engine.  First check if the CFG is valid.
311   // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
312   if (!mgr.getCFG(D))
313     return;
314   ExprEngine Eng(mgr, ObjCGCEnabled);
315 
316   // Set the graph auditor.
317   OwningPtr<ExplodedNode::Auditor> Auditor;
318   if (mgr.shouldVisualizeUbigraph()) {
319     Auditor.reset(CreateUbiViz());
320     ExplodedNode::SetAuditor(Auditor.get());
321   }
322 
323   // Execute the worklist algorithm.
324   Eng.ExecuteWorkList(mgr.getAnalysisDeclContextManager().getStackFrame(D, 0),
325                       mgr.getMaxNodes());
326 
327   // Release the auditor (if any) so that it doesn't monitor the graph
328   // created BugReporter.
329   ExplodedNode::SetAuditor(0);
330 
331   // Visualize the exploded graph.
332   if (mgr.shouldVisualizeGraphviz())
333     Eng.ViewGraph(mgr.shouldTrimGraph());
334 
335   // Display warnings.
336   Eng.getBugReporter().FlushReports();
337 }
338 
339 static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
340                                    Decl *D) {
341 
342   switch (mgr.getLangOptions().getGC()) {
343   case LangOptions::NonGC:
344     ActionExprEngine(C, mgr, D, false);
345     break;
346 
347   case LangOptions::GCOnly:
348     ActionExprEngine(C, mgr, D, true);
349     break;
350 
351   case LangOptions::HybridGC:
352     ActionExprEngine(C, mgr, D, false);
353     ActionExprEngine(C, mgr, D, true);
354     break;
355   }
356 }
357 
358 //===----------------------------------------------------------------------===//
359 // AnalysisConsumer creation.
360 //===----------------------------------------------------------------------===//
361 
362 ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
363                                           const std::string& outDir,
364                                           const AnalyzerOptions& opts,
365                                           ArrayRef<std::string> plugins) {
366   // Disable the effects of '-Werror' when using the AnalysisConsumer.
367   pp.getDiagnostics().setWarningsAsErrors(false);
368 
369   return new AnalysisConsumer(pp, outDir, opts, plugins);
370 }
371 
372 //===----------------------------------------------------------------------===//
373 // Ubigraph Visualization.  FIXME: Move to separate file.
374 //===----------------------------------------------------------------------===//
375 
376 namespace {
377 
378 class UbigraphViz : public ExplodedNode::Auditor {
379   OwningPtr<raw_ostream> Out;
380   llvm::sys::Path Dir, Filename;
381   unsigned Cntr;
382 
383   typedef llvm::DenseMap<void*,unsigned> VMap;
384   VMap M;
385 
386 public:
387   UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
388               llvm::sys::Path& filename);
389 
390   ~UbigraphViz();
391 
392   virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
393 };
394 
395 } // end anonymous namespace
396 
397 static ExplodedNode::Auditor* CreateUbiViz() {
398   std::string ErrMsg;
399 
400   llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
401   if (!ErrMsg.empty())
402     return 0;
403 
404   llvm::sys::Path Filename = Dir;
405   Filename.appendComponent("llvm_ubi");
406   Filename.makeUnique(true,&ErrMsg);
407 
408   if (!ErrMsg.empty())
409     return 0;
410 
411   llvm::errs() << "Writing '" << Filename.str() << "'.\n";
412 
413   OwningPtr<llvm::raw_fd_ostream> Stream;
414   Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
415 
416   if (!ErrMsg.empty())
417     return 0;
418 
419   return new UbigraphViz(Stream.take(), Dir, Filename);
420 }
421 
422 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
423 
424   assert (Src != Dst && "Self-edges are not allowed.");
425 
426   // Lookup the Src.  If it is a new node, it's a root.
427   VMap::iterator SrcI= M.find(Src);
428   unsigned SrcID;
429 
430   if (SrcI == M.end()) {
431     M[Src] = SrcID = Cntr++;
432     *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
433   }
434   else
435     SrcID = SrcI->second;
436 
437   // Lookup the Dst.
438   VMap::iterator DstI= M.find(Dst);
439   unsigned DstID;
440 
441   if (DstI == M.end()) {
442     M[Dst] = DstID = Cntr++;
443     *Out << "('vertex', " << DstID << ")\n";
444   }
445   else {
446     // We have hit DstID before.  Change its style to reflect a cache hit.
447     DstID = DstI->second;
448     *Out << "('change_vertex_style', " << DstID << ", 1)\n";
449   }
450 
451   // Add the edge.
452   *Out << "('edge', " << SrcID << ", " << DstID
453        << ", ('arrow','true'), ('oriented', 'true'))\n";
454 }
455 
456 UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
457                          llvm::sys::Path& filename)
458   : Out(out), Dir(dir), Filename(filename), Cntr(0) {
459 
460   *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
461   *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
462           " ('size', '1.5'))\n";
463 }
464 
465 UbigraphViz::~UbigraphViz() {
466   Out.reset(0);
467   llvm::errs() << "Running 'ubiviz' program... ";
468   std::string ErrMsg;
469   llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
470   std::vector<const char*> args;
471   args.push_back(Ubiviz.c_str());
472   args.push_back(Filename.c_str());
473   args.push_back(0);
474 
475   if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
476     llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
477   }
478 
479   // Delete the directory.
480   Dir.eraseFromDisk(true);
481 }
482