Skip to content

Commit

Permalink
Use Platform-Guard Assertion Annotations for some known cases (#52689)
Browse files Browse the repository at this point in the history
* Use platform guard attributes
  • Loading branch information
buyaa-n committed May 17, 2021
1 parent 9f368f4 commit 3b8adb7
Show file tree
Hide file tree
Showing 11 changed files with 38 additions and 21 deletions.
2 changes: 1 addition & 1 deletion eng/Versions.props
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
<MicrosoftCodeAnalysisVersion>3.8.0</MicrosoftCodeAnalysisVersion>
</PropertyGroup>
<PropertyGroup>
<MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-preview5.21219.2</MicrosoftCodeAnalysisNetAnalyzersVersion>
<MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-preview5.21262.4</MicrosoftCodeAnalysisNetAnalyzersVersion>
<MicrosoftCodeAnalysisCSharpCodeStyleVersion>3.10.0-2.final</MicrosoftCodeAnalysisCSharpCodeStyleVersion>
<MicrosoftCodeAnalysisCSharpVersion>3.10.0-2.final</MicrosoftCodeAnalysisCSharpVersion>
<!-- Arcade dependencies -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options, IEnu
_optionsReloadToken = _options.OnChange(ReloadLoggerOptions);

_messageQueue = new ConsoleLoggerProcessor();
// TODO update when https://github.com/dotnet/runtime/issues/44922 implemented
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || DoesWindowsConsoleSupportAnsi())

if (DoesConsoleSupportAnsi())
{
_messageQueue.Console = new AnsiLogConsole();
_messageQueue.ErrorConsole = new AnsiLogConsole(stdErr: true);
Expand All @@ -60,8 +60,14 @@ public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options, IEnu
}
}

private static bool DoesWindowsConsoleSupportAnsi()
[UnsupportedOSPlatformGuard("windows")]
private static bool DoesConsoleSupportAnsi()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return true;
}

// for Windows, check the console mode
var stdOutHandle = Interop.Kernel32.GetStdHandle(Interop.Kernel32.STD_OUTPUT_HANDLE);
if (!Interop.Kernel32.GetConsoleMode(stdOutHandle, out int consoleMode))
Expand Down
1 change: 1 addition & 0 deletions src/libraries/System.Net.Http/ref/System.Net.Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@ protected override void SerializeToStream(System.IO.Stream stream, System.Net.Tr
public sealed partial class SocketsHttpHandler : System.Net.Http.HttpMessageHandler
{
public SocketsHttpHandler() { }
[System.Runtime.Versioning.UnsupportedOSPlatformGuardAttribute("browser")]
public static bool IsSupported { get { throw null; } }
public bool AllowAutoRedirect { get { throw null; } set { } }
public System.Net.DecompressionMethods AutomaticDecompression { get { throw null; } set { } }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ namespace System.Net.Http
[UnsupportedOSPlatform("browser")]
public sealed class SocketsHttpHandler : HttpMessageHandler
{
[UnsupportedOSPlatformGuard("browser")]
public static bool IsSupported => false;

public bool UseCookies
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ internal sealed class HttpConnectionPool : IDisposable
private byte[]? _http2AltSvcOriginUri;
internal readonly byte[]? _http2EncodedAuthorityHostHeader;

[SupportedOSPlatformGuard("linux")]
[SupportedOSPlatformGuard("macOS")]
[SupportedOSPlatformGuard("Windows")]
private readonly bool _http3Enabled;
private Http3Connection? _http3Connection;
private SemaphoreSlim? _http3ConnectionCreateLock;
Expand Down Expand Up @@ -122,8 +125,8 @@ public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionK
}

_http2Enabled = _poolManager.Settings._maxHttpVersion >= HttpVersion.Version20;
// TODO: Replace with Platform-Guard Assertion Annotations once https://github.com/dotnet/runtime/issues/44922 is finished
if ((OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())

if (IsHttp3Supported())
{
_http3Enabled = _poolManager.Settings._maxHttpVersion >= HttpVersion.Version30 && (_poolManager.Settings._quicImplementationProvider ?? QuicImplementationProviders.Default).IsSupported;
}
Expand Down Expand Up @@ -261,8 +264,7 @@ public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionK
_http3EncodedAuthorityHostHeader = QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReferenceToArray(H3StaticTable.Authority, hostHeader);
}

// TODO: Replace with Platform-Guard Assertion Annotations once https://github.com/dotnet/runtime/issues/44922 is finished
if ((OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
if (IsHttp3Supported())
{
if (_http3Enabled)
{
Expand All @@ -281,14 +283,17 @@ public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionK
if (NetEventSource.Log.IsEnabled()) Trace($"{this}");
}

[SupportedOSPlatformGuard("linux")]
[SupportedOSPlatformGuard("macOS")]
[SupportedOSPlatformGuard("Windows")]
internal static bool IsHttp3Supported() => (OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();
private static readonly List<SslApplicationProtocol> s_http3ApplicationProtocols = CreateHttp3ApplicationProtocols();
private static readonly List<SslApplicationProtocol> s_http2ApplicationProtocols = new List<SslApplicationProtocol>() { SslApplicationProtocol.Http2, SslApplicationProtocol.Http11 };
private static readonly List<SslApplicationProtocol> s_http2OnlyApplicationProtocols = new List<SslApplicationProtocol>() { SslApplicationProtocol.Http2 };

private static List<SslApplicationProtocol> CreateHttp3ApplicationProtocols()
{
// TODO: Replace with Platform-Guard Assertion Annotations once https://github.com/dotnet/runtime/issues/44922 is finished
if ((OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
if (IsHttp3Supported())
{
// TODO: Once the HTTP/3 versions are part of SslApplicationProtocol, see https://github.com/dotnet/runtime/issues/1293, move this back to field initialization.
return new List<SslApplicationProtocol>() { Http3Connection.Http3ApplicationProtocol31, Http3Connection.Http3ApplicationProtocol30, Http3Connection.Http3ApplicationProtocol29 };
Expand Down Expand Up @@ -866,8 +871,7 @@ private async ValueTask<HttpResponseMessage> DetermineVersionAndSendAsync(HttpRe
{
HttpResponseMessage? response;

// TODO: Replace with Platform-Guard Assertion Annotations once https://github.com/dotnet/runtime/issues/44922 is finished
if ((OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
if (IsHttp3Supported())
{
response = await TrySendUsingHttp3Async(request, async, doRequestAuth, cancellationToken).ConfigureAwait(false);
if (response is not null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,8 @@ public HttpConnectionSettings CloneAndNormalize()
_plaintextStreamFilter = _plaintextStreamFilter
};

// TODO: Replace with Platform-Guard Assertion Annotations once https://github.com/dotnet/runtime/issues/44922 is finished
// TODO: Remove if/when QuicImplementationProvider is removed from System.Net.Quic.
if ((OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
if (HttpConnectionPool.IsHttp3Supported())
{
settings._quicImplementationProvider = _quicImplementationProvider;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ private void CheckDisposedOrStarted()
/// <summary>
/// Gets a value that indicates whether the handler is supported on the current platform.
/// </summary>
[UnsupportedOSPlatformGuard("browser")]
public static bool IsSupported => true;

public bool UseCookies
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@
using System;
using System.IO;
using System.Net.Http;
using System.Runtime.Versioning;
using System.Threading.Tasks;

class Program
{
[SupportedOSPlatformGuard("linux")]
[SupportedOSPlatformGuard("macOS")]
[SupportedOSPlatformGuard("Windows")]
private static bool IsHttp3Supported => (OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();

static async Task<int> Main(string[] args)
{
using var client = new HttpClient();
Expand All @@ -18,8 +24,7 @@ static async Task<int> Main(string[] args)
const string quicDll = "System.Net.Quic.dll";
var quicDllExists = File.Exists(Path.Combine(AppContext.BaseDirectory, quicDll));

// TODO: Replace with Platform-Guard Assertion Annotations once https://github.com/dotnet/runtime/issues/44922 is finished
if ((OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid()) || OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
if (IsHttp3Supported)
{
Console.WriteLine($"Expected {quicDll} is {(quicDllExists ? "present - OK" : "missing - BAD")}.");
return quicDllExists ? 100 : -1;
Expand All @@ -30,4 +35,4 @@ static async Task<int> Main(string[] args)
return quicDllExists ? -1 : 100;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,11 @@ protected internal override void QueueTask(Task task)
if (Thread.IsThreadStartSupported && (options & TaskCreationOptions.LongRunning) != 0)
{
// Run LongRunning tasks on their own dedicated thread.
#pragma warning disable CA1416 // TODO: https://github.com/dotnet/runtime/issues/44922
new Thread(s_longRunningThreadWork)
{
IsBackground = true,
Name = ".NET Long Running Task"
}.UnsafeStart(task);
#pragma warning restore CA1416
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,8 @@ public Thread(ParameterizedThreadStart start, int maxStackSize)
}

#if !TARGET_BROWSER
internal const bool IsThreadStartSupported = true;
[UnsupportedOSPlatformGuard("browser")]
internal static bool IsThreadStartSupported => true;

/// <summary>Causes the operating system to change the state of the current instance to <see cref="ThreadState.Running"/>, and optionally supplies an object containing data to be used by the method the thread executes.</summary>
/// <param name="parameter">An object that contains data to be used by the method the thread executes.</param>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ namespace System.Threading
{
public partial class Thread
{
internal const bool IsThreadStartSupported = false;
[UnsupportedOSPlatformGuard("browser")]
internal static bool IsThreadStartSupported => false;

[UnsupportedOSPlatform("browser")]
public void Start() => throw new PlatformNotSupportedException();
Expand Down

0 comments on commit 3b8adb7

Please sign in to comment.