How do I force msbuild to create SARIF Files on CodeAnalysis

821 views Asked by At

If I run the code analysis in Visual Studio 2022 (on a c++ project) I get a XML and a SARIF file for every code file.

Code Analysis with Visual Studio

No I try to run the code analysis with MSBuild 2022:

MSBuild.exe solution.sln -p:Configuration=Release /p:RunCodeAnalysis=true

But with this call I only get the code analysis XML files and no SARIF files.

Any idea how to force MSBuild to create the SARIF files?

2

There are 2 answers

0
habakuk On BEST ANSWER

https://docs.microsoft.com/en-us/answers/questions/512275/what-to-do-with-static-code-analysis-result-xml-fi.html describes a solution:

Add a Directory.build.props file to your Visual Studio solution:

<?xml version="1.0" encoding="utf-8"?> 
 <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
   <ItemDefinitionGroup>
     <ClCompile>
         <AdditionalOptions>$(ClOptions) %(AdditionalOptions)</AdditionalOptions>
     </ClCompile>
   </ItemDefinitionGroup>
 </Project>

Now I can extend my MSBuild Command line on my CI-Server (TeamCity):

/p:RunCodeAnalysis=true /p:ClOptions="/analyze:log%20MyApp.nativecodeanalysis.combined.sarif" (I had to replace the whitespace with %20).

And one SARIF file is generated, or if you want one SARIF file for every code file:

/p:RunCodeAnalysis=true /p:CaOptions="/analyze:log:format:sarif"

If you want to add additional command line switches you have to separate it with %20:

/p:CaOptions=/analyze:log:format:sarif%20/analyze:log:compilerwarnings

BUT: If I activate Clang-Tidy in my Visual Studio project I get the error CLANGTIDY : error : no such file or directory: '/analyze:log' [clang-diagnostic-error] and CLANGTIDY : error : unable to handle compilation, expected exactly one compiler job in ... - Does someone has an idea about that (except disabling Clang-Tidy)?

1
Tianyu On

Try to use following command line:

cl.exe <file/project path> /analyze:autolog:ext .nativecodeanalysis.sarif

Or

cl.exe <file/project path> /analyze:autolog:ext .sarif

Though MSBuild.exe invokes cl.exe to compile, it seems creating a .sarif file is only available for directly using cl.exe and its command.

Here’s the related document: Analysis log options

/analyze:autolog:ext extension

Overrides the default extension of the analysis log files, and uses extension instead. If you use the .sarif extension, the log file uses the SARIF format instead of the default XML format.