all repos — xyw @ 13b16677dbafd92d9695aa0708ac30383cad92a8

A minimal virtual machine and assembler for terminals.

devices/file.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>

#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#define PATH_SEP '\\'
#else
#include <dirent.h>
#include <unistd.h>
#define PATH_SEP '/'
#endif

#include "../xyw.h"

extern xyw_byte xyw_memory[];

/* file device */
#define FILE_PATH 0x0
#define FILE_TYPE 0x2
#define FILE_SIZE 0x3
#define FILE_SUCCESS 0x5
#define FILE_LENGTH 0x7
#define FILE_READ 0x9
#define FILE_WRITE 0xB
#define FILE_OPERATION 0xD

/* File operations */
#define FILE_OP_READ 0x01
#define FILE_OP_WRITE 0x02
#define FILE_OP_APPEND 0x03
#define FILE_OP_DELETE 0x04

/* File types */
#define XYW_FILE_TYPE_UNKNOWN 0x00
#define FILE_TYPE_FILE 0x01
#define FILE_TYPE_DIRECTORY 0x02

/* Error codes (high nibble = 3 for file device) */
#define FILE_ERROR_NOT_FOUND 0x31
#define FILE_ERROR_ACCESS_DENIED 0x32
#define FILE_ERROR_INVALID_OP 0x33
#define FILE_ERROR_IO_ERROR 0x34

/* Maximum path length */
#define FILE_MAX_PATH 256

/* Internal state for streaming */
static FILE *file_handle = NULL;
static char file_current_path[FILE_MAX_PATH] = {0};
static long file_cursor = 0;
static int file_is_write_mode = 0;

/* Get null-terminated string from memory at given address */
static void get_path_string(xyw_word addr, char *buf, size_t bufsize)
{
    size_t i;
    for (i = 0; i < bufsize - 1 && xyw_memory[addr + i] != 0; i++)
    {
        buf[i] = xyw_memory[addr + i];
    }
    buf[i] = '\0';
}

/* Close any open file */
static void file_close(void)
{
    if (file_handle)
    {
        fclose(file_handle);
        file_handle = NULL;
    }
    file_current_path[0] = '\0';
    file_cursor = 0;
    file_is_write_mode = 0;
}

/* Update file type and size based on path */
static void update_file_stats(xyw_byte *data)
{
    xyw_word path_addr = XYW_PEEKW(&data[FILE_PATH]);
    char path[FILE_MAX_PATH];
    struct stat st;

    if (path_addr == 0)
    {
        data[FILE_TYPE] = XYW_FILE_TYPE_UNKNOWN;
        XYW_POKEW(&data[FILE_SIZE], 0);
        return;
    }

    get_path_string(path_addr, path, FILE_MAX_PATH);

    if (stat(path, &st) != 0)
    {
        data[FILE_TYPE] = XYW_FILE_TYPE_UNKNOWN;
        XYW_POKEW(&data[FILE_SIZE], 0);
        return;
    }

    if (S_ISDIR(st.st_mode))
    {
        data[FILE_TYPE] = FILE_TYPE_DIRECTORY;
        XYW_POKEW(&data[FILE_SIZE], 0);
    }
    else if (S_ISREG(st.st_mode))
    {
        data[FILE_TYPE] = FILE_TYPE_FILE;
        /* Cap size at 64KB (0xFFFF) */
        xyw_word size = (st.st_size > 0xFFFF) ? 0xFFFF : (xyw_word)st.st_size;
        XYW_POKEW(&data[FILE_SIZE], size);
    }
    else
    {
        data[FILE_TYPE] = XYW_FILE_TYPE_UNKNOWN;
        XYW_POKEW(&data[FILE_SIZE], 0);
    }
}

