Skip to content
Open
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
23 changes: 23 additions & 0 deletions documentation/project-docs/developer-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,29 @@ Use `BuildStarted` and `BuildFinished` to manage state for one build. `Shutdown`
one logger instance. It does not necessarily end the process. A persistent server can run
multiple builds in one process. Refresh the environment and trace context for each build.

### MSBuild SDK-location discovery

The CLI lets MSBuild discover SDK locations from its selected toolset. It does not
generate `MSBuildExtensionsPath` or `MSBuildSDKsPath` environment variables. Explicit
environment overrides remain inherited by MSBuild and child processes.
[`MSBuildForwardingAppWithoutLogging`](../../src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs)
still supplies `DOTNET_HOST_PATH` so tasks can invoke the selected .NET host.

Direct evaluation for `dotnet run` and MTP `dotnet test` follows the same discovery
rules. The CLI does not add an `MSBuildExtensionsPath` global property.
[`CommonRunHelpers`](../../src/Cli/dotnet/Commands/Run/CommonRunHelpers.cs)
preserves caller-supplied properties.

This prevents new CLI invocations from leaking SDK-location defaults into nested
invocations that select another SDK. An older parent CLI can still supply stale
values. The child preserves those values because it cannot distinguish them from
intentional overrides.

Discovery tests must start a fresh child process without `MSBUILD_EXE_PATH`,
`MSBuildSDKsPath`, or `MSBuildExtensionsPath`. Remove these environment entries
rather than assigning empty strings. The test harness supplies toolset paths for
in-process tests, which can otherwise hide discovery failures.

## Running tests

### Windows
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,6 @@ public static string MSBuildVersion
/// </remarks>
private ForwardingAppImplementation? _forwardingApp;

/// <summary>
/// A test-only hook for the MSBuildExtensionsPath, which is a key location that MSBuild logic is read from by the MSBuild Common Targets.
/// </summary>
internal static string? MSBuildExtensionsPathTestHook = null;

/// <summary>
/// Structure describing the parsed and forwarded MSBuild arguments for this command.
/// </summary>
Expand Down Expand Up @@ -342,19 +337,16 @@ public static string GetMSBuildSDKsPath()

/// <summary>
/// Gets the required environment variables for MSBuild.
/// The Common Targets require specific environment variables to be set in order to function correctly:
/// MSBuild discovers SDK locations from its toolset unless the caller supplies explicit overrides.
/// Do not publish SDK-location defaults in the environment: nested CLI invocations can select a different SDK.
/// <list type="bullet">
/// <item><term>MSBuildExtensionsPath</term><description>The path to the 'MSBuild extensions' - where the Common Targets themselves will be loaded from. Also where SDK Resolvers will be loaded from.</description></item>
/// <item><term>MSBuildSDKsPath</term><description>The path to the 'MSBuild SDKs' - where the SDKs will be loaded from by the default resolver. </description></item>
/// <item><term>DOTNET_HOST_PATH</term><description>The path to the .NET SDK host - used to execute .NET applications by targets in the Common Targets that need to run managed .NET binaries that are not shipped with apphosts.</description></item>
/// </list>
/// </summary>
internal static Dictionary<string, string?> GetMSBuildRequiredEnvironmentVariables()
{
return new()
{
{ "MSBuildExtensionsPath", MSBuildExtensionsPathTestHook ?? Environment.GetEnvironmentVariable("MSBuildExtensionsPath") ?? SdkPaths.SdkDirectory },
{ "MSBuildSDKsPath", GetMSBuildSDKsPath() },
{ "DOTNET_HOST_PATH", GetDotnetPath() },
};
}
Expand Down
9 changes: 8 additions & 1 deletion src/Cli/dotnet-aot/SdkRootResolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ the module self-locates.
processes. A caller-provided value (e.g. a `runtimeconfig.json` `configProperties`
entry) is honored, but must point to an existing directory or the bridge errors out.
- **Read.** In-repo code reads `SdkPaths.SdkDirectory` (in
`Microsoft.DotNet.Cli.Utils`), which resolves the `Microsoft.DotNet.Sdk.Root`
`Microsoft.DotNet.Cli.CoreUtils`), which resolves the `Microsoft.DotNet.Sdk.Root`
AppContext value -> the SDK assembly directory -> `AppContext.BaseDirectory` (once,
cached). Out-of-repo code (MSBuild tasks, NuGet, the runtime) reads the
`Microsoft.DotNet.Sdk.Root` AppContext value first, else its existing BCL logic. The
Expand All @@ -71,6 +71,13 @@ The same forwarding code is shared by both CLIs and therefore consistently uses
`SdkPaths.SdkDirectory`; this remains equivalent to `AppContext.BaseDirectory` in
the normal managed SDK layout.

