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     llvm::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 (PathDiagnosticMacroPiece::const_iterator I=P.begin(), E=P.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::Event:
279     ReportEvent(o, cast<PathDiagnosticEventPiece>(P), FM, SM, LangOpts,
280                 indent);
281     break;
282   case PathDiagnosticPiece::Macro:
283     ReportMacro(o, cast<PathDiagnosticMacroPiece>(P), FM, SM, LangOpts,
284                 indent);
285     break;
286   }
287 }
288 
289 void PlistDiagnostics::FlushDiagnosticsImpl(
290                                     std::vector<const PathDiagnostic *> &Diags,
291                                     SmallVectorImpl<std::string> *FilesMade) {
292   // Build up a set of FIDs that we use by scanning the locations and
293   // ranges of the diagnostics.
294   FIDMap FM;
295   SmallVector<FileID, 10> Fids;
296   const SourceManager* SM = 0;
297 
298   if (!Diags.empty())
299     SM = &(*Diags.begin())->begin()->getLocation().getManager();
300 
301   for (std::vector<const PathDiagnostic*>::iterator DI = Diags.begin(),
302        DE = Diags.end(); DI != DE; ++DI) {
303 
304     const PathDiagnostic *D = *DI;
305 
306     for (PathDiagnostic::const_iterator I=D->begin(), E=D->end(); I!=E; ++I) {
307       AddFID(FM, Fids, SM, I->getLocation().asLocation());
308 
309       for (PathDiagnosticPiece::range_iterator RI=I->ranges_begin(),
310            RE=I->ranges_end(); RI!=RE; ++RI) {
311         AddFID(FM, Fids, SM, RI->getBegin());
312         AddFID(FM, Fids, SM, RI->getEnd());
313       }
314     }
315   }
316 
317   // Open the file.
318   std::string ErrMsg;
319   llvm::raw_fd_ostream o(OutputFile.c_str(), ErrMsg);
320   if (!ErrMsg.empty()) {
321     llvm::errs() << "warning: could not create file: " << OutputFile << '\n';
322     return;
323   }
324 
325   // Write the plist header.
326   o << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
327   "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" "
328   "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
329   "<plist version=\"1.0\">\n";
330 
331   // Write the root object: a <dict> containing...
332   //  - "files", an <array> mapping from FIDs to file names
333   //  - "diagnostics", an <array> containing the path diagnostics
334   o << "<dict>\n"
335        " <key>files</key>\n"
336        " <array>\n";
337 
338   for (SmallVectorImpl<FileID>::iterator I=Fids.begin(), E=Fids.end();
339        I!=E; ++I) {
340     o << "  ";
341     EmitString(o, SM->getFileEntryForID(*I)->getName()) << '\n';
342   }
343 
344   o << " </array>\n"
345        " <key>diagnostics</key>\n"
346        " <array>\n";
347 
348   for (std::vector<const PathDiagnostic*>::iterator DI=Diags.begin(),
349        DE = Diags.end(); DI!=DE; ++DI) {
350 
351     o << "  <dict>\n"
352          "   <key>path</key>\n";
353 
354     const PathDiagnostic *D = *DI;
355 
356     o << "   <array>\n";
357 
358     for (PathDiagnostic::const_iterator I=D->begin(), E=D->end(); I != E; ++I)
359       ReportDiag(o, *I, FM, *SM, LangOpts);
360 
361     o << "   </array>\n";
362 
363     // Output the bug type and bug category.
364     o << "   <key>description</key>";
365     EmitString(o, D->getDescription()) << '\n';
366     o << "   <key>category</key>";
367     EmitString(o, D->getCategory()) << '\n';
368     o << "   <key>type</key>";
369     EmitString(o, D->getBugType()) << '\n';
370 
371     // Output the location of the bug.
372     o << "  <key>location</key>\n";
373     EmitLocation(o, *SM, LangOpts, D->getLocation(), FM, 2);
374 
375     // Output the diagnostic to the sub-diagnostic client, if any.
376     if (SubPD) {
377       std::vector<const PathDiagnostic *> SubDiags;
378       SubDiags.push_back(D);
379       SmallVector<std::string, 1> SubFilesMade;
380       SubPD->FlushDiagnosticsImpl(SubDiags, &SubFilesMade);
381 
382       if (!SubFilesMade.empty()) {
383         o << "  <key>" << SubPD->getName() << "_files</key>\n";
384         o << "  <array>\n";
385         for (size_t i = 0, n = SubFilesMade.size(); i < n ; ++i)
386           o << "   <string>" << SubFilesMade[i] << "</string>\n";
387         o << "  </array>\n";
388       }
389     }
390 
391     // Close up the entry.
392     o << "  </dict>\n";
393   }
394 
395   o << " </array>\n";
396 
397   // Finish.
398   o << "</dict>\n</plist>";
399 
400   if (FilesMade)
401     FilesMade->push_back(OutputFile);
402 }
403