all repos — xyw @ a37b6851e9265dadbec0aba7a41f25360cf7f488

A minimal virtual machine and assembler for terminals.

xywrun.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
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "xyw.h"

#include "devices/system.h"
#include "devices/terminal.h"
#include "devices/clock.h"
#include "devices/file.h"
#include "devices/beeper.h"

#define MEMORY_SIZE 0x10000

#define USER_STACK_SIZE 128
#define SYSTEM_FRAME_SIZE 8
#define SYSTEM_MAX_FRAMES 48

#define USER_MEMORY_START 0x000
#define DEVICE_AREA_START 0xff00

#define MAX_IMAGE_EXEC_DEPTH 8
#define MAX_IMAGE_EXEC_PATH_LENGTH 256

#define POLL_INTERVAL_MS 100

/* system device addresses */
#define SYSTEM_STATE 0xff00
#define SYSTEM_ERROR 0xff01
#define SYSTEM_PAGE 0xff02
#define SYSTEM_RANDOM 0xff03
#define SYSTEM_ON_ERROR 0xff04

/* Terminal device addresses */
#define TERMINAL_INPUT 0xff10
#define TERMINAL_ON_KEYPRESS 0xff12
#define TERMINAL_ON_ARGUMENT 0xff14

/* Clock device addresses */
#define CLOCK_TIMER 0xff28
#define CLOCK_ON_TIMER_ELAPSED 0xff2a

#ifdef _WIN32
#include <conio.h>
#include <windows.h>
int getch_timeout(int timeout_ms)
{
    HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
    if (WaitForSingleObject(h, timeout_ms) == WAIT_OBJECT_0 && _kbhit())
        return _getch();
    return 0;
}
#else
#include <unistd.h>
int getch_timeout(int timeout_ms)
{
    (void)timeout_ms; // bounded by VMIN=0/VTIME in terminal_init()
    int c = getchar();
    return (c == EOF) ? 0 : c;
}
#endif
typedef enum
{
    XYW_ERROR_NONE = 0,
    XYW_ERROR_DIVISION_BY_ZERO,
    XYW_ERROR_STACK_UNDERFLOW,
    XYW_ERROR_STACK_OVERFLOW,
    XYW_ERROR_EXEC_DEPTH_EXCEEDED,
    XYW_ERROR_IMAGE_NOT_FOUND,
    XYW_ERROR_IMAGE_READ_ERROR,
} xyw_error;

#define SYSTEM_STATE_RUNNING 0x01
#define SYSTEM_STATE_WAITING 0x02
#define SYSTEM_STATE_DEBUG 0x40
#define SYSTEM_STATE_ERROR 0x80

/// Main memory
xyw_byte xyw_memory[MEMORY_SIZE];

/// Stacks (not part of addressable memory)
static xyw_byte user_stack[USER_STACK_SIZE];
static xyw_byte system_stack[SYSTEM_MAX_FRAMES * SYSTEM_FRAME_SIZE];
static xyw_byte s = 0; // system stack frame index
static xyw_byte u = 0; // user stack pointer

#define DIRECT_PAGE (xyw_memory[SYSTEM_PAGE] << 8)

//// registers
static xyw_byte x_val = 0; // X register storage
static xyw_byte y_val = 0; // Y register storage
xyw_byte *x = &x_val;
xyw_byte *y = &y_val;
xyw_byte *dev_error = &xyw_memory[SYSTEM_ERROR];

//// 2-byte registers
static xyw_word pc_storage = 0; // Program counter storage
static xyw_word xw_storage = 0; // 16-bit X register storage
static xyw_word yw_storage = 0; // 16-bit Y register storage
xyw_word *pc = &pc_storage;
xyw_word *xw = &xw_storage;
xyw_word *yw = &yw_storage;

//// Helpers to retrieve device number and address within the device
static inline int get_device(xyw_word addr)
{
    if (addr < DEVICE_AREA_START)
        return -1;
    return (addr - DEVICE_AREA_START) / 16;
}

static inline xyw_byte *get_device_data(xyw_word addr)
{
    return xyw_devices[get_device(addr)].data;
}

static inline xyw_byte get_device_address(xyw_word addr)
{
    // Given $FF41, it should return $01
    return (xyw_byte)((addr - DEVICE_AREA_START) & 0x0F);
}

//// Read/write memory helpers

static inline xyw_byte readb(xyw_word addr)
{
    int dev_num = get_device(addr);
    if (dev_num >= 0 && xyw_devices[dev_num].input)
    {
        xyw_byte dev_addr = get_device_address(addr);
        return xyw_devices[dev_num].input(get_device_data(addr), dev_addr, dev_error);
    }
    return xyw_memory[addr];
}

