Skip to content

Commit ee88144

Browse files
bug fixes
1 parent c144dc8 commit ee88144

4 files changed

Lines changed: 54 additions & 64 deletions

File tree

tools/extensions/CodeQL.VisualStudio/CodeQL.VisualStudio/CodeQLQuerySelectorPage.xaml.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName
8484
private void ButtonOK_Click(object sender, RoutedEventArgs e)
8585
{
8686
CodeQLService.Instance.SelectedQuery = queryListBox.SelectedItem as string;
87+
8788
this.DialogResult = true;
8889
this.Close();
8990
}

tools/extensions/CodeQL.VisualStudio/CodeQL.VisualStudio/CodeQLRunner.cs

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) Microsoft. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

4+
using Microsoft.CodeAnalysis.Sarif;
45
using Microsoft.VisualStudio.CodeAnalysis.CodeQL.Exceptions;
56
using Microsoft.VisualStudio.Shell;
67
using Newtonsoft.Json.Linq;
@@ -43,7 +44,18 @@ public sealed class CodeQLRunner
4344
/// <summary>
4445
/// Gets or sets where the databases will be placed.
4546
/// </summary>
46-
public string DatabaseDirectory { get; set; }
47+
public string DatabaseDirectory
48+
{
49+
get
50+
{
51+
if(string.IsNullOrEmpty(AnalysisDirectory))
52+
{
53+
throw new Exception("Analysis directory not set");
54+
}
55+
return Path.Combine(AnalysisDirectory, "codeql_db");
56+
}
57+
set { }
58+
}
4759

4860
/// <summary>
4961
/// Gets or sets where codeql will be installed.
@@ -53,7 +65,10 @@ public sealed class CodeQLRunner
5365
/// <summary>
5466
/// Directory where analysis is being performed.
5567
/// </summary>
56-
private string analysisDir;
68+
public string AnalysisDirectory
69+
{
70+
get; set;
71+
}
5772

5873
/// <summary>
5974
/// Optional output windows pane.
@@ -155,12 +170,14 @@ public sealed class CodeQLRunner
155170

