Skip to content

Commit b89922e

Browse files
max-charlambMax Charlamb
andauthored
Add preferred module support to runtimes (#6194)
## Summary Add a target-scoped preferred runtime module to `!runtimes`: ```text runtimes --module <name> runtimes --address <hex-base> runtimes --clear-priority ``` This PR is based directly on `main` and preserves its existing runtime-discovery fallback and early-stop behavior. It does not include the default/full discovery rework. Default discovery probes the preferred module first, using runtime-description providers in priority order, and stops immediately on a successful match. If the module is unavailable or unrecognized, discovery follows main's existing normal-module, automatic-hint, and single-file fallback paths without retrying a preferred module already probed. Full enumeration (`--all`) ignores the preference and retains main's existing enumeration behavior. Preferences survive target flushes and are cleared explicitly. Changing or clearing the preference refreshes cached runtime discovery and the current runtime context. Module-name selection rejects missing or ambiguous matches; address selection requires an exact module base and accepts the existing hexadecimal address formats. Update SOS command help and add regression coverage for preferred-first default discovery, preference-independent full enumeration, unhinted single-file fallback after a failed preference, deduplication, provider priority, command validation, cache/context refresh, and target isolation. ## Validation 172 focused runtime provider, discovery, and command test cases passed. Co-authored-by: Max Charlamb <maxcharlamb@microsoft.com> Copilot-Session: dc2f081b-c77b-449b-a16c-7e09bf1cd9e2
1 parent f4a4c90 commit b89922e

9 files changed

Lines changed: 405 additions & 8 deletions

File tree

‎src/Microsoft.Diagnostics.DebugServices.Implementation/DescriptionBasedRuntimeProvider.cs‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -119,15 +119,30 @@ internal IEnumerable<RuntimeDescription> EnumerateRuntimeDescriptions(
119119
IModule[] modules = _services.GetService<IModuleService>().EnumerateModules().ToArray();
120120
HashSet<ulong> handledModules = [];
121121

122-
// DotNetRuntimeDiscoveryProvider is efficient at discovering coreclr/clr .NET runtimes, so we try it first.
122+
if (!all &&
123+
_services.GetService<IRuntimeService>()?.PreferredRuntimeModule is ulong preferredBase &&
124+
modules.FirstOrDefault(module => module.ImageBase == preferredBase) is IModule preferredModule)
125+
{
126+
handledModules.Add(preferredModule.ImageBase);
127+
foreach (RuntimeDescription description in EnumerateRuntimeDescriptions(orderedProviders, [preferredModule]))
128+
{
129+
yield return description;
130+
yield break;
131+
}
132+
}
133+
134+
// DotNetRuntimeDiscoveryProvider is efficient at discovering coreclr/clr .NET runtimes.
135+
bool foundNormalRuntime = false;
136+
IModule[] normalModules = modules.Where(module => !handledModules.Contains(module.ImageBase)).ToArray();
123137
foreach (RuntimeDescription description in EnumerateRuntimeDescriptions(
124-
orderedProviders.OfType<DotNetRuntimeDiscoveryProvider>(), modules))
138+
orderedProviders.OfType<DotNetRuntimeDiscoveryProvider>(), normalModules))
125139
{
140+
foundNormalRuntime = true;
126141
handledModules.Add(description.Module.ImageBase);
127142
yield return description;
128143
}
129144

130-
if (handledModules.Count > 0 && !all)
145+
if (foundNormalRuntime && !all)
131146
{
132147
yield break;
133148
}

‎src/Microsoft.Diagnostics.DebugServices.Implementation/RuntimeService.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ private void Flush()
4444

4545
#region IRuntimeService
4646

47+
public ulong? PreferredRuntimeModule { get; set; }
48+
4749
/// <summary>
4850
/// Returns the list of runtimes in the target
4951
/// </summary>

