diff --git a/src/TaskAnalyzer.Tests/MultiThreadableTaskAnalyzerTests.cs b/src/TaskAnalyzer.Tests/MultiThreadableTaskAnalyzerTests.cs index 12b36e74fac..8dccbfa5949 100644 --- a/src/TaskAnalyzer.Tests/MultiThreadableTaskAnalyzerTests.cs +++ b/src/TaskAnalyzer.Tests/MultiThreadableTaskAnalyzerTests.cs @@ -461,6 +461,104 @@ public override bool Execute() diags.ShouldNotContain(d => d.Id == DiagnosticIds.FilePathRequiresAbsolute); } + [Fact] + public async Task FileInfo_WithAbsolutePathValue_NoDiagnostic() + { + const string source = """ + using System.IO; + using Microsoft.Build.Framework; + public class MyTask : Microsoft.Build.Utilities.Task, IMultiThreadableTask + { + public TaskEnvironment TaskEnvironment { get; set; } + public override bool Execute() + { + new FileInfo(TaskEnvironment.GetAbsolutePath("foo.txt").Value); + return true; + } + } + """; + + CreateCompilation(source).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty(); + var diags = await GetDiagnosticsAsync(source); + + diags.ShouldBeEmpty(); + } + + [Fact] + public async Task DirectoryCreate_WithAbsolutePathValueThroughLocal_NoDiagnostic() + { + const string source = """ + using System.IO; + using Microsoft.Build.Framework; + public class MyTask : Microsoft.Build.Utilities.Task, IMultiThreadableTask + { + public TaskEnvironment TaskEnvironment { get; set; } + public override bool Execute() + { + string dir = TaskEnvironment.GetAbsolutePath("out").Value; + Directory.CreateDirectory(dir); + return true; + } + } + """; + + CreateCompilation(source).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty(); + var diags = await GetDiagnosticsAsync(source); + + diags.ShouldBeEmpty(); + } + + [Fact] + public async Task FileOpenRead_WithAbsolutePathParameterValue_NoDiagnostic() + { + const string source = """ + using System.IO; + using Microsoft.Build.Framework; + public class MyTask : Microsoft.Build.Utilities.Task, IMultiThreadableTask + { + public TaskEnvironment TaskEnvironment { get; set; } + private static void Read(AbsolutePath path) => File.OpenRead(path.Value); + public override bool Execute() + { + Read(TaskEnvironment.GetAbsolutePath("foo.txt")); + return true; + } + } + """; + + CreateCompilation(source).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty(); + var diags = await GetDiagnosticsAsync(source); + + diags.ShouldBeEmpty(); + } + + [Fact] + public async Task FileInfo_WithUnrelatedValueProperty_ReportsDiagnostic() + { + const string source = """ + using System.Collections.Generic; + using System.IO; + using Microsoft.Build.Framework; + public class MyTask : Microsoft.Build.Utilities.Task, IMultiThreadableTask + { + public TaskEnvironment TaskEnvironment { get; set; } + public override bool Execute() + { + foreach (KeyValuePair entry in new Dictionary()) + { + new FileInfo(entry.Value); + } + return true; + } + } + """; + + CreateCompilation(source).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty(); + var diags = await GetDiagnosticsAsync(source); + + diags.ShouldHaveSingleItem().Id.ShouldBe(DiagnosticIds.FilePathRequiresAbsolute); + } + [Fact] public async Task FileDelete_WithNullableAbsolutePathVariable_NoDiagnostic() { @@ -720,9 +818,13 @@ public override bool Execute() } [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task GetFullPathLookalike_DoesNotProveAnAbsoluteResult(bool useMetadataReference) + [InlineData(false, "GetFullPath(path.Value)")] + [InlineData(true, "GetFullPath(path.Value)")] + [InlineData(false, "GetDirectoryName(path.Value)")] + [InlineData(true, "GetDirectoryName(path.Value)")] + [InlineData(false, "Combine(path.Value, \"child.txt\")")] + [InlineData(true, "Combine(path.Value, \"child.txt\")")] + public async Task PathHelperLookalike_DoesNotProveAnAbsoluteResult(bool useMetadataReference, string invocation) { const string lookalikeSource = """ namespace System.IO @@ -730,10 +832,12 @@ namespace System.IO public static class Path { public static string GetFullPath(string path) => "relative.txt"; + public static string GetDirectoryName(string path) => "relative.txt"; + public static string Combine(string path1, string path2) => "relative.txt"; } } """; - const string source = """ + var source = $$""" using System.IO; using Microsoft.Build.Framework; [MSBuildMultiThreadableTask] @@ -742,7 +846,7 @@ public class MyTask : Microsoft.Build.Utilities.Task public override bool Execute() { AbsolutePath path = new TaskEnvironment().GetAbsolutePath("relative.txt"); - File.Exists(Path.GetFullPath(path.Value)); + File.Exists(Path.{{invocation}}); return true; } } diff --git a/src/TaskAnalyzer.Tests/TransitiveCallChainAnalyzerTests.cs b/src/TaskAnalyzer.Tests/TransitiveCallChainAnalyzerTests.cs index 6b4503a8fec..ff87d36722a 100644 --- a/src/TaskAnalyzer.Tests/TransitiveCallChainAnalyzerTests.cs +++ b/src/TaskAnalyzer.Tests/TransitiveCallChainAnalyzerTests.cs @@ -213,6 +213,81 @@ public override bool Execute() transitive.ShouldBeEmpty(); } + [Theory] + [InlineData("new FileInfo(path.Value);")] + [InlineData("string dir = path.Value; Directory.CreateDirectory(dir);")] + [InlineData("using var stream = File.OpenRead(path.Value);")] + [InlineData("using var stream = File.OpenRead(Path.Combine(Path.GetDirectoryName(path.Value), \"child.txt\"));")] + [InlineData("string full = Path.GetFullPath(path.Value); string dir = Path.GetDirectoryName(full); using var stream = File.OpenRead(Path.Combine(dir, \"child.txt\"));")] + public async Task HelperWithAbsolutePathValue_NoDiagnostics(string helperBody) + { + var source = $$""" + using System.IO; + using Microsoft.Build.Framework; + public static class PathHelper + { + public static void Read(AbsolutePath path) + { + {{helperBody}} + } + } + [MSBuildMultiThreadableTask] + public class MyTask : Microsoft.Build.Utilities.Task + { + public override bool Execute() + { + PathHelper.Read(new TaskEnvironment().GetAbsolutePath("relative.txt")); + return true; + } + } + """; + + CreateCompilation(source).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty(); + var diags = await GetAllDiagnosticsAsync(source); + + diags.ShouldBeEmpty(); + } + + [Theory] + [InlineData("path.OriginalValue")] + [InlineData("other.Value")] + [InlineData("path.Value.Substring(1)")] + public async Task HelperWithUnsafePathValue_StillProducesDiagnostic(string argument) + { + var source = $$""" + using System.IO; + using Microsoft.Build.Framework; + namespace Other + { + public class AbsolutePath { public string Value => "relative.txt"; } + } + public static class PathHelper + { + public static void Read(AbsolutePath path) + { + var other = new Other.AbsolutePath(); + using var stream = File.OpenRead({{argument}}); + } + } + [MSBuildMultiThreadableTask] + public class MyTask : Microsoft.Build.Utilities.Task + { + public override bool Execute() + { + PathHelper.Read(new TaskEnvironment().GetAbsolutePath("relative.txt")); + 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("File.OpenRead"); + } + [Theory] [InlineData(false, "GetCanonicalForm")] [InlineData(true, "GetCanonicalForm")] diff --git a/src/TaskAnalyzer/MultiThreadableTaskAnalyzer.cs b/src/TaskAnalyzer/MultiThreadableTaskAnalyzer.cs index b75d80c7ec7..02745934888 100644 --- a/src/TaskAnalyzer/MultiThreadableTaskAnalyzer.cs +++ b/src/TaskAnalyzer/MultiThreadableTaskAnalyzer.cs @@ -52,6 +52,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte var taskEnvironmentType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.TaskEnvironmentFullName); var absolutePathType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.AbsolutePathFullName); var iTaskItemType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.ITaskItemFullName); + var systemIOPathType = ResolveSystemIOPath(compilationContext.Compilation); var consoleType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.ConsoleFullName); var multiThreadableTaskType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.IMultiThreadableTaskFullName); var contributingMultiThreadableTaskBaseTypes = FindContributingMultiThreadableTaskBaseTypes( @@ -84,7 +85,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte // Register operation-level analysis within this type symbolStartContext.RegisterOperationAction( ctx => AnalyzeOperation(ctx, bannedApiLookup, filePathTypes, analyzeAsMultiThreadable, analyzeAllTasksByTree, - taskEnvironmentType, absolutePathType, iTaskItemType, consoleType), + taskEnvironmentType, absolutePathType, iTaskItemType, consoleType, systemIOPathType), OperationKind.Invocation, OperationKind.ObjectCreation, OperationKind.PropertyReference, @@ -103,7 +104,8 @@ private static void AnalyzeOperation( INamedTypeSymbol? taskEnvironmentType, INamedTypeSymbol? absolutePathType, INamedTypeSymbol? iTaskItemType, - INamedTypeSymbol? consoleType) + INamedTypeSymbol? consoleType, + INamedTypeSymbol? systemIOPathType) { ISymbol? referencedSymbol = null; ImmutableArray arguments = default; @@ -147,7 +149,7 @@ private static void AnalyzeOperation( // Check banned API lookup (handles MSBuildTask0001, 0002, 0004) if (bannedApiLookup.TryGetValue(referencedSymbol, out var entry)) { - if (IsAbsolutePathCanonicalization(context.Operation, absolutePathType)) + if (IsAbsolutePathCanonicalization(context.Operation, absolutePathType, systemIOPathType)) { return; } @@ -192,7 +194,7 @@ private static void AnalyzeOperation( if (containingType is not null && filePathTypes.Contains(containingType) && ShouldReportEnvironmentRules(context, analyzeAsMultiThreadable, analyzeAllTasksByTree) && - HasUnwrappedPathArgument(arguments, taskEnvironmentType, absolutePathType, iTaskItemType)) + HasUnwrappedPathArgument(arguments, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType)) { string displayName = isConstructor ? $"new {containingType.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat)}(...)" diff --git a/src/TaskAnalyzer/MultiThreadableTaskCodeFixProvider.cs b/src/TaskAnalyzer/MultiThreadableTaskCodeFixProvider.cs index 84b27963a67..7fd4fca68f3 100644 --- a/src/TaskAnalyzer/MultiThreadableTaskCodeFixProvider.cs +++ b/src/TaskAnalyzer/MultiThreadableTaskCodeFixProvider.cs @@ -122,6 +122,7 @@ private static void RegisterFilePathFix(CodeFixContext context, SemanticModel se var taskEnvironmentType = compilation.GetTypeByMetadataName(WellKnownTypeNames.TaskEnvironmentFullName); var absolutePathType = compilation.GetTypeByMetadataName(WellKnownTypeNames.AbsolutePathFullName); var iTaskItemType = compilation.GetTypeByMetadataName(WellKnownTypeNames.ITaskItemFullName); + var systemIOPathType = ResolveSystemIOPath(compilation); foreach (var argument in arguments) { @@ -137,7 +138,7 @@ private static void RegisterFilePathFix(CodeFixContext context, SemanticModel se // optional parameters, whose syntax is the call itself). if (argument.Syntax is ArgumentSyntax argumentSyntax && argumentList.Arguments.Contains(argumentSyntax) && - !IsWrappedSafely(argument.Value, taskEnvironmentType, absolutePathType, iTaskItemType)) + !IsWrappedSafely(argument.Value, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType)) { return argumentSyntax; } diff --git a/src/TaskAnalyzer/PreferTypedParameterAnalyzer.cs b/src/TaskAnalyzer/PreferTypedParameterAnalyzer.cs index 8282129088b..6df1c54081c 100644 --- a/src/TaskAnalyzer/PreferTypedParameterAnalyzer.cs +++ b/src/TaskAnalyzer/PreferTypedParameterAnalyzer.cs @@ -96,6 +96,7 @@ private static void OnCompilationStart(CompilationStartAnalysisContext compilati var outputAttributeType = types.OutputAttribute; var fileInfoType = types.FileInfo; var directoryInfoType = types.DirectoryInfo; + var systemIOPathType = ResolveSystemIOPath(compilationContext.Compilation); compilationContext.RegisterSymbolStartAction(symbolStartContext => { @@ -124,7 +125,7 @@ private static void OnCompilationStart(CompilationStartAnalysisContext compilati { AnalyzeOperation(ctx, pendingDiagnostics, stringInputProps, taskItemInputProps, absolutePathType, taskEnvironmentType, iTaskItemType, - fileInfoType, directoryInfoType); + fileInfoType, directoryInfoType, systemIOPathType); }, OperationKind.ObjectCreation, OperationKind.Invocation); @@ -371,19 +372,20 @@ private static void AnalyzeOperation( INamedTypeSymbol? taskEnvironmentType, INamedTypeSymbol? iTaskItemType, INamedTypeSymbol? fileInfoType, - INamedTypeSymbol? directoryInfoType) + INamedTypeSymbol? directoryInfoType, + INamedTypeSymbol? systemIOPathType) { switch (context.Operation) { case IObjectCreationOperation creation: AnalyzeObjectCreation(pendingDiagnostics, creation, stringInputProps, taskItemInputProps, - absolutePathType, taskEnvironmentType, iTaskItemType, fileInfoType, directoryInfoType); + absolutePathType, taskEnvironmentType, iTaskItemType, fileInfoType, directoryInfoType, systemIOPathType); break; case IInvocationOperation invocation: AnalyzeInvocation(pendingDiagnostics, invocation, stringInputProps, taskItemInputProps, absolutePathType, taskEnvironmentType, iTaskItemType, - fileInfoType, directoryInfoType); + fileInfoType, directoryInfoType, systemIOPathType); break; } } @@ -558,7 +560,8 @@ private static void ReportStringPathConsumers( HashSet stringInputProps, INamedTypeSymbol? taskEnvironmentType, INamedTypeSymbol? absolutePathType, - INamedTypeSymbol? iTaskItemType) + INamedTypeSymbol? iTaskItemType, + INamedTypeSymbol? systemIOPathType) { var flagged = new HashSet(SymbolEqualityComparer.Default); foreach (var arg in arguments) @@ -572,7 +575,7 @@ private static void ReportStringPathConsumers( // Only raw (unwrapped) string arguments represent the daisy-chain scenario. A safely-wrapped // argument is either already correct or covered by the existing 0006 conversion branches. - if (IsWrappedSafely(arg.Value, taskEnvironmentType, absolutePathType, iTaskItemType)) + if (IsWrappedSafely(arg.Value, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType)) { continue; } @@ -594,7 +597,8 @@ private static void AnalyzeObjectCreation( INamedTypeSymbol? taskEnvironmentType, INamedTypeSymbol? iTaskItemType, INamedTypeSymbol? fileInfoType, - INamedTypeSymbol? directoryInfoType) + INamedTypeSymbol? directoryInfoType, + INamedTypeSymbol? systemIOPathType) { var createdType = creation.Type; if (createdType is null || creation.Arguments.Length == 0) @@ -692,7 +696,7 @@ private static void AnalyzeObjectCreation( if (createdTypeName is "System.IO.FileStream" or "System.IO.StreamReader" or "System.IO.StreamWriter") { ReportStringPathConsumers(pendingDiagnostics, creation.Arguments, creation.Syntax.GetLocation(), - "FileInfo", stringInputProps, taskEnvironmentType, absolutePathType, iTaskItemType); + "FileInfo", stringInputProps, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType); } } } @@ -706,7 +710,8 @@ private static void AnalyzeInvocation( INamedTypeSymbol? taskEnvironmentType, INamedTypeSymbol? iTaskItemType, INamedTypeSymbol? fileInfoType, - INamedTypeSymbol? directoryInfoType) + INamedTypeSymbol? directoryInfoType, + INamedTypeSymbol? systemIOPathType) { var method = invocation.TargetMethod; @@ -801,7 +806,7 @@ taskEnvironmentType is not null && if (consumerType is not null) { ReportStringPathConsumers(pendingDiagnostics, invocation.Arguments, invocation.Syntax.GetLocation(), - consumerType, stringInputProps, taskEnvironmentType, absolutePathType, iTaskItemType); + consumerType, stringInputProps, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType); } } diff --git a/src/TaskAnalyzer/README.md b/src/TaskAnalyzer/README.md index 45eaa740864..9c9c47e4a89 100644 --- a/src/TaskAnalyzer/README.md +++ b/src/TaskAnalyzer/README.md @@ -186,6 +186,9 @@ File.Exists(item.GetMetadataValue("FullPath")) // 5. Argument already typed as AbsolutePath void Helper(AbsolutePath p) => File.Exists(p); + +// 6. AbsolutePath.Value +File.Exists(abs.Value) ``` ### MSBuildTask0004 — Potential Issue (Review Required) diff --git a/src/TaskAnalyzer/SharedAnalyzerHelpers.cs b/src/TaskAnalyzer/SharedAnalyzerHelpers.cs index 3230f080a44..332a6e8faa9 100644 --- a/src/TaskAnalyzer/SharedAnalyzerHelpers.cs +++ b/src/TaskAnalyzer/SharedAnalyzerHelpers.cs @@ -242,7 +242,8 @@ internal static bool HasUnwrappedPathArgument( ImmutableArray arguments, INamedTypeSymbol? taskEnvironmentType, INamedTypeSymbol? absolutePathType, - INamedTypeSymbol? iTaskItemType) + INamedTypeSymbol? iTaskItemType, + INamedTypeSymbol? systemIOPathType) { for (int i = 0; i < arguments.Length; i++) { @@ -258,7 +259,7 @@ internal static bool HasUnwrappedPathArgument( continue; } - if (!IsWrappedSafely(arg.Value, taskEnvironmentType, absolutePathType, iTaskItemType)) + if (!IsWrappedSafely(arg.Value, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType)) { return true; } @@ -271,7 +272,10 @@ internal static bool HasUnwrappedPathArgument( /// Recognizes the normalization operation used by AbsolutePath.GetCanonicalForm and its polyfills. /// Unlike arbitrary strings, AbsolutePath.Value is already fully qualified. /// - internal static bool IsAbsolutePathCanonicalization(IOperation operation, INamedTypeSymbol? absolutePathType) + internal static bool IsAbsolutePathCanonicalization( + IOperation operation, + INamedTypeSymbol? absolutePathType, + INamedTypeSymbol? systemIOPathType) { if (absolutePathType is null || operation is not IInvocationOperation invocation || @@ -288,24 +292,28 @@ operation is not IInvocationOperation invocation || 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; - } + return IsAbsolutePathValue(argument, absolutePathType) && IsSystemIOPath(invocation, systemIOPathType); + } - // 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); + internal static INamedTypeSymbol? ResolveSystemIOPath(Compilation compilation) + { + // Resolve Path from the core library, not a source or referenced lookalike. + var coreLibrary = compilation.GetSpecialType(SpecialType.System_Object).ContainingAssembly; + return coreLibrary?.GetTypeByMetadataName("System.IO.Path"); } + private static bool IsSystemIOPath(IInvocationOperation invocation, INamedTypeSymbol? systemIOPathType) => + systemIOPathType is not null && + SymbolEqualityComparer.Default.Equals(invocation.TargetMethod.ContainingType, systemIOPathType); + + private static bool IsAbsolutePathValue(IOperation operation, INamedTypeSymbol? absolutePathType) => + absolutePathType is not null && + operation is IPropertyReferenceOperation + { + Property: { Name: "Value", IsStatic: false, Type.SpecialType: SpecialType.System_String } property + } && + SymbolEqualityComparer.Default.Equals(property.ContainingType, absolutePathType); + /// /// Recursively checks if an operation represents a safely-wrapped path. /// @@ -313,7 +321,8 @@ internal static bool IsWrappedSafely( IOperation operation, INamedTypeSymbol? taskEnvironmentType, INamedTypeSymbol? absolutePathType, - INamedTypeSymbol? iTaskItemType) + INamedTypeSymbol? iTaskItemType, + INamedTypeSymbol? systemIOPathType) { // Unwrap conversions (implicit AbsolutePath -> string, etc.) while (operation is IConversionOperation conversion) @@ -369,18 +378,18 @@ literal.ConstantValue.Value is string metadataName && // Check: Path.GetDirectoryName(safe) — directory of an absolute path is absolute if (invocation.TargetMethod.Name == "GetDirectoryName" && - invocation.TargetMethod.ContainingType?.ToDisplayString() == "System.IO.Path" && + IsSystemIOPath(invocation, systemIOPathType) && invocation.Arguments.Length >= 1 && - IsWrappedSafely(invocation.Arguments[0].Value, taskEnvironmentType, absolutePathType, iTaskItemType)) + IsWrappedSafely(invocation.Arguments[0].Value, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType)) { return true; } // Check: Path.Combine(safe, ...) — result is absolute when first arg is absolute if (invocation.TargetMethod.Name == "Combine" && - invocation.TargetMethod.ContainingType?.ToDisplayString() == "System.IO.Path" && + IsSystemIOPath(invocation, systemIOPathType) && invocation.Arguments.Length >= 2 && - IsWrappedSafely(invocation.Arguments[0].Value, taskEnvironmentType, absolutePathType, iTaskItemType)) + IsWrappedSafely(invocation.Arguments[0].Value, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType)) { return true; } @@ -388,15 +397,15 @@ 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). // Only the specific AbsolutePath.Value normalization also exempts the GetFullPath call. - if (IsAbsolutePathCanonicalization(invocation, absolutePathType)) + if (IsAbsolutePathCanonicalization(invocation, absolutePathType, systemIOPathType)) { return true; } if (invocation.TargetMethod.Name == "GetFullPath" && - invocation.TargetMethod.ContainingType?.ToDisplayString() == "System.IO.Path" && + IsSystemIOPath(invocation, systemIOPathType) && invocation.Arguments.Length >= 1 && - IsWrappedSafely(invocation.Arguments[0].Value, taskEnvironmentType, absolutePathType, iTaskItemType)) + IsWrappedSafely(invocation.Arguments[0].Value, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType)) { return true; } @@ -412,6 +421,12 @@ literal.ConstantValue.Value is string metadataName && } } + // AbsolutePath.Value is already fully qualified; no canonicalization is required. + if (IsAbsolutePathValue(operation, absolutePathType)) + { + return true; + } + // Check: argument type is AbsolutePath or Nullable if (absolutePathType is not null && operation.Type is not null && @@ -435,7 +450,7 @@ operation.Type is not null && if (declOp is IVariableDeclaratorOperation declarator && declarator.Initializer?.Value is IOperation initValue) { - return IsWrappedSafely(initValue, taskEnvironmentType, absolutePathType, iTaskItemType); + return IsWrappedSafely(initValue, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType); } } } diff --git a/src/TaskAnalyzer/TransitiveCallChainAnalyzer.cs b/src/TaskAnalyzer/TransitiveCallChainAnalyzer.cs index 22726daddcd..cd5a462084d 100644 --- a/src/TaskAnalyzer/TransitiveCallChainAnalyzer.cs +++ b/src/TaskAnalyzer/TransitiveCallChainAnalyzer.cs @@ -55,6 +55,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte var taskEnvironmentType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.TaskEnvironmentFullName); var absolutePathType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.AbsolutePathFullName); var iTaskItemType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.ITaskItemFullName); + var systemIOPathType = ResolveSystemIOPath(compilationContext.Compilation); var consoleType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.ConsoleFullName); var multiThreadableTaskType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.IMultiThreadableTaskFullName); @@ -76,7 +77,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte { ScanOperation(opCtx, callGraph, directViolations, bannedApiLookup, filePathTypes, taskEnvironmentType, absolutePathType, iTaskItemType, consoleType, iTaskType, - multiThreadableTaskType, contributingMultiThreadableTaskBaseTypes, directAnalysisStateCache); + multiThreadableTaskType, contributingMultiThreadableTaskBaseTypes, directAnalysisStateCache, systemIOPathType); }, OperationKind.Invocation, OperationKind.ObjectCreation, @@ -108,7 +109,8 @@ private static void ScanOperation( INamedTypeSymbol iTaskType, INamedTypeSymbol? multiThreadableTaskType, ImmutableHashSet contributingMultiThreadableTaskBaseTypes, - ConcurrentDictionary directAnalysisStateCache) + ConcurrentDictionary directAnalysisStateCache, + INamedTypeSymbol? systemIOPathType) { var containingSymbol = context.ContainingSymbol; if (containingSymbol is not IMethodSymbol containingMethod) @@ -191,7 +193,7 @@ 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)) + if (IsAbsolutePathCanonicalization(context.Operation, absolutePathType, systemIOPathType)) { return; } @@ -237,7 +239,7 @@ private static void ScanOperation( var methodContainingType = method.ContainingType; if (methodContainingType is not null && filePathTypes.Contains(methodContainingType)) { - if (HasUnwrappedPathArgument(arguments, taskEnvironmentType, absolutePathType, iTaskItemType)) + if (HasUnwrappedPathArgument(arguments, taskEnvironmentType, absolutePathType, iTaskItemType, systemIOPathType)) { if (IsReportedByDirectAnalyzer( context,