• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- PlistDiagnostics.cpp - Plist Diagnostics for Paths -----*- C++ -*-===//
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 //  This file defines the PlistDiagnostics object.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
15 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallVector.h"
23 using namespace clang;
24 using namespace ento;
25 
26 typedef llvm::DenseMap<FileID, unsigned> FIDMap;
27 
28 
29 namespace {
30   class PlistDiagnostics : public PathDiagnosticConsumer {
31     const std::string OutputFile;
32     const LangOptions &LangOpts;
33     OwningPtr<PathDiagnosticConsumer> SubPD;
34     bool flushed;
35     const bool SupportsCrossFileDiagnostics;
36   public:
37     PlistDiagnostics(const std::string& prefix, const LangOptions &LangOpts,
38                      bool supportsMultipleFiles,
39                      PathDiagnosticConsumer *subPD);
40 
~PlistDiagnostics()41     virtual ~PlistDiagnostics() {}
42 
43     void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
44                               SmallVectorImpl<std::string> *FilesMade);
45 
getName() const46     virtual StringRef getName() const {
47       return "PlistDiagnostics";
48     }
49 
50     PathGenerationScheme getGenerationScheme() const;
supportsLogicalOpControlFlow() const51     bool supportsLogicalOpControlFlow() const { return true; }
supportsAllBlockEdges() const52     bool supportsAllBlockEdges() const { return true; }
useVerboseDescription() const53     virtual bool useVerboseDescription() const { return false; }
supportsCrossFileDiagnostics() const54     virtual bool supportsCrossFileDiagnostics() const {
55       return SupportsCrossFileDiagnostics;
56     }
57   };
58 } // end anonymous namespace
59 
PlistDiagnostics(const std::string & output,const LangOptions & LO,bool supportsMultipleFiles,PathDiagnosticConsumer * subPD)60 PlistDiagnostics::PlistDiagnostics(const std::string& output,
61                                    const LangOptions &LO,
62                                    bool supportsMultipleFiles,
63                                    PathDiagnosticConsumer *subPD)
64   : OutputFile(output), LangOpts(LO), SubPD(subPD), flushed(false),
65     SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
66 
67 PathDiagnosticConsumer*
createPlistDiagnosticConsumer(const std::string & s,const Preprocessor & PP,PathDiagnosticConsumer * subPD)68 ento::createPlistDiagnosticConsumer(const std::string& s, const Preprocessor &PP,
69                                   PathDiagnosticConsumer *subPD) {
70   return new PlistDiagnostics(s, PP.getLangOpts(), false, subPD);
71 }
72 
73 PathDiagnosticConsumer*
createPlistMultiFileDiagnosticConsumer(const std::string & s,const Preprocessor & PP)74 ento::createPlistMultiFileDiagnosticConsumer(const std::string &s,
75                                               const Preprocessor &PP) {
76   return new PlistDiagnostics(s, PP.getLangOpts(), true, 0);
77 }
78 
79 PathDiagnosticConsumer::PathGenerationScheme
getGenerationScheme() const80 PlistDiagnostics::getGenerationScheme() const {
81   if (const PathDiagnosticConsumer *PD = SubPD.get())
82     return PD->getGenerationScheme();
83 
84   return Extensive;
85 }
86 
AddFID(FIDMap & FIDs,SmallVectorImpl<FileID> & V,const SourceManager * SM,SourceLocation L)87 static void AddFID(FIDMap &FIDs, SmallVectorImpl<FileID> &V,
88                    const SourceManager* SM, SourceLocation L) {
89 
90   FileID FID = SM->getFileID(SM->getExpansionLoc(L));
91   FIDMap::iterator I = FIDs.find(FID);
92   if (I != FIDs.end()) return;
93   FIDs[FID] = V.size();
94   V.push_back(FID);
95 }
96 
GetFID(const FIDMap & FIDs,const SourceManager & SM,SourceLocation L)97 static unsigned GetFID(const FIDMap& FIDs, const SourceManager &SM,
98                        SourceLocation L) {
99   FileID FID = SM.getFileID(SM.getExpansionLoc(L));
100   FIDMap::const_iterator I = FIDs.find(FID);
101   assert(I != FIDs.end());
102   return I->second;
103 }
104 
Indent(raw_ostream & o,const unsigned indent)105 static raw_ostream &Indent(raw_ostream &o, const unsigned indent) {
106   for (unsigned i = 0; i < indent; ++i) o << ' ';
107   return o;
108 }
109 
EmitLocation(raw_ostream & o,const SourceManager & SM,const LangOptions & LangOpts,SourceLocation L,const FIDMap & FM,unsigned indent,bool extend=false)110 static void EmitLocation(raw_ostream &o, const SourceManager &SM,
111                          const LangOptions &LangOpts,
112                          SourceLocation L, const FIDMap &FM,
113                          unsigned indent, bool extend = false) {
114 
115   FullSourceLoc Loc(SM.getExpansionLoc(L), const_cast<SourceManager&>(SM));
116 
117   // Add in the length of the token, so that we cover multi-char tokens.
118   unsigned offset =
119     extend ? Lexer::MeasureTokenLength(Loc, SM, LangOpts) - 1 : 0;
120 
121   Indent(o, indent) << "<dict>\n";
122   Indent(o, indent) << " <key>line</key><integer>"
123                     << Loc.getExpansionLineNumber() << "</integer>\n";
124   Indent(o, indent) << " <key>col</key><integer>"
125                     << Loc.getExpansionColumnNumber() + offset << "</integer>\n";
126   Indent(o, indent) << " <key>file</key><integer>"
127                     << GetFID(FM, SM, Loc) << "</integer>\n";
128   Indent(o, indent) << "</dict>\n";
129 }
130 
EmitLocation(raw_ostream & o,const SourceManager & SM,const LangOptions & LangOpts,const PathDiagnosticLocation & L,const FIDMap & FM,unsigned indent,bool extend=false)131 static void EmitLocation(raw_ostream &o, const SourceManager &SM,
132                          const LangOptions &LangOpts,
133                          const PathDiagnosticLocation &L, const FIDMap& FM,
134                          unsigned indent, bool extend = false) {
135   EmitLocation(o, SM, LangOpts, L.asLocation(), FM, indent, extend);
136 }
137 
EmitRange(raw_ostream & o,const SourceManager & SM,const LangOptions & LangOpts,PathDiagnosticRange R,const FIDMap & FM,unsigned indent)138 static void EmitRange(raw_ostream &o, const SourceManager &SM,
139                       const LangOptions &LangOpts,
140                       PathDiagnosticRange R, const FIDMap &FM,
141                       unsigned indent) {
142   Indent(o, indent) << "<array>\n";
143   EmitLocation(o, SM, LangOpts, R.getBegin(), FM, indent+1);
144   EmitLocation(o, SM, LangOpts, R.getEnd(), FM, indent+1, !R.isPoint);
145   Indent(o, indent) << "</array>\n";
146 }
147 
EmitString(raw_ostream & o,StringRef s)148 static raw_ostream &EmitString(raw_ostream &o, StringRef s) {
149   o << "<string>";
150   for (StringRef::const_iterator I = s.begin(), E = s.end(); I != E; ++I) {
151     char c = *I;
152     switch (c) {
153     default:   o << c; break;
154     case '&':  o << "&amp;"; break;
155     case '<':  o << "&lt;"; break;
156     case '>':  o << "&gt;"; break;
157     case '\'': o << "&apos;"; break;
158     case '\"': o << "&quot;"; break;
159     }
160   }
161   o << "</string>";
162   return o;
163 }
164 
ReportControlFlow(raw_ostream & o,const PathDiagnosticControlFlowPiece & P,const FIDMap & FM,const SourceManager & SM,const LangOptions & LangOpts,unsigned indent)165 static void ReportControlFlow(raw_ostream &o,
166                               const PathDiagnosticControlFlowPiece& P,
167                               const FIDMap& FM,
168                               const SourceManager &SM,
169                               const LangOptions &LangOpts,
170                               unsigned indent) {
171 
172   Indent(o, indent) << "<dict>\n";
173   ++indent;
174 
175   Indent(o, indent) << "<key>kind</key><string>control</string>\n";
176 
177   // Emit edges.
178   Indent(o, indent) << "<key>edges</key>\n";
179   ++indent;
180   Indent(o, indent) << "<array>\n";
181   ++indent;
182   for (PathDiagnosticControlFlowPiece::const_iterator I=P.begin(), E=P.end();
183        I!=E; ++I) {
184     Indent(o, indent) << "<dict>\n";
185     ++indent;
186     Indent(o, indent) << "<key>start</key>\n";
187     EmitRange(o, SM, LangOpts, I->getStart().asRange(), FM, indent+1);
188     Indent(o, indent) << "<key>end</key>\n";
189     EmitRange(o, SM, LangOpts, I->getEnd().asRange(), FM, indent+1);
190     --indent;
191     Indent(o, indent) << "</dict>\n";
192   }
193   --indent;
194   Indent(o, indent) << "</array>\n";
195   --indent;
196 
197   // Output any helper text.
198   const std::string& s = P.getString();
199   if (!s.empty()) {
200     Indent(o, indent) << "<key>alternate</key>";
201     EmitString(o, s) << '\n';
202   }
203 
204   --indent;
205   Indent(o, indent) << "</dict>\n";
206 }
207 
ReportEvent(raw_ostream & o,const PathDiagnosticPiece & P,const FIDMap & FM,const SourceManager & SM,const LangOptions & LangOpts,unsigned indent,unsigned depth)208 static void ReportEvent(raw_ostream &o, const PathDiagnosticPiece& P,
209                         const FIDMap& FM,
210                         const SourceManager &SM,
211                         const LangOptions &LangOpts,
212                         unsigned indent,
213                         unsigned depth) {
214 
215   Indent(o, indent) << "<dict>\n";
216   ++indent;
217 
218   Indent(o, indent) << "<key>kind</key><string>event</string>\n";
219 
220   // Output the location.
221   FullSourceLoc L = P.getLocation().asLocation();
222 
223   Indent(o, indent) << "<key>location</key>\n";
224   EmitLocation(o, SM, LangOpts, L, FM, indent);
225 
226   // Output the ranges (if any).
227   PathDiagnosticPiece::range_iterator RI = P.ranges_begin(),
228   RE = P.ranges_end();
229 
230   if (RI != RE) {
231     Indent(o, indent) << "<key>ranges</key>\n";
232     Indent(o, indent) << "<array>\n";
233     ++indent;
234     for (; RI != RE; ++RI)
235       EmitRange(o, SM, LangOpts, *RI, FM, indent+1);
236     --indent;
237     Indent(o, indent) << "</array>\n";
238   }
239 
240   // Output the call depth.
241   Indent(o, indent) << "<key>depth</key>"
242                     << "<integer>" << depth << "</integer>\n";
243 
244   // Output the text.
245   assert(!P.getString().empty());
246   Indent(o, indent) << "<key>extended_message</key>\n";
247   Indent(o, indent);
248   EmitString(o, P.getString()) << '\n';
249 
250   // Output the short text.
251   // FIXME: Really use a short string.
252   Indent(o, indent) << "<key>message</key>\n";
253   EmitString(o, P.getString()) << '\n';
254 
255   // Finish up.
256   --indent;
257   Indent(o, indent); o << "</dict>\n";
258 }
259 
260 static void ReportPiece(raw_ostream &o,
261                         const PathDiagnosticPiece &P,
262                         const FIDMap& FM, const SourceManager &SM,
263                         const LangOptions &LangOpts,
264                         unsigned indent,
265                         unsigned depth,
266                         bool includeControlFlow);
267 
ReportCall(raw_ostream & o,const PathDiagnosticCallPiece & P,const FIDMap & FM,const SourceManager & SM,const LangOptions & LangOpts,unsigned indent,unsigned depth)268 static void ReportCall(raw_ostream &o,
269                        const PathDiagnosticCallPiece &P,
270                        const FIDMap& FM, const SourceManager &SM,
271                        const LangOptions &LangOpts,
272                        unsigned indent,
273                        unsigned depth) {
274 
275   IntrusiveRefCntPtr<PathDiagnosticEventPiece> callEnter =
276     P.getCallEnterEvent();
277 
278   if (callEnter)
279     ReportPiece(o, *callEnter, FM, SM, LangOpts, indent, depth, true);
280 
281   IntrusiveRefCntPtr<PathDiagnosticEventPiece> callEnterWithinCaller =
282     P.getCallEnterWithinCallerEvent();
283 
284   ++depth;
285 
286   if (callEnterWithinCaller)
287     ReportPiece(o, *callEnterWithinCaller, FM, SM, LangOpts,
288                 indent, depth, true);
289 
290   for (PathPieces::const_iterator I = P.path.begin(), E = P.path.end();I!=E;++I)
291     ReportPiece(o, **I, FM, SM, LangOpts, indent, depth, true);
292 
293   IntrusiveRefCntPtr<PathDiagnosticEventPiece> callExit =
294     P.getCallExitEvent();
295 
296   if (callExit)
297     ReportPiece(o, *callExit, FM, SM, LangOpts, indent, depth, true);
298 }
299 
ReportMacro(raw_ostream & o,const PathDiagnosticMacroPiece & P,const FIDMap & FM,const SourceManager & SM,const LangOptions & LangOpts,unsigned indent,unsigned depth)300 static void ReportMacro(raw_ostream &o,
301                         const PathDiagnosticMacroPiece& P,
302                         const FIDMap& FM, const SourceManager &SM,
303                         const LangOptions &LangOpts,
304                         unsigned indent,
305                         unsigned depth) {
306 
307   for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
308        I!=E; ++I) {
309     ReportPiece(o, **I, FM, SM, LangOpts, indent, depth, false);
310   }
311 }
312 
ReportDiag(raw_ostream & o,const PathDiagnosticPiece & P,const FIDMap & FM,const SourceManager & SM,const LangOptions & LangOpts)313 static void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P,
314                        const FIDMap& FM, const SourceManager &SM,
315                        const LangOptions &LangOpts) {
316   ReportPiece(o, P, FM, SM, LangOpts, 4, 0, true);
317 }
318 
ReportPiece(raw_ostream & o,const PathDiagnosticPiece & P,const FIDMap & FM,const SourceManager & SM,const LangOptions & LangOpts,unsigned indent,unsigned depth,bool includeControlFlow)319 static void ReportPiece(raw_ostream &o,
320                         const PathDiagnosticPiece &P,
321                         const FIDMap& FM, const SourceManager &SM,
322                         const LangOptions &LangOpts,
323                         unsigned indent,
324                         unsigned depth,
325                         bool includeControlFlow) {
326   switch (P.getKind()) {
327     case PathDiagnosticPiece::ControlFlow:
328       if (includeControlFlow)
329         ReportControlFlow(o, cast<PathDiagnosticControlFlowPiece>(P), FM, SM,
330                           LangOpts, indent);
331       break;
332     case PathDiagnosticPiece::Call:
333       ReportCall(o, cast<PathDiagnosticCallPiece>(P), FM, SM, LangOpts,
334                  indent, depth);
335       break;
336     case PathDiagnosticPiece::Event:
337       ReportEvent(o, cast<PathDiagnosticSpotPiece>(P), FM, SM, LangOpts,
338                   indent, depth);
339       break;
340     case PathDiagnosticPiece::Macro:
341       ReportMacro(o, cast<PathDiagnosticMacroPiece>(P), FM, SM, LangOpts,
342                   indent, depth);
343       break;
344   }
345 }
346 
FlushDiagnosticsImpl(std::vector<const PathDiagnostic * > & Diags,SmallVectorImpl<std::string> * FilesMade)347 void PlistDiagnostics::FlushDiagnosticsImpl(
348                                     std::vector<const PathDiagnostic *> &Diags,
349                                     SmallVectorImpl<std::string> *FilesMade) {
350   // Build up a set of FIDs that we use by scanning the locations and
351   // ranges of the diagnostics.
352   FIDMap FM;
353   SmallVector<FileID, 10> Fids;
354   const SourceManager* SM = 0;
355 
356   if (!Diags.empty())
357     SM = &(*(*Diags.begin())->path.begin())->getLocation().getManager();
358 
359 
360   for (std::vector<const PathDiagnostic*>::iterator DI = Diags.begin(),
361        DE = Diags.end(); DI != DE; ++DI) {
362 
363     const PathDiagnostic *D = *DI;
364 
365     llvm::SmallVector<const PathPieces *, 5> WorkList;
366     WorkList.push_back(&D->path);
367 
368     while (!WorkList.empty()) {
369       const PathPieces &path = *WorkList.back();
370       WorkList.pop_back();
371 
372       for (PathPieces::const_iterator I = path.begin(), E = path.end();
373            I!=E; ++I) {
374         const PathDiagnosticPiece *piece = I->getPtr();
375         AddFID(FM, Fids, SM, piece->getLocation().asLocation());
376 
377         for (PathDiagnosticPiece::range_iterator RI = piece->ranges_begin(),
378              RE= piece->ranges_end(); RI != RE; ++RI) {
379           AddFID(FM, Fids, SM, RI->getBegin());
380           AddFID(FM, Fids, SM, RI->getEnd());
381         }
382 
383         if (const PathDiagnosticCallPiece *call =
384             dyn_cast<PathDiagnosticCallPiece>(piece)) {
385           WorkList.push_back(&call->path);
386         }
387         else if (const PathDiagnosticMacroPiece *macro =
388                  dyn_cast<PathDiagnosticMacroPiece>(piece)) {
389           WorkList.push_back(&macro->subPieces);
390         }
391       }
392     }
393   }
394 
395   // Open the file.
396   std::string ErrMsg;
397   llvm::raw_fd_ostream o(OutputFile.c_str(), ErrMsg);
398   if (!ErrMsg.empty()) {
399     llvm::errs() << "warning: could not create file: " << OutputFile << '\n';
400     return;
401   }
402 
403   // Write the plist header.
404   o << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
405   "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" "
406   "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
407   "<plist version=\"1.0\">\n";
408 
409   // Write the root object: a <dict> containing...
410   //  - "files", an <array> mapping from FIDs to file names
411   //  - "diagnostics", an <array> containing the path diagnostics
412   o << "<dict>\n"
413        " <key>files</key>\n"
414        " <array>\n";
415 
416   for (SmallVectorImpl<FileID>::iterator I=Fids.begin(), E=Fids.end();
417        I!=E; ++I) {
418     o << "  ";
419     EmitString(o, SM->getFileEntryForID(*I)->getName()) << '\n';
420   }
421 
422   o << " </array>\n"
423        " <key>diagnostics</key>\n"
424        " <array>\n";
425 
426   for (std::vector<const PathDiagnostic*>::iterator DI=Diags.begin(),
427        DE = Diags.end(); DI!=DE; ++DI) {
428 
429     o << "  <dict>\n"
430          "   <key>path</key>\n";
431 
432     const PathDiagnostic *D = *DI;
433 
434     o << "   <array>\n";
435 
436     for (PathPieces::const_iterator I = D->path.begin(), E = D->path.end();
437          I != E; ++I)
438       ReportDiag(o, **I, FM, *SM, LangOpts);
439 
440     o << "   </array>\n";
441 
442     // Output the bug type and bug category.
443     o << "   <key>description</key>";
444     EmitString(o, D->getDescription()) << '\n';
445     o << "   <key>category</key>";
446     EmitString(o, D->getCategory()) << '\n';
447     o << "   <key>type</key>";
448     EmitString(o, D->getBugType()) << '\n';
449 
450     // Output information about the semantic context where
451     // the issue occurred.
452     if (const Decl *DeclWithIssue = D->getDeclWithIssue()) {
453       // FIXME: handle blocks, which have no name.
454       if (const NamedDecl *ND = dyn_cast<NamedDecl>(DeclWithIssue)) {
455         StringRef declKind;
456         switch (ND->getKind()) {
457           case Decl::CXXRecord:
458             declKind = "C++ class";
459             break;
460           case Decl::CXXMethod:
461             declKind = "C++ method";
462             break;
463           case Decl::ObjCMethod:
464             declKind = "Objective-C method";
465             break;
466           case Decl::Function:
467             declKind = "function";
468             break;
469           default:
470             break;
471         }
472         if (!declKind.empty()) {
473           const std::string &declName = ND->getDeclName().getAsString();
474           o << "  <key>issue_context_kind</key>";
475           EmitString(o, declKind) << '\n';
476           o << "  <key>issue_context</key>";
477           EmitString(o, declName) << '\n';
478         }
479       }
480     }
481 
482     // Output the location of the bug.
483     o << "  <key>location</key>\n";
484     EmitLocation(o, *SM, LangOpts, D->getLocation(), FM, 2);
485 
486     // Output the diagnostic to the sub-diagnostic client, if any.
487     if (SubPD) {
488       std::vector<const PathDiagnostic *> SubDiags;
489       SubDiags.push_back(D);
490       SmallVector<std::string, 1> SubFilesMade;
491       SubPD->FlushDiagnosticsImpl(SubDiags, &SubFilesMade);
492 
493       if (!SubFilesMade.empty()) {
494         o << "  <key>" << SubPD->getName() << "_files</key>\n";
495         o << "  <array>\n";
496         for (size_t i = 0, n = SubFilesMade.size(); i < n ; ++i)
497           o << "   <string>" << SubFilesMade[i] << "</string>\n";
498         o << "  </array>\n";
499       }
500     }
501 
502     // Close up the entry.
503     o << "  </dict>\n";
504   }
505 
506   o << " </array>\n";
507 
508   // Finish.
509   o << "</dict>\n</plist>";
510 
511   if (FilesMade)
512     FilesMade->push_back(OutputFile);
513 }
514