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
4 changes: 3 additions & 1 deletion .agents/skills/spice86-config/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ dotnet run --project src/Spice86 -- -e program.exe --HttpApiPort 0 --McpHttpPort
| `--TimeMultiplier` | 1.0 | Scales emulated time (>1 faster, <1 slower, 0 freezes emulated time) |
| `--InstructionTimeScale` | (none) | PIT timer scale (alternative to TimeMultiplier) |
| `--ClockJitterSeed` | (none) | Deterministic clock jitter offset (0 to 0.01 ms) |
| `--ReproducibleRun` | (none) | Deterministic preset: sets `--InstructionTimeScale`, `--RenderingMode Sync`, and default `--ClockStartTime` (1993-06-01T00:00:00Z) |
| `--ReproducibleRun` | (none) | Deterministic preset: sets `--InstructionTimeScale`, `--RenderingMode Sync`, default `--ClockStartTime` (1993-06-01T00:00:00Z), and writes applied host input events to `spice86dumpInputRecording.jsonl` with the other dump files (CD audio is out of scope) |
| `--ReplayInput` | (none) | Path to a `spice86dumpInputRecording.jsonl` file to replay (ignores live input until finished) |
| `--ReplayInputBy` | Cycle | Replay scheduling key: `Cycle` (exact at same speed/mode) or `Time` (best effort by emulated time) |
| `--ClockStartTime` | UtcNow | Fixed emulated start date/time (ISO 8601) |

