~vdupras/duskos

ref: ab62853f9ec65075c9e1a480861b5c0cea7b5e7c duskos/posix/vm.c -rw-r--r-- 19.9 KiB
ab62853fVirgil Dupras xcomp/tools: fix broken orgifydict a month ago
                                                                                
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
/* VM for bootstrapping Dusk from POSIX platforms

This is a Forth VM that has the goal of being able to bootstrap Dusk from any
POSIX platform. It is limited compared to bare-metal builds because it cannot
run CC, but it still has the ability to load assemblers and thus create bare
metal builds.

The VM is little endian.
*/
#include <inttypes.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MEMSZ 0x100000 // 1MB
#define STACKSZ 0x800
#define RSTOP MEMSZ
#define PSTOP (RSTOP-STACKSZ)
#define SYSVARSSZ 0x80
#define SYSVARS ((PSTOP-STACKSZ)-SYSVARSSZ)
#define HERE SYSVARS
#define CURRENT (HERE+4)
#define COMPILING (CURRENT+4)
#define NEXTMETA (COMPILING+4)
#define INRD (NEXTMETA+4)
#define EMIT (INRD+4)
#define ABORT (EMIT+4)
#define MAINLOOP (ABORT+4)
#define CURWORD (MAINLOOP+4)
#define IOBUFSZ 0x800
#define IOBUF (SYSVARS-IOBUFSZ)
#define HEREMAX IOBUF


typedef uint8_t byte;
typedef uint16_t word;
typedef uint32_t dword;

struct VM {
    dword PSP;
    dword RSP;
    dword PC; // when PC >= MEMSZ, machine is halted
    dword toptr;
    dword areg;
    byte mem[MEMSZ];
};

static struct VM vm = {0};
static FILE *bootfp;

// Utilities
static byte gb(dword addr) { return vm.mem[addr]; }
static word gw(dword addr) { return gb(addr) | (gb(addr+1)<<8); }
static dword gd(dword addr) { return gw(addr) | (gw(addr+2)<<16); }
static dword gpc() { dword n = gd(vm.PC); vm.PC += 4; return n; }
static void sb(dword addr, byte b) { vm.mem[addr] = b; }
static void sw(dword addr, word w) { sb(addr, w); sb(addr+1, w>>8); }
static void sd(dword addr, dword d) { sw(addr, d); sw(addr+2, d>>16); }
static dword ppeek() { return gd(vm.PSP); }
static dword ppop() { dword n = ppeek(); vm.PSP += 4; return n; }
static void ppush(dword d) { vm.PSP -= 4; sd(vm.PSP, d); }
static dword rpeek() { return gd(vm.RSP); }
static dword rpop() { dword n = rpeek(); vm.RSP += 4; return n; }
static void rpush(dword d) { vm.RSP -= 4; sd(vm.RSP, d); }
static dword here() { return gd(HERE); }
static void allot(dword n) { sd(HERE, here()+n); }
static dword current() { return gd(CURRENT); }
static dword _find(byte *name, byte slen) {
    dword a = current();
    byte len;
    while (a) {
        len = gb(a-1) & 0x3f;
        if ((len == slen) && (memcmp(name, &vm.mem[a-9-len], len)==0)) {
            return a;
        }
        a = gd(a-5);
    }
    return 0;
}
static dword find(char *name) {
    return _find((byte*)name, strlen(name));
}
static void cwrite(byte b) {
    sb(here(), b);
    allot(1);
}
static void dwrite(dword d) {
    sd(here(), d);
    allot(4);
}
static void retwr() { cwrite(0x02); }
static void litwr(dword n) {
    cwrite(0x03); // LIT
    dwrite(n);
}

static void callwr(dword a) {
    cwrite(0x01); // CALL
    dwrite(a);
}
static void callword(dword addr); // forward declaration
static void _entry(byte *name, byte slen) {
    memcpy(&vm.mem[here()], name, slen);
    allot(slen);
    dwrite(gd(NEXTMETA));
    dwrite(current());
    cwrite(slen);
    sd(CURRENT, here());
    sd(NEXTMETA, 0);
}
static void entry(char *name) {
    _entry((byte*)name, strlen(name));
}
static void toexec(dword a) {
    ppush(a);
    vm.PC = vm.toptr;
    vm.toptr = 0;
}

