-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathAppHostSupport_Tests.cs
More file actions
283 lines (237 loc) · 13.3 KB
/
AppHostSupport_Tests.cs
File metadata and controls
283 lines (237 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Framework;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
using Microsoft.Build.UnitTests;
using Shouldly;
using Xunit;
#nullable disable
namespace Microsoft.Build.Engine.UnitTests.BackEnd
{
/// <summary>
/// Tests for MSBuild App Host support functionality.
/// Tests the DOTNET_ROOT environment variable handling for app host bootstrap.
/// </summary>
public sealed class AppHostSupport_Tests
{
private readonly ITestOutputHelper _output;
private readonly string _dotnetHostPath = NativeMethodsShared.IsWindows
? @"C:\Program Files\dotnet\dotnet.exe"
: "/usr/share/dotnet/dotnet";
public AppHostSupport_Tests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void CreateDotnetRootEnvironmentOverrides_SetsDotnetRootFromHostPath()
{
var overrides = DotnetHostEnvironmentHelper.CreateDotnetRootEnvironmentOverrides(_dotnetHostPath);
overrides.ShouldNotBeNull();
overrides.ShouldContainKey("DOTNET_ROOT");
string expectedDotnetRoot = Path.GetDirectoryName(_dotnetHostPath);
overrides["DOTNET_ROOT"].ShouldBe(expectedDotnetRoot);
}
[Fact]
public void CreateDotnetRootEnvironmentOverrides_ClearsArchitectureSpecificVariables()
{
var overrides = DotnetHostEnvironmentHelper.CreateDotnetRootEnvironmentOverrides(_dotnetHostPath);
// Assert - architecture-specific variables should be set to null (to be cleared)
overrides.ShouldContainKey("DOTNET_ROOT_X64");
overrides["DOTNET_ROOT_X64"].ShouldBeNull();
overrides.ShouldContainKey("DOTNET_ROOT_X86");
overrides["DOTNET_ROOT_X86"].ShouldBeNull();
overrides.ShouldContainKey("DOTNET_ROOT_ARM64");
overrides["DOTNET_ROOT_ARM64"].ShouldBeNull();
}
[WindowsOnlyTheory]
[InlineData(@"C:\custom\sdk\dotnet.exe", @"C:\custom\sdk")]
[InlineData(@"D:\tools\dotnet\dotnet.exe", @"D:\tools\dotnet")]
public void CreateDotnetRootEnvironmentOverrides_HandlesVariousPaths_Windows(string hostPath, string expectedRoot)
{
var overrides = DotnetHostEnvironmentHelper.CreateDotnetRootEnvironmentOverrides(hostPath);
overrides["DOTNET_ROOT"].ShouldBe(expectedRoot);
}
[UnixOnlyTheory]
[InlineData("/usr/local/share/dotnet/dotnet", "/usr/local/share/dotnet")]
[InlineData("/home/user/.dotnet/dotnet", "/home/user/.dotnet")]
public void CreateDotnetRootEnvironmentOverrides_HandlesVariousPaths_Unix(string hostPath, string expectedRoot)
{
var overrides = DotnetHostEnvironmentHelper.CreateDotnetRootEnvironmentOverrides(hostPath);
overrides["DOTNET_ROOT"].ShouldBe(expectedRoot);
}
[Fact]
public void ClearBootstrapDotnetRootEnvironment_ClearsVariablesNotInOriginalEnvironment()
{
using (TestEnvironment env = TestEnvironment.Create(_output))
{
// Arrange - set DOTNET_ROOT variants that simulate app host bootstrap
env.SetEnvironmentVariable("DOTNET_ROOT", @"C:\TestDotnet");
env.SetEnvironmentVariable("DOTNET_ROOT_X64", @"C:\TestDotnetX64");
// This might seem redundant, but it's not.
// ClearBootstrapDotnetRootEnvironment is a production method that alters env variables directly via Environment class.
// This clears DOTNET_ROOT_X86 which might have been originally set.
// To ensure that DOTNET_ROOT_X86 is restored, we set it to itself so that TestEnvironment.Dispose restores it back.
env.SetEnvironmentVariable("DOTNET_ROOT_X86", Environment.GetEnvironmentVariable("DOTNET_ROOT_X86"));
// Original environment does NOT have these variables
var originalEnvironment = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
DotnetHostEnvironmentHelper.ClearBootstrapDotnetRootEnvironment(originalEnvironment);
Environment.GetEnvironmentVariable("DOTNET_ROOT").ShouldBeNull();
Environment.GetEnvironmentVariable("DOTNET_ROOT_X64").ShouldBeNull();
}
}
[Fact]
public void ClearBootstrapDotnetRootEnvironment_PreservesVariablesInOriginalEnvironment()
{
using (TestEnvironment env = TestEnvironment.Create(_output))
{
// Arrange - set DOTNET_ROOT that was in the original environment
string originalValue = @"C:\OriginalDotnet";
env.SetEnvironmentVariable("DOTNET_ROOT", originalValue);
// Register other DOTNET_ROOT variants with TestEnvironment so cleanup works correctly.
// These will be cleared by the helper if not in originalEnvironment.
env.SetEnvironmentVariable("DOTNET_ROOT_X64", null);
env.SetEnvironmentVariable("DOTNET_ROOT_X86", null);
env.SetEnvironmentVariable("DOTNET_ROOT_ARM64", null);
// Original environment HAS DOTNET_ROOT
var originalEnvironment = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["DOTNET_ROOT"] = originalValue
};
DotnetHostEnvironmentHelper.ClearBootstrapDotnetRootEnvironment(originalEnvironment);
// Assert - DOTNET_ROOT should be preserved since it was in original environment
Environment.GetEnvironmentVariable("DOTNET_ROOT").ShouldBe(originalValue);
}
}
[Fact]
public void ClearBootstrapDotnetRootEnvironment_HandlesMixedScenario()
{
using (TestEnvironment env = TestEnvironment.Create(_output))
{
string originalDotnetRoot = @"C:\OriginalDotnet";
string bootstrapX64 = @"C:\BootstrapX64";
env.SetEnvironmentVariable("DOTNET_ROOT", originalDotnetRoot);
env.SetEnvironmentVariable("DOTNET_ROOT_X64", bootstrapX64);
env.SetEnvironmentVariable("DOTNET_ROOT_X86", @"C:\BootstrapX86");
// Original environment has DOTNET_ROOT but not the architecture-specific ones
var originalEnvironment = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["DOTNET_ROOT"] = originalDotnetRoot
};
DotnetHostEnvironmentHelper.ClearBootstrapDotnetRootEnvironment(originalEnvironment);
Environment.GetEnvironmentVariable("DOTNET_ROOT").ShouldBe(originalDotnetRoot); // Preserved
Environment.GetEnvironmentVariable("DOTNET_ROOT_X64").ShouldBeNull(); // Cleared
Environment.GetEnvironmentVariable("DOTNET_ROOT_X86").ShouldBeNull(); // Cleared
Environment.GetEnvironmentVariable("DOTNET_ROOT_ARM64").ShouldBeNull(); // Was already null
}
}
/// <summary>
/// Regression test for the macOS /tmp → /private/tmp symlink issue (MSB4216).
///
/// Before the fix, the parent passed $(NetCoreSdkRoot) as toolsDirectory —
/// an MSBuild property that can contain unresolved symlinks. The child always
/// defaults to BuildEnvironmentHelper (which resolves symlinks via
/// AppContext.BaseDirectory). This caused different handshake hashes.
///
/// After the fix (on .NET Core), the parent also omits toolsDirectory,
/// so both sides default to BuildEnvironmentHelper.
///
/// This test proves that an arbitrary external path (simulating $(NetCoreSdkRoot))
/// CAN produce a different handshake than the BuildEnvironmentHelper default,
/// and that omitting toolsDirectory on both sides always matches.
/// </summary>
#if NET
[Fact]
public void Handshake_ExternalPathCanMismatch_DefaultAlwaysMatches()
{
// Use explicit NET runtime and current architecture to ensure the NET
// HandshakeOptions flag is set, which is required for passing toolsDirectory
// to the Handshake constructor.
var netTaskHostParams = new TaskHostParameters(
runtime: XMakeAttributes.MSBuildRuntimeValues.net,
architecture: XMakeAttributes.GetCurrentMSBuildArchitecture(),
dotnetHostPath: null,
msBuildAssemblyPath: null);
HandshakeOptions options = CommunicationsUtilities.GetHandshakeOptions(
taskHost: true,
taskHostParameters: netTaskHostParams,
nodeReuse: false);
// Simulate child: no explicit toolsDirectory → defaults to BuildEnvironmentHelper.
var childHandshake = new Handshake(options);
// After the fix: parent also omits toolsDirectory → same default → must match.
var parentFixedHandshake = new Handshake(options);
parentFixedHandshake.GetKey().ShouldBe(childHandshake.GetKey(),
"When both parent and child omit toolsDirectory, they must produce " +
"identical handshake keys (both default to BuildEnvironmentHelper).");
// Before the fix: parent passed an external path ($(NetCoreSdkRoot)).
// If that path differs from BuildEnvironmentHelper (e.g. symlinks),
// the handshake would mismatch.
string externalPath = Path.Combine(Path.GetTempPath(), $"different_path_{Guid.NewGuid():N}");
var parentBrokenHandshake = new Handshake(options, externalPath);
parentBrokenHandshake.GetKey().ShouldNotBe(childHandshake.GetKey(),
"An arbitrary external toolsDirectory should produce a different handshake " +
"than the BuildEnvironmentHelper default, proving the mismatch scenario.");
}
#endif
/// <summary>
/// Proves that using a symlinked path vs a resolved path in the handshake
/// produces DIFFERENT keys — demonstrating the exact bug on macOS where
/// /tmp is a symlink to /private/tmp.
///
/// This test creates a real symlink to prove the mismatch. It only runs on
/// Unix (.NET Core) where symlinks are natively supported and the scenario is relevant.
/// </summary>
#if NET
[UnixOnlyFact]
public void Handshake_WithSymlinkedToolsDirectory_ProducesDifferentKey()
{
// Create a real directory and a symlink pointing to it.
string realDir = Path.Combine(Path.GetTempPath(), $"msbuild_test_real_{Guid.NewGuid():N}");
string symlinkDir = Path.Combine(Path.GetTempPath(), $"msbuild_test_link_{Guid.NewGuid():N}");
try
{
Directory.CreateDirectory(realDir);
Directory.CreateSymbolicLink(symlinkDir, realDir);
HandshakeOptions options = CommunicationsUtilities.GetHandshakeOptions(
taskHost: true,
taskHostParameters: TaskHostParameters.Empty,
nodeReuse: false);
// Parent using the symlink path (like $(MSBuildThisFileDirectory) would on macOS /tmp)
var symlinkHandshake = new Handshake(options, symlinkDir);
// Child using the resolved real path (like AppContext.BaseDirectory resolves /private/tmp)
var realHandshake = new Handshake(options, realDir);
// These produce DIFFERENT keys — this is the bug.
// If these were used as parent vs child toolsDirectory, the pipe names would
// differ and the parent could never connect to the child → MSB4216.
symlinkHandshake.GetKey().ShouldNotBe(realHandshake.GetKey(),
"Symlinked and resolved paths should produce different handshake keys " +
"(they are different strings). This demonstrates why the parent must NOT " +
"use an MSBuild property path that may contain unresolved symlinks — it " +
"must use MSBuildToolsDirectoryRoot (same source as the child) instead.");
// Using the SAME source (MSBuildToolsDirectoryRoot) on both sides always matches,
// regardless of symlinks, because both compute it from AppContext.BaseDirectory.
string consistentDir = BuildEnvironmentHelper.Instance.MSBuildToolsDirectoryRoot;
var parentFixed = new Handshake(options, consistentDir);
var childDefault = new Handshake(options);
parentFixed.GetKey().ShouldBe(childDefault.GetKey(),
"Using MSBuildToolsDirectoryRoot on both sides must produce matching keys.");
}
finally
{
if (Directory.Exists(symlinkDir))
{
Directory.Delete(symlinkDir);
}
if (Directory.Exists(realDir))
{
Directory.Delete(realDir);
}
}
}
#endif
}
}