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   public:
36     PlistDiagnostics(const std::string& prefix, const LangOptions &LangOpts,
37                      PathDiagnosticConsumer *subPD);
38 
39     virtual ~PlistDiagnostics() {}
40 
41     void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
42                               SmallVectorImpl<std::string> *FilesMade);
43 
44     virtual StringRef getName() const {
45       return "PlistDiagnostics";
46     }
47 
48     PathGenerationScheme getGenerationScheme() const;
49     bool supportsLogicalOpControlFlow() const { return true; }
50     bool supportsAllBlockEdges() const { return true; }
51     virtual bool useVerboseDescription() const { return false; }
52   };
53 } // end anonymous namespace
54 
55 PlistDiagnostics::PlistDiagnostics(const std::string& output,
56                                    const LangOptions &LO,
57                                    PathDiagnosticConsumer *subPD)
58   : OutputFile(output), LangOpts(LO), SubPD(subPD), flushed(false) {}
59 
60 PathDiagnosticConsumer*
61 ento::createPlistDiagnosticConsumer(const std::string& s, const Preprocessor &PP,
62                                   PathDiagnosticConsumer *subPD) {
63   return new PlistDiagnostics(s, PP.getLangOptions(), subPD);
64 }
65 
66 PathDiagnosticConsumer::PathGenerationScheme
67 PlistDiagnostics::getGenerationScheme() const {
68   if (const PathDiagnosticConsumer *PD = SubPD.get())
69     return PD->getGenerationScheme();
70 
71   return Extensive;
72 }
73 
74 static void AddFID(FIDMap &FIDs, SmallVectorImpl<FileID> &V,
75                    const SourceManager* SM, SourceLocation L) {
76 
77   FileID FID = SM->getFileID(SM->getExpansionLoc(L));
78   FIDMap::iterator I = FIDs.find(FID);
79   if (I != FIDs.end()) return;
80   FIDs[FID] = V.size();
81   V.push_back(FID);
82 }
83 
84 static unsigned GetFID(const FIDMap& FIDs, const SourceManager &SM,
85                        SourceLocation L) {
86   FileID FID = SM.getFileID(SM.getExpansionLoc(L));
87   FIDMap::const_iterator I = FIDs.find(FID);
88   assert(I != FIDs.end());
89   return I->second;
90 }
91 
92 static raw_ostream &Indent(raw_ostream &o, const unsigned indent) {
93   for (unsigned i = 0; i < indent; ++i) o << ' ';
94   return o;
95 }
96 
97 static void EmitLocation(raw_ostream &o, const SourceManager &SM,
98                          const LangOptions &LangOpts,
99                          SourceLocation L, const FIDMap &FM,
100                          unsigned indent, bool extend = false) {
101 
102   FullSourceLoc Loc(SM.getExpansionLoc(L), const_cast<SourceManager&>(SM));
103 
104   // Add in the length of the token, so that we cover multi-char tokens.
105   unsigned offset =
106     extend ? Lexer::MeasureTokenLength(Loc, SM, LangOpts) - 1 : 0;
107 
108   Indent(o, indent) << "<dict>\n";
109   Indent(o, indent) << " <key>line</key><integer>"
110                     << Loc.getExpansionLineNumber() << "</integer>\n";
111   Indent(o, indent) << " <key>col</key><integer>"
112                     << Loc.getExpansionColumnNumber() + offset << "</integer>\n";
113   Indent(o, indent) << " <key>file</key><integer>"
114                     << GetFID(FM, SM, Loc) << "</integer>\n";
115   Indent(o, indent) << "</dict>\n";
116 }
117 
118 static void EmitLocation(raw_ostream &o, const SourceManager &SM,
119                          const LangOptions &LangOpts,
120                          const PathDiagnosticLocation &L, const FIDMap& FM,
121                          unsigned indent, bool extend = false) {
122   EmitLocation(o, SM, LangOpts, L.asLocation(), FM, indent, extend);
123 }
124 
125 static void EmitRange(raw_ostream &o, const SourceManager &SM,
126                       const LangOptions &LangOpts,
127                       PathDiagnosticRange R, const FIDMap &FM,
128                       unsigned indent) {
129   Indent(o, indent) << "<array>\n";
130   EmitLocation(o, SM, LangOpts, R.getBegin(), FM, indent+1);
131   EmitLocation(o, SM, LangOpts, R.getEnd(), FM, indent+1, !R.isPoint);
132   Indent(o, indent) << "</array>\n";
133 }
134 
135 static raw_ostream &EmitString(raw_ostream &o,
136                                      const std::string& s) {
137   o << "<string>";
138   for (std::string::const_iterator I=s.begin(), E=s.end(); I!=E; ++I) {
139     char c = *I;
140     switch (c) {
141     default:   o << c; break;
142     case '&':  o << "&amp;"; break;
143     case '<':  o << "&lt;"; break;
144     case '>':  o << "&gt;"; break;
145     case '\'': o << "&apos;"; break;
146     case '\"': o << "&quot;"; break;
147     }
148   }
149   o << "</string>";
150   return o;
151 }
152 
153 static void ReportControlFlow(raw_ostream &o,
154                               const PathDiagnosticControlFlowPiece& P,
155                               const FIDMap& FM,
156                               const SourceManager &SM,
157                               const LangOptions &LangOpts,
158                               unsigned indent) {
159 
160   Indent(o, indent) << "<dict>\n";
161   ++indent;
162 
163   Indent(o, indent) << "<key>kind</key><string>control</string>\n";
164 
165   // Emit edges.
166   Indent(o, indent) << "<key>edges</key>\n";
167   ++indent;
168   Indent(o, indent) << "<array>\n";
169   ++indent;
170   for (PathDiagnosticControlFlowPiece::const_iterator I=P.begin(), E=P.end();
171        I!=E; ++I) {
172     Indent(o, indent) << "<dict>\n";
173     ++indent;
174     Indent(o, indent) << "<key>start</key>\n";
175     EmitRange(o, SM, LangOpts, I->getStart().asRange(), FM, indent+1);
176     Indent(o, indent) << "<key>end</key>\n";
177     EmitRange(o, SM, LangOpts, I->getEnd().asRange(), FM, indent+1);
178     --indent;
179     Indent(o, indent) << "</dict>\n";
180   }
181   --indent;
182   Indent(o, indent) << "</array>\n";
183   --indent;
184 
185   // Output any helper text.
186   const std::string& s = P.getString();
187   if (!s.empty()) {
188     Indent(o, indent) << "<key>alternate</key>";
189     EmitString(o, s) << '\n';
190   }
191 
192   --indent;
193   Indent(o, indent) << "</dict>\n";
194 }
195 
196 static void ReportEvent(raw_ostream &o, const PathDiagnosticPiece& P,
197                         const FIDMap& FM,
198                         const SourceManager &SM,
199                         const LangOptions &LangOpts,
200                         unsigned indent) {
201 
202   Indent(o, indent) << "<dict>\n";
203   ++indent;
204 
205   Indent(o, indent) << "<key>kind</key><string>event</string>\n";
206 
207   // Output the location.
208   FullSourceLoc L = P.getLocation().asLocation();
209 
210   Indent(o, indent) << "<key>location</key>\n";
211   EmitLocation(o, SM, LangOpts, L, FM, indent);
212 
213   // Output the ranges (if any).
214   PathDiagnosticPiece::range_iterator RI = P.ranges_begin(),
215   RE = P.ranges_end();
216 
217   if (RI != RE) {
218     Indent(o, indent) << "<key>ranges</key>\n";
219     Indent(o, indent) << "<array>\n";
220     ++indent;
221     for (; RI != RE; ++RI)
222       EmitRange(o, SM, LangOpts, *RI, FM, indent+1);
223     --indent;
224     Indent(o, indent) << "</array>\n";
225   }
226 
227   // Output the text.
228   assert(!P.getString().empty());
229   Indent(o, indent) << "<key>extended_message</key>\n";
230   Indent(o, indent);
231   EmitString(o, P.getString()) << '\n';
232 
233   // Output the short text.
234   // FIXME: Really use a short string.
235   Indent(o, indent) << "<key>message</key>\n";
236   EmitString(o, P.getString()) << '\n';
237 
238   // Finish up.
239   --indent;
240   Indent(o, indent); o << "</dict>\n";
241 }
242 
243 static void ReportMacro(raw_ostream &o,
244                         const PathDiagnosticMacroPiece& P,
245                         const FIDMap& FM, const SourceManager &SM,
246                         const LangOptions &LangOpts,
247                         unsigned indent) {
248 
249   for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
250        I!=E; ++I) {
251 
252     switch ((*I)->getKind()) {
253     default:
254       break;
255     case PathDiagnosticPiece::Event:
256       ReportEvent(o, cast<PathDiagnosticEventPiece>(**I), FM, SM, LangOpts,
257                   indent);
258       break;
259     case PathDiagnosticPiece::Macro:
260       ReportMacro(o, cast<PathDiagnosticMacroPiece>(**I), FM, SM, LangOpts,
261                   indent);
262       break;
263     }
264   }
265 }
266 
267 static void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P,
268                        const FIDMap& FM, const SourceManager &SM,
269                        const LangOptions &LangOpts) {
270 
271   unsigned indent = 4;
272 
273   switch (P.getKind()) {
274   case PathDiagnosticPiece::ControlFlow:
275     ReportControlFlow(o, cast<PathDiagnosticControlFlowPiece>(P), FM, SM,
276                       LangOpts, indent);
277     break;
278   case PathDiagnosticPiece::CallEnter:
279   case PathDiagnosticPiece::CallExit:
280   case PathDiagnosticPiece::Event:
281     ReportEvent(o, cast<PathDiagnosticSpotPiece>(P), FM, SM, LangOpts,
282                 indent);
283     break;
284   case PathDiagnosticPiece::Macro:
285     ReportMacro(o, cast<PathDiagnosticMacroPiece>(P), FM, SM, LangOpts,
286                 indent);
287     break;
288   }
289 }
290 
291 void PlistDiagnostics::FlushDiagnosticsImpl(
292                                     std::vector<const PathDiagnostic *> &Diags,
293                                     SmallVectorImpl<std::string> *FilesMade) {
294   // Build up a set of FIDs that we use by scanning the locations and
295   // ranges of the diagnostics.
296   FIDMap FM;
297   SmallVector<FileID, 10> Fids;
298   const SourceManager* SM = 0;
299 
300   if (!Diags.empty())
301     SM = &(*(*Diags.begin())->path.begin())->getLocation().getManager();
302 
303   for (std::vector<const PathDiagnostic*>::iterator DI = Diags.begin(),
304        DE = Diags.end(); DI != DE; ++DI) {
305 
306     const PathDiagnostic *D = *DI;
307 
308     for (PathPieces::const_iterator I = D->path.begin(), E = D->path.end();
309          I!=E; ++I) {
310       AddFID(FM, Fids, SM, (*I)->getLocation().asLocation());
311 
312       for (PathDiagnosticPiece::range_iterator RI = (*I)->ranges_begin(),
313            RE= (*I)->ranges_end(); RI != RE; ++RI) {
314         AddFID(FM, Fids, SM, RI->getBegin());
315         AddFID(FM, Fids, SM, RI->getEnd());
316       }
317     }
318   }
319 
320   // Open the file.
321   std::string ErrMsg;
322   llvm::raw_fd_ostream o(OutputFile.c_str(), ErrMsg);
323   if (!ErrMsg.empty()) {
324     llvm::errs() << "warning: could not create file: " << OutputFile << '\n';
325     return;
326   }
327 
328   // Write the plist header.
329   o << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
330   "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" "
331   "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
332   "<plist version=\"1.0\">\n";
333 
334   // Write the root object: a <dict> containing...
335   //  - "files", an <array> mapping from FIDs to file names
336   //  - "diagnostics", an <array> containing the path diagnostics
337   o << "<dict>\n"
338        " <key>files</key>\n"
339        " <array>\n";
340 
341   for (SmallVectorImpl<FileID>::iterator I=Fids.begin(), E=Fids.end();
342        I!=E; ++I) {
343     o << "  ";
344     EmitString(o, SM->getFileEntryForID(*I)->getName()) << '\n';
345   }
346 
347   o << " </array>\n"
348        " <key>diagnostics</key>\n"
349        " <array>\n";
350 
351   for (std::vector<const PathDiagnostic*>::iterator DI=Diags.begin(),
352        DE = Diags.end(); DI!=DE; ++DI) {
353 
354     o << "  <dict>\n"
355          "   <key>path</key>\n";
356 
357     const PathDiagnostic *D = *DI;
358 
359     o << "   <array>\n";
360 
361     for (PathPieces::const_iterator I = D->path.begin(), E = D->path.end();
362          I != E; ++I)
363       ReportDiag(o, **I, FM, *SM, LangOpts);
364 
365     o << "   </array>\n";
366 
367     // Output the bug type and bug category.
368     o << "   <key>description</key>";
369     EmitString(o, D->getDescription()) << '\n';
370     o << "   <key>category</key>";
371     EmitString(o, D->getCategory()) << '\n';
372     o << "   <key>type</key>";
373     EmitString(o, D->getBugType()) << '\n';
374 
375     // Output the location of the bug.
376     o << "  <key>location</key>\n";
377     EmitLocation(o, *SM, LangOpts, D->getLocation(), FM, 2);
378 
379     // Output the diagnostic to the sub-diagnostic client, if any.
380     if (SubPD) {
381       std::vector<const PathDiagnostic *> SubDiags;
382       SubDiags.push_back(D);
383       SmallVector<std::string, 1> SubFilesMade;
384       SubPD->FlushDiagnosticsImpl(SubDiags, &SubFilesMade);
385 
386       if (!SubFilesMade.empty()) {
387         o << "  <key>" << SubPD->getName() << "_files</key>\n";
388         o << "  <array>\n";
389         for (size_t i = 0, n = SubFilesMade.size(); i < n ; ++i)
390           o << "   <string>" << SubFilesMade[i] << "</string>\n";
391         o << "  </array>\n";
392       }
393     }
394 
395     // Close up the entry.
396     o << "  </dict>\n";
397   }
398 
399   o << " </array>\n";
400 
401   // Finish.
402   o << "</dict>\n</plist>";
403 
404   if (FilesMade)
405     FilesMade->push_back(OutputFile);
406 }
407