// Operations
/* The VM works in a simple manner. The VM reads the byte where PC points to in
memory, increases PC by 1 and executes the corresponding function in the
function list below. As simple as this. */

static void JUMP() { // op: 00
    vm.PC = gpc();
}

static void CALL() { // op: 01
    dword n = gpc();
    rpush(vm.PC);
    vm.PC = n;
}

static void RET() { // op: 02
    vm.PC = rpop();
}

static void LIT() { // op: 03
    dword n = gpc();
    ppush(n);
}

static void BYE() { // op: 04
    vm.PC = MEMSZ;
}

static void BYEFAIL() { // op: 05
    vm.PC = MEMSZ + 1;
}

static void QUIT() { // op: 06
    vm.toptr = 0;
    vm.RSP = RSTOP;
    vm.PC = gd(MAINLOOP);
}

static void ABORT_() { // op: 07
    vm.PSP = PSTOP;
    sd(COMPILING, 0);
    sd(NEXTMETA, 0);
    QUIT();
}

static void EXECUTE() { // op: 08
    vm.PC = ppop();
}

static void CELL() { // op: 09
    ppush(rpop());
}

static void VAL() { // op: 0a
    dword a = rpop();
    if (vm.toptr) {
        toexec(a);
    } else {
        ppush(gd(a));
    }
}

static void ALIAS() { // op: 0b
    dword a = rpop();
    if (vm.toptr) {
        toexec(a);
    } else {
        vm.PC = gd(a);
    }
}

static void DOES() { // op: 0c
    dword a = rpop();
    ppush(a+4);
    vm.PC = gd(a);
}

static void SLIT() { // op: 0d
    dword a = rpop();
    ppush(a);
    vm.PC = a + gb(a) + 1;
}

static void BR() { // op: 0e
    vm.PC = gd(rpop());
}

static void CBR() { // op: 0f
    if (ppop()) {
        rpush(rpop()+4);
    } else {
        BR();
    }
}

static void NEXT() { // op: 10
    dword r = rpop();
    dword n = rpop();
    if (--n) {
        rpush(n);
        vm.PC = gd(r);
    } else {
        vm.PC = r+4;
    }
}

static void SYSALIAS() { // op: 11
    dword a = gpc();
    if (vm.toptr) {
        toexec(a);
    } else {
        vm.PC = gd(a);
    }
}

static void SYSVAL() { // op: 12
    dword a = gpc();
    if (vm.toptr) {
        toexec(a);
    } else {
        ppush(gd(a));
    }
}

static void BOOTRD() { // op: 13
    ppush(fgetc(bootfp));
}

static void STDOUT() { // op: 14
    dword c = ppop();
    write(STDOUT_FILENO, &c, 1);
}

static void STDERR() { // op: 15
    dword c = ppop();
    write(STDERR_FILENO, &c, 1);
}

static void KEY() { // op: 16
    ppush(getc(stdin));
}

static void DROP() { // op: 17
    ppop();
}

static void DUP() { // op: 18
    ppush(ppeek());
}

static void CDUP() { // op: 19
    if (ppeek()) { DUP(); }
}

static void SWAP() { // op: 1a
    dword a = ppop();
    dword b = ppop();
    ppush(a); ppush(b);
}

static void OVER() { // op: 1b
    dword a = gd(vm.PSP+4);
    ppush(a);
}

static void ROT() { // op: 1c
    dword a = ppop();
    dword b = ppop();
    dword c = ppop();
    ppush(b); ppush(a); ppush(c);
}

static void ROTR() { // op: 1d
    dword a = ppop();
    dword b = ppop();
    dword c = ppop();
    ppush(a); ppush(c); ppush(b);
}

static void NIP() { // op: 1e
    dword n = ppop();
    sd(vm.PSP, n);
}

static void TUCK() { // op: 1f
    dword a = ppop();
    dword b = ppop();
    ppush(a); ppush(b); ppush(a);
}

/* Warning: RS routines are all called, which means that we have to work from
the second item from the top rather than the first. */

static void RS2PS() { // op: 20
    dword a = rpop();
    ppush(rpop());
    rpush(a);
}

static void PS2RS() { // op: 21
    dword a = rpop();
    rpush(ppop());
    rpush(a);
}

static void RSGET() { // op: 22
    ppush(gd(vm.RSP+4));
}

static void RDROP() { // op: 23
    dword a = rpop();
    rpop();
    rpush(a);
}

