Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

605 Zeilen
29KB

  1. # C64Tools.psm1 - build, run, test, and inspect Commodore 64/128 programs.
  2. #
  3. # Entry point for people and agents: tools\c64.ps1 (or c64.cmd at the repo root).
  4. # Requires PowerShell 7+ (pwsh), cc65, and VICE 3.x. Run `c64 doctor` to check.
  5. Set-StrictMode -Version 3.0
  6. $ErrorActionPreference = "Stop"
  7. $script:RepoRoot = Split-Path $PSScriptRoot -Parent
  8. $script:ToolCache = @{}
  9. # ---------------------------------------------------------------------------
  10. # Tool discovery
  11. # ---------------------------------------------------------------------------
  12. function Get-C64SearchDirs {
  13. $dirs = [System.Collections.Generic.List[string]]::new()
  14. if ($env:C64_TOOLS_PATH) { $env:C64_TOOLS_PATH -split ';' | Where-Object { $_ } | ForEach-Object { $dirs.Add($_) } }
  15. if ($env:VICE_HOME) { $dirs.Add((Join-Path $env:VICE_HOME "bin")); $dirs.Add($env:VICE_HOME) }
  16. if ($env:CC65_HOME) { $dirs.Add((Join-Path $env:CC65_HOME "bin")) }
  17. $globs = @(
  18. "$env:ProgramFiles\GTK3VICE-*\bin",
  19. "$env:ProgramFiles\SDL2VICE-*",
  20. "$env:LOCALAPPDATA\Microsoft\WinGet\Packages\VICE-Team.VICE*\GTK3VICE-*\bin",
  21. "$env:ProgramFiles\cc65*\bin",
  22. "C:\cc65\bin",
  23. "$env:ProgramFiles\ACME*",
  24. "$env:ProgramFiles\64tass*"
  25. )
  26. foreach ($g in $globs) {
  27. Get-Item -Path $g -ErrorAction SilentlyContinue |
  28. Sort-Object FullName -Descending | ForEach-Object { $dirs.Add($_.FullName) }
  29. }
  30. return $dirs
  31. }
  32. function Find-C64Tool {
  33. <# Returns the full path of a toolchain executable, or $null. #>
  34. param([Parameter(Mandatory)][string]$Name)
  35. if ($script:ToolCache.Contains($Name)) { return $script:ToolCache[$Name] }
  36. $found = $null
  37. foreach ($dir in Get-C64SearchDirs) {
  38. $candidate = Join-Path $dir "$Name.exe"
  39. if (Test-Path -LiteralPath $candidate) { $found = $candidate; break }
  40. }
  41. if (-not $found) {
  42. $cmd = Get-Command $Name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
  43. if ($cmd) { $found = $cmd.Source }
  44. }
  45. $script:ToolCache[$Name] = $found
  46. return $found
  47. }
  48. function Get-C64Tool {
  49. param([Parameter(Mandatory)][string]$Name)
  50. $path = Find-C64Tool $Name
  51. if (-not $path) { throw "$Name was not found. Run 'c64 doctor' and install it or set C64_TOOLS_PATH." }
  52. return $path
  53. }
  54. function Invoke-C64Native {
  55. <# Runs a console tool, echoes the command line, returns its output; throws on non-zero exit. #>
  56. param([Parameter(Mandatory)][string]$Tool, [string[]]$Arguments = @(), [string]$WorkingDirectory)
  57. $exe = Get-C64Tool $Tool
  58. Write-Host ("> {0} {1}" -f $Tool, ($Arguments -join ' ')) -ForegroundColor DarkGray
  59. if ($WorkingDirectory) { Push-Location $WorkingDirectory }
  60. try {
  61. $output = & $exe @Arguments 2>&1 | ForEach-Object { "$_" }
  62. $code = $LASTEXITCODE
  63. } finally {
  64. if ($WorkingDirectory) { Pop-Location }
  65. }
  66. if ($code -ne 0) {
  67. $output | ForEach-Object { Write-Host $_ }
  68. throw "$Tool failed with exit code $code"
  69. }
  70. return $output
  71. }
  72. # ---------------------------------------------------------------------------
  73. # Projects
  74. # ---------------------------------------------------------------------------
  75. function Get-C64Project {
  76. <#
  77. Resolves a project from a directory containing c64project.json, a path to the
  78. manifest itself, or a single source file (.c, .s, .asm, .bas).
  79. #>
  80. param([Parameter(Mandatory)][string]$Path)
  81. $full = [IO.Path]::GetFullPath((Join-Path (Get-Location) $Path))
  82. if (Test-Path -LiteralPath $full -PathType Container) {
  83. $manifest = Join-Path $full "c64project.json"
  84. if (-not (Test-Path -LiteralPath $manifest)) {
  85. throw "no c64project.json in $full. Pass a source file instead, or create one with 'c64 new'."
  86. }
  87. $full = $manifest
  88. }
  89. if (-not (Test-Path -LiteralPath $full)) { throw "not found: $Path" }
  90. if ([IO.Path]::GetFileName($full) -eq "c64project.json") {
  91. $dir = Split-Path $full -Parent
  92. $m = Get-Content -Raw -LiteralPath $full | ConvertFrom-Json -AsHashtable
  93. } else {
  94. $dir = Split-Path $full -Parent
  95. $ext = [IO.Path]::GetExtension($full).ToLowerInvariant()
  96. $lang = switch ($ext) {
  97. ".c" { "c" } ".s" { "asm" } ".asm" { "asm" } ".a65" { "asm" } ".bas" { "basic" }
  98. default { throw "unknown source type '$ext' (expected .c, .s, .asm, .bas)" }
  99. }
  100. $m = @{ name = [IO.Path]::GetFileNameWithoutExtension($full); language = $lang
  101. sources = @([IO.Path]::GetFileName($full)) }
  102. }
  103. $name = if ($m.Contains("name")) { $m.name } else { Split-Path $dir -Leaf }
  104. $machine = if ($m.Contains("machine")) { $m.machine } else { "c64" }
  105. if ($machine -notin @("c64", "c128")) { throw "machine must be c64 or c128, not '$machine'" }
  106. $buildDir = Join-Path $dir "build"
  107. $out = if ($m.Contains("output")) { Join-Path $dir $m.output } else { Join-Path $buildDir "$name.prg" }
  108. $sources = @()
  109. foreach ($pattern in @($m.sources)) {
  110. $hits = @(Get-ChildItem -Path (Join-Path $dir $pattern) -File -ErrorAction SilentlyContinue | Sort-Object Name)
  111. if (-not $hits -and -not [Management.Automation.WildcardPattern]::ContainsWildcardCharacters($pattern)) {
  112. throw "source file '$pattern' not found in $dir"
  113. }
  114. $sources += @($hits | ForEach-Object { $_.FullName })
  115. }
  116. if (-not $sources) { throw "no source files matched $(@($m.sources) -join ', ') in $dir" }
  117. $config = $null
  118. if ($m.Contains("config") -and $m.config) { $config = Join-Path $dir $m.config }
  119. $disk = $null
  120. if ($m.Contains("disk") -and $m.disk) {
  121. $disk = if ($m.disk -is [bool]) { Join-Path $buildDir "$name.d64" } else { Join-Path $dir $m.disk }
  122. }
  123. return [pscustomobject]@{
  124. Name = $name
  125. Dir = $dir
  126. Machine = $machine
  127. Language = $m.language
  128. Sources = $sources
  129. Config = $config
  130. Flags = @(if ($m.Contains("flags")) { $m.flags })
  131. Output = $out
  132. Labels = [IO.Path]::ChangeExtension($out, ".lbl")
  133. Map = [IO.Path]::ChangeExtension($out, ".map")
  134. Disk = $disk
  135. DiskFiles = @(if ($m.Contains("diskFiles")) { $m.diskFiles })
  136. Test = $(if ($m.Contains("test")) { $m.test } else { @{} })
  137. BasicCase = $(if ($m.Contains("basicCase")) { $m.basicCase } else { "lower" })
  138. }
  139. }
  140. function Convert-C64BasicSource {
  141. <#
  142. petcat tokenizes lower-case keywords (unshifted PETSCII), and lower-case text in
  143. strings shows as upper case on the C64's default character set. So listings are
  144. lowered by default and may be written exactly as the C64 displays them.
  145. -Preserve passes the text through for mixed-case (shifted) PETSCII.
  146. Non-ASCII punctuation becomes ASCII.
  147. #>
  148. param([string]$Text, [switch]$Preserve)
  149. $Text = $Text -replace '[–—]', '-' -replace '[‘’]', "'" -replace '[“”]', '"' -replace '←', '_'
  150. $Text = $Text -replace '[^\t\r\n\x20-\x7E]', '?'
  151. if (-not $Preserve) { $Text = $Text.ToLowerInvariant() }
  152. $lines = $Text -split "`r?`n" | Where-Object { $_.Trim() -ne "" }
  153. return ($lines -join "`n") + "`n"
  154. }
  155. function Get-C64PrgInfo {
  156. param([Parameter(Mandatory)][string]$Path)
  157. $bytes = [IO.File]::ReadAllBytes($Path)
  158. $load = $bytes[0] + 256 * $bytes[1]
  159. $end = $load + $bytes.Length - 3
  160. return [pscustomobject]@{ Load = $load; End = $end; Size = $bytes.Length - 2 }
  161. }
  162. function Invoke-C64Build {
  163. param([Parameter(Mandatory)][string]$Path)
  164. $p = Get-C64Project $Path
  165. New-Item -ItemType Directory -Force -Path (Split-Path $p.Output -Parent) | Out-Null
  166. switch ($p.Language) {
  167. { $_ -in "c", "asm" } {
  168. $argv = @("-t", $p.Machine)
  169. if ($p.Config) {
  170. $argv += @("-C", $p.Config)
  171. } elseif ($p.Language -eq "asm") {
  172. # Assembly with cc65's BASIC-stub config: the program starts at the first
  173. # byte of the CODE segment and runs with SYS (no C runtime).
  174. $argv += @("-C", "$($p.Machine)-asm.cfg", "-u", "__EXEHDR__")
  175. }
  176. if ($p.Language -eq "c" -and -not ($p.Flags -contains "-O" -or $p.Flags -contains "-Oi" -or $p.Flags -contains "-Or" -or $p.Flags -contains "-Os")) {
  177. $argv += "-O"
  178. }
  179. $argv += $p.Flags
  180. $inc = Join-Path $script:RepoRoot "lib"
  181. $argv += @("-I", $inc, "--asm-include-dir", $inc)
  182. $argv += @("-g", "-Ln", $p.Labels, "-m", $p.Map, "-o", $p.Output)
  183. $argv += $p.Sources
  184. Invoke-C64Native -Tool "cl65" -Arguments $argv -WorkingDirectory (Split-Path $p.Output -Parent) | ForEach-Object { Write-Host $_ }
  185. }
  186. "basic" {
  187. if ($p.Sources.Count -ne 1) { throw "a BASIC project has exactly one source file" }
  188. $tmp = Join-Path (Split-Path $p.Output -Parent) "$($p.Name).petcat.txt"
  189. $text = Convert-C64BasicSource (Get-Content -Raw -LiteralPath $p.Sources[0]) -Preserve:($p.BasicCase -eq "preserve")
  190. [IO.File]::WriteAllText($tmp, $text, [Text.Encoding]::ASCII)
  191. $dialect = if ($p.Machine -eq "c128") { "-w70" } else { "-w2" }
  192. Invoke-C64Native -Tool "petcat" -Arguments @($dialect, "-o", $p.Output, "--", $tmp) | ForEach-Object { Write-Host $_ }
  193. if (Test-Path -LiteralPath $p.Labels) { Remove-Item -LiteralPath $p.Labels }
  194. }
  195. default { throw "unsupported language '$($p.Language)' (use c, asm, or basic)" }
  196. }
  197. if (-not (Test-Path -LiteralPath $p.Output)) { throw "build produced no output at $($p.Output)" }
  198. $info = Get-C64PrgInfo $p.Output
  199. if ($p.Disk) {
  200. $diskName = $p.Name.ToLowerInvariant()
  201. if ($diskName.Length -gt 16) { $diskName = $diskName.Substring(0, 16) }
  202. $fmt = [IO.Path]::GetExtension($p.Disk).TrimStart('.').ToLowerInvariant()
  203. if (Test-Path -LiteralPath $p.Disk) { Remove-Item -LiteralPath $p.Disk }
  204. $c1541 = @("-format", "$diskName,00", $fmt, $p.Disk, "-write", $p.Output, $diskName)
  205. foreach ($f in $p.DiskFiles) {
  206. $src = Join-Path $p.Dir $f.path
  207. $dest = if ($f.Contains("name")) { $f.name } else { [IO.Path]::GetFileNameWithoutExtension($src).ToLowerInvariant() }
  208. if ($f.Contains("type") -and $f.type -eq "seq") { $dest = "$dest,s" }
  209. $c1541 += @("-write", $src, $dest)
  210. }
  211. Invoke-C64Native -Tool "c1541" -Arguments $c1541 | Out-Null
  212. }
  213. $rel = [IO.Path]::GetRelativePath((Get-Location).Path, $p.Output)
  214. Write-Host ("built {0} `${1:X4}-`${2:X4} ({3:N0} bytes)" -f $rel, $info.Load, $info.End, $info.Size) -ForegroundColor Green
  215. if ($p.Machine -eq "c64" -and $info.End -ge 0xA000 -and $info.Load -lt 0xA000) {
  216. Write-Warning "program extends past `$9FFF into BASIC ROM space; it must bank out BASIC before running."
  217. }
  218. if ($p.Disk) { Write-Host "disk $([IO.Path]::GetRelativePath((Get-Location).Path, $p.Disk))" -ForegroundColor Green }
  219. return $p
  220. }
  221. # ---------------------------------------------------------------------------
  222. # Emulator
  223. # ---------------------------------------------------------------------------
  224. function Get-C64Emulator([string]$Machine) { if ($Machine -eq "c128") { "x128" } else { "x64sc" } }
  225. function Resolve-C64Program {
  226. <# Accepts a .prg/.d64/.d71/.d81 directly, or anything Get-C64Project accepts (built first). #>
  227. param([Parameter(Mandatory)][string]$Path, [switch]$NoBuild, [string]$Machine, [switch]$FromDisk)
  228. $ext = [IO.Path]::GetExtension($Path).ToLowerInvariant()
  229. if ($ext -in ".prg", ".d64", ".d71", ".d81", ".t64", ".crt") {
  230. $full = [IO.Path]::GetFullPath((Join-Path (Get-Location) $Path))
  231. if (-not (Test-Path -LiteralPath $full)) { throw "not found: $Path" }
  232. $lbl = [IO.Path]::ChangeExtension($full, ".lbl")
  233. $outDir = Join-Path (Split-Path $full -Parent) "build"
  234. if ((Split-Path (Split-Path $full -Parent) -Leaf) -eq "build") { $outDir = Split-Path $full -Parent }
  235. return [pscustomobject]@{ Name = [IO.Path]::GetFileNameWithoutExtension($full); Program = $full
  236. Labels = $(if (Test-Path -LiteralPath $lbl) { $lbl } else { $null })
  237. Machine = $(if ($Machine) { $Machine } else { "c64" }); OutDir = $outDir; Test = @{} }
  238. }
  239. $p = if ($NoBuild) { Get-C64Project $Path } else { Invoke-C64Build $Path }
  240. # Injecting the PRG is fast and reliable; -FromDisk boots the disk image like real hardware.
  241. $prog = if ($FromDisk -and $p.Disk) { $p.Disk } else { $p.Output }
  242. return [pscustomobject]@{ Name = $p.Name; Program = $prog
  243. Labels = $(if (Test-Path -LiteralPath $p.Labels) { $p.Labels } else { $null })
  244. Machine = $(if ($Machine) { $Machine } else { $p.Machine }); OutDir = (Split-Path $p.Output -Parent); Test = $p.Test }
  245. }
  246. function Get-C64AutostartArgs($Target) {
  247. $argv = @("-autostart", ('"' + $Target.Program + '"'), "-autostart-warp")
  248. if ([IO.Path]::GetExtension($Target.Program) -ieq ".prg") { $argv += @("-autostartprgmode", "1") }
  249. return $argv
  250. }
  251. function Start-C64 {
  252. <# Launch a program interactively. -Monitor opens the remote monitor on port 6510 with labels loaded. #>
  253. param([Parameter(Mandatory)][string]$Path, [switch]$Monitor, [switch]$Warp, [string]$Keys,
  254. [int]$MonitorPort = 6510, [string]$Machine, [switch]$NoBuild, [switch]$FromDisk, [string[]]$ViceArgs = @())
  255. $t = Resolve-C64Program -Path $Path -NoBuild:$NoBuild -Machine $Machine -FromDisk:$FromDisk
  256. $argv = @("-default")
  257. if ($Monitor) {
  258. $argv += @("-remotemonitor", "-remotemonitoraddress", "ip4://127.0.0.1:$MonitorPort")
  259. if ($t.Labels) { $argv += @("-moncommands", ('"' + $t.Labels + '"')) }
  260. }
  261. if ($Warp) { $argv += "-warp" }
  262. if ($Keys) { $argv += @("-keybuf", ('"' + $Keys + '"')) }
  263. $argv += $ViceArgs
  264. $argv += Get-C64AutostartArgs $t
  265. $emu = Get-C64Tool (Get-C64Emulator $t.Machine)
  266. Write-Host ("> {0} {1}" -f (Split-Path $emu -Leaf), ($argv -join ' ')) -ForegroundColor DarkGray
  267. $proc = Start-Process -FilePath $emu -ArgumentList $argv -PassThru
  268. Write-Host "started $(Split-Path $emu -Leaf) (pid $($proc.Id))" -ForegroundColor Green
  269. if ($Monitor) {
  270. Write-Host "remote monitor: c64 mon `"r`" (labels: $(if ($t.Labels) { 'loaded' } else { 'none' }))"
  271. }
  272. return $proc
  273. }
  274. # ---------------------------------------------------------------------------
  275. # Screen decoding
  276. # ---------------------------------------------------------------------------
  277. function Convert-C64ScreenCode {
  278. <# Screen code -> printable ASCII. Reverse video is ignored. Graphics become '#'. #>
  279. param([byte]$Code, [bool]$Lowercase)
  280. $c = $Code -band 0x7F
  281. if ($c -eq 0) { return "@" }
  282. if ($c -le 26) { if ($Lowercase) { return [char](0x60 + $c) } else { return [char](0x40 + $c) } }
  283. if ($c -le 31) { return @('[', '\', ']', '^', '_')[$c - 27] }
  284. if ($c -le 63) { return [char]$c }
  285. if ($c -eq 96) { return " " }
  286. if ($Lowercase -and $c -ge 65 -and $c -le 90) { return [char]$c }
  287. if ($c -eq 64 -or $c -eq 67) { return "-" }
  288. if ($c -eq 93 -or $c -eq 66) { return "|" }
  289. return "#"
  290. }
  291. function Read-C64Screen {
  292. <#
  293. Decodes a test dump (ram.bin + io.bin written by the monitor) into the text the
  294. VIC-II is displaying, following $DD00 (VIC bank) and $D018 (matrix, charset).
  295. #>
  296. param([Parameter(Mandatory)][string]$DumpDir, [int]$Columns = 40, [int]$Rows = 25)
  297. $ram = [IO.File]::ReadAllBytes((Join-Path $DumpDir "ram.bin"))
  298. $io = [IO.File]::ReadAllBytes((Join-Path $DumpDir "io.bin"))
  299. $d018 = $io[2 + 0x18]; $dd00 = $io[2 + 0xD00]; $d011 = $io[2 + 0x11]
  300. $bank = (3 - ($dd00 -band 3)) * 0x4000
  301. $base = $bank + (($d018 -shr 4) * 0x400)
  302. $lower = ($d018 -band 2) -ne 0
  303. $lines = for ($r = 0; $r -lt $Rows; $r++) {
  304. $sb = [Text.StringBuilder]::new()
  305. for ($c = 0; $c -lt $Columns; $c++) {
  306. [void]$sb.Append((Convert-C64ScreenCode $ram[2 + $base + $r * $Columns + $c] $lower))
  307. }
  308. $sb.ToString().TrimEnd()
  309. }
  310. return [pscustomobject]@{
  311. Text = ($lines -join "`n"); Lines = $lines; ScreenBase = $base; Lowercase = $lower
  312. Bitmap = (($d011 -band 0x20) -ne 0); Border = $io[2 + 0x20] -band 15; Background = $io[2 + 0x21] -band 15
  313. }
  314. }
  315. function Get-C64BasicErrorName([int]$Number) {
  316. $names = @{ 1 = "TOO MANY FILES"; 2 = "FILE OPEN"; 3 = "FILE NOT OPEN"; 4 = "FILE NOT FOUND"
  317. 5 = "DEVICE NOT PRESENT"; 6 = "NOT INPUT FILE"; 7 = "NOT OUTPUT FILE"; 8 = "MISSING FILE NAME"
  318. 9 = "ILLEGAL DEVICE NUMBER"; 10 = "NEXT WITHOUT FOR"; 11 = "SYNTAX"; 12 = "RETURN WITHOUT GOSUB"
  319. 13 = "OUT OF DATA"; 14 = "ILLEGAL QUANTITY"; 15 = "OVERFLOW"; 16 = "OUT OF MEMORY"
  320. 17 = "UNDEF'D STATEMENT"; 18 = "BAD SUBSCRIPT"; 19 = "REDIM'D ARRAY"; 20 = "DIVISION BY ZERO"
  321. 21 = "ILLEGAL DIRECT"; 22 = "TYPE MISMATCH"; 23 = "STRING TOO LONG"; 24 = "FILE DATA"
  322. 25 = "FORMULA TOO COMPLEX"; 26 = "CAN'T CONTINUE"; 27 = "UNDEF'D FUNCTION"; 28 = "VERIFY"; 29 = "LOAD"
  323. 30 = "BREAK" }
  324. if ($names.ContainsKey($Number)) { return $names[$Number] } else { return "unknown" }
  325. }
  326. # ---------------------------------------------------------------------------
  327. # Headless test
  328. # ---------------------------------------------------------------------------
  329. function Invoke-C64Test {
  330. <#
  331. Runs a program headlessly in VICE, captures a dump, and decides pass/fail.
  332. Trigger (when to capture), first match wins:
  333. -Until <label|$addr> break when the PC reaches it
  334. -AfterJiffies <n> after n Kernal IRQs (1/60 s NTSC, 1/50 s PAL), counted from power-on
  335. (default) the program's first store to $D7FF (the VICE debug-cart register)
  336. Verdict: fail on timeout; with the $D7FF trigger, fail unless the stored value is 0;
  337. fail if any -Expect text is missing from the screen.
  338. Outputs in <build>/test/: screen.txt, screenshot.png, ram.bin, io.bin, monitor.log, result.json
  339. #>
  340. param(
  341. [Parameter(Mandatory)][string]$Path,
  342. [string[]]$Expect = @(),
  343. [string]$Until,
  344. [int]$AfterJiffies = 0,
  345. [string]$TickAddress,
  346. [string]$Keys,
  347. [int]$TimeoutSeconds = 0,
  348. [long]$MaxCycles = 0,
  349. [string]$Machine,
  350. [switch]$NoBuild,
  351. [switch]$Ntsc,
  352. [switch]$FromDisk,
  353. [string[]]$ViceArgs = @()
  354. )
  355. $t = Resolve-C64Program -Path $Path -NoBuild:$NoBuild -Machine $Machine -FromDisk:$FromDisk
  356. # Manifest defaults; command-line values win.
  357. $cfg = $t.Test
  358. if (-not $Expect -and $cfg.Contains("expect")) { $Expect = @($cfg.expect) }
  359. if (-not $Until -and $cfg.Contains("until")) { $Until = $cfg.until }
  360. if ($AfterJiffies -eq 0 -and $cfg.Contains("afterJiffies")) { $AfterJiffies = [int]$cfg.afterJiffies }
  361. if (-not $TickAddress -and $cfg.Contains("tickAddress")) { $TickAddress = $cfg.tickAddress }
  362. if (-not $Keys -and $cfg.Contains("keys")) { $Keys = $cfg.keys }
  363. if ($TimeoutSeconds -eq 0) { $TimeoutSeconds = if ($cfg.Contains("timeoutSeconds")) { [int]$cfg.timeoutSeconds } else { 60 } }
  364. if ($MaxCycles -eq 0) { $MaxCycles = if ($cfg.Contains("maxCycles")) { [long]$cfg.maxCycles } else { 150000000 } }
  365. $out = Join-Path $t.OutDir "test"
  366. if (Test-Path -LiteralPath $out) { Remove-Item -LiteralPath $out -Recurse -Force }
  367. New-Item -ItemType Directory -Force -Path $out | Out-Null
  368. $o = $out -replace '\\', '/'
  369. $mode = "d7ff"; $trigger = "watch store d7ff"
  370. if ($Until) {
  371. $mode = "until"
  372. $addr = if ($Until -match '^\$?[0-9a-fA-F]{1,4}$') { $Until.TrimStart('$') } else { "." + $Until.TrimStart('.') }
  373. $trigger = "break exec $addr"
  374. } elseif ($AfterJiffies -gt 0) {
  375. $mode = "jiffies"
  376. $tick = if ($TickAddress) { $TickAddress.TrimStart('$') } elseif ($t.Machine -eq "c128") { "fa65" } else { "ea31" }
  377. $trigger = "break exec $tick`nignore 1 $AfterJiffies"
  378. }
  379. $onHit = @(
  380. "bank io", "save `"$o/io.bin`" 0 d000 dfff",
  381. "bank ram", "save `"$o/ram.bin`" 0 0000 ffff",
  382. "bank cpu", "r",
  383. "save `"$o/done.bin`" 0 0002 0002",
  384. "quit" # from a playback file, quit exits cleanly (flushes the log, writes the screenshot)
  385. ) -join "`n"
  386. Set-Content -Encoding ascii -LiteralPath (Join-Path $out "onhit.mon") -Value $onHit
  387. $setup = @()
  388. if ($t.Labels) { $setup += Get-Content -LiteralPath $t.Labels }
  389. $setup += $trigger
  390. $setup += "command 1 `"pb \`"$o/onhit.mon\`"`""
  391. if ($t.Machine -eq "c64") {
  392. # BASIC's ERROR routine: X holds the error number. Capture and fail fast.
  393. $setup += "break exec a437"
  394. $setup += "command 2 `"pb \`"$o/onhit.mon\`"`""
  395. }
  396. $setup += "x"
  397. Set-Content -Encoding ascii -LiteralPath (Join-Path $out "setup.mon") -Value $setup
  398. $log = Join-Path $out "monitor.log"
  399. $shot = Join-Path $out "screenshot.png"
  400. $argv = @("-default", "-sounddev", "dummy", "-minimized", "-warp",
  401. "-limitcycles", "$MaxCycles",
  402. "-moncommands", ('"' + (Join-Path $out "setup.mon") + '"'),
  403. "-monlog", "-monlogname", ('"' + $log + '"'),
  404. "-exitscreenshot", ('"' + $shot + '"'))
  405. if ($Ntsc) { $argv += "-ntsc" }
  406. if ($Keys) { $argv += @("-keybuf", ('"' + $Keys + '"')) }
  407. $argv += $ViceArgs
  408. $argv += Get-C64AutostartArgs $t
  409. $emu = Get-C64Tool (Get-C64Emulator $t.Machine)
  410. Write-Host ("> {0} {1}" -f (Split-Path $emu -Leaf), ($argv -join ' ')) -ForegroundColor DarkGray
  411. $sw = [Diagnostics.Stopwatch]::StartNew()
  412. $proc = Start-Process -FilePath $emu -ArgumentList $argv -PassThru
  413. $done = Join-Path $out "done.bin"
  414. while (-not $proc.HasExited -and -not (Test-Path -LiteralPath $done) -and $sw.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
  415. Start-Sleep -Milliseconds 100
  416. }
  417. $captured = Test-Path -LiteralPath $done
  418. if (-not $proc.HasExited) {
  419. # A clean close flushes the monitor log and writes the exit screenshot.
  420. [void]$proc.CloseMainWindow()
  421. if (-not $proc.WaitForExit(10000)) { $proc.Kill(); $proc.WaitForExit() }
  422. }
  423. $seconds = [math]::Round($sw.Elapsed.TotalSeconds, 1)
  424. $result = [ordered]@{ program = $t.Program; mode = $mode; passed = $false; reason = ""; code = $null
  425. seconds = $seconds; screen = $null; missing = @(); pc = $null }
  426. $reasons = @()
  427. if (-not $captured) {
  428. $why = if ($sw.Elapsed.TotalSeconds -ge $TimeoutSeconds) { "wall-clock timeout ($TimeoutSeconds s)" } else { "emulator stopped after $MaxCycles cycles" }
  429. $reasons += "trigger never fired: $why"
  430. } else {
  431. $screen = Read-C64Screen -DumpDir $out
  432. Set-Content -LiteralPath (Join-Path $out "screen.txt") -Value $screen.Text -Encoding utf8
  433. $result.screen = $screen.Text
  434. $logText = if (Test-Path -LiteralPath $log) { Get-Content -Raw -LiteralPath $log } else { "" }
  435. if ($logText -match '(?m)^\.;([0-9a-f]{4}) ([0-9a-f]{2}) ([0-9a-f]{2})') {
  436. $result.pc = '$' + $Matches[1].ToUpperInvariant()
  437. if ($t.Machine -eq "c64" -and $Matches[1] -eq "a437") {
  438. $num = [Convert]::ToInt32($Matches[3], 16)
  439. $result.code = $num
  440. $reasons += "BASIC error $num ($(Get-C64BasicErrorName $num))"
  441. $mode = "basic-error"; $result.mode = $mode
  442. }
  443. }
  444. if ($mode -eq "d7ff") {
  445. $io = [IO.File]::ReadAllBytes((Join-Path $out "io.bin"))
  446. $result.code = [int]$io[2 + 0x7FF]
  447. if ($result.code -ne 0) { $reasons += "program reported failure code $($result.code) via `$D7FF" }
  448. }
  449. foreach ($e in $Expect) {
  450. if ($screen.Text.IndexOf($e, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $result.missing += $e }
  451. }
  452. if ($result.missing) { $reasons += "screen is missing: " + (($result.missing | ForEach-Object { "'$_'" }) -join ", ") }
  453. }
  454. $result.passed = ($reasons.Count -eq 0)
  455. $result.reason = if ($result.passed) { "ok" } else { $reasons -join "; " }
  456. $result | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $out "result.json") -Encoding utf8
  457. if ($result.screen) {
  458. Write-Host ("+" + ("-" * 40) + "+")
  459. $result.screen -split "`n" | ForEach-Object { Write-Host ("|" + $_.PadRight(40) + "|") }
  460. Write-Host ("+" + ("-" * 40) + "+")
  461. }
  462. $rel = [IO.Path]::GetRelativePath((Get-Location).Path, $out)
  463. if ($result.passed) {
  464. Write-Host "PASS $($t.Name) [$mode, ${seconds}s] artifacts: $rel" -ForegroundColor Green
  465. } else {
  466. Write-Host "FAIL $($t.Name) [$mode, ${seconds}s] $($result.reason) artifacts: $rel" -ForegroundColor Red
  467. }
  468. return [pscustomobject]$result
  469. }
  470. # ---------------------------------------------------------------------------
  471. # Remote monitor client
  472. # ---------------------------------------------------------------------------
  473. function Send-C64Monitor {
  474. <#
  475. Sends commands to a running VICE remote monitor (start one with `c64 run -Monitor`).
  476. Each command's output is returned. Emulation pauses while the monitor is active;
  477. unless -Stay is given, 'x' is sent at the end so the program keeps running.
  478. #>
  479. param([Parameter(Mandatory)][string[]]$Command, [int]$Port = 6510, [switch]$Stay, [int]$TimeoutMs = 5000)
  480. $client = [Net.Sockets.TcpClient]::new()
  481. try {
  482. $client.Connect("127.0.0.1", $Port)
  483. } catch {
  484. throw "no VICE remote monitor on port $Port. Start the program with 'c64 run <path> -Monitor'."
  485. }
  486. $stream = $client.GetStream()
  487. $stream.ReadTimeout = 300
  488. $buffer = [byte[]]::new(65536)
  489. $readUntilPrompt = {
  490. $sb = [Text.StringBuilder]::new()
  491. $deadline = [DateTime]::UtcNow.AddMilliseconds($TimeoutMs)
  492. while ([DateTime]::UtcNow -lt $deadline) {
  493. try {
  494. $n = $stream.Read($buffer, 0, $buffer.Length)
  495. if ($n -le 0) { break }
  496. [void]$sb.Append([Text.Encoding]::ASCII.GetString($buffer, 0, $n))
  497. if ($sb.ToString() -match '\(C:\$[0-9a-f]{4}\) $') { break }
  498. } catch [IO.IOException] { }
  499. }
  500. return $sb.ToString()
  501. }
  502. $send = { param($text) $bytes = [Text.Encoding]::ASCII.GetBytes("$text`n"); $stream.Write($bytes, 0, $bytes.Length) }
  503. try {
  504. & $send ""
  505. [void](& $readUntilPrompt)
  506. $results = foreach ($cmd in $Command) {
  507. & $send $cmd
  508. $text = & $readUntilPrompt
  509. ($text -replace '(?m)^\(C:\$[0-9a-f]{4}\) ?$', '').TrimEnd()
  510. }
  511. if (-not $Stay) { & $send "x" }
  512. return $results
  513. } finally {
  514. $client.Close()
  515. }
  516. }
  517. # ---------------------------------------------------------------------------
  518. # Project scaffolding and environment check
  519. # ---------------------------------------------------------------------------
  520. function New-C64Project {
  521. param([Parameter(Mandatory)][string]$Name, [ValidateSet("c", "asm", "basic")][string]$Template = "c",
  522. [string]$Destination)
  523. if ($Name -notmatch '^[a-z0-9][a-z0-9-]*$') { throw "use a lower-case name with letters, digits, and dashes" }
  524. $src = Join-Path $script:RepoRoot "templates\$Template"
  525. if (-not $Destination) { $Destination = Join-Path $script:RepoRoot "projects\$Name" }
  526. if (Test-Path -LiteralPath $Destination) { throw "$Destination already exists" }
  527. Copy-Item -LiteralPath $src -Destination $Destination -Recurse
  528. Get-ChildItem -LiteralPath $Destination -Recurse -File | ForEach-Object {
  529. $text = Get-Content -Raw -LiteralPath $_.FullName
  530. $new = $text.Replace("__NAME__", $Name)
  531. if ($new -ne $text) { [IO.File]::WriteAllText($_.FullName, $new) }
  532. }
  533. $buildDir = Join-Path $Destination "build"
  534. if (Test-Path -LiteralPath $buildDir) { Remove-Item -LiteralPath $buildDir -Recurse -Force }
  535. Write-Host "created $([IO.Path]::GetRelativePath((Get-Location).Path, $Destination)) from templates\$Template" -ForegroundColor Green
  536. return $Destination
  537. }
  538. function Test-C64Environment {
  539. $rows = foreach ($t in @(
  540. @{ n = "cl65"; why = "cc65 C compiler driver (required)" },
  541. @{ n = "ca65"; why = "cc65 assembler (required)" },
  542. @{ n = "ld65"; why = "cc65 linker (required)" },
  543. @{ n = "x64sc"; why = "VICE C64 emulator (required)" },
  544. @{ n = "x128"; why = "VICE C128 emulator (C128 projects)" },
  545. @{ n = "c1541"; why = "VICE disk image tool (disk images)" },
  546. @{ n = "petcat"; why = "VICE BASIC tokenizer (BASIC projects)" },
  547. @{ n = "acme"; why = "ACME assembler (optional)" },
  548. @{ n = "64tass"; why = "64tass assembler (optional)" },
  549. @{ n = "exomizer"; why = "Exomizer cruncher (optional)" })) {
  550. $p = Find-C64Tool $t.n
  551. [pscustomobject]@{ Tool = $t.n; Status = $(if ($p) { "ok" } else { "missing" }); Purpose = $t.why; Path = $p }
  552. }
  553. $rows += [pscustomobject]@{ Tool = "pwsh"; Status = "ok"; Purpose = "PowerShell $($PSVersionTable.PSVersion)"; Path = (Get-Process -Id $PID).Path }
  554. return $rows
  555. }
  556. Export-ModuleMember -Function Find-C64Tool, Get-C64Tool, Get-C64Project, Invoke-C64Build, Start-C64,
  557. Invoke-C64Test, Read-C64Screen, Convert-C64ScreenCode, Send-C64Monitor, New-C64Project,
  558. Test-C64Environment, Get-C64PrgInfo, Convert-C64BasicSource

Powered by TurnKey Linux.