選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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

Powered by TurnKey Linux.