Files

212 lines
13 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
/// A grant fixes the input names and build recipe at consent time. An ordinary
/// project contributes C and headers only; its Make recipes and options never run.
struct MCPCMOCProject: Equatable, Sendable {
static let diskPaths = ["assets/words.txt", "include/hello.h", "main.c", "src/disk.c", "src/display.c"]
static let diskControls = ["Makefile", "tools/build-data.pl", CMOCProject.configurationFilename]
static let libraryHeaders = ["cmoc.h", "coco.h", "decbfile.h", "stdarg.h", "assert.h", "setjmp.h", "disk.h", "lores.h", "gimeterm.h"]
let paths: [String]
let entry: String
let helloDisk: Bool
let customMake: Bool
let configuration: CMOCProjectConfiguration
init(project: CMOCProject, files: [String], customMake: Bool = false) throws {
self.customMake = customMake
configuration = try project.configuration.validated()
let available = Set(files)
helloDisk = !customMake && Set(Self.diskPaths + Self.diskControls).isSubset(of: available)
if customMake {
entry = project.configuration.entrySource
paths = available.filter { CMOCProject.isEditable($0) }.sorted()
guard paths.contains(entry), paths.contains(configuration.makefile), paths.count <= 1024,
Set(paths.map { $0.lowercased() }).count == paths.count else {
throw CMOCBuildError.message("unsupported_project_sources: choose a project with at most 1,024 distinct shared text files")
}
for path in paths { try CMOCProject.validateRelativePath(path) }
} else if helloDisk {
paths = Self.diskPaths
entry = "main.c"
} else {
entry = project.configuration.entrySource
paths = available.filter { $0.hasSuffix(".c") || $0.hasSuffix(".h") }.sorted()
guard paths.contains(entry), entry.hasSuffix(".c"), paths.count <= 64,
Set(paths.map { $0.lowercased() }).count == paths.count,
paths.allSatisfy(Self.validPath) else { throw CMOCBuildError.message("unsupported_project_sources") }
}
}
private static func validPath(_ path: String) -> Bool {
guard path.utf8.count <= 200, !path.hasPrefix("obj/"), !path.hasPrefix("generated/") else { return false }
return path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { part in
guard let first = part.first, first.isASCII, first.isLetter || first == "_" || first.isNumber else { return false }
return part.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || "_.-".contains($0)) }
}
}
// Remove C comments before classifying directives. Quoted strings and
// character literals stay intact; comments cannot hide a leading #include.
private static let lexicalTokens = try! NSRegularExpression(pattern: ##"(?s)/\*.*?(?:\*/|\z)|//[^\r\n]*|"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'"##)
private static func uncomment(_ source: String) -> String {
let text = source as NSString
let result = NSMutableString(capacity: text.length)
var start = 0
for token in lexicalTokens.matches(in: source, range: NSRange(location: 0, length: text.length)) {
let value = text.substring(with: token.range)
guard value.hasPrefix("/") else { continue }
result.append(text.substring(with: NSRange(location: start, length: token.range.location - start)))
result.append(" " + String(value.filter { $0.isNewline }))
start = NSMaxRange(token.range)
}
result.append(text.substring(from: start))
return result as String
}
func validate(_ source: String, path: String, trusted: Set<String>? = nil) throws {
guard source.utf8.count <= (customMake ? CMOCProject.maximumSourceBytes : 65536), !source.utf8.contains(0) else {
throw CMOCBuildError.message("file_too_large: " + path)
}
if customMake { return } // The user explicitly approved this project's Make recipe and compiler inputs.
var rejectedLine = 1
// Locate the first construct outside the restricted C-source mode.
if let range = source.range(of: #"(?m)^.*(?:\basm\b|__asm|_Pragma|__has_include|_CMOC_CONCAT|%:|\?\?|##|#\s*(?:pragma|line|error|warning)).*$"#, options: .regularExpression) {
rejectedLine = source[..<range.lowerBound].filter { $0 == "\n" }.count + 1
}
func rejection(_ line: Int) -> CMOCBuildError {
.message("unsupported_source_directive: \(path):\(line): This construct is outside the restricted C connection. For your own Make project, select Use Project Makefile in Assistant Access.")
}
let denied = rejection(rejectedLine)
guard !source.contains("%:"), !source.contains("??"), !source.contains("##"),
source.utf8.allSatisfy({ $0 == 9 || $0 == 10 || $0 == 13 || $0 >= 32 }),
source.range(of: #"\\[ \t]*(?:\r|\n|$)|\\[uU][0-9a-fA-F]"#, options: .regularExpression) == nil,
source.range(of: #"\b(asm|__asm_?_?|_Pragma|__has_include(?:_next)?|_CMOC_CONCAT2?)\b"#, options: .regularExpression) == nil else { throw denied }
if let trusted {
guard source.components(separatedBy: .newlines).allSatisfy({ !$0.contains("#") || trusted.contains($0) }) else { throw denied }
return
}
for (index, line) in Self.uncomment(source).components(separatedBy: .newlines).enumerated() {
let denied = rejection(index + 1)
let directive = line.trimmingCharacters(in: .whitespaces)
guard directive.hasPrefix("#") else { continue }
let body = directive.dropFirst().trimmingCharacters(in: .whitespaces)
let nameEnd = body.firstIndex(where: { !$0.isLetter && $0 != "_" }) ?? body.endIndex
let keyword = String(body[..<nameEnd])
let arg = body[nameEnd...].trimmingCharacters(in: .whitespaces)
switch keyword {
case "ifndef", "ifdef", "undef":
guard keyword != "undef" || !arg.hasPrefix("_") else { throw denied }
guard arg.range(of: #"^[A-Za-z_]\w*$"#, options: .regularExpression) != nil else { throw denied }
continue
case "else", "endif":
guard arg.isEmpty else { throw denied }
continue
case "define", "if", "elif":
// Fixed includes below; no stringification, token concatenation,
// injected directives or changes to compiler predefined macros.
guard !arg.isEmpty, !arg.contains("#"), keyword != "define" || !arg.hasPrefix("_") else { throw denied }
continue
case "include": break
default: throw denied
}
guard arg.count >= 3, let first = arg.first, let last = arg.last else { throw denied }
let name = String(arg.dropFirst().dropLast())
if first == "<", last == ">", Self.libraryHeaders.contains(name) { continue }
let parent = (path as NSString).deletingLastPathComponent
guard first == "\"", last == "\"", Self.validPath(name), name.hasSuffix(".h"),
paths.contains(name) || paths.contains("include/" + name) || paths.contains(parent + "/" + name) else { throw denied }
}
}
func snapshotProject(at directory: URL, inputs: [String: String], buildInputs: [String: Data]? = nil,
support: CMOCBuildSupportSnapshot? = nil, permissions: [String: Int] = [:],
modificationDates: [String: Date] = [:], overlayPaths: Set<String> = []) throws -> CMOCProject {
if customMake {
guard var files = buildInputs else { throw CMOCBuildError.message("missing_project_source") }
for (path, text) in inputs { files[path] = try CMOCProject.sourceBytes(text) }
let fm = FileManager.default
try fm.createDirectory(at: directory, withIntermediateDirectories: true)
for (path, bytes) in files {
try CMOCProject.validateRelativePath(path)
let url = directory.appendingPathComponent(path)
try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try bytes.write(to: url, options: .withoutOverwriting)
if let mode = permissions[path] { try fm.setAttributes([.posixPermissions: mode], ofItemAtPath: url.path) }
if !overlayPaths.contains(path), let date = modificationDates[path] {
try fm.setAttributes([.modificationDate: date], ofItemAtPath: url.path)
}
}
for relative in configuration.buildSupportDirectories {
try fm.createDirectory(at: directory.appendingPathComponent(relative).standardizedFileURL, withIntermediateDirectories: true)
}
if let support {
for (path, bytes) in support.files {
guard configuration.buildSupportDirectories.contains(where: { path.hasPrefix($0 + "/") }) else {
throw CMOCBuildError.message("unapproved_build_support")
}
let url = directory.appendingPathComponent(path).standardizedFileURL
try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try bytes.write(to: url, options: .withoutOverwriting)
if let mode = support.permissions[path] { try fm.setAttributes([.posixPermissions: mode], ofItemAtPath: url.path) }
}
}
return try CMOCProject.open(at: directory)
}
if helloDisk { return try CMOCProject.createHelloDisk(at: directory) }
var recipe = CMOCMakefileSettings()
recipe.sources = paths.filter { $0.hasSuffix(".c") }
recipe.compilerOptions = ["-I."] // Allow a nested source to include a shared header at the project root.
recipe.includePaths = paths.contains(where: { $0.hasPrefix("include/") }) ? ["include"] : []
var configuration = CMOCProjectConfiguration()
configuration.entrySource = entry
configuration.makefileSettings = recipe
configuration.buildTarget = "build"
let fm = FileManager.default
try fm.createDirectory(at: directory, withIntermediateDirectories: false)
for path in paths {
guard let source = inputs[path] else { throw CMOCBuildError.message("missing_project_source") }
let url = directory.appendingPathComponent(path)
try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try Data(source.utf8).write(to: url, options: .withoutOverwriting)
}
try Data(recipe.generateMakefile().utf8).write(to: directory.appendingPathComponent("Makefile"))
try JSONEncoder().encode(configuration).write(to: directory.appendingPathComponent(CMOCProject.configurationFilename))
return try CMOCProject.open(at: directory)
}
}
struct MCPCMOCEdit: Equatable {
let path: String
let before: String
let after: String
}
/// Frozen inputs for an explicitly approved Make build. Binary resources are
/// build inputs but are not exposed as assistant-readable text.
struct MCPCMOCMakeInputs: Equatable, Sendable {
let makefile: String
let files: [String: Data]
let permissions: [String: Int]
var modificationDates: [String: Date] = [:]
var overlayPaths: Set<String> = []
let support: CMOCBuildSupportSnapshot
static func == (lhs: Self, rhs: Self) -> Bool {
// Modification times are Make scheduling hints, not source revisions.
// Overlay membership can change on Save without changing any bytes.
lhs.makefile == rhs.makefile && lhs.files == rhs.files && lhs.permissions == rhs.permissions && lhs.support == rhs.support
}
var recipeID: String {
let controls = files.filter { path, _ in
let name = (path as NSString).lastPathComponent
return path == makefile || (permissions[path] ?? 0) & 0o111 != 0
|| ["Makefile", "makefile", "GNUmakefile", CMOCProject.configurationFilename].contains(name)
|| ["mk", "pl", "py", "sh", "rb"].contains((path as NSString).pathExtension.lowercased())
}.mapValues(CMOCProject.sha256)
let rows = controls.merging(support.hashes) { first, _ in first }.sorted { $0.key < $1.key }
return CMOCProject.sha256(Data(rows.map { "\($0.key):\($0.value):\(permissions[$0.key] ?? 0)" }.joined(separator: "\n").utf8))
}
}