|
- # C64Tools.psm1 - build, run, test, and inspect Commodore 64/128 programs.
- #
- # Entry point for people and agents: tools\c64.ps1 (or c64.cmd at the repo root).
- # Requires PowerShell 7+ (pwsh), cc65, and VICE 3.x. Run `c64 doctor` to check.
-
- Set-StrictMode -Version 3.0
- $ErrorActionPreference = "Stop"
-
- $script:RepoRoot = Split-Path $PSScriptRoot -Parent
- $script:ToolCache = @{}
-
- # ---------------------------------------------------------------------------
- # Tool discovery
- # ---------------------------------------------------------------------------
-
- function Get-C64SearchDirs {
- $dirs = [System.Collections.Generic.List[string]]::new()
- if ($env:C64_TOOLS_PATH) { $env:C64_TOOLS_PATH -split ';' | Where-Object { $_ } | ForEach-Object { $dirs.Add($_) } }
- if ($env:VICE_HOME) { $dirs.Add((Join-Path $env:VICE_HOME "bin")); $dirs.Add($env:VICE_HOME) }
- if ($env:CC65_HOME) { $dirs.Add((Join-Path $env:CC65_HOME "bin")) }
- $globs = @(
- "$env:ProgramFiles\GTK3VICE-*\bin",
- "$env:ProgramFiles\SDL2VICE-*",
- "$env:LOCALAPPDATA\Microsoft\WinGet\Packages\VICE-Team.VICE*\GTK3VICE-*\bin",
- "$env:ProgramFiles\cc65*\bin",
- "C:\cc65\bin",
- "$env:ProgramFiles\ACME*",
- "$env:ProgramFiles\64tass*"
- )
- foreach ($g in $globs) {
- Get-Item -Path $g -ErrorAction SilentlyContinue |
- Sort-Object FullName -Descending | ForEach-Object { $dirs.Add($_.FullName) }
- }
- return $dirs
- }
-
- function Find-C64Tool {
- <# Returns the full path of a toolchain executable, or $null. #>
- param([Parameter(Mandatory)][string]$Name)
- if ($script:ToolCache.Contains($Name)) { return $script:ToolCache[$Name] }
- $found = $null
- foreach ($dir in Get-C64SearchDirs) {
- $candidate = Join-Path $dir "$Name.exe"
- if (Test-Path -LiteralPath $candidate) { $found = $candidate; break }
- }
- if (-not $found) {
- $cmd = Get-Command $Name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
- if ($cmd) { $found = $cmd.Source }
- }
- $script:ToolCache[$Name] = $found
- return $found
- }
-
- function Get-C64Tool {
- param([Parameter(Mandatory)][string]$Name)
- $path = Find-C64Tool $Name
- if (-not $path) { throw "$Name was not found. Run 'c64 doctor' and install it or set C64_TOOLS_PATH." }
- return $path
- }
-
- function Invoke-C64Native {
- <# Runs a console tool, echoes the command line, returns its output; throws on non-zero exit. #>
- param([Parameter(Mandatory)][string]$Tool, [string[]]$Arguments = @(), [string]$WorkingDirectory)
- $exe = Get-C64Tool $Tool
- Write-Host ("> {0} {1}" -f $Tool, ($Arguments -join ' ')) -ForegroundColor DarkGray
- if ($WorkingDirectory) { Push-Location $WorkingDirectory }
- try {
- $output = & $exe @Arguments 2>&1 | ForEach-Object { "$_" }
- $code = $LASTEXITCODE
- } finally {
- if ($WorkingDirectory) { Pop-Location }
- }
- if ($code -ne 0) {
- $output | ForEach-Object { Write-Host $_ }
- throw "$Tool failed with exit code $code"
- }
- return $output
- }
-
- function Resolve-C64Path([string]$Path) {
- <# Absolute or relative-to-current-directory path -> full path. #>
- if ([IO.Path]::IsPathRooted($Path)) { return [IO.Path]::GetFullPath($Path) }
- return [IO.Path]::GetFullPath((Join-Path (Get-Location).Path $Path))
- }
-
- # ---------------------------------------------------------------------------
- # Projects
- # ---------------------------------------------------------------------------
-
- function Get-C64Project {
- <#
- Resolves a project from a directory containing c64project.json, a path to the
- manifest itself, or a single source file (.c, .s, .asm, .bas).
- #>
- param([Parameter(Mandatory)][string]$Path)
- $full = (Resolve-C64Path $Path)
- if (Test-Path -LiteralPath $full -PathType Container) {
- $manifest = Join-Path $full "c64project.json"
- if (-not (Test-Path -LiteralPath $manifest)) {
- throw "no c64project.json in $full. Pass a source file instead, or create one with 'c64 new'."
- }
- $full = $manifest
- }
- if (-not (Test-Path -LiteralPath $full)) { throw "not found: $Path" }
-
- if ([IO.Path]::GetFileName($full) -eq "c64project.json") {
- $dir = Split-Path $full -Parent
- $m = Get-Content -Raw -LiteralPath $full | ConvertFrom-Json -AsHashtable
- } else {
- $dir = Split-Path $full -Parent
- $ext = [IO.Path]::GetExtension($full).ToLowerInvariant()
- $lang = switch ($ext) {
- ".c" { "c" } ".s" { "asm" } ".asm" { "asm" } ".a65" { "asm" } ".bas" { "basic" }
- default { throw "unknown source type '$ext' (expected .c, .s, .asm, .bas)" }
- }
- $m = @{ name = [IO.Path]::GetFileNameWithoutExtension($full); language = $lang
- sources = @([IO.Path]::GetFileName($full)) }
- }
-
- $name = if ($m.Contains("name")) { $m.name } else { Split-Path $dir -Leaf }
- $machine = if ($m.Contains("machine")) { $m.machine } else { "c64" }
- if ($machine -notin @("c64", "c128")) { throw "machine must be c64 or c128, not '$machine'" }
- $buildDir = Join-Path $dir "build"
- $out = if ($m.Contains("output")) { Join-Path $dir $m.output } else { Join-Path $buildDir "$name.prg" }
- $sources = @()
- foreach ($pattern in @($m.sources)) {
- $hits = @(Get-ChildItem -Path (Join-Path $dir $pattern) -File -ErrorAction SilentlyContinue | Sort-Object Name)
- if (-not $hits -and -not [Management.Automation.WildcardPattern]::ContainsWildcardCharacters($pattern)) {
- throw "source file '$pattern' not found in $dir"
- }
- $sources += @($hits | ForEach-Object { $_.FullName })
- }
- if (-not $sources) { throw "no source files matched $(@($m.sources) -join ', ') in $dir" }
- $config = $null
- if ($m.Contains("config") -and $m.config) { $config = Join-Path $dir $m.config }
- $disk = $null
- if ($m.Contains("disk") -and $m.disk) {
- $disk = if ($m.disk -is [bool]) { Join-Path $buildDir "$name.d64" } else { Join-Path $dir $m.disk }
- }
-
- return [pscustomobject]@{
- Name = $name
- Dir = $dir
- Machine = $machine
- Language = $m.language
- Sources = $sources
- Config = $config
- Flags = @(if ($m.Contains("flags")) { $m.flags })
- Output = $out
- Labels = [IO.Path]::ChangeExtension($out, ".lbl")
- Map = [IO.Path]::ChangeExtension($out, ".map")
- Disk = $disk
- DiskFiles = @(if ($m.Contains("diskFiles")) { $m.diskFiles })
- Test = $(if ($m.Contains("test")) { $m.test } else { @{} })
- Cc65Target = $(if ($m.Contains("cc65Target")) { $m.cc65Target } else { $machine })
- BasicCase = $(if ($m.Contains("basicCase")) { $m.basicCase } else { "lower" })
- }
- }
-
- function Convert-C64BasicSource {
- <#
- petcat tokenizes lower-case keywords (unshifted PETSCII), and lower-case text in
- strings shows as upper case on the C64's default character set. So listings are
- lowered by default and may be written exactly as the C64 displays them.
- -Preserve passes the text through for mixed-case (shifted) PETSCII.
- Non-ASCII punctuation becomes ASCII.
- #>
- param([string]$Text, [switch]$Preserve)
- $Text = $Text -replace '[–—]', '-' -replace '[‘’]', "'" -replace '[“”]', '"' -replace '←', '_'
- $Text = $Text -replace '[^\t\r\n\x20-\x7E]', '?'
- if (-not $Preserve) { $Text = $Text.ToLowerInvariant() }
- # Order lines the way the C64 screen editor stores them: by line number, a later
- # duplicate replacing an earlier one. petcat keeps file order, and a GOTO to a
- # higher line that sits earlier in the file then fails with UNDEF'D STATEMENT.
- $script:BasicWarned = [System.Collections.Generic.HashSet[string]]::new()
- $byNumber = [System.Collections.Generic.SortedDictionary[int, string]]::new()
- foreach ($line in ($Text -split "`r?`n")) {
- if ($line.Trim() -eq "") { continue }
- if ($line -notmatch '^\s*(\d+)') { throw "BASIC line without a line number: '$line'" }
- $num = [int]$Matches[1]
- if ($num -gt 63999) { throw "BASIC line number $num is above 63999" }
- if ($byNumber.ContainsKey($num)) { Write-Warning "BASIC line $num appears twice; the later one wins" }
- $byNumber[$num] = $line.TrimStart()
- Test-C64BasicVariableNames $line
- }
- return (@($byNumber.Values) -join "`n") + "`n"
- }
-
- function Test-C64BasicVariableNames([string]$Line) {
- <#
- Warns about variable names that the tokenizer splits around a keyword, such as
- NOTE% (NOT E%) or WAVEFORM (WAVE FOR M). Only assignment targets and DIM entries
- are checked, and names that start with a statement keyword are skipped, so
- compact code like FORI=1TO10 does not trigger it.
- #>
- $keywords = @("end","for","next","data","input","dim","read","let","goto","run","if","restore",
- "gosub","return","stop","on","wait","load","save","verify","def","poke","print","cont","list",
- "clr","cmd","sys","open","close","get","new","to","fn","then","not","step","and","or","sgn",
- "int","abs","usr","fre","pos","sqr","rnd","log","exp","cos","sin","tan","atn","peek","len",
- "str$","val","asc","chr$","left$","right$","mid$","go")
- $statements = @("end","for","next","data","input","dim","read","let","goto","run","if","restore",
- "gosub","return","stop","on","wait","load","save","verify","def","poke","print","cont","list",
- "clr","cmd","sys","open","close","get","new","rem","go")
- $code = [regex]::Replace($Line.ToLowerInvariant(), '"[^"]*"?', '""')
- $code = [regex]::Replace($code, '^\s*\d+', '')
- $code = ($code -split '\brem')[0]
- $names = @()
- foreach ($stmt in ($code -split ':|then')) {
- if ($stmt -match '^\s*dim\s+(.*)$') {
- $names += @([regex]::Matches($Matches[1], '([a-z][a-z0-9]*)[%$]?\s*\(') | ForEach-Object { $_.Groups[1].Value })
- } elseif ($stmt -match '^\s*(let\s+)?([a-z][a-z0-9]*)[%$]?\s*(\([^)]*\))?\s*=') {
- $names += $Matches[2]
- }
- }
- foreach ($word in $names) {
- if ($keywords -contains $word) { continue }
- if (@($statements | Where-Object { $word.StartsWith($_) })) { continue }
- $hits = @($keywords | Where-Object { $_.Length -gt 1 -and $word.Contains($_.TrimEnd('$')) })
- if ($hits -and $script:BasicWarned.Add($word)) {
- Write-Warning ("BASIC: variable {0} contains the keyword {1}, which the tokenizer splits out: {2}" -f $word.ToUpperInvariant(), ($hits -join "/").ToUpperInvariant(), $Line.Trim())
- }
- }
- }
-
- function Get-C64PrgInfo {
- param([Parameter(Mandatory)][string]$Path)
- $bytes = [IO.File]::ReadAllBytes($Path)
- $load = $bytes[0] + 256 * $bytes[1]
- $end = $load + $bytes.Length - 3
- return [pscustomobject]@{ Load = $load; End = $end; Size = $bytes.Length - 2 }
- }
-
- function Invoke-C64Build {
- param([Parameter(Mandatory)][string]$Path)
- $p = Get-C64Project $Path
- New-Item -ItemType Directory -Force -Path (Split-Path $p.Output -Parent) | Out-Null
-
- switch ($p.Language) {
- { $_ -in "c", "asm" } {
- # cc65Target "none" skips the target's PETSCII charmap: string bytes stay raw ASCII,
- # matching a plain `ca65 file.s` build. Needs its own linker config.
- $argv = @("-t", $p.Cc65Target)
- if ($p.Config) {
- $argv += @("-C", $p.Config)
- } elseif ($p.Cc65Target -eq "none") {
- throw 'cc65Target "none" needs a linker config ("config" in c64project.json)'
- } elseif ($p.Language -eq "asm") {
- # Assembly with cc65's BASIC-stub config: the program starts at the first
- # byte of the CODE segment and runs with SYS (no C runtime).
- $argv += @("-C", "$($p.Machine)-asm.cfg", "-u", "__EXEHDR__")
- }
- 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")) {
- $argv += "-O"
- }
- $argv += $p.Flags
- $inc = Join-Path $script:RepoRoot "lib"
- $argv += @("-I", $inc, "--asm-include-dir", $inc)
- $argv += @("-g", "-Ln", $p.Labels, "-m", $p.Map, "-o", $p.Output)
- $argv += $p.Sources
- Invoke-C64Native -Tool "cl65" -Arguments $argv -WorkingDirectory (Split-Path $p.Output -Parent) | ForEach-Object { Write-Host $_ }
- }
- "basic" {
- if ($p.Sources.Count -ne 1) { throw "a BASIC project has exactly one source file" }
- $tmp = Join-Path (Split-Path $p.Output -Parent) "$($p.Name).petcat.txt"
- $text = Convert-C64BasicSource (Get-Content -Raw -LiteralPath $p.Sources[0]) -Preserve:($p.BasicCase -eq "preserve")
- [IO.File]::WriteAllText($tmp, $text, [Text.Encoding]::ASCII)
- $dialect = if ($p.Machine -eq "c128") { "-w70" } else { "-w2" }
- Invoke-C64Native -Tool "petcat" -Arguments @($dialect, "-o", $p.Output, "--", $tmp) | ForEach-Object { Write-Host $_ }
- if (Test-Path -LiteralPath $p.Labels) { Remove-Item -LiteralPath $p.Labels }
- }
- default { throw "unsupported language '$($p.Language)' (use c, asm, or basic)" }
- }
-
- if (-not (Test-Path -LiteralPath $p.Output)) { throw "build produced no output at $($p.Output)" }
- $info = Get-C64PrgInfo $p.Output
-
- if ($p.Disk) {
- $diskName = $p.Name.ToLowerInvariant()
- if ($diskName.Length -gt 16) { $diskName = $diskName.Substring(0, 16) }
- $fmt = [IO.Path]::GetExtension($p.Disk).TrimStart('.').ToLowerInvariant()
- if (Test-Path -LiteralPath $p.Disk) { Remove-Item -LiteralPath $p.Disk }
- $c1541 = @("-format", "$diskName,00", $fmt, $p.Disk, "-write", $p.Output, $diskName)
- foreach ($f in $p.DiskFiles) {
- $src = Join-Path $p.Dir $f.path
- $dest = if ($f.Contains("name")) { $f.name } else { [IO.Path]::GetFileNameWithoutExtension($src).ToLowerInvariant() }
- if ($f.Contains("type") -and $f.type -eq "seq") { $dest = "$dest,s" }
- $c1541 += @("-write", $src, $dest)
- }
- Invoke-C64Native -Tool "c1541" -Arguments $c1541 | Out-Null
- }
-
- $rel = [IO.Path]::GetRelativePath((Get-Location).Path, $p.Output)
- Write-Host ("built {0} `${1:X4}-`${2:X4} ({3:N0} bytes)" -f $rel, $info.Load, $info.End, $info.Size) -ForegroundColor Green
- if ($p.Machine -eq "c64" -and $info.End -ge 0xA000 -and $info.Load -lt 0xA000) {
- Write-Warning "program extends past `$9FFF into BASIC ROM space; it must bank out BASIC before running."
- }
- if ($p.Disk) { Write-Host "disk $([IO.Path]::GetRelativePath((Get-Location).Path, $p.Disk))" -ForegroundColor Green }
- return $p
- }
-
- # ---------------------------------------------------------------------------
- # Emulator
- # ---------------------------------------------------------------------------
-
- function Get-C64Emulator([string]$Machine) { if ($Machine -eq "c128") { "x128" } else { "x64sc" } }
-
- function Resolve-C64Program {
- <# Accepts a .prg/.d64/.d71/.d81 directly, or anything Get-C64Project accepts (built first). #>
- param([Parameter(Mandatory)][string]$Path, [switch]$NoBuild, [string]$Machine, [switch]$FromDisk)
- $ext = [IO.Path]::GetExtension($Path).ToLowerInvariant()
- if ($ext -in ".prg", ".d64", ".d71", ".d81", ".t64", ".crt") {
- $full = (Resolve-C64Path $Path)
- if (-not (Test-Path -LiteralPath $full)) { throw "not found: $Path" }
- $lbl = [IO.Path]::ChangeExtension($full, ".lbl")
- $outDir = Join-Path (Split-Path $full -Parent) "build"
- if ((Split-Path (Split-Path $full -Parent) -Leaf) -eq "build") { $outDir = Split-Path $full -Parent }
- return [pscustomobject]@{ Name = [IO.Path]::GetFileNameWithoutExtension($full); Program = $full
- Labels = $(if (Test-Path -LiteralPath $lbl) { $lbl } else { $null })
- Machine = $(if ($Machine) { $Machine } else { "c64" }); OutDir = $outDir; Test = @{} }
- }
- $p = if ($NoBuild) { Get-C64Project $Path } else { Invoke-C64Build $Path }
- # Injecting the PRG is fast and reliable; -FromDisk boots the disk image like real hardware.
- $prog = if ($FromDisk -and $p.Disk) { $p.Disk } else { $p.Output }
- return [pscustomobject]@{ Name = $p.Name; Program = $prog
- Labels = $(if (Test-Path -LiteralPath $p.Labels) { $p.Labels } else { $null })
- Machine = $(if ($Machine) { $Machine } else { $p.Machine }); OutDir = (Split-Path $p.Output -Parent); Test = $p.Test }
- }
-
- function Get-C64DiskArgs([string]$Disk) {
- <# Attach an extra disk image to drive 8 (the autostarted program is injected separately). #>
- if (-not $Disk) { return @() }
- $full = (Resolve-C64Path $Disk)
- if (-not (Test-Path -LiteralPath $full)) { throw "disk image not found: $Disk" }
- return @("-8", ('"' + $full + '"'))
- }
-
- function Get-C64AutostartArgs($Target) {
- $argv = @("-autostart", ('"' + $Target.Program + '"'), "-autostart-warp")
- if ([IO.Path]::GetExtension($Target.Program) -ieq ".prg") { $argv += @("-autostartprgmode", "1") }
- return $argv
- }
-
- function Start-C64 {
- <# Launch a program interactively. -Monitor opens the remote monitor on port 6510 with labels loaded. #>
- param([Parameter(Mandatory)][string]$Path, [switch]$Monitor, [switch]$Warp, [string]$Keys,
- [int]$MonitorPort = 6510, [string]$Machine, [switch]$NoBuild, [switch]$FromDisk, [string]$Disk,
- [string[]]$ViceArgs = @())
- $t = Resolve-C64Program -Path $Path -NoBuild:$NoBuild -Machine $Machine -FromDisk:$FromDisk
- $argv = @("-default")
- if ($Monitor) {
- $argv += @("-remotemonitor", "-remotemonitoraddress", "ip4://127.0.0.1:$MonitorPort")
- if ($t.Labels) { $argv += @("-moncommands", ('"' + $t.Labels + '"')) }
- }
- if ($Warp) { $argv += "-warp" }
- if ($Keys) { $argv += @("-keybuf", ('"' + $Keys + '"')) }
- $argv += Get-C64DiskArgs $Disk
- $argv += $ViceArgs
- $argv += Get-C64AutostartArgs $t
- $emu = Get-C64Tool (Get-C64Emulator $t.Machine)
- Write-Host ("> {0} {1}" -f (Split-Path $emu -Leaf), ($argv -join ' ')) -ForegroundColor DarkGray
- $proc = Start-Process -FilePath $emu -ArgumentList $argv -PassThru
- Write-Host "started $(Split-Path $emu -Leaf) (pid $($proc.Id))" -ForegroundColor Green
- if ($Monitor) {
- Write-Host "remote monitor: c64 mon `"r`" (labels: $(if ($t.Labels) { 'loaded' } else { 'none' }))"
- }
- return $proc
- }
-
- # ---------------------------------------------------------------------------
- # Screen decoding
- # ---------------------------------------------------------------------------
-
- function Convert-C64ScreenCode {
- <# Screen code -> printable ASCII. Reverse video is ignored. Graphics become '#'. #>
- param([byte]$Code, [bool]$Lowercase)
- $c = $Code -band 0x7F
- if ($c -eq 0) { return "@" }
- if ($c -le 26) { if ($Lowercase) { return [char](0x60 + $c) } else { return [char](0x40 + $c) } }
- if ($c -le 31) { return @('[', '\', ']', '^', '_')[$c - 27] }
- if ($c -le 63) { return [char]$c }
- if ($c -eq 96) { return " " }
- if ($Lowercase -and $c -ge 65 -and $c -le 90) { return [char]$c }
- if ($c -eq 64 -or $c -eq 67) { return "-" }
- if ($c -eq 93 -or $c -eq 66) { return "|" }
- return "#"
- }
-
- function Read-C64Screen {
- <#
- Decodes a test dump (ram.bin + io.bin written by the monitor) into the text the
- VIC-II is displaying, following $DD00 (VIC bank) and $D018 (matrix, charset).
- #>
- param([Parameter(Mandatory)][string]$DumpDir, [int]$Columns = 40, [int]$Rows = 25)
- $ram = [IO.File]::ReadAllBytes((Join-Path $DumpDir "ram.bin"))
- $io = [IO.File]::ReadAllBytes((Join-Path $DumpDir "io.bin"))
- $d018 = $io[2 + 0x18]; $dd00 = $io[2 + 0xD00]; $d011 = $io[2 + 0x11]
- $bank = (3 - ($dd00 -band 3)) * 0x4000
- $base = $bank + (($d018 -shr 4) * 0x400)
- $lower = ($d018 -band 2) -ne 0
- $lines = for ($r = 0; $r -lt $Rows; $r++) {
- $sb = [Text.StringBuilder]::new()
- for ($c = 0; $c -lt $Columns; $c++) {
- [void]$sb.Append((Convert-C64ScreenCode $ram[2 + $base + $r * $Columns + $c] $lower))
- }
- $sb.ToString().TrimEnd()
- }
- return [pscustomobject]@{
- Text = ($lines -join "`n"); Lines = $lines; ScreenBase = $base; Lowercase = $lower
- Bitmap = (($d011 -band 0x20) -ne 0); Border = $io[2 + 0x20] -band 15; Background = $io[2 + 0x21] -band 15
- }
- }
-
- function Get-C64BasicErrorName([int]$Number) {
- $names = @{ 1 = "TOO MANY FILES"; 2 = "FILE OPEN"; 3 = "FILE NOT OPEN"; 4 = "FILE NOT FOUND"
- 5 = "DEVICE NOT PRESENT"; 6 = "NOT INPUT FILE"; 7 = "NOT OUTPUT FILE"; 8 = "MISSING FILE NAME"
- 9 = "ILLEGAL DEVICE NUMBER"; 10 = "NEXT WITHOUT FOR"; 11 = "SYNTAX"; 12 = "RETURN WITHOUT GOSUB"
- 13 = "OUT OF DATA"; 14 = "ILLEGAL QUANTITY"; 15 = "OVERFLOW"; 16 = "OUT OF MEMORY"
- 17 = "UNDEF'D STATEMENT"; 18 = "BAD SUBSCRIPT"; 19 = "REDIM'D ARRAY"; 20 = "DIVISION BY ZERO"
- 21 = "ILLEGAL DIRECT"; 22 = "TYPE MISMATCH"; 23 = "STRING TOO LONG"; 24 = "FILE DATA"
- 25 = "FORMULA TOO COMPLEX"; 26 = "CAN'T CONTINUE"; 27 = "UNDEF'D FUNCTION"; 28 = "VERIFY"; 29 = "LOAD"
- 30 = "BREAK" }
- if ($names.ContainsKey($Number)) { return $names[$Number] } else { return "unknown" }
- }
-
- # ---------------------------------------------------------------------------
- # Headless test
- # ---------------------------------------------------------------------------
-
- function Invoke-C64Test {
- <#
- Runs a program headlessly in VICE, captures a dump, and decides pass/fail.
-
- Trigger (when to capture), first match wins:
- -Until <label|$addr> break when the PC reaches it
- -AfterJiffies <n> after n Kernal IRQs (1/60 s NTSC, 1/50 s PAL), counted from power-on
- (default) the program's first store to $D7FF (the VICE debug-cart register)
-
- Verdict: fail on timeout; with the $D7FF trigger, fail unless the stored value is 0;
- fail if any -Expect text is missing from the screen.
- Outputs in <build>/test/<name>/: screen.txt, screenshot.png, ram.bin, io.bin, monitor.log, result.json
- #>
- param(
- [Parameter(Mandatory)][string]$Path,
- [string[]]$Expect = @(),
- [string]$Until,
- [int]$AfterJiffies = 0,
- [string]$TickAddress,
- [string]$Keys,
- [int]$TimeoutSeconds = 0,
- [long]$MaxCycles = 0,
- [string]$Machine,
- [switch]$NoBuild,
- [switch]$Ntsc,
- [switch]$FromDisk,
- [string]$Disk,
- [string[]]$ViceArgs = @()
- )
- $t = Resolve-C64Program -Path $Path -NoBuild:$NoBuild -Machine $Machine -FromDisk:$FromDisk
-
- # Manifest defaults; command-line values win.
- $cfg = $t.Test
- if (-not $Expect -and $cfg.Contains("expect")) { $Expect = @($cfg.expect) }
- if (-not $Until -and $cfg.Contains("until")) { $Until = $cfg.until }
- if ($AfterJiffies -eq 0 -and $cfg.Contains("afterJiffies")) { $AfterJiffies = [int]$cfg.afterJiffies }
- if (-not $TickAddress -and $cfg.Contains("tickAddress")) { $TickAddress = $cfg.tickAddress }
- if (-not $Keys -and $cfg.Contains("keys")) { $Keys = $cfg.keys }
- if ($TimeoutSeconds -eq 0) { $TimeoutSeconds = if ($cfg.Contains("timeoutSeconds")) { [int]$cfg.timeoutSeconds } else { 60 } }
- if ($MaxCycles -eq 0) { $MaxCycles = if ($cfg.Contains("maxCycles")) { [long]$cfg.maxCycles } else { 150000000 } }
-
- $out = Join-Path (Join-Path $t.OutDir "test") $t.Name
- if (Test-Path -LiteralPath $out) { Remove-Item -LiteralPath $out -Recurse -Force }
- New-Item -ItemType Directory -Force -Path $out | Out-Null
- $o = $out -replace '\\', '/'
-
- $mode = "d7ff"; $trigger = "watch store d7ff"
- if ($Until) {
- $mode = "until"
- $addr = if ($Until -match '^\$?[0-9a-fA-F]{1,4}$') { $Until.TrimStart('$') } else { "." + $Until.TrimStart('.') }
- $trigger = "break exec $addr"
- } elseif ($AfterJiffies -gt 0) {
- $mode = "jiffies"
- $tick = if ($TickAddress) { $TickAddress.TrimStart('$') } elseif ($t.Machine -eq "c128") { "fa65" } else { "ea31" }
- # The VICE monitor reads numbers as hex: pass the count in hex.
- $trigger = "break exec $tick`nignore 1 {0:x}" -f $AfterJiffies
- }
-
- $onHit = @(
- "bank io", "save `"$o/io.bin`" 0 d000 dfff",
- "bank ram", "save `"$o/ram.bin`" 0 0000 ffff",
- "bank cpu", "r",
- "save `"$o/done.bin`" 0 0002 0002",
- "quit" # from a playback file, quit exits cleanly (flushes the log, writes the screenshot)
- ) -join "`n"
- Set-Content -Encoding ascii -LiteralPath (Join-Path $out "onhit.mon") -Value $onHit
- $setup = @()
- if ($t.Labels) { $setup += Get-Content -LiteralPath $t.Labels }
- $setup += $trigger
- $setup += "command 1 `"pb \`"$o/onhit.mon\`"`""
- if ($t.Machine -eq "c64") {
- # BASIC's ERROR routine: X holds the error number. Capture and fail fast.
- $setup += "break exec a437"
- $setup += "command 2 `"pb \`"$o/onhit.mon\`"`""
- }
- $setup += "x"
- Set-Content -Encoding ascii -LiteralPath (Join-Path $out "setup.mon") -Value $setup
-
- $log = Join-Path $out "monitor.log"
- $viceLog = Join-Path $out "vice.log"
- $stdout = Join-Path $out "vice.stdout.log"
- $stderr = Join-Path $out "vice.stderr.log"
- $shot = Join-Path $out "screenshot.png"
- # -refreshonbreak: warp mode skips rendering frames, so without it the exit
- # screenshot can be several frames older than the RAM dump.
- $argv = @("-default", "-sounddev", "dummy", "-minimized", "-warp", "-refreshonbreak",
- "-limitcycles", "$MaxCycles",
- "-logfile", ('"' + $viceLog + '"'),
- "-moncommands", ('"' + (Join-Path $out "setup.mon") + '"'),
- "-monlog", "-monlogname", ('"' + $log + '"'),
- "-exitscreenshot", ('"' + $shot + '"'))
- if ($Ntsc) { $argv += "-ntsc" }
- if ($Keys) { $argv += @("-keybuf", ('"' + $Keys + '"')) }
- if (-not $Disk -and $cfg.Contains("disk")) { $Disk = Join-Path (Split-Path $t.OutDir -Parent) $cfg.disk }
- $argv += Get-C64DiskArgs $Disk
- $argv += $ViceArgs
- $argv += Get-C64AutostartArgs $t
-
- $emu = Get-C64Tool (Get-C64Emulator $t.Machine)
- Write-Host ("> {0} {1}" -f (Split-Path $emu -Leaf), ($argv -join ' ')) -ForegroundColor DarkGray
- $sw = [Diagnostics.Stopwatch]::StartNew()
- $done = Join-Path $out "done.bin"
- $proc = $null
- $launchError = $null
- try {
- $proc = Start-Process -FilePath $emu -ArgumentList $argv -PassThru -WindowStyle Hidden `
- -RedirectStandardOutput $stdout -RedirectStandardError $stderr -ErrorAction Stop
- } catch {
- $launchError = $_.Exception.Message
- }
- $timedOut = $false
- if ($proc) {
- while (-not $proc.HasExited -and -not (Test-Path -LiteralPath $done) -and $sw.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
- Start-Sleep -Milliseconds 100
- }
- $timedOut = -not $proc.HasExited -and -not (Test-Path -LiteralPath $done)
- # Let monitor playback finish its quit command and flush the logs and screenshot.
- if (-not $timedOut) { [void]$proc.WaitForExit(10000) }
- if (-not $proc.HasExited) {
- [void]$proc.CloseMainWindow()
- if (-not $proc.WaitForExit(10000)) { $proc.Kill(); $proc.WaitForExit() }
- }
- }
- $captured = Test-Path -LiteralPath $done
- $seconds = [math]::Round($sw.Elapsed.TotalSeconds, 1)
-
- $result = [ordered]@{ program = $t.Program; mode = $mode; passed = $false; reason = ""; code = $null
- seconds = $seconds; screen = $null; missing = @(); pc = $null
- emulatorExitCode = $(if ($proc) { $proc.ExitCode }) }
- $reasons = @()
- if ($launchError) {
- $reasons += "could not start VICE: $launchError"
- } elseif ($timedOut) {
- $reasons += "trigger never fired: wall-clock timeout ($TimeoutSeconds s)"
- } elseif (-not $captured) {
- $reasons += "trigger never fired: VICE exited with code $($result.emulatorExitCode); see vice.log and vice.stdout.log / vice.stderr.log"
- } else {
- $screen = Read-C64Screen -DumpDir $out
- Set-Content -LiteralPath (Join-Path $out "screen.txt") -Value $screen.Text -Encoding utf8
- $result.screen = $screen.Text
- $logText = if (Test-Path -LiteralPath $log) { Get-Content -Raw -LiteralPath $log } else { "" }
- if ($logText -match '(?m)^\.;([0-9a-f]{4}) ([0-9a-f]{2}) ([0-9a-f]{2})') {
- $result.pc = '$' + $Matches[1].ToUpperInvariant()
- if ($t.Machine -eq "c64" -and $Matches[1] -eq "a437") {
- $num = [Convert]::ToInt32($Matches[3], 16)
- $result.code = $num
- $ram = [IO.File]::ReadAllBytes((Join-Path $out "ram.bin"))
- $line = $ram[2 + 0x39] + 256 * $ram[2 + 0x3A] # CURLIN; $FFxx = direct mode
- $where = if ($ram[2 + 0x3A] -eq 0xFF) { "in direct mode" } else { "in line $line" }
- $reasons += "BASIC error $num ($(Get-C64BasicErrorName $num)) $where"
- $mode = "basic-error"; $result.mode = $mode
- }
- }
- if ($mode -eq "d7ff") {
- $io = [IO.File]::ReadAllBytes((Join-Path $out "io.bin"))
- $result.code = [int]$io[2 + 0x7FF]
- if ($result.code -ne 0) { $reasons += "program reported failure code $($result.code) via `$D7FF" }
- }
- foreach ($e in $Expect) {
- if ($screen.Text.IndexOf($e, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $result.missing += $e }
- }
- if ($result.missing) { $reasons += "screen is missing: " + (($result.missing | ForEach-Object { "'$_'" }) -join ", ") }
- }
- $result.passed = ($reasons.Count -eq 0)
- $result.reason = if ($result.passed) { "ok" } else { $reasons -join "; " }
- $result | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $out "result.json") -Encoding utf8
-
- if ($result.screen) {
- Write-Host ("+" + ("-" * 40) + "+")
- $result.screen -split "`n" | ForEach-Object { Write-Host ("|" + $_.PadRight(40) + "|") }
- Write-Host ("+" + ("-" * 40) + "+")
- }
- $rel = [IO.Path]::GetRelativePath((Get-Location).Path, $out)
- if ($result.passed) {
- Write-Host "PASS $($t.Name) [$mode, ${seconds}s] artifacts: $rel" -ForegroundColor Green
- } else {
- Write-Host "FAIL $($t.Name) [$mode, ${seconds}s] $($result.reason) artifacts: $rel" -ForegroundColor Red
- }
- return [pscustomobject]$result
- }
-
- # ---------------------------------------------------------------------------
- # Remote monitor client
- # ---------------------------------------------------------------------------
-
- function Send-C64Monitor {
- <#
- Sends commands to a running VICE remote monitor (start one with `c64 run -Monitor`).
- Each command's output is returned. Emulation pauses while the monitor is active;
- unless -Stay is given, 'x' is sent at the end so the program keeps running.
- #>
- param([Parameter(Mandatory)][string[]]$Command, [int]$Port = 6510, [switch]$Stay, [int]$TimeoutMs = 5000)
- $client = [Net.Sockets.TcpClient]::new()
- try {
- $client.Connect("127.0.0.1", $Port)
- } catch {
- throw "no VICE remote monitor on port $Port. Start the program with 'c64 run <path> -Monitor'."
- }
- $stream = $client.GetStream()
- $stream.ReadTimeout = 300
- $buffer = [byte[]]::new(65536)
- $readUntilPrompt = {
- $sb = [Text.StringBuilder]::new()
- $deadline = [DateTime]::UtcNow.AddMilliseconds($TimeoutMs)
- while ([DateTime]::UtcNow -lt $deadline) {
- try {
- $n = $stream.Read($buffer, 0, $buffer.Length)
- if ($n -le 0) { break }
- [void]$sb.Append([Text.Encoding]::ASCII.GetString($buffer, 0, $n))
- if ($sb.ToString() -match '\(C:\$[0-9a-f]{4}\) $') { break }
- } catch [IO.IOException] { }
- }
- return $sb.ToString()
- }
- $send = { param($text) $bytes = [Text.Encoding]::ASCII.GetBytes("$text`n"); $stream.Write($bytes, 0, $bytes.Length) }
- try {
- & $send ""
- [void](& $readUntilPrompt)
- $results = foreach ($cmd in $Command) {
- & $send $cmd
- $text = & $readUntilPrompt
- ($text -replace '(?m)^\(C:\$[0-9a-f]{4}\) ?$', '').TrimEnd()
- }
- if (-not $Stay) { & $send "x" }
- return $results
- } finally {
- $client.Close()
- }
- }
-
- # ---------------------------------------------------------------------------
- # Project scaffolding and environment check
- # ---------------------------------------------------------------------------
-
- function New-C64Project {
- param([Parameter(Mandatory)][string]$Name, [ValidateSet("c", "asm", "basic")][string]$Template = "c",
- [string]$Destination)
- if ($Name -notmatch '^[a-z0-9][a-z0-9-]*$') { throw "use a lower-case name with letters, digits, and dashes" }
- $src = Join-Path $script:RepoRoot "templates\$Template"
- if (-not $Destination) { $Destination = Join-Path $script:RepoRoot "projects\$Name" }
- if (Test-Path -LiteralPath $Destination) { throw "$Destination already exists" }
- Copy-Item -LiteralPath $src -Destination $Destination -Recurse
- Get-ChildItem -LiteralPath $Destination -Recurse -File | ForEach-Object {
- $text = Get-Content -Raw -LiteralPath $_.FullName
- $new = $text.Replace("__NAME__", $Name)
- if ($new -ne $text) { [IO.File]::WriteAllText($_.FullName, $new) }
- }
- $buildDir = Join-Path $Destination "build"
- if (Test-Path -LiteralPath $buildDir) { Remove-Item -LiteralPath $buildDir -Recurse -Force }
- Write-Host "created $([IO.Path]::GetRelativePath((Get-Location).Path, $Destination)) from templates\$Template" -ForegroundColor Green
- return $Destination
- }
-
- function Test-C64Environment {
- $rows = foreach ($t in @(
- @{ n = "cl65"; why = "cc65 C compiler driver (required)" },
- @{ n = "ca65"; why = "cc65 assembler (required)" },
- @{ n = "ld65"; why = "cc65 linker (required)" },
- @{ n = "x64sc"; why = "VICE C64 emulator (required)" },
- @{ n = "x128"; why = "VICE C128 emulator (C128 projects)" },
- @{ n = "c1541"; why = "VICE disk image tool (disk images)" },
- @{ n = "petcat"; why = "VICE BASIC tokenizer (BASIC projects)" },
- @{ n = "acme"; why = "ACME assembler (optional)" },
- @{ n = "64tass"; why = "64tass assembler (optional)" },
- @{ n = "exomizer"; why = "Exomizer cruncher (optional)" })) {
- $p = Find-C64Tool $t.n
- [pscustomobject]@{ Tool = $t.n; Status = $(if ($p) { "ok" } else { "missing" }); Purpose = $t.why; Path = $p }
- }
- $rows += [pscustomobject]@{ Tool = "pwsh"; Status = "ok"; Purpose = "PowerShell $($PSVersionTable.PSVersion)"; Path = (Get-Process -Id $PID).Path }
- return $rows
- }
-
- Export-ModuleMember -Function Find-C64Tool, Get-C64Tool, Get-C64Project, Invoke-C64Build, Start-C64,
- Invoke-C64Test, Read-C64Screen, Convert-C64ScreenCode, Send-C64Monitor, New-C64Project,
- Test-C64Environment, Get-C64PrgInfo, Convert-C64BasicSource
|