-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
213 lines (184 loc) · 8.28 KB
/
Copy pathProgram.cs
File metadata and controls
213 lines (184 loc) · 8.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
using System;
using System.Data;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using Microsoft.VisualBasic;
using Microsoft.Xna.Framework.Input;
namespace KAPE8bitEmulator
{
/// <summary> The main class. </summary>
public static class Program
{
public const string FIXED_NAME = "Battlesnake";
public static bool HasEmbeddedBinary = false;
public static bool IsHeadless = false;
public static int HeadlessTimeoutMs = 1000; // Default 1 second
public static string HeadlessDumpPath = "";
public static string FileName = "";
/// <summary> The main entry point for the application. </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("KAPE-8bit 6502 Emulator (C) 2022 zment\n");
Args = args;
var parsed = ArgParser.Parse(args ?? Array.Empty<string>());
// Flags
IsHeadless = parsed.Switches.ContainsKey("headless");
if (parsed.Switches.TryGetValue("timeout", out var t) && int.TryParse(t, out int to))
HeadlessTimeoutMs = to;
if (parsed.Switches.TryGetValue("dump", out var dp))
{
HeadlessDumpPath = dp;
if (HeadlessDumpPath == "true")
HeadlessDumpPath = Path.Combine(Path.GetDirectoryName(parsed!.FileName!)!, Path.GetFileNameWithoutExtension(parsed!.FileName!)! + ".dump");
}
if (parsed.Switches.ContainsKey("debug"))
KAPE8bitEmulator.DebugMode = true;
// Lightweight traversal tracing (Push/IRQ/PushKey)
if (parsed.Switches.ContainsKey("trace-cpu"))
KAPE8bitEmulator.CpuTraceMode = true;
if (parsed.Switches.ContainsKey("trace-gpu"))
KAPE8bitEmulator.GpuTraceMode = true;
// Determine binary filename (explicit --run takes precedence)
FileName = parsed.FileName!;
HasEmbeddedBinary = string.IsNullOrEmpty(FileName);
// Validate explicit --run usage: if user supplied --run but no filename, error out
if (parsed.Switches.ContainsKey("run") && string.Equals(parsed.Switches["run"], "true", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Error: '--run' specified but no filename provided. Use '--run <file>' or provide the filename positionally.");
Environment.Exit(1);
}
// Print args for visibility (kept from previous behavior)
for (int i = 0; i < Args.Length; i++) Console.WriteLine($"Arg {i}: {Args[i]}");
if (IsHeadless)
{
RunHeadless();
// Ensure process terminates cleanly after headless run
Environment.Exit(0);
}
else
{
using (var game = new KAPE8bitEmulator())
game.Run();
// Ensure process terminates cleanly after normal run
Environment.Exit(0);
}
}
private static void RunHeadless()
{
Console.WriteLine("Running in headless mode");
Console.WriteLine($"Timeout: {HeadlessTimeoutMs}ms");
if (!string.IsNullOrEmpty(HeadlessDumpPath))
{
Console.WriteLine($"Memory dump output: {HeadlessDumpPath}");
}
Console.WriteLine();
// Initialize emulator components
var sram = new SRAM64k();
if (HasEmbeddedBinary)
{
Console.WriteLine("[Headless] Loading embedded binary");
sram.FillFromEmbeddedBinary();
}
else
{
Console.WriteLine($"[Headless] Loading binary: {FileName}");
sram.FillRam(FileName);
}
// Create a minimal GPU proxy that just handles writes without graphics
var gpuProxy = new HeadlessGPUProxy();
var cpu = new CPU_6502();
new NMITimer(KAPE8bitEmulator.NMI_FPS, KAPE8bitEmulator.TICKS_PER_NMI, cpu);
sram.RegisterMap(cpu);
gpuProxy.RegisterWrite(cpu);
// Create a headless keyboard device so we can simulate key events
// for testing. Create the keyboard before mapping SRAM so the
// keyboard's read/write handlers take precedence over the SRAM
// fall-through handlers.
var keyboard = new KeyboardDevice(cpu);
Console.WriteLine("[Headless] Starting CPU execution...");
cpu.Reset();
cpu.EnterCycleLoop();
// If requested, simulate a keypress to trigger IRQ handling.
if (Args != null && Array.Exists(Args, a => string.Equals(a, "--simulate-key", StringComparison.OrdinalIgnoreCase)))
{
// Enable IRQ via the keyboard control register (bit1 = IRQ enable)
try
{
int writeBpCounter = 0;
cpu.RegisterWriteBreakpointAction(0x0201, "INT_Vector 0 written", () =>
{
writeBpCounter++;
if (writeBpCounter == 2) {
Console.WriteLine("[Headless] Enabling Keyboard IRQs when INT Vector low byte is written");
keyboard.WriteControl(0xF770, 0x02); // bit1 = IRQ enable
}
});
keyboard.PushKey(Keys.A, false, true);
Console.WriteLine("[Headless] Simulated keypress 'A' (0x41)");
}
catch (Exception ex)
{
Console.WriteLine($"[Headless] Failed to simulate key: {ex.Message}");
}
}
// Run for timeout duration or until CPU halts
long startTick = DateTime.UtcNow.Ticks;
long timeoutTicks = (long)HeadlessTimeoutMs * 10000; // Convert ms to 100ns ticks
while (true)
{
long elapsed = DateTime.UtcNow.Ticks - startTick;
if (elapsed >= timeoutTicks)
{
Console.WriteLine($"[Headless] Exiting successfully");
break;
}
if (!cpu.IsRunning)
{
Console.WriteLine("[Headless] CPU halted");
break;
}
Thread.Sleep(100); // Small sleep to prevent busy-loop
}
Console.WriteLine("[Headless] Stopping CPU...");
cpu.Stop();
// Dump memory if requested
if (!string.IsNullOrEmpty(HeadlessDumpPath))
{
try
{
var ram = sram.GetRamCopy();
File.WriteAllBytes(HeadlessDumpPath, ram);
Console.WriteLine($"[Headless] Memory dump written to {HeadlessDumpPath}");
}
catch (Exception ex)
{
Console.WriteLine($"[Headless] Failed to write memory dump: {ex.Message}");
}
}
Console.WriteLine("[Headless] Exiting...");
}
/// <summary> Minimal GPU proxy for headless mode - handles GPU writes without graphics rendering. </summary>
private class HeadlessGPUProxy
{
// Minimal implementation - just enough to satisfy CPU write requests
public void RegisterWrite(CPU_6502 cpu)
{
bool isTerminal = false;
// Register GPU address range (0x8000-0xBFFF) to absorb writes
cpu.RegisterWrite(0x8000, 0xBFFF, (address, value) =>
{
// Silently absorb GPU writes in headless mode
if (KAPE8bitEmulator.DebugMode)
Console.WriteLine($"[GPU] Write to ${address:X4}: ${value:X2}");
if (isTerminal)
Console.Write($"{(char) value}");
if (value == 0x02)
isTerminal = true;
});
}
}
public static string[] Args = Array.Empty<string>();
}
}