-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathntvdm.cxx
9781 lines (8523 loc) · 381 KB
/
ntvdm.cxx
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
// NT Virtual DOS Machine. Not the real one, but one that works on 64-bit Windows.
// Written by David Lee in late 2022
// This only simulates a small subset of DOS and BIOS behavior.
// I only implemented BIOS/DOS calls used by tested apps, so there are some big gaps.
// Only CGA/EGA/VGA text mode 3 (80 x 25/43/50 color) is supported.
// No graphics, sound, mouse, or anything else not needed for simple command-line apps.
// tested apps:
// Turbo Pascal 1.00A, 2.00B, 3.02A, 4.0, 5.0, 5.5, 6.0, and 7.0, both the apps and the programs they generate.
// masm.exe V1.10 and link.exe V2.00 from MS-DOS v2.0
// ba BASIC compiler in my ttt repo
// Wordstar Release 4
// GWBASIC.COM.
// QBASIC 7.1. and apps the QBASIC compiler creates.
// Brief 3.1. Use b.exe's -k flag for compatible keyboard handling. (automatically set in code below)
// ExeHdr: Microsoft (R) EXE File Header Utility Version 2.01
// Link.exe: Microsoft (R) Segmented-Executable Linker Version 5.10
// BC.exe: Microsoft Basic compiler 7.10 (part of Quick Basic 7.1)
// Microsoft BASIC Compiler v 5.36 (bascom.com)
// Microsoft 8086 Object Linker Version 3.01 (C) Copyright Microsoft Corp 1983, 1984, 1985
// Microsoft C v1, v2, and v3
// Turbo C 1.0 and 2.0
// QuickC 1.0, 1.01, and 2.x. ilink.exe in 2.x doesn't work because it relies on undocumented MCB behavior.
// Quick Pascal 1.0
// Lotus 1-2-3 v1.0a
// Word for DOS 6.0.
// Multiplan v2. Setup for later versions fail, but they fail in dosbox too.
// Microsoft Works v3.0.
// Turbo Assembler tasm.
// PC-LISP V3.00
// muLISP v5.10 interpreter (released by Microsoft).
// Microsoft Pascal v1, v3, v4
// MT+86 - Pascal V3.1.1 from Digital Research
// IBM Personal Computer Pascal Compiler Version 2.00 (generated apps require WRAP_HMA_ADDRESSES be true in i8086.hxx)
// Microsoft COBOL Compiler Version 5.0 (compiler and generated apps). Linker requires 286 but QBX's linker works fine.
// Digital Research PL/I-86 Compiler Version 1.0, link86, and generated apps.
// Microsoft FORTRAN77, the linker, and generated apps.
//
// I went from 8085/6800/Z80 machines to Amiga to IBM 360/370 to VAX/VMS to Unix to
// Windows to OS/2 to NT to Mac to Linux, and mostly skipped DOS programming. Hence this fills a gap
// in my knowledge.
//
// Useful: http://www2.ift.ulaval.ca/~marchand/ift17583/dosints.pdf
// https://en.wikipedia.org/wiki/Program_Segment_Prefix
// https://stanislavs.org/helppc/bios_data_area.html
// https://stanislavs.org/helppc/scan_codes.html
// http://www.ctyme.com/intr/int.htm
// https://grandidierite.github.io/dos-interrupts/
// https://fd.lod.bz/rbil/interrup/dos_kernel/2152.html
// https://faydoc.tripod.com/structures/13/1378.htm
// https://www.pcjs.org/documents/books/mspl13/msdos/encyclopedia/section5/
//
// Memory map:
// 0x00000 -- 0x003ff interrupt vectors; only claimed first x40 of slots for bios/DOS
// 0x00400 -- 0x0057f bios data
// 0x00580 -- 0x005ff "list of lists" is 0x5b0 and extends in both directions
// 0x00600 -- 0x00bff assembly code for interrupt helper routines that can't be accomplished in C
// 0x00c00 -- 0x00fff interrupt routine stubs (here, not in BIOS space because it fits)
// 0x01000 -- 0xb7fff apps are loaded here. On real hardware you can only go to 0x9ffff.
// 0xb8000 -- 0xeffff reserved for hardware (CGA in particular)
// 0xf0000 -- 0xfbfff system monitor (0 for now)
// 0xfc000 -- 0xfffff bios code and hard-coded bios data (mostly 0 for now)
#include <djl_os.hxx>
#include <sys/timeb.h>
#include <memory.h>
#include <chrono>
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#ifdef _WIN32
#include <io.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <pthread.h>
#include <time.h>
#include <string>
#include <regex.h>
#endif
#include <assert.h>
#include <vector>
#include <djltrace.hxx>
#include <djl_con.hxx>
#include <djl_cycle.hxx>
#include <djl_durat.hxx>
#include <djl_thrd.hxx>
#include <djl_kslog.hxx>
#include <djl8086d.hxx>
#include "i8086.hxx"
using namespace std;
using namespace std::chrono;
// using assembly for keyboard input enables timer interrupts while spinning for a keystroke
#define USE_ASSEMBLY_FOR_KBD true
// machine code for various interrupts. generated with tasm\mint.bat.
uint64_t int16_0_code[] = {
0x01b4c08e0040b806, 0x8326faf9741669cd, 0x1a3e832602001a06, 0x1a06c726077c3e00, 0x0000cb07fb001e00,
};
uint64_t int21_1_code[] = {
0xcd0ab41669cd00b4, 0x000000cb01b41069,
};
uint64_t int21_8_code[] = {
0xb4c08e0040b85306, 0x26faf9741669cd01, 0xd03e8026001a1e8b, 0x01478a260d740000, 0x11eb0000d006c626, 0x0975003c078a2690, 0x16eb0100d006c626, 0x2602001a06832690,
0x26077c3e001a3e83, 0xb4fb001e001a06c7, 0x00000000cb075b08,
};
uint64_t int21_a_code[] = {
0x000144c6f28b5653, 0xcd01b43674003c80, 0x3c16cd00b4fa7416, 0x7400017c800c7508, 0x339010eb014cfeec, 0x3c024088015c8adb, 0xd08a0144fe10740d, 0x3a01448a21cd02b4,
0x00cb5b5ef8ca7504,
};
uint64_t int21_3f_code[] = {
0x00f1bf5657525153, 0x0000eb06c72ef28b, 0xc5e9037500f98300, 0x50b9037e50f98300, 0xa12e00e90e892e00, 0x7c00ef063b2e00ed, 0xb4fa7416cd01b46d, 0x00e93e832e16cd00,
0x2e1075083c147401, 0x2ee2740000ef3e83, 0x2e901eeb00ef0eff, 0x2e01882e00ef1e8b, 0x22740d3c00ef06ff, 0xe93e832e0875083c, 0x02b4d08a06740100, 0x3b2e00efa12e21cd,
0x004f3d197400e906, 0x2e00ef1e8b2ea775, 0x00ef06ff2e0a01c6, 0x8b2e21cd02b40ab2, 0x8b2e018b2e00ed1e, 0x06ff2e008900eb1e, 0x2e00ed06ff2e00eb, 0x00ef063b2e00eda1,
0x0000ed06c72e1175, 0x000000ef06c72e00, 0x2e00e9a12e900ceb, 0xa12ec07500eb063b, 0x5b595a5f5ef800eb, 0x00000000000000cb, 0x0000000000000000, 0x0000000000000000,
0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000,
0x0000000000000000,
};
// end of machine code
uint16_t AllocateEnvironment( uint16_t segStartingEnv, const char * pathToExecute, const char * pcmdLineEnv );
uint16_t LoadBinary( const char * app, const char * acAppArgs, uint8_t lenAppArgs, uint16_t segment, bool setupRegs,
uint16_t * reg_ss, uint16_t * reg_sp, uint16_t * reg_cs, uint16_t * reg_ip, bool bootSectorLoad );
uint16_t LoadOverlay( const char * app, uint16_t segLoadAddress, uint16_t segmentRelocationFactor );
uint16_t GetSegment( uint8_t * p )
{
uint64_t ptr = (uint64_t) p;
uint64_t mem = (uint64_t) memory;
ptr -= mem;
return (uint16_t) ( ptr >> 4 );
} //GetSegment
struct FileEntry
{
char path[ MAX_PATH ];
FILE * fp;
uint16_t handle; // DOS handle, not host OS handle
uint8_t mode; // 0=ro, 1=wo, 2=rw. upper bits are used for sharing/private
uint16_t seg_process; // process that opened the file
void Trace()
{
tracer.Trace( " handle %04x, path %s, owning process %04x\n", handle, path, seg_process );
}
};
struct AppExecuteMode3
{
uint16_t segLoadAddress;
uint16_t segmentRelocationFactor;
void Trace()
{
tracer.Trace( " AppExecuteMode3:\n" );
tracer.Trace( " segLoadAddress: %#x\n", segLoadAddress );
tracer.Trace( " segmentRelocationFactor: %#x\n", segmentRelocationFactor );
} //Trace
};
struct AppExecute
{
uint16_t segEnvironment; // for mode 3, this is segment load address
uint16_t offsetCommandTail; // for mode 3, this is segment relocation factor
uint16_t segCommandTail;
uint16_t offsetFirstFCB;
uint16_t segFirstFCB;
uint16_t offsetSecondFCB;
uint16_t segSecondFCB;
uint16_t func1SP; // these 4 are return values if al = 1
uint16_t func1SS;
uint16_t func1IP;
uint16_t func1CS;
void Trace()
{
tracer.Trace( " app execute block:\n" );
tracer.Trace( " segEnvironment: %04x\n", segEnvironment );
tracer.Trace( " offsetCommandTail: %04x\n", offsetCommandTail );
tracer.Trace( " segCommandTail: %04x\n", segCommandTail );
}
};
struct ExeHeader
{
uint16_t signature;
uint16_t bytes_in_last_block;
uint16_t blocks_in_file;
uint16_t num_relocs;
uint16_t header_paragraphs;
uint16_t min_extra_paragraphs;
uint16_t max_extra_paragraphs;
uint16_t relative_ss;
uint16_t sp;
uint16_t checksum;
uint16_t ip;
uint16_t relative_cs;
uint16_t reloc_table_offset;
uint16_t overlay_number;
void Trace()
{
tracer.Trace( " exe header:\n" );
tracer.Trace( " signature: %04x = %u\n", signature, signature );
tracer.Trace( " bytes in last block: %04x = %u\n", bytes_in_last_block, bytes_in_last_block );
tracer.Trace( " blocks in file: %04x = %u\n", blocks_in_file, blocks_in_file );
tracer.Trace( " num relocs: %04x = %u\n", num_relocs, num_relocs );
tracer.Trace( " header paragraphs: %04x = %u\n", header_paragraphs, header_paragraphs );
tracer.Trace( " min extra paragraphs: %04x = %u\n", min_extra_paragraphs, min_extra_paragraphs );
tracer.Trace( " max extra paragraphs: %04x = %u\n", max_extra_paragraphs, max_extra_paragraphs );
tracer.Trace( " relative ss: %04x = %u\n", relative_ss, relative_ss );
tracer.Trace( " sp: %04x = %u\n", sp, sp );
tracer.Trace( " checksum: %04x = %u\n", checksum, checksum );
tracer.Trace( " ip: %04x = %u\n", ip, ip );
tracer.Trace( " relative cs: %04x = %u\n", relative_cs, relative_cs );
tracer.Trace( " reloc table offset: %04x = %u\n", reloc_table_offset, reloc_table_offset );
tracer.Trace( " overlay_number: %04x = %u\n", overlay_number, overlay_number );
}
};
struct ExeRelocation
{
uint16_t offset;
uint16_t segment;
};
struct DosAllocation
{
uint16_t segment; // segment handed out to the app, 1 past the MCB
uint16_t para_length; // length in paragraphs including MCB.
uint16_t seg_process; // the process PSP that allocated the memory or 0 prior to the app running
};
struct IntCalled
{
uint8_t i; // interrupt #
uint16_t c; // ah command (0xffff if n/a)
uint32_t calls; // # of times invoked
};
const uint8_t DefaultVideoAttribute = 7; // light grey text
const uint8_t DefaultVideoMode = 3; // 3=80x25 16 colors
const uint32_t ScreenColumns = 80;
const uint32_t DefaultScreenRows = 25;
const uint32_t ScreenColumnsM1 = ScreenColumns - 1; // columns minus 1
const uint32_t ScreenBufferSegment = 0xb800; // location in i8086 physical RAM of CGA display. 16k, 4k per page.
const uint32_t MachineCodeSegment = 0x0060; // machine code for keyboard/etc. starts here
const uint16_t AppSegment = 0x1000 / 16; // base address for apps in the vm. 4k. DOS uses 0x1920 == 6.4k
const uint32_t DOS_FILENAME_SIZE = 13; // 8 + 3 + '.' + 0-termination
const uint16_t InterruptRoutineSegment = 0x00c0; // interrupt routines start here.
const uint16_t SegmentListOfLists = 0x50;
const uint16_t OffsetListOfLists = 0xb0;
const uint64_t OffsetDeviceControlBlock = 0xe0;
#if 0
const uint16_t OffsetSystemFileTable = 0xf0;
#endif
CDJLTrace tracer;
static uint16_t g_segHardware = ScreenBufferSegment; // first byte beyond where apps have available memory
static uint16_t blankLine[ScreenColumns] = {0}; // an optimization for filling lines with blanks
static std::mutex g_mtxEverything; // one mutex for all shared state
static ConsoleConfiguration g_consoleConfig; // to get into and out of 80x25 mode
static bool g_haltExecution = false; // true when the app is shutting down
static uint16_t g_diskTransferSegment = 0; // segment of current disk transfer area
static uint16_t g_diskTransferOffset = 0; // offset of current disk transfer area
static vector<FileEntry> g_fileEntries; // vector of currently open files
static vector<FileEntry> g_fileEntriesFCB; // vector of currently open files with FCBs
static vector<DosAllocation> g_allocEntries; // vector of blocks allocated to DOS apps
static uint16_t g_currentPSP = 0; // psp of the currently running process
static uint16_t g_mainPSP = 0; // psp of the main app
static bool g_use80xRowsMode = false; // true to force 80 x 25/43/50 with cursor positioning
static bool g_forceConsole = false; // true to force teletype mode, with no cursor positioning
static bool g_int16_1_loop = false; // true if an app is looping to get keyboard input. don't busy loop.
static bool g_KbdPeekAvailable = false; // true when peek on the keyboard sees keystrokes
static bool g_int9_pending = false; // true if an int9 was scheduled but not yet invoked
static long g_injectedControlC = 0; // # of control c events to inject
static int g_appTerminationReturnCode = 0; // when int 21 function 4c is invoked to terminate an app, this is the app return code
static char g_acRoot[ MAX_PATH ]; // host folder ending in slash/backslash that maps to DOS "C:\"
static char g_acApp[ MAX_PATH ]; // the DOS .com or .exe being run
static char g_thisApp[ MAX_PATH ]; // name of this exe (argv[0]), likely NTVDM
static char g_lastLoadedApp[ MAX_PATH ] = {0}; // path of most recenly loaded program (though it may have terminated)
static bool g_PackedFileCorruptWorkaround = false; // if true, allocate memory starting at 64k, not AppSegment
static uint16_t g_int21_3f_seg = 0; // segment where this code resides with ip = 0
static uint16_t g_int21_a_seg = 0; // "
static uint16_t g_int21_1_seg = 0; // "
static uint16_t g_int21_8_seg = 0; // "
static uint16_t g_int16_0_seg = 0; // "
static char cwd[ MAX_PATH ] = {0}; // used as a temporary in several locations
static vector<IntCalled> g_InterruptsCalled; // track interrupt usage
static high_resolution_clock::time_point g_tAppStart; // system time at app start
static uint8_t g_bufferLastUpdate[ 80 * 50 * 2 ] = {0}; // used to check for changes in video memory. At most we support 80 by 50
static CKeyStrokes g_keyStrokes; // read or write keystrokes between kslog.txt and the app
static bool g_UseOneThread = false; // true if no keyboard thread should be used
static bool g_InRVOS = false; // true if running in the RISC-V + Linux emulator RVOS
static bool g_InARMOS = false; // true if running in the ARM64 + Linux emulator ARMOS
static uint64_t g_msAtStart = 0; // milliseconds since epoch at app start
static bool g_SendControlCInt = false; // set to true when/if a ^C is detected and an interrupt should be sent
static uint16_t g_builtInHandles[ 5 ] = { 0, 1, 2, 3, 4 }; // stdin, stdout, stderr, stdaux, stdprn are all mapped to self initially
static bool g_IsIntelC45App = false; // true for apps generated by the Intel C compiler
// Set to true to fill dos memory allocations with patterns to detect apps that use memory they previously freed.
static bool g_fillDOSMemoryBlocks = false;
static bool g_validateState = false;
const uint16_t DOS_HANDLE_INVALID = (uint16_t) -1;
#ifndef _WIN32
static bool g_forcePathsUpper = false; // helpful for Linux
static bool g_forcePathsLower = false; // helpful for Linux
static bool g_altPressedRecently = false; // hack because I can't figure out if ALT is currently pressed
#endif
bool ValidDOSFilename( char * pc )
{
if ( 0 == *pc )
return false;
if ( !strcmp( pc, "." ) )
return false;
if ( !strcmp( pc, ".." ) )
return false;
const char * pcinvalid = "<>,;:=?[]%|()/\\";
for ( size_t i = 0; i < strlen( pcinvalid ); i++ )
if ( strchr( pc, pcinvalid[i] ) )
return false;
size_t len = strlen( pc );
if ( len > 12 )
return false;
char * pcdot = strchr( pc, '.' );
if ( !pcdot && ( len > 8 ) )
return false;
if ( pcdot && ( ( pcdot - pc ) > 8 ) )
return false;
return true;
} //ValidDOSFilename
bool ValidDOSPathname( char * pc )
{
if ( !strcmp( pc, "." ) )
return true;
if ( !strcmp( pc, ".." ) )
return true;
return ValidDOSFilename( pc );
} //ValidDOSPathname
bool is_a_folder( const char * path )
{
#ifdef _WIN32
uint32_t attr = GetFileAttributesA( path );
if ( INVALID_FILE_ATTRIBUTES == attr )
return false;
return ( 0 != ( attr & FILE_ATTRIBUTE_DIRECTORY ) );
#else
struct stat statbuf;
int ret = stat( path, & statbuf );
if ( 0 != ret )
return false;
return ( S_ISDIR( statbuf.st_mode ) );
#endif
} //is_a_folder
void ensure_ends_in_slash( char * p )
{
char slash =
#ifdef _WIN32
'\\';
#else
'/';
#endif
size_t len = strlen( p );
if ( 0 == len || ( slash != p[ len - 1] ) )
{
p[ len ] = slash;
p[ len + 1 ] = 0;
return;
}
} //ensure_ends_in_slash
void backslash_to_slash( char * p )
{
while ( *p )
{
if ( '\\' == *p )
*p = '/';
p++;
}
} //backslash_to_slash
void slash_to_backslash( char * p )
{
while ( *p )
{
if ( '/' == *p )
*p = '\\';
p++;
}
} //slash_to_backslash
void cr_to_zero( char * p )
{
while ( *p )
{
if ( '\r' == *p )
{
*p = 0;
break;
}
p++;
}
} //cr_to_zero
int ends_with( const char * str, const char * end )
{
size_t len = strlen( str );
size_t lenend = strlen( end );
if ( len < lenend )
return false;
return !_stricmp( str + len - lenend, end );
} //ends_with
int begins_with( const char * str, const char * start )
{
while ( *str && *start )
{
if ( tolower( *str ) != tolower( *start ) )
return false;
str++;
start++;
}
return true;
} //begins_with
void remove_double_backslash( char * p )
{
do
{
char * ps = strstr( p, "\\\\" );
if ( !ps )
break;
size_t len = strlen( ps );
memmove( ps, ps + 1, len );
} while( true );
} //remove_double_backslash
const char * DOSToHostPath( const char * p )
{
tracer.Trace( " original dos path: '%s'\n", p );
const char * poriginal = p;
char dos_path[ MAX_PATH ];
strcpy( dos_path, p );
slash_to_backslash( dos_path ); // DOS lets apps use forward slashes (Brief does this)
// DOS permits double backslashes in paths. Reduce them to single slash
remove_double_backslash( dos_path );
p = dos_path;
static char host_path[ MAX_PATH ];
if ( 0 == *p )
{
*host_path = 0;
return host_path;
}
else if ( ':' == p[1] )
{
strcpy( host_path, g_acRoot );
if ( '\\' == p[2] )
strcat( host_path, p + 3 ); // the whole path
else
strcpy( host_path, p + 2 ); // just the filename assumed to be in the current directory
}
else if ( '\\' == p[0] )
{
if ( ! begins_with( poriginal, g_acRoot ) )
{
strcpy( host_path, g_acRoot );
strcat( host_path, p + 1 );
}
}
else
strcpy( host_path, p );
#ifndef _WIN32
backslash_to_slash( host_path );
cr_to_zero( host_path );
char * start = host_path;
if ( '/' == host_path[0] )
start += strlen( g_acRoot );
if ( g_forcePathsLower )
strlwr( start );
else if ( g_forcePathsUpper )
strupr( start );
#endif
tracer.Trace( " translated dos path '%s' to host path '%s'\n", p, host_path );
assert( !strstr( host_path, "//" ) );
assert( !strstr( host_path, "\\\\" ) );
return host_path;
} //DOSToHostPath
#ifdef _WIN32
static HANDLE g_hConsoleOutput = 0; // the Windows console output handle
static HANDLE g_hConsoleInput = 0; // the Windows console input handle
static HANDLE g_heventKeyStroke;
#endif
uint8_t * GetDiskTransferAddress() { return cpu.flat_address8( g_diskTransferSegment, g_diskTransferOffset ); }
#pragma pack( push, 1 )
struct DosFindFile
{
uint8_t undocumentedA[ 0xc ]; // no attempt to mock this because I haven't found apps that use it
uint8_t search_attributes; // at offset 0x0c
uint8_t undocumentedB[ 0x8 ]; // no attempt to mock this because I haven't found apps that use it
uint8_t file_attributes; // at offset 0x15
uint16_t file_time; // 0x16
uint16_t file_date; // 0x18
uint32_t file_size; // 0x1a
char file_name[ DOS_FILENAME_SIZE ]; // 0x1e 8.3, blanks stripped, null-terminated
};
#pragma pack(pop)
static void version()
{
printf( "%s\n", build_string() );
exit( 1 );
} //version
static void usage( char const * perr )
{
g_consoleConfig.RestoreConsole( false );
if ( perr )
printf( "error: %s\n", perr );
printf( "Usage: %s [OPTION]... PROGRAM [ARGUMENT]...\n", g_thisApp );
printf( "Emulates an 8086 and MS-DOS 3.30 runtime environment.\n" );
printf( "\n" );
printf( " -b load/run program as the boot sector at 07c0:0000\n" );
printf( " -c tty mode. don't automatically make text area 80x25.\n" );
printf( " -C make text area 80x25 (not tty mode). also -C:43 -C:50\n" );
printf( " -d don't clear the display on exit\n" );
printf( " -e:env,... define environment variables.\n" );
printf( " -f fill memory blocks with patterns to find app bugs\n" );
printf( " -h load high above 64k and below 0xa0000.\n" );
printf( " -i trace instructions to %s.log.\n", g_thisApp );
printf( " -j app debugging: validate CPU state periodically\n" );
printf( " -m after the app ends, print video memory\n" );
printf( " -p show performance stats on exit.\n" );
printf( " -r:root root folder that maps to C:\\\n" );
printf( " -t enable debug tracing to %s.log\n", g_thisApp );
#ifdef I8086_TRACK_CYCLES
printf( " -s:X set processor speed in Hz.\n" );
printf( " for 4.77 MHz 8086 use -s:4770000.\n" );
printf( " for 4.77 MHz 8088 use -s:4500000.\n" );
#endif
#ifndef _WIN32
printf( " -u force DOS paths to be uppercase\n" );
printf( " -l force DOS paths to be lowercase\n" );
#endif
/* work in progress
printf( " -kr read keystrokes from kslog.txt\n" );
printf( " -kw write keywtrokes to kslog.txt\n" );
*/
printf( " -v output version information and exit.\n" );
printf( " -? output this help and exit.\n" );
printf( "\n" );
printf( "Examples:\n" );
#ifdef _WIN32
printf( " %s -u -e:include=.\\inc msc.exe demo.c,,\\;\n", g_thisApp );
printf( " %s -u -e:lib=.\\lib link.exe demo,,\\;\n", g_thisApp );
printf( " %s -u -e:include=.\\inc,lib=.\\lib demo.exe one two three\n", g_thisApp );
printf( " %s -r:. QBX\n", g_thisApp );
#else
printf( " %s -u -e:include=.\\\\inc msc.exe demo.c,,\\\\;\n", g_thisApp );
printf( " %s -u -e:lib=.\\\\lib link.exe demo,,\\\\;\n", g_thisApp );
printf( " %s -u -e:include=.\\\\inc,lib=.\\\\lib demo.exe one two three\n", g_thisApp );
printf( " %s -r:. -u QBX\n", g_thisApp );
#endif
printf( " %s -s:4770000 turbo.com\n", g_thisApp );
printf( "%s\n", build_string() );
exit( 1 );
} //usage
class CKbdBuffer
{
private:
uint8_t * pbiosdata;
uint16_t * phead;
uint16_t * ptail;
public:
CKbdBuffer()
{
pbiosdata = cpu.flat_address8( 0x40, 0 );
phead = (uint16_t *) ( pbiosdata + 0x1a );
ptail = (uint16_t *) ( pbiosdata + 0x1c );
}
bool IsFull() { return ( ( *phead == ( *ptail + 2 ) ) || ( ( 0x1e == *phead ) && ( 0x3c == *ptail ) ) ); }
bool IsEmpty() { return ( *phead == *ptail ); }
void Trace() { tracer.Trace( " kbd buffer head = %04x, tail = %04x\n", *phead, *ptail ); }
void Add( uint8_t asciiChar, uint8_t scancode, bool userGenerated = true )
{
if ( userGenerated )
{
uint16_t stroke = ( ( (uint16_t) scancode ) << 8 ) | asciiChar;
g_keyStrokes.Append( stroke );
}
if ( IsFull() )
tracer.Trace( " dropping keystroke on the floor because the DOS buffer is full\n" );
else
{
pbiosdata[ *ptail ] = asciiChar;
(*ptail)++;
pbiosdata[ *ptail ] = scancode;
(*ptail)++;
if ( *ptail >= 0x3e )
*ptail = 0x1e;
tracer.Trace( " added asciichar %02x scancode %02x, new head = %04x, tail: %04x\n", asciiChar, scancode, *phead, *ptail );
}
} //Add
uint8_t CurAsciiChar()
{
assert( !IsEmpty() );
return pbiosdata[ *phead ];
} //CurAsciiChar
uint8_t CurScancode()
{
assert( !IsEmpty() );
return pbiosdata[ 1 + ( *phead ) ];
} //CurScancode
uint8_t Consume()
{
assert( !IsEmpty() );
uint8_t r = pbiosdata[ *phead ];
(*phead)++;
if ( *phead >= 0x3e )
*phead = 0x1e;
tracer.Trace( " consumed char %02x, new head = %04x, tail %04x\n", r, *phead, *ptail );
return r;
} //Consume
uint32_t FreeSpots()
{
if ( IsFull() )
return 0;
if ( IsEmpty() )
return 16;
uint16_t head = *phead;
uint16_t tail = *ptail;
assert( 0 == ( head & 1 ) );
assert( 0 == ( tail & 1 ) );
assert( head >= 0x1e && head < 0x3e );
assert( tail >= 0x1e && tail < 0x3e );
uint32_t count = 0;
if ( head > tail )
count = ( head - tail ) / 2;
else
count = 16 - ( ( tail - head ) / 2 );
assert( count >= 1 && count <= 15 );
tracer.Trace( " free spots in kbd buffer: %u. head %02x, tail %02x\n", count, head, tail );
return count;
} //FreeSpots
};
uint64_t time_since_last()
{
static high_resolution_clock::time_point tPrev = high_resolution_clock::now();
high_resolution_clock::time_point tNow = high_resolution_clock::now();
uint64_t duration = duration_cast<std::chrono::milliseconds>( tNow - tPrev ).count();
tPrev = tNow;
return duration;
} //time_since_last
uint8_t GetActiveDisplayPage()
{
uint8_t activePage = * cpu.flat_address8( 0x40, 0x62 );
assert( activePage <= 3 );
return activePage;
} //GetActiveDisplayPage
void SetActiveDisplayPage( uint8_t page )
{
assert( page <= 3 );
* cpu.flat_address8( 0x40, 0x62 ) = page;
} //SetActiveDisplayPage
uint8_t GetVideoMode()
{
return * cpu.flat_address8( 0x40, 0x49 );
} //GetVideoMode
void SetVideoMode( uint8_t mode )
{
* cpu.flat_address8( 0x40, 0x49 ) = mode;
} //SetVideoMode
uint8_t GetVideoModeOptions()
{
return * cpu.flat_address8( 0x40, 0x87 );
} //GetVideoModeOptions
void SetVideoModeOptions( uint8_t val )
{
* cpu.flat_address8( 0x40, 0x87 ) = val;
} //SetVideoModeOptions
uint8_t GetVideoDisplayCombination()
{
return * cpu.flat_address8( 0x40, 0x8a );
} //GetVideoDisplayCombination
void SetVideoDisplayCombination( uint8_t comb )
{
* cpu.flat_address8( 0x40, 0x8a ) = comb;
} //SetVideoDisplayCombination
uint8_t GetScreenRows()
{
return 1 + cpu.mbyte( 0x40, 0x84 );
} //GetScreenRows
uint8_t GetScreenRowsM1()
{
return cpu.mbyte( 0x40, 0x84 );
} //GetScreenRowsM1
void SetScreenRows( uint8_t rows )
{
tracer.Trace( " setting screen rows to %u\n", rows );
* cpu.flat_address8( 0x40, 0x84 ) = rows - 1;
} //SetScreenRows
void TraceBiosInfo()
{
tracer.Trace( " bios information:\n" );
tracer.Trace( " 0x49 display mode: %#x\n", cpu.mbyte( 0x40, 0x49 ) );
tracer.Trace( " 0x62 active display page: %#x\n", cpu.mbyte( 0x40, 0x62 ) );
tracer.Trace( " 0x84 screen rows: %#x\n", cpu.mbyte( 0x40, 0x84 ) );
tracer.Trace( " 0x87 ega feature bits: %#x\n", cpu.mbyte( 0x40, 0x87 ) );
tracer.Trace( " 0x89 video display area: %#x\n", cpu.mbyte( 0x40, 0x89 ) );
tracer.Trace( " 0x8a video display combination: %#x\n", cpu.mbyte( 0x40, 0x8a ) );
} //TraceBiosInfo
uint8_t * GetVideoMem( uint8_t displayPage )
{
return cpu.flat_address8( ScreenBufferSegment, 0x1000 * displayPage );
} //GetVideoMem
bool DisplayUpdateRequired()
{
return ( 0 != memcmp( g_bufferLastUpdate, GetVideoMem( GetActiveDisplayPage() ), ScreenColumns * GetScreenRows() * 2 ) );
} //DisplayUpdateRequired
void SleepAndScheduleInterruptCheck()
{
if ( g_UseOneThread && g_consoleConfig.throttled_kbhit() )
g_KbdPeekAvailable = true; // make sure an int9 gets scheduled
CKbdBuffer kbd_buf;
//tracer.Trace( " update required: %d, kbdpeek available: %d\n", DisplayUpdateRequired(), g_KbdPeekAvailable );
if ( kbd_buf.IsEmpty() && !DisplayUpdateRequired() && !g_KbdPeekAvailable )
{
tracer.Trace( " sleeping in SleepAndScheduleInterruptCheck. g_KbdPeekAvailable %d\n", g_KbdPeekAvailable );
#ifdef _WIN32
DWORD dw = WaitForSingleObject( g_heventKeyStroke, 1 );
tracer.Trace( " sleep woke up due to %s\n", ( 0 == dw ) ? "keystroke event signaled" : "timeout" );
#else
sleep_ms( 10 );
#endif
// just because the event was signaled doesn't ensure a keystroke is available. It may be from earlier, but that's OK
}
cpu.exit_emulate_early(); // fall out of the instruction loop early to check for a timer or keyboard interrupt
} //SleepAndScheduleInterruptCheck
#pragma pack( push, 1 )
struct DOSPSP
{
uint16_t int20Code; // 00 machine code cd 20 to end app
uint16_t topOfMemory; // 02 in segment (paragraph) form. one byte beyond what's allocated to the program.
uint8_t reserved; // 04 generally 0
uint8_t dispatcherCPM; // 05 obsolete cp/m-style code to call dispatcher
uint16_t comAvailable; // 06 .com programs bytes available in segment (cp/m holdover)
uint16_t farJumpCPM; // 08 remainder of jump started above
uint32_t int22TerminateAddress; // 0a When a child process ends, there is where execution resumes in the parent.
uint32_t int23ControlBreak; // 0e
uint32_t int24CriticalError; // 12
uint16_t segParent; // 16 parent process segment address of PSP
uint8_t fileHandles[20]; // 18 undocumented, but MS COBOL writes to this
uint16_t segEnvironment; // 2c
uint32_t ssspEntry; // 2e ss:sp on entry to last int21 function. undocumented
uint16_t handleArraySize; // 32 undocumented. dos 3+: number of entries in jft, default 20
uint32_t handleArrayPointer; // 34 undocumented. dos 3+: pointer to jft
uint32_t previousPSP; // 38 undocumented. default 0xffff:ffff. pointer to previous psp
uint16_t parentAX; // 3c These parentXX fields aren't in DOS. They save register values
uint16_t parentBX; // so when execution resumes after a child process ends all is as it was.
uint16_t parentCX;
uint16_t parentDX;
uint16_t parentDI;
uint16_t parentSI;
uint16_t parentES;
uint16_t parentDS;
uint16_t parentBP;
uint8_t reserved2[ 2 ];
uint8_t dispatcher[3]; // undocumented
uint8_t builtInClosed; // bitmask of built-in handles closed by this process for restoration at exit
uint8_t reserved3[8];
uint8_t firstFCB[16]; // 5c later parts of a real fcb shared with secondFCB
uint8_t secondFCB[16]; // 6c only the first part is used
uint16_t parentSS; // 7c not DOS standard -- I use it to restore SS on child app exit
uint16_t parentSP; // 7e not DOS standard -- I use it to restore SP on child app exit
uint8_t countCommandTail; // 80 # of characters in command tail. This byte and beyond later used as Disk Transfer Address
uint8_t commandTail[127]; // 81 command line characters after executable, CR=0xd terminated
void TraceHandleMap()
{
tracer.Trace( " handlemap: " );
for ( size_t x = 0; x < _countof( fileHandles ); x++ )
tracer.Trace( "%02x ", fileHandles[ x ] );
tracer.Trace( "\n" );
}
void Trace()
{
assert( 0x16 == offsetof( DOSPSP, segParent ) );
assert( 0x5c == offsetof( DOSPSP, firstFCB ) );
assert( 0x6c == offsetof( DOSPSP, secondFCB ) );
assert( 0x80 == offsetof( DOSPSP, countCommandTail ) );
tracer.Trace( " PSP: %04x\n", GetSegment( (uint8_t *) this ) );
tracer.TraceBinaryData( (uint8_t *) this, sizeof( DOSPSP ), 4 );
tracer.Trace( " topOfMemory: %04x\n", topOfMemory );
tracer.Trace( " segParent: %04x\n", segParent );
tracer.Trace( " builtInClosed: %02x\n", builtInClosed );
tracer.Trace( " int22 return / terminate address: %04x\n", int22TerminateAddress );
tracer.Trace( " int23 control break address: %04x\n", int23ControlBreak );
tracer.Trace( " int24 critical error address: %04x\n", int24CriticalError );
tracer.Trace( " command tail: len %u, '%.*s'\n", (uint32_t) countCommandTail, (uint32_t) countCommandTail, commandTail );
//tracer.TraceBinaryData( (uint8_t *) &countCommandTail, 0x80, 8 );
tracer.Trace( " handleArraySize: %u\n", (uint32_t) handleArraySize );
tracer.Trace( " handleArrayPointer: %04x\n", handleArrayPointer );
TraceHandleMap();
tracer.Trace( " segEnvironment: %04x\n", segEnvironment );
if ( 0 != segEnvironment )
{
const char * penv = (char *) cpu.flat_address( segEnvironment, 0 );
tracer.TraceBinaryData( (uint8_t *) penv, 0x100, 6 );
}
}
};
#pragma pack(pop)
bool isFilenameChar( char c )
{
char l = (char) tolower( c );
return ( ( l >= 'a' && l <= 'z' ) || ( l >= '0' && l <= '9' ) || '_' == c || '^' == c || '$' == c || '~' == c || '!' == c || '*' == c );
} //isFilenameChar
static const char * get_access_mode( uint8_t mode )
{
uint8_t m = mode & 3;
if ( 0 == m )
return "read-only";
if ( 1 == m )
return "write-only";
if ( 2 == m )
return "read/write";
return "invalid";
} //get_access_mode
static void trace_all_open_files()
{
tracer.Trace( " built-in handle map: " );
for ( size_t i = 0; i <= 4; i++ )
tracer.Trace( " %04x => %04x, ", i, g_builtInHandles[ i ] );
tracer.Trace( "\n" );
size_t cEntries = g_fileEntries.size();
tracer.Trace( " all files, count %d:\n", cEntries );
for ( size_t i = 0; i < cEntries; i++ )
{
FileEntry & fe = g_fileEntries[ i ];
tracer.Trace( " file entry %d, fp %p, handle %u, mode %s, process %u, path %s\n",
i, fe.fp, fe.handle, get_access_mode( fe.mode ), fe.seg_process, fe.path );
}
} //trace_all_open_files
static void trace_all_open_files_fcb()
{
size_t cEntries = g_fileEntriesFCB.size();
tracer.Trace( " all fcb files, count %d:\n", cEntries );
for ( size_t i = 0; i < cEntries; i++ )
{
FileEntry & fe = g_fileEntriesFCB[ i ];
tracer.Trace( " fcb file entry %d, fp %p, handle %u, mode %s, process %u, path %s\n",
i, fe.fp, fe.handle, get_access_mode( fe.mode ), fe.seg_process, fe.path );
}
} //trace_all_open_files_fcb
static bool tc_build_file_open()
{
// check if it looks like Turbo C is building something so we won't sleep in dos idle loop, which it calls
// all the time regardless of whether it's building something.
static const char * build_ext[] = { ".obj", ".c", ".h", ".exe", ".lib", };
size_t cEntries = g_fileEntries.size();
for ( size_t i = 0; i < cEntries; i++ )
{
FileEntry & fe = g_fileEntries[ i ];
for ( size_t e = 0; e < _countof( build_ext ); e++ )
if ( ends_with( fe.path, build_ext[ e ] ) )
return true;
}
return false;
} //tc_build_file_open
uint8_t get_current_drive()
{
// 0 == A...
#ifdef _WIN32
GetCurrentDirectoryA( sizeof( cwd ), cwd );
return (uint8_t) toupper( cwd[0] ) - 'A';
#else
return 2; // 'C'
#endif
} //get_current_drive
static int compare_int_entries( const void * a, const void * b )
{
// sort by int then ah
IntCalled const * pa = (IntCalled const *) a;
IntCalled const * pb = (IntCalled const *) b;
if ( pa->i > pb->i )
return 1;
if ( pa->i == pb->i )
{
if ( pa->c > pb->c )
return 1;
if ( pa->c == pb->c )
return 0;
}
return -1;
} //compare_int_entries
static int compare_file_entries( const void * a, const void * b )
{