-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.cpp
1441 lines (1330 loc) · 46 KB
/
main.cpp
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
/*
*--------------------------------------------------------------------
* Project: VM65 - Virtual Machine/CPU emulator programming
* framework.
*
* File: main.cpp
*
* Purpose: Define User Interface, Debug Console and main loop
* of the app.
*
* Date: 8/25/2016
*
* Copyright: (C) by Marek Karcz 2016. All rights reserved.
*
* Contact: [email protected]
*
* License Agreement and Warranty:
This software is provided with No Warranty.
I (Marek Karcz) will not be held responsible for any damage to
computer systems, data or user's health resulting from use.
Please proceed responsibly and exercise common sense.
This software is provided in hope that it will be useful.
It is free of charge for non-commercial and educational use.
Distribution of this software in non-commercial and educational
derivative work is permitted under condition that original
copyright notices and comments are preserved. Some 3-rd party work
included with this project may require separate application for
permission from their respective authors/copyright owners.
*--------------------------------------------------------------------
*/
#include <cstdlib>
#include <iostream>
#include <bitset>
#include <chrono>
#include <thread>
#include <string.h>
#include "system.h"
#include "MKCpu.h"
#include "Memory.h"
#include "Display.h"
#include "VMachine.h"
#include "GraphDisp.h"
#include "MemMapDev.h"
#include "ConsoleIO.h"
#include "MKGenException.h"
using namespace std;
using namespace MKBasic;
#define ANIM_DELAY 250
#define PROMPT_ADDR "Address (0..FFFF): "
#define PROMPT_START_ADDR "Start address (0..FFFF): "
#define PROMPT_RANGE_ADDR "Enter address range (0..0xFFFF).."
#define PROMPT_END_ADDR "End address (0..FFFF): "
const bool ClsIfDirty = true;
char diss_buf[DISS_BUF_SIZE]; // last disassembled instruction buffer
char curr_buf[DISS_BUF_SIZE]; // current disassembled instruction buffer
VMachine *pvm = NULL;
ConsoleIO *pconio = NULL;
Regs *preg = NULL;
bool ioecho = false, opbrk = false, needhelp = false;
bool loadbin = false, loadhex = false, reset = false, execvm = false;
int g_stackdisp_lines = 1;
string ramfile = "dummy.ram";
bool ShowRegs(Regs *preg, VMachine *pvm, bool ioecho, bool showiostat);
void ShowHelp();
void CmdArgHelp(string prgname);
void CopyrightBanner();
/*
*--------------------------------------------------------------------
* Method: PressEnter2Cont()
* Purpose: Print a message and wait for ENTER to be pressed.
* Arguments: msg - string : message
* Returns:
*--------------------------------------------------------------------
*/
void PressEnter2Cont(string msg)
{
string mesg = msg;
if (0 == msg.length()) mesg = "Press [ENTER]...";
cout << mesg;
fflush(stdin);
while (true) {
int c = getchar();
if ('\n' == c || EOF == c) break;
}
}
/*
*--------------------------------------------------------------------
* Method: RunSingleInstr()
* Purpose: Execute single instruction of the CPU (all cycles).
* Arguments: addr - unsigned short, instruction address
* Returns: pointer to CPU registers
*--------------------------------------------------------------------
*/
Regs *RunSingleInstr(unsigned short addr)
{
Regs *ret = NULL;
pvm->Disassemble(addr, diss_buf);
// skip # cycles per op-code specs
do {
ret = pvm->Step(addr);
} while (ret->CyclesLeft > 0);
// and now execute the actual op-code
ret = pvm->Step(addr);
pvm->Disassemble(ret->PtrAddr, curr_buf);
return ret;
}
/*
*--------------------------------------------------------------------
* Method: RunSingleCurrInstr()
* Purpose: Execute single instruction of the CPU (all cycles)
* at current address.
* Arguments: n/a
* Returns: pointer to CPU registers
*--------------------------------------------------------------------
*/
Regs *RunSingleCurrInstr()
{
Regs *ret = NULL;
pvm->Disassemble(preg->PtrAddr, diss_buf);
// skip # cycles per op-code specs
do {
ret = pvm->Step();
} while (ret->CyclesLeft > 0);
// and now execute the actual op-code
ret = pvm->Step();
pvm->Disassemble(ret->PtrAddr, curr_buf);
return ret;
}
/*
*--------------------------------------------------------------------
* Method: VMErr
* Purpose: Data structure and macros supporting VM errors
* messages
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
#define WARN_UNEXPECTED_EOF "WARNING: Unexpected EOF (image shorter than 64kB)."
#define WARN_NOHDR_BINIMG "WARNING: No header found in binary image."
#define WARN_HDRPRBLM_BINIMG "WARNING: Problem with binary image header."
struct VMErr {
int id;
char text1[80];
char text2[80];
} g_vmerrtbl[] = {
{MEMIMGERR_RAMBIN_EOF, WARN_UNEXPECTED_EOF, ""},
{MEMIMGERR_RAMBIN_OPEN, "WARNING: Unable to open memory image file.", ""},
{MEMIMGERR_RAMBIN_HDR, WARN_HDRPRBLM_BINIMG, ""},
{MEMIMGERR_RAMBIN_NOHDR, WARN_NOHDR_BINIMG, ""},
{MEMIMGERR_RAMBIN_HDRANDEOF, WARN_HDRPRBLM_BINIMG, WARN_UNEXPECTED_EOF},
{MEMIMGERR_RAMBIN_NOHDRANDEOF,WARN_NOHDR_BINIMG, WARN_UNEXPECTED_EOF},
{MEMIMGERR_INTELH_OPEN, "WARNING: Unable to open Intel HEX file.", ""},
{MEMIMGERR_INTELH_SYNTAX, "ERROR: Syntax error.", ""},
{MEMIMGERR_INTELH_FMT, "ERROR: Intel HEX format error.", ""},
{MEMIMGERR_VM65_OPEN, "ERROR: Unable to open memory definition file.", ""},
{MEMIMGERR_VM65_IGNPROCWRN, "WARNING: There were problems while processing memory definition file.", ""},
{VMERR_SAVE_SNAPSHOT, "WARNING: There was a problem saving memory snapshot.", ""},
{-1, "", ""}
};
/*
*--------------------------------------------------------------------
* Method: PrintVMErr()
* Purpose: Print the warning/error message.
* Arguments: err - integer, error code
* Returns: n/a
*--------------------------------------------------------------------
*/
void PrintVMErr(int err)
{
bool pressenter = false;
for (int i=0; g_vmerrtbl[i].id >= 0; i++) {
if (g_vmerrtbl[i].id == err) {
pressenter = true;
if (strlen(g_vmerrtbl[i].text1)) {
cout << g_vmerrtbl[i].text1 << endl;
}
if (strlen(g_vmerrtbl[i].text2)) {
cout << g_vmerrtbl[i].text2 << endl;
}
break;
}
}
if (pressenter) {
PressEnter2Cont("");
}
}
#if defined(LINUX)
#include <signal.h>
void trap_signal(int signum);
/*
*--------------------------------------------------------------------
* Method: trap_signal()
* Purpose: handle signal
* Arguments: signum - signal #
* Returns: n/a
*--------------------------------------------------------------------
*/
void trap_signal(int signum)
{
if (NULL != pconio) {
pconio->CloseCursesScr();
}
if (NULL != pvm && NULL != preg) {
pvm->SetOpInterrupt(true);
opbrk = true;
}
cout << "Signal caught: " << dec << signum << endl;
return;
}
/*
*--------------------------------------------------------------------
* Method: reset_terminal_mode()
* Purpose: Close curses window.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void reset_terminal_mode()
{
if (NULL != pconio) pconio->CloseCursesScr();
cout << "Thank you for using VM65." << endl;
}
#endif // #if defined(LINUX)
#if defined(WINDOWS)
#include <windows.h>
BOOL CtrlHandler(DWORD fdwCtrlType);
/*
*--------------------------------------------------------------------
* Method: CtrlHandler()
* Purpose: handle signal
* Arguments: fdwCtrlType - event type
* Returns: BOOL - TRUE if event handled, FALSE if needs further
* processing.
*--------------------------------------------------------------------
*/
BOOL CtrlHandler(DWORD fdwCtrlType)
{
switch( fdwCtrlType )
{
case CTRL_C_EVENT:
if (NULL != pvm && NULL != preg) {
pvm->SetOpInterrupt(true);
opbrk = true;
}
return TRUE;
case CTRL_CLOSE_EVENT:
cout << "Ctrl-Close event" << endl;
return TRUE ;
case CTRL_BREAK_EVENT:
if (NULL != pvm && NULL != preg) {
pvm->SetOpInterrupt(true);
opbrk = true;
}
return TRUE;
case CTRL_LOGOFF_EVENT:
cout << "Ctrl-Logoff event" << endl;
return FALSE;
case CTRL_SHUTDOWN_EVENT:
Beep( 750, 500 );
cout << "Ctrl-Shutdown event" << endl;
return FALSE;
default:
return FALSE;
}
}
#endif
/*
*--------------------------------------------------------------------
* Method: PromptNewAddress()
* Purpose: Prompt user to enter 16-bit address (hex) in console.
* Arguments: prompt - prompt text
* Returns: unsigned int - address entered by user
*--------------------------------------------------------------------
*/
unsigned int PromptNewAddress(string prompt)
{
unsigned int newaddr = 0x10000;
while (newaddr > 0xFFFF) {
cout << prompt;
cin >> hex >> newaddr;
}
return newaddr;
}
/*
*--------------------------------------------------------------------
* Thank you stackoverflow.com.
* http://stackoverflow.com/questions/111928/
* is-there-a-printf-converter-to-print-in-binary-format
*--------------------------------------------------------------------
*/
#define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
#define BYTETOBINARY(byte) \
(byte & 0x80 ? 1 : 0), \
(byte & 0x40 ? 1 : 0), \
(byte & 0x20 ? 1 : 0), \
(byte & 0x10 ? 1 : 0), \
(byte & 0x08 ? 1 : 0), \
(byte & 0x04 ? 1 : 0), \
(byte & 0x02 ? 1 : 0), \
(byte & 0x01 ? 1 : 0)
/*
*--------------------------------------------------------------------
* Method: ShowRegs()
* Purpose: Display status of CPU registers on DOS console.
* Arguments: preg - pointer to registers structure
* pvm - pointer to VM
* ioaddr - address setup for char I/O emulation
* ioecho - local I/O echo flag
* showiostat - if true, I/O emulation status is shown
* Returns: boolean - true if the stack pointer was longer than
* 15 (the screen must be cleared).
*--------------------------------------------------------------------
*/
bool ShowRegs(Regs *preg, VMachine *pvm, bool ioecho, bool showiostat)
{
bool ret = false;
char sBuf[80] = {0};
sprintf(sBuf, "| PC: $%04x | Acc: $%02x (" BYTETOBINARYPATTERN
") | X: $%02x | Y: $%02x |",
preg->PtrAddr, preg->Acc, BYTETOBINARY(preg->Acc),
preg->IndX, preg->IndY);
cout << "*-------------*-----------------------*----------*----------*";
cout << endl;
cout << sBuf << endl;
cout << "*-------------*-----------------------*----------*----------*";
cout << endl;
cout << "| NV-BDIZC |";
cout << " : " << diss_buf << " " << endl;
cout << "| " << bitset<8>((int)preg->Flags) << " |";
cout << " : " << curr_buf << " " << endl;
cout << "*-------------*" << endl;
cout << endl;
cout << "Stack: $" << hex << (unsigned short)preg->PtrStack << " " << endl;
cout << " ";
cout << " \r";
// display stack contents
cout << " [";
int j = 0, stacklines = 1;
for (unsigned int addr = 0x0101 + preg->PtrStack; addr < 0x0200; addr++) {
unsigned int hv = (unsigned int)pvm->MemPeek8bit(addr);
if (hv < 16) {
cout << 0;
}
cout << hex << hv << " ";
j++;
if (j > 15) {
cout << "]" << endl;
cout << " [";
j=0;
stacklines++;
}
}
cout << "] " << endl;
ret = (stacklines < g_stackdisp_lines);
g_stackdisp_lines = stacklines;
// end display stack contents
if (showiostat) {
cout << endl << "I/O status: ";
cout << (pvm->GetCharIOActive() ? "enabled" : "disabled") << ", ";
cout << " at: $" << hex << pvm->GetCharIOAddr() << ", ";
cout << " local echo: " << (ioecho ? "ON" : "OFF") << "." << endl;
cout << "Graphics status: ";
cout << (pvm->GetGraphDispActive() ? "enabled" : "disabled") << ", ";
cout << " at: $" << hex << pvm->GetGraphDispAddr() << endl;
cout << "ROM: ";
cout << ((pvm->IsROMEnabled()) ? "enabled." : "disabled.") << " ";
cout << "Range: $" << hex << pvm->GetROMBegin() << " - $";
cout << hex << pvm->GetROMEnd() << "." << endl;
cout << "Op-code execute history: ";
cout << (pvm->IsExecHistoryActive() ? "enabled" : "disabled");
cout << "." << endl;
}
cout << " \r";
return ret;
}
/*
*--------------------------------------------------------------------
* Method: ShowMenu()
* Purpose: Print available commands on the console.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void ShowMenu()
{
cout << "------------------------------------+----------------------------------------" << endl;
cout << " C - continue, S - step | A - set address for next step" << endl;
cout << " G - go/cont. from new address | N - go number of steps, P - IRQ" << endl;
cout << " I - toggle char I/O emulation | X - execute from new address" << endl;
cout << " T - show I/O console | B - blank (clear) screen" << endl;
cout << " E - toggle I/O local echo | F - toggle registers animation" << endl;
cout << " J - set animation delay | M - dump memory, W - write memory" << endl;
cout << " K - toggle ROM emulation | R - show registers, Y - snapshot" << endl;
cout << " L - load memory image | O - display op-code exec. history" << endl;
cout << " D - disassemble code in memory | Q - quit, 0 - reset, H - help" << endl;
cout << " V - toggle graphics emulation | U - enable/disable exec. history" << endl;
cout << " Z - enable/disable debug traces | 1 - enable/disable perf. stats" << endl;
cout << " 2 - display debug traces | ? - show this menu" << endl;
cout << "------------------------------------+----------------------------------------" << endl;
}
/*
*--------------------------------------------------------------------
* Method: RunSteps()
* Purpose: Execute multiple steps of CPU emulation.
* Arguments:
* step - boolean flag, true if step by step mode
* nsteps - # if steps
* brk - current status of break flag
* preg - pointer to CPU registers
* stct - step counter
* pvm - pointer to VM
* lrts - status of last RTS flag
* anim - boolean flag, true - registers animation mode
* delay - delay for anim mode
*
* Returns: n/a
*--------------------------------------------------------------------
*/
inline void RunSteps(bool step,
int nsteps,
bool brk,
Regs *preg,
int stct,
VMachine *pvm,
bool lrts,
bool anim,
int delay)
{
bool cls = false;
brk = preg->SoftIrq;
lrts = preg->LastRTS;
while(step && nsteps > 1 && !brk && !lrts && !opbrk) {
preg = RunSingleCurrInstr();
cout << "addr: $" << hex << preg->PtrAddr << ", step: " << dec << stct;
cout << " \r";
if (anim) {
if (cls & ClsIfDirty) { pvm->ClearScreen(); cls = false; }
pvm->ScrHome();
cls = ShowRegs(preg,pvm,false,false);
cout << endl;
this_thread::sleep_for(chrono::milliseconds(delay));
}
brk = preg->SoftIrq;
lrts = preg->LastRTS;
nsteps--;
stct++;
}
}
/*
*--------------------------------------------------------------------
* Method: ShowSpeedStats()
* Purpose:
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void ShowSpeedStats()
{
if (pvm->IsPerfStatsActive()) {
cout << endl;
cout << dec;
cout << "CPU emulation speed stats: " << endl;
cout << "|-> Average speed based on 1MHz CPU: " << pvm->GetPerfStats().perf_onemhz << " %" << endl;
cout << "|-> Last measured # of cycles exec.: " << pvm->GetPerfStats().prev_cycles << endl;
cout << "|-> Last measured time of execution: " << pvm->GetPerfStats().prev_usec << " usec" << endl;
cout << endl;
} else {
cout << endl;
cout << "Emulation performance stats is OFF." << endl;
cout << endl;
}
}
/*
*--------------------------------------------------------------------
* Method: ExecHistory()
* Purpose: Display history of executed VM65 code in assembly
* mnemonics format.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void ExecHistory()
{
if (pvm->IsExecHistoryActive()) {
queue<string> exechist(pvm->GetExecHistory());
cout << "PC : INSTR ACC | X | Y | PS | SP";
cout << endl;
cout << "------------------------------------+-----+-----+-----+-----";
cout << endl;
while (exechist.size()) {
cout << exechist.front() << endl;
exechist.pop();
}
} else {
cout << "Sorry. Op-code execute history is currently disabled." << endl;
}
}
/*
*--------------------------------------------------------------------
* Method: LoadImage()
* Purpose: Load memory image from file. Set new execute address.
* Arguments: newaddr - current execute address
* Returns: unsigned int - new execute address
*--------------------------------------------------------------------
*/
unsigned int LoadImage(unsigned int newaddr)
{
char typ = 0;
for (char c = tolower(typ);
c != 'a' && c != 'b' && c != 'h' && c != 'd';
c = tolower(typ)) {
cout << "Type (A - auto/B - binary/H - Intel HEX/D - definition): ";
cin >> typ;
}
cout << " [";
switch (tolower(typ)) {
case 'a': cout << "auto"; break;
case 'b': cout << "binary"; break;
case 'h': cout << "Intel HEX"; break;
case 'd': cout << "definition"; break;
default: break; // should never happen
}
cout << "]" << endl;
string name;
cout << "Memory Image File Name: ";
cin >> name;
cout << " [" << name << "]" << endl;
if (typ == 'b') PrintVMErr (pvm->LoadRAMBin(name));
else if (typ == 'h') PrintVMErr (pvm->LoadRAMHex(name));
else if (typ == 'd') {
PrintVMErr (pvm->LoadRAMDef(name));
if (pvm->IsAutoExec()) execvm = true;
if (newaddr == 0) newaddr = 0x10000;
}
else { // automatic file format detection
pvm->LoadRAM(name);
if (pvm->IsAutoExec()) execvm = true;
if (newaddr == 0) newaddr = 0x10000;
}
PrintVMErr(pvm->GetLastError());
return newaddr;
}
/*
*--------------------------------------------------------------------
* Method: ToggleIO()
* Purpose:
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
unsigned int ToggleIO(unsigned int ioaddr)
{
if (pvm->GetCharIOActive()) {
pvm->DisableCharIO();
cout << "I/O deactivated." << endl;
} else {
ioaddr = PromptNewAddress(PROMPT_ADDR);
cout << " [" << hex << ioaddr << "]" << endl;
pvm->SetCharIO(ioaddr, ioecho);
cout << "I/O activated." << endl;
}
return ioaddr;
}
/*
*--------------------------------------------------------------------
* Method: ToggleGrDisp()
* Purpose:
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
unsigned int ToggleGrDisp(unsigned int graddr)
{
if (pvm->GetGraphDispActive()) {
pvm->DisableGraphDisp();
cout << "Graphics display deactivated." << endl;
} else {
graddr = PromptNewAddress(PROMPT_ADDR);
cout << " [" << hex << graddr << "]" << endl;
pvm->SetGraphDisp(graddr);
cout << "Graphics display activated." << endl;
}
return graddr;
}
/*
*--------------------------------------------------------------------
* Method: WriteToMemory()
* Purpose: Take user input and write to memory.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void WriteToMemory()
{
unsigned int tmpaddr = PromptNewAddress(PROMPT_ADDR);
cout << " [" << hex << tmpaddr << "]" << endl;
cout << "Enter hex bytes [00..FF] values separated with NL or spaces, end with [100]:" << endl;
unsigned short v = 0;
while (true) {
cin >> hex >> v;
cout << " " << hex << v;
if (v > 0xFF) break;
pvm->MemPoke8bit(tmpaddr++, v & 0xFF);
};
cout << endl;
}
/*
*--------------------------------------------------------------------
* Method: DisassembleMemory()
* Purpose: Disassemble machine code in memory to symbolic format.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void DisassembleMemory()
{
unsigned int addrbeg = 0x10000, addrend = 0x10000;
cout << PROMPT_RANGE_ADDR << endl;
addrbeg = PromptNewAddress(PROMPT_START_ADDR);
cout << " [" << hex << addrbeg << "]" << endl;
addrend = PromptNewAddress(PROMPT_END_ADDR);
cout << " [" << hex << addrend << "]" << endl;
cout << endl;
for (unsigned int addr = addrbeg; addr <= addrend;) {
char instrbuf[DISS_BUF_SIZE];
addr = pvm->Disassemble((unsigned short)addr, instrbuf);
cout << instrbuf << endl;
}
}
/*
*--------------------------------------------------------------------
* Method: DumpMemory()
* Purpose: Display contents of memory, range entered by user.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void DumpMemory()
{
unsigned int addrbeg = 0x10000, addrend = 0x10000;
cout << PROMPT_RANGE_ADDR << endl;
addrbeg = PromptNewAddress(PROMPT_START_ADDR);
cout << " [" << hex << addrbeg << "]" << endl;
addrend = PromptNewAddress(PROMPT_END_ADDR);
cout << " [" << hex << addrend << "]" << endl;
cout << endl;
for (unsigned int addr = addrbeg; addr <= addrend; addr+=16) {
cout << "\t|";
for (unsigned int j=0; j < 16; j++) {
unsigned int hv = (unsigned int)pvm->MemPeek8bit(addr+j);
if (hv < 16) {
cout << 0;
}
cout << hex << hv << " ";
}
cout << "|";
for (int j=0; j < 16; j++) {
char cc = (char)pvm->MemPeek8bit(addr+j);
if (isprint(cc))
cout << cc;
else
cout << "?";
}
cout << '\r';
cout << hex << addr;
cout << endl;
}
}
/*
*--------------------------------------------------------------------
* Method: ToggleDebugTraces()
* Purpose: Enable/disable debug traces.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void ToggleDebugTraces()
{
if (pvm->IsDebugTraceActive()) {
pvm->DisableDebugTrace();
cout << "Debug traces disabled." << endl;
} else {
pvm->EnableDebugTrace();
cout << "Debug traces enabled." << endl;
}
}
/*
*--------------------------------------------------------------------
* Macro: SCRDIV_xxCOL
* Purpose: Print line out of xx '-' signs, no NL.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
#define SCRDIV_20COL cout << "--------------------";
#define SCRDIV_19COL cout << "-------------------";
#define SCRDIV_79COL SCRDIV_20COL; SCRDIV_20COL; SCRDIV_20COL; SCRDIV_19COL;
/*
*--------------------------------------------------------------------
* Method: DebugTraces()
* Purpose: Show debug traces.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void DebugTraces()
{
if (pvm->IsDebugTraceActive()) {
queue<string> dbgtrc(pvm->GetDebugTraces());
cout << "Time [usec] : Message" << endl;
SCRDIV_79COL; cout << endl;
int n=0;
while (dbgtrc.size()) {
cout << dbgtrc.front() << endl;
dbgtrc.pop();
if (n++ == 20) {
n = 0;
cout << endl;
PressEnter2Cont("Press [ENTER] for more...");
cout << endl;
}
}
SCRDIV_79COL; cout << endl;
} else {
cout << "Sorry. Debug traces are currently disabled." << endl;
}
}
/*
*--------------------------------------------------------------------
* Method: TogglePerfStats()
* Purpose: Enable/disable performance stats.
* Arguments:
* Returns:
*--------------------------------------------------------------------
*/
void TogglePerfStats()
{
if (pvm->IsPerfStatsActive()) {
pvm->DisablePerfStats();
cout << "Performance stats were disabled." << endl;
} else {
pvm->EnablePerfStats();
cout << "Performance stats were enabled." << endl;
}
}
/*
*--------------------------------------------------------------------
* Method: LoadArgs()
* Purpose: Parse command line arguments.
* Arguments: int argc, char *argv[], standard C command line args.
* Returns: n/a
*--------------------------------------------------------------------
*/
void LoadArgs(int argc, char *argv[])
{
for (int i=1; i<argc; i++) {
if (!strcmp(argv[i], "-r")) {
reset = true;
execvm = true;
} else if (!strcmp(argv[i], "-b")) {
loadbin = true;
} else if (!strcmp(argv[i], "-x")) {
loadhex = true;
} else if (!strcmp(argv[i], "-h")) {
needhelp = true;
} else {
ramfile = argv[i];
}
}
}
/************ corrected in makefile
// Quick and dirty SDL2 workaround to 'undefined reference to WinMain'
#ifdef main
#undef main
#endif
*****************/
/*
*--------------------------------------------------------------------
* Method: main()
* Purpose: Application entry point/main loop.
* Arguments: int argc, char *argv[], standard C command line args.
* Returns: int - general principle is to return 0 if OK, non-zero
* otherwise
*--------------------------------------------------------------------
*/
int main(int argc, char *argv[]) {
#if defined(LINUX)
signal(SIGINT, trap_signal);
signal(SIGTERM, trap_signal);
if (atexit(reset_terminal_mode)) {
cout << "WARNING: Can't set exit function." << endl;
PressEnter2Cont("");
}
#endif
#if defined(WINDOWS)
SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE );
#endif
pconio = new ConsoleIO();
if (NULL == pconio) throw MKGenException("Out of memory - ConsoleIO");
pconio->InitCursesScr();
pconio->CloseCursesScr();
string romfile("dummy.rom");
LoadArgs(argc, argv);
if (needhelp) { CmdArgHelp(argv[0]); exit(0); }
if (loadbin && loadhex) {
cout << "ERROR: Can't load both formats at the same time." << endl;
exit(-1);
}
try {
cout << endl;
if (loadbin) {
pvm = new VMachine(romfile, "dummy.ram");
if (NULL != pvm) {
PrintVMErr (pvm->LoadRAMBin(ramfile));
if (!reset) { reset = execvm = pvm->IsAutoReset(); }
}
} else if (loadhex) {
pvm = new VMachine(romfile, "dummy.ram");
if (NULL != pvm) PrintVMErr (pvm->LoadRAMHex(ramfile));
}
else {
pvm = new VMachine(romfile, ramfile);
if (NULL != pvm) PrintVMErr(pvm->GetLastError());
if (NULL != pvm && !reset) { reset = execvm = pvm->IsAutoReset(); }
}
if (NULL == pvm) {
throw MKGenException("Out of memory - VMachine");
}
pvm->ClearScreen();
CopyrightBanner();
string cmd;
bool runvm = false, step = false, brk = false, execaddr = false, stop = true;
bool lrts = false, anim = false, enrom = pvm->IsROMEnabled(), show_menu = true;
unsigned int newaddr = pvm->GetRunAddr(), ioaddr = pvm->GetCharIOAddr();
unsigned int graddr = pvm->GetGraphDispAddr();
unsigned int rombegin = pvm->GetROMBegin(), romend = pvm->GetROMEnd(), delay = ANIM_DELAY;
int nsteps = 0;
if (pvm->IsAutoExec()) {
execvm = true;
}
if (newaddr == 0) newaddr = 0x10000;
bool bloop = true;
while (bloop) {
preg = pvm->GetRegs();
if (runvm) {
if (anim) pvm->ClearScreen();
int stct = 1;
if (execaddr) {
preg = ((step) ? RunSingleInstr(newaddr) : pvm->Run(newaddr));
RunSteps(step,nsteps,brk,preg,stct,pvm,lrts,anim,delay);
execaddr = false;
} else {
preg = ((step) ? RunSingleCurrInstr() : pvm->Run());
RunSteps(step,nsteps,brk,preg,stct,pvm,lrts,anim,delay);
}
pconio->InitCursesScr();
pconio->CloseCursesScr();
if (step)
cout << "\rExecuted " << dec << stct << ((stct == 1) ? " step." : " steps.") << " " << endl;
nsteps = 0;
runvm = step = false;
newaddr = 0x10000;
} else if (execvm) {
if (reset) {
pvm->Reset();
preg = pvm->GetRegs();
reset = false;
} else {
preg = (execaddr ? pvm->Exec(newaddr) : pvm->Exec());
}
execvm = false;
execaddr = false;
brk = preg->SoftIrq;
lrts = preg->LastRTS;
newaddr = 0x10000;
}
pconio->InitCursesScr();
pconio->CloseCursesScr();
if (brk || opbrk || stop || lrts) {
pvm->ClearScreen();
pvm->ShowIO();
cout << endl;
if (opbrk) {
cout << "Interrupted at " << hex << preg->PtrAddr << endl;
} else if (brk) {
cout << "BRK at " << hex << preg->PtrAddr << endl;
} else if (lrts) {
cout << "FINISHED at " << hex << ((newaddr > 0xFFFF) ? preg->PtrAddr : newaddr) << endl;
} else if (stop) {
cout << "STOPPED at " << hex << ((newaddr > 0xFFFF) ? preg->PtrAddr : newaddr) << endl;
}
ShowSpeedStats();
opbrk = brk = stop = lrts = false;
pvm->SetOpInterrupt(false);
ShowRegs(preg,pvm,ioecho,true);
show_menu = true;
}
if (show_menu) {
ShowMenu();
show_menu = false;
} else {
cout << endl;
cout << "Type '?' and press [ENTER] for Menu ..." << endl;
cout << endl;
}
cout << "> ";
cin >> cmd;
char c = tolower(cmd.c_str()[0]);
// Interpret and execute user input / commands.
switch (c) {
case '?': show_menu = true;
break;
// display help
case 'h': ShowHelp();