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
122 changes: 122 additions & 0 deletions src/TaskAnalyzer.Tests/MultiThreadableTaskAnalyzerTests.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Shouldly;
using Xunit;
using static Microsoft.Build.TaskAuthoring.Analyzer.Tests.TestHelpers;
Expand Down Expand Up @@ -580,6 +584,124 @@ public override bool Execute()
diags.ShouldNotContain(d => d.Id == DiagnosticIds.FilePathRequiresAbsolute);
}

[Theory]
[InlineData("all")]
[InlineData("multithreadable_only")]
public async Task GetFullPathOfAbsolutePathValue_NoDiagnostics(string scope)
{
const string source = """
using System.IO;
using Microsoft.Build.Framework;
using IOPath = System.IO.Path;

[MSBuildMultiThreadableTask]
public class MyTask : Microsoft.Build.Utilities.Task, IMultiThreadableTask
{
public TaskEnvironment TaskEnvironment { get; set; } = new TaskEnvironment();
public override bool Execute()
{
AbsolutePath path = TaskEnvironment.GetAbsolutePath("relative.txt");
AbsolutePath? nullablePath = path;
string canonical = Path.GetFullPath(path.Value);
File.Exists(canonical);
File.Exists(IOPath.GetFullPath(path: TaskEnvironment.GetAbsolutePath("other.txt").Value));
File.Exists(Path.GetFullPath(nullablePath.Value.Value));
File.Exists(Path.GetFullPath((string)path.Value));
return true;
}
}
""";

CreateCompilation(source).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty();
var diags = await GetDiagnosticsWithScopeAsync(source, scope);

diags.ShouldBeEmpty();
}

