Skip to content
Draft
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
6 changes: 2 additions & 4 deletions .vsts-dotnet-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,7 @@ jobs:
continueOnError: true
condition: eq(variables.onlyDocChanged, 0)

# Dedicated /mt validation that turns on the TaskAnalyzer (BuildAnalyzer=true),
# kept as a separate Linux Core job because the analyzer is more expensive and the regular
# bootstrapped CI jobs (which all run /mt now too) do not need it.
# Dedicated Linux Core validation of multithreaded mode.
- job: BootstrapMSBuildWithMTMode
displayName: "Linux Core Multithreaded Mode"
pool:
Expand All @@ -235,7 +233,7 @@ jobs:
- bash: sudo apt-get update
- bash: sudo apt-get install -y libxml2
# Intentionally not running tests
- bash: . 'build.sh' --ci --stage2 --stage2Argument '/p:BuildAnalyzer=true'
- bash: . 'build.sh' --ci --stage2
displayName: Build (with stage2)
condition: eq(variables.onlyDocChanged, 0)
env:
Expand Down
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Instructions for GitHub Copilot and other AI coding agents working with the MSBu
* Performance is the top priority - minimize allocations, avoid LINQ in hot paths, use efficient algorithms.
* Always use the latest C# features, currently C# 14, especially collection expressions (`[]` over `new Type[]`).
* Match the style of surrounding code when making edits, but modernize aggressively for substantial changes.
* When assessing MT task safety, treat Wave18_8-disabled migration paths as non-MT compatibility fallbacks.

## Code Review Instructions

Expand Down Expand Up @@ -52,6 +53,7 @@ When reviewing pull requests:
* Insert a newline before the opening curly brace of any code block.
* Use pattern matching and switch expressions wherever possible.
* Use `nameof` instead of string literals when referring to member names.
* Comments describe the current behavior and invariants, not the change history or why an edit was introduced. Match surrounding comment verbosity.

### Nullable Reference Types

Expand Down
19 changes: 17 additions & 2 deletions src/TaskAnalyzer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -624,12 +624,27 @@ Add the analyzer package as a private package reference:

### MSBuild Tasks Build

To enable the analyzer in the MSBuild Tasks project build, pass `/p:BuildAnalyzer=true`:
The analyzer is referenced unconditionally by `Microsoft.Build.Tasks.csproj`, so it runs on every
build of that project -- local, repo CI, and VMR product/source builds alike. No switch is needed:

```
dotnet build src/Tasks/Microsoft.Build.Tasks.csproj /p:BuildAnalyzer=true
dotnet build src/Tasks/Microsoft.Build.Tasks.csproj
```

`src/Tasks/TaskAnalyzer.globalconfig` explicitly sets
`msbuild_task_analyzer.run_mt_analyzers_on_all_tasks = false`. MT migration diagnostics
therefore apply only to MT-scoped code, including its contributing base classes and
helper call chains. Running the analyzer on every build does not opt unmigrated tasks
into all-task migration analysis. Rules that apply to all tasks remain active.

Its warnings are not demoted through `WarningsNotAsErrors`, so under `/warnaserror` (which Arcade
passes in CI) a new finding breaks the build. Suppress a verified safe use at the call site with
`#pragma warning disable`, and always state in the comment which invariant makes that call safe.

Existing unresolved findings are baselined separately with narrow call-site pragmas and `TODO`
comments describing the unsafe behavior or unverified safety assumption. These suppressions
keep builds working; they do not fix the underlying issues or establish that the calls are MT-safe.

## Example

**Before** (unsafe):
Expand Down
2 changes: 2 additions & 0 deletions src/Tasks/AppConfig/AppConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ internal void Load(string appConfigFilePath)

// Need a filestream as the XmlReader doesn't support nonstandard unicode characters in path.
// No need to dispose - as 'CloseInput' was passed to XmlReaderSettings
#pragma warning disable MSBuildTask0005 // RAR supplies a fully qualified path in MT mode; Wave18_8 opt-out is a non-MT fallback.
FileStream fs = File.OpenRead(appConfigFilePath);
#pragma warning restore MSBuildTask0005
#pragma warning disable CA2000 // Dispose objects before losing scope is suppressed because the reader is disposed in the finally block
reader = XmlReader.Create(fs, readerSettings);
#pragma warning restore CA2000 // Dispose objects before losing scope
Expand Down
6 changes: 6 additions & 0 deletions src/Tasks/AssemblyDependency/AssemblyInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,10 @@ private void CorePopulateMetadata()
return;
}

