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 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 |
#include <stdio.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"
// 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
#define FILE_OP_COPY 0x05
#define FILE_OP_MOVE 0x06
// 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
#define FILE_ERROR_PATH_TOO_LONG 0x35
#define FILE_ERROR_BUFFER_OUT_OF_RANGE 0x36
// 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 int 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';
return (xyw_memory[addr + i] != 0) ? -1 : 0;
}
// Returns 1 if [addr, addr+length) fits entirely within xyw_memory, 0 otherwise.
static int file_buffer_in_range(xyw_word addr, xyw_word length)
{
return ((unsigned int)addr + (unsigned int)length) <= XYW_MEMORY_SIZE;
}
// 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_byte *error)
{
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;
}
if (get_path_string(path_addr, path, FILE_MAX_PATH) != 0)
{
*error = FILE_ERROR_PATH_TOO_LONG;
data[FILE_TYPE] = XYW_FILE_TYPE_UNKNOWN;
XYW_POKEW(&data[FILE_SIZE], 0);
return;
}
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;
}
if (!file_buffer_in_range(buffer_addr, length))
{
XYW_DBG(" Buffer out of range for file_read: addr=%04X length=%04X\n", buffer_addr, length);
*error = FILE_ERROR_BUFFER_OUT_OF_RANGE;
return;
}
if (get_path_string(path_addr, path, FILE_MAX_PATH) != 0)
{
*error = FILE_ERROR_PATH_TOO_LONG;
return;
}
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, only if not already there
if (ftell(file_handle) != file_cursor && 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;
}
if (!file_buffer_in_range(buffer_addr, length))
{
XYW_DBG(" Buffer out of range for file_write: addr=%04X length=%04X\n", buffer_addr, length);
*error = FILE_ERROR_BUFFER_OUT_OF_RANGE;
return;
}
if (get_path_string(path_addr, path, FILE_MAX_PATH) != 0)
{
*error = FILE_ERROR_PATH_TOO_LONG;
return;
}
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), skip if already positioned
if (!append && ftell(file_handle) != file_cursor && 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);
// 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 file size
data[FILE_TYPE] = FILE_TYPE_FILE;
XYW_POKEW(&data[FILE_SIZE], (xyw_word)(file_cursor > 0xFFFF ? 0xFFFF : file_cursor));
}
// 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];
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;
}
if (get_path_string(path_addr, path, FILE_MAX_PATH) != 0)
{
*error = FILE_ERROR_PATH_TOO_LONG;
return;
}
// 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, error);
}
// Parse "source|destination" from path string
static int split_path_pair(xyw_byte *data, char *src, char *dst, size_t bufsize)
{
xyw_word path_addr = XYW_PEEKW(&data[FILE_PATH]);
char combined[FILE_MAX_PATH * 2];
if (path_addr == 0)
return -1;
if (get_path_string(path_addr, combined, sizeof(combined)) != 0)
{
return -1;
}
char *sep = strchr(combined, '|');
if (!sep)
return -1;
*sep = '\0';
strncpy(src, combined, bufsize - 1);
src[bufsize - 1] = '\0';
strncpy(dst, sep + 1, bufsize - 1);
dst[bufsize - 1] = '\0';
return 0;
}
// Copy a file
static void file_copy(xyw_byte *data, xyw_byte *error)
{
char src[FILE_MAX_PATH], dst[FILE_MAX_PATH];
XYW_POKEW(&data[FILE_SUCCESS], 0);
if (split_path_pair(data, src, dst, FILE_MAX_PATH) != 0)
{
*error = FILE_ERROR_INVALID_OP;
return;
}
// Close if source or dest is currently open
if (file_handle && (strcmp(file_current_path, src) == 0 || strcmp(file_current_path, dst) == 0))
file_close();
XYW_DBG(" Copying: %s -> %s\n", src, dst);
FILE *in = fopen(src, "rb");
if (!in)
{
*error = FILE_ERROR_NOT_FOUND;
return;
}
FILE *out = fopen(dst, "wb");
if (!out)
{
fclose(in);
*error = FILE_ERROR_ACCESS_DENIED;
return;
}
char buf[4096];
size_t total = 0;
size_t n;
while ((n = fread(buf, 1, sizeof(buf), in)) > 0)
{
if (fwrite(buf, 1, n, out) != n)
{
fclose(in);
fclose(out);
*error = FILE_ERROR_IO_ERROR;
return;
}
total += n;
}
fclose(in);
fclose(out);
XYW_POKEW(&data[FILE_SUCCESS], (xyw_word)(total > 0xFFFF ? 0xFFFF : total));
}
// Move (rename) a file
static void file_move(xyw_byte *data, xyw_byte *error)
{
char src[FILE_MAX_PATH], dst[FILE_MAX_PATH];
XYW_POKEW(&data[FILE_SUCCESS], 0);
if (split_path_pair(data, src, dst, FILE_MAX_PATH) != 0)
{
*error = FILE_ERROR_INVALID_OP;
return;
}
// Close if source or dest is currently open
if (file_handle && (strcmp(file_current_path, src) == 0 || strcmp(file_current_path, dst) == 0))
file_close();
XYW_DBG(" Moving: %s -> %s\n", src, dst);
if (rename(src, dst) != 0)
{
// rename may fail across filesystems; fall back to copy+delete
file_copy(data, error);
if (*error != 0)
return;
if (remove(src) != 0)
{
*error = FILE_ERROR_IO_ERROR;
return;
}
}
XYW_POKEW(&data[FILE_SUCCESS], 1);
}
void file_setup(xyw_byte *data, xyw_byte *error)
{
(void)error;
// 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 (check only last byte, so that this doesn't get fired twice,
once for each byte), close current file, update stats, reset cursor */
if (addr == FILE_PATH + 1)
{
file_close();
update_file_stats(data, error);
}
// 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;
case FILE_OP_COPY:
file_copy(data, error);
break;
case FILE_OP_MOVE:
file_move(data, error);
break;
default:
if (op != 0)
{
*error = FILE_ERROR_INVALID_OP;
}
break;
}
// Clear operation after execution
data[FILE_OPERATION] = 0;
}
}
|