// SPDX-License-Identifier: GPL-3.0-or-later // Protocol derived from VCC's SDC simulator, E. J. Jaquay (2025), and the // CoCo SDC User Guide, Darren Atkinson. Host storage is a native POSIX adapter. #include "SDCDevice.h" #include #include #include #include #include #include #include #include namespace VCC::Devices { namespace { constexpr std::uint8_t busyReady = 3, invalid = 0x84, ioError = 0x88, notFound = 0x90, inUse = 0xa0, protectedError = 0xc0; constexpr std::uint64_t maximumBytes = 512ull * 1024 * 1024; struct Failure : std::runtime_error { std::uint8_t status; Failure(std::uint8_t status, const std::string& what) : runtime_error(what), status(status) {} }; struct FD { int value = -1; FD() = default; explicit FD(int value) : value(value) {} ~FD() { if (value >= 0) close(value); } FD(FD&& other) noexcept : value(std::exchange(other.value, -1)) {} FD& operator=(FD&& other) noexcept { if (value >= 0) close(value); value = std::exchange(other.value, -1); return *this; } FD(const FD&) = delete; explicit operator bool() const { return value >= 0; } }; std::string upper(std::string value) { for (auto& c : value) if (c >= 'a' && c <= 'z') c -= 'a' - 'A'; return value; } bool shortName(const std::string& name) { auto dot = name.find('.'); const auto base = dot == std::string::npos ? name : name.substr(0, dot); const auto ext = dot == std::string::npos ? "" : name.substr(dot + 1); if (base.empty() || base.size() > 8 || ext.size() > 3) return false; for (unsigned char c : base + ext) if (c <= 32 || c >= 127 || std::strchr("\"*+,/:;<=>?[\\]|", c) || c == '.') return false; return true; } std::string fatName(std::string name) { if (name.size() == 11 && name.find('.') == std::string::npos) { auto base = name.substr(0,8), ext = name.substr(8); while (!base.empty() && base.back() == ' ') base.pop_back(); while (!ext.empty() && ext.back() == ' ') ext.pop_back(); return base + (ext.empty() ? "" : "." + ext); } return name; } bool wildcard(const std::string& p, const std::string& n) { if (p == "*.*") return true; std::size_t i = 0, j = 0, star = std::string::npos, back = 0; while (j < n.size()) { if (i < p.size() && (p[i] == '?' || p[i] == n[j])) { ++i; ++j; } else if (i < p.size() && p[i] == '*') { star = i++; back = j; } else if (star != std::string::npos) { i = star + 1; j = ++back; } else return false; } while (i < p.size() && p[i] == '*') ++i; return i == p.size(); } unsigned diskNumber(const std::string& name) { auto dot=name.find('.'); auto base=name.substr(0,dot); return !base.empty() && base.back()>='1' && base.back()<='9' ? base.back()-'0' : 0; } std::vector names(int fd) { // openat(".") obtains an independent directory offset (dup alone does not). int next = openat(fd, ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (next < 0) throw Failure(ioError, "The SD card folder could not be read."); DIR* dir = fdopendir(next); if (!dir) { close(next); throw Failure(ioError, "The SD card folder could not be listed."); } std::vector result; while (auto ent = readdir(dir)) { std::string n = ent->d_name; if (n != "." && n != "..") result.push_back(n); if (result.size() > 65536) { closedir(dir); throw Failure(ioError, "The SD card folder has too many entries."); } } closedir(dir); std::sort(result.begin(), result.end(), [](const auto& a, const auto& b) { return upper(a) < upper(b); }); return result; } std::string actualName(int fd, const std::string& desired, bool mustExist = true) { std::string result; for (const auto& n : names(fd)) if (upper(n) == upper(desired)) { if (!result.empty()) throw Failure(invalid, "Two SD files have the same case-insensitive name."); result = n; } if (!result.empty()) return result; if (mustExist) throw Failure(notFound, "SD file or folder not found: " + desired); return desired; } std::string join(const std::vector& parts) { std::string result; for (const auto& p : parts) { if (!result.empty()) result += '/'; result += p; } return result; } } struct SDCDevice::Impl { struct Entry { std::string name, path; bool directory = false, readOnly = true; std::uint32_t size = 0; std::array record() const { std::array r{}; std::fill_n(r.begin(),11,' '); auto dot = name.find('.'); std::string base = dot == std::string::npos ? name : name.substr(0,dot); std::string ext = dot == std::string::npos ? "" : name.substr(dot+1); if (name == "..") { base = ".."; ext.clear(); } base = upper(base); ext = upper(ext); std::copy_n(base.begin(),std::min(8,base.size()),r.begin()); std::copy_n(ext.begin(),std::min(3,ext.size()),r.begin()+8); r[11] = (directory ? 0x10 : 0) | (readOnly ? 1 : 0); for (unsigned i=0;i<4;++i) r[12+i] = size >> (24-i*8); return r; } }; struct Disk { FD fd; Entry entry; std::size_t header = 0; unsigned sides = 1, sectors = 18; bool raw = false, writable = false, formatReadOnly = false; struct stat expected{}; std::vector set; std::size_t setIndex = 0; std::uint64_t reads = 0, writes = 0; }; std::vector rom; std::string rootFolder, error; FD root; bool protectedCard; std::vector cwd; std::array disks; bool latched = false, receive = false, byteMode = false, streaming = false; std::uint8_t command = 0, status = 0, bankData = 0, bank = 0; std::array params{}, reply{}; std::array buffer{}; unsigned offset = 0, count = 0, half = 0; std::uint32_t streamBlock = 0; std::vector directory; std::size_t cursor = 0; bool directoryInitiated = false; std::uint8_t floppyDrive = 0, track = 0, sector = 1, floppyData = 0, floppyStatus = 0; bool floppyWrite = false; unsigned floppyOffset = 0, floppyCount = 0; std::array floppyBuffer{}; Impl(std::vector bytes, std::string folder, bool protect) : rom(std::move(bytes)), rootFolder(std::move(folder)), protectedCard(protect) { if (!rom.empty() && rom.size() != 8192 && rom.size() != 16384) throw std::invalid_argument("SDC-DOS ROM must contain 8 or 16 KiB."); if (!rootFolder.empty()) { std::error_code ec; auto canonical = std::filesystem::canonical(rootFolder,ec); if (ec) throw std::invalid_argument("The SD card folder is unavailable. Choose it again."); rootFolder = canonical.string(); root = FD(open(rootFolder.c_str(),O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)); if (!root) throw std::invalid_argument("The SD card folder could not be opened."); } } std::vector components(const std::string& input) const { if (!root) throw Failure(notFound,"No SD card folder is selected."); if (input.size() > 255 || input.find('\\') != std::string::npos || input.find(':') != std::string::npos) throw Failure(invalid,"Invalid SD path."); for (unsigned char c : input) if (c < 32 || c >= 127) throw Failure(invalid,"SD paths must use printable ASCII names."); auto out = !input.empty() && input.front() == '/' ? std::vector{} : cwd; std::istringstream stream(input); for (std::string part; std::getline(stream,part,'/');) { part = fatName(part); if (part.empty() || part == ".") continue; if (part == "..") { if (out.empty()) throw Failure(invalid,"SD paths cannot leave the selected folder."); out.pop_back(); } else out.push_back(part); } return out; } FD openDir(const std::vector& parts) const { if (!root) throw Failure(notFound,"No SD card folder is selected."); FD fd(dup(root.value)); for (const auto& p : parts) { const auto n = actualName(fd.value,p); FD next(openat(fd.value,n.c_str(),O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)); if (!next) throw Failure(invalid,"SD paths must use real directories inside the selected folder."); fd = std::move(next); } return fd; } struct Parent { FD fd; std::string name; std::vector parts; }; Parent parent(const std::string& path, bool exists = true) const { auto parts = components(path); if (parts.empty()) throw Failure(invalid,"An SD file name is required."); auto name = parts.back(); parts.pop_back(); auto fd = openDir(parts); name = actualName(fd.value,name,exists); return {std::move(fd),name,parts}; } Entry entry(int fd, const std::string& name, const std::vector& parts) const { struct stat s{}; if (fstatat(fd,name.c_str(),&s,AT_SYMLINK_NOFOLLOW) || (!S_ISREG(s.st_mode) && !S_ISDIR(s.st_mode))) throw Failure(invalid,"SD files cannot be symbolic links or special devices."); if (s.st_size < 0 || std::uint64_t(s.st_size) > maximumBytes) throw Failure(invalid,"SD images are limited to 512 MiB."); auto full = parts; full.push_back(name); return {name,"/"+join(full),S_ISDIR(s.st_mode),(s.st_mode & 0222) == 0, S_ISDIR(s.st_mode) ? 0u : static_cast(s.st_size)}; } std::vector list(const std::string& path, bool includeParent) const { auto parts = components(path.empty() ? "*" : path); std::string pattern = "*"; if (!parts.empty() && !path.empty() && path.back() != '/') { pattern = parts.back(); parts.pop_back(); } auto fd = openDir(parts); std::vector out; if (includeParent && !parts.empty() && (pattern == "*" || pattern == "*.*")) out.push_back({"..","",true,false,0}); for (const auto& name : names(fd.value)) { if (!shortName(name) || !wildcard(upper(pattern),upper(name))) continue; try { out.push_back(entry(fd.value,name,parts)); } catch (const Failure&) { continue; } } return out; } bool mountedPath(const std::string& path) const { for (const auto& d : disks) if (d.fd && upper(d.entry.path) == upper(path)) return true; return false; } Disk openDisk(const Entry& e, bool raw) { auto p = parent(e.path); Disk d; d.entry = entry(p.fd.value,p.name,p.parts); if (d.entry.directory) throw Failure(invalid,"An SD disk image is required."); d.raw = raw; if (!protectedCard && !d.entry.readOnly) { d.fd = FD(openat(p.fd.value,p.name.c_str(),O_RDWR | O_NOFOLLOW | O_CLOEXEC)); d.writable = bool(d.fd); } if (!d.fd) d.fd = FD(openat(p.fd.value,p.name.c_str(),O_RDONLY | O_NOFOLLOW | O_CLOEXEC)); if (!d.fd) throw Failure(ioError,"The SD disk image could not be opened."); struct stat s{}; if (fstat(d.fd.value,&s) || !S_ISREG(s.st_mode) || s.st_size < 0 || std::uint64_t(s.st_size) > maximumBytes) throw Failure(invalid,"Invalid SD disk image."); d.entry.size = static_cast(s.st_size); d.expected = s; if (!raw) { std::array h{}; auto n = pread(d.fd.value,h.data(),h.size(),0); if (n < 12) throw Failure(invalid,"The SD disk image is too short."); if (std::memcmp(h.data(),"SDF1",4) == 0) throw Failure(invalid,"SDF track images are not supported yet. Use a DSK image."); d.header = d.entry.size % 256; if (!d.header) d.sides = (d.entry.size/256 > 720 && d.entry.size/256 <= 2880) ? 2 : 1; else if (d.header <= 4) { d.sectors = h[0]; if (d.header >= 2) d.sides = h[1]; if (!d.sectors || (d.sides != 1 && d.sides != 2) || (d.header >= 3 && h[2] != 1) || (d.header >= 4 && h[3] != 1)) throw Failure(invalid,"This JVC image geometry is unsupported (256-byte sectors are required)."); } else if (d.header == 12 && h[0] == 'd' && h[1] == 'k' && h[2] == 12 && h[3] == 0) { d.sides = h[9]; if (d.sides != 1 && d.sides != 2) throw Failure(invalid,"Invalid VDK side count."); if (h[10] & 1) { d.writable = false; d.formatReadOnly = true; } } else throw Failure(invalid,"Unsupported SD image header. Use a raw, JVC or VDK disk image."); } return d; } static bool sameRevision(const struct stat& a,const struct stat& b) { #ifdef __APPLE__ const auto am=a.st_mtimespec,bm=b.st_mtimespec,ac=a.st_ctimespec,bc=b.st_ctimespec; #else const auto am=a.st_mtim,bm=b.st_mtim,ac=a.st_ctim,bc=b.st_ctim; #endif return a.st_dev==b.st_dev && a.st_ino==b.st_ino && a.st_size==b.st_size && am.tv_sec==bm.tv_sec && am.tv_nsec==bm.tv_nsec && ac.tv_sec==bc.tv_sec && ac.tv_nsec==bc.tv_nsec; } void verifyRevision(const Disk& d) const { // An atomic save by another app replaces the path but leaves this open // descriptor pointing at an unlinked file. Never report those writes as // saved. Also reject in-place size/content revisions observed since our // mount or last write, instead of silently combining two editors' data. struct stat selected{},heldRoot{},held{},atPath{}; if (lstat(rootFolder.c_str(),&selected) || fstat(root.value,&heldRoot) || !S_ISDIR(selected.st_mode) || selected.st_dev!=heldRoot.st_dev || selected.st_ino!=heldRoot.st_ino) throw Failure(ioError,"The SD card folder moved or was replaced. Select the folder again before saving."); auto p=parent(d.entry.path); if (fstat(d.fd.value,&held) || fstatat(p.fd.value,p.name.c_str(),&atPath,AT_SYMLINK_NOFOLLOW) || !S_ISREG(atPath.st_mode) || !sameRevision(held,d.expected) || !sameRevision(atPath,d.expected)) throw Failure(ioError,"The SD image changed outside VCC. Eject and mount it again before saving."); } void protect(bool value) { if (protectedCard==value) return; if (value) { // Locking must always succeed, even after the source has vanished. protectedCard=true; for (auto& d : disks) if (d.fd) { try { verifyRevision(d); auto p=parent(d.entry.path); FD next(openat(p.fd.value,p.name.c_str(),O_RDONLY|O_NOFOLLOW|O_CLOEXEC)); struct stat candidate{}; if (next && !fstat(next.value,&candidate) && sameRevision(candidate,d.expected)) d.fd=std::move(next); } catch (const Failure&) { /* keep readable media; the card lock prevents every write */ } d.writable=false; } return; } std::array next; std::array writable{}; // Prepare both replacement descriptors before changing either drive or // the card lock. Protection uses actual O_RDONLY descriptors as well as // command gating; unlocking never reopens a changed/replaced file. for (unsigned i=0;i<2;++i) { auto& d=disks[i]; if (!d.fd) continue; verifyRevision(d); auto p=parent(d.entry.path); if (!value && !d.formatReadOnly && !d.entry.readOnly) { next[i]=FD(openat(p.fd.value,p.name.c_str(),O_RDWR|O_NOFOLLOW|O_CLOEXEC)); writable[i]=bool(next[i]); } if (!next[i]) next[i]=FD(openat(p.fd.value,p.name.c_str(),O_RDONLY|O_NOFOLLOW|O_CLOEXEC)); struct stat candidate{}; if (!next[i] || fstat(next[i].value,&candidate) || !sameRevision(candidate,d.expected)) throw Failure(ioError,"The SD image could not be reopened safely. Mount it again."); } for (unsigned i=0;i<2;++i) if (next[i]) { disks[i].fd=std::move(next[i]); disks[i].writable=writable[i]; } protectedCard=value; } void checkOtherDrive(unsigned drive,const Disk& candidate) const { const auto& other=disks[1-drive]; if (!other.fd) return; struct stat a{},b{}; if (fstat(candidate.fd.value,&a) || fstat(other.fd.value,&b)) throw Failure(ioError,"The SD image identity could not be checked."); if (a.st_dev==b.st_dev && a.st_ino==b.st_ino) throw Failure(inUse,"This SD image is already mounted in the other drive."); } void mount(unsigned drive, const std::string& path, bool raw = false) { if (drive > 1) throw std::invalid_argument("SDC drive must be 0 or 1."); if (path.empty()) { eject(drive); return; } auto found = list(path,false); if (found.empty() && path.find('.') == std::string::npos) found = list(path+".DSK",false); if (found.empty() && path.find('.') == std::string::npos) found = list(path+"*",false); if (found.size() == 1 && found[0].directory) { found = list(found[0].path+"/*.DSK",false); found.erase(std::remove_if(found.begin(),found.end(),[](const Entry& e){ return !diskNumber(e.name); }),found.end()); std::stable_sort(found.begin(),found.end(),[](const Entry& a,const Entry& b){ return diskNumber(a.name) 1) throw std::invalid_argument("SDC drive must be 0 or 1."); auto reads = disks[drive].reads, writes = disks[drive].writes; disks[drive] = Disk{}; disks[drive].reads = reads; disks[drive].writes = writes; } void nextDisk(unsigned drive, unsigned position = 0) { if (drive > 1) throw std::invalid_argument("SDC drive must be 0 or 1."); auto& d = disks[drive]; if (d.set.empty()) throw Failure(notFound,"There is no mounted disk set."); auto index=d.set.size(); unsigned current=diskNumber(d.entry.name), best=10; for (std::size_t i=0;icurrent && n= d.set.size()) throw Failure(notFound,"Disk number is outside the mounted set (numbered 1 through 9)."); if (disks[1-drive].fd && upper(d.set[index].path) == upper(disks[1-drive].entry.path)) throw Failure(inUse,"This SD image is already mounted in the other drive."); auto next = openDisk(d.set[index],d.raw); checkOtherDrive(drive,next); next.set = d.set; next.setIndex = index; next.reads = d.reads; next.writes = d.writes; d = std::move(next); } std::uint64_t diskOffset(unsigned drive, std::uint32_t lsn, unsigned size, bool singleSide) const { const auto& d = disks[drive]; if (!d.fd) throw Failure(notFound,"No SD image is mounted in drive " + std::to_string(drive) + "."); std::uint64_t adjusted = lsn; if (singleSide && d.sides == 2) adjusted += (lsn/d.sectors)*d.sectors; auto offset = adjusted * size + (size == 512 ? 0 : d.header); if (offset + size > maximumBytes) throw Failure(notFound,"SD sector is outside the supported image range."); return offset; } void readDisk(unsigned drive, std::uint32_t lsn, unsigned size, bool singleSide, std::uint8_t* out) { auto offset = diskOffset(drive,lsn,size,singleSide); auto& d = disks[drive]; if (offset + size > d.entry.size) throw Failure(notFound,"SD sector is past the end of the image."); ssize_t result; do { result = pread(d.fd.value,out,size,static_cast(offset)); } while (result < 0 && errno == EINTR); if (result != size) throw Failure(ioError,"The SD image could not be read completely."); ++d.reads; } void writeDisk(unsigned drive, std::uint32_t lsn, bool singleSide, const std::uint8_t* data) { auto offset = diskOffset(drive,lsn,256,singleSide); auto& d = disks[drive]; if (protectedCard || !d.writable) throw Failure(protectedError,"The SD card or disk image is write protected."); verifyRevision(d); // Disk images can grow (raw files start empty). A bounded single pwrite // acknowledges success only after all bytes are accepted by the host. ssize_t result; do { result = pwrite(d.fd.value,data,256,static_cast(offset)); } while (result < 0 && errno == EINTR); if (result != 256) throw Failure(ioError,"The SD image could not be saved completely."); if (fstat(d.fd.value,&d.expected)) throw Failure(ioError,"The saved SD image could not be verified."); d.entry.size = static_cast(std::max(d.entry.size,offset+256)); ++d.writes; } void loadReply(const std::uint8_t* bytes, unsigned length) { if (length > buffer.size()) throw Failure(invalid,"Invalid SD reply length."); std::copy_n(bytes,length,buffer.begin()); offset = half = 0; count = length; receive = false; reply = {}; status = 0; } void nextStream() { const auto& d = disks[command&1]; if (std::uint64_t(streamBlock)*512 >= d.entry.size) { streaming = false; status = 0; count = 0; return; } // A short final host block is padded, matching SD-card sector granularity. auto offsetInFile = diskOffset(command&1,streamBlock,512,false); auto size = static_cast(std::min(512,d.entry.size-offsetInFile)); buffer.fill(0); ssize_t got; do { got = pread(d.fd.value,buffer.data(),size,static_cast(offsetInFile)); } while (got < 0 && errno == EINTR); if (got != size) throw Failure(ioError,"SD streaming read failed."); ++disks[command&1].reads; offset = half = 0; count = 512; status = 0; ++streamBlock; } void fail(const Failure& f) { status = f.status; error = f.what(); count = offset = half = 0; receive = streaming = false; } void dispatch(std::uint8_t code) { bool wasStreaming = streaming; command = code; status = 0; reply = {}; count = offset = half = 0; error.clear(); receive = streaming = false; byteMode = (code&4) != 0; auto lsn = (std::uint32_t(params[0])<<16) | (params[1]<<8) | params[2]; switch (code&0xf0) { case 0x80: readDisk(code&1,lsn,256,(code&2)!=0,buffer.data()); count = 256; break; case 0x90: if (!disks[code&1].fd) throw Failure(notFound,"No image mounted for SD streaming."); streaming = true; streamBlock = lsn; nextStream(); break; case 0xa0: case 0xe0: receive = true; count = 256; buffer.fill(0); break; case 0xc0: info(); break; case 0xd0: if (!wasStreaming && params[0]=='#') nextDisk(code&1,params[1]); break; default: throw Failure(invalid,"Unsupported SDC command."); } } void info() { auto& d = disks[command&1]; byteMode = false; switch (params[0]) { case 'I': { if (!d.fd) throw Failure(notFound,"No SD image is mounted."); auto e = d.entry; e.readOnly = protectedCard || !d.writable; std::array r{}; auto rec=e.record(); std::copy_n(rec.begin(),12,r.begin()); for (unsigned i=0;i<4;++i) r[28+i]=e.size>>(8*i); loadReply(r.data(),r.size()); break; } case 'C': { std::array r{}; // Root is an immediate failed/not-found response, not a READY // block followed by failure. SDC Explorer uses carry from its // command routine to terminate its parent-directory walk; that // routine consumes READY blocks without rechecking final status. if (cwd.empty()) { status=notFound; break; } Entry e; e.name = cwd.back(); e.directory = true; auto rec = e.record(); std::copy(rec.begin(),rec.end(),r.begin()); loadReply(r.data(),r.size()); break; } case 'Q': { if (!d.fd) throw Failure(notFound,"No SD image is mounted."); auto sectors = (d.entry.size-d.header)/256; reply = {std::uint8_t(sectors>>16),std::uint8_t(sectors>>8),std::uint8_t(sectors)}; status = 0; break; } case '>': { if (!directoryInitiated) throw Failure(notFound,"An SD directory listing has not been initiated."); std::array r{}; for (unsigned i=0;i<16 && cursor(3+path.size())); auto q = parent(target,false); if (!shortName(q.name)) throw Failure(invalid,"SD names must use the 8.3 format."); struct stat exists{}; if (!fstatat(q.fd.value,q.name.c_str(),&exists,AT_SYMLINK_NOFOLLOW)) throw Failure(inUse,"The destination SD item already exists."); #ifdef __APPLE__ if (renameatx_np(p.fd.value,p.name.c_str(),q.fd.value,q.name.c_str(),RENAME_EXCL)) #else if (renameat(p.fd.value,p.name.c_str(),q.fd.value,q.name.c_str())) #endif throw Failure(ioError,"The SD item could not be renamed."); } break; } default: throw Failure(invalid,"Unsupported SDC extended command."); } status = 0; } void receiveByte(std::uint8_t byte) { buffer[offset++] = byte; if (--count) return; receive = false; offset = 0; if ((command&0xf0)==0xa0) { auto lsn = (std::uint32_t(params[0])<<16) | (params[1]<<8) | params[2]; writeDisk(command&1,lsn,(command&2)!=0,buffer.data()); status = 0; } else update(); } std::uint8_t replyByte(std::uint8_t port) { if (receive || !count) return reply[port-0x49]; std::uint8_t value; if (byteMode) { if (port != 0x4b) return reply[1]; value = buffer[offset++]; --count; } else { unsigned bit = port == 0x4a ? 1 : 2; value = buffer[offset+(port==0x4b ? 1 : 0)]; half |= bit; if (half == 3) { half = 0; offset += 2; count -= 2; } } if (!count && streaming) nextStream(); return value; } void reset() { for (unsigned i=0;i<2;++i) eject(i); cwd.clear(); directory.clear(); cursor = 0; directoryInitiated = false; latched = receive = byteMode = streaming = false; command = status = bankData = bank = 0; params = {}; reply = {}; offset = count = half = 0; error.clear(); floppyDrive = track = floppyData = floppyStatus = 0; sector = 1; floppyWrite = false; floppyOffset = floppyCount = 0; if (!root) return; // User-selected startup configuration is capped; it is data, not host commands. try { auto p = parent("/startup.cfg"); FD fd(openat(p.fd.value,p.name.c_str(),O_RDONLY|O_NOFOLLOW|O_CLOEXEC)); struct stat s{}; if (!fd || fstat(fd.value,&s) || !S_ISREG(s.st_mode) || s.st_size > 16384) throw Failure(invalid,"Invalid SDC startup.cfg."); std::string text(static_cast(s.st_size),'\0'); if (pread(fd.value,text.data(),text.size(),0) != static_cast(text.size())) throw Failure(ioError,"SDC startup.cfg could not be read."); std::istringstream lines(text); for (std::string line; std::getline(lines,line);) { if (!line.empty() && line.back()=='\r') line.pop_back(); if (line.size()<3 || line[1]!='=') continue; try { if (line[0]=='0' || line[0]=='1') mount(line[0]-'0',line.substr(2)); else if (line[0]=='D') { auto next = components(line.substr(2)); auto test = openDir(next); cwd = std::move(next); } } catch (const Failure& f) { error = f.what(); } } } catch (const Failure& f) { if (f.status != notFound) error = f.what(); } status = 0; } void floppyCommand(std::uint8_t value, DeviceHost& host) { floppyWrite = false; floppyCount = floppyOffset = 0; floppyStatus = 0; switch(value>>4) { case 0: track=0; host.cartridgeNmi(); break; case 1: track=floppyData; host.cartridgeNmi(); break; case 2: case 3: host.cartridgeNmi(); break; case 4: case 5: if(track<255) ++track; host.cartridgeNmi(); break; case 6: case 7: if(track) --track; host.cartridgeNmi(); break; case 8: case 9: if (disks[floppyDrive].raw) throw Failure(invalid,"Raw SD files do not support floppy commands."); if (!sector || sector>disks[floppyDrive].sectors) throw Failure(notFound,"Invalid floppy sector."); readDisk(floppyDrive,track*disks[floppyDrive].sectors+sector-1,256,true,floppyBuffer.data()); floppyCount=256; floppyStatus=3; break; case 10: case 11: if (disks[floppyDrive].raw) throw Failure(invalid,"Raw SD files do not support floppy commands."); if (protectedCard || !disks[floppyDrive].writable) throw Failure(protectedError,"SD image is write protected."); if (!sector || sector>disks[floppyDrive].sectors) throw Failure(notFound,"Invalid floppy sector."); floppyWrite=true; floppyCount=256; floppyStatus=3; break; case 13: if(value&8) host.cartridgeNmi(); break; default: throw Failure(invalid,"This SDC floppy command is not supported."); } } }; SDCDevice::SDCDevice(std::vector rom, std::string rootFolder, bool protectedCard) : impl(std::make_unique(std::move(rom),std::move(rootFolder),protectedCard)) { impl->reset(); } SDCDevice::~SDCDevice() = default; void SDCDevice::reset() { impl->reset(); } std::uint8_t SDCDevice::readMemory(std::uint16_t address) const { const auto& p=*impl; if (p.rom.empty() || p.bank != 0) return 0xff; auto offset = address & 0x3fff; return p.rom[offset % p.rom.size()]; } std::uint8_t SDCDevice::readPort(std::uint8_t port, DeviceHost& host) { auto& p=*impl; try { if (p.latched) { if(port==0x48) return p.count ? busyReady : p.status; if(port==0x49) return p.reply[0]; if(port==0x4a || port==0x4b) return p.replyByte(port); } else { if(port==0x43) return p.bank | (p.bankData&0xf8); if(port==0x48) return p.floppyStatus; if(port==0x49) return p.track; if(port==0x4a) return p.sector; if(port==0x4b) { if(p.floppyCount && !p.floppyWrite) { auto value=p.floppyBuffer[p.floppyOffset++]; if(!--p.floppyCount) { p.floppyStatus=0; host.cartridgeNmi(); } return value; } return p.floppyData; } } } catch(const Failure& f) { p.fail(f); } return 0; } void SDCDevice::writePort(std::uint8_t port, std::uint8_t value, DeviceHost& host) { auto& p=*impl; try { if(port==0x40) { if(p.latched) { p.latched = p.streaming = p.receive = false; p.count = p.status = 0; // SDC-DOS reads the reply registers while forming its next LSN. // A previous V (version) reply must not offset that sector by one. p.params = {}; p.reply = {}; } else if((value&0x43)==0x43) { p.latched=true; p.status=0; } else if(value&1) p.floppyDrive=0; else if(value&2) p.floppyDrive=1; return; } if(p.latched) { if(port==0x48) p.dispatch(value); else if(port==0x49) p.params[0]=value; else if(port==0x4a || port==0x4b) { if(p.receive && p.count) p.receiveByte(value); else p.params[port-0x49]=value; } } else { if(port==0x42) p.bankData=value; else if(port==0x43) { if(!(value&0x80)) p.bank=value&7; } else if(port==0x48) p.floppyCommand(value,host); else if(port==0x49) p.track=value; else if(port==0x4a) p.sector=value; else if(port==0x4b) { p.floppyData=value; if(p.floppyWrite && p.floppyCount) { p.floppyBuffer[p.floppyOffset++]=value; if(!--p.floppyCount) { p.writeDisk(p.floppyDrive,p.track*p.disks[p.floppyDrive].sectors+p.sector-1,true,p.floppyBuffer.data()); p.floppyStatus=0; p.floppyWrite=false; host.cartridgeNmi(); } } } } } catch(const Failure& f) { p.fail(f); if(!p.latched) { p.floppyStatus = f.status==protectedError ? 0x40 : 0x10; p.floppyCount=0; p.floppyWrite=false; host.cartridgeNmi(); } } } SDCDevice::Snapshot SDCDevice::snapshot() const { Snapshot out; const auto& p=*impl; out.rootFolder=p.rootFolder; out.currentDirectory="/"+join(p.cwd); out.error=p.error; out.writeProtected=p.protectedCard; for(unsigned i=0;i<2;++i) { const auto& d=p.disks[i]; auto& s=out.drives[i]; s.name=d.entry.path; s.mounted=bool(d.fd); s.writeProtected=p.protectedCard||!d.writable; s.reads=d.reads; s.writes=d.writes; } return out; } void SDCDevice::mount(unsigned drive, const std::string& guestPath) { impl->mount(drive,guestPath); } void SDCDevice::eject(unsigned drive) { impl->eject(drive); } void SDCDevice::nextDisk(unsigned drive) { impl->nextDisk(drive); } void SDCDevice::setWriteProtected(bool value) { impl->protect(value); } }