`MSBuildForwardingAppWithoutLogging` uses this directory to select `MSBuild.dll`.
It does not generate `MSBuildSDKsPath` or `MSBuildExtensionsPath` environment
variables. MSBuild discovers these locations from its toolset unless the caller
supplies explicit overrides. `DOTNET_HOST_PATH` still identifies the .NET host.
See [MSBuild SDK-location discovery](../../../documentation/project-docs/developer-guide.md#msbuild-sdk-location-discovery)
for inherited-override limitations and test-environment requirements.

## Testing

The authoritative integration layout is produced by the full Debug redist build:
Expand Down
7 changes: 1 addition & 6 deletions src/Cli/dotnet/Commands/Run/CommonRunHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,16 +98,11 @@ internal static bool TrySplitApplicationArgumentsAtDoubleDash(
}

/// <summary>
/// Creates a dictionary of global properties for MSBuild from the command line arguments.
/// This includes properties that are passed via the command line, as well as some
/// properties that are set to improve performance at the cost of correctness -
/// specifically Compile, None, and EmbeddedResource items are not globbed by default.
/// See <see cref="Commands.Restore.RestoringCommand.RestoreOptimizationProperties"/> for more details.
/// Creates a mutable copy of command-line global properties for direct MSBuild evaluation.
/// </summary>
public static Dictionary<string, string> GetGlobalPropertiesFromArgs(MSBuildArgs msbuildArgs)
{
var globalProperties = msbuildArgs.GlobalProperties?.ToDictionary() ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
globalProperties[Constants.MSBuildExtensionsPath] = AppContext.BaseDirectory;
return globalProperties;
}

Expand Down
1 change: 0 additions & 1 deletion src/Cli/dotnet/Commands/Run/RunCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1219,7 +1219,6 @@ private void SendProjectBasedTelemetry(LaunchProfile? launchSettings)
{
var globalProperties = MSBuildArgs.GlobalProperties?.ToDictionary() ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
globalProperties[Constants.EnableDefaultItems] = "false";
Comment thread
baronfel marked this conversation as resolved.
Resolved
globalProperties[Constants.MSBuildExtensionsPath] = AppContext.BaseDirectory;

using var collection = new ProjectCollection(globalProperties: globalProperties);
var project = collection.LoadProject(ProjectFileFullPath).CreateProjectInstance();
Expand Down
5 changes: 0 additions & 5 deletions test/Microsoft.NET.TestFramework/SdkTestContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -334,11 +334,6 @@ public static void Initialize()
Environment.SetEnvironmentVariable(
"MSBuildSDKsPath",
Path.Combine(testContext.ToolsetUnderTest.SdksPath));

#if NETCOREAPP
MSBuildForwardingAppWithoutLogging.MSBuildExtensionsPathTestHook =
testContext.ToolsetUnderTest.SdkFolderUnderTest;
#endif
}

public static string? GetRepoRoot()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project>
<Target Name="CheckDiscoveryEnvironment" BeforeTargets="Build;ComputeRunArguments">
<Error Condition="$([System.Environment]::GetEnvironmentVariable('MSBuildSDKsPath')) != ''"
Text="MSBuildSDKsPath leaked into the build environment." />
<Error Condition="$([System.Environment]::GetEnvironmentVariable('MSBuildExtensionsPath')) != ''"
Text="MSBuildExtensionsPath leaked into the build environment." />
</Target>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<Project>
<PropertyGroup>
<DiscoveryExtensionsPath>$(MSBuildThisFileDirectory)</DiscoveryExtensionsPath>
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<Project Sdk="Discovery.Sdk">
<Import Project="$(MSBuildExtensionsPath)\Discovery.props" />
</Project>
23 changes: 23 additions & 0 deletions test/TestAssets/TestProjects/MSBuildSdkDiscovery/Probe.proj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>$(CurrentTargetFramework)</TargetFramework>
</PropertyGroup>
<Target Name="Report">
<Error Condition="$([System.Environment]::GetEnvironmentVariable('MSBuildSDKsPath')) != ''"
Text="MSBuildSDKsPath leaked into the build environment." />
<Error Condition="$([System.Environment]::GetEnvironmentVariable('MSBuildExtensionsPath')) != ''"
Text="MSBuildExtensionsPath leaked into the build environment." />
<WriteLinesToFile File="$(MSBuildProjectDirectory)\paths.txt"
Lines="$(MSBuildToolsPath);$(MSBuildExtensionsPath);$(MSBuildSDKsPath);$([System.IO.Path]::GetFullPath('$(MicrosoftNETBuildTasksAssembly)'))"
Overwrite="true" />
</Target>
<Target Name="Probe" DependsOnTargets="Report">
<MSBuild Projects="$(MSBuildProjectFullPath)"
Targets="Report"
Properties="DiscoveryWorker=true"
BuildInParallel="true" />
<Exec Condition="'$(Nested)' != 'true'"
WorkingDirectory="$(MSBuildProjectDirectory)\nested"
Command="&quot;$(DOTNET_HOST_PATH)&quot; msbuild Probe.proj -t:Probe -p:Nested=true -p:DiscoveryNodeReuse=$(DiscoveryNodeReuse) -nr:$(DiscoveryNodeReuse) -bl:2-{}.binlog" />
</Target>
</Project>
3 changes: 3 additions & 0 deletions test/TestAssets/TestProjects/MSBuildSdkDiscovery/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#:property PublishAot=false

System.Console.WriteLine("SDK discovery succeeded");
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<Project>
<PropertyGroup>
<DiscoverySdkPath>$(MSBuildThisFileDirectory)</DiscoverySdkPath>
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<Project />
12 changes: 6 additions & 6 deletions test/dotnet-aot.Tests/MSBuildEvaluationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ public void MSBuildForwardingUsesVersionedSdkDirectory()
forceOutOfProc: true);

