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,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;
|
||||
}
|
||||
Reference in new issue
Block a user