namespace Spice86.Core.CLI; using Spectre.Console.Cli; using Spice86.Audio.Filters; using Spice86.Core.Emulator.CPU; using Spice86.Core.Emulator.Devices.Input.Mouse; using Spice86.Core.Emulator.Devices.Sound; using Spice86.Core.Emulator.Devices.Sound.Blaster; using Spice86.Core.Emulator.Devices.Timer; using Spice86.Core.Emulator.Function; using System.ComponentModel; /// Configuration for spice86, that is what to run and how. Set on startup. public sealed class Configuration : CommandSettings { /// /// CPU cycles per ms. Can be more precisely specified than instructions per second. Overrides instructions per second if used. /// [CommandOption("--Cycles ")] public int? Cycles { get; init; } /// /// Cpu Model to emulate /// [CommandOption("--CpuModel ")] [DefaultValue(CpuModel.INTEL_80286)] public CpuModel CpuModel { get; init; } /// /// Gets if the A20 gate is silenced. If true memory addresses will rollover above 1 MB. /// [CommandOption("--A20Gate")] public bool A20Gate { get; init; } /// Comma list selecting what generated overrides contain: entries applied left to /// right, +name enables and -name disables (no sign enables). The valid names are /// the rows of : /// AsmComments, CheckBuild (a preset for the service-call notifications, branch probes and /// split port accesses of a check build; later entries may override it), BranchProbes, /// ServiceCallNotifications, DeviceOperations, AssumeUnknownMemoryIsRam, /// AssumeAccessesStayInSegment, AssumeAbandonedStackSlotsUnobserved and /// AssumeSavedSlotsWrittenOnlyByPops. An unknown name fails parsing and lists them. Every dump /// writes manifest.json next to the sources, whatever the selection. [CommandOption("--GeneratedCode ")] public string? GeneratedCode { get; init; } /// Validates the --GeneratedCode list: every entry must be a valid sign and a /// known name. public override Spectre.Console.ValidationResult Validate() { try { Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration.GeneratedCodeSelection.Resolve(GeneratedCode); } catch (FormatException exception) { return Spectre.Console.ValidationResult.Error(exception.Message); } return Spectre.Console.ValidationResult.Success(); } /// /// Total RAM size, in KB, from physical address 0. Backs conventional memory, the HMA, and the /// unified extended-memory pool shared by XMS and EMS. Default is 16MB (16384), can be raised up /// to 64MB (65536) for demanding DOS extenders. /// [CommandOption("--RamSizeKb ")] [DefaultValue(RamSizeDefaultKb)] public int RamSizeKb { get; init; } = RamSizeDefaultKb; /// Default value for : 16MB. public const int RamSizeDefaultKb = 16 * 1024; /// Maximum allowed value for : 64MB. public const int RamSizeMaxKb = 64 * 1024; /// /// Gets if the program will be paused on start and stop. If is set, the program will be paused anyway. /// [CommandOption("--Debug")] public bool Debug { get; init; } /// Path to C drive, default is exe parent. [CommandOption("-c|--CDrive ")] public string? CDrive { get; set; } /// Path to executable. [CommandOption("-e|--Exe ")] public string Exe { get; set; } = string.Empty; /// List of parameters to give to the emulated program. [CommandOption("-a|--ExeArgs ")] public string? ExeArgs { get; set; } /// Hexadecimal string representing the expected SHA256 checksum of the emulated program. [CommandOption("-x|--ExpectedChecksum ")] public string? ExpectedChecksum { get; init; } /// The value of the expected SHA256 checksum. public byte[] ExpectedChecksumValue { get; set; } = Array.Empty(); /// Instantiated . Created by . public IOverrideSupplier? OverrideSupplier { get; set; } /// Name of a class in the current folder that will generate the initial function information. See documentation for more information. [CommandOption("-o|--OverrideSupplierClassName ")] public string? OverrideSupplierClassName { get; init; } /// If false it will use the names provided by but not the code. Use this in the code for . [CommandOption("-u|--UseCodeOverride ")] public bool? UseCodeOverride { get; set; } /// Gets a value indicating whether the option is set to true. public bool UseCodeOverrideOption => UseCodeOverride ?? true; /// /// Gets a value indicating whether C# code overrides actually replace emulated asm. This is true only when an /// is set and is enabled. When active, overrides /// mask the original asm and make the CFG jump between overrides, so CFG and execution flow dumps are not representative. /// public bool CodeOverridesActive => UseCodeOverrideOption && OverrideSupplier != null; /// /// Flag indicating if headless mode is enabled. When this option is not specified, the normal UI is used. /// [CommandOption("-h|--HeadlessMode ")] public HeadlessType? HeadlessMode { get; init; } /// /// If true, will fail when encountering an unhandled IO port. Useful to check for unimplemented hardware. false by default. /// [CommandOption("-f|--FailOnUnhandledPort")] public bool FailOnUnhandledPort { get; init; } /// /// GDB port spice86 will listen to. /// [CommandOption("-g|--GdbPort ")] [DefaultValue(10000)] public int GdbPort { get; init; } /// /// HTTP API port Spice86 will listen on. /// [CommandOption("--HttpApiPort|--http-api-port ")] [DefaultValue(20000)] public int HttpApiPort { get; init; } = 20000; /// /// Directory to dump data to when not specified otherwise. If blank dumps to SPICE86_DUMPS_FOLDER, and if not defined dumps to a sub directory named with the program SHA 256 signature. /// [CommandOption("-r|--RecordedDataDirectory ")] public string? RecordedDataDirectory { get; init; } /// /// When true, reloads the previously dumped CFG instruction graph (spice86dumpCfgReload.json) /// from the recorded data directory into live emulator state at startup, so previously explored /// program structure is restored across restarts. No-op if the file is absent. /// [CommandOption("--ReloadCfgGraph ")] [DefaultValue(true)] public bool ReloadCfgGraph { get; init; } /// /// Install DOS interrupt vectors or not. /// [CommandOption("-v|--InitializeDOS ")] public bool? InitializeDOS { get; set; } /// /// Only for /// [CommandOption("-i|--InstructionTimeScale ")] public long? InstructionTimeScale { get; set; } /// /// Optional seed for a deterministic clock jitter. When set, ElapsedTimeMs includes an offset in /// [0, 0.01] ms that depends only on the emulated time and the seed, so phase locks between devices do not /// hold forever. When null (the default), the clock has no jitter. /// [CommandOption("--ClockJitterSeed ")] public int? ClockJitterSeed { get; init; } /// /// Preset for a deterministic run at the given CPU cycles per second. Sets /// to the argument, to /// , and to /// when not set. /// [CommandOption("--ReproducibleRun ")] public long? ReproducibleRun { get; set; } /// /// Optional fixed start date/time for the emulated clock. Accepts any value parseable by /// (e.g. an ISO 8601 string like /// 1993-06-01T00:00:00Z). When null (the default), the emulated clock starts /// from at launch time. /// [CommandOption("--ClockStartTime ")] public DateTimeOffset? ClockStartTime { get; set; } /// /// Scales emulated time: 1 is normal speed, 2 makes emulated time pass twice as fast, 0 stops /// emulated time while the CPU keeps running. Negative values are rejected. /// [CommandOption("-t|--TimeMultiplier ")] [DefaultValue(1D)] public double TimeMultiplier { get; init; } /// /// The memory segment where the program will be loaded. The DOS PSP (Program Segment Prefix) and MCB (Memory Control Block) will be created before it. /// [CommandOption("-p|--ProgramEntryPointSegment ")] [DefaultValue("0x170")] public string? ProgramEntryPointSegmentString { get => null; set => ProgramEntryPointSegment = CommandLineParser.ParseHexDecBinUInt16(value ?? throw new ArgumentNullException(nameof(value))); } public ushort ProgramEntryPointSegment; /// /// The memory address where the ASM handlers for interrupts and so on are to be written. Default is F000 which is the bios segment. Not all games will be happy with this changed to something else. /// [CommandOption("--ProvidedAsmHandlersSegment ")] [DefaultValue((ushort)0xF000)] public ushort ProvidedAsmHandlersSegment { get; init; } /// /// Determines whether logs should be silenced or not. /// [CommandOption("-s|--SilencedLogs")] public bool SilencedLogs { get; init; } /// /// Determines whether verbose level logs should be enabled or not. /// [CommandOption("-l|--VerboseLogs")] public bool VerboseLogs { get; init; } /// /// Determines whether warning level logs should be enabled or not. /// [CommandOption("-w|--WarningLogs")] public bool WarningLogs { get; init; } /// /// The path to the zip file or directory containing the MT-32 ROM files. /// [CommandOption("-m|--Mt32RomsPath ")] public string? Mt32RomsPath { get; init; } /// /// Determines whether EMS (Expanded Memory Specification) should be enabled or not. /// [CommandOption("--Ems ")] public bool? Ems { get; init; } /// /// Determines whether DOS Upper Memory Blocks (UMBs) are available. /// [CommandOption("--Umb ")] [DefaultValue(true)] public bool Umb { get; set; } = true; /// /// Specify the type of mouse to use. /// [CommandOption("--Mouse ")] [DefaultValue(MouseType.Ps2)] public MouseType Mouse { get; init; } /// /// Specify a C header file to be used for structure information /// [CommandOption("--StructureFile ")] public string? StructureFile { get; init; } /// /// Audio engine to use /// [CommandOption("--AudioEngine ")] [DefaultValue(AudioEngine.CrossPlatform)] public AudioEngine AudioEngine { get; init; } /// /// Select the OPL synthesis mode. /// [CommandOption("--OplMode ")] [DefaultValue(OplMode.Opl3)] public OplMode OplMode { get; init; } /// /// Sound Blaster type to emulate. /// [CommandOption("--SbType ")] [DefaultValue(SbType.SBPro2)] public SbType SbType { get; init; } /// /// Sound Blaster base I/O address. /// [CommandOption("--SbBase ")] [DefaultValue((ushort)0x220)] public ushort SbBase { get; init; } /// /// Sound Blaster IRQ line. /// [CommandOption("--SbIrq ")] [DefaultValue((byte)7)] public byte SbIrq { get; init; } /// /// Sound Blaster 8-bit DMA channel. /// [CommandOption("--SbDma ")] [DefaultValue((byte)1)] public byte SbDma { get; init; } /// /// Sound Blaster 16-bit high DMA channel. /// [CommandOption("--SbHdma ")] [DefaultValue((byte)5)] public byte SbHdma { get; init; } /// /// Enable Sound Blaster mixer control of OPL voices. /// [CommandOption("--SbMixer ")] [DefaultValue(true)] public bool? SbMixer { get; init; } [CommandOption("--Xms ")] public bool? Xms { get; init; } /// /// If true, will throw an exception and crash when encountering an invalid opcode. /// If false, will handle invalid opcodes as CPU faults (int 0x06). /// Default is true because usually invalid opcode means emulator bug. /// [CommandOption("--FailOnInvalidOpcode ")] [DefaultValue(true)] public bool FailOnInvalidOpcode { get; init; } /// /// If true, logs every executed instruction to a file (similar to DOSBox heavy logging). /// This will significantly impact performance. Default is false. /// [CommandOption("--CpuHeavyLog")] public bool CpuHeavyLog { get; set; } /// /// Custom file path for CPU heavy log output. If not specified, defaults to {DumpDirectory}/cpu_heavy.log /// [CommandOption("--CpuHeavyLogDumpFile ")] public string? CpuHeavyLogDumpFile { get; init; } /// /// Named expressions appended to every CPU heavy log line. /// Each entry must be in "name=expression" format (e.g. "life=AX+1" or /// "mem=word ptr ds:[0x0100]"). Evaluated per instruction; compiled once at startup. /// Only active when is true. /// /// The option is named --CpuHeavyLogExpressions and accepts multiple values. /// Provide each pair as a quoted value when the expression contains spaces. /// Example: --CpuHeavyLogExpressions "life=AX+1" "myvalue=word ptr ds:[0x0456]" /// /// Splitting rule: the string is split on the first '='. For example /// flag=AX==0 becomes name flag and expression AX==0. /// [CommandOption("--CpuHeavyLogExpressions ")] public string[]? CpuHeavyLogExpressions { get; init; } [CommandOption("--AsmRenderingStyle ")] [DefaultValue(AsmRenderingStyle.Spice86)] public AsmRenderingStyle AsmRenderingStyle { get; init; } /// /// The number of CPU cycles after which the emulator will automatically stop. When greater than 0, a cycle /// breakpoint is registered before the emulation starts and triggers a clean shutdown. Set to 0 (default) /// to leave the emulator running until explicitly stopped. /// [CommandOption("--StopAfterCycles ")] public long StopAfterCycles { get; init; } /// /// Port for the MCP HTTP server. /// [CommandOption("--McpHttpPort ")] [DefaultValue(8081)] public int McpHttpPort { get; init; } /// /// Selects the VGA rendering mode. Sync fires VGA events on the emulation thread for determinism; /// Async fires them on the UI thread for better performance. Null means Async. /// [CommandOption("--RenderingMode ")] public RenderingMode? RenderingMode { get; set; } /// /// Controls how the JIT compiler handles instruction execution delegates. /// /// InterpretedThenCompiledDefault. Assigns an interpreted delegate immediately, then swaps in an optimized compiled delegate in the background. /// InterpretedOnlyOnly uses interpreted delegates. No background compilation threads are started. /// CompiledOnlyCompiles each instruction synchronously on first encounter, skipping the interpreted phase. /// /// [CommandOption("--JitMode ")] [DefaultValue(JitMode.InterpretedThenCompiled)] public JitMode JitMode { get; init; } /// /// Controls whether an INT instruction whose IVT entry is 0:0 is treated as valid. /// When true, execution continues at physical address 0. When false (default), a fatal exception is raised /// to catch uninitialized IVT entries. /// [CommandOption("--AllowIvtAddress0")] public bool AllowIvtAddress0 { get; init; } /// /// Controls what HLT does when interrupts are enabled. /// When false (default), HLT idles the CPU until the next hardware interrupt, like real hardware. /// When true, HLT always stops the emulation, which test programs use as an end marker. /// HLT with interrupts disabled always stops the emulation. /// [CommandOption("--HltStopsEmulation")] public bool HltStopsEmulation { get; set; } /// /// When true, the JIT executes each instruction's execution AST after it went through the IR round trip /// the code generator uses: lifted to IR, structured back to a CPU AST, with ALU calls expanded inline. /// Meant for checking that round trip; it makes each compiled instruction bigger. False by default. /// [CommandOption("--JitGeneratorIr")] public bool JitGeneratorIr { get; init; } /// /// When true (default), the speculative CFG explorer is enabled: after each newly-observed /// instruction is parsed, the explorer performs a recursive-descent static decode of all /// statically-reachable successors that have not yet been observed, marking the resulting nodes /// as speculative. This allows the C# code generator to emit real branches for unobserved /// conditional arms instead of always falling back to FailAsUntested. /// When false, no speculative nodes, edges, or index entries are created; the graph content is /// byte-identical to the pre-feature baseline. /// [CommandOption("--EnableSpeculativeCfgExploration ")] [DefaultValue(true)] public bool EnableSpeculativeCfgExploration { get; init; } = true; }