Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
186 changes: 186 additions & 0 deletions src/TaskAnalyzer.Tests/TransitiveCallChainAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -244,4 +244,190 @@ public override bool Execute()
msg.ShouldContain("A.Step1");
msg.ShouldContain("B.Step2");
}

[Fact]
public async Task Diagnostic_IsReportedAtUnsafeCallSite_NotAtTaskEntryPoint()
{
var source = """
using System;
public class TestHelper
{
public static void DoWork() { Environment.Exit(1); }
}

public class MyTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
TestHelper.DoWork();
return true;
}
}
""";

var diags = await GetAllDiagnosticsAsync(source);

var transitive = diags.Where(d => d.Id == DiagnosticIds.TransitiveUnsafeCall).ToArray();
transitive.ShouldNotBeEmpty();

// Primary location is the unsafe call itself, so a suppression next to it is honored.
var span = transitive[0].Location.SourceSpan;
source.Substring(span.Start, span.Length).ShouldBe("Environment.Exit(1)");

// The task entry point remains reachable as an additional location.
transitive[0].AdditionalLocations.Count.ShouldBe(1);
var taskSpan = transitive[0].AdditionalLocations[0].SourceSpan;
source.Substring(taskSpan.Start, taskSpan.Length).ShouldBe("Execute");
}

[Fact]
public async Task PragmaDisableAtUnsafeCallSite_SuppressesDiagnostic()
{
var diags = await GetAllDiagnosticsAsync("""
using System.Diagnostics;
public class ProcessService
{
public static void KillProcessTree(Process process)
{
#pragma warning disable MSBuildTask0005
process.Kill(entireProcessTree: true);
#pragma warning restore MSBuildTask0005
}
}

public class MyTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
ProcessService.KillProcessTree(new Process());
return true;
}
}
""");

diags.Where(d => d.Id == DiagnosticIds.TransitiveUnsafeCall).ShouldBeEmpty();
}

[Fact]
public async Task SuppressMessageAttributeOnHelperMethod_SuppressesDiagnostic()
{
var diags = await GetAllDiagnosticsAsync("""
using System.Diagnostics;
public class ProcessService
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("MSBuild.TaskAuthoring", "MSBuildTask0005", Justification = "Only kills processes this task started.")]
public static void KillProcessTree(Process process)
{
process.Kill(entireProcessTree: true);
}
}

public class MyTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
ProcessService.KillProcessTree(new Process());
return true;
}
}
""");

diags.Where(d => d.Id == DiagnosticIds.TransitiveUnsafeCall).ShouldBeEmpty();
}

[Fact]
public async Task PragmaDisableAtOneCallSite_StillReportsOtherCallSiteOfSameApi()
{
var diags = await GetAllDiagnosticsAsync("""
using System.Diagnostics;
public class ProcessService
{
public static void ReviewedKill(Process process)
{
#pragma warning disable MSBuildTask0005
process.Kill(entireProcessTree: true);
#pragma warning restore MSBuildTask0005
}

public static void UnreviewedKill(Process process)
{
process.Kill(entireProcessTree: true);
}
}

public class MyTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
ProcessService.ReviewedKill(new Process());
ProcessService.UnreviewedKill(new Process());
return true;
}
}
""");

// Suppressing one reviewed call must not blind the analyzer to the other call to the same API.
var transitive = diags.Where(d => d.Id == DiagnosticIds.TransitiveUnsafeCall).ToArray();
transitive.Length.ShouldBe(1);
transitive[0].GetMessage().ShouldContain("UnreviewedKill");
}

[Fact]
public async Task PragmaDisableAtCallSite_DoesNotHideUnrelatedTransitiveViolations()
{
var diags = await GetAllDiagnosticsAsync("""
using System;
using System.Diagnostics;
public class ProcessService
{
public static void Run(Process process)
{
#pragma warning disable MSBuildTask0005
process.Kill(entireProcessTree: true);
#pragma warning restore MSBuildTask0005
Environment.Exit(1);
}
}

public class MyTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
ProcessService.Run(new Process());
return true;
}
}
""");

var transitive = diags.Where(d => d.Id == DiagnosticIds.TransitiveUnsafeCall).ToArray();
transitive.Length.ShouldBe(1);
transitive[0].GetMessage().ShouldContain("Environment.Exit");
}

