Coverage Report

Created: 2020-11-24 06:42

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