Skip to content

[Microsoft.Android.Build.BaseTasks] Remove process state from Files - #13847

Merged
jonathanpeppers merged 1 commit into
mainfrom
jonathanpeppers-files-environment-multithreaded
Dec 1, 2026
Merged

jonathanpeppers merged 1 commit into
mainfrom
jonathanpeppers-files-environment-multithreaded

Conversation

@jonathanpeppers

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: a92004bb12dc9bc35b0e2357ce6357b047f6a28b

Dimension Assessment Rationale
Change confidence 8/10 ↑ All changed projects build with the analyzer rules set as errors.
↑ BaseTasks tests pass, except one failure caused by the local SDK.
↑ A second-model review found no remaining issues after two fixes.
↓ Full-build and device tests were not run locally; CI is pending.
↓ Callers that passed drive-relative or unusual paths are checked only by reading the code.

Context: dotnet/maui#40614

Files in Microsoft.Android.Build.BaseTasks is a shared helper that most of our MSBuild tasks call. Two parts of it are not safe when MSBuild runs tasks on several threads in one process (-mt):

  • GetFileWriteRetryAttempts () and GetFileWriteRetryDelay () read DOTNET_ANDROID_FILE_WRITE_RETRY_ATTEMPTS and DOTNET_ANDROID_FILE_WRITE_RETRY_DELAY_MS from the process environment and keep the values in static fields. The CopyIfChanged (), CopyIfStreamChanged (), and ExtractAll () overloads without a TaskEnvironment use them.
  • Path parameters are string, so a relative path resolves against the process working directory, not the project directory. GetArchiveExtractionPath (), EnumerateArchiveFiles (), and ExtractAll () also call Path.GetFullPath ().

Microsoft.Build.TaskAuthoring.Analyzer is already enabled for this assembly, but it reports neither problem. It follows calls only inside one compilation, and Microsoft.Android.Build.BaseTasks has no multithreaded tasks. Callers in Xamarin.Android.Build.Tasks and Microsoft.Android.Build.Tasks do not get diagnostics from Files. All current [MSBuildMultiThreadableTask] tasks already use the TaskEnvironment overloads, so there is no known bug today. This change makes the compiler and analyzer catch new ones.

Changes

  • Mark Files with [MSBuildMultiThreadableTaskAnalyzed], so the analyzer checks the class itself. Microsoft.Build.Framework does not ship this attribute; the analyzer finds it by name, so it is declared as an internal type.
  • Take the retry settings from a TaskEnvironment parameter, as Make Resizetizer tasks safe for multithreaded MSBuild maui#40614 does. Remove the overloads that read the process environment.
  • Change path parameters from string to AbsolutePath. There is no implicit conversion from string, so each caller must root the path. Multithreaded tasks use TaskEnvironment.GetAbsolutePath (), which their own analyzer checks. Other tasks use TaskEnvironment.Fallback.GetAbsolutePath (), which resolves against the process working directory, as before. Path.GetFullPath () calls become AbsolutePath.GetCanonicalForm (), which calls Path.GetFullPath () on the rooted path, so the archive path-traversal checks do not change.
  • CleanBOM () used Path.GetTempFileName (), which the analyzer reports. It now writes {guid}.tmp in the same directory, and only when the file has a BOM.
  • Remove Archive (), ArchiveZip (), ArchiveZipUpdate (), and the [Obsolete] ExtractAll () overload. Nothing in this repository calls them.
  • Remove the CopyIfZipChanged_BareFileName test. An AbsolutePath is always rooted, so a bare file name cannot get to CopyIfZipChanged () now.