### Audio & Sound
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,9 @@ Spice86 -e program.exe --CpuHeavyLog \
-u, --UseCodeOverride (Default: true) <true or false> if false it will use the names provided by overrideSupplierClassName but not the code
-i, --InstructionTimeScale <number of instructions that have to be executed by the emulator to consider a second passed> if blank will use time based timer.
--ClockJitterSeed <CLOCKJITTERSEED> Optional integer seed enabling a small deterministic clock jitter (0 to 0.01 ms, a function of the emulated time). Omit to disable.
--ReproducibleRun <CYCLESPERSECOND> Deterministic run preset: sets --InstructionTimeScale to <CYCLESPERSECOND>, --RenderingMode Sync, and --ClockStartTime to 1993-06-01T00:00:00Z when omitted. Cannot be combined with --InstructionTimeScale, --Cycles, or --RenderingMode Async.
--ReproducibleRun <CYCLESPERSECOND> Deterministic run preset: sets --InstructionTimeScale to <CYCLESPERSECOND>, --RenderingMode Sync, and --ClockStartTime to 1993-06-01T00:00:00Z when omitted, and writes the applied host input events to spice86dumpInputRecording.jsonl with the other dump files. Cannot be combined with --InstructionTimeScale, --Cycles, or --RenderingMode Async. Note: CD audio advances on the mixer thread and is out of scope for deterministic replay.
--ReplayInput <REPLAYINPUT> Path to a recorded input JSON Lines file (spice86dumpInputRecording.jsonl) to replay. Live host input is ignored until all recorded events are applied.
--ReplayInputBy <REPLAYINPUTBY> (Default: Cycle) Key used to schedule replayed events: Cycle (exact at the same speed and mode) or Time (best effort by emulated time).
--GeneratedCode <LIST> Comma list selecting what generated overrides contain: +name enables, -name disables (no sign enables), applied left to right. Names: AsmComments, CheckBuild (a preset for the service-call notifications, branch probes and split port accesses of a check build), BranchProbes, ServiceCallNotifications, DeviceOperations, AssumeUnknownMemoryIsRam, AssumeAccessesStayInSegment, AssumeAbandonedStackSlotsUnobserved, AssumeSavedSlotsWrittenOnlyByPops. Every dump writes manifest.json next to the sources, whatever the selection.
--ClockStartTime <CLOCKSTARTTIME> Optional UTC start date/time for the emulated clock (parseable by DateTime.Parse, e.g. 1993-06-01T00:00:00Z). When omitted defaults to the current UTC time.
-t, --TimeMultiplier (Default: 1) Scales emulated time: if >1 emulated time goes faster, if <1 slower, 0 stops emulated time.
Expand Down
13 changes: 13 additions & 0 deletions src/Spice86.Core/CLI/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,19 @@ public override Spectre.Console.ValidationResult Validate() {
[CommandOption("--ReproducibleRun <CYCLESPERSECOND>")]
public long? ReproducibleRun { get; set; }

/// <summary>
/// Path to a recorded input JSON Lines file (<c>spice86dumpInputRecording.jsonl</c>) to replay.
/// </summary>
[CommandOption("--ReplayInput <REPLAYINPUT>")]
public string? ReplayInput { get; init; }

/// <summary>
/// Selects whether <see cref="ReplayInput"/> schedules events by CPU cycle or by emulated elapsed time.
/// </summary>
[CommandOption("--ReplayInputBy <REPLAYINPUTBY>")]
[DefaultValue(ReplayInputKey.Cycle)]
public ReplayInputKey ReplayInputBy { get; init; }

/// <summary>
/// Optional fixed start date/time for the emulated clock. Accepts any value parseable by
/// <see cref="DateTimeOffset.Parse(string)"/> (e.g. an ISO 8601 string like
Expand Down
12 changes: 12 additions & 0 deletions src/Spice86.Core/CLI/ReplayInputKey.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Spice86.Core.CLI;

/// <summary>
/// Selects which key schedules replayed input events.
/// </summary>
public enum ReplayInputKey {
/// <summary>Schedule each replayed event at its recorded CPU cycle count.</summary>
Cycle,

/// <summary>Schedule each replayed event at its recorded emulated elapsed time in milliseconds.</summary>
Time
}
6 changes: 6 additions & 0 deletions src/Spice86.Core/Emulator/ProgramExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace Spice86.Core.Emulator;

using Spice86.Core.Emulator.StateSerialization;
using Spice86.Core.Emulator.VM;
using Spice86.Core.Emulator.VM.Input.Recording;
using Spice86.Shared.Interfaces;

/// <summary>
Expand All @@ -19,6 +20,7 @@ public sealed class ProgramExecutor : IDisposable {
private readonly EmulatorStateSerializer _emulatorStateSerializer;
private readonly IShutdownCoordinator _shutdownCoordinator;
private readonly ExecutionPolicy _executionPolicy;
private readonly InputReplayDriver _inputReplayDriver;

/// <summary>
/// Initializes a new instance of <see cref="ProgramExecutor"/>. The initial program is loaded eagerly
Expand All @@ -29,18 +31,21 @@ public sealed class ProgramExecutor : IDisposable {
/// <param name="emulationLoop">The core emulation loop driver.</param>
/// <param name="emulatorStateSerializer">Writes the recorded emulation state on normal exit.</param>
/// <param name="shutdownCoordinator">Coordinates idempotent post-run teardown.</param>
/// <param name="inputReplayDriver">Arms the recorded input replay when the run starts.</param>
/// <param name="loggerService">The logging service to use.</param>
internal ProgramExecutor(
ProgramBootstrapper programBootstrapper,
ExecutionPolicy executionPolicy,
EmulationLoop emulationLoop,
EmulatorStateSerializer emulatorStateSerializer,
IShutdownCoordinator shutdownCoordinator,
InputReplayDriver inputReplayDriver,
ILogger loggerService) {
_emulationLoop = emulationLoop;
_emulatorStateSerializer = emulatorStateSerializer;
_shutdownCoordinator = shutdownCoordinator;
_executionPolicy = executionPolicy;
_inputReplayDriver = inputReplayDriver;
_loggerService = loggerService;
programBootstrapper.LoadInitialProgram();
}
Expand All @@ -57,6 +62,7 @@ public void Run() {
_executionPolicy.ApplyStartupBreakpoints();
_executionPolicy.StartGdbServer();
_executionPolicy.RegisterStopAfterCyclesBreakpoint();
_inputReplayDriver.Start();

_emulationLoop.Run();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ public enum DumpPhase {
Symbols,

/// <summary>Writing the breakpoints JSON dump.</summary>
Breakpoints
Breakpoints,

/// <summary>Writing the input recording of a reproducible run.</summary>
InputRecording
}

/// <summary>
Expand Down Expand Up @@ -91,7 +94,8 @@ public sealed class DumpProgressReporter {
[DumpPhase.CodeSource] = "Generated C# source",
[DumpPhase.CodeProject] = "Generated project",
[DumpPhase.Symbols] = "Ghidra symbols",
[DumpPhase.Breakpoints] = "Breakpoints"
[DumpPhase.Breakpoints] = "Breakpoints",
[DumpPhase.InputRecording] = "Input recording"
};

private static readonly IReadOnlyDictionary<DumpPhase, string> StepLabels =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ protected EmulationStateDataIoHandler(EmulatorStateSerializationFolder emulatorS
/// </summary>
protected string BreakpointsFile => $"{DataDirectory}/Breakpoints.json";

/// <summary>
/// Gets name of the file the input recording dump.
/// </summary>
internal string InputRecordingFile => GenerateDumpFileName("InputRecording.jsonl");

/// <summary>
/// Gets name of the file the CFG blocks JSON dump.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace Spice86.Core.Emulator.StateSerialization;

using Spice86.Core.Emulator.Function;
using Spice86.Core.Emulator.StateSerialization.CfgReload;
using Spice86.Core.Emulator.VM.Input.Recording;
using Spice86.Shared.Emulator.VM.Breakpoint.Serializable;

using System.Text.Json;
Expand Down Expand Up @@ -37,6 +38,11 @@ public IEnumerable<FunctionInformation> ReadGhidraSymbolsFromFileOrCreate() {
return new GhidraSymbolsExporter(LoggerService).ReadFromFileOrCreate(SymbolsFile);
}

/// <summary>Reads the recorded input events to replay, or none when no replay file is given.</summary>
internal IReadOnlyList<RecordedInputEvent> ReadInputRecordingOrEmpty(string? path) {
return path is null ? [] : InputRecordingReader.Read(path);
}

public SerializableUserBreakpointCollection ReadBreakpointsFromFileOrCreate() {
if (!File.Exists(BreakpointsFile) || new FileInfo(BreakpointsFile).Length == 0) {
return new();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ namespace Spice86.Core.Emulator.StateSerialization;
using Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration.Model;
using Spice86.Core.Emulator.ReverseEngineer.ControlFlowGraph;
using Spice86.Core.Emulator.StateSerialization.CfgReload;
using Spice86.Core.Emulator.VM.Input.Recording;
using Spice86.Shared.Emulator.Memory;
using Spice86.Shared.Emulator.VM.Breakpoint.Serializable;
using Spice86.Shared.Interfaces;
Expand Down Expand Up @@ -43,6 +44,7 @@ public class EmulationStateDataWriter : EmulationStateDataIoHandler {
private readonly Configuration _configuration;
private readonly CfgNodeIndex _nodeIndex;
private readonly RecordedRunFacts _recordedRunFacts;
private readonly InputRecording _inputRecording;
private readonly DumpProgressReporter _progress;
private readonly Lock _writeLock = new();

Expand All @@ -64,6 +66,7 @@ public class EmulationStateDataWriter : EmulationStateDataIoHandler {
/// <param name="configuration">The emulator configuration, used to derive the program checksum baked into the generated project.</param>
/// <param name="nodeIndex">The persistent graph index whose poison set is serialized with the CFG reload dump.</param>
/// <param name="recordedRunFacts">The recorded run facts serialized with the CFG reload dump.</param>
/// <param name="inputRecording">The host input events recorded during a reproducible run.</param>
/// <param name="progress">Reports dump phases and steps to the log and to UI subscribers.</param>
/// <param name="loggerService">The logger service implementation.</param>
internal EmulationStateDataWriter(State state,
Expand All @@ -81,6 +84,7 @@ internal EmulationStateDataWriter(State state,
Configuration configuration,
CfgNodeIndex nodeIndex,
RecordedRunFacts recordedRunFacts,
InputRecording inputRecording,
DumpProgressReporter progress,
ILogger loggerService) : base(emulatorStateSerializationFolder, loggerService) {
_executionAddressesExtractor = executionAddressesExtractor;
Expand All @@ -97,6 +101,7 @@ internal EmulationStateDataWriter(State state,
_configuration = configuration;
_nodeIndex = nodeIndex;
_recordedRunFacts = recordedRunFacts;
_inputRecording = inputRecording;
_progress = progress;
}

Expand Down Expand Up @@ -137,6 +142,10 @@ public void Write() {
}
WritePhase(DumpPhase.Symbols, SymbolsFile, () => new GhidraSymbolsExporter(LoggerService).Write(executionAddresses, _functionCatalogue, dataSymbolLabels, SymbolsFile));
WritePhase(DumpPhase.Breakpoints, BreakpointsFile, () => WriteBreakpoints(BreakpointsFile));
if (_inputRecording.IsEnabled) {
WritePhase(DumpPhase.InputRecording, InputRecordingFile,
() => InputRecordingWriter.Write(InputRecordingFile, _inputRecording.Snapshot()));
Comment thread
kevinferrare marked this conversation as resolved.
Resolved
}
succeeded = true;
} finally {
_progress.EndDump(succeeded);
Expand Down Expand Up @@ -197,4 +206,4 @@ private void WriteBreakpoints(string filePath) {
using FileStream fileStream = File.Open(filePath, FileMode.Create);
fileStream.Write(Encoding.UTF8.GetBytes(jsonString));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
namespace Spice86.Core.Emulator.VM.Input.Recording;

using Spice86.Core.Emulator.VM.Input.Events;
using Spice86.Shared.Emulator.Keyboard;
using Spice86.Shared.Emulator.Mouse;
using Spice86.Shared.Interfaces;

using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;

/// <summary>Shared JSON serializer options for input event recordings.</summary>
public static class InputEventSerialization {
/// <summary>JSON options using web defaults, string enum names and a "kind" discriminator for input events.</summary>
public static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web) {
Converters = { new JsonStringEnumConverter() },
TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { DescribeInputEventKinds } }
};

/// <summary>Registers the queued input kinds on <see cref="IInputEvent"/>, which lives in
/// Spice86.Shared and cannot name the Core command records in attributes.</summary>
private static void DescribeInputEventKinds(JsonTypeInfo typeInfo) {
if (typeInfo.Type != typeof(IInputEvent)) {
return;
}
typeInfo.PolymorphismOptions = new JsonPolymorphismOptions {
TypeDiscriminatorPropertyName = "kind",
DerivedTypes = {
new JsonDerivedType(typeof(KeyboardEventArgs), "key"),
new JsonDerivedType(typeof(MouseMoveEventArgs), "mouseMove"),
new JsonDerivedType(typeof(MouseButtonEventArgs), "mouseButton"),
new JsonDerivedType(typeof(ReleaseAllKeysInput), "releaseAllKeys"),
new JsonDerivedType(typeof(TimeMultiplierInput), "timeMultiplier")
Comment thread
kevinferrare marked this conversation as resolved.
Resolved
}
};
}
}
44 changes: 44 additions & 0 deletions src/Spice86.Core/Emulator/VM/Input/Recording/InputRecording.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
namespace Spice86.Core.Emulator.VM.Input.Recording;

using System.Linq;

/// <summary>
/// Collects the host input events applied during a reproducible run, for the dump to write.
/// </summary>
public sealed class InputRecording {
private readonly List<RecordedInputEvent> _events = [];
private readonly Lock _lock = new();

/// <summary>
/// Creates a recording; a disabled one ignores every event and is not dumped.
/// </summary>
public InputRecording(bool isEnabled) {
IsEnabled = isEnabled;
}

/// <summary>
/// Whether events are collected and dumped (set by --ReproducibleRun).
/// </summary>
public bool IsEnabled { get; }

/// <summary>
/// Adds an applied event; does nothing when the recording is disabled.
/// </summary>
public void Add(RecordedInputEvent recordedEvent) {
if (!IsEnabled) {
return;
}
lock (_lock) {
_events.Add(recordedEvent);
}
}

/// <summary>
/// Copy of the events recorded so far, safe to take while emulation runs.
/// </summary>
public IReadOnlyList<RecordedInputEvent> Snapshot() {
lock (_lock) {
return _events.ToList();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace Spice86.Core.Emulator.VM.Input.Recording;

using Spice86.Shared.Emulator.Errors;

using System.IO;
using System.Text.Json;

internal static class InputRecordingReader {
internal static IReadOnlyList<RecordedInputEvent> Read(string path) {
List<RecordedInputEvent> events = [];
int lineNumber = 0;
foreach (string line in File.ReadLines(path)) {
lineNumber++;
if (!string.IsNullOrWhiteSpace(line)) {
events.Add(Parse(path, lineNumber, line));
}
}
return events;
}

private static RecordedInputEvent Parse(string path, int lineNumber, string line) {
try {
RecordedInputEvent? recorded = JsonSerializer.Deserialize<RecordedInputEvent>(line, InputEventSerialization.Options);
if (recorded?.Event is null) {
throw new JsonException("The line holds no event.");
}
return recorded;
} catch (JsonException exception) {
throw new UnrecoverableException($"Invalid input recording {path} at line {lineNumber}: {exception.Message}", exception);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace Spice86.Core.Emulator.VM.Input.Recording;

using System.IO;
using System.Linq;
using System.Text.Json;

/// <summary>
/// Writes recorded host input events as JSON Lines, the counterpart of <see cref="InputRecordingReader"/>.
/// </summary>
internal static class InputRecordingWriter {
internal static void Write(string path, IReadOnlyList<RecordedInputEvent> events) {
File.WriteAllLines(path, events.Select(e => JsonSerializer.Serialize(e, InputEventSerialization.Options)));
}
}
25 changes: 25 additions & 0 deletions src/Spice86.Core/Emulator/VM/Input/Recording/InputReplay.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace Spice86.Core.Emulator.VM.Input.Recording;

/// <summary>
/// Holds the ordered stream of recorded input events being replayed.
/// </summary>
public sealed class InputReplay {
private readonly IReadOnlyList<RecordedInputEvent> _events;
private int _index;

/// <summary>
/// Initializes a new instance of the <see cref="InputReplay"/> class.
/// </summary>
public InputReplay(IReadOnlyList<RecordedInputEvent> events) {
_events = events;
}

/// <summary>Gets a value indicating whether recorded events remain to be replayed.</summary>
public bool IsReplaying => _index < _events.Count;

/// <summary>Gets the next recorded event to be applied.</summary>
public RecordedInputEvent Next => _events[_index];

/// <summary>Consumes and returns the next recorded event.</summary>
public RecordedInputEvent TakeNext() => _events[_index++];
}
Loading
Loading