Assert.AreEqual(Path.Combine(sdkDirectory, "MSBuild.dll"), forwardingApp.MSBuildPath);
Assert.AreEqual(
Path.Combine(sdkDirectory, "Sdks"),
forwardingApp.GetProcessStartInfo().Environment["MSBuildSDKsPath"]);
Assert.AreEqual(
sdkDirectory,
forwardingApp.GetProcessStartInfo().Environment["MSBuildExtensionsPath"]);
foreach (string name in new[] { "MSBuildSDKsPath", "MSBuildExtensionsPath" })
{
Assert.IsFalse(MSBuildForwardingAppWithoutLogging.GetMSBuildRequiredEnvironmentVariables().ContainsKey(name));
forwardingApp.GetProcessStartInfo().Environment.TryGetValue(name, out string? actual);
Assert.AreEqual(Environment.GetEnvironmentVariable(name), actual);
}
}

[TestMethod]
Expand Down
148 changes: 148 additions & 0 deletions test/dotnet.Tests/CommandTests/MSBuild/GivenMSBuildSdkDiscovery.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.Json;
using Microsoft.Build.Framework;
using Microsoft.Build.Logging.StructuredLogger;

namespace Microsoft.DotNet.Cli.MSBuild.Tests;

[TestClass]
public sealed class GivenMSBuildSdkDiscovery : SdkTest
{
[TestMethod]
public void NestedInvocationsDiscoverTheirSelectedToolset()
{
var toolset = SdkTestContext.Current.ToolsetUnderTest;
var asset = TestAssetsManager.CopyTestAsset("MSBuildSdkDiscovery", identifier: Guid.NewGuid().ToString("N")).WithSource();
string nestedDirectory = Path.Combine(asset.Path, "nested");
string alternateRoot = Path.Combine(asset.Path, "alternate");
string alternateSdk = Path.Combine(alternateRoot, "sdk", "99.0.100");

Directory.CreateDirectory(nestedDirectory);
File.Copy(Path.Combine(asset.Path, "Probe.proj"), Path.Combine(nestedDirectory, "Probe.proj"), overwrite: true);
Directory.CreateDirectory(alternateSdk);
foreach (string file in Directory.EnumerateFiles(toolset.SdkFolderUnderTest))
{
File.Copy(file, Path.Combine(alternateSdk, Path.GetFileName(file)));
}
foreach (string directory in Directory.EnumerateDirectories(toolset.SdkFolderUnderTest))
{
Directory.CreateSymbolicLink(Path.Combine(alternateSdk, Path.GetFileName(directory)), directory);
}
Directory.CreateSymbolicLink(Path.Combine(alternateRoot, "shared"), Path.Combine(toolset.DotNetRoot, "shared"));
Directory.CreateSymbolicLink(Path.Combine(alternateRoot, "host"), Path.Combine(toolset.DotNetRoot, "host"));

WriteGlobalJson(asset.Path, toolset.DotNetRoot, toolset.SdkVersion);
WriteGlobalJson(nestedDirectory, alternateRoot, "99.0.100");

int invocation = 0;
foreach (var (outOfProc, useServer, nodeReuse) in new[]
{
(false, false, false),
(true, false, false),
(false, true, false),
(false, true, true)
})
{
string binlog = Path.Combine(asset.Path, $"{++invocation}.binlog");
var command = CreateDiscoveryCommand(asset.Path, "msbuild");
command.WithEnvironmentVariable("DOTNET_CLI_RUN_MSBUILD_OUTOFPROC", outOfProc.ToString());
command.WithEnvironmentVariable("DOTNET_CLI_USE_MSBUILD_SERVER", useServer.ToString());
command.WithEnvironmentVariable("MSBUILDUSESERVER", useServer ? "1" : "0");
command.WithEnvironmentVariable("MSBUILDNOINPROCNODE", "1");
var result = command.Execute("Probe.proj", "-t:Probe", $"-nr:{nodeReuse}",
$"-p:DiscoveryUseServer={useServer}", $"-p:DiscoveryNodeReuse={nodeReuse}", $"-bl:{binlog}");
if (File.Exists(binlog))
{
TestContext.AddResultFile(binlog);
}
result.Should().Pass();

AssertPaths(asset.Path, toolset.SdkFolderUnderTest);
AssertPaths(nestedDirectory, alternateSdk);

var events = BinaryLog.ReadRecords(binlog).Select(record => record.Args).ToArray();
events.OfType<TargetStartedEventArgs>().Where(args => args.TargetName == "Report")
.Should().Contain(args => args.BuildEventContext!.NodeId > 1);
}
}

[TestMethod]
public void EvaluationWithoutBuildDiscoversSdkImports()
{
var asset = TestAssetsManager.CopyTestAsset("MSBuildSdkDiscovery").WithSource();
var toolset = SdkTestContext.Current.ToolsetUnderTest;
WriteGlobalJson(asset.Path, toolset.DotNetRoot, toolset.SdkVersion);

var command = CreateDiscoveryCommand(asset.Path, "msbuild");
command.WithEnvironmentVariable("DOTNET_CLI_USE_MSBUILD_SERVER", "false");
command.WithEnvironmentVariable("MSBUILDUSESERVER", "0");
var result = command.Execute("Probe.proj", "-getProperty:MSBuildToolsPath,MSBuildExtensionsPath,MSBuildSDKsPath,MicrosoftNETBuildTasksAssembly", BinLogArgument([]));
result.Should().Pass();
using var output = JsonDocument.Parse(result.StdOut!);
var properties = output.RootElement.GetProperty("Properties");
string sdkDirectory = TestPathUtility.ResolveTempPrefixLink(toolset.SdkFolderUnderTest);
string sdksDirectory = TestPathUtility.ResolveTempPrefixLink(toolset.SdksPath);
Path.TrimEndingDirectorySeparator(properties.GetProperty("MSBuildToolsPath").GetString()!)
.Should().Be(sdkDirectory);
Path.TrimEndingDirectorySeparator(properties.GetProperty("MSBuildExtensionsPath").GetString()!)
.Should().Be(sdkDirectory);
properties.GetProperty("MSBuildSDKsPath").GetString().Should().Be(sdksDirectory);
Path.GetFullPath(properties.GetProperty("MicrosoftNETBuildTasksAssembly").GetString()!)
.Should().StartWith(sdksDirectory + Path.DirectorySeparatorChar);
}

[TestMethod]
public void FileBasedRunDiscoversSdkWithoutEnvironmentDefaults()
{
var asset = TestAssetsManager.CopyTestAsset("MSBuildSdkDiscovery").WithSource();
var toolset = SdkTestContext.Current.ToolsetUnderTest;
WriteGlobalJson(asset.Path, toolset.DotNetRoot, toolset.SdkVersion);

CreateDiscoveryCommand(asset.Path, "run", "--file", "Program.cs")
.Execute(BinLogArgument([]))
.Should().Pass()
.And.HaveStdOutContaining("SDK discovery succeeded");
}

[TestMethod]
public void ExplicitEnvironmentOverridesSelectSdkImports()
{
var asset = TestAssetsManager.CopyTestAsset("MSBuildSdkDiscovery").WithSource();
string extensionsPath = Path.Combine(asset.Path, "Extensions");
string sdksPath = Path.Combine(asset.Path, "Sdks");
var command = new DotnetCommand(Log, "msbuild") { WorkingDirectory = asset.Path };
command.EnvironmentToRemove.Add("MSBUILD_EXE_PATH");
command.WithEnvironmentVariable("MSBuildExtensionsPath", extensionsPath);
command.WithEnvironmentVariable("MSBuildSDKsPath", sdksPath);
command.Execute("Override.proj", "-getProperty:DiscoveryExtensionsPath,DiscoverySdkPath", BinLogArgument([]))
.Should().Pass()
.And.HaveStdOutContaining(JsonSerializer.Serialize(extensionsPath + Path.DirectorySeparatorChar))
.And.HaveStdOutContaining(JsonSerializer.Serialize(Path.Combine(sdksPath, "Discovery.Sdk", "Sdk") + Path.DirectorySeparatorChar));
}

private DotnetCommand CreateDiscoveryCommand(string workingDirectory, params string[] args)
{
var command = new DotnetCommand(Log, args) { WorkingDirectory = workingDirectory };
command.EnvironmentToRemove.AddRange(["MSBUILD_EXE_PATH", "MSBuildSDKsPath", "MSBuildExtensionsPath"]);
return command;
}

private static void WriteGlobalJson(string directory, string root, string version)
=> File.WriteAllText(Path.Combine(directory, "global.json"), JsonSerializer.Serialize(new
{
sdk = new { version, paths = new[] { root }, rollForward = "disable", allowPrerelease = true }
}));

private static void AssertPaths(string projectDirectory, string sdkDirectory)
{
sdkDirectory = TestPathUtility.ResolveTempPrefixLink(sdkDirectory);
string[] paths = File.ReadAllLines(Path.Combine(projectDirectory, "paths.txt"));
paths.Should().HaveCount(4);
Path.TrimEndingDirectorySeparator(paths[0]).Should().Be(sdkDirectory);
Path.TrimEndingDirectorySeparator(paths[1]).Should().Be(sdkDirectory);
Path.TrimEndingDirectorySeparator(paths[2]).Should().Be(Path.Combine(sdkDirectory, "Sdks"));
paths[3].Should().StartWith(Path.Combine(sdkDirectory, "Sdks") + Path.DirectorySeparatorChar);
}
}
Loading