diff --git a/c64.cmd b/c64.cmd new file mode 100644 index 0000000..62fab0a --- /dev/null +++ b/c64.cmd @@ -0,0 +1,5 @@ +@echo off +rem Repository entry point: c64 doctor | new | build | run | test | mon | screen +rem See tools\c64.ps1 for details. Requires PowerShell 7 (pwsh). +pwsh -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\c64.ps1" %* +exit /b %ERRORLEVEL% diff --git a/lib/c64test.h b/lib/c64test.h new file mode 100644 index 0000000..cc3a4c9 --- /dev/null +++ b/lib/c64test.h @@ -0,0 +1,29 @@ +/* + * c64test.h - report a test result to the repository's headless test runner. + * + * `c64 test` watches for the first store to $D7FF and treats the value as the + * result: 0 = pass, anything else = failure code. VICE's debug cartridge uses the + * same register, so `x64sc -debugcart` also exits with this code. + * + * On real hardware $D7FF is an image of an unused SID register ($D41F); the + * store does nothing, so these calls can stay in shipped code. + * + * The runner captures the screen at that moment, so print what you want + * checked before reporting. + */ +#ifndef C64TEST_H +#define C64TEST_H + +#define C64TEST_RESULT (*(volatile unsigned char *)0xD7FF) + +/* Report success. */ +#define c64test_pass() (C64TEST_RESULT = 0) + +/* Report failure with a code 1-255 (use it to say which check failed). */ +#define c64test_fail(code) (C64TEST_RESULT = (unsigned char)(code)) + +/* Check a condition; on failure report `code` and stop the test. */ +#define c64test_check(cond, code) \ + do { if (!(cond)) { c64test_fail(code); for (;;) {} } } while (0) + +#endif diff --git a/lib/c64test.inc b/lib/c64test.inc new file mode 100644 index 0000000..a6700b9 --- /dev/null +++ b/lib/c64test.inc @@ -0,0 +1,22 @@ +; c64test.inc - report a test result to the repository's headless test runner (ca65). +; +; `c64 test` watches for the first store to $D7FF and treats the value as the +; result: 0 = pass, anything else = failure code. VICE's debug cartridge uses the +; same register, so `x64sc -debugcart` also exits with this code. On real hardware +; $D7FF is an image of an unused SID register; the store is harmless. +; +; The runner captures the screen at that moment, so print what you want checked first. + +C64TEST_RESULT = $D7FF + +; Report success. Clobbers A. +.macro TEST_PASS + lda #0 + sta C64TEST_RESULT +.endmacro + +; Report failure code (1-255). Clobbers A. +.macro TEST_FAIL code + lda #code + sta C64TEST_RESULT +.endmacro diff --git a/projects/README.md b/projects/README.md new file mode 100644 index 0000000..e3e2784 --- /dev/null +++ b/projects/README.md @@ -0,0 +1,9 @@ +# projects/ + +New programs go here. Create one with: + +``` +c64 new -Template c|asm|basic +``` + +Each project is self-contained: `c64project.json`, `src/`, and a git-ignored `build/`. diff --git a/templates/asm/c64project.json b/templates/asm/c64project.json new file mode 100644 index 0000000..80658df --- /dev/null +++ b/templates/asm/c64project.json @@ -0,0 +1,11 @@ +{ + "name": "__NAME__", + "machine": "c64", + "language": "asm", + "sources": ["src/*.s"], + "disk": true, + "test": { + "expect": ["READY TO GO"], + "timeoutSeconds": 60 + } +} diff --git a/templates/asm/src/main.s b/templates/asm/src/main.s new file mode 100644 index 0000000..8449299 --- /dev/null +++ b/templates/asm/src/main.s @@ -0,0 +1,68 @@ +; __NAME__ - ca65 assembly program for the Commodore 64. +; +; Built with cc65's c64-asm.cfg plus its BASIC stub (10 SYS 2061), so the first +; byte of CODE runs at $080D. Add "config": "src/my.cfg" to c64project.json if +; you need a custom memory layout. +; +; c64 build projects/__NAME__ c64 run projects/__NAME__ c64 test projects/__NAME__ + + .include "c64.inc" ; cc65: VIC, SID, CIA register names + .include "cbm_kernal.inc" ; cc65: CHROUT, GETIN, PLOT, ... + .include "c64test.inc" ; repo lib/: TEST_PASS / TEST_FAIL + +ptr = $FB ; free zero page ($FB-$FE) + +COLOR_BLACK = 0 ; c64.inc has no color names +COLOR_WHITE = 1 +COLOR_BLUE = 6 + + .segment "CODE" +main: + lda #COLOR_BLUE + sta VIC_BORDERCOLOR + lda #COLOR_BLACK + sta VIC_BG_COLOR0 + lda #banner + jsr print + + jsr self_test + + TEST_PASS ; screen is ready: let `c64 test` capture it + +wait: jsr GETIN ; wait for a key, then return to BASIC + beq wait + rts + +; Print the zero-terminated PETSCII string at A (low) / Y (high). +.proc print + sta ptr + sty ptr+1 + ldy #0 +loop: lda (ptr),y + beq done + jsr CHROUT + iny + bne loop +done: rts +.endproc + +; Checks that stop the test with a failure code. +.proc self_test + lda #2 + clc + adc #3 + cmp #5 + beq ok + TEST_FAIL 1 +hang: jmp hang +ok: rts +.endproc + + .segment "RODATA" +; ca65 converts string literals to PETSCII: lower-case ASCII becomes the letters the +; C64 shows in its default upper-case mode. Upper-case ASCII becomes shifted PETSCII, +; which displays as graphics characters. Write text in lower case. +banner: .byte $93, $05 ; clear screen, white text + .byte "__NAME__", $0D, $0D + .byte "ready to go", $0D, 0 diff --git a/templates/basic/c64project.json b/templates/basic/c64project.json new file mode 100644 index 0000000..f219a39 --- /dev/null +++ b/templates/basic/c64project.json @@ -0,0 +1,11 @@ +{ + "name": "__NAME__", + "machine": "c64", + "language": "basic", + "sources": ["src/main.bas"], + "disk": true, + "test": { + "expect": ["READY TO GO"], + "timeoutSeconds": 60 + } +} diff --git a/templates/basic/src/main.bas b/templates/basic/src/main.bas new file mode 100644 index 0000000..b50f0a3 --- /dev/null +++ b/templates/basic/src/main.bas @@ -0,0 +1,10 @@ +10 REM __NAME__ - BASIC 2.0 PROGRAM +20 REM BUILT WITH PETCAT. WRITE IT IN UPPER CASE AS THE C64 SHOWS IT; +30 REM CONTROL CODES USE PETCAT NAMES SUCH AS {CLR} AND {WHT}. +40 PRINT "{CLR}{WHT}";:POKE 53280,6:POKE 53281,0 +50 PRINT "__NAME__":PRINT +60 S=2+3:IF S<>5 THEN POKE 55295,1:END +70 PRINT "READY TO GO" +80 REM POKE 55295 ($D7FF) TELLS C64 TEST THE SCREEN IS READY; 0 = PASS +90 POKE 55295,0 +100 END diff --git a/templates/c/c64project.json b/templates/c/c64project.json new file mode 100644 index 0000000..4de9086 --- /dev/null +++ b/templates/c/c64project.json @@ -0,0 +1,12 @@ +{ + "name": "__NAME__", + "machine": "c64", + "language": "c", + "sources": ["src/*.c", "src/*.s"], + "flags": ["-Oirs"], + "disk": true, + "test": { + "expect": ["READY TO GO"], + "timeoutSeconds": 60 + } +} diff --git a/templates/c/src/main.c b/templates/c/src/main.c new file mode 100644 index 0000000..c7af238 --- /dev/null +++ b/templates/c/src/main.c @@ -0,0 +1,47 @@ +/* + * __NAME__ - cc65 C program for the Commodore 64. + * + * c64 build projects/__NAME__ -> build/__NAME__.prg, .d64, .lbl, .map + * c64 run projects/__NAME__ -> autostart in VICE + * c64 test projects/__NAME__ -> headless self-test, prints the screen + */ +#include /* includes c64.h or c128.h for the target */ +#include +#include +#include +#include "c64test.h" + +/* Pure logic lives in functions that can be checked on the machine. */ +static unsigned int add_scores(unsigned int a, unsigned int b) +{ + return a + b; +} + +static void self_test(void) +{ + static const char name[] = "C64"; + + c64test_check(add_scores(2, 3) == 5, 1); + c64test_check(add_scores(40000u, 25536u) == 0, 2); /* 16-bit wraparound */ + c64test_check(strlen(name) == 3, 3); +} + +int main(void) +{ + bordercolor(COLOR_BLUE); + bgcolor(COLOR_BLACK); + textcolor(COLOR_WHITE); + clrscr(); + + self_test(); + + cputsxy(0, 0, "__NAME__"); + cputsxy(0, 2, "READY TO GO"); + + /* Tell `c64 test` the program reached its steady state. Harmless on hardware. */ + c64test_pass(); + + cputsxy(0, 4, "PRESS ANY KEY"); + cgetc(); + return 0; +} diff --git a/tools/C64Tools.psm1 b/tools/C64Tools.psm1 new file mode 100644 index 0000000..be33166 --- /dev/null +++ b/tools/C64Tools.psm1 @@ -0,0 +1,604 @@ +# 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 +} + +# --------------------------------------------------------------------------- +# 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 = [IO.Path]::GetFullPath((Join-Path (Get-Location) $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 { @{} }) + 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() } + $lines = $Text -split "`r?`n" | Where-Object { $_.Trim() -ne "" } + return ($lines -join "`n") + "`n" +} + +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" } { + $argv = @("-t", $p.Machine) + if ($p.Config) { + $argv += @("-C", $p.Config) + } 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 = [IO.Path]::GetFullPath((Join-Path (Get-Location) $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-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[]]$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 += $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 break when the PC reaches it + -AfterJiffies 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 /test/: 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[]]$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 $t.OutDir "test" + 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" } + $trigger = "break exec $tick`nignore 1 $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" + $shot = Join-Path $out "screenshot.png" + $argv = @("-default", "-sounddev", "dummy", "-minimized", "-warp", + "-limitcycles", "$MaxCycles", + "-moncommands", ('"' + (Join-Path $out "setup.mon") + '"'), + "-monlog", "-monlogname", ('"' + $log + '"'), + "-exitscreenshot", ('"' + $shot + '"')) + if ($Ntsc) { $argv += "-ntsc" } + if ($Keys) { $argv += @("-keybuf", ('"' + $Keys + '"')) } + $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() + $proc = Start-Process -FilePath $emu -ArgumentList $argv -PassThru + $done = Join-Path $out "done.bin" + while (-not $proc.HasExited -and -not (Test-Path -LiteralPath $done) -and $sw.Elapsed.TotalSeconds -lt $TimeoutSeconds) { + Start-Sleep -Milliseconds 100 + } + $captured = Test-Path -LiteralPath $done + if (-not $proc.HasExited) { + # A clean close flushes the monitor log and writes the exit screenshot. + [void]$proc.CloseMainWindow() + if (-not $proc.WaitForExit(10000)) { $proc.Kill(); $proc.WaitForExit() } + } + $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 } + $reasons = @() + if (-not $captured) { + $why = if ($sw.Elapsed.TotalSeconds -ge $TimeoutSeconds) { "wall-clock timeout ($TimeoutSeconds s)" } else { "emulator stopped after $MaxCycles cycles" } + $reasons += "trigger never fired: $why" + } 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 + $reasons += "BASIC error $num ($(Get-C64BasicErrorName $num))" + $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 -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 diff --git a/tools/c64.ps1 b/tools/c64.ps1 new file mode 100644 index 0000000..96f4209 --- /dev/null +++ b/tools/c64.ps1 @@ -0,0 +1,108 @@ +<# +.SYNOPSIS + One command for building, running, testing, and inspecting C64/C128 programs. + +.DESCRIPTION + c64 doctor check that cc65 and VICE are installed + c64 new [-Template c|asm|basic] + create projects/ from templates/ + c64 build build to /build/.prg (+ .lbl labels, .map) + c64 run [-Monitor] [-Warp] [-Keys "text\n"] + build if needed, then autostart in VICE + c64 test [-Expect TEXT ...] [-Until label] [-AfterJiffies n] [-Keys ...] + headless run; prints the screen and PASS/FAIL; exit code 0/1 + c64 mon "" ["" ...] [-Stay] + send commands to the VICE remote monitor started by run -Monitor + c64 screen re-decode screen text from a test dump + + is a directory with c64project.json. is a single .c, .s, .asm, or .bas. + Exit codes: 0 success/pass, 1 test failure, 2 usage or tool error. +#> +param( + [Parameter(Position = 0)][string]$Verb = "help", + [Parameter(Position = 1, ValueFromRemainingArguments = $true)][object[]]$Rest = @() +) + +$ErrorActionPreference = "Stop" +Import-Module (Join-Path $PSScriptRoot "C64Tools.psm1") -Force + +function Split-C64Args([object[]]$Items) { + # Turns "-Name value" / "-Switch" pairs into a hashtable for splatting; bare words are positional. + $named = @{}; $positional = @() + $i = 0 + while ($i -lt $Items.Count) { + $item = "$($Items[$i])" + if ($item -match '^-([A-Za-z][A-Za-z0-9]*)$') { + $key = $Matches[1] + $next = if ($i + 1 -lt $Items.Count) { "$($Items[$i + 1])" } else { $null } + if ($null -ne $next -and $next -notmatch '^-[A-Za-z]') { + if ($named.ContainsKey($key)) { $named[$key] = @($named[$key]) + $next } else { $named[$key] = $next } + $i += 2 + } else { + $named[$key] = $true; $i += 1 + } + } else { + $positional += $item; $i += 1 + } + } + return @{ Named = $named; Positional = $positional } +} + +function Use-Array($named, [string[]]$keys) { + foreach ($k in $keys) { if ($named.ContainsKey($k)) { $named[$k] = [string[]]@($named[$k]) } } +} + +try { + $parsed = Split-C64Args $Rest + $n = $parsed.Named + $pos = $parsed.Positional + switch ($Verb.ToLowerInvariant()) { + "doctor" { + $rows = Test-C64Environment + $rows | Format-Table Tool, Status, Purpose, Path -AutoSize | Out-String -Width 200 | Write-Host + $missing = @($rows | Where-Object { $_.Status -eq "missing" -and $_.Purpose -match "required" }) + if ($missing) { Write-Host "missing required tools: $($missing.Tool -join ', ')" -ForegroundColor Red; exit 2 } + Write-Host "toolchain ready" -ForegroundColor Green + } + "new" { + if (-not $pos) { throw "usage: c64 new [-Template c|asm|basic] [-Destination dir]" } + $n.Name = $pos[0] + [void](New-C64Project @n) + } + "build" { + if (-not $pos) { throw "usage: c64 build " } + foreach ($p in $pos) { [void](Invoke-C64Build -Path $p) } + } + "run" { + if (-not $pos) { throw "usage: c64 run [-Monitor] [-Warp] [-Keys text]" } + Use-Array $n @("ViceArgs") + [void](Start-C64 -Path $pos[0] @n) + } + "test" { + if (-not $pos) { throw "usage: c64 test [-Expect text] [-Until label] [-AfterJiffies n]" } + Use-Array $n @("Expect", "ViceArgs") + $failed = 0 + foreach ($p in $pos) { + $r = Invoke-C64Test -Path $p @n + if (-not $r.passed) { $failed++ } + } + if ($pos.Count -gt 1) { Write-Host "$($pos.Count - $failed)/$($pos.Count) passed" } + exit $(if ($failed) { 1 } else { 0 }) + } + "mon" { + if (-not $pos) { throw "usage: c64 mon `"`" [...] [-Port 6510] [-Stay]" } + Send-C64Monitor -Command $pos @n | ForEach-Object { Write-Output $_ } + } + "screen" { + if (-not $pos) { throw "usage: c64 screen " } + (Read-C64Screen -DumpDir $pos[0]).Text | Write-Output + } + { $_ -in "help", "-h", "--help", "/?" } { + Get-Help $PSCommandPath -Detailed | Out-String | Write-Host + } + default { throw "unknown command '$Verb'. Try: c64 help" } + } +} catch { + Write-Host "error: $($_.Exception.Message)" -ForegroundColor Red + exit 2 +}