static inline void writeb(xyw_word addr, xyw_byte val)
{
    xyw_memory[addr] = val;
    int dev_num = get_device(addr);
    if (dev_num >= 0 && xyw_devices[dev_num].output)
    {
        xyw_byte dev_addr = get_device_address(addr);
        xyw_devices[dev_num].output(get_device_data(addr), dev_addr, dev_error);
    }
}

static inline xyw_word readw(xyw_word addr)
{
    // Read high and low bytes independently to handle device boundaries
    xyw_byte high = readb(addr);
    xyw_byte low = readb(addr + 1);
    return (xyw_word)((high << 8) | low);
}

static inline void writew(xyw_word addr, xyw_word val)
{
    // Write high and low bytes independently to handle device boundaries
    // and trigger output handlers for both bytes
    writeb(addr, (xyw_byte)(val >> 8));
    writeb(addr + 1, (xyw_byte)(val & 0xFF));
}

//// Device dispatchers

//// System stack management (frame-based)
// Each frame is SYSTEM_FRAME_SIZE (8) bytes:
//   offset 0-1: return address (xyw_word, big-endian)
//   offset 2:   x register (xyw_byte)
//   offset 3:   y register (xyw_byte)
//   offset 4-5: xw register (xyw_word, big-endian)
//   offset 6-7: yw register (xyw_word, big-endian)
// *s is a frame index (0..SYSTEM_MAX_FRAMES-1), not a byte offset.

static void ss_push_frame(xyw_word return_addr)
{
    if (s >= SYSTEM_MAX_FRAMES)
    {
        xyw_memory[SYSTEM_ERROR] = XYW_ERROR_STACK_OVERFLOW;
        return;
    }
    xyw_byte *base = &system_stack[s * SYSTEM_FRAME_SIZE];
    base[0] = (xyw_byte)(return_addr >> 8);
    base[1] = (xyw_byte)(return_addr & 0xFF);
    base[2] = *x;
    base[3] = *y;
    base[4] = (xyw_byte)(*xw >> 8);
    base[5] = (xyw_byte)(*xw & 0xFF);
    base[6] = (xyw_byte)(*yw >> 8);
    base[7] = (xyw_byte)(*yw & 0xFF);
    s++;
}

static xyw_word ss_pop_frame()
{
    if (s < 1)
    {
        xyw_memory[SYSTEM_ERROR] = XYW_ERROR_STACK_UNDERFLOW;
        return -1;
    }
    s--;
    xyw_byte *base = &system_stack[s * SYSTEM_FRAME_SIZE];
    xyw_word return_addr = (xyw_word)((base[0] << 8) | base[1]);
    *x = base[2];
    *y = base[3];
    *xw = (xyw_word)((base[4] << 8) | base[5]);
    *yw = (xyw_word)((base[6] << 8) | base[7]);
    // Clear the frame
    for (int i = 0; i < SYSTEM_FRAME_SIZE; i++) base[i] = 0;
    return return_addr;
}

//// User stack management

static void us_push(xyw_byte val)
{
    if (u > USER_STACK_SIZE - 1)
    {
        xyw_memory[SYSTEM_ERROR] = XYW_ERROR_STACK_OVERFLOW;
        return;
    }
    XYW_DBG(" => %02X\n", val);
    user_stack[u++] = val;
}

static void us_pushw(xyw_word val)
{
    if (u > USER_STACK_SIZE - 2)
    {
        xyw_memory[SYSTEM_ERROR] = XYW_ERROR_STACK_OVERFLOW;
        return;
    }
    user_stack[u]     = (xyw_byte)(val >> 8);
    user_stack[u + 1] = (xyw_byte)(val & 0xFF);
    XYW_DBG(" => %04X\n", val);
    u += 2;
}

static xyw_byte us_pop()
{
    if (u < 1)
    {
        xyw_memory[SYSTEM_ERROR] = XYW_ERROR_STACK_UNDERFLOW;
        return -1;
    }
    u -= 1;
    xyw_byte val = user_stack[u];
    user_stack[u] = 0;
    return val;
}

static xyw_word us_popw()
{
    if (u < 2)
    {
        xyw_memory[SYSTEM_ERROR] = XYW_ERROR_STACK_UNDERFLOW;
        return -1;
    }
    xyw_word val = (xyw_word)((user_stack[u - 2] << 8) | user_stack[u - 1]);
    user_stack[u - 2] = 0;
    user_stack[u - 1] = 0;
    u -= 2;
    return val;
}

// clang-format off

