// SPDX-License-Identifier: GPL-3.0-or-later import Foundation /// A build-produced declaration of unpacked code placement. Hashes bind this /// declaration to one retained build; object relocation replay and live physical /// RAM comparisons provide the independent byte checks before debugging. struct CMOCBankedDebugLayout: Sendable { struct File: Decodable, Sendable { let path: String; let sha256: String } struct Page: Decodable, Equatable, Sendable { let logicalPage: Int; let physicalPage: Int } struct CodeGuard: Equatable, Sendable { let address: UInt16; let bytes: [UInt8] } struct Framebuffer: Decodable, Equatable, Sendable { let id: String let physicalAddress: Int let mode: String var canvasBytes: Int? = nil var workerFields: [String: Any] { var fields: [String: Any] = ["id": id, "physical_address": physicalAddress, "mode": mode] if let canvasBytes { fields["canvas_bytes"] = canvasBytes } return fields } } struct Image: Decodable, Sendable { let path: String let logicalAddress: Int let offset: Int? let length: Int? } struct Module: Sendable { let id: String let sections: [String] let codeSections: [String] let logicalAddress: Int let bytes: [UInt8] let pages: [Page] let codeGuards: [CodeGuard] func physicalAddress(_ logical: Int) -> UInt32? { guard (0..<65536).contains(logical), let page = pages.first(where: { $0.logicalPage == logical / 8192 }) else { return nil } return UInt32(page.physicalPage * 8192 + logical % 8192) } func isMapped(physicalPages: [Int]) -> Bool { physicalPages.count == 8 && pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage } } } private struct ModuleRecord: Decodable { let id: String; let sections: [String]; let codeSections: [String]; let image: Image?; let pages: [Page] } private struct Manifest: Decodable { let version: Int; let entryPoint: Int let binary: File; let disk: File?; let linkMap: File let sources: [String: String]; let artifacts: [String: String] let modules: [ModuleRecord] let framebuffers: [Framebuffer]? } let entryPoint: UInt16 let binarySHA256: String let linkMap: Data let sourceHashes: [String: String] let artifactHashes: [String: String] let modules: [Module] var framebuffers: [Framebuffer] = [] func module(forSection name: String) -> Module? { modules.first { $0.sections.contains(name) } } func module(id: String) -> Module? { modules.first { $0.id == id } } static func parse(data: Data, directory: URL, sources: [String: Data], binary: Data, binaryPath: String, diskPath: String? = nil, allowedOutputs: [String]) throws -> Self { func fail(_ text: String) -> CMOCSourceMap.Failure { .invalid("banked manifest: " + text) } guard data.count <= 1024 * 1024 else { throw fail("manifest exceeds 1 MB.") } // Bound recursive decoding before handing untrusted JSON to Decodable. var pending: [(Any, Int)] = [(try JSONSerialization.jsonObject(with: data), 0)], nodes = 0 while let (value, depth) = pending.popLast() { nodes += 1 guard depth <= 16, nodes <= 30000 else { throw fail("manifest nesting or record limit exceeded.") } if let values = value as? [String: Any] { pending += values.values.map { ($0, depth + 1) } } if let values = value as? [Any] { pending += values.map { ($0, depth + 1) } } } let manifest = try JSONDecoder().decode(Manifest.self, from: data) guard manifest.version == 1, (0..<65536).contains(manifest.entryPoint), !manifest.modules.isEmpty, manifest.modules.count <= 256, manifest.artifacts.count <= 8192, sources.count <= 4096 else { throw fail("unsupported version or record count.") } func path(_ value: String) throws { guard !value.isEmpty, value.utf8.count <= 4096, !value.hasPrefix("/"), !value.contains("\\"), !value.contains("\0"), !value.split(separator: "/", omittingEmptySubsequences: false).contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }), (value as NSString).standardizingPath == value else { throw fail("paths must be canonical project-relative identities.") } } func hash(_ value: String) throws { guard value.count == 64, value.allSatisfy({ $0.isASCII && ($0.isNumber || ("a"..."f").contains(String($0))) }) else { throw fail("invalid SHA-256.") } } let root = directory.resolvingSymlinksInPath().standardizedFileURL let outputs = Set(allowedOutputs) var loaded: [String: Data] = [:], total = 0 func read(_ name: String, digest: String) throws -> Data { try path(name); try hash(digest) guard outputs.contains(name) else { throw fail("an artifact was not retained as a declared build output.") } if let data = loaded[name] { guard CMOCSourceMap.sha256(data) == digest else { throw fail("conflicting artifact hashes.") }; return data } let url = root.appendingPathComponent(name) guard url.resolvingSymlinksInPath().path == url.path else { throw fail("artifact paths must not traverse symbolic links.") } let info = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= 8 * 1024 * 1024 else { throw fail("artifact is not a bounded regular file.") } let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } let value = try handle.read(upToCount: 8 * 1024 * 1024 + 1) ?? Data() total += value.count guard value.count <= 8 * 1024 * 1024, total <= 128 * 1024 * 1024, CMOCSourceMap.sha256(value) == digest else { throw fail("artifact changed or exceeds verification limits.") } loaded[name] = value; return value } guard manifest.sources == sources.mapValues(CMOCSourceMap.sha256) else { throw fail("source snapshot differs from the manifest.") } for (name, digest) in manifest.sources { try path(name); try hash(digest) } guard manifest.binary.path == binaryPath, CMOCSourceMap.sha256(binary) == manifest.binary.sha256 else { throw fail("delivered executable differs from the manifest.") } _ = try read(manifest.binary.path, digest: manifest.binary.sha256) if let disk = manifest.disk { guard disk.path == diskPath else { throw fail("delivered disk identity differs from the manifest.") } _ = try read(disk.path, digest: disk.sha256) } else if diskPath != nil { throw fail("delivered disk is missing from the manifest.") } let linkMap = try read(manifest.linkMap.path, digest: manifest.linkMap.sha256) guard let mapText = String(data: linkMap, encoding: .utf8), !mapText.contains("\0") else { throw fail("invalid linker-map encoding.") } let sectionPattern = try NSRegularExpression(pattern: #"^Section: ([^\s]+) \((.+)\) load at ([0-9A-Fa-f]{4}), length ([0-9A-Fa-f]{4})$"#) var placements: [(name: String, address: Int, length: Int)] = [] let rows = mapText.components(separatedBy: .newlines) guard rows.count <= 100000, rows.allSatisfy({ $0.utf8.count <= 8192 }) else { throw fail("linker map exceeds limits.") } for row in rows { let ns = row as NSString guard let match = sectionPattern.firstMatch(in: row, range: NSRange(location: 0, length: ns.length)) else { if row.hasPrefix("Section:") { throw fail("unsupported section placement.") }; continue } placements.append((ns.substring(with: match.range(at: 1)), Int(ns.substring(with: match.range(at: 3)), radix: 16)!, Int(ns.substring(with: match.range(at: 4)), radix: 16)!)) } for (name, digest) in manifest.artifacts { _ = try read(name, digest: digest) } var modules: [Module] = [], ids = Set(), sections = Set() var physical: [UInt32: String] = [:] for record in manifest.modules { guard !record.id.isEmpty, record.id.count <= 128, ids.insert(record.id).inserted, !record.sections.isEmpty, record.sections.count <= 256, Set(record.codeSections).count == record.codeSections.count, Set(record.codeSections).isSubset(of: Set(record.sections)), !record.pages.isEmpty, record.pages.count <= 8 else { throw fail("invalid or repeated module identity.") } for section in record.sections { guard !section.isEmpty, section.count <= 256, !section.contains(where: \.isWhitespace), sections.insert(section).inserted else { throw fail("section has ambiguous module ownership.") } } guard Set(record.pages.map(\.logicalPage)).count == record.pages.count, record.pages.allSatisfy({ (0..<8).contains($0.logicalPage) && (0..<1024).contains($0.physicalPage) }) else { throw fail("module image or page layout is invalid.") } let logicalAddress: Int, moduleBytes: [UInt8] if let declaredImage = record.image { guard let digest = manifest.artifacts[declaredImage.path] else { throw fail("module image is missing from the artifact evidence.") } let image = try read(declaredImage.path, digest: digest) let offset = declaredImage.offset ?? 0 guard offset >= 0, offset <= image.count else { throw fail("module image range is invalid.") } let length = declaredImage.length ?? (image.count - offset) guard length > 0, length <= image.count - offset, declaredImage.logicalAddress >= 0, declaredImage.logicalAddress < 65536, length <= 65536 - declaredImage.logicalAddress else { throw fail("module image range is invalid.") } logicalAddress = declaredImage.logicalAddress moduleBytes = Array(image[offset..<(offset + length)]) } else { guard record.codeSections.isEmpty else { throw fail("module \(record.id): executable codeSections require a module image.") } // Pure BSS owns real physical storage but has no initialized // bytes. Relocation verification still rejects any initialized // object section whose bytes are absent from this empty image. logicalAddress = placements.first { record.sections.contains($0.name) }?.address ?? 0 moduleBytes = [] } var guards: [CodeGuard] = [], occupiedCode = Set() for section in record.codeSections { let matching = placements.filter { $0.name == section } guard !matching.isEmpty else { throw fail("an executable section is missing from the linker map.") } for placement in matching where placement.length > 0 { let start = placement.address - logicalAddress guard start >= 0, start <= moduleBytes.count, placement.length <= moduleBytes.count - start else { throw fail("executable section leaves its module image.") } for address in placement.address..<(placement.address + placement.length) { guard occupiedCode.insert(address).inserted else { throw fail("executable section placements overlap inside a module.") } } guards.append(CodeGuard(address: UInt16(placement.address), bytes: Array(moduleBytes[start..<(start + placement.length)]))) } } let module = Module(id: record.id, sections: record.sections, codeSections: record.codeSections, logicalAddress: logicalAddress, bytes: moduleBytes, pages: record.pages, codeGuards: guards.sorted { $0.address < $1.address }) var imagePhysical = Set() for logical in module.logicalAddress..<(module.logicalAddress + moduleBytes.count) { guard let address = module.physicalAddress(logical), imagePhysical.insert(address).inserted, physical[address] == nil || physical[address] == module.id else { throw fail("module images overlap physical RAM or lack a page identity.") } physical[address] = module.id } // BSS has no image bytes, but its storage must still have one // physical owner. Initialized non-code data follows the same rule. for section in record.sections where !record.codeSections.contains(section) { let matching = placements.filter { $0.name == section } guard !matching.isEmpty else { throw fail("a data section is missing from the linker map.") } for placement in matching where placement.length > 0 { for logical in placement.address..<(placement.address + placement.length) { guard let address = module.physicalAddress(logical), physical[address] == nil || physical[address] == module.id else { throw fail("module storage overlaps another module's physical RAM or lacks a page identity.") } physical[address] = module.id } } } modules.append(module) } // A compressed transport can enter through its loader, outside every // eventual source module. Bind this entry to the delivered DECB trailer. guard try CMOCSourceMap.decbEntryPoint(binary) == UInt16(manifest.entryPoint) else { throw fail("entry point differs from the delivered executable.") } let buffers = manifest.framebuffers ?? [] let modes = Set(["sg4", "pmode0", "pmode1", "pmode2", "pmode3", "pmode4", "hscreen1", "hscreen2", "hscreen3", "hscreen4", "current_gime"]) guard buffers.count <= 4, Set(buffers.map(\.id)).count == buffers.count, buffers.allSatisfy({ buffer in buffer.id != "displayed" && (1...64).contains(buffer.id.utf8.count) && buffer.id.utf8.allSatisfy({ (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 95 || $0 == 45 }) && (0..<(8 * 1024 * 1024)).contains(buffer.physicalAddress) && modes.contains(buffer.mode) && { if buffer.mode == "current_gime" { guard let size = buffer.canvasBytes, (8192...(8 * 1024 * 1024)).contains(size), size & (size - 1) == 0, buffer.physicalAddress % size == 0, buffer.physicalAddress <= 8 * 1024 * 1024 - size else { return false } return true } return buffer.canvasBytes == nil }() }) else { throw fail("invalid framebuffer declaration.") } let canvases = buffers.filter { $0.mode == "current_gime" } for (index, canvas) in canvases.enumerated() { let range = canvas.physicalAddress..<(canvas.physicalAddress + canvas.canvasBytes!) guard canvases.dropFirst(index + 1).allSatisfy({ other in !range.overlaps(other.physicalAddress..<(other.physicalAddress + other.canvasBytes!)) }) else { throw fail("overlapping current GIME canvases.") } } return Self(entryPoint: UInt16(manifest.entryPoint), binarySHA256: manifest.binary.sha256, linkMap: linkMap, sourceHashes: manifest.sources, artifactHashes: manifest.artifacts, modules: modules, framebuffers: buffers) } }