diff --git a/src/Microsoft.Diagnostics.DebugServices.Implementation/DescriptionBasedRuntimeProvider.cs b/src/Microsoft.Diagnostics.DebugServices.Implementation/DescriptionBasedRuntimeProvider.cs index b2e94a58e0..847ec36a51 100644 --- a/src/Microsoft.Diagnostics.DebugServices.Implementation/DescriptionBasedRuntimeProvider.cs +++ b/src/Microsoft.Diagnostics.DebugServices.Implementation/DescriptionBasedRuntimeProvider.cs @@ -119,15 +119,30 @@ internal IEnumerable EnumerateRuntimeDescriptions( IModule[] modules = _services.GetService().EnumerateModules().ToArray(); HashSet handledModules = []; - // DotNetRuntimeDiscoveryProvider is efficient at discovering coreclr/clr .NET runtimes, so we try it first. + if (!all && + _services.GetService()?.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(), modules)) + orderedProviders.OfType(), normalModules)) { + foundNormalRuntime = true; handledModules.Add(description.Module.ImageBase); yield return description; } - if (handledModules.Count > 0 && !all) + if (foundNormalRuntime && !all) { yield break; } diff --git a/src/Microsoft.Diagnostics.DebugServices.Implementation/RuntimeService.cs b/src/Microsoft.Diagnostics.DebugServices.Implementation/RuntimeService.cs index b37c5d6f33..cf10caa748 100644 --- a/src/Microsoft.Diagnostics.DebugServices.Implementation/RuntimeService.cs +++ b/src/Microsoft.Diagnostics.DebugServices.Implementation/RuntimeService.cs @@ -44,6 +44,8 @@ private void Flush() #region IRuntimeService + public ulong? PreferredRuntimeModule { get; set; } + /// /// Returns the list of runtimes in the target /// diff --git a/src/Microsoft.Diagnostics.DebugServices/IRuntimeService.cs b/src/Microsoft.Diagnostics.DebugServices/IRuntimeService.cs index 3ba22b1ed7..a72d74b217 100644 --- a/src/Microsoft.Diagnostics.DebugServices/IRuntimeService.cs +++ b/src/Microsoft.Diagnostics.DebugServices/IRuntimeService.cs @@ -10,6 +10,13 @@ namespace Microsoft.Diagnostics.DebugServices /// public interface IRuntimeService { + /// + /// 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. + /// + ulong? PreferredRuntimeModule { get; set; } + /// /// Returns the list of runtimes in the target /// diff --git a/src/Microsoft.Diagnostics.ExtensionCommands/Host/RuntimesCommand.cs b/src/Microsoft.Diagnostics.ExtensionCommands/Host/RuntimesCommand.cs index a20466d6fd..602d34afb2 100644 --- a/src/Microsoft.Diagnostics.ExtensionCommands/Host/RuntimesCommand.cs +++ b/src/Microsoft.Diagnostics.ExtensionCommands/Host/RuntimesCommand.cs @@ -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; } @@ -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; } @@ -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) { @@ -76,6 +120,12 @@ public override void Invoke() flush = true; } + if (preferredModule != RuntimeService.PreferredRuntimeModule) + { + RuntimeService.PreferredRuntimeModule = preferredModule; + flush = true; + } + if (flush) { Target.Flush(); @@ -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(); } } diff --git a/src/SOS/Strike/sosdocs.txt b/src/SOS/Strike/sosdocs.txt index d0905d45ac..bf911a2ace 100644 --- a/src/SOS/Strike/sosdocs.txt +++ b/src/SOS/Strike/sosdocs.txt @@ -2011,11 +2011,17 @@ runtime directory. \\ COMMAND: runtimes. -runtimes [-netfx] [-netcore] +runtimes [-netfx] [-netcore] [--all] [--module | --address | --clear-priority] -netfx - switch to the desktop .NET Framework runtime if loaded. -netcore - switch to the .NET Core runtime if loaded. +--module - try the named module before any other runtime discovery. +--address - 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. \\ - diff --git a/src/SOS/Strike/sosdocsunix.txt b/src/SOS/Strike/sosdocsunix.txt index fa6945192a..4b45153bc3 100644 --- a/src/SOS/Strike/sosdocsunix.txt +++ b/src/SOS/Strike/sosdocsunix.txt @@ -1691,8 +1691,16 @@ on another machine or for triage dumps. \\ COMMAND: runtimes. -runtimes +runtimes [--all] [--module | --address | --clear-priority] List the .NET runtimes in the target process. -\\ +--module - try the named module before any other runtime discovery. +--address - 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. +\\ diff --git a/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTestTarget.cs b/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTestTarget.cs index a2f09f5847..be456ce186 100644 --- a/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTestTarget.cs +++ b/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTestTarget.cs @@ -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(Symbols); + ServiceContainer hostServices = _host.CreateServiceContainer(); + hostServices.AddService(Symbols); + hostServices.AddService(new ContextService(_host)); _target = new(_host, platform, architecture, _memory, services => new TestModules(services, _modules, Symbols, ExportProbes)); } diff --git a/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTests.cs b/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTests.cs index 812cfc2680..08dd568fbc 100644 --- a/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTests.cs +++ b/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimeDiscoveryTests.cs @@ -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().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 describe, int priority = 0) : IRuntimeDescriptionProvider { public int Priority => priority; diff --git a/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimesCommandTests.cs b/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimesCommandTests.cs new file mode 100644 index 0000000000..90b07d66f2 --- /dev/null +++ b/src/tests/Microsoft.Diagnostics.DebugServices.UnitTests/RuntimesCommandTests.cs @@ -0,0 +1,141 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Runtime.InteropServices; +using Microsoft.Diagnostics.DebugServices.Implementation; +using Microsoft.Diagnostics.ExtensionCommands; +using Xunit; + +namespace Microsoft.Diagnostics.DebugServices.UnitTests +{ + public class RuntimesCommandTests + { + [Theory] + [InlineData("--module preferred")] + [InlineData("--address 30000")] + [InlineData("--address 0x30000")] + [InlineData("--address 00000000`00030000")] + public void PreferenceRefreshesCachedDiscoveryAndCanBeCleared(string option) + { + using RuntimeDiscoveryTestTarget target = CreateTarget(); + IRuntime original = Assert.Single(target.Enumerate()); + IContextService context = target.Services.GetService(); + Assert.Same(original, context.GetCurrentRuntime()); + (CommandService commands, ServiceContainer services, CaptureConsoleService console) = CreateCommandServices(target); + + commands.Execute($"runtimes {option}", services); + + Assert.Equal(0x30000UL, target.Runtimes.PreferredRuntimeModule); + Assert.Equal(0x30000UL, Assert.Single(target.Enumerate()).RuntimeModule.ImageBase); + Assert.Equal(0x30000UL, context.GetCurrentRuntime().RuntimeModule.ImageBase); + Assert.Contains(console.OutputLines, line => line.Contains("Preferred runtime module: 0000000000030000")); + + target.Flush(); + Assert.Equal(0x30000UL, target.Runtimes.PreferredRuntimeModule); + Assert.Equal(0x30000UL, Assert.Single(target.Enumerate()).RuntimeModule.ImageBase); + using RuntimeDiscoveryTestTarget other = CreateTarget(); + Assert.Null(other.Runtimes.PreferredRuntimeModule); + Assert.Equal(0x20000UL, Assert.Single(other.Enumerate()).RuntimeModule.ImageBase); + + commands.Execute("runtimes --clear-priority --netcore", services); + + Assert.Null(target.Runtimes.PreferredRuntimeModule); + Assert.Equal(0x20000UL, Assert.Single(target.Enumerate()).RuntimeModule.ImageBase); + Assert.Equal(0x20000UL, context.GetCurrentRuntime().RuntimeModule.ImageBase); + target.Symbols.Verify(); + other.Symbols.Verify(); + } + + [Theory] + [InlineData("--module missing", "was not found")] + [InlineData("--address xyz", "Invalid module base address")] + [InlineData("--address 20001", "Invalid module base address")] + [InlineData("--module preferred --address 30000", "Specify only one")] + [InlineData("--module preferred --clear-priority", "Specify only one")] + [InlineData("--address 30000 --clear-priority", "Specify only one")] + public void InvalidPreferenceDoesNotChangeCachedDiscovery(string option, string message) + { + using RuntimeDiscoveryTestTarget target = CreateTarget(); + target.Runtimes.PreferredRuntimeModule = 0x30000; + IRuntime original = Assert.Single(target.Enumerate()); + (CommandService commands, ServiceContainer services, _) = CreateCommandServices(target); + + DiagnosticsException exception = Assert.Throws(() => commands.Execute($"runtimes {option}", services)); + + Assert.Contains(message, exception.Message); + Assert.Equal(0x30000UL, target.Runtimes.PreferredRuntimeModule); + Assert.Same(original, Assert.Single(target.Enumerate())); + target.Symbols.Verify(); + } + + [Fact] + public void PreferredModuleOverridesNormalRuntimeDiscovery() + { + using RuntimeDiscoveryTestTarget target = CreateTarget(); + target.AddCoreRuntime(0x40000, diagnosticHeader: false); + Assert.Equal(0x40000UL, Assert.Single(target.Enumerate()).RuntimeModule.ImageBase); + (CommandService commands, ServiceContainer services, _) = CreateCommandServices(target); + + commands.Execute("runtimes --module preferred --netcore", services); + + Assert.Equal(0x30000UL, Assert.Single(target.Enumerate()).RuntimeModule.ImageBase); + Assert.Equal(0x30000UL, target.Services.GetService().GetCurrentRuntime().RuntimeModule.ImageBase); + target.Symbols.Verify(); + } + + [Fact] + public void AllDoesNotPrioritizePreferredModule() + { + using RuntimeDiscoveryTestTarget target = CreateTarget(); + (CommandService commands, ServiceContainer services, _) = CreateCommandServices(target); + + commands.Execute("runtimes --module preferred --all", services); + + IRuntime[] runtimes = target.Enumerate(); + Assert.Equal(2, runtimes.Length); + Assert.Equal(0x20000UL, runtimes[0].RuntimeModule.ImageBase); + Assert.Equal(0x30000UL, runtimes[1].RuntimeModule.ImageBase); + Assert.Equal(0x30000UL, target.Runtimes.PreferredRuntimeModule); + Assert.Equal(0x20000UL, target.Services.GetService().GetCurrentRuntime().RuntimeModule.ImageBase); + target.Symbols.Verify(); + } + + [Fact] + public void AmbiguousModuleNameRequiresAnAddress() + { + using RuntimeDiscoveryTestTarget target = CreateTarget(); + target.AddModule(0x40000, "/other/preferred"); + (CommandService commands, ServiceContainer services, _) = CreateCommandServices(target); + + DiagnosticsException exception = Assert.Throws(() => + commands.Execute("runtimes --module preferred", services)); + + Assert.Contains("ambiguous", exception.Message); + Assert.Contains("--address", exception.Message); + Assert.Null(target.Runtimes.PreferredRuntimeModule); + target.Symbols.Verify(); + } + + private static RuntimeDiscoveryTestTarget CreateTarget() + { + RuntimeDiscoveryTestTarget target = new(OSPlatform.Linux, Architecture.X64); + RuntimeDiscoveryTestTarget.ModuleDefinition automatic = target.AddModule(0x20000, "/app/automatic"); + RuntimeDiscoveryTestTarget.ModuleDefinition preferred = target.AddModule(0x30000, "/app/preferred"); + target.AddSingleFileRuntime(automatic); + target.AddSingleFileRuntime(preferred); + target.AddDiagnosticHeader(automatic.ImageBase); + return target; + } + + private static (CommandService Commands, ServiceContainer Services, CaptureConsoleService Console) CreateCommandServices( + RuntimeDiscoveryTestTarget target) + { + CommandService commands = new(); + commands.AddCommands(typeof(RuntimesCommand)); + CaptureConsoleService console = new(); + ServiceContainer services = new(target.Services); + services.AddService(console); + return (commands, services, console); + } + } +}