static void SCNT() { // op: 24
    ppush((PSTOP-vm.PSP)>>2);
}

static void RCNT() { // op: 25
    ppush(((RSTOP-vm.RSP)>>2)-1);
}

static void ASET() { // op: 26
    vm.areg = ppop();
}

static void AGET() { // op: 27
    ppush(vm.areg);
}

static void ACFETCH() { // op: 28
    ppush(gb(vm.areg));
}

static void ACSTORE() { // op: 29
    sb(vm.areg, ppop());
}

static void AINC() { // op: 2a
    vm.areg++;
}

static void ADEC() { // op: 2b
    vm.areg--;
}

static void A2RS() { // op: 2c
    dword a = rpop();
    rpush(vm.areg);
    rpush(a);
}

static void RS2A() { // op: 2d
    dword a = rpop();
    vm.areg = rpop();
    rpush(a);
}

static void TOSET() { // op: 2e
    vm.toptr = ppop();
}

static void TOGET() { // op: 2f
    ppush(vm.toptr);
    vm.toptr = 0;
}

static void INC() { // op: 30
    ppush(ppop()+1);
}

static void DEC() { // op: 31
    ppush(ppop()-1);
}

static void CFETCH() { // op: 32
    ppush(gb(ppop()));
}

static void CSTORE() { // op: 33
    dword a = ppop();
    sb(a, ppop());
}

static void CWRITE() { // op: 34
    cwrite(ppop());
}

static void WFETCH() { // op: 35
    ppush(gw(ppop()));
}

static void WSTORE() { // op: 36
    dword a = ppop();
    sw(a, ppop());
}

static void FETCH() { // op: 37
    ppush(gd(ppop()));
}

static void STORE() { // op: 38
    dword a = ppop();
    sd(a, ppop());
}

static void ADDSTORE() { // op: 39
    dword a = ppop();
    sd(a, gd(a)+ppop());
}

static void WRITE() { // op: 3a
    dwrite(ppop());
}

static void ADD() { // op: 3b
    dword n = ppop();
    ppush(ppop()+n);
}

static void SUB() { // op: 3c
    dword n = ppop();
    ppush(ppop()-n);
}

static void MUL() { // op: 3d
    dword n = ppop();
    ppush(ppop()*n);
}

// ( a b -- r q )
static void DIVMOD() { // op: 3e
    dword b = ppop();
    dword a = ppop();
    ppush(a%b);
    ppush(a/b);
}

static void AND() { // op: 3f
    dword n = ppop();
    ppush(ppop()&n);
}

static void OR() { // op: 40
    dword n = ppop();
    ppush(ppop()|n);
}

static void XOR() { // op: 41
    dword n = ppop();
    ppush(ppop()^n);
}

static void BOOL() { // op: 42
    if (ppop()) { ppush(1); } else { ppush(0); }
}

static void NOT() { // op: 43
    if (ppop()) { ppush(0); } else { ppush(1); }
}

static void LT() { // op: 44
    dword n = ppop();
    if (ppop()<n) { ppush(1); } else { ppush(0); }
}

static void SHLC() { // op: 45
    dword n = ppop();
    ppush(n<<1);
    ppush(n>>31);
}

static void SHRC() { // op: 46
    dword n = ppop();
    ppush(n>>1);
    ppush(n&1);
}

// ( n u -- n )
static void LSHIFT() { // op: 47
    dword u = ppop();
    dword n = ppop();
    ppush(n<<u);
}

static void RSHIFT() { // op: 48
    dword u = ppop();
    dword n = ppop();
    ppush(n>>u);
}

static void LITN() { // op: 49
    litwr(ppop());
}

static void EXECUTEWR() { // op: 4a
    callwr(ppop());
}

static void EXITWR() { // op: 4b
    retwr();
}

static void MOVE() { // op: 4c
    dword u = ppop();
    dword dst = ppop();
    dword src = ppop();
    memcpy(&vm.mem[dst], &vm.mem[src], u);
}

static void MOVEWR() { // op: 4d
    dword u = ppop();
    ppush(here());
    allot(u);
    ppush(u);
    MOVE();
}

static void RTYPE() { // op: 4e
    dword u = ppop();
    dword a = ppop();
    write(STDOUT_FILENO, &vm.mem[a], u);
}