156171
public void Initialize(string sourceDir = "", string buildEnv = "", Action<string> outputFunc = null)
157172
{
158-
analysisDir = sourceDir;
159-
DatabaseDirectory = Path.Combine(analysisDir, "codeql_db");
173+
if(!string.IsNullOrEmpty(sourceDir))
174+
{
175+
AnalysisDirectory = sourceDir;
176+
}
160177

161-
if (!Directory.Exists(analysisDir))
178+
if (!Directory.Exists(AnalysisDirectory))
162179
{
163-
throw new Exception("Analysis directory does not exist: " + analysisDir);
180+
throw new Exception("Analysis directory does not exist: " + AnalysisDirectory);
164181
}
165182
this.outputFunc = outputFunc;
166183
this.buildEnv = buildEnv;
@@ -378,7 +395,7 @@ public async Task<List<string>> FindQueriesAsync(string qlpack, bool queriesNSui
378395
string query = line.Replace("\"", string.Empty).Replace("\\\\", "/").Replace("\\", "/").Trim(',').Trim();
379396
if (!IsExclusion(query))
380397
{
381-
queries.Add(query.Substring(query.IndexOf("packages"))); // display packages from root of pack, not from root of filesystem
398+
queries.Add(query);
382399
}
383400
}
384401
}
@@ -494,7 +511,7 @@ private void ProcessExited(object sender, System.EventArgs e)
494511
/// <exception cref="Exception"> Exception </exception>
495512
public async Task<int> CountDBSourceCodeLinesAsync()
496513
{
497-
string output = await RunCodeQLProcAsync("database print-baseline codeql_db", workingDir: analysisDir);
514+
string output = await RunCodeQLProcAsync("database print-baseline codeql_db", workingDir: AnalysisDirectory);
498515
foreach (string line in output.Split(Environment.NewLine.ToCharArray()[0]))
499516
{
500517
if (line.EndsWith("cpp."))
@@ -531,7 +548,7 @@ public async Task AddDBDiagInfoAsync(string projectDir, string message, int sour
531548
{
532549
throw new ArgumentException("Invalid severity level. Use 'error', 'warning', or 'note'.");
533550
}
534-
_ = await RunCodeQLProcAsync("database add-diagnostic --plaintext-message=\"" + message + "\" --source-id=" + sourceId.ToString() + " --source-name=CodeqlVSExt" + " --severity=" + severity + " codeql_db", workingDir: analysisDir);
551+
_ = await RunCodeQLProcAsync("database add-diagnostic --plaintext-message=\"" + message + "\" --source-id=" + sourceId.ToString() + " --source-name=CodeqlVSExt" + " --severity=" + severity + " codeql_db", workingDir: AnalysisDirectory);
535552
}
536553
catch (Exception ex)
537554
{
@@ -545,7 +562,7 @@ public async Task AddDBDiagInfoAsync(string projectDir, string message, int sour
545562
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
546563
public async Task<string> GetDBDiagAsync()
547564
{
548-
return await RunCodeQLProcAsync("database export-diagnostics .\\codeql_db\\ --format=raw", workingDir: analysisDir);
565+
return await RunCodeQLProcAsync("database export-diagnostics .\\codeql_db\\ --format=raw", workingDir: AnalysisDirectory);
549566
}
550567

551568
/// <summary>
@@ -646,7 +663,7 @@ public async Task GenerateDatabaseAsync(string buildCommand, CancellationToken c
646663
}
647664

648665
string strCmdText = string.Empty;
649-
string dbPath = System.IO.Path.Combine(analysisDir, "codeql_db");
666+
string dbPath = System.IO.Path.Combine(AnalysisDirectory, "codeql_db");
650667
string useThreads = string.IsNullOrWhiteSpace(threads) ? "" : " --threads=" + threads + " ";
651668
string useRam = string.IsNullOrWhiteSpace(ram) ? "" : " --ram=" + ram + " " ;
652669

@@ -656,7 +673,7 @@ public async Task GenerateDatabaseAsync(string buildCommand, CancellationToken c
656673
"create", "\"" + dbPath + "\"",
657674
"--force-overwrite",
658675
"--language=cpp",
659-
"--source-root=" + "\"" + analysisDir + "\"",
676+
"--source-root=" + "\"" + AnalysisDirectory + "\"",
660677
"--command=" + "\"" + buildCommand + "\"",
661678
useThreads,
662679
useRam
@@ -692,7 +709,7 @@ public async Task<string> RunCodeQLQuerySetAsync(string query, CancellationToken
692709
proccessExitedFunc = ProcessExited;
693710
}
694711

695-
string dbPath = Path.Combine(analysisDir, "codeql_db");
712+
string dbPath = Path.Combine(AnalysisDirectory, "codeql_db");
696713
if (!Directory.Exists(dbPath))
697714
{
698715
throw new DatabaseNotFinalizedException("Database not created");
@@ -706,7 +723,7 @@ public async Task<string> RunCodeQLQuerySetAsync(string query, CancellationToken
706723
}
707724
}
708725

709-
string resultsDir = Path.Combine(analysisDir, ".sarif");
726+
string resultsDir = Path.Combine(AnalysisDirectory, ".sarif");
710727
if (!Directory.Exists(resultsDir))
711728
{
712729
_ = Directory.CreateDirectory(resultsDir);

tools/extensions/CodeQL.VisualStudio/CodeQL.VisualStudio/CodeQLService.cs

Lines changed: 21 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -63,28 +63,8 @@ public class Source
6363

6464
}
6565

66-
67-
68-
6966
private BuildInfo _buildInfo;
7067

71-
/// <summary>
72-
/// Dictionary of query names to be displayed in the UI, and their full path.
73-
/// </summary>
74-
private Dictionary<string, string> _queryDict;
75-
//public List<string> AvailableQueries
76-
//{
77-
// get
78-
// {
79-
// if (_queryDict != null)
80-
// {
81-
// return _queryDict.Keys.ToList();
82-
// }
83-
// return new List<string>();
84-
// }
85-
// set { }
86-
//}
87-
8868
public string SelectedQuery { get; set; }
8969

9070

@@ -136,7 +116,6 @@ private CodeQLService()
136116
{
137117
_taskCompleted = null;
138118
_cancelToken = null;
139-
_queryDict = new Dictionary<string, string>();
140119
_buildInfo = new BuildInfo();
141120
}
142121

@@ -275,10 +254,6 @@ public static bool CodeQLIsInstalled()
275254

276255
public async System.Threading.Tasks.Task<string> RunCodeQLQueryAsync(string query)
277256
{
278-
if (!_queryDict.TryGetValue(query, out string querySet))
279-
{
280-
throw new ArgumentException("Query file does not exist: " + query);
281-
}
282257

283258
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
284259
string visualStudioShellPath = ProjectHelper.GetVisualStudioFolder();
@@ -289,14 +264,14 @@ public async System.Threading.Tasks.Task<string> RunCodeQLQueryAsync(string quer
289264
string startCommand = "\"" + Path.Combine(visualStudioShellPath, @"VC\Auxiliary\Build\vcvarsall.bat") + "\" " + projectArch + " && cd /d \"" + projectDirectory + "\" &&";
290265

291266
List<string> queriesList;
292-
if (querySet.EndsWith(".qls") || querySet.EndsWith("ql"))
267+
if (query.EndsWith(".qls") || query.EndsWith("ql"))
293268
{
294-
queriesList = File.Exists(querySet)
295-
? new List<string>() { querySet }
296-
: throw new ArgumentException("Query file does not exist: " + querySet);
269+
queriesList = File.Exists(query)
270+
? new List<string>() { query }
271+
: throw new ArgumentException("Query file does not exist: " + query);
297272
}
298273
await ProjectHelper.ShowProgressAsync("Analyzing CodeQL Database...");
299-
string sarifResults = await CodeQLRunner.Instance.RunCodeQLQuerySetAsync(querySet, _cancelToken.Token,
274+
string sarifResults = await CodeQLRunner.Instance.RunCodeQLQuerySetAsync(query, _cancelToken.Token,
300275
ram: CodeQLGeneralOptions.Instance.MemoryUsage,
301276
threads: CodeQLGeneralOptions.Instance.Threads,
302277
additionalSearchPath: CodeQLGeneralOptions.Instance.AdditionalQueryLocations);
@@ -314,19 +289,13 @@ public async System.Threading.Tasks.Task<bool> GenerateCodeQLDatabaseAsync()
314289
{
315290
await ProjectHelper.ShowProgressAsync("Generating CodeQL Database...");
316291
// don't need to create again if the project is clean and a database exists.
317-
318-
if(!(await ProjectHelper.IsProjectDirtyAsync()) && _buildInfo.BuildGuid.Equals((await GetDatabaseBuildGuidAsync())))
319-
{
320-
_taskCompleted.TrySetResult(true);
321-
return true;
322-
}
292+
323293
string arch = "";
324294
string configName = "";
325295
string projectName = "";
326296
await ThreadHelper.JoinableTaskFactory.RunAsync(async () =>
327297
{
328298
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
329-
330299
await ProjectHelper.BuildProjectAsync();
331300
// TODO check if build failed
332301
Project activeProject = ProjectHelper.GetActiveProject();
@@ -340,20 +309,23 @@ await ThreadHelper.JoinableTaskFactory.RunAsync(async () =>
340309

341310
CodeQLRunner.Instance.Initialize(projectDir, startCommand, CodeQLOutput);
342311
});
343-
string buildCmd = string.Empty;
344-
if (!string.IsNullOrWhiteSpace(CodeQLGeneralOptions.Instance.CustomBuildCommand))
345-
{
346-
buildCmd = CodeQLGeneralOptions.Instance.CustomBuildCommand;
347-
}
348-
else
349-
{
350-
buildCmd = "msbuild " + projectName + " /t:rebuild /p:Configuration=" + configName + " /p:Platform=" + arch;
351-
}
352-
353312

354-
await CodeQLRunner.Instance.GenerateDatabaseAsync(buildCmd, _cancelToken.Token, ram: CodeQLGeneralOptions.Instance.MemoryUsage, threads: CodeQLGeneralOptions.Instance.Threads);
313+
if (await ProjectHelper.IsProjectDirtyAsync())
314+
{
315+
// TODO check build guid // _buildInfo.BuildGuid.Equals((await GetDatabaseBuildGuidAsync()))
316+
string buildCmd = string.Empty;
317+
if (!string.IsNullOrWhiteSpace(CodeQLGeneralOptions.Instance.CustomBuildCommand))
318+
{
319+
buildCmd = CodeQLGeneralOptions.Instance.CustomBuildCommand;
320+
}
321+
else
322+
{
323+
buildCmd = "msbuild " + projectName + " /t:rebuild /p:Configuration=" + configName + " /p:Platform=" + arch;
324+
}
355325

356-
await UpdateDatabaseBuildInfoAsync();
326+
await CodeQLRunner.Instance.GenerateDatabaseAsync(buildCmd, _cancelToken.Token, ram: CodeQLGeneralOptions.Instance.MemoryUsage, threads: CodeQLGeneralOptions.Instance.Threads);
327+
await UpdateDatabaseBuildInfoAsync();
328+
}
357329
_taskCompleted.TrySetResult(true);
358330
return true;
359331
}

tools/extensions/CodeQL.VisualStudio/CodeQL.VisualStudio/ProjectHelper.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,7 @@ internal static async System.Threading.Tasks.Task<bool> IsProjectDirtyAsync()
363363
{
364364
return true;
365365
}
366-
List<string> dbFiles = new List<string>(Directory.GetFiles(dbPath, "cli-diagnostics-add-*", SearchOption.TopDirectoryOnly));
366+
List<string> dbFiles = new List<string>(Directory.GetFiles(Path.Combine(dbPath, "diagnostic"), "cli-diagnostics-add-*", SearchOption.TopDirectoryOnly));
367367
var lastBuildTime = dbFiles.Max(file => File.GetLastWriteTimeUtc(file));
368368
var sourceFiles = Directory.GetFiles(projectPath, "*.c*", SearchOption.AllDirectories)
369369
.Concat(Directory.GetFiles(projectPath, "*.h", SearchOption.AllDirectories));

0 commit comments

Comments
 (0)