-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
h2.c
2617 lines (2348 loc) · 78.5 KB
/
h2.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
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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @file h2.c
* @brief Simulate the H2 CPU and surrounding system
* @copyright Richard James Howe (2017)
* @license MIT
*
* This file contains the simulator and debugger for the H2,
* The H2 is written in VHDL and
* is based on the J1 processor (see http://excamera.com/sphinx/fpga-j1.html).
*
* The processor has been tested on an FPGA and is working.
* The project can be found at: https://github.com/howerj/forth-cpu */
/* ========================== Preamble: Types, Macros, Globals ============= */
#include "h2.h"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#define UNUSED(VARIABLE) ((void)(VARIABLE))
#ifdef _WIN32 /* Making standard input streams on Windows binary */
#include <windows.h>
#include <io.h>
#include <fcntl.h>
extern int _fileno(FILE *stream);
static void binary(FILE *f) { _setmode(_fileno(f), _O_BINARY); }
#else
static inline void binary(FILE *f) { UNUSED(f); }
#endif
#define DEFAULT_STEPS (0) /*default is to run forever*/
#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
#define MIN(X, Y) ((X) > (Y) ? (Y) : (X))
#define NUMBER_OF_INTERRUPTS (8u)
#define OP_BRANCH (0x0000)
#define OP_0BRANCH (0x2000)
#define OP_CALL (0x4000)
#define OP_ALU_OP (0x6000)
#define OP_LITERAL (0x8000)
#define IS_LITERAL(INST) (((INST) & 0x8000) == 0x8000)
#define IS_BRANCH(INST) (((INST) & 0xE000) == 0x0000)
#define IS_0BRANCH(INST) (((INST) & 0xE000) == 0x2000)
#define IS_CALL(INST) (((INST) & 0xE000) == 0x4000)
#define IS_ALU_OP(INST) (((INST) & 0xE000) == 0x6000)
#define ALU_OP_LENGTH (5u)
#define ALU_OP_START (8u)
#define ALU_OP(INST) (((INST) >> ALU_OP_START) & ((1 << ALU_OP_LENGTH) - 1))
#define DSTACK_LENGTH (2u)
#define DSTACK_START (0u)
#define DSTACK(INST) (((INST) >> DSTACK_START) & ((1 << DSTACK_LENGTH) - 1))
#define RSTACK_LENGTH (2u)
#define RSTACK_START (2u)
#define RSTACK(INST) (((INST) >> RSTACK_START) & ((1 << RSTACK_LENGTH) - 1))
#define R_TO_PC_BIT_INDEX (4u)
#define N_TO_ADDR_T_BIT_INDEX (5u)
#define T_TO_R_BIT_INDEX (6u)
#define T_TO_N_BIT_INDEX (7u)
#define R_TO_PC (1u << R_TO_PC_BIT_INDEX)
#define N_TO_ADDR_T (1u << N_TO_ADDR_T_BIT_INDEX)
#define T_TO_R (1u << T_TO_R_BIT_INDEX)
#define T_TO_N (1u << T_TO_N_BIT_INDEX)
typedef enum {
ALU_OP_T, /**< Top of Stack */
ALU_OP_N, /**< Copy T to N */
ALU_OP_T_PLUS_N, /**< Addition */
ALU_OP_T_AND_N, /**< Bitwise AND */
ALU_OP_T_OR_N, /**< Bitwise OR */
ALU_OP_T_XOR_N, /**< Bitwise XOR */
ALU_OP_T_INVERT, /**< Bitwise Inversion */
ALU_OP_T_EQUAL_N, /**< Equality test */
ALU_OP_N_LESS_T, /**< Signed comparison */
ALU_OP_N_RSHIFT_T, /**< Logical Right Shift */
ALU_OP_T_DECREMENT, /**< Decrement */
ALU_OP_R, /**< Top of return stack */
ALU_OP_T_LOAD, /**< Load from address */
ALU_OP_N_LSHIFT_T, /**< Logical Left Shift */
ALU_OP_DEPTH, /**< Depth of stack */
ALU_OP_N_ULESS_T, /**< Unsigned comparison */
ALU_OP_ENABLE_INTERRUPTS, /**< Enable interrupts */
ALU_OP_INTERRUPTS_ENABLED, /**< Are interrupts on? */
ALU_OP_RDEPTH, /**< R Stack Depth */
ALU_OP_T_EQUAL_0, /**< T == 0 */
ALU_OP_CPU_ID, /**< CPU Identifier */
ALU_OP_LITERAL, /**< undocumented; set T to instruction & $7fff */
} alu_code_e;
#define DELTA_0 (0)
#define DELTA_1 (1)
#define DELTA_N2 (2)
#define DELTA_N1 (3)
#define MK_DSTACK(DELTA) ((DELTA) << DSTACK_START)
#define MK_RSTACK(DELTA) ((DELTA) << RSTACK_START)
#define MK_CODE(CODE) ((CODE) << ALU_OP_START)
/**
* @warning This table keeps most things synchronized when it comes
* to instructions, the exception is in the lexer, which accepts
* a range of tokens in one clause of the grammar from the first
* instruction to the last. This must be manually updated
* @note In the original J1 specification both r@ and r> both have
* their T_TO_R bit set in their instruction description tables, this
* appears to be incorrect */
#define X_MACRO_INSTRUCTIONS \
X(DUP, "dup", true, (OP_ALU_OP | MK_CODE(ALU_OP_T) | T_TO_N | MK_DSTACK(DELTA_1)))\
X(OVER, "over", true, (OP_ALU_OP | MK_CODE(ALU_OP_N) | T_TO_N | MK_DSTACK(DELTA_1)))\
X(OVERADD,"over+", false, (OP_ALU_OP | MK_CODE(ALU_OP_T_PLUS_N)))\
X(OVERAND,"over-and", false, (OP_ALU_OP | MK_CODE(ALU_OP_T_AND_N)))\
X(INVERT, "invert", true, (OP_ALU_OP | MK_CODE(ALU_OP_T_INVERT)))\
X(ADD, "+", true, (OP_ALU_OP | MK_CODE(ALU_OP_T_PLUS_N) | MK_DSTACK(DELTA_N1)))\
X(SWAP, "swap", true, (OP_ALU_OP | MK_CODE(ALU_OP_N) | T_TO_N))\
X(NIP, "nip", true, (OP_ALU_OP | MK_CODE(ALU_OP_T) | MK_DSTACK(DELTA_N1)))\
X(DROP, "drop", true, (OP_ALU_OP | MK_CODE(ALU_OP_N) | MK_DSTACK(DELTA_N1)))\
X(EXIT, "exit", true, (OP_ALU_OP | MK_CODE(ALU_OP_T) | R_TO_PC | MK_RSTACK(DELTA_N1)))\
X(TOR, ">r", true, (OP_ALU_OP | MK_CODE(ALU_OP_N) | T_TO_R | MK_DSTACK(DELTA_N1) | MK_RSTACK(DELTA_1)))\
X(FROMR, "r>", true, (OP_ALU_OP | MK_CODE(ALU_OP_R) | T_TO_N | MK_DSTACK(DELTA_1) | MK_RSTACK(DELTA_N1)))\
X(RAT, "r@", true, (OP_ALU_OP | MK_CODE(ALU_OP_R) | T_TO_N | MK_DSTACK(DELTA_1)))\
X(LOAD, "@", true, (OP_ALU_OP | MK_CODE(ALU_OP_T_LOAD)))\
X(STORE, "store", false, (OP_ALU_OP | MK_CODE(ALU_OP_N) | N_TO_ADDR_T | MK_DSTACK(DELTA_N1)))\
X(RSHIFT, "rshift", true, (OP_ALU_OP | MK_CODE(ALU_OP_N_RSHIFT_T) | MK_DSTACK(DELTA_N1)))\
X(LSHIFT, "lshift", true, (OP_ALU_OP | MK_CODE(ALU_OP_N_LSHIFT_T) | MK_DSTACK(DELTA_N1)))\
X(EQUAL, "=", true, (OP_ALU_OP | MK_CODE(ALU_OP_T_EQUAL_N) | MK_DSTACK(DELTA_N1)))\
X(ULESS, "u<", true, (OP_ALU_OP | MK_CODE(ALU_OP_N_ULESS_T) | MK_DSTACK(DELTA_N1)))\
X(LESS, "<", true, (OP_ALU_OP | MK_CODE(ALU_OP_N_LESS_T) | MK_DSTACK(DELTA_N1)))\
X(AND, "and", true, (OP_ALU_OP | MK_CODE(ALU_OP_T_AND_N) | MK_DSTACK(DELTA_N1)))\
X(XOR, "xor", true, (OP_ALU_OP | MK_CODE(ALU_OP_T_XOR_N) | MK_DSTACK(DELTA_N1)))\
X(OR, "or", true, (OP_ALU_OP | MK_CODE(ALU_OP_T_OR_N) | MK_DSTACK(DELTA_N1)))\
X(DEPTH, "sp@", true, (OP_ALU_OP | MK_CODE(ALU_OP_DEPTH) | T_TO_N | MK_DSTACK(DELTA_1)))\
X(T_N1, "1-", true, (OP_ALU_OP | MK_CODE(ALU_OP_T_DECREMENT)))\
X(IEN, "ien!", true, (OP_ALU_OP | MK_CODE(ALU_OP_ENABLE_INTERRUPTS) | MK_DSTACK(DELTA_N1)))\
X(ISIEN, "ien?", true, (OP_ALU_OP | MK_CODE(ALU_OP_INTERRUPTS_ENABLED) | T_TO_N | MK_DSTACK(DELTA_1)))\
X(RDEPTH, "rp@", true, (OP_ALU_OP | MK_CODE(ALU_OP_RDEPTH) | T_TO_N | MK_DSTACK(DELTA_1)))\
X(TE0, "0=", true, (OP_ALU_OP | MK_CODE(ALU_OP_T_EQUAL_0)))\
X(NOP, "nop", false, (OP_ALU_OP | MK_CODE(ALU_OP_T)))\
X(CPU_ID, "cpu-id", true, (OP_ALU_OP | MK_CODE(ALU_OP_CPU_ID)) | MK_DSTACK(DELTA_1))\
X(RUP, "rup", false, (OP_ALU_OP | MK_CODE(ALU_OP_T)) | MK_RSTACK(DELTA_1))\
X(DUPTOR, "dup>r", false, (OP_ALU_OP | MK_CODE(ALU_OP_T)) | T_TO_R | MK_RSTACK(DELTA_1))\
X(RDROP, "rdrop", true, (OP_ALU_OP | MK_CODE(ALU_OP_T) | MK_RSTACK(DELTA_N1)))
typedef enum {
#define X(NAME, STRING, DEFINE, INSTRUCTION) CODE_ ## NAME = INSTRUCTION,
X_MACRO_INSTRUCTIONS
#undef X
} forth_word_codes_e;
static const char *log_levels[] = {
#define X(ENUM, NAME) [ENUM] = NAME,
X_MACRO_LOGGING
#undef X
};
log_level_e log_level = LOG_WARNING;
typedef struct {
int error;
int jmp_buf_valid;
jmp_buf j;
} error_t;
/* ========================== Preamble: Types, Macros, Globals ============= */
/* ========================== Utilities ==================================== */
int logger(log_level_e level, const char *func, const unsigned line, const char *fmt, ...) {
int r = 0;
assert(func);
assert(fmt);
assert(level <= LOG_ALL_MESSAGES);
if (level <= log_level) {
va_list ap;
fprintf(stderr, "[%s %u] %s: ", func, line, log_levels[level]);
va_start(ap, fmt);
r = vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
fflush(stderr);
}
if (level == LOG_FATAL)
exit(EXIT_FAILURE);
return r;
}
static const char *reason(void) {
static const char *unknown = "unknown reason";
if (errno == 0)
return unknown;
const char *r = strerror(errno);
if (!r)
return unknown;
return r;
}
void *allocate_or_die(const size_t length) {
errno = 0;
void *r = calloc(1, length);
if (!r)
fatal("allocation of size %u failed: %s", (unsigned)length, reason());
return r;
}
FILE *fopen_or_die(const char *file, const char *mode) {
assert(file);
assert(mode);
errno = 0;
FILE *f = fopen(file, mode);
if (!f)
fatal("failed to open file '%s' (mode %s): %s", file, mode, reason());
return f;
}
static int string_to_long(const int base, long *n, const char *s) {
char *end = NULL;
assert(base >= 0);
assert(base != 1);
assert(base <= 36);
assert(n);
assert(s);
errno = 0;
*n = strtol(s, &end, base);
return errno || *s == '\0' || *end != '\0';
}
static int string_to_cell(int base, uint16_t *n, const char *s) {
long n1 = 0;
const int r = string_to_long(base, &n1, s);
*n = n1;
return r;
}
static char *duplicate(const char *str) {
assert(str);
const size_t length = strlen(str);
assert((length + 1) > length);
errno = 0;
char *r = malloc(length + 1);
if (!r)
fatal("duplicate of '%s' failed: %s", str, reason());
strcpy(r, str);
return r;
}
static void ethrow(error_t *e) {
if (e && e->jmp_buf_valid) {
e->jmp_buf_valid = 0;
e->error = 1;
longjmp(e->j, 1);
}
exit(EXIT_FAILURE);
}
h2_t *h2_new(const uint16_t start_address) {
h2_t *h = allocate_or_die(sizeof(h2_t));
h->pc = start_address;
for (uint16_t i = 0; i < start_address; i++)
h->core[i] = OP_BRANCH | start_address;
return h;
}
void h2_free(h2_t * const h) {
if (!h)
return;
free(h->bp.points);
memset(h, 0, sizeof(*h));
free(h);
}
int binary_memory_load(FILE *input, uint16_t *p, const size_t length) {
assert(input);
assert(p);
for (size_t i = 0; i < length; i++) {
errno = 0;
const int r1 = fgetc(input);
const int r2 = fgetc(input);
if (r1 < 0 || r2 < 0) {
debug("memory read failed: %s", strerror(errno));
return -1;
}
p[i] = (((unsigned)r1 & 0xffu)) | (((unsigned)r2 & 0xffu) << 8u);
}
return 0;
}
int binary_memory_save(FILE *output, const uint16_t * const p, const size_t length) {
assert(output);
assert(p);
for (size_t i = 0; i < length; i++) {
errno = 0;
const int r1 = fputc((p[i]) & 0xff,output);
const int r2 = fputc((p[i] >> 8u) & 0xff, output);
if (r1 < 0 || r2 < 0) {
debug("memory write failed: %s", strerror(errno));
return -1;
}
}
return 0;
}
int nvram_load_and_transfer(h2_io_t *io, const char *name, const bool transfer_to_sram) {
assert(io);
assert(name);
FILE *input = NULL;
int r = 0;
errno = 0;
if ((input = fopen(name, "rb"))) {
r = binary_memory_load(input, io->soc->flash.nvram, CHIP_MEMORY_SIZE);
if (transfer_to_sram)
memcpy(io->soc->vram, io->soc->flash.nvram, CHIP_MEMORY_SIZE);
fclose(input);
} else {
error("nvram file read (from %s) failed: %s", name, strerror(errno));
r = -1;
}
return r;
}
int nvram_save(h2_io_t *io, const char *name) {
FILE *output = NULL;
int r = 0;
assert(io);
assert(name);
errno = 0;
if ((output = fopen(name, "wb"))) {
r = binary_memory_save(output, io->soc->flash.nvram, CHIP_MEMORY_SIZE);
fclose(output);
} else {
error("nvram file write (to %s) failed: %s", name, strerror(errno));
r = -1;
}
return r;
}
int memory_load(FILE *input, uint16_t *p, const size_t length) {
assert(input);
assert(p);
char line[80] = {0}; /*more than enough!*/
size_t i = 0;
for (;fgets(line, sizeof(line), input); i++) {
int r;
if (i >= length) {
error("file contains too many lines: %u", (unsigned)i);
return -1;
}
r = string_to_cell(16, &p[i], line);
if (!r) {
error("invalid line - expected hex string: %s", line);
return -1;
}
debug("%u %u", (unsigned)i, (unsigned)p[i]);
}
return 0;
}
int memory_save(FILE *output, const uint16_t * const p, const size_t length) {
assert(output);
assert(p);
for (size_t i = 0; i < length; i++)
if (fprintf(output, "%04"PRIx16"\n", p[i]) < 0) {
error("failed to write line: %lu", (unsigned long)i);
return -1;
}
return 0;
}
int h2_load(h2_t *h, FILE *hexfile) {
assert(h);
assert(hexfile);
return memory_load(hexfile, h->core, MAX_CORE);
}
int h2_save(const h2_t * const h, FILE *output, const bool full) {
assert(h);
assert(output);
return memory_save(output, h->core, full ? MAX_CORE : h->pc);
}
/* From: https://stackoverflow.com/questions/215557/how-do-i-implement-a-circular-list-ring-buffer-in-c */
fifo_t *fifo_new(const size_t size) {
assert(size >= 2); /* It does not make sense to have a FIFO less than this size */
fifo_data_t *buffer = allocate_or_die(size * sizeof(buffer[0]));
fifo_t *fifo = allocate_or_die(sizeof(fifo_t));
fifo->buffer = buffer;
fifo->head = 0;
fifo->tail = 0;
fifo->size = size;
return fifo;
}
void fifo_free(fifo_t *fifo) {
if (!fifo)
return;
free(fifo->buffer);
free(fifo);
}
bool fifo_is_full(const fifo_t * const fifo) {
assert(fifo);
return (fifo->head == (fifo->size - 1) && fifo->tail == 0)
|| (fifo->head == (fifo->tail - 1));
}
bool fifo_is_empty(const fifo_t * const fifo) {
assert(fifo);
return fifo->head == fifo->tail;
}
size_t fifo_count(const fifo_t * const fifo) {
assert(fifo);
if (fifo_is_empty(fifo))
return 0;
else if (fifo_is_full(fifo))
return fifo->size;
else if (fifo->head < fifo->tail)
return fifo->head + (fifo->size - fifo->tail);
else
return fifo->head - fifo->tail;
}
size_t fifo_push(fifo_t * fifo, fifo_data_t data) {
assert(fifo);
if (fifo_is_full(fifo))
return 0;
fifo->buffer[fifo->head] = data;
fifo->head++;
if (fifo->head == fifo->size)
fifo->head = 0;
return 1;
}
size_t fifo_pop(fifo_t * fifo, fifo_data_t * data) {
assert(fifo);
assert(data);
if (fifo_is_empty(fifo))
return 0;
*data = fifo->buffer[fifo->tail];
fifo->tail++;
if (fifo->tail == fifo->size)
fifo->tail = 0;
return 1;
}
#ifdef __unix__
#include <unistd.h>
#include <termios.h>
static int getch(void) {
struct termios oldattr, newattr;
tcgetattr(STDIN_FILENO, &oldattr);
newattr = oldattr;
newattr.c_iflag &= ~(ICRNL);
newattr.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newattr);
const int ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldattr);
return ch;
}
static int putch(int c) {
int res = putchar(c);
fflush(stdout);
return res;
}
#else
#ifdef _WIN32
extern int getch(void);
extern int putch(int c);
#else
static int getch(void) {
return getchar();
}
static int putch(const int c) {
return putchar(c);
}
#endif
#endif /** __unix__ **/
static int wrap_getch(bool *debug_on) {
const int ch = getch();
assert(debug_on);
if (ch == EOF) {
note("End Of Input - exiting");
exit(EXIT_SUCCESS);
}
if (ch == ESCAPE && debug_on)
*debug_on = true;
return ch == DELETE ? BACKSPACE : ch;
}
/* ========================== Utilities ==================================== */
/* ========================== Symbol Table ================================= */
static const char *symbol_names[] = {
[SYMBOL_TYPE_LABEL] = "label",
[SYMBOL_TYPE_CALL] = "call",
[SYMBOL_TYPE_CONSTANT] = "constant",
[SYMBOL_TYPE_VARIABLE] = "variable",
NULL
};
static symbol_t *symbol_new(const symbol_type_e type, const char *id, const uint16_t value) {
symbol_t *s = allocate_or_die(sizeof(*s));
assert(id);
s->id = duplicate(id);
s->value = value;
s->type = type;
return s;
}
static void symbol_free(symbol_t *s) {
if (!s)
return;
free(s->id);
memset(s, 0, sizeof(*s));
free(s);
}
static symbol_table_t *symbol_table_new(void) {
symbol_table_t *t = allocate_or_die(sizeof(*t));
return t;
}
static void symbol_table_free(symbol_table_t *t) {
if (!t)
return;
for (size_t i = 0; i < t->length; i++)
symbol_free(t->symbols[i]);
free(t->symbols);
memset(t, 0, sizeof(*t));
free(t);
}
static symbol_t *symbol_table_lookup(const symbol_table_t * const t, const char *id) {
for (size_t i = 0; i < t->length; i++)
if (!strcmp(t->symbols[i]->id, id))
return t->symbols[i];
return NULL;
}
/** @note There can be multiple symbols with the same value of the same type */
static const symbol_t *symbol_table_reverse_lookup(const symbol_table_t * const t, const symbol_type_e type, const uint16_t value) {
for (size_t i = 0; i < t->length; i++)
if (t->symbols[i]->type == type && t->symbols[i]->value == value)
return t->symbols[i];
return NULL;
}
static int symbol_table_add(symbol_table_t *t, symbol_type_e type, const char *id, uint16_t value, error_t *e, bool hidden, bool used) {
symbol_t *s = symbol_new(type, id, value);
symbol_t **xs = NULL;
assert(t);
if (symbol_table_lookup(t, id)) {
symbol_free(s);
error("redefinition of symbol: %s", id);
if (e)
ethrow(e);
else
return -1;
}
s->hidden = hidden;
s->used = used;
t->length++;
errno = 0;
xs = realloc(t->symbols, sizeof(*t->symbols) * t->length);
if (!xs)
fatal("reallocate of size %u failed: %s", (unsigned)t->length, reason());
t->symbols = xs;
t->symbols[t->length - 1] = s;
return 0;
}
static int symbol_table_print(symbol_table_t *t, FILE *output) {
assert(t);
assert(output);
for (size_t i = 0; i < t->length; i++) {
symbol_t *s = t->symbols[i];
char *visibility = s->hidden ? "hidden" : "visible";
char *used = s->used ? "used" : "unused";
if (fprintf(output, "%s %s %"PRId16" %s %s\n", symbol_names[s->type], s->id, s->value, visibility, used) < 0)
return -1;
}
return 0;
}
symbol_table_t *symbol_table_load(FILE *input) {
assert(input);
symbol_table_t *t = symbol_table_new();
char symbol[80] = { 0 };
char id[256] = { 0 };
char visibility[80] = { 0 };
uint16_t value = false;
while (!feof(input)) {
int r = 0;
memset(symbol, 0, sizeof(symbol));
memset(id, 0, sizeof(id));
memset(visibility, 0, sizeof(visibility));
value = 0;
r = fscanf(input, "%79s%255s%"SCNu16"%79s", symbol, id, &value, visibility);
if (r != 4 && r > 0) {
error("invalid symbol table: %d", r);
goto fail;
}
if (r == 4) {
size_t i = 0;
bool hidden = false;
if (!strcmp(visibility, "hidden")) {
hidden = true;
}else if (!strcmp(visibility, "visible")) {
error("invalid visibility value: %s", visibility);
goto fail;
}
for (i = 0; symbol_names[i] && strcmp(symbol_names[i], symbol); i++)
/*do nothing*/;
if (symbol_names[i]) {
if (symbol_table_add(t, i, id, value, NULL, hidden, false) < 0)
goto fail;
} else {
error("invalid symbol: %s", symbol);
goto fail;
}
}
}
if (log_level >= LOG_DEBUG)
symbol_table_print(t, stderr);
return t;
fail:
symbol_table_free(t);
return NULL;
}
/* ========================== Symbol Table ================================= */
/* ========================== Disassembler ================================= */
static const char *instruction_to_string(const uint16_t i) {
switch (i) {
#define X(NAME, STRING, DEFINE, INSTRUCTION) case CODE_ ## NAME : return STRING ;
X_MACRO_INSTRUCTIONS
#undef X
default: break;
}
return NULL;
}
static const char *alu_op_to_string(const uint16_t instruction) {
switch (ALU_OP(instruction)) {
case ALU_OP_T: return "T";
case ALU_OP_N: return "N";
case ALU_OP_T_PLUS_N: return "T+N";
case ALU_OP_T_AND_N: return "T&N";
case ALU_OP_T_OR_N: return "T|N";
case ALU_OP_T_XOR_N: return "T^N";
case ALU_OP_T_INVERT: return "~T";
case ALU_OP_T_EQUAL_N: return "N=T";
case ALU_OP_N_LESS_T: return "T>N";
case ALU_OP_N_RSHIFT_T: return "N>>T";
case ALU_OP_T_DECREMENT: return "T-1";
case ALU_OP_R: return "R";
case ALU_OP_T_LOAD: return "[T]";
case ALU_OP_N_LSHIFT_T: return "N<<T";
case ALU_OP_DEPTH: return "depth";
case ALU_OP_N_ULESS_T: return "Tu>N";
case ALU_OP_ENABLE_INTERRUPTS: return "ien";
case ALU_OP_INTERRUPTS_ENABLED: return "ien?";
case ALU_OP_RDEPTH: return "rdepth";
case ALU_OP_T_EQUAL_0: return "0=";
case ALU_OP_CPU_ID: return "cpu-id";
case ALU_OP_LITERAL: return "literal";
default: return "unknown";
}
}
static char *disassembler_alu(const uint16_t instruction) {
char buf[256] = {0};
const char *r = instruction_to_string(OP_ALU_OP | instruction);
if (r)
return duplicate(r);
sprintf(buf, "%04x:%s:%s:%s:%s:%s:%u:%u",
(unsigned)instruction,
alu_op_to_string(instruction),
(instruction & T_TO_N) ? "T->N" : "",
(instruction & T_TO_R) ? "T->R" : "",
(instruction & N_TO_ADDR_T) ? "N->[T]" : "",
(instruction & R_TO_PC) ? "R->PC" : "",
(unsigned)(instruction & 0x000C),
(unsigned)(instruction & 0x0003));
return duplicate(buf);
}
static const char *disassemble_jump(const symbol_table_t * const symbols, const symbol_type_e type, const uint16_t address) {
if (!symbols)
return "";
const symbol_t * const found = symbol_table_reverse_lookup(symbols, type, address);
return found ? found->id : "";
}
#define CSI "\033["
#define ANSI_RESET (CSI "0m")
#define ANSI_BLACK (CSI "30m")
#define ANSI_RED (CSI "31m")
#define ANSI_GREEN (CSI "32m")
#define ANSI_YELLOW (CSI "33m")
#define ANSI_BLUE (CSI "34m")
#define ANSI_MAGENTA (CSI "35m")
#define ANSI_CYAN (CSI "36m")
#define ANSI_WHITE (CSI "37m")
typedef enum {
DCM_NONE,
DCM_X11,
DCM_ANSI,
DCM_MAX_DCM
} disassemble_color_method_e;
typedef enum {
DC_LITERAL,
DC_ALU,
DC_CALL,
DC_0BRANCH,
DC_BRANCH,
DC_ERROR, /* Invalid instruction */
DC_RESET, /* Reset color */
} decompilation_color_e;
static int disassemble_instruction(const uint16_t instruction, FILE *output, const symbol_table_t * const symbols, const disassemble_color_method_e dcm) {
int r = 0;
char *s = NULL;
assert(output);
assert(dcm < DCM_MAX_DCM);
static const char *colors[3][7] = { /* for colorizing decompilation stream with in-band signalling */
/* LITERAL ALU CALL 0BRANCH BRANCH ERROR RESET */
[DCM_NONE] = { "", "", "", "", "", "", "" }, /* No-Color */
[DCM_X11] = { "?HotPink?", "?SkyBlue?", "?GreenYellow?", "?Khaki?", "?MediumTurquoise?", "?FireBrick?", "" }, /* X11/GTKWave */
[DCM_ANSI] = { ANSI_MAGENTA, ANSI_BLUE, ANSI_GREEN, ANSI_YELLOW, ANSI_CYAN, ANSI_RED, ANSI_RESET }, /* ANSI Escape Sequences */
};
const char **color = colors[dcm];
const unsigned short literal = instruction & 0x7FFF;
const unsigned short address = instruction & 0x1FFF;
if (IS_LITERAL(instruction))
r = fprintf(output, "%s%hx%s", color[DC_LITERAL], literal, color[DC_RESET]);
else if (IS_ALU_OP(instruction))
r = fprintf(output, "%s%s%s", color[DC_ALU], s = disassembler_alu(instruction), color[DC_RESET]);
else if (IS_CALL(instruction))
r = fprintf(output, "%scall%s %hx %s", color[DC_CALL], color[DC_RESET], address, disassemble_jump(symbols, SYMBOL_TYPE_CALL, address));
else if (IS_0BRANCH(instruction))
r = fprintf(output, "%s0branch%s %hx %s", color[DC_0BRANCH], color[DC_RESET], address, disassemble_jump(symbols, SYMBOL_TYPE_LABEL, address));
else if (IS_BRANCH(instruction))
r = fprintf(output, "%sbranch%s %hx %s", color[DC_BRANCH], color[DC_RESET], address, disassemble_jump(symbols, SYMBOL_TYPE_LABEL, address));
else
r = fprintf(output, "%s?(%hx)%s", color[DC_ERROR], instruction, color[DC_RESET]);
free(s);
return r < 0 ? -1 : 0;
}
int h2_disassemble(const disassemble_color_method_e dcm, FILE *input, FILE *output, const symbol_table_t * const symbols) {
assert(input);
assert(output);
assert(dcm < DCM_MAX_DCM);
while (!feof(input)) {
char line[80] = { 0 };
if (fscanf(input, "%79s", line) != 1)
return -1;
if (line[0]) {
uint16_t instruction = 0;
if (string_to_cell(16, &instruction, line)) {
error("invalid input to disassembler: %s", line);
return -1;
}
if (disassemble_instruction(instruction, output, symbols, dcm) < 0) {
error("disassembly failed");
return -1;
}
if (fputc('\n', output) != '\n') {
error("disassembly failed");
return -1;
}
fflush(output);
}
}
return 0;
}
/* ========================== Disassembler ================================= */
/* ========================== Simulation And Debugger ====================== */
/* @note At the moment I/O is not cycle accurate, the UART behaves as if reads
* and writes happen instantly, along with the PS/2 keyboard. Also the UART
* has a FIFO which is not simulated. It should be easy enough to delay for
* the roughly the right number of cycles, but not to get exact cycle
* accurate timing. */
static char to_char(const uint8_t c) {
return isprint(c) ? c : '.';
}
static void memory_print(FILE *out, const uint16_t start, const uint16_t * const p, const uint16_t length, const bool chars) {
const uint16_t line_length = 16;
assert(out);
assert(p);
for (uint16_t i = 0; i < length; i += line_length) {
fprintf(out, "%04"PRIx16 ": ", i + start);
for (uint16_t j = 0; j < line_length && j + i < length; j++)
fprintf(out, "%04"PRIx16 " ", p[j + i]);
fputc('\t', out);
if (chars) /* correct endianess? */
for (uint16_t j = 0; j < line_length && j + i < length; j++)
fprintf(out, "%c%c", to_char(p[j + i] >> 8), to_char(p[j + i]));
putc('\n', out);
}
putc('\n', out);
}
static bool break_point_find(const break_point_t * const bp, const uint16_t find_me) {
assert(bp);
for (size_t i = 0; i < bp->length; i++)
if (bp->points[i] == find_me)
return true;
return false;
}
static void break_point_add(break_point_t *bp, const uint16_t point) {
assert(bp);
if (break_point_find(bp, point))
return;
const size_t a = (bp->length + 1) * sizeof(bp->points[0]);
uint16_t *r = realloc(bp->points, a);
if (!r || a < bp->length)
fatal("realloc of size %u failed", (unsigned)a);
r[bp->length] = point;
bp->length++;
bp->points = r;
}
static int break_point_print(FILE *out, const break_point_t * const bp) {
assert(out);
assert(bp);
for (size_t i = 0; i < bp->length; i++)
if (fprintf(out, "\t0x%04"PRIx16 "\n", bp->points[i]) < 0)
return -1;
return 0;
}
#define LED_7_SEGMENT_DISPLAY_CHARSET_HEX "0123456789AbCdEF"
#define LED_7_SEGMENT_DISPLAY_CHARSET_BCD "0123456789 .- "
static char l7seg(const uint8_t c) {
static const char *v = LED_7_SEGMENT_DISPLAY_CHARSET_HEX;
return v[c & 0xf];
}
void soc_print(FILE *out, const h2_soc_state_t * const soc) {
assert(out);
assert(soc);
const unsigned char led0 = l7seg(soc->led_7_segments >> 12);
const unsigned char led1 = l7seg(soc->led_7_segments >> 8);
const unsigned char led2 = l7seg(soc->led_7_segments >> 4);
const unsigned char led3 = l7seg(soc->led_7_segments);
fprintf(out, "LEDS: %02"PRIx8"\n", soc->leds);
/*fprintf(out, "VGA Cursor: %04"PRIx16"\n", soc->vga_cursor);
fprintf(out, "VGA Control: %04"PRIx16"\n", soc->vga_control);*/
fprintf(out, "Timer Control: %04"PRIx16"\n", soc->timer_control);
fprintf(out, "Timer: %04"PRIx16"\n", soc->timer);
fprintf(out, "IRC Mask: %04"PRIx16"\n", soc->irc_mask);
fprintf(out, "UART Input: %02"PRIx8"\n", soc->uart_getchar_register);
fprintf(out, "LED 7 segment: %c%c%c%c\n", led0, led1, led2, led3);
fprintf(out, "Switches: %04"PRIx16"\n", soc->switches);
fprintf(out, "Waiting: %s\n", soc->wait ? "true" : "false");
fprintf(out, "Flash Control: %04"PRIx16"\n", soc->mem_control);
fprintf(out, "Flash Address Lo: %04"PRIx16"\n", soc->mem_addr_low);
fprintf(out, "Flash Data Out: %04"PRIx16"\n", soc->mem_dout);
fprintf(out, "UART TX Baud: %04"PRIx16"\n", soc->uart_tx_baud);
fprintf(out, "UART RX Baud: %04"PRIx16"\n", soc->uart_rx_baud);
fprintf(out, "UART Control: %04"PRIx16"\n", soc->uart_control);
}
static void terminal_default_command_sequence(vt100_t * const t) {
assert(t);
t->n1 = 1;
t->n2 = 1;
t->command_index = 0;
}
static void terminal_at_xy(vt100_t * const t, unsigned x, unsigned y, const bool limit_not_wrap) {
assert(t);
if (limit_not_wrap) {
x = MAX(x, 0);
y = MAX(y, 0);
x = MIN(x, t->width - 1);
y = MIN(y, t->height - 1);
} else {
x %= t->width;
y %= t->height;
}
t->cursor = (y * t->width) + x;
}
static int terminal_x_current(const vt100_t * const t) {
assert(t);
return t->cursor % t->width;
}
static int terminal_y_current(const vt100_t * const t) {
assert(t);
return t->cursor / t->width;
}
static void terminal_at_xy_relative(vt100_t *t, const int x, const int y, const bool limit_not_wrap) {
assert(t);
const int x_current = terminal_x_current(t);
const int y_current = terminal_y_current(t);
terminal_at_xy(t, x_current + x, y_current + y, limit_not_wrap);
}
static void terminal_parse_attribute(vt100_attribute_t * const a, const unsigned v) {
assert(a);
switch (v) {
case 0:
memset(a, 0, sizeof(*a));
a->foreground_color = WHITE;
a->background_color = BLACK;
return;
case 1: a->bold = true; return;
case 22: a->bold = false; return;
case 4: a->under_score = true; return;
case 5: a->blink = true; return;
case 25: a->blink = false; return;
case 7: a->reverse_video = true; return;
case 39: a->reverse_video = false; return;
case 8: a->conceal = true; return;
case 28: a->conceal = false; return;
default:
if (v >= 30 && v <= 37)
a->foreground_color = v - 30;
if (v >= 40 && v <= 47)
a->background_color = v - 40;
}
}
static const vt100_attribute_t vt100_default_attribute = {
.foreground_color = WHITE,
.background_color = BLACK,
};
static void terminal_attribute_block_set(vt100_t *t, const size_t size, const vt100_attribute_t * const a) {
assert(t);
assert(a);
for (size_t i = 0; i < size; i++)
memcpy(&t->attributes[i], a, sizeof(*a));
}
static int terminal_escape_sequences(vt100_t * const t, const uint8_t c) {
assert(t);
assert(t->state != TERMINAL_NORMAL_MODE);
switch (t->state) {
case TERMINAL_CSI: /* process CSI and some non-CSI Escape Only commands */
switch (c) {
case '[': t->state = TERMINAL_COMMAND; break;