//// Operations that support stack and all registers
#define OPC_SR2(opc, body) { \
    case opc: { const int w=0, rx=0, ry=0; xyw_byte b = us_pop(); xyw_byte a = us_pop(); body; (void)(rx); (void)(ry); (void)(w);} break; \
    case XYW_MODE_X|opc: { const int w=0, rx=1, ry=0; xyw_byte b = *x; xyw_byte a = us_pop(); body; (void)(rx); (void)(ry); (void)(w); } break; \
    case XYW_MODE_Y|opc: { const int w=0, rx=0, ry=1; xyw_byte b = *y; xyw_byte a = us_pop(); body; (void)(rx); (void)(ry); (void)(w); } break; \
    case XYW_MODE_X|XYW_MODE_Y|opc: { const int w=0, rx=1, ry=1; xyw_byte a = *x; xyw_byte b = *y; body; (void)(rx); (void)(ry); (void)(w); } break; \
    case XYW_MODE_W|opc: { const int w=1, rx=0, ry=0; xyw_word b = us_popw(); xyw_word a = us_popw(); body; (void)(rx); (void)(ry); (void)(w); } break; \
    case XYW_MODE_X|XYW_MODE_W|opc: { const int w=1, rx=1, ry=0; xyw_word b = *xw; xyw_word a = us_popw(); body; (void)(rx); (void)(ry); (void)(w); } break; \
    case XYW_MODE_Y|XYW_MODE_W|opc: { const int w=1, rx=0, ry=1; xyw_word b = *yw; xyw_word a = us_popw(); body; (void)(rx); (void)(ry); (void)(w); } break; \
    case XYW_MODE_X|XYW_MODE_Y|XYW_MODE_W|opc: { const int w=1, rx=1, ry=1; xyw_word a = *xw; xyw_word b = *yw; body; (void)(rx); (void)(ry); (void)(w); } break; \
}

//// Operations that support stack and one register
#define OPC_SR1(opc, init, body) { \
    case opc: { const int w=0, rx=0, ry=0; init; body; } break; \
    case XYW_MODE_X|opc: { const int w=0, rx=1, ry=0; init; body; } break; \
    case XYW_MODE_Y|opc: { const int w=0, rx=0, ry=1; init; body; } break; \
    case XYW_MODE_W|opc: { const int w=1, rx=0, ry=0; init; body; } break; \
    case XYW_MODE_X|XYW_MODE_W|opc: { const int w=1, rx=1, ry=0; init; body; } break; \
    case XYW_MODE_Y|XYW_MODE_W|opc: { const int w=1, rx=0, ry=1; init; body; } break; \
}

//// Operations that support both registers always set
#define OPC_SR1r(opc, body) { \
    case XYW_MODE_X|XYW_MODE_Y|opc: { const int w=0, rx=1, ry=1; xyw_byte a = *x; xyw_byte b = *y; body;(void)(w);(void)(a);(void)(b);(void)(rx);(void)(ry); } break; \
    case XYW_MODE_X|XYW_MODE_Y|XYW_MODE_W|opc: { const int w=1, rx=1, ry=1; xyw_word a = *xw; xyw_word b = *yw; body;(void)(w);(void)(a);(void)(b);(void)(rx);(void)(ry); } break; \
}

// OVR: Duplicates the second stack item: a b -- a b a
#define OPC_OVR(opc) { \
    case opc: { \
        xyw_byte b = us_pop(); xyw_byte a = us_pop(); \
        us_push(a); us_push(b); us_push(a); \
    } break; \
    case XYW_MODE_W|opc: { \
        xyw_word b = us_popw(); xyw_word a = us_popw(); \
        us_pushw(a); us_pushw(b); us_pushw(a); \
    } break; \
}

// ROT: Rotates the third stack item to the top: a b c -- b c a
#define OPC_ROT(opc) { \
    case opc: { \
        xyw_byte c = us_pop(); xyw_byte b = us_pop(); xyw_byte a = us_pop(); \
        us_push(b); us_push(c); us_push(a); \
    } break; \
    case XYW_MODE_W|opc: { \
        xyw_word c = us_popw(); xyw_word b = us_popw(); xyw_word a = us_popw(); \
        us_pushw(b); us_pushw(c); us_pushw(a); \
    } break; \
}

