Skip to content

Commit

Permalink
Avoid MSBuild crash when DOTNET_SYSTEM_GLOBALIZATION_INVARIANT mode i…
Browse files Browse the repository at this point in the history
…s enabled and console codepage, not ANSI. (#8738)

Context
If DOTNET_SYSTEM_GLOBALIZATION_INVARIANT is enabled and console codepage non-ANSI MSBuild will crash on an attempt to create CultureInfo:

Unhandled exception. System.Globalization.CultureNotFoundException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-US is an invalid culture identifier.
Changes Made
Keep the current thread culture the same if CurrentUICulture is Invariant.
  • Loading branch information
mfilippov authored May 10, 2023
1 parent 37b52c8 commit 7f4bef8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
24 changes: 24 additions & 0 deletions src/MSBuild.UnitTests/XMake_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,30 @@ public void SetConsoleUICulture()
thisThread.CurrentUICulture = originalUICulture;
}

/// <summary>
/// We shouldn't change the UI culture if the current UI culture is invariant.
/// In other cases, we can get an exception on CultureInfo creation when System.Globalization.Invariant enabled.
/// </summary>

[Fact]
public void SetConsoleUICultureInInvariantCulture()
{
Thread thisThread = Thread.CurrentThread;

// Save the current UI culture, so we can restore it at the end of this unit test.
CultureInfo originalUICulture = thisThread.CurrentUICulture;

thisThread.CurrentUICulture = CultureInfo.InvariantCulture;
MSBuildApp.SetConsoleUI();

// Make sure we don't change culture.
thisThread.CurrentUICulture.ShouldBe(CultureInfo.InvariantCulture);

// Restore the current UI culture back to the way it was at the beginning of this unit test.
thisThread.CurrentUICulture = originalUICulture;
}


#if FEATURE_SYSTEM_CONFIGURATION
/// <summary>
/// Invalid configuration file should not dump stack.
Expand Down
3 changes: 2 additions & 1 deletion src/MSBuild/XMake.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1693,7 +1693,8 @@ internal static void SetConsoleUI()
&&
codepage != thisThread.CurrentUICulture.TextInfo.OEMCodePage
&&
codepage != thisThread.CurrentUICulture.TextInfo.ANSICodePage)
codepage != thisThread.CurrentUICulture.TextInfo.ANSICodePage
&& !Equals(CultureInfo.InvariantCulture, thisThread.CurrentUICulture))
{
thisThread.CurrentUICulture = new CultureInfo("en-US");
return;
Expand Down

0 comments on commit 7f4bef8

Please sign in to comment.