You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

683 lines
34KB

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

Powered by TurnKey Linux.