// Create address based on direct page or full address
#define ADDR(ad) (w ? (ad) : (DIRECT_PAGE | (ad)))
// Push a value to stack
#define PUSH(n) do { if (w) { us_pushw((xyw_word)(n)); } else { us_push((xyw_byte)(n)); } } while(0)
// Pop value from stack
#define POP() (w ? us_popw() : us_pop())
// Get argument from x register or stack
#define ARGX (rx ? (w ? *xw : *x) : (w ? us_popw() : us_pop()))
// Get argument from y register or stack
#define ARGY (ry ? (w ? *yw : *y) : (w ? us_popw() : us_pop()))
// Get argument from x or y register or stack
#define ARG (rx ? ARGX : (ry ? ARGY : POP()))
// Set value to x register or push to stack
#define SETX(v) rx ? (w ? (*xw = (xyw_word)(v)) : (*x = (xyw_byte)(v))) : (w ? us_pushw((xyw_word)(v)) : us_push((xyw_byte)(v)))
// Set value to y register or push to stack
#define SETY(v) ry ? (w ? (*yw = (xyw_word)(v)) : (*y = (xyw_byte)(v))) : (w ? us_pushw((xyw_word)(v)) : us_push((xyw_byte)(v)))
// Set value to x or y register or push to stack
#define SET(v) do { if (rx) { SETX(v); } else if (ry) { SETY(v); } else { PUSH(v); } } while(0)

// Read a value from memory
#define READ(addr) (w ? readw(addr) : readb(addr))
// Read top of the user stack (direct array access, no device dispatch)
#define TOP (w ? (xyw_word)((user_stack[u - 2] << 8) | user_stack[u - 1]) : (xyw_word)user_stack[u - 1])

//// Initialize devices

xyw_device xyw_devices[XYW_TOTAL_DEVICES] = {
    // System device
    {&xyw_memory[0xff00], system_setup, system_input, system_output, 0},
    // Terminal device
    {&xyw_memory[0xff10], terminal_init, terminal_input, terminal_output, terminal_teardown},
    // Clock device
    {&xyw_memory[0xff20], clock_setup, clock_input, clock_output, 0},
    // File device
    {&xyw_memory[0xff30], file_setup, file_input, file_output, 0},
    // Beeper device
    {&xyw_memory[0xff40], 0, beeper_input, beeper_output, beeper_teardown},
    // ...
};
// clang-format on

static int system_error_state()
{
    return xyw_memory[SYSTEM_STATE] & SYSTEM_STATE_ERROR;
}

static int system_running_state()
{
    return xyw_memory[SYSTEM_STATE] & SYSTEM_STATE_RUNNING;
}

static int system_waiting_state()
{
    return xyw_memory[SYSTEM_STATE] & SYSTEM_STATE_WAITING;
}

//// Internal VM state
xyw_byte error_handler_entry_s = 0;

// Argument feeding state (CLI args)
static int arg_index = 1;
static int arg_char_pos = 0;

// Sub-image argument feeding state
#define MAX_SUBIMAGE_ARGS 256
static char subimage_args_buf[MAX_SUBIMAGE_ARGS];
static int subimage_args_active = 0;
static int subimage_args_pos = 0;

static int process_events()
{
    // Error handling
    if (xyw_memory[SYSTEM_ERROR] != XYW_ERROR_NONE && !system_error_state())
    {
        xyw_word on_error_handler = XYW_PEEKW(&xyw_memory[SYSTEM_ON_ERROR]);
        // If an error handler is set, jump to it
        if (on_error_handler != 0)
        {
            XYW_DBG("Error occurred: %02X, jumping to error handler at %04X\n", xyw_memory[SYSTEM_ERROR], on_error_handler);
            // Enter error state
            xyw_memory[SYSTEM_STATE] |= SYSTEM_STATE_ERROR;
            error_handler_entry_s = s; // Record stack depth before pushing return address
            ss_push_frame(*pc);
            *pc = on_error_handler;
        }
        else
        {
            // No error handler: halt execution
            xyw_memory[SYSTEM_STATE] &= ~SYSTEM_STATE_RUNNING;
            return xyw_memory[SYSTEM_ERROR];
        }
    }
    return 0;
}

//// Snapshot management

typedef struct {
    xyw_byte memory[MEMORY_SIZE];
    xyw_byte user_stack[USER_STACK_SIZE];
    xyw_byte system_stack[SYSTEM_MAX_FRAMES * SYSTEM_FRAME_SIZE];
    xyw_byte s, u, x_val, y_val;
    xyw_word pc_val, xw_val, yw_val;
    xyw_byte error_handler_entry_s;
    int argv_processed;
    int arg_index;
    int arg_char_pos;
    char subimage_args_buf[MAX_SUBIMAGE_ARGS];
    int subimage_args_active;
    int subimage_args_pos;
} xyw_image_snapshot;

static xyw_image_snapshot exec_stack[MAX_IMAGE_EXEC_DEPTH];
static int exec_stack_depth = 0;
static int exec_pending = 0;
static char exec_path_buf[MAX_IMAGE_EXEC_PATH_LENGTH];

// Read a null-terminated string out of VM memory into a local buffer
static void get_string_from_memory(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';
}

