-
Notifications
You must be signed in to change notification settings - Fork 166
Apply .cctor deadlock defense on .NET Core (follow-up to #8498) #8517
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
181 changes: 181 additions & 0 deletions
181
...r/src/Datadog.Trace.ClrProfiler.Managed.Loader/ManagedProfilerAssemblyResolver.NetCore.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| // <copyright file="ManagedProfilerAssemblyResolver.NetCore.cs" company="Datadog"> | ||
| // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. | ||
| // </copyright> | ||
|
|
||
| #if NETCOREAPP | ||
|
|
||
| #nullable enable | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Reflection; | ||
| using System.Runtime.Loader; | ||
|
|
||
| namespace Datadog.Trace.ClrProfiler.Managed.Loader; | ||
|
|
||
| // Owns the AppDomain.AssemblyResolve and AssemblyLoadContext.Default.Resolving | ||
| // callbacks on .NET Core. Kept on a separate class from Startup so the handlers | ||
| // can be dispatched without forcing Startup's type-initializer to have finished - | ||
| // the same defense applied to the .NET Framework path. The Framework-specific | ||
| // configBuilder trigger doesn't exist on .NET Core, but any sync-over-async work | ||
| // in the Startup..cctor chain whose continuation probes Type.GetType or the ALC | ||
| // on a ThreadPool thread would hit the same .cctor x sync-over-async hazard. | ||
| internal static class ManagedProfilerAssemblyResolver | ||
| { | ||
| private static readonly AssemblyLoadContext DependencyLoadContext = new ManagedProfilerAssemblyLoadContext(); | ||
|
|
||
| private static CachedAssembly[]? _assemblies; | ||
|
|
||
| // Seeded by Startup..cctor before the handlers are subscribed. | ||
| internal static string? ManagedProfilerDirectory { get; set; } | ||
|
|
||
| internal static void PopulateAssemblyCache(string directory) | ||
| { | ||
| if (!Directory.Exists(directory)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // List/Array due to the number of files in the tracer home folder | ||
| // (7 in netstandard, 2 netcoreapp3.1+) | ||
| var assemblies = new List<CachedAssembly>(); | ||
| foreach (var file in Directory.EnumerateFiles(directory, "*.dll", SearchOption.TopDirectoryOnly)) | ||
| { | ||
| assemblies.Add(new CachedAssembly(file, null)); | ||
| } | ||
|
|
||
| _assemblies = [..assemblies]; | ||
| StartupLogger.Debug("Total number of assemblies: {0}", _assemblies.Length); | ||
| } | ||
|
|
||
| internal static Assembly? OnAssemblyResolve(object sender, ResolveEventArgs args) | ||
| { | ||
| try | ||
| { | ||
| return ResolveAssembly(args.Name); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| StartupLogger.Log(ex, "Error resolving assembly: {0}", args.Name); | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| internal static Assembly? OnAssemblyLoadContextResolving(AssemblyLoadContext context, AssemblyName assemblyName) | ||
| { | ||
| try | ||
| { | ||
| return ResolveAssembly(assemblyName.Name); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| StartupLogger.Log(ex, "Error resolving assembly: {0}", assemblyName.Name); | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| internal static Assembly? ResolveAssembly(string name) | ||
| { | ||
| var assemblyName = new AssemblyName(name); | ||
|
|
||
| // On .NET Framework, having a non-US locale can cause mscorlib | ||
| // to enter the AssemblyResolve event when searching for resources | ||
| // in its satellite assemblies. This seems to have been fixed in | ||
| // .NET Core in the 2.0 servicing branch, so we should not see this | ||
| // occur but guard against it anyway. If we do see it, exit early | ||
| // so we don't cause infinite recursion. | ||
| if (string.Equals(assemblyName.Name, "System.Private.CoreLib.resources", StringComparison.OrdinalIgnoreCase) || | ||
| string.Equals(assemblyName.Name, "System.Net.Http", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| // WARNING: Logs must not be added _before_ we check for the above bail-out conditions | ||
| StartupLogger.Debug("Assembly Resolve event received for: {0}. Searching in: {1}", name, ManagedProfilerDirectory); | ||
| var path = Path.Combine(ManagedProfilerDirectory ?? string.Empty, $"{assemblyName.Name}.dll"); | ||
|
|
||
| if (IsDatadogAssembly(path, out var cachedAssembly)) | ||
| { | ||
| // The file exists in the Home folder... | ||
| if (cachedAssembly is not null) | ||
| { | ||
| // The assembly is already loaded. | ||
| StartupLogger.Debug("Loading from cache. [Path: {0}]", path); | ||
| return cachedAssembly; | ||
| } | ||
|
|
||
| // Only load the main profiler into the default AssemblyLoadContext. | ||
| // If the NuGet package provides Datadog.Trace or other libraries, loading them is handled in the following two ways: | ||
| // 1) If the AssemblyVersion is greater than or equal to the version used by Datadog.Trace, the assembly | ||
| // will load successfully and will not invoke this resolve event. | ||
| // 2) If the AssemblyVersion is lower than the version used by Datadog.Trace, the assembly will fail to load | ||
| // and invoke this resolve event. It must be loaded in a separate AssemblyLoadContext since the application will only | ||
| // load the originally referenced version. | ||
| StartupLogger.Debug("Calling DependencyLoadContext.LoadFromAssemblyPath(\"{0}\")", path); | ||
| var assembly = DependencyLoadContext.LoadFromAssemblyPath(path); // Load unresolved framework and third-party dependencies into a custom AssemblyLoadContext | ||
| SetDatadogAssembly(path, assembly); | ||
| return assembly; | ||
| } | ||
|
|
||
| // The file doesn't exist in the Home folder. | ||
| StartupLogger.Debug("Assembly not found in path: {0}", path); | ||
| return null; | ||
| } | ||
|
|
||
| private static bool IsDatadogAssembly(string path, out Assembly? cachedAssembly) | ||
| { | ||
| if (_assemblies is null) | ||
| { | ||
| cachedAssembly = null; | ||
| return false; | ||
| } | ||
|
|
||
| for (var i = 0; i < _assemblies.Length; i++) | ||
| { | ||
| var assembly = _assemblies[i]; | ||
| if (assembly.Path == path) | ||
| { | ||
| cachedAssembly = assembly.Assembly; | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| cachedAssembly = null; | ||
| return false; | ||
| } | ||
|
|
||
| private static void SetDatadogAssembly(string path, Assembly cachedAssembly) | ||
| { | ||
| if (_assemblies is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| for (var i = 0; i < _assemblies.Length; i++) | ||
| { | ||
| if (_assemblies[i].Path == path) | ||
| { | ||
| _assemblies[i] = new CachedAssembly(path, cachedAssembly); | ||
| return; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private readonly struct CachedAssembly | ||
| { | ||
| public readonly string Path; | ||
| public readonly Assembly? Assembly; | ||
|
|
||
| public CachedAssembly(string path, Assembly? assembly) | ||
| { | ||
| Path = path; | ||
| Assembly = assembly; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #endif | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe this is just a cut-and paste from Startup.NetCore, right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Almost. It was, but I noticed that the original code had no try/catch (the .net framework version does) so these were added.