diff --git a/README.md b/README.md index d2d7487..c5bee11 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,14 @@ file is where they live. moment rather than a dozen. - A debugger with breakpoints (conditions included, like `$C000 if a == $10`), read/write watchpoints, single stepping, a syntax-highlighted disassembly, the stack, and a hex view of - the address space. + the address space. A ca65/ld65 build can be attached from the Source tab with **Attach Debug Info…**: build + objects with `ca65 -g`, link with `ld65 --dbgfile game.dbg`, and the debugger follows the current + source line in a syntax-highlighted 6502 editor, shows symbols in the disassembly, and sets + breakpoints from the source gutter. Those breakpoints name bytes of PRG ROM rather than + `$8000`-style windows, so they follow the right code through bank switches. If the checkout moved + since the build, **Find Sources…** accepts either the project or a source folder and also finds + generated includes in nearby build folders. Hovering a symbol shows its linked value and source + definition; Cmd/Ctrl-click or **Go to Definition** follows it, including ca65's `@` local labels. - CPU tracing in nestest's log format, so a trace diffs cleanly against other emulators. - **Start Music...** writes what the sound chip plays to a MIDI file — one part per pulse and one for the triangle, read a frame at a time so nothing in the melody is missed, with the tempo set so diff --git a/mynes-core/src/main/java/com/github/dimiro1/mynes/debug/Debugger.java b/mynes-core/src/main/java/com/github/dimiro1/mynes/debug/Debugger.java index 6f80b75..ca97a2c 100644 --- a/mynes-core/src/main/java/com/github/dimiro1/mynes/debug/Debugger.java +++ b/mynes-core/src/main/java/com/github/dimiro1/mynes/debug/Debugger.java @@ -4,6 +4,7 @@ import com.github.dimiro1.mynes.MMU; import com.github.dimiro1.mynes.NES; import com.github.dimiro1.mynes.PPU; +import com.github.dimiro1.mynes.mappers.Mapper; import java.util.Collections; import java.util.Locale; @@ -261,7 +262,18 @@ public interface EventSink { private final boolean[] watchReadAt = new boolean[0x10000]; private final boolean[] watchWriteAt = new boolean[0x10000]; + /** + * Breakpoints on bytes of the program ROM rather than on CPU addresses. + *

+ * A CPU address is not the identity of a line of code on a banked cartridge: half a dozen + * different banks may all spend part of a frame at $8000. The offset is. Kept as the same flat + * lookup the address breakpoints use, because this is asked once per instruction while any one + * of these is down. + */ + private boolean[] breakAtPRG = new boolean[0]; + private final Set breakpoints = new TreeSet<>(); + private final Set prgBreakpoints = new TreeSet<>(); /** * The conditional breakpoints only, which is nearly always none of them. @@ -296,6 +308,7 @@ public interface EventSink { private MMU memory; private CPU cpu; private PPU ppu; + private Mapper mapper; /** * Whoever is collecting a frame's worth of what the machine did, or null when nobody is. @@ -347,6 +360,15 @@ public void attach(final NES nes) { memory = nes.getMemory(); cpu = nes.getCPU(); ppu = nes.getPPU(); + mapper = nes.getBus().getMapper(); + + // A debugger outlives a power cycle, so rebuild the fast lookup over the new cartridge + // without throwing away the user's points. A genuinely new cartridge is cleared by the + // window before it is attached; discard impossible points for direct callers too. + breakAtPRG = new boolean[nes.getCart().prgROM().length]; + prgBreakpoints.removeIf(offset -> offset >= breakAtPRG.length); + prgBreakpoints.stream() + .forEach(offset -> breakAtPRG[offset] = true); wireHooks(); } @@ -364,6 +386,7 @@ public boolean isArmed() { return stepping != Stepping.NONE || haltAsked || !breakpoints.isEmpty() + || !prgBreakpoints.isEmpty() || !watchpoints.isEmpty(); } @@ -406,6 +429,16 @@ public Stop afterInstruction(final int pc, final int wasPC) { return new Stop(Reason.BREAKPOINT, pc, null, -1, -1, -1); } + if (pc >= 0x8000 && !prgBreakpoints.isEmpty()) { + var offset = mapper.prgOffset(pc); + + if (offset >= 0 && offset < breakAtPRG.length && breakAtPRG[offset]) { + stepping = Stepping.NONE; + + return new Stop(Reason.BREAKPOINT, pc, null, -1, -1, -1); + } + } + if (stepping == Stepping.INSTRUCTION) { stepping = Stepping.NONE; @@ -580,6 +613,39 @@ public boolean toggleBreakpoint(final int pc) { return true; } + /** + * Stops before whichever CPU address is currently backed by this byte of program ROM. + *

+ * This is the breakpoint a source line wants. On a banked board it follows the code rather + * than the window the code happens to be showing through; on a mirrored NROM it deliberately + * fires through either alias, since both execute the same byte. + */ + public void addPRGBreakpoint(final int offset) { + checkPRGOffset(offset); + prgBreakpoints.add(offset); + breakAtPRG[offset] = true; + } + + public void removePRGBreakpoint(final int offset) { + prgBreakpoints.remove(offset); + + if (offset >= 0 && offset < breakAtPRG.length) { + breakAtPRG[offset] = false; + } + } + + public boolean togglePRGBreakpoint(final int offset) { + if (prgBreakpoints.contains(offset)) { + removePRGBreakpoint(offset); + + return false; + } + + addPRGBreakpoint(offset); + + return true; + } + /** * Stops the machine after an instruction writes to this address. */ @@ -713,12 +779,18 @@ public void unwatched(final Runnable work) { */ public void clear() { breakpoints.forEach(pc -> breakAt[pc] = false); + prgBreakpoints.forEach(offset -> { + if (offset < breakAtPRG.length) { + breakAtPRG[offset] = false; + } + }); watchpoints.keySet().forEach(address -> { watchReadAt[address] = false; watchWriteAt[address] = false; }); breakpoints.clear(); + prgBreakpoints.clear(); conditions.clear(); watchpoints.clear(); @@ -732,6 +804,13 @@ public Set breakpoints() { return Collections.unmodifiableSet(breakpoints); } + /** + * Breakpoints whose identity is an offset into {@link com.github.dimiro1.mynes.Cart#prgROM()}. + */ + public Set prgBreakpoints() { + return Collections.unmodifiableSet(prgBreakpoints); + } + /** * The conditions, by the address they are on. Only the conditional breakpoints are in here; an * address in {@link #breakpoints()} and not in this stops on every pass. @@ -785,6 +864,15 @@ private boolean conditionHolds(final int pc) { return condition == null || condition.holds(cpu.getState(), memory::peek); } + private void checkPRGOffset(final int offset) { + if (offset < 0 || offset >= breakAtPRG.length) { + throw new IllegalArgumentException(String.format( + "PRG offset $%X is outside this cartridge's $%X bytes", + offset, + breakAtPRG.length)); + } + } + /** * Puts the three hooks down or picks them up, according to whether anything is still watching. *

diff --git a/mynes-core/src/test/java/com/github/dimiro1/mynes/debug/DebuggerTests.java b/mynes-core/src/test/java/com/github/dimiro1/mynes/debug/DebuggerTests.java index 0bb173a..627ab27 100644 --- a/mynes-core/src/test/java/com/github/dimiro1/mynes/debug/DebuggerTests.java +++ b/mynes-core/src/test/java/com/github/dimiro1/mynes/debug/DebuggerTests.java @@ -94,6 +94,50 @@ void aBreakpointSomewhereTheProgramNeverGoesNeverFires() { assertNull(run(20)); } + @Test + void aProgramRomBreakpointStopsAtTheByteBehindTheCpuAddress() { + debugger.addPRGBreakpoint(8); + + var stop = run(10); + + assertNotNull(stop); + assertEquals(LDX, stop.pc()); + assertEquals(java.util.Set.of(8), debugger.prgBreakpoints()); + } + + @Test + void aProgramRomBreakpointArmsAndCanBeRemoved() { + debugger.addPRGBreakpoint(8); + + assertTrue(debugger.isArmed()); + + debugger.removePRGBreakpoint(8); + + assertFalse(debugger.isArmed()); + assertNull(run(20)); + } + + @Test + void aProgramRomBreakpointFollowsTheBankRatherThanTheCpuAddress() { + var banked = new NES(Cart.load(mapper2ROM(), "banked-debugger.nes")); + var watching = new Debugger(); + + watching.attach(banked); + watching.addPRGBreakpoint(0); + + assertNotNull(watching.afterInstruction(0x8000, 0xC000), + "bank zero initially occupies $8000"); + + banked.getMemory().write(0x8000, 1); + + assertNull(watching.afterInstruction(0x8000, 0xC000), + "the same CPU address now names bank one"); + + watching.addPRGBreakpoint(0x4000); + assertNotNull(watching.afterInstruction(0x8000, 0xC000), + "and a point on bank one follows it into the window"); + } + @Test void aRemovedBreakpointStopsStopping() { debugger.addBreakpoint(LDX); @@ -309,11 +353,13 @@ void theTrailRemembersWhatActuallyRan() { @Test void clearingForgetsEveryPoint() { debugger.addBreakpoint(LDX); + debugger.addPRGBreakpoint(8); debugger.addWatchpoint(0x0300); debugger.clear(); assertEquals(java.util.Set.of(), debugger.breakpoints()); + assertEquals(java.util.Set.of(), debugger.prgBreakpoints()); assertEquals(java.util.Map.of(), debugger.watchpoints()); assertFalse(debugger.isArmed()); assertNull(run(20)); @@ -464,4 +510,19 @@ private static byte[] rom() { return image; } + + /** A two-bank UxROM image: bank zero is switchable at $8000, bank one fixed at $C000. */ + private static byte[] mapper2ROM() { + var image = new byte[16 + 0x8000 + 0x2000]; + + image[0] = 'N'; + image[1] = 'E'; + image[2] = 'S'; + image[3] = 0x1A; + image[4] = 2; + image[5] = 1; + image[6] = 0x20; + + return image; + } } diff --git a/mynes-desktop/pom.xml b/mynes-desktop/pom.xml index a2132f0..1f42c73 100644 --- a/mynes-desktop/pom.xml +++ b/mynes-desktop/pom.xml @@ -70,6 +70,10 @@ com.miglayout miglayout-swing + + com.fifesoft + rsyntaxtextarea + diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/controlpanel/ControlPanelFrame.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/controlpanel/ControlPanelFrame.java index 8c3c9f6..179075d 100644 --- a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/controlpanel/ControlPanelFrame.java +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/controlpanel/ControlPanelFrame.java @@ -201,10 +201,10 @@ public void setMachine( observeTheMachine(); if (debugger == null) { - debugger = new DebuggerPanel(nes, runner, points); + debugger = new DebuggerPanel(nes, runner, points, cart); debugger.installKeysIn(getRootPane()); } else { - debugger.setMachine(nes, runner); + debugger.setMachine(nes, runner, cart); } var inFront = tabs.getSelectedIndex(); diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/Cc65DebugInfo.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/Cc65DebugInfo.java new file mode 100644 index 0000000..86debb1 --- /dev/null +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/Cc65DebugInfo.java @@ -0,0 +1,601 @@ +package com.github.dimiro1.mynes.ui.debugger; + +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Reads the text file written by {@code ld65 --dbgfile}. */ +final class Cc65DebugInfo { + private record FileRecord(int id, String name, long size, long modified) { + } + + private record Segment( + int id, String name, int start, int size, @Nullable String output, int outputOffset) { + } + + private record Span(int id, int segment, int start, int size) { + } + + private record LineRecord(int id, int file, int line, int type, List spans) { + } + + private record SymbolRecord( + String name, + String kind, + int value, + @Nullable Integer segment, + @Nullable Integer definition, + List references) { + } + + private Cc65DebugInfo() { + } + + static SourceProgram read( + final Path debugFile, final byte[] prgROM, final @Nullable Path sourceRoot) + throws IOException { + + var records = Files.readAllLines(debugFile, StandardCharsets.UTF_8); + var versionSeen = false; + var files = new LinkedHashMap(); + var segments = new LinkedHashMap(); + var spans = new LinkedHashMap(); + var lines = new ArrayList(); + var symbols = new ArrayList(); + + for (var number = 0; number < records.size(); number++) { + var record = records.get(number); + + if (record.isBlank()) { + continue; + } + + var tab = record.indexOf('\t'); + + if (tab < 0) { + throw bad(debugFile, number, "record has no tab"); + } + + var kind = record.substring(0, tab); + var values = attributes(record.substring(tab + 1), debugFile, number); + + try { + switch (kind) { + case "version" -> { + var major = integer(required(values, "major")); + + if (major != 2) { + throw bad(debugFile, number, "unsupported debug format version " + major); + } + + versionSeen = true; + } + case "file" -> { + var file = new FileRecord( + integer(required(values, "id")), + required(values, "name"), + integer(required(values, "size")), + integer(values.getOrDefault("mtime", "0"))); + + files.put(file.id(), file); + } + case "seg" -> { + var segment = new Segment( + integer(required(values, "id")), + required(values, "name"), + integer(required(values, "start")), + integer(required(values, "size")), + values.get("oname"), + integer(values.getOrDefault("ooffs", "-1"))); + + segments.put(segment.id(), segment); + } + case "span" -> { + var span = new Span( + integer(required(values, "id")), + integer(required(values, "seg")), + integer(required(values, "start")), + integer(required(values, "size"))); + + spans.put(span.id(), span); + } + case "line" -> lines.add(new LineRecord( + integer(required(values, "id")), + integer(required(values, "file")), + integer(required(values, "line")), + integer(values.getOrDefault("type", "0")), + ids(values.get("span")))); + case "sym" -> symbols.add(new SymbolRecord( + required(values, "name"), + values.getOrDefault("type", "symbol"), + integer(required(values, "val")), + values.containsKey("seg") ? integer(values.get("seg")) : null, + values.containsKey("def") ? integer(values.get("def")) : null, + ids(values.get("ref")))); + default -> { /* The source view has no use for modules, scopes, types or csym. */ } + } + } catch (NumberFormatException e) { + throw bad(debugFile, number, "invalid number", e); + } + } + + if (!versionSeen) { + throw new IOException(debugFile + " is not an ld65 debug file (no version record)"); + } + + var warnings = new ArrayList(); + var sourceFiles = new ArrayList(); + var resolvedById = new HashMap(); + var sourceFileIds = new LinkedHashSet(); + + lines.forEach(line -> sourceFileIds.add(line.file())); + + for (var file : files.values()) { + // ld65 also records binary inputs to .incbin (for example CHR data). With no source + // line pointing into them they are not source files and must not be decoded as text. + if (!sourceFileIds.contains(file.id())) { + continue; + } + + var resolved = resolveSource(debugFile, sourceRoot, file.name()); + var text = resolved == null + ? List.of() + : Files.readAllLines(resolved, StandardCharsets.UTF_8); + var stale = resolved != null && stale(resolved, file); + var sourceFile = new SourceProgram.SourceFile( + file.id(), file.name(), resolved, List.copyOf(text), stale); + + sourceFiles.add(sourceFile); + resolvedById.put(file.id(), sourceFile); + + if (resolved == null) { + warnings.add("Could not find " + file.name()); + } else if (stale) { + warnings.add(sourceFile.displayName() + " has changed since the program was built"); + } + } + + var outputBases = outputBases(debugFile, sourceRoot, segments.values(), prgROM, warnings); + var ranges = new LinkedHashMap>>(); + var preferred = new ArrayList(); + + // The ordinary source location before a macro body when both own one span. See SourceProgram. + lines.sort(Comparator.comparingInt(line -> line.type() == 2 ? 1 : 0)); + + for (var line : lines) { + var file = resolvedById.get(line.file()); + + if (file == null) { + continue; + } + + var lineRanges = new ArrayList(); + + for (var spanId : line.spans()) { + var span = spans.get(spanId); + var segment = span == null ? null : segments.get(span.segment()); + var range = rangeOf(segment, span, outputBases, prgROM.length); + + if (range != null) { + lineRanges.add(range); + ranges.computeIfAbsent(file.id(), ignored -> new LinkedHashMap<>()) + .computeIfAbsent(line.line(), ignored -> new ArrayList<>()) + .add(range); + } + } + + preferred.add(new SourceProgram.SourceLine(file, line.line(), "", lineRanges)); + } + + var sourceSymbols = new ArrayList(); + var linesById = new HashMap(); + + lines.forEach(line -> linesById.put(line.id(), line)); + + for (var symbol : symbols) { + Integer prgOffset = null; + + if (symbol.segment() != null) { + var segment = segments.get(symbol.segment()); + + if (segment != null && segment.output() != null) { + var base = outputBases.get(segment.output()); + + if (base != null) { + var offset = segment.outputOffset() - base + symbol.value() - segment.start(); + + if (offset >= 0 && offset < prgROM.length) { + prgOffset = offset; + } + } + } + } + + var definition = locationOf( + symbol.definition() == null ? null : linesById.get(symbol.definition()), + resolvedById); + var references = symbol.references().stream() + .map(linesById::get) + .map(line -> locationOf(line, resolvedById)) + .filter(java.util.Objects::nonNull) + .toList(); + + sourceSymbols.add(new SourceProgram.Symbol( + symbol.name(), + symbol.kind(), + symbol.value(), + prgOffset, + definition, + references)); + } + + return new SourceProgram( + debugFile.toAbsolutePath().normalize(), + sourceFiles, + ranges, + preferred, + sourceSymbols, + prgROM.length, + warnings); + } + + private static @Nullable SourceProgram.Location locationOf( + final @Nullable LineRecord line, + final Map files) { + if (line == null) { + return null; + } + + var file = files.get(line.file()); + + return file == null ? null : new SourceProgram.Location(file, line.line()); + } + + private static @Nullable SourceProgram.Range rangeOf( + final @Nullable Segment segment, + final Span span, + final Map outputBases, + final int prgBytes) { + + if (segment == null || segment.output() == null || segment.outputOffset() < 0 + || segment.start() < 0x8000 || segment.start() > 0xFFFF) { + return null; + } + + var outputBase = outputBases.get(segment.output()); + + if (outputBase == null) { + return null; + } + + var offset = segment.outputOffset() - outputBase + span.start(); + + if (offset < 0 || offset >= prgBytes || span.size() <= 0) { + return null; + } + + var size = Math.min(span.size(), prgBytes - offset); + + return new SourceProgram.Range(offset, (segment.start() + span.start()) & 0xFFFF, size); + } + + /** The byte in each linker output file at which the cartridge's PRG ROM begins. */ + private static Map outputBases( + final Path debugFile, + final @Nullable Path sourceRoot, + final Iterable segments, + final byte[] prgROM, + final List warnings) throws IOException { + + var byOutput = new LinkedHashMap>(); + + for (var segment : segments) { + if (segment.output() != null) { + byOutput.computeIfAbsent(segment.output(), ignored -> new ArrayList<>()).add(segment); + } + } + + var bases = new HashMap(); + + for (var entry : byOutput.entrySet()) { + var inferred = entry.getValue().stream() + .filter(segment -> segment.name().equalsIgnoreCase("HEADER")) + .mapToInt(segment -> segment.outputOffset() + segment.size()) + .max() + .orElseGet(() -> entry.getKey().toLowerCase().endsWith(".nes") ? 16 : 0); + var output = resolveOutput(debugFile, sourceRoot, entry.getKey()); + + if (output != null) { + var base = indexOf(Files.readAllBytes(output), prgROM, inferred); + + if (base >= 0) { + bases.put(entry.getKey(), base); + continue; + } + } + + // A normal .nes output starts with the 16-byte header. This inference is also available + // when the old build directory no longer exists, which is precisely when source-root + // remapping is useful. A separate PRG binary starts at zero. + bases.put(entry.getKey(), inferred); + + if (entry.getValue().stream().anyMatch(segment -> segment.start() >= 0x8000)) { + warnings.add("Could not verify " + entry.getKey() + + " against the loaded ROM; using its linked offsets"); + } + } + + return bases; + } + + private static int indexOf(final byte[] whole, final byte[] wanted, final int preferred) { + if (wanted.length == 0 || whole.length < wanted.length) { + return -1; + } + + var found = -1; + + outer: + for (var start = 0; start <= whole.length - wanted.length; start++) { + if (whole[start] != wanted[0] + || whole[start + wanted.length - 1] != wanted[wanted.length - 1]) { + continue; + } + + for (var at = 1; at < wanted.length - 1; at++) { + if (whole[start + at] != wanted[at]) { + continue outer; + } + } + + if (found < 0 || Math.abs(start - preferred) < Math.abs(found - preferred)) { + found = start; + } + } + + return found; + } + + private static boolean stale(final Path path, final FileRecord recorded) throws IOException { + if (recorded.size() > 0 && Files.size(path) != recorded.size()) { + return true; + } + + if (recorded.modified() <= 0) { + return false; + } + + var actual = Files.getLastModifiedTime(path).toMillis() / 1_000; + + return actual > recorded.modified() + 2; + } + + private static @Nullable Path resolveSource( + final Path debugFile, final @Nullable Path root, final String recorded) throws IOException { + + var named = Path.of(recorded); + var candidates = new LinkedHashSet(); + + candidates.add(named); + for (var base : searchRoots(debugFile, root)) { + candidates.add(base.resolve(named).normalize()); + + if (named.getFileName() != null) { + candidates.add(base.resolve(named.getFileName()).normalize()); + } + } + + for (var candidate : candidates) { + if (Files.isRegularFile(candidate)) { + return candidate.toAbsolutePath().normalize(); + } + } + + if (named.getFileName() == null) { + return null; + } + + // A source folder is a useful anchor, not a fence: generated includes commonly sit in a + // sibling build folder. Try the anchor and its nearby project roots, stopping at the first + // root where the file name is unambiguous. + for (var base : recursiveSearchRoots(root)) { + if (!Files.isDirectory(base)) { + continue; + } + + try (var paths = Files.walk(base, 8)) { + var matches = paths + .filter(Files::isRegularFile) + .filter(path -> path.getFileName().equals(named.getFileName())) + .limit(2) + .toList(); + + if (matches.size() == 1) { + return matches.getFirst().toAbsolutePath().normalize(); + } + } + } + + return null; + } + + private static List recursiveSearchRoots(final @Nullable Path root) { + if (root == null) { + return List.of(); + } + + var roots = new LinkedHashSet(); + addWithParents(roots, root, 1); + + return List.copyOf(roots); + } + + private static @Nullable Path resolveOutput( + final Path debugFile, final @Nullable Path root, final String recorded) { + + var named = Path.of(recorded); + var candidates = new LinkedHashSet(); + + candidates.add(named); + for (var base : searchRoots(debugFile, root)) { + candidates.add(base.resolve(named).normalize()); + if (named.getFileName() != null) { + candidates.add(base.resolve(named.getFileName())); + } + } + + return candidates.stream() + .filter(Files::isRegularFile) + .findFirst() + .map(path -> path.toAbsolutePath().normalize()) + .orElse(null); + } + + /** + * Places a recorded build-relative path is likely to be relative to. Both a selected source + * folder and the folder containing the debug file are anchors; their parents cover the common + * {@code project/src} plus {@code project/build} layout without asking for multiple roots. + */ + private static List searchRoots(final Path debugFile, final @Nullable Path root) { + var roots = new LinkedHashSet(); + + if (root != null) { + addWithParents(roots, root, 2); + } + + var debugParent = debugFile.toAbsolutePath().normalize().getParent(); + + if (debugParent != null) { + addWithParents(roots, debugParent, 2); + } + + return List.copyOf(roots); + } + + private static void addWithParents( + final Set roots, final Path start, final int parents) { + var at = start.toAbsolutePath().normalize(); + + for (var level = 0; at != null && level <= parents; level++, at = at.getParent()) { + roots.add(at); + } + } + + private static Map attributes( + final String text, final Path file, final int line) throws IOException { + + var out = new LinkedHashMap(); + var at = 0; + + while (at < text.length()) { + var equals = text.indexOf('=', at); + + if (equals < 0) { + throw bad(file, line, "attribute has no '='"); + } + + var key = text.substring(at, equals).trim(); + at = equals + 1; + + String value; + if (at < text.length() && text.charAt(at) == '"') { + var quoted = new StringBuilder(); + var escaped = false; + at++; + + while (at < text.length()) { + var c = text.charAt(at++); + + if (escaped) { + // ld65 quotes a literal backslash and quote as \\ and \". Preserve the + // slash for every other pair: a Windows path written as C:\Users must not + // silently turn into C:Users when a producer did not double its separators. + if (c != '\\' && c != '"') { + quoted.append('\\'); + } + + quoted.append(c); + escaped = false; + } else if (c == '\\') { + escaped = true; + } else if (c == '"') { + break; + } else { + quoted.append(c); + } + } + + value = quoted.toString(); + } else { + var comma = text.indexOf(',', at); + var end = comma < 0 ? text.length() : comma; + + value = text.substring(at, end).trim(); + at = end; + } + + out.put(key, value); + + if (at < text.length() && text.charAt(at) == ',') { + at++; + } + } + + return out; + } + + private static List ids(final @Nullable String text) { + if (text == null || text.isBlank()) { + return List.of(); + } + + var out = new ArrayList(); + + for (var id : text.split("\\+")) { + out.add(integer(id)); + } + + return List.copyOf(out); + } + + private static int integer(final String text) { + var value = text.trim(); + + if (value.startsWith("0x") || value.startsWith("0X")) { + return (int) Long.parseLong(value.substring(2), 16); + } + + return Integer.parseInt(value); + } + + private static String required(final Map values, final String key) { + var value = values.get(key); + + if (value == null) { + throw new IllegalArgumentException("missing " + key); + } + + return value; + } + + private static IOException bad(final Path file, final int zeroBasedLine, final String message) { + return new IOException(file + ":" + (zeroBasedLine + 1) + ": " + message); + } + + private static IOException bad( + final Path file, final int zeroBasedLine, final String message, final Exception cause) { + return new IOException(file + ":" + (zeroBasedLine + 1) + ": " + message, cause); + } +} diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/DebuggerPanel.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/DebuggerPanel.java index a6a2629..538e76f 100644 --- a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/DebuggerPanel.java +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/DebuggerPanel.java @@ -1,5 +1,7 @@ package com.github.dimiro1.mynes.ui.debugger; +import com.formdev.flatlaf.util.SystemFileChooser; +import com.github.dimiro1.mynes.Cart; import com.github.dimiro1.mynes.NES; import com.github.dimiro1.mynes.debug.Condition; import com.github.dimiro1.mynes.debug.Debugger; @@ -15,6 +17,8 @@ import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JSplitPane; +import javax.swing.JTabbedPane; +import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import java.awt.Color; @@ -24,6 +28,9 @@ import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; +import java.io.IOException; +import java.nio.file.Path; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; @@ -54,9 +61,13 @@ * a view that opened at a size chosen for the last bug is a small trap. */ public final class DebuggerPanel extends JPanel { + private static final System.Logger logger = System.getLogger("Debugger"); + private final Debugger debugger; private final DisassemblyPanel disassembly = new DisassemblyPanel(new Listing()); + private final SourcePanel source = new SourcePanel(new Sources()); + private final JTabbedPane code = new JTabbedPane(); private final RegistersPanel registers = new RegistersPanel(); private final StackPanel stack = new StackPanel(); private final MemoryPanel memory = new MemoryPanel(); @@ -71,6 +82,15 @@ public final class DebuggerPanel extends JPanel { private NES nes; private EmulatorRunner runner; + private Cart cart; + private MachineSnapshot snapshot; + private SourceProgram sourceProgram; + private Path sourceRoot; + + private final SystemFileChooser debugChooser = new SystemFileChooser(); + private final SystemFileChooser sourceChooser = new SystemFileChooser(); + private final SourceAssociations associations = + SourceAssociations.load(SourceAssociations.DEFAULT_PATH); /** * Whether the machine is stopped because of something done in this view, which is what decides @@ -83,21 +103,41 @@ public final class DebuggerPanel extends JPanel { * put down itself from one the user did and only take the first kind back up. */ private Set knownBreakpoints = Set.of(); + private Set knownPRGBreakpoints = Set.of(); /** * A breakpoint this view put down for Run to Here and owes the debugger back, or -1. */ private int runToAddress = -1; + private Set runToPRG = Set.of(); public DebuggerPanel( final NES nes, final EmulatorRunner runner, final Debugger debugger) { + this(nes, runner, debugger, nes.getCart()); + } + + public DebuggerPanel( + final NES nes, final EmulatorRunner runner, final Debugger debugger, final Cart cart) { + this.nes = nes; this.runner = runner; this.debugger = debugger; + this.cart = cart; this.points = new PointsPanel(new Editing()); + var filter = new SystemFileChooser.FileNameExtensionFilter("ld65 debug information", "dbg"); + debugChooser.addChoosableFileFilter(filter); + debugChooser.setFileFilter(filter); + debugChooser.setDialogTitle("Attach Debug Information"); + debugChooser.setApproveButtonText("Attach"); + + sourceChooser.setFileSelectionMode(SystemFileChooser.DIRECTORIES_ONLY); + sourceChooser.setDialogTitle("Find Source Files"); + sourceChooser.setApproveButtonText("Use Folder"); + init(); + restoreSources(); } private void init() { @@ -122,19 +162,23 @@ private void init() { var side = new JPanel(new MigLayout("insets 0, fill, wrap 1, gap 0", "[grow,fill]", "[][grow,fill]")); side.add(registers); side.add(stack, "hmin 120"); + code.addTab("Source", source); + code.addTab("Disassembly", disassembly); + code.setSelectedComponent(disassembly); + // A split pane opens its divider at the first component's preferred width and never takes // one below its minimum, so both are said for every pane: the preferred sizes are where the // dividers start, and the minimums are what stops a drag from squashing a panel into // buttons drawn as "...". The points panel works its own minimum out from its rows. - disassembly.setPreferredSize(new Dimension(700, 400)); - disassembly.setMinimumSize(new Dimension(380, 160)); + code.setPreferredSize(new Dimension(700, 400)); + code.setMinimumSize(new Dimension(380, 160)); side.setPreferredSize(new Dimension(400, 400)); side.setMinimumSize(new Dimension(300, 200)); memory.setPreferredSize(new Dimension(660, 280)); memory.setMinimumSize(new Dimension(420, 120)); points.setPreferredSize(new Dimension(Math.max(440, points.getMinimumSize().width), 280)); - var top = split(JSplitPane.HORIZONTAL_SPLIT, disassembly, side, 0.7); + var top = split(JSplitPane.HORIZONTAL_SPLIT, code, side, 0.7); var bottom = split(JSplitPane.HORIZONTAL_SPLIT, memory, points, 0.62); var body = split(JSplitPane.VERTICAL_SPLIT, top, bottom, 0.56); @@ -212,8 +256,24 @@ public void actionPerformed(final ActionEvent e) { * the power to test. */ public void setMachine(final NES nes, final EmulatorRunner runner) { + setMachine(nes, runner, nes.getCart()); + } + + public void setMachine(final NES nes, final EmulatorRunner runner, final Cart cart) { + var sameCartridge = this.cart.sha256().equals(cart.sha256()); + this.nes = nes; this.runner = runner; + this.cart = cart; + snapshot = null; + + if (!sameCartridge) { + sourceProgram = null; + sourceRoot = null; + source.detach(); + disassembly.setSourceProgram(null); + code.setSelectedComponent(disassembly); + } // What is on show describes a machine that no longer exists. The points stay -- they are the // user's, and keeping them is the whole reason this view is repointed rather than closed -- @@ -226,14 +286,22 @@ public void setMachine(final NES nes, final EmulatorRunner runner) { // clears them: the points are the user's while the game is the same game, and a list of // breakpoints that are no longer set would be the worst kind of stale. var breaks = Set.copyOf(debugger.breakpoints()); + var prgBreaks = Set.copyOf(debugger.prgBreakpoints()); var conditions = Map.copyOf(debugger.conditions()); knownBreakpoints = breaks; + knownPRGBreakpoints = prgBreaks; - points.show(breaks, conditions, Map.copyOf(debugger.watchpoints())); + points.show(breaks, conditions, prgBreaks, sourceProgram, + Map.copyOf(debugger.watchpoints())); disassembly.setBreakpoints(breaks, conditions); + source.setBreakpoints(prgBreaks); running(); + + if (!sameCartridge) { + restoreSources(); + } } /** @@ -243,19 +311,28 @@ public void setMachine(final NES nes, final EmulatorRunner runner) { public void stopped(final Debugger.Stop stop) { stoppedByUs = true; - var snapshot = MachineSnapshot.of(nes, debugger); + snapshot = MachineSnapshot.of(nes, debugger); var breaks = Set.copyOf(debugger.breakpoints()); + var prgBreaks = Set.copyOf(debugger.prgBreakpoints()); var conditions = Map.copyOf(debugger.conditions()); knownBreakpoints = breaks; + knownPRGBreakpoints = prgBreaks; disassembly.show(snapshot, breaks, conditions); registers.show(snapshot.machine()); stack.show(snapshot); memory.show(snapshot, stop); - points.show(breaks, conditions, Map.copyOf(debugger.watchpoints())); + points.show(breaks, conditions, prgBreaks, sourceProgram, + Map.copyOf(debugger.watchpoints())); + + SourceProgram.SourceLine sourceLine = null; + if (sourceProgram != null) { + sourceLine = sourceProgram.lineAt(snapshot.prgOffset(stop.pc())); + source.show(sourceProgram, sourceLine, prgBreaks); + } - status.setText(describe(stop)); + status.setText(describe(stop, sourceLine)); dot.setColour(Theme.stopped()); run.setEnabled(true); @@ -272,6 +349,12 @@ public void stopped(final Debugger.Stop stop) { runToAddress = -1; edit(() -> debugger.removeBreakpoint(address)); } + + if (!runToPRG.isEmpty()) { + var offsets = runToPRG; + runToPRG = Set.of(); + edit(() -> offsets.forEach(debugger::removePRGBreakpoint)); + } } /** @@ -295,6 +378,7 @@ public void running() { registers.stale(); stack.stale(); + source.clearMachine(); status.setText("Running"); dot.setColour(Theme.running()); @@ -332,6 +416,16 @@ private void stepOneFrame() { } private void toggleBreakpointAtSelection() { + if (code.getSelectedComponent() == source) { + var line = source.selectedLine(); + + if (line != null && line.hasCode()) { + toggleSourceBreakpoint(line); + } + + return; + } + var address = disassembly.selectedAddress(); if (address >= 0) { @@ -377,6 +471,160 @@ public void showInMemory(final int address) { } } + private void toggleSourceBreakpoint(final SourceProgram.SourceLine line) { + var offsets = line.breakpointOffsets(); + var remove = offsets.stream().allMatch(knownPRGBreakpoints::contains); + + edit(() -> offsets.forEach(offset -> { + if (remove) { + debugger.removePRGBreakpoint(offset); + } else { + debugger.addPRGBreakpoint(offset); + } + })); + } + + /** The source listing's file and breakpoint actions. */ + private final class Sources implements SourcePanel.Actions { + @Override + public void attach() { + if (debugChooser.showOpenDialog(DebuggerPanel.this) == SystemFileChooser.APPROVE_OPTION) { + loadSources(debugChooser.getSelectedFile().toPath(), null, true); + } + } + + @Override + public void locateSources() { + if (sourceProgram == null) { + return; + } + + if (sourceRoot != null) { + sourceChooser.setCurrentDirectory(sourceRoot.toFile()); + } + + if (sourceChooser.showOpenDialog(DebuggerPanel.this) + != SystemFileChooser.APPROVE_OPTION) { + return; + } + + loadSources(sourceProgram.debugFile(), sourceChooser.getSelectedFile().toPath(), false); + } + + @Override + public void detach() { + var offsets = Set.copyOf(knownPRGBreakpoints); + + sourceProgram = null; + sourceRoot = null; + source.detach(); + disassembly.setSourceProgram(null); + code.setSelectedComponent(disassembly); + edit(() -> offsets.forEach(debugger::removePRGBreakpoint)); + + try { + associations.forget(cart.sha256()); + } catch (IOException e) { + logger.log(System.Logger.Level.WARNING, "could not forget source association", e); + } + } + + @Override + public void toggleBreakpoint(final SourceProgram.SourceLine line) { + toggleSourceBreakpoint(line); + } + + @Override + public void runTo(final SourceProgram.SourceLine line) { + var temporary = new LinkedHashSet(); + + for (var offset : line.breakpointOffsets()) { + if (!knownPRGBreakpoints.contains(offset)) { + temporary.add(offset); + } + } + + runToPRG = Set.copyOf(temporary); + edit(() -> temporary.forEach(debugger::addPRGBreakpoint)); + resume(); + } + + @Override + public void showInDisassembly(final SourceProgram.SourceLine line) { + if (!line.ranges().isEmpty()) { + disassembly.goTo(line.ranges().getFirst().cpuAddress()); + code.setSelectedComponent(disassembly); + } + } + } + + private void loadSources( + final Path debugFile, final Path root, final boolean offerRoot) { + try { + var resolvedRoot = root; + var loaded = Cc65DebugInfo.read(debugFile, cart.prgROM(), resolvedRoot); + + if (offerRoot && loaded.hasMissingFiles()) { + var answer = JOptionPane.showConfirmDialog( + this, + "Some recorded source paths no longer exist. Choose the project folder?", + "Find Source Files", + JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE); + + if (answer == JOptionPane.YES_OPTION + && sourceChooser.showOpenDialog(this) == SystemFileChooser.APPROVE_OPTION) { + resolvedRoot = sourceChooser.getSelectedFile().toPath(); + loaded = Cc65DebugInfo.read(debugFile, cart.prgROM(), resolvedRoot); + } + } + + sourceProgram = loaded; + sourceRoot = resolvedRoot; + disassembly.setSourceProgram(loaded); + + var line = snapshot == null ? null + : loaded.lineAt(snapshot.prgOffset(snapshot.cpu().pc())); + source.show(loaded, line, knownPRGBreakpoints); + code.setSelectedComponent(source); + + try { + associations.remember(cart.sha256(), debugFile, resolvedRoot); + } catch (IOException e) { + logger.log(System.Logger.Level.WARNING, "could not remember source association", e); + } + } catch (IOException | RuntimeException e) { + logger.log(System.Logger.Level.ERROR, "could not load " + debugFile, e); + JOptionPane.showMessageDialog( + this, + "Could not attach " + debugFile.getFileName() + ": " + e.getMessage(), + "Debug Information", + JOptionPane.ERROR_MESSAGE); + } + } + + private void restoreSources() { + var remembered = associations.get(cart.sha256()); + + if (remembered == null || !java.nio.file.Files.isRegularFile(remembered.debugFile())) { + return; + } + + try { + var loaded = Cc65DebugInfo.read( + remembered.debugFile(), cart.prgROM(), remembered.sourceRoot()); + + sourceProgram = loaded; + sourceRoot = remembered.sourceRoot(); + disassembly.setSourceProgram(loaded); + source.show(loaded, null, knownPRGBreakpoints); + code.setSelectedComponent(source); + } catch (IOException | RuntimeException e) { + logger.log(System.Logger.Level.WARNING, + "could not restore " + remembered.debugFile(), e); + } + } + /** * What the points panel asks for, all of it posted onto the emulation thread. */ @@ -396,6 +644,11 @@ public void removeBreakpoint(final int address) { edit(() -> debugger.removeBreakpoint(address)); } + @Override + public void removePRGBreakpoint(final int offset) { + edit(() -> debugger.removePRGBreakpoint(offset)); + } + @Override public void removeWatchpoint(final int address) { edit(() -> debugger.removeWatchpoint(address)); @@ -419,19 +672,23 @@ private void edit(final Runnable change) { change.run(); var breaks = Set.copyOf(debugger.breakpoints()); + var prgBreaks = Set.copyOf(debugger.prgBreakpoints()); var conditions = Map.copyOf(debugger.conditions()); var watches = Map.copyOf(debugger.watchpoints()); SwingUtilities.invokeLater(() -> { knownBreakpoints = breaks; - points.show(breaks, conditions, watches); + knownPRGBreakpoints = prgBreaks; + points.show(breaks, conditions, prgBreaks, sourceProgram, watches); disassembly.setBreakpoints(breaks, conditions); + source.setBreakpoints(prgBreaks); }); }); } - private static String describe(final Debugger.Stop stop) { - return "Stopped · " + switch (stop.reason()) { + private static String describe( + final Debugger.Stop stop, final SourceProgram.SourceLine sourceLine) { + var stopped = "Stopped · " + switch (stop.reason()) { case BREAKPOINT -> String.format("breakpoint at $%04X", stop.pc()); case WATCHPOINT -> String.format( "watchpoint: $%04X %s $%02X by the instruction at $%04X", @@ -443,6 +700,8 @@ private static String describe(final Debugger.Stop stop) { case FRAME -> String.format("end of frame, at $%04X", stop.pc()); case ASKED -> String.format("at $%04X", stop.pc()); }; + + return sourceLine == null ? stopped : stopped + " · " + sourceLine.location(); } /** diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/DisassemblyPanel.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/DisassemblyPanel.java index 4d9ceec..ed9398d 100644 --- a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/DisassemblyPanel.java +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/DisassemblyPanel.java @@ -4,6 +4,7 @@ import com.github.dimiro1.mynes.debug.Condition; import com.github.dimiro1.mynes.debug.Disassembler; import net.miginfocom.swing.MigLayout; +import org.jetbrains.annotations.Nullable; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; @@ -78,7 +79,7 @@ interface Actions { * @param current whether this is the instruction about to run. * @param ran whether it is one that already has, which is what greys the history out. */ - record Row(int address, String bytes, String text, boolean current, boolean ran) { + record Row(int address, String bytes, String text, @Nullable String symbol, boolean current, boolean ran) { } private final DefaultListModel model = new DefaultListModel<>(); @@ -90,6 +91,7 @@ record Row(int address, String bytes, String text, boolean current, boolean ran) private Map conditions = Map.of(); private MachineSnapshot snapshot; + private SourceProgram sourceProgram; /** * Where to list from, or -1 to follow the PC. @@ -191,6 +193,16 @@ void clear() { model.clear(); } + /** Lists from an address selected in the source view. */ + void goTo(final int address) { + origin = address & 0xFFFF; + from.setText(String.format("$%04X", origin)); + + if (snapshot != null) { + rebuild(); + } + } + /** * Redraws the gutter after a point has been put down or picked up, without disturbing the * listing itself -- which still describes wherever the machine stopped. @@ -202,6 +214,14 @@ void setBreakpoints(final Set breakpoints, final Map + * Taken from the bank layout in the same readout as the PC, rather than by asking the live + * mapper later: the machine may have resumed by the time Swing paints the answer. + */ + int prgOffset(final int address) { + var cpuAddress = address & 0xFFFF; + + if (cpuAddress < 0x8000) { + return -1; + } + + var window = (cpuAddress - 0x8000) / com.github.dimiro1.mynes.mappers.Mapper.Banks.PRG_WINDOW; + var within = cpuAddress & (com.github.dimiro1.mynes.mappers.Mapper.Banks.PRG_WINDOW - 1); + + return machine.board().banks().prg()[window] + * com.github.dimiro1.mynes.mappers.Mapper.Banks.PRG_WINDOW + within; + } + /** * What is on the stack, top first, which is the order it will come off in. */ diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/PointsPanel.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/PointsPanel.java index e2730c0..523372e 100644 --- a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/PointsPanel.java +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/PointsPanel.java @@ -59,6 +59,8 @@ interface Points { void removeBreakpoint(int address); + void removePRGBreakpoint(int offset); + void removeWatchpoint(int address); void clear(); @@ -68,10 +70,11 @@ interface Points { * One line of either table: an address, and whatever else there is to say about it -- the * condition on a breakpoint, the direction of a watchpoint. */ - private record Point(int address, String detail) { + private record Point(int key, String place, String detail) { } private final PointTable breakpoints; + private final PointTable sourceBreakpoints; private final PointTable watchpoints; private final JTextField entry = new JTextField(12); @@ -82,9 +85,11 @@ private record Point(int address, String detail) { super(new MigLayout( "insets 4 8 8 8, fill, wrap 1, gapy 4", "[grow,fill]", - "[][grow,fill][][grow,fill][]4[][]")); + "[][grow,fill][][grow,fill][][grow,fill][]4[][]")); breakpoints = new PointTable("Breakpoints", "Condition", points::removeBreakpoint); + sourceBreakpoints = new PointTable( + "Source Breakpoints", "Source", points::removePRGBreakpoint); watchpoints = new PointTable("Watchpoints", "On", points::removeWatchpoint); entry.setFont(Theme.MONOSPACED); @@ -134,6 +139,8 @@ private record Point(int address, String detail) { add(breakpoints.header); add(breakpoints.scroll, "grow, hmin 60"); + add(sourceBreakpoints.header, "gaptop 8"); + add(sourceBreakpoints.scroll, "grow, hmin 44"); add(watchpoints.header, "gaptop 8"); add(watchpoints.scroll, "grow, hmin 60"); add(entryRow, "growx"); @@ -157,6 +164,8 @@ public Dimension getMinimumSize() { void show( final Set breaks, final Map conditions, + final Set prgBreaks, + final SourceProgram source, final Map watches) { var breakRows = new ArrayList(breaks.size()); @@ -164,14 +173,30 @@ void show( for (var address : breaks) { var condition = conditions.get(address); - breakRows.add(new Point(address, condition == null ? "" : "if " + condition.text())); + breakRows.add(new Point( + address, + String.format("$%04X", address), + condition == null ? "" : "if " + condition.text())); + } + + var sourceRows = new ArrayList(prgBreaks.size()); + + for (var offset : prgBreaks) { + var line = source == null ? null : source.lineForBreakpoint(offset); + + sourceRows.add(new Point( + offset, + String.format("PRG+$%05X", offset), + line == null ? "" : line.location())); } var watchRows = new ArrayList(watches.size()); - watches.forEach((address, on) -> watchRows.add(new Point(address, on.id()))); + watches.forEach((address, on) -> watchRows.add(new Point( + address, String.format("$%04X", address), on.id()))); breakpoints.show(breakRows); + sourceBreakpoints.show(sourceRows); watchpoints.show(watchRows); } @@ -233,7 +258,7 @@ private static final class PointTable { var metrics = table.getFontMetrics(Theme.MONOSPACED); var headerMetrics = table.getTableHeader().getFontMetrics(table.getTableHeader().getFont()); var addressWidth = Math.max( - metrics.stringWidth("$0000"), headerMetrics.stringWidth("Address")) + metrics.stringWidth("PRG+$00000"), headerMetrics.stringWidth("Address")) + metrics.charWidth('0') * 2; table.getColumnModel().getColumn(0).setMinWidth(addressWidth); @@ -291,7 +316,7 @@ private void removeSelected(final IntConsumer onRemove) { var row = table.getSelectedRow(); if (row >= 0 && row < model.rows.size()) { - onRemove.accept(model.rows.get(row).address()); + onRemove.accept(model.rows.get(row).key()); } } @@ -317,7 +342,7 @@ public String getColumnName(final int column) { public Object getValueAt(final int row, final int column) { var point = rows.get(row); - return column == 0 ? String.format("$%04X", point.address()) : point.detail(); + return column == 0 ? point.place() : point.detail(); } } diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/SourceAssociations.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/SourceAssociations.java new file mode 100644 index 0000000..1022367 --- /dev/null +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/SourceAssociations.java @@ -0,0 +1,117 @@ +package com.github.dimiro1.mynes.ui.debugger; + +import com.github.dimiro1.mynes.ui.Config; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + +/** Remembers which local debug build belongs to a cartridge digest. */ +final class SourceAssociations { + static final Path DEFAULT_PATH = Config.DEFAULT_PATH.resolveSibling("debug-sources.properties"); + + record Entry(Path debugFile, @Nullable Path sourceRoot) { + } + + private static final String DEBUG_SUFFIX = ".debug"; + private static final String ROOT_SUFFIX = ".root"; + + private final Path path; + private final Map entries; + + private SourceAssociations(final Path path, final Map entries) { + this.path = path; + this.entries = entries; + } + + static SourceAssociations load(final Path path) { + var properties = new Properties(); + + if (Files.isRegularFile(path)) { + try (var input = Files.newInputStream(path)) { + properties.load(input); + } catch (IOException | IllegalArgumentException ignored) { + // A local convenience file must never keep the emulator from opening. The selected + // .dbg can simply be attached again, which will replace whatever was broken. + } + } + + var entries = new LinkedHashMap(); + + for (var key : properties.stringPropertyNames()) { + if (!key.endsWith(DEBUG_SUFFIX)) { + continue; + } + + var digest = key.substring(0, key.length() - DEBUG_SUFFIX.length()); + var debug = path(properties.getProperty(key)); + var root = path(properties.getProperty(digest + ROOT_SUFFIX)); + + if (debug != null) { + entries.put(digest, new Entry(debug, root)); + } + } + + return new SourceAssociations(path, entries); + } + + @Nullable Entry get(final String digest) { + return entries.get(digest); + } + + void remember(final String digest, final Path debugFile, final @Nullable Path sourceRoot) + throws IOException { + entries.put(digest, new Entry( + debugFile.toAbsolutePath().normalize(), + sourceRoot == null ? null : sourceRoot.toAbsolutePath().normalize())); + save(); + } + + void forget(final String digest) throws IOException { + entries.remove(digest); + save(); + } + + private void save() throws IOException { + var parent = path.toAbsolutePath().getParent(); + + if (parent != null) { + Files.createDirectories(parent); + } + + var properties = new Properties(); + + entries.forEach((digest, entry) -> { + properties.setProperty(digest + DEBUG_SUFFIX, entry.debugFile().toString()); + + if (entry.sourceRoot() != null) { + properties.setProperty(digest + ROOT_SUFFIX, entry.sourceRoot().toString()); + } + }); + + try (var output = Files.newOutputStream( + path, + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE)) { + properties.store(output, "Source debug files, keyed by cartridge SHA-256"); + } + } + + private static @Nullable Path path(final @Nullable String text) { + if (text == null || text.isBlank()) { + return null; + } + + try { + return Path.of(text).toAbsolutePath().normalize(); + } catch (RuntimeException ignored) { + return null; + } + } +} diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/SourcePanel.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/SourcePanel.java new file mode 100644 index 0000000..0d9691e --- /dev/null +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/SourcePanel.java @@ -0,0 +1,625 @@ +package com.github.dimiro1.mynes.ui.debugger; + +import net.miginfocom.swing.MigLayout; +import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; +import org.fife.ui.rsyntaxtextarea.SyntaxConstants; +import org.fife.ui.rsyntaxtextarea.Token; +import org.fife.ui.rtextarea.IconRowEvent; +import org.fife.ui.rtextarea.IconRowListener; +import org.fife.ui.rtextarea.RTextScrollPane; +import org.jetbrains.annotations.Nullable; + +import javax.swing.BorderFactory; +import javax.swing.DefaultComboBoxModel; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.InputEvent; +import java.util.Set; + +/** A read-only, syntax-highlighted source listing over the linked bytes in a ca65 program. */ +final class SourcePanel extends JPanel { + interface Actions { + void attach(); + + void locateSources(); + + void detach(); + + void toggleBreakpoint(SourceProgram.SourceLine line); + + void runTo(SourceProgram.SourceLine line); + + void showInDisassembly(SourceProgram.SourceLine line); + } + + private final DefaultComboBoxModel fileModel = + new DefaultComboBoxModel<>(); + private final JComboBox files = new JComboBox<>(fileModel); + private final Listing listing = new Listing(); + private final RTextScrollPane scroll = new RTextScrollPane(listing, true); + private final JLabel note = Theme.note("Attach an ld65 .dbg file to follow source code."); + private final JButton locate = new JButton("Find Sources…"); + private final JButton detach = new JButton("Detach"); + private final Actions actions; + + private @Nullable SourceProgram program; + private @Nullable SourceProgram.SourceFile displayedFile; + private @Nullable SourceProgram.SourceLine current; + private @Nullable SourceProgram.SourceLine selected; + private Set breakpoints = Set.of(); + private boolean choosingFile; + private boolean changingText; + + SourcePanel(final Actions actions) { + super(new MigLayout("insets 4 8 8 8, fill", "[][grow][][pref!][]", "[][grow,fill][]")); + + this.actions = actions; + + listing.setFont(Theme.MONOSPACED); + listing.setEditable(false); + listing.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_ASSEMBLER_6502); + listing.setCodeFoldingEnabled(false); + listing.setHighlightCurrentLine(false); + listing.setAntiAliasingEnabled(true); + listing.setBackground(Theme.background()); + listing.setForeground(Theme.foreground()); + listing.setSelectionColor(Theme.selectionBackground()); + listing.setSelectedTextColor(Theme.selectionForeground()); + listing.addMouseListener(new Mouse()); + listing.addCaretListener(event -> { + if (!changingText) { + selected = lineAtCaret(); + } + }); + + scroll.setLineNumbersEnabled(true); + scroll.setIconRowHeaderEnabled(true); + scroll.setBorder(BorderFactory.createLineBorder(Theme.dim())); + scroll.getGutter().setLineNumberFont(Theme.MONOSPACED); + scroll.getGutter().setLineNumberColor(Theme.muted()); + scroll.getGutter().setCurrentLineNumberColor(Theme.muted()); + scroll.getGutter().setBorderColor(Theme.dim()); + scroll.getGutter().setIconRowHeaderInheritsGutterBackground(true); + scroll.getGutter().addIconRowListener(new GutterClicks()); + + files.setEnabled(false); + files.addActionListener(event -> { + if (!choosingFile) { + rebuild((SourceProgram.SourceFile) files.getSelectedItem()); + } + }); + + var attach = new JButton("Attach Debug Info…"); + + attach.setToolTipText("Open the .dbg file written by ld65 --dbgfile"); + attach.addActionListener(event -> actions.attach()); + + locate.setToolTipText("Choose a project or source folder when recorded paths have moved"); + locate.addActionListener(event -> actions.locateSources()); + locate.setVisible(false); + + detach.setToolTipText("Stop using source and symbols for this cartridge"); + detach.addActionListener(event -> actions.detach()); + detach.setEnabled(false); + + add(Theme.heading("Source")); + add(files, "growx"); + add(attach); + add(locate); + add(detach, "wrap"); + add(scroll, "span 5, grow, wrap"); + add(note, "span 5, growx"); + } + + void show( + final SourceProgram source, + final @Nullable SourceProgram.SourceLine line, + final Set breaks) { + + if (program != source) { + setProgram(source); + } + + current = line; + breakpoints = breaks; + + if (line != null && files.getSelectedItem() != line.file()) { + choosingFile = true; + files.setSelectedItem(line.file()); + choosingFile = false; + rebuild(line.file()); + } else { + refreshDecorations(); + } + + scrollToCurrent(); + } + + void setBreakpoints(final Set breaks) { + breakpoints = breaks; + refreshDecorations(); + } + + void clearMachine() { + current = null; + refreshDecorations(); + } + + void detach() { + program = null; + displayedFile = null; + current = null; + selected = null; + breakpoints = Set.of(); + fileModel.removeAllElements(); + setListingText(""); + refreshDecorations(); + files.setEnabled(false); + locate.setVisible(false); + detach.setEnabled(false); + note.setText("Attach an ld65 .dbg file to follow source code."); + } + + @Nullable SourceProgram.SourceLine selectedLine() { + return selected != null ? selected : current; + } + + private void setProgram(final SourceProgram source) { + program = source; + selected = null; + choosingFile = true; + fileModel.removeAllElements(); + source.files().forEach(fileModel::addElement); + choosingFile = false; + + files.setEnabled(fileModel.getSize() > 0); + locate.setVisible(source.hasMissingFiles()); + detach.setEnabled(true); + + if (source.warnings().isEmpty()) { + note.setText(source.debugFile().getFileName() + " · source matches the build"); + } else { + note.setText(String.join(" · ", source.warnings())); + } + + rebuild((SourceProgram.SourceFile) files.getSelectedItem()); + } + + private void rebuild(final @Nullable SourceProgram.SourceFile file) { + displayedFile = file; + selected = null; + + if (program == null || file == null) { + setListingText(""); + refreshDecorations(); + return; + } + + var text = new StringBuilder(); + + // A missing file may still have line records. Keep the line count stable so that a future + // remap and every .dbg line number still point at the same row. + for (var number = 1; ; number++) { + var line = program.line(file, number); + + if (line == null) { + break; + } + + if (!text.isEmpty()) { + text.append('\n'); + } + + text.append(line.text()); + } + + setListingText(text.toString()); + refreshDecorations(); + } + + private void setListingText(final String text) { + changingText = true; + + try { + listing.setText(text); + listing.setCaretPosition(0); + } finally { + changingText = false; + } + } + + private void refreshDecorations() { + listing.removeAllLineHighlights(); + scroll.getGutter().removeAllTrackingIcons(); + + if (program == null || displayedFile == null) { + return; + } + + for (var number = 1; number <= listing.getLineCount(); number++) { + var line = program.line(displayedFile, number); + + if (line == null) { + continue; + } + + var isCurrent = line == current; + var hasBreakpoint = hasBreakpoint(line); + + try { + if (isCurrent) { + listing.addLineHighlight(number - 1, Theme.currentRow()); + } + + if (isCurrent || hasBreakpoint) { + scroll.getGutter().addLineTrackingIcon( + number - 1, + new MarkerIcon(hasBreakpoint, isCurrent), + markerTooltip(line, hasBreakpoint, isCurrent)); + } + } catch (BadLocationException ignored) { + // The text and SourceProgram are rebuilt together; a transient document update can + // only make this decoration one repaint late. + } + } + + listing.repaint(); + } + + private void scrollToCurrent() { + if (current == null || displayedFile != current.file()) { + return; + } + + var line = current; + + SwingUtilities.invokeLater(() -> { + try { + var offset = listing.getLineStartOffset(line.number() - 1); + var shape = listing.modelToView2D(offset); + + if (shape == null) { + return; + } + + var bounds = shape.getBounds(); + var visible = listing.getVisibleRect(); + var centered = new Rectangle( + bounds.x, + Math.max(0, bounds.y - visible.height / 3), + Math.max(bounds.width, 1), + Math.max(visible.height, bounds.height)); + + listing.scrollRectToVisible(centered); + } catch (BadLocationException ignored) { + // A stale or missing source can legitimately have fewer physical lines. + } + }); + } + + private boolean hasBreakpoint(final SourceProgram.SourceLine line) { + return line.breakpointOffsets().stream().anyMatch(breakpoints::contains); + } + + private @Nullable SourceProgram.SourceLine lineAtCaret() { + return line(listing.getCaretLineNumber()); + } + + private @Nullable SourceProgram.SourceLine lineAt(final Point point) { + try { + return line(listing.getLineOfOffset(listing.viewToModel2D(point))); + } catch (BadLocationException ignored) { + return null; + } + } + + private @Nullable SourceProgram.SourceLine line(final int zeroBasedLine) { + return program == null || displayedFile == null + ? null : program.line(displayedFile, zeroBasedLine + 1); + } + + private String markerTooltip( + final SourceProgram.SourceLine line, + final boolean hasBreakpoint, + final boolean isCurrent) { + var prefix = hasBreakpoint && isCurrent ? "Breakpoint · Current instruction · " + : hasBreakpoint ? "Breakpoint · " : "Current instruction · "; + + return prefix + rangeTooltip(line); + } + + private String rangeTooltip(final SourceProgram.SourceLine line) { + return line.ranges().stream() + .map(range -> String.format( + "PRG+$%05X · linked at $%04X · %d byte%s", + range.prgOffset(), + range.cpuAddress(), + range.size(), + range.size() == 1 ? "" : "s")) + .reduce((left, right) -> left + " | " + right) + .orElse(line.location()); + } + + private @Nullable SourceProgram.Symbol symbolAt(final Point point) { + var line = lineAt(point); + var token = listing.viewToToken(point); + + return symbol(line, token); + } + + private @Nullable SourceProgram.Symbol symbolAtCaret() { + return symbol(lineAtCaret(), listing.modelToToken(listing.getCaretPosition())); + } + + private @Nullable SourceProgram.Symbol symbol( + final @Nullable SourceProgram.SourceLine line, final @Nullable Token token) { + if (program == null || line == null || token == null || !token.isPaintable()) { + return null; + } + + return program.symbolAt(line, token.getLexeme()); + } + + private String symbolTooltip(final SourceProgram.Symbol symbol) { + var kind = switch (symbol.kind()) { + case "lab" -> "label"; + case "equ" -> "constant"; + default -> symbol.kind(); + }; + var definition = symbol.definition() == null + ? "No source definition in debug information" + : "Defined at " + symbol.definition().displayName(); + + return "" + html(symbol.name()) + " = $" + + String.format("%04X", symbol.value() & 0xFFFF) + + " · " + html(kind) + "
" + html(definition) + + (symbol.definition() == null ? "" : "
Cmd/Ctrl-click to go to definition") + + ""; + } + + private static String html(final String text) { + return text.replace("&", "&") + .replace("<", "<") + .replace(">", ">"); + } + + private void goToDefinition(final SourceProgram.Symbol symbol) { + var definition = symbol.definition(); + + if (program == null || definition == null) { + return; + } + + if (displayedFile != definition.file()) { + choosingFile = true; + files.setSelectedItem(definition.file()); + choosingFile = false; + rebuild(definition.file()); + } + + var line = program.line(definition.file(), definition.line()); + + if (line == null) { + return; + } + + selected = line; + + try { + var start = listing.getLineStartOffset(definition.line() - 1); + var end = listing.getLineEndOffset(definition.line() - 1); + var source = listing.getText(start, end - start); + var column = source.indexOf(symbol.name()); + var symbolStart = column < 0 ? start : start + column; + var symbolEnd = column < 0 ? start : symbolStart + symbol.name().length(); + + listing.requestFocusInWindow(); + listing.select(symbolStart, symbolEnd); + + var shape = listing.modelToView2D(symbolStart); + + if (shape != null) { + var bounds = shape.getBounds(); + var visible = listing.getVisibleRect(); + + bounds.grow(0, Math.max(0, visible.height / 3)); + listing.scrollRectToVisible(bounds); + } + } catch (BadLocationException ignored) { + // A changed source may no longer have the definition line recorded by the build. + } + } + + private final class Mouse extends MouseAdapter { + @Override + public void mouseClicked(final MouseEvent event) { + if (!SwingUtilities.isLeftMouseButton(event)) { + return; + } + + if ((event.getModifiersEx() + & (InputEvent.META_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)) != 0) { + var symbol = symbolAt(event.getPoint()); + + if (symbol != null && symbol.definition() != null) { + goToDefinition(symbol); + event.consume(); + } + + return; + } + + if (event.getClickCount() == 2) { + var line = lineAt(event.getPoint()); + + if (line != null && line.hasCode()) { + actions.toggleBreakpoint(line); + } + } + } + } + + private final class GutterClicks implements IconRowListener { + @Override + public void bookmarkAdded(final IconRowEvent event) { + } + + @Override + public void bookmarkRemoved(final IconRowEvent event) { + } + + @Override + public void mouseClicked(final IconRowEvent event, final MouseEvent mouse) { + var line = line(event.getLine()); + + if (SwingUtilities.isLeftMouseButton(mouse) && line != null && line.hasCode()) { + selected = line; + actions.toggleBreakpoint(line); + event.consume(); + } + } + } + + private final class Listing extends RSyntaxTextArea { + private JMenuItem toggle; + private JMenuItem runTo; + private JMenuItem definition; + private JMenuItem disassembly; + + @Override + public String getToolTipText(final MouseEvent event) { + var line = lineAt(event.getPoint()); + var symbol = symbolAt(event.getPoint()); + + return symbol != null ? symbolTooltip(symbol) + : line == null || !line.hasCode() ? null : rangeTooltip(line); + } + + @Override + protected JPopupMenu createPopupMenu() { + var menu = super.createPopupMenu(); + + menu.addSeparator(); + + toggle = new JMenuItem("Set Breakpoint"); + toggle.addActionListener(ignored -> withSelected(actions::toggleBreakpoint)); + menu.add(toggle); + + runTo = new JMenuItem("Run to Line"); + runTo.addActionListener(ignored -> withSelected(actions::runTo)); + menu.add(runTo); + + definition = new JMenuItem("Go to Definition"); + definition.addActionListener(ignored -> { + var symbol = symbolAtCaret(); + + if (symbol != null) { + goToDefinition(symbol); + } + }); + menu.add(definition); + + disassembly = new JMenuItem("Show in Disassembly"); + disassembly.addActionListener(ignored -> withSelected(actions::showInDisassembly)); + menu.add(disassembly); + + return menu; + } + + @Override + protected void configurePopupMenu(final JPopupMenu menu) { + super.configurePopupMenu(menu); + + var line = lineAtCaret(); + var enabled = line != null && line.hasCode(); + var symbol = symbolAtCaret(); + + toggle.setText(line != null && hasBreakpoint(line) + ? "Remove Breakpoint" : "Set Breakpoint"); + toggle.setEnabled(enabled); + runTo.setEnabled(enabled); + definition.setEnabled(symbol != null && symbol.definition() != null); + disassembly.setEnabled(enabled); + } + + @Override + protected void processMouseEvent(final MouseEvent event) { + if (event.isPopupTrigger()) { + var line = lineAt(event.getPoint()); + + if (line != null) { + selected = line; + setCaretPosition(viewToModel2D(event.getPoint())); + } + } + + super.processMouseEvent(event); + } + + private void withSelected( + final java.util.function.Consumer action) { + var line = selectedLine(); + + if (line != null && line.hasCode()) { + action.accept(line); + } + } + } + + /** One gutter slot that can show a breakpoint, the PC arrow, or both without overlap. */ + private record MarkerIcon(boolean breakpoint, boolean current) implements Icon { + private static final int WIDTH = 24; + private static final int HEIGHT = 14; + + @Override + public int getIconWidth() { + return WIDTH; + } + + @Override + public int getIconHeight() { + return HEIGHT; + } + + @Override + public void paintIcon( + final Component component, final Graphics graphics, final int x, final int y) { + var g = (Graphics2D) graphics.create(); + + try { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + if (breakpoint) { + g.setColor(Theme.breakpoint()); + g.fillOval(x + 2, y + 3, 9, 9); + } + + if (current) { + g.setColor(Theme.accent()); + g.fillPolygon( + new int[]{x + 14, x + 22, x + 14}, + new int[]{y + 2, y + 7, y + 12}, + 3); + } + } finally { + g.dispose(); + } + } + } +} diff --git a/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/SourceProgram.java b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/SourceProgram.java new file mode 100644 index 0000000..de7895a --- /dev/null +++ b/mynes-desktop/src/main/java/com/github/dimiro1/mynes/ui/debugger/SourceProgram.java @@ -0,0 +1,261 @@ +package com.github.dimiro1.mynes.ui.debugger; + +import org.jetbrains.annotations.Nullable; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Source, symbols and their places in one particular program ROM. + *

+ * Nothing here is ca65-shaped. The parser turns its files, lines, spans and segments into the two + * questions the window asks: which source line owns this byte of PRG ROM, and which bytes did this + * source line emit. Keeping that seam clean is what leaves room for another assembler later. + */ +final class SourceProgram { + record SourceFile( + int id, + String recordedPath, + @Nullable Path path, + List text, + boolean stale) { + + String displayName() { + if (path != null && path.getFileName() != null) { + return path.getFileName().toString(); + } + + var recorded = Path.of(recordedPath); + + return recorded.getFileName() == null ? recordedPath : recorded.getFileName().toString(); + } + + @Override + public String toString() { + return displayName() + (path == null ? " (missing)" : stale ? " (changed)" : ""); + } + } + + /** + * One contiguous range a source line emitted. + * + * @param prgOffset its stable place in the cartridge's program ROM. + * @param cpuAddress where the linker intended it to run; a banked mapper may show it elsewhere. + * @param size how many bytes came from the line. + */ + record Range(int prgOffset, int cpuAddress, int size) { + boolean contains(final int offset) { + return offset >= prgOffset && offset < prgOffset + size; + } + } + + record SourceLine(SourceFile file, int number, String text, List ranges) { + /** Every place execution may enter for this line, in PRG order and only once. */ + Set breakpointOffsets() { + var offsets = new LinkedHashSet(); + + ranges.forEach(range -> offsets.add(range.prgOffset())); + + return Collections.unmodifiableSet(offsets); + } + + boolean hasCode() { + return !ranges.isEmpty(); + } + + String location() { + return file.displayName() + ":" + number; + } + } + + record Location(SourceFile file, int line) { + String displayName() { + return file.displayName() + ":" + line; + } + } + + record Symbol( + String name, + String kind, + int value, + @Nullable Integer prgOffset, + @Nullable Location definition, + List references) { + } + + private record FileLine(int file, int line) { + } + + private final Path debugFile; + private final List files; + private final Map lines; + private final SourceLine[] lineAtPRG; + private final Map> symbolsAtPRG; + private final Map> symbolsAtAddress; + private final Map> symbolsByName; + private final Map>> symbolsBySourceLine; + private final List warnings; + + SourceProgram( + final Path debugFile, + final List files, + final Map>> ranges, + final List preferredLines, + final List symbols, + final int prgBytes, + final List warnings) { + + this.debugFile = debugFile; + this.files = List.copyOf(files); + this.warnings = List.copyOf(warnings); + this.lines = new LinkedHashMap<>(); + this.lineAtPRG = new SourceLine[prgBytes]; + this.symbolsAtPRG = new LinkedHashMap<>(); + this.symbolsAtAddress = new LinkedHashMap<>(); + this.symbolsByName = new LinkedHashMap<>(); + this.symbolsBySourceLine = new LinkedHashMap<>(); + + for (var file : files) { + var byLine = ranges.getOrDefault(file.id(), Map.of()); + var count = Math.max( + file.text().size(), + byLine.keySet().stream().mapToInt(Integer::intValue).max().orElse(0)); + + for (var number = 1; number <= count; number++) { + var text = number <= file.text().size() ? file.text().get(number - 1) : ""; + var sourceLine = new SourceLine( + file, + number, + text, + List.copyOf(byLine.getOrDefault(number, List.of()))); + + lines.put(new FileLine(file.id(), number), sourceLine); + } + } + + // Direct assembler/C locations precede macro-definition locations in this list. First wins + // where both own the same generated bytes, so stopping on a macro expansion lands on the + // call somebody wrote rather than on the macro body shared by every call. + for (var preferred : preferredLines) { + var sourceLine = line(preferred.file(), preferred.number()); + + if (sourceLine == null) { + continue; + } + + for (var range : preferred.ranges()) { + var until = Math.min(lineAtPRG.length, range.prgOffset() + range.size()); + + for (var offset = Math.max(0, range.prgOffset()); offset < until; offset++) { + if (lineAtPRG[offset] == null) { + lineAtPRG[offset] = sourceLine; + } + } + } + } + + for (var symbol : symbols) { + symbolsAtAddress.computeIfAbsent(symbol.value() & 0xFFFF, ignored -> new ArrayList<>()) + .add(symbol); + symbolsByName.computeIfAbsent(symbol.name(), ignored -> new ArrayList<>()).add(symbol); + + if (symbol.prgOffset() != null) { + symbolsAtPRG.computeIfAbsent(symbol.prgOffset(), ignored -> new ArrayList<>()) + .add(symbol); + } + + if (symbol.definition() != null) { + addSourceSymbol(symbol.definition(), symbol); + } + + symbol.references().forEach(reference -> addSourceSymbol(reference, symbol)); + } + } + + Path debugFile() { + return debugFile; + } + + List files() { + return files; + } + + List warnings() { + return warnings; + } + + boolean hasMissingFiles() { + return files.stream().anyMatch(file -> file.path() == null); + } + + @Nullable SourceLine line(final SourceFile file, final int number) { + return lines.get(new FileLine(file.id(), number)); + } + + @Nullable SourceLine lineAt(final int prgOffset) { + return prgOffset >= 0 && prgOffset < lineAtPRG.length ? lineAtPRG[prgOffset] : null; + } + + List symbolsAt(final int prgOffset, final int cpuAddress) { + var physical = symbolsAtPRG.get(prgOffset); + + return physical != null ? List.copyOf(physical) + : List.copyOf(symbolsAtAddress.getOrDefault(cpuAddress & 0xFFFF, List.of())); + } + + @Nullable String firstSymbolAt(final int prgOffset, final int cpuAddress) { + var found = symbolsAt(prgOffset, cpuAddress); + + return found.isEmpty() ? null : found.getFirst().name(); + } + + /** + * The symbol this spelling means on this source line. The .dbg reference records disambiguate + * cheap local labels such as {@code @done}; a globally unique name is the useful fallback for + * lines produced through macros that did not receive a direct reference record. + */ + @Nullable Symbol symbolAt(final SourceLine line, final String name) { + var onLine = symbolsBySourceLine + .getOrDefault(new FileLine(line.file().id(), line.number()), Map.of()) + .getOrDefault(name, List.of()); + + if (!onLine.isEmpty()) { + return onLine.getFirst(); + } + + var named = symbolsByName.getOrDefault(name, List.of()); + + return named.size() == 1 ? named.getFirst() : null; + } + + @Nullable SourceLine lineForBreakpoint(final int prgOffset) { + var exact = lineAt(prgOffset); + + if (exact != null && exact.breakpointOffsets().contains(prgOffset)) { + return exact; + } + + for (var sourceLine : lines.values()) { + if (sourceLine.breakpointOffsets().contains(prgOffset)) { + return sourceLine; + } + } + + return null; + } + + private void addSourceSymbol(final Location location, final Symbol symbol) { + symbolsBySourceLine + .computeIfAbsent( + new FileLine(location.file().id(), location.line()), + ignored -> new LinkedHashMap<>()) + .computeIfAbsent(symbol.name(), ignored -> new ArrayList<>()) + .add(symbol); + } +} diff --git a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/Cc65DebugInfoTests.java b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/Cc65DebugInfoTests.java new file mode 100644 index 0000000..3f2da1d --- /dev/null +++ b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/Cc65DebugInfoTests.java @@ -0,0 +1,233 @@ +package com.github.dimiro1.mynes.ui.debugger; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class Cc65DebugInfoTests { + @TempDir + private Path directory; + + @Test + void linesAndSymbolsAreMappedThroughSpansAndOutputOffsets() throws Exception { + var source = directory.resolve("game.s"); + var rom = directory.resolve("game.nes"); + var debug = directory.resolve("game.dbg"); + var sourceText = """ + reset: + sei + loop: + inc counter + jmp loop + """; + var prg = new byte[0x4000]; + var image = new byte[16 + prg.length + 0x2000]; + + prg[0] = 0x78; + prg[1] = (byte) 0xE6; + prg[2] = 0; + prg[3] = 0x4C; + System.arraycopy(prg, 0, image, 16, prg.length); + + Files.writeString(source, sourceText); + Files.write(rom, image); + Files.writeString(debug, debug(source, rom)); + + var program = Cc65DebugInfo.read(debug, prg, null); + + assertEquals("game.s", program.files().getFirst().displayName()); + assertEquals(2, program.lineAt(0).number()); + assertEquals(4, program.lineAt(1).number()); + assertEquals(java.util.Set.of(1), program.lineAt(1).breakpointOffsets()); + assertEquals("reset", program.firstSymbolAt(0, 0xC000)); + assertEquals("loop", program.firstSymbolAt(1, 0xC001)); + var reset = program.symbolAt(program.lineAt(1), "reset"); + + assertNotNull(reset); + assertNotNull(reset.definition()); + assertEquals("game.s:2", reset.definition().displayName()); + assertTrue(program.warnings().isEmpty()); + } + + @Test + void theMacroCallWinsOverTheMacroDefinitionForTheSameBytes() throws Exception { + var source = directory.resolve("game.s"); + var rom = directory.resolve("game.nes"); + var debug = directory.resolve("game.dbg"); + var text = "macro body\ncall macro\n"; + var prg = new byte[0x4000]; + var image = new byte[16 + prg.length]; + + Files.writeString(source, text); + System.arraycopy(prg, 0, image, 16, prg.length); + Files.write(rom, image); + Files.writeString(debug, """ + version\tmajor=2,minor=0 + file\tid=0,name="%s",size=%d,mtime=0 + line\tid=0,file=0,line=1,type=2,count=1,span=0 + line\tid=1,file=0,line=2,span=0 + seg\tid=0,name="CODE",start=0xC000,size=1,addrsize=absolute,type=ro,oname="%s",ooffs=16 + span\tid=0,seg=0,start=0,size=1 + """.formatted(source, Files.size(source), rom)); + + var program = Cc65DebugInfo.read(debug, prg, null); + + assertEquals(2, program.lineAt(0).number()); + } + + @Test + void aMovedSourceCanBeFoundUnderTheRootTheUserChooses() throws Exception { + var root = Files.createDirectories(directory.resolve("checkout/src")); + var source = root.resolve("game.s"); + var debug = directory.resolve("game.dbg"); + var rom = directory.resolve("game.nes"); + var prg = new byte[0x4000]; + var image = new byte[16 + prg.length]; + + Files.writeString(source, "sei\n"); + System.arraycopy(prg, 0, image, 16, prg.length); + Files.write(rom, image); + Files.writeString(debug, debugRecord("/old/computer/project/src/game.s", source, rom)); + + var withoutRoot = Cc65DebugInfo.read(debug, prg, null); + var withRoot = Cc65DebugInfo.read(debug, prg, directory.resolve("checkout")); + + assertTrue(withoutRoot.hasMissingFiles()); + assertFalse(withRoot.hasMissingFiles()); + assertEquals(source, withRoot.files().getFirst().path()); + } + + @Test + void aSourceFolderAlsoFindsGeneratedIncludesInASiblingBuildFolder() throws Exception { + var project = Files.createDirectories(directory.resolve("checkout")); + var sources = Files.createDirectories(project.resolve("src")); + var build = Files.createDirectories(project.resolve("build")); + var source = sources.resolve("main.s"); + var generated = build.resolve("tiles.inc"); + var binary = build.resolve("game.chr"); + var rom = build.resolve("game.nes"); + var debug = build.resolve("game.dbg"); + var prg = new byte[0x4000]; + var image = new byte[16 + prg.length]; + + Files.writeString(source, "sei\n"); + Files.writeString(generated, ".byte 0\n"); + Files.write(binary, new byte[]{0, (byte) 0xFF, 0}); + System.arraycopy(prg, 0, image, 16, prg.length); + Files.write(rom, image); + Files.writeString(debug, """ + version\tmajor=2,minor=0 + file\tid=0,name="src/main.s",size=%d,mtime=0 + file\tid=1,name="src/../build/tiles.inc",size=%d,mtime=0 + file\tid=2,name="src/../build/game.chr",size=%d,mtime=0 + line\tid=0,file=0,line=1,span=0 + line\tid=1,file=1,line=1 + seg\tid=0,name="CODE",start=0xC000,size=1,addrsize=absolute,type=ro,oname="build/game.nes",ooffs=16 + span\tid=0,seg=0,start=0,size=1 + """.formatted(Files.size(source), Files.size(generated), Files.size(binary))); + + var program = Cc65DebugInfo.read(debug, prg, sources); + + assertFalse(program.hasMissingFiles()); + assertEquals(2, program.files().size(), "binary linker inputs are not source files"); + assertEquals(source, program.files().get(0).path()); + assertEquals(generated, program.files().get(1).path()); + } + + @Test + void changedSourceIsMarkedStale() throws Exception { + var source = directory.resolve("game.s"); + var debug = directory.resolve("game.dbg"); + var rom = directory.resolve("game.nes"); + var prg = new byte[0x4000]; + var image = new byte[16 + prg.length]; + + Files.writeString(source, "sei\n"); + System.arraycopy(prg, 0, image, 16, prg.length); + Files.write(rom, image); + Files.writeString(debug, debugRecord(source.toString(), source, rom)); + Files.writeString(source, "sei\nnop\n"); + Files.setLastModifiedTime(source, FileTime.fromMillis(System.currentTimeMillis() + 10_000)); + + var program = Cc65DebugInfo.read(debug, prg, null); + + assertTrue(program.files().getFirst().stale()); + assertFalse(program.warnings().isEmpty()); + } + + @Test + void anOffsetWithNoLineOrSymbolSaysNothing() throws Exception { + var source = directory.resolve("game.s"); + var rom = directory.resolve("game.nes"); + var debug = directory.resolve("game.dbg"); + var prg = new byte[0x4000]; + var image = new byte[16 + prg.length]; + + Files.writeString(source, "sei\n"); + System.arraycopy(prg, 0, image, 16, prg.length); + Files.write(rom, image); + Files.writeString(debug, debugRecord(source.toString(), source, rom)); + + var program = Cc65DebugInfo.read(debug, prg, null); + + assertNull(program.lineAt(100)); + assertNull(program.firstSymbolAt(100, 0xC064)); + assertNotNull(program.lineAt(0)); + } + + @Test + void aQuotedWindowsPathKeepsItsBackslashSeparators() throws Exception { + var debug = directory.resolve("game.dbg"); + var recorded = "C:\\Users\\builder\\src\\game.s"; + + Files.writeString(debug, """ + version\tmajor=2,minor=0 + file\tid=0,name="%s",size=1,mtime=0 + line\tid=0,file=0,line=1 + """.formatted(recorded)); + + var program = Cc65DebugInfo.read(debug, new byte[0x4000], null); + + assertEquals(recorded, program.files().getFirst().recordedPath()); + } + + private String debug(final Path source, final Path rom) throws Exception { + return """ + version\tmajor=2,minor=0 + file\tid=0,name="%s",size=%d,mtime=0 + line\tid=0,file=0,line=2,span=0 + line\tid=1,file=0,line=4,span=1 + line\tid=2,file=0,line=5,span=2 + seg\tid=0,name="CODE",start=0xC000,size=6,addrsize=absolute,type=ro,oname="%s",ooffs=16 + span\tid=0,seg=0,start=0,size=1 + span\tid=1,seg=0,start=1,size=2 + span\tid=2,seg=0,start=3,size=3 + sym\tid=0,name="reset",addrsize=absolute,val=0xC000,seg=0,type=lab,def=0,ref=1 + sym\tid=1,name="loop",addrsize=absolute,val=0xC001,seg=0,type=lab + """.formatted(source, Files.size(source), rom); + } + + private String debugRecord(final String recorded, final Path source, final Path rom) + throws Exception { + return """ + version\tmajor=2,minor=0 + file\tid=0,name="%s",size=%d,mtime=%d + line\tid=0,file=0,line=1,span=0 + seg\tid=0,name="CODE",start=0xC000,size=1,addrsize=absolute,type=ro,oname="%s",ooffs=16 + span\tid=0,seg=0,start=0,size=1 + """.formatted( + recorded, + Files.size(source), + Files.getLastModifiedTime(source).toMillis() / 1_000, + rom); + } +} diff --git a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/MachineSnapshotTests.java b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/MachineSnapshotTests.java index 4f8a3c4..c5a7fe5 100644 --- a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/MachineSnapshotTests.java +++ b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/MachineSnapshotTests.java @@ -91,6 +91,17 @@ void itCarriesTheTrailSoTheListingHasHistory() { assertNotEquals(0, MachineSnapshot.of(nes, debugger).trail().length); } + @Test + void itCarriesThePhysicalProgramRomOffsetBehindTheCpuAddress() { + var snapshot = MachineSnapshot.of(nes, debugger); + + assertEquals(0, snapshot.prgOffset(0x8000)); + assertEquals(0, snapshot.prgOffset(0xC000), + "a 16KB NROM mirrors the same byte through both halves"); + assertEquals(0x2000, snapshot.prgOffset(0xA000)); + assertEquals(-1, snapshot.prgOffset(0x7FFF)); + } + /** * The pointer names the next free slot, so a byte pushed is one above it -- and the listing * shows the top first, because that is the order the bytes come off in. diff --git a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/SourceAssociationsTests.java b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/SourceAssociationsTests.java new file mode 100644 index 0000000..e443426 --- /dev/null +++ b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/SourceAssociationsTests.java @@ -0,0 +1,56 @@ +package com.github.dimiro1.mynes.ui.debugger; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class SourceAssociationsTests { + @TempDir + private Path directory; + + @Test + void anAssociationRoundTripsByCartridgeDigest() throws Exception { + var path = directory.resolve("debug-sources.properties"); + var debug = directory.resolve("build/game.dbg"); + var root = directory.resolve("checkout"); + var associations = SourceAssociations.load(path); + + associations.remember("abc123", debug, root); + + var loaded = SourceAssociations.load(path).get("abc123"); + + assertEquals(debug.toAbsolutePath(), loaded.debugFile()); + assertEquals(root.toAbsolutePath(), loaded.sourceRoot()); + } + + @Test + void forgettingRemovesOnlyThatCartridge() throws Exception { + var path = directory.resolve("debug-sources.properties"); + var associations = SourceAssociations.load(path); + + associations.remember("one", directory.resolve("one.dbg"), null); + associations.remember("two", directory.resolve("two.dbg"), null); + associations.forget("one"); + + var loaded = SourceAssociations.load(path); + + assertNull(loaded.get("one")); + assertEquals( + directory.resolve("two.dbg").toAbsolutePath(), + loaded.get("two").debugFile()); + } + + @Test + void aBrokenFileBehavesLikeAnEmptyOne() throws Exception { + var path = directory.resolve("debug-sources.properties"); + + Files.writeString(path, "\\uNOTHEX=broken"); + + assertNull(SourceAssociations.load(path).get("anything")); + } +} diff --git a/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/SourcePanelTests.java b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/SourcePanelTests.java new file mode 100644 index 0000000..5c08d3f --- /dev/null +++ b/mynes-desktop/src/test/java/com/github/dimiro1/mynes/ui/debugger/SourcePanelTests.java @@ -0,0 +1,85 @@ +package com.github.dimiro1.mynes.ui.debugger; + +import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; +import org.fife.ui.rsyntaxtextarea.SyntaxConstants; +import org.junit.jupiter.api.Test; + +import java.awt.Component; +import java.awt.Container; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** Exercises the source component in each debugger state without opening a window. */ +class SourcePanelTests { + @Test + void sourceCurrentLineAndBreakpointRenderWithoutAWindow() { + var file = new SourceProgram.SourceFile( + 0, + "src/game.s", + Path.of("src/game.s"), + List.of("reset:", " sei", " jmp reset"), + false); + var first = new SourceProgram.Range(0, 0xC000, 1); + var second = new SourceProgram.Range(1, 0xC001, 3); + var program = new SourceProgram( + Path.of("game.dbg"), + List.of(file), + Map.of(0, Map.of(2, List.of(first), 3, List.of(second))), + List.of( + new SourceProgram.SourceLine(file, 2, "", List.of(first)), + new SourceProgram.SourceLine(file, 3, "", List.of(second))), + List.of(), + 0x4000, + List.of()); + var panel = new SourcePanel(new NoActions()); + + panel.show(program, program.lineAt(0), Set.of(0)); + + var listing = component(panel, RSyntaxTextArea.class); + + assertNotNull(listing); + assertEquals(SyntaxConstants.SYNTAX_STYLE_ASSEMBLER_6502, + listing.getSyntaxEditingStyle()); + assertEquals(String.join("\n", file.text()), listing.getText()); + assertNotNull(listing.getTokenListForLine(1)); + + panel.clearMachine(); + panel.setBreakpoints(Set.of()); + + panel.detach(); + assertEquals("", listing.getText()); + } + + private static T component( + final Container parent, final Class type) { + for (var child : parent.getComponents()) { + if (type.isInstance(child)) { + return type.cast(child); + } + + if (child instanceof Container container) { + var nested = component(container, type); + + if (nested != null) { + return nested; + } + } + } + + return null; + } + + private static final class NoActions implements SourcePanel.Actions { + @Override public void attach() { } + @Override public void locateSources() { } + @Override public void detach() { } + @Override public void toggleBreakpoint(final SourceProgram.SourceLine line) { } + @Override public void runTo(final SourceProgram.SourceLine line) { } + @Override public void showInDisassembly(final SourceProgram.SourceLine line) { } + } +} diff --git a/pom.xml b/pom.xml index 720690e..a2fa9c9 100644 --- a/pom.xml +++ b/pom.xml @@ -47,6 +47,7 @@ 3.7.2 11.4.3 + 4.0.1 26.1.0 2.22.1 6.1.3 @@ -100,6 +101,11 @@ miglayout-swing ${miglayout.version} + + com.fifesoft + rsyntaxtextarea + ${rsyntaxtextarea.version} +