Validation

  • dotnet build of Microsoft.Android.Build.BaseTasks, Microsoft.Android.Build.Tasks, Xamarin.Android.Build.Tasks, Microsoft.Android.Build.BaseTasks-Tests, and Xamarin.Android.Build.Tests: 0 errors. .editorconfig makes analyzer rules MSBuildTask0002 to MSBuildTask0005 errors.
  • dotnet test --project tests/Microsoft.Android.Build.BaseTasks-Tests/Microsoft.Android.Build.BaseTasks-Tests.csproj: 161 passed, 8 skipped, 1 failed. The failure is FailedAndroidToolTaskShouldLogOutputAsError ("--info",True,""): dotnet --info fails with the local .NET 12 SDK used for this run (The given key 'android-deps' was not present in the dictionary). It is not related to this change.
  • Not run locally: full-build tests (Xamarin.Android.Build.Tests) and device tests.

Context: dotnet/maui#40614

`Files` in `Microsoft.Android.Build.BaseTasks` is a shared helper that most of our MSBuild tasks call. Two parts of it are not safe when MSBuild runs tasks on several threads in one process (`-mt`):

  * `GetFileWriteRetryAttempts ()` and `GetFileWriteRetryDelay ()` read `DOTNET_ANDROID_FILE_WRITE_RETRY_ATTEMPTS` and `DOTNET_ANDROID_FILE_WRITE_RETRY_DELAY_MS` from the process environment and keep the values in static fields. The `CopyIfChanged ()`, `CopyIfStreamChanged ()`, and `ExtractAll ()` overloads without a `TaskEnvironment` use them.
  * Path parameters are `string`, so a relative path resolves against the process working directory, not the project directory. `GetArchiveExtractionPath ()`, `EnumerateArchiveFiles ()`, and `ExtractAll ()` also call `Path.GetFullPath ()`.

`Microsoft.Build.TaskAuthoring.Analyzer` is already enabled for this assembly, but it reports neither problem. It follows calls only inside one compilation, and `Microsoft.Android.Build.BaseTasks` has no multithreaded tasks. Callers in `Xamarin.Android.Build.Tasks` and `Microsoft.Android.Build.Tasks` do not get diagnostics from `Files`. All current `[MSBuildMultiThreadableTask]` tasks already use the `TaskEnvironment` overloads, so there is no known bug today. This change makes the compiler and analyzer catch new ones.

### Changes

  * Mark `Files` with `[MSBuildMultiThreadableTaskAnalyzed]`, so the analyzer checks the class itself. `Microsoft.Build.Framework` does not ship this attribute; the analyzer finds it by name, so it is declared as an internal type.
  * Take the retry settings from a `TaskEnvironment` parameter, as dotnet/maui#40614 does. Remove the overloads that read the process environment.
  * Change path parameters from `string` to `AbsolutePath`. There is no implicit conversion from `string`, so each caller must root the path. Multithreaded tasks use `TaskEnvironment.GetAbsolutePath ()`, which their own analyzer checks. Other tasks use `TaskEnvironment.Fallback.GetAbsolutePath ()`, which resolves against the process working directory, as before. `Path.GetFullPath ()` calls become `AbsolutePath.GetCanonicalForm ()`, which calls `Path.GetFullPath ()` on the rooted path, so the archive path-traversal checks do not change.
  * `CleanBOM ()` used `Path.GetTempFileName ()`, which the analyzer reports. It now writes `{guid}.tmp` in the same directory, and only when the file has a BOM.
  * Remove `Archive ()`, `ArchiveZip ()`, `ArchiveZipUpdate ()`, and the `[Obsolete]` `ExtractAll ()` overload. Nothing in this repository calls them.
  * Remove the `CopyIfZipChanged_BareFileName` test. An `AbsolutePath` is always rooted, so a bare file name cannot get to `CopyIfZipChanged ()` now.

