// SPDX-License-Identifier: GPL-3.0-or-later import XCTest import AppKit final class DebugSourceTests: XCTestCase { private func row(_ address: String = "8000", _ bytes: String = "7C4000", _ source: String = "loop inc $4000", file: String = "hello.asm", number: Int = 1, marker: String = " ") -> String { address + marker + bytes.padding(toLength: 16, withPad: " ", startingAt: 0) + " (" + String(repeating: " ", count: max(0, 17 - file.count)) + file + String(format: "):%05d ", number) + source } private func parse(_ text: String) throws -> DebugSourceListing { try .parse(Data(text.utf8), name: "test.lst") } func testLWASMMetadataSourceAndExactAddressAssociation() throws { let listing = try parse(row("0000", "12", "start nop", number: 1) + "\n" + row("0001", "20FD", " bra start", file: "include.asm", number: 42)) XCTAssertEqual(listing.lines.count, 2) XCTAssertEqual(listing.lines[0].address, 0) XCTAssertEqual(listing.lines[0].bytes, [0x12]) XCTAssertEqual(listing.lines[1].location, "include.asm:42") XCTAssertTrue(listing.lines[1].text.contains("bra start")) XCTAssertEqual(listing.line(at: 0, preferring: nil), 0, "Zero address and first line are valid") XCTAssertNil(listing.line(at: 2, preferring: nil), "Never guess source by nearest address") } func testDuplicateAddressesRemainVisibleAndSearchWraps() throws { let listing = try parse(row("8000", "7C4000", "first nop") + "\n" + row("8000", "7C4000", "second nop") + "\n" + row("8001", "12", "third nop")) XCTAssertEqual(listing.byAddress[0x8000], [0, 1]) XCTAssertEqual(listing.line(at: 0x8000, preferring: 1), 1) XCTAssertEqual(listing.line(at: 0x8000, preferring: 2), 0) XCTAssertEqual(listing.find("FIRST", after: 2), 0) XCTAssertEqual(listing.find("hello.asm", after: 0), 1) XCTAssertNil(listing.find("missing", after: nil)) } func testDirectivesContinuationAndMalformedAddressesDoNotCreateBreakpoints() throws { let listing = try parse([ row(), row("8003", "", "org $8003"), row("0020", "12", "data fcb $12", marker: "."), row("0010", "", "field rmb 1", marker: "s"), row("GGGG", "12"), row("8004", "123"), row("8005", "????"), " 0102030405060708", "Symbol: DEAD = 1234", "80001234 plain text" ].joined(separator: "\n")) XCTAssertEqual(listing.addressedLineCount, 1) XCTAssertTrue(listing.lines.dropFirst().allSatisfy { $0.address == nil }) XCTAssertEqual(listing.lines[7].text, " 0102030405060708", "Preserve unassociated continuation text") } func testNoFilenameCycleColumnsAndTextEncodings() throws { let noFile = "8000 1234 00001 [4] nop" let listing = try parse(noFile) XCTAssertEqual(listing.lines[0].sourceLine, 1) XCTAssertNil(listing.lines[0].sourceFile) XCTAssertEqual(listing.lines[0].bytes, [0x12, 0x34]) XCTAssertTrue(listing.lines[0].text.contains("[4]")) let text = "\u{feff}" + row("8000", "7C4000", "* café") + "\r\n" + row("8003", "12") + "\r" XCTAssertEqual(try parse(text).addressedLineCount, 2) XCTAssertEqual(try DebugSourceListing.parse(XCTUnwrap(text.data(using: .utf16)), name: "utf16.lst").addressedLineCount, 2) XCTAssertThrowsError(try DebugSourceListing.parse(Data([0xff, 0, 1]), name: "bad.lst")) } func testImportBoundsAndUnsupportedFilesAreRejected() throws { XCTAssertThrowsError(try parse("8000 is ordinary text, not a listing")) XCTAssertThrowsError(try parse(row() + "\n" + String(repeating: "x", count: 4097))) XCTAssertThrowsError(try parse(row() + String(repeating: "\n", count: 50_001))) XCTAssertThrowsError(try DebugSourceListing.parse(Data(repeating: 32, count: DebugSourceListing.maximumBytes + 1), name: "huge.lst")) XCTAssertThrowsError(try DebugSourceListing.read(FileManager.default.temporaryDirectory)) XCTAssertThrowsError(try parse(row(" ", "", " SECTION code") + "\n" + row())) { error in XCTAssertTrue(error.localizedDescription.contains("linker map")) } XCTAssertEqual(try parse(row("8000", "12", "* SECTION is only a comment")).addressedLineCount, 1) } func testFilenamePaddingUsesUTF8Bytes() throws { let filename = "café.asm" let padded = String(repeating: " ", count: 17 - filename.utf8.count) + filename let listing = try parse("8000 12 (" + padded + "):00001 nop") XCTAssertEqual(listing.lines[0].sourceFile, filename) XCTAssertEqual(listing.lines[0].address, 0x8000) } func testAuthenticLWASMFixture() throws { let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() let listing = try DebugSourceListing.read(root.appendingPathComponent("platforms/macos/Tests/Fixtures/debugger-source.lst")) XCTAssertEqual(listing.addressedLineCount, 6) XCTAssertEqual(listing.byAddress[0x8000], [4]) XCTAssertEqual(listing.lines[4].bytes, [0x7c, 0x40, 0x00]) XCTAssertEqual(listing.lines[4].sourceLine, 5) XCTAssertEqual(listing.byAddress[0], [13]) XCTAssertNil(listing.lines[10].address) } @MainActor func testSourceImportSearchNavigationFailureAndSharedBreakpointsPreserveMachine() async throws { _ = NSApplication.shared let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: folder) } let suite = "VCCSourceTests-" + UUID().uuidString let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } let machine = MachineModel(diskStore: .init(url: folder.appendingPathComponent("disks.json")), displayDefaults: defaults, inputStore: .init(url: folder.appendingPathComponent("input.json"))) let debugger = DebuggerModel(machine: machine) let polling = Task { await debugger.poll() } func until(_ condition: () -> Bool) async throws { for _ in 0..<500 { if condition() { return }; try await Task.sleep(nanoseconds: 10_000_000) } throw NSError(domain: "SourceTestTimeout", code: 1) } do { try await until { !machine.busy } machine.loadDiagnostic() try await until { debugger.snapshot?.machine.state == .paused && !machine.busy } let generation = debugger.snapshot?.machine.generation, cycles = debugger.snapshot?.machine.cycles, focus = machine.focusRequest let url = folder.appendingPathComponent("diagnostic.lst") try (row() + "\n" + row("8003", "20FB", " bra loop", number: 2)).write(to: url, atomically: true, encoding: .utf8) await debugger.loadListing(url) XCTAssertEqual(debugger.codePane, .source) XCTAssertEqual(debugger.currentSourceLine, 0) debugger.sourceSearch = "bra loop"; debugger.findSource() XCTAssertEqual(debugger.selectedSourceLine, 1); XCTAssertFalse(debugger.sourceFollowPC) debugger.toggleBreakpoint(at: 0x8003) try await until { debugger.breakpoints == [0x8003] && !debugger.commandPending } debugger.step() try await until { debugger.programCounter == 0x8003 && !debugger.commandPending } XCTAssertEqual(debugger.currentSourceLine, 1) debugger.showDisassembly(at: 0x8003) XCTAssertEqual(debugger.codePane, .disassembly) XCTAssertEqual(machine.focusRequest, focus) XCTAssertEqual(debugger.snapshot?.machine.generation, generation) XCTAssertGreaterThan(debugger.snapshot?.machine.cycles ?? 0, cycles ?? 0) let bad = folder.appendingPathComponent("bad.lst") try "invalid".write(to: bad, atomically: true, encoding: .utf8) await debugger.loadListing(bad) XCTAssertNotNil(debugger.sourceMessage); XCTAssertEqual(debugger.listing?.name, "diagnostic.lst") debugger.unloadListing() XCTAssertNil(debugger.listing); XCTAssertEqual(debugger.breakpoints, [0x8003]) XCTAssertEqual(machine.state, .paused) } catch { polling.cancel(); await polling.value await withCheckedContinuation { done in machine.shutdown { done.resume() } } throw error } polling.cancel(); await polling.value await withCheckedContinuation { done in machine.shutdown { done.resume() } } } }