// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include "BasicProgram.h" #include "MachineDefs.h" #include "VideoHost.h" #include "CassetteDeck.h" #include "AudioBuffer.h" #include "PrinterCapture.h" #include "../devices/CartridgeDevice.h" #include "../devices/DriveWireTransport.h" #include "tcc1014mmu.h" #include #include #include #include #include #include namespace VCC::Mac { enum class Processor { MC6809, HD6309 }; enum class VideoOutput { RGB = 0, Composite = 1, CompositeAlternate = 2 }; struct MachineConfiguration { Processor processor = Processor::MC6809; unsigned ram = 1; // retained MMU choices: 128 KiB, 512 KiB, 2 MiB, 8 MiB unsigned overclock = 1; // 1...16, applies only when the guest selects double speed unsigned frameInterval = 1; // publish one in 1...6 frames; devices always run void validate() const; }; enum class RunState { Empty, Paused, Running }; struct Frame { static constexpr unsigned width = 640, height = 480; std::uint64_t generation = 0, number = 0; VideoRect activeArea{0, 0, width, height}; // Immutable after publication; packed 0x00RRGGBB, opaque when displayed. std::vector pixels; }; struct JoystickInputSnapshot { unsigned x = 8191, y = 8191, buttons = 0, mode = 0; }; struct Snapshot { RunState state = RunState::Empty; VideoOutput videoOutput = VideoOutput::RGB; MachineConfiguration configuration; CPUState cpu; std::uint64_t generation = 0, frames = 0, cycles = 0; std::array joysticks{}; // right, left; side-effect-free host input bool keyboardHeld = false; // never exposes the actual typed keys // Explicit code replacement/edit epoch, separate from reset generation. std::uint64_t debuggerProgramRevision = 0, debuggerMappingFingerprint = 0; bool debuggerDevelopmentAttached = false, debuggerAssemblyAttached = false, debuggerSourceStepping = false; bool debuggerBankedDevelopment = false; bool basicDebugAttached = false; int basicStoppedLine = -1, basicSourceOffset = -1; unsigned basicSourceLength = 0; bool basicStepping = false, basicCanStepOut = false; int basicErrorLine = -1; std::string basicErrorCode; std::string basicDebugStatus; std::shared_ptr frame; }; struct DebugCodeGuard { std::uint16_t address = 0; std::vector bytes; }; // Both page numbers identify 8 KiB RAM pages. Physical pages are the actual // installed RAM backing, after mirroring; a ROM overlay never matches. struct DebugBankedPage { std::uint8_t logicalPage = 0; std::uint32_t physicalPage = 0; }; struct DebugBankedModule { std::string identifier; std::vector pages; std::vector guards; // Absent preserves logical-point behavior. An explicit set qualifies only // these stops to this module; an empty set retains source/step evidence only. std::optional> breakpointAddresses = std::nullopt; }; enum class SourceStepMode { Into, Over, Out }; struct DebugSourceInstruction { std::uint16_t address = 0; std::uint32_t location = 0; // caller's stable file + source-line identity std::vector bytes; std::string moduleIdentifier = {}; // required only for bank-qualified development }; struct DebugSnapshot { CPUState cpu; RunState state = RunState::Empty; std::uint64_t generation = 0, cycles = 0; std::vector breakpoints, disabledBreakpoints; std::uint16_t memoryAddress = 0; std::vector memory; // Zero means an I/O address whose value cannot be inspected safely. // Never interpret the corresponding placeholder byte as a device value. std::vector memoryAvailable; MMUState mmu; std::uint32_t physicalAddress = 0; std::vector physicalMemory; std::string stopReason; }; struct DebugMemoryRange { CPUState cpu; std::uint32_t address = 0, capacity = 0; std::uint64_t generation = 0, cycles = 0; std::vector bytes, available; }; enum class DebugGraphicsMode { SG4, PMODE0, PMODE1, PMODE2, PMODE3, PMODE4, HSCREEN1, HSCREEN2, HSCREEN3, HSCREEN4, CurrentGime }; struct DebugGraphicsPixel { std::uint32_t byteIndex; std::uint8_t mask; }; struct DebugGraphicsPreview { std::array palette{}; // Live six-bit GIME palette registers. std::string modeName; std::uint32_t address = 0, width = 0, height = 0; std::uint32_t bytesPerRow = 0, pixelsPerByte = 0, linesPerRow = 0, bytesPerCell = 1; std::uint32_t videoOrigin = 0, rowStrideBytes = 0, horizontalOffsetBytes = 0, verticalScrollLines = 0; std::string canvasIdentifier; std::uint32_t canvasAddress = 0, canvasBytes = 0, viewportOffset = 0; bool physical = false, text = false, semigraphics = false; std::uint64_t generation = 0, cycles = 0, mappingFingerprint = 0; // Pixel colors use the same 0x00RRGGBB packing as Frame. A row offset // indexes the compact byte arrays, even on scrolled or repeated rows. std::vector pixels, rowByteOffsets, byteAddresses; std::vector bytes, available; DebugGraphicsPixel pixelInfo(unsigned x, unsigned y) const; }; // These declarations are supplied by the owning project's verified build // manifest, never by a public arbitrary-memory read request. struct DebugGraphicsBuffer { std::string identifier; std::uint32_t physicalAddress = 0; DebugGraphicsMode mode = DebugGraphicsMode::HSCREEN2; bool alternatePalette = false; std::uint32_t canvasBytes = 0; // Explicit power-of-two span for CurrentGime only. }; struct DebugGraphicsCapture { DebugGraphicsPreview displayed; std::optional declared; std::string declaredIdentifier; }; struct DebugTraceRecord { TraceEvent event = TraceEvent::Instruction; std::uint64_t clock = 0, frame = 0; CPUState before, after; std::array bytes{}; unsigned availableBytes = 0, line = 0; long cycles = 0; std::string detail; }; struct DebugTraceSnapshot { bool armed = false, capturing = false, use6309 = false; std::uint64_t identifier = 0; std::size_t total = 0, limit = 0, offset = 0; std::string status = "No trace"; std::vector records; }; // Pure formatting over an immutable export snapshot; safe off the machine queue. std::string FormatDebugTraceCSV(const DebugTraceSnapshot& trace); // All operations, including destruction, belong on the owner's serial queue. // Only one loaded session is permitted because the retained core has globals. // Standalone low-level core tests must not run alongside a loaded session. class MachineSession { public: MachineSession(); ~MachineSession(); MachineSession(const MachineSession&) = delete; MachineSession& operator=(const MachineSession&) = delete; void load(const std::vector& rom, Processor processor = Processor::MC6809); void loadDiagnostic(Processor processor = Processor::MC6809); void debuggerLoadBinary(const std::vector& binary, std::uint16_t breakpoint); void debuggerLoadBinary(const std::vector& binary, const std::vector& breakpoints); void launchAssembly(const std::vector& binary, const std::vector& points, const std::vector& guards, bool pauseAtEntry, bool requires6309, std::uint64_t expectedGeneration, std::uint64_t expectedRevision, std::uint64_t expectedMapping); // Interactive grants follow only a compiled program entered with a verified Disk BASIC return. void armSharedCompiledCall(); bool sharedCompiledCallActive() const; bool sharedCompiledCallReturned() const; const std::string* sharedCompiledReturnScreen() const; void pasteSharedCompiledKey(std::uint64_t chord); void pauseAssembly(const Snapshot& expected); void controlAssembly(bool step, const Snapshot& expected); void updateAssembly(const std::vector& points, const Snapshot& expected); void clearAssembly(const Snapshot& expected); // Arms source breakpoints without changing RAM/PC or running the machine. // They become active only when all supplied verified code ranges match RAM. void debuggerArmDevelopmentBreakpoints(const std::vector& breakpoints, const std::vector& guards); // Modules may overlap in logical memory. Each stop verifies only its own // module's complete code and physical mappings, never unmapped overlays. // An empty breakpoint set retains inspectable/step-capable module evidence. void debuggerArmBankedDevelopmentBreakpoints(const std::vector& breakpoints, const std::vector& modules); void debuggerClearDevelopmentBreakpoints(); void debuggerContinueFromEntry(std::uint16_t entry); void quickLoad(const std::vector& binary); // validate, load mapped memory, jump and run; no reset void configure(const MachineConfiguration& configuration); // CPU/RAM changes cold reset void resume(); // A complete host-input snapshot takes effect before the first resumed CPU // slice, including the instruction that leaves a debugger breakpoint. The // returned immutable snapshot records actual staged input before that slice; // a new breakpoint may already have released live input when this returns. Snapshot resumeWithInput(std::uint64_t keys, const std::array& joysticks); void pause(); void setJoystick(unsigned port, unsigned x, unsigned y, unsigned buttons, unsigned mode); void releaseInputs() noexcept; // neutralizes host inputs even at a paused stop void setVideoOutput(VideoOutput output); // presentation only; no CPU reset or audio flush // Host opt-in, independent of guest media and saved profiles. An empty // factory closes active connections and removes access to the Becker port. void setDriveWireFactory(Devices::DriveWireFactory factory); bool driveWireEnabled() const { return bool(driveWireFactory); } void setKeyboard(std::uint64_t keys); // complete held-key matrix, ignored unless running // Opt-in one-shot DOS 255 at the next RGBDOS prompt. Advances with guest // frames, never wall-clock sleeps; resets/real keys cancel it. void requestNitros9Boot(); bool nitros9BootPending() const; void paste(const std::vector& chords); // bounded, frame-paced keyboard input void cancelPaste(); std::size_t pasteRemaining() const; bool basicExecutingStoredSource() const; bool basicAtDirectPrompt() const; // Recognized ROM direct-mode input stack, independent of displayed text. std::string basicReadSource() const; std::vector basicInspect(const std::string& source) const; std::vector basicExportSource(const std::string& source, const std::string& filename, BasicExportFormat format) const; void basicLoadSource(const std::string& source, bool run, const std::vector& breakpoints = {}); void basicSetBreakpoints(const std::string& source, const std::vector& lines); void basicClearDebug(); void basicContinue(const std::string& source); void basicStep(const std::string& source, bool over); void basicStepOut(const std::string& source); std::string copyScreenText() const; // hardware text only; graphics are rejected void softReset(); // retain RAM; restart hardware, preserve running/paused state void reset(); // cold reset, preserves running/paused state void advance(); // one bounded frame; no-op when paused/empty void shutdown(); // idempotent; permits later loading Snapshot snapshot() const; // Owned snapshots on the same serial queue as execution. Reads wrap in the // logical 16-bit address space; no I/O read side effects are permitted. // Physical inspection reads installed RAM, bypassing ROM/MMU/I/O. It is // bounded to 256 bytes and truncates at the end; it never wraps or writes. DebugSnapshot debuggerSnapshot(std::uint16_t address = 0, unsigned count = 256, std::uint32_t physicalAddress = 0, unsigned physicalCount = 0) const; // Exact non-wrapping immutable range, bounded by the selected memory space. // Mapped I/O is explicitly unavailable; exporting it must fail, not fill zeros. DebugMemoryRange debuggerMemoryRange(std::uint32_t address, std::uint32_t count, bool physical) const; DebugGraphicsPreview debuggerGraphicsPreview(bool currentPage, bool physical, std::uint32_t address, DebugGraphicsMode mode, bool alternatePalette = false, const std::vector& canvases = {}) const; // Fresh, borderless previews from one paused state, not the history of the // last published raster frame. Reads do not advance the guest or live GPU. DebugGraphicsCapture debuggerGraphicsCapture(const std::optional& declared = std::nullopt, const std::vector& canvases = {}) const; void debuggerStep(); // paused only; retained Windows instruction-step semantics // Begins a bounded normal-execution step. advance() progresses it; pause() // cancels. Permanent breakpoints remain active, including inside callees. void debuggerStepSource(SourceStepMode mode, const std::vector& instructions, std::uint64_t expectedGeneration, std::uint64_t expectedProgramRevision, std::uint64_t expectedMappingFingerprint, std::uint16_t expectedPC, unsigned maximumInstructions = 1000000, unsigned maximumFrames = 600); void debuggerSetPC(std::uint16_t address); // paused only, same ForcePC semantics as Windows void debuggerSetBreakpoints(std::vector addresses); void debuggerConfigureBreakpoints(std::vector enabled, std::vector disabled); // Captures stop at the bound without pausing or resetting guest execution. void debuggerStartTrace(unsigned maximum, const std::vector& starts, const std::vector& stops, bool screen, bool scheduler); void debuggerStopTrace(); void debuggerClearTrace(); DebugTraceSnapshot debuggerTrace(std::size_t offset = 0, unsigned count = 256) const; DebugTraceSnapshot debuggerTraceForExport(std::size_t first, std::size_t count) const; std::string debuggerExportTrace(std::size_t first, std::size_t count) const; // Atomic preflight, 1...256 bytes, no wrapping, mapped RAM only (below FE00). void debuggerWriteMemory(std::uint16_t address, const std::vector& bytes); PrinterCapture& printer() { return *printerCapture; } const PrinterCapture& printer() const { return *printerCapture; } CassetteDeck& cassette() { return *tape; } Devices::CartridgeBus& cartridges() { return *bus; } std::vector takeAudio(); // drains samples on the owner queue private: void resumeImpl(const std::uint64_t* keys, const std::array* joysticks, Snapshot* staged = nullptr); bool basicInputState(unsigned top) const; void loadDevelopmentImage(const std::vector& binary, const std::vector& points, const std::vector* assemblyGuards); void checkAssembly(const Snapshot& expected) const; struct Impl; Devices::DriveWireFactory driveWireFactory; std::shared_ptr printerCapture; std::shared_ptr tape; std::shared_ptr bus; std::unique_ptr impl; MachineConfiguration configuration; std::uint64_t generation = 0, nextTraceIdentifier = 0, debuggerProgramRevision = 0; VideoOutput videoOutput = VideoOutput::RGB; }; }