Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SarifDiagnostics.cpp - Sarif Diagnostics for Paths -----*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file defines the SarifDiagnostics object.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Analysis/PathDiagnostic.h"
14
#include "clang/Basic/Version.h"
15
#include "clang/Lex/Preprocessor.h"
16
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
17
#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
18
#include "llvm/ADT/STLExtras.h"
19
#include "llvm/ADT/StringMap.h"
20
#include "llvm/Support/ConvertUTF.h"
21
#include "llvm/Support/JSON.h"
22
#include "llvm/Support/Path.h"
23
24
using namespace llvm;
25
using namespace clang;
26
using namespace ento;
27
28
namespace {
29
class SarifDiagnostics : public PathDiagnosticConsumer {
30
  std::string OutputFile;
31
  const LangOptions &LO;
32
33
public:
34
  SarifDiagnostics(AnalyzerOptions &, const std::string &Output,
35
                   const LangOptions &LO)
36
2
      : OutputFile(Output), LO(LO) {}
37
2
  ~SarifDiagnostics() override = default;
38
39
  void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
40
                            FilesMade *FM) override;
41
42
0
  StringRef getName() const override { return "SarifDiagnostics"; }
43
162
  PathGenerationScheme getGenerationScheme() const override { return Minimal; }
44
0
  bool supportsLogicalOpControlFlow() const override { return true; }
45
6
  bool supportsCrossFileDiagnostics() const override { return true; }
46
};
47
} // end anonymous namespace
48
49
void ento::createSarifDiagnosticConsumer(
50
    AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
51
    const std::string &Output, const Preprocessor &PP,
52
2
    const cross_tu::CrossTranslationUnitContext &) {
53
2
  C.push_back(new SarifDiagnostics(AnalyzerOpts, Output, PP.getLangOpts()));
54
2
}
55
56
24
static StringRef getFileName(const FileEntry &FE) {
57
24
  StringRef Filename = FE.tryGetRealPathName();
58
24
  if (Filename.empty())
59
0
    Filename = FE.getName();
60
24
  return Filename;
61
24
}
62
63
2.59k
static std::string percentEncodeURICharacter(char C) {
64
2.59k
  // RFC 3986 claims alpha, numeric, and this handful of
65
2.59k
  // characters are not reserved for the path component and
66
2.59k
  // should be written out directly. Otherwise, percent
67
2.59k
  // encode the character and write that out instead of the
68
2.59k
  // reserved character.
69
2.59k
  if (llvm::isAlnum(C) ||
70
2.59k
      
StringRef::npos != StringRef("-._~:@!$&'()*+,;=").find(C)120
)
71
2.59k
    return std::string(&C, 1);
72
0
  return "%" + llvm::toHex(StringRef(&C, 1));
73
0
}
74
75
24
static std::string fileNameToURI(StringRef Filename) {
76
24
  llvm::SmallString<32> Ret = StringRef("file://");
77
24
78
24
  // Get the root name to see if it has a URI authority.
79
24
  StringRef Root = sys::path::root_name(Filename);
80
24
  if (Root.startswith("//")) {
81
0
    // There is an authority, so add it to the URI.
82
0
    Ret += Root.drop_front(2).str();
83
24
  } else if (!Root.empty()) {
84
0
    // There is no authority, so end the component and add the root to the URI.
85
0
    Ret += Twine("/" + Root).str();
86
0
  }
87
24
88
24
  auto Iter = sys::path::begin(Filename), End = sys::path::end(Filename);
89
24
  assert(Iter != End && "Expected there to be a non-root path component.");
90
24
  // Add the rest of the path components, encoding any reserved characters;
91
24
  // we skip past the first path component, as it was handled it above.
92
264
  std::for_each(++Iter, End, [&Ret](StringRef Component) {
93
264
    // For reasons unknown to me, we may get a backslash with Windows native
94
264
    // paths for the initial backslash following the drive component, which
95
264
    // we need to ignore as a URI path part.
96
264
    if (Component == "\\")
97
0
      return;
98
264
99
264
    // Add the separator between the previous path part and the one being
100
264
    // currently processed.
101
264
    Ret += "/";
102
264
103
264
    // URI encode the part.
104
2.59k
    for (char C : Component) {
105
2.59k
      Ret += percentEncodeURICharacter(C);
106
2.59k
    }
107
264
  });
108
24
109
24
  return std::string(Ret);
110
24
}
111
112
2
static json::Object createArtifactLocation(const FileEntry &FE) {
113
2
  return json::Object{{"uri", fileNameToURI(getFileName(FE))}};
114
2
}
115
116
2
static json::Object createArtifact(const FileEntry &FE) {
117
2
  return json::Object{{"location", createArtifactLocation(FE)},
118
2
                      {"roles", json::Array{"resultFile"}},
119
2
                      {"length", FE.getSize()},
120
2
                      {"mimeType", "text/plain"}};
121
2
}
122
123
static json::Object createArtifactLocation(const FileEntry &FE,
124
22
                                           json::Array &Artifacts) {
125
22
  std::string FileURI = fileNameToURI(getFileName(FE));
126
22
127
22
  // See if the Artifacts array contains this URI already. If it does not,
128
22
  // create a new artifact object to add to the array.
129
22
  auto I = llvm::find_if(Artifacts, [&](const json::Value &File) {
130
20
    if (const json::Object *Obj = File.getAsObject()) {
131
20
      if (const json::Object *FileLoc = Obj->getObject("location")) {
132
20
        Optional<StringRef> URI = FileLoc->getString("uri");
133
20
        return URI && URI->equals(FileURI);
134
20
      }
135
0
    }
136
0
    return false;
137
0
  });
138
22
139
22
  // Calculate the index within the artifact array so it can be stored in
140
22
  // the JSON object.
141
22
  auto Index = static_cast<unsigned>(std::distance(Artifacts.begin(), I));
142
22
  if (I == Artifacts.end())
143
2
    Artifacts.push_back(createArtifact(FE));
144
22
145
22
  return json::Object{{"uri", FileURI}, {"index", Index}};
146
22
}
147
148
static unsigned int adjustColumnPos(const SourceManager &SM, SourceLocation Loc,
149
44
                                    unsigned int TokenLen = 0) {
150
44
  assert(!Loc.isInvalid() && "invalid Loc when adjusting column position");
151
44
152
44
  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedExpansionLoc(Loc);
153
44
  assert(LocInfo.second > SM.getExpansionColumnNumber(Loc) &&
154
44
         "position in file is before column number?");
155
44
156
44
  bool InvalidBuffer = false;
157
44
  const MemoryBuffer *Buf = SM.getBuffer(LocInfo.first, &InvalidBuffer);
158
44
  assert(!InvalidBuffer && "got an invalid buffer for the location's file");
159
44
  assert(Buf->getBufferSize() >= (LocInfo.second + TokenLen) &&
160
44
         "token extends past end of buffer?");
161
44
162
44
  // Adjust the offset to be the start of the line, since we'll be counting
163
44
  // Unicode characters from there until our column offset.
164
44
  unsigned int Off = LocInfo.second - (SM.getExpansionColumnNumber(Loc) - 1);
165
44
  unsigned int Ret = 1;
166
471
  while (Off < (LocInfo.second + TokenLen)) {
167
427
    Off += getNumBytesForUTF8(Buf->getBuffer()[Off]);
168
427
    Ret++;
169
427
  }
170
44
171
44
  return Ret;
172
44
}
173
174
static json::Object createTextRegion(const LangOptions &LO, SourceRange R,
175
22
                                     const SourceManager &SM) {
176
22
  json::Object Region{
177
22
      {"startLine", SM.getExpansionLineNumber(R.getBegin())},
178
22
      {"startColumn", adjustColumnPos(SM, R.getBegin())},
179
22
  };
180
22
  if (R.getBegin() == R.getEnd()) {
181
8
    Region["endColumn"] = adjustColumnPos(SM, R.getBegin());
182
14
  } else {
183
14
    Region["endLine"] = SM.getExpansionLineNumber(R.getEnd());
184
14
    Region["endColumn"] = adjustColumnPos(
185
14
        SM, R.getEnd(),
186
14
        Lexer::MeasureTokenLength(R.getEnd(), SM, LO));
187
14
  }
188
22
  return Region;
189
22
}
190
191
static json::Object createPhysicalLocation(const LangOptions &LO,
192
                                           SourceRange R, const FileEntry &FE,
193
                                           const SourceManager &SMgr,
194
22
                                           json::Array &Artifacts) {
195
22
  return json::Object{
196
22
      {{"artifactLocation", createArtifactLocation(FE, Artifacts)},
197
22
       {"region", createTextRegion(LO, R, SMgr)}}};
198
22
}
199
200
enum class Importance { Important, Essential, Unimportant };
201
202
16
static StringRef importanceToStr(Importance I) {
203
16
  switch (I) {
204
2
  case Importance::Important:
205
2
    return "important";
206
12
  case Importance::Essential:
207
12
    return "essential";
208
2
  case Importance::Unimportant:
209
2
    return "unimportant";
210
0
  }
211
0
  llvm_unreachable("Fully covered switch is not so fully covered");
212
0
}
213
214
static json::Object createThreadFlowLocation(json::Object &&Location,
215
16
                                             Importance I) {
216
16
  return json::Object{{"location", std::move(Location)},
217
16
                      {"importance", importanceToStr(I)}};
218
16
}
219
220
27
static json::Object createMessage(StringRef Text) {
221
27
  return json::Object{{"text", Text.str()}};
222
27
}
223
224
static json::Object createLocation(json::Object &&PhysicalLocation,
225
22
                                   StringRef Message = "") {
226
22
  json::Object Ret{{"physicalLocation", std::move(PhysicalLocation)}};
227
22
  if (!Message.empty())
228
16
    Ret.insert({"message", createMessage(Message)});
229
22
  return Ret;
230
22
}
231
232
16
static Importance calculateImportance(const PathDiagnosticPiece &Piece) {
233
16
  switch (Piece.getKind()) {
234
0
  case PathDiagnosticPiece::Call:
235
0
  case PathDiagnosticPiece::Macro:
236
0
  case PathDiagnosticPiece::Note:
237
0
  case PathDiagnosticPiece::PopUp:
238
0
    // FIXME: What should be reported here?
239
0
    break;
240
14
  case PathDiagnosticPiece::Event:
241
14
    return Piece.getTagStr() == "ConditionBRVisitor" ? 
Importance::Important2
242
14
                                                     : 
Importance::Essential12
;
243
2
  case PathDiagnosticPiece::ControlFlow:
244
2
    return Importance::Unimportant;
245
0
  }
246
0
  return Importance::Unimportant;
247
0
}
248
249
static json::Object createThreadFlow(const LangOptions &LO,
250
                                     const PathPieces &Pieces,
251
6
                                     json::Array &Artifacts) {
252
6
  const SourceManager &SMgr = Pieces.front()->getLocation().getManager();
253
6
  json::Array Locations;
254
16
  for (const auto &Piece : Pieces) {
255
16
    const PathDiagnosticLocation &P = Piece->getLocation();
256
16
    Locations.push_back(createThreadFlowLocation(
257
16
        createLocation(createPhysicalLocation(
258
16
                           LO, P.asRange(),
259
16
                           *P.asLocation().getExpansionLoc().getFileEntry(),
260
16
                           SMgr, Artifacts),
261
16
                       Piece->getString()),
262
16
        calculateImportance(*Piece)));
263
16
  }
264
6
  return json::Object{{"locations", std::move(Locations)}};
265
6
}
266
267
static json::Object createCodeFlow(const LangOptions &LO,
268
                                   const PathPieces &Pieces,
269
6
                                   json::Array &Artifacts) {
270
6
  return json::Object{
271
6
      {"threadFlows", json::Array{createThreadFlow(LO, Pieces, Artifacts)}}};
272
6
}
273
274
static json::Object createResult(const LangOptions &LO,
275
                                 const PathDiagnostic &Diag,
276
                                 json::Array &Artifacts,
277
6
                                 const StringMap<unsigned> &RuleMapping) {
278
6
  const PathPieces &Path = Diag.path.flatten(false);
279
6
  const SourceManager &SMgr = Path.front()->getLocation().getManager();
280
6
281
6
  auto Iter = RuleMapping.find(Diag.getCheckerName());
282
6
  assert(Iter != RuleMapping.end() && "Rule ID is not in the array index map?");
283
6
284
6
  return json::Object{
285
6
      {"message", createMessage(Diag.getVerboseDescription())},
286
6
      {"codeFlows", json::Array{createCodeFlow(LO, Path, Artifacts)}},
287
6
      {"locations",
288
6
       json::Array{createLocation(createPhysicalLocation(
289
6
           LO, Diag.getLocation().asRange(),
290
6
           *Diag.getLocation().asLocation().getExpansionLoc().getFileEntry(),
291
6
           SMgr, Artifacts))}},
292
6
      {"ruleIndex", Iter->getValue()},
293
6
      {"ruleId", Diag.getCheckerName()}};
294
6
}
295
296
5
static StringRef getRuleDescription(StringRef CheckName) {
297
5
  return llvm::StringSwitch<StringRef>(CheckName)
298
5
#define GET_CHECKERS
299
5
#define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN)                 \
300
885
  .Case(FULLNAME, HELPTEXT)
301
5
#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
302
5
#undef CHECKER
303
5
#undef GET_CHECKERS
304
5
      ;
305
5
}
306
307
5
static StringRef getRuleHelpURIStr(StringRef CheckName) {
308
5
  return llvm::StringSwitch<StringRef>(CheckName)
309
5
#define GET_CHECKERS
310
5
#define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN)                 \
311
885
  .Case(FULLNAME, DOC_URI)
312
5
#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
313
5
#undef CHECKER
314
5
#undef GET_CHECKERS
315
5
      ;
316
5
}
317
318
5
static json::Object createRule(const PathDiagnostic &Diag) {
319
5
  StringRef CheckName = Diag.getCheckerName();
320
5
  json::Object Ret{
321
5
      {"fullDescription", createMessage(getRuleDescription(CheckName))},
322
5
      {"name", CheckName},
323
5
      {"id", CheckName}};
324
5
325
5
  std::string RuleURI = std::string(getRuleHelpURIStr(CheckName));
326
5
  if (!RuleURI.empty())
327
3
    Ret["helpUri"] = RuleURI;
328
5
329
5
  return Ret;
330
5
}
331
332
static json::Array createRules(std::vector<const PathDiagnostic *> &Diags,
333
2
                               StringMap<unsigned> &RuleMapping) {
334
2
  json::Array Rules;
335
2
  llvm::StringSet<> Seen;
336
2
337
6
  llvm::for_each(Diags, [&](const PathDiagnostic *D) {
338
6
    StringRef RuleID = D->getCheckerName();
339
6
    std::pair<llvm::StringSet<>::iterator, bool> P = Seen.insert(RuleID);
340
6
    if (P.second) {
341
5
      RuleMapping[RuleID] = Rules.size(); // Maps RuleID to an Array Index.
342
5
      Rules.push_back(createRule(*D));
343
5
    }
344
6
  });
345
2
346
2
  return Rules;
347
2
}
348
349
static json::Object createTool(std::vector<const PathDiagnostic *> &Diags,
350
2
                               StringMap<unsigned> &RuleMapping) {
351
2
  return json::Object{
352
2
      {"driver", json::Object{{"name", "clang"},
353
2
                              {"fullName", "clang static analyzer"},
354
2
                              {"language", "en-US"},
355
2
                              {"version", getClangFullVersion()},
356
2
                              {"rules", createRules(Diags, RuleMapping)}}}};
357
2
}
358
359
static json::Object createRun(const LangOptions &LO,
360
2
                              std::vector<const PathDiagnostic *> &Diags) {
361
2
  json::Array Results, Artifacts;
362
2
  StringMap<unsigned> RuleMapping;
363
2
  json::Object Tool = createTool(Diags, RuleMapping);
364
2
  
365
6
  llvm::for_each(Diags, [&](const PathDiagnostic *D) {
366
6
    Results.push_back(createResult(LO, *D, Artifacts, RuleMapping));
367
6
  });
368
2
369
2
  return json::Object{{"tool", std::move(Tool)},
370
2
                      {"results", std::move(Results)},
371
2
                      {"artifacts", std::move(Artifacts)},
372
2
                      {"columnKind", "unicodeCodePoints"}};
373
2
}
374
375
void SarifDiagnostics::FlushDiagnosticsImpl(
376
2
    std::vector<const PathDiagnostic *> &Diags, FilesMade *) {
377
2
  // We currently overwrite the file if it already exists. However, it may be
378
2
  // useful to add a feature someday that allows the user to append a run to an
379
2
  // existing SARIF file. One danger from that approach is that the size of the
380
2
  // file can become large very quickly, so decoding into JSON to append a run
381
2
  // may be an expensive operation.
382
2
  std::error_code EC;
383
2
  llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::OF_Text);
384
2
  if (EC) {
385
0
    llvm::errs() << "warning: could not create file: " << EC.message() << '\n';
386
0
    return;
387
0
  }
388
2
  json::Object Sarif{
389
2
      {"$schema",
390
2
       "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json"},
391
2
      {"version", "2.1.0"},
392
2
      {"runs", json::Array{createRun(LO, Diags)}}};
393
2
  OS << llvm::formatv("{0:2}\n", json::Value(std::move(Sarif)));
394
2
}