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 @@ -119,15 +119,30 @@ internal IEnumerable<RuntimeDescription> EnumerateRuntimeDescriptions(
IModule[] modules = _services.GetService<IModuleService>().EnumerateModules().ToArray();
HashSet<ulong> handledModules = [];

// DotNetRuntimeDiscoveryProvider is efficient at discovering coreclr/clr .NET runtimes, so we try it first.
if (!all &&
_services.GetService<IRuntimeService>()?.PreferredRuntimeModule is ulong preferredBase &&
modules.FirstOrDefault(module => module.ImageBase == preferredBase) is IModule preferredModule)
{
handledModules.Add(preferredModule.ImageBase);
foreach (RuntimeDescription description in EnumerateRuntimeDescriptions(orderedProviders, [preferredModule]))
{
yield return description;
yield break;
}
}

// DotNetRuntimeDiscoveryProvider is efficient at discovering coreclr/clr .NET runtimes.
bool foundNormalRuntime = false;
IModule[] normalModules = modules.Where(module => !handledModules.Contains(module.ImageBase)).ToArray();
foreach (RuntimeDescription description in EnumerateRuntimeDescriptions(
orderedProviders.OfType<DotNetRuntimeDiscoveryProvider>(), modules))
orderedProviders.OfType<DotNetRuntimeDiscoveryProvider>(), normalModules))
{
foundNormalRuntime = true;
handledModules.Add(description.Module.ImageBase);
yield return description;
}

if (handledModules.Count > 0 && !all)
if (foundNormalRuntime && !all)
{
yield break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ private void Flush()

#region IRuntimeService

public ulong? PreferredRuntimeModule { get; set; }

/// <summary>
/// Returns the list of runtimes in the target
/// </summary>
Expand Down
7 changes: 7 additions & 0 deletions src/Microsoft.Diagnostics.DebugServices/IRuntimeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ namespace Microsoft.Diagnostics.DebugServices
/// </summary>
public interface IRuntimeService
{
/// <summary>
/// Module base address to try first during default runtime discovery.
/// Full runtime enumeration ignores this preference.
/// The preference survives target flushes. Flush the target after changing it.
/// </summary>
ulong? PreferredRuntimeModule { get; set; }

/// <summary>
/// Returns the list of runtimes in the target
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ public class RuntimesCommand : CommandBase
[ServiceImport]
public ITarget Target { get; set; }

[ServiceImport]
public IModuleService ModuleService { get; set; }

[Argument(Help = "Switch to the runtime by id.")]
public int? Id { get; set; }

Expand All @@ -36,6 +39,15 @@ public class RuntimesCommand : CommandBase
[Option(Name = "--all", Aliases = new string[] { "-a" }, Help = "Forces all runtimes to be enumerated.")]
public bool All { get; set; }

[Option(Name = "--module", Help = "Tries the named module first, stopping on a match unless --all is specified.")]
public string ModuleName { get; set; }

[Option(Name = "--address", Help = "Tries the module at the hexadecimal base address first, stopping on a match unless --all is specified.")]
public string ModuleAddress { get; set; }

[Option(Name = "--clear-priority", Help = "Clears the preferred runtime module.")]
public bool ClearPriority { get; set; }

[Option(Name = "--usecdac", Help = "Controls cDAC usage: true (required), false (disabled), prefer (allow DAC fallback).")]
public string UseCDac { get; set; }

Expand All @@ -49,6 +61,38 @@ public override void Invoke()
throw new DiagnosticsException("Cannot specify both -netfx and -netcore options");
}

if ((ModuleName is not null ? 1 : 0) + (ModuleAddress is not null ? 1 : 0) + (ClearPriority ? 1 : 0) > 1)
{
throw new DiagnosticsException("Specify only one of --module, --address, or --clear-priority");
}

ulong? preferredModule = RuntimeService.PreferredRuntimeModule;
if (ModuleName is not null)
{
IModule[] matches = ModuleService.GetModuleFromModuleName(ModuleName).ToArray();
if (matches.Length == 0)
{
throw new DiagnosticsException($"Module '{ModuleName}' was not found");
}
if (matches.Length > 1)
{
throw new DiagnosticsException($"Module '{ModuleName}' is ambiguous. Use --address to specify a module base address.");
}
preferredModule = matches[0].ImageBase;
}
else if (ModuleAddress is not null)
{
if (!TryParseAddress(ModuleAddress, out ulong address))
{
throw new DiagnosticsException($"Invalid module base address '{ModuleAddress}'");
}
preferredModule = ModuleService.GetModuleFromBaseAddress(address).ImageBase;
}
else if (ClearPriority)
{
preferredModule = null;
}

bool flush = false;
if (UseCDac is not null)
{
Expand Down Expand Up @@ -76,6 +120,12 @@ public override void Invoke()
flush = true;
}

if (preferredModule != RuntimeService.PreferredRuntimeModule)
{
RuntimeService.PreferredRuntimeModule = preferredModule;
flush = true;
}

if (flush)
{
Target.Flush();
Expand Down Expand Up @@ -125,6 +175,10 @@ public override void Invoke()
this.DisplayResources(runtime.RuntimeModule, all: false, indent: " ");
this.DisplayRuntimeExports(runtime.RuntimeModule, error: true, indent: " ");
}
if (RuntimeService.PreferredRuntimeModule is ulong preferredBase)
{
WriteLine($"Preferred runtime module: {preferredBase:X16}");
}
this.DisplaySettingService();
}
}
Expand Down
10 changes: 8 additions & 2 deletions src/SOS/Strike/sosdocs.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2011,11 +2011,17 @@ runtime directory.
\\