// RAR reads metadata only from resolved reference paths; direct AssemblyFiles inputs are documented as fully qualified.
#pragma warning disable MSBuildTask0005
using (var stream = File.OpenRead(_sourceFile))
#pragma warning restore MSBuildTask0005
using (var peFile = new PEReader(stream))
{
bool hasMetadata = false;
Expand Down Expand Up @@ -996,7 +999,10 @@ public static string GetRuntimeVersion(string path)
return string.Empty;
}

// RAR probes runtime versions only for resolved reference paths; direct AssemblyFiles inputs are documented as fully qualified.
#pragma warning disable MSBuildTask0005
using Stream stream = File.OpenRead(path);
#pragma warning restore MSBuildTask0005
using BinaryReader reader = new BinaryReader(stream);
return GetRuntimeVersion(reader);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Tasks/AssemblyDependency/GlobalAssemblyCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -293,9 +293,9 @@ internal static string GetLocation(
// The GAC is a process-wide / machine-wide resource, so the MSBUILDDISABLEGACRARCACHE
// opt-out is read from the process environment rather than the per-task TaskEnvironment.
// Per-task overrides of MSBUILD* environment variables are not supported.
#pragma warning disable MSBuildTask0002
#pragma warning disable MSBuildTask0002, MSBuildTask0005
bool useGacRarCache = Environment.GetEnvironmentVariable("MSBUILDDISABLEGACRARCACHE") == null;
#pragma warning restore MSBuildTask0002
#pragma warning restore MSBuildTask0002, MSBuildTask0005
if (buildEngine != null && useGacRarCache)
{
string key = $"44d78b60-3bbe-48fe-9493-04119ebf515f|{targetProcessorArchitecture}|{targetedRuntimeVersion}|{fullFusionName}|{specificVersion}";
Expand Down
4 changes: 4 additions & 0 deletions src/Tasks/AssemblyDependency/ReferenceTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3027,7 +3027,11 @@ IMAGE_FILE_MACHINE_IA64 0x200 Intel Itanium processor family
* */

UInt16 machineType = NativeMethods.IMAGE_FILE_MACHINE_INVALID;
// TODO: Drive-relative WinMDImplementationFile metadata can replace the qualified parent path.
// Tracked by https://github.com/dotnet/msbuild/issues/13196.
#pragma warning disable MSBuildTask0005
using (FileStream implementationStream = new FileStream(dllPath, FileMode.Open, FileAccess.Read))
#pragma warning restore MSBuildTask0005
{
// Seek to location that contains PE offset.
implementationStream.Seek(PEOFFSET, SeekOrigin.Begin);
Expand Down
3 changes: 3 additions & 0 deletions src/Tasks/BootstrapperUtil/ResourceUpdater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,10 @@ public bool UpdateResources(AbsolutePath filename, BuildResults results)
// Read in the file data
int fileLength;
byte[] fileContent;
// GenerateLauncher has only string resources; this file-resource loop is unreachable.
#pragma warning disable MSBuildTask0005
using (FileStream fs = File.OpenRead(resource.Filename))
#pragma warning restore MSBuildTask0005
{
fileLength = (int)fs.Length;
fileContent = new byte[fileLength];
Expand Down
2 changes: 2 additions & 0 deletions src/Tasks/FileIO/WriteLinesToFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ private static void MoveFileWithOverwrite(string source, string destination)
Microsoft.IO.File.Move(source, destination, overwrite: true);
#elif NET
// File.Move(overwrite) is available natively on .NET 5+.
#pragma warning disable MSBuildTask0003 // SaveAtomically supplies a fully qualified destination and a sibling temporary file.
System.IO.File.Move(source, destination, overwrite: true);
#pragma warning restore MSBuildTask0003
#else
// netstandard2.0 output is ref asm only and never executed at runtime.
throw new PlatformNotSupportedException();
Expand Down
10 changes: 9 additions & 1 deletion src/Tasks/FileState.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
Expand Down Expand Up @@ -131,7 +131,9 @@ public FileDirInfo(string filename)
}

// Throw nice message as far as we can. At this point IO is OK.
#pragma warning disable MSBuildTask0005 // FileState's AbsolutePath remains fully qualified after AttemptToShortenPath.
Length = new FileInfo(_filename).Length;
#pragma warning restore MSBuildTask0005

// Otherwise this will give at least something
NativeMethodsShared.ThrowExceptionForErrorCode(error);
Expand All @@ -148,7 +150,9 @@ public FileDirInfo(string filename)
else
#endif
{
#pragma warning disable MSBuildTask0005 // FileState's AbsolutePath remains fully qualified after AttemptToShortenPath.
var fileInfo = new FileInfo(_filename);
#pragma warning restore MSBuildTask0005

if (fileInfo.Exists)
{
Expand All @@ -160,7 +164,9 @@ public FileDirInfo(string filename)
}
else
{
#pragma warning disable MSBuildTask0005 // _filename is the fully qualified path supplied by FileState.
var directoryInfo = new DirectoryInfo(_filename);
#pragma warning restore MSBuildTask0005

if (directoryInfo.Exists)
{
Expand Down Expand Up @@ -201,7 +207,9 @@ public void ThrowFileInfoException(bool doThrow)
if (doThrow)
{
// Provoke exception
#pragma warning disable MSBuildTask0005 // _filename is the fully qualified path supplied by FileState.
var length = (new FileInfo(_filename)).Length;
#pragma warning restore MSBuildTask0005
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/Tasks/FormatUrl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ public override bool Execute()
if (InputUrl.Length > 0 && NativeMethodsShared.IsWindows && string.IsNullOrWhiteSpace(InputUrl))
{
Log.LogErrorWithCodeFromResources("FormatUrl.WhitespaceInputUrlNotAllowedOnWindows", InputUrl);
#pragma warning disable MSBuildTask0002 // Whitespace input throws ArgumentException on Windows without resolving a path.
Path.GetFullPath(InputUrl);
#pragma warning restore MSBuildTask0002
}

OutputUrl = PathUtil.Format(InputUrl, TaskEnvironment.ProjectDirectory);
Expand Down
2 changes: 0 additions & 2 deletions src/Tasks/GenerateLauncher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ public sealed class GenerateLauncher : TaskExtension, IMultiThreadableTask
public ITaskItem OutputEntryPoint { get; set; }
#endregion

// MSBuildTask0005 (transitive unsafe API) warnings are currently emitted here due to
// an analyzer limitation around data-flow reachability. See https://github.com/dotnet/msbuild/issues/13867.
public override bool Execute()
{
if (!NativeMethodsShared.IsWindows)
Expand Down
4 changes: 4 additions & 0 deletions src/Tasks/ManifestUtil/AssemblyIdentity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,11 @@ public static AssemblyIdentity FromManifest(string path)
try
{
var readerSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, CloseInput = true };
// TODO: Manifest.ResolvePath can leave drive-relative paths that depend on process state.
// Tracked by https://github.com/dotnet/msbuild/issues/13196.
#pragma warning disable MSBuildTask0005
FileStream fs = File.OpenRead(path);
#pragma warning restore MSBuildTask0005
using (XmlReader xmlReader = XmlReader.Create(fs, readerSettings))
{
document.Load(xmlReader);
Expand Down
2 changes: 2 additions & 0 deletions src/Tasks/ManifestUtil/DeployManifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,9 @@ private static string GetInstallableFramework(string redistListFilePath)
{
var doc = new XmlDocument();
var xrSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, CloseInput = true };
#pragma warning disable MSBuildTask0005 // Reference-assembly lookup returns a full path; only the constant RedistList\FrameworkList.xml suffix is appended.
FileStream fs = File.OpenRead(redistListFilePath);
#pragma warning restore MSBuildTask0005
using (XmlReader xr = XmlReader.Create(fs, xrSettings))
{
doc.Load(xr);
Expand Down
8 changes: 8 additions & 0 deletions src/Tasks/ManifestUtil/LauncherBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ private bool CopyLauncherToOutputDirectory(AbsolutePath launcher, AbsolutePath o
try
{
EnsureFolderExists(Path.GetDirectoryName(outputExe.Value));
#pragma warning disable MSBuildTask0005 // Both paths are fully qualified by Build using TaskEnvironment.
File.Copy(launcher.Value, outputExe.Value, true);
#pragma warning restore MSBuildTask0005
ClearReadOnlyAttribute(outputExe.Value);
}
catch (Exception ex) when (ExceptionHandling.IsIoRelatedException(ex))
Expand All @@ -122,17 +124,23 @@ private static void EnsureFolderExists(string strFolderPath)
{
if (!FileSystems.Default.DirectoryExists(strFolderPath))
{
#pragma warning disable MSBuildTask0005 // strFolderPath is the parent of the fully qualified outputExe path.
Directory.CreateDirectory(strFolderPath);
#pragma warning restore MSBuildTask0005
}
}

private static void ClearReadOnlyAttribute(string strFileName)
{
#pragma warning disable MSBuildTask0005 // strFileName is the fully qualified outputExe path.
FileAttributes attribs = File.GetAttributes(strFileName);
#pragma warning restore MSBuildTask0005
if ((attribs & FileAttributes.ReadOnly) != 0)
{
attribs &= (~FileAttributes.ReadOnly);
#pragma warning disable MSBuildTask0005 // strFileName is the fully qualified outputExe path.
File.SetAttributes(strFileName, attribs);
#pragma warning restore MSBuildTask0005
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/Tasks/ManifestUtil/Manifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,9 @@ private static string ResolvePath(string path, string[] searchPaths)
if (!String.IsNullOrEmpty(searchPath))
{
string resolvedPath = Path.Combine(searchPath, path);
#pragma warning disable MSBuildTask0005 // MT callers supply ProjectDirectory as searchPath; path is unrooted in this branch.
resolvedPath = Path.GetFullPath(resolvedPath);
#pragma warning restore MSBuildTask0005
if (FileSystems.Default.FileExists(resolvedPath))
{
return resolvedPath;
Expand Down Expand Up @@ -381,7 +383,9 @@ internal static void UpdateEntryPoint(string inputPath, string outputPath, strin
{
var document = new XmlDocument();
var xrSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, CloseInput = true };
#pragma warning disable MSBuildTask0005 // UpdateManifest supplies a TaskEnvironment-resolved inputPath.
FileStream fs = File.OpenRead(inputPath);
#pragma warning restore MSBuildTask0005
using (XmlReader xr = XmlReader.Create(fs, xrSettings))
{
document.Load(xr);
Expand Down
4 changes: 4 additions & 0 deletions src/Tasks/ManifestUtil/ManifestReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,11 @@ public static Manifest ReadManifest(string path, bool preserveStream)
public static Manifest ReadManifest(string manifestType, string path, bool preserveStream)
{
Manifest m;
// TODO: EntryPoint.ResolvedPath can remain drive-relative during deployment validation.
// Tracked by https://github.com/dotnet/msbuild/issues/13196.
#pragma warning disable MSBuildTask0005
using (Stream s = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
#pragma warning restore MSBuildTask0005
{
byte[] buffer = new byte[2];
s.ReadExactly(buffer, 0, 2);
Expand Down
10 changes: 10 additions & 0 deletions src/Tasks/ManifestUtil/ManifestWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ public static void WriteManifest(Manifest manifest, string path)
[RequiresDynamicCode("Writes a ClickOnce manifest, which uses XmlSerializer and XslCompiledTransform; both require runtime code generation not supported with Native AOT.")]
public static void WriteManifest(Manifest manifest, string path, string targetframeWorkVersion)
{
#pragma warning disable MSBuildTask0005 // GenerateManifestBase supplies a TaskEnvironment-resolved output path.
using (Stream s = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Write))
#pragma warning restore MSBuildTask0005
{
WriteManifest(manifest, s, targetframeWorkVersion);
}
Expand Down Expand Up @@ -143,7 +145,11 @@ private static void WriteManifest(Manifest manifest, Stream output, string targe
{
try
{
// TODO: XML identity names can override logPath with a drive-relative path or collide across projects.
// Known opt-in VSPLOG risk: https://github.com/dotnet/msbuild/issues/13645.
#pragma warning disable MSBuildTask0005
File.Copy(temp, Path.Combine(Util.logPath, n + ".trust-file.xml"), true);
#pragma warning restore MSBuildTask0005
}
catch (IOException)
{
Expand All @@ -166,7 +172,9 @@ private static void WriteManifest(Manifest manifest, Stream output, string targe
}
finally
{
#pragma warning disable MSBuildTask0005 // temp is a unique, fully qualified FileUtilities.GetTemporaryFileName path.
File.Delete(temp);
#pragma warning restore MSBuildTask0005
}
}
}
Expand All @@ -191,7 +199,9 @@ private static void WriteManifest(Manifest manifest, Stream output, string targe
}
finally
{
#pragma warning disable MSBuildTask0005 // temp is a unique, fully qualified path from Util.WriteTempFile.
File.Delete(temp);
#pragma warning restore MSBuildTask0005
}
Util.WriteLogFile(n + ".write.2-merged.xml", s3);
}
Expand Down
3 changes: 3 additions & 0 deletions src/Tasks/ManifestUtil/MetadataReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ private MetadataReader(string path)
{
try
{
// TODO: Dependencies may be drive-relative; WindowsBase.dll is read before ResolveFiles roots it.
#pragma warning disable MSBuildTask0005
_assemblyStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read);
#pragma warning restore MSBuildTask0005
if (_assemblyStream != null)
{
_peReader = new PEReader(_assemblyStream, PEStreamOptions.LeaveOpen);
Expand Down
4 changes: 4 additions & 0 deletions src/Tasks/ManifestUtil/PathUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,11 @@ public static bool IsNativeAssembly(string path)
public static bool IsPEFile(string path)
{
byte[] buffer = new byte[2];
// TODO: Native manifest references can remain drive-relative after Manifest.ResolvePath.
// Tracked by https://github.com/dotnet/msbuild/issues/13196.
#pragma warning disable MSBuildTask0005
using (Stream s = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
#pragma warning restore MSBuildTask0005
{
s.ReadExactly(buffer, 0, 2);
}
Expand Down
Loading
Loading