void xyw_request_exec(xyw_word path_addr)
{
    get_string_from_memory(path_addr, exec_path_buf, sizeof(exec_path_buf));
    exec_pending = 1;
}

static void split_exec_string(char *full, char **path, char **argstart)
{
    char *sp = strchr(full, ' ');
    if (sp)
    {
        *sp = '\0';
        *argstart = sp + 1;
    }
    else
    {
        *argstart = NULL;
    }
    *path = full;
}

static void reset_vm_state(void)
{
    memset(xyw_memory, 0, sizeof(xyw_memory));
    memset(user_stack, 0, sizeof(user_stack));
    memset(system_stack, 0, sizeof(system_stack));
    s = 0;
    u = 0;
    x_val = 0;
    y_val = 0;
    xw_storage = 0;
    yw_storage = 0;
    pc_storage = 0;
    error_handler_entry_s = 0;
    xyw_argv_processed = 0;
}

static int load_and_launch(const char *path, char *argstart)
{
    FILE *fp = fopen(path, "rb");
    if (!fp)
    {
        fprintf(stderr, "Error - Could not open file [%s]\n", path);
        xyw_memory[SYSTEM_ERROR] = XYW_ERROR_IMAGE_NOT_FOUND;
        xyw_memory[SYSTEM_STATE] &= ~SYSTEM_STATE_RUNNING;
        return -1;
    }
    size_t bytes_read = fread(&xyw_memory[USER_MEMORY_START], 1, MEMORY_SIZE - USER_MEMORY_START, fp);
    fclose(fp);
    if (bytes_read == 0)
    {
        fprintf(stderr, "Error - Could not read file contents [%s]\n", path);
        xyw_memory[SYSTEM_ERROR] = XYW_ERROR_IMAGE_READ_ERROR;
        xyw_memory[SYSTEM_STATE] &= ~SYSTEM_STATE_RUNNING;
        return -1;
    }
    xyw_memory[SYSTEM_STATE] |= SYSTEM_STATE_RUNNING;

    for (int i = 0; i < XYW_TOTAL_DEVICES; i++)
        if (xyw_devices[i].setup)
            xyw_devices[i].setup(xyw_devices[i].data);

    xyw_memory[SYSTEM_PAGE] = 0xff;
    *pc = 0x0000;

    // Store sub-image arguments for deferred feeding via feed_next_event
    // Include image path as first argument (matching CLI argv convention)
    if (argstart)
    {
        snprintf(subimage_args_buf, MAX_SUBIMAGE_ARGS, "%s %s", path, argstart);
        subimage_args_active = 1;
        subimage_args_pos = 0;
    }
    else
    {
        subimage_args_active = 0;
    }
    return 0;
}

static void save_snapshot(xyw_image_snapshot *snap)
{
    XYW_DBG("== Saving snapshot");
    memcpy(snap->memory, xyw_memory, sizeof(xyw_memory));
    memcpy(snap->user_stack, user_stack, sizeof(user_stack));
    memcpy(snap->system_stack, system_stack, sizeof(system_stack));
    snap->s = s;
    snap->u = u;
    snap->x_val = x_val;
    snap->y_val = y_val;
    snap->pc_val = *pc;
    snap->xw_val = *xw;
    snap->yw_val = *yw;
    snap->error_handler_entry_s = error_handler_entry_s;
    snap->argv_processed = xyw_argv_processed;
    snap->arg_index = arg_index;
    snap->arg_char_pos = arg_char_pos;
    memcpy(snap->subimage_args_buf, subimage_args_buf, sizeof(subimage_args_buf));
    snap->subimage_args_active = subimage_args_active;
    snap->subimage_args_pos = subimage_args_pos;
}

static void restore_snapshot(xyw_image_snapshot *snap)
{
    XYW_DBG("== Restoring snapshot");
    memcpy(xyw_memory, snap->memory, sizeof(xyw_memory));
    memcpy(user_stack, snap->user_stack, sizeof(user_stack));
    memcpy(system_stack, snap->system_stack, sizeof(system_stack));
    s = snap->s;
    u = snap->u;
    x_val = snap->x_val;
    y_val = snap->y_val;
    *pc = snap->pc_val;
    *xw = snap->xw_val;
    *yw = snap->yw_val;
    error_handler_entry_s = snap->error_handler_entry_s;
    xyw_argv_processed = snap->argv_processed;
    arg_index = snap->arg_index;
    arg_char_pos = snap->arg_char_pos;
    memcpy(subimage_args_buf, snap->subimage_args_buf, sizeof(subimage_args_buf));
    subimage_args_active = snap->subimage_args_active;
    subimage_args_pos = snap->subimage_args_pos;

    // Devices with state outside xyw_memory (file cursor, clock timer target,
    // beeper device) don't roll back automatically — re-sync to a clean slate
    for (int i = 0; i < XYW_TOTAL_DEVICES; i++)
        if (xyw_devices[i].setup)
            xyw_devices[i].setup(xyw_devices[i].data);
}