[Theory]
[InlineData("\"relative.txt\"")]
[InlineData("path.OriginalValue")]
[InlineData("other.Value")]
[InlineData("text")]
[InlineData("path.Value.Substring(1)")]
[InlineData("Path.Combine(path.Value, \"relative.txt\")")]
[InlineData("path.Value, path.Value")]
public async Task GetFullPathWithoutAbsolutePathValue_StillProducesDiagnostic(string arguments)
{
var source = $$"""
using System.IO;
using Microsoft.Build.Framework;
public class OtherPath { public string Value => "relative.txt"; }
public class MyTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
AbsolutePath path = new TaskEnvironment().GetAbsolutePath("relative.txt");
var other = new OtherPath();
string text = path.Value;
text = "relative.txt";
_ = Path.GetFullPath({{arguments}});
return true;
}
}
""";

CreateCompilation(source).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty();
var diags = await GetDiagnosticsAsync(source);

diags.ShouldHaveSingleItem().Id.ShouldBe(DiagnosticIds.TaskEnvironmentRequired);
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GetFullPathLookalike_DoesNotProveAnAbsoluteResult(bool useMetadataReference)
{
const string lookalikeSource = """
namespace System.IO
{
public static class Path
{
public static string GetFullPath(string path) => "relative.txt";
}
}
""";
const string source = """
using System.IO;
using Microsoft.Build.Framework;
public class MyTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
AbsolutePath path = new TaskEnvironment().GetAbsolutePath("relative.txt");
File.Exists(Path.GetFullPath(path.Value));
return true;
}
}
""";

var compilation = CreateCompilation(useMetadataReference
? "extern alias lookalike; using Path = lookalike::System.IO.Path;\n" + source
: source + lookalikeSource);
if (useMetadataReference)
{
var lookalikeCompilation = CSharpCompilation.Create(
"PathLookalike",
[CSharpSyntaxTree.ParseText(lookalikeSource)],
GetCoreReferences(),
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using var image = new MemoryStream();
lookalikeCompilation.Emit(image).Success.ShouldBeTrue();
compilation = compilation.AddReferences(MetadataReference.CreateFromImage(
image.ToArray(), MetadataReferenceProperties.Assembly.WithAliases(["lookalike"])));
}

compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty();
var diags = await compilation.WithAnalyzers([new MultiThreadableTaskAnalyzer()]).GetAnalyzerDiagnosticsAsync();

diags.ShouldContain(d => d.Id == DiagnosticIds.FilePathRequiresAbsolute);
}

[Fact]
public async Task FileInfo_WithGetFullPathOfRelative_ProducesDiagnostic()
{
Expand Down
86 changes: 86 additions & 0 deletions src/TaskAnalyzer.Tests/TransitiveCallChainAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,92 @@ public override bool Execute()
transitive.ShouldBeEmpty();
}

[Theory]
[InlineData("all", "GetCanonicalForm")]
[InlineData("multithreadable_only", "GetCanonicalForm")]
[InlineData("all", "Normalize")]
[InlineData("multithreadable_only", "Normalize")]
public async Task AbsolutePathCanonicalizationPolyfill_NoDiagnostics(string scope, string methodName)
{
var source = $$"""
using System.IO;
using Microsoft.Build.Framework;

public static class AbsolutePathExtensions
{
public static AbsolutePath {{methodName}}(this AbsolutePath path) =>
new AbsolutePath(Path.GetFullPath(path.Value));

public static bool Exists(AbsolutePath path) =>
File.Exists(Path.GetFullPath(path.Value));
}

[MSBuildMultiThreadableTask]
public class MyTask : Microsoft.Build.Utilities.Task, IMultiThreadableTask
{
public TaskEnvironment TaskEnvironment { get; set; } = new TaskEnvironment();
public override bool Execute()
{
AbsolutePath path = TaskEnvironment.GetAbsolutePath("relative.txt");
File.Exists(path.{{methodName}}());
File.Exists(AbsolutePathExtensions.{{methodName}}(path));
AbsolutePathExtensions.Exists(path);
return true;
}
}
""";

var compilation = CreateCompilation(source);
compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty();
var options = new AnalyzerOptions([], new TestAnalyzerConfigOptionsProvider(new()
{
[SharedAnalyzerHelpers.ScopeOptionKey] = scope
}));
var diags = await compilation.WithAnalyzers(
[new MultiThreadableTaskAnalyzer(), new TransitiveCallChainAnalyzer()], options).GetAnalyzerDiagnosticsAsync();

diags.ShouldBeEmpty();
}

[Theory]
[InlineData("path.OriginalValue")]
[InlineData("relative")]
[InlineData("other.Value")]
public async Task CanonicalizationPolyfillWithUnsafeInput_StillProducesDiagnostic(string argument)
{
var source = $$"""
using System.IO;
using Microsoft.Build.Framework;
public class OtherPath { public string Value => "relative.txt"; }
public static class AbsolutePathExtensions
{
public static AbsolutePath GetCanonicalForm(this AbsolutePath path)
{
var other = new OtherPath();
string relative = path.Value;
relative = "relative.txt";
return new AbsolutePath(Path.GetFullPath({{argument}}));
}
}
public class MyTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
AbsolutePath path = new TaskEnvironment().GetAbsolutePath("relative.txt");
File.Exists(path.GetCanonicalForm());
return true;
}
}
""";

CreateCompilation(source).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty();
var diags = await GetAllDiagnosticsAsync(source);

var diagnostic = diags.ShouldHaveSingleItem();
diagnostic.Id.ShouldBe(DiagnosticIds.TransitiveUnsafeCall);
diagnostic.GetMessage().ShouldContain("Path.GetFullPath");
}

[Fact]
public async Task RecursiveCallChain_DoesNotStackOverflow()
{
Expand Down
5 changes: 5 additions & 0 deletions src/TaskAnalyzer/MultiThreadableTaskAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,11 @@ private static void AnalyzeOperation(
// Check banned API lookup (handles MSBuildTask0001, 0002, 0004)
if (bannedApiLookup.TryGetValue(referencedSymbol, out var entry))
{
if (IsAbsolutePathCanonicalization(context.Operation, absolutePathType))
{
return;
}

// MSBuildTask0002 (TaskEnvironment) is gated by scope setting
if (entry.Category == BannedApiDefinitions.ApiCategory.TaskEnvironment && !reportEnvironmentRules)
{
Expand Down
9 changes: 9 additions & 0 deletions src/TaskAnalyzer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ These APIs access process-global state that varies per task in multithreaded mod
| `Process.Start()` (all overloads) | `TaskEnvironment.GetProcessStartInfo()` |
| `new ProcessStartInfo()` (all overloads) | `TaskEnvironment.GetProcessStartInfo()` |

**Canonicalization exception:** `Path.GetFullPath(path.Value)` is accepted when `path.Value`
is the instance property of the resolved `Microsoft.Build.Framework.AbsolutePath` type.
This is the normalization operation used by `AbsolutePath.GetCanonicalForm()` itself:
it canonicalizes an already fully qualified value rather than resolving a relative path
against the process working directory. The exception applies to direct calls and
source helpers/polyfills reached through MSBuildTask0005, and the resulting string is
recognized as absolute by MSBuildTask0003. No helper method name is whitelisted.
`OriginalValue`, unrelated `Value` properties, and unproven string locals are not exempt.

### MSBuildTask0003 — File Paths Must Be Absolute

File system APIs that accept a path parameter will resolve relative paths against the process working directory — which is shared and unpredictable in multithreaded mode.
Expand Down
46 changes: 45 additions & 1 deletion src/TaskAnalyzer/SharedAnalyzerHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,45 @@ internal static bool HasUnwrappedPathArgument(
return false;
}

/// <summary>
/// Recognizes the normalization operation used by AbsolutePath.GetCanonicalForm and its polyfills.
/// Unlike arbitrary strings, AbsolutePath.Value is already fully qualified.
/// </summary>
internal static bool IsAbsolutePathCanonicalization(IOperation operation, INamedTypeSymbol? absolutePathType)
{
if (absolutePathType is null ||
operation is not IInvocationOperation invocation ||
invocation.TargetMethod.Name != "GetFullPath" ||
invocation.TargetMethod.ReturnType.SpecialType != SpecialType.System_String ||
invocation.Arguments.Length != 1)
{
return false;
}

var argument = invocation.Arguments[0].Value;
while (argument is IConversionOperation { Conversion.IsIdentity: true } conversion)
{
argument = conversion.Operand;
}

if (argument is not IPropertyReferenceOperation
{
Property: { Name: "Value", IsStatic: false, Type.SpecialType: SpecialType.System_String } property
})
{
return false;
}

if (!SymbolEqualityComparer.Default.Equals(property.ContainingType, absolutePathType))
{
return false;
}

// Resolve Path from the intrinsic string's assembly, not a source or referenced lookalike.
var pathType = invocation.TargetMethod.ReturnType.ContainingAssembly?.GetTypeByMetadataName("System.IO.Path");
return SymbolEqualityComparer.Default.Equals(invocation.TargetMethod.ContainingType, pathType);
}

/// <summary>
/// Recursively checks if an operation represents a safely-wrapped path.
/// </summary>
Expand Down Expand Up @@ -194,7 +233,12 @@ literal.ConstantValue.Value is string metadataName &&

// Check: Path.GetFullPath(safe) — safe only when input is already absolute.
// If input is relative, GetFullPath resolves against CWD (wrong in MT).
// The GetFullPath call itself is still flagged by MSBuildTask0002 regardless.
// Only the specific AbsolutePath.Value normalization also exempts the GetFullPath call.
if (IsAbsolutePathCanonicalization(invocation, absolutePathType))
{
return true;
}

if (invocation.TargetMethod.Name == "GetFullPath" &&
invocation.TargetMethod.ContainingType?.ToDisplayString() == "System.IO.Path" &&
invocation.Arguments.Length >= 1 &&
Expand Down
5 changes: 5 additions & 0 deletions src/TaskAnalyzer/TransitiveCallChainAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,11 @@ private static void ScanOperation(
// Check if this is a banned API call → record as a direct violation
if (bannedApiLookup.TryGetValue(referencedSymbol, out var entry))
{
if (IsAbsolutePathCanonicalization(context.Operation, absolutePathType))
{
return;
}

var displayName = referencedSymbol.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat);
var violation = new ViolationInfo(entry.Category.ToString(), displayName, entry.Message, context.Operation.Syntax.GetLocation());
directViolations.GetOrAdd(callerKey, _ => new ConcurrentBag<ViolationInfo>()).Add(violation);
Expand Down
Loading