‎src/Microsoft.Diagnostics.DebugServices/IRuntimeService.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ namespace Microsoft.Diagnostics.DebugServices
1010
/// </summary>
1111
public interface IRuntimeService
1212
{
13+
/// <summary>
14+
/// Module base address to try first during default runtime discovery.
15+
/// Full runtime enumeration ignores this preference.
16+
/// The preference survives target flushes. Flush the target after changing it.
17+
/// </summary>
18+
ulong? PreferredRuntimeModule { get; set; }
19+
1320
/// <summary>
1421
/// Returns the list of runtimes in the target
1522
/// </summary>

‎src/Microsoft.Diagnostics.ExtensionCommands/Host/RuntimesCommand.cs‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ public class RuntimesCommand : CommandBase
2424
[ServiceImport]
2525
public ITarget Target { get; set; }
2626

27+
[ServiceImport]
28+
public IModuleService ModuleService { get; set; }
29+
2730
[Argument(Help = "Switch to the runtime by id.")]
2831
public int? Id { get; set; }
2932

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

42+
[Option(Name = "--module", Help = "Tries the named module first, stopping on a match unless --all is specified.")]
43+
public string ModuleName { get; set; }
44+
45+
[Option(Name = "--address", Help = "Tries the module at the hexadecimal base address first, stopping on a match unless --all is specified.")]
46+
public string ModuleAddress { get; set; }
47+
48+
[Option(Name = "--clear-priority", Help = "Clears the preferred runtime module.")]
49+
public bool ClearPriority { get; set; }
50+
3951
[Option(Name = "--usecdac", Help = "Controls cDAC usage: true (required), false (disabled), prefer (allow DAC fallback).")]
4052
public string UseCDac { get; set; }
4153

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

64+
if ((ModuleName is not null ? 1 : 0) + (ModuleAddress is not null ? 1 : 0) + (ClearPriority ? 1 : 0) > 1)
65+
{
66+
throw new DiagnosticsException("Specify only one of --module, --address, or --clear-priority");
67+
}
68+
69+
ulong? preferredModule = RuntimeService.PreferredRuntimeModule;
70+
if (ModuleName is not null)
71+
{
72+
IModule[] matches = ModuleService.GetModuleFromModuleName(ModuleName).ToArray();
73+
if (matches.Length == 0)
74+
{
75+
throw new DiagnosticsException($"Module '{ModuleName}' was not found");
76+
}
77+
if (matches.Length > 1)
78+
{
79+
throw new DiagnosticsException($"Module '{ModuleName}' is ambiguous. Use --address to specify a module base address.");
80+
}
81+
preferredModule = matches[0].ImageBase;
82+
}
83+
else if (ModuleAddress is not null)
84+
{
85+
if (!TryParseAddress(ModuleAddress, out ulong address))
86+
{
87+
throw new DiagnosticsException($"Invalid module base address '{ModuleAddress}'");
88+
}
89+
preferredModule = ModuleService.GetModuleFromBaseAddress(address).ImageBase;
90+
}
91+
else if (ClearPriority)
92+
{
93+
preferredModule = null;
94+
}
95+
5296
bool flush = false;
5397
if (UseCDac is not null)
5498
{
@@ -76,6 +120,12 @@ public override void Invoke()
76120
flush = true;
77121
}
78122

123+
if (preferredModule != RuntimeService.PreferredRuntimeModule)
124+
{
125+
RuntimeService.PreferredRuntimeModule = preferredModule;
126+
flush = true;
127+
}
128+
79129
if (flush)
80130
{
81131
Target.Flush();
@@ -125,6 +175,10 @@ public override void Invoke()
125175
this.DisplayResources(runtime.RuntimeModule, all: false, indent: " ");
126176
this.DisplayRuntimeExports(runtime.RuntimeModule, error: true, indent: " ");
127177
}
178+
if (RuntimeService.PreferredRuntimeModule is ulong preferredBase)
179+
{
180+
WriteLine($"Preferred runtime module: {preferredBase:X16}");
181+
}
128182
this.DisplaySettingService();
129183
}
130184
}

‎src/SOS/Strike/sosdocs.txt‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2011,11 +2011,17 @@ runtime directory.
20112011
\\
20122012

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

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

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

‎src/SOS/Strike/sosdocsunix.txt‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1691,8 +1691,16 @@ on another machine or for triage dumps.
16911691
\\
16921692

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

16961696
List the .NET runtimes in the target process.
1697-
\\
16981697