static void handle_exec_requests(void)
{
    if (!exec_pending)
        return;
    exec_pending = 0;

    if (exec_stack_depth >= MAX_IMAGE_EXEC_DEPTH)
    {
        xyw_memory[SYSTEM_ERROR] = XYW_ERROR_EXEC_DEPTH_EXCEEDED;
        return;
    }
    save_snapshot(&exec_stack[exec_stack_depth++]);

    char path_copy[MAX_IMAGE_EXEC_PATH_LENGTH];
    strncpy(path_copy, exec_path_buf, sizeof(path_copy) - 1);
    path_copy[sizeof(path_copy) - 1] = '\0';
    char *path, *argstart;
    split_exec_string(path_copy, &path, &argstart);

    reset_vm_state();
    if (load_and_launch(path, argstart) != 0)
    {
        // Restore parent state so error handler can run in the caller's context
        restore_snapshot(&exec_stack[--exec_stack_depth]);
    }
}

//// Event dispatch (WAITING state)

// Addresses of all event handler slots — add new handlers here.
// Both has_event_handlers() and feed_next_event() stay in sync via this table.
static const xyw_word event_handler_addrs[] = {
    TERMINAL_ON_ARGUMENT,
    TERMINAL_ON_KEYPRESS,
    CLOCK_ON_TIMER_ELAPSED,
};
#define NUM_EVENT_HANDLERS (sizeof(event_handler_addrs) / sizeof(event_handler_addrs[0]))

static int has_event_handlers(void)
{
    for (size_t i = 0; i < NUM_EVENT_HANDLERS; i++)
        if (XYW_PEEKW(&xyw_memory[event_handler_addrs[i]]))
            return 1;
    return 0;
}

// Feed the next external event and dispatch its handler.
// Returns 1 if an event was dispatched, 0 if no more events.
static int feed_next_event(void)
{
    // Feed command line arguments
    xyw_word on_arg_handler = XYW_PEEKW(&xyw_memory[TERMINAL_ON_ARGUMENT]);
    if (!xyw_argv_processed && on_arg_handler)
    {
        if (subimage_args_active)
        {
            // Feed from sub-image argument string (space-separated)
            char c = subimage_args_buf[subimage_args_pos];
            if (c == ' ')
            {
                xyw_memory[TERMINAL_INPUT] = XYW_ARGUMENT_SEPARATOR;
                subimage_args_pos++;
            }
            else if (c != '\0')
            {
                xyw_memory[TERMINAL_INPUT] = (xyw_byte)c;
                subimage_args_pos++;
            }
            else
            {
                xyw_memory[TERMINAL_INPUT] = XYW_END_OF_ARGUMENTS;
                xyw_argv_processed = 1;
                subimage_args_active = 0;
            }
        }
        else if (arg_index < xyw_argc)
        {
            // Feed from CLI argv
            char c = xyw_argv[arg_index][arg_char_pos];
            if (c != '\0')
            {
                xyw_memory[TERMINAL_INPUT] = (xyw_byte)c;
                arg_char_pos++;
            }
            else if (arg_index < xyw_argc - 1)
            {
                xyw_memory[TERMINAL_INPUT] = XYW_ARGUMENT_SEPARATOR;
                arg_index++;
                arg_char_pos = 0;
            }
            else
            {
                xyw_memory[TERMINAL_INPUT] = XYW_END_OF_ARGUMENTS;
                xyw_argv_processed = 1;
            }
        }
        else
        {
            // No arguments, just send end marker
            xyw_memory[TERMINAL_INPUT] = XYW_END_OF_ARGUMENTS;
            xyw_argv_processed = 1;
        }
        xyw_memory[SYSTEM_STATE] |= SYSTEM_STATE_RUNNING;
        // Sentinel return: handler's RTS returns to device space, cleanly ending dispatch
        ss_push_frame(DEVICE_AREA_START);
        *pc = on_arg_handler;
        return 1;
    }

    // Keypress handling (non-blocking: returns 0 on timeout)
    xyw_word on_keypress_handler = XYW_PEEKW(&xyw_memory[TERMINAL_ON_KEYPRESS]);

    // Timer handling
    xyw_word on_timer_handler = XYW_PEEKW(&xyw_memory[CLOCK_ON_TIMER_ELAPSED]);

    // Polling loop: keep checking until an event fires or exit is requested
    while (on_keypress_handler || on_timer_handler)
    {
        if (on_keypress_handler)
        {
            int c = getch_timeout(POLL_INTERVAL_MS);
            if (c > 0)
            {
                if (c == 3 || c == 4) return 0; // CTRL+C or CTRL+D
                xyw_memory[TERMINAL_INPUT] = (xyw_byte)c;
                xyw_memory[SYSTEM_STATE] |= SYSTEM_STATE_RUNNING;
                // Sentinel return: handler's RTS returns to device space, cleanly ending dispatch
                ss_push_frame(DEVICE_AREA_START);
                *pc = on_keypress_handler;
                return 1;
            }
            // c == 0: no key this cycle — fall through to timer check
        }

        if (on_timer_handler)
        {
            int elapsed = on_keypress_handler
                ? (readw(CLOCK_TIMER) == 0 && readb(CLOCK_ON_TIMER_ELAPSED))
                : readb(CLOCK_ON_TIMER_ELAPSED); // blocking: timer-only program
            if (elapsed)
            {
                xyw_memory[SYSTEM_STATE] |= SYSTEM_STATE_RUNNING;
                // Sentinel return: handler's RTS returns to device space, cleanly ending dispatch
                ss_push_frame(DEVICE_AREA_START);
                *pc = on_timer_handler;
                return 1;
            }
        }
    }

    return 0;
}

