698 lines
54 KiB
Plaintext
698 lines
54 KiB
Plaintext
// 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
|