Publish VCC Plus OSS source distribution for 3.6.2 build 60

This commit is contained in:
Brian Holman committed 2026-11-13 00:14:03 -07:00
commit c652a5276d
1192 files changed
+272368

No files matched your search

@@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/// Synchronous, bounded operations on caller-owned private working images.
/// Call off the main thread. Internal serialization protects retained C code.
@interface VCCDiskImageEditorBackend : NSObject
/// Discover validated volumes in a raw floppy/hard-drive image. IDs encode the
/// filesystem, byte offset and extent; all regions outside the selected volume
/// remain opaque and are never reformatted or inferred as free space.
+ (nullable NSArray<NSDictionary<NSString *, id> *> *)discoverVolumesAtURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(discoverVolumes(at:));
+ (BOOL)extractVolume:(NSString *)volumeID imageURL:(NSURL *)imageURL outputURL:(NSURL *)outputURL error:(NSError **)error NS_SWIFT_NAME(extractVolume(_:imageURL:outputURL:));
+ (BOOL)replaceVolume:(NSString *)volumeID imageURL:(NSURL *)imageURL volumeURL:(NSURL *)volumeURL error:(NSError **)error NS_SWIFT_NAME(replaceVolume(_:imageURL:volumeURL:));
+ (nullable NSDictionary<NSString *, id> *)inspectImageAtURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(inspectImage(at:));
+ (nullable NSArray<NSDictionary<NSString *, id> *> *)listDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(listDirectory(_:imageURL:));
+ (nullable NSData *)readFile:(NSString *)path imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(readFile(_:imageURL:));
+ (nullable NSString *)identifyFile:(NSString *)path imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(identifyFile(_:imageURL:));
+ (BOOL)importData:(NSData *)data named:(NSString *)name directory:(NSString *)directory imageURL:(NSURL *)imageURL fileType:(NSInteger)fileType ascii:(BOOL)ascii replace:(BOOL)replace error:(NSError **)error NS_SWIFT_NAME(importData(_:named:directory:imageURL:fileType:ascii:replace:));
+ (BOOL)makeDirectory:(NSString *)name inDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(makeDirectory(_:in:imageURL:));
+ (BOOL)renameEntry:(NSString *)path toName:(NSString *)name imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(renameEntry(_:to:imageURL:));
+ (BOOL)deleteEntry:(NSString *)path directory:(BOOL)directory imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(deleteEntry(_:directory:imageURL:));
/// Relink regular files within one OS-9 image without copying their data or
/// replacing descriptors. The empty destination path denotes the root.
+ (BOOL)moveFiles:(NSArray<NSString *> *)paths toDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error NS_SWIFT_NAME(moveFiles(_:toDirectory:imageURL:));
/// OS-9's two-byte owner is represented as high-byte group / low-byte user.
/// Permissions are owner/public rwx and single access (0...127); type is kept.
+ (BOOL)setOS9MetadataForPath:(NSString *)path imageURL:(NSURL *)imageURL ownerUser:(NSInteger)ownerUser ownerGroup:(NSInteger)ownerGroup permissions:(NSInteger)permissions error:(NSError **)error NS_SWIFT_NAME(setOS9Metadata(for:imageURL:ownerUser:ownerGroup:permissions:));
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,697 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#import "DiskImageEditorBackend.h"
#include <algorithm>
#include <array>
#include <cerrno>
#include <cctype>
#include <fcntl.h>
#include <functional>
#include <map>
#include <mutex>
#include <set>
#include <stdexcept>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
extern "C" {
#include "decbpath.h"
#include "os9path.h"
#include "os9module.h"
}
namespace {
constexpr size_t limit = 512 * 1024 * 1024;
constexpr size_t fileLimit = 16 * 1024 * 1024;
constexpr size_t sectorSize = 256;
constexpr size_t rawTrackBytes = 18 * sectorSize;
constexpr size_t decbVolumeBytes = 35 * rawTrackBytes;
std::recursive_mutex backendMutex;
using Bytes = std::vector<uint8_t>;
[[noreturn]] void fail(const std::string& message) { throw std::runtime_error(message); }
uint32_t be(const Bytes& bytes, size_t offset, size_t count) {
if (offset > bytes.size() || count > bytes.size() - offset) fail("The disk image contains a truncated structure.");
uint32_t value = 0; for (size_t i = 0; i < count; ++i) value = (value << 8) | bytes[offset + i]; return value;
}
std::string lower(std::string value) { for (char& c : value) c = char(std::tolower(static_cast<unsigned char>(c))); return value; }
std::string string(NSString *value) {
const char *bytes = value.UTF8String; if (!bytes) fail("This name is not valid UTF-8."); return bytes;
}
NSString *text(const std::string& value) { return [[NSString alloc] initWithBytes:value.data() length:value.size() encoding:NSUTF8StringEncoding] ?: @""; }
std::string name(std::string value, bool decb, bool allowDots = false) {
if (value.empty() || value.size() > (decb ? 12 : 29) || (!allowDots && (value == "." || value == "..")))
fail(decb ? "Use a Disk BASIC name of up to eight characters and a three-character extension." : "Use an OS-9 name of 1–29 ASCII characters.");
for (unsigned char c : value) if (c < 32 || c > 126 || c == '/' || c == '\\' || c == ',' || c == ':' || c == '@')
fail("The image name contains an unsupported character.");
if (decb) {
const auto dot = value.find('.');
if (dot == 0 || (dot != std::string::npos && (dot > 8 || dot + 1 == value.size() || value.size() - dot - 1 > 3 || value.find('.', dot + 1) != std::string::npos)) || (dot == std::string::npos && value.size() > 8))
fail("Use a Disk BASIC name of up to eight characters and a three-character extension.");
for (char& c : value) c = char(std::toupper(static_cast<unsigned char>(c)));
}
return value;
}
std::string imagePath(NSString *input, bool decb, bool rootAllowed = false) {
const auto path = string(input);
if (path.empty()) { if (rootAllowed) return path; fail("Select a file or directory within the image."); }
if (path.size() > 1024 || path.front() == '/' || path.back() == '/') fail("Use a relative path inside the image.");
std::string out; size_t start = 0, components = 0;
while (start < path.size()) {
const auto end = path.find('/', start);
const auto part = name(path.substr(start, end == std::string::npos ? end : end - start), decb);
if (++components > 32 || (decb && components > 1)) fail("The image path is too deep for this filesystem.");
if (!out.empty()) out += '/'; out += part;
if (end == std::string::npos) break; start = end + 1;
}
return out;
}
Bytes load(NSURL *url) {
if (!url.isFileURL || [url.path containsString:@","]) fail("Choose a local private working image with no comma in its path.");
const int fd = open(url.fileSystemRepresentation, O_RDONLY | O_NOFOLLOW);
if (fd < 0) fail("The working disk image could not be opened.");
struct stat info{};
if (fstat(fd, &info) != 0 || !S_ISREG(info.st_mode) || info.st_size < 256 || info.st_size > off_t(limit)) { close(fd); fail("Choose a regular disk image between 256 bytes and 512 MiB."); }
Bytes bytes(size_t(info.st_size)); size_t offset = 0;
while (offset < bytes.size()) { const ssize_t got = read(fd, bytes.data() + offset, bytes.size() - offset); if (got <= 0) { close(fd); fail("The disk image could not be read completely."); } offset += size_t(got); }
uint8_t extra; const auto additional = read(fd, &extra, 1); close(fd);
if (additional != 0) fail("The working image changed while it was being read.");
return bytes;
}
struct Node {
std::string path, parent, name; bool directory = false;
size_t size = 0, descriptorSector = 0; unsigned type = 0, ascii = 0, attributes = 0, owner = 0, group = 0;
id modified = NSNull.null; Bytes content; std::vector<size_t> dataSectors;
};
struct Image {
Bytes bytes; bool decb = false; size_t capacity = 0, free = 0, unit = 0;
std::map<std::string, Node> nodes;
const Node& find(const std::string& path) const {
auto found = nodes.find(lower(path)); if (found == nodes.end()) fail("The selected image entry no longer exists."); return found->second;
}
};
std::string padded(const Bytes& b, size_t offset, size_t size) {
std::string value(reinterpret_cast<const char *>(b.data() + offset), size);
while (!value.empty() && value.back() == ' ') value.pop_back(); return value;
}
void validateDECB(Image& image) {
auto& b = image.bytes;
if (b.size() < decbVolumeBytes || b.size() % rawTrackBytes != 0)
fail("Disk BASIC editing requires a complete 35-track raw filesystem, optionally followed by whole supplementary tracks. Other image layouts are preserved but cannot be edited here.");
// Disk BASIC's 68-granule filesystem occupies only the first 35 tracks.
// Supplementary tracks are opaque application data, never free granules.
image.decb = true; image.unit = 2304; image.capacity = 68 * image.unit;
constexpr size_t fat = (17 * 18 + 1) * 256, directory = (17 * 18 + 2) * 256;
auto chain = [&](unsigned first) {
std::vector<unsigned> result; std::set<unsigned> visited; unsigned current = first;
for (;;) {
if (current >= 68 || !visited.insert(current).second) fail("The Disk BASIC allocation chain is out of range or cyclic.");
result.push_back(current); const unsigned next = b[fat + current];
if (next >= 0xc0 && next <= 0xc9) return result;
if (next >= 68) fail("The Disk BASIC allocation chain has an invalid terminator."); current = next;
}
};
for (unsigned i = 0; i < 68; ++i) { if (b[fat + i] == 255) image.free += image.unit; else (void)chain(i); }
Node root; root.directory = true; image.nodes.emplace("", root);
std::set<unsigned> claimed;
for (unsigned i = 0; i < 72; ++i) {
const auto offset = directory + i * 32; if (b[offset] == 255 || b[offset] == 0) continue;
Node n; n.name = padded(b, offset, 8); const auto ext = padded(b, offset + 8, 3); if (!ext.empty()) n.name += '.' + ext;
n.path = name(n.name, true); n.name = n.path; n.type = b[offset + 11]; n.ascii = b[offset + 12];
if (n.type > 3 || (n.ascii != 0 && n.ascii != 255)) fail("The Disk BASIC file has unsupported type or encoding metadata.");
const auto allocated = chain(b[offset + 13]); const auto last = b[fat + allocated.back()] & 0x3f; const auto lastBytes = be(b, offset + 14, 2);
if (lastBytes > 256 || (last == 0 && lastBytes != 0)) fail("The Disk BASIC last-sector length is invalid.");
n.size = (allocated.size() - 1) * 2304 + (last > 0 ? last - 1 : 0) * 256 + lastBytes;
for (unsigned granule : allocated) {
if (!claimed.insert(granule).second) fail("Two Disk BASIC files share an allocation granule.");
const size_t sector = size_t(granule / 2 + (granule >= 34 ? 1 : 0)) * 18 + (granule % 2) * 9;
n.content.insert(n.content.end(), b.begin() + sector * 256, b.begin() + sector * 256 + 2304);
}
if (n.size > n.content.size()) fail("The Disk BASIC file length exceeds its allocation."); n.content.resize(n.size);
if (!image.nodes.emplace(lower(n.path), std::move(n)).second) fail("The Disk BASIC directory has duplicate names.");
}
}
id modifiedTime(const Bytes& b, size_t offset) {
const unsigned year = b[offset] + 1900, month = b[offset + 1], day = b[offset + 2], hour = b[offset + 3], minute = b[offset + 4];
if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59) return NSNull.null;
NSDateComponents *parts = [NSDateComponents new]; parts.year = year; parts.month = month; parts.day = day; parts.hour = hour; parts.minute = minute;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *date = [calendar dateFromComponents:parts]; return date ? @([date timeIntervalSince1970]) : NSNull.null;
}
void validateOS9(Image& image) {
auto& b = image.bytes; const size_t sectors = be(b, 0, 3), mapBytes = be(b, 4, 2), cluster = be(b, 6, 2), rootFD = be(b, 8, 3);
const auto declaredSectorSize = be(b, offsetof(lsn0_sect, dd_lsnsize), 2);
const auto sectorsPerTrack = be(b, offsetof(lsn0_sect, dd_spt), 2);
const bool osk = be(b, offsetof(lsn0_sect, dd_sync), 4) == 0x4372757a;
const auto track0 = be(b, osk ? offsetof(lsn0_sect, dd_opt.m68k.pd_t0s) : offsetof(lsn0_sect, dd_opt.m6809.pd_t0s), 2);
// The upstream raw reader uses the first byte of dd_lsnsize; historical
// writers also store 1 in the low byte. Both spellings still mean 256.
if (!sectors || sectors * 256 != b.size() || cluster == 0 || cluster > 256 || (cluster & (cluster - 1)) || !rootFD || rootFD >= sectors || (declaredSectorSize != 0 && declaredSectorSize != 1 && declaredSectorSize != 256) || !sectorsPerTrack || (track0 && track0 != sectorsPerTrack))
fail("The OS-9 geometry is invalid or is not a supported raw 256-byte-sector image.");
const size_t clusters = (sectors + cluster - 1) / cluster, mapSectors = (mapBytes + 255) / 256;
if (mapBytes < (clusters + 7) / 8 || mapBytes > b.size() - 256 || mapSectors + 1 >= sectors) fail("The OS-9 allocation bitmap is truncated.");
auto allocated = [&](size_t sector) { const auto bit = sector / cluster; return (b[256 + bit / 8] & (0x80 >> (bit % 8))) != 0; };
const size_t bootStart = be(b, offsetof(lsn0_sect, dd_bt), 3), bootBytes = be(b, offsetof(lsn0_sect, dd_bsz), 2);
if (bootStart) {
// A zero byte length can designate the fragmented-boot descriptor.
// At minimum its pointed sector must remain within allocated space.
const size_t bootSectors = bootBytes ? (bootBytes + sectorSize - 1) / sectorSize : 1;
if (bootStart >= sectors || bootSectors > sectors - bootStart) fail("The OS-9 boot extent is outside the volume.");
for (size_t sector = bootStart; sector < bootStart + bootSectors; ++sector)
if (!allocated(sector)) fail("An OS-9 boot sector is marked free in the allocation bitmap.");
if (!bootBytes) {
const size_t descriptor = bootStart * sectorSize; size_t allocation = 0;
for (size_t i = 0; i < 48; ++i) {
const size_t segment = descriptor + 16 + i * 5, start = be(b, segment, 3), count = be(b, segment + 3, 2);
if (!count) { if (start) fail("The fragmented OS-9 boot segment is invalid."); continue; }
if (!start || start >= sectors || count > sectors - start) fail("The fragmented OS-9 boot segment is outside the volume.");
for (size_t sector = start; sector < start + count; ++sector)
if (!allocated(sector)) fail("A fragmented OS-9 boot sector is marked free.");
allocation += count * sectorSize;
}
if (be(b, descriptor + 9, 4) > allocation) fail("The fragmented OS-9 boot file is shorter than its descriptor.");
}
} else if (bootBytes) fail("The OS-9 boot extent has no starting sector.");
image.capacity = sectors * 256; image.unit = cluster * 256;
for (size_t c = 0; c < clusters; ++c) if (!allocated(c * cluster)) image.free += std::min(cluster, sectors - c * cluster) * 256;
std::vector<size_t> owners(sectors, 0);
for (size_t s = 0; s <= mapSectors; ++s) { if (!allocated(s)) fail("OS-9 reserved sectors are marked free."); owners[s] = size_t(-1); }
std::set<size_t> directories, activeDirectories, claimedFDs; size_t materializedBytes = 0;
std::function<void(size_t, std::string, std::string, unsigned)> visit;
visit = [&](size_t fd, std::string path, std::string parent, unsigned depth) {
if (fd >= sectors || !fd || depth > 32 || image.nodes.size() >= 4096) fail("The OS-9 directory tree exceeds safe bounds.");
const size_t offset = fd * 256; Node n; n.descriptorSector = fd; n.path = path; n.parent = parent; n.name = path.substr(path.rfind('/') == std::string::npos ? 0 : path.rfind('/') + 1);
n.attributes = b[offset]; n.directory = (n.attributes & 0x80) != 0; n.owner = b[offset + 2]; n.group = b[offset + 1]; n.modified = modifiedTime(b, offset + 3); n.size = be(b, offset + 9, 4);
if (n.size > b.size() || b[offset + 8] == 0) fail("The OS-9 descriptor has invalid length or link count.");
if (n.size > limit * 2 - materializedBytes) fail("The OS-9 tree contains too many aliased file bytes.");
const bool firstFD = claimedFDs.insert(fd).second;
if (firstFD) { if (owners[fd] || !allocated(fd)) fail("The OS-9 descriptor overlaps another allocation or is marked free."); owners[fd] = fd; }
std::set<size_t> localSectors;
for (unsigned i = 0; i < 48; ++i) {
const size_t pos = offset + 16 + i * 5, start = be(b, pos, 3), count = be(b, pos + 3, 2);
if (!count) { if (start) fail("The OS-9 segment has no length."); continue; }
if (start == 0 || start >= sectors || count > sectors - start) fail("The OS-9 file segment is outside the image.");
for (size_t s = start; s < start + count; ++s) {
if (!localSectors.insert(s).second || !allocated(s) || (firstFD && owners[s])) fail("The OS-9 file allocation is cross-linked or marked free.");
if (firstFD) owners[s] = fd;
n.dataSectors.push_back(s);
}
if (count * sectorSize > limit * 2 - materializedBytes) fail("The OS-9 tree contains too many aliased allocation bytes.");
materializedBytes += count * sectorSize;
const size_t needed = std::min(count * sectorSize, n.size - std::min(n.size, n.content.size()));
n.content.insert(n.content.end(), b.begin() + start * sectorSize, b.begin() + start * sectorSize + needed);
}
if (n.size > n.content.size()) fail("The OS-9 file is shorter than its descriptor claims."); n.content.resize(n.size);
if (!image.nodes.emplace(lower(path), n).second) fail("The OS-9 directory contains duplicate names.");
if (!n.directory) return;
if (!activeDirectories.insert(fd).second || !directories.insert(fd).second || n.size % 32) fail("The OS-9 directory is cyclic or has an invalid size.");
for (size_t i = 0; i < n.content.size(); i += 32) {
if (n.content[i] == 0) continue;
std::string child; bool terminated = false;
for (size_t j = 0; j < 29; ++j) { const auto c = n.content[i + j]; child += char(c & 127); if (c & 128) { terminated = true; break; } }
if (!terminated) fail("An OS-9 directory name is not terminated.");
const size_t childFD = be(n.content, i + 29, 3);
if (!childFD || childFD >= sectors) fail("An OS-9 directory entry points outside the image.");
if (child == "." || child == "..") continue;
child = name(child, false); visit(childFD, path.empty() ? child : path + '/' + child, path, depth + 1);
}
activeDirectories.erase(fd);
};
visit(rootFD, "", "", 0);
if (!image.find("").directory) fail("The OS-9 root descriptor is not a directory.");
std::map<size_t,size_t> clusterOwners;
for (size_t sector = mapSectors + 1; sector < sectors; ++sector) {
if (!owners[sector] || owners[sector] == size_t(-1)) continue;
const auto prior = clusterOwners.emplace(sector / cluster, owners[sector]);
if (!prior.second && prior.first->second != owners[sector]) fail("OS-9 files share an allocation cluster.");
}
}
Image inspect(NSURL *url) {
Image image; image.bytes = load(url);
diskimage_format format = DISKIMAGE_UNKNOWN;
if (_diskimage_identify(url.fileSystemRepresentation, &format) || format != DISKIMAGE_RAW)
fail("The editor currently supports raw disk images. Other image containers are preserved but cannot be edited here.");
if (image.bytes.size() % 256 == 0 && be(image.bytes, 0, 3) == image.bytes.size() / 256) validateOS9(image);
else validateDECB(image);
return image;
}
struct ByteRange { size_t offset, length; };
std::vector<ByteRange> externalBootRanges(const Bytes& bytes, size_t filesystemBytes) {
const size_t start = be(bytes, offsetof(lsn0_sect, dd_bt), 3), length = be(bytes, offsetof(lsn0_sect, dd_bsz), 2);
if (!start || start < filesystemBytes / sectorSize) return {};
const size_t sectors = bytes.size() / sectorSize;
auto range = [&](size_t first, size_t count) {
if (!count || first >= sectors || count > sectors - first || first < filesystemBytes / sectorSize)
fail("The external OS-9 boot extent is outside the hard-drive image or crosses its filesystem boundary.");
return ByteRange{first * sectorSize, count * sectorSize};
};
if (length) return {range(start, (length + sectorSize - 1) / sectorSize)};
std::vector<ByteRange> protectedRanges{range(start, 1)};
const size_t descriptor = start * sectorSize; size_t allocatedBytes = 0;
if ((bytes[descriptor] & 0x80) || !bytes[descriptor + 8]) fail("The external fragmented OS-9 boot descriptor is invalid.");
for (size_t i = 0; i < 48; ++i) {
const size_t segment = descriptor + 16 + i * 5, first = be(bytes, segment, 3), count = be(bytes, segment + 3, 2);
if (!count) { if (first) fail("The external fragmented OS-9 boot segment has no length."); continue; }
protectedRanges.push_back(range(first, count)); allocatedBytes += count * sectorSize;
}
if (be(bytes, descriptor + 9, 4) > allocatedBytes) fail("The external fragmented OS-9 boot file is shorter than its descriptor.");
return protectedRanges;
}
void clearExternalBootPointer(Bytes& bytes) {
std::fill_n(bytes.begin() + offsetof(lsn0_sect, dd_bt), 5, 0);
}
struct Volume { std::string id, format, name; size_t offset, length, index; };
std::vector<Volume> discover(const Bytes& bytes) {
if (bytes.size() % sectorSize) fail("A raw hard-drive image must contain complete 256-byte sectors.");
std::vector<Volume> volumes; std::vector<ByteRange> protectedBoot; size_t hdbStart = 0;
// An RBF volume may occupy a prefix of a combined OS-9/HDB-DOS image.
// Only its declared extent is inspected; no heuristic sector scanning.
const size_t extent = be(bytes, 0, 3) * sectorSize;
const size_t cluster = be(bytes, 6, 2);
const bool rbfHeader = be(bytes, 4, 2) != 0 && cluster != 0 && cluster <= 256 && !(cluster & (cluster - 1)) && be(bytes, 8, 3) != 0;
if (rbfHeader) {
if (extent < 3 * sectorSize || extent > bytes.size()) fail("The OS-9 declared volume extent is outside the image.");
protectedBoot = externalBootRanges(bytes, extent);
Image image; image.bytes.assign(bytes.begin(), bytes.begin() + extent);
if (!protectedBoot.empty()) clearExternalBootPointer(image.bytes);
validateOS9(image);
std::string volumeName;
for (size_t i = 31; i < 63; ++i) { const auto c = bytes[i]; if (!c) break; volumeName += char(c & 127); if (c & 128) break; }
volumes.push_back({"os9:0:" + std::to_string(extent), "os9", volumeName.empty() ? "OS-9 volume" : "OS-9 — " + volumeName, 0, extent, 0});
hdbStart = extent;
}
const size_t slots = (bytes.size() - hdbStart) / decbVolumeBytes;
for (size_t index = 0; index < slots; ++index) {
const size_t offset = hdbStart + index * decbVolumeBytes;
bool bootOverlap = false;
for (const auto& range : protectedBoot) if (offset < range.offset + range.length && range.offset < offset + decbVolumeBytes) bootOverlap = true;
if (bootOverlap) continue; // bootstrap storage is never a writable BASIC disk
Image image; image.bytes.assign(bytes.begin() + offset, bytes.begin() + offset + decbVolumeBytes);
try { validateDECB(image); }
catch (const std::exception&) { continue; } // unformatted/foreign slots remain opaque
const bool hard = hdbStart != 0 || slots > 1;
volumes.push_back({"decb:" + std::to_string(offset) + ":" + std::to_string(decbVolumeBytes), "decb",
hard ? "HDB-DOS disk " + std::to_string(index) : "Disk BASIC", offset, decbVolumeBytes, index});
}
if (volumes.empty()) fail("No supported OS-9 or Disk BASIC volume was found. Unformatted and foreign regions are preserved without modification.");
return volumes;
}
const Volume& selected(const std::vector<Volume>& volumes, NSString *identifier) {
const auto id = string(identifier);
for (const auto& volume : volumes) if (volume.id == id) return volume;
fail("The selected volume no longer matches this image. Reopen the editor and choose it again.");
}
std::vector<char> toolPath(NSURL *url, const std::string& path) { const auto full = std::string(url.fileSystemRepresentation) + ',' + path; std::vector<char> result(full.begin(), full.end()); result.push_back(0); return result; }
void check(error_code error, const char *operation) { if (error) fail(std::string(operation) + " failed (ToolShed error " + std::to_string(error) + ")."); }
struct OpenPath {
bool decb; decb_path_id d = nullptr; os9_path_id o = nullptr;
OpenPath(bool value) : decb(value) {}
~OpenPath() { if (d) _decb_close(d); if (o) _os9_close(o); }
void open(NSURL *url, const std::string& path, int mode = FAM_READ) {
auto p = toolPath(url, path);
if (decb) { decb_path_id opened = nullptr; check(_decb_open(&opened,p.data(),mode),"Open image file"); d = opened; }
else { os9_path_id opened = nullptr; check(_os9_open(&opened,p.data(),mode),"Open image file"); o = opened; }
}
void close() { if (d) { const auto result = _decb_close(d); d = nullptr; check(result, "Close image file"); } if (o) { const auto result = _os9_close(o); o = nullptr; check(result, "Close image file"); } }
};
NSData *readEntry(NSURL *url, const Image& image, const std::string& path) {
const auto& n = image.find(path); if (n.directory) fail("Choose a file to export or inspect.");
if (n.size > fileLimit) fail("Export or inspect files no larger than 16 MiB.");
if (!image.decb && image.unit > sectorSize) return [NSData dataWithBytes:n.content.data() length:n.content.size()];
OpenPath file(image.decb); file.open(url, n.path); Bytes out(n.size); size_t offset = 0;
while (offset < out.size()) {
u_int count = u_int(out.size() - offset); const auto result = image.decb ? _decb_read(file.d, out.data() + offset, &count) : _os9_read(file.o, out.data() + offset, &count);
if (count > out.size() - offset || !count || (result && result != EOS_EOF)) fail("The file could not be read completely."); offset += count;
}
file.close(); if (out != n.content) fail("The filesystem reader disagrees with the validated file allocation.");
return [NSData dataWithBytes:out.data() length:out.size()];
}
// OS-9 directory entries are 32-byte records aligned within 256-byte sectors.
// Relinking them leaves every file descriptor and data allocation untouched.
size_t directoryOffset(const Node& directory, size_t logical) {
if (!directory.directory || logical % 32 || logical / sectorSize >= directory.dataSectors.size())
fail("The OS-9 directory entry is outside its allocation.");
return directory.dataSectors[logical / sectorSize] * sectorSize + logical % sectorSize;
}
size_t findDirectoryEntry(const Image& image, const Node& directory, const Node& node) {
for (size_t i = 0; i < directory.size; i += 32) {
if (!directory.content[i]) continue;
std::string entryName;
for (size_t j = 0; j < 29; ++j) {
const auto c = directory.content[i + j]; entryName += char(c & 127);
if (c & 128) break;
}
if (lower(entryName) == lower(node.name) && be(directory.content, i + 29, 3) == node.descriptorSector)
return directoryOffset(directory, i);
}
fail("The selected file's directory entry changed. Refresh and select it again.");
}
void putBigEndian(Bytes& bytes, size_t offset, size_t length, size_t value) {
if (offset > bytes.size() || length > bytes.size() - offset || (length < sizeof(size_t) && value >> (length * 8)))
fail("The OS-9 directory metadata exceeds its supported bounds.");
for (size_t i = 0; i < length; ++i) { bytes[offset + length - i - 1] = uint8_t(value); value >>= 8; }
}
void growDirectory(Bytes& bytes, Node& directory) {
const size_t sectors = bytes.size() / sectorSize;
const size_t cluster = be(bytes, 6, 2);
size_t freeSector = 0;
for (size_t s = cluster; s + cluster <= sectors; s += cluster) if (!(bytes[sectorSize + (s / cluster) / 8] & (0x80 >> ((s / cluster) % 8)))) { freeSector = s; break; }
if (!freeSector) fail("The destination directory needs another sector, but the OS-9 disk is full.");
const size_t fd = directory.descriptorSector * sectorSize;
size_t freeSegment = size_t(-1), lastSegment = size_t(-1);
for (size_t i = 0; i < 48; ++i) {
const size_t segment = fd + 16 + i * 5;
if (be(bytes, segment + 3, 2)) lastSegment = segment;
else if (freeSegment == size_t(-1)) freeSegment = segment;
}
// RBF on the 6x09 keeps a segment within one allocation-map sector
// (2048 single-sector clusters). Prefer adjacent legal growth first.
if (lastSegment != size_t(-1)) {
const size_t start = be(bytes, lastSegment, 3), count = be(bytes, lastSegment + 3, 2), adjacent = start + count;
if (count + cluster <= 65535 && adjacent + cluster <= sectors && adjacent % cluster == 0 && adjacent / cluster / 2048 == start / cluster / 2048 &&
!(bytes[sectorSize + (adjacent / cluster) / 8] & (0x80 >> ((adjacent / cluster) % 8)))) freeSector = adjacent;
}
if (lastSegment != size_t(-1) && be(bytes, lastSegment, 3) + be(bytes, lastSegment + 3, 2) == freeSector &&
freeSector / cluster / 2048 == be(bytes, lastSegment, 3) / cluster / 2048 && be(bytes, lastSegment + 3, 2) + cluster <= 65535) {
putBigEndian(bytes, lastSegment + 3, 2, be(bytes, lastSegment + 3, 2) + cluster);
} else {
// Append after the last occupied segment so logical directory offsets
// remain stable even when an input descriptor contains segment holes.
const size_t appended = lastSegment == size_t(-1) ? fd + 16 : lastSegment + 5;
// Match the retained allocator: leave its final descriptor segment
// empty, although inspection accepts existing 48-segment images.
if (freeSegment == size_t(-1) || appended >= fd + 16 + 47 * 5)
fail("The destination directory has no room for another allocation segment.");
putBigEndian(bytes, appended, 3, freeSector); putBigEndian(bytes, appended + 3, 2, cluster);
}
bytes[sectorSize + (freeSector / cluster) / 8] |= uint8_t(0x80 >> ((freeSector / cluster) % 8));
std::fill(bytes.begin() + freeSector * sectorSize, bytes.begin() + (freeSector + cluster) * sectorSize, 0);
for (size_t s = freeSector; s < freeSector + cluster; ++s) directory.dataSectors.push_back(s);
}
// The retained allocator scans sector counts as bitmap bits for multi-sector
// clusters. Keep those volumes on this bounded, cluster-aware transaction path
// rather than passing them to allocator entry points that can overrun the map.
size_t clusterSize(const Bytes& bytes) { return be(bytes, 6, 2); }
void markCluster(Bytes& bytes, size_t sector, bool allocated) {
const size_t bit = sector / clusterSize(bytes), byte = sectorSize + bit / 8;
if (byte >= sectorSize + be(bytes, 4, 2)) fail("The OS-9 allocation bit is outside its bitmap.");
const uint8_t mask = uint8_t(0x80 >> (bit % 8));
if (allocated) bytes[byte] |= mask; else bytes[byte] &= uint8_t(~mask);
}
size_t allocateCluster(Bytes& bytes) {
const size_t cluster = clusterSize(bytes), sectors = bytes.size() / sectorSize;
for (size_t sector = cluster; sector + cluster <= sectors; sector += cluster) {
const size_t bit = sector / cluster;
if (!(bytes[sectorSize + bit / 8] & (0x80 >> (bit % 8)))) {
markCluster(bytes, sector, true);
std::fill(bytes.begin() + sector * sectorSize, bytes.begin() + (sector + cluster) * sectorSize, 0);
return sector;
}
}
fail("The OS-9 volume has no free complete allocation cluster.");
}
void appendSegment(Bytes& bytes, Node& node, size_t start, size_t count) {
const size_t descriptor = node.descriptorSector * sectorSize, cluster = clusterSize(bytes);
size_t last = size_t(-1), slot = 0;
for (; slot < 47; ++slot) {
const size_t entry = descriptor + 16 + slot * 5;
if (!be(bytes, entry + 3, 2)) break;
last = entry;
}
if (last != size_t(-1) && be(bytes, last, 3) + be(bytes, last + 3, 2) == start &&
be(bytes, last + 3, 2) + count <= 65535 && be(bytes, last, 3) / cluster / 2048 == (start + count - 1) / cluster / 2048) {
putBigEndian(bytes, last + 3, 2, be(bytes, last + 3, 2) + count);
} else {
if (slot >= 47) fail("The OS-9 file has no room for another allocation segment.");
putBigEndian(bytes, descriptor + 16 + slot * 5, 3, start);
putBigEndian(bytes, descriptor + 19 + slot * 5, 2, count);
}
for (size_t sector = start; sector < start + count; ++sector) node.dataSectors.push_back(sector);
}
std::array<uint8_t,32> directoryEntry(const std::string& name, size_t descriptor) {
std::array<uint8_t,32> entry{};
std::copy(name.begin(), name.end(), entry.begin()); entry[name.size() - 1] |= 0x80;
entry[29] = uint8_t(descriptor >> 16); entry[30] = uint8_t(descriptor >> 8); entry[31] = uint8_t(descriptor);
return entry;
}
void insertEntry(Bytes& bytes, Node& parent, const std::string& name, size_t descriptor) {
size_t logical = 0;
while (logical < parent.content.size() && parent.content[logical]) logical += 32;
if (logical == parent.content.size()) {
if (logical + 32 > parent.dataSectors.size() * sectorSize) growDirectory(bytes, parent);
parent.content.resize(logical + 32, 0); parent.size = parent.content.size();
putBigEndian(bytes, parent.descriptorSector * sectorSize + 9, 4, parent.size);
}
const auto entry = directoryEntry(name, descriptor); const size_t offset = directoryOffset(parent, logical);
std::copy(entry.begin(), entry.end(), bytes.begin() + offset);
std::copy(entry.begin(), entry.end(), parent.content.begin() + logical);
}
void deleteClusterEntry(Bytes& bytes, const Image& image, const Node& node) {
const size_t entry = findDirectoryEntry(image, image.find(node.parent), node);
std::fill_n(bytes.begin() + entry, 32, 0);
const size_t descriptor = node.descriptorSector * sectorSize;
if (--bytes[descriptor + 8]) return;
const size_t cluster = clusterSize(bytes);
std::set<size_t> owned{node.descriptorSector / cluster};
for (const size_t sector : node.dataSectors) owned.insert(sector / cluster);
const size_t mapSectors = (be(bytes, 4, 2) + sectorSize - 1) / sectorSize;
for (const size_t index : owned) {
if (index * cluster <= mapSectors) fail("A removed entry shares a reserved filesystem cluster.");
markCluster(bytes, index * cluster, false);
}
}
Bytes createClusterEntry(const Image& image, const Node& parentInput, const std::string& filename, const uint8_t *data, size_t length, bool directory, bool replace) {
Bytes bytes = image.bytes; Node parent = parentInput;
const auto path = parent.path.empty() ? filename : parent.path + '/' + filename;
auto existing = image.nodes.find(lower(path));
if (existing != image.nodes.end()) {
if (!replace || existing->second.directory) fail("An entry already has that name.");
deleteClusterEntry(bytes, image, existing->second);
const size_t offset = findDirectoryEntry(image, parent, existing->second);
for (size_t logical = 0; logical < parent.content.size(); logical += 32)
if (directoryOffset(parent, logical) == offset) std::fill_n(parent.content.begin() + logical, 32, 0);
}
const size_t cluster = clusterSize(bytes), descriptor = allocateCluster(bytes);
Node node; node.descriptorSector = descriptor; node.directory = directory;
const size_t base = descriptor * sectorSize;
bytes[base] = directory ? 0xbf : 0x0b; bytes[base + 8] = 1;
NSDateComponents *now = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:NSDate.date];
bytes[base + 3] = uint8_t(now.year - 1900); bytes[base + 4] = uint8_t(now.month); bytes[base + 5] = uint8_t(now.day); bytes[base + 6] = uint8_t(now.hour); bytes[base + 7] = uint8_t(now.minute);
std::copy_n(bytes.begin() + base + 3, 3, bytes.begin() + base + 13);
if (cluster > 1) appendSegment(bytes, node, descriptor + 1, cluster - 1);
Bytes directoryData;
if (directory) {
directoryData.resize(64); const auto dot = directoryEntry(".", descriptor), up = directoryEntry("..", parent.descriptorSector);
std::copy(dot.begin(), dot.end(), directoryData.begin()); std::copy(up.begin(), up.end(), directoryData.begin() + 32);
data = directoryData.data(); length = directoryData.size();
}
while (node.dataSectors.size() * sectorSize < length) appendSegment(bytes, node, allocateCluster(bytes), cluster);
for (size_t logical = 0; logical < length; ++logical) bytes[node.dataSectors[logical / sectorSize] * sectorSize + logical % sectorSize] = data[logical];
putBigEndian(bytes, base + 9, 4, length); insertEntry(bytes, parent, filename, descriptor);
return bytes;
}
Bytes movedOS9Files(const Image& image, NSArray<NSString *> *paths, NSString *destination) {
if (image.decb) fail("Moving files between folders is available only for OS-9 images.");
if (paths.count == 0 || paths.count > 4096) fail("Select from one to 4096 regular files to move.");
Node target = image.find(imagePath(destination, false, true));
if (!target.directory) fail("Choose an OS-9 destination folder.");
struct Move { const Node *node; size_t offset; std::array<uint8_t,32> entry; };
std::vector<Move> moves; std::set<std::string> sources, names;
for (NSString *path in paths) {
if (![path isKindOfClass:NSString.class]) fail("Select valid image paths to move.");
const auto& node = image.find(imagePath(path, false));
if (node.directory) fail("Move regular files only. Folders are destinations and cannot be moved.");
if (!sources.insert(lower(node.path)).second) fail("A file was selected more than once. Refresh the selection.");
if (lower(node.parent) == lower(target.path)) fail("The selected file is already in that folder. Choose a different destination.");
const auto dest = target.path.empty() ? node.name : target.path + '/' + node.name;
if (!names.insert(lower(node.name)).second || image.nodes.count(lower(dest)))
fail("A destination name already exists or repeats within the selection. No files were moved; choose another folder.");
const size_t offset = findDirectoryEntry(image, image.find(node.parent), node);
Move move{&node, offset, {}}; std::copy_n(image.bytes.begin() + offset, 32, move.entry.begin()); moves.push_back(move);
}
Bytes next = image.bytes;
for (const auto& move : moves) {
size_t slot = 0;
while (slot < target.content.size() && target.content[slot]) slot += 32;
if (slot == target.content.size()) {
if (slot + 32 > target.dataSectors.size() * sectorSize) growDirectory(next, target);
target.content.resize(slot + 32, 0); target.size = target.content.size();
putBigEndian(next, target.descriptorSector * sectorSize + 9, 4, target.size);
}
const size_t offset = directoryOffset(target, slot);
std::copy(move.entry.begin(), move.entry.end(), next.begin() + offset);
std::copy(move.entry.begin(), move.entry.end(), target.content.begin() + slot);
}
// A plan is complete before any source entry is removed or any file is
// written. Failure at any point leaves the caller's working image intact.
for (const auto& move : moves) std::fill_n(next.begin() + move.offset, 32, 0);
for (const auto& move : moves) {
const size_t descriptor = move.node->descriptorSector * sectorSize;
if (!std::equal(image.bytes.begin() + descriptor, image.bytes.begin() + descriptor + sectorSize, next.begin() + descriptor))
fail("A move changed a file descriptor; no changes were kept.");
for (const size_t sector : move.node->dataSectors)
if (!std::equal(image.bytes.begin() + sector * sectorSize, image.bytes.begin() + (sector + 1) * sectorSize, next.begin() + sector * sectorSize))
fail("A move changed file data; no changes were kept.");
}
return next;
}
void setError(NSError **error, const std::exception& value) { if (error) *error = [NSError errorWithDomain:@"VCCDiskImageEditor" code:1 userInfo:@{NSLocalizedDescriptionKey:text(value.what())}]; }
void restore(NSURL *url, const Bytes& bytes) { NSError *error = nil; if (![[NSData dataWithBytes:bytes.data() length:bytes.size()] writeToURL:url options:NSDataWritingAtomic error:&error]) fail("A working-image operation failed and its private copy could not be restored. Close the editor and reopen the original image."); }
template<class Operation> BOOL mutate(NSURL *url, Operation operation, NSError **error) {
std::lock_guard<std::recursive_mutex> lock(backendMutex);
try {
auto image = inspect(url);
try {
operation(image);
const auto after = load(url);
if (after.size() != image.bytes.size() ||
(image.decb && !std::equal(image.bytes.begin() + decbVolumeBytes, image.bytes.end(), after.begin() + decbVolumeBytes)))
fail("The filesystem operation changed the image size or protected supplementary tracks. The private working image has been restored.");
(void)inspect(url);
}
catch (...) { restore(url, image.bytes); throw; }
return YES;
} catch (const std::exception& value) { setError(error, value); return NO; }
}
NSString *attributes(unsigned bits) {
NSMutableArray *items = [NSMutableArray array];
for (const auto& item : std::array<std::pair<unsigned,const char *>,8>{{{0x80,"d"},{0x40,"s"},{1,"r"},{2,"w"},{4,"e"},{8,"pr"},{16,"pw"},{32,"pe"}}}) if (bits & item.first) [items addObject:@(item.second)];
return [items componentsJoinedByString:@" "];
}
}
@implementation VCCDiskImageEditorBackend
+ (NSArray<NSDictionary<NSString *,id> *> *)discoverVolumesAtURL:(NSURL *)imageURL error:(NSError **)error {
std::lock_guard<std::recursive_mutex> lock(backendMutex);
try {
diskimage_format format = DISKIMAGE_UNKNOWN;
if (_diskimage_identify(imageURL.fileSystemRepresentation, &format) || format != DISKIMAGE_RAW)
fail("The editor supports raw floppy and hard-drive images; other containers are preserved without conversion.");
const auto bytes = load(imageURL); const auto volumes = discover(bytes);
NSMutableArray *rows = [NSMutableArray array];
for (const auto& volume : volumes) [rows addObject:@{@"id":text(volume.id), @"format":text(volume.format), @"name":text(volume.name), @"offset_bytes":@(volume.offset), @"byte_count":@(volume.length), @"index":@(volume.index)}];
return rows;
} catch (const std::exception& value) { setError(error, value); return nil; }
}
+ (BOOL)extractVolume:(NSString *)volumeID imageURL:(NSURL *)imageURL outputURL:(NSURL *)outputURL error:(NSError **)error {
std::lock_guard<std::recursive_mutex> lock(backendMutex);
try { const auto bytes = load(imageURL); const auto volumes = discover(bytes); const auto volume = selected(volumes, volumeID);
if ([imageURL.URLByResolvingSymlinksInPath isEqual:outputURL.URLByResolvingSymlinksInPath]) fail("Extract a volume to a separate private working file.");
Bytes part(bytes.begin() + volume.offset, bytes.begin() + volume.offset + volume.length);
if (volume.format == "os9" && !externalBootRanges(bytes, volume.length).empty()) clearExternalBootPointer(part);
restore(outputURL, part); return YES;
} catch (const std::exception& value) { setError(error, value); return NO; }
}
+ (BOOL)replaceVolume:(NSString *)volumeID imageURL:(NSURL *)imageURL volumeURL:(NSURL *)volumeURL error:(NSError **)error {
std::lock_guard<std::recursive_mutex> lock(backendMutex);
try { auto bytes = load(imageURL); const auto volumes = discover(bytes); const auto volume = selected(volumes, volumeID); const auto part = inspect(volumeURL);
if (part.bytes.size() != volume.length || part.decb != (volume.format == "decb")) fail("The edited volume changed its size or filesystem type. No changes were applied.");
const bool externalBoot = volume.format == "os9" && !externalBootRanges(bytes, volume.length).empty();
std::array<uint8_t,5> pointer{};
if (externalBoot) std::copy_n(bytes.begin() + offsetof(lsn0_sect, dd_bt), 5, pointer.begin());
std::copy(part.bytes.begin(), part.bytes.end(), bytes.begin() + volume.offset);
if (externalBoot) std::copy(pointer.begin(), pointer.end(), bytes.begin() + offsetof(lsn0_sect, dd_bt));
(void)discover(bytes); // validate the original boot pointer in its full container context
restore(imageURL, bytes); return YES;
} catch (const std::exception& value) { setError(error, value); return NO; }
}
+ (NSDictionary<NSString *,id> *)inspectImageAtURL:(NSURL *)imageURL error:(NSError **)error {
std::lock_guard<std::recursive_mutex> lock(backendMutex);
try { const auto image = inspect(imageURL); return @{@"format":image.decb ? @"decb" : @"os9", @"format_name":image.decb ? @"Disk BASIC" : @"OS-9 RBF", @"byte_count":@(image.bytes.size()), @"writable":@YES, @"capacity_bytes":@(image.capacity), @"used_bytes":@(image.capacity - image.free), @"free_bytes":@(image.free), @"allocation_unit_bytes":@(image.unit), @"protected_suffix_bytes":@(image.decb ? image.bytes.size() - decbVolumeBytes : 0)}; }
catch (const std::exception& value) { setError(error, value); return nil; }
}
+ (NSArray<NSDictionary<NSString *,id> *> *)listDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error {
std::lock_guard<std::recursive_mutex> lock(backendMutex);
try {
const auto image = inspect(imageURL); const auto path = imagePath(directory, image.decb, true); const auto& folder = image.find(path); if (!folder.directory) fail("This entry is not a directory.");
NSMutableArray *rows = [NSMutableArray array];
for (const auto& pair : image.nodes) { const auto& n = pair.second; if (n.path.empty() || lower(n.parent) != lower(folder.path)) continue;
NSString *type = image.decb ? @[@"BASIC program",@"BASIC data",@"Machine language",@"Text"][n.type] : n.directory ? @"Folder" : @"OS-9 file";
[rows addObject:@{@"name":text(n.name),@"path":text(n.path),@"size":@(n.size),@"is_directory":@(n.directory),@"type":type,@"file_type":image.decb ? @(n.type) : NSNull.null,@"encoding":image.decb ? (n.ascii ? @"ASCII" : @"Binary") : @"",@"ascii":@(n.ascii != 0),@"attributes":image.decb ? @"" : attributes(n.attributes),@"permissions":image.decb ? NSNull.null : @(n.attributes & 0x7f),@"owner":@(n.owner),@"group":@(n.group),@"modified":n.modified}]; }
return rows;
} catch (const std::exception& value) { setError(error, value); return nil; }
}
+ (NSData *)readFile:(NSString *)path imageURL:(NSURL *)imageURL error:(NSError **)error {
std::lock_guard<std::recursive_mutex> lock(backendMutex);
try { const auto image = inspect(imageURL); return readEntry(imageURL, image, imagePath(path, image.decb)); }
catch (const std::exception& value) { setError(error, value); return nil; }
}
+ (NSString *)identifyFile:(NSString *)path imageURL:(NSURL *)imageURL error:(NSError **)error {
std::lock_guard<std::recursive_mutex> lock(backendMutex);
try {
const auto image = inspect(imageURL); NSData *data = readEntry(imageURL, image, imagePath(path, image.decb)); const auto *begin = static_cast<const uint8_t *>(data.bytes); Bytes bytes(begin, begin + data.length);
NSMutableArray *modules = [NSMutableArray array]; size_t offset = 0;
while (offset < bytes.size()) {
const bool os9 = bytes.size() - offset >= OS9_HEADER_SIZE && be(bytes, offset, 2) == 0x87cd;
const bool osk = bytes.size() - offset >= OSK_HEADER_SIZE && be(bytes, offset, 2) == 0x4afc;
if (!os9 && !osk) fail("The selected file does not contain a complete supported OS-9 module.");
const size_t header = os9 ? OS9_HEADER_SIZE : OSK_HEADER_SIZE, size = be(bytes, offset + (os9 ? 2 : 4), os9 ? 2 : 4), nameOffset = be(bytes, offset + (os9 ? 4 : 12), os9 ? 2 : 4);
if (size < header + 3 || size > bytes.size() - offset || nameOffset >= size - 3) fail("The OS-9 module has a truncated or invalid header.");
std::string moduleName; bool ended = false;
for (size_t i = nameOffset; i < size - 3 && moduleName.size() < 255; ++i) { const auto c = bytes[offset + i]; if ((c & 127) < 32 || (c & 127) > 126) fail("The OS-9 module name is invalid."); moduleName += char(c & 127); if (c & 128) { ended = true; break; } }
if (!ended) fail("The OS-9 module name is not terminated.");
u_char crc[3] = {255,255,255}; const bool good = _os9_crc_compute(bytes.data() + offset, u_int(size), crc) != 0;
[modules addObject:[NSString stringWithFormat:@"%@ module: %@\nOffset: %zu bytes\nSize: %zu bytes\nCRC: %@",os9 ? @"OS-9/6809" : @"OS-9/68K",text(moduleName),offset,size,good ? @"Valid" : @"Mismatch"]];
offset += size;
}
if (!modules.count) fail("The selected file is empty."); return [modules componentsJoinedByString:@"\n\n"];
} catch (const std::exception& value) { setError(error, value); return nil; }
}
+ (BOOL)importData:(NSData *)data named:(NSString *)filename directory:(NSString *)directory imageURL:(NSURL *)imageURL fileType:(NSInteger)fileType ascii:(BOOL)ascii replace:(BOOL)replace error:(NSError **)error {
return mutate(imageURL, [&](const Image& image) {
if (data.length > fileLimit || fileType < 0 || fileType > 3) fail("Choose a supported file type and a file no larger than 16 MiB.");
const auto dir = imagePath(directory, image.decb, true); const auto& parent = image.find(dir); if (!parent.directory) fail("The import destination is not a directory.");
const auto base = name(string(filename), image.decb); const auto dest = parent.path.empty() ? base : parent.path + '/' + base;
const auto existing = image.nodes.find(lower(dest)); if (existing != image.nodes.end() && (!replace || existing->second.directory)) fail(existing->second.directory ? "A directory already has that name." : "A file already has that name. Confirm replacement or use a different name.");
if (data.length > image.capacity) fail("This file is larger than the disk's usable capacity.");
if (!image.decb && image.unit > sectorSize) { restore(imageURL, createClusterEntry(image, parent, base, static_cast<const uint8_t *>(data.bytes), data.length, false, replace)); return; }
OpenPath file(image.decb); auto path = toolPath(imageURL, dest);
if (image.decb) { decb_path_id opened = nullptr; check(_decb_create(&opened,path.data(),FAM_WRITE | (replace ? 0 : FAM_NOCREATE),int(fileType),ascii ? 255 : 0),"Create image file"); file.d = opened; }
else { os9_path_id opened = nullptr; check(_os9_create(&opened,path.data(),FAM_WRITE | (replace ? 0 : FAM_NOCREATE),FAP_READ|FAP_WRITE|FAP_PREAD),"Create image file"); file.o = opened; }
size_t offset = 0; const auto *bytes = static_cast<const uint8_t *>(data.bytes);
while (offset < data.length) { u_int count = u_int(data.length - offset); const auto result = image.decb ? _decb_write(file.d,const_cast<uint8_t *>(bytes + offset),&count) : _os9_write(file.o,const_cast<uint8_t *>(bytes + offset),&count); check(result,"Write image file"); if (!count || count > data.length - offset) fail("The image writer did not complete the file."); offset += count; }
file.close();
}, error);
}
+ (BOOL)makeDirectory:(NSString *)filename inDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error {
return mutate(imageURL, [&](const Image& image) { if (image.decb) fail("Disk BASIC images do not support folders."); const auto dir = imagePath(directory,false,true); const auto& parent = image.find(dir); if (!parent.directory) fail("The destination is not a directory."); const auto base = name(string(filename),false); const auto dest = parent.path.empty() ? base : parent.path + '/' + base; if (image.nodes.count(lower(dest))) fail("An entry already has that name."); if (image.unit > sectorSize) { restore(imageURL, createClusterEntry(image, parent, base, nullptr, 0, true, false)); return; } auto path = toolPath(imageURL,dest); check(_os9_makdir(path.data()),"Create OS-9 directory"); }, error);
}
+ (BOOL)renameEntry:(NSString *)entry toName:(NSString *)filename imageURL:(NSURL *)imageURL error:(NSError **)error {
return mutate(imageURL, [&](const Image& image) { const auto& node = image.find(imagePath(entry,image.decb)); const auto base = name(string(filename),image.decb); const auto dest = node.parent.empty() ? base : node.parent + '/' + base; if (image.nodes.count(lower(dest))) fail("An entry already has that name."); if (!image.decb && image.unit > sectorSize) { auto bytes = image.bytes; const size_t offset = findDirectoryEntry(image, image.find(node.parent), node); const auto entry = directoryEntry(base, node.descriptorSector); std::copy(entry.begin(), entry.end(), bytes.begin() + offset); restore(imageURL, bytes); return; } auto path = toolPath(imageURL,node.path); std::vector<char> newName(base.begin(),base.end());newName.push_back(0); check(image.decb ? _decb_rename(path.data(),newName.data()) : _os9_rename(path.data(),newName.data()),"Rename image entry"); }, error);
}
+ (BOOL)deleteEntry:(NSString *)entry directory:(BOOL)directory imageURL:(NSURL *)imageURL error:(NSError **)error {
return mutate(imageURL, [&](const Image& image) { const auto& node = image.find(imagePath(entry,image.decb)); if (node.directory != bool(directory)) fail("The selected entry changed type. Refresh the directory."); if (node.directory) for (const auto& pair : image.nodes) if (!pair.second.path.empty() && lower(pair.second.parent) == lower(node.path)) fail("Delete the folder's contents before deleting the folder."); if (!image.decb && image.unit > sectorSize) { auto bytes = image.bytes; deleteClusterEntry(bytes, image, node); restore(imageURL, bytes); return; } auto path = toolPath(imageURL,node.path); check(image.decb ? _decb_kill(path.data()) : node.directory ? _os9_delete_directory(path.data()) : _os9_delete(path.data()),"Delete image entry"); }, error);
}
+ (BOOL)moveFiles:(NSArray<NSString *> *)paths toDirectory:(NSString *)directory imageURL:(NSURL *)imageURL error:(NSError **)error {
return mutate(imageURL, [&](const Image& image) { restore(imageURL, movedOS9Files(image, paths, directory)); }, error);
}
+ (BOOL)setOS9MetadataForPath:(NSString *)entry imageURL:(NSURL *)imageURL ownerUser:(NSInteger)ownerUser ownerGroup:(NSInteger)ownerGroup permissions:(NSInteger)permissions error:(NSError **)error {
return mutate(imageURL, [&](const Image& image) {
if (image.decb) fail("Disk BASIC entries do not have OS-9 ownership or permission attributes.");
if (ownerUser < 0 || ownerUser > 255 || ownerGroup < 0 || ownerGroup > 255 || permissions < 0 || permissions > 127)
fail("Use owner user and group values from 0 to 255 and permission bits from 0 to 127. The directory type cannot be changed.");
const auto& node = image.find(imagePath(entry, false, true));
// Host disk maintenance deliberately does not impersonate a guest UID.
// A raw RBF path can repair even an entry with no guest access bits,
// without changing it temporarily or bypassing host write protection.
if (image.unit > sectorSize) { auto bytes = image.bytes; const size_t offset = node.descriptorSector * sectorSize; bytes[offset] = uint8_t((bytes[offset] & 0x80) | permissions); bytes[offset + 1] = uint8_t(ownerGroup); bytes[offset + 2] = uint8_t(ownerUser); restore(imageURL, bytes); return; }
OpenPath raw(false); raw.open(imageURL, "@", FAM_WRITE);
fd_stats descriptor{};
check(_os9_lsn_get(raw.o, int(node.descriptorSector), 0, &descriptor, sizeof(descriptor)), "Read OS-9 descriptor");
const size_t offset = node.descriptorSector * sectorSize;
const auto *actual = reinterpret_cast<const uint8_t *>(&descriptor);
if (!std::equal(actual, actual + sizeof(descriptor), image.bytes.begin() + offset))
fail("The OS-9 descriptor changed while its metadata was being edited.");
descriptor.fd_att = static_cast<u_char>((descriptor.fd_att & FAP_DIR) | permissions);
descriptor.fd_own[0] = static_cast<u_char>(ownerGroup);
descriptor.fd_own[1] = static_cast<u_char>(ownerUser);
check(_os9_lsn_put(raw.o, int(node.descriptorSector), 0, &descriptor, sizeof(descriptor)), "Write OS-9 metadata");
raw.close();
auto expected = image.bytes;
expected[offset] = descriptor.fd_att;
expected[offset + 1] = descriptor.fd_own[0];
expected[offset + 2] = descriptor.fd_own[1];
if (load(imageURL) != expected) fail("The metadata edit changed bytes outside the entry's attributes and owner. The private working image has been restored.");
}, error);
}
@end
+106
View File
@@ -0,0 +1,106 @@
#pragma once
#include <algorithm>
#include <array>
#include <cstdint>
#include <vector>
namespace VCC::Mac {
using TerminalGrid = std::array<std::array<char, 80>, 24>;
// Encode an addressed terminal screen for the stock NitrOS-9 telnet client's
// output path, which passes ordinary bytes straight through to CoWin.
class DriveWireTerminalOutput {
public:
static constexpr std::size_t maxDrawBytes = 2010;
void draw(const TerminalGrid& cells, int x, int y, bool cursorVisible,
bool clear, std::vector<std::uint8_t>& out) {
const auto start = out.size();
if (clear || !known) {
out.push_back(0x0c);
for (auto& row : painted) row.fill(' ');
cursorX = cursorY = -1;
visibilityKnown = false;
known = true;
}
constexpr int bottom = 23;
for (int row = 0; row < bottom - 1; ++row) {
paintRow(row, cells[row], out);
}
// GRFDRV wraps immediately after the last column. To write the
// bottom-right cell without scrolling away the first line, prepare
// the last row one line up and move it down with CoWin's insert-line.
// Ordinary changes elsewhere on the bottom row avoid that extra work.
if (glyph(cells[bottom].back()) != painted[bottom].back()) {
paintRow(bottom - 1, cells[bottom], out);
position(0, bottom - 1, out);
out.insert(out.end(), {0x1f, 0x30});
painted[bottom] = painted[bottom - 1];
painted[bottom - 1].fill(' ');
} else {
paintRow(bottom, cells[bottom], out);
}
paintRow(bottom - 1, cells[bottom - 1], out);
// CoWin may move the cursor on a write, including automatic wrapping.
// Reposition it even when the logical position itself didn't change.
x = std::clamp(x, 0, 79);
y = std::clamp(y, 0, 23);
if (out.size() != start || x != cursorX || y != cursorY) {
position(x, y, out);
cursorX = x;
cursorY = y;
}
if (!visibilityKnown || visible != cursorVisible) {
out.insert(out.end(), {0x05, static_cast<std::uint8_t>(cursorVisible ? 0x21 : 0x20)});
visible = cursorVisible;
visibilityKnown = true;
}
}
private:
using Row = TerminalGrid::value_type;
TerminalGrid painted{};
int cursorX = -1, cursorY = -1;
bool known = false, visibilityKnown = false, visible = true;
static char glyph(char ch) {
const auto byte = static_cast<unsigned char>(ch);
return byte >= 0x20 && byte <= 0x7e ? ch : '?';
}
static void position(int x, int y, std::vector<std::uint8_t>& out) {
out.insert(out.end(), {0x02, static_cast<std::uint8_t>(0x20 + x),
static_cast<std::uint8_t>(0x20 + y)});
}
void paintRow(int row, const Row& desired, std::vector<std::uint8_t>& out) {
auto& current = painted[row];
std::size_t x = 0;
while (x < desired.size()) {
if (current[x] == glyph(desired[x])) {
++x;
continue;
}
const auto first = x;
position(static_cast<int>(x), row, out);
auto lastChange = x;
// Repaint short gaps: an absolute cursor move costs three bytes.
// Even an alternating pattern costs at most 83 bytes per row.
while (x < desired.size() && x - lastChange <= 4) {
if (current[x] != glyph(desired[x])) lastChange = x;
++x;
}
for (auto column = first; column <= lastChange; ++column) {
current[column] = glyph(desired[column]);
out.push_back(static_cast<std::uint8_t>(current[column]));
}
}
}
};
} // namespace VCC::Mac
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "DriveWireShell.h"
#include "../../../src/devices/DriveWireTransport.h"
#include <strings.h>
namespace VCC::Mac {
inline std::unique_ptr<Devices::DriveWireTransport> openDriveWireEndpoint(
DriveWireShell& shell, const std::string& host, uint16_t port) {
// This name exists only inside the emulator. Never send it to DNS or
// redirect normal localhost connections to a privileged command prompt.
if (strcasecmp(host.c_str(), "macshell") == 0)
return port == 2323 ? shell.connect() : nullptr;
return Devices::makeDriveWireTCPConnection(host, port);
}
}
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "devices/DriveWireTransport.h"
#include <memory>
#include <string>
namespace VCC::Mac {
// An explicit, one-use invitation for this emulator's guest. No network listener.
class DriveWireShell {
public:
enum class StartupFiles { user, isolatedTest };
explicit DriveWireShell(StartupFiles files = StartupFiles::user);
~DriveWireShell();
void arm();
std::uint64_t requestID() const;
bool decide(std::uint64_t id, bool allow);
void stop();
std::string status() const;
std::unique_ptr<Devices::DriveWireTransport> connect();
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
}
+368
View File
@@ -0,0 +1,368 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "DriveWireShell.h"
#include "DriveWireTerminal.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <deque>
#include <fcntl.h>
#include <limits.h>
#include <mutex>
#include <poll.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <termios.h>
#include <thread>
#include <unistd.h>
#include <util.h>
#include <vector>
namespace VCC::Mac {
namespace {
using Transport = Devices::DriveWireTransport;
using State = Transport::State;
using namespace std::chrono_literals;
constexpr std::size_t queueLimit = 65536;
struct Child {
pid_t pid = -1;
int master = -1;
~Child() {
if (master >= 0) ::close(master);
}
};
// Spawn directly into a fresh session. The child gets only its three tty
// descriptors and a small interactive environment. No login helper, command
// string, or user-supplied executable path is involved.
bool spawnShell(Child& child, DriveWireShell::StartupFiles startup) {
passwd record{}, *user = nullptr;
std::array<char, 32768> account{};
if (::getpwuid_r(::getuid(), &record, account.data(), account.size(), &user) || !user) return false;
std::string home = record.pw_dir, shell = record.pw_shell, name = record.pw_name;
if (home.empty() || home.front() != '/' || shell.empty() || shell.front() != '/') return false;
int slave = -1;
winsize size{24, 80, 0, 0};
char tty[PATH_MAX]{};
if (::openpty(&child.master, &slave, tty, nullptr, &size) != 0) return false;
if (::fcntl(child.master, F_SETFD, FD_CLOEXEC) < 0 || ::fcntl(slave, F_SETFD, FD_CLOEXEC) < 0 ||
::fcntl(child.master, F_SETFL, O_NONBLOCK) < 0) {
::close(slave);
return false;
}
termios modes{};
if (::tcgetattr(slave, &modes) == 0) {
modes.c_cc[VERASE] = 8; // CoCo backspace
::tcsetattr(slave, TCSANOW, &modes);
}
std::string term = "TERM=vt100", path = "PATH=/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin";
std::string dir = "HOME=" + home, login = "LOGNAME=" + name, uid = "USER=" + name, sh = "SHELL=" + shell;
std::string locale = "LANG=en_US.UTF-8", prompt = "PS1=$ ", history = "HISTFILE=/dev/null";
// Ordinary sessions use the account's interactive login shell. Only
// the integration tests suppress personal startup scripts and history.
auto base = shell.substr(shell.find_last_of('/') + 1);
bool isolated = startup == DriveWireShell::StartupFiles::isolatedTest;
if (isolated && base != "zsh" && base != "bash") { shell = "/bin/sh"; sh = "SHELL=" + shell; base = "sh"; }
std::vector<std::string> options{isolated ? base : "-" + base};
if (isolated && base == "zsh") options.insert(options.end(), {"-f", "-o", "no_zle"});
if (isolated && base == "bash") options.insert(options.end(), {"--noprofile", "--norc", "--noediting"});
options.emplace_back("-i");
std::vector<char*> args;
for (auto& option : options) args.push_back(option.data());
args.push_back(nullptr);
std::vector<char*> env{dir.data(), login.data(), uid.data(), sh.data(), term.data(), path.data(), locale.data()};
if (isolated) { env.push_back(prompt.data()); env.push_back(history.data()); }
env.push_back(nullptr);
// These pointers and limits are computed before fork. The child of the
// multithreaded Mac app uses only descriptor/signal syscalls and execve.
auto executable = shell.c_str();
auto directory = home.c_str();
auto arguments = args.data();
auto environment = env.data();
const int maxFD = static_cast<int>(::sysconf(_SC_OPEN_MAX));
int handshake[2]{};
if (maxFD < 3 || ::pipe(handshake) < 0) { ::close(slave); return false; }
if (::fcntl(handshake[0], F_SETFD, FD_CLOEXEC) < 0 || ::fcntl(handshake[1], F_SETFD, FD_CLOEXEC) < 0) {
::close(slave); ::close(handshake[0]); ::close(handshake[1]); return false;
}
sigset_t mask;
sigemptyset(&mask);
struct sigaction defaults{};
defaults.sa_handler = SIG_DFL;
sigemptyset(&defaults.sa_mask);
child.pid = ::fork();
if (child.pid == 0) {
::close(handshake[0]);
bool ok = ::setsid() >= 0 && ::ioctl(slave, TIOCSCTTY, 0) == 0;
for (int fd = 0; ok && fd < 3; ++fd)
ok = ::dup2(slave, fd) >= 0 && ::fcntl(fd, F_SETFD, 0) == 0;
for (int fd = 3; fd < maxFD; ++fd) if (fd != handshake[1]) ::close(fd);
for (int signal = 1; signal < NSIG; ++signal) {
if (signal != SIGKILL && signal != SIGSTOP) ::sigaction(signal, &defaults, nullptr);
}
::sigprocmask(SIG_SETMASK, &mask, nullptr);
if (ok && ::chdir(directory) == 0) ::execve(executable, arguments, environment);
const char failed = 1;
(void)::write(handshake[1], &failed, 1);
_exit(127);
}
::close(slave);
::close(handshake[1]);
char failure;
ssize_t result;
do { result = ::read(handshake[0], &failure, 1); } while (result < 0 && errno == EINTR);
::close(handshake[0]);
if (child.pid < 0) return false;
if (result == 0) return true;
while (::waitpid(child.pid, nullptr, 0) < 0 && errno == EINTR) {}
return false;
}
void hangup(Child& child) {
// Closing a controlling tty sends HUP to its foreground group. Also signal
// the shell's own group when a foreground job has taken control. Keep its
// pid unreaped until sending signals is finished to avoid pid reuse.
pid_t foreground = ::tcgetpgrp(child.master);
if (foreground > 0 && foreground != child.pid && ::getsid(foreground) == child.pid) {
::kill(-foreground, SIGHUP);
::kill(-foreground, SIGCONT);
// Explicit revocation must also stop a foreground program that traps
// terminal hangups. Limit the signal to the shell's own session.
if (::getsid(foreground) == child.pid) ::kill(-foreground, SIGKILL);
}
::kill(-child.pid, SIGHUP);
::kill(-child.pid, SIGCONT);
::close(child.master);
child.master = -1;
for (unsigned i = 0; i < 20; ++i) {
int status = 0;
pid_t done = ::waitpid(child.pid, &status, WNOHANG);
if (done == child.pid || (done < 0 && errno == ECHILD)) return;
std::this_thread::sleep_for(10ms);
}
::kill(child.pid, SIGKILL);
while (::waitpid(child.pid, nullptr, 0) < 0 && errno == EINTR) {}
}
// Option (the CoCo Alt key) distinguishes cursor keys from OS-9 editing
// characters. The stock telnet client sends the corresponding high-bit codes.
char cursorDirection(std::uint8_t key) {
switch (key) {
case 0x8c: return 'A'; // up
case 0x8a: return 'B'; // down
case 0x89: return 'C'; // right
case 0x88: return 'D'; // left
default: return 0;
}
}
class Terminal {
public:
std::atomic<State> state{State::connecting};
std::atomic<bool> stopped{false};
std::atomic<bool> launched{false};
const std::chrono::steady_clock::time_point expires = std::chrono::steady_clock::now() + 2min;
bool waiting() const {
return !launched && !stopped && state == State::connecting && std::chrono::steady_clock::now() < expires;
}
State transportState() const {
if (!launched && !waiting()) return State::failed;
return stopped ? State::closed : state.load();
}
void cancel() {
std::lock_guard lock(mutex);
stopped = true;
incoming.clear();
outgoing.clear();
}
std::size_t read(std::uint8_t* bytes, std::size_t count) {
std::lock_guard lock(mutex);
if (stopped) return 0;
count = std::min(count, incoming.size());
std::copy_n(incoming.begin(), count, bytes);
incoming.erase(incoming.begin(), incoming.begin() + count);
return count;
}
bool write(const std::uint8_t* bytes, std::size_t count) {
std::lock_guard lock(mutex);
if (stopped || state != State::connected || count > queueLimit - outgoing.size()) return false;
// The stock OS-9 telnet client sends its abort byte for CoCo Break
// (Mac Escape). Backspace and Tab also double as left/right on the
// wire; keep their normal shell meanings.
const auto arrows = std::count_if(bytes, bytes + count, cursorDirection);
if (count + 2 * arrows > queueLimit - outgoing.size()) return false;
for (std::size_t i = 0; i < count; ++i) {
if (auto direction = cursorDirection(bytes[i])) {
outgoing.push_back(0x1b);
outgoing.push_back(applicationKeys ? 'O' : '[');
outgoing.push_back(direction);
} else {
outgoing.push_back(bytes[i] == 0x05 ? 0x1b : bytes[i]);
}
}
return true;
}
void run(DriveWireShell::StartupFiles startup) {
Child child;
if (stopped || !spawnShell(child, startup)) { state = State::failed; return; }
state = State::connected;
bool reaped = false;
DriveWireTerminal terminal;
std::vector<std::uint8_t> display;
std::size_t displayOffset = 0;
while (!stopped) {
std::array<std::uint8_t, 4096> data{};
std::size_t room, pending;
{
std::lock_guard lock(mutex);
// One PTY read can expand into a screen redraw. Drain that redraw
// in order before consuming more output, even after shell exit.
auto transfer = std::min(display.size() - displayOffset, queueLimit - incoming.size());
incoming.insert(incoming.end(), display.begin() + displayOffset,
display.begin() + displayOffset + transfer);
displayOffset += transfer;
room = displayOffset == display.size() && incoming.size() < queueLimit ? data.size() : 0;
pending = std::min(data.size(), outgoing.size());
}
if (!reaped) {
pid_t result = ::waitpid(child.pid, nullptr, WNOHANG);
reaped = result == child.pid || (result < 0 && errno == ECHILD);
}
pollfd descriptor{child.master, short((room ? POLLIN : 0) | (pending ? POLLOUT : 0)), 0};
if (!room && !pending) { std::this_thread::sleep_for(10ms); continue; }
int result = ::poll(&descriptor, 1, 10);
if (result < 0 && errno == EINTR) continue;
if (result < 0) break;
if (pending && (descriptor.revents & POLLOUT)) {
std::lock_guard lock(mutex);
if (stopped) break;
std::copy_n(outgoing.begin(), pending, data.begin());
auto sent = ::write(child.master, data.data(), pending); // non-blocking PTY
if (sent > 0) outgoing.erase(outgoing.begin(), outgoing.begin() + sent);
else if (sent < 0 && errno != EINTR && errno != EAGAIN) break;
}
if (room && (descriptor.revents & (POLLIN | POLLHUP | POLLERR))) {
auto n = ::read(child.master, data.data(), room);
if (n > 0) {
display = terminal.consume(data.data(), static_cast<std::size_t>(n));
displayOffset = 0;
auto replies = terminal.takeReply();
std::lock_guard lock(mutex);
applicationKeys = terminal.applicationCursor();
if (stopped || replies.size() > queueLimit - outgoing.size()) break;
outgoing.insert(outgoing.end(), replies.begin(), replies.end());
continue; // collect any final output before reporting EOF
}
if (n < 0 && errno == EINTR) continue;
if (n <= 0 && (n == 0 || errno != EAGAIN || reaped)) break;
}
if (reaped && room) break;
}
if (!reaped) hangup(child);
state = State::closed;
}
private:
std::mutex mutex;
std::deque<std::uint8_t> incoming, outgoing;
bool applicationKeys = false; // guarded by mutex
};
class ShellChannel final : public Transport {
public:
explicit ShellChannel(std::shared_ptr<Terminal> terminal) : terminal(std::move(terminal)) {}
~ShellChannel() override { terminal->cancel(); }
State state() override { return terminal->transportState(); }
std::size_t read(std::uint8_t* bytes, std::size_t count) override { return terminal->read(bytes, count); }
bool write(const std::uint8_t* bytes, std::size_t count) override { return terminal->write(bytes, count); }
private:
std::shared_ptr<Terminal> terminal;
};
}
struct DriveWireShell::Impl {
explicit Impl(StartupFiles startup) : startup(startup) {}
StartupFiles startup;
mutable std::mutex mutex;
std::chrono::steady_clock::time_point readyUntil{};
std::weak_ptr<Terminal> active;
std::uint64_t sequence = 0, pendingID = 0;
void clear() {
readyUntil = {};
pendingID = 0;
if (auto current = active.lock()) current->cancel();
active.reset();
}
void start(const std::shared_ptr<Terminal>& live) {
live->launched = true;
try {
std::thread([live, files = startup]{ live->run(files); }).detach();
} catch (const std::system_error&) {
live->state = State::failed;
}
}
};
DriveWireShell::DriveWireShell(StartupFiles files) : impl(std::make_unique<Impl>(files)) {}
DriveWireShell::~DriveWireShell() { stop(); }
void DriveWireShell::arm() {
std::lock_guard lock(impl->mutex);
impl->clear();
impl->readyUntil = std::chrono::steady_clock::now() + 2min;
}
void DriveWireShell::stop() {
std::lock_guard lock(impl->mutex);
impl->clear();
}
std::string DriveWireShell::status() const {
std::lock_guard lock(impl->mutex);
if (std::chrono::steady_clock::now() < impl->readyUntil) return "ready";
if (auto live = impl->active.lock()) {
if (live->waiting()) return "requested";
auto state = live->transportState();
if (state == State::connecting || state == State::connected) return "connected";
}
return "idle";
}
std::uint64_t DriveWireShell::requestID() const {
std::lock_guard lock(impl->mutex);
auto live = impl->active.lock();
return live && live->waiting() ? impl->pendingID : 0;
}
bool DriveWireShell::decide(std::uint64_t id, bool allow) {
std::lock_guard lock(impl->mutex);
auto live = impl->active.lock();
if (!id || id != impl->pendingID || !live || !live->waiting()) return false;
impl->pendingID = 0;
if (allow) impl->start(live);
else live->state = State::failed;
return true;
}
std::unique_ptr<Transport> DriveWireShell::connect() {
std::lock_guard lock(impl->mutex);
if (auto live = impl->active.lock()) {
auto state = live->transportState();
if (state == State::connecting || state == State::connected) return {};
}
auto live = std::make_shared<Terminal>();
auto channel = std::make_unique<ShellChannel>(live);
impl->active = live;
if (std::chrono::steady_clock::now() < impl->readyUntil) {
impl->readyUntil = {};
impl->pendingID = 0;
impl->start(live);
} else {
if (!++impl->sequence) ++impl->sequence;
impl->pendingID = impl->sequence;
}
return channel;
}
}
+182
View File
@@ -0,0 +1,182 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "devices/DriveWireTransport.h"
#import <Network/Network.h>
#include <algorithm>
#include <deque>
#include <mutex>
#include <vector>
namespace VCC::Devices {
namespace {
using State = DriveWireTransport::State;
constexpr size_t bufferLimit = 64 * 1024;
constexpr size_t receiveChunk = 8192;
class Stream : public std::enable_shared_from_this<Stream> {
public:
explicit Stream(nw_connection_t connection) : connection(connection) {}
void start() {
auto weak = weak_from_this();
nw_connection_set_queue(connection, queue);
nw_connection_set_state_changed_handler(connection, ^(nw_connection_state_t state, nw_error_t) {
auto stream = weak.lock();
if (!stream) return;
switch (state) {
case nw_connection_state_ready:
{
std::lock_guard lock(stream->mutex);
if (stream->status != State::connecting) return;
stream->status = State::connected;
}
stream->receive();
break;
case nw_connection_state_failed:
case nw_connection_state_waiting:
stream->finish(State::failed);
break;
default:
break;
}
});
nw_connection_start(connection);
}
void finish(State reason) {
{
std::lock_guard lock(mutex);
if (status == State::closed || status == State::failed) return;
status = reason;
outgoing.clear();
}
nw_connection_force_cancel(connection);
}
State state() {
std::lock_guard lock(mutex);
return status;
}
size_t read(uint8_t* bytes, size_t capacity) {
std::lock_guard lock(mutex);
size_t count = std::min(capacity, incoming.size());
if (!count) return 0;
bool wasFull = incoming.size() == bufferLimit;
std::copy_n(incoming.begin(), count, bytes);
incoming.erase(incoming.begin(), incoming.begin() + count);
if (wasFull && status == State::connected) {
auto weak = weak_from_this();
dispatch_async(queue, ^{ if (auto stream = weak.lock()) stream->receive(); });
}
return count;
}
bool write(const uint8_t* bytes, size_t count) {
std::lock_guard lock(mutex);
if (status != State::connected || count > bufferLimit - outgoing.size() - inFlight) return false;
if (!count) return true;
outgoing.insert(outgoing.end(), bytes, bytes + count);
if (!sending) {
sending = true;
auto weak = weak_from_this();
dispatch_async(queue, ^{ if (auto stream = weak.lock()) stream->send(); });
}
return true;
}
private:
// Only the private serial network queue calls receive() and send().
void receive() {
size_t room;
{
std::lock_guard lock(mutex);
room = bufferLimit - incoming.size();
if (receiving || !room || status != State::connected) return;
receiving = true;
}
auto weak = weak_from_this();
nw_connection_receive(connection, 1, static_cast<uint32_t>(std::min(room, receiveChunk)),
^(dispatch_data_t data, nw_content_context_t, bool complete, nw_error_t error) {
auto stream = weak.lock();
if (!stream) return;
stream->receiving = false;
if (data) {
std::lock_guard lock(stream->mutex);
dispatch_data_apply(data, ^bool(dispatch_data_t, size_t, const void* buffer, size_t size) {
const auto* first = static_cast<const uint8_t*>(buffer);
stream->incoming.insert(stream->incoming.end(), first, first + size);
return true;
});
}
if (error || complete) stream->finish(error ? State::failed : State::closed);
else stream->receive();
});
}
void send() {
std::vector<uint8_t> batch;
{
std::lock_guard lock(mutex);
if (status != State::connected || outgoing.empty()) {
sending = false;
return;
}
batch.swap(outgoing);
inFlight = batch.size();
}
// The default destructor copies our temporary batch into the dispatch data.
auto data = dispatch_data_create(batch.data(), batch.size(), nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
auto weak = weak_from_this();
nw_connection_send(connection, data, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, ^(nw_error_t error) {
auto stream = weak.lock();
if (!stream) return;
{
std::lock_guard lock(stream->mutex);
stream->inFlight = 0;
}
if (error) stream->finish(State::failed);
else stream->send();
});
}
nw_connection_t connection;
dispatch_queue_t queue = dispatch_queue_create("com.brianholman.vccplus.drivewire.tcp", DISPATCH_QUEUE_SERIAL);
std::mutex mutex;
State status = State::connecting;
std::deque<uint8_t> incoming;
std::vector<uint8_t> outgoing;
size_t inFlight = 0;
bool sending = false;
bool receiving = false;
};
class TCPTransport final : public DriveWireTransport {
public:
explicit TCPTransport(std::shared_ptr<Stream> stream) : stream(std::move(stream)) {}
~TCPTransport() override { stream->finish(State::closed); }
State state() override { return stream->state(); }
size_t read(uint8_t* bytes, size_t capacity) override { return stream->read(bytes, capacity); }
bool write(const uint8_t* bytes, size_t count) override { return stream->write(bytes, count); }
private:
std::shared_ptr<Stream> stream;
};
} // namespace
std::unique_ptr<DriveWireTransport> makeDriveWireTCPConnection(const std::string& host, uint16_t port) {
if (host.empty() || host.find('\0') != std::string::npos || !port) return {};
auto endpoint = nw_endpoint_create_host(host.c_str(), std::to_string(port).c_str());
auto parameters = nw_parameters_create_secure_tcp(NW_PARAMETERS_DISABLE_PROTOCOL, ^(nw_protocol_options_t tcp) {
nw_tcp_options_set_connection_timeout(tcp, 10);
nw_tcp_options_set_no_delay(tcp, true);
});
auto connection = nw_connection_create(endpoint, parameters);
if (!connection) return {};
auto stream = std::make_shared<Stream>(connection);
stream->start();
return std::make_unique<TCPTransport>(std::move(stream));
}
} // namespace VCC::Devices
+349
View File
@@ -0,0 +1,349 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "DriveWireCoWin.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <utility>
#include <vector>
namespace VCC::Mac {
// A PTY advertises an 80x24 VT-style terminal. The historical OS-9 telnet
// client writes the received bytes straight to its CoWin window. Keep shell
// output relative until a program takes ownership of the screen so connecting
// does not erase the guest's login transcript.
class DriveWireTerminal {
public:
std::vector<std::uint8_t> consume(const std::uint8_t* bytes, std::size_t count) {
std::vector<std::uint8_t> output;
for (std::size_t i = 0; i < count; ++i) parse(bytes[i], output);
if (managed) {
auto& s = screen();
// A guest can quit telnet at any time. Leave its native cursor
// visible even when a Mac program requests an invisible cursor.
renderer.draw(s.cells, s.x, s.y, true, invalidate, output);
invalidate = false;
if (returnToTranscript) {
managed = false;
returnToTranscript = false;
}
}
return output;
}
bool applicationCursor() const { return applicationKeys; }
std::string takeReply() { return std::exchange(replies, {}); }
private:
using Bytes = std::vector<std::uint8_t>;
static constexpr int width = 80, height = 24;
struct Screen {
TerminalGrid cells;
int x = 0, y = 0, savedX = 0, savedY = 0, top = 0, bottom = height-1;
bool pendingWrap = false;
Screen() { for (auto& line : cells) line.fill(' '); }
};
Screen normal, alternate;
DriveWireTerminalOutput renderer;
bool inAlternate = false, managed = false, invalidate = false, returnToTranscript = false;
bool origin = false, autoWrap = true, insert = false, applicationKeys = false;
bool g0Graphics = false, g1Graphics = false, shifted = false, selectG1 = false;
std::array<bool, width> tabs = [] {
std::array<bool, width> stops{};
for (int x = 8; x < width; x += 8) stops[x] = true;
return stops;
}();
enum class State { plain, escape, charset, intermediate, csi, string, stringEscape };
State state = State::plain;
std::array<int,16> args{};
std::size_t argument = 0;
bool privateMode = false, ignoredSequence = false;
int utfRemaining = 0;
std::string replies;
Screen& screen() { return inAlternate ? alternate : normal; }
int param(std::size_t i, int fallback = 1) const {
return i <= argument && args[i] != 0 ? args[i] : fallback;
}
void reply(const std::string& value) {
if (replies.size() + value.size() <= 128) replies += value;
}
void beginScreen() {
if (!managed) invalidate = true;
managed = true;
returnToTranscript = false;
}
void direct(Bytes& out, std::uint8_t ch, int repeat = 1) const {
if (!managed) out.insert(out.end(), repeat, ch);
}
void scroll(int top, int bottom, int number, bool down) {
auto& lines = screen().cells;
const int n = std::min(number, bottom-top+1);
if (n <= 0) return;
if (down) {
std::move_backward(lines.begin()+top, lines.begin()+bottom+1-n, lines.begin()+bottom+1);
for (int row = top; row < top+n; ++row) lines[row].fill(' ');
} else {
std::move(lines.begin()+top+n, lines.begin()+bottom+1, lines.begin()+top);
for (int row = bottom+1-n; row <= bottom; ++row) lines[row].fill(' ');
}
}
void index(bool reverse) {
auto& s = screen();
s.pendingWrap = false;
if (reverse && s.y == s.top) scroll(s.top, s.bottom, 1, true);
else if (!reverse && s.y == s.bottom) scroll(s.top, s.bottom, 1, false);
else s.y = std::clamp(s.y + (reverse ? -1 : 1), 0, height-1);
}
void move(int x, int y) {
auto& s = screen();
s.x = std::clamp(x, 0, width-1);
s.y = std::clamp(y, origin ? s.top : 0, origin ? s.bottom : height-1);
s.pendingWrap = false;
}
void horizontal(int x, Bytes& out) {
auto& s = screen();
int target = std::clamp(x, 0, width-1);
if (target == 0) direct(out, 13);
else if (target != s.x) direct(out, target < s.x ? 8 : 6, std::abs(target-s.x));
move(target, s.y);
}
void save() { auto& s = screen(); s.savedX = s.x; s.savedY = s.y; }
void restore() { auto& s = screen(); move(s.savedX, s.savedY); }
void alternateMode(bool enable, int mode) {
if (enable == inAlternate) return;
beginScreen();
if (enable && mode == 1049) save();
if (enable && mode != 47) alternate = Screen{};
inAlternate = enable;
if (!enable && mode == 1049) restore();
returnToTranscript = !enable;
}
void put(char ch, Bytes& out) {
auto& s = screen();
if (s.pendingWrap) { index(false); s.x = 0; }
auto& line = s.cells[s.y];
if (insert) std::move_backward(line.begin()+s.x, line.end()-1, line.end());
line[s.x] = ch;
direct(out, ch);
if (s.x < width-1) ++s.x;
else s.pendingWrap = autoWrap;
}
static char graphic(char ch) {
switch (ch) {
case 'q': case 'o': case 'p': case 'r': case 's': return '-';
case 'x': return '|';
case 'j': case 'k': case 'l': case 'm': case 'n':
case 't': case 'u': case 'v': case 'w': return '+';
default: return ch;
}
}
void tab(bool back) {
auto& s = screen();
int x = s.x;
do { x += back ? -1 : 1; } while (x > 0 && x < width-1 && !tabs[x]);
move(x, s.y);
}
void control(std::uint8_t ch, Bytes& out) {
auto& s = screen();
switch (ch) {
case 7: out.push_back(ch); break;
case 8: if (s.x > 0) direct(out, ch); move(s.x-1, s.y); break;
case 9: {
int oldX = s.x;
tab(false);
direct(out, 6, s.x-oldX);
break;
}
case 10: case 11: case 12: index(false); direct(out, 10); break;
case 13: move(0, s.y); direct(out, 13); break;
case 14: shifted = true; break;
case 15: shifted = false; break;
}
}
void eraseLine(int mode, Bytes& out) {
auto& s = screen();
auto& line = s.cells[s.y];
if (mode == 0) {
std::fill(line.begin()+s.x, line.end(), ' ');
direct(out, 4);
} else if (mode == 1) {
beginScreen();
std::fill(line.begin(), line.begin()+s.x+1, ' ');
} else if (mode == 2) {
line.fill(' ');
// Some CoWin erase-line paths also move the cursor.
if (!managed) { direct(out, 13); direct(out, 4); direct(out, 6, s.x); }
}
}
void eraseDisplay(int mode, Bytes& out) {
auto& s = screen();
if (mode == 3) return; // discard saved scrollback only
if (mode == 0) {
eraseLine(0, out);
for (int y = s.y+1; y < height; ++y) s.cells[y].fill(' ');
direct(out, 11);
} else if (mode == 1 || mode == 2) {
beginScreen();
for (int y = 0; y < (mode == 2 ? height : s.y); ++y) s.cells[y].fill(' ');
if (mode == 1) eraseLine(1, out);
}
}
void modes(bool on) {
for (std::size_t i = 0; i <= argument; ++i) {
if (!privateMode) {
if (args[i] == 4) { insert = on; if (on) beginScreen(); }
continue;
}
switch (args[i]) {
case 1: applicationKeys = on; break;
case 6: origin = on; beginScreen(); move(0, on ? screen().top : 0); break;
case 7: autoWrap = on; screen().pendingWrap = false; break;
case 47: case 1047: case 1049: alternateMode(on, args[i]); break;
case 1048: if (on) save(); else { beginScreen(); restore(); } break;
}
}
}
void csi(std::uint8_t final, Bytes& out) {
auto& s = screen();
const int n = param(0), mode = args[0];
if (final == 'h' || final == 'l') { modes(final == 'h'); return; }
if (privateMode) return;
switch (final) {
case 'A': case 'B': case 'e': {
const int oldY = s.y;
move(s.x, s.y + (final == 'A' ? -n : n));
direct(out, final == 'A' ? 9 : 10, std::abs(oldY-s.y));
break;
}
case 'C': case 'a': horizontal(s.x+n, out); break;
case 'D': horizontal(s.x-n, out); break;
case 'E': case 'F': beginScreen(); move(0, s.y + (final == 'E' ? n : -n)); break;
case 'G': case '`': horizontal(n-1, out); break;
case 'd': beginScreen(); move(s.x, n-1 + (origin ? s.top : 0)); break;
case 'H': case 'f': beginScreen(); move(param(1)-1, n-1 + (origin ? s.top : 0)); break;
case 'K': eraseLine(mode, out); break;
case 'J': eraseDisplay(mode, out); break;
case 's': save(); break;
case 'u': beginScreen(); restore(); break;
case 'r': {
int top = n-1, bottom = param(1,height)-1;
if (top >= bottom || bottom >= height) break;
beginScreen();
s.top = top; s.bottom = bottom;
move(0, origin ? top : 0);
break;
}
case 'L': case 'M':
if (s.y >= s.top && s.y <= s.bottom) {
beginScreen(); scroll(s.y, s.bottom, n, final == 'L');
}
break;
case 'S': case 'T': beginScreen(); scroll(s.top, s.bottom, n, final == 'T'); break;
case '@': case 'P': case 'X': {
beginScreen();
auto& line = s.cells[s.y];
auto pos = line.begin()+s.x;
const int count = std::min(n,width-s.x);
if (final == '@') std::move_backward(pos, line.end()-count, line.end());
if (final == 'P') {
std::move(pos+count, line.end(), pos);
std::fill(line.end()-count,line.end(),' ');
} else std::fill(pos,pos+count,' ');
break;
}
case 'I': case 'Z': {
int oldX = s.x;
for (int i = 0; i < std::min(n,width); ++i) tab(final == 'Z');
direct(out, final == 'Z' ? 8 : 6, std::abs(s.x-oldX));
break;
}
case 'g': if (mode == 0) tabs[s.x] = false; else if (mode == 3) tabs.fill(false); break;
case 'c': if (mode == 0) reply("\x1b[?1;0c"); break;
case 'n':
if (mode == 5) reply("\x1b[0n");
if (mode == 6) reply("\x1b[" + std::to_string(s.y+1-(origin ? s.top : 0)) +
";" + std::to_string(s.x+1) + "R");
break;
}
}
void startCSI() {
state = State::csi;
args.fill(0);
argument = 0;
ignoredSequence = false;
privateMode = false;
}
void escape(std::uint8_t ch, Bytes& out) {
state = State::plain;
switch (ch) {
case '[': startCSI(); break;
case ']': case 'P': case '^': case '_': case 'X': state = State::string; break;
case '(': case ')': selectG1 = ch == ')'; state = State::charset; break;
case '7': save(); break;
case '8': beginScreen(); restore(); break;
case 'D': index(false); direct(out, 10); break;
case 'E': control(13, out); control(10, out); break;
case 'M': beginScreen(); index(true); break;
case 'H': tabs[screen().x] = true; break;
case 'Z': reply("\x1b[?1;0c"); break;
case 'c':
*this = DriveWireTerminal{};
beginScreen();
break;
default:
if (ch >= 0x20 && ch <= 0x2f) state = State::intermediate;
}
}
static int continuationCount(std::uint8_t ch) {
return ch < 0xc2 || ch > 0xf4 ? 0 : ch < 0xe0 ? 1 : ch < 0xf0 ? 2 : 3;
}
void parse(std::uint8_t ch, Bytes& out) {
if (ch == 0x18 || ch == 0x1a) { state = State::plain; utfRemaining = 0; return; }
if (state == State::string || state == State::stringEscape) {
// A UTF-8 continuation byte in an OSC title can equal C1 ST.
if (utfRemaining && (ch & 0xc0) == 0x80) { --utfRemaining; return; }
utfRemaining = continuationCount(ch);
if (ch == 7 || ch == 0x9c || (state == State::stringEscape && ch == '\\')) state = State::plain;
else state = ch == 27 ? State::stringEscape : State::string;
return;
}
if (ch == 27) { state = State::escape; utfRemaining = 0; return; }
if (ch < 32) { control(ch, out); return; }
if (state == State::escape) { escape(ch, out); return; }
if (state == State::charset) {
if (selectG1) g1Graphics = ch == '0';
else g0Graphics = ch == '0';
state = State::plain;
return;
}
if (state == State::intermediate) { if (ch >= 0x30) state = State::plain; return; }
if (state == State::csi) {
if (ch >= '0' && ch <= '9') args[argument] = std::min(9999, 10*args[argument]+ch-'0');
else if (ch == ';') {
if (argument+1 < args.size()) ++argument;
else ignoredSequence = true;
} else if (ch == '?' && argument == 0 && !args[0]) privateMode = true;
else if (ch >= 0x40 && ch <= 0x7e) {
if (!ignoredSequence) csi(ch, out);
state = State::plain;
} else ignoredSequence = true;
return;
}
if (utfRemaining && (ch & 0xc0) == 0x80) { --utfRemaining; return; }
utfRemaining = 0;
if (ch == 0x9b) { startCSI(); return; }
if (ch == 0x90 || ch == 0x98 || ch == 0x9d || ch == 0x9e || ch == 0x9f) { state = State::string; return; }
if (ch >= 0xc0) {
utfRemaining = continuationCount(ch);
put('?', out);
} else if (ch >= 32 && ch < 127) put((shifted ? g1Graphics : g0Graphics) ? graphic(ch) : ch, out);
}
};
}
+21
View File
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "../../../src/core/AudioBuffer.h"
#include <memory>
namespace VCC::Mac {
// All methods except the internal render callback belong to the machine queue.
class MacAudioOutput {
public:
MacAudioOutput();
~MacAudioOutput();
void start(); // throws a user-visible error; never opens an input device
void stop(); // stops callback before clearing queued samples
bool running() const;
std::uint64_t starts() const;
bool needsRestart() const;
AudioBuffer& buffer();
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
}
+50
View File
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#import <AVFoundation/AVFoundation.h>
#include "MacAudioOutput.h"
#include <stdexcept>
#include <string>
namespace VCC::Mac {
struct MacAudioOutput::Impl {
std::shared_ptr<AudioBuffer> ring = std::make_shared<AudioBuffer>();
std::shared_ptr<std::atomic<bool>> changed = std::make_shared<std::atomic<bool>>(false);
AVAudioEngine *engine = nil;
id observer = nil;
std::uint64_t starts = 0;
~Impl() { stop(); }
void stop() {
if(observer) { [[NSNotificationCenter defaultCenter] removeObserver:observer]; observer=nil; }
[engine stop]; engine=nil; ring->clear(); changed->store(false);
}
};
MacAudioOutput::MacAudioOutput() : impl(std::make_unique<Impl>()) {}
MacAudioOutput::~MacAudioOutput() = default;
AudioBuffer& MacAudioOutput::buffer() { return *impl->ring; }
std::uint64_t MacAudioOutput::starts() const { return impl->starts; }
bool MacAudioOutput::running() const { return impl->engine.isRunning; }
bool MacAudioOutput::needsRestart() const { return impl->changed->load() || (impl->engine && !impl->engine.isRunning); }
void MacAudioOutput::stop() { impl->stop(); }
void MacAudioOutput::start() {
if(running()) return;
// A new graph follows the current default output device and its sample rate.
impl->engine = [AVAudioEngine new];
AVAudioFormat *format = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2];
auto ring=impl->ring;
AVAudioSourceNode *source = [[AVAudioSourceNode alloc] initWithFormat:format renderBlock:
^OSStatus(BOOL *silence, const AudioTimeStamp *, AVAudioFrameCount frames, AudioBufferList *list) {
if(list->mNumberBuffers != 2) return kAudio_ParamError;
ring->read(static_cast<float*>(list->mBuffers[0].mData),static_cast<float*>(list->mBuffers[1].mData),frames);
*silence=NO; return noErr;
}];
[impl->engine attachNode:source];
[impl->engine connect:source to:impl->engine.mainMixerNode format:format];
auto changed=impl->changed;
impl->observer=[[NSNotificationCenter defaultCenter] addObserverForName:AVAudioEngineConfigurationChangeNotification
object:impl->engine queue:nil usingBlock:^(NSNotification*) { changed->store(true); }];
NSError *error=nil;
if(![impl->engine startAndReturnError:&error]) {
const std::string message=error.localizedDescription.UTF8String ?: "Unable to start Mac audio output";
impl->stop(); throw std::runtime_error(message);
}
++impl->starts;
}
}
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
FOUNDATION_EXPORT NSErrorDomain const VCCLibraryArchiveErrorDomain;
typedef NS_ERROR_ENUM(VCCLibraryArchiveErrorDomain, VCCLibraryArchiveError) {
VCCLibraryArchiveErrorInvalid = 1,
VCCLibraryArchiveErrorUnsupported,
VCCLibraryArchiveErrorUnsafePath,
VCCLibraryArchiveErrorCollision,
VCCLibraryArchiveErrorLimit,
VCCLibraryArchiveErrorCancelled,
VCCLibraryArchiveErrorIO
};
@interface VCCLibraryArchive : NSObject
// Synchronous worker API: call off the main thread. The destination must not
// exist; on failure only the new directory created by this call is removed.
// Returns regular-file relative paths. No links, executable permissions, or
// archive ownership/timestamps are restored. ZIP64/multi-volume ZIPs are rejected.
+ (nullable NSArray<NSString *> *)extractZIPAtURL:(NSURL *)archiveURL
toNewDirectory:(NSURL *)destinationURL
maximumExpandedBytes:(uint64_t)maximumExpandedBytes
maximumEntries:(NSUInteger)maximumEntries
shouldCancel:(BOOL (^ _Nullable)(void))shouldCancel
error:(NSError **)error
NS_SWIFT_NAME(extractZIP(at:toNewDirectory:maximumExpandedBytes:maximumEntries:shouldCancel:));
@end
NS_ASSUME_NONNULL_END
+266
View File
@@ -0,0 +1,266 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#import "VCCLibraryArchive.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <map>
#include <set>
// A narrow adapter for the stable system libarchive ABI. Apple's SDK exports
// these functions in libarchive.tbd but does not supply libarchive headers.
// No external program, Homebrew installation, or bundled library is required.
extern "C" {
struct archive;
struct archive_entry;
struct archive *archive_read_new(void);
int archive_read_support_format_zip_seekable(struct archive *);
int archive_read_open_fd(struct archive *, int, size_t);
int archive_read_next_header(struct archive *, struct archive_entry **);
ssize_t archive_read_data(struct archive *, void *, size_t);
int archive_read_close(struct archive *);
int archive_read_free(struct archive *);
const char *archive_error_string(struct archive *);
const char *archive_entry_pathname_utf8(struct archive_entry *);
const char *archive_entry_pathname(struct archive_entry *);
const char *archive_entry_symlink(struct archive_entry *);
const char *archive_entry_hardlink(struct archive_entry *);
mode_t archive_entry_filetype(struct archive_entry *);
int64_t archive_entry_size(struct archive_entry *);
int archive_entry_size_is_set(struct archive_entry *);
int archive_entry_is_encrypted(struct archive_entry *);
}
NSErrorDomain const VCCLibraryArchiveErrorDomain = @"com.brianholman.vccplus.library.archive";
namespace {
constexpr int archiveOK = 0, archiveEOF = 1;
struct Descriptor {
int fd = -1;
explicit Descriptor(int value = -1): fd(value) {}
~Descriptor() { if (fd >= 0) close(fd); }
Descriptor(const Descriptor &) = delete;
Descriptor &operator=(const Descriptor &) = delete;
void reset(int value) { if (fd >= 0) close(fd); fd = value; }
};
struct Reader {
struct archive *value = archive_read_new();
~Reader() { if (value) archive_read_free(value); }
};
bool fail(NSError **error, VCCLibraryArchiveError code, NSString *message) {
if (error) *error = [NSError errorWithDomain:VCCLibraryArchiveErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey:message}];
return false;
}
bool cancelled(BOOL (^check)(void), NSError **error) {
return check && check() ? !fail(error, VCCLibraryArchiveErrorCancelled, @"Installation was cancelled.") : false;
}
NSString *archiveMessage(struct archive *value, NSString *fallback) {
const char *text = archive_error_string(value);
return text ? [NSString stringWithFormat:@"%@: %s", fallback, text] : fallback;
}
uint16_t u16(const uint8_t *p) { return uint16_t(p[0]) | uint16_t(p[1]) << 8; }
uint32_t u32(const uint8_t *p) { return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; }
bool readAt(int fd, uint64_t offset, void *buffer, size_t count) {
size_t done = 0;
while (done < count) {
ssize_t n = pread(fd, (uint8_t *)buffer + done, count - done, (off_t)(offset + done));
if (n < 0 && errno == EINTR) continue;
if (n <= 0) return false;
done += (size_t)n;
}
return true;
}
// Require the complete central directory. A streaming unzip reader can otherwise
// accept a truncated ZIP with intact local headers. Inspect raw names too: C APIs
// cannot expose embedded NULs, and ZIP readers may normalize Windows separators.
bool checkContainer(int fd, uint64_t fileSize, NSUInteger maxEntries, BOOL (^check)(void), uint64_t &entryCount, NSError **error) {
if (fileSize < 22) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP file is truncated or invalid.");
size_t tailSize = (size_t)MIN(fileSize, uint64_t(65557));
std::vector<uint8_t> tail(tailSize);
if (!readAt(fd, fileSize - tailSize, tail.data(), tailSize)) return fail(error, VCCLibraryArchiveErrorIO, @"The ZIP file could not be read.");
int64_t end = -1;
for (int64_t i = (int64_t)tailSize - 22; i >= 0; --i) {
if (u32(tail.data() + i) == 0x06054b50 && (uint64_t)i + 22 + u16(tail.data() + i + 20) == tailSize) { end = i; break; }
}
if (end < 0) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP file has no complete end-of-directory record.");
const uint8_t *e = tail.data() + end;
uint64_t count = u16(e + 10), centralSize = u32(e + 12), centralOffset = u32(e + 16);
if (u16(e + 4) || u16(e + 6) || u16(e + 8) != count || count == 65535 || centralSize == UINT32_MAX || centralOffset == UINT32_MAX)
return fail(error, VCCLibraryArchiveErrorUnsupported, @"Multi-volume and ZIP64 packages are not supported by this installer.");
if (count > maxEntries) return fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP file contains too many entries.");
const uint64_t endOffset = fileSize - tailSize + (uint64_t)end;
if (centralOffset > endOffset || centralSize != endOffset - centralOffset) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP central directory is incomplete or inconsistent.");
uint64_t offset = centralOffset;
for (uint64_t index = 0; index < count; ++index) {
if (cancelled(check, error)) return false;
uint8_t header[46];
if (offset > endOffset || endOffset - offset < sizeof(header) || !readAt(fd, offset, header, sizeof(header)) || u32(header) != 0x02014b50)
return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP central directory contains a damaged entry.");
const uint64_t nameLength = u16(header + 28), extraLength = u16(header + 30), commentLength = u16(header + 32);
uint64_t length = sizeof(header) + nameLength + extraLength + commentLength;
if (length > endOffset - offset || nameLength == 0 || nameLength > 4096)
return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP file contains an invalid filename.");
if ((u16(header + 8) & 1) || (u16(header + 8) & 0x40)) return fail(error, VCCLibraryArchiveErrorUnsupported, @"Encrypted ZIP packages are not supported.");
// Some readers normalize unsupported Unix entry kinds into regular
// files. Reject those kinds from the original central attributes too.
const mode_t storedType = (mode_t)((u32(header + 38) >> 16) & S_IFMT);
if (storedType && storedType != S_IFREG && storedType != S_IFDIR)
return fail(error, VCCLibraryArchiveErrorUnsupported, @"ZIP packages containing links or special files cannot be installed.");
if (u16(header + 34) || u32(header + 20) == UINT32_MAX || u32(header + 24) == UINT32_MAX || u32(header + 42) == UINT32_MAX)
return fail(error, VCCLibraryArchiveErrorUnsupported, @"Multi-volume and ZIP64 packages are not supported by this installer.");
std::vector<uint8_t> name((size_t)nameLength);
if (!readAt(fd, offset + sizeof(header), name.data(), name.size())) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP filename is truncated.");
for (auto byte : name) if (byte == 0 || byte == '\\' || byte == ':')
return fail(error, VCCLibraryArchiveErrorUnsafePath, @"The ZIP file contains an unsafe filename.");
// Ensure local and central names agree, before the reader chooses one.
uint8_t local[30]; const uint64_t localOffset = u32(header + 42);
if (localOffset > centralOffset || centralOffset - localOffset < sizeof(local) || !readAt(fd, localOffset, local, sizeof(local)) || u32(local) != 0x04034b50 || u16(local + 26) != nameLength)
return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP local header does not match its directory entry.");
const uint64_t dataStart = localOffset + sizeof(local) + nameLength + u16(local + 28);
if (dataStart > centralOffset || u32(header + 20) > centralOffset - dataStart || u16(local + 6) != u16(header + 8) || u16(local + 8) != u16(header + 10))
return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP entry extends beyond its stored data.");
std::vector<uint8_t> localName((size_t)nameLength);
if (!readAt(fd, localOffset + sizeof(local), localName.data(), localName.size()) || localName != name)
return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP filename differs between its headers.");
offset += length;
}
if (offset != endOffset) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP directory length does not match its entries.");
entryCount = count;
return true;
}
NSArray<NSString *> *pathComponents(NSString *path, bool directory, NSError **error) {
if (directory && [path hasSuffix:@"/"]) path = [path substringToIndex:path.length - 1];
if (!path.length || [path hasPrefix:@"/"] || [path rangeOfString:@"\\"].location != NSNotFound || [path rangeOfString:@":"].location != NSNotFound || [path rangeOfCharacterFromSet:NSCharacterSet.controlCharacterSet].location != NSNotFound) {
fail(error, VCCLibraryArchiveErrorUnsafePath, @"The ZIP file contains an unsafe path."); return nil;
}
NSArray<NSString *> *parts = [path componentsSeparatedByString:@"/"];
if (parts.count > 64) { fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP directory nesting is too deep."); return nil; }
for (NSString *part in parts) {
if (!part.length || [part isEqualToString:@"."] || [part isEqualToString:@".."] || [part lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 255) {
fail(error, VCCLibraryArchiveErrorUnsafePath, @"The ZIP file contains an unsafe or unsupported path component."); return nil;
}
}
return parts;
}
NSString *collisionKey(NSString *path) {
return [[path precomposedStringWithCanonicalMapping] stringByFoldingWithOptions:NSCaseInsensitiveSearch locale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
}
bool writeAll(int fd, const void *bytes, size_t size) {
size_t done = 0;
while (done < size) {
ssize_t n = write(fd, (const uint8_t *)bytes + done, size - done);
if (n < 0 && errno == EINTR) continue;
if (n <= 0) return false;
done += (size_t)n;
}
return true;
}
}
@implementation VCCLibraryArchive
+ (NSArray<NSString *> *)extractZIPAtURL:(NSURL *)archiveURL toNewDirectory:(NSURL *)destinationURL maximumExpandedBytes:(uint64_t)maximumExpandedBytes maximumEntries:(NSUInteger)maximumEntries shouldCancel:(BOOL (^)(void))shouldCancel error:(NSError **)error {
if (error) *error = nil;
if (!archiveURL.isFileURL || !destinationURL.isFileURL || !maximumEntries || !maximumExpandedBytes) {
fail(error, VCCLibraryArchiveErrorInvalid, @"A local ZIP file, new local destination, and positive extraction limits are required."); return nil;
}
if (cancelled(shouldCancel, error)) return nil;
Descriptor source(open(archiveURL.fileSystemRepresentation, O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
struct stat sourceInfo;
if (source.fd < 0 || fstat(source.fd, &sourceInfo) != 0 || !S_ISREG(sourceInfo.st_mode) || sourceInfo.st_size < 0) {
fail(error, VCCLibraryArchiveErrorIO, @"The downloaded ZIP is not a readable regular file."); return nil;
}
uint64_t expectedEntries = 0;
if (!checkContainer(source.fd, (uint64_t)sourceInfo.st_size, maximumEntries, shouldCancel, expectedEntries, error)) return nil;
if (mkdir(destinationURL.fileSystemRepresentation, 0700) != 0) {
fail(error, VCCLibraryArchiveErrorIO, @"The extraction destination already exists or could not be created."); return nil;
}
bool success = false;
@try {
Descriptor root(open(destinationURL.fileSystemRepresentation, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
Reader reader;
if (root.fd < 0 || !reader.value || archive_read_support_format_zip_seekable(reader.value) != archiveOK || archive_read_open_fd(reader.value, source.fd, 65536) != archiveOK) {
fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP package could not be opened."); return nil;
}
std::map<std::string, std::string> paths;
std::set<std::string> explicitEntries;
NSMutableArray<NSString *> *files = [NSMutableArray array];
uint64_t total = 0, count = 0;
struct archive_entry *entry = nullptr;
int status;
while ((status = archive_read_next_header(reader.value, &entry)) == archiveOK) {
if (cancelled(shouldCancel, error)) return nil;
if (++count > maximumEntries) { fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP file contains too many entries."); return nil; }
mode_t type = archive_entry_filetype(entry);
bool directory = type == S_IFDIR;
if ((type != S_IFREG && !directory) || archive_entry_symlink(entry) || archive_entry_hardlink(entry)) {
fail(error, VCCLibraryArchiveErrorUnsupported, @"ZIP packages containing links or special files cannot be installed."); return nil;
}
if (archive_entry_is_encrypted(entry)) { fail(error, VCCLibraryArchiveErrorUnsupported, @"Encrypted ZIP packages are not supported."); return nil; }
const char *utf8 = archive_entry_pathname_utf8(entry);
if (!utf8) utf8 = archive_entry_pathname(entry);
NSString *path = utf8 ? [[NSString alloc] initWithUTF8String:utf8] : nil;
if (!path) { fail(error, VCCLibraryArchiveErrorUnsupported, @"A ZIP filename cannot be represented safely on this Mac."); return nil; }
NSArray<NSString *> *parts = pathComponents(path, directory, error);
if (!parts) return nil;
NSString *relative = [parts componentsJoinedByString:@"/"];
std::string fullKey(collisionKey(relative).UTF8String);
if (!explicitEntries.insert(fullKey).second) { fail(error, VCCLibraryArchiveErrorCollision, @"The ZIP file contains duplicate or conflicting filenames."); return nil; }
NSString *prefix = @"";
for (NSString *part in parts) {
prefix = prefix.length ? [prefix stringByAppendingFormat:@"/%@", part] : part;
std::string key(collisionKey(prefix).UTF8String), original(prefix.UTF8String);
auto prior = paths.find(key);
if (prior != paths.end() && prior->second != original) { fail(error, VCCLibraryArchiveErrorCollision, @"ZIP paths differ only by letter case or Unicode spelling and would collide on a Mac."); return nil; }
paths[key] = original;
}
int64_t declared = archive_entry_size(entry);
if (!archive_entry_size_is_set(entry) || declared < 0 || (uint64_t)declared > maximumExpandedBytes - total || (directory && declared != 0)) {
fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP package exceeds the expanded-size limit or has an invalid entry size."); return nil;
}
Descriptor parent(dup(root.fd));
if (parent.fd < 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extraction directory could not be opened."); return nil; }
NSUInteger directories = directory ? parts.count : parts.count - 1;
for (NSUInteger i = 0; i < directories; ++i) {
const char *name = parts[i].fileSystemRepresentation;
if (mkdirat(parent.fd, name, 0755) != 0 && errno != EEXIST) { fail(error, VCCLibraryArchiveErrorIO, @"A ZIP directory could not be created."); return nil; }
int child = openat(parent.fd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (child < 0) { fail(error, VCCLibraryArchiveErrorCollision, @"A ZIP path conflicts with an existing file or link."); return nil; }
parent.reset(child);
if (fchmod(parent.fd, 0755) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extracted directory permissions could not be set."); return nil; }
}
Descriptor output;
if (!directory) {
output.reset(openat(parent.fd, parts.lastObject.fileSystemRepresentation, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600));
if (output.fd < 0) { fail(error, VCCLibraryArchiveErrorCollision, @"A ZIP output path already exists or could not be created."); return nil; }
}
uint8_t buffer[65536]; uint64_t written = 0;
while (true) {
if (cancelled(shouldCancel, error)) return nil;
ssize_t bytes = archive_read_data(reader.value, buffer, sizeof(buffer));
if (bytes < 0) { fail(error, VCCLibraryArchiveErrorInvalid, archiveMessage(reader.value, @"A ZIP entry is damaged or uses unsupported compression")); return nil; }
if (!bytes) break;
if (directory || (uint64_t)bytes > maximumExpandedBytes - total || (uint64_t)bytes > (uint64_t)declared - written) {
fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP expanded data exceeds its declared size or the installation limit."); return nil;
}
if (!writeAll(output.fd, buffer, (size_t)bytes)) { fail(error, VCCLibraryArchiveErrorIO, @"The ZIP data could not be saved. Check available disk space."); return nil; }
written += (uint64_t)bytes; total += (uint64_t)bytes;
}
if (written != (uint64_t)declared) { fail(error, VCCLibraryArchiveErrorInvalid, @"A ZIP entry is truncated."); return nil; }
if (!directory) {
if (fchmod(output.fd, 0644) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extracted file permissions could not be set."); return nil; }
[files addObject:relative];
}
}
if (status != archiveEOF || count != expectedEntries || archive_read_close(reader.value) != archiveOK) {
fail(error, VCCLibraryArchiveErrorInvalid, archiveMessage(reader.value, @"The ZIP package is incomplete or damaged")); return nil;
}
if (cancelled(shouldCancel, error)) return nil;
if (fchmod(root.fd, 0755) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extraction directory permissions could not be set."); return nil; }
success = true;
return files;
} @finally {
if (!success) [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:nil];
}
}
@end
@@ -0,0 +1,4 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#import "VCCMachineController.h"
#import "VCCLibraryArchive.h"
#import "DiskImageEditorBackend.h"
@@ -0,0 +1,369 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, VCCMachineState) {
VCCMachineStateEmpty, VCCMachineStatePaused, VCCMachineStateRunning, VCCMachineStateClosed
};
typedef NS_ENUM(NSInteger, VCCFloppyFormat) {
VCCFloppyFormatStandard, VCCFloppyFormatTrackDMK, VCCFloppyFormatSectorVDK
};
typedef NS_ENUM(NSInteger, VCCDiskInsertionReset) {
VCCDiskInsertionResetNone, VCCDiskInsertionResetSoftReset, VCCDiskInsertionResetColdRestart
};
// Immutable copies only; no borrowed RAM or rendering pointers cross the queue.
@interface VCCDiskSnapshot : NSObject
@property(nonatomic, readonly) BOOL mounted, dirty, writeProtected, sourceReadOnly;
@property(nonatomic, readonly) NSString *name;
@property(nonatomic, readonly, nullable) NSString *floppyExtension;
@property(nonatomic, readonly) BOOL formatWriteProtected;
@property(nonatomic, readonly) NSUInteger tracks, sides, byteCount;
@property(nonatomic, readonly) uint64_t readEvents, writeEvents;
@end
// Immutable mounted-image snapshot held by one controller-owned edit lease.
@interface VCCDiskEditCapture : NSObject
@property(nonatomic, readonly) NSData *data;
@property(nonatomic, readonly) NSString *name;
@property(nonatomic, readonly) uint64_t token;
@property(nonatomic, readonly) NSInteger drive;
@property(nonatomic, readonly) BOOL canApply;
@end
@interface VCCHardDiskSave : NSObject
@property(nonatomic, readonly) NSData *data; // full export, or packed [LSN little-endian UInt32, 256 bytes] records
@property(nonatomic, readonly) uint64_t token;
@property(nonatomic, readonly) NSUInteger byteCount;
@end
// Raw, immutable printer bytes captured at one emulation-queue boundary.
@interface VCCPrinterOutput : NSObject
@property(nonatomic, readonly) NSData *bytes;
@property(nonatomic, readonly) uint64_t revision, droppedBytes;
@property(nonatomic, readonly) NSUInteger capacity;
@property(nonatomic, readonly) BOOL enabled;
@end
// A native grant can invalidate its owner while an emulator operation is queued.
@interface VCCCompiledRunLease : NSObject
@property(nonatomic, readonly, getter=isValid) BOOL valid;
- (void)invalidate;
@end
// Immutable input values copied from the same core snapshot as state/frame identity.
// Ports are ordered right (0), left (1); no hardware identities or typed keys.
@interface VCCJoystickInputSnapshot : NSObject
@property(nonatomic, readonly) NSUInteger x, y, buttons, mode;
@end
@interface VCCMachineSnapshot : NSObject
@property(nonatomic, readonly) VCCMachineState state;
@property(nonatomic, readonly) uint64_t generation;
@property(nonatomic, readonly) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, assistantMediaRevision;
@property(nonatomic, readonly) BOOL debuggerDevelopmentAttached, debuggerAssemblyAttached, debuggerSourceStepping;
@property(nonatomic, readonly) BOOL debuggerBankedDevelopment;
@property(nonatomic, readonly) BOOL basicDebugAttached, assistantCompiledReturned;
@property(nonatomic, readonly) NSArray<NSString *> *assistantDeviceBlockers;
@property(nonatomic, readonly, nullable) NSNumber *assistantDirectPrompt, *assistantEmptyBASIC; // On-demand readiness observation.
@property(nonatomic, readonly, nullable) NSString *assistantLoadedSource; // Only the guarded transfer completion.
@property(nonatomic, readonly) NSInteger basicStoppedLine; // -1 unless stopped before a BASIC statement
@property(nonatomic, readonly) NSInteger basicSourceOffset;
@property(nonatomic, readonly) NSUInteger basicSourceLength;
@property(nonatomic, readonly) BOOL basicStepping, basicCanStepOut;
@property(nonatomic, readonly) NSInteger basicErrorLine;
@property(nonatomic, readonly) NSString *basicErrorCode;
@property(nonatomic, readonly) NSString *basicDebugStatus;
@property(nonatomic, readonly) uint64_t frames;
@property(nonatomic, readonly, copy) NSArray<VCCJoystickInputSnapshot *> *joystickInputs;
@property(nonatomic, readonly) BOOL keyboardInputHeld;
@property(nonatomic, readonly) NSUInteger pasteRemaining;
@property(nonatomic, readonly) BOOL printerEnabled;
@property(nonatomic, readonly) uint64_t printerRevision, printerDroppedBytes;
@property(nonatomic, readonly) NSUInteger printerByteCount;
@property(nonatomic, readonly) uint64_t cycles;
@property(nonatomic, readonly) uint16_t programCounter;
@property(nonatomic, readonly) CGRect activeVideoRect; // Bounds belonging to pixels, not the latest register state.
@property(nonatomic, readonly, nullable) NSData *pixels; // 640x480, little-endian 0x00RRGGBB
@property(nonatomic, readonly, nullable) NSString *errorMessage;
@property(nonatomic, readonly) BOOL use6309, fastForward;
@property(nonatomic, readonly) NSUInteger ramConfiguration, cpuOverclock, frameInterval;
@property(nonatomic, readonly) uint64_t presentedFrame; // Completed guest rasters at publication.
@property(nonatomic, readonly) uint64_t pixelRevision; // Includes redraws between rasters at a BASIC stop.
@property(nonatomic, readonly) NSInteger videoOutput; // 0 RGB, 1 composite, 2 alternate composite phase
@property(nonatomic, readonly) BOOL audioEnabled;
@property(nonatomic, readonly) BOOL driveWireEnabled;
@property(nonatomic, readonly, copy) NSString *macShellStatus;
@property(nonatomic, readonly) uint64_t macShellRequestID;
@property(nonatomic, readonly) uint64_t audioUnderruns, audioOverruns, audioConsumed;
// Lifetime totals except current occupancy (audioBuffered) and maximum fields.
// Nonzero signal is counted before gain; reset/pause do not clear diagnostics.
@property(nonatomic, readonly) uint64_t audioSubmitted, audioSignalSamples, audioBuffered, audioStarts;
@property(nonatomic, readonly) uint64_t audioMaximumRequest, audioMaximumRefillGapNanoseconds;
@property(nonatomic, readonly) BOOL tapeMounted, tapeMotor, tapeDirty, tapeFast, tapeWAV;
@property(nonatomic, readonly) NSInteger tapeMode;
@property(nonatomic, readonly) uint64_t tapePosition, tapeLength;
@property(nonatomic, readonly) uint64_t tapeReadEvents, tapeWriteEvents;
@property(nonatomic, readonly) BOOL diskEnabled, diskBusy, diskMotor, diskConnected, diskEditorLocked;
@property(nonatomic, readonly) BOOL hardDiskConnected, hardClockEnabled, hardClockReadOnly;
@property(nonatomic, readonly) NSUInteger hardSelectedDrive, hardSector, hardStatus;
@property(nonatomic, readonly) uint64_t hardFlushRequests;
@property(nonatomic, readonly) NSArray<VCCDiskSnapshot *> *hardDisks; // two drives
@property(nonatomic, readonly) BOOL sdcReadOnly;
@property(nonatomic, readonly) NSArray<NSString *> *sdcDriveNames;
@property(nonatomic, readonly) NSString *sdcDirectory;
@property(nonatomic, readonly, nullable) NSString *sdcError;
@property(nonatomic, readonly) uint64_t sdcReadCount, sdcWriteCount;
@property(nonatomic, readonly) BOOL multiPakEnabled;
@property(nonatomic, readonly) NSUInteger physicalSlot, romSlot, ioSlot;
@property(nonatomic, readonly) NSArray<NSNumber *> *cartridgeKinds;
@property(nonatomic, readonly) NSArray<NSString *> *cartridgeNames; // single then slots 1...4
@property(nonatomic, readonly) NSString *diskROMName;
@property(nonatomic, readonly) NSInteger diskSelectedDrive;
@property(nonatomic, readonly) NSUInteger diskTrack, diskSector, diskSide;
@property(nonatomic, readonly) NSArray<VCCDiskSnapshot *> *disks; // always four drives
@end
// Owned, validated payload for a complete profile switch. Image indices 0...3
// are floppies and 4...5 are hard disks; empty image data denotes no medium.
@interface VCCMachineProfile : NSObject <NSCopying>
@property(nonatomic) BOOL use6309, fastForward, sound, multiPak, clockEnabled, clockReadOnly, cassetteWAV, fastCassette;
@property(nonatomic) NSInteger ram, overclock, frameInterval, videoOutput, physicalSlot;
@property(nonatomic) float volume;
@property(nonatomic, copy, nullable) NSData *systemROM, *diskROM, *cassette;
@property(nonatomic, copy) NSString *diskROMName;
@property(nonatomic, copy) NSArray<NSNumber*> *kinds, *readOnly, *protectedImages;
@property(nonatomic, copy) NSArray<NSData*> *cartridgeROMs, *images;
@property(nonatomic, copy) NSArray<NSString*> *cartridgeNames, *imageNames;
@property(nonatomic, copy) NSArray<NSString*> *sdcFolders;
@property(nonatomic, copy) NSArray<NSNumber*> *sdcReadOnly;
@end
typedef void (^VCCMachineCompletion)(VCCMachineSnapshot *snapshot);
// Debugger data is captured on the same queue and at the same boundary as
// machine state. Unavailable I/O bytes are marked separately, never read.
@interface VCCDebugInstruction : NSObject
@property(nonatomic, readonly) uint16_t address;
@property(nonatomic, readonly) NSData *bytes;
@property(nonatomic, readonly) NSString *mnemonic, *operand;
@property(nonatomic, readonly) BOOL valid;
@end
@interface VCCDebugMemoryCapture : NSObject
@property(nonatomic, readonly) VCCMachineSnapshot *machine;
@property(nonatomic, readonly) uint32_t address, capacity;
@property(nonatomic, readonly) NSData *bytes, *available;
@property(nonatomic, readonly) NSArray<VCCDebugInstruction *> *instructions;
// Parallel offsets distinguish physical locations from assumed logical PCs.
@property(nonatomic, readonly) NSArray<NSNumber *> *instructionOffsets;
@end
// Pixel coordinates use the captured source resolution, before display zoom.
// Addresses are in the same space as the enclosing capture.
@interface VCCDebugGraphicsPixel : NSObject
@property(nonatomic, readonly) uint32_t address;
@property(nonatomic, readonly) uint8_t value, mask;
@property(nonatomic, readonly, nullable) NSNumber *attributeAddress, *attributeValue; // attributed text cells
@property(nonatomic, readonly) BOOL available;
@end
@interface VCCDebugGraphicsCapture : NSObject
@property(nonatomic, readonly) VCCMachineSnapshot *machine;
@property(nonatomic, readonly, nullable) NSString *errorMessage;
@property(nonatomic, readonly) NSString *modeName;
@property(nonatomic, readonly) NSInteger width, height;
@property(nonatomic, readonly) uint32_t address;
@property(nonatomic, readonly) BOOL physical;
@property(nonatomic, readonly) NSData *rgba; // R, G, B, A; four bytes per pixel, rows top-down.
- (nullable VCCDebugGraphicsPixel *)pixelAtX:(NSInteger)x y:(NSInteger)y NS_SWIFT_NAME(pixel(x:y:));
- (BOOL)hasSameLayoutAs:(VCCDebugGraphicsCapture *)other NS_SWIFT_NAME(hasSameLayout(as:));
@end
@interface VCCMemoryMapping : NSObject
@property(nonatomic, readonly) uint16_t page;
@property(nonatomic, readonly) uint32_t ramAddress, sourceAddress;
@property(nonatomic, readonly) NSInteger source; // 0 RAM, 1 internal ROM, 2 cartridge ROM
@end
@interface VCCMMUSnapshot : NSObject
@property(nonatomic, readonly) BOOL enabled, ramVectors, allRAM;
@property(nonatomic, readonly) NSUInteger activeTask, romMap, prefix;
@property(nonatomic, readonly) uint32_t ramByteCount, vectorRAMAddress;
@property(nonatomic, readonly) NSArray<NSNumber *> *task0, *task1;
// Eight logical 8 KiB banks, before FE00/vector and FF00/I/O overrides.
@property(nonatomic, readonly) NSArray<VCCMemoryMapping *> *effective;
@end
@interface VCCDebuggerSnapshot : NSObject
@property(nonatomic, readonly) VCCMachineSnapshot *machine;
@property(nonatomic, readonly) NSDictionary<NSString *, NSNumber *> *registers;
@property(nonatomic, readonly) NSArray<VCCDebugInstruction *> *instructions;
@property(nonatomic, readonly) NSArray<NSNumber *> *breakpoints, *disabledBreakpoints;
@property(nonatomic, readonly) uint16_t memoryAddress;
@property(nonatomic, readonly) NSData *memory, *memoryAvailable;
// Full logical memory and availability captured atomically with registers.
@property(nonatomic, readonly) NSData *logicalMemory, *logicalMemoryAvailable;
@property(nonatomic, readonly) NSString *stopReason;
@property(nonatomic, readonly) VCCMMUSnapshot *mmu;
@property(nonatomic, readonly) uint32_t physicalAddress;
@property(nonatomic, readonly) NSData *physicalMemory; // Raw RAM, never overlaid ROM/I/O; read-only.
@end
// Commands are asynchronous and ordered on a private serial queue. Completions
// are delivered on the main queue. One process-wide machine may be loaded.
// Shutdown is terminal; deallocation also drains work and releases the core.
@interface VCCTraceRecord : NSObject
@property(nonatomic, readonly) NSUInteger index;
@property(nonatomic, readonly) uint64_t clock, frame;
@property(nonatomic, readonly) NSInteger cycles;
@property(nonatomic, readonly) uint16_t address;
@property(nonatomic, readonly) NSString *kind, *instruction, *detail, *before, *after;
@end
@interface VCCTraceSnapshot : NSObject
@property(nonatomic, readonly) BOOL armed, capturing;
@property(nonatomic, readonly) uint64_t identifier;
@property(nonatomic, readonly) NSUInteger total, limit, offset;
@property(nonatomic, readonly) NSString *status;
@property(nonatomic, readonly) NSArray<VCCTraceRecord *> *records;
@end
@interface VCCMachineController : NSObject
// Capture starts disabled. Toggling or clearing never pauses/resets the machine.
// Closing a UI window has no effect; reset/profile replacement retain output.
- (void)setPrinterEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion;
- (void)clearPrinterOutputWithCompletion:(VCCMachineCompletion)completion;
- (void)printerOutputWithCompletion:(void (^)(VCCPrinterOutput *, VCCMachineSnapshot *))completion;
- (void)debuggerSnapshotAtAddress:(uint16_t)address followPC:(BOOL)followPC memoryAddress:(uint16_t)memoryAddress completion:(void (^)(VCCDebuggerSnapshot *))completion NS_SWIFT_NAME(debuggerSnapshot(address:followPC:memoryAddress:completion:));
- (void)debuggerSnapshotAtAddress:(uint16_t)address followPC:(BOOL)followPC memoryAddress:(uint16_t)memoryAddress physicalAddress:(uint32_t)physicalAddress physicalMemory:(BOOL)physicalMemory completion:(void (^)(VCCDebuggerSnapshot *))completion NS_SWIFT_NAME(debuggerSnapshot(address:followPC:memoryAddress:physicalAddress:physicalMemory:completion:));
// Mode for an address preview: SG4, PMODE 0–4, then HSCREEN 1–4 (0–9).
// Current page derives the interpretation, palette and physical address from the machine.
- (void)debuggerGraphicsCurrentPage:(BOOL)currentPage address:(uint32_t)address physical:(BOOL)physical mode:(NSInteger)mode alternatePalette:(BOOL)alternatePalette completion:(void (^)(VCCDebugGraphicsCapture *))completion NS_SWIFT_NAME(debuggerGraphics(currentPage:address:physical:mode:alternatePalette:completion:));
- (void)debuggerStepWithCompletion:(VCCMachineCompletion)completion;
// mode: 0 into, 1 over, 2 out. Completion acknowledges start; poll machine state
// for the eventual pause. pauseWithCompletion cancels a pending source step.
- (void)debuggerStepSource:(NSInteger)mode addresses:(NSArray<NSNumber *> *)addresses locations:(NSArray<NSNumber *> *)locations bytes:(NSArray<NSData *> *)bytes generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepSource(mode:addresses:locations:bytes:generation:programRevision:mappingFingerprint:programCounter:completion:));
- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray<NSNumber *> *)addresses locations:(NSArray<NSNumber *> *)locations bytes:(NSArray<NSData *> *)bytes moduleIdentifiers:(NSArray<NSString *> *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepBankedSource(mode:addresses:locations:bytes:moduleIdentifiers:generation:programRevision:mappingFingerprint:programCounter:completion:));
- (void)debuggerMemoryAtAddress:(uint32_t)address count:(uint32_t)count physical:(BOOL)physical logicalAddress:(uint16_t)logicalAddress os9:(BOOL)os9 decode:(BOOL)decode completion:(void (^)(VCCDebugMemoryCapture *))completion NS_SWIFT_NAME(debuggerMemory(address:count:physical:logicalAddress:os9:decode:completion:));
- (void)debuggerSetPC:(uint16_t)address completion:(VCCMachineCompletion)completion;
- (void)debuggerSetBreakpoints:(NSArray<NSNumber *> *)addresses completion:(VCCMachineCompletion)completion;
- (void)debuggerConfigureBreakpoints:(NSArray<NSNumber *> *)enabled disabled:(NSArray<NSNumber *> *)disabled completion:(VCCMachineCompletion)completion;
- (void)debuggerStartTrace:(NSUInteger)maximum starts:(NSArray<NSNumber *> *)starts stops:(NSArray<NSNumber *> *)stops screen:(BOOL)screen scheduler:(BOOL)scheduler completion:(VCCMachineCompletion)completion;
- (void)debuggerStopTraceWithCompletion:(VCCMachineCompletion)completion;
- (void)debuggerClearTraceWithCompletion:(VCCMachineCompletion)completion;
- (void)debuggerTraceAtOffset:(NSUInteger)offset completion:(void (^)(VCCTraceSnapshot *, VCCMachineSnapshot *))completion NS_SWIFT_NAME(debuggerTrace(offset:completion:));
- (void)debuggerExportTraceFrom:(NSUInteger)first count:(NSUInteger)count completion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(debuggerExportTrace(first:count:completion:));
// Direct BASIC transfers are serialized with emulation; no synthetic key events.
// Scoped BASIC operations validate machine identity, mounted devices and guest program on its owner queue.
- (void)assistantReadinessWithCompletion:(VCCMachineCompletion)completion NS_SWIFT_NAME(assistantReadiness(completion:));
- (void)assistantLoadSource:(NSString *)source breakpoints:(NSArray<NSNumber *> *)lines expected:(VCCMachineSnapshot *)expected existing:(NSString *)existing completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(assistantLoad(source:breakpoints:expected:existing:completion:));
- (void)assistantPaste:(NSArray<NSNumber *> *)chords runID:(NSString *)runID direct:(BOOL)direct expected:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(assistantPaste(chords:runID:direct:expected:source:completion:));
- (void)cancelAssistantPaste:(NSString *)runID;
- (void)compiledGuest:(VCCCompiledRunLease *)lease runID:(NSString *)runID expected:(VCCMachineSnapshot *)expected assembly:(BOOL)assembly key:(nullable NSNumber *)key readScreen:(BOOL)readScreen finalScreen:(BOOL)finalScreen completion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(compiledGuest(lease:runID:expected:assembly:key:readScreen:finalScreen:completion:));
- (void)checkReviewedBASIC:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(VCCMachineCompletion)completion;
- (void)assistantScreen:(VCCMachineSnapshot *)expected source:(NSString *)source completion:(void (^)(NSDictionary<NSString *,id> * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(assistantScreen(expected:source:completion:));
- (void)basicLoadSource:(NSString *)source run:(BOOL)run completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicLoadSource(_:run:completion:));
- (void)basicLoadSource:(NSString *)source run:(BOOL)run breakpoints:(NSArray<NSNumber *> *)lines completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicLoadSource(_:run:breakpoints:completion:));
- (void)basicSetBreakpoints:(NSArray<NSNumber *> *)lines source:(NSString *)source completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicSetBreakpoints(_:source:completion:));
- (void)basicContinueSource:(NSString *)source completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicContinue(source:completion:));
- (void)basicStepSource:(NSString *)source over:(BOOL)over completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicStep(source:over:completion:));
- (void)basicStepOutSource:(NSString *)source completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(basicStepOut(source:completion:));
- (void)basicClearDebugWithCompletion:(VCCMachineCompletion)completion;
- (void)basicExportSource:(NSString *)source name:(NSString *)name cassette:(BOOL)cassette completion:(void (^)(NSData * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(basicExportSource(_:name:cassette:completion:));
- (void)basicInspectSource:(NSString *)source completion:(void (^)(NSArray<NSDictionary<NSString *, id> *> * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(basicInspect(source:completion:));
- (void)basicReadSourceWithCompletion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(basicReadSource(completion:));
- (void)debuggerWriteMemoryAtAddress:(uint16_t)address data:(NSData *)data completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerWriteMemory(address:data:completion:));
// Stages/validates all devices first, rejects dirty media, then cold-loads paused.
// applied distinguishes a committed setup from a preflight rejection, including
// the unlikely case of a core allocation failure after media installation.
- (void)applyProfile:(VCCMachineProfile*)profile completion:(void (^)(BOOL applied, VCCMachineSnapshot *snapshot))completion NS_SWIFT_NAME(applyProfile(_:completion:));
- (void)configureMachineWith6309:(BOOL)use6309 ram:(NSInteger)ram overclock:(NSInteger)overclock frameInterval:(NSInteger)interval fastForward:(BOOL)fastForward completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(configureMachine(use6309:ram:overclock:frameInterval:fastForward:completion:));
- (void)setVideoOutput:(NSInteger)output completion:(VCCMachineCompletion)completion;
- (void)loadDiagnosticWithCompletion:(VCCMachineCompletion)completion;
- (void)loadDiagnosticWith6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(loadDiagnostic(use6309:completion:));
- (void)loadROM:(NSData *)rom use6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion;
// Fire-and-forget input shares the command queue; no frame copy per key event.
- (void)setJoystick:(NSUInteger)port x:(NSUInteger)x y:(NSUInteger)y buttons:(NSUInteger)buttons mode:(NSUInteger)mode;
- (void)pasteChords:(NSArray<NSNumber*> *)chords completion:(VCCMachineCompletion)completion;
- (void)cancelPasteWithCompletion:(VCCMachineCompletion)completion;
- (void)copyScreenTextWithCompletion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion;
// Read-only discovery for loading automation; graphics screens return nil without setting a user-visible error.
- (void)inspectScreenTextWithCompletion:(void (^)(NSString * _Nullable, VCCMachineSnapshot *))completion;
- (void)setKeyboardMask:(uint64_t)keys;
- (void)launchAssembly:(NSData *)binary points:(NSArray<NSNumber *> *)points addresses:(NSArray<NSNumber *> *)addresses bytes:(NSArray<NSData *> *)bytes pauseAtEntry:(BOOL)pauseAtEntry requires6309:(BOOL)requires6309 generation:(uint64_t)generation revision:(uint64_t)revision mapping:(uint64_t)mapping completion:(VCCMachineCompletion)completion;
- (void)launchAssembly:(NSData *)binary points:(NSArray<NSNumber *> *)points addresses:(NSArray<NSNumber *> *)addresses bytes:(NSArray<NSData *> *)bytes pauseAtEntry:(BOOL)pauseAtEntry requires6309:(BOOL)requires6309 generation:(uint64_t)generation revision:(uint64_t)revision mapping:(uint64_t)mapping shared:(BOOL)shared completion:(VCCMachineCompletion)completion;
- (void)pauseAssembly:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion;
- (void)controlAssembly:(BOOL)step expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion;
- (void)updateAssembly:(NSArray<NSNumber *> *)points expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion;
- (void)clearAssembly:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion;
- (void)startReviewedC:(NSData *)binary disk:(nullable NSData *)disk name:(NSString *)name stop:(uint16_t)stop expected:(VCCMachineSnapshot *)expected completion:(VCCMachineCompletion)completion;
- (void)continueReviewedC:(VCCMachineSnapshot *)expected name:(NSString *)name stop:(uint16_t)stop bytes:(NSData *)bytes completion:(VCCMachineCompletion)completion;
- (void)ejectReviewedCDisk:(NSString *)name completion:(VCCMachineCompletion)completion;
- (void)debuggerLoadBinary:(NSData *)binary breakpoint:(uint16_t)breakpoint completion:(VCCMachineCompletion)completion;
- (void)debuggerLoadBinary:(NSData *)binary breakpoints:(NSArray<NSNumber *> *)breakpoints completion:(VCCMachineCompletion)completion;
- (void)debuggerArmDevelopmentBreakpoints:(NSArray<NSNumber *> *)breakpoints guardAddresses:(NSArray<NSNumber *> *)guardAddresses guardBytes:(NSArray<NSData *> *)guardBytes completion:(VCCMachineCompletion)completion;
// Module dictionaries: id:String, pages:[{logicalPage:Number,physicalPage:Number}],
// addresses:[Number], bytes:[Data], optional breakpoints:[Number]. An explicit
// breakpoint array qualifies stops to this module; empty retains only code evidence.
// Pages identify actual installed 8 KiB RAM.
- (void)debuggerArmBankedDevelopmentBreakpoints:(NSArray<NSNumber *> *)breakpoints modules:(NSArray<NSDictionary<NSString *, id> *> *)modules completion:(VCCMachineCompletion)completion;
- (void)debuggerClearDevelopmentBreakpointsWithCompletion:(VCCMachineCompletion)completion;
- (void)quickLoadBinary:(NSData *)binary completion:(VCCMachineCompletion)completion;
- (void)requestNitros9BootWithCompletion:(VCCMachineCompletion)completion;
- (void)resumeWithCompletion:(VCCMachineCompletion)completion;
- (void)pauseWithCompletion:(VCCMachineCompletion)completion;
- (void)softResetWithCompletion:(VCCMachineCompletion)completion;
- (void)resetWithCompletion:(VCCMachineCompletion)completion;
- (void)startMacShellWithCompletion:(VCCMachineCompletion)completion NS_SWIFT_NAME(startMacShell(completion:));
- (void)stopMacShellWithCompletion:(VCCMachineCompletion)completion NS_SWIFT_NAME(stopMacShell(completion:));
- (void)decideMacShellRequest:(uint64_t)requestID allow:(BOOL)allow completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(decideMacShellRequest(_:allow:completion:));
- (void)setDriveWireEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion;
- (void)setAudioEnabled:(BOOL)enabled volume:(float)volume completion:(VCCMachineCompletion)completion;
- (void)mountTape:(NSData *)data wav:(BOOL)wav completion:(VCCMachineCompletion)completion;
// 0 stop, 1 play, 2 rewind, 3 eject, 4 record CAS, 5 record WAV.
- (void)tapeAction:(NSInteger)action completion:(VCCMachineCompletion)completion;
- (void)seekTape:(uint64_t)position completion:(VCCMachineCompletion)completion;
- (void)setTapeFast:(BOOL)enabled completion:(VCCMachineCompletion)completion;
- (void)exportTapeWithCompletion:(void (^)(NSData * _Nullable, VCCMachineSnapshot *))completion;
- (void)discardTapeWithCompletion:(VCCMachineCompletion)completion;
- (void)markTapeSavedWithCompletion:(VCCMachineCompletion)completion;
// Atomic layout change; kinds: 0 empty, 1 raw ROM, 2 FD-502, 3 virtual hard disk, 4 RAM disk, 5 Orchestra-90 (optional 8 KiB ROM), 6 Speech/Sound (PIC + speech payload, or empty), 7 CoCo SDC (8/16 KiB ROM).
// Empty ROM data for kind 1 represents an unavailable remembered file.
// Changes pause and cold reset; disk contents and save acknowledgements survive.
- (void)configureCartridges:(NSArray<NSNumber *> *)kinds roms:(NSArray<NSData *> *)roms names:(NSArray<NSString *> *)names multiPak:(BOOL)enabled physicalSlot:(NSInteger)slot completion:(VCCMachineCompletion)completion;
// SDC folders are explicit host roots, never guest paths. Writes are opt-in.
- (void)configureCartridges:(NSArray<NSNumber *> *)kinds roms:(NSArray<NSData *> *)roms names:(NSArray<NSString *> *)names multiPak:(BOOL)enabled physicalSlot:(NSInteger)slot sdcFolders:(NSArray<NSString *> *)folders sdcReadOnly:(NSArray<NSNumber *> *)readOnly completion:(VCCMachineCompletion)completion;
// Disk changes pause execution and reject in-progress controller commands.
- (void)pauseForDiskChangeWithCompletion:(VCCMachineCompletion)completion;
- (void)loadDiskROM:(NSData *)rom name:(NSString *)name completion:(VCCMachineCompletion)completion;
- (void)disableDisksWithCompletion:(VCCMachineCompletion)completion;
- (void)mountDisk:(NSData *)data drive:(NSInteger)drive name:(NSString *)name readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion;
// Validate the complete replacement and media guards before resetting; reset and
// mount share one serialized transaction. Reset does not execute the new disk.
- (void)mountDisk:(NSData *)data drive:(NSInteger)drive name:(NSString *)name readOnly:(BOOL)readOnly reset:(VCCDiskInsertionReset)reset completion:(VCCMachineCompletion)completion;
- (void)createDiskInDrive:(NSInteger)drive completion:(VCCMachineCompletion)completion;
- (void)createDiskInDrive:(NSInteger)drive format:(VCCFloppyFormat)format completion:(VCCMachineCompletion)completion;
- (void)ejectDiskInDrive:(NSInteger)drive discard:(BOOL)discard completion:(VCCMachineCompletion)completion;
- (void)setDiskWriteProtected:(BOOL)enabled drive:(NSInteger)drive completion:(VCCMachineCompletion)completion;
// Export freezes execution and returns immutable bytes and a one-use token.
// Acknowledge only after a successful host write; stale tokens never clear dirty state.
- (void)exportDiskInDrive:(NSInteger)drive completion:(void (^)(NSData * _Nullable, uint64_t, VCCMachineSnapshot *))completion;
// Copy completed in-memory bytes on the worker queue without pausing execution,
// changing media/dirty state, or consuming an export/save acknowledgement token.
- (void)snapshotDiskCopyInDrive:(NSInteger)drive completion:(void (^)(NSData * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(snapshotDiskCopy(inDrive:completion:));
- (void)markDiskSavedInDrive:(NSInteger)drive token:(uint64_t)token name:(NSString *)name completion:(VCCMachineCompletion)completion;
// Acquiring a lease pauses at an idle disk boundary. All execution/media
// mutations are refused until cancel or a confirmed edited-image commit.
- (void)beginDiskEditorInDrive:(NSInteger)drive completion:(void (^)(VCCDiskEditCapture * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(beginDiskEditor(inDrive:completion:));
- (void)beginHardDiskEditorInDrive:(NSInteger)drive completion:(void (^)(VCCDiskEditCapture * _Nullable, VCCMachineSnapshot *))completion NS_SWIFT_NAME(beginHardDiskEditor(inDrive:completion:));
- (void)prepareDiskEditorToken:(uint64_t)token data:(NSData *)data completion:(void (^)(BOOL, VCCMachineSnapshot *))completion NS_SWIFT_NAME(prepareDiskEditor(token:data:completion:));
- (void)commitDiskEditorToken:(uint64_t)token restartConfirmed:(BOOL)restartConfirmed sourceSaved:(BOOL)sourceSaved completion:(void (^)(BOOL, VCCMachineSnapshot *))completion NS_SWIFT_NAME(commitDiskEditor(token:restartConfirmed:sourceSaved:completion:));
- (void)cancelDiskEditorToken:(uint64_t)token completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(cancelDiskEditor(token:completion:));
- (void)snapshotWithCompletion:(VCCMachineCompletion)completion;
// Background saving neither pauses the CPU nor restarts audio. Nil means no
// eligible completed write. A stale acknowledgement leaves newer writes dirty.
- (void)captureDiskForSavingInDrive:(NSInteger)drive completion:(void (^)(NSData * _Nullable, uint64_t, VCCMachineSnapshot *))completion;
- (void)acknowledgeDiskSaveInDrive:(NSInteger)drive token:(uint64_t)token completion:(VCCMachineCompletion)completion;
- (void)mountHardDisk:(NSData *)data drive:(NSInteger)drive name:(NSString *)name readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion;
- (void)createHardDiskInDrive:(NSInteger)drive size:(NSUInteger)size completion:(VCCMachineCompletion)completion;
// 0 eject, 1 discard/eject, 2 protect, 3 allow writes.
- (void)hardDiskAction:(NSInteger)action drive:(NSInteger)drive completion:(VCCMachineCompletion)completion;
- (void)configureHardClock:(BOOL)enabled readOnly:(BOOL)readOnly completion:(VCCMachineCompletion)completion;
- (void)captureHardDiskInDrive:(NSInteger)drive full:(BOOL)full completion:(void (^)(VCCHardDiskSave * _Nullable, VCCMachineSnapshot *))completion;
- (void)acknowledgeHardDiskInDrive:(NSInteger)drive token:(uint64_t)token name:(NSString * _Nullable)name completion:(VCCMachineCompletion)completion;
- (void)shutdownWithCompletion:(VCCMachineCompletion)completion;
@end
NS_ASSUME_NONNULL_END
File diff suppressed because it is too large. Load diff