msbuild icon indicating copy to clipboard operation
msbuild copied to clipboard

Fix NET task host MSB4216 handshake failure via child-side salt widening

Open ViktorHofer opened this issue 5 months ago • 5 comments

Context

A .NET Framework MSBuild host (e.g. VS) launching the .NET SDK task host can fail the handshake with:

error MSB4216: Could not run the "..." task because MSBuild could not create or connect
to a task host with runtime "NET" and architecture "x86".

The handshake salt is a case-sensitive hash of the SDK tools directory. For the .NET task host the two sides derive that directory string differently:

  • Host (.NET Framework MSBuild) passes the tools directory derived from the $(NetCoreSdkRoot) property, whose drive-letter casing is propagated verbatim from the environment (e.g. an Azure DevOps D:\a\_work\1\s sources path) and is never canonicalized.
  • Child (.NET task host) resolves its own path via Environment.ProcessPath (GetModuleFileNameW), which on these agents reports a lowercase drive letter.

When those casings differ (proven from the failing build''s comm traces: host D:\...\sdk\11.0.100-preview.5... vs child d:\...\sdk\11.0.100-preview.5..., salts -1569896665 vs -930293759) the salts differ and the handshake fails. Because the NET task host uses a sentinel version (99.99.99.99), host and child can be different MSBuild builds, so both must agree on the salt input.

Approach (child-side salt widening)

The child validates the salt, so the fix widens what the child accepts: when the received salt does not match, the .NET task host child also accepts the salt computed from its tools directory with the opposite drive-letter casing. Both spellings denote the same directory on Windows, so this only adds an accepted value.

This is the only approach that is provably non-regressing:

  • It is monotonic — the child accepts a superset of salts, so no host that connects successfully today can ever be rejected. There is no salt value change, hence no version-skew flag-day.
  • The added value denotes the same SDK directory, so node-reuse isolation is preserved (a genuinely different tools directory is still rejected — covered by a unit test).
  • It needs no Arcade workaround and no VS change: it fixes any VS-host / updated-SDK-child pairing as soon as the SDK carries this change.

Scope is limited to the Runtime="NET" task host path (IsNetTaskHost); other node types and the CLR2 task host are untouched.

The only pairing this cannot fix is an already-shipped old SDK child — no host change can alter how an old child hashes its own path. Customers get the fix by moving to an SDK that contains it.

Why the previous host-side approach was abandoned

