Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ Set the environment variable `MSBUILDDEBUGONSTART` to control debugger behavior

For example, set `MSBUILDDEBUGONSTART` to `2`, then attach a debugger to the process manually after it starts.

## Debugging MSBuild Server

With Server enabled, use `MSBUILDDEBUGONSTART=4` to launch a debugger in the server (Windows), or `5` to wait for manual attachment. These modes skip the forwarding client and other child nodes, and pause **after connection but before evaluation**, on either a new or reused server.

```powershell
$env:MSBUILDUSESERVER = '1'
$env:MSBUILDDEBUGONSTART = '5'
dotnet msbuild .\project.proj
```

Attach to the server PID printed in the terminal and resume execution; unlike mode `2`, no Enter key is needed. No connection or handshake changes are required because the client is already connected. Existing cancellation/fallback behavior is unchanged: resume or stop the server manually to abandon the wait. Unset `MSBUILDDEBUGONSTART` when finished. These modes do not cover server startup or handshake debugging.

## Using the repository binaries to perform builds

## Run tests from the command line
Expand Down
2 changes: 2 additions & 0 deletions documentation/wiki/MSBuild-Environment-Variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ Some of the env variables listed here are unsupported, meaning there is no guara
- `MSBUILDDEBUGONSTART=1`
- Launches debugger on build start. Works on Windows operating systems only.
- Setting the value of 2 allows for manually attaching a debugger to a process ID. This works on Windows and non-Windows operating systems.
- `4` launches a debugger only in MSBuild Server; `5` waits for manual attachment there. Both stop after the client connects and before evaluation, so attaching does not consume the connection timeout. They work with new or reused servers and leave the forwarding client, workers, and TaskHosts alone.
- For `5`, attach to the server PID printed in the client terminal; no Enter key is needed. These settings do not enable Server. Existing cancellation and fallback behavior are unchanged; resume or stop the server manually to abandon an attachment wait.
Comment thread
JanProvaznik marked this conversation as resolved.
Resolved
- `MSBUILDDEBUGSCHEDULER=1` & `MSBUILDDEBUGPATH=<DIRECTORY>`
- Dumps scheduler state at specified directory.
- `MsBuildSkipEagerWildCardEvaluationRegexes`
Expand Down
77 changes: 77 additions & 0 deletions src/MSBuild.UnitTests/MSBuildServer_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
using Shouldly;
using Xunit;
using Path = System.IO.Path;
using StringWriter = System.IO.StringWriter;
using TextWriter = System.IO.TextWriter;

namespace Microsoft.Build.Engine.UnitTests
{
Expand Down Expand Up @@ -110,6 +112,81 @@ public MSBuildServer_Tests(ITestOutputHelper output)

public void Dispose() => _env.Dispose();

[Theory]
[InlineData("4")]
[InlineData("5")]
public void ServerOnlyDebuggingSkipsInProcessBuilds(string mode)
{
_env.SetEnvironmentVariable("MSBUILDDEBUGONSTART", mode);
TransientTestFile project = _env.CreateFile("debug.proj", "<Project><Target Name='Build' /></Project>");
MSBuildApp.Execute(["MSBuild.exe", project.Path]).ShouldBe(MSBuildApp.ExitType.Success);
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ServerOnlyDebuggingWaitsBeforeEvaluation(bool warmServer)
{
_env.SetEnvironmentVariable("MSBUILDNODEHANDSHAKESALT", Guid.NewGuid().ToString("N"));
_env.SetEnvironmentVariable("MSBUILDDEBUGONSTART", null);
TransientTestFile project = _env.CreateFile("debug.proj", "<Project><Target Name='Build' /></Project>");
MSBuildClient launchClient = new(["MSBuild.exe", project.Path], BuildEnvironmentHelper.Instance.CurrentMSBuildExePath);
FieldInfo pidField = typeof(MSBuildClient).GetField("_launchedServerPid", BindingFlags.Instance | BindingFlags.NonPublic)!;
if (warmServer)
{
launchClient.Execute(CancellationToken.None).MSBuildAppExitTypeString.ShouldBe("Success");
}

_env.SetEnvironmentVariable("MSBUILDDEBUGONSTART", "5");
MSBuildClient debugClient = warmServer
? new(["MSBuild.exe", "never-evaluated.proj"], BuildEnvironmentHelper.Instance.CurrentMSBuildExePath)
: launchClient;
using StringWriter output = new();
TextWriter originalOutput = Console.Out;
TextWriter synchronizedOutput = TextWriter.Synchronized(output);
Task<MSBuildClientExitResult>? build = null;
Process? server = null;
try
{
Console.SetOut(synchronizedOutput);
build = Task.Run(() => debugClient.Execute(CancellationToken.None));
SpinWait.SpinUntil(() => pidField.GetValue(launchClient) is int || build.IsCompleted, 10000).ShouldBeTrue();
int pid = pidField.GetValue(launchClient).ShouldBeOfType<int>();
_env.WithTransientProcess(pid);
server = Process.GetProcessById(pid);
SpinWait.SpinUntil(() =>
{
lock (synchronizedOutput)
{
return output.ToString().Contains($"PID {pid}") || build.IsCompleted;
}
}, 10000).ShouldBeTrue();
build.IsCompleted.ShouldBeFalse("the server must wait before evaluating the project");
lock (synchronizedOutput)
{
output.ToString().ShouldContain($"PID {pid}");
}
}
finally
{
Console.SetOut(originalOutput);
// No debugger is attached in this test; stop only the isolated server we launched.
if (server is not null)
{
if (!server.HasExited)
{
server.Kill();
}
server.Dispose();
}
if (build is not null)
{
await Task.WhenAny(build, Task.Delay(10000));
build.IsCompleted.ShouldBeTrue();
}
}
}

[Fact]
public void MSBuildServerTest()
{
Expand Down
11 changes: 11 additions & 0 deletions src/MSBuild/XMake.cs
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,7 @@ private static void DebuggerLaunchCheck()
{
#if FEATURE_DEBUG_LAUNCH
case "1":
case "4" when s_isServerNode:
Debugger.Launch();
break;
case "3":
Expand All @@ -809,6 +810,16 @@ private static void DebuggerLaunchCheck()
Console.ReadLine();

break;

case "5" when s_isServerNode:
// The server has connected and redirected its output, but cannot read the client's stdin.
Console.WriteLine($"Waiting for debugger to attach ({EnvironmentUtilities.ProcessPath} PID {EnvironmentUtilities.CurrentProcessId}).");
Console.Out.Flush();
while (!Debugger.IsAttached)
{
Thread.Sleep(100);
}
break;
}
}

Expand Down
Loading