1698+
--module <name> - try the named module before any other runtime discovery.
1699+
--address <base> - try the module at the specified hexadecimal base address first.
1700+
--clear-priority - clear the preferred module.
1701+
--all - enumerate all runtimes.
1702+
1703+
If the preferred module is recognized, discovery stops unless --all is specified.
1704+
Otherwise, discovery falls back to normal runtime modules, automatic hints, and
1705+
remaining modules. The preference is per target and survives flushes.
1706+
\\

‎src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTestTarget.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ public RuntimeDiscoveryTestTarget(OSPlatform platform, Architecture architecture
3434
{
3535
_memory = new(architecture is Architecture.X86 or Architecture.Arm ? 4 : 8);
3636
configureProviders?.Invoke(_host.ServiceManager);
37-
_host.CreateServiceContainer().AddService<ISymbolService>(Symbols);
37+
ServiceContainer hostServices = _host.CreateServiceContainer();
38+
hostServices.AddService<ISymbolService>(Symbols);
39+
hostServices.AddService<IContextService>(new ContextService(_host));
3840
_target = new(_host, platform, architecture, _memory,
3941
services => new TestModules(services, _modules, Symbols, ExportProbes));
4042
}

‎src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTests.cs‎

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -791,6 +791,168 @@ public void DiagnosticHintDoesNotProbeCrashRuntime()
791791
target.Symbols.Verify();
792792
}
793793