The earlier revision normalized the launch path on the host with GetFinalPathNameByHandle, which always returns an uppercase drive letter. That matched neither direction reliably: it was a no-op for an already-uppercase host path (exactly the failing build), could not match a child whose loader-resolved path used a lowercase drive, and risked regressing configurations whose working casing was lowercase. The same uppercasing is also why the Arcade workaround (dotnet/arcade#17002) silently no-op''d.

Changes Made

  • src/Framework/BackEnd/Handshake.cs: for the .NET task host, precompute the salt for the tools directory with the opposite drive-letter casing (_netTaskHostSaltDriveCaseVariant) and expose IsNetTaskHostSaltMatch. Helper TryGetDriveLetterCaseVariant returns false off-Windows and for driveless/UNC paths, so non-Windows and non-drive cases are unchanged.
  • src/Shared/NodeEndpointOutOfProcBase.cs: in the child''s IsHandshakePartValid, add a Salt case inside the existing #if NET NET-task-host allowance block that accepts the drive-case variant.
  • src/Build.UnitTests/BackEnd/AppHostSupport_Tests.cs: three Windows-only tests — accepts the drive-casing variant, rejects an unrelated SDK directory (isolation preserved), and confirms non-NET-task-host nodes do not widen acceptance.
  • The previous host-side canonicalization in NodeProviderOutOfProcTaskHost.cs and the GetFinalPathNameByHandle entry in NativeMethods.txt are reverted.

Testing

  • Handshake_NetTaskHost_AcceptsDriveLetterCasingDifference, Handshake_NetTaskHost_RejectsUnrelatedToolsDirectory, Handshake_NonNetTaskHost_DoesNotWidenSaltAcceptance — pass (net10.0).
  • Existing Handshake_ExternalPathCanMismatch_DefaultAlwaysMatches — still passes (no regression).
  • Engine, MSBuild, MSBuildTaskHost and the test project build clean (0 warnings).

Notes

  • See #14026 for the full root-cause analysis and the comm-trace / binlog evidence.
  • No new warnings or errors are introduced, so this is safe under /WarnAsError; no Change Wave is needed (pure compatibility widening).

ViktorHofer avatar Jun 11 '26 10:06 ViktorHofer

Converting back to draft. This approach - changing the salt computation - would break existing scenarios.

ViktorHofer avatar Jun 11 '26 13:06 ViktorHofer

For consideration: possible subdirectory-casing regression in NormalizePathCasing

I think the host-side normalization may be canonicalizing a superset of what the child task host does, which could break the handshake in a scenario that works today. Sharing the analysis + a small experiment in case it's useful.

The two APIs are not equivalent

The child derives its tools directory from Environment.ProcessPath / AppContext.BaseDirectory, whereas this PR canonicalizes via GetFinalPathNameByHandle. I launched the same exe (on-disk folder casing AbcDef) through differently-cased paths and printed both:

Launched as Child ProcessPath / AppContext.BaseDir GetFinalPathNameByHandle
D:\rtprobe\AbcDef\probe.exe D:\rtprobe\AbcDef\ \\?\D:\rtprobe\AbcDef\
d:\rtprobe\abcdef\probe.exe D:\rtprobe\abcdef\ \\?\D:\rtprobe\AbcDef\
D:\RTPROBE\ABCDEF\probe.exe D:\RTPROBE\ABCDEF\ \\?\D:\rtprobe\AbcDef\

So:

  • The child canonicalizes only the drive letter (forced to the OS-registered casing) and preserves the launch-provided casing of every subdirectory.
  • GetFinalPathNameByHandle rewrites every component to true on-disk casing.

The original MSB4216 was only a drive-letter difference precisely because the child preserves subdirectory casing. This is also why CI passes here: in the Azure DevOps repro the agent creates the folders with the same casing it reports, so only the drive diverges.

Scenario that works today but would break after this change

Condition: a subdirectory in $(NetCoreSdkRoot) is cased differently from on-disk while the drive letter already matches (e.g. %USERPROFILE% = C:\Users\john while disk is C:\Users\John, or an SDK path supplied via DOTNET_ROOT / global.json / a mapped or subst drive whose folder casing differs from disk). This is the same "casing propagated verbatim from the environment" root cause described in the PR, just on a non-drive component.

  • Today: host salt input = provided string C:\Users\john\.dotnet\sdk\x.y.z; child derives C:\Users\john\... (subdir preserved, drive already C:). Match -> handshake succeeds.
  • After this change: NormalizePathCasing -> C:\Users\John\... (on-disk John). It differs from the input only by casing, so string.Equals(..., OrdinalIgnoreCase) is true and the canonical form is adopted. The child still reports C:\Users\john\... (child unmodified) -> different salt -> MSB4216.

The OrdinalIgnoreCase guard doesn't catch this

if (!string.IsNullOrEmpty(canonicalPath) &&
    string.Equals(canonicalPath, path, StringComparison.OrdinalIgnoreCase))
    return canonicalPath;

The guard is meant to ensure "purely a casing change," but a casing change in a subdirectory is exactly the harmful case here, and OrdinalIgnoreCase treats it as safe. The guard rejects structural changes (symlinks/8.3) but not the subdir-casing rewrite that desyncs host and child. NormalizePathCasing_IsIndependentOfInputCasing only varies the drive letter, so it wouldn't exercise this path.

Possible direction

To reproduce the child exactly, the host could canonicalize the drive letter only and preserve all subdirectory casing from the provided path - e.g. take the root/drive casing from GetFinalPathNameByHandle (or a volume query) and splice back the original remainder (canonicalDrive + originalRemainder). That fixes the reported drive-letter bug without ever rewriting subdirectory casing, keeping host and child byte-for-byte aligned in all cases.

Severity is latent (won't reproduce on the exact Azure DevOps repro), but it would surface on hosts where any folder's on-disk casing differs from the property/environment casing (USERPROFILE case skew, env-var-supplied SDK paths, subst/mapped drives, restored/copied trees) - and the failure mode is the same MSB4216 this PR removes.

Happy to be wrong if the child is actually expected to canonicalize full-path casing somewhere I've missed - just wanted to flag it before merge.

JanProvaznik avatar Jun 12 '26 12:06 JanProvaznik

Waiting on the workaround to actually work. The test build is still failing: https://dnceng.visualstudio.com/internal/_build/results?buildId=2998823&view=results

ViktorHofer avatar Jun 15 '26 10:06 ViktorHofer

Direction change: host-side canonicalization → child-side salt widening

Pushed a2ef63f534, which reverts the host-side GetFinalPathNameByHandle approach and replaces it with child-side salt widening. Title/description updated accordingly.

Why the switch. I pulled the comm traces + binlog from the failing build (dnceng 2998823) and confirmed the divergence is purely the drive letter:

Side tools directory salt
Host (VS 18.6.3, $(NetCoreSdkRoot)) D:\a\_work\1\s\.dotnet\sdk\11.0.100-preview.5... -1569896665
Child (.NET task host, Environment.ProcessPath) d:\a\_work\1\s\.dotnet\sdk\11.0.100-preview.5... -930293759

GetFinalPathNameByHandle always returns an uppercase drive, so the host-side fix (and the Arcade workaround in dotnet/arcade#17002) was a no-op on this already-uppercase host path and could never match the child''s lowercase d:. There is no cheap host-side API that reproduces the .NET loader''s casing, so any host-side canonicalization is guessing.

The new approach makes the child — which is the side that validates the salt — accept the salt computed for the opposite drive-letter casing of its own tools directory. Properties:

  • Monotonic / non-regressing: the child only adds an accepted value, so no host that connects today can be rejected; there is no salt-value change and therefore no version-skew flag-day.
  • Isolation preserved: the added value is the same directory; an unrelated SDK dir is still rejected (unit-tested).
  • No Arcade and no VS change required: fixes any VS-host / updated-SDK-child pairing once the SDK carries it.
  • Scoped to the Runtime="NET" task host path only; CLR2 and other node types untouched.

The only thing it can''t fix is an already-shipped old SDK child (no host change can alter how an old child hashes its own path) — those are picked up by moving to a fixed SDK.

On the Arcade workaround (dotnet/arcade#17002)

It can''t work as written for the same uppercasing reason. A corrected interim is possible but constrained: the reliable form has to ask the SDK for the exact path it will hash (the host can''t predict the loader casing); a cheaper CI-only variant is to lowercase the work-drive letter of $(NetCoreSdkRoot). Given this child-side fix needs no casing prediction, Arcade would only be a first-party stopgap for builds still on an old SDK.

ViktorHofer avatar Jun 15 '26 12:06 ViktorHofer

✅ Validated this fix end-to-end locally (Summary written by COPILOT)

I built the bootstrap from this branch and confirmed the child-side salt widening fixes the MSB4216 handshake failure in a live cross-process handshake (Framework host → .NET task host), with a controlled A/B that reproduces the exact drive-letter-casing divergence from the bug.

Test setup

Because a normal dev volume doesn't canonicalize drive-letter casing the way the failing CI agents do (so host and child naturally agree), I forced the divergence:

  • Routed the .NET task host to the bootstrap (so the child actually runs this branch's code, not the installed SDK): DOTNET_MSBUILD_SDK_RESOLVER_CLI_DIR=artifacts\bin\bootstrap\core
  • Mimicked the agent with a temporary, env-gated hook in the child that flips the drive-letter casing of its own tools directory before computing the handshake salt — reproducing exactly the "host D: vs child d:" split from #14026.
  • Ran a Runtime="NET" / TaskHostFactory task via the bootstrap .NET Framework MSBuild.exe, with MSBUILDDEBUGCOMM=1 to capture the handshake salts.

A/B result

Scenario Drive-case flip Salt-variant acceptance Host salt Child expected Result
With the fix D: → d: enabled (this PR) -317269178 2067888120 ✅ accepted via the drive-case variant → build succeeded
Negative control D: → d: disabled -317269178 2067888120 ❌ MSB4216

The negative control reproduces the original failure byte-for-byte:

Handshake failed. Received -317269178 from host for Salt but expected 2067888120.
Probably the host is a different MSBuild build.
...
error MSB4216: Could not run the "ExampleTask" task because MSBuild could not create
or connect to a task host with runtime "NET" and architecture "*".

With the fix enabled, the child receives the same diverging salt (-317269178, computed by the host from the D:-cased tools directory) but accepts it via IsNetTaskHostSaltMatch, and the handshake completes — the task runs in the .NET task host and the build succeeds.

Also verified

  • Handshake_NetTaskHost_* unit tests pass (net10.0).
  • The matching-case NetTaskHostTest_AppHostFromResolvedSdk E2E test still passes (no regression).
  • Engine / MSBuild / task host projects build clean (0 warnings).

AlesProkop avatar Jun 23 '26 11:06 AlesProkop