[Fact]
public async Task DistinctCallSitesOfSameApi_EachReportedSeparately()
{
var diags = await GetAllDiagnosticsAsync("""
using System;
public class UnsafeHelper
{
public static void First() { Environment.Exit(1); }
public static void Second() { Environment.Exit(2); }
}

public class MyTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
UnsafeHelper.First();
UnsafeHelper.Second();
return true;
}
}
""");

var transitive = diags.Where(d => d.Id == DiagnosticIds.TransitiveUnsafeCall).ToArray();
transitive.Length.ShouldBe(2);
transitive.Select(d => d.Location.SourceSpan).Distinct().Count().ShouldBe(2);
}
}
39 changes: 35 additions & 4 deletions src/TaskAnalyzer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,38 @@ These APIs may cause version conflicts or other issues in a shared task host.
| `Activator.CreateInstanceFrom` | May cause version conflicts |
| `AppDomain.Load`, `CreateInstance`, `CreateInstanceFrom` | May cause version conflicts |

### MSBuildTask0005 — Transitive Unsafe API Usage

MSBuildTask0001–MSBuildTask0004 only look at code written inside a task class — or inside a helper explicitly opted in with `[MSBuildMultiThreadableTaskAnalyzed]` (see [Analysis Scope](#analysis-scope)). MSBuildTask0005 closes that gap: it builds a compilation-wide call graph and walks it from every task's members, so an unsafe API reached through a shared helper is still reported.

The diagnostic is reported **at the unsafe call site** — inside the helper — and names the task entry point plus the full call chain in the message:

```
ProcessService.cs(23,9): warning MSBuildTask0005: 'CreateSourceArtifact.Execute' transitively calls
unsafe API 'Process.Kill(bool)' via: CreateSourceArtifact.Execute → CreateSourceArtifact.ExecuteAsync
→ ProcessService.RunProcessAsync → Process.Kill(bool)
```

The task entry point is also attached as an additional location, so editors can navigate from the helper to the task that reaches it.

**Suppressing a reviewed call.** Because the diagnostic is reported at the call site, the standard Roslyn suppression mechanisms work exactly where the reviewed code lives — either `#pragma warning disable`:

```csharp
#pragma warning disable MSBuildTask0005 // Only kills processes this task started; entireProcessTree walks descendants.
try { process.Kill(entireProcessTree: true); } catch { }
#pragma warning restore MSBuildTask0005
```

or `[SuppressMessage]` on the containing member, which records the review next to the code:

```csharp
[SuppressMessage("MSBuild.TaskAuthoring", "MSBuildTask0005",
Justification = "Only kills processes this task started; entireProcessTree walks descendants, not the MSBuild host.")]
private static void KillProcessTree(Process process) => process.Kill(entireProcessTree: true);
```

Each unsafe call site is reported once per task type, so suppressing one reviewed call does **not** hide other transitive violations reachable from the same task — including other calls to the same API. Suppressing on the task's `Execute` method has no effect; scope the suppression to the call site instead.

### MSBuildTask0006 — Prefer Typed Path Parameters

When a task has a `string` input property and converts it to `AbsolutePath`, `FileInfo`, or `DirectoryInfo` inside the task body, the analyzer suggests changing the property type directly. MSBuild can bind these types automatically.
Expand Down Expand Up @@ -301,7 +333,7 @@ The analyzer determines what to check based on the type declaration:

MSBuildTask0006–MSBuildTask0008 apply only when the `[MSBuildMultiThreadableTask]` attribute is applied **directly** to the task class. The attribute is `Inherited = false`, so a task that merely derives from a base class implementing `IMultiThreadableTask` (or carrying the attribute) has not itself opted into multithreaded support and is not subject to these three rules. Input properties are collected from the task class **and its base classes**, so an `ITaskItem`/`string` input declared on a shared base task is still analyzed.

The `[MSBuildMultiThreadableTaskAnalyzed]` attribute allows opting helper classes into **direct** analysis by the `MultiThreadableTaskAnalyzer` (MSBuildTask0001–0004). Without it, only classes implementing `ITask` receive per-line diagnostics and code fixes for those rules. The **transitive** analyzer (MSBuildTask0005) already discovers helpers via call graph analysis, but it reports only at the task entry point. Adding this attribute to a helper class gives you inline diagnostics and code fixes directly in the helper's source.
The `[MSBuildMultiThreadableTaskAnalyzed]` attribute allows opting helper classes into **direct** analysis by the `MultiThreadableTaskAnalyzer` (MSBuildTask0001–0004). Without it, only classes implementing `ITask` receive per-line diagnostics and code fixes for those rules. The **transitive** analyzer (MSBuildTask0005) already discovers helpers via call graph analysis and reports at the unsafe call site, but it offers no code fixes and only fires for helpers actually reachable from a task. Adding this attribute to a helper class gives you diagnostics and code fixes in the helper's source regardless of whether a task reaches it.

**When to use:** Apply `[MSBuildMultiThreadableTaskAnalyzed]` to utility or helper classes that are primarily used by multithreadable tasks and where you want immediate in-editor feedback (squiggles and code fixes) on unsafe APIs within those helpers.

Expand Down Expand Up @@ -429,11 +461,10 @@ public class CopyFiles : Task, IMultiThreadableTask

## Tests

193 tests covering all rules, safe patterns, edge cases, code fixes, and compiler diagnostic suppression:
Unit tests for all rules, safe patterns, edge cases, code fixes, and compiler diagnostic suppressions live in `src/TaskAnalyzer.Tests`. Run them from the repository root:

```
cd src/TaskAnalyzer.Tests
dotnet test
.\build.cmd -test -projects src\TaskAnalyzer.Tests\TaskAnalyzer.Tests.csproj -c Debug
```

## Architecture
Expand Down
54 changes: 42 additions & 12 deletions src/TaskAnalyzer/TransitiveCallChainAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ namespace Microsoft.Build.TaskAuthoring.Analyzer
/// a task class, this analyzer builds a compilation-wide call graph and traces method calls
/// transitively to find unsafe APIs called by helper methods, utility classes, etc.
///
/// Reports MSBuildTask0005 with the full call chain for traceability.
/// Reports MSBuildTask0005 at the unsafe call site — so that <c>#pragma warning disable</c> and
/// <c>[SuppressMessage]</c> next to the reviewed call are honored — with the full call chain in
/// the message and the task entry point as an additional location.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class TransitiveCallChainAnalyzer : DiagnosticAnalyzer
Expand Down Expand Up @@ -177,7 +179,7 @@ private static void ScanOperation(
if (bannedApiLookup.TryGetValue(referencedSymbol, out var entry))
{
var displayName = referencedSymbol.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat);
var violation = new ViolationInfo(entry.Category.ToString(), displayName, entry.Message);
var violation = new ViolationInfo(entry.Category.ToString(), displayName, entry.Message, context.Operation.Syntax.GetLocation());
Comment thread
ViktorHofer marked this conversation as resolved.
Resolved
directViolations.GetOrAdd(callerKey, _ => new ConcurrentBag<ViolationInfo>()).Add(violation);
return;
}
Expand All @@ -192,7 +194,7 @@ private static void ScanOperation(
string message = referencedSymbol.Name.StartsWith("Read", StringComparison.Ordinal)
? "may cause deadlocks in automated builds"
: "interferes with build logging; use Log.LogMessage instead";
var violation = new ViolationInfo("CriticalError", displayName, message);
var violation = new ViolationInfo("CriticalError", displayName, message, context.Operation.Syntax.GetLocation());
directViolations.GetOrAdd(callerKey, _ => new ConcurrentBag<ViolationInfo>()).Add(violation);
return;
}
Expand All @@ -208,7 +210,7 @@ private static void ScanOperation(
{
var displayName = referencedSymbol.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat);
var violation = new ViolationInfo("FilePathRequiresAbsolute", displayName,
"may resolve relative paths against the process working directory");
"may resolve relative paths against the process working directory", context.Operation.Syntax.GetLocation());
directViolations.GetOrAdd(callerKey, _ => new ConcurrentBag<ViolationInfo>()).Add(violation);
}
}
Expand Down Expand Up @@ -260,8 +262,10 @@ private static void AnalyzeTransitiveViolations(
foreach (var taskType in taskTypes)
{
// Track reported violations per task type to avoid flooding with duplicates.
// Key: target banned API display name. We report only the shortest chain per API.
var reportedPerTaskType = new HashSet<string>(StringComparer.Ordinal);
// Key: the location the diagnostic is reported at plus the target banned API display name.
// Keeping the location in the key means a suppression on one reviewed call does not hide a
// second, unreviewed call to the same API. Only the shortest chain per location is reported.
var reportedPerTaskType = new HashSet<(string ApiDisplayName, Location Location)>();

foreach (var member in taskType.GetMembers())
{
Expand Down Expand Up @@ -333,28 +337,47 @@ private static void AnalyzeTransitiveViolations(

/// <summary>
/// Reports a transitive violation with deduplication per task type.
/// Only the first (shortest) chain reaching each banned API is reported.
/// Only the first (shortest) chain reaching each unsafe call site is reported.
/// </summary>
/// <remarks>
/// The diagnostic is reported at the unsafe call site rather than at the task entry point so that
/// a <c>#pragma warning disable MSBuildTask0005</c> — or a <c>[SuppressMessage]</c> attribute on the
/// containing member — placed next to the reviewed call actually suppresses it. The task entry point
/// is still named in the message and carried as an additional location.
/// </remarks>
private static void ReportTransitiveViolation(
CompilationAnalysisContext context,
IMethodSymbol taskMethod,
ViolationInfo violation,
List<string> chain,
HashSet<string> reportedPerTaskType)
HashSet<(string ApiDisplayName, Location Location)> reportedPerTaskType)
{
// Deduplicate by target API — report each banned API only once per task type
if (!reportedPerTaskType.Add(violation.ApiDisplayName))
var taskMethodLocation = taskMethod.Locations.Length > 0 ? taskMethod.Locations[0] : Location.None;

// Prefer the call site; fall back to the task entry point when the call site has no source location.
bool hasCallSite = violation.Location.SourceTree is not null;
var location = hasCallSite ? violation.Location : taskMethodLocation;

// Deduplicate by the location the diagnostic is actually reported at, plus the target API. Keying
// on the call site means a suppression on one reviewed call does not hide a second, unreviewed
// call to the same API; keying on the *effective* location means the fallback above does not
// collapse violations that land on different task members.
if (!reportedPerTaskType.Add((violation.ApiDisplayName, location)))
{
return;
}

var chainWithApi = new List<string>(chain) { violation.ApiDisplayName };
var chainStr = string.Join(" → ", chainWithApi);

var location = taskMethod.Locations.Length > 0 ? taskMethod.Locations[0] : Location.None;
var additionalLocations = hasCallSite && taskMethodLocation.SourceTree is not null
? ImmutableArray.Create(taskMethodLocation)
: ImmutableArray<Location>.Empty;

context.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.TransitiveUnsafeCall,
location,
additionalLocations,
FormatMethodFull(taskMethod),
violation.ApiDisplayName,
chainStr));
Expand Down Expand Up @@ -425,11 +448,18 @@ internal readonly struct ViolationInfo
public string ApiDisplayName { get; }
public string Message { get; }

public ViolationInfo(string category, string apiDisplayName, string message)
/// <summary>
/// Source location of the unsafe call itself. MSBuildTask0005 is reported here so that
/// suppressions placed next to the reviewed call are honored.
/// </summary>
public Location Location { get; }

public ViolationInfo(string category, string apiDisplayName, string message, Location location)
{
Category = category;
ApiDisplayName = apiDisplayName;
Message = message;
Location = location;
}
}
}
Expand Down