Publish VCC Plus OSS source distribution for 3.6.2 build 60
This commit is contained in:
commit
c652a5276d
1192 files changed
+272368
No files matched your search
@@ -0,0 +1,219 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/bank.h>
|
||||
|
||||
typedef unsigned char byte;
|
||||
#define WINDOW 0x8000u
|
||||
#define TASK0 ((byte *)0xFFA0)
|
||||
#define CHUNK 32
|
||||
|
||||
static byte active;
|
||||
static byte marker;
|
||||
|
||||
static asm byte lowProgramAndStack(void)
|
||||
{
|
||||
asm {
|
||||
program_end import
|
||||
program_start import
|
||||
s_rodata import
|
||||
l_rodata import
|
||||
s_rwdata import
|
||||
ldx #s_rodata
|
||||
cmpx #program_start
|
||||
blo @no
|
||||
ldx #s_rwdata
|
||||
cmpx #s_rodata+l_rodata
|
||||
blo @no
|
||||
ldx #program_end
|
||||
cmpx #s_rwdata
|
||||
blo @no
|
||||
cmpx #$8000
|
||||
bhi @no
|
||||
cmps #$8000
|
||||
bhi @no
|
||||
ldb #1
|
||||
rts
|
||||
@no clrb
|
||||
}
|
||||
}
|
||||
|
||||
static asm byte irqEnabled(void)
|
||||
{
|
||||
asm {
|
||||
tfr cc,b
|
||||
bitb #$10
|
||||
bne @no
|
||||
ldb #1
|
||||
rts
|
||||
@no clrb
|
||||
}
|
||||
}
|
||||
|
||||
static asm unsigned programStart(void)
|
||||
{
|
||||
asm {
|
||||
program_start import
|
||||
ldd #program_start
|
||||
}
|
||||
}
|
||||
|
||||
static asm unsigned writableStart(void)
|
||||
{
|
||||
asm {
|
||||
s_rwdata import
|
||||
ldd #s_rwdata
|
||||
}
|
||||
}
|
||||
|
||||
// Read back the real MMU register. A NOP ($12) supplies zero high bus bits
|
||||
// on a 128/512 KiB machine, whose register drives only the bottom six bits.
|
||||
static asm byte readPage(const byte *entry)
|
||||
{
|
||||
asm {
|
||||
ldx 2,s
|
||||
ldb ,x
|
||||
nop
|
||||
}
|
||||
}
|
||||
|
||||
// Prove that task 0 bank 4 can actually select the requested banks. First
|
||||
// read our own low-memory marker through a second address, twice. Then map
|
||||
// the candidate bank and check if changing the marker is visible there.
|
||||
// On 128 KiB, $28 aliases $38 (and $29 aliases $39, etc.). All writes in
|
||||
// this probe go to our own byte, never through the borrowed window.
|
||||
static byte independent(byte ordinary, byte candidate, byte *window, byte *local)
|
||||
{
|
||||
byte ok;
|
||||
asm {
|
||||
pshs cc,y
|
||||
orcc #$50
|
||||
lda >$ffa4
|
||||
nop
|
||||
pshs a
|
||||
ldx :local
|
||||
ldy :window
|
||||
lda :ordinary
|
||||
sta >$ffa4
|
||||
lda #$5a
|
||||
sta ,x
|
||||
cmpa ,y
|
||||
bne @reject
|
||||
coma
|
||||
sta ,x
|
||||
cmpa ,y
|
||||
bne @reject
|
||||
lda :candidate
|
||||
sta >$ffa4
|
||||
lda ,y
|
||||
coma
|
||||
sta ,x
|
||||
cmpa ,y
|
||||
beq @reject
|
||||
ldb #1
|
||||
bra @restore
|
||||
@reject clrb
|
||||
@restore
|
||||
clr ,x
|
||||
puls a
|
||||
sta >$ffa4
|
||||
puls cc,y
|
||||
stb :ok
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
static byte usableMap(void)
|
||||
{
|
||||
unsigned address = (unsigned)▮
|
||||
byte slot = (byte)(address >> 13);
|
||||
byte i, page;
|
||||
|
||||
if (!lowProgramAndStack() || slot >= 4 || *(unsigned *)0xfff8 != 0xfef7)
|
||||
return 0;
|
||||
for (i = 0; i < 16; ++i) {
|
||||
page = readPage(TASK0 + i);
|
||||
if (i < 8 && page != 0x38 + i)
|
||||
return 0;
|
||||
if (page >= BANK_FIRST_PAGE && page < BANK_FIRST_PAGE + 4)
|
||||
return 0;
|
||||
}
|
||||
return independent(0x38 + slot, BANK_FIRST_PAGE + slot,
|
||||
(byte *)(WINDOW + (address & (BANK_PAGE_SIZE - 1))), &marker);
|
||||
}
|
||||
|
||||
byte bank_open(void)
|
||||
{
|
||||
if (active || !irqEnabled() || !usableMap())
|
||||
return 0;
|
||||
active = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
void bank_close(void)
|
||||
{
|
||||
active = 0;
|
||||
}
|
||||
|
||||
// All addresses and the byte count are prepared before remapping. Keep a
|
||||
// 32-byte bound on the masked interval so BASIC can service interrupts even
|
||||
// when the caller transfers a full asset in one request.
|
||||
static void copyChunk(byte page, const byte *source, byte *destination, byte count)
|
||||
{
|
||||
asm {
|
||||
pshs cc,y
|
||||
orcc #$50
|
||||
lda >$ffa4
|
||||
nop
|
||||
pshs a
|
||||
ldx :source
|
||||
ldy :destination
|
||||
ldb :count
|
||||
lda :page
|
||||
sta >$ffa4
|
||||
@copy lda ,x+
|
||||
sta ,y+
|
||||
decb
|
||||
bne @copy
|
||||
puls a
|
||||
sta >$ffa4
|
||||
puls cc,y
|
||||
}
|
||||
}
|
||||
|
||||
static byte transfer(unsigned offset, byte *buffer, unsigned length, byte writing)
|
||||
{
|
||||
unsigned address = (unsigned)buffer;
|
||||
if (!active || offset > BANK_CAPACITY || length > BANK_CAPACITY - offset)
|
||||
return 0;
|
||||
if (!length)
|
||||
return 1;
|
||||
if (address < (writing ? programStart() : writableStart()) ||
|
||||
address >= WINDOW || length > WINDOW - address || !usableMap())
|
||||
return 0;
|
||||
|
||||
while (length) {
|
||||
unsigned inPage = offset & (BANK_PAGE_SIZE - 1);
|
||||
unsigned count = BANK_PAGE_SIZE - inPage;
|
||||
byte page = (byte)(BANK_FIRST_PAGE + (offset >> 13));
|
||||
byte *window = (byte *)(WINDOW + inPage);
|
||||
if (count > CHUNK) count = CHUNK;
|
||||
if (count > length) count = length;
|
||||
if (writing)
|
||||
copyChunk(page, buffer, window, (byte) count);
|
||||
else
|
||||
copyChunk(page, window, buffer, (byte) count);
|
||||
buffer += count;
|
||||
offset += count;
|
||||
length -= count;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
byte bank_read(unsigned offset, void *destination, unsigned length)
|
||||
{
|
||||
return transfer(offset, (byte *)destination, length, 0);
|
||||
}
|
||||
|
||||
byte bank_write(unsigned offset, const void *source, unsigned length)
|
||||
{
|
||||
return transfer(offset, (byte *)source, length, 1);
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/cassette.h>
|
||||
#include <cmoc.h>
|
||||
|
||||
typedef unsigned char Byte;
|
||||
typedef struct TapeBlock {
|
||||
Byte type, size, data[255];
|
||||
} TapeBlock;
|
||||
|
||||
static TapeBlock block;
|
||||
static Byte mode, position;
|
||||
static int readStatus;
|
||||
enum { CLOSED, READING, WRITING };
|
||||
|
||||
// The ROM's generic leader and block-write vectors take their parameters in
|
||||
// BASIC's scratch bytes. Save these and the caller's register/mask state.
|
||||
static asm void writeBlock(TapeBlock *p)
|
||||
{
|
||||
asm {
|
||||
ldx 2,s
|
||||
pshs cc,dp,y,u
|
||||
orcc #$50
|
||||
clra
|
||||
tfr a,dp
|
||||
ldd <$7c
|
||||
pshs d
|
||||
ldd <$7e
|
||||
pshs d
|
||||
ldd <$80
|
||||
pshs d
|
||||
lda <$85
|
||||
ldb >$ff20 ; restore DAC and serial outputs after ROM writes
|
||||
pshs d
|
||||
ldd ,x++
|
||||
std <$7c
|
||||
stx <$7e
|
||||
jsr [$a00c] ; gapped tape, leader at every block
|
||||
jsr [$a008] ; ROM generates type, count, data, checksum
|
||||
lda >$ff21
|
||||
anda #$f7
|
||||
sta >$ff21 ; stop motor between blocks
|
||||
puls d
|
||||
stb >$ff20
|
||||
sta <$85
|
||||
puls d
|
||||
std <$80
|
||||
puls d
|
||||
std <$7e
|
||||
puls d
|
||||
std <$7c
|
||||
puls cc,dp,y,u
|
||||
}
|
||||
}
|
||||
|
||||
// ROM BLKIN waits indefinitely for a transition on a damaged tape. Decode a
|
||||
// complete block with bounded edge waits instead. High pulse widths are
|
||||
// calibrated against the alternating leader in each gapped block. The fast
|
||||
// CAS reader supplies pulse widths in BASIC's normal period scratch byte.
|
||||
static asm Byte readBlock(TapeBlock *p, const Byte *wanted)
|
||||
{
|
||||
asm {
|
||||
ldx 2,s
|
||||
pshs cc,dp,y,u
|
||||
orcc #$50
|
||||
clra
|
||||
tfr a,dp
|
||||
tfr x,y
|
||||
leas -12,s
|
||||
tfr s,u
|
||||
; U frame: saved ROM period, threshold, min, max, bit counter,
|
||||
; edge timeout multiplier, sync search budget, block address, wanted name.
|
||||
sty 8,u
|
||||
ldd 22,u ; second argument above 12 locals, 6 saved registers and PC
|
||||
std 10,u
|
||||
lda <$83
|
||||
sta ,u
|
||||
clr <$83
|
||||
lda >$ff21
|
||||
ora #8
|
||||
sta >$ff21
|
||||
lbsr tapeRX_width ; discard the initial partial pulse
|
||||
lda #255
|
||||
sta 2,u
|
||||
clr 3,u
|
||||
ldb #24
|
||||
tapeRX_learn lbsr tapeRX_width
|
||||
cmpa 2,u
|
||||
bhs tapeRX_max
|
||||
sta 2,u
|
||||
tapeRX_max cmpa 3,u
|
||||
bls tapeRX_next
|
||||
sta 3,u
|
||||
tapeRX_next decb
|
||||
bne tapeRX_learn
|
||||
lda 3,u
|
||||
suba 2,u
|
||||
lsra
|
||||
adda 2,u
|
||||
sta 1,u
|
||||
tapeRX_scan ldy 8,u
|
||||
ldd #$ffff
|
||||
std 6,u
|
||||
clrb
|
||||
tapeRX_sync lbsr tapeRX_bit
|
||||
rorb ; bits arrive least significant first
|
||||
cmpb #$3c
|
||||
beq tapeRX_packet
|
||||
ldx 6,u
|
||||
leax -1,x
|
||||
stx 6,u
|
||||
bne tapeRX_sync
|
||||
lbra tapeRX_error
|
||||
tapeRX_packet lbsr tapeRX_byte
|
||||
stb ,y+
|
||||
lbsr tapeRX_byte
|
||||
stb ,y+
|
||||
stb 2,u ; remaining payload bytes
|
||||
addb -2,y
|
||||
stb 3,u ; additive checksum including type and count
|
||||
tst 2,u
|
||||
beq tapeRX_check
|
||||
tapeRX_data lbsr tapeRX_byte
|
||||
stb ,y+
|
||||
addb 3,u
|
||||
stb 3,u
|
||||
dec 2,u
|
||||
bne tapeRX_data
|
||||
tapeRX_check lbsr tapeRX_byte
|
||||
cmpb 3,u
|
||||
bne tapeRX_error
|
||||
; During named lookup keep the motor on through unrelated files.
|
||||
; Nongapped program blocks can have only a single short sync leader.
|
||||
ldx 10,u
|
||||
beq tapeRX_ok
|
||||
ldy 8,u
|
||||
tst ,y+
|
||||
bne tapeRX_scan
|
||||
lda ,y+
|
||||
cmpa #15
|
||||
bne tapeRX_error
|
||||
ldb #8
|
||||
tapeRX_name lda ,y+
|
||||
cmpa ,x+
|
||||
bne tapeRX_scan
|
||||
decb
|
||||
bne tapeRX_name
|
||||
tapeRX_ok clrb
|
||||
bra tapeRX_finish
|
||||
tapeRX_error ldb #1
|
||||
tapeRX_finish tfr u,s ; also unwinds any nested edge/byte calls
|
||||
lda ,u
|
||||
sta <$83
|
||||
lda >$ff21
|
||||
anda #$f7
|
||||
sta >$ff21
|
||||
leas 12,s
|
||||
puls cc,dp,y,u,pc
|
||||
|
||||
tapeRX_byte lda #8
|
||||
sta 4,u
|
||||
tapeRX_bits bsr tapeRX_bit
|
||||
rorb
|
||||
dec 4,u
|
||||
bne tapeRX_bits
|
||||
rts
|
||||
tapeRX_bit bsr tapeRX_width
|
||||
cmpa 1,u ; short high phase represents a one
|
||||
rts
|
||||
|
||||
tapeRX_width lda #3 ; allow the initial motor silence
|
||||
sta 5,u
|
||||
ldx #0
|
||||
tapeRX_rise lda >$ff20
|
||||
lsra
|
||||
bcs tapeRX_high
|
||||
leax -1,x
|
||||
bne tapeRX_rise
|
||||
dec 5,u
|
||||
bne tapeRX_rise
|
||||
lbra tapeRX_error
|
||||
tapeRX_high ldx #0
|
||||
lda #3
|
||||
sta 5,u
|
||||
tapeRX_fall leax 1,x
|
||||
bne tapeRX_sample
|
||||
dec 5,u
|
||||
lbeq tapeRX_error
|
||||
tapeRX_sample lda >$ff20
|
||||
lsra
|
||||
bcs tapeRX_fall
|
||||
lda <$83
|
||||
bne tapeRX_measured ; accelerated reader supplied the period
|
||||
cmpx #255
|
||||
blo tapeRX_short
|
||||
lda #255
|
||||
rts
|
||||
tapeRX_short pshs x
|
||||
lda 1,s
|
||||
leas 2,s
|
||||
tapeRX_measured rts
|
||||
}
|
||||
}
|
||||
|
||||
static int fileName(const char *name, Byte *dest)
|
||||
{
|
||||
// Avoid interfering with a BASIC file or an already active motor.
|
||||
if (mode || *(Byte *)0x78 || (*(Byte *)0xff21 & 8)) return VCC_TAPE_BUSY;
|
||||
if (!name || !*name) return VCC_TAPE_INVALID;
|
||||
memset(dest, ' ', 8);
|
||||
for (Byte i = 0; *name; ++i) {
|
||||
Byte ch = *name++;
|
||||
if (i == 8 || ch < 32 || ch > 126) return VCC_TAPE_INVALID;
|
||||
dest[i] = ch;
|
||||
}
|
||||
return VCC_TAPE_OK;
|
||||
}
|
||||
|
||||
int vcc_tape_open_write(const char *name)
|
||||
{
|
||||
int status = fileName(name, block.data);
|
||||
if (status) return status;
|
||||
block.type = 0;
|
||||
block.size = 15;
|
||||
block.data[8] = 1; // BASIC data file
|
||||
block.data[9] = block.data[10] = 255; // ASCII, gapped
|
||||
memset(block.data + 11, 0, 4);
|
||||
writeBlock(&block);
|
||||
mode = WRITING;
|
||||
block.type = 1;
|
||||
block.size = 0;
|
||||
return VCC_TAPE_OK;
|
||||
}
|
||||
|
||||
static void putByte(Byte ch)
|
||||
{
|
||||
block.data[block.size++] = ch;
|
||||
if (block.size == 255) {
|
||||
writeBlock(&block);
|
||||
block.size = 0;
|
||||
}
|
||||
}
|
||||
|
||||
int vcc_tape_write_line(const char *line)
|
||||
{
|
||||
if (mode != WRITING || !line) return VCC_TAPE_INVALID;
|
||||
for (const char *s = line; *s; ++s)
|
||||
if ((Byte)*s < 32 || (Byte)*s > 126) return VCC_TAPE_INVALID;
|
||||
while (*line) putByte(*line++);
|
||||
putByte(13);
|
||||
return VCC_TAPE_OK;
|
||||
}
|
||||
|
||||
int vcc_tape_open_read(const char *name)
|
||||
{
|
||||
Byte wanted[8];
|
||||
int status = fileName(name, wanted);
|
||||
if (status) return status;
|
||||
if (readBlock(&block, wanted)) return VCC_TAPE_IO;
|
||||
if (block.data[8] != 1 || !block.data[9] || !block.data[10]) return VCC_TAPE_TYPE;
|
||||
mode = READING;
|
||||
block.size = position = 0;
|
||||
readStatus = VCC_TAPE_OK;
|
||||
return VCC_TAPE_OK;
|
||||
}
|
||||
|
||||
int vcc_tape_read_line(char *line, unsigned capacity)
|
||||
{
|
||||
unsigned used = 0;
|
||||
Byte haveText = 0, overflow = 0;
|
||||
if (!line || !capacity) return VCC_TAPE_INVALID;
|
||||
line[0] = 0;
|
||||
if (mode != READING) return VCC_TAPE_INVALID;
|
||||
if (readStatus) return readStatus;
|
||||
for (;;) {
|
||||
while (position == block.size) {
|
||||
if (readBlock(&block, 0)) {
|
||||
readStatus = VCC_TAPE_IO;
|
||||
} else if (block.type == 255 && !block.size) {
|
||||
readStatus = VCC_TAPE_EOF;
|
||||
// BASIC can suppress its last CR with PRINT #-1,"TEXT";.
|
||||
if (haveText) {
|
||||
if (overflow) {
|
||||
line[0] = 0;
|
||||
return VCC_TAPE_LONG;
|
||||
}
|
||||
line[used] = 0;
|
||||
return VCC_TAPE_OK;
|
||||
}
|
||||
} else if (block.type != 1) {
|
||||
readStatus = VCC_TAPE_IO;
|
||||
}
|
||||
if (readStatus) {
|
||||
line[0] = 0;
|
||||
return readStatus;
|
||||
}
|
||||
position = 0;
|
||||
}
|
||||
Byte ch = block.data[position++];
|
||||
if (ch == 13) {
|
||||
if (overflow) {
|
||||
line[0] = 0;
|
||||
return VCC_TAPE_LONG;
|
||||
}
|
||||
line[used] = 0;
|
||||
return VCC_TAPE_OK;
|
||||
}
|
||||
if (ch < 32 || ch > 126) {
|
||||
line[0] = 0;
|
||||
return readStatus = VCC_TAPE_IO;
|
||||
}
|
||||
haveText = 1;
|
||||
if (used < capacity - 1) line[used++] = ch;
|
||||
else overflow = 1;
|
||||
}
|
||||
}
|
||||
|
||||
int vcc_tape_close(void)
|
||||
{
|
||||
if (!mode) return VCC_TAPE_INVALID;
|
||||
if (mode == WRITING) {
|
||||
if (block.size) writeBlock(&block);
|
||||
block.type = 255;
|
||||
block.size = 0;
|
||||
writeBlock(&block);
|
||||
}
|
||||
mode = CLOSED;
|
||||
return VCC_TAPE_OK;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <ctype.h>
|
||||
|
||||
int isblank(int c) { return c == ' ' || c == '\t'; }
|
||||
int iscntrl(int c) { return (c >= 0 && c < ' ') || c == 127; }
|
||||
int isgraph(int c) { return c >= '!' && c <= '~'; }
|
||||
int islower(int c) { return c >= 'a' && c <= 'z'; }
|
||||
int isprint(int c) { return c >= ' ' && c <= '~'; }
|
||||
int ispunct(int c) {
|
||||
return (c >= '!' && c <= '/') || (c >= ':' && c <= '@')
|
||||
|| (c >= '[' && c <= '`') || (c >= '{' && c <= '~');
|
||||
}
|
||||
int isupper(int c) { return c >= 'A' && c <= 'Z'; }
|
||||
int isxdigit(int c) {
|
||||
return isdigit(c) || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <stdio.h>
|
||||
#include "disk-internal.h"
|
||||
|
||||
// Remove the name before freeing its storage. An interrupted reclaim can
|
||||
// leave allocated space behind, but a live file never points into free space.
|
||||
static byte eraseEntry(byte drive, byte sector, byte offset)
|
||||
{
|
||||
DECBDirEntry *entry = (DECBDirEntry *)(vcc_disk_buffers.directory + offset);
|
||||
DECBDirEntry erased;
|
||||
byte first = entry->name[0], g = entry->firstGranule;
|
||||
entry->name[0] = 0;
|
||||
memcpy(&erased, entry, sizeof(erased));
|
||||
byte error = vcc_disk_sector(drive, DECB_DSKCON_WRITE, sector, vcc_disk_buffers.directory);
|
||||
if (error) return error;
|
||||
// checkOwnership has already checked every link for range and sharing.
|
||||
while (g < DECB_MAX_NUM_GRANULES)
|
||||
{
|
||||
byte next = vcc_disk_buffers.fat[g];
|
||||
vcc_disk_buffers.fat[g] = 0xff;
|
||||
g = next;
|
||||
}
|
||||
DECBDrive *registered = decb_getDrive(drive);
|
||||
if (registered) registered->fatLoaded = FALSE;
|
||||
error = vcc_disk_sector(drive, DECB_DSKCON_WRITE, 2, vcc_disk_buffers.fat);
|
||||
// If the reclaim was refused, restore the name only when the old FAT
|
||||
// and deleted entry can both be confirmed on disk. Otherwise leave it
|
||||
// detached: reattaching to an uncertain chain could damage another file.
|
||||
if (error && !vcc_disk_sector(drive, DECB_DSKCON_READ, 2, vcc_disk_buffers.fat)
|
||||
&& !memcmp(vcc_disk_buffers.fat, vcc_disk_buffers.previousFAT, DECB_MAX_NUM_GRANULES)
|
||||
&& !vcc_disk_sector(drive, DECB_DSKCON_READ, sector, vcc_disk_buffers.directory)
|
||||
&& !memcmp(entry, &erased, sizeof(erased)))
|
||||
{
|
||||
entry->name[0] = first;
|
||||
vcc_disk_sector(drive, DECB_DSKCON_WRITE, sector, vcc_disk_buffers.directory);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
static byte closedPath(const char *path, char *name, byte *drive)
|
||||
{
|
||||
char raw[13];
|
||||
byte error = vcc_disk_parse_path(path, raw, drive);
|
||||
if (error) return error;
|
||||
decb_normalizeFilename(name, raw);
|
||||
return vcc_disk_path_open(*drive, name) ? DECB_ERR_ALREADY_EXISTS : DECB_OK;
|
||||
}
|
||||
|
||||
static int changeName(const char *path, const char *destination)
|
||||
{
|
||||
byte drive, newDrive, sector, offset;
|
||||
char name[12], newName[12];
|
||||
byte error = closedPath(path, name, &drive);
|
||||
if (error) return vcc_disk_result(error);
|
||||
if (destination)
|
||||
{
|
||||
error = closedPath(destination, newName, &newDrive);
|
||||
if (error) return vcc_disk_result(error);
|
||||
if (drive != newDrive) return vcc_disk_result(DECB_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
struct VccDiskBackend saved;
|
||||
error = vcc_disk_use_rom(&saved);
|
||||
if (error) return vcc_disk_result(error);
|
||||
error = vcc_disk_check_volume(drive);
|
||||
if (!error && destination)
|
||||
{
|
||||
error = decb_findDirEntry(FALSE, drive, newName, vcc_disk_buffers.directory, §or, &offset);
|
||||
if (error == DECB_OK) error = DECB_ERR_ALREADY_EXISTS;
|
||||
else if (error == DECB_ERR_NOT_FOUND) error = DECB_OK;
|
||||
}
|
||||
if (!error)
|
||||
error = decb_findDirEntry(FALSE, drive, name, vcc_disk_buffers.directory, §or, &offset);
|
||||
if (!error)
|
||||
{
|
||||
if (destination)
|
||||
{
|
||||
memcpy(vcc_disk_buffers.directory + offset, newName, 11);
|
||||
error = vcc_disk_sector(drive, DECB_DSKCON_WRITE, sector, vcc_disk_buffers.directory);
|
||||
}
|
||||
else
|
||||
error = eraseEntry(drive, sector, offset);
|
||||
}
|
||||
vcc_disk_restore(&saved);
|
||||
return vcc_disk_result(error);
|
||||
}
|
||||
|
||||
int rename(const char *oldPath, const char *newPath)
|
||||
{
|
||||
if (!newPath) return vcc_disk_result(DECB_ERR_INVALID_ARGUMENT);
|
||||
return changeName(oldPath, newPath);
|
||||
}
|
||||
|
||||
int remove(const char *path)
|
||||
{
|
||||
return changeName(path, NULL);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_DISK_INTERNAL_H
|
||||
#define VCC_DISK_INTERNAL_H
|
||||
|
||||
#include <decbfile.h>
|
||||
|
||||
typedef void (*DskConRoutine)(void);
|
||||
struct VccDiskBackend
|
||||
{
|
||||
DskConRoutine routine;
|
||||
DECBDskConVariables *variables;
|
||||
};
|
||||
|
||||
struct VccDiskBuffers
|
||||
{
|
||||
byte *fat, *directory;
|
||||
const byte *previousFAT;
|
||||
};
|
||||
|
||||
extern const struct VccDiskBuffers vcc_disk_buffers;
|
||||
byte vcc_disk_parse_path(const char *path, char *raw, byte *drive);
|
||||
byte vcc_disk_path_open(byte drive, const char *normalizedName);
|
||||
byte vcc_disk_use_rom(struct VccDiskBackend *saved);
|
||||
byte vcc_disk_check_volume(byte drive);
|
||||
void vcc_disk_restore(const struct VccDiskBackend *saved);
|
||||
byte vcc_disk_sector(byte drive, byte op, byte sector, byte *buf);
|
||||
int vcc_disk_result(byte error);
|
||||
extern DECBDrive *decb_getDrive(byte driveNo);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,37 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <stdio.h>
|
||||
#include "format-internal.h"
|
||||
|
||||
// Keep the stream dependency in a separate archive member so snprintf-only
|
||||
// programs can link without a Disk BASIC runtime.
|
||||
static int storeFile(void *context, const char *source, char fill, unsigned count)
|
||||
{
|
||||
FILE *stream = (FILE *) context;
|
||||
if (source)
|
||||
return fwrite(source, 1, count, stream) == count ? 0 : -1;
|
||||
char padding[32];
|
||||
unsigned chunk = count < sizeof(padding) ? count : sizeof(padding);
|
||||
memset(padding, fill, chunk);
|
||||
while (count) {
|
||||
if (chunk > count) chunk = count;
|
||||
if (fwrite(padding, 1, chunk, stream) != chunk) return -1;
|
||||
count -= chunk;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int vfprintf(FILE *stream, const char *format, va_list args)
|
||||
{
|
||||
// Check stream direction and pending errors even for an empty format.
|
||||
if (fputs("", stream) == EOF) return -1;
|
||||
return vcc_format_to(storeFile, stream, format, args);
|
||||
}
|
||||
|
||||
int fprintf(FILE *stream, const char *format, ...)
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
int result = vfprintf(stream, format, args);
|
||||
va_end(args);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <cmoc.h>
|
||||
#include <vcc/decimal.h>
|
||||
|
||||
// A nonzero BASIC float has magnitude M * 2^(exponent - 160), where M is
|
||||
// its unsigned 32-bit significand with an implicit leading one. Scaling M
|
||||
// by 5^places is exact in five bytes; the remaining factor is a power of two.
|
||||
static unsigned long roundedUnits(const unsigned char *packed, unsigned char places)
|
||||
{
|
||||
unsigned exponent = packed[0];
|
||||
if (!exponent) return 0UL;
|
||||
unsigned shift = 159 - exponent - places; // Keep one extra bit for rounding.
|
||||
if (shift >= 40) return 0UL;
|
||||
|
||||
unsigned char product[5];
|
||||
product[0] = 0;
|
||||
product[1] = packed[1] | 0x80;
|
||||
memcpy(product + 2, packed + 2, 3);
|
||||
for (unsigned step = 0; step < places; ++step) {
|
||||
unsigned carry = 0;
|
||||
for (unsigned i = sizeof(product); i > 0; --i) {
|
||||
unsigned part = (unsigned) product[i - 1] * 5 + carry;
|
||||
product[i - 1] = (unsigned char) part;
|
||||
carry = part >> 8;
|
||||
}
|
||||
}
|
||||
|
||||
// Within the accepted range shift is at least 12, so at most four
|
||||
// bytes contribute. Bit zero after shifting is the half-unit bit.
|
||||
unsigned bytes = sizeof(product) - shift / 8;
|
||||
unsigned long units = 0UL;
|
||||
for (unsigned i = 0; i < bytes; ++i)
|
||||
units = (units << 8) | product[i];
|
||||
units >>= shift % 8;
|
||||
return (units + 1UL) >> 1;
|
||||
}
|
||||
|
||||
int vcc_fixed(char *dest, unsigned capacity, float value, unsigned char places)
|
||||
{
|
||||
const unsigned char *packed = (const unsigned char *) &value;
|
||||
if (capacity && !dest) return -1;
|
||||
if (places > 3 || packed[0] > 144) { // Exponent 145 begins at 65536.
|
||||
if (capacity) dest[0] = '\0';
|
||||
return -1;
|
||||
}
|
||||
|
||||
unsigned long units = roundedUnits(packed, places);
|
||||
char digits[11]; // Room for a decimal unsigned long and its terminator.
|
||||
ultoa10(units, digits);
|
||||
int count = strlen(digits);
|
||||
int point = count - (int) places;
|
||||
char text[10]; // Longest possible output is "-65536.000", before the NUL.
|
||||
unsigned length = 0;
|
||||
if (units && (packed[1] & 0x80)) text[length++] = '-';
|
||||
if (point <= 0) text[length++] = '0';
|
||||
for (int i = 0; i < point; ++i) text[length++] = digits[i];
|
||||
if (places) {
|
||||
text[length++] = '.';
|
||||
for (int i = point; i < count; ++i)
|
||||
text[length++] = i < 0 ? '0' : digits[i];
|
||||
}
|
||||
|
||||
if (capacity) {
|
||||
unsigned stored = length < capacity ? length : capacity - 1;
|
||||
memcpy(dest, text, stored);
|
||||
dest[stored] = '\0';
|
||||
}
|
||||
return (int) length;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_FORMAT_INTERNAL_H
|
||||
#define VCC_FORMAT_INTERNAL_H
|
||||
#include <stdarg.h>
|
||||
|
||||
// A null source repeats fill. The sink accepts all count bytes or returns -1.
|
||||
typedef int (*VCCFormatWrite)(void *context, const char *source, char fill, unsigned count);
|
||||
int vcc_format_to(VCCFormatWrite write, void *context, const char *format, va_list args);
|
||||
#endif
|
||||
@@ -0,0 +1,175 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <stdio.h>
|
||||
#include <limits.h>
|
||||
#include "format-internal.h"
|
||||
|
||||
typedef struct Buffer {
|
||||
char *next;
|
||||
size_t remaining; // Excludes the final NUL.
|
||||
} Buffer;
|
||||
|
||||
static int storeBuffer(void *context, const char *source, char fill, unsigned count)
|
||||
{
|
||||
Buffer *buffer = (Buffer *) context;
|
||||
unsigned stored = count < buffer->remaining ? count : buffer->remaining;
|
||||
if (stored) {
|
||||
if (source)
|
||||
memcpy(buffer->next, source, stored);
|
||||
else
|
||||
memset(buffer->next, fill, stored);
|
||||
buffer->next += stored;
|
||||
buffer->remaining -= stored;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
typedef struct Output {
|
||||
VCCFormatWrite write;
|
||||
void *context;
|
||||
unsigned total; // Saturates one past the largest signed result.
|
||||
} Output;
|
||||
|
||||
static int emit(Output *out, const char *source, char fill, unsigned count)
|
||||
{
|
||||
if (count == 0) return 0;
|
||||
if (out->write(out->context, source, fill, count) < 0) return -1;
|
||||
if (out->total <= INT_MAX) {
|
||||
if (count > INT_MAX - out->total)
|
||||
out->total = (unsigned) INT_MAX + 1;
|
||||
else
|
||||
out->total += count;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Consume literal field width or precision. Values outside the supported
|
||||
// range cannot be represented reliably on this target.
|
||||
static int decimalField(const char **cursor)
|
||||
{
|
||||
unsigned value = 0;
|
||||
while (**cursor >= '0' && **cursor <= '9') {
|
||||
unsigned digit = **cursor - '0';
|
||||
if (value > (INT_MAX - digit) / 10)
|
||||
return -1;
|
||||
value = value * 10 + digit;
|
||||
++*cursor;
|
||||
}
|
||||
return (int) value;
|
||||
}
|
||||
|
||||
int vcc_format_to(VCCFormatWrite write, void *context, const char *format, va_list args)
|
||||
{
|
||||
Output out;
|
||||
if (!format) return -1;
|
||||
out.write = write;
|
||||
out.context = context;
|
||||
out.total = 0;
|
||||
|
||||
while (*format) {
|
||||
if (*format != '%') {
|
||||
const char *start = format;
|
||||
do { ++format; } while (*format && *format != '%');
|
||||
if (emit(&out, start, 0, format - start) < 0) return -1;
|
||||
continue;
|
||||
}
|
||||
++format;
|
||||
if (*format == '%') {
|
||||
if (emit(&out, 0, '%', 1) < 0) return -1;
|
||||
++format;
|
||||
continue;
|
||||
}
|
||||
|
||||
int left = 0, padZero = 0;
|
||||
while (*format == '-' || *format == '0') {
|
||||
if (*format == '-') left = 1;
|
||||
else padZero = 1;
|
||||
++format;
|
||||
}
|
||||
int width = decimalField(&format);
|
||||
if (width < 0) return -1;
|
||||
int precision = -1;
|
||||
if (*format == '.') {
|
||||
++format;
|
||||
precision = decimalField(&format);
|
||||
if (precision < 0) return -1;
|
||||
}
|
||||
int wide = *format == 'l';
|
||||
if (wide) ++format;
|
||||
char conversion = *format++;
|
||||
char digits[11]; // A 32-bit unsigned integer has at most 11 octal digits.
|
||||
const char *text = digits;
|
||||
unsigned length = 0, zeroes = 0;
|
||||
int negative = 0;
|
||||
if (conversion == 's') {
|
||||
if (wide || padZero) return -1;
|
||||
text = va_arg(args, const char *);
|
||||
// With a precision, the input need not be NUL terminated.
|
||||
while ((precision < 0 || length < (unsigned) precision) && text[length])
|
||||
++length;
|
||||
} else if (conversion == 'c') {
|
||||
if (wide || padZero || precision >= 0) return -1;
|
||||
digits[0] = (char) va_arg(args, int);
|
||||
length = 1;
|
||||
} else {
|
||||
unsigned base;
|
||||
switch (conversion) {
|
||||
case 'i': case 'd': case 'u': base = 10; break;
|
||||
case 'o': base = 8; break;
|
||||
case 'X': case 'x': base = 16; break;
|
||||
default: return -1;
|
||||
}
|
||||
unsigned long value;
|
||||
if (conversion == 'i' || conversion == 'd') {
|
||||
long number;
|
||||
if (wide) number = va_arg(args, long);
|
||||
else number = va_arg(args, int);
|
||||
negative = number < 0;
|
||||
value = (unsigned long) number;
|
||||
if (negative) value = 0UL - value;
|
||||
} else if (wide) value = va_arg(args, unsigned long);
|
||||
else value = va_arg(args, unsigned);
|
||||
|
||||
if (value || precision != 0) {
|
||||
do {
|
||||
unsigned digit = (unsigned) (value % base);
|
||||
const char *alphabet = conversion == 'X' ? "0123456789ABCDEF" : "0123456789abcdef";
|
||||
digits[sizeof(digits) - ++length] = alphabet[digit];
|
||||
value /= base;
|
||||
} while (value);
|
||||
}
|
||||
text = digits + sizeof(digits) - length;
|
||||
if (precision > (int) length) zeroes = (unsigned) precision - length;
|
||||
}
|
||||
unsigned occupied = length + zeroes + negative;
|
||||
unsigned gap = (unsigned) width > occupied ? (unsigned) width - occupied : 0U;
|
||||
if (padZero && !left && precision < 0) {
|
||||
zeroes += gap;
|
||||
gap = 0;
|
||||
}
|
||||
if (!left && emit(&out, 0, ' ', gap) < 0) return -1;
|
||||
if (negative && emit(&out, 0, '-', 1) < 0) return -1;
|
||||
if (emit(&out, 0, '0', zeroes) < 0 || emit(&out, text, 0, length) < 0) return -1;
|
||||
if (left && emit(&out, 0, ' ', gap) < 0) return -1;
|
||||
}
|
||||
return out.total > INT_MAX ? -1 : (int) out.total;
|
||||
}
|
||||
|
||||
int vsnprintf(char *dest, size_t capacity, const char *format, va_list args)
|
||||
{
|
||||
Buffer buffer;
|
||||
if (capacity && !dest) return -1;
|
||||
buffer.next = dest;
|
||||
buffer.remaining = capacity ? capacity - 1U : 0U;
|
||||
int result = vcc_format_to(storeBuffer, &buffer, format, args);
|
||||
if (capacity) *buffer.next = 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
int snprintf(char *dest, size_t capacity, const char *format, ...)
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
int result = vsnprintf(dest, capacity, format, args);
|
||||
va_end(args);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <stdlib.h>
|
||||
#include <limits.h>
|
||||
#include <wydealloc.h>
|
||||
|
||||
static MemPool pool;
|
||||
static size_t liveBlocks;
|
||||
|
||||
int vcc_heap_init(void *buffer, size_t capacity)
|
||||
{
|
||||
// 16 bytes leaves room for even the smallest block, including WydeAlloc
|
||||
// bookkeeping and the two-byte capacity we keep for realloc.
|
||||
if (liveBlocks || !buffer || capacity < 16 || capacity > UINT_MAX - (unsigned) buffer)
|
||||
return 0;
|
||||
// Normalize the backend byte result to the public int success value.
|
||||
return MemPool_init(&pool, buffer, (char *) buffer + capacity) ? 1 : 0;
|
||||
}
|
||||
|
||||
void *malloc(size_t size)
|
||||
{
|
||||
if (!pool.start || !size || size > UINT_MAX - sizeof(size_t))
|
||||
return NULL;
|
||||
|
||||
// CMOC's 6809 ABI allows a size_t at any byte address. Keep its value in
|
||||
// our own allocation so we never depend on WydeAlloc's private block layout.
|
||||
size_t *block = (size_t *) MemPool_alloc(&pool, size + sizeof(size_t));
|
||||
if (!block)
|
||||
return NULL;
|
||||
*block = size;
|
||||
++liveBlocks;
|
||||
return block + 1;
|
||||
}
|
||||
|
||||
void free(void *ptr)
|
||||
{
|
||||
if (ptr)
|
||||
{
|
||||
MemPool_free(&pool, (size_t *) ptr - 1);
|
||||
--liveBlocks;
|
||||
}
|
||||
}
|
||||
|
||||
void *calloc(size_t count, size_t size)
|
||||
{
|
||||
if (!count || !size || count > UINT_MAX / size)
|
||||
return NULL;
|
||||
size_t total = count * size;
|
||||
void *ptr = malloc(total);
|
||||
if (ptr)
|
||||
memset(ptr, 0, total);
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void *realloc(void *ptr, size_t size)
|
||||
{
|
||||
if (!ptr)
|
||||
return malloc(size);
|
||||
if (size == 0)
|
||||
{
|
||||
free(ptr);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
size_t capacity = *((size_t *) ptr - 1);
|
||||
if (size <= capacity)
|
||||
return ptr;
|
||||
void *larger = malloc(size);
|
||||
if (larger)
|
||||
{
|
||||
memcpy(larger, ptr, capacity);
|
||||
free(ptr);
|
||||
}
|
||||
return larger;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_COMPAT_CTYPE_H
|
||||
#define VCC_COMPAT_CTYPE_H
|
||||
|
||||
// The CMOC runtime supplies isalnum, isalpha, isdigit, isspace, tolower and toupper.
|
||||
#include <cmoc.h>
|
||||
int isblank(int c);
|
||||
int iscntrl(int c);
|
||||
int isgraph(int c);
|
||||
int islower(int c);
|
||||
int isprint(int c);
|
||||
int ispunct(int c);
|
||||
int isupper(int c);
|
||||
int isxdigit(int c);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Both include orders leave CMOC's legacy rewind(FileDesc *) available.
|
||||
#ifndef VCC_COMPAT_DISK_H
|
||||
#define VCC_COMPAT_DISK_H
|
||||
|
||||
#ifdef VCC_COMPAT_STDIO_H
|
||||
#undef rewind
|
||||
#endif
|
||||
#include "../../disk.h"
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_COMPAT_ERRNO_H
|
||||
#define VCC_COMPAT_ERRNO_H
|
||||
|
||||
// Foreground guest error indicator for strtol and strtoul.
|
||||
extern int errno;
|
||||
#define EINVAL 22
|
||||
#define ERANGE 34
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_COMPAT_LIMITS_H
|
||||
#define VCC_COMPAT_LIMITS_H
|
||||
|
||||
#define CHAR_BIT 8
|
||||
#define SCHAR_MIN (-127 - 1)
|
||||
#define SCHAR_MAX 127
|
||||
#define UCHAR_MAX 255U
|
||||
#ifdef _CMOC_unsigned_char_
|
||||
#define CHAR_MIN 0
|
||||
#define CHAR_MAX UCHAR_MAX
|
||||
#else
|
||||
#define CHAR_MIN SCHAR_MIN
|
||||
#define CHAR_MAX SCHAR_MAX
|
||||
#endif
|
||||
#define SHRT_MIN (-32767 - 1)
|
||||
#define SHRT_MAX 32767
|
||||
#define USHRT_MAX 65535U
|
||||
#define INT_MIN SHRT_MIN
|
||||
#define INT_MAX SHRT_MAX
|
||||
#define UINT_MAX USHRT_MAX
|
||||
#define LONG_MIN (-2147483647L - 1L)
|
||||
#define LONG_MAX 2147483647L
|
||||
#define ULONG_MAX 4294967295UL
|
||||
#define MB_LEN_MAX 1
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_COMPAT_STDDEF_H
|
||||
#define VCC_COMPAT_STDDEF_H
|
||||
|
||||
// Reuse CMOC's definitions of size_t, NULL and offsetof.
|
||||
#include <cmoc.h>
|
||||
typedef signed int ptrdiff_t;
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,41 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_COMPAT_STDINT_H
|
||||
#define VCC_COMPAT_STDINT_H
|
||||
|
||||
#include <limits.h>
|
||||
|
||||
// coco.h uses the same guard and types for its exact-width declarations.
|
||||
#ifndef _CMOC_STDINT_
|
||||
#define _CMOC_STDINT_
|
||||
typedef signed char int8_t;
|
||||
typedef unsigned char uint8_t;
|
||||
typedef signed int int16_t;
|
||||
typedef unsigned int uint16_t;
|
||||
typedef signed long int32_t;
|
||||
typedef unsigned long uint32_t;
|
||||
#endif
|
||||
|
||||
typedef signed int intptr_t;
|
||||
typedef unsigned int uintptr_t;
|
||||
typedef signed long intmax_t;
|
||||
typedef unsigned long uintmax_t;
|
||||
#define INT8_MIN SCHAR_MIN
|
||||
#define INT8_MAX SCHAR_MAX
|
||||
#define UINT8_MAX UCHAR_MAX
|
||||
#define INT16_MIN INT_MIN
|
||||
#define INT16_MAX INT_MAX
|
||||
#define UINT16_MAX UINT_MAX
|
||||
#define INT32_MIN LONG_MIN
|
||||
#define INT32_MAX LONG_MAX
|
||||
#define UINT32_MAX ULONG_MAX
|
||||
#define INTPTR_MIN INT_MIN
|
||||
#define INTPTR_MAX INT_MAX
|
||||
#define UINTPTR_MAX UINT_MAX
|
||||
#define INTMAX_MIN LONG_MIN
|
||||
#define INTMAX_MAX LONG_MAX
|
||||
#define UINTMAX_MAX ULONG_MAX
|
||||
#ifndef SIZE_MAX
|
||||
#define SIZE_MAX 0xFFFFu
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,80 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_COMPAT_STDIO_H
|
||||
#define VCC_COMPAT_STDIO_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdarg.h>
|
||||
#define EOF (-1)
|
||||
#define SEEK_SET 0
|
||||
#define SEEK_CUR 1
|
||||
#define SEEK_END 2
|
||||
|
||||
// %% %c %s %d %i %u %o %x %X. Integer forms also accept l. A decimal
|
||||
// width, left alignment, zero padding, and string/integer precision are
|
||||
// supported. Return the full length, or -1 for unsupported formats or lengths
|
||||
// above INT_MAX. If capacity is positive the prefix is always NUL terminated.
|
||||
// A null destination is allowed when capacity is zero. Input and output must
|
||||
// not overlap.
|
||||
int snprintf(char *dest, size_t capacity, const char *format, ...);
|
||||
int vsnprintf(char *dest, size_t capacity, const char *format, va_list args);
|
||||
|
||||
// Two foreground Disk BASIC streams. Names use 8.3 format with an optional
|
||||
// :0 through :3 drive suffix (default :0). Modes r, w and a read, truncate
|
||||
// and append respectively; w/a create missing files. Append b for binary.
|
||||
// Add + for both input and output. r+ requires an existing file. w+ creates
|
||||
// or truncates; a+ creates or preserves. All three start reading at byte zero.
|
||||
// Every a+ write appends, even after a seek. Both +b and b+ select binary.
|
||||
// After input, seek or rewind before writing unless input encountered EOF.
|
||||
// Flush, seek or rewind between output and input.
|
||||
// Text reads fold CR, LF and CRLF to C newline; text writes C newline as CR.
|
||||
// Close streams before changing mounted media or writing through another API.
|
||||
typedef struct VCCFile FILE;
|
||||
FILE *fopen(const char *path, const char *mode);
|
||||
int fclose(FILE *stream);
|
||||
// Disk BASIC file management uses the same paths as fopen. Close participating
|
||||
// files first. rename stays on one drive and refuses an existing destination,
|
||||
// including an alias of the source. remove releases the file's granules.
|
||||
// Both return 0 on success or EOF on failure; inspect vcc_file_error().
|
||||
int rename(const char *oldPath, const char *newPath);
|
||||
int remove(const char *path);
|
||||
int fgetc(FILE *stream);
|
||||
char *fgets(char *dest, int capacity, FILE *stream);
|
||||
size_t fread(void *dest, size_t size, size_t count, FILE *stream);
|
||||
// Same conversions and length limit as snprintf. Return the number of bytes
|
||||
// accepted or a negative value on error. A prefix may already be written.
|
||||
// Check fflush or fclose for delayed disk errors.
|
||||
int fprintf(FILE *stream, const char *format, ...);
|
||||
int vfprintf(FILE *stream, const char *format, va_list args);
|
||||
int fputc(int c, FILE *stream);
|
||||
int fputs(const char *text, FILE *stream);
|
||||
size_t fwrite(const void *source, size_t size, size_t count, FILE *stream);
|
||||
// Publish data and the file's exact length. A fresh reader can open the file
|
||||
// while the writer remains open. Pass NULL to flush all open output streams.
|
||||
// Returns 0 on success or EOF on failure. Check fclose for delayed errors.
|
||||
int fflush(FILE *stream);
|
||||
// Positions are 32-bit offsets in the guest file. Binary streams support
|
||||
// signed offsets from any origin within the existing file. In text mode
|
||||
// restore an ftell bookmark with SEEK_SET, or use zero with any origin.
|
||||
// Seeking flushes pending output. The next append write still goes to EOF.
|
||||
long ftell(FILE *stream);
|
||||
int fseek(FILE *stream, long offset, int origin);
|
||||
// With <stdio.h> alone, rewind is an alias for this function, including
|
||||
// when taking its address. In a file that also includes CMOC's <disk.h>,
|
||||
// rewind keeps its FileDesc meaning; use vcc_rewind for a FILE stream.
|
||||
// A successful rewind clears EOF and errors. Check ferror after a retry.
|
||||
void vcc_rewind(FILE *stream);
|
||||
#ifndef _H_disk
|
||||
#define rewind vcc_rewind
|
||||
#endif
|
||||
int feof(FILE *stream);
|
||||
int ferror(FILE *stream);
|
||||
// Clear this open stream's EOF and error indicators. The position, pending
|
||||
// bytes and last I/O direction are preserved. To retry a failed flush on
|
||||
// the same disk, correct the cause, call clearerr, then call fflush again.
|
||||
void clearerr(FILE *stream);
|
||||
|
||||
// The latest failure (including a failed fopen). A successful fopen resets
|
||||
// this value to DECB_OK. See <decbfile.h> for DECB_ERR_* values.
|
||||
unsigned char vcc_file_error(void);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,32 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_COMPAT_STDLIB_H
|
||||
#define VCC_COMPAT_STDLIB_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
// stddef.h has already included cmoc.h. Replace its decimal-only macros in
|
||||
// this opt-in header, leaving the explicitly named CMOC routines available.
|
||||
#undef strtol
|
||||
#undef strtoul
|
||||
long strtol(const char *text, char **endptr, int base);
|
||||
unsigned long strtoul(const char *text, char **endptr, int base);
|
||||
|
||||
// Supply a writable guest array (at least 16 bytes) that stays at the same
|
||||
// address for the lifetime of the heap. Its one-past-end address must fit in
|
||||
// 16 bits. Return 1 on success or 0 if invalid or any allocation is live.
|
||||
// A rejected initialization leaves the current heap and its contents intact.
|
||||
int vcc_heap_init(void *buffer, size_t capacity);
|
||||
|
||||
// Zero-size requests return NULL. Allocation can also fail before initialization
|
||||
// or when no contiguous block fits. calloc checks for multiplication overflow.
|
||||
void *malloc(size_t size);
|
||||
void *calloc(size_t count, size_t size);
|
||||
|
||||
// Growth may move the block. If it fails, the old allocation stays valid.
|
||||
// Shrinking keeps the existing block. realloc(ptr, 0) releases it.
|
||||
void *realloc(void *ptr, size_t size);
|
||||
|
||||
// Accepts NULL or a live pointer returned by this heap.
|
||||
void free(void *ptr);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,15 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_COMPAT_STRING_H
|
||||
#define VCC_COMPAT_STRING_H
|
||||
|
||||
// CMOC declares the byte and string operations, including memmove, strchr,
|
||||
// strcmp and strtok, in its runtime header. Use those same declarations.
|
||||
#include <cmoc.h>
|
||||
|
||||
// POSIX extension. Start with a writable string, then pass NULL to continue.
|
||||
// Give each active scan its own char * and pass its address on every call.
|
||||
// Tokens share the input buffer. Separators are skipped and each delimiter
|
||||
// that ends a returned token becomes a zero byte.
|
||||
char *strtok_r(char *text, const char *delimiters, char **saveptr);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,45 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/printer.h>
|
||||
#include "format-internal.h"
|
||||
|
||||
// Use the BASIC PUTCHR vector directly so a CMOC console hook stays private
|
||||
// to the program. Restore the previous BASIC device after each character.
|
||||
static asm void printerChar(unsigned char c)
|
||||
{
|
||||
asm {
|
||||
lda 3,s
|
||||
cmpa #10
|
||||
bne @send
|
||||
lda #13
|
||||
@send ldb >$006f ; BASIC DEVNUM
|
||||
pshs b,y,u
|
||||
ldb #-2 ; DEV_PRINTER
|
||||
stb >$006f
|
||||
jsr [$a002] ; PUTCHR takes the character in A
|
||||
puls b,y,u
|
||||
stb >$006f
|
||||
}
|
||||
}
|
||||
|
||||
static int writePrinter(void *context, const char *source, char fill, unsigned count)
|
||||
{
|
||||
while (count--) {
|
||||
char c = source ? *source++ : fill;
|
||||
printerChar(c);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int vcc_printer_vprintf(const char *format, va_list args)
|
||||
{
|
||||
return vcc_format_to(writePrinter, 0, format, args);
|
||||
}
|
||||
|
||||
int vcc_printer_printf(const char *format, ...)
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
int result = vcc_printer_vprintf(format, args);
|
||||
va_end(args);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,840 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Buffered streams on a Disk BASIC volume. All I/O runs in the foreground.
|
||||
#include <stdio.h>
|
||||
#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;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
|
||||
int errno;
|
||||
|
||||
typedef struct ParseStatus {
|
||||
int negative;
|
||||
int overflow;
|
||||
} ParseStatus;
|
||||
|
||||
// 36 terminates the scan in every supported base.
|
||||
static unsigned digitValue(char c)
|
||||
{
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'A' && c <= 'Z') return c - 'A' + 10;
|
||||
if (c >= 'a' && c <= 'z') return c - 'a' + 10;
|
||||
return 36;
|
||||
}
|
||||
|
||||
static unsigned long magnitude(const char *text, char **endptr, int base,
|
||||
int signedResult, ParseStatus *status)
|
||||
{
|
||||
const char *p = text;
|
||||
status->negative = 0;
|
||||
status->overflow = 0;
|
||||
if (endptr) *endptr = (char *) text;
|
||||
if (base != 0 && (base < 2 || base > 36)) {
|
||||
errno = EINVAL;
|
||||
return 0UL;
|
||||
}
|
||||
while (isspace((unsigned char) *p)) ++p;
|
||||
if (*p == '+' || *p == '-') {
|
||||
status->negative = (*p == '-');
|
||||
++p;
|
||||
}
|
||||
// In "0x!" the zero is a valid digit and the x ends the number.
|
||||
if ((base == 0 || base == 16) && *p == '0' &&
|
||||
(p[1] == 'x' || p[1] == 'X') && digitValue(p[2]) < 16) {
|
||||
base = 16;
|
||||
p += 2;
|
||||
} else if (base == 0) {
|
||||
base = (*p == '0') ? 8 : 10;
|
||||
}
|
||||
|
||||
unsigned digit = digitValue(*p);
|
||||
if (digit >= (unsigned) base) return 0UL;
|
||||
unsigned long limit = ULONG_MAX;
|
||||
if (signedResult) limit = (unsigned long) LONG_MAX + status->negative;
|
||||
unsigned long cutoff = limit / (unsigned) base;
|
||||
unsigned lastDigit = (unsigned) (limit - cutoff * (unsigned) base);
|
||||
unsigned long value = 0UL;
|
||||
do {
|
||||
if (!status->overflow) {
|
||||
if (value > cutoff || (value == cutoff && digit > lastDigit)) {
|
||||
status->overflow = 1;
|
||||
value = limit;
|
||||
errno = ERANGE;
|
||||
} else {
|
||||
value = value * (unsigned) base + digit;
|
||||
}
|
||||
}
|
||||
// Even after saturation, the end pointer must skip every valid digit.
|
||||
digit = digitValue(*++p);
|
||||
} while (digit < (unsigned) base);
|
||||
if (endptr) *endptr = (char *) p;
|
||||
return value;
|
||||
}
|
||||
|
||||
long strtol(const char *text, char **endptr, int base)
|
||||
{
|
||||
ParseStatus status;
|
||||
unsigned long value = magnitude(text, endptr, base, 1, &status);
|
||||
if (!status.negative) return (long) value;
|
||||
if (value > (unsigned long) LONG_MAX) return LONG_MIN;
|
||||
return -(long) value;
|
||||
}
|
||||
|
||||
unsigned long strtoul(const char *text, char **endptr, int base)
|
||||
{
|
||||
ParseStatus status;
|
||||
unsigned long value = magnitude(text, endptr, base, 0, &status);
|
||||
if (status.negative && !status.overflow) return 0UL - value;
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Run the compatibility smoke test, including nested tokenization, on both guest CPUs."""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("runtime", type=Path)
|
||||
parser.add_argument("core", type=Path)
|
||||
parser.add_argument("rom", type=Path)
|
||||
args = parser.parse_args()
|
||||
runtime, core, rom = [p.resolve(strict=True) for p in (args.runtime, args.core, args.rom)]
|
||||
tests = Path(__file__).resolve().parent
|
||||
runner = tests.parents[3] / "tests/toolchain/run-compiled.cpp"
|
||||
env = dict(os.environ, VCC_CMOC_COMPAT="1")
|
||||
with tempfile.TemporaryDirectory(prefix="vcc-compat-") as tmp:
|
||||
def run(*args):
|
||||
subprocess.run(args, cwd=tmp, env=env, check=True)
|
||||
|
||||
run("xcrun", "clang++", "-std=c++17", "-O2", "-mmacosx-version-min=14.0",
|
||||
runner, core, "-o", "run")
|
||||
for opt in ("-O0", "-O2"):
|
||||
cc = [runtime / "bin/cmoc", "--coco", opt, "-Werror"]
|
||||
caller = [*cc, "--org=2800", "-o", "TEST.BIN", tests / "compat-check.c"]
|
||||
print(f"{opt} caller with staged library", flush=True)
|
||||
run(*caller, "-lvcccompat")
|
||||
run("./run", rom, "TEST.BIN", "COMPAT PASS")
|
||||
if opt == "-O0":
|
||||
# The staged archive always contains the optimized implementation.
|
||||
print("Checking the unoptimized compatibility routines as well", flush=True)
|
||||
units = ["tokenize", "ctype", "format"]
|
||||
for unit in units:
|
||||
run(*cc, "-c", "-o", unit + ".o", tests.parent / (unit + ".c"))
|
||||
run(*caller, *(unit + ".o" for unit in units))
|
||||
run("./run", rom, "TEST.BIN", "COMPAT PASS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,119 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Build with the compatibility include directory and -lvcccompat. Run on either
|
||||
// emulated CPU; a failed check reports its source line on the CoCo screen.
|
||||
#ifdef COCO_HEADER_FIRST
|
||||
#include <coco.h>
|
||||
#endif
|
||||
#include <stdint.h>
|
||||
#include <limits.h>
|
||||
#include <stddef.h>
|
||||
#include <ctype.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <coco.h>
|
||||
|
||||
#define CHECK(test) do { if (!(test)) return __LINE__; } while (0)
|
||||
|
||||
struct Pair { uint8_t tag; uint16_t number; };
|
||||
|
||||
static int checkTokens(void)
|
||||
{
|
||||
char row[] = "||MARS|RED,,COLD|4||";
|
||||
char plain[] = "A B";
|
||||
char separators[] = " | ,";
|
||||
char untouched[] = "ONE TWO";
|
||||
char empty[] = "";
|
||||
char *field, *trait;
|
||||
// A fresh scan ignores the cursor's prior value. A token points into
|
||||
// the original writable line. Splitting it can start a second scan.
|
||||
CHECK(strtok_r(row, "|", &field) == row + 2);
|
||||
CHECK(strcmp(row + 2, "MARS") == 0);
|
||||
char *traits = strtok_r(NULL, "|", &field);
|
||||
CHECK(traits == row + 7);
|
||||
CHECK(strtok_r(traits, ",", &trait) == traits);
|
||||
CHECK(strcmp(traits, "RED") == 0);
|
||||
CHECK(strtok(plain, " ") == plain);
|
||||
CHECK(strtok_r(NULL, ",", &trait) == traits + 5);
|
||||
CHECK(strcmp(traits + 5, "COLD") == 0);
|
||||
CHECK(strtok_r(NULL, ",", &trait) == NULL);
|
||||
CHECK(strtok_r(NULL, "|", &field) == row + 17);
|
||||
CHECK(strcmp(row + 17, "4") == 0);
|
||||
CHECK(strtok_r(NULL, "|", &field) == NULL);
|
||||
CHECK(strtok_r(NULL, "|", &field) == NULL);
|
||||
CHECK(strtok(NULL, " ") == plain + 2);
|
||||
|
||||
CHECK(strtok_r(empty, ",", &field) == NULL);
|
||||
CHECK(strtok_r(separators, " ,|", &field) == NULL);
|
||||
CHECK(strtok_r(untouched, "", &field) == untouched);
|
||||
CHECK(strcmp(untouched, "ONE TWO") == 0);
|
||||
CHECK(strtok_r(NULL, "", &field) == NULL);
|
||||
char changed[] = "A,B:C+D";
|
||||
CHECK(strtok_r(changed, ",", &field) == changed);
|
||||
CHECK(strtok_r(NULL, ":+", &field) == changed + 2);
|
||||
CHECK(strcmp(changed + 2, "B") == 0);
|
||||
// Starting a new string abandons the remainder of the previous one.
|
||||
CHECK(strtok_r(untouched, " ", &field) == untouched);
|
||||
CHECK(strtok_r(NULL, " ", &field) == untouched + 4);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int viaList(char *buf, size_t n, const char *fmt, ...)
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
int code = vsnprintf(buf, n, fmt, args);
|
||||
va_end(args);
|
||||
return code;
|
||||
}
|
||||
|
||||
static int checks(void)
|
||||
{
|
||||
char box[18], longBuf[42];
|
||||
const char raw[2] = { 'A', 'B' };
|
||||
CHECK(sizeof(int8_t) == 1 && sizeof(int16_t) == 2 && sizeof(int32_t) == 4);
|
||||
CHECK(sizeof(size_t) == 2 && sizeof(ptrdiff_t) == 2 && sizeof(uintptr_t) == sizeof(void *));
|
||||
CHECK(offsetof(struct Pair, number) == 1 && CHAR_BIT == 8);
|
||||
#ifdef _CMOC_unsigned_char_
|
||||
CHECK(CHAR_MIN == 0 && CHAR_MAX == 255);
|
||||
#else
|
||||
CHECK(CHAR_MIN == -128 && CHAR_MAX == 127);
|
||||
#endif
|
||||
CHECK(iscntrl(EOF) == 0 && isspace(EOF) == 0 && tolower(EOF) == EOF && toupper(EOF) == EOF);
|
||||
CHECK(isblank('\t') && !isblank('\r') && iscntrl(127) && !isprint(127));
|
||||
CHECK(isprint(' ') && !isgraph(' ') && isgraph('!') && ispunct('!') && !ispunct('a'));
|
||||
CHECK(isxdigit('F') && isxdigit('b') && !isxdigit('G') && islower('b') && isupper('B'));
|
||||
strcpy(box, "abcd");
|
||||
memmove(box + 1, box, 4);
|
||||
box[5] = 0;
|
||||
CHECK(strcmp(box, "aabcd") == 0);
|
||||
CHECK(strlen("") == 0 && memmove(box, box, 0) == box);
|
||||
CHECK(snprintf(box, sizeof(box), NULL) < 0 && box[0] == 0);
|
||||
memset(box, '@', sizeof(box));
|
||||
CHECK(snprintf(NULL, 0, "%s %c", "CoCo", '3') == 6);
|
||||
CHECK(snprintf(box + 1, 0, "abc") == 3 && box[1] == '@');
|
||||
CHECK(snprintf(box + 1, 1, "abc") == 3 && box[1] == 0 && box[2] == '@');
|
||||
CHECK(snprintf(box + 1, 4, "earth") == 5 && strcmp(box + 1, "ear") == 0);
|
||||
CHECK(box[0] == '@' && box[5] == '@');
|
||||
CHECK(snprintf(box, 6, "earth") == 5 && strcmp(box, "earth") == 0);
|
||||
CHECK(snprintf(box, sizeof(box), "%cX", 0) == 2 && !box[0] && box[1] == 'X' && !box[2]);
|
||||
CHECK(viaList(box, sizeof(box), "%04x,%X,%o", 0x1aU, 0xbeefU, 8U) == 12);
|
||||
CHECK(!strcmp(box, "001a,BEEF,10"));
|
||||
CHECK(snprintf(box, sizeof(box), "%-4.2s|%.0u", raw, 0U) == 5 && strcmp(box, "AB |") == 0);
|
||||
CHECK(snprintf(box, sizeof(box), "%05d %4.2d %%", -23, 3) == 12 && !strcmp(box, "-0023 03 %"));
|
||||
CHECK(snprintf(longBuf, sizeof(longBuf), "%ld,%lu,%lo", LONG_MIN, ULONG_MAX, ULONG_MAX) == 34);
|
||||
CHECK(!strcmp(longBuf, "-2147483648,4294967295,37777777777"));
|
||||
CHECK(snprintf(box, sizeof(box), "%d", INT_MIN) == 6 && !strcmp(box, "-32768"));
|
||||
CHECK(snprintf(NULL, 0, "%32767d", 1) == INT_MAX);
|
||||
CHECK(snprintf(box, 2, "a%32767d", 1) < 0 && !strcmp(box, "a"));
|
||||
CHECK(snprintf(box, 3, "x%f") < 0 && !strcmp(box, "x"));
|
||||
CHECK(snprintf(box, 3, "x%") < 0 && !strcmp(box, "x"));
|
||||
return checkTokens();
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int failure = checks();
|
||||
if (failure) printf("COMPAT FAIL %d\n", failure);
|
||||
else printf("COMPAT PASS\n");
|
||||
return failure != 0;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <string.h>
|
||||
|
||||
char *strtok_r(char *text, const char *delimiters, char **saveptr)
|
||||
{
|
||||
if (text == NULL)
|
||||
text = *saveptr;
|
||||
if (text == NULL)
|
||||
return NULL;
|
||||
|
||||
char *token = text + strspn(text, delimiters);
|
||||
if (*token == '\0') {
|
||||
*saveptr = NULL;
|
||||
return NULL;
|
||||
}
|
||||
char *separator = strpbrk(token, delimiters);
|
||||
if (separator) {
|
||||
*separator = '\0';
|
||||
*saveptr = separator + 1;
|
||||
} else {
|
||||
*saveptr = NULL;
|
||||
}
|
||||
return token;
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/gime.h>
|
||||
|
||||
typedef unsigned char byte;
|
||||
#define REG(addr) (*(byte *)(addr))
|
||||
|
||||
#define FIRST_PAGE 0x20
|
||||
#define SECOND_PAGE 0x24
|
||||
#define WINDOW 0x8000
|
||||
|
||||
static byte back; // Zero when closed; otherwise an 8 KiB block number.
|
||||
static byte palette[16];
|
||||
static const byte *textImage;
|
||||
|
||||
// program_end is provided by CMOC's linker script. While bank 4 is mapped,
|
||||
// neither an instruction fetch nor a stack access may land in the window.
|
||||
static asm byte lowProgramAndStack(void)
|
||||
{
|
||||
asm {
|
||||
program_end import
|
||||
ldx #program_end
|
||||
cmpx #$8000
|
||||
bhi @reject
|
||||
cmps #$8000
|
||||
bhi @reject
|
||||
tfr cc,b
|
||||
bitb #$10
|
||||
bne @reject
|
||||
ldb #1
|
||||
rts
|
||||
@reject clrb
|
||||
}
|
||||
}
|
||||
|
||||
// A real 128 KiB GIME accepts the same MMU register writes as a 512 KiB
|
||||
// machine, but blocks $20 and $30 alias. Change just one byte reversibly.
|
||||
// An inactive window (for instance, wrong task) also fails this test.
|
||||
static asm byte independentBanks(void)
|
||||
{
|
||||
asm {
|
||||
pshs cc
|
||||
orcc #$50
|
||||
lda >$ffa4
|
||||
pshs a
|
||||
lda #$30
|
||||
sta >$ffa4
|
||||
lda >$9555
|
||||
pshs a
|
||||
lda #$20
|
||||
sta >$ffa4
|
||||
lda >$9555
|
||||
pshs a
|
||||
coma
|
||||
sta >$9555
|
||||
cmpa >$9555
|
||||
bne @alias
|
||||
lda #$30
|
||||
sta >$ffa4
|
||||
ldb >$9555
|
||||
cmpb 1,s
|
||||
bne @alias
|
||||
ldb #1
|
||||
bra @restore
|
||||
@alias clrb
|
||||
@restore
|
||||
lda #$20
|
||||
sta >$ffa4
|
||||
puls a
|
||||
sta >$9555
|
||||
leas 1,s
|
||||
puls a
|
||||
sta >$ffa4
|
||||
puls cc
|
||||
}
|
||||
}
|
||||
|
||||
// BASIC's 16-bit TIMER is incremented by its vertical interrupt handler.
|
||||
// Poll the complete word, including through wraparound, with interrupts live.
|
||||
// Aligned 32 KiB images share a zero low offset; flipping needs one store.
|
||||
// The countdown makes missing IRQs a recoverable error.
|
||||
static byte field(byte offsetHigh, byte flip)
|
||||
{
|
||||
asm {
|
||||
ldd >$0112
|
||||
ldx #$2000
|
||||
@wait cmpd >$0112
|
||||
bne @blank
|
||||
leax -1,x
|
||||
bne @wait
|
||||
clrb
|
||||
bra @done
|
||||
@blank tst :flip
|
||||
beq @success
|
||||
ldb :offsetHigh
|
||||
stb >$ff9d
|
||||
@success
|
||||
ldb #1
|
||||
@done stb :flip
|
||||
}
|
||||
return flip;
|
||||
}
|
||||
|
||||
// Paint at most one scan-line fragment in one bank. Preserve the other nibble
|
||||
// at either edge. Mask interrupts only across the short-lived mapping: BASIC
|
||||
// can take its normal 60 Hz interrupt between scan lines.
|
||||
static void span(byte bank, unsigned address, byte lowFirst, byte pairs,
|
||||
byte highLast, byte color)
|
||||
{
|
||||
byte packed = (color << 4) | color;
|
||||
asm {
|
||||
pshs cc
|
||||
orcc #$50
|
||||
lda >$ffa4
|
||||
pshs a
|
||||
lda :bank
|
||||
sta >$ffa4
|
||||
ldx :address
|
||||
tst :lowFirst
|
||||
beq @pairs
|
||||
lda ,x
|
||||
anda #$f0
|
||||
ora :color
|
||||
sta ,x+
|
||||
@pairs ldb :pairs
|
||||
beq @last
|
||||
lda :packed
|
||||
@loop sta ,x+
|
||||
decb
|
||||
bne @loop
|
||||
@last tst :highLast
|
||||
beq @done
|
||||
lda :packed
|
||||
anda #$f0
|
||||
ldb ,x
|
||||
andb #$0f
|
||||
pshs b
|
||||
ora ,s+
|
||||
sta ,x
|
||||
@done puls a
|
||||
sta >$ffa4
|
||||
puls cc
|
||||
}
|
||||
}
|
||||
|
||||
void gime_fill_rect(unsigned x, unsigned y, unsigned w, unsigned h, byte color)
|
||||
{
|
||||
unsigned rowPixel;
|
||||
if (!back || color > 15 || x >= GIME_WIDTH || y >= GIME_HEIGHT || !w || !h)
|
||||
return;
|
||||
if (w > GIME_WIDTH - x) w = GIME_WIDTH - x;
|
||||
if (h > GIME_HEIGHT - y) h = GIME_HEIGHT - y;
|
||||
rowPixel = y * GIME_WIDTH + x;
|
||||
while (h--) {
|
||||
unsigned pixel = rowPixel;
|
||||
unsigned remaining = w;
|
||||
while (remaining) {
|
||||
unsigned inBank = pixel & 0x3fff;
|
||||
unsigned count = 0x4000 - inBank;
|
||||
byte first = (byte)(pixel & 1);
|
||||
if (count > remaining) count = remaining;
|
||||
span((byte)(back + (pixel >> 14)), WINDOW + (inBank >> 1), first,
|
||||
(byte)((count - first) >> 1), (byte)((count - first) & 1), color);
|
||||
pixel += count;
|
||||
remaining -= count;
|
||||
}
|
||||
rowPixel += GIME_WIDTH;
|
||||
}
|
||||
}
|
||||
|
||||
void gime_plot(unsigned x, unsigned y, byte color)
|
||||
{
|
||||
gime_fill_rect(x, y, 1, 1, color);
|
||||
}
|
||||
|
||||
void gime_clear(byte color)
|
||||
{
|
||||
gime_fill_rect(0, 0, GIME_WIDTH, GIME_HEIGHT, color);
|
||||
}
|
||||
|
||||
void gime_set_palette(byte slot, byte rgb)
|
||||
{
|
||||
if (back && slot < 16 && rgb < 64)
|
||||
REG(0xffb0 + slot) = rgb;
|
||||
}
|
||||
|
||||
byte gime_open(void)
|
||||
{
|
||||
byte i, width;
|
||||
// Super Extended BASIC defines HRMODE at $E6 and HRWIDTH at $E7.
|
||||
if (back || !lowProgramAndStack() || *(unsigned *)0xfff8 != 0xfef7 ||
|
||||
REG(0xe6) != 0 || REG(0xe7) > 2)
|
||||
return 0;
|
||||
for (i = 0; i < 16; ++i) {
|
||||
byte bank = REG(0xffa0 + i) & 0x3f;
|
||||
if (bank >= FIRST_PAGE && bank < SECOND_PAGE + 4)
|
||||
return 0;
|
||||
}
|
||||
if (!field(0, 0) || !independentBanks())
|
||||
return 0;
|
||||
|
||||
width = REG(0xe7);
|
||||
textImage = (const byte *)0xe032 + width * 9;
|
||||
for (i = 0; i < 16; ++i)
|
||||
palette[i] = REG(0xffb0 + i) & 0x3f;
|
||||
|
||||
back = FIRST_PAGE;
|
||||
gime_clear(0);
|
||||
back = SECOND_PAGE;
|
||||
gime_clear(0);
|
||||
if (!field(0, 0)) {
|
||||
back = 0;
|
||||
return 0;
|
||||
}
|
||||
// Super Extended BASIC keeps editable images of the write-only registers
|
||||
// at $E032 (text tables) and $E070 (graphics). Keep the ROM's color phase.
|
||||
REG(0xff90) = REG(0xe070);
|
||||
REG(0xff98) = REG(0xe071);
|
||||
REG(0xff99) = 0x1e; // 192 lines, 160 bytes per row, 16 colors.
|
||||
REG(0xff9c) = 0;
|
||||
REG(0xff9d) = FIRST_PAGE << 2;
|
||||
REG(0xff9e) = 0;
|
||||
REG(0xff9f) = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
byte gime_present(void)
|
||||
{
|
||||
if (!back || !field(back << 2, 1))
|
||||
return 0;
|
||||
back = (back == SECOND_PAGE ? FIRST_PAGE : SECOND_PAGE);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void gime_close(void)
|
||||
{
|
||||
byte i;
|
||||
if (!back) return;
|
||||
field(0, 0); // Even if the timer stops, always give the display back.
|
||||
REG(0xff90) = textImage[0];
|
||||
REG(0xff98) = textImage[1];
|
||||
REG(0xff99) = textImage[2];
|
||||
REG(0xff9c) = textImage[5];
|
||||
REG(0xff9d) = textImage[6];
|
||||
REG(0xff9e) = textImage[7];
|
||||
REG(0xff9f) = textImage[8];
|
||||
for (i = 0; i < 16; ++i)
|
||||
REG(0xffb0 + i) = palette[i];
|
||||
back = 0;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_BANK_H
|
||||
#define VCC_BANK_H
|
||||
|
||||
#define BANK_FIRST_PAGE 0x28
|
||||
#define BANK_PAGE_SIZE 8192u
|
||||
#define BANK_CAPACITY 32768u
|
||||
|
||||
// Claim the BASIC program's dedicated physical blocks $28-$2B ($50000-$57FFF).
|
||||
// The caller reserves this RAM for assets. Opening and closing do not clear it.
|
||||
// Requires stock CoCo 3 BASIC task 0, 512 KiB or more, and a normal CMOC layout
|
||||
// below $8000. On RAM expansions retain BASIC's default $FF9B bank/prefix and
|
||||
// map; these write-only settings cannot be reconstructed after custom paging.
|
||||
// Compatible with gime_open(). Use from foreground code; open with IRQ enabled.
|
||||
// Return 1 on success, 0 for an unsupported setup or a second open.
|
||||
unsigned char bank_open(void);
|
||||
|
||||
// Transfer exactly length bytes at a byte offset measured from BANK_FIRST_PAGE.
|
||||
// A transfer may span pages. The complete range must fit BANK_CAPACITY.
|
||||
// Supply a caller-owned C buffer entirely below $8000; read requires writable
|
||||
// data, write accepts const data. A zero length needs no buffer and permits
|
||||
// offset == BANK_CAPACITY. Return 1 on success or 0 before copying any bytes.
|
||||
// Between calls both MMU tasks and the normal expansion group must stay under
|
||||
// BASIC's control. Each short copy restores the CPU mapping and interrupt mask.
|
||||
unsigned char bank_read(unsigned offset, void *destination, unsigned length);
|
||||
unsigned char bank_write(unsigned offset, const void *source, unsigned length);
|
||||
|
||||
// Release the claim. Safe to repeat. RAM contents survive until reused/reset.
|
||||
void bank_close(void);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_CASSETTE_H
|
||||
#define VCC_CASSETTE_H
|
||||
|
||||
#define VCC_TAPE_OK 0
|
||||
#define VCC_TAPE_EOF 1
|
||||
#define VCC_TAPE_IO (-1)
|
||||
#define VCC_TAPE_INVALID (-2)
|
||||
#define VCC_TAPE_LONG (-3)
|
||||
#define VCC_TAPE_BUSY (-4)
|
||||
#define VCC_TAPE_TYPE (-5)
|
||||
|
||||
// One foreground stream at a time. Position the tape and select Record or
|
||||
// Play before opening. Names are 1-8 printable ASCII characters and are
|
||||
// case-sensitive, as in BASIC. The guest cannot confirm recording at the port.
|
||||
int vcc_tape_open_write(const char *name);
|
||||
int vcc_tape_write_line(const char *line); // printable ASCII, adds one CR
|
||||
int vcc_tape_open_read(const char *name);
|
||||
int vcc_tape_read_line(char *line, unsigned capacity); // capacity includes NUL
|
||||
int vcc_tape_close(void);
|
||||
|
||||
// Read returns OK for a complete line (including a blank line), EOF only for
|
||||
// a checked end block (a final text fragment is delivered first), LONG after
|
||||
// consuming an oversized line, and IO for a damaged or incomplete recording.
|
||||
// An unsuccessful read leaves line empty.
|
||||
// Close releases a reader even after an error and finishes a writer's tape.
|
||||
#endif
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_DECIMAL_H
|
||||
#define VCC_DECIMAL_H
|
||||
|
||||
#if !defined(_COCO_BASIC_) || defined(_CMOC_MC6839_) || defined(_CMOC_NATIVE_FLOAT_)
|
||||
#error vcc_fixed requires the CoCo BASIC floating-point backend
|
||||
#endif
|
||||
|
||||
// Write value with 0 through 3 decimal places. Its magnitude must be below
|
||||
// 65536 before rounding. Round the represented value to nearest, with ties
|
||||
// away from zero. A rounded zero is unsigned. Link with vcccompat.
|
||||
// Return the full character count, excluding the terminator. If capacity is
|
||||
// positive, write a terminated prefix. NULL is valid only for zero capacity.
|
||||
// Return -1 for a bad argument or range, emptying a writable destination.
|
||||
int vcc_fixed(char *dest, unsigned capacity, float value, unsigned char places);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_GIME_H
|
||||
#define VCC_GIME_H
|
||||
|
||||
#define GIME_WIDTH 320
|
||||
#define GIME_HEIGHT 192
|
||||
|
||||
// Open from ordinary IRQ-enabled CoCo 3 BASIC text (WIDTH 32, 40 or 80).
|
||||
// Requires 512 KB or more, the standard BASIC MMU task 0 and video RAM group,
|
||||
// and a CMOC program, globals and stack below $8000. Reserve physical RAM
|
||||
// $40000..$4FFFF for both pages. Opening clears the images in that RAM.
|
||||
// Raw video/MMU register changes and interrupt-handler calls are unsupported.
|
||||
// Returns 1 on success, 0 for unsupported hardware/state or an existing session.
|
||||
unsigned char gime_open(void);
|
||||
|
||||
// Draw into the hidden page. Its contents persist when it becomes hidden again.
|
||||
// Coordinates are unsigned, rectangles are clipped at the right and bottom.
|
||||
// Empty rectangles, colors above 15 and draws outside a session do nothing.
|
||||
void gime_plot(unsigned x, unsigned y, unsigned char color);
|
||||
void gime_fill_rect(unsigned x, unsigned y, unsigned w, unsigned h, unsigned char color);
|
||||
void gime_clear(unsigned char color);
|
||||
|
||||
// Set one of the 16 shared palette entries immediately (GIME six-bit color).
|
||||
// Out-of-range slots/colors and calls outside a session do nothing.
|
||||
void gime_set_palette(unsigned char slot, unsigned char rgb);
|
||||
|
||||
// Wait for the next BASIC vertical interrupt, then display the finished page.
|
||||
// Returns 0 if closed or the field timer fails to advance. A failed presentation
|
||||
// leaves the displayed and drawing pages alone.
|
||||
unsigned char gime_present(void);
|
||||
|
||||
// Restore BASIC's text display and its original palette. Safe to repeat.
|
||||
void gime_close(void);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,32 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_INPUT_H
|
||||
#define VCC_INPUT_H
|
||||
|
||||
#define INPUT_RIGHT 0
|
||||
#define INPUT_LEFT 1
|
||||
#define INPUT_PRIMARY 1
|
||||
#define INPUT_SECONDARY 2
|
||||
|
||||
typedef struct {
|
||||
unsigned char port; // Set by input_init.
|
||||
unsigned char x, y; // 0..63, increasing to the right and down.
|
||||
signed char dx, dy; // -1 below 26, 0 from 26 through 37, +1 above 37.
|
||||
unsigned char held; // Buttons down in this sample.
|
||||
unsigned char pressed; // Buttons newly down since the preceding sample.
|
||||
unsigned char released; // Buttons newly up since the preceding sample.
|
||||
} VccInput;
|
||||
|
||||
// Sample the chosen port to establish a baseline. A button already down is
|
||||
// held, with no press or release event. Use separate state for each player.
|
||||
// An invalid port gives a neutral, inactive state. A null pointer is ignored.
|
||||
void input_init(VccInput *input, unsigned char port);
|
||||
|
||||
// Take one foreground sample per game update. Transitions between samples
|
||||
// cannot be observed. Test button fields with INPUT_PRIMARY / INPUT_SECONDARY.
|
||||
// Uses the standard CoCo analog joystick circuit in BASIC PIA configuration.
|
||||
// Restores the sound gate, mux, DAC and keyboard column output before return.
|
||||
// The short PIA transaction masks IRQ/FIRQ and uses normal data-register reads
|
||||
// (which can acknowledge PIA interrupt flags). Link input followed by bcontrol.
|
||||
void input_sample(VccInput *input);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,52 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_ORCH90_H
|
||||
#define VCC_ORCH90_H
|
||||
|
||||
// One frame, in playback order. Each DAC accepts a level from 0 through 255.
|
||||
struct orch90_frame {
|
||||
unsigned char left;
|
||||
unsigned char right;
|
||||
};
|
||||
|
||||
#define ORCH90_CLOCK_NORMAL 0
|
||||
#define ORCH90_CLOCK_FAST 1
|
||||
|
||||
// Set both DAC levels. The hardware holds them until another write.
|
||||
void orch90_write(unsigned char left, unsigned char right);
|
||||
|
||||
// Foreground playback at approximately 4,000 stereo frames/second on a CoCo 3.
|
||||
// Set clock to the CURRENT guest CPU speed. This call leaves that speed,
|
||||
// interrupt masks and timers alone. Interrupt handlers may delay playback.
|
||||
// frames must be CPU-readable and remain mapped for the entire call.
|
||||
// The last frame remains latched. A valid empty block succeeds without writes.
|
||||
// Returns 1 on success, 0 for a bad clock, missing data or an address wrap.
|
||||
// Success confirms the data was sent; this write-only hardware has no ID.
|
||||
unsigned char orch90_play(const struct orch90_frame *frames, unsigned int count,
|
||||
unsigned char clock);
|
||||
|
||||
// Start asynchronous playback on a CoCo 3 BASIC-based setup. Each stereo
|
||||
// frame lasts four serviced scanlines (about 3,930 frames/s at NTSC timing).
|
||||
// loop: 0 plays once, 1 repeats. count must be nonzero. Keep the whole frame
|
||||
// array readable, mapped and unchanged until playback ends. Keep the program,
|
||||
// its stack and its interrupt handler resident. Call from the foreground.
|
||||
//
|
||||
// clock must describe the current CPU clock. The player uses fast speed for
|
||||
// the duration and restores that setting when done. It borrows the stock BASIC
|
||||
// IRQ trampoline and PIA horizontal IRQ. IRQ and BASIC's vertical IRQ must
|
||||
// be enabled and HSYNC free. Sampling begins on the second vertical interrupt.
|
||||
// Keep these resources exclusive, including the DACs and clock, and allow IRQs
|
||||
// to run. Long interrupt masks or PIA reads can delay audio. BASIC's vertical
|
||||
// interrupt still runs. The GIME timer and FIRQ vector are untouched.
|
||||
// Returns 1 when started, 0 on refusal (including another active playback).
|
||||
unsigned char orch90_start(const struct orch90_frame *frames, unsigned int count,
|
||||
unsigned char loop, unsigned char clock);
|
||||
|
||||
// 1 while playing, 0 when idle. A one-shot releases its resources after the
|
||||
// final sample interval. The two write-only DACs then rest at midpoint 128.
|
||||
unsigned char orch90_active(void);
|
||||
|
||||
// Stop immediately and release the IRQ and clock. Safe when already idle.
|
||||
// Always stop before returning to BASIC, unloading or remapping active data.
|
||||
void orch90_stop(void);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_PRINTER_H
|
||||
#define VCC_PRINTER_H
|
||||
|
||||
#include <stdarg.h>
|
||||
|
||||
// Send formatted text to the CoCo BASIC serial printer from foreground code.
|
||||
// Use the same integer, character and string conversions as vcccompat snprintf.
|
||||
// Each C newline goes to the ROM as a carriage return. The return value counts
|
||||
// formatted characters submitted, up to 32767, or is -1 for a format/count
|
||||
// error. A prefix may already have been sent. The guest cannot tell whether
|
||||
// the host captured, saved or printed the report. Link with -lvcccompat.
|
||||
int vcc_printer_printf(const char *format, ...);
|
||||
int vcc_printer_vprintf(const char *format, va_list args);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_SDC_H
|
||||
#define VCC_SDC_H
|
||||
|
||||
#define SDC_OK 0
|
||||
#define SDC_END 1
|
||||
#define SDC_UNAVAILABLE 2
|
||||
#define SDC_TIMEOUT 3
|
||||
#define SDC_INVALID 0x84
|
||||
#define SDC_IO 0x88
|
||||
#define SDC_NOT_FOUND 0x90
|
||||
#define SDC_IN_USE 0xa0
|
||||
#define SDC_PROTECTED 0xc0
|
||||
|
||||
#define SDC_READ_ONLY 0x01
|
||||
#define SDC_DIRECTORY 0x10
|
||||
|
||||
typedef struct {
|
||||
char name[13]; // NUL-terminated 8.3 basename (or "..").
|
||||
unsigned char attributes;
|
||||
unsigned long size; // Bytes; zero for a directory.
|
||||
} SdcEntry;
|
||||
|
||||
// Foreground calls from a normal low-memory CMOC program under CoCo 3 BASIC.
|
||||
// The SDC-DOS cartridge must supply both the selected ROM and I/O. Each
|
||||
// operation restores normal controller mode and the caller's interrupt mask.
|
||||
unsigned char sdc_probe(void);
|
||||
|
||||
// Start one card-directory search. NULL or "" lists the current directory.
|
||||
// Use "/" for the card root, e.g. "/GAMES/*.DSK" for a filtered listing.
|
||||
// Paths use printable ASCII and must fit within 253 bytes. A new search
|
||||
// replaces the previous one. The card's current directory stays unchanged.
|
||||
unsigned char sdc_list_begin(const char *pattern);
|
||||
|
||||
// Return one entry, SDC_END after the last, or an error. The controller has
|
||||
// one listing cursor: finish before another program or routine starts a list.
|
||||
unsigned char sdc_list_next(SdcEntry *entry);
|
||||
|
||||
// Inspect drive 0 or 1. SDC_NOT_FOUND means no image is mounted. Entry output
|
||||
// is valid only on SDC_OK. name is the image basename, including extension.
|
||||
unsigned char sdc_mounted(unsigned char drive, SdcEntry *entry);
|
||||
|
||||
// Mount an image by its exact 8.3 guest filename (including its extension),
|
||||
// optionally within card directories. Close any files using the target drive
|
||||
// and finish any decbfile session with a cached FAT before changing media.
|
||||
// Mounting uses the controller listing cursor and ends the previous search.
|
||||
// An empty name is invalid. Never ejects or creates media as a fallback.
|
||||
// After a transport timeout, query the drive before retrying the operation.
|
||||
unsigned char sdc_mount(unsigned char drive, const char *path);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,113 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_SSC_H
|
||||
#define VCC_SSC_H
|
||||
|
||||
// CoCo guest interface to the Tandy Speech/Sound Cartridge.
|
||||
// The command latch is shared. Give one foreground producer exclusive access
|
||||
// until each phrase or effect has been submitted, including the terminator.
|
||||
#define SSC_OK 0
|
||||
#define SSC_TIMEOUT 1
|
||||
#define SSC_INVALID 2
|
||||
#define SSC_PENDING 3
|
||||
|
||||
#define SSC_READY 0x80
|
||||
#define SSC_SPEECH_IDLE 0x40
|
||||
#define SSC_EFFECT_IDLE 0x20
|
||||
#define SSC_MAX_TEXT 62
|
||||
|
||||
// Raw documented status bits. Test SSC_READY before every output byte. The two
|
||||
// IDLE signals can take time to respond after an execution command. Reading
|
||||
// this port cannot reliably detect a cartridge on every physical CoCo.
|
||||
unsigned char ssc_status(void);
|
||||
unsigned char ssc_try_write(unsigned char value); // 1 submitted, 0 busy
|
||||
|
||||
// Choose the cartridge input on the CoCo audio mux and enable the speaker.
|
||||
// Restore the saved token after playback. Joystick/cassette routines share
|
||||
// this mux: after any that change it, reselect the cartridge for listening.
|
||||
// Keep the original token for the final restore. These calls preserve PIA IRQ
|
||||
// settings. Neither call resets the cartridge or waits for sound to finish.
|
||||
unsigned int ssc_route_audio(void);
|
||||
void ssc_restore_audio(unsigned int saved);
|
||||
|
||||
// Reset the cartridge, discarding speech, effects and saved cartridge buffers.
|
||||
// Use explicitly to recover from an interrupted/partially timed-out command.
|
||||
void ssc_reset(void);
|
||||
|
||||
typedef struct {
|
||||
const char *next;
|
||||
unsigned char remaining;
|
||||
} ssc_phrase;
|
||||
|
||||
// Say 1..SSC_MAX_TEXT printable ASCII characters. Lowercase letters are sent
|
||||
// as uppercase. A space and carriage return are supplied. Keep text unchanged
|
||||
// until SSC_OK from ssc_service; ssc_begin_phrase sends nothing. Service once
|
||||
// per main-loop iteration; each call attempts at most one byte. SSC_OK means
|
||||
// submitted. Allow the firmware time to start playback before testing IDLE.
|
||||
unsigned char ssc_begin_phrase(ssc_phrase *phrase, const char *text);
|
||||
unsigned char ssc_service(ssc_phrase *phrase);
|
||||
|
||||
// Synchronous submission with a maximum number of status polls PER BYTE.
|
||||
// A zero limit returns SSC_TIMEOUT without writing. Text is reusable upon
|
||||
// return. The sound can still be playing. On timeout some bytes may already
|
||||
// have been submitted; reset before starting an unrelated command.
|
||||
unsigned char ssc_say(const char *text, unsigned int poll_limit);
|
||||
|
||||
// Play a fixed-amplitude effect using cartridge sound buffer 0, replacing its
|
||||
// contents. Channels A/B/C are 0/1/2, volume is 0..15. Tone period is 1..4095;
|
||||
// noise period is 0..31. Duration (0..255) uses the cartridge's current timer
|
||||
// base. Both effects include a final silence. The per-byte poll limit has
|
||||
// the same meaning as in ssc_say.
|
||||
unsigned char ssc_play_effect(unsigned char channel, unsigned int period,
|
||||
unsigned char volume, unsigned char duration,
|
||||
unsigned int poll_limit);
|
||||
unsigned char ssc_play_noise(unsigned char channel, unsigned char period,
|
||||
unsigned char volume, unsigned char duration,
|
||||
unsigned int poll_limit);
|
||||
|
||||
// Stored English text and allophones share eight speech slots, numbered 0..7.
|
||||
// Play a slot with the function matching the data most recently stored there.
|
||||
// Slots are volatile cartridge RAM. Store once, then play repeatedly. Loading
|
||||
// sends no execute command. SSC_OK from play means submitted, as for ssc_say.
|
||||
// Wait for playback to finish before replacing a slot that is in use.
|
||||
unsigned char ssc_store_phrase(unsigned char slot, const char *text,
|
||||
unsigned int poll_limit);
|
||||
unsigned char ssc_play_phrase(unsigned char slot, unsigned int poll_limit);
|
||||
|
||||
// SP0256-AL2 allophone addresses, in chip order. PA1..PA5 are pauses.
|
||||
// Use unsigned char arrays for pronunciations. Each element occupies one byte.
|
||||
enum {
|
||||
SSC_AL_PA1 = 0, SSC_AL_PA2, SSC_AL_PA3, SSC_AL_PA4, SSC_AL_PA5, SSC_AL_OY, SSC_AL_AY, SSC_AL_EH,
|
||||
SSC_AL_KK3, SSC_AL_PP, SSC_AL_JH, SSC_AL_NN1, SSC_AL_IH, SSC_AL_TT2, SSC_AL_RR1, SSC_AL_AX,
|
||||
SSC_AL_MM, SSC_AL_TT1, SSC_AL_DH1, SSC_AL_IY, SSC_AL_EY, SSC_AL_DD1, SSC_AL_UW1, SSC_AL_AO,
|
||||
SSC_AL_AA, SSC_AL_YY2, SSC_AL_AE, SSC_AL_HH1, SSC_AL_BB1, SSC_AL_TH, SSC_AL_UH, SSC_AL_UW2,
|
||||
SSC_AL_AW, SSC_AL_DD2, SSC_AL_GG3, SSC_AL_VV, SSC_AL_GG1, SSC_AL_SH, SSC_AL_ZH, SSC_AL_RR2,
|
||||
SSC_AL_FF, SSC_AL_KK2, SSC_AL_KK1, SSC_AL_ZZ, SSC_AL_NG, SSC_AL_LL, SSC_AL_WW, SSC_AL_XR,
|
||||
SSC_AL_WH, SSC_AL_YY1, SSC_AL_CH, SSC_AL_ER1, SSC_AL_ER2, SSC_AL_OW, SSC_AL_DH2, SSC_AL_SS,
|
||||
SSC_AL_NN2, SSC_AL_HH2, SSC_AL_OR, SSC_AL_AR, SSC_AL_YR, SSC_AL_GG2, SSC_AL_EL, SSC_AL_BB2
|
||||
};
|
||||
#define SSC_MAX_ALLOPHONES 62
|
||||
|
||||
// Provide 1..62 codes in the range 0..63. The SDK adds the final quiet pause
|
||||
// and terminator. Invalid input leaves the slot alone. After a timeout during
|
||||
// a load, use ssc_reset and reload your buffers before issuing new commands.
|
||||
unsigned char ssc_store_allophones(unsigned char slot, const unsigned char *codes,
|
||||
unsigned int count, unsigned int poll_limit);
|
||||
unsigned char ssc_play_allophones(unsigned char slot, unsigned int poll_limit);
|
||||
|
||||
// Store a single tone using the AY's hardware volume envelope, followed by
|
||||
// silence on that channel. Sound slots 0..7 are separate from the speech slots.
|
||||
// ssc_play_effect and ssc_play_noise replace sound slot 0. Channel is 0..2,
|
||||
// tone period is 1..4095, shape is 0..15, envelope period is 1..65535.
|
||||
// Envelope period controls the fade rate; duration (0..255) is in the current
|
||||
// cartridge timer units. The one envelope generator is shared by all channels.
|
||||
#define SSC_ENV_DECAY 0 // loud to silent once
|
||||
#define SSC_ENV_REPEAT_DECAY 8 // repeating downward ramp
|
||||
#define SSC_ENV_REPEAT_RISE 12 // repeating upward ramp
|
||||
#define SSC_ENV_TRIANGLE 14 // repeating rise and fall
|
||||
unsigned char ssc_store_enveloped_tone(unsigned char slot, unsigned char channel,
|
||||
unsigned int tone_period, unsigned char shape,
|
||||
unsigned int envelope_period, unsigned char duration,
|
||||
unsigned int poll_limit);
|
||||
unsigned char ssc_play_stored_effect(unsigned char slot, unsigned int poll_limit);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/input.h>
|
||||
#include <Joystick.h>
|
||||
|
||||
#define MUX_LOW (*(unsigned char *)0xFF01)
|
||||
#define KEY_COLUMNS (*(unsigned char *)0xFF02)
|
||||
#define MUX_HIGH (*(unsigned char *)0xFF03)
|
||||
#define DAC (*(unsigned char *)0xFF20)
|
||||
#define SOUND_GATE (*(unsigned char *)0xFF23)
|
||||
|
||||
// BControl selects the axis. Try each bit of the six-bit DAC once, preserving
|
||||
// the two unrelated PIA pins on every write (including serial output).
|
||||
static byte readAxis(byte axis, byte lowPins)
|
||||
{
|
||||
byte trialBit, value;
|
||||
Joystick_selectAnalogMuxInputs(axis);
|
||||
asm {
|
||||
clr :value
|
||||
lda #32
|
||||
sta :trialBit
|
||||
@trial lda :value
|
||||
ora :trialBit
|
||||
tfr a,b
|
||||
lslb
|
||||
lslb
|
||||
orb :lowPins
|
||||
stb >$ff20
|
||||
tst >$ff00
|
||||
bpl @next // Comparator low: this trial is too high.
|
||||
sta :value
|
||||
@next lsr :trialBit
|
||||
bne @trial
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static signed char direction(byte axis)
|
||||
{
|
||||
if (axis < 26) return -1;
|
||||
if (axis > 37) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void input_sample(VccInput *input)
|
||||
{
|
||||
byte flags, low, high, gate, dac, columns;
|
||||
byte axis, x, y, rows, down, previous;
|
||||
|
||||
if (!input || input->port > INPUT_LEFT)
|
||||
return;
|
||||
|
||||
axis = input->port << 1;
|
||||
// Keep an interrupt from selecting a different axis halfway through a
|
||||
// conversion. BASIC can resume scanning immediately after restoration.
|
||||
asm {
|
||||
tfr cc,a
|
||||
orcc #$50
|
||||
sta :flags
|
||||
}
|
||||
low = MUX_LOW;
|
||||
high = MUX_HIGH;
|
||||
gate = SOUND_GATE;
|
||||
columns = KEY_COLUMNS;
|
||||
dac = DAC;
|
||||
Joystick_disableSound();
|
||||
x = readAxis(axis, dac & 3);
|
||||
y = readAxis(axis + 1, dac & 3);
|
||||
|
||||
// BControl deselects every keyboard column before reading button rows.
|
||||
// Right primary/secondary are rows 0/2, left are rows 1/3, active low.
|
||||
rows = Joystick_getButtonStates2();
|
||||
KEY_COLUMNS = columns;
|
||||
DAC = dac;
|
||||
MUX_LOW = low;
|
||||
MUX_HIGH = high;
|
||||
SOUND_GATE = gate;
|
||||
asm {
|
||||
lda :flags
|
||||
tfr a,cc
|
||||
}
|
||||
|
||||
down = (byte)~rows >> input->port;
|
||||
down = (down & 1) | ((down >> 1) & 2);
|
||||
previous = input->held;
|
||||
input->x = x;
|
||||
input->y = y;
|
||||
input->dx = direction(x);
|
||||
input->dy = direction(y);
|
||||
input->held = down;
|
||||
input->pressed = down & ~previous;
|
||||
input->released = previous & ~down;
|
||||
}
|
||||
|
||||
void input_init(VccInput *input, byte port)
|
||||
{
|
||||
if (!input)
|
||||
return;
|
||||
input->port = port;
|
||||
input->x = input->y = 31;
|
||||
input->dx = input->dy = 0;
|
||||
input->held = 0;
|
||||
input_sample(input);
|
||||
input->pressed = input->released = 0;
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/orch90.h>
|
||||
|
||||
static const struct orch90_frame *firstFrame, *nextFrame, *endFrame;
|
||||
static unsigned char playing, looping, previousClock, scanlines, fieldsToStart;
|
||||
|
||||
// Called with IRQ masked by the foreground or by hardware interrupt entry.
|
||||
// Restore just the enable bit we borrowed. Preserve the current mux selection.
|
||||
static asm void releasePlayback(void)
|
||||
{
|
||||
asm {
|
||||
lda >$ff01
|
||||
bita #1
|
||||
beq @vector // An early stop can cancel before HSYNC is armed.
|
||||
anda #$3e
|
||||
sta >$ff01
|
||||
@vector lda #$16 // Original LBRA $010C at the CoCo 3 IRQ vector.
|
||||
sta >$fef7
|
||||
ldd #$0212
|
||||
std >$fef8
|
||||
ldd #$8080 // The write-only DACs rest at their midpoint.
|
||||
std >$ff7a
|
||||
clr :playing
|
||||
tst :previousClock
|
||||
bne @done
|
||||
clr >$ffd8 // Return a previously normal-speed CoCo to 0.89 MHz.
|
||||
@done
|
||||
}
|
||||
}
|
||||
|
||||
// A full IRQ stacks D and X on both supported CPUs. Keep this handler in
|
||||
// resident code, with PC-relative data independent of the foreground's DP.
|
||||
static asm __norts__ void scanlineIRQ(void)
|
||||
{
|
||||
asm {
|
||||
lda >$ff01
|
||||
bpl @chain // A different source interrupted the foreground.
|
||||
lda >$ff00 // Acknowledge the horizontal edge.
|
||||
dec :scanlines
|
||||
bne @vertical
|
||||
lda #4
|
||||
sta :scanlines
|
||||
ldx :nextFrame
|
||||
cmpx :endFrame
|
||||
bne @sample
|
||||
tst :looping
|
||||
beq @end
|
||||
ldx :firstFrame
|
||||
@sample ldd ,x++ // Left and right are consecutive DAC addresses.
|
||||
std >$ff7a
|
||||
stx :nextFrame
|
||||
@vertical
|
||||
lda >$ff03 // BASIC's timer and keyboard still get VSYNC.
|
||||
bpl @return
|
||||
bita #1
|
||||
beq @return
|
||||
@chain jmp >$010c
|
||||
@end lbsr releasePlayback
|
||||
bra @vertical
|
||||
@return rti
|
||||
}
|
||||
}
|
||||
|
||||
// Let a requested speed change settle before the first DAC sample. Some
|
||||
// hosts apply it at their next frame boundary. Only count genuine BASIC
|
||||
// vertical interrupts, even if another IRQ arrives while we are waiting.
|
||||
static asm __norts__ void armAtVerticalIRQ(void)
|
||||
{
|
||||
asm {
|
||||
lda >$ff03
|
||||
bpl @chain
|
||||
dec :fieldsToStart
|
||||
bne @chain
|
||||
leax scanlineIRQ
|
||||
stx >$fef8
|
||||
lda >$ff00 // Drop any horizontal edge before sampling.
|
||||
lda >$ff01
|
||||
anda #$3f
|
||||
ora #1
|
||||
sta >$ff01
|
||||
@chain jmp >$010c
|
||||
}
|
||||
}
|
||||
|
||||
unsigned char orch90_start(const struct orch90_frame *frames, unsigned int count,
|
||||
unsigned char loop, unsigned char clock)
|
||||
{
|
||||
unsigned char installed;
|
||||
if (!frames || !count || count > (0u - (unsigned int)frames) / sizeof(*frames)
|
||||
|| loop > 1 || clock > ORCH90_CLOCK_FAST)
|
||||
return 0;
|
||||
asm {
|
||||
pshs cc
|
||||
tfr cc,a
|
||||
orcc #$50
|
||||
bita #$10
|
||||
bne @reject
|
||||
tst :playing
|
||||
bne @reject
|
||||
ldd >$fff8 // Stock CoCo 3 IRQ trampoline: LBRA $010C.
|
||||
cmpd #$fef7
|
||||
bne @reject
|
||||
lda >$fef7
|
||||
cmpa #$16
|
||||
bne @reject
|
||||
ldd >$fef8
|
||||
cmpd #$0212
|
||||
bne @reject
|
||||
lda >$ff01 // HSYNC must be free, with PIA data accessible.
|
||||
anda #5
|
||||
cmpa #4
|
||||
bne @reject
|
||||
lda >$ff03 // Arm from the ordinary enabled vertical IRQ.
|
||||
anda #5
|
||||
cmpa #5
|
||||
bne @reject
|
||||
ldx :frames
|
||||
stx :firstFrame
|
||||
stx :nextFrame
|
||||
ldd :count
|
||||
lslb
|
||||
rola
|
||||
leax d,x
|
||||
stx :endFrame
|
||||
lda :loop
|
||||
sta :looping
|
||||
lda :clock
|
||||
sta :previousClock
|
||||
bne @fast
|
||||
clr >$ffd9 // Allow processing time between horizontal IRQs.
|
||||
@fast lda #4
|
||||
sta :scanlines
|
||||
lda #$7e
|
||||
sta >$fef7
|
||||
leax armAtVerticalIRQ
|
||||
stx >$fef8
|
||||
lda #2
|
||||
sta :fieldsToStart
|
||||
lda #1
|
||||
sta :playing
|
||||
bra @done
|
||||
@reject clra
|
||||
@done sta :installed
|
||||
puls cc
|
||||
}
|
||||
return installed;
|
||||
}
|
||||
|
||||
asm unsigned char orch90_active(void)
|
||||
{
|
||||
asm {
|
||||
ldb :playing
|
||||
}
|
||||
}
|
||||
|
||||
asm void orch90_stop(void)
|
||||
{
|
||||
asm {
|
||||
pshs cc
|
||||
orcc #$50
|
||||
tst :playing
|
||||
beq @done
|
||||
lbsr releasePlayback
|
||||
@done puls cc
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/orch90.h>
|
||||
|
||||
unsigned char orch90_play(const struct orch90_frame *frames, unsigned int count,
|
||||
unsigned char clock)
|
||||
{
|
||||
unsigned int savedY;
|
||||
unsigned char delay;
|
||||
|
||||
if (clock != ORCH90_CLOCK_NORMAL && clock != ORCH90_CLOCK_FAST)
|
||||
return 0;
|
||||
if (count == 0)
|
||||
return 1;
|
||||
// For a non-null 16-bit address, unsigned negation counts the remaining
|
||||
// bytes up to and including $FFFF. Each sample frame requires two.
|
||||
if (!frames || count > (0u - (unsigned int)frames) / sizeof(*frames))
|
||||
return 0;
|
||||
|
||||
delay = clock == ORCH90_CLOCK_NORMAL ? 39 : 84;
|
||||
asm {
|
||||
ldx :frames
|
||||
sty :savedY
|
||||
ldy :count
|
||||
@frame
|
||||
ldd ,x++ // One interleaved left/right pair.
|
||||
std >$ff7a
|
||||
ldb :delay
|
||||
@wait
|
||||
decb
|
||||
bne @wait
|
||||
leay -1,y
|
||||
bne @frame
|
||||
ldy :savedY
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/orch90.h>
|
||||
|
||||
void orch90_write(unsigned char left, unsigned char right)
|
||||
{
|
||||
asm {
|
||||
lda :left
|
||||
ldb :right
|
||||
std >$ff7a // D is big-endian: left at $FF7A, right at $FF7B.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/sdc.h>
|
||||
#include <cmoc.h>
|
||||
|
||||
typedef unsigned char byte;
|
||||
|
||||
static byte packet[256];
|
||||
static byte directory[256];
|
||||
static byte listing, recordNumber;
|
||||
|
||||
// Stock CoCo 3 BASIC shadows its ROM in RAM. Briefly expose the *live*
|
||||
// cartridge ROM, checking its SDC-DOS identifier as well as the MPI routes.
|
||||
// Merely writing a test value to $FF42 could send it to a Becker port; $FF43
|
||||
// is writable RAM-disk data on another cartridge. Neither is a safe probe.
|
||||
static asm byte selectedSDC(void)
|
||||
{
|
||||
asm {
|
||||
program_end import
|
||||
ldx #program_end
|
||||
cmpx #$8000
|
||||
bhi @no
|
||||
cmps #$8000
|
||||
bhi @no
|
||||
ldd >$c000
|
||||
cmpd #$444b ; Disk BASIC "DK"
|
||||
bne @no
|
||||
ldd >$e000
|
||||
cmpd #$00e6 ; Super Extended BASIC ROM header
|
||||
bne @no
|
||||
ldb >$ff7f
|
||||
tfr b,a
|
||||
lsra
|
||||
lsra
|
||||
lsra
|
||||
lsra
|
||||
pshs b
|
||||
eora ,s+
|
||||
bita #3 ; I/O and cartridge ROM routed to same slot
|
||||
bne @no
|
||||
sta >$ffde ; overlay external ROM at $c000-$fdff
|
||||
ldd >$e000
|
||||
cmpd #$5344 ; "SDC-DOS "
|
||||
bne @restoreNo
|
||||
ldd >$e002
|
||||
cmpd #$432d
|
||||
bne @restoreNo
|
||||
ldd >$e004
|
||||
cmpd #$444f
|
||||
bne @restoreNo
|
||||
ldd >$e006
|
||||
cmpd #$5320
|
||||
bne @restoreNo
|
||||
sta >$ffdf ; restore all-RAM mapping
|
||||
ldb #1
|
||||
rts
|
||||
@restoreNo
|
||||
sta >$ffdf
|
||||
@no clrb
|
||||
}
|
||||
}
|
||||
|
||||
// BUSY may precede READY for a block. A device reporting an error or going
|
||||
// idle without the expected data must never leave the foreground wedged.
|
||||
static asm byte waitForBlock(void)
|
||||
{
|
||||
asm {
|
||||
ldx #$4000
|
||||
@again ldb >$ff48
|
||||
bmi @done
|
||||
bitb #2
|
||||
bne @ok
|
||||
bitb #1
|
||||
beq @missing
|
||||
leax -1,x
|
||||
bne @again
|
||||
ldb #3 ; SDC_TIMEOUT
|
||||
rts
|
||||
@missing ldb #$88 ; SDC_IO
|
||||
rts
|
||||
@ok clrb
|
||||
@done
|
||||
}
|
||||
}
|
||||
|
||||
static asm byte waitForIdle(void)
|
||||
{
|
||||
asm {
|
||||
ldx #$4000
|
||||
@again ldb >$ff48
|
||||
bmi @done
|
||||
bitb #1
|
||||
beq @ok
|
||||
leax -1,x
|
||||
bne @again
|
||||
ldb #3 ; SDC_TIMEOUT
|
||||
rts
|
||||
@ok clrb
|
||||
@done
|
||||
}
|
||||
}
|
||||
|
||||
static asm void readBlock(byte *data)
|
||||
{
|
||||
asm {
|
||||
ldx 2,s
|
||||
lda #128
|
||||
pshs a
|
||||
@pair ldd >$ff4a
|
||||
std ,x++
|
||||
dec ,s
|
||||
bne @pair
|
||||
leas 1,s
|
||||
}
|
||||
}
|
||||
|
||||
static asm void writeBlock(const byte *data)
|
||||
{
|
||||
asm {
|
||||
ldx 2,s
|
||||
lda #128
|
||||
pshs a
|
||||
@pair ldd ,x++
|
||||
std >$ff4a
|
||||
dec ,s
|
||||
bne @pair
|
||||
leas 1,s
|
||||
}
|
||||
}
|
||||
|
||||
// Enter with the latch owned. Atkinson's CoCo SDC User Guide, chapter 7,
|
||||
// requires an idle controller before issue and a settling interval afterward.
|
||||
static byte issue(byte code, byte parameter, byte *block)
|
||||
{
|
||||
byte status = waitForIdle();
|
||||
if (status != SDC_OK)
|
||||
return status;
|
||||
asm {
|
||||
lda :parameter
|
||||
sta >$ff49
|
||||
lda :code
|
||||
sta >$ff48
|
||||
ldb #10 ; at least 20 us on a stock fast CoCo 3
|
||||
@settle decb
|
||||
bne @settle
|
||||
}
|
||||
if (block) {
|
||||
status = waitForBlock();
|
||||
if (status != SDC_OK)
|
||||
return status;
|
||||
if ((code & 0xf0) == 0xe0)
|
||||
writeBlock(block);
|
||||
else
|
||||
readBlock(block);
|
||||
}
|
||||
status = waitForIdle();
|
||||
if (status == SDC_OK && !block) {
|
||||
// The V command returns a nonzero revision in the data pair.
|
||||
asm {
|
||||
ldd >$ff4a
|
||||
bne @revision
|
||||
ldb #2
|
||||
stb :status
|
||||
@revision
|
||||
}
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
// An entire command owns the controller since interrupts can use the floppy
|
||||
// latch. Save CC before probing and release the latch on every exit path.
|
||||
// Only command $E0 (L: or M:) writes a packet. No raw-sector writes occur.
|
||||
static byte command(byte code, byte parameter, byte *block)
|
||||
{
|
||||
byte savedCC, status;
|
||||
asm {
|
||||
tfr cc,b
|
||||
orcc #$50
|
||||
stb :savedCC
|
||||
}
|
||||
status = SDC_UNAVAILABLE;
|
||||
if (selectedSDC()) {
|
||||
asm {
|
||||
lda #$43
|
||||
sta >$ff40
|
||||
}
|
||||
status = issue(code, parameter, block);
|
||||
asm { clr >$ff40 }
|
||||
}
|
||||
asm {
|
||||
ldb :savedCC
|
||||
tfr b,cc
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
byte sdc_probe(void)
|
||||
{
|
||||
return command(0xc0, 'V', NULL);
|
||||
}
|
||||
|
||||
static byte preparePacket(byte operation, const char *path)
|
||||
{
|
||||
unsigned i;
|
||||
if (!path || !*path)
|
||||
return SDC_INVALID;
|
||||
for (i = 0; path[i]; ++i) {
|
||||
byte c = path[i];
|
||||
if (i == 253 || c < ' ' || c > '~' || c == '\\' || c == ':')
|
||||
return SDC_INVALID;
|
||||
}
|
||||
memset(packet, 0, sizeof(packet));
|
||||
packet[0] = operation;
|
||||
packet[1] = ':';
|
||||
memcpy(packet + 2, path, i);
|
||||
return SDC_OK;
|
||||
}
|
||||
|
||||
static byte startListing(void)
|
||||
{
|
||||
byte status = command(0xe0, 0, packet);
|
||||
listing = 0;
|
||||
if (status == SDC_OK) {
|
||||
recordNumber = 16; // Fetch the first page on demand.
|
||||
listing = 1;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
byte sdc_list_begin(const char *pattern)
|
||||
{
|
||||
byte status = preparePacket('L', pattern && *pattern ? pattern : "*");
|
||||
if (status != SDC_OK) {
|
||||
listing = 0;
|
||||
return status;
|
||||
}
|
||||
return startListing();
|
||||
}
|
||||
|
||||
static void decodeName(SdcEntry *entry, const byte *record)
|
||||
{
|
||||
byte i, n = 0;
|
||||
for (i = 0; i < 8 && record[i] != ' '; ++i)
|
||||
entry->name[n++] = record[i];
|
||||
if (record[8] != ' ') {
|
||||
entry->name[n++] = '.';
|
||||
for (i = 8; i < 11 && record[i] != ' '; ++i)
|
||||
entry->name[n++] = record[i];
|
||||
}
|
||||
entry->name[n] = 0;
|
||||
entry->attributes = record[11];
|
||||
}
|
||||
|
||||
byte sdc_list_next(SdcEntry *entry)
|
||||
{
|
||||
const byte *record;
|
||||
byte status;
|
||||
if (!entry)
|
||||
return SDC_INVALID;
|
||||
if (!listing)
|
||||
return SDC_END;
|
||||
if (recordNumber == 16) {
|
||||
status = command(0xc0, '>', directory);
|
||||
if (status != SDC_OK) {
|
||||
listing = 0;
|
||||
return status;
|
||||
}
|
||||
recordNumber = 0;
|
||||
}
|
||||
record = directory + ((unsigned)recordNumber << 4);
|
||||
if (!record[0]) {
|
||||
listing = 0;
|
||||
return SDC_END;
|
||||
}
|
||||
++recordNumber;
|
||||
decodeName(entry, record);
|
||||
memcpy(&entry->size, record + 12, 4); // Listing size is big-endian like the CPU.
|
||||
return SDC_OK;
|
||||
}
|
||||
|
||||
byte sdc_mounted(byte drive, SdcEntry *entry)
|
||||
{
|
||||
byte status, i;
|
||||
if (drive > 1 || !entry)
|
||||
return SDC_INVALID;
|
||||
status = command(0xc0 | drive, 'I', packet);
|
||||
if (status != SDC_OK)
|
||||
return status;
|
||||
decodeName(entry, packet);
|
||||
// Mounted-image information uses the FAT directory's little-endian size.
|
||||
for (i = 0; i < 4; ++i)
|
||||
((byte *)&entry->size)[i] = packet[31 - i];
|
||||
return SDC_OK;
|
||||
}
|
||||
|
||||
// M: also accepts wildcards, implicit extensions, directories and disk sets.
|
||||
// Require an explicit 8.3 image filename so a typo cannot select a different
|
||||
// first match. Only directories may be preceded by "." or ".." components.
|
||||
static byte exactFilename(const char *path)
|
||||
{
|
||||
const char *base = path;
|
||||
const char *p;
|
||||
byte len = 0, ext = 0;
|
||||
for (p = path; *p; ++p) {
|
||||
if (*p == '*' || *p == '?')
|
||||
return 0;
|
||||
if (*p == '/')
|
||||
base = p + 1;
|
||||
}
|
||||
for (p = base; *p; ++p) {
|
||||
if (*p == '.') {
|
||||
if (!len || ext) return 0;
|
||||
ext = 1;
|
||||
len = 0;
|
||||
} else {
|
||||
if (*p <= ' ' || strchr("\"+,;<=>[]|", *p) || ++len > (ext ? 3 : 8))
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return ext && len;
|
||||
}
|
||||
|
||||
byte sdc_mount(byte drive, const char *path)
|
||||
{
|
||||
byte status;
|
||||
byte *control;
|
||||
SdcEntry entry;
|
||||
if (drive > 1)
|
||||
return SDC_INVALID;
|
||||
status = preparePacket('L', path);
|
||||
if (status != SDC_OK || !exactFilename(path))
|
||||
return SDC_INVALID;
|
||||
control = (byte *)0x0800 + (unsigned)drive * 74;
|
||||
if (control[0] || control[1]) // Disk BASIC has open files or a pending FAT.
|
||||
return SDC_IN_USE;
|
||||
// The native M: command interprets even a folder named "X.DSK" as a
|
||||
// numbered disk set. Look up the exact card entry before authorizing M:.
|
||||
status = startListing();
|
||||
if (status != SDC_OK)
|
||||
return status;
|
||||
status = sdc_list_next(&entry);
|
||||
listing = 0;
|
||||
if (status == SDC_END)
|
||||
return SDC_NOT_FOUND;
|
||||
if (status != SDC_OK)
|
||||
return status;
|
||||
if (entry.attributes & SDC_DIRECTORY)
|
||||
return SDC_INVALID;
|
||||
// The search used the same path; only the operation byte differs.
|
||||
packet[0] = 'M';
|
||||
return command(0xe0 | drive, 0, packet);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/ssc.h>
|
||||
#include "internal.h"
|
||||
|
||||
// Load one timed event into sound buffer 0, a silent event on the same
|
||||
// channel, then the terminator and Execute Buffer 0 command. The firmware
|
||||
// would otherwise continue playing the last event beyond its duration.
|
||||
static unsigned char play_event(unsigned char operation, unsigned int period,
|
||||
unsigned char volume, unsigned char duration,
|
||||
unsigned int poll_limit)
|
||||
{
|
||||
unsigned char packet[11];
|
||||
unsigned char i = 0;
|
||||
packet[i++] = 0x98;
|
||||
packet[i++] = operation | volume;
|
||||
if (!(operation & 0x80))
|
||||
packet[i++] = (unsigned char)(period >> 8);
|
||||
packet[i++] = (unsigned char)period;
|
||||
packet[i++] = duration;
|
||||
packet[i++] = operation;
|
||||
if (!(operation & 0x80))
|
||||
packet[i++] = (unsigned char)(period >> 8);
|
||||
packet[i++] = (unsigned char)period;
|
||||
packet[i++] = 0;
|
||||
packet[i++] = 0xFF;
|
||||
packet[i++] = 0xD8;
|
||||
return ssc_write_bytes(packet, i, poll_limit);
|
||||
}
|
||||
|
||||
unsigned char ssc_play_effect(unsigned char channel, unsigned int period,
|
||||
unsigned char volume, unsigned char duration,
|
||||
unsigned int poll_limit)
|
||||
{
|
||||
if (channel > 2 || !period || period > 4095 || volume > 15)
|
||||
return SSC_INVALID;
|
||||
return play_event(channel << 5, period, volume, duration, poll_limit);
|
||||
}
|
||||
|
||||
unsigned char ssc_play_noise(unsigned char channel, unsigned char period,
|
||||
unsigned char volume, unsigned char duration,
|
||||
unsigned int poll_limit)
|
||||
{
|
||||
if (channel > 2 || period > 31 || volume > 15)
|
||||
return SSC_INVALID;
|
||||
return play_event(0x80 | (channel << 5), period, volume, duration, poll_limit);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef VCC_SSC_INTERNAL_H
|
||||
#define VCC_SSC_INTERNAL_H
|
||||
|
||||
// Prevalidated packet or portion of a packet. Each byte gets its own budget.
|
||||
unsigned char ssc_write_bytes(const unsigned char *bytes, unsigned int count,
|
||||
unsigned int poll_limit);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,80 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/ssc.h>
|
||||
#include "internal.h"
|
||||
|
||||
unsigned char ssc_begin_phrase(ssc_phrase *phrase, const char *text)
|
||||
{
|
||||
unsigned char length = 0;
|
||||
if (!phrase || !text)
|
||||
return SSC_INVALID;
|
||||
while (text[length]) {
|
||||
unsigned char c = text[length];
|
||||
if (length >= SSC_MAX_TEXT || c < 32 || c > 126)
|
||||
return SSC_INVALID;
|
||||
++length;
|
||||
}
|
||||
if (!length)
|
||||
return SSC_INVALID;
|
||||
phrase->next = text;
|
||||
phrase->remaining = length + 2;
|
||||
return SSC_OK;
|
||||
}
|
||||
|
||||
unsigned char ssc_service(ssc_phrase *phrase)
|
||||
{
|
||||
unsigned char value;
|
||||
if (!phrase || phrase->remaining > SSC_MAX_TEXT + 2)
|
||||
return SSC_INVALID;
|
||||
if (!phrase->remaining)
|
||||
return SSC_OK;
|
||||
if (phrase->remaining > 2) {
|
||||
value = *phrase->next;
|
||||
if (value >= 'a' && value <= 'z')
|
||||
value -= 'a' - 'A';
|
||||
} else {
|
||||
value = phrase->remaining == 2 ? ' ' : 13;
|
||||
}
|
||||
if (ssc_try_write(value)) {
|
||||
if (phrase->remaining > 2)
|
||||
++phrase->next;
|
||||
--phrase->remaining;
|
||||
}
|
||||
return phrase->remaining ? SSC_PENDING : SSC_OK;
|
||||
}
|
||||
|
||||
static unsigned char submit_phrase(ssc_phrase *phrase, unsigned int poll_limit)
|
||||
{
|
||||
unsigned int budget = poll_limit;
|
||||
while (budget) {
|
||||
unsigned char before = phrase->remaining;
|
||||
if (ssc_service(phrase) == SSC_OK)
|
||||
return SSC_OK;
|
||||
if (before == phrase->remaining)
|
||||
--budget;
|
||||
else
|
||||
budget = poll_limit;
|
||||
}
|
||||
return SSC_TIMEOUT;
|
||||
}
|
||||
|
||||
unsigned char ssc_say(const char *text, unsigned int poll_limit)
|
||||
{
|
||||
ssc_phrase phrase;
|
||||
unsigned char result = ssc_begin_phrase(&phrase, text);
|
||||
if (result != SSC_OK)
|
||||
return result;
|
||||
return submit_phrase(&phrase, poll_limit);
|
||||
}
|
||||
|
||||
unsigned char ssc_store_phrase(unsigned char slot, const char *text,
|
||||
unsigned int poll_limit)
|
||||
{
|
||||
ssc_phrase phrase;
|
||||
unsigned char command;
|
||||
if (slot > 7 || ssc_begin_phrase(&phrase, text) != SSC_OK)
|
||||
return SSC_INVALID;
|
||||
command = 0x90 + slot;
|
||||
if (ssc_write_bytes(&command, 1, poll_limit) != SSC_OK)
|
||||
return SSC_TIMEOUT;
|
||||
return submit_phrase(&phrase, poll_limit);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/ssc.h>
|
||||
#include "internal.h"
|
||||
|
||||
// CMOC accepts volatile but does not implement its C semantics. Use one
|
||||
// explicit bus read per poll; a second read must never reuse the first value.
|
||||
asm unsigned char ssc_status(void)
|
||||
{
|
||||
asm {
|
||||
ldb $FF7E
|
||||
andb #$E0
|
||||
}
|
||||
}
|
||||
|
||||
asm unsigned char ssc_try_write(unsigned char value)
|
||||
{
|
||||
asm {
|
||||
tst $FF7E
|
||||
bpl @busy
|
||||
ldb 3,s ; low byte of first CMOC argument
|
||||
stb $FF7E
|
||||
ldb #1
|
||||
bra @done
|
||||
@busy clrb
|
||||
@done
|
||||
}
|
||||
}
|
||||
|
||||
asm void ssc_reset(void)
|
||||
{
|
||||
asm {
|
||||
ldb #1
|
||||
stb $FF7D
|
||||
clrb
|
||||
stb $FF7D
|
||||
}
|
||||
}
|
||||
|
||||
unsigned char ssc_write_bytes(const unsigned char *bytes, unsigned int count,
|
||||
unsigned int poll_limit)
|
||||
{
|
||||
while (count) {
|
||||
unsigned int remaining = poll_limit;
|
||||
while (remaining && !ssc_try_write(*bytes))
|
||||
--remaining;
|
||||
if (!remaining)
|
||||
return SSC_TIMEOUT;
|
||||
++bytes;
|
||||
--count;
|
||||
}
|
||||
return SSC_OK;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/ssc.h>
|
||||
|
||||
// C2 mode and level occupy bits 5..3. Bits 2..0 select the PIA data
|
||||
// register, interrupt edge and interrupt enable. Bits 7..6 are IRQ flags.
|
||||
#define PIA_MUX_LOW (*(unsigned char *)0xFF01)
|
||||
#define PIA_MUX_HIGH (*(unsigned char *)0xFF03)
|
||||
#define PIA_SOUND (*(unsigned char *)0xFF23)
|
||||
#define C2_LOW 0x30
|
||||
#define C2_HIGH 0x38
|
||||
|
||||
unsigned int ssc_route_audio(void)
|
||||
{
|
||||
unsigned char flags, low, high, sound;
|
||||
unsigned int saved;
|
||||
// Keep an interrupt handler from changing a control register between our
|
||||
// read and write. The exact incoming interrupt masks are restored.
|
||||
asm {
|
||||
tfr cc,a
|
||||
orcc #$50
|
||||
sta :flags
|
||||
}
|
||||
low = PIA_MUX_LOW;
|
||||
high = PIA_MUX_HIGH;
|
||||
sound = PIA_SOUND;
|
||||
saved = ((unsigned int)(low & 0x38) << 3) | (high & 0x38) | ((sound & 0x38) >> 3);
|
||||
PIA_MUX_LOW = (low & 7) | C2_LOW;
|
||||
PIA_MUX_HIGH = (high & 7) | C2_HIGH;
|
||||
PIA_SOUND = (sound & 7) | C2_HIGH;
|
||||
asm {
|
||||
lda :flags
|
||||
tfr a,cc
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
void ssc_restore_audio(unsigned int saved)
|
||||
{
|
||||
unsigned char flags;
|
||||
asm {
|
||||
tfr cc,a
|
||||
orcc #$50
|
||||
sta :flags
|
||||
}
|
||||
PIA_MUX_LOW = (PIA_MUX_LOW & 7) | (unsigned char)((saved >> 3) & 0x38);
|
||||
PIA_MUX_HIGH = (PIA_MUX_HIGH & 7) | (unsigned char)(saved & 0x38);
|
||||
PIA_SOUND = (PIA_SOUND & 7) | (unsigned char)((saved << 3) & 0x38);
|
||||
asm {
|
||||
lda :flags
|
||||
tfr a,cc
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <vcc/ssc.h>
|
||||
#include "internal.h"
|
||||
|
||||
static unsigned char play_slot(unsigned char command, unsigned char slot,
|
||||
unsigned int poll_limit)
|
||||
{
|
||||
if (slot > 7)
|
||||
return SSC_INVALID;
|
||||
command += slot;
|
||||
return ssc_write_bytes(&command, 1, poll_limit);
|
||||
}
|
||||
|
||||
unsigned char ssc_play_phrase(unsigned char slot, unsigned int poll_limit)
|
||||
{
|
||||
return play_slot(0xD0, slot, poll_limit);
|
||||
}
|
||||
|
||||
unsigned char ssc_store_allophones(unsigned char slot, const unsigned char *codes,
|
||||
unsigned int count, unsigned int poll_limit)
|
||||
{
|
||||
static const unsigned char end[] = {SSC_AL_PA1, 0xFF};
|
||||
unsigned char command;
|
||||
unsigned int i;
|
||||
if (slot > 7 || !codes || !count || count > SSC_MAX_ALLOPHONES)
|
||||
return SSC_INVALID;
|
||||
for (i = 0; i < count; ++i)
|
||||
if (codes[i] > SSC_AL_BB2)
|
||||
return SSC_INVALID;
|
||||
|
||||
command = 0xB0 + slot;
|
||||
if (ssc_write_bytes(&command, 1, poll_limit) != SSC_OK ||
|
||||
ssc_write_bytes(codes, count, poll_limit) != SSC_OK)
|
||||
return SSC_TIMEOUT;
|
||||
return ssc_write_bytes(end, sizeof(end), poll_limit);
|
||||
}
|
||||
|
||||
unsigned char ssc_play_allophones(unsigned char slot, unsigned int poll_limit)
|
||||
{
|
||||
return play_slot(0xF0, slot, poll_limit);
|
||||
}
|
||||
|
||||
unsigned char ssc_store_enveloped_tone(unsigned char slot, unsigned char channel,
|
||||
unsigned int tone_period, unsigned char shape,
|
||||
unsigned int envelope_period, unsigned char duration,
|
||||
unsigned int poll_limit)
|
||||
{
|
||||
unsigned char packet[18];
|
||||
if (slot > 7 || channel > 2 || !tone_period || tone_period > 4095 ||
|
||||
shape > 15 || !envelope_period)
|
||||
return SSC_INVALID;
|
||||
|
||||
packet[0] = 0x98 + slot;
|
||||
// The PIC writes the shape before the period. On a cold cartridge a
|
||||
// one-shot can finish at the old period before the PIC enables the tone.
|
||||
// Prime the generator and retrigger with the tone gate already open.
|
||||
packet[1] = 0x60 | shape;
|
||||
packet[2] = (unsigned char)(envelope_period >> 8);
|
||||
packet[3] = (unsigned char)envelope_period;
|
||||
packet[4] = 0;
|
||||
packet[5] = (channel << 5) | 0x10;
|
||||
packet[6] = (unsigned char)(tone_period >> 8);
|
||||
packet[7] = (unsigned char)tone_period;
|
||||
packet[8] = duration; // The tone's timer schedules the silence.
|
||||
packet[9] = packet[1];
|
||||
packet[10] = packet[2];
|
||||
packet[11] = packet[3];
|
||||
packet[12] = 0;
|
||||
packet[13] = channel << 5; // Final event selects fixed amplitude zero.
|
||||
packet[14] = packet[6];
|
||||
packet[15] = packet[7];
|
||||
packet[16] = 0;
|
||||
packet[17] = 0xFF;
|
||||
return ssc_write_bytes(packet, sizeof(packet), poll_limit);
|
||||
}
|
||||
|
||||
unsigned char ssc_play_stored_effect(unsigned char slot, unsigned int poll_limit)
|
||||
{
|
||||
return play_slot(0xD8, slot, poll_limit);
|
||||
}
|
||||
Reference in new issue
Block a user