// Runs a CP/M 2.2 program on the 8080 core with a host folder as its disk, for building CP/M software // with its own tools (LASM, MLOAD, ASM ...). Every drive letter is the folder; files are found ignoring case. // Usage: CpmRun [--dir folder] [command tail] // Set CPMRUN_TRACE=1 to list the BDOS calls on stderr. using System.Text; using Zimul80r.Core.Cpu; string folder = Directory.GetCurrentDirectory(); var rest = new List(args); if (rest.Count >= 2 && rest[0] == "--dir") { folder = rest[1]; rest.RemoveRange(0, 2); } if (rest.Count == 0) { Console.WriteLine("usage: CpmRun [--dir folder] [command tail]"); return 1; } var cpm = new Cpm(folder); string program = File.Exists(rest[0]) ? rest[0] : cpm.FindProgram(Path.GetFileName(rest[0])) ?? rest[0]; if (!File.Exists(program)) { Console.WriteLine($"{rest[0]}?"); return 1; } cpm.Load(program, string.Join(' ', rest.Skip(1))); return cpm.Run(); /// A TPA up to E400, a BDOS trapped at E406 and a BIOS jump table at F200 whose entries are trapped. sealed class Cpm : IZ80Bus { const ushort Bdos = 0xE406, Bios = 0xF200; const int BiosEntries = 17; const long CycleLimit = 20_000_000_000; static readonly bool Trace = Environment.GetEnvironmentVariable("CPMRUN_TRACE") == "1"; readonly byte[] _memory = new byte[0x10000]; readonly string _folder; readonly I8080 _cpu; ushort _dma = 0x80; string[] _search = []; int _searchIndex; byte _user; public Cpm(string folder) { _folder = folder; _cpu = new I8080(this); } public string? Find(string name) => Directory.EnumerateFiles(_folder).FirstOrDefault(f => string.Equals(Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase)); /// A program named on the command line, as the CCP finds it: NAME means NAME.COM (or here NAME.HEX). public string? FindProgram(string name) => Path.HasExtension(name) ? Find(name) : Find(name + ".COM") ?? Find(name + ".HEX"); public void Load(string program, string tail) { byte[] bytes = File.ReadAllBytes(program); if (program.EndsWith(".hex", StringComparison.OrdinalIgnoreCase)) LoadHex(Encoding.ASCII.GetString(bytes)); else bytes.CopyTo(_memory, 0x0100); _memory[0] = 0xC3; Poke16(1, Bios + 3); // warm boot _memory[5] = 0xC3; Poke16(6, Bdos); for (int i = 0; i < BiosEntries; i++) { _memory[Bios + i * 3] = 0xC3; Poke16(Bios + i * 3 + 1, Bios + i * 3); } tail = tail.ToUpperInvariant(); string spaced = tail.Length > 0 ? " " + tail : ""; _memory[0x80] = (byte)Math.Min(spaced.Length, 127); Encoding.ASCII.GetBytes(spaced[..Math.Min(spaced.Length, 127)]).CopyTo(_memory, 0x81); string[] words = tail.Split(' ', StringSplitOptions.RemoveEmptyEntries); ParseFcb(0x5C, words.ElementAtOrDefault(0) ?? ""); ParseFcb(0x6C, words.ElementAtOrDefault(1) ?? ""); _cpu.Reset(); _cpu.PC = 0x0100; _cpu.SP = Bdos - 6; Push(0x0000); } void LoadHex(string text) { foreach (string raw in text.Split('\n')) { string line = raw.Trim(); if (!line.StartsWith(':') || line.Length < 11) continue; int count = Convert.ToInt32(line[1..3], 16), address = Convert.ToInt32(line[3..7], 16); if (Convert.ToInt32(line[7..9], 16) != 0) continue; for (int i = 0; i < count; i++) _memory[(address + i) & 0xFFFF] = Convert.ToByte(line.Substring(9 + i * 2, 2), 16); } } public int Run() { while (_cpu.Cycles < CycleLimit) { ushort pc = _cpu.PC; if (pc == 0x0000) return 0; if (pc == Bdos) { CallBdos(); Return(); } else if (pc >= Bios && pc < Bios + BiosEntries * 3 && (pc - Bios) % 3 == 0) { int entry = (pc - Bios) / 3; if (entry <= 1) return 0; // cold or warm boot CallBios(entry); Return(); } else _cpu.Step(); } Console.WriteLine("\r\n[CpmRun: stopped after the cycle limit]"); return 2; } void CallBios(int entry) { switch (entry) { case 2: _cpu.A = Console.KeyAvailable ? (byte)0xFF : (byte)0; break; case 3: _cpu.A = ReadKey(); break; case 4 or 5: Console.Write((char)(_cpu.C & 0x7F)); break; // CONOUT, LIST } } void CallBdos() { int function = _cpu.C; ushort de = _cpu.DE; int result = 0; switch (function) { case 0: _cpu.PC = 0; return; case 1: result = ReadKey(); Console.Write((char)result); break; case 2 or 4 or 5: Console.Write((char)(_cpu.E & 0x7F)); break; case 3: result = 0x1A; break; case 6: if (_cpu.E == 0xFF) result = Console.KeyAvailable ? ReadKey() : 0; else Console.Write((char)(_cpu.E & 0x7F)); break; case 7 or 8: break; case 9: for (ushort a = de; _memory[a] != '$'; a++) Console.Write((char)(_memory[a] & 0x7F)); break; case 10: ReadLine(de); break; case 11: result = Console.KeyAvailable ? 0xFF : 0; break; case 12: result = 0x22; break; case 13: _dma = 0x80; break; case 14 or 37: break; case 15: result = Open(de); break; case 16: result = Exists(de) ? 0 : 0xFF; break; case 17: result = SearchFirst(de); break; case 18: result = SearchNext(); break; case 19: result = Delete(de); break; case 20: result = Read(de, SequentialRecord(de), advance: true); break; case 21: result = Write(de, SequentialRecord(de), advance: true); break; case 22: result = Make(de); break; case 23: result = Rename(de); break; case 24: result = 1; break; case 25: result = 0; break; case 26: _dma = de; break; case 32: if (_cpu.E == 0xFF) result = _user; else _user = (byte)(_cpu.E & 0x0F); break; case 33: result = Read(de, RandomRecord(de), advance: false); break; case 34 or 40: result = Write(de, RandomRecord(de), advance: false); break; case 35: SetRandomRecord(de, (int)((Length(de) + 127) / 128)); break; case 36: SetRandomRecord(de, SequentialRecord(de)); break; default: Console.Error.WriteLine($"\r\n[CpmRun: BDOS function {function} isn't supported]"); break; } if (Trace && function is not (2 or 9)) { bool file = function is >= 15 and <= 23 or >= 33 and <= 36; Console.Error.WriteLine($"[BDOS {function} DE={de:X4}{(file ? $" {FcbName(de)} record {SequentialRecord(de)}" : "")} -> {result:X2}]"); } _cpu.A = (byte)result; _cpu.L = (byte)result; _cpu.H = 0; _cpu.B = 0; } static byte ReadKey() { int c = Console.In.Read(); return c < 0 ? (byte)0x1A : c == '\n' ? (byte)'\r' : (byte)c; } void ReadLine(ushort buffer) { string line = Console.In.ReadLine() ?? ""; int max = _memory[buffer]; line = line[..Math.Min(line.Length, max)]; _memory[buffer + 1] = (byte)line.Length; Encoding.ASCII.GetBytes(line).CopyTo(_memory, buffer + 2); } // ---- files ---- string FcbName(ushort fcb) { string Part(int offset, int length) => Encoding.ASCII.GetString(_memory, fcb + offset, length).Select(c => (char)(c & 0x7F)).Aggregate("", (s, c) => s + c).TrimEnd(); string name = Part(1, 8), ext = Part(9, 3); return ext.Length > 0 ? $"{name}.{ext}" : name; } string HostPath(ushort fcb) => Find(FcbName(fcb)) ?? Path.Combine(_folder, FcbName(fcb)); bool Exists(ushort fcb) => Find(FcbName(fcb)) != null; long Length(ushort fcb) => Exists(fcb) ? new FileInfo(HostPath(fcb)).Length : 0; int Open(ushort fcb) { if (!Exists(fcb)) return 0xFF; _memory[fcb + 14] = 0; // the module byte: open sets it, as the BDOS does int extent = _memory[fcb + 12]; long records = (Length(fcb) + 127) / 128 - extent * 128L; _memory[fcb + 15] = (byte)Math.Clamp(records, 0, 128); _memory[fcb + 32] = 0; return 0; } int Make(ushort fcb) { File.WriteAllBytes(HostPath(fcb), []); _memory[fcb + 12] = _memory[fcb + 14] = _memory[fcb + 15] = _memory[fcb + 32] = 0; return 0; } int Delete(ushort fcb) { var matches = Matches(fcb).ToList(); foreach (string f in matches) File.Delete(f); return matches.Count > 0 ? 0 : 0xFF; } int Rename(ushort fcb) { if (!Exists(fcb)) return 0xFF; string to = Path.Combine(_folder, FcbName((ushort)(fcb + 16))); if (File.Exists(to)) File.Delete(to); File.Move(HostPath(fcb), to); return 0; } IEnumerable Matches(ushort fcb) { string pattern = Encoding.ASCII.GetString(_memory, fcb + 1, 11); foreach (string f in Directory.EnumerateFiles(_folder).Order()) { string padded = Padded(Path.GetFileName(f)); if (padded.Length == 11 && Enumerable.Range(0, 11).All(i => pattern[i] == '?' || char.ToUpperInvariant((char)(pattern[i] & 0x7F)) == padded[i])) yield return f; } } static string Padded(string fileName) { string name = Path.GetFileNameWithoutExtension(fileName).ToUpperInvariant(), ext = Path.GetExtension(fileName).TrimStart('.').ToUpperInvariant(); return name.Length <= 8 && ext.Length <= 3 ? name.PadRight(8) + ext.PadRight(3) : ""; } int SearchFirst(ushort fcb) { _search = Matches(fcb).ToArray(); _searchIndex = 0; return SearchNext(); } int SearchNext() { if (_searchIndex >= _search.Length) return 0xFF; string f = _search[_searchIndex++]; Array.Clear(_memory, _dma, 128); _memory[_dma] = 0; Encoding.ASCII.GetBytes(Padded(Path.GetFileName(f))).CopyTo(_memory, _dma + 1); long records = (new FileInfo(f).Length + 127) / 128; _memory[_dma + 12] = (byte)(Math.Max(0, records - 1) / 128); _memory[_dma + 15] = (byte)Math.Min(128, records - _memory[_dma + 12] * 128L); return 0; } int SequentialRecord(ushort fcb) => ((_memory[fcb + 14] & 0x3F) * 32 + (_memory[fcb + 12] & 0x1F)) * 128 + (_memory[fcb + 32] & 0x7F); int RandomRecord(ushort fcb) => _memory[fcb + 33] | _memory[fcb + 34] << 8 | _memory[fcb + 35] << 16; void SetRandomRecord(ushort fcb, int record) { _memory[fcb + 33] = (byte)record; _memory[fcb + 34] = (byte)(record >> 8); _memory[fcb + 35] = (byte)(record >> 16); } void SetSequentialRecord(ushort fcb, int record) { _memory[fcb + 32] = (byte)(record % 128); _memory[fcb + 12] = (byte)(record / 128 % 32); _memory[fcb + 14] = (byte)(record / 128 / 32); } int Read(ushort fcb, int record, bool advance) { if (!Exists(fcb)) return 0xFF; using var stream = File.OpenRead(HostPath(fcb)); if ((long)record * 128 >= stream.Length) return 1; stream.Position = (long)record * 128; var buffer = new byte[128]; Array.Fill(buffer, (byte)0x1A); stream.ReadAtLeast(buffer, 128, throwOnEndOfStream: false); buffer.CopyTo(_memory, _dma); if (advance) SetSequentialRecord(fcb, record + 1); else SetSequentialRecord(fcb, record); return 0; } int Write(ushort fcb, int record, bool advance) { using var stream = new FileStream(HostPath(fcb), FileMode.OpenOrCreate, FileAccess.Write); stream.Position = (long)record * 128; stream.Write(_memory, _dma, 128); if (advance) SetSequentialRecord(fcb, record + 1); else SetSequentialRecord(fcb, record); return 0; } void ParseFcb(ushort fcb, string word) { Array.Clear(_memory, fcb, 16); Array.Fill(_memory, (byte)' ', fcb + 1, 11); if (word.Length >= 2 && word[1] == ':') { _memory[fcb] = (byte)(word[0] - 'A' + 1); word = word[2..]; } string[] parts = word.Split('.', 2); void Put(string text, int offset, int length) { for (int i = 0; i < Math.Min(text.Length, length); i++) { if (text[i] == '*') { Array.Fill(_memory, (byte)'?', fcb + offset + i, length - i); break; } _memory[fcb + offset + i] = (byte)text[i]; } } Put(parts[0], 1, 8); if (parts.Length > 1) Put(parts[1], 9, 3); } // ---- CPU plumbing ---- void Poke16(int address, int value) { _memory[address] = (byte)value; _memory[address + 1] = (byte)(value >> 8); } void Push(ushort value) { _cpu.SP -= 2; Poke16(_cpu.SP, value); } void Return() { _cpu.PC = (ushort)(_memory[_cpu.SP] | _memory[(ushort)(_cpu.SP + 1)] << 8); _cpu.SP += 2; } public byte ReadMemory(ushort address) => _memory[address]; public void WriteMemory(ushort address, byte value) => _memory[address] = value; public byte ReadPort(ushort port) => 0xFF; public void WritePort(ushort port, byte value) { } public bool InterruptPending => false; public byte AcknowledgeInterrupt() => 0xFF; public void OnReti() { } }