114 lines
6.6 KiB
Swift
114 lines
6.6 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import Foundation
|
|
|
|
/// Immutable LWASM listing. Source filenames are descriptive metadata only;
|
|
/// importing a listing never opens those paths or loads its bytes into the CPU.
|
|
struct DebugSourceListing: Sendable {
|
|
struct Line: Identifiable, Sendable {
|
|
let id: Int
|
|
let text: String
|
|
let sourceFile: String?
|
|
let sourceLine: Int?
|
|
let address: UInt16?
|
|
let bytes: [UInt8]
|
|
var location: String {
|
|
guard let sourceLine else { return "Listing line \(id + 1)" }
|
|
return "\(sourceFile ?? "Source"):\(sourceLine)"
|
|
}
|
|
}
|
|
enum ImportError: LocalizedError {
|
|
case tooLarge, encoding, format, notFile, relocatable
|
|
var errorDescription: String? {
|
|
switch self {
|
|
case .tooLarge: return "Use a listing smaller than 8 MB, with at most 50,000 lines and 4,096 characters per line."
|
|
case .encoding: return "The listing must be UTF-8 or BOM-marked UTF-16 text."
|
|
case .format: return "No addressed LWASM byte lines were found. Generate a listing with LWASM --list and use final logical CPU addresses."
|
|
case .notFile: return "Choose a regular listing file."
|
|
case .relocatable: return "This listing uses relocatable sections. Its addresses need a linker map before they can match CPU addresses. Open a final absolute LWASM listing; CMOC/link-map integration is planned separately."
|
|
}
|
|
}
|
|
}
|
|
static let maximumBytes = 8 * 1024 * 1024
|
|
let name: String
|
|
let lines: [Line]
|
|
let byAddress: [UInt16: [Int]]
|
|
var addressedLineCount: Int { byAddress.values.reduce(0) { $0 + $1.count } }
|
|
|
|
static func read(_ url: URL) throws -> Self {
|
|
let access = url.startAccessingSecurityScopedResource()
|
|
defer { if access { url.stopAccessingSecurityScopedResource() } }
|
|
guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw ImportError.notFile }
|
|
let file = try FileHandle(forReadingFrom: url)
|
|
defer { try? file.close() }
|
|
let data = try file.read(upToCount: maximumBytes + 1) ?? Data()
|
|
return try parse(data, name: url.lastPathComponent)
|
|
}
|
|
|
|
static func parse(_ data: Data, name: String) throws -> Self {
|
|
guard data.count <= maximumBytes else { throw ImportError.tooLarge }
|
|
let encoding: String.Encoding = data.starts(with: [0xff, 0xfe]) || data.starts(with: [0xfe, 0xff]) ? .utf16 : .utf8
|
|
guard var text = String(data: data, encoding: encoding), !text.contains("\0") else { throw ImportError.encoding }
|
|
if text.hasPrefix("\u{feff}") { text.removeFirst() }
|
|
text = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
|
|
let rawLines = text.split(separator: "\n", omittingEmptySubsequences: false)
|
|
guard rawLines.count <= 50_000 else { throw ImportError.tooLarge }
|
|
// LWASM list.c: address/marker + 16 byte digits + space, followed by
|
|
// (17-column filename):line or --list-nofiles' decimal line number.
|
|
// Cycle-count columns stay in the displayed text, without interpretation.
|
|
let metadata = try NSRegularExpression(pattern: #"^(?:\((.{0,17})\):([0-9]{5,})|([0-9]{5,})) (.*)$"#)
|
|
let section = try NSRegularExpression(pattern: #"(?i)^\s*(?:[a-z_.$@?][a-z0-9_.$@?]*\s+)?(?:section|endsection)\b"#)
|
|
var lines: [Line] = []
|
|
var addresses: [UInt16: [Int]] = [:]
|
|
for (index, raw) in rawLines.enumerated() {
|
|
guard raw.count <= 4096 else { throw ImportError.tooLarge }
|
|
let string = String(raw), octets = Array(string.utf8)
|
|
var sourceFile: String?, sourceLine: Int?, address: UInt16?
|
|
var sourceText = string, bytes: [UInt8] = []
|
|
if octets.count >= 22, octets[21] == 32 {
|
|
let remainder = String(decoding: octets.dropFirst(22), as: UTF8.self)
|
|
let ns = remainder as NSString
|
|
if let match = metadata.firstMatch(in: remainder, range: NSRange(location: 0, length: ns.length)) {
|
|
func group(_ i: Int) -> String? { match.range(at: i).location == NSNotFound ? nil : ns.substring(with: match.range(at: i)) }
|
|
sourceFile = group(1)?.trimmingCharacters(in: .whitespaces)
|
|
sourceLine = (group(2) ?? group(3)).flatMap(Int.init)
|
|
sourceText = group(4) ?? ""
|
|
if section.firstMatch(in: sourceText, range: NSRange(sourceText.startIndex..., in: sourceText)) != nil {
|
|
throw ImportError.relocatable
|
|
}
|
|
let digits = String(decoding: octets[5..<21], as: UTF8.self).trimmingCharacters(in: .whitespaces)
|
|
// A space denotes a logical address. '.' (OS-9 data) and
|
|
// 's' (structure offset) are not CPU-code associations.
|
|
if octets[4] == 32, digits.count > 0, digits.count % 2 == 0,
|
|
digits.allSatisfy({ $0.isASCII && $0.isHexDigit }),
|
|
octets.prefix(4).allSatisfy({ (48...57).contains($0) || (65...70).contains($0) || (97...102).contains($0) }),
|
|
let value = UInt16(String(decoding: octets.prefix(4), as: UTF8.self), radix: 16) {
|
|
address = value
|
|
let chars = Array(digits)
|
|
bytes = stride(from: 0, to: chars.count, by: 2).compactMap { UInt8(String(chars[$0...($0 + 1)]), radix: 16) }
|
|
addresses[value, default: []].append(index)
|
|
}
|
|
}
|
|
}
|
|
lines.append(Line(id: index, text: sourceText, sourceFile: sourceFile, sourceLine: sourceLine, address: address, bytes: bytes))
|
|
}
|
|
guard !addresses.isEmpty else { throw ImportError.format }
|
|
return Self(name: name, lines: lines, byAddress: addresses)
|
|
}
|
|
|
|
func line(at address: UInt16, preferring selected: Int?) -> Int? {
|
|
guard let candidates = byAddress[address] else { return nil }
|
|
return selected.flatMap { candidates.contains($0) ? $0 : nil } ?? candidates.first
|
|
}
|
|
|
|
func find(_ query: String, after selected: Int?) -> Int? {
|
|
guard !query.isEmpty else { return nil }
|
|
let start = selected.map { ($0 + 1) % lines.count } ?? 0
|
|
for offset in 0..<lines.count {
|
|
let index = (start + offset) % lines.count
|
|
let line = lines[index]
|
|
if line.text.localizedCaseInsensitiveContains(query) || line.location.localizedCaseInsensitiveContains(query) { return index }
|
|
}
|
|
return nil
|
|
}
|
|
}
|