### Validation

  * `dotnet build` of `Microsoft.Android.Build.BaseTasks`, `Microsoft.Android.Build.Tasks`, `Xamarin.Android.Build.Tasks`, `Microsoft.Android.Build.BaseTasks-Tests`, and `Xamarin.Android.Build.Tests`: 0 errors. `.editorconfig` makes analyzer rules MSBuildTask0002 to MSBuildTask0005 errors.
  * `dotnet test --project tests/Microsoft.Android.Build.BaseTasks-Tests/Microsoft.Android.Build.BaseTasks-Tests.csproj`: 161 passed, 8 skipped, 1 failed. The failure is `FailedAndroidToolTaskShouldLogOutputAsError ("--info",True,"")`: `dotnet --info` fails with the local .NET 12 SDK used for this run (`The given key 'android-deps' was not present in the dictionary`). It is not related to this change.
  * Not run locally: full-build tests (`Xamarin.Android.Build.Tests`) and device tests.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 21:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

The review identifies no active issues requiring changes.

No open issues 🎉

What changed in this PR

This PR makes the shared Files helpers easier to validate for multithreaded MSBuild execution. Explicit paths and task environments let the compiler and analyzer catch unsafe usage across task assemblies.

Changes:

  • Require AbsolutePath inputs and task-scoped retry settings, and enable direct analyzer checks on Files.
  • Update callers, tests, benchmarks, and guidance for the revised APIs.
  • Remove unused archive helpers and create BOM-cleanup temporary files beside the source file.
File Description
tests/​Xamarin.Android.Tools.Benchmarks/​FilesHashBenchmarks.cs Pass absolute paths to hashing benchmarks.
tests/​Microsoft.Android.Build.BaseTasks-Tests/​FilesTests.cs Adapt tests and remove the obsolete bare-filename case.
src/​Xamarin.Android.Build.Tasks/​Utilities/​RtxtWriter.cs Supply an explicit path and retry environment.
src/​Xamarin.Android.Build.Tasks/​Utilities/​MonoAndroidHelper.JavaLibraries.cs Wrap full filenames for hashing.
src/​Xamarin.Android.Build.Tasks/​Utilities/​MonoAndroidHelper.cs Adapt assembly copying, ZIP reading, and map writing.
src/​Xamarin.Android.Build.Tasks/​Utilities/​AndroidResource.cs Adapt XML resource writes.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​IncrementalBuildTest.cs Centralize path conversion for hash assertions.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ResolveLibraryProjectImports.cs Adapt import hashing, extraction, and permissions.
src/​Xamarin.Android.Build.Tasks/​Tasks/​RemoveUnknownFiles.cs Root paths before changing permissions.
src/​Xamarin.Android.Build.Tasks/​Tasks/​RemoveDirFixed.cs Supply retry environment and absolute directory paths.
src/​Xamarin.Android.Build.Tasks/​Tasks/​PreTrimmingFixLegacyBindings.cs Adapt assembly and symbol copying.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ManifestMerger.cs Adapt manifest output copying.
src/​Xamarin.Android.Build.Tasks/​Tasks/​GenerateResourceDesignerIntermediateClass.cs Root the generated output path.
src/​Xamarin.Android.Build.Tasks/​Tasks/​GenerateResourceDesigner.cs Adapt resource designer writes.
src/​Xamarin.Android.Build.Tasks/​Tasks/​GenerateProguardConfiguration.cs Root the configuration output path.
src/​Xamarin.Android.Build.Tasks/​Tasks/​GenerateLayoutBindings.cs Adapt generated binding copies.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ExtractJarsFromAar.cs Carry absolute paths through extraction and cleanup.
src/​Xamarin.Android.Build.Tasks/​Tasks/​CopyIfChanged.cs Adapt copying and permission updates.
src/​Xamarin.Android.Build.Tasks/​Tasks/​CopyGeneratedJavaResourceClasses.cs Adapt generated Java resource copies.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ConvertResourcesCases.cs Adapt permission changes and BOM cleanup.
src/​Microsoft.Android.Build.Tasks/​Utilities/​ZipArchiveEx.cs Root archive enumeration paths.
src/​Microsoft.Android.Build.Tasks/​Utilities/​RuntimeProviderSourceGenerator.cs Preserve the resolved AbsolutePath type.
src/​Microsoft.Android.Build.Tasks/​Utilities/​AssemblyCompressor.cs Adapt compressed assembly writes.
src/​Microsoft.Android.Build.Tasks/​Tasks/​GetAssetPacks.cs Adapt asset-pack cache writes.
src/​Microsoft.Android.Build.Tasks/​Tasks/​GenerateTrimmableTypeMap.cs Preserve absolute Java output path types.
src/​Microsoft.Android.Build.Tasks/​Tasks/​GenerateNativeApplicationConfigSources.cs Adapt bootstrap source writes.
src/​Microsoft.Android.Build.Tasks/​Tasks/​GenerateMissingTypeMapStubs.cs Adapt generated typemap stub writes.
src/​Microsoft.Android.Build.Tasks/​Tasks/​Aapt2Link.cs Adapt resource archive and text output copies.
src/​Microsoft.Android.Build.Tasks/​Tasks/​Aapt2Compile.cs Adapt archive enumeration and cleanup.
src/​Microsoft.Android.Build.BaseTasks/​MSBuildMultiThreadableTaskAnalyzedAttribute.cs Define the internal analyzer marker attribute.
src/​Microsoft.Android.Build.BaseTasks/​Files.cs Enforce explicit paths and environments; simplify helpers.
src-ThirdParty/​android-platform-tools-base/​SymbolWriter.cs Adapt generated R.java writes.
Documentation/​guides/​MSBuildBestPractices.md Document helper analysis and absolute-path contracts.
build-tools/​Xamarin.Android.Tools.BootstrapTasks/​Xamarin.Android.Tools.BootstrapTasks/​UnzipDirectoryChildren.cs Pass an absolute extraction destination.
build-tools/​Xamarin.Android.Tools.BootstrapTasks/​Xamarin.Android.Tools.BootstrapTasks/​CheckApiCompatibility.cs Adapt archive extraction path validation.

