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/PathSensitive/TransferFuncs.h"
29 #include "clang/StaticAnalyzer/Core/PathDiagnosticClients.h"
30 
31 #include "clang/Basic/FileManager.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Frontend/AnalyzerOptions.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/Program.h"
38 #include "llvm/ADT/OwningPtr.h"
39 
40 using namespace clang;
41 using namespace ento;
42 
43 static ExplodedNode::Auditor* CreateUbiViz();
44 
45 //===----------------------------------------------------------------------===//
46 // Special PathDiagnosticClients.
47 //===----------------------------------------------------------------------===//
48 
49 static PathDiagnosticClient*
50 createPlistHTMLDiagnosticClient(const std::string& prefix,
51                                 const Preprocessor &PP) {
52   PathDiagnosticClient *PD =
53     createHTMLDiagnosticClient(llvm::sys::path::parent_path(prefix), PP);
54   return createPlistDiagnosticClient(prefix, PP, PD);
55 }
56 
57 //===----------------------------------------------------------------------===//
58 // AnalysisConsumer declaration.
59 //===----------------------------------------------------------------------===//
60 
61 namespace {
62 
63 class AnalysisConsumer : public ASTConsumer {
64 public:
65   ASTContext* Ctx;
66   const Preprocessor &PP;
67   const std::string OutDir;
68   AnalyzerOptions Opts;
69 
70   // PD is owned by AnalysisManager.
71   PathDiagnosticClient *PD;
72 
73   StoreManagerCreator CreateStoreMgr;
74   ConstraintManagerCreator CreateConstraintMgr;
75 
76   llvm::OwningPtr<CheckerManager> checkerMgr;
77   llvm::OwningPtr<AnalysisManager> Mgr;
78 
79   AnalysisConsumer(const Preprocessor& pp,
80                    const std::string& outdir,
81                    const AnalyzerOptions& opts)
82     : Ctx(0), PP(pp), OutDir(outdir),
83       Opts(opts), PD(0) {
84     DigestAnalyzerOptions();
85   }
86 
87   void DigestAnalyzerOptions() {
88     // Create the PathDiagnosticClient.
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 = createTextPathDiagnosticClient("", PP);
100     }
101 
102     // Create the analyzer component creators.
103     switch (Opts.AnalysisStoreOpt) {
104     default:
105       assert(0 && "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       assert(0 && "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(registerCheckers(Opts, PP.getLangOptions(),
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.PurgeDead, 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 
165   void HandleCode(Decl *D);
166 };
167 } // end anonymous namespace
168 
169 //===----------------------------------------------------------------------===//
170 // AnalysisConsumer implementation.
171 //===----------------------------------------------------------------------===//
172 
173 void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
174   BugReporter BR(*Mgr);
175   for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
176        I != E; ++I) {
177     Decl *D = *I;
178     checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
179 
180     switch (D->getKind()) {
181       case Decl::Namespace: {
182         HandleDeclContext(C, cast<NamespaceDecl>(D));
183         break;
184       }
185       case Decl::CXXConstructor:
186       case Decl::CXXDestructor:
187       case Decl::CXXConversion:
188       case Decl::CXXMethod:
189       case Decl::Function: {
190         FunctionDecl* FD = cast<FunctionDecl>(D);
191         // We skip function template definitions, as their semantics is
192         // only determined when they are instantiated.
193         if (FD->isThisDeclarationADefinition() &&
194             !FD->isDependentContext()) {
195           if (!Opts.AnalyzeSpecificFunction.empty() &&
196               FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction)
197             break;
198           DisplayFunction(FD);
199           HandleCode(FD);
200         }
201         break;
202       }
203 
204       case Decl::ObjCImplementation: {
205         ObjCImplementationDecl* ID = cast<ObjCImplementationDecl>(*I);
206         HandleCode(ID);
207 
208         for (ObjCImplementationDecl::method_iterator MI = ID->meth_begin(),
209              ME = ID->meth_end(); MI != ME; ++MI) {
210           checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR);
211 
212           if ((*MI)->isThisDeclarationADefinition()) {
213             if (!Opts.AnalyzeSpecificFunction.empty() &&
214                 Opts.AnalyzeSpecificFunction != (*MI)->getSelector().getAsString())
215               break;
216             DisplayFunction(*MI);
217             HandleCode(*MI);
218           }
219         }
220         break;
221       }
222 
223       default:
224         break;
225     }
226   }
227 }
228 
229 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
230   BugReporter BR(*Mgr);
231   TranslationUnitDecl *TU = C.getTranslationUnitDecl();
232   checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
233   HandleDeclContext(C, TU);
234 
235   // Explicitly destroy the PathDiagnosticClient.  This will flush its output.
236   // FIXME: This should be replaced with something that doesn't rely on
237   // side-effects in PathDiagnosticClient's destructor. This is required when
238   // used with option -disable-free.
239   Mgr.reset(NULL);
240 }
241 
242 static void FindBlocks(DeclContext *D, llvm::SmallVectorImpl<Decl*> &WL) {
243   if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
244     WL.push_back(BD);
245 
246   for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
247        I!=E; ++I)
248     if (DeclContext *DC = dyn_cast<DeclContext>(*I))
249       FindBlocks(DC, WL);
250 }
251 
252 static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
253                                  Decl *D);
254 
255 void AnalysisConsumer::HandleCode(Decl *D) {
256 
257   // Don't run the actions if an error has occured with parsing the file.
258   Diagnostic &Diags = PP.getDiagnostics();
259   if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
260     return;
261 
262   // Don't run the actions on declarations in header files unless
263   // otherwise specified.
264   SourceManager &SM = Ctx->getSourceManager();
265   SourceLocation SL = SM.getInstantiationLoc(D->getLocation());
266   if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
267     return;
268 
269   // Clear the AnalysisManager of old AnalysisContexts.
270   Mgr->ClearContexts();
271 
272   // Dispatch on the actions.
273   llvm::SmallVector<Decl*, 10> WL;
274   WL.push_back(D);
275 
276   if (D->hasBody() && Opts.AnalyzeNestedBlocks)
277     FindBlocks(cast<DeclContext>(D), WL);
278 
279   BugReporter BR(*Mgr);
280   for (llvm::SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
281        WI != WE; ++WI)
282     if ((*WI)->hasBody()) {
283       checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
284       if (checkerMgr->hasPathSensitiveCheckers())
285         ActionObjCMemChecker(*this, *Mgr, *WI);
286     }
287 }
288 
289 //===----------------------------------------------------------------------===//
290 // Path-sensitive checking.
291 //===----------------------------------------------------------------------===//
292 
293 static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager& mgr,
294                                Decl *D,
295                                TransferFuncs* tf) {
296 
297   llvm::OwningPtr<TransferFuncs> TF(tf);
298 
299   // Construct the analysis engine.  We first query for the LiveVariables
300   // information to see if the CFG is valid.
301   // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
302   if (!mgr.getLiveVariables(D))
303     return;
304   ExprEngine Eng(mgr, TF.take());
305 
306   // Set the graph auditor.
307   llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
308   if (mgr.shouldVisualizeUbigraph()) {
309     Auditor.reset(CreateUbiViz());
310     ExplodedNode::SetAuditor(Auditor.get());
311   }
312 
313   // Execute the worklist algorithm.
314   Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
315 
316   // Release the auditor (if any) so that it doesn't monitor the graph
317   // created BugReporter.
318   ExplodedNode::SetAuditor(0);
319 
320   // Visualize the exploded graph.
321   if (mgr.shouldVisualizeGraphviz())
322     Eng.ViewGraph(mgr.shouldTrimGraph());
323 
324   // Display warnings.
325   Eng.getBugReporter().FlushReports();
326 }
327 
328 static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr,
329                                   Decl *D, bool GCEnabled) {
330 
331   TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(),
332                                          GCEnabled,
333                                          mgr.getLangOptions());
334 
335   ActionExprEngine(C, mgr, D, TF);
336 }
337 
338 static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
339                                Decl *D) {
340 
341  switch (mgr.getLangOptions().getGCMode()) {
342  default:
343    assert (false && "Invalid GC mode.");
344  case LangOptions::NonGC:
345    ActionObjCMemCheckerAux(C, mgr, D, false);
346    break;
347 
348  case LangOptions::GCOnly:
349    ActionObjCMemCheckerAux(C, mgr, D, true);
350    break;
351 
352  case LangOptions::HybridGC:
353    ActionObjCMemCheckerAux(C, mgr, D, false);
354    ActionObjCMemCheckerAux(C, mgr, D, true);
355    break;
356  }
357 }
358 
359 //===----------------------------------------------------------------------===//
360 // AnalysisConsumer creation.
361 //===----------------------------------------------------------------------===//
362 
363 ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
364                                            const std::string& OutDir,
365                                            const AnalyzerOptions& Opts) {
366   llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(pp, OutDir, Opts));
367 
368   // Last, disable the effects of '-Werror' when using the AnalysisConsumer.
369   pp.getDiagnostics().setWarningsAsErrors(false);
370 
371   return C.take();
372 }
373 
374 //===----------------------------------------------------------------------===//
375 // Ubigraph Visualization.  FIXME: Move to separate file.
376 //===----------------------------------------------------------------------===//
377 
378 namespace {
379 
380 class UbigraphViz : public ExplodedNode::Auditor {
381   llvm::OwningPtr<llvm::raw_ostream> Out;
382   llvm::sys::Path Dir, Filename;
383   unsigned Cntr;
384 
385   typedef llvm::DenseMap<void*,unsigned> VMap;
386   VMap M;
387 
388 public:
389   UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
390               llvm::sys::Path& filename);
391 
392   ~UbigraphViz();
393 
394   virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst);
395 };
396 
397 } // end anonymous namespace
398 
399 static ExplodedNode::Auditor* CreateUbiViz() {
400   std::string ErrMsg;
401 
402   llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
403   if (!ErrMsg.empty())
404     return 0;
405 
406   llvm::sys::Path Filename = Dir;
407   Filename.appendComponent("llvm_ubi");
408   Filename.makeUnique(true,&ErrMsg);
409 
410   if (!ErrMsg.empty())
411     return 0;
412 
413   llvm::errs() << "Writing '" << Filename.str() << "'.\n";
414 
415   llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
416   Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
417 
418   if (!ErrMsg.empty())
419     return 0;
420 
421   return new UbigraphViz(Stream.take(), Dir, Filename);
422 }
423 
424 void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) {
425 
426   assert (Src != Dst && "Self-edges are not allowed.");
427 
428   // Lookup the Src.  If it is a new node, it's a root.
429   VMap::iterator SrcI= M.find(Src);
430   unsigned SrcID;
431 
432   if (SrcI == M.end()) {
433     M[Src] = SrcID = Cntr++;
434     *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
435   }
436   else
437     SrcID = SrcI->second;
438 
439   // Lookup the Dst.
440   VMap::iterator DstI= M.find(Dst);
441   unsigned DstID;
442 
443   if (DstI == M.end()) {
444     M[Dst] = DstID = Cntr++;
445     *Out << "('vertex', " << DstID << ")\n";
446   }
447   else {
448     // We have hit DstID before.  Change its style to reflect a cache hit.
449     DstID = DstI->second;
450     *Out << "('change_vertex_style', " << DstID << ", 1)\n";
451   }
452 
453   // Add the edge.
454   *Out << "('edge', " << SrcID << ", " << DstID
455        << ", ('arrow','true'), ('oriented', 'true'))\n";
456 }
457 
458 UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
459                          llvm::sys::Path& filename)
460   : Out(out), Dir(dir), Filename(filename), Cntr(0) {
461 
462   *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
463   *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
464           " ('size', '1.5'))\n";
465 }
466 
467 UbigraphViz::~UbigraphViz() {
468   Out.reset(0);
469   llvm::errs() << "Running 'ubiviz' program... ";
470   std::string ErrMsg;
471   llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
472   std::vector<const char*> args;
473   args.push_back(Ubiviz.c_str());
474   args.push_back(Filename.c_str());
475   args.push_back(0);
476 
477   if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
478     llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
479   }
480 
481   // Delete the directory.
482   Dir.eraseFromDisk(true);
483 }
484