forked from makarcz/vm6502
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VMachine.cpp
1931 lines (1809 loc) · 52.3 KB
/
VMachine.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: VMachine.cpp
*
* Purpose: Implementation of VMachine class.
* The VMachine class implements the Virtual Machine
* in its entirety. It creates all the objects that
* emulate the component's of the whole system and
* implements the methods to execute the code on the
* emulated platform.
*
* 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 apply 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 <stdio.h>
#include <iostream>
#include <sstream>
#include <string.h>
#include "system.h"
#include "VMachine.h"
#include "MKGenException.h"
using namespace std;
namespace MKBasic {
/*
*--------------------------------------------------------------------
* Method: VMachine()
* Purpose: Default class constructor.
* Arguments: n/a
* Returns: n/a
*--------------------------------------------------------------------
*/
VMachine::VMachine()
{
InitVM();
}
/*
*--------------------------------------------------------------------
* Method: VMachine()
* Purpose: Custom class constructor.
* Arguments: romfname - name of the ROM definition file
* ramfname - name of the RAM definition file
* Returns: n/a
*--------------------------------------------------------------------
*/
VMachine::VMachine(string romfname, string ramfname)
{
InitVM();
LoadROM(romfname);
LoadRAM(ramfname);
}
/*
*--------------------------------------------------------------------
* Method: ~VMachine()
* Purpose: Class destructor.
* Arguments: n/a
* Returns: n/a
*--------------------------------------------------------------------
*/
VMachine::~VMachine()
{
delete mpCPU;
delete mpROM;
delete mpRAM;
delete mpConIO;
}
/*
*--------------------------------------------------------------------
* Method: InitVM()
* Purpose: Initialize class.
* Arguments: n/a
* Returns: n/a
f *--------------------------------------------------------------------
*/
void VMachine::InitVM()
{
mOpInterrupt = false;
mpRAM = new Memory();
mPerfStats.cycles = 0;
mPerfStats.perf_onemhz = 0;
mPerfStats.prev_cycles = 0;
mPerfStats.prev_usec = 0;
mOldStyleHeader = false;
mError = VMERR_OK;
mAutoExec = false;
mAutoReset = false;
mCharIOAddr = CHARIO_ADDR;
mCharIOActive = mCharIO = false;
mGraphDispActive = false;
mPerfStatsActive = false;
mDebugTraceActive = false;
if (NULL == mpRAM) {
throw MKGenException("Unable to initialize VM (RAM).");
}
mRunAddr = mpRAM->Peek16bit(0xFFFC); // address under RESET vector
mpROM = new Memory();
if (NULL == mpROM) {
throw MKGenException("Unable to initialize VM (ROM).");
}
mpCPU = new MKCpu(mpRAM);
if (NULL == mpCPU) {
throw MKGenException("Unable to initialize VM (CPU).");
}
mpConIO = new ConsoleIO();
if (NULL == mpConIO) {
throw MKGenException("Unable to initialize VM (ConsoleIO)");
}
mBeginTime = high_resolution_clock::now();
}
/*
*--------------------------------------------------------------------
* Method: ClearScreen()
* Purpose: Clear the working are of the VM - DOS.
* This is not a part of virtual display emulation.
* Arguments: n/a
* Returns: n/a
*--------------------------------------------------------------------
*/
void VMachine::ClearScreen()
{
mpConIO->ClearScreen();
}
/*
*--------------------------------------------------------------------
* Method: ScrHome()
* Purpose: Bring the console cursor to home position - DOS.
* This is not a part of virtual display emulation.
* Arguments: n/a
* Returns: n/a
*--------------------------------------------------------------------
*/
void VMachine::ScrHome()
{
mpConIO->ScrHome();
}
/*
*--------------------------------------------------------------------
* Method: ShowDisp()
* Purpose: Show the emulated virtual text display device contents.
* Arguments: n/a
* Returns: n/a
*--------------------------------------------------------------------
*/
void VMachine::ShowDisp()
{
if (mCharIOActive && NULL != mpDisp) {
ScrHome();
mpDisp->ShowScr();
}
}
/*
*--------------------------------------------------------------------
* Method: CalcCurrPerf()
* Purpose: Calculate CPU emulation performance based on 1 MHz model
* CPU.
* Arguments: n/a
* Returns: Integer, the % of speed as compared to 1 MHz CPU.
*--------------------------------------------------------------------
*/
int VMachine::CalcCurrPerf()
{
if (!mPerfStatsActive) return 0;
auto lap = high_resolution_clock::now();
long usec = duration_cast<microseconds>(lap-mPerfStats.begin_time).count();
if (usec > 0) {
int currperf = (int)(((double)mPerfStats.cycles / (double)usec) * 100.0);
if (mPerfStats.perf_onemhz == 0)
mPerfStats.perf_onemhz = currperf;
else
mPerfStats.perf_onemhz = (mPerfStats.perf_onemhz + currperf) / 2;
mPerfStats.prev_cycles = mPerfStats.cycles;
mPerfStats.prev_usec = usec;
mPerfStats.cycles = 0;
mPerfStats.begin_time = lap;
if (mDebugTraceActive) { // prepare and log some debug traces
stringstream sscp, ssap;
string msg, avgprf, curprf;
ssap << mPerfStats.perf_onemhz;
ssap >> avgprf;
sscp << currperf;
sscp >> curprf;
msg = "Perf. measured. Curr.: " + curprf + " %, Avg.: " + avgprf + " %";
AddDebugTrace(msg);
}
}
return mPerfStats.perf_onemhz;
}
/*
*--------------------------------------------------------------------
* Method: PERFSTAT_LAP (macro)
* Purpose: Calculate emulation performace at pre-defined interval
* of real time and clock ticks.
* Arguments: cycles - long : number of clock ticks executed so far
* begin - time_point<high_resolution_clock> : the moment
* when time measurement started
* Returns: n/a
* Remarks: Call inside emulation execute loop.
*--------------------------------------------------------------------
*/
#define PERFSTAT_LAP(cycles,begin) \
{ \
if (mPerfStatsActive && cycles%PERFSTAT_CYCLES == 0) { \
long usec = duration_cast<microseconds> \
(high_resolution_clock::now()-begin).count(); \
if (usec >= PERFSTAT_INTERVAL) CalcCurrPerf(); \
} \
}
/*
*--------------------------------------------------------------------
* Method: Run()
* Purpose: Run VM until software break instruction.
* Arguments: n/a
* Returns: Pointer to CPU registers and flags.
*--------------------------------------------------------------------
*/
Regs *VMachine::Run()
{
Regs *cpureg = NULL;
AddDebugTrace("Running code at: $" + Addr2HexStr(mRunAddr));
mOpInterrupt = false;
mpConIO->InitCursesScr();
ClearScreen();
ShowDisp();
mPerfStats.cycles = 0;
mPerfStats.begin_time = high_resolution_clock::now();
while (true) {
mPerfStats.cycles++;
cpureg = Step();
if (cpureg->CyclesLeft == 0 && mCharIO) ShowDisp();
if (cpureg->SoftIrq || mOpInterrupt) break;
PERFSTAT_LAP(mPerfStats.cycles,mPerfStats.begin_time);
}
CalcCurrPerf();
ShowDisp();
mpConIO->CloseCursesScr();
return cpureg;
}
/*
*--------------------------------------------------------------------
* Method: Run()
* Purpose: Run VM from specified address until software break
* instruction.
* Arguments: addr - start execution address
* Returns: Pointer to CPU registers and flags.
*--------------------------------------------------------------------
*/
Regs *VMachine::Run(unsigned short addr)
{
mRunAddr = addr;
return Run();
}
/*
*--------------------------------------------------------------------
* Method: Exec()
* Purpose: Run VM from current address until last RTS (if enabled).
* NOTE: Stack must be empty for last RTS to be trapped.
* Arguments: n/a
* Returns: Pointer to CPU registers and flags.
*--------------------------------------------------------------------
*/
Regs *VMachine::Exec()
{
Regs *cpureg = NULL;
AddDebugTrace("Executing code at: $" + Addr2HexStr(mRunAddr));
mOpInterrupt = false;
mpConIO->InitCursesScr();
ClearScreen();
ShowDisp();
mPerfStats.cycles = 0;
mPerfStats.begin_time = high_resolution_clock::now();
while (true) {
mPerfStats.cycles++;
cpureg = Step();
if (cpureg->LastRTS || mOpInterrupt) break;
PERFSTAT_LAP(mPerfStats.cycles,mPerfStats.begin_time);
}
CalcCurrPerf();
ShowDisp();
mpConIO->CloseCursesScr();
return cpureg;
}
/*
*--------------------------------------------------------------------
* Method: GetPerfStats()
* Purpose: Get performance stats data.
* Arguments:
* Returns: struct PerfStats
*--------------------------------------------------------------------
*/
PerfStats VMachine::GetPerfStats()
{
return mPerfStats;
}
/*
*--------------------------------------------------------------------
* Method: Exec()
* Purpose: Run VM from specified address until RTS.
* Arguments: addr - start execution address
* Returns: Pointer to CPU registers and flags.
*--------------------------------------------------------------------
*/
Regs *VMachine::Exec(unsigned short addr)
{
mRunAddr = addr;
return Exec();
}
/*
*--------------------------------------------------------------------
* Method: Step()
* Purpose: Execute single opcode.
* Arguments: n/a
* Returns: Pointer to CPU registers and flags.
*--------------------------------------------------------------------
*/
Regs *VMachine::Step()
{
Regs *cpureg = NULL;
cpureg = mpCPU->ExecOpcode(mRunAddr);
if (mGraphDispActive && cpureg->CyclesLeft == 0) {
mpRAM->GraphDisp_ReadEvents();
}
mRunAddr = cpureg->PtrAddr;
return cpureg;
}
/*
*--------------------------------------------------------------------
* Method: Step()
* Purpose: Execute single opcode.
* Arguments: addr (unsigned short) - opcode address
* Returns: Pointer to CPU registers and flags.
*--------------------------------------------------------------------
*/
Regs *VMachine::Step(unsigned short addr)
{
mRunAddr = addr;
return Step();
}
/*
*--------------------------------------------------------------------
* Method: LoadROM()
* Purpose: Load data from memory definition file to the memory.
* Arguments: romfname - name of the ROM file definition
* Returns: n/a
*--------------------------------------------------------------------
*/
void VMachine::LoadROM(string romfname)
{
LoadMEM(romfname, mpROM);
}
/*
*--------------------------------------------------------------------
* Method: LoadRAM()
* Purpose: Load data from memory definition file to the memory.
* Arguments: ramfname - name of the RAM file definition
* Returns: int - error code
*--------------------------------------------------------------------
*/
int VMachine::LoadRAM(string ramfname)
{
int err = 0;
eMemoryImageTypes memimg_type = GetMemoryImageType(ramfname);
switch (memimg_type) {
case MEMIMG_VM65DEF: err = LoadMEM(ramfname, mpRAM); break;
case MEMIMG_INTELHEX: err = LoadRAMHex(ramfname); break;
case MEMIMG_BIN:
default: // unknown type, try to read as binary
// and hope for the best
err = LoadRAMBin(ramfname);
break;
}
mError = err;
if (mDebugTraceActive && err) {
stringstream sserr;
string msg, strerr;
sserr << err;
sserr >> strerr;
msg = "ERROR: LoadRAM, error code: " + strerr;
AddDebugTrace(msg);
}
return err;
}
/*
*--------------------------------------------------------------------
* Method: GetMemoryImageType()
* Purpose: Detect format of memory image file.
* Arguments: ramfname - name of the RAM file definition
* Returns: eMemoryImageTypes - code of the memory image format
*--------------------------------------------------------------------
*/
eMemoryImageTypes VMachine::GetMemoryImageType(string ramfname)
{
eMemoryImageTypes ret = MEMIMG_UNKNOWN;
char buf[256] = {0};
FILE *fp = NULL;
int n = 0;
if ((fp = fopen(ramfname.c_str(), "rb")) != NULL) {
memset(buf, 0, 256);
while (0 == feof(fp) && 0 == ferror(fp)) {
unsigned char val = fgetc(fp);
buf[n++] = val;
if (n >= 256) break;
}
fclose(fp);
}
bool possibly_intelhex = true;
for (int i=0; i<256; i++) {
char *pc = buf+i;
if (isspace(buf[i])) continue;
if (i < 256-9 // 256 less the length of the longest expected keyword
&&
(!strncmp(pc, "ADDR", 4)
|| !strncmp(pc, "ORG", 3)
|| !strncmp(pc, "IOADDR", 6)
|| !strncmp(pc, "ROMBEGIN", 8)
|| !strncmp(pc, "ROMEND", 6)
|| !strncmp(pc, "ENROM", 5)
|| !strncmp(pc, "ENIO", 4)
|| !strncmp(pc, "EXEC", 4)
|| !strncmp(pc, "RESET", 5)
|| !strncmp(pc, "ENGRAPH", 7)
|| !strncmp(pc, "GRAPHADDR", 9))
)
{
ret = MEMIMG_VM65DEF;
break;
}
if (buf[i] != ':'
&& buf[i] != '0'
&& buf[i] != '1'
&& buf[i] != '2'
&& buf[i] != '3'
&& buf[i] != '4'
&& buf[i] != '5'
&& buf[i] != '6'
&& buf[i] != '7'
&& buf[i] != '8'
&& buf[i] != '9'
&& tolower(buf[i]) != 'a'
&& tolower(buf[i]) != 'b'
&& tolower(buf[i]) != 'c'
&& tolower(buf[i]) != 'd'
&& tolower(buf[i]) != 'e'
&& tolower(buf[i]) != 'f')
{
possibly_intelhex = false;
}
}
if (ret == MEMIMG_UNKNOWN && possibly_intelhex)
ret = MEMIMG_INTELHEX;
return ret;
}
/*
*--------------------------------------------------------------------
* Method: HasHdrData()
* Purpose: Check for header in the binary memory image.
* Arguments: File pointer.
* Returns: true if magic keyword found at the beginning of the
* memory image file, false otherwise
*--------------------------------------------------------------------
*/
bool VMachine::HasHdrData(FILE *fp)
{
bool ret = false;
int n = 0, l = strlen(HDRMAGICKEY);
char buf[20];
memset(buf, 0, 20);
rewind(fp);
while (0 == feof(fp) && 0 == ferror(fp)) {
unsigned char val = fgetc(fp);
buf[n] = val;
n++;
if (n >= l) break;
}
ret = (0 == strncmp(buf, HDRMAGICKEY, l));
AddDebugTrace(((ret) ? "HasHdrData: YES" : "HasHdrData: NO"));
return ret;
}
/*
*--------------------------------------------------------------------
* Method: HasOldHdrData()
* Purpose: Check for previous version header in the binary memory
* image.
* Arguments: File pointer.
* Returns: true if magic keyword found at the beginning of the
* memory image file, false otherwise
*--------------------------------------------------------------------
*/
bool VMachine::HasOldHdrData(FILE *fp)
{
bool ret = false;
int n = 0, l = strlen(HDRMAGICKEY_OLD);
char buf[20];
memset(buf, 0, 20);
rewind(fp);
while (0 == feof(fp) && 0 == ferror(fp)) {
unsigned char val = fgetc(fp);
buf[n] = val;
n++;
if (n >= l) break;
}
ret = (0 == strncmp(buf, HDRMAGICKEY_OLD, l));
AddDebugTrace(((ret) ? "HasOldHdrData: YES" : "HasOldHdrData: NO"));
return ret;
}
/*
*--------------------------------------------------------------------
* Method: LoadHdrData()
* Purpose: Load data from binary image header.
* Arguments: File pointer.
* Returns: bool, true if success, false if error
*
* Details:
* Header of the binary memory image consists of magic keyword
* string followed by the 128 bytes of data (unsigned char values).
* It has following format:
*
* MAGIC_KEYWORD
* aabbccddefghijklmm[remaining unused bytes]
*
* Where:
* MAGIC_KEYWORD - text string indicating header, may vary between
* versions thus rendering headers from previous
* versions incompatible - currently: "SNAPSHOT2"
* NOTE: Previous version of header is currently
* recognized and can be read, the magic
* keyword of previous version: "SNAPSHOT".
* Old header had only 15 bytes of data.
* This backwards compatibility will be
* removed in next version as the new
* format of header with 128 bytes for
* data leaves space for expansion without
* the need of changing file format.
* aa - low and hi bytes of execute address (PC)
* bb - low and hi bytes of char IO address
* cc - low and hi bytes of ROM begin address
* dd - low and hi bytes of ROM end address
* e - 0 if char IO is disabled, 1 if enabled
* f - 0 if ROM is disabled, 1 if enabled
* g - value in CPU Acc (accumulator) register
* h - value in CPU X (X index) register
* i - value in CPU Y (Y index) register
* j - value in CPU PS (processor status/flags)
* k - value in CPU SP (stack pointer) register
* l - 0 if generic graphics display device is disabled,
* 1 if graphics display is enabled
* mm - low and hi bytes of graphics display base address
*
* NOTE:
* If magic keyword was detected, this part is already read and file
* pointer position is at the 1-st byte of data. Therefore this
* method does not have to read and skip the magic keyword.
*--------------------------------------------------------------------
*/
bool VMachine::LoadHdrData(FILE *fp)
{
int n = 0, l = 0, hdrdtlen = HDRDATALEN;
unsigned short rb = 0, re = 0;
Regs r;
bool ret = false;
if (mOldStyleHeader) hdrdtlen = HDRDATALEN_OLD;
while (0 == feof(fp) && 0 == ferror(fp) && n < hdrdtlen) {
unsigned char val = fgetc(fp);
switch (n)
{
case 1: mRunAddr = l + 256 * val;
ADD_DBG_LDMEMPARHEX("LoadHdrData : mRunAddr",mRunAddr);
break;
case 3: mCharIOAddr = l + 256 * val;
ADD_DBG_LDMEMPARHEX("LoadHdrData : mCharIOAddr",mCharIOAddr);
break;
case 5: rb = l + 256 * val;
break;
case 7: re = l + 256 * val;
break;
case 8: mCharIOActive = (val != 0);
ADD_DBG_LDMEMPARVAL("LoadHdrData : mCharIOActive",mCharIOActive);
break;
case 9: if (val != 0) {
mpRAM->EnableROM(rb, re);
} else {
mpRAM->SetROM(rb, re);
}
ADD_DBG_LDMEMPARHEX("LoadHdrData : ROM begin",rb);
ADD_DBG_LDMEMPARHEX("LoadHdrData : ROM end",re);
ADD_DBG_LDMEMPARVAL("LoadHdrData : ROM enable",((val!=0)?1:0));
break;
case 10: r.Acc = val;
break;
case 11: r.IndX = val;
break;
case 12: r.IndY = val;
break;
case 13: r.Flags = val;
break;
case 14: r.PtrStack = val;
ret = true;
break;
case 15: mGraphDispActive = (val != 0);
ADD_DBG_LDMEMPARVAL("LoadHdrData : mGraphDispActive",mGraphDispActive);
break;
case 17: if (mGraphDispActive) SetGraphDisp(l + 256 * val);
else DisableGraphDisp();
ADD_DBG_LDMEMPARHEX("LoadHdrData : Graph. Disp. addr",(l + 256 * val));
break;
default: break;
}
l = val;
n++;
}
if (ret) {
r.PtrAddr = mRunAddr;
mpCPU->SetRegs(r);
}
return ret;
}
/*
*--------------------------------------------------------------------
* Method: SaveHdrData()
* Purpose: Save header data to binary file (memory snapshot).
* Arguments: File pointer, must be opened for writing in binary mode.
* Returns: n/a
*--------------------------------------------------------------------
*/
void VMachine::SaveHdrData(FILE *fp)
{
char buf[20] = {0};
int n = HDRDATALEN;
strcpy(buf, HDRMAGICKEY);
for (unsigned int i = 0; i < strlen(HDRMAGICKEY); i++) {
fputc(buf[i], fp);
}
Regs *reg = mpCPU->GetRegs();
unsigned char lo = 0, hi = 0;
lo = (unsigned char) (reg->PtrAddr & 0x00FF);
hi = (unsigned char) ((reg->PtrAddr & 0xFF00) >> 8);
SAVE_HDR_DATA(lo,fp,n);
SAVE_HDR_DATA(hi,fp,n);
lo = (unsigned char) (mCharIOAddr & 0x00FF);
hi = (unsigned char) ((mCharIOAddr & 0xFF00) >> 8);
SAVE_HDR_DATA(lo,fp,n);
SAVE_HDR_DATA(hi,fp,n);
lo = (unsigned char) (GetROMBegin() & 0x00FF);
hi = (unsigned char) ((GetROMBegin() & 0xFF00) >> 8);
SAVE_HDR_DATA(lo,fp,n);
SAVE_HDR_DATA(hi,fp,n);
lo = (unsigned char) (GetROMEnd() & 0x00FF);
hi = (unsigned char) ((GetROMEnd() & 0xFF00) >> 8);
SAVE_HDR_DATA(lo,fp,n);
SAVE_HDR_DATA(hi,fp,n);
lo = (mCharIOActive ? 1 : 0);
SAVE_HDR_DATA(lo,fp,n);
lo = (IsROMEnabled() ? 1 : 0);
SAVE_HDR_DATA(lo,fp,n);
Regs *pregs = mpCPU->GetRegs();
if (pregs != NULL) {
SAVE_HDR_DATA(pregs->Acc,fp,n);
SAVE_HDR_DATA(pregs->IndX,fp,n);
SAVE_HDR_DATA(pregs->IndY,fp,n);
SAVE_HDR_DATA(pregs->Flags,fp,n);
SAVE_HDR_DATA(pregs->PtrStack,fp,n);
}
lo = (mGraphDispActive ? 1 : 0);
SAVE_HDR_DATA(lo,fp,n);
lo = (unsigned char) (GetGraphDispAddr() & 0x00FF);
hi = (unsigned char) ((GetGraphDispAddr() & 0xFF00) >> 8);
SAVE_HDR_DATA(lo,fp,n);
SAVE_HDR_DATA(hi,fp,n);
// fill up the unused slots of header data with 0-s
for (int i = n; i > 0; i--) fputc(0, fp);
}
/*
*--------------------------------------------------------------------
* Method: SaveSnapshot()
* Purpose: Save current state of the VM and memory image.
* Arguments: String - file name.
* Returns: int, 0 if successful, greater then 0 if not (# of bytes
* not written).
*--------------------------------------------------------------------
*/
int VMachine::SaveSnapshot(string fname)
{
FILE *fp = NULL;
int ret = MAX_8BIT_ADDR+1;
if ((fp = fopen(fname.c_str(), "wb")) != NULL) {
SaveHdrData(fp);
for (int addr = 0; addr < MAX_8BIT_ADDR+1; addr++) {
if (addr != mCharIOAddr && addr != mCharIOAddr+1) {
unsigned char b = mpRAM->Peek8bitImg((unsigned short)addr);
if (EOF != fputc(b, fp)) ret--;
else break;
} else {
if (EOF != fputc(0, fp)) ret--;
else break;
}
}
fclose(fp);
}
if (0 != ret) mError = VMERR_SAVE_SNAPSHOT;
if (mDebugTraceActive && ret) {
stringstream sserr;
string msg, strerr;
sserr << ret;
sserr >> strerr;
msg = "ERROR: SaveSnapshot, error code: " + strerr;
AddDebugTrace(msg);
}
return ret;
}
/*
*--------------------------------------------------------------------
* Method: LoadRAMBin()
* Purpose: Load data from binary image file to the memory.
* Arguments: ramfname - name of the RAM file definition
* Returns: int - error code
* MEMIMGERR_OK - OK
* MEMIMGERR_RAMBIN_EOF
* - WARNING: Unexpected EOF (image shorter than 64kB).
* MEMIMGERR_RAMBIN_OPEN
* - WARNING: Unable to open memory image file.
* MEMIMGERR_RAMBIN_HDR
* - WARNING: Problem with binary image header.
* MEMIMGERR_RAMBIN_NOHDR
* - WARNING: No header found in binary image.
* MEMIMGERR_RAMBIN_HDRANDEOF
* - WARNING: Problem with binary image header and
* Unexpected EOF (image shorter than 64kB).
* MEMIMGERR_RAMBIN_NOHDRANDEOF
* - WARNING: No header found in binary image and
* Unexpected EOF (image shorter than 64kB).
* TO DO:
* - Add fixed size header to binary image with emulator
* configuration data. Presence of the header will be detected
* by magic key at the beginning. Header should also include
* snapshot info, so the program can continue from the place
* where it was frozen/saved.
*--------------------------------------------------------------------
*/
int VMachine::LoadRAMBin(string ramfname)
{
FILE *fp = NULL;
unsigned short addr = 0x0000;
int n = 0;
Memory *pm = mpRAM;
int ret = MEMIMGERR_RAMBIN_OPEN;
AddDebugTrace("LoadRAMBin : " + ramfname);
mOldStyleHeader = false;
if ((fp = fopen(ramfname.c_str(), "rb")) != NULL) {
if (HasHdrData(fp) || (mOldStyleHeader = HasOldHdrData(fp))) {
ret = (LoadHdrData(fp) ? MEMIMGERR_OK : MEMIMGERR_RAMBIN_HDR);
} else {
ret = MEMIMGERR_RAMBIN_NOHDR;
rewind(fp);
}
// temporarily disable emulation facilities to allow
// proper memory image initialization
bool tmp1 = mCharIOActive, tmp2 = mpRAM->IsROMEnabled();
DisableCharIO();
DisableROM();
while (0 == feof(fp) && 0 == ferror(fp)) {
unsigned char val = fgetc(fp);
pm->Poke8bitImg(addr, val);
addr++; n++;
}
fclose(fp);
// restore emulation facilities status
if (tmp1) SetCharIO(mCharIOAddr, false);
if (tmp2) EnableROM();
if (n <= 0xFFFF) {
switch (ret) {
case MEMIMGERR_OK:
ret = MEMIMGERR_RAMBIN_EOF;
break;
case MEMIMGERR_RAMBIN_HDR:
ret = MEMIMGERR_RAMBIN_HDRANDEOF;
break;
case MEMIMGERR_RAMBIN_NOHDR:
ret = MEMIMGERR_RAMBIN_NOHDRANDEOF;
break;
default: break;
}
}
}
mError = ret;
return ret;
}
/*
*--------------------------------------------------------------------
* Method: LoadRAMHex()
* Purpose: Load data from Intel HEX file format to memory.
* Arguments: hexfname - name of the HEX file
* Returns: int, MEMIMGERR_OK if OK, otherwise error code:
* MEMIMGERR_INTELH_OPEN - unable to open file
* MEMIMGERR_INTELH_SYNTAX - syntax error
* MEMIMGERR_INTELH_FMT - hex format error
*--------------------------------------------------------------------
*/
int VMachine::LoadRAMHex(string hexfname)
{
char line[256] = {0};
FILE *fp = NULL;
int ret = 0;
unsigned int addr = 0;
bool tmp1 = mCharIOActive, tmp2 = mpRAM->IsROMEnabled();
DisableCharIO();
DisableROM();
if ((fp = fopen(hexfname.c_str(), "r")) != NULL) {
while (0 == feof(fp) && 0 == ferror(fp)) {
line[0] = '\0';
fgets(line, 256, fp);
if (line[0] == ':') {
if (0 == strcmp(line, HEXEOF)) {
break; // EOF, we are done here.
}
char blen[3] = {0,0,0};
char baddr[5] = {0,0,0,0,0};
char brectype[3] = {0,0,0};
blen[0] = line[1];
blen[1] = line[2];
blen[2] = 0;
baddr[0] = line[3];
baddr[1] = line[4];
baddr[2] = line[5];
baddr[3] = line[6];
baddr[4] = 0;
brectype[0] = line[7];
brectype[1] = line[8];
brectype[2] = 0;
unsigned int reclen = 0, rectype = 0;
sscanf(blen, "%02x", &reclen);
sscanf(baddr, "%04x", &addr);
sscanf(brectype, "%02x", &rectype);
if (reclen == 0 && rectype == 1) break; // EOF, we are done here.
if (rectype != 0) continue; // not a data record, next!
for (unsigned int i=9; i<reclen*2+9; i+=2,addr++) {
if (i>=strlen(line)-3) {
ret = MEMIMGERR_INTELH_FMT; // hex format error
break;
}
char dbuf[3] = {0,0,0};
unsigned int byteval = 0;
Memory *pm = mpRAM;
dbuf[0] = line[i];
dbuf[1] = line[i+1];
dbuf[2] = 0;
sscanf(dbuf, "%02x", &byteval);
pm->Poke8bitImg(addr, (unsigned char)byteval&0x00FF);
}
} else {
ret = MEMIMGERR_INTELH_SYNTAX; // syntax error
break;
}
}
fclose(fp);
} else {
ret = MEMIMGERR_INTELH_OPEN; // unable to open file
}
if (tmp1) SetCharIO(mCharIOAddr, false);
if (tmp2) EnableROM();
mError = ret;
return ret;
}
/*
*--------------------------------------------------------------------
* Method: LoadRAMDef()
* Purpose: Load RAM from VM65 memory definition file.
* Arguments: memfname - file name
* Returns: int - error code.
*--------------------------------------------------------------------
*/
int VMachine::LoadRAMDef(string memfname)
{
return LoadMEM(memfname, mpRAM);
}
/*
*--------------------------------------------------------------------
* Method: LoadMEM()
* Purpose: Load data from VM65 memory definition file to the
* provided memory device.
* Arguments: memfname - name of memory definition file
* pmem - pointer to memory object
* Returns: int - error code
* Details:
* Format of the memory definition file:
* [; comment]
* [ADDR
* address]
* [data]
* [ORG
* address]
* [data]
* [IOADDR
* address]
* [ROMBEGIN
* address]
* [ROMEND
* address]
* [ENIO]
* [ENROM]
* [EXEC
* addrress]
* [ENGRAPH]
* [GRAPHADDR
* address]
* [RESET]
*
* Where:
* [] - optional token
* ADDR - label indicating that starting address will follow in next
* line, it also defines run address
* ORG - label indicating that the address counter will change to the