COMMAND: runtimes.
runtimes [-netfx] [-netcore]
runtimes [-netfx] [-netcore] [--all] [--module <name> | --address <base> | --clear-priority]

-netfx - switch to the desktop .NET Framework runtime if loaded.
-netcore - switch to the .NET Core runtime if loaded.
--module <name> - try the named module before any other runtime discovery.
--address <base> - try the module at the specified hexadecimal base address first.
--clear-priority - clear the preferred module.
--all - enumerate all runtimes.

List and select the .NET runtimes in the target process.
If the preferred module is recognized, discovery stops unless --all is specified.
Otherwise, discovery falls back to normal runtime modules, automatic hints, and
remaining modules. The preference is per target and survives flushes.
\\

12 changes: 10 additions & 2 deletions src/SOS/Strike/sosdocsunix.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1691,8 +1691,16 @@ on another machine or for triage dumps.
\\

COMMAND: runtimes.
runtimes
runtimes [--all] [--module <name> | --address <base> | --clear-priority]

List the .NET runtimes in the target process.
\\

--module <name> - try the named module before any other runtime discovery.
--address <base> - try the module at the specified hexadecimal base address first.
--clear-priority - clear the preferred module.
--all - enumerate all runtimes.

If the preferred module is recognized, discovery stops unless --all is specified.
Otherwise, discovery falls back to normal runtime modules, automatic hints, and
remaining modules. The preference is per target and survives flushes.
\\
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ public RuntimeDiscoveryTestTarget(OSPlatform platform, Architecture architecture
{
_memory = new(architecture is Architecture.X86 or Architecture.Arm ? 4 : 8);
configureProviders?.Invoke(_host.ServiceManager);
_host.CreateServiceContainer().AddService<ISymbolService>(Symbols);
ServiceContainer hostServices = _host.CreateServiceContainer();
hostServices.AddService<ISymbolService>(Symbols);
hostServices.AddService<IContextService>(new ContextService(_host));
_target = new(_host, platform, architecture, _memory,
services => new TestModules(services, _modules, Symbols, ExportProbes));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,168 @@ public void DiagnosticHintDoesNotProbeCrashRuntime()
target.Symbols.Verify();
}

[Theory]
[InlineData("WINDOWS", RuntimeEnumerationFlags.Default)]
[InlineData("WINDOWS", RuntimeEnumerationFlags.All)]
[InlineData("LINUX", RuntimeEnumerationFlags.Default)]
[InlineData("LINUX", RuntimeEnumerationFlags.All)]
[InlineData("OSX", RuntimeEnumerationFlags.Default)]
[InlineData("OSX", RuntimeEnumerationFlags.All)]
public void OnlyDefaultDiscoveryPrioritizesPreferredModule(string platform, RuntimeEnumerationFlags flags)
{
OSPlatform os = OSPlatform.Create(platform);
using RuntimeDiscoveryTestTarget target = new(os, Architecture.X64);
target.AddModule(0x10000, ApplicationName(os, "unrelated"), needsSymbols: true);
RuntimeDiscoveryTestTarget.ModuleDefinition automatic = target.AddModule(0x20000, ApplicationName(os, "automatic"), entryPoint: true);
RuntimeDiscoveryTestTarget.ModuleDefinition preferred = target.AddModule(0x30000, ApplicationName(os, "preferred"));
target.AddSingleFileRuntime(automatic);
target.AddSingleFileRuntime(preferred);
target.AddDiagnosticHeader(automatic.ImageBase);
target.Runtimes.PreferredRuntimeModule = preferred.ImageBase;
if (flags == RuntimeEnumerationFlags.All)
{
target.Symbols.ExpectSymbolFile(0x10000, result: null);
}

Assert.Equal(flags == RuntimeEnumerationFlags.All ? [automatic.ImageBase, preferred.ImageBase] : new[] { preferred.ImageBase },
target.Enumerate(flags).Select(runtime => runtime.RuntimeModule.ImageBase));
Assert.Equal(flags == RuntimeEnumerationFlags.All ? [automatic.ImageBase, 0x10000UL, preferred.ImageBase] : new[] { preferred.ImageBase },
target.ExportProbes.Where(probe => probe.Symbol == "DotNetRuntimeInfo").Select(probe => probe.ModuleBase));
target.Symbols.Verify();
}

[Theory]
[InlineData(RuntimeEnumerationFlags.Default)]
[InlineData(RuntimeEnumerationFlags.All)]
public void OnlyDefaultDiscoveryProbesPreferredModuleBeforeNormalRuntime(RuntimeEnumerationFlags flags)
{
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
RuntimeDiscoveryTestTarget.ModuleDefinition preferred = target.AddModule(0x10000, "/app/preferred", needsSymbols: true);
target.AddSingleFileRuntime(preferred, symbolOnly: true);
target.AddCoreRuntime(0x20000);
target.Runtimes.PreferredRuntimeModule = preferred.ImageBase;
target.Symbols.ExpectSymbolFile(preferred.ImageBase, result: "mock-symbols");

IRuntime[] runtimes = target.Enumerate(flags);
Assert.Equal(preferred.ImageBase, Assert.Single(runtimes, runtime => runtime.Services.GetService<ClrInfo>().IsSingleFile).RuntimeModule.ImageBase);
Assert.Equal(flags == RuntimeEnumerationFlags.All ? 2 : 1, runtimes.Length);
Assert.Equal(flags == RuntimeEnumerationFlags.All ? 0x20000UL : preferred.ImageBase, target.ExportProbes.First().ModuleBase);
Assert.Equal([preferred.ImageBase], target.Symbols.Requests);
target.Symbols.Verify();
}

[Theory]
[InlineData(RuntimeEnumerationFlags.Default)]
[InlineData(RuntimeEnumerationFlags.All)]
public void PreferredNamedRuntimeIsOnlyPrioritizedInDefaultDiscovery(RuntimeEnumerationFlags flags)
{
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
target.AddCoreRuntime(0x20000, diagnosticHeader: false);
target.AddCoreRuntime(0x30000, diagnosticHeader: false);
target.Runtimes.PreferredRuntimeModule = 0x30000;

Assert.Equal(flags == RuntimeEnumerationFlags.All ? [0x20000UL, 0x30000UL] : new[] { 0x30000UL },
target.Enumerate(flags).Select(runtime => runtime.RuntimeModule.ImageBase));
Assert.Equal(flags == RuntimeEnumerationFlags.All ? [0x20000UL, 0x30000UL] : new[] { 0x30000UL },
target.ExportProbes.Where(probe => probe.Symbol == "DotNetRuntimeContractDescriptor").Select(probe => probe.ModuleBase));
target.Symbols.Verify();
}

[Theory]
[InlineData(RuntimeEnumerationFlags.Default)]
[InlineData(RuntimeEnumerationFlags.All)]
public void UnrecognizedPreferredModuleFallsBackToNormalDiscovery(RuntimeEnumerationFlags flags)
{
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
target.AddModule(0x10000, "/app/preferred", needsSymbols: true);
target.AddCoreRuntime(0x20000);
target.Runtimes.PreferredRuntimeModule = 0x10000;
target.Symbols.ExpectSymbolFile(0x10000, result: null);

Assert.Equal(0x20000UL, Assert.Single(target.Enumerate(flags)).RuntimeModule.ImageBase);
Assert.Single(target.ExportProbes, probe => probe.ModuleBase == 0x10000 && probe.Symbol == "DotNetRuntimeInfo");
target.Symbols.Verify();
}

[Theory]
[InlineData(RuntimeEnumerationFlags.Default)]
[InlineData(RuntimeEnumerationFlags.All)]
public void UnrecognizedPreferredModuleRetainsUnhintedSingleFileFallback(RuntimeEnumerationFlags flags)
{
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
target.AddModule(0x10000, "/app/preferred", needsSymbols: true);
RuntimeDiscoveryTestTarget.ModuleDefinition app = target.AddModule(0x20000, "/app/singlefile", needsSymbols: true);
target.AddSingleFileRuntime(app, symbolOnly: true);
target.Runtimes.PreferredRuntimeModule = 0x10000;
target.Symbols.ExpectSymbolFile(0x10000, result: null);
target.Symbols.ExpectSymbolFile(app.ImageBase, result: "mock-symbols");

Assert.Equal(app.ImageBase, Assert.Single(target.Enumerate(flags)).RuntimeModule.ImageBase);
Assert.Equal([0x10000UL, app.ImageBase], target.Symbols.Requests);
target.Symbols.Verify();
}

[Theory]
[InlineData(RuntimeEnumerationFlags.Default)]
[InlineData(RuntimeEnumerationFlags.All)]
public void UnrecognizedPreferredModuleFallsBackWithoutRetrying(RuntimeEnumerationFlags flags)
{
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
target.AddModule(0x10000, "/app/preferred", needsSymbols: true);
RuntimeDiscoveryTestTarget.ModuleDefinition automatic = target.AddModule(0x20000, "/app/automatic");
target.AddSingleFileRuntime(automatic);
target.AddDiagnosticHeader(automatic.ImageBase);
target.Runtimes.PreferredRuntimeModule = 0x10000;
target.Symbols.ExpectSymbolFile(0x10000, result: null);

Assert.Equal(automatic.ImageBase, Assert.Single(target.Enumerate(flags)).RuntimeModule.ImageBase);
Assert.Equal(flags == RuntimeEnumerationFlags.All ? [automatic.ImageBase, 0x10000UL] : new[] { 0x10000UL, automatic.ImageBase }, target.ExportProbes
.Where(probe => probe.Symbol == "DotNetRuntimeInfo").Select(probe => probe.ModuleBase));
target.Symbols.Verify();
}

[Fact]
public void PreferredModuleTriesAllProvidersBeforeAutomaticHints()
{
List<(int Priority, ulong ModuleBase)> calls = [];
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64, manager => {
foreach (int priority in new[] { 100, 50 })
{
manager.AddProviderFactory(typeof(IRuntimeDescriptionProvider), _ =>
new TestRuntimeDiscoveryProvider(module => {
calls.Add((priority, module.ImageBase));
return module.ImageBase == (priority == 100 ? 0x20000UL : 0x30000UL)
? new RuntimeDescription(module, RuntimeType.NativeAOT, new Version(1, 0))
: null;
}, priority));
}
});
target.AddModule(0x20000, "/app/automatic");
target.AddModule(0x30000, "/app/preferred");
target.AddDiagnosticHeader(0x20000);
target.Runtimes.PreferredRuntimeModule = 0x30000;

Assert.Equal(0x30000UL, Assert.Single(target.Enumerate()).RuntimeModule.ImageBase);
Assert.Equal([(100, 0x30000UL), (50, 0x30000UL)], calls);
target.Symbols.Verify();
}

[Theory]
[InlineData(RuntimeEnumerationFlags.Default)]
[InlineData(RuntimeEnumerationFlags.All)]
public void PreferredModuleMatchingAutomaticHintIsOnlyProbedOnce(RuntimeEnumerationFlags flags)
{
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
RuntimeDiscoveryTestTarget.ModuleDefinition app = target.AddModule(0x20000, "/app/preferred");
target.AddSingleFileRuntime(app);
target.AddDiagnosticHeader(app.ImageBase);
target.Runtimes.PreferredRuntimeModule = app.ImageBase;

Assert.Equal(app.ImageBase, Assert.Single(target.Enumerate(flags)).RuntimeModule.ImageBase);
Assert.Single(target.ExportProbes, probe => probe.Symbol == "DotNetRuntimeInfo");
target.Symbols.Verify();
}

private sealed class TestRuntimeDiscoveryProvider(Func<IModule, RuntimeDescription> describe, int priority = 0) : IRuntimeDescriptionProvider
{
public int Priority => priority;
Expand Down
Loading
Loading