1 //===- unittests/Basic/SarifTest.cpp - Test writing SARIF documents -------===// 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 #include "clang/Basic/Sarif.h" 10 #include "clang/Basic/DiagnosticIDs.h" 11 #include "clang/Basic/DiagnosticOptions.h" 12 #include "clang/Basic/FileManager.h" 13 #include "clang/Basic/FileSystemOptions.h" 14 #include "clang/Basic/LangOptions.h" 15 #include "clang/Basic/SourceLocation.h" 16 #include "clang/Basic/SourceManager.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/Support/FormatVariadic.h" 19 #include "llvm/Support/JSON.h" 20 #include "llvm/Support/MemoryBuffer.h" 21 #include "llvm/Support/VirtualFileSystem.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include "gmock/gmock-matchers.h" 24 #include "gtest/gtest-death-test.h" 25 #include "gtest/gtest-matchers.h" 26 #include "gtest/gtest.h" 27 28 #include <algorithm> 29 30 using namespace clang; 31 32 namespace { 33 34 using LineCol = std::pair<unsigned int, unsigned int>; 35 36 static std::string serializeSarifDocument(llvm::json::Object &&Doc) { 37 std::string Output; 38 llvm::json::Value value(std::move(Doc)); 39 llvm::raw_string_ostream OS{Output}; 40 OS << llvm::formatv("{0}", value); 41 OS.flush(); 42 return Output; 43 } 44 45 class SarifDocumentWriterTest : public ::testing::Test { 46 protected: 47 SarifDocumentWriterTest() 48 : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), 49 FileMgr(FileSystemOptions(), InMemoryFileSystem), 50 DiagID(new DiagnosticIDs()), DiagOpts(new DiagnosticOptions()), 51 Diags(DiagID, DiagOpts.get(), new IgnoringDiagConsumer()), 52 SourceMgr(Diags, FileMgr) {} 53 54 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem; 55 FileManager FileMgr; 56 IntrusiveRefCntPtr<DiagnosticIDs> DiagID; 57 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts; 58 DiagnosticsEngine Diags; 59 SourceManager SourceMgr; 60 LangOptions LangOpts; 61 62 FileID registerSource(llvm::StringRef Name, const char *SourceText, 63 bool IsMainFile = false) { 64 std::unique_ptr<llvm::MemoryBuffer> SourceBuf = 65 llvm::MemoryBuffer::getMemBuffer(SourceText); 66 const FileEntry *SourceFile = 67 FileMgr.getVirtualFile(Name, SourceBuf->getBufferSize(), 0); 68 SourceMgr.overrideFileContents(SourceFile, std::move(SourceBuf)); 69 FileID FID = SourceMgr.getOrCreateFileID(SourceFile, SrcMgr::C_User); 70 if (IsMainFile) 71 SourceMgr.setMainFileID(FID); 72 return FID; 73 } 74 75 CharSourceRange getFakeCharSourceRange(FileID FID, LineCol Begin, 76 LineCol End) { 77 auto BeginLoc = SourceMgr.translateLineCol(FID, Begin.first, Begin.second); 78 auto EndLoc = SourceMgr.translateLineCol(FID, End.first, End.second); 79 return CharSourceRange{SourceRange{BeginLoc, EndLoc}, /* ITR = */ false}; 80 } 81 }; 82 83 TEST_F(SarifDocumentWriterTest, canCreateEmptyDocument) { 84 // GIVEN: 85 SarifDocumentWriter Writer{SourceMgr}; 86 87 // WHEN: 88 const llvm::json::Object &EmptyDoc = Writer.createDocument(); 89 std::vector<StringRef> Keys(EmptyDoc.size()); 90 std::transform(EmptyDoc.begin(), EmptyDoc.end(), Keys.begin(), 91 [](auto item) { return item.getFirst(); }); 92 93 // THEN: 94 ASSERT_THAT(Keys, testing::UnorderedElementsAre("$schema", "version")); 95 } 96 97 // Test that a newly inserted run will associate correct tool names 98 TEST_F(SarifDocumentWriterTest, canCreateDocumentWithOneRun) { 99 // GIVEN: 100 SarifDocumentWriter Writer{SourceMgr}; 101 const char *ShortName = "sariftest"; 102 const char *LongName = "sarif writer test"; 103 104 // WHEN: 105 Writer.createRun(ShortName, LongName); 106 Writer.endRun(); 107 const llvm::json::Object &Doc = Writer.createDocument(); 108 const llvm::json::Array *Runs = Doc.getArray("runs"); 109 110 // THEN: 111 // A run was created 112 ASSERT_THAT(Runs, testing::NotNull()); 113 114 // It is the only run 115 ASSERT_EQ(Runs->size(), 1UL); 116 117 // The tool associated with the run was the tool 118 const llvm::json::Object *driver = 119 Runs->begin()->getAsObject()->getObject("tool")->getObject("driver"); 120 ASSERT_THAT(driver, testing::NotNull()); 121 122 ASSERT_TRUE(driver->getString("name").hasValue()); 123 ASSERT_TRUE(driver->getString("fullName").hasValue()); 124 ASSERT_TRUE(driver->getString("language").hasValue()); 125 126 EXPECT_EQ(driver->getString("name").getValue(), ShortName); 127 EXPECT_EQ(driver->getString("fullName").getValue(), LongName); 128 EXPECT_EQ(driver->getString("language").getValue(), "en-US"); 129 } 130 131 TEST_F(SarifDocumentWriterTest, addingResultsWillCrashIfThereIsNoRun) { 132 #if defined(NDEBUG) || !GTEST_HAS_DEATH_TEST 133 GTEST_SKIP() << "This death test is only available for debug builds."; 134 #endif 135 // GIVEN: 136 SarifDocumentWriter Writer{SourceMgr}; 137 138 // WHEN: 139 // A SarifDocumentWriter::createRun(...) was not called prior to 140 // SarifDocumentWriter::appendResult(...) 141 // But a rule exists 142 auto RuleIdx = Writer.createRule(SarifRule::create()); 143 const SarifResult &EmptyResult = SarifResult::create(RuleIdx); 144 145 // THEN: 146 auto Matcher = ::testing::AnyOf( 147 ::testing::HasSubstr("create a run first"), 148 ::testing::HasSubstr("no runs associated with the document")); 149 ASSERT_DEATH(Writer.appendResult(EmptyResult), Matcher); 150 } 151 152 // Test adding rule and result shows up in the final document 153 TEST_F(SarifDocumentWriterTest, addingResultWithValidRuleAndRunIsOk) { 154 // GIVEN: 155 SarifDocumentWriter Writer{SourceMgr}; 156 const SarifRule &Rule = 157 SarifRule::create() 158 .setRuleId("clang.unittest") 159 .setDescription("Example rule created during unit tests") 160 .setName("clang unit test"); 161 162 // WHEN: 163 Writer.createRun("sarif test", "sarif test runner"); 164 unsigned RuleIdx = Writer.createRule(Rule); 165 const SarifResult &result = SarifResult::create(RuleIdx); 166 167 Writer.appendResult(result); 168 const llvm::json::Object &Doc = Writer.createDocument(); 169 170 // THEN: 171 // A document with a valid schema and version exists 172 ASSERT_THAT(Doc.get("$schema"), ::testing::NotNull()); 173 ASSERT_THAT(Doc.get("version"), ::testing::NotNull()); 174 const llvm::json::Array *Runs = Doc.getArray("runs"); 175 176 // A run exists on this document 177 ASSERT_THAT(Runs, ::testing::NotNull()); 178 ASSERT_EQ(Runs->size(), 1UL); 179 const llvm::json::Object *TheRun = Runs->back().getAsObject(); 180 181 // The run has slots for tools, results, rules and artifacts 182 ASSERT_THAT(TheRun->get("tool"), ::testing::NotNull()); 183 ASSERT_THAT(TheRun->get("results"), ::testing::NotNull()); 184 ASSERT_THAT(TheRun->get("artifacts"), ::testing::NotNull()); 185 const llvm::json::Object *Driver = 186 TheRun->getObject("tool")->getObject("driver"); 187 const llvm::json::Array *Results = TheRun->getArray("results"); 188 const llvm::json::Array *Artifacts = TheRun->getArray("artifacts"); 189 190 // The tool is as expected 191 ASSERT_TRUE(Driver->getString("name").hasValue()); 192 ASSERT_TRUE(Driver->getString("fullName").hasValue()); 193 194 EXPECT_EQ(Driver->getString("name").getValue(), "sarif test"); 195 EXPECT_EQ(Driver->getString("fullName").getValue(), "sarif test runner"); 196 197 // The results are as expected 198 EXPECT_EQ(Results->size(), 1UL); 199 200 // The artifacts are as expected 201 EXPECT_TRUE(Artifacts->empty()); 202 } 203 204 TEST_F(SarifDocumentWriterTest, checkSerializingResults) { 205 // GIVEN: 206 const std::string ExpectedOutput = 207 R"({"$schema":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json","runs":[{"artifacts":[],"columnKind":"unicodeCodePoints","results":[{"message":{"text":""},"ruleId":"clang.unittest","ruleIndex":0}],"tool":{"driver":{"fullName":"sarif test runner","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"sarif test","rules":[{"fullDescription":{"text":"Example rule created during unit tests"},"id":"clang.unittest","name":"clang unit test"}],"version":"1.0.0"}}}],"version":"2.1.0"})"; 208 209 SarifDocumentWriter Writer{SourceMgr}; 210 const SarifRule &Rule = 211 SarifRule::create() 212 .setRuleId("clang.unittest") 213 .setDescription("Example rule created during unit tests") 214 .setName("clang unit test"); 215 216 // WHEN: A run contains a result 217 Writer.createRun("sarif test", "sarif test runner", "1.0.0"); 218 unsigned ruleIdx = Writer.createRule(Rule); 219 const SarifResult &Result = SarifResult::create(ruleIdx); 220 Writer.appendResult(Result); 221 std::string Output = serializeSarifDocument(Writer.createDocument()); 222 223 // THEN: 224 ASSERT_THAT(Output, ::testing::StrEq(ExpectedOutput)); 225 } 226 227 // Check that serializing artifacts from results produces valid SARIF 228 TEST_F(SarifDocumentWriterTest, checkSerializingArtifacts) { 229 // GIVEN: 230 const std::string ExpectedOutput = 231 R"({"$schema":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json","runs":[{"artifacts":[{"length":40,"location":{"index":0,"uri":"file:///main.cpp"},"mimeType":"text/plain","roles":["resultFile"]}],"columnKind":"unicodeCodePoints","results":[{"locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":14,"startColumn":14,"startLine":3}}}],"message":{"text":"expected ';' after top level declarator"},"ruleId":"clang.unittest","ruleIndex":0}],"tool":{"driver":{"fullName":"sarif test runner","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"sarif test","rules":[{"fullDescription":{"text":"Example rule created during unit tests"},"id":"clang.unittest","name":"clang unit test"}],"version":"1.0.0"}}}],"version":"2.1.0"})"; 232 233 SarifDocumentWriter Writer{SourceMgr}; 234 const SarifRule &Rule = 235 SarifRule::create() 236 .setRuleId("clang.unittest") 237 .setDescription("Example rule created during unit tests") 238 .setName("clang unit test"); 239 240 // WHEN: A result is added with valid source locations for its diagnostics 241 Writer.createRun("sarif test", "sarif test runner", "1.0.0"); 242 unsigned RuleIdx = Writer.createRule(Rule); 243 244 llvm::SmallVector<CharSourceRange, 1> DiagLocs; 245 const char *SourceText = "int foo = 0;\n" 246 "int bar = 1;\n" 247 "float x = 0.0\n"; 248 249 FileID MainFileID = 250 registerSource("/main.cpp", SourceText, /* IsMainFile = */ true); 251 CharSourceRange SourceCSR = 252 getFakeCharSourceRange(MainFileID, {3, 14}, {3, 14}); 253 254 DiagLocs.push_back(SourceCSR); 255 256 const SarifResult &Result = 257 SarifResult::create(RuleIdx).setLocations(DiagLocs).setDiagnosticMessage( 258 "expected ';' after top level declarator"); 259 Writer.appendResult(Result); 260 std::string Output = serializeSarifDocument(Writer.createDocument()); 261 262 // THEN: Assert that the serialized SARIF is as expected 263 ASSERT_THAT(Output, ::testing::StrEq(ExpectedOutput)); 264 } 265 266 TEST_F(SarifDocumentWriterTest, checkSerializingCodeflows) { 267 // GIVEN: 268 const std::string ExpectedOutput = 269 R"({"$schema":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json","runs":[{"artifacts":[{"length":27,"location":{"index":1,"uri":"file:///test-header-1.h"},"mimeType":"text/plain","roles":["resultFile"]},{"length":30,"location":{"index":2,"uri":"file:///test-header-2.h"},"mimeType":"text/plain","roles":["resultFile"]},{"length":28,"location":{"index":3,"uri":"file:///test-header-3.h"},"mimeType":"text/plain","roles":["resultFile"]},{"length":41,"location":{"index":0,"uri":"file:///main.cpp"},"mimeType":"text/plain","roles":["resultFile"]}],"columnKind":"unicodeCodePoints","results":[{"codeFlows":[{"threadFlows":[{"locations":[{"importance":"essential","location":{"message":{"text":"Message #1"},"physicalLocation":{"artifactLocation":{"index":1},"region":{"endColumn":8,"endLine":2,"startColumn":1,"startLine":1}}}},{"importance":"important","location":{"message":{"text":"Message #2"},"physicalLocation":{"artifactLocation":{"index":2},"region":{"endColumn":8,"endLine":2,"startColumn":1,"startLine":1}}}},{"importance":"unimportant","location":{"message":{"text":"Message #3"},"physicalLocation":{"artifactLocation":{"index":3},"region":{"endColumn":8,"endLine":2,"startColumn":1,"startLine":1}}}}]}]}],"locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":8,"endLine":2,"startColumn":5,"startLine":2}}}],"message":{"text":"Redefinition of 'foo'"},"ruleId":"clang.unittest","ruleIndex":0}],"tool":{"driver":{"fullName":"sarif test runner","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"sarif test","rules":[{"fullDescription":{"text":"Example rule created during unit tests"},"id":"clang.unittest","name":"clang unit test"}],"version":"1.0.0"}}}],"version":"2.1.0"})"; 270 271 const char *SourceText = "int foo = 0;\n" 272 "int foo = 1;\n" 273 "float x = 0.0;\n"; 274 FileID MainFileID = 275 registerSource("/main.cpp", SourceText, /* IsMainFile = */ true); 276 CharSourceRange DiagLoc{getFakeCharSourceRange(MainFileID, {2, 5}, {2, 8})}; 277 278 SarifDocumentWriter Writer{SourceMgr}; 279 const SarifRule &Rule = 280 SarifRule::create() 281 .setRuleId("clang.unittest") 282 .setDescription("Example rule created during unit tests") 283 .setName("clang unit test"); 284 285 constexpr unsigned int NUM_CASES = 3; 286 llvm::SmallVector<ThreadFlow, NUM_CASES> Threadflows; 287 const char *HeaderTexts[NUM_CASES]{("#pragma once\n" 288 "#include <foo>"), 289 ("#ifndef FOO\n" 290 "#define FOO\n" 291 "#endif"), 292 ("#ifdef FOO\n" 293 "#undef FOO\n" 294 "#endif")}; 295 const char *HeaderNames[NUM_CASES]{"/test-header-1.h", "/test-header-2.h", 296 "/test-header-3.h"}; 297 ThreadFlowImportance Importances[NUM_CASES]{ 298 ThreadFlowImportance::Essential, ThreadFlowImportance::Important, 299 ThreadFlowImportance::Unimportant}; 300 for (size_t Idx = 0; Idx != NUM_CASES; ++Idx) { 301 FileID FID = registerSource(HeaderNames[Idx], HeaderTexts[Idx]); 302 CharSourceRange &&CSR = getFakeCharSourceRange(FID, {1, 1}, {2, 8}); 303 std::string Message = llvm::formatv("Message #{0}", Idx + 1); 304 ThreadFlow Item = ThreadFlow::create() 305 .setRange(CSR) 306 .setImportance(Importances[Idx]) 307 .setMessage(Message); 308 Threadflows.push_back(Item); 309 } 310 311 // WHEN: A result containing code flows and diagnostic locations is added 312 Writer.createRun("sarif test", "sarif test runner", "1.0.0"); 313 unsigned RuleIdx = Writer.createRule(Rule); 314 const SarifResult &Result = SarifResult::create(RuleIdx) 315 .setLocations({DiagLoc}) 316 .setDiagnosticMessage("Redefinition of 'foo'") 317 .setThreadFlows(Threadflows); 318 Writer.appendResult(Result); 319 std::string Output = serializeSarifDocument(Writer.createDocument()); 320 321 // THEN: Assert that the serialized SARIF is as expected 322 ASSERT_THAT(Output, ::testing::StrEq(ExpectedOutput)); 323 } 324 325 } // namespace 326