// SPDX-License-Identifier: GPL-3.0-or-later // Buffered streams on a Disk BASIC volume. All I/O runs in the foreground. #include #include "disk-internal.h" // Only update streams need to remember the last direction of actual I/O. enum { NOT_UPDATE, UPDATE_READY, UPDATE_READING, UPDATE_READ_EOF, UPDATE_WRITING }; struct VCCFile { byte open, writable, update, append, resumeAppend, drive, text, skipLF, eof, error, dirty; char name[12]; // normalized directory identity byte dirSector, dirOffset, granuleCount; // sector/position locate the cursor even when the buffer is empty. // sectorCount and lastBytes describe the published file (reader snapshot). word sector, sectorCount, lastBytes, position, valid; byte granules[DECB_MAX_NUM_GRANULES]; byte buffer[256]; }; static struct VCCFile files[2]; static byte lastError; // The pinned decbfile exposes a setter but no getter for its active DSKCON // backend. Borrow only these two pointers around synchronous ROM I/O. Calling // decb_init here would discard someone else's drive registry and dirty FAT. extern DskConRoutine decb_dskcon_routine; extern DECBDskConVariables *decb_dskcon_variables; byte vcc_disk_use_rom(struct VccDiskBackend *saved) { if (*(const word *) 0xC000 != 0x444B) // Disk BASIC "DK" signature return DECB_ERR_IO; saved->routine = decb_dskcon_routine; saved->variables = decb_dskcon_variables; return decb_setDskConAddresses(*(DskConRoutine *) 0xC004, *(DECBDskConVariables **) 0xC006); } void vcc_disk_restore(const struct VccDiskBackend *saved) { decb_setDskConAddresses(saved->routine, saved->variables); } static byte validFile(FILE *stream) { return (stream == &files[0] || stream == &files[1]) && stream->open; } byte vcc_disk_parse_path(const char *path, char *name, byte *drive) { byte length = 0, extension = 0; if (path == NULL || *path == 0) return DECB_ERR_INVALID_ARGUMENT; while (*path && *path != ':') { byte c = *path++; if (c == '.') { if (extension || length == 0) return DECB_ERR_INVALID_ARGUMENT; extension = 1; length = 0; } else if (c <= ' ' || c > '~' || c == '/' || c == '\\' || c == '*' || c == '?' || ++length > (extension ? 3 : 8)) return DECB_ERR_INVALID_ARGUMENT; *name++ = c; } if (!length) return DECB_ERR_INVALID_ARGUMENT; *name = 0; *drive = 0; if (*path == ':') { ++path; if (*path < '0' || *path > '3' || path[1] != 0) return DECB_ERR_INVALID_ARGUMENT; *drive = *path - '0'; } return DECB_OK; } // Snapshot only this file's granules. Validate the entire chain before exposing // it to the caller so damaged links cannot index outside the FAT or loop forever. static byte readChain(FILE *stream, byte granule) { if (stream->lastBytes > 256) return DECB_ERR_CORRUPT_DIR; if (!decb_dskcon(DECB_DSKCON_READ, stream->buffer, stream->drive, 17, 2)) return DECB_ERR_IO; for (byte i = 0; i < DECB_MAX_NUM_GRANULES; ++i) { if (granule >= DECB_MAX_NUM_GRANULES) return DECB_ERR_CORRUPT_FAT; stream->granules[i] = granule; byte link = stream->buffer[granule]; if (link >= 0xC0 && link <= 0xC9) { // Disk writers encode empty files as C0/0 or C1/0. if (link == 0xC0 && (i != 0 || stream->lastBytes != 0)) return DECB_ERR_CORRUPT_FAT; stream->granuleCount = i + 1; stream->sectorCount = (word) i * 9 + (link - 0xC0); if (stream->sectorCount && !stream->lastBytes) { --stream->sectorCount; stream->lastBytes = 256; } return DECB_OK; } granule = link; } return DECB_ERR_CORRUPT_FAT; } // The two output work sectors are shared by foreground operations. Read them // fresh for each allocation so two writers can safely grow different files. static byte fat[256], directory[256]; static byte previousFAT[DECB_MAX_NUM_GRANULES]; // The separately linked directory operations borrow these same work areas. const struct VccDiskBuffers vcc_disk_buffers = {fat, directory, previousFAT}; byte vcc_disk_sector(byte drive, byte op, byte sector, byte *buf) { if (!decb_dskcon(op, buf, drive, 17, sector)) return DECB_ERR_IO; return DECB_OK; } static byte payloadIO(FILE *stream, byte op, byte granule, word index, byte *buffer) { byte track = (granule >> 1) + (granule >= 34); // Skip directory track 17. byte sector = (granule & 1 ? 10 : 1) + (byte)(index % 9); if (!decb_dskcon(op, buffer, stream->drive, track, sector)) return DECB_ERR_IO; return DECB_OK; } static byte writableVolume(byte drive) { // Disk BASIC Unravelled, "FAT control bytes": a drive with an active // BASIC file uses the ROM's cached FAT. Once all files close the next // BASIC open reloads it. Never allocate underneath an active DOS file. byte *control = (byte *)0x0800 + (word)drive * 74; DECBDrive *registered = decb_getDrive(drive); if (control[0] || control[1] || (registered && registered->fatNeedsSave)) return DECB_ERR_ALREADY_EXISTS; return DECB_OK; } static byte loadFAT(byte drive) { byte error = vcc_disk_sector(drive, DECB_DSKCON_READ, 2, fat); if (!error) memcpy(previousFAT, fat, sizeof(previousFAT)); return error; } static byte freeGranule(void) { for (byte g = 0; g < DECB_MAX_NUM_GRANULES; ++g) if (fat[g] == 0xff) return g; return 0xff; } // A malicious/accidentally cross-linked directory must not let truncation // or allocation recycle another file's granule. Orphaned (reserved) granules // remain occupied. One bit per granule also bounds cyclic chain traversal. static byte checkOwnership(byte drive) { byte seen[9]; memset(seen, 0, sizeof(seen)); for (byte sector = 3; sector <= DECB_LAST_DIR_SECTOR; ++sector) { byte error = vcc_disk_sector(drive, DECB_DSKCON_READ, sector, directory); if (error) return error; for (word offset = 0; offset < 256; offset += 32) { DECBDirEntry *entry = (DECBDirEntry *)(directory + offset); if ((byte)entry->name[0] == 0xff) return DECB_OK; if (!entry->name[0]) continue; byte g = entry->firstGranule; for (;;) { if (g >= DECB_MAX_NUM_GRANULES) return DECB_ERR_CORRUPT_FAT; byte bit = (byte)(1 << (g & 7)); if (seen[g >> 3] & bit) return DECB_ERR_CORRUPT_FAT; seen[g >> 3] |= bit; g = fat[g]; if (g >= 0xc0 && g <= 0xc9) break; } } } return DECB_OK; } // Validate the shared allocation table before any directory mutation. byte vcc_disk_check_volume(byte drive) { byte error = writableVolume(drive); if (!error) error = loadFAT(drive); if (!error) error = checkOwnership(drive); return error; } byte vcc_disk_path_open(byte drive, const char *name) { for (byte i = 0; i < 2; ++i) if (files[i].open && files[i].drive == drive && !strcmp(files[i].name, name)) return TRUE; return FALSE; } int vcc_disk_result(byte error) { lastError = error; return error ? EOF : 0; } // Publish the FAT before the directory so an entry never names a free // granule. Roll back a changed FAT after a failed directory-sector write // when the drive still responds. DECB has no journal or power-loss recovery. static byte publish(FILE *stream, byte directoryChanged) { byte changed = memcmp(fat, previousFAT, sizeof(previousFAT)) != 0; if (changed) { DECBDrive *registered = decb_getDrive(stream->drive); if (registered) registered->fatLoaded = FALSE; if (vcc_disk_sector(stream->drive, DECB_DSKCON_WRITE, 2, fat)) return DECB_ERR_IO; } if (directoryChanged && vcc_disk_sector(stream->drive, DECB_DSKCON_WRITE, stream->dirSector, directory)) { if (changed) { memcpy(fat, previousFAT, sizeof(previousFAT)); vcc_disk_sector(stream->drive, DECB_DSKCON_WRITE, 2, fat); } return DECB_ERR_IO; } return DECB_OK; } // Create or truncate to a canonical empty BASIC data file (C1, zero bytes). // When truncating on a full disk, keep the existing first granule. static byte makeEmpty(FILE *stream, byte exists) { byte error = loadFAT(stream->drive); if (error) return error; if (exists) { for (byte i = 1; i < stream->granuleCount; ++i) fat[stream->granules[i]] = 0xff; } else { error = decb_findDirEntry(TRUE, stream->drive, stream->name, directory, &stream->dirSector, &stream->dirOffset); if (error == DECB_ERR_NOT_FOUND) return DECB_ERR_OUT_OF_SPACE; if (error) return error; stream->granules[0] = freeGranule(); if (stream->granules[0] == 0xff) return DECB_ERR_OUT_OF_SPACE; } fat[stream->granules[0]] = 0xc1; stream->granuleCount = 1; stream->sectorCount = stream->lastBytes = 0; DECBDirEntry *entry = (DECBDirEntry *)(directory + stream->dirOffset); memset(entry, 0, sizeof(DECBDirEntry)); memcpy(entry->name, stream->name, 11); entry->fileType = DECB_TYPE_BASIC_DATA; entry->fileFormat = stream->text ? DECB_FORMAT_ASCII : DECB_FORMAT_BINARY; entry->firstGranule = stream->granules[0]; return publish(stream, 1); } static byte openFile(FILE *stream, byte mode) { byte error; if (stream->writable) { error = vcc_disk_check_volume(stream->drive); if (error) return error; } error = decb_findDirEntry(FALSE, stream->drive, stream->name, directory, &stream->dirSector, &stream->dirOffset); if (error) { if (error == DECB_ERR_NOT_FOUND && mode != 'r') return makeEmpty(stream, 0); return error; } DECBDirEntry *entry = (DECBDirEntry *)(directory + stream->dirOffset); stream->lastBytes = entry->numBytesUsedInLastSector; error = readChain(stream, entry->firstGranule); if (error) return error; if (mode == 'w') return makeEmpty(stream, 1); // An append-update file opens for reading at byte zero. Its first // write, even before a read or seek, must start at the published end. if (mode == 'a' && stream->update) stream->resumeAppend = TRUE; else if (mode == 'a' && stream->sectorCount) { stream->sector = stream->sectorCount - 1; stream->position = stream->lastBytes; if (stream->position < 256) { stream->valid = stream->lastBytes; return payloadIO(stream, DECB_DSKCON_READ, stream->granules[stream->sector / 9], stream->sector, stream->buffer); } } return DECB_OK; } FILE *fopen(const char *path, const char *mode) { char name[13]; byte drive; if (!mode || (*mode != 'r' && *mode != 'w' && *mode != 'a')) { lastError = DECB_ERR_INVALID_ARGUMENT; return NULL; } const char *suffix = mode + 1; byte update = !strcmp(suffix, "+") || !strcmp(suffix, "+b") || !strcmp(suffix, "b+"); if (!update && *suffix && strcmp(suffix, "b")) { lastError = DECB_ERR_INVALID_ARGUMENT; return NULL; } lastError = vcc_disk_parse_path(path, name, &drive); if (lastError) return NULL; FILE *stream = !files[0].open ? &files[0] : &files[1]; if (stream->open) { lastError = DECB_ERR_OUT_OF_SPACE; return NULL; } decb_normalizeFilename(stream->name, name); if ((update || *mode != 'r') && vcc_disk_path_open(drive, stream->name)) { lastError = DECB_ERR_ALREADY_EXISTS; return NULL; } struct VccDiskBackend saved; lastError = vcc_disk_use_rom(&saved); if (lastError) return NULL; stream->drive = drive; stream->writable = update || *mode != 'r'; stream->update = update ? UPDATE_READY : NOT_UPDATE; stream->append = *mode == 'a'; stream->resumeAppend = FALSE; stream->text = strchr(mode, 'b') == NULL; stream->skipLF = stream->error = stream->eof = stream->dirty = 0; stream->sector = stream->position = stream->valid = 0; lastError = openFile(stream, *mode); vcc_disk_restore(&saved); if (lastError) return NULL; stream->open = 1; return stream; } static word sectorLength(FILE *stream, word sector) { if (sector >= stream->sectorCount) return 0; return sector + 1 == stream->sectorCount ? stream->lastBytes : 256U; } static void advanceSector(FILE *stream) { ++stream->sector; stream->position = stream->valid = 0; } // The extra destination lets a text seek inspect its preceding byte without // disturbing the live buffer or cursor if reading the disk fails. static byte readSector(FILE *stream, word sector, byte *dest) { struct VccDiskBackend saved; byte error = vcc_disk_use_rom(&saved); if (!error) { error = payloadIO(stream, DECB_DSKCON_READ, stream->granules[sector / 9], sector, dest); vcc_disk_restore(&saved); } if (error) lastError = stream->error = error; return error; } static byte refill(FILE *stream) { if (stream->error) return FALSE; if (stream->position == 256) advanceSector(stream); word used = sectorLength(stream, stream->sector); if (stream->eof || stream->position >= used) { // The last read encountered EOF even if clearerr later clears the indicator. if (stream->update) stream->update = UPDATE_READ_EOF; stream->eof = TRUE; return FALSE; } if (readSector(stream, stream->sector, stream->buffer)) return FALSE; stream->valid = used; return TRUE; } static int readChar(FILE *stream) { for (;;) { if (stream->position >= stream->valid && !refill(stream)) return EOF; byte c = stream->buffer[stream->position++]; if (!stream->text) return (int) c; if (stream->skipLF) { stream->skipLF = 0; if (c == 10) continue; } if (c == 13) stream->skipLF = 1; return (c == 13 || c == 10) ? (int) '\n' : (int) c; } } static byte canRead(FILE *stream) { if (!validFile(stream) || (stream->writable && !stream->update) || stream->update == UPDATE_WRITING) { lastError = DECB_ERR_INVALID_ARGUMENT; return FALSE; } return TRUE; } int fgetc(FILE *stream) { if (!canRead(stream)) return EOF; if (stream->update) stream->update = UPDATE_READING; return readChar(stream); } char *fgets(char *dest, int capacity, FILE *stream) { if (!dest || capacity <= 0 || !canRead(stream)) { lastError = DECB_ERR_INVALID_ARGUMENT; return NULL; } if (capacity > 1 && stream->update) stream->update = UPDATE_READING; char *p = dest; while (--capacity > 0) { int c = readChar(stream); if (c == EOF) { if (p == dest || stream->error) return NULL; break; } *p++ = (char) c; if (c == '\n') break; } *p = 0; return dest; } static size_t readBytes(FILE *stream, byte *dest, size_t count) { size_t done = 0; while (done < count) { if (stream->text) { int c = readChar(stream); if (c == EOF) break; dest[done++] = (byte) c; } else { if (stream->position >= stream->valid && !refill(stream)) break; word n = stream->valid - stream->position; if (n > count - done) n = count - done; memcpy(dest + done, stream->buffer + stream->position, n); stream->position += n; done += n; } } return done; } size_t fread(void *dest, size_t size, size_t count, FILE *stream) { if (!size || !count) return 0; if (!dest || !canRead(stream)) { lastError = DECB_ERR_INVALID_ARGUMENT; return 0; } if (stream->update) stream->update = UPDATE_READING; if (size == 1) return readBytes(stream, (byte *) dest, count); byte *p = (byte *) dest; size_t done = 0; while (done < count && readBytes(stream, p, size) == size) { ++done; p += size; } return done; } // Publish the current sector. Overwrites keep the existing length and tail; // growth also publishes the new extent. Retain the buffer for the next write. static byte writeBuffer(FILE *stream) { byte error = writableVolume(stream->drive); if (error) return error; error = vcc_disk_sector(stream->drive, DECB_DSKCON_READ, stream->dirSector, directory); if (error) return error; DECBDirEntry *entry = (DECBDirEntry *)(directory + stream->dirOffset); if (memcmp(entry->name, stream->name, 11) || entry->firstGranule != stream->granules[0]) return DECB_ERR_CORRUPT_DIR; // A pure overwrite must preserve the following bytes, granules, and // directory length; writeBytes loaded the original sector before editing. if (stream->position <= sectorLength(stream, stream->sector)) { error = payloadIO(stream, DECB_DSKCON_WRITE, stream->granules[stream->sector / 9], stream->sector, stream->buffer); if (!error) stream->dirty = FALSE; return error; } error = loadFAT(stream->drive); if (error) return error; byte fileGranule = (byte)(stream->sector / 9); byte granule; if (fileGranule == stream->granuleCount) { if (fileGranule >= DECB_MAX_NUM_GRANULES) return DECB_ERR_OUT_OF_SPACE; granule = freeGranule(); if (granule == 0xff) return DECB_ERR_OUT_OF_SPACE; byte oldTail = stream->granules[fileGranule - 1]; if (fat[oldTail] != 0xc9) return DECB_ERR_CORRUPT_FAT; fat[oldTail] = granule; } else { granule = stream->granules[fileGranule]; if (fat[granule] < 0xc0 || fat[granule] > 0xc9) return DECB_ERR_CORRUPT_FAT; } fat[granule] = (byte)(0xc1 + stream->sector % 9); // A newly reused sector must not expose stale data as final-sector slack. memset(stream->buffer + stream->position, 0, 256 - stream->position); error = payloadIO(stream, DECB_DSKCON_WRITE, granule, stream->sector, stream->buffer); if (error) return error; byte lengthChanged = entry->numBytesUsedInLastSector != stream->position; entry->numBytesUsedInLastSector = stream->position; error = publish(stream, lengthChanged); if (error) return error; if (fileGranule == stream->granuleCount) stream->granules[stream->granuleCount++] = granule; stream->sectorCount = stream->sector + 1; stream->lastBytes = stream->position; stream->dirty = FALSE; return DECB_OK; } static int flushOutput(FILE *stream) { if (stream->error) { lastError = stream->error; return EOF; } if (stream->dirty) { struct VccDiskBackend saved; byte error = vcc_disk_use_rom(&saved); if (!error) { error = writeBuffer(stream); vcc_disk_restore(&saved); } if (error) { lastError = stream->error = error; return EOF; } } return 0; } // Internal sector writes do not end the caller's output phase. static int finishOutput(FILE *stream) { if (flushOutput(stream) == EOF) return EOF; if (stream->update == UPDATE_WRITING) stream->update = UPDATE_READY; return 0; } static byte canFlush(FILE *stream) { return stream->writable && stream->update != UPDATE_READING && stream->update != UPDATE_READ_EOF; } int fflush(FILE *stream) { if (!stream) { int result = 0; for (byte i = 0; i < 2; ++i) if (files[i].open && canFlush(&files[i]) && finishOutput(&files[i]) == EOF) result = EOF; return result; } if (!validFile(stream) || !canFlush(stream)) { lastError = DECB_ERR_INVALID_ARGUMENT; return EOF; } return finishOutput(stream); } static long bytePosition(word sector, word position) { return ((long)sector << 8) + position; } long ftell(FILE *stream) { if (validFile(stream)) return bytePosition(stream->sector, stream->position); lastError = DECB_ERR_INVALID_ARGUMENT; return -1L; } static long publishedLength(FILE *stream) { if (!stream->sectorCount) return 0L; return bytePosition(stream->sectorCount - 1, stream->lastBytes); } static void setPosition(FILE *stream, long target) { stream->sector = (word)((unsigned long)target >> 8); stream->position = (byte)target; stream->valid = 0; } int fseek(FILE *stream, long offset, int origin) { if (!validFile(stream) || (origin != SEEK_SET && origin != SEEK_CUR && origin != SEEK_END) || (stream->text && origin != SEEK_SET && offset != 0L)) { lastError = DECB_ERR_INVALID_ARGUMENT; return EOF; } long cursor = ftell(stream); long length = publishedLength(stream); if (stream->dirty && cursor > length) length = cursor; long base = 0L; if (origin == SEEK_CUR) base = cursor; if (origin == SEEK_END) base = length; // Check bounds before adding; negating the caller's LONG_MIN overflows. if (offset < -base || offset > length - base) { lastError = DECB_ERR_INVALID_ARGUMENT; return EOF; } long target = base + offset; if (stream->writable && flushOutput(stream) == EOF) return EOF; byte skipLF = FALSE; if (stream->text && (!stream->writable || stream->update) && target > 0L) { unsigned long previous = (unsigned long)target - 1UL; word sector = (word)(previous >> 8); byte index = (byte)previous; if (stream->sector == sector && index < stream->valid) skipLF = stream->buffer[index] == 13; else { if (readSector(stream, sector, directory)) return EOF; skipLF = directory[index] == 13; } } if (stream->update) stream->update = UPDATE_READY; setPosition(stream, target); stream->skipLF = skipLF; stream->eof = FALSE; stream->resumeAppend = stream->append && target != length; return 0; } void vcc_rewind(FILE *stream) { if (!validFile(stream)) { lastError = DECB_ERR_INVALID_ARGUMENT; return; } // Clearing a previous output error also allows a pending sector to be // retried when the user has removed write protection from the same disk. stream->error = 0; fseek(stream, 0L, SEEK_SET); } static size_t writeBytes(FILE *stream, const byte *source, size_t count) { size_t done = 0; if (stream->error) { lastError = stream->error; return 0; } if (count && stream->update) { stream->update = UPDATE_WRITING; stream->eof = FALSE; } if (count && stream->resumeAppend) { setPosition(stream, publishedLength(stream)); stream->resumeAppend = FALSE; } while (done < count) { if (stream->position == 256) { if (flushOutput(stream) == EOF) break; advanceSector(stream); } if (!stream->valid) { word used = sectorLength(stream, stream->sector); if (used && readSector(stream, stream->sector, stream->buffer)) break; stream->valid = used; } word n = 256 - stream->position; if (n > count - done) n = count - done; byte *dest = stream->buffer + stream->position; if (stream->text) { for (word i = 0; i < n; ++i) { byte c = source[done + i]; dest[i] = c == '\n' ? (byte)13 : c; } if (stream->update) stream->skipLF = dest[n - 1] == 13; } else memcpy(dest, source + done, n); stream->dirty = TRUE; stream->position += n; if (stream->position > stream->valid) stream->valid = stream->position; done += n; } return done; } static byte canWrite(FILE *stream) { if (validFile(stream) && stream->writable && stream->update != UPDATE_READING) return TRUE; lastError = DECB_ERR_INVALID_ARGUMENT; return FALSE; } size_t fwrite(const void *source, size_t size, size_t count, FILE *stream) { if (!size || !count) return 0; if (!canWrite(stream) || !source) { lastError = DECB_ERR_INVALID_ARGUMENT; return 0; } const byte *p = (const byte *)source; if (size == 1) return writeBytes(stream, p, count); size_t done = 0; while (done < count && writeBytes(stream, p, size) == size) { ++done; p += size; } return done; } int fputc(int c, FILE *stream) { byte b = (byte)c; if (!canWrite(stream) || writeBytes(stream, &b, 1) != 1) return EOF; return (int)b; } int fputs(const char *text, FILE *stream) { if (!canWrite(stream) || !text) { lastError = DECB_ERR_INVALID_ARGUMENT; return EOF; } if (stream->error) { lastError = stream->error; return EOF; } size_t n = strlen(text); if (writeBytes(stream, (const byte *)text, n) != n) return EOF; return 0; } int fclose(FILE *stream) { if (!validFile(stream)) { lastError = DECB_ERR_INVALID_ARGUMENT; return EOF; } int result = stream->writable ? flushOutput(stream) : 0; stream->open = 0; return result; } int feof(FILE *stream) { return validFile(stream) && stream->eof; } int ferror(FILE *stream) { return validFile(stream) ? stream->error : DECB_ERR_INVALID_ARGUMENT; } void clearerr(FILE *stream) { if (!validFile(stream)) { lastError = DECB_ERR_INVALID_ARGUMENT; return; } stream->error = stream->eof = 0; } unsigned char vcc_file_error(void) { return lastError; }