static void WNF() { // op: 4f
    write(STDOUT_FILENO, &vm.mem[CURWORD+1], vm.mem[CURWORD]);
    write(STDOUT_FILENO, " word not found", 15);
    vm.PC = gd(ABORT);
}

static void STACKCHK() { // op: 50
    if (vm.PSP > PSTOP) {
        write(STDOUT_FILENO, "stack underflow", 15);
        vm.PC = gd(ABORT);
    }
}

static void MAYBEWORD() { // op: 51
    dword c, a;
	// save toptr so that it doesn't mess in<, which could be calling a word
	// with to semantics
    dword toptr = vm.toptr;
    vm.toptr = 0;
    do {
        callword(gd(INRD));
        c = ppop();
        if (c >> 31) { // EOF
            vm.toptr = toptr;
            ppush(0);
            return;
        }
    } while (c <= ' ');
    a = CURWORD+1;
    do {
        sb(a++, c);
        callword(gd(INRD));
        c = ppop();
    } while (!(c >> 31) && (c > ' '));
    vm.toptr = toptr;
    sb(CURWORD, a-CURWORD-1); // len
    ppush(CURWORD);
}

static void WORD() { // op: 52
    MAYBEWORD();
    if (!ppeek()) {
        write(STDOUT_FILENO, "word expected", 13);
        vm.PC = gd(ABORT);
    }
}

static void PARSE() { // op: 53
    dword s = ppop();
    byte len = gb(s++);
    dword n = 0;
    byte neg = 0;
    byte c;
    if (!len) goto err;
    switch (gb(s)) {
        case '\'':
            if (len != 3) goto err;
            if (gb(s+2) != '\'') goto err;
            n = gb(s+1);
            break;
        case '$':
            s++; len--;
            if (!len) goto err;
            while (len--) {
                c = (gb(s++) | 0x20) - '0';
                if (c >= 10) {
                    c -= ('a'-'0');
                    if (c >= 6) goto err;
                    c += 10;
                }
                n *= 16;
                n += c;
            }
            break;
        case '-':
            neg = 1;
            s++; len--;
            if (!len) goto err;
        default: // decimal
            while (len--) {
                c = gb(s++) - '0';
                if (c >= 10) goto err;
                n *= 10;
                n += c;
            }
            if (neg) n *= -1;
    }
    ppush(n); ppush(1);
    return;
err:
    ppush(0);
}

// ( a1 a2 u -- f )
static void REQ() { // op: 54
    dword u = ppop();
    dword a2 = ppop();
    dword a1 = ppop();
    ppush(memcmp(&vm.mem[a1], &vm.mem[a2], u) == 0);
}

static void FIND() { // op: 55
    dword s = ppop();
    byte len = gb(s++);
    ppush(_find(&vm.mem[s], len));
}

static void APOS() { // op: 56
    WORD();
    FIND();
    if (!ppeek()) WNF();
}

static void ENTRY() { // op: 57
    dword s = ppop();
    byte len = gb(s++);
    _entry(&vm.mem[s], len);
}

static void XTCOMP() { // op: 58
    sd(COMPILING, 1);
    while (gd(COMPILING)) {
        WORD();
        PARSE();
        if (ppop()) {
            LITN();
        } else {
            ppush(CURWORD);
            FIND();
            if (!ppeek()) { WNF(); return; }
            if (gb(ppeek()-1) & 0x80) { // immediate
                callword(ppop());
            } else {
                EXECUTEWR();
            }
        }
    }
    EXITWR();
}

static void DOCOL() { // op: 59
    WORD();
    ENTRY();
    XTCOMP();
}

static void STOPCOL() { // op: 5a
    sd(COMPILING, 0);
}

static void RUNWORD() { // op: 5b
    PARSE();
    if (!ppop()) {
        ppush(CURWORD);
        FIND();
        if (!ppeek()) { WNF(); return; }
        callword(ppop());
        STACKCHK();
    }
}

static void EXIT() { // op: 5c
    rpop();
}

/* Filesystem

At POSIX level, we don't have access to the underlying FS structure such as
inodes, making Dusk's 32-bit "ID" system a bit awkward. What we're going to do
here is have a buffer of all requested paths, and the index in that buffer will
be our ID.

To simplify cursor management, we have a single IO buffer that we rotate our
reads into.
*/
#define MAXPATHSZ 0x100
#define FSIDCNT 0x200
static char fsids[FSIDCNT][MAXPATHSZ] = {0};
static dword iobufpos = 0;