Review effort: Balanced

@jonathanpeppers

Copy link
Copy Markdown
Member Author

/azp run Xamarin.Android-PR

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

@jonathanpeppers

Copy link
Copy Markdown
Member Author

Internal Xamarin.Android-PR build 16171894 failed. I reviewed the failures, and none of them appear to be caused by this PR. They can be ignored:

Failure Why it can be ignored
Task: PoliCheck English / Run PoliCheck Post Analysis Fails on every main build. #13838 fixes it.
Task: Windows > Build & Smoke Test / Ensure no modified/untracked files Untracked .sarif file left by the Guardian tools. Fails on every main build.
Test: AndroidGradleProjectTests.BindPackLibrary (True,NativeAOT) Network error in the log: could not resolve.
Test: Microsoft.Android.TrimmingTests.BindingTrimmingTests.JavaExceptionIsActivatedAsBoundTypeWithoutWarnings (CoreClrPartialTrimming) The app on the emulator did not report a result. Not in the area of this PR.
Test: NuGetPackageVersionFinderTests.ShortTaskNameResolvesWithNuGetMetadataInFullMSBuild Fails on every main build.

The public CI (dnceng-public) is offline, so this internal build is the only CI result.

@jonathanpeppers

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

🚀 Android PR Reviewer has started processing this issue comment

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Needs Changes — CI is red; no actionable code findings.

Reviewed all 35 changed files and the affected helper/caller context at a92004b. Findings: 0 errors, 0 warnings, 0 suggestions. The explicit AbsolutePath boundary and removal of cached process-environment retry settings are consistent with the stated goal; legacy callers retain fallback resolution, and archive validation remains intact.