/* Read file contents into memory buffer with cursor support */
static void file_read(xyw_byte *data, xyw_byte *error)
{
    xyw_word path_addr = XYW_PEEKW(&data[FILE_PATH]);
    xyw_word buffer_addr = XYW_PEEKW(&data[FILE_READ]);
    xyw_word length = XYW_PEEKW(&data[FILE_LENGTH]);
    char path[FILE_MAX_PATH];

    /* Clear success */
    XYW_POKEW(&data[FILE_SUCCESS], 0);

    if (path_addr == 0 || buffer_addr == 0 || length == 0)
    {
        XYW_DBG("   Invalid parameters for file_read\n");
        *error = FILE_ERROR_INVALID_OP;
        return;
    }

    get_path_string(path_addr, path, FILE_MAX_PATH);

    XYW_DBG("   Reading file: %s, length=%u, cursor=%ld\n", path, length, file_cursor);

    /* Check if it's a directory - list contents (no cursor support for dirs) */
    if (data[FILE_TYPE] == FILE_TYPE_DIRECTORY)
    {
        xyw_word offset = 0;

#ifdef _WIN32
        WIN32_FIND_DATAA findData;
        HANDLE hFind;
        char searchPath[FILE_MAX_PATH + 3];

        snprintf(searchPath, sizeof(searchPath), "%s\\*", path);
        hFind = FindFirstFileA(searchPath, &findData);

        if (hFind == INVALID_HANDLE_VALUE)
        {
            XYW_DBG("   Failed to open directory: %s\n", path);
            *error = FILE_ERROR_ACCESS_DENIED;
            return;
        }

        /* Output . and .. first */
        char line[FILE_MAX_PATH + 16];
        int len = snprintf(line, sizeof(line), "%02X %04X .\n", FILE_TYPE_DIRECTORY, 0);
        if (len <= (int)length)
        {
            memcpy(&xyw_memory[buffer_addr + offset], line, len);
            offset += len;
        }
        len = snprintf(line, sizeof(line), "%02X %04X ..\n", FILE_TYPE_DIRECTORY, 0);
        if (offset + len <= length)
        {
            memcpy(&xyw_memory[buffer_addr + offset], line, len);
            offset += len;
        }

        do
        {
            if (strcmp(findData.cFileName, ".") == 0 ||
                strcmp(findData.cFileName, "..") == 0)
            {
                continue;
            }

            xyw_byte type = (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                                ? FILE_TYPE_DIRECTORY
                                : FILE_TYPE_FILE;
            xyw_word size = 0;
            if (type == FILE_TYPE_FILE)
            {
                size = (findData.nFileSizeLow > 0xFFFF) ? 0xFFFF : (xyw_word)findData.nFileSizeLow;
            }

            len = snprintf(line, sizeof(line), "%02X %04X %s\n", type, size, findData.cFileName);

            if (offset + len > length)
                break;

            memcpy(&xyw_memory[buffer_addr + offset], line, len);
            offset += len;
        } while (FindNextFileA(hFind, &findData) != 0);

        FindClose(hFind);
#else
        DIR *dir = opendir(path);
        struct dirent *entry;
        struct stat st;
        char full_path[FILE_MAX_PATH * 2];

        if (!dir)
        {
            XYW_DBG("   Failed to open directory: %s\n", path);
            *error = FILE_ERROR_ACCESS_DENIED;
            return;
        }

        /* Output . and .. first */
        char line[FILE_MAX_PATH + 16];
        int len = snprintf(line, sizeof(line), "%02X %04X .\n", FILE_TYPE_DIRECTORY, 0);
        if (len <= (int)length)
        {
            memcpy(&xyw_memory[buffer_addr + offset], line, len);
            offset += len;
        }
        len = snprintf(line, sizeof(line), "%02X %04X ..\n", FILE_TYPE_DIRECTORY, 0);
        if (offset + len <= length)
        {
            memcpy(&xyw_memory[buffer_addr + offset], line, len);
            offset += len;
        }

        while ((entry = readdir(dir)) != NULL)
        {
            if (strcmp(entry->d_name, ".") == 0 ||
                strcmp(entry->d_name, "..") == 0)
            {
                continue;
            }

            snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

            xyw_byte type = XYW_FILE_TYPE_UNKNOWN;
            xyw_word size = 0;

            if (stat(full_path, &st) == 0)
            {
                if (S_ISDIR(st.st_mode))
                {
                    type = FILE_TYPE_DIRECTORY;
                }
                else if (S_ISREG(st.st_mode))
                {
                    type = FILE_TYPE_FILE;
                    size = (st.st_size > 0xFFFF) ? 0xFFFF : (xyw_word)st.st_size;
                }
            }

            len = snprintf(line, sizeof(line), "%02X %04X %s\n", type, size, entry->d_name);

            if (offset + len > length)
                break;

            memcpy(&xyw_memory[buffer_addr + offset], line, len);
            offset += len;
        }

        closedir(dir);
#endif

        /* Null-terminate if space */
        if (offset < length)
        {
            xyw_memory[buffer_addr + offset] = 0;
        }

        XYW_POKEW(&data[FILE_SUCCESS], offset);
        return;
    }

    /* Regular file read with cursor */

    /* Open file if not already open or if path changed */
    if (!file_handle || strcmp(file_current_path, path) != 0 || file_is_write_mode)
    {
        file_close();
        file_handle = fopen(path, "rb");
        if (!file_handle)
        {
            XYW_DBG("   Failed to open file: %s\n", path);
            *error = FILE_ERROR_NOT_FOUND;
            return;
        }
        strncpy(file_current_path, path, FILE_MAX_PATH - 1);
        file_current_path[FILE_MAX_PATH - 1] = '\0';
        file_cursor = 0;
        file_is_write_mode = 0;
    }

    /* Seek to cursor position */
    if (fseek(file_handle, file_cursor, SEEK_SET) != 0)
    {
        XYW_DBG("   Failed to seek in file: %s\n", path);
        *error = FILE_ERROR_IO_ERROR;
        return;
    }

    /* Read data */
    size_t bytes_read = fread(&xyw_memory[buffer_addr], 1, length, file_handle);

    /* Advance cursor */
    file_cursor += bytes_read;

    /* Null-terminate if space and we read less than length */
    if (bytes_read < length)
    {
        xyw_memory[buffer_addr + bytes_read] = 0;
    }

    XYW_DBG("   Read %zu bytes, cursor now at %ld\n", bytes_read, file_cursor);
    XYW_POKEW(&data[FILE_SUCCESS], (xyw_word)bytes_read);
}

/* Write memory buffer to file with cursor support */
static void file_write_op(xyw_byte *data, xyw_byte *error, int append)
{
    xyw_word path_addr = XYW_PEEKW(&data[FILE_PATH]);
    xyw_word buffer_addr = XYW_PEEKW(&data[FILE_WRITE]);
    xyw_word length = XYW_PEEKW(&data[FILE_LENGTH]);
    char path[FILE_MAX_PATH];

    /* Clear success */
    XYW_POKEW(&data[FILE_SUCCESS], 0);

    if (path_addr == 0 || buffer_addr == 0 || length == 0)
    {
        XYW_DBG("   Invalid parameters for file_write\n");
        *error = FILE_ERROR_INVALID_OP;
        return;
    }

    get_path_string(path_addr, path, FILE_MAX_PATH);

    XYW_DBG("   Writing to file: %s (append=%d), length=%u, cursor=%ld\n", path, append, length, file_cursor);

    /* Open file if not already open, path changed, or mode changed */
    int need_reopen = !file_handle ||
                      strcmp(file_current_path, path) != 0 ||
                      !file_is_write_mode;

    if (need_reopen)
    {
        file_close();

        /* For append, open in append mode; otherwise open for read/write or create */
        if (append)
        {
            file_handle = fopen(path, "ab");
        }
        else
        {
            /* Try to open existing file for r+b, if fails create with wb */
            file_handle = fopen(path, "r+b");
            if (!file_handle)
            {
                file_handle = fopen(path, "wb");
            }
        }

        if (!file_handle)
        {
            XYW_DBG("   Failed to open file for writing: %s (errno=%d: %s)\n", path, errno, strerror(errno));
            *error = FILE_ERROR_ACCESS_DENIED;
            return;
        }

        strncpy(file_current_path, path, FILE_MAX_PATH - 1);
        file_current_path[FILE_MAX_PATH - 1] = '\0';
        file_is_write_mode = 1;

        if (append)
        {
            /* Seek to end for append */
            fseek(file_handle, 0, SEEK_END);
            file_cursor = ftell(file_handle);
        }
        else
        {
            file_cursor = 0;
        }
    }

    /* Seek to cursor position (for non-append continuing writes) */
    if (!append && fseek(file_handle, file_cursor, SEEK_SET) != 0)
    {
        XYW_DBG("   Failed to seek in file: %s\n", path);
        *error = FILE_ERROR_IO_ERROR;
        return;
    }

    /* Find actual content length (stop at null terminator if present) */
    xyw_word actual_length = 0;
    while (actual_length < length && xyw_memory[buffer_addr + actual_length] != 0)
    {
        actual_length++;
    }

    if (actual_length == 0)
    {
        XYW_DBG("   Empty content for file_write\n");
        return;
    }

    /* Write data */
    size_t written = fwrite(&xyw_memory[buffer_addr], 1, actual_length, file_handle);
    fflush(file_handle);

    /* Advance cursor */
    file_cursor += written;

    XYW_DBG("   Wrote %zu bytes (of %u max), cursor now at %ld\n", written, length, file_cursor);
    XYW_POKEW(&data[FILE_SUCCESS], (xyw_word)written);

    /* Update stats after write */
    update_file_stats(data);
}

/* Delete a file */
static void file_delete(xyw_byte *data, xyw_byte *error)
{
    xyw_word path_addr = XYW_PEEKW(&data[FILE_PATH]);
    char path[FILE_MAX_PATH];

    /* Clear success */
    XYW_POKEW(&data[FILE_SUCCESS], 0);

    if (path_addr == 0)
    {
        XYW_DBG("   Invalid path address for file_delete\n");
        *error = FILE_ERROR_INVALID_OP;
        return;
    }

    get_path_string(path_addr, path, FILE_MAX_PATH);

    /* Close file if it's the one being deleted */
    if (file_handle && strcmp(file_current_path, path) == 0)
    {
        file_close();
    }

    XYW_DBG("   Deleting file: %s\n", path);

    if (remove(path) != 0)
    {
        XYW_DBG("   Failed to delete file: %s\n", path);
        *error = FILE_ERROR_ACCESS_DENIED;
        return;
    }

    /* Success = 1 for successful delete */
    XYW_POKEW(&data[FILE_SUCCESS], 1);

    /* Update stats after delete */
    update_file_stats(data);
}

void file_init(xyw_byte *data)
{
    /* Close any open file */
    file_close();

    /* Clear all device memory */
    memset(data, 0, 16);
}

xyw_byte file_input(xyw_byte *data, xyw_byte addr, xyw_byte *error)
{
    (void)error;
    return data[addr];
}

void file_output(xyw_byte *data, xyw_byte addr, xyw_byte *error)
{
    /* When path is written, close current file, update stats, reset cursor */
    if (addr == FILE_PATH || addr == FILE_PATH + 1)
    {
        file_close();
        update_file_stats(data);
    }

    /* When operation is written, execute it */
    if (addr == FILE_OPERATION)
    {
        xyw_byte op = data[FILE_OPERATION];

        switch (op)
        {
        case FILE_OP_READ:
            file_read(data, error);
            break;
        case FILE_OP_WRITE:
            file_write_op(data, error, 0);
            break;
        case FILE_OP_APPEND:
            file_write_op(data, error, 1);
            break;
        case FILE_OP_DELETE:
            file_delete(data, error);
            break;
        default:
            if (op != 0)
            {
                *error = FILE_ERROR_INVALID_OP;
            }
            break;
        }

        /* Clear operation after execution */
        data[FILE_OPERATION] = 0;
    }
}