Skip to content
Closed
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
114 changes: 109 additions & 5 deletions src/TaskAnalyzer.Tests/MultiThreadableTaskAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can see how this pattern isn't wrong but is it one we want to encourage? Isn't avoiding the need for this why we did the silent cast-to-string support?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, I also was not sure whether we would like to encourage this. On the other hand, we, while already had the silent cast - i believe it was there from the first version, used Value ourselves and I think customers would do that as well. And it is not too wrong to explicitly do.

@baronfel what do you think?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My preference is to not encourage the mis-use of the API. .Value is a foot-gun, and it requires us to expand analysis to include strings in more places, which complicates the analyzer.

I'd rather have this analzyer flag .Value and ship a codefix that updates the code to use the implicit AbsoluteValue -> string conversion at the given call-site.

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<string, string> entry in new Dictionary<string, string>())
{
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()
{
Expand Down Expand Up @@ -720,20 +818,26 @@ 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
{
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]
Expand All @@ -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;
}
}
Expand Down
75 changes: 75 additions & 0 deletions src/TaskAnalyzer.Tests/TransitiveCallChainAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down
10 changes: 6 additions & 4 deletions src/TaskAnalyzer/MultiThreadableTaskAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -103,7 +104,8 @@ private static void AnalyzeOperation(
INamedTypeSymbol? taskEnvironmentType,
INamedTypeSymbol? absolutePathType,
INamedTypeSymbol? iTaskItemType,
INamedTypeSymbol? consoleType)
INamedTypeSymbol? consoleType,
INamedTypeSymbol? systemIOPathType)
{
ISymbol? referencedSymbol = null;
ImmutableArray<IArgumentOperation> arguments = default;
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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)}(...)"
Expand Down
3 changes: 2 additions & 1 deletion src/TaskAnalyzer/MultiThreadableTaskCodeFixProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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;
}
Expand Down
25 changes: 15 additions & 10 deletions src/TaskAnalyzer/PreferTypedParameterAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 =>
{
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -558,7 +560,8 @@ private static void ReportStringPathConsumers(
HashSet<IPropertySymbol> stringInputProps,
INamedTypeSymbol? taskEnvironmentType,
INamedTypeSymbol? absolutePathType,
INamedTypeSymbol? iTaskItemType)
INamedTypeSymbol? iTaskItemType,
INamedTypeSymbol? systemIOPathType)
{
var flagged = new HashSet<IPropertySymbol>(SymbolEqualityComparer.Default);
foreach (var arg in arguments)
Expand All @@ -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;
}
Expand All @@ -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)
Expand Down Expand Up @@ -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);
}
}
}
Expand All @@ -706,7 +710,8 @@ private static void AnalyzeInvocation(
INamedTypeSymbol? taskEnvironmentType,
INamedTypeSymbol? iTaskItemType,
INamedTypeSymbol? fileInfoType,
INamedTypeSymbol? directoryInfoType)
INamedTypeSymbol? directoryInfoType,
INamedTypeSymbol? systemIOPathType)
Comment on lines +713 to +714
{
var method = invocation.TargetMethod;

Expand Down Expand Up @@ -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);
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/TaskAnalyzer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading