Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolve ILLink warnings in System.Diagnostics.DiagnosticSource #50265

Merged
merged 3 commits into from
Apr 7, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<CLSCompliant>false</CLSCompliant>
Expand Down Expand Up @@ -31,6 +31,7 @@
<ItemGroup Condition="$([MSBuild]::GetTargetFrameworkIdentifier('$(TargetFramework)')) != '.NETCoreApp'">
<Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\DynamicDependencyAttribute.cs" />
<Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\DynamicallyAccessedMemberTypes.cs" />
<Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\RequiresUnreferencedCodeAttribute.cs" />
<Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\UnconditionalSuppressMessageAttribute.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'netstandard1.1'">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Threading;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace System.Diagnostics
{
Expand Down Expand Up @@ -255,6 +256,7 @@ public override bool IsEnabled(string name, object? arg1, object? arg2 = null)
/// <summary>
/// Override abstract method
/// </summary>
[RequiresUnreferencedCode(WriteRequiresUnreferencedCode)]
public override void Write(string name, object? value)
{
for (DiagnosticSubscription? curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;

namespace System.Diagnostics
{
Expand All @@ -15,6 +16,8 @@ namespace System.Diagnostics
/// </summary>
public abstract partial class DiagnosticSource
{
internal const string WriteRequiresUnreferencedCode = "The type of object being written to DiagnosticSource cannot be discovered statically.";

/// <summary>
/// Write is a generic way of logging complex payloads. Each notification
/// is given a name, which identifies it as well as a object (typically an anonymous type)
Expand All @@ -31,6 +34,7 @@ public abstract partial class DiagnosticSource
/// <param name="name">The name of the event being written.</param>
/// <param name="value">An object that represent the value being passed as a payload for the event.
/// This is often an anonymous type which contains several sub-values.</param>
[RequiresUnreferencedCode(WriteRequiresUnreferencedCode)]
public abstract void Write(string name, object? value);

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace System.Diagnostics
{
Expand All @@ -24,6 +25,7 @@ public abstract partial class DiagnosticSource
/// <param name="args">An object that represent the value being passed as a payload for the event.</param>
/// <returns>Started Activity for convenient chaining</returns>
/// <seealso cref="Activity"/>
[RequiresUnreferencedCode(WriteRequiresUnreferencedCode)]
public Activity StartActivity(Activity activity, object? args)
{
activity.Start();
Expand All @@ -41,6 +43,7 @@ public Activity StartActivity(Activity activity, object? args)
/// <param name="activity">Activity to be stopped</param>
/// <param name="args">An object that represent the value being passed as a payload for the event.</param>
/// <seealso cref="Activity"/>
[RequiresUnreferencedCode(WriteRequiresUnreferencedCode)]
public void StopActivity(Activity activity, object? args)
{
// Stop sets the end time if it was unset, but we want it set before we issue the write
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,9 @@ public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx,
if (eventNameFilter != null)
eventNameFilterPredicate = (string eventName) => eventNameFilter == eventName;

var subscription = newListener.Subscribe(new CallbackObserver<KeyValuePair<string, object?>>(delegate (KeyValuePair<string, object?> evnt)
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "DiagnosticSource.Write is marked with RequiresUnreferencedCode.")]
void OnEventWritten(KeyValuePair<string, object?> evnt)
{
// The filter given to the DiagnosticSource may not work if users don't is 'IsEnabled' as expected.
// Thus we look for any events that may have snuck through and filter them out before forwarding.
Expand All @@ -727,7 +729,9 @@ public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx,
var outputArgs = this.Morph(evnt.Value);
var eventName = evnt.Key;
writeEvent(newListener.Name, eventName, outputArgs);
}), eventNameFilterPredicate);
}

var subscription = newListener.Subscribe(new CallbackObserver<KeyValuePair<string, object?>>(OnEventWritten), eventNameFilterPredicate);
_liveSubscriptions = new Subscriptions(subscription, _liveSubscriptions);
}
}));
Expand Down Expand Up @@ -948,41 +952,55 @@ internal static void CreateActivityListener(DiagnosticSourceEventSource eventSou
return false;
};

eventSource._activityListener.ActivityStarted = activity =>
eventSource._activityListener.ActivityStarted = activity => OnActivityStarted(eventSource, activity);

eventSource._activityListener.ActivityStopped = activity => OnActivityStopped(eventSource, activity);
vitek-karas marked this conversation as resolved.
Show resolved Hide resolved

ActivitySource.AddActivityListener(eventSource._activityListener);
}

[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(Activity))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(ActivityContext))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(ActivityEvent))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(ActivityLink))]
[DynamicDependency(nameof(DateTime.Ticks), typeof(DateTime))]
[DynamicDependency(nameof(TimeSpan.Ticks), typeof(TimeSpan))]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "Activity's properties are being preserved with the DynamicDependencies on OnActivityStarted.")]
private static void OnActivityStarted(DiagnosticSourceEventSource eventSource, Activity activity)
{
FilterAndTransform? list = eventSource._activitySourceSpecs;
while (list != null)
{
FilterAndTransform? list = eventSource._activitySourceSpecs;
while (list != null)
if ((list.Events & ActivityEvents.ActivityStart) != 0 &&
(activity.Source.Name == list.SourceName || list.SourceName == "*") &&
(list.ActivityName == null || list.ActivityName == activity.OperationName))
{
if ((list.Events & ActivityEvents.ActivityStart) != 0 &&
(activity.Source.Name == list.SourceName || list.SourceName == "*") &&
(list.ActivityName == null || list.ActivityName == activity.OperationName))
{
eventSource.ActivityStart(activity.Source.Name, activity.OperationName, list.Morph(activity));
return;
}

list = list.Next;
eventSource.ActivityStart(activity.Source.Name, activity.OperationName, list.Morph(activity));
return;
}
};

eventSource._activityListener.ActivityStopped = activity =>
list = list.Next;
}
}

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "Activity's properties are being preserved with the DynamicDependencies on OnActivityStarted.")]
private static void OnActivityStopped(DiagnosticSourceEventSource eventSource, Activity activity)
{
FilterAndTransform? list = eventSource._activitySourceSpecs;
while (list != null)
{
FilterAndTransform? list = eventSource._activitySourceSpecs;
while (list != null)
if ((list.Events & ActivityEvents.ActivityStop) != 0 &&
(activity.Source.Name == list.SourceName || list.SourceName == "*") &&
(list.ActivityName == null || list.ActivityName == activity.OperationName))
{
if ((list.Events & ActivityEvents.ActivityStop) != 0 &&
(activity.Source.Name == list.SourceName || list.SourceName == "*") &&
(list.ActivityName == null || list.ActivityName == activity.OperationName))
{
eventSource.ActivityStop(activity.Source.Name, activity.OperationName, list.Morph(activity));
return;
}

list = list.Next;
eventSource.ActivityStop(activity.Source.Name, activity.OperationName, list.Morph(activity));
return;
}
};

ActivitySource.AddActivityListener(eventSource._activityListener);
list = list.Next;
}
}

// Move all wildcard nodes at the end of the list.
Expand Down Expand Up @@ -1067,6 +1085,7 @@ private void Dispose()
}
}

[RequiresUnreferencedCode(DiagnosticSource.WriteRequiresUnreferencedCode)]
public List<KeyValuePair<string, string?>> Morph(object? args)
{
// Transform the args into a bag of key-value strings.
Expand Down Expand Up @@ -1105,7 +1124,11 @@ private void Dispose()
Interlocked.CompareExchange(ref _implicitTransformsTable,
new ConcurrentDictionary<Type, TransformSpec?>(1, 8), null);
}
implicitTransforms = _implicitTransformsTable.GetOrAdd(argType, type => MakeImplicitTransforms(type));
implicitTransforms = _implicitTransformsTable.GetOrAdd(argType, type => MakeImplicitTransformsWrapper(type));

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "The Morph method has RequiresUnreferencedCode, but the trimmer can't see through lamdba calls.")]
static TransformSpec? MakeImplicitTransformsWrapper(Type transformType) => MakeImplicitTransforms(transformType);
}

// implicitTransformas now fetched from cache or constructed, use it to Fetch all the implicit fields.
Expand Down Expand Up @@ -1145,6 +1168,7 @@ private void Dispose()

// Given a type generate all the implicit transforms for type (that is for every field
// generate the spec that fetches it).
[RequiresUnreferencedCode(DiagnosticSource.WriteRequiresUnreferencedCode)]
private static TransformSpec? MakeImplicitTransforms(Type type)
{
TransformSpec? newSerializableArgs = null;
Expand Down Expand Up @@ -1239,6 +1263,7 @@ public TransformSpec(string transformSpec, int startIdx, int endIdx, TransformSp
/// if the spec is OUTSTR=EVENT_VALUE.PROP1.PROP2.PROP3 and the ultimate value of PROP3 is
/// 10 then the return key value pair is KeyValuePair("OUTSTR","10")
/// </summary>
[RequiresUnreferencedCode(DiagnosticSource.WriteRequiresUnreferencedCode)]
public KeyValuePair<string, string?> Morph(object? obj)
{
for (PropertySpec? cur = _fetches; cur != null; cur = cur.Next)
Expand Down Expand Up @@ -1289,6 +1314,7 @@ public PropertySpec(string propertyName, PropertySpec? next)
/// Given an object fetch the property that this PropertySpec represents.
/// obj may be null when IsStatic is true, otherwise it must be non-null.
/// </summary>
[RequiresUnreferencedCode(DiagnosticSource.WriteRequiresUnreferencedCode)]
public object? Fetch(object? obj)
{
PropertyFetch? fetch = _fetchForExpectedType;
Expand Down Expand Up @@ -1331,9 +1357,7 @@ public PropertyFetch(Type? type)
/// <summary>
/// Create a property fetcher for a propertyName
/// </summary>
[DynamicDependency("#ctor(System.Type)", typeof(EnumeratePropertyFetch<>))]
[DynamicDependency("#ctor(System.Type,System.Reflection.PropertyInfo)", typeof(RefTypedFetchProperty<,>))]
[DynamicDependency("#ctor(System.Type,System.Reflection.PropertyInfo)", typeof(ValueTypedFetchProperty<,>))]
[RequiresUnreferencedCode(DiagnosticSource.WriteRequiresUnreferencedCode)]
public static PropertyFetch FetcherForProperty(Type? type, string propertyName)
{
if (propertyName == null)
Expand Down Expand Up @@ -1385,7 +1409,7 @@ public static PropertyFetch FetcherForProperty(Type? type, string propertyName)
PropertyInfo? propertyInfo = typeInfo.GetDeclaredProperty(propertyName);
if (propertyInfo == null)
{
Logger.Message($"Property {propertyName} not found on {type}");
Logger.Message($"Property {propertyName} not found on {type}. Ensure the name is spelled correctly. If you published the application with PublishTrimmed=true, ensure the property was not trimmed away.");
return new PropertyFetch(type);
}
// Delegate creation below is incompatible with static properties.
Expand Down
Loading