794+
[Theory]
795+
[InlineData("WINDOWS", RuntimeEnumerationFlags.Default)]
796+
[InlineData("WINDOWS", RuntimeEnumerationFlags.All)]
797+
[InlineData("LINUX", RuntimeEnumerationFlags.Default)]
798+
[InlineData("LINUX", RuntimeEnumerationFlags.All)]
799+
[InlineData("OSX", RuntimeEnumerationFlags.Default)]
800+
[InlineData("OSX", RuntimeEnumerationFlags.All)]
801+
public void OnlyDefaultDiscoveryPrioritizesPreferredModule(string platform, RuntimeEnumerationFlags flags)
802+
{
803+
OSPlatform os = OSPlatform.Create(platform);
804+
using RuntimeDiscoveryTestTarget target = new(os, Architecture.X64);
805+
target.AddModule(0x10000, ApplicationName(os, "unrelated"), needsSymbols: true);
806+
RuntimeDiscoveryTestTarget.ModuleDefinition automatic = target.AddModule(0x20000, ApplicationName(os, "automatic"), entryPoint: true);
807+
RuntimeDiscoveryTestTarget.ModuleDefinition preferred = target.AddModule(0x30000, ApplicationName(os, "preferred"));
808+
target.AddSingleFileRuntime(automatic);
809+
target.AddSingleFileRuntime(preferred);
810+
target.AddDiagnosticHeader(automatic.ImageBase);
811+
target.Runtimes.PreferredRuntimeModule = preferred.ImageBase;
812+
if (flags == RuntimeEnumerationFlags.All)
813+
{
814+
target.Symbols.ExpectSymbolFile(0x10000, result: null);
815+
}
816+
817+
Assert.Equal(flags == RuntimeEnumerationFlags.All ? [automatic.ImageBase, preferred.ImageBase] : new[] { preferred.ImageBase },
818+
target.Enumerate(flags).Select(runtime => runtime.RuntimeModule.ImageBase));
819+
Assert.Equal(flags == RuntimeEnumerationFlags.All ? [automatic.ImageBase, 0x10000UL, preferred.ImageBase] : new[] { preferred.ImageBase },
820+
target.ExportProbes.Where(probe => probe.Symbol == "DotNetRuntimeInfo").Select(probe => probe.ModuleBase));
821+
target.Symbols.Verify();
822+
}
823+
824+
[Theory]
825+
[InlineData(RuntimeEnumerationFlags.Default)]
826+
[InlineData(RuntimeEnumerationFlags.All)]
827+
public void OnlyDefaultDiscoveryProbesPreferredModuleBeforeNormalRuntime(RuntimeEnumerationFlags flags)
828+
{
829+
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
830+
RuntimeDiscoveryTestTarget.ModuleDefinition preferred = target.AddModule(0x10000, "/app/preferred", needsSymbols: true);
831+
target.AddSingleFileRuntime(preferred, symbolOnly: true);
832+
target.AddCoreRuntime(0x20000);
833+
target.Runtimes.PreferredRuntimeModule = preferred.ImageBase;
834+
target.Symbols.ExpectSymbolFile(preferred.ImageBase, result: "mock-symbols");
835+
836+
IRuntime[] runtimes = target.Enumerate(flags);
837+
Assert.Equal(preferred.ImageBase, Assert.Single(runtimes, runtime => runtime.Services.GetService<ClrInfo>().IsSingleFile).RuntimeModule.ImageBase);
838+
Assert.Equal(flags == RuntimeEnumerationFlags.All ? 2 : 1, runtimes.Length);
839+
Assert.Equal(flags == RuntimeEnumerationFlags.All ? 0x20000UL : preferred.ImageBase, target.ExportProbes.First().ModuleBase);
840+
Assert.Equal([preferred.ImageBase], target.Symbols.Requests);
841+
target.Symbols.Verify();
842+
}
843+
844+
[Theory]
845+
[InlineData(RuntimeEnumerationFlags.Default)]
846+
[InlineData(RuntimeEnumerationFlags.All)]
847+
public void PreferredNamedRuntimeIsOnlyPrioritizedInDefaultDiscovery(RuntimeEnumerationFlags flags)
848+
{
849+
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
850+
target.AddCoreRuntime(0x20000, diagnosticHeader: false);
851+
target.AddCoreRuntime(0x30000, diagnosticHeader: false);
852+
target.Runtimes.PreferredRuntimeModule = 0x30000;
853+
854+
Assert.Equal(flags == RuntimeEnumerationFlags.All ? [0x20000UL, 0x30000UL] : new[] { 0x30000UL },
855+
target.Enumerate(flags).Select(runtime => runtime.RuntimeModule.ImageBase));
856+
Assert.Equal(flags == RuntimeEnumerationFlags.All ? [0x20000UL, 0x30000UL] : new[] { 0x30000UL },
857+
target.ExportProbes.Where(probe => probe.Symbol == "DotNetRuntimeContractDescriptor").Select(probe => probe.ModuleBase));
858+
target.Symbols.Verify();
859+
}
860+
861+
[Theory]
862+
[InlineData(RuntimeEnumerationFlags.Default)]
863+
[InlineData(RuntimeEnumerationFlags.All)]
864+
public void UnrecognizedPreferredModuleFallsBackToNormalDiscovery(RuntimeEnumerationFlags flags)
865+
{
866+
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
867+
target.AddModule(0x10000, "/app/preferred", needsSymbols: true);
868+
target.AddCoreRuntime(0x20000);
869+
target.Runtimes.PreferredRuntimeModule = 0x10000;
870+
target.Symbols.ExpectSymbolFile(0x10000, result: null);
871+
872+
Assert.Equal(0x20000UL, Assert.Single(target.Enumerate(flags)).RuntimeModule.ImageBase);
873+
Assert.Single(target.ExportProbes, probe => probe.ModuleBase == 0x10000 && probe.Symbol == "DotNetRuntimeInfo");
874+
target.Symbols.Verify();
875+
}
876+
877+
[Theory]
878+
[InlineData(RuntimeEnumerationFlags.Default)]
879+
[InlineData(RuntimeEnumerationFlags.All)]
880+
public void UnrecognizedPreferredModuleRetainsUnhintedSingleFileFallback(RuntimeEnumerationFlags flags)
881+
{
882+
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
883+
target.AddModule(0x10000, "/app/preferred", needsSymbols: true);
884+
RuntimeDiscoveryTestTarget.ModuleDefinition app = target.AddModule(0x20000, "/app/singlefile", needsSymbols: true);
885+
target.AddSingleFileRuntime(app, symbolOnly: true);
886+
target.Runtimes.PreferredRuntimeModule = 0x10000;
887+
target.Symbols.ExpectSymbolFile(0x10000, result: null);
888+
target.Symbols.ExpectSymbolFile(app.ImageBase, result: "mock-symbols");
889+
890+
Assert.Equal(app.ImageBase, Assert.Single(target.Enumerate(flags)).RuntimeModule.ImageBase);
891+
Assert.Equal([0x10000UL, app.ImageBase], target.Symbols.Requests);
892+
target.Symbols.Verify();
893+
}
894+
895+
[Theory]
896+
[InlineData(RuntimeEnumerationFlags.Default)]
897+
[InlineData(RuntimeEnumerationFlags.All)]
898+
public void UnrecognizedPreferredModuleFallsBackWithoutRetrying(RuntimeEnumerationFlags flags)
899+
{
900+
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
901+
target.AddModule(0x10000, "/app/preferred", needsSymbols: true);
902+
RuntimeDiscoveryTestTarget.ModuleDefinition automatic = target.AddModule(0x20000, "/app/automatic");
903+
target.AddSingleFileRuntime(automatic);
904+
target.AddDiagnosticHeader(automatic.ImageBase);
905+
target.Runtimes.PreferredRuntimeModule = 0x10000;
906+
target.Symbols.ExpectSymbolFile(0x10000, result: null);
907+
908+
Assert.Equal(automatic.ImageBase, Assert.Single(target.Enumerate(flags)).RuntimeModule.ImageBase);
909+
Assert.Equal(flags == RuntimeEnumerationFlags.All ? [automatic.ImageBase, 0x10000UL] : new[] { 0x10000UL, automatic.ImageBase }, target.ExportProbes
910+
.Where(probe => probe.Symbol == "DotNetRuntimeInfo").Select(probe => probe.ModuleBase));
911+
target.Symbols.Verify();
912+
}
913+
914+
[Fact]
915+
public void PreferredModuleTriesAllProvidersBeforeAutomaticHints()
916+
{
917+
List<(int Priority, ulong ModuleBase)> calls = [];
918+
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64, manager => {
919+
foreach (int priority in new[] { 100, 50 })
920+
{
921+
manager.AddProviderFactory(typeof(IRuntimeDescriptionProvider), _ =>
922+
new TestRuntimeDiscoveryProvider(module => {
923+
calls.Add((priority, module.ImageBase));
924+
return module.ImageBase == (priority == 100 ? 0x20000UL : 0x30000UL)
925+
? new RuntimeDescription(module, RuntimeType.NativeAOT, new Version(1, 0))
926+
: null;
927+
}, priority));
928+
}
929+
});
930+
target.AddModule(0x20000, "/app/automatic");
931+
target.AddModule(0x30000, "/app/preferred");
932+
target.AddDiagnosticHeader(0x20000);
933+
target.Runtimes.PreferredRuntimeModule = 0x30000;
934+
935+
Assert.Equal(0x30000UL, Assert.Single(target.Enumerate()).RuntimeModule.ImageBase);
936+
Assert.Equal([(100, 0x30000UL), (50, 0x30000UL)], calls);
937+
target.Symbols.Verify();
938+
}
939+
940+
[Theory]
941+
[InlineData(RuntimeEnumerationFlags.Default)]
942+
[InlineData(RuntimeEnumerationFlags.All)]
943+
public void PreferredModuleMatchingAutomaticHintIsOnlyProbedOnce(RuntimeEnumerationFlags flags)
944+
{
945+
using RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64);
946+
RuntimeDiscoveryTestTarget.ModuleDefinition app = target.AddModule(0x20000, "/app/preferred");
947+
target.AddSingleFileRuntime(app);
948+
target.AddDiagnosticHeader(app.ImageBase);
949+
target.Runtimes.PreferredRuntimeModule = app.ImageBase;
950+
951+
Assert.Equal(app.ImageBase, Assert.Single(target.Enumerate(flags)).RuntimeModule.ImageBase);
952+
Assert.Single(target.ExportProbes, probe => probe.Symbol == "DotNetRuntimeInfo");
953+
target.Symbols.Verify();
954+
}
955+
794956
private sealed class TestRuntimeDiscoveryProvider(Func<IModule, RuntimeDescription> describe, int priority = 0) : IRuntimeDescriptionProvider
795957
{
796958
public int Priority => priority;

0 commit comments

Comments
 (0)