static dword findpath(char *path) {
    for (dword i=0; i<FSIDCNT; i++) {
        if (strcmp(path, fsids[i]) == 0) return i;
    }
    return 0;
}

static int getfiledesc(dword hdl) {
    return (int)(gd(hdl+20)|(((int64_t)gd(hdl+24))<<32));
}

static void FCHILD () { // op: 5d
    dword s = ppop();
    byte len = gb(s++);
    dword parent = ppop();
    char path[MAXPATHSZ] = {0};
    dword res;
    if ((parent >= FSIDCNT) || !fsids[parent][0]) {
        printf("Out of bounds FSID\n");
        vm.PC = gd(ABORT);
        return;
    }
    strcpy(path, fsids[parent]);
    strcat(path, "/");
    strncat(path, (char*)&vm.mem[s], len);
    res = findpath(path);
    if (!res) {
        // Verify if path actually exists in FS, then create a new ID
        struct stat sb;
        if (stat(path, &sb) != 0) { // does not exist
            ppush(0);
            return;
        }
        while (fsids[++res][0]);
        strcpy(fsids[res], path);
    }
    ppush(res);
}

// Our handles are simply the regular IO/File preludes followed by the POSIX
// file descriptor, a 64bit int.
static void FOPEN () { // op: 5e
    dword fsid = ppop();
    char *path;
    int fd;
    if ((fsid >= FSIDCNT) || !fsids[fsid][0]) {
        printf("Out of bounds FSID\n");
        vm.PC = gd(ABORT);
        return;
    }
    path = fsids[fsid];
    fd = open(path, 0);
    if (fd < 0) {
        printf("Can't open %s\n", path);
        vm.PC = gd(ABORT);
        return;
    }
    ppush(here()); // File cursor we're about to create
    dwrite(find("_freadbuf"));
    dwrite(find("abort")); // writebuf
    dwrite(find("drop")); // flush
    dwrite(find("2drop")); // seek
    dwrite(find("_fclose")); // close
    dwrite(fd);
    dwrite((int64_t)fd>>32);
}

static void FREADBUF () { // op: 5f
    dword hdl = ppop();
    dword n = ppop();
    int res;
    int fd = getfiledesc(hdl);
    dword a;
    if (!fd) {
        ppush(0);
        return;
    }
    if (iobufpos+n >= IOBUFSZ) {
        iobufpos = 0;
    }
    a = IOBUF + iobufpos;
    res = read(fd, &vm.mem[a], n);
    if (res < 0) {
        printf("I/O readbuf error\n");
        vm.PC = gd(ABORT);
        return;
    }
    iobufpos += res;
    if (res) ppush(a);
    ppush((dword)res);
}

static void FCLOSE () { // op: 60
    dword hdl = ppop();
    int fd = getfiledesc(hdl);
    if (fd) {
        close(fd);
        sd(hdl+20, 0);
        sd(hdl+24, 0);
    }
}

#define OPCNT 0x61
static void (*ops[OPCNT])() = {
    JUMP, CALL, RET, LIT, BYE, BYEFAIL, QUIT, ABORT_,
    EXECUTE, CELL, VAL, ALIAS, DOES, SLIT, BR, CBR,
    NEXT, SYSALIAS, SYSVAL, BOOTRD, STDOUT, STDERR, KEY, DROP,
    DUP, CDUP, SWAP, OVER, ROT, ROTR, NIP, TUCK,
    RS2PS, PS2RS, RSGET, RDROP, SCNT, RCNT, ASET, AGET,
    ACFETCH, ACSTORE, AINC, ADEC, A2RS, RS2A, TOSET, TOGET,
    INC, DEC, CFETCH, CSTORE, CWRITE, WFETCH, WSTORE, FETCH,
    STORE, ADDSTORE, WRITE, ADD, SUB, MUL, DIVMOD, AND,
    OR, XOR, BOOL, NOT, LT, SHLC, SHRC, LSHIFT,
    RSHIFT, LITN, EXECUTEWR, EXITWR, MOVE, MOVEWR, RTYPE, WNF,
    STACKCHK, MAYBEWORD, WORD, PARSE, REQ, FIND, APOS, ENTRY,
    XTCOMP, DOCOL, STOPCOL, RUNWORD, EXIT, FCHILD, FOPEN, FREADBUF,
    FCLOSE};