CI: Xamarin.Android-PR build [16171894]((devdiv.visualstudio.com/redacted) reports failure. CLA and the GitHub reviewer check passed; no public dotnet-android checks are present. The maintainer's comment attributes the failures to existing/infrastructure issues, but I could not independently verify that classification: the Azure timeline request requires authentication. No local builds or tests were run. This review does not establish that CI failures are unrelated or that the PR is merge-ready.

Generated by Android PR Reviewer for #13847 · copilot · gpt61 · ~70 AIC · ⌖ ~8 AIC · ⊞ 23.1K
Comment /review to run again

@jonathanpeppers jonathanpeppers added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Dec 1, 2026
@jonathanpeppers

Copy link
Copy Markdown
Member Author

@dalexsoto review

@dalexsoto

Copy link
Copy Markdown
Member

In response to @jonathanpeppers's request: My static review is queued for the next monitoring tick. I still need to read the retry-settings and AbsolutePath changes in src/Microsoft.Android.Build.BaseTasks/Files.cs, the new analyzer attribute, and the 33 related caller/test/documentation changes, including ResolveLibraryProjectImports.cs and FilesTests.cs. Those changed hunks have not been reviewed within this tick's time limit; there was no source-access error. This is a reviewer coverage gap, not a defect identified in the PR.

@dalexsoto dalexsoto left a comment

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.

The Files helpers consistently resolve paths through the task-scoped environment, and removing the process-wide retry cache avoids leaking settings between projects. Archive-path validation and the remaining internal callers remain compatible. No blocking issues found.

@jonathanpeppers

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

🚀 Android PR Reviewer has started processing this issue comment

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Needs Changes — CI remains red

Reviewed all 35 changed files at a92004b, including their full source and relevant callers. Source findings: 0 errors, 0 warnings, 0 suggestions. No substantiated code defects found. The absolute-path migration preserves archive canonicalization and unchanged-content behavior, while explicit task environments remove the process-wide retry cache.

CI: Xamarin.Android-PR build 16171894 failed. The maintainer's failure analysis attributes this to pre-existing tooling failures and unrelated tests, but I could not independently verify the logs: Azure DevOps CLI requires authentication. No public dotnet-android checks were returned; the two returned check runs passed. This verdict reflects unresolved CI status, not an identified source defect.

Static review only; no local builds or tests were run.

Generated by Android PR Reviewer for #13847 · copilot · gpt61 · ~88 AIC · ⌖ ~12 AIC · ⊞ 22.3K
Comment /review to run again

@jonathanpeppers

Copy link
Copy Markdown
Member Author

Why so many callers pass TaskEnvironment.Fallback

Could an optional TaskEnvironment parameter (default Fallback) or string overloads make this diff smaller? The diff adds 76 lines that use TaskEnvironment.Fallback:

  • 44 lines convert a path: TaskEnvironment.Fallback.GetAbsolutePath (path). They exist because the Files path parameters are now AbsolutePath.
  • 29 lines pass TaskEnvironment.Fallback as the retry-settings argument, but also create or pass an AbsolutePath.
  • 3 lines change only because of the retry-settings argument (one in ExtractJarsFromAar.cs, two in RemoveDirFixed.cs). Both files also have path changes.

Optional TaskEnvironment parameter (default Fallback): some lines get shorter, but no file drops out of the diff. A multithreaded task that leaves out the argument reads the process environment, and Microsoft.Build.TaskAuthoring.Analyzer does not report this, because it does not follow calls across assemblies.

string overloads that call TaskEnvironment.Fallback.GetAbsolutePath (): about 25 of the 30 caller files drop out of the diff. But a multithreaded task can then call the string overload with a relative path, and nothing reports it. The AbsolutePath parameters exist to close that gap: without an implicit conversion from string, each caller must root the path at compile time.

So the current approach stays. Each Fallback call site marks a task that is not multithreaded yet. When that task changes to MultithreadedAndroidTask, change TaskEnvironment.Fallback to the task's own TaskEnvironment, and its analyzer checks the call.

@jonathanpeppers
jonathanpeppers merged commit df9441a into main Dec 1, 2026
2 of 3 checks passed
@jonathanpeppers
jonathanpeppers deleted the jonathanpeppers-files-environment-multithreaded branch December 1, 2026 22:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants