clang 24.0.0git
Sarif.cpp
Go to the documentation of this file.
1//===-- clang/Basic/Sarif.cpp - SarifDocumentWriter class definition ------===//
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/// \file
10/// This file contains the declaration of the SARIFDocumentWriter class, and
11/// associated builders such as:
12/// - \ref SarifArtifact
13/// - \ref SarifArtifactLocation
14/// - \ref SarifRule
15/// - \ref SarifResult
16//===----------------------------------------------------------------------===//
17#include "clang/Basic/Sarif.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/ConvertUTF.h"
24#include "llvm/Support/JSON.h"
25#include "llvm/Support/Path.h"
26
27#include <optional>
28#include <string>
29#include <utility>
30
31using namespace clang;
32using namespace llvm;
33
36
37static StringRef getFileName(FileEntryRef FE) {
38 StringRef Filename = FE.getFileEntry().tryGetRealPathName();
39 if (Filename.empty())
40 Filename = FE.getName();
41 return Filename;
42}
43/// \name URI
44/// @{
45
46/// \internal
47/// \brief
48/// Return the RFC3986 encoding of the input character.
49///
50/// \param C Character to encode to RFC3986.
51///
52/// \return The RFC3986 representation of \c C.
53static std::string percentEncodeURICharacter(char C) {
54 // RFC 3986 claims alpha, numeric, and this handful of
55 // characters are not reserved for the path component and
56 // should be written out directly. Otherwise, percent
57 // encode the character and write that out instead of the
58 // reserved character.
59 if (llvm::isAlnum(C) || StringRef("-._~:@!$&'()*+,;=").contains(C))
60 return std::string(&C, 1);
61 return "%" + llvm::toHex(StringRef(&C, 1));
62}
63
64/// \internal
65/// \brief Return a URI representing the given file name.
66///
67/// \param Filename The filename to be represented as URI.
68///
69/// \return RFC3986 URI representing the input file name.
70std::string SarifDocumentWriter::fileNameToURI(StringRef Filename) {
71 SmallString<32> Ret = StringRef("file://");
72
73 // Get the root name to see if it has a URI authority.
74 StringRef Root = sys::path::root_name(Filename);
75 if (Root.starts_with("//")) {
76 // There is an authority, so add it to the URI.
77 Ret += Root.drop_front(2).str();
78 } else if (!Root.empty()) {
79 // There is no authority, so end the component and add the root to the URI.
80 Ret += Twine("/" + Root).str();
81 }
82
83 auto Iter = sys::path::begin(Filename), End = sys::path::end(Filename);
84 assert(Iter != End && "Expected there to be a non-root path component.");
85 // Add the rest of the path components, encoding any reserved characters;
86 // we skip past the first path component, as it was handled it above.
87 for (StringRef Component : llvm::make_range(++Iter, End)) {
88 // For reasons unknown to me, we may get a backslash with Windows native
89 // paths for the initial backslash following the drive component, which
90 // we need to ignore as a URI path part.
91 if (Component == "\\")
92 continue;
93
94 // Add the separator between the previous path part and the one being
95 // currently processed.
96 Ret += "/";
97
98 // URI encode the part.
99 for (char C : Component) {
101 }
102 }
103
104 return std::string(Ret);
105}
106/// @}
107
108/// \brief Calculate the column position expressed in the number of UTF-8 code
109/// points from column start to the source location
110///
111/// \param Loc The source location whose column needs to be calculated.
112/// \param TokenLen Optional hint for when the token is multiple bytes long.
113///
114/// \return The column number as a UTF-8 aware byte offset from column start to
115/// the effective source location.
116static unsigned int adjustColumnPos(FullSourceLoc Loc,
117 unsigned int TokenLen = 0) {
118 assert(!Loc.isInvalid() && "invalid Loc when adjusting column position");
119
121 std::optional<MemoryBufferRef> Buf =
122 Loc.getManager().getBufferOrNone(LocInfo.first);
123 assert(Buf && "got an invalid buffer for the location's file");
124 assert(Buf->getBufferSize() >= (LocInfo.second + TokenLen) &&
125 "token extends past end of buffer?");
126
127 // Adjust the offset to be the start of the line, since we'll be counting
128 // Unicode characters from there until our column offset.
129 unsigned int Off = LocInfo.second - (Loc.getExpansionColumnNumber() - 1);
130 unsigned int Ret = 1;
131 while (Off < (LocInfo.second + TokenLen)) {
132 Off += getNumBytesForUTF8(Buf->getBuffer()[Off]);
133 Ret++;
134 }
135
136 return Ret;
137}
138
139/// \name SARIF Utilities
140/// @{
141
142/// \internal
143static json::Object createMessage(StringRef Text) {
144 return json::Object{{"text", Text.str()}};
145}
146
147/// \internal
148/// \pre CharSourceRange must be a token range
149static json::Object createTextRegion(const SourceManager &SM,
150 const CharSourceRange &R) {
151 FullSourceLoc BeginCharLoc{R.getBegin(), SM};
152 FullSourceLoc EndCharLoc{R.getEnd(), SM};
153 json::Object Region{{"startLine", BeginCharLoc.getExpansionLineNumber()},
154 {"startColumn", adjustColumnPos(BeginCharLoc)}};
155
156 if (BeginCharLoc == EndCharLoc) {
157 Region["endColumn"] = adjustColumnPos(BeginCharLoc);
158 } else {
159 Region["endLine"] = EndCharLoc.getExpansionLineNumber();
160 Region["endColumn"] = adjustColumnPos(EndCharLoc);
161 }
162 return Region;
163}
164
165/// \internal
166/// SARIF allows a location with only a message and no physicalLocation.
167static json::Object
168createLocation(std::optional<json::Object> &&PhysicalLocation,
169 StringRef Message = "") {
170 json::Object Ret;
171 if (PhysicalLocation)
172 Ret["physicalLocation"] = std::move(*PhysicalLocation);
173 if (!Message.empty())
174 Ret["message"] = createMessage(Message);
175 return Ret;
176}
177
179 switch (I) {
181 return "important";
183 return "essential";
185 return "unimportant";
186 }
187 llvm_unreachable("Fully covered switch is not so fully covered");
188}
189
191 switch (R) {
193 return "none";
195 return "note";
197 return "warning";
199 return "error";
200 }
201 llvm_unreachable("Potentially un-handled SarifResultLevel. "
202 "Is the switch not fully covered?");
203}
204
205static json::Object
206createThreadFlowLocation(json::Object &&Location,
207 const ThreadFlowImportance &Importance) {
208 return json::Object{{"location", std::move(Location)},
209 {"importance", importanceToStr(Importance)}};
210}
211/// @}
212
213std::optional<json::Object>
214SarifDocumentWriter::createPhysicalLocation(const CharSourceRange &R) {
215 if (R.isInvalid())
216 return std::nullopt;
217 assert(R.isCharRange() &&
218 "Cannot create a physicalLocation from a token range!");
219 FullSourceLoc Start{R.getBegin(), SourceMgr};
221 if (!FE)
222 return std::nullopt;
223
224 const std::string &FileURI = fileNameToURI(getFileName(*FE));
225 auto I = CurrentArtifacts.find(FileURI);
226
227 if (I == CurrentArtifacts.end()) {
228 uint32_t Idx = static_cast<uint32_t>(CurrentArtifacts.size());
229 const SarifArtifactLocation &Location =
231 const SarifArtifact &Artifact = SarifArtifact::create(Location)
232 .setRoles({"resultFile"})
233 .setLength(FE->getSize())
234 .setMimeType("text/plain");
235 auto StatusIter = CurrentArtifacts.insert({FileURI, Artifact});
236 // If inserted, ensure the original iterator points to the newly inserted
237 // element, so it can be used downstream.
238 if (StatusIter.second)
239 I = StatusIter.first;
240 }
241 assert(I != CurrentArtifacts.end() && "Failed to insert new artifact");
242 const SarifArtifactLocation &Location = I->second.Location;
243 json::Object ArtifactLocationObject{{"uri", Location.URI}};
244 if (Location.Index.has_value())
245 ArtifactLocationObject["index"] = *Location.Index;
246 return json::Object{{{"artifactLocation", std::move(ArtifactLocationObject)},
247 {"region", createTextRegion(SourceMgr, R)}}};
248}
249
250json::Object &SarifDocumentWriter::getCurrentTool() {
251 assert(!Closed && "SARIF Document is closed. "
252 "Need to call createRun() before using getcurrentTool!");
253
254 // Since Closed = false here, expect there to be at least 1 Run, anything
255 // else is an invalid state.
256 assert(!Runs.empty() && "There are no runs associated with the document!");
257
258 return *Runs.back().getAsObject()->get("tool")->getAsObject();
259}
260
261void SarifDocumentWriter::reset() {
262 CurrentRules.clear();
263 CurrentArtifacts.clear();
264}
265
267 // Exit early if trying to close a closed Document.
268 if (Closed) {
269 reset();
270 return;
271 }
272
273 // Since Closed = false here, expect there to be at least 1 Run, anything
274 // else is an invalid state.
275 assert(!Runs.empty() && "There are no runs associated with the document!");
276
277 // Flush all the rules.
278 json::Object &Tool = getCurrentTool();
279 json::Array Rules;
280 for (const SarifRule &R : CurrentRules) {
281 json::Object Config{
282 {"enabled", R.DefaultConfiguration.Enabled},
283 {"level", resultLevelToStr(R.DefaultConfiguration.Level)},
284 {"rank", R.DefaultConfiguration.Rank}};
285 json::Object Rule{
286 {"name", R.Name},
287 {"id", R.Id},
288 {"fullDescription", json::Object{{"text", R.Description}}},
289 {"defaultConfiguration", std::move(Config)}};
290 if (!R.HelpURI.empty())
291 Rule["helpUri"] = R.HelpURI;
292 if (!R.DeprecatedIds.empty())
293 Rule["deprecatedIds"] = json::Array(R.DeprecatedIds);
294
295 Rules.emplace_back(std::move(Rule));
296 }
297 json::Object &Driver = *Tool.getObject("driver");
298 Driver["rules"] = std::move(Rules);
299
300 // Flush all the artifacts.
301 json::Object &Run = getCurrentRun();
302 json::Array *Artifacts = Run.getArray("artifacts");
304 for (const auto &[K, V] : CurrentArtifacts)
305 Vec.emplace_back(K, V);
306 // artifactLocation.index refers to the position in this array.
307 llvm::sort(Vec, [](const std::pair<StringRef, SarifArtifact> &L,
308 const std::pair<StringRef, SarifArtifact> &R) {
309 return L.second.Location.Index < R.second.Location.Index;
310 });
311 for (const auto &[_, A] : Vec) {
312 json::Object Loc{{"uri", A.Location.URI}};
313 if (A.Location.Index.has_value()) {
314 Loc["index"] = static_cast<int64_t>(*A.Location.Index);
315 }
316 json::Object Artifact;
317 Artifact["location"] = std::move(Loc);
318 if (A.Length.has_value())
319 Artifact["length"] = static_cast<int64_t>(*A.Length);
320 if (!A.Roles.empty())
321 Artifact["roles"] = json::Array(A.Roles);
322 if (!A.MimeType.empty())
323 Artifact["mimeType"] = A.MimeType;
324 if (A.Offset.has_value())
325 Artifact["offset"] = *A.Offset;
326 Artifacts->push_back(json::Value(std::move(Artifact)));
327 }
328
329 // Clear, reset temporaries before next run.
330 reset();
331
332 // Mark the document as closed.
333 Closed = true;
334}
335
336json::Array
337SarifDocumentWriter::createThreadFlows(ArrayRef<ThreadFlow> ThreadFlows) {
338 json::Object Ret{{"locations", json::Array{}}};
339 json::Array Locs;
340 for (const auto &ThreadFlow : ThreadFlows) {
341 json::Object Loc = createLocation(createPhysicalLocation(ThreadFlow.Range),
342 ThreadFlow.Message);
343 Locs.emplace_back(
344 createThreadFlowLocation(std::move(Loc), ThreadFlow.Importance));
345 }
346 Ret["locations"] = std::move(Locs);
347 return json::Array{std::move(Ret)};
348}
349
350json::Object
351SarifDocumentWriter::createCodeFlow(ArrayRef<ThreadFlow> ThreadFlows) {
352 return json::Object{{"threadFlows", createThreadFlows(ThreadFlows)}};
353}
354
355void SarifDocumentWriter::createRun(StringRef ShortToolName,
356 StringRef LongToolName,
357 StringRef ToolVersion,
358 StringRef InformationUri) {
359 // Clear resources associated with a previous run.
360 endRun();
361
362 // Signify a new run has begun.
363 Closed = false;
364
365 json::Object Tool{{"driver", json::Object{{"name", ShortToolName},
366 {"fullName", LongToolName},
367 {"language", "en-US"},
368 {"version", ToolVersion},
369 {"informationUri", InformationUri},
370 {"rules", json::Array{}}}}};
371 json::Object TheRun{{"tool", std::move(Tool)},
372 {"results", {}},
373 {"artifacts", {}},
374 {"columnKind", "unicodeCodePoints"}};
375 Runs.emplace_back(std::move(TheRun));
376}
377
378json::Object &SarifDocumentWriter::getCurrentRun() {
379 assert(!Closed &&
380 "SARIF Document is closed. "
381 "Can only getCurrentRun() if document is opened via createRun(), "
382 "create a run first");
383
384 // Since Closed = false here, expect there to be at least 1 Run, anything
385 // else is an invalid state.
386 assert(!Runs.empty() && "There are no runs associated with the document!");
387 return *Runs.back().getAsObject();
388}
389
391 size_t Ret = CurrentRules.size();
392 CurrentRules.emplace_back(Rule);
393 return Ret;
394}
395
397 size_t RuleIdx = Result.RuleIdx;
398 assert(RuleIdx < CurrentRules.size() &&
399 "Trying to reference a rule that doesn't exist");
400 const SarifRule &Rule = CurrentRules[RuleIdx];
401 assert(Rule.DefaultConfiguration.Enabled &&
402 "Cannot add a result referencing a disabled Rule");
403 json::Object Ret{{"message", createMessage(Result.DiagnosticMessage)},
404 {"ruleIndex", static_cast<int64_t>(RuleIdx)},
405 {"ruleId", Rule.Id}};
406
407 if (!Result.HostedViewerURI.empty()) {
408 Ret["hostedViewerUri"] = Result.HostedViewerURI;
409 }
410
411 if (!Result.Properties.empty()) {
412 json::Object Properties;
413 for (const auto &[Key, Value] : Result.Properties)
414 Properties[Key.str()] = Value;
415 Ret["properties"] = std::move(Properties);
416 }
417
418 json::Array Locs;
419 for (const auto &Range : Result.Locations)
420 if (std::optional<json::Object> PL = createPhysicalLocation(Range))
421 Locs.emplace_back(createLocation(std::move(PL)));
422 if (!Locs.empty())
423 Ret["locations"] = std::move(Locs);
424
425 // relatedLocations must hold unique items, a distinct Id per location is
426 // added to keep notes unique.
427 json::Array ReLocs;
428 int64_t RelatedLocationId = 0;
429 for (const auto &[Range, Message] : Result.RelatedLocations) {
430 json::Object Loc = createLocation(createPhysicalLocation(Range), Message);
431 if (Loc.empty())
432 continue;
433 Loc["id"] = RelatedLocationId++;
434 ReLocs.emplace_back(std::move(Loc));
435 }
436
437 if (!ReLocs.empty())
438 Ret["relatedLocations"] = std::move(ReLocs);
439
440 if (!Result.PartialFingerprints.empty()) {
441 json::Object fingerprints = {};
442 for (auto &pair : Result.PartialFingerprints) {
443 fingerprints[pair.first] = pair.second;
444 }
445 Ret["partialFingerprints"] = std::move(fingerprints);
446 }
447
448 if (!Result.ThreadFlows.empty())
449 Ret["codeFlows"] = json::Array{createCodeFlow(Result.ThreadFlows)};
450
451 Ret["level"] = resultLevelToStr(
452 Result.LevelOverride.value_or(Rule.DefaultConfiguration.Level));
453
454 json::Object &Run = getCurrentRun();
455 json::Array *Results = Run.getArray("results");
456 Results->emplace_back(std::move(Ret));
457}
458
460 // Flush all temporaries to their destinations if needed.
461 endRun();
462
463 json::Object Doc{
464 {"$schema", SchemaURI},
465 {"version", SchemaVersion},
466 };
467 if (!Runs.empty())
468 Doc["runs"] = json::Array(Runs);
469 return Doc;
470}
#define V(N, I)
static StringRef importanceToStr(ThreadFlowImportance I)
Definition Sarif.cpp:178
static json::Object createMessage(StringRef Text)
Definition Sarif.cpp:143
static StringRef getFileName(FileEntryRef FE)
Definition Sarif.cpp:37
static unsigned int adjustColumnPos(FullSourceLoc Loc, unsigned int TokenLen=0)
Calculate the column position expressed in the number of UTF-8 code points from column start to the s...
Definition Sarif.cpp:116
static std::string percentEncodeURICharacter(char C)
Definition Sarif.cpp:53
static json::Object createThreadFlowLocation(json::Object &&Location, const ThreadFlowImportance &Importance)
Definition Sarif.cpp:206
static json::Object createTextRegion(const SourceManager &SM, const CharSourceRange &R)
Definition Sarif.cpp:149
static json::Object createLocation(std::optional< json::Object > &&PhysicalLocation, StringRef Message="")
Definition Sarif.cpp:168
static StringRef resultLevelToStr(SarifResultLevel R)
Definition Sarif.cpp:190
Defines clang::SarifDocumentWriter, clang::SarifRule, clang::SarifResult.
static bool contains(const std::set< tok::TokenKind > &Terminators, const Token &Tok)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
static SarifArtifactLocation create(llvm::StringRef URI)
Definition Sarif.h:82
static SarifArtifact create(const SarifArtifactLocation &Loc)
Definition Sarif.h:119
Represents a byte-granular source range.
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
const FileEntry & getFileEntry() const
Definition FileEntry.h:70
off_t getSize() const
Definition FileEntry.h:317
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
StringRef tryGetRealPathName() const
Definition FileEntry.h:298
A SourceLocation and its associated SourceManager.
FileIDAndOffset getDecomposedExpansionLoc() const
Decompose the underlying SourceLocation into a raw (FileID + Offset) pair, after walking through all ...
FullSourceLoc getExpansionLoc() const
OptionalFileEntryRef getFileEntryRef() const
unsigned getExpansionColumnNumber(bool *Invalid=nullptr) const
const SourceManager & getManager() const
unsigned getExpansionLineNumber(bool *Invalid=nullptr) const
void createRun(const llvm::StringRef ShortToolName, const llvm::StringRef LongToolName, const llvm::StringRef ToolVersion=CLANG_VERSION_STRING, const llvm::StringRef InformationUri="https://clang.llvm.org/docs/UsersManual.html")
Create a new run with which any upcoming analysis will be associated.
Definition Sarif.cpp:355
size_t createRule(const SarifRule &Rule)
Associate the given rule with the current run.
Definition Sarif.cpp:390
static std::string fileNameToURI(llvm::StringRef Filename)
Definition Sarif.cpp:70
llvm::json::Object createDocument()
Return the SARIF document in its current state.
Definition Sarif.cpp:459
void endRun()
If there is a current run, end it.
Definition Sarif.cpp:266
void appendResult(const SarifResult &SarifResult)
Append a new result to the currently in-flight run.
Definition Sarif.cpp:396
A SARIF result (also called a "reporting item") is a unit of output produced when one of the tool's r...
Definition Sarif.h:322
A SARIF rule (reportingDescriptor object) contains information that describes a reporting item genera...
Definition Sarif.h:257
This class handles loading and caching of source files into memory.
std::optional< llvm::MemoryBufferRef > getBufferOrNone(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
SarifArtifactLocation setIndex(uint32_t Idx)
Definition Sarif.h:86
Since every clang artifact MUST have a location (there being no nested artifacts),...
Definition Sarif.h:104
SarifArtifact setMimeType(llvm::StringRef ArtifactMimeType)
Definition Sarif.h:138
SarifArtifact setRoles(std::initializer_list< llvm::StringRef > ArtifactRoles)
Definition Sarif.h:133
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:276
std::variant< TUSummary, LUSummary, WPASuite > Artifact
Sum type returned by SerializationFormat::readArtifact, used when the caller does not know up-front w...
Top level wrappers for InstallAPI frontend operations.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
std::pair< FileID, unsigned > FileIDAndOffset
SarifResultLevel
The level of severity associated with a SarifResult.
Definition Sarif.h:165
ThreadFlowImportance
Definition Sarif.h:146
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ Off
Never emit colors regardless of the output stream.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30