static char *opnames[OPCNT] = {
    NULL, NULL, NULL, NULL, "bye", "byefail", "quit", "(abort)",
    "execute", "(cell)", "(val)", "(alias)", "(does)", "(s)", "(br)", "(?br)",
    "(next)", NULL, NULL, "boot<", "(emit)", "stderr", "key", "drop",
    "dup", "?dup", "swap", "over", "rot", "rot>", "nip", "tuck",
    "r>", ">r", "r@", "rdrop", "scnt", "rcnt", ">A", "A>",
    "Ac@", "Ac!", "A+", "A-", "A>r", "r>A", "[to]", "to?",
    "1+", "1-", "c@", "c!", "c,", "w@", "w!", "@",
    "!", "+!", ",", "+", "-", "*", "/mod", "and",
    "or", "xor", "bool", "not", "<", "<<c", ">>c", "lshift",
    "rshift", "litn", "execute,", "exit,", "move", "move,", "rtype", "(wnf)",
    "stack?", "maybeword", "word", "parse", "[]=", "find", "'", "entry",
    "xtcomp", ":", ";", "runword", "exit", "fchild", "fopen", "_freadbuf",
    "_fclose"};

static void oprun1() { // run next op
    byte opcode = vm.mem[vm.PC++];
    if (opcode >= OPCNT) {
        printf("Illegal opcode %02x at PC %08x\n", opcode, vm.PC-1);
        BYEFAIL();
    } else {
        ops[opcode]();
    }
}

static void callword(dword addr) {
    dword oldPC;
    // We push a special "0" marker to RS. This way, when PC is 0, we know that
    // it's time to return from our callword().
    rpush(0);
    oldPC = vm.PC;
    vm.PC = addr;
    while (vm.PC && (vm.PC < MEMSZ)) oprun1();
    if (vm.PC < MEMSZ) {
        vm.PC = oldPC;
    }
}

// Dictionary building
static void opentry(byte op) {
    entry(opnames[op]);
    cwrite(op);
}

static void makeimm(char *name) {
    dword a = find(name)-1;
    sb(a, gb(a)|0x80);
}

static void sysalias(char *name, dword addr) {
    entry(name);
    cwrite(0x11); // SYSALIAS
    dwrite(addr);
    retwr();
}

static void sysval(char *name, dword addr) {
    entry(name);
    cwrite(0x12); // SYSVAL
    dwrite(addr);
    retwr();
}

static void sysconst(char *name, dword val) {
    entry(name);
    litwr(val);
    retwr();
}

static void buildsysdict() {
    sd(HERE, 0);
    sd(CURRENT, 0);
    entry("noop"); retwr();
    for (int i=0x04; i<OPCNT; i++) { if (opnames[i]) { opentry(i); retwr(); } }
    makeimm(";");
    sd(INRD, find("boot<"));
    sd(EMIT, find("(emit)"));
    sd(ABORT, find("byefail"));
    sysalias("in<", INRD);
    sysalias("emit", EMIT);
    sysalias("abort", ABORT);
    sysalias("main", MAINLOOP);
    sysval("here", HERE);
    sysval("current", CURRENT);
    sysval("compiling", COMPILING);
    sysconst("heremax", HEREMAX);
    sysconst("curword", CURWORD);
    sysconst("nextmeta", NEXTMETA);
    entry("mainloop");
    sd(MAINLOOP, here());
    callwr(find("word"));
    callwr(find("runword"));
    cwrite(0x00); // JUMP
    dwrite(gd(MAINLOOP));
}

// Interpret loop
int main() {
    strcpy(fsids[0], "fs"); // Set FS root path
    bootfp = fopen("posix/boot.fs", "r");
    if (!bootfp) {
        printf("Can't open boot file.\n");
        return 1;
    }
    buildsysdict();
    vm.PC = find("(abort)");
    while (vm.PC < MEMSZ) oprun1();
    fclose(bootfp);
    if (vm.PC > MEMSZ) {
        fprintf(stderr, "Dumping memory to memdump.\n");
        FILE *fp = fopen("memdump", "w");
        fwrite(vm.mem, MEMSZ, 1, fp);
        fclose(fp);
    }
    return MEMSZ - vm.PC;
}