//// Main evaluation function - runs from current pc until BRK
int xyw_eval(xyw_word start_pc)
{
    *pc = start_pc;

    // Save register state so event handlers don't corrupt the caller's registers
    xyw_byte saved_x = *x;
    xyw_byte saved_y = *y;
    xyw_word saved_xw = *xw;
    xyw_word saved_yw = *yw;

    if (xyw_debug)
    {
        xyw_memory[SYSTEM_STATE] |= SYSTEM_STATE_DEBUG;
    }
    while (1)
    {
        if (*pc >= DEVICE_AREA_START)
        {
            xyw_memory[SYSTEM_STATE] &= ~SYSTEM_STATE_RUNNING;
        } 
        if (!system_running_state())
        {
            if (system_waiting_state())
            {
                if (feed_next_event())
                {
                    continue; // handler was dispatched, go execute it
                }
                xyw_memory[SYSTEM_STATE] &= ~SYSTEM_STATE_WAITING;
            }
            if (exec_stack_depth > 0)
            {
                restore_snapshot(&exec_stack[--exec_stack_depth]);
                continue;   // resume the parent exactly where it left off
            }
            break;          // no parent -- genuinely done
        }

        process_events();
        handle_exec_requests();
        if (!system_running_state())
        {
            continue;
        }
        XYW_DBG(" -- PC: %04X -> %02X (%s) [U:%02X|S:%02X|X:%02X|Y:%02X|XW:%04X|YW:%04X]\n", *pc, xyw_memory[*pc], xyw_instructions[xyw_memory[*pc] & 0x1F], u, s, *x, *y, *xw, *yw);
        switch (xyw_memory[*pc])
        {
            // clang-format off
            /* HLT */ case 0x00: 
                xyw_memory[SYSTEM_STATE] &= ~SYSTEM_STATE_RUNNING;
                if (has_event_handlers())
                {
                    xyw_memory[SYSTEM_STATE] |= SYSTEM_STATE_WAITING;
                }
                break;
            /* NOP */ case 0x01: break;
            /* PSH */ OPC_SR1(0x02, , if (rx||ry) { PUSH(ARG); } else { (*pc)++; PUSH(READ(*pc)); if (w) { (*pc)++; } })
            /* PSH */ OPC_SR1r(0x02, PUSH(a); PUSH(b); )
            /* POP */ OPC_SR1(0x03, , if (rx||ry) { SET(POP()); } else { POP(); } );
            /* POP */ OPC_SR1r(0x03, if (w) { xyw_word val = us_popw(); *xw = val; *yw = val; } else { xyw_byte val = us_pop(); *x = val; *y = val; } );
            /* LDB */ OPC_SR1(0x04, , us_push(readb(ADDR(ARG))));
            /* LDB */ OPC_SR1r(0x04, us_push(readb(ADDR(ARGX))); us_push(readb(ADDR(ARGY))); );
            /* LDW */ OPC_SR1(0x05, , us_pushw(readw(ADDR(ARG)) ));
            /* LDW */ OPC_SR1r(0x05, us_pushw(readw(ADDR(ARGX))); us_pushw(readw(ADDR(ARGY))); );
            /* STB */ OPC_SR1(0x06, xyw_word addr = ADDR(ARG); xyw_byte val = us_pop(), writeb( addr, val ));
            /* STB */ OPC_SR1r(0x06, xyw_byte val = us_pop(); writeb( ADDR(ARGX), val ); writeb( ADDR(ARGY), val ); );
            /* STW */ OPC_SR1(0x07, xyw_word addr = ADDR(ARG); xyw_word val = us_popw(), writew( addr, val ));
            /* STW */ OPC_SR1r(0x07, xyw_word val = us_popw(); writew( ADDR(ARGX), val ); writew( ADDR(ARGY), val ); );
            /* INC */ OPC_SR1(0x08, , SET(ARG + 1));
            /* INC */ OPC_SR1r(0x08, SET(ARGX + 1); SET(ARGY + 1); );
            /* DEC */ OPC_SR1(0x09, , SET(ARG - 1));
            /* DEC */ OPC_SR1r(0x09, SET(ARGX - 1); SET(ARGY - 1); );
            /* SHL */ OPC_SR1(0x0A, xyw_byte val = us_pop(), SET(ARG << val));
            /* SHL */ OPC_SR1r(0x0A, xyw_byte val = us_pop(); SET(ARGX << val); SET(ARGY << val); );
            /* SHR */ OPC_SR1(0x0B, xyw_byte val = us_pop(), SET(ARG >> val));
            /* SHR */ OPC_SR1r(0x0B, xyw_byte val = us_pop(); SET(ARGX >> val); SET(ARGY >> val); );
            /* ADD */ OPC_SR2(0x0C, PUSH(a + b));
            /* SUB */ OPC_SR2(0x0D, PUSH(a - b));
            /* MUL */ OPC_SR2(0x0E, PUSH(a * b));
            /* DIV */ OPC_SR2(0x0F, if (b) { PUSH(a % b); PUSH(a / b); } else { xyw_memory[SYSTEM_ERROR] = XYW_ERROR_DIVISION_BY_ZERO; } );
            /* EQU */ OPC_SR2(0x10, us_push(a == b));
            /* NEQ */ OPC_SR2(0x11, us_push(a != b));
            /* GTH */ OPC_SR2(0x12, us_push(a > b));
            /* LTH */ OPC_SR2(0x13, us_push(a < b));
            /* NOT */ OPC_SR1(0x14, , SET(~ARG));
            /* NOT */ OPC_SR1r(0x14, SET(~ARGX); SET(~ARGY); );
            /* AND */ OPC_SR2(0x15, PUSH(a & b));
            /* IOR */ OPC_SR2(0x16, PUSH(a | b));
            /* XOR */ OPC_SR2(0x17, PUSH(a ^ b));
            /* DUP */ OPC_SR1(0x18, , SET(TOP));
            /* DUP */ OPC_SR1r(0x18, SETX(TOP); SETY(TOP); );
            /* SWP */ OPC_SR2(0x19, if ((rx||ry)) { SET(b); } else { PUSH(b); PUSH(a); } );
            /* OVR */ OPC_OVR(0x1A);
            /* ROT */ OPC_ROT(0x1B);
            /* JMP */ OPC_SR1(0x1C, , *pc = ADDR(ARG)-1;);
            /* JCN */ OPC_SR1(0x1D, , xyw_word addr = ADDR(ARG); xyw_byte cond = us_pop(); if (cond) { *pc = addr-1; });
            /* JSR */ OPC_SR1(0x1E, xyw_word addr = ADDR(ARG),  ss_push_frame(*pc+1); *pc = addr-1;);
            /* RTS */ case 0x1F: 
                *pc = ss_pop_frame()-1; 
                // If returning from error handler, clear flag to allow re-trigger
                if ((system_error_state()) && s == error_handler_entry_s) {
                    xyw_memory[SYSTEM_STATE] &= ~SYSTEM_STATE_ERROR;
                    error_handler_entry_s = 0;
                }
                break;
            // clang-format on
        }
        (*pc)++;
        if (xyw_memory[SYSTEM_ERROR] != XYW_ERROR_NONE) continue;
    }
    // Restore register state saved at entry (protects caller from event handler side-effects)
    *x = saved_x;
    *y = saved_y;
    *xw = saved_xw;
    *yw = saved_yw;
    return xyw_memory[SYSTEM_ERROR];
}

static void xyw_teardown_devices(void)
{
    for (int i = 0; i < XYW_TOTAL_DEVICES; i++)
    {
        if (xyw_devices[i].teardown)
        {
            xyw_devices[i].teardown(xyw_devices[i].data);
        }
    }
}

//// Main run function
int xyw_run(const char *input)
{
    atexit(xyw_teardown_devices);

    if (load_and_launch(input, NULL) != 0)
    {
        return -1;
    }

    XYW_DBG("Loaded image into memory\